diff --git a/node_modules/workbox-background-sync/src/lib/QueueStore.ts b/node_modules/workbox-background-sync/src/lib/QueueStore.ts new file mode 100644 index 0000000000000000000000000000000000000000..67461e3ee253a7ae6c142ffae4dd3494bd50405c --- /dev/null +++ b/node_modules/workbox-background-sync/src/lib/QueueStore.ts @@ -0,0 +1,179 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {assert} from 'workbox-core/_private/assert.js'; +import { + UnidentifiedQueueStoreEntry, + QueueStoreEntry, + QueueDb, +} from './QueueDb.js'; +import '../_version.js'; + +/** + * A class to manage storing requests from a Queue in IndexedDB, + * indexed by their queue name for easier access. + * + * Most developers will not need to access this class directly; + * it is exposed for advanced use cases. + */ +export class QueueStore { + private readonly _queueName: string; + private readonly _queueDb: QueueDb; + + /** + * Associates this instance with a Queue instance, so entries added can be + * identified by their queue name. + * + * @param {string} queueName + */ + constructor(queueName: string) { + this._queueName = queueName; + this._queueDb = new QueueDb(); + } + + /** + * Append an entry last in the queue. + * + * @param {Object} entry + * @param {Object} entry.requestData + * @param {number} [entry.timestamp] + * @param {Object} [entry.metadata] + */ + async pushEntry(entry: UnidentifiedQueueStoreEntry): Promise { + if (process.env.NODE_ENV !== 'production') { + assert!.isType(entry, 'object', { + moduleName: 'workbox-background-sync', + className: 'QueueStore', + funcName: 'pushEntry', + paramName: 'entry', + }); + assert!.isType(entry.requestData, 'object', { + moduleName: 'workbox-background-sync', + className: 'QueueStore', + funcName: 'pushEntry', + paramName: 'entry.requestData', + }); + } + + // Don't specify an ID since one is automatically generated. + delete entry.id; + entry.queueName = this._queueName; + + await this._queueDb.addEntry(entry); + } + + /** + * Prepend an entry first in the queue. + * + * @param {Object} entry + * @param {Object} entry.requestData + * @param {number} [entry.timestamp] + * @param {Object} [entry.metadata] + */ + async unshiftEntry(entry: UnidentifiedQueueStoreEntry): Promise { + if (process.env.NODE_ENV !== 'production') { + assert!.isType(entry, 'object', { + moduleName: 'workbox-background-sync', + className: 'QueueStore', + funcName: 'unshiftEntry', + paramName: 'entry', + }); + assert!.isType(entry.requestData, 'object', { + moduleName: 'workbox-background-sync', + className: 'QueueStore', + funcName: 'unshiftEntry', + paramName: 'entry.requestData', + }); + } + + const firstId = await this._queueDb.getFirstEntryId(); + + if (firstId) { + // Pick an ID one less than the lowest ID in the object store. + entry.id = firstId - 1; + } else { + // Otherwise let the auto-incrementor assign the ID. + delete entry.id; + } + entry.queueName = this._queueName; + + await this._queueDb.addEntry(entry); + } + + /** + * Removes and returns the last entry in the queue matching the `queueName`. + * + * @return {Promise} + */ + async popEntry(): Promise { + return this._removeEntry( + await this._queueDb.getLastEntryByQueueName(this._queueName), + ); + } + + /** + * Removes and returns the first entry in the queue matching the `queueName`. + * + * @return {Promise} + */ + async shiftEntry(): Promise { + return this._removeEntry( + await this._queueDb.getFirstEntryByQueueName(this._queueName), + ); + } + + /** + * Returns all entries in the store matching the `queueName`. + * + * @param {Object} options See {@link workbox-background-sync.Queue~getAll} + * @return {Promise>} + */ + async getAll(): Promise { + return await this._queueDb.getAllEntriesByQueueName(this._queueName); + } + + /** + * Returns the number of entries in the store matching the `queueName`. + * + * @param {Object} options See {@link workbox-background-sync.Queue~size} + * @return {Promise} + */ + async size(): Promise { + return await this._queueDb.getEntryCountByQueueName(this._queueName); + } + + /** + * Deletes the entry for the given ID. + * + * WARNING: this method does not ensure the deleted entry belongs to this + * queue (i.e. matches the `queueName`). But this limitation is acceptable + * as this class is not publicly exposed. An additional check would make + * this method slower than it needs to be. + * + * @param {number} id + */ + async deleteEntry(id: number): Promise { + await this._queueDb.deleteEntry(id); + } + + /** + * Removes and returns the first or last entry in the queue (based on the + * `direction` argument) matching the `queueName`. + * + * @return {Promise} + * @private + */ + async _removeEntry( + entry?: QueueStoreEntry, + ): Promise { + if (entry) { + await this.deleteEntry(entry.id); + } + return entry; + } +} diff --git a/node_modules/workbox-background-sync/src/lib/StorableRequest.ts b/node_modules/workbox-background-sync/src/lib/StorableRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..f28d6aef62f241ad3f2846dff6d5436d6fb77744 --- /dev/null +++ b/node_modules/workbox-background-sync/src/lib/StorableRequest.ts @@ -0,0 +1,156 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {assert} from 'workbox-core/_private/assert.js'; +import {MapLikeObject} from 'workbox-core/types.js'; +import '../_version.js'; + +type SerializableProperties = + | 'method' + | 'referrer' + | 'referrerPolicy' + | 'mode' + | 'credentials' + | 'cache' + | 'redirect' + | 'integrity' + | 'keepalive'; + +const serializableProperties: SerializableProperties[] = [ + 'method', + 'referrer', + 'referrerPolicy', + 'mode', + 'credentials', + 'cache', + 'redirect', + 'integrity', + 'keepalive', +]; + +export interface RequestData extends MapLikeObject { + url: string; + headers: MapLikeObject; + body?: ArrayBuffer; +} + +/** + * A class to make it easier to serialize and de-serialize requests so they + * can be stored in IndexedDB. + * + * Most developers will not need to access this class directly; + * it is exposed for advanced use cases. + */ +class StorableRequest { + private readonly _requestData: RequestData; + + /** + * Converts a Request object to a plain object that can be structured + * cloned or JSON-stringified. + * + * @param {Request} request + * @return {Promise} + */ + static async fromRequest(request: Request): Promise { + const requestData: RequestData = { + url: request.url, + headers: {}, + }; + + // Set the body if present. + if (request.method !== 'GET') { + // Use ArrayBuffer to support non-text request bodies. + // NOTE: we can't use Blobs becuse Safari doesn't support storing + // Blobs in IndexedDB in some cases: + // https://github.com/dfahlander/Dexie.js/issues/618#issuecomment-398348457 + requestData.body = await request.clone().arrayBuffer(); + } + + // Convert the headers from an iterable to an object. + for (const [key, value] of request.headers.entries()) { + requestData.headers[key] = value; + } + + // Add all other serializable request properties + for (const prop of serializableProperties) { + if (request[prop] !== undefined) { + requestData[prop] = request[prop]; + } + } + + return new StorableRequest(requestData); + } + + /** + * Accepts an object of request data that can be used to construct a + * `Request` but can also be stored in IndexedDB. + * + * @param {Object} requestData An object of request data that includes the + * `url` plus any relevant properties of + * [requestInit]{@link https://fetch.spec.whatwg.org/#requestinit}. + */ + constructor(requestData: RequestData) { + if (process.env.NODE_ENV !== 'production') { + assert!.isType(requestData, 'object', { + moduleName: 'workbox-background-sync', + className: 'StorableRequest', + funcName: 'constructor', + paramName: 'requestData', + }); + assert!.isType(requestData.url, 'string', { + moduleName: 'workbox-background-sync', + className: 'StorableRequest', + funcName: 'constructor', + paramName: 'requestData.url', + }); + } + + // If the request's mode is `navigate`, convert it to `same-origin` since + // navigation requests can't be constructed via script. + if (requestData['mode'] === 'navigate') { + requestData['mode'] = 'same-origin'; + } + + this._requestData = requestData; + } + + /** + * Returns a deep clone of the instances `_requestData` object. + * + * @return {Object} + */ + toObject(): RequestData { + const requestData = Object.assign({}, this._requestData); + requestData.headers = Object.assign({}, this._requestData.headers); + if (requestData.body) { + requestData.body = requestData.body.slice(0); + } + + return requestData; + } + + /** + * Converts this instance to a Request. + * + * @return {Request} + */ + toRequest(): Request { + return new Request(this._requestData.url, this._requestData); + } + + /** + * Creates and returns a deep clone of the instance. + * + * @return {StorableRequest} + */ + clone(): StorableRequest { + return new StorableRequest(this.toObject()); + } +} + +export {StorableRequest}; diff --git a/node_modules/workbox-background-sync/tsconfig.json b/node_modules/workbox-background-sync/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..3bb2772b586c4d0ceee3d014e64dba7aafbdd570 --- /dev/null +++ b/node_modules/workbox-background-sync/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tsconfig", + "compilerOptions": { + "composite": true, + "outDir": "./", + "rootDir": "./src", + "tsBuildInfoFile": "./tsconfig.tsbuildinfo" + }, + "include": ["src/**/*.ts"], + "references": [{"path": "../workbox-core/"}] +} diff --git a/node_modules/workbox-broadcast-update/BroadcastCacheUpdate.d.ts b/node_modules/workbox-broadcast-update/BroadcastCacheUpdate.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7f356b34d1dc3cd22d80d73ebada155e62b4d89b --- /dev/null +++ b/node_modules/workbox-broadcast-update/BroadcastCacheUpdate.d.ts @@ -0,0 +1,70 @@ +import { CacheDidUpdateCallbackParam } from 'workbox-core/types.js'; +import './_version.js'; +export interface BroadcastCacheUpdateOptions { + headersToCheck?: string[]; + generatePayload?: (options: CacheDidUpdateCallbackParam) => Record; + notifyAllClients?: boolean; +} +/** + * Uses the `postMessage()` API to inform any open windows/tabs when a cached + * response has been updated. + * + * For efficiency's sake, the underlying response bodies are not compared; + * only specific response headers are checked. + * + * @memberof workbox-broadcast-update + */ +declare class BroadcastCacheUpdate { + private readonly _headersToCheck; + private readonly _generatePayload; + private readonly _notifyAllClients; + /** + * Construct a BroadcastCacheUpdate instance with a specific `channelName` to + * broadcast messages on + * + * @param {Object} [options] + * @param {Array} [options.headersToCheck=['content-length', 'etag', 'last-modified']] + * A list of headers that will be used to determine whether the responses + * differ. + * @param {string} [options.generatePayload] A function whose return value + * will be used as the `payload` field in any cache update messages sent + * to the window clients. + * @param {boolean} [options.notifyAllClients=true] If true (the default) then + * all open clients will receive a message. If false, then only the client + * that make the original request will be notified of the update. + */ + constructor({ generatePayload, headersToCheck, notifyAllClients, }?: BroadcastCacheUpdateOptions); + /** + * Compares two [Responses](https://developer.mozilla.org/en-US/docs/Web/API/Response) + * and sends a message (via `postMessage()`) to all window clients if the + * responses differ. Neither of the Responses can be + * [opaque](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses). + * + * The message that's posted has the following format (where `payload` can + * be customized via the `generatePayload` option the instance is created + * with): + * + * ``` + * { + * type: 'CACHE_UPDATED', + * meta: 'workbox-broadcast-update', + * payload: { + * cacheName: 'the-cache-name', + * updatedURL: 'https://example.com/' + * } + * } + * ``` + * + * @param {Object} options + * @param {Response} [options.oldResponse] Cached response to compare. + * @param {Response} options.newResponse Possibly updated response to compare. + * @param {Request} options.request The request. + * @param {string} options.cacheName Name of the cache the responses belong + * to. This is included in the broadcast message. + * @param {Event} options.event event The event that triggered + * this possible cache update. + * @return {Promise} Resolves once the update is sent. + */ + notifyIfUpdated(options: CacheDidUpdateCallbackParam): Promise; +} +export { BroadcastCacheUpdate }; diff --git a/node_modules/workbox-broadcast-update/BroadcastCacheUpdate.js b/node_modules/workbox-broadcast-update/BroadcastCacheUpdate.js new file mode 100644 index 0000000000000000000000000000000000000000..fe96ede69207f6becb58df307c75af66af57ff0b --- /dev/null +++ b/node_modules/workbox-broadcast-update/BroadcastCacheUpdate.js @@ -0,0 +1,164 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { assert } from 'workbox-core/_private/assert.js'; +import { timeout } from 'workbox-core/_private/timeout.js'; +import { resultingClientExists } from 'workbox-core/_private/resultingClientExists.js'; +import { logger } from 'workbox-core/_private/logger.js'; +import { responsesAreSame } from './responsesAreSame.js'; +import { CACHE_UPDATED_MESSAGE_META, CACHE_UPDATED_MESSAGE_TYPE, DEFAULT_HEADERS_TO_CHECK, NOTIFY_ALL_CLIENTS, } from './utils/constants.js'; +import './_version.js'; +// UA-sniff Safari: https://stackoverflow.com/questions/7944460/detect-safari-browser +// TODO(philipwalton): remove once this Safari bug fix has been released. +// https://bugs.webkit.org/show_bug.cgi?id=201169 +const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); +/** + * Generates the default payload used in update messages. By default the + * payload includes the `cacheName` and `updatedURL` fields. + * + * @return Object + * @private + */ +function defaultPayloadGenerator(data) { + return { + cacheName: data.cacheName, + updatedURL: data.request.url, + }; +} +/** + * Uses the `postMessage()` API to inform any open windows/tabs when a cached + * response has been updated. + * + * For efficiency's sake, the underlying response bodies are not compared; + * only specific response headers are checked. + * + * @memberof workbox-broadcast-update + */ +class BroadcastCacheUpdate { + /** + * Construct a BroadcastCacheUpdate instance with a specific `channelName` to + * broadcast messages on + * + * @param {Object} [options] + * @param {Array} [options.headersToCheck=['content-length', 'etag', 'last-modified']] + * A list of headers that will be used to determine whether the responses + * differ. + * @param {string} [options.generatePayload] A function whose return value + * will be used as the `payload` field in any cache update messages sent + * to the window clients. + * @param {boolean} [options.notifyAllClients=true] If true (the default) then + * all open clients will receive a message. If false, then only the client + * that make the original request will be notified of the update. + */ + constructor({ generatePayload, headersToCheck, notifyAllClients, } = {}) { + this._headersToCheck = headersToCheck || DEFAULT_HEADERS_TO_CHECK; + this._generatePayload = generatePayload || defaultPayloadGenerator; + this._notifyAllClients = notifyAllClients !== null && notifyAllClients !== void 0 ? notifyAllClients : NOTIFY_ALL_CLIENTS; + } + /** + * Compares two [Responses](https://developer.mozilla.org/en-US/docs/Web/API/Response) + * and sends a message (via `postMessage()`) to all window clients if the + * responses differ. Neither of the Responses can be + * [opaque](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses). + * + * The message that's posted has the following format (where `payload` can + * be customized via the `generatePayload` option the instance is created + * with): + * + * ``` + * { + * type: 'CACHE_UPDATED', + * meta: 'workbox-broadcast-update', + * payload: { + * cacheName: 'the-cache-name', + * updatedURL: 'https://example.com/' + * } + * } + * ``` + * + * @param {Object} options + * @param {Response} [options.oldResponse] Cached response to compare. + * @param {Response} options.newResponse Possibly updated response to compare. + * @param {Request} options.request The request. + * @param {string} options.cacheName Name of the cache the responses belong + * to. This is included in the broadcast message. + * @param {Event} options.event event The event that triggered + * this possible cache update. + * @return {Promise} Resolves once the update is sent. + */ + async notifyIfUpdated(options) { + if (process.env.NODE_ENV !== 'production') { + assert.isType(options.cacheName, 'string', { + moduleName: 'workbox-broadcast-update', + className: 'BroadcastCacheUpdate', + funcName: 'notifyIfUpdated', + paramName: 'cacheName', + }); + assert.isInstance(options.newResponse, Response, { + moduleName: 'workbox-broadcast-update', + className: 'BroadcastCacheUpdate', + funcName: 'notifyIfUpdated', + paramName: 'newResponse', + }); + assert.isInstance(options.request, Request, { + moduleName: 'workbox-broadcast-update', + className: 'BroadcastCacheUpdate', + funcName: 'notifyIfUpdated', + paramName: 'request', + }); + } + // Without two responses there is nothing to compare. + if (!options.oldResponse) { + return; + } + if (!responsesAreSame(options.oldResponse, options.newResponse, this._headersToCheck)) { + if (process.env.NODE_ENV !== 'production') { + logger.log(`Newer response found (and cached) for:`, options.request.url); + } + const messageData = { + type: CACHE_UPDATED_MESSAGE_TYPE, + meta: CACHE_UPDATED_MESSAGE_META, + payload: this._generatePayload(options), + }; + // For navigation requests, wait until the new window client exists + // before sending the message + if (options.request.mode === 'navigate') { + let resultingClientId; + if (options.event instanceof FetchEvent) { + resultingClientId = options.event.resultingClientId; + } + const resultingWin = await resultingClientExists(resultingClientId); + // Safari does not currently implement postMessage buffering and + // there's no good way to feature detect that, so to increase the + // chances of the message being delivered in Safari, we add a timeout. + // We also do this if `resultingClientExists()` didn't return a client, + // which means it timed out, so it's worth waiting a bit longer. + if (!resultingWin || isSafari) { + // 3500 is chosen because (according to CrUX data) 80% of mobile + // websites hit the DOMContentLoaded event in less than 3.5 seconds. + // And presumably sites implementing service worker are on the + // higher end of the performance spectrum. + await timeout(3500); + } + } + if (this._notifyAllClients) { + const windows = await self.clients.matchAll({ type: 'window' }); + for (const win of windows) { + win.postMessage(messageData); + } + } + else { + // See https://github.com/GoogleChrome/workbox/issues/2895 + if (options.event instanceof FetchEvent) { + const client = await self.clients.get(options.event.clientId); + client === null || client === void 0 ? void 0 : client.postMessage(messageData); + } + } + } + } +} +export { BroadcastCacheUpdate }; diff --git a/node_modules/workbox-broadcast-update/BroadcastCacheUpdate.mjs b/node_modules/workbox-broadcast-update/BroadcastCacheUpdate.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5a63fb6dc89b3bdeaa2a0eb85093462edaac0532 --- /dev/null +++ b/node_modules/workbox-broadcast-update/BroadcastCacheUpdate.mjs @@ -0,0 +1 @@ +export * from './BroadcastCacheUpdate.js'; \ No newline at end of file diff --git a/node_modules/workbox-broadcast-update/BroadcastUpdatePlugin.d.ts b/node_modules/workbox-broadcast-update/BroadcastUpdatePlugin.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5a00f52d6a7431e16da3d5a4ed62e47eebb96320 --- /dev/null +++ b/node_modules/workbox-broadcast-update/BroadcastUpdatePlugin.d.ts @@ -0,0 +1,41 @@ +import { WorkboxPlugin } from 'workbox-core/types.js'; +import { BroadcastCacheUpdateOptions } from './BroadcastCacheUpdate.js'; +import './_version.js'; +/** + * This plugin will automatically broadcast a message whenever a cached response + * is updated. + * + * @memberof workbox-broadcast-update + */ +declare class BroadcastUpdatePlugin implements WorkboxPlugin { + private readonly _broadcastUpdate; + /** + * Construct a {@link workbox-broadcast-update.BroadcastUpdate} instance with + * the passed options and calls its `notifyIfUpdated` method whenever the + * plugin's `cacheDidUpdate` callback is invoked. + * + * @param {Object} [options] + * @param {Array} [options.headersToCheck=['content-length', 'etag', 'last-modified']] + * A list of headers that will be used to determine whether the responses + * differ. + * @param {string} [options.generatePayload] A function whose return value + * will be used as the `payload` field in any cache update messages sent + * to the window clients. + */ + constructor(options?: BroadcastCacheUpdateOptions); + /** + * A "lifecycle" callback that will be triggered automatically by the + * `workbox-sw` and `workbox-runtime-caching` handlers when an entry is + * added to a cache. + * + * @private + * @param {Object} options The input object to this function. + * @param {string} options.cacheName Name of the cache being updated. + * @param {Response} [options.oldResponse] The previous cached value, if any. + * @param {Response} options.newResponse The new value in the cache. + * @param {Request} options.request The request that triggered the update. + * @param {Request} options.event The event that triggered the update. + */ + cacheDidUpdate: WorkboxPlugin['cacheDidUpdate']; +} +export { BroadcastUpdatePlugin }; diff --git a/node_modules/workbox-broadcast-update/BroadcastUpdatePlugin.js b/node_modules/workbox-broadcast-update/BroadcastUpdatePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..95337fcea72a6971ae4969ae43749dde6bfd71aa --- /dev/null +++ b/node_modules/workbox-broadcast-update/BroadcastUpdatePlugin.js @@ -0,0 +1,51 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js'; +import { BroadcastCacheUpdate, } from './BroadcastCacheUpdate.js'; +import './_version.js'; +/** + * This plugin will automatically broadcast a message whenever a cached response + * is updated. + * + * @memberof workbox-broadcast-update + */ +class BroadcastUpdatePlugin { + /** + * Construct a {@link workbox-broadcast-update.BroadcastUpdate} instance with + * the passed options and calls its `notifyIfUpdated` method whenever the + * plugin's `cacheDidUpdate` callback is invoked. + * + * @param {Object} [options] + * @param {Array} [options.headersToCheck=['content-length', 'etag', 'last-modified']] + * A list of headers that will be used to determine whether the responses + * differ. + * @param {string} [options.generatePayload] A function whose return value + * will be used as the `payload` field in any cache update messages sent + * to the window clients. + */ + constructor(options) { + /** + * A "lifecycle" callback that will be triggered automatically by the + * `workbox-sw` and `workbox-runtime-caching` handlers when an entry is + * added to a cache. + * + * @private + * @param {Object} options The input object to this function. + * @param {string} options.cacheName Name of the cache being updated. + * @param {Response} [options.oldResponse] The previous cached value, if any. + * @param {Response} options.newResponse The new value in the cache. + * @param {Request} options.request The request that triggered the update. + * @param {Request} options.event The event that triggered the update. + */ + this.cacheDidUpdate = async (options) => { + dontWaitFor(this._broadcastUpdate.notifyIfUpdated(options)); + }; + this._broadcastUpdate = new BroadcastCacheUpdate(options); + } +} +export { BroadcastUpdatePlugin }; diff --git a/node_modules/workbox-broadcast-update/BroadcastUpdatePlugin.mjs b/node_modules/workbox-broadcast-update/BroadcastUpdatePlugin.mjs new file mode 100644 index 0000000000000000000000000000000000000000..974685cac0b7e62173a3c7e136ec5997230c5adf --- /dev/null +++ b/node_modules/workbox-broadcast-update/BroadcastUpdatePlugin.mjs @@ -0,0 +1 @@ +export * from './BroadcastUpdatePlugin.js'; \ No newline at end of file diff --git a/node_modules/workbox-broadcast-update/LICENSE b/node_modules/workbox-broadcast-update/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..845b545fd0f5031a944cda8cf9018eb066500040 --- /dev/null +++ b/node_modules/workbox-broadcast-update/LICENSE @@ -0,0 +1,19 @@ +Copyright 2018 Google LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/workbox-broadcast-update/README.md b/node_modules/workbox-broadcast-update/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a6796d289926cc3b5b55d9e549009298c269eb60 --- /dev/null +++ b/node_modules/workbox-broadcast-update/README.md @@ -0,0 +1 @@ +This module's documentation can be found at https://developers.google.com/web/tools/workbox/modules/workbox-broadcast-update diff --git a/node_modules/workbox-broadcast-update/_version.d.ts b/node_modules/workbox-broadcast-update/_version.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/workbox-broadcast-update/_version.js b/node_modules/workbox-broadcast-update/_version.js new file mode 100644 index 0000000000000000000000000000000000000000..6c5403f2b0c85d215e82b88178633e3a38737fa3 --- /dev/null +++ b/node_modules/workbox-broadcast-update/_version.js @@ -0,0 +1,6 @@ +"use strict"; +// @ts-ignore +try { + self['workbox:broadcast-update:7.4.0'] && _(); +} +catch (e) { } diff --git a/node_modules/workbox-broadcast-update/_version.mjs b/node_modules/workbox-broadcast-update/_version.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d66db8348cbe6b812ce2fb77c9fe5877081d7c20 --- /dev/null +++ b/node_modules/workbox-broadcast-update/_version.mjs @@ -0,0 +1 @@ +try{self['workbox:broadcast-update:7.4.1']&&_()}catch(e){}// eslint-disable-line \ No newline at end of file diff --git a/node_modules/workbox-broadcast-update/build/workbox-broadcast-update.dev.js b/node_modules/workbox-broadcast-update/build/workbox-broadcast-update.dev.js new file mode 100644 index 0000000000000000000000000000000000000000..9b26ecc0493574b697788a13123b38c6487f602c --- /dev/null +++ b/node_modules/workbox-broadcast-update/build/workbox-broadcast-update.dev.js @@ -0,0 +1,282 @@ +this.workbox = this.workbox || {}; +this.workbox.broadcastUpdate = (function (exports, assert_js, timeout_js, resultingClientExists_js, logger_js, WorkboxError_js, dontWaitFor_js) { + 'use strict'; + + // @ts-ignore + try { + self['workbox:broadcast-update:7.4.0'] && _(); + } catch (e) {} + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Given two `Response's`, compares several header values to see if they are + * the same or not. + * + * @param {Response} firstResponse + * @param {Response} secondResponse + * @param {Array} headersToCheck + * @return {boolean} + * + * @memberof workbox-broadcast-update + */ + const responsesAreSame = (firstResponse, secondResponse, headersToCheck) => { + { + if (!(firstResponse instanceof Response && secondResponse instanceof Response)) { + throw new WorkboxError_js.WorkboxError('invalid-responses-are-same-args'); + } + } + const atLeastOneHeaderAvailable = headersToCheck.some(header => { + return firstResponse.headers.has(header) && secondResponse.headers.has(header); + }); + if (!atLeastOneHeaderAvailable) { + { + logger_js.logger.warn(`Unable to determine where the response has been updated ` + `because none of the headers that would be checked are present.`); + logger_js.logger.debug(`Attempting to compare the following: `, firstResponse, secondResponse, headersToCheck); + } + // Just return true, indicating the that responses are the same, since we + // can't determine otherwise. + return true; + } + return headersToCheck.every(header => { + const headerStateComparison = firstResponse.headers.has(header) === secondResponse.headers.has(header); + const headerValueComparison = firstResponse.headers.get(header) === secondResponse.headers.get(header); + return headerStateComparison && headerValueComparison; + }); + }; + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + const CACHE_UPDATED_MESSAGE_TYPE = 'CACHE_UPDATED'; + const CACHE_UPDATED_MESSAGE_META = 'workbox-broadcast-update'; + const NOTIFY_ALL_CLIENTS = true; + const DEFAULT_HEADERS_TO_CHECK = ['content-length', 'etag', 'last-modified']; + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + // UA-sniff Safari: https://stackoverflow.com/questions/7944460/detect-safari-browser + // TODO(philipwalton): remove once this Safari bug fix has been released. + // https://bugs.webkit.org/show_bug.cgi?id=201169 + const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); + /** + * Generates the default payload used in update messages. By default the + * payload includes the `cacheName` and `updatedURL` fields. + * + * @return Object + * @private + */ + function defaultPayloadGenerator(data) { + return { + cacheName: data.cacheName, + updatedURL: data.request.url + }; + } + /** + * Uses the `postMessage()` API to inform any open windows/tabs when a cached + * response has been updated. + * + * For efficiency's sake, the underlying response bodies are not compared; + * only specific response headers are checked. + * + * @memberof workbox-broadcast-update + */ + class BroadcastCacheUpdate { + /** + * Construct a BroadcastCacheUpdate instance with a specific `channelName` to + * broadcast messages on + * + * @param {Object} [options] + * @param {Array} [options.headersToCheck=['content-length', 'etag', 'last-modified']] + * A list of headers that will be used to determine whether the responses + * differ. + * @param {string} [options.generatePayload] A function whose return value + * will be used as the `payload` field in any cache update messages sent + * to the window clients. + * @param {boolean} [options.notifyAllClients=true] If true (the default) then + * all open clients will receive a message. If false, then only the client + * that make the original request will be notified of the update. + */ + constructor({ + generatePayload, + headersToCheck, + notifyAllClients + } = {}) { + this._headersToCheck = headersToCheck || DEFAULT_HEADERS_TO_CHECK; + this._generatePayload = generatePayload || defaultPayloadGenerator; + this._notifyAllClients = notifyAllClients !== null && notifyAllClients !== void 0 ? notifyAllClients : NOTIFY_ALL_CLIENTS; + } + /** + * Compares two [Responses](https://developer.mozilla.org/en-US/docs/Web/API/Response) + * and sends a message (via `postMessage()`) to all window clients if the + * responses differ. Neither of the Responses can be + * [opaque](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses). + * + * The message that's posted has the following format (where `payload` can + * be customized via the `generatePayload` option the instance is created + * with): + * + * ``` + * { + * type: 'CACHE_UPDATED', + * meta: 'workbox-broadcast-update', + * payload: { + * cacheName: 'the-cache-name', + * updatedURL: 'https://example.com/' + * } + * } + * ``` + * + * @param {Object} options + * @param {Response} [options.oldResponse] Cached response to compare. + * @param {Response} options.newResponse Possibly updated response to compare. + * @param {Request} options.request The request. + * @param {string} options.cacheName Name of the cache the responses belong + * to. This is included in the broadcast message. + * @param {Event} options.event event The event that triggered + * this possible cache update. + * @return {Promise} Resolves once the update is sent. + */ + async notifyIfUpdated(options) { + { + assert_js.assert.isType(options.cacheName, 'string', { + moduleName: 'workbox-broadcast-update', + className: 'BroadcastCacheUpdate', + funcName: 'notifyIfUpdated', + paramName: 'cacheName' + }); + assert_js.assert.isInstance(options.newResponse, Response, { + moduleName: 'workbox-broadcast-update', + className: 'BroadcastCacheUpdate', + funcName: 'notifyIfUpdated', + paramName: 'newResponse' + }); + assert_js.assert.isInstance(options.request, Request, { + moduleName: 'workbox-broadcast-update', + className: 'BroadcastCacheUpdate', + funcName: 'notifyIfUpdated', + paramName: 'request' + }); + } + // Without two responses there is nothing to compare. + if (!options.oldResponse) { + return; + } + if (!responsesAreSame(options.oldResponse, options.newResponse, this._headersToCheck)) { + { + logger_js.logger.log(`Newer response found (and cached) for:`, options.request.url); + } + const messageData = { + type: CACHE_UPDATED_MESSAGE_TYPE, + meta: CACHE_UPDATED_MESSAGE_META, + payload: this._generatePayload(options) + }; + // For navigation requests, wait until the new window client exists + // before sending the message + if (options.request.mode === 'navigate') { + let resultingClientId; + if (options.event instanceof FetchEvent) { + resultingClientId = options.event.resultingClientId; + } + const resultingWin = await resultingClientExists_js.resultingClientExists(resultingClientId); + // Safari does not currently implement postMessage buffering and + // there's no good way to feature detect that, so to increase the + // chances of the message being delivered in Safari, we add a timeout. + // We also do this if `resultingClientExists()` didn't return a client, + // which means it timed out, so it's worth waiting a bit longer. + if (!resultingWin || isSafari) { + // 3500 is chosen because (according to CrUX data) 80% of mobile + // websites hit the DOMContentLoaded event in less than 3.5 seconds. + // And presumably sites implementing service worker are on the + // higher end of the performance spectrum. + await timeout_js.timeout(3500); + } + } + if (this._notifyAllClients) { + const windows = await self.clients.matchAll({ + type: 'window' + }); + for (const win of windows) { + win.postMessage(messageData); + } + } else { + // See https://github.com/GoogleChrome/workbox/issues/2895 + if (options.event instanceof FetchEvent) { + const client = await self.clients.get(options.event.clientId); + client === null || client === void 0 ? void 0 : client.postMessage(messageData); + } + } + } + } + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * This plugin will automatically broadcast a message whenever a cached response + * is updated. + * + * @memberof workbox-broadcast-update + */ + class BroadcastUpdatePlugin { + /** + * Construct a {@link workbox-broadcast-update.BroadcastUpdate} instance with + * the passed options and calls its `notifyIfUpdated` method whenever the + * plugin's `cacheDidUpdate` callback is invoked. + * + * @param {Object} [options] + * @param {Array} [options.headersToCheck=['content-length', 'etag', 'last-modified']] + * A list of headers that will be used to determine whether the responses + * differ. + * @param {string} [options.generatePayload] A function whose return value + * will be used as the `payload` field in any cache update messages sent + * to the window clients. + */ + constructor(options) { + /** + * A "lifecycle" callback that will be triggered automatically by the + * `workbox-sw` and `workbox-runtime-caching` handlers when an entry is + * added to a cache. + * + * @private + * @param {Object} options The input object to this function. + * @param {string} options.cacheName Name of the cache being updated. + * @param {Response} [options.oldResponse] The previous cached value, if any. + * @param {Response} options.newResponse The new value in the cache. + * @param {Request} options.request The request that triggered the update. + * @param {Request} options.event The event that triggered the update. + */ + this.cacheDidUpdate = async options => { + dontWaitFor_js.dontWaitFor(this._broadcastUpdate.notifyIfUpdated(options)); + }; + this._broadcastUpdate = new BroadcastCacheUpdate(options); + } + } + + exports.BroadcastCacheUpdate = BroadcastCacheUpdate; + exports.BroadcastUpdatePlugin = BroadcastUpdatePlugin; + exports.responsesAreSame = responsesAreSame; + + return exports; + +})({}, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private); +//# sourceMappingURL=workbox-broadcast-update.dev.js.map diff --git a/node_modules/workbox-broadcast-update/build/workbox-broadcast-update.dev.js.map b/node_modules/workbox-broadcast-update/build/workbox-broadcast-update.dev.js.map new file mode 100644 index 0000000000000000000000000000000000000000..de6fe0ba539f0259f4d7230a9c4b5ad8d8b1c49b --- /dev/null +++ b/node_modules/workbox-broadcast-update/build/workbox-broadcast-update.dev.js.map @@ -0,0 +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:7.4.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} headersToCheck\n * @return {boolean}\n *\n * @memberof workbox-broadcast-update\n */\nconst responsesAreSame = (firstResponse, secondResponse, headersToCheck) => {\n if (process.env.NODE_ENV !== 'production') {\n if (!(firstResponse instanceof Response && 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) && 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) === secondResponse.headers.has(header);\n const headerValueComparison = firstResponse.headers.get(header) === 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 NOTIFY_ALL_CLIENTS = true;\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_META, CACHE_UPDATED_MESSAGE_TYPE, DEFAULT_HEADERS_TO_CHECK, NOTIFY_ALL_CLIENTS, } 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 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} [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 * @param {boolean} [options.notifyAllClients=true] If true (the default) then\n * all open clients will receive a message. If false, then only the client\n * that make the original request will be notified of the update.\n */\n constructor({ generatePayload, headersToCheck, notifyAllClients, } = {}) {\n this._headersToCheck = headersToCheck || DEFAULT_HEADERS_TO_CHECK;\n this._generatePayload = generatePayload || defaultPayloadGenerator;\n this._notifyAllClients = notifyAllClients !== null && notifyAllClients !== void 0 ? notifyAllClients : NOTIFY_ALL_CLIENTS;\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. Neither of the Responses can be\n * [opaque](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses).\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 The 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 if (this._notifyAllClients) {\n const windows = await self.clients.matchAll({ type: 'window' });\n for (const win of windows) {\n win.postMessage(messageData);\n }\n }\n else {\n // See https://github.com/GoogleChrome/workbox/issues/2895\n if (options.event instanceof FetchEvent) {\n const client = await self.clients.get(options.event.clientId);\n client === null || client === void 0 ? void 0 : client.postMessage(messageData);\n }\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 workbox-broadcast-update\n */\nclass BroadcastUpdatePlugin {\n /**\n * Construct a {@link workbox-broadcast-update.BroadcastUpdate} instance with\n * the passed options and calls its `notifyIfUpdated` method whenever the\n * plugin's `cacheDidUpdate` callback is invoked.\n *\n * @param {Object} [options]\n * @param {Array} [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","NOTIFY_ALL_CLIENTS","DEFAULT_HEADERS_TO_CHECK","isSafari","test","navigator","userAgent","defaultPayloadGenerator","data","cacheName","updatedURL","request","url","BroadcastCacheUpdate","constructor","generatePayload","notifyAllClients","_headersToCheck","_generatePayload","_notifyAllClients","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","client","clientId","BroadcastUpdatePlugin","cacheDidUpdate","dontWaitFor","_broadcastUpdate"],"mappings":";;;;IACA;IACA,IAAI;IACAA,EAAAA,IAAI,CAAC,gCAAgC,CAAC,IAAIC,CAAC,EAAE;IACjD,CAAC,CACD,OAAOC,CAAC,EAAE,CAAE;;ICLZ;IACA;;IAEA;IACA;IACA;IACA;IAIA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;AACA,UAAMC,gBAAgB,GAAGA,CAACC,aAAa,EAAEC,cAAc,EAAEC,cAAc,KAAK;IACxE,EAA2C;QACvC,IAAI,EAAEF,aAAa,YAAYG,QAAQ,IAAIF,cAAc,YAAYE,QAAQ,CAAC,EAAE;IAC5E,MAAA,MAAM,IAAIC,4BAAY,CAAC,iCAAiC,CAAC;IAC7D,IAAA;IACJ,EAAA;IACA,EAAA,MAAMC,yBAAyB,GAAGH,cAAc,CAACI,IAAI,CAAEC,MAAM,IAAK;IAC9D,IAAA,OAAQP,aAAa,CAACQ,OAAO,CAACC,GAAG,CAACF,MAAM,CAAC,IAAIN,cAAc,CAACO,OAAO,CAACC,GAAG,CAACF,MAAM,CAAC;IACnF,EAAA,CAAC,CA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,SAAC,CAAC;IAC/D,QAAA,KAAK,MAAMa,GAAG,IAAIH,OAAO,EAAE;IACvBG,UAAAA,GAAG,CAACC,WAAW,CAACf,WAAW,CAAC;IAChC,QAAA;IACJ,MAAA,CAAC,MACI;IACD;IACA,QAAA,IAAIZ,OAAO,CAACkB,KAAK,YAAYC,UAAU,EAAE;IACrC,UAAA,MAAMS,MAAM,GAAG,MAAMvE,IAAI,CAACmE,OAAO,CAAC/C,GAAG,CAACuB,OAAO,CAACkB,KAAK,CAACW,QAAQ,CAAC;IAC7DD,UAAAA,MAAM,KAAK,IAAI,IAAIA,MAAM,KAAK,MAAM,GAAG,MAAM,GAAGA,MAAM,CAACD,WAAW,CAACf,WAAW,CAAC;IACnF,QAAA;IACJ,MAAA;IACJ,IAAA;IACJ,EAAA;IACJ;;IClKA;IACA;;IAEA;IACA;IACA;IACA;IAIA;IACA;IACA;IACA;IACA;IACA;IACA,MAAMkB,qBAAqB,CAAC;IACxB;IACJ;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;MACIrC,WAAWA,CAACO,OAAO,EAAE;IACjB;IACR;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACQ,IAAA,IAAI,CAAC+B,cAAc,GAAG,MAAO/B,OAAO,IAAK;UACrCgC,0BAAW,CAAC,IAAI,CAACC,gBAAgB,CAAClC,eAAe,CAACC,OAAO,CAAC,CAAC;QAC/D,CAAC;IACD,IAAA,IAAI,CAACiC,gBAAgB,GAAG,IAAIzC,oBAAoB,CAACQ,OAAO,CAAC;IAC7D,EAAA;IACJ;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/workbox-broadcast-update/build/workbox-broadcast-update.prod.js b/node_modules/workbox-broadcast-update/build/workbox-broadcast-update.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..8f062c8973872ef4935a9b9e1b7ff85ff51f74bf --- /dev/null +++ b/node_modules/workbox-broadcast-update/build/workbox-broadcast-update.prod.js @@ -0,0 +1,2 @@ +this.workbox=this.workbox||{},this.workbox.broadcastUpdate=function(t,s,a,e){"use strict";try{self["workbox:broadcast-update:7.4.0"]&&_()}catch(t){}const n=(t,s,a)=>!a.some((a=>t.headers.has(a)&&s.headers.has(a)))||a.every((a=>{const e=t.headers.has(a)===s.headers.has(a),n=t.headers.get(a)===s.headers.get(a);return e&&n})),i=["content-length","etag","last-modified"],o=/^((?!chrome|android).)*safari/i.test(navigator.userAgent);function c(t){return{cacheName:t.cacheName,updatedURL:t.request.url}}class r{constructor({generatePayload:t,headersToCheck:s,notifyAllClients:a}={}){this.ht=s||i,this.ft=t||c,this.lt=null==a||a}async notifyIfUpdated(t){if(t.oldResponse&&!n(t.oldResponse,t.newResponse,this.ht)){const e={type:"CACHE_UPDATED",meta:"workbox-broadcast-update",payload:this.ft(t)};if("navigate"===t.request.mode){let e;t.event instanceof FetchEvent&&(e=t.event.resultingClientId);await a.resultingClientExists(e)&&!o||await s.timeout(3500)}if(this.lt){const t=await self.clients.matchAll({type:"window"});for(const s of t)s.postMessage(e)}else if(t.event instanceof FetchEvent){const s=await self.clients.get(t.event.clientId);null==s||s.postMessage(e)}}}}return t.BroadcastCacheUpdate=r,t.BroadcastUpdatePlugin=class{constructor(t){this.cacheDidUpdate=async t=>{e.dontWaitFor(this.dt.notifyIfUpdated(t))},this.dt=new r(t)}},t.responsesAreSame=n,t}({},workbox.core._private,workbox.core._private,workbox.core._private); +//# sourceMappingURL=workbox-broadcast-update.prod.js.map diff --git a/node_modules/workbox-broadcast-update/build/workbox-broadcast-update.prod.js.map b/node_modules/workbox-broadcast-update/build/workbox-broadcast-update.prod.js.map new file mode 100644 index 0000000000000000000000000000000000000000..f7c6ea56cb09c07ecd78df91ae5af0918700912d --- /dev/null +++ b/node_modules/workbox-broadcast-update/build/workbox-broadcast-update.prod.js.map @@ -0,0 +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:7.4.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} headersToCheck\n * @return {boolean}\n *\n * @memberof workbox-broadcast-update\n */\nconst responsesAreSame = (firstResponse, secondResponse, headersToCheck) => {\n if (process.env.NODE_ENV !== 'production') {\n if (!(firstResponse instanceof Response && 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) && 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) === secondResponse.headers.has(header);\n const headerValueComparison = firstResponse.headers.get(header) === 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 NOTIFY_ALL_CLIENTS = true;\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_META, CACHE_UPDATED_MESSAGE_TYPE, DEFAULT_HEADERS_TO_CHECK, NOTIFY_ALL_CLIENTS, } 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 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} [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 * @param {boolean} [options.notifyAllClients=true] If true (the default) then\n * all open clients will receive a message. If false, then only the client\n * that make the original request will be notified of the update.\n */\n constructor({ generatePayload, headersToCheck, notifyAllClients, } = {}) {\n this._headersToCheck = headersToCheck || DEFAULT_HEADERS_TO_CHECK;\n this._generatePayload = generatePayload || defaultPayloadGenerator;\n this._notifyAllClients = notifyAllClients !== null && notifyAllClients !== void 0 ? notifyAllClients : NOTIFY_ALL_CLIENTS;\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. Neither of the Responses can be\n * [opaque](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses).\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 The 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 if (this._notifyAllClients) {\n const windows = await self.clients.matchAll({ type: 'window' });\n for (const win of windows) {\n win.postMessage(messageData);\n }\n }\n else {\n // See https://github.com/GoogleChrome/workbox/issues/2895\n if (options.event instanceof FetchEvent) {\n const client = await self.clients.get(options.event.clientId);\n client === null || client === void 0 ? void 0 : client.postMessage(messageData);\n }\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 workbox-broadcast-update\n */\nclass BroadcastUpdatePlugin {\n /**\n * Construct a {@link workbox-broadcast-update.BroadcastUpdate} instance with\n * the passed options and calls its `notifyIfUpdated` method whenever the\n * plugin's `cacheDidUpdate` callback is invoked.\n *\n * @param {Object} [options]\n * @param {Array} [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","notifyAllClients","this","_headersToCheck","_generatePayload","_notifyAllClients","async","options","oldResponse","newResponse","messageData","type","meta","payload","mode","resultingClientId","event","FetchEvent","resultingClientExists","timeout","windows","clients","matchAll","win","postMessage","client","clientId","cacheDidUpdate","dontWaitFor","_broadcastUpdate","notifyIfUpdated"],"mappings":"0FAEA,IACIA,KAAK,mCAAqCC,GAC9C,CACA,MAAOC,GAAK,CCgBZ,MAAMC,EAAmBA,CAACC,EAAeC,EAAgBC,KAMnBA,EAAeC,MAAMC,GAC3CJ,EAAcK,QAAQC,IAAIF,IAAWH,EAAeI,QAAQC,IAAIF,MAYrEF,EAAeK,OAAOH,IACzB,MAAMI,EAAwBR,EAAcK,QAAQC,IAAIF,KAAYH,EAAeI,QAAQC,IAAIF,GACzFK,EAAwBT,EAAc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diff --git a/node_modules/workbox-broadcast-update/index.d.ts b/node_modules/workbox-broadcast-update/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7589de0fe37b903363ca67e0e6f0b4760b3c6fd9 --- /dev/null +++ b/node_modules/workbox-broadcast-update/index.d.ts @@ -0,0 +1,8 @@ +import { BroadcastCacheUpdate, BroadcastCacheUpdateOptions } from './BroadcastCacheUpdate.js'; +import { BroadcastUpdatePlugin } from './BroadcastUpdatePlugin.js'; +import { responsesAreSame } from './responsesAreSame.js'; +import './_version.js'; +/** + * @module workbox-broadcast-update + */ +export { BroadcastCacheUpdate, BroadcastCacheUpdateOptions, BroadcastUpdatePlugin, responsesAreSame, }; diff --git a/node_modules/workbox-broadcast-update/index.js b/node_modules/workbox-broadcast-update/index.js new file mode 100644 index 0000000000000000000000000000000000000000..28b271fcfa879db2a735d5d17a52e5ec5a274b74 --- /dev/null +++ b/node_modules/workbox-broadcast-update/index.js @@ -0,0 +1,15 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { BroadcastCacheUpdate, } from './BroadcastCacheUpdate.js'; +import { BroadcastUpdatePlugin } from './BroadcastUpdatePlugin.js'; +import { responsesAreSame } from './responsesAreSame.js'; +import './_version.js'; +/** + * @module workbox-broadcast-update + */ +export { BroadcastCacheUpdate, BroadcastUpdatePlugin, responsesAreSame, }; diff --git a/node_modules/workbox-broadcast-update/index.mjs b/node_modules/workbox-broadcast-update/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..833b6a2f3226fec78490a3b7a622dc5146f94b53 --- /dev/null +++ b/node_modules/workbox-broadcast-update/index.mjs @@ -0,0 +1 @@ +export * from './index.js'; \ No newline at end of file diff --git a/node_modules/workbox-broadcast-update/package.json b/node_modules/workbox-broadcast-update/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d32182a5771ef2edbc3a1567da8aca68534c9e70 --- /dev/null +++ b/node_modules/workbox-broadcast-update/package.json @@ -0,0 +1,31 @@ +{ + "name": "workbox-broadcast-update", + "version": "7.4.1", + "license": "MIT", + "author": "Google's Web DevRel Team and Google's Aurora Team", + "description": "A service worker helper library that uses the Broadcast Channel API to announce when a cached response has updated", + "repository": { + "type": "git", + "url": "git+https://github.com/googlechrome/workbox.git" + }, + "bugs": "https://github.com/googlechrome/workbox/issues", + "homepage": "https://github.com/GoogleChrome/workbox", + "keywords": [ + "workbox", + "workboxjs", + "service worker", + "sw", + "workbox-plugin" + ], + "workbox": { + "browserNamespace": "workbox.broadcastUpdate", + "packageType": "sw" + }, + "main": "index.js", + "module": "index.mjs", + "types": "index.d.ts", + "dependencies": { + "workbox-core": "7.4.1" + }, + "gitHead": "62b9d8ba8eb3c1a2ab8aac9d84c90cda7865d6a3" +} diff --git a/node_modules/workbox-broadcast-update/responsesAreSame.d.ts b/node_modules/workbox-broadcast-update/responsesAreSame.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d6d10aff40826458cd15b48fe5d5fab13b7872d9 --- /dev/null +++ b/node_modules/workbox-broadcast-update/responsesAreSame.d.ts @@ -0,0 +1,14 @@ +import './_version.js'; +/** + * Given two `Response's`, compares several header values to see if they are + * the same or not. + * + * @param {Response} firstResponse + * @param {Response} secondResponse + * @param {Array} headersToCheck + * @return {boolean} + * + * @memberof workbox-broadcast-update + */ +declare const responsesAreSame: (firstResponse: Response, secondResponse: Response, headersToCheck: string[]) => boolean; +export { responsesAreSame }; diff --git a/node_modules/workbox-broadcast-update/responsesAreSame.js b/node_modules/workbox-broadcast-update/responsesAreSame.js new file mode 100644 index 0000000000000000000000000000000000000000..708ea920f2a33c4a981b3dc2632724d459153445 --- /dev/null +++ b/node_modules/workbox-broadcast-update/responsesAreSame.js @@ -0,0 +1,47 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { WorkboxError } from 'workbox-core/_private/WorkboxError.js'; +import { logger } from 'workbox-core/_private/logger.js'; +import './_version.js'; +/** + * Given two `Response's`, compares several header values to see if they are + * the same or not. + * + * @param {Response} firstResponse + * @param {Response} secondResponse + * @param {Array} headersToCheck + * @return {boolean} + * + * @memberof workbox-broadcast-update + */ +const responsesAreSame = (firstResponse, secondResponse, headersToCheck) => { + if (process.env.NODE_ENV !== 'production') { + if (!(firstResponse instanceof Response && secondResponse instanceof Response)) { + throw new WorkboxError('invalid-responses-are-same-args'); + } + } + const atLeastOneHeaderAvailable = headersToCheck.some((header) => { + return (firstResponse.headers.has(header) && secondResponse.headers.has(header)); + }); + if (!atLeastOneHeaderAvailable) { + if (process.env.NODE_ENV !== 'production') { + logger.warn(`Unable to determine where the response has been updated ` + + `because none of the headers that would be checked are present.`); + logger.debug(`Attempting to compare the following: `, firstResponse, secondResponse, headersToCheck); + } + // Just return true, indicating the that responses are the same, since we + // can't determine otherwise. + return true; + } + return headersToCheck.every((header) => { + const headerStateComparison = firstResponse.headers.has(header) === secondResponse.headers.has(header); + const headerValueComparison = firstResponse.headers.get(header) === secondResponse.headers.get(header); + return headerStateComparison && headerValueComparison; + }); +}; +export { responsesAreSame }; diff --git a/node_modules/workbox-broadcast-update/responsesAreSame.mjs b/node_modules/workbox-broadcast-update/responsesAreSame.mjs new file mode 100644 index 0000000000000000000000000000000000000000..02cb5347fd644090b948ca6021df9eb378ef9a76 --- /dev/null +++ b/node_modules/workbox-broadcast-update/responsesAreSame.mjs @@ -0,0 +1 @@ +export * from './responsesAreSame.js'; \ No newline at end of file diff --git a/node_modules/workbox-broadcast-update/src/BroadcastCacheUpdate.ts b/node_modules/workbox-broadcast-update/src/BroadcastCacheUpdate.ts new file mode 100644 index 0000000000000000000000000000000000000000..8f708d4b73f68191906546e786cdbf707233fe86 --- /dev/null +++ b/node_modules/workbox-broadcast-update/src/BroadcastCacheUpdate.ts @@ -0,0 +1,215 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {assert} from 'workbox-core/_private/assert.js'; +import {timeout} from 'workbox-core/_private/timeout.js'; +import {resultingClientExists} from 'workbox-core/_private/resultingClientExists.js'; +import {CacheDidUpdateCallbackParam} from 'workbox-core/types.js'; +import {logger} from 'workbox-core/_private/logger.js'; +import {responsesAreSame} from './responsesAreSame.js'; +import { + CACHE_UPDATED_MESSAGE_META, + CACHE_UPDATED_MESSAGE_TYPE, + DEFAULT_HEADERS_TO_CHECK, + NOTIFY_ALL_CLIENTS, +} from './utils/constants.js'; + +import './_version.js'; + +// UA-sniff Safari: https://stackoverflow.com/questions/7944460/detect-safari-browser +// TODO(philipwalton): remove once this Safari bug fix has been released. +// https://bugs.webkit.org/show_bug.cgi?id=201169 +const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); + +// Give TypeScript the correct global. +declare let self: ServiceWorkerGlobalScope; + +export interface BroadcastCacheUpdateOptions { + headersToCheck?: string[]; + generatePayload?: ( + options: CacheDidUpdateCallbackParam, + ) => Record; + notifyAllClients?: boolean; +} + +/** + * Generates the default payload used in update messages. By default the + * payload includes the `cacheName` and `updatedURL` fields. + * + * @return Object + * @private + */ +function defaultPayloadGenerator( + data: CacheDidUpdateCallbackParam, +): Record { + return { + cacheName: data.cacheName, + updatedURL: data.request.url, + }; +} + +/** + * Uses the `postMessage()` API to inform any open windows/tabs when a cached + * response has been updated. + * + * For efficiency's sake, the underlying response bodies are not compared; + * only specific response headers are checked. + * + * @memberof workbox-broadcast-update + */ +class BroadcastCacheUpdate { + private readonly _headersToCheck: string[]; + private readonly _generatePayload: ( + options: CacheDidUpdateCallbackParam, + ) => Record; + private readonly _notifyAllClients: boolean; + + /** + * Construct a BroadcastCacheUpdate instance with a specific `channelName` to + * broadcast messages on + * + * @param {Object} [options] + * @param {Array} [options.headersToCheck=['content-length', 'etag', 'last-modified']] + * A list of headers that will be used to determine whether the responses + * differ. + * @param {string} [options.generatePayload] A function whose return value + * will be used as the `payload` field in any cache update messages sent + * to the window clients. + * @param {boolean} [options.notifyAllClients=true] If true (the default) then + * all open clients will receive a message. If false, then only the client + * that make the original request will be notified of the update. + */ + constructor({ + generatePayload, + headersToCheck, + notifyAllClients, + }: BroadcastCacheUpdateOptions = {}) { + this._headersToCheck = headersToCheck || DEFAULT_HEADERS_TO_CHECK; + this._generatePayload = generatePayload || defaultPayloadGenerator; + this._notifyAllClients = notifyAllClients ?? NOTIFY_ALL_CLIENTS; + } + + /** + * Compares two [Responses](https://developer.mozilla.org/en-US/docs/Web/API/Response) + * and sends a message (via `postMessage()`) to all window clients if the + * responses differ. Neither of the Responses can be + * [opaque](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses). + * + * The message that's posted has the following format (where `payload` can + * be customized via the `generatePayload` option the instance is created + * with): + * + * ``` + * { + * type: 'CACHE_UPDATED', + * meta: 'workbox-broadcast-update', + * payload: { + * cacheName: 'the-cache-name', + * updatedURL: 'https://example.com/' + * } + * } + * ``` + * + * @param {Object} options + * @param {Response} [options.oldResponse] Cached response to compare. + * @param {Response} options.newResponse Possibly updated response to compare. + * @param {Request} options.request The request. + * @param {string} options.cacheName Name of the cache the responses belong + * to. This is included in the broadcast message. + * @param {Event} options.event event The event that triggered + * this possible cache update. + * @return {Promise} Resolves once the update is sent. + */ + async notifyIfUpdated(options: CacheDidUpdateCallbackParam): Promise { + if (process.env.NODE_ENV !== 'production') { + assert!.isType(options.cacheName, 'string', { + moduleName: 'workbox-broadcast-update', + className: 'BroadcastCacheUpdate', + funcName: 'notifyIfUpdated', + paramName: 'cacheName', + }); + assert!.isInstance(options.newResponse, Response, { + moduleName: 'workbox-broadcast-update', + className: 'BroadcastCacheUpdate', + funcName: 'notifyIfUpdated', + paramName: 'newResponse', + }); + assert!.isInstance(options.request, Request, { + moduleName: 'workbox-broadcast-update', + className: 'BroadcastCacheUpdate', + funcName: 'notifyIfUpdated', + paramName: 'request', + }); + } + + // Without two responses there is nothing to compare. + if (!options.oldResponse) { + return; + } + + if ( + !responsesAreSame( + options.oldResponse, + options.newResponse, + this._headersToCheck, + ) + ) { + if (process.env.NODE_ENV !== 'production') { + logger.log( + `Newer response found (and cached) for:`, + options.request.url, + ); + } + + const messageData = { + type: CACHE_UPDATED_MESSAGE_TYPE, + meta: CACHE_UPDATED_MESSAGE_META, + payload: this._generatePayload(options), + }; + + // For navigation requests, wait until the new window client exists + // before sending the message + if (options.request.mode === 'navigate') { + let resultingClientId: string | undefined; + if (options.event instanceof FetchEvent) { + resultingClientId = options.event.resultingClientId; + } + + const resultingWin = await resultingClientExists(resultingClientId); + + // Safari does not currently implement postMessage buffering and + // there's no good way to feature detect that, so to increase the + // chances of the message being delivered in Safari, we add a timeout. + // We also do this if `resultingClientExists()` didn't return a client, + // which means it timed out, so it's worth waiting a bit longer. + if (!resultingWin || isSafari) { + // 3500 is chosen because (according to CrUX data) 80% of mobile + // websites hit the DOMContentLoaded event in less than 3.5 seconds. + // And presumably sites implementing service worker are on the + // higher end of the performance spectrum. + await timeout(3500); + } + } + + if (this._notifyAllClients) { + const windows = await self.clients.matchAll({type: 'window'}); + for (const win of windows) { + win.postMessage(messageData); + } + } else { + // See https://github.com/GoogleChrome/workbox/issues/2895 + if (options.event instanceof FetchEvent) { + const client = await self.clients.get(options.event.clientId); + client?.postMessage(messageData); + } + } + } + } +} + +export {BroadcastCacheUpdate}; diff --git a/node_modules/workbox-broadcast-update/src/BroadcastUpdatePlugin.ts b/node_modules/workbox-broadcast-update/src/BroadcastUpdatePlugin.ts new file mode 100644 index 0000000000000000000000000000000000000000..886bf2ed16949c993625719c9eebcff6e71a50f7 --- /dev/null +++ b/node_modules/workbox-broadcast-update/src/BroadcastUpdatePlugin.ts @@ -0,0 +1,63 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {dontWaitFor} from 'workbox-core/_private/dontWaitFor.js'; +import {WorkboxPlugin} from 'workbox-core/types.js'; + +import { + BroadcastCacheUpdate, + BroadcastCacheUpdateOptions, +} from './BroadcastCacheUpdate.js'; + +import './_version.js'; + +/** + * This plugin will automatically broadcast a message whenever a cached response + * is updated. + * + * @memberof workbox-broadcast-update + */ +class BroadcastUpdatePlugin implements WorkboxPlugin { + private readonly _broadcastUpdate: BroadcastCacheUpdate; + + /** + * Construct a {@link workbox-broadcast-update.BroadcastUpdate} instance with + * the passed options and calls its `notifyIfUpdated` method whenever the + * plugin's `cacheDidUpdate` callback is invoked. + * + * @param {Object} [options] + * @param {Array} [options.headersToCheck=['content-length', 'etag', 'last-modified']] + * A list of headers that will be used to determine whether the responses + * differ. + * @param {string} [options.generatePayload] A function whose return value + * will be used as the `payload` field in any cache update messages sent + * to the window clients. + */ + constructor(options?: BroadcastCacheUpdateOptions) { + this._broadcastUpdate = new BroadcastCacheUpdate(options); + } + + /** + * A "lifecycle" callback that will be triggered automatically by the + * `workbox-sw` and `workbox-runtime-caching` handlers when an entry is + * added to a cache. + * + * @private + * @param {Object} options The input object to this function. + * @param {string} options.cacheName Name of the cache being updated. + * @param {Response} [options.oldResponse] The previous cached value, if any. + * @param {Response} options.newResponse The new value in the cache. + * @param {Request} options.request The request that triggered the update. + * @param {Request} options.event The event that triggered the update. + */ + cacheDidUpdate: WorkboxPlugin['cacheDidUpdate'] = async (options) => { + dontWaitFor(this._broadcastUpdate.notifyIfUpdated(options)); + }; +} + +export {BroadcastUpdatePlugin}; diff --git a/node_modules/workbox-broadcast-update/src/_version.ts b/node_modules/workbox-broadcast-update/src/_version.ts new file mode 100644 index 0000000000000000000000000000000000000000..c019524599c3326f7431e8904edcb2322d0ce055 --- /dev/null +++ b/node_modules/workbox-broadcast-update/src/_version.ts @@ -0,0 +1,2 @@ +// @ts-ignore +try{self['workbox:broadcast-update:7.4.1']&&_()}catch(e){} \ No newline at end of file diff --git a/node_modules/workbox-broadcast-update/src/index.ts b/node_modules/workbox-broadcast-update/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..88f0969563703b96f6e5788ce24319e8b2991288 --- /dev/null +++ b/node_modules/workbox-broadcast-update/src/index.ts @@ -0,0 +1,27 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import { + BroadcastCacheUpdate, + BroadcastCacheUpdateOptions, +} from './BroadcastCacheUpdate.js'; +import {BroadcastUpdatePlugin} from './BroadcastUpdatePlugin.js'; +import {responsesAreSame} from './responsesAreSame.js'; + +import './_version.js'; + +/** + * @module workbox-broadcast-update + */ + +export { + BroadcastCacheUpdate, + BroadcastCacheUpdateOptions, + BroadcastUpdatePlugin, + responsesAreSame, +}; diff --git a/node_modules/workbox-broadcast-update/src/responsesAreSame.ts b/node_modules/workbox-broadcast-update/src/responsesAreSame.ts new file mode 100644 index 0000000000000000000000000000000000000000..a2e6dd4a1d845a769a09f11b05dc7ddec08308a7 --- /dev/null +++ b/node_modules/workbox-broadcast-update/src/responsesAreSame.ts @@ -0,0 +1,72 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {WorkboxError} from 'workbox-core/_private/WorkboxError.js'; +import {logger} from 'workbox-core/_private/logger.js'; +import './_version.js'; + +/** + * Given two `Response's`, compares several header values to see if they are + * the same or not. + * + * @param {Response} firstResponse + * @param {Response} secondResponse + * @param {Array} headersToCheck + * @return {boolean} + * + * @memberof workbox-broadcast-update + */ +const responsesAreSame = ( + firstResponse: Response, + secondResponse: Response, + headersToCheck: string[], +): boolean => { + if (process.env.NODE_ENV !== 'production') { + if ( + !(firstResponse instanceof Response && secondResponse instanceof Response) + ) { + throw new WorkboxError('invalid-responses-are-same-args'); + } + } + + const atLeastOneHeaderAvailable = headersToCheck.some((header) => { + return ( + firstResponse.headers.has(header) && secondResponse.headers.has(header) + ); + }); + + if (!atLeastOneHeaderAvailable) { + if (process.env.NODE_ENV !== 'production') { + logger.warn( + `Unable to determine where the response has been updated ` + + `because none of the headers that would be checked are present.`, + ); + logger.debug( + `Attempting to compare the following: `, + firstResponse, + secondResponse, + headersToCheck, + ); + } + + // Just return true, indicating the that responses are the same, since we + // can't determine otherwise. + return true; + } + + return headersToCheck.every((header) => { + const headerStateComparison = + firstResponse.headers.has(header) === secondResponse.headers.has(header); + const headerValueComparison = + firstResponse.headers.get(header) === secondResponse.headers.get(header); + + return headerStateComparison && headerValueComparison; + }); +}; + +export {responsesAreSame}; diff --git a/node_modules/workbox-broadcast-update/src/utils/constants.ts b/node_modules/workbox-broadcast-update/src/utils/constants.ts new file mode 100644 index 0000000000000000000000000000000000000000..fb05156675c5e3a11c50a93c0884ebb2d6bc6fac --- /dev/null +++ b/node_modules/workbox-broadcast-update/src/utils/constants.ts @@ -0,0 +1,18 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import '../_version.js'; + +export const CACHE_UPDATED_MESSAGE_TYPE = 'CACHE_UPDATED'; +export const CACHE_UPDATED_MESSAGE_META = 'workbox-broadcast-update'; +export const NOTIFY_ALL_CLIENTS = true; +export const DEFAULT_HEADERS_TO_CHECK: string[] = [ + 'content-length', + 'etag', + 'last-modified', +]; diff --git a/node_modules/workbox-broadcast-update/tsconfig.json b/node_modules/workbox-broadcast-update/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..3bb2772b586c4d0ceee3d014e64dba7aafbdd570 --- /dev/null +++ b/node_modules/workbox-broadcast-update/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tsconfig", + "compilerOptions": { + "composite": true, + "outDir": "./", + "rootDir": "./src", + "tsBuildInfoFile": "./tsconfig.tsbuildinfo" + }, + "include": ["src/**/*.ts"], + "references": [{"path": "../workbox-core/"}] +} diff --git a/node_modules/workbox-broadcast-update/utils/constants.d.ts b/node_modules/workbox-broadcast-update/utils/constants.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f3cdefdf5beb63e659336a453e022d33c12d493c --- /dev/null +++ b/node_modules/workbox-broadcast-update/utils/constants.d.ts @@ -0,0 +1,5 @@ +import '../_version.js'; +export declare const CACHE_UPDATED_MESSAGE_TYPE = "CACHE_UPDATED"; +export declare const CACHE_UPDATED_MESSAGE_META = "workbox-broadcast-update"; +export declare const NOTIFY_ALL_CLIENTS = true; +export declare const DEFAULT_HEADERS_TO_CHECK: string[]; diff --git a/node_modules/workbox-broadcast-update/utils/constants.js b/node_modules/workbox-broadcast-update/utils/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..bad6da02d9efb5b57a80b3a69cc67ab5fb0b1259 --- /dev/null +++ b/node_modules/workbox-broadcast-update/utils/constants.js @@ -0,0 +1,16 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import '../_version.js'; +export const CACHE_UPDATED_MESSAGE_TYPE = 'CACHE_UPDATED'; +export const CACHE_UPDATED_MESSAGE_META = 'workbox-broadcast-update'; +export const NOTIFY_ALL_CLIENTS = true; +export const DEFAULT_HEADERS_TO_CHECK = [ + 'content-length', + 'etag', + 'last-modified', +]; diff --git a/node_modules/workbox-broadcast-update/utils/constants.mjs b/node_modules/workbox-broadcast-update/utils/constants.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f3f4c8f2658cad983ad14478588d456cb83091d0 --- /dev/null +++ b/node_modules/workbox-broadcast-update/utils/constants.mjs @@ -0,0 +1 @@ +export * from './constants.js'; \ No newline at end of file diff --git a/node_modules/workbox-build/.ncurc.js b/node_modules/workbox-build/.ncurc.js new file mode 100644 index 0000000000000000000000000000000000000000..4c0afaf979de33dd8a5295fdee1764b7cb9f4f7a --- /dev/null +++ b/node_modules/workbox-build/.ncurc.js @@ -0,0 +1,19 @@ +/* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +// We use `npx npm-check-updates` to find updates to dependencies. +// Some dependencies have breaking changes that we can't resolve. +// This config file excludes those dependencies from the checks +// until we're able to remediate our code to deal with them. +module.exports = { + reject: [ + // joi v16 is the last release to support Node v10: + // https://github.com/sideway/joi/issues/2262 + '@hapi/joi', + ], +}; diff --git a/node_modules/workbox-build/LICENSE b/node_modules/workbox-build/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..845b545fd0f5031a944cda8cf9018eb066500040 --- /dev/null +++ b/node_modules/workbox-build/LICENSE @@ -0,0 +1,19 @@ +Copyright 2018 Google LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/workbox-build/README.md b/node_modules/workbox-build/README.md new file mode 100644 index 0000000000000000000000000000000000000000..01fb53f19ff6c720815c57b8c52f0fc0ac7bf3df --- /dev/null +++ b/node_modules/workbox-build/README.md @@ -0,0 +1 @@ +This module's documentation can be found at https://developer.chrome.com/docs/workbox/modules/workbox-build diff --git a/node_modules/workbox-build/build/cdn-details.json b/node_modules/workbox-build/build/cdn-details.json new file mode 100644 index 0000000000000000000000000000000000000000..a08cb94e7acc44e12d320310ea7d404dba28e8c2 --- /dev/null +++ b/node_modules/workbox-build/build/cdn-details.json @@ -0,0 +1,6 @@ +{ + "origin": "https://storage.googleapis.com", + "bucketName": "workbox-cdn", + "releasesDir": "releases", + "latestVersion": "7.4.1" +} diff --git a/node_modules/workbox-build/build/generate-sw.d.ts b/node_modules/workbox-build/build/generate-sw.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..66b6fa8b60439483877056f88bf84e864b060871 --- /dev/null +++ b/node_modules/workbox-build/build/generate-sw.d.ts @@ -0,0 +1,47 @@ +import { BuildResult, GenerateSWOptions } from './types'; +/** + * This method creates a list of URLs to precache, referred to as a "precache + * manifest", based on the options you provide. + * + * It also takes in additional options that configures the service worker's + * behavior, like any `runtimeCaching` rules it should use. + * + * Based on the precache manifest and the additional configuration, it writes + * a ready-to-use service worker file to disk at `swDest`. + * + * ``` + * // The following lists some common options; see the rest of the documentation + * // for the full set of options and defaults. + * const {count, size, warnings} = await generateSW({ + * dontCacheBustURLsMatching: [new RegExp('...')], + * globDirectory: '...', + * globPatterns: ['...', '...'], + * maximumFileSizeToCacheInBytes: ..., + * navigateFallback: '...', + * runtimeCaching: [{ + * // Routing via a matchCallback function: + * urlPattern: ({request, url}) => ..., + * handler: '...', + * options: { + * cacheName: '...', + * expiration: { + * maxEntries: ..., + * }, + * }, + * }, { + * // Routing via a RegExp: + * urlPattern: new RegExp('...'), + * handler: '...', + * options: { + * cacheName: '...', + * plugins: [..., ...], + * }, + * }], + * skipWaiting: ..., + * swDest: '...', + * }); + * ``` + * + * @memberof workbox-build + */ +export declare function generateSW(config: GenerateSWOptions): Promise; diff --git a/node_modules/workbox-build/build/generate-sw.js b/node_modules/workbox-build/build/generate-sw.js new file mode 100644 index 0000000000000000000000000000000000000000..87c5248f06950b512808433cc2f913c13a151ec8 --- /dev/null +++ b/node_modules/workbox-build/build/generate-sw.js @@ -0,0 +1,105 @@ +"use strict"; +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.generateSW = void 0; +const upath_1 = __importDefault(require("upath")); +const get_file_manifest_entries_1 = require("./lib/get-file-manifest-entries"); +const rebase_path_1 = require("./lib/rebase-path"); +const validate_options_1 = require("./lib/validate-options"); +const write_sw_using_default_template_1 = require("./lib/write-sw-using-default-template"); +/** + * This method creates a list of URLs to precache, referred to as a "precache + * manifest", based on the options you provide. + * + * It also takes in additional options that configures the service worker's + * behavior, like any `runtimeCaching` rules it should use. + * + * Based on the precache manifest and the additional configuration, it writes + * a ready-to-use service worker file to disk at `swDest`. + * + * ``` + * // The following lists some common options; see the rest of the documentation + * // for the full set of options and defaults. + * const {count, size, warnings} = await generateSW({ + * dontCacheBustURLsMatching: [new RegExp('...')], + * globDirectory: '...', + * globPatterns: ['...', '...'], + * maximumFileSizeToCacheInBytes: ..., + * navigateFallback: '...', + * runtimeCaching: [{ + * // Routing via a matchCallback function: + * urlPattern: ({request, url}) => ..., + * handler: '...', + * options: { + * cacheName: '...', + * expiration: { + * maxEntries: ..., + * }, + * }, + * }, { + * // Routing via a RegExp: + * urlPattern: new RegExp('...'), + * handler: '...', + * options: { + * cacheName: '...', + * plugins: [..., ...], + * }, + * }], + * skipWaiting: ..., + * swDest: '...', + * }); + * ``` + * + * @memberof workbox-build + */ +async function generateSW(config) { + const options = (0, validate_options_1.validateGenerateSWOptions)(config); + let entriesResult; + if (options.globDirectory) { + // Make sure we leave swDest out of the precache manifest. + options.globIgnores.push((0, rebase_path_1.rebasePath)({ + baseDirectory: options.globDirectory, + file: options.swDest, + })); + // If we create an extra external runtime file, ignore that, too. + // See https://rollupjs.org/guide/en/#outputchunkfilenames for naming. + if (!options.inlineWorkboxRuntime) { + const swDestDir = upath_1.default.dirname(options.swDest); + const workboxRuntimeFile = upath_1.default.join(swDestDir, 'workbox-*.js'); + options.globIgnores.push((0, rebase_path_1.rebasePath)({ + baseDirectory: options.globDirectory, + file: workboxRuntimeFile, + })); + } + // We've previously asserted that options.globDirectory is set, so this + // should be a safe cast. + entriesResult = await (0, get_file_manifest_entries_1.getFileManifestEntries)(options); + } + else { + entriesResult = { + count: 0, + manifestEntries: [], + size: 0, + warnings: [], + }; + } + const filePaths = await (0, write_sw_using_default_template_1.writeSWUsingDefaultTemplate)(Object.assign({ + manifestEntries: entriesResult.manifestEntries, + }, options)); + return { + filePaths, + count: entriesResult.count, + size: entriesResult.size, + warnings: entriesResult.warnings, + }; +} +exports.generateSW = generateSW; diff --git a/node_modules/workbox-build/build/get-manifest.d.ts b/node_modules/workbox-build/build/get-manifest.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..95c61adf226bbd2a30d0d1110d523d56c362ea38 --- /dev/null +++ b/node_modules/workbox-build/build/get-manifest.d.ts @@ -0,0 +1,20 @@ +import { GetManifestOptions, GetManifestResult } from './types'; +/** + * This method returns a list of URLs to precache, referred to as a "precache + * manifest", along with details about the number of entries and their size, + * based on the options you provide. + * + * ``` + * // The following lists some common options; see the rest of the documentation + * // for the full set of options and defaults. + * const {count, manifestEntries, size, warnings} = await getManifest({ + * dontCacheBustURLsMatching: [new RegExp('...')], + * globDirectory: '...', + * globPatterns: ['...', '...'], + * maximumFileSizeToCacheInBytes: ..., + * }); + * ``` + * + * @memberof workbox-build + */ +export declare function getManifest(config: GetManifestOptions): Promise; diff --git a/node_modules/workbox-build/build/get-manifest.js b/node_modules/workbox-build/build/get-manifest.js new file mode 100644 index 0000000000000000000000000000000000000000..ebf65ceb9715bb40466122081d51da45412c9b1e --- /dev/null +++ b/node_modules/workbox-build/build/get-manifest.js @@ -0,0 +1,35 @@ +"use strict"; +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getManifest = void 0; +const get_file_manifest_entries_1 = require("./lib/get-file-manifest-entries"); +const validate_options_1 = require("./lib/validate-options"); +/** + * This method returns a list of URLs to precache, referred to as a "precache + * manifest", along with details about the number of entries and their size, + * based on the options you provide. + * + * ``` + * // The following lists some common options; see the rest of the documentation + * // for the full set of options and defaults. + * const {count, manifestEntries, size, warnings} = await getManifest({ + * dontCacheBustURLsMatching: [new RegExp('...')], + * globDirectory: '...', + * globPatterns: ['...', '...'], + * maximumFileSizeToCacheInBytes: ..., + * }); + * ``` + * + * @memberof workbox-build + */ +async function getManifest(config) { + const options = (0, validate_options_1.validateGetManifestOptions)(config); + return await (0, get_file_manifest_entries_1.getFileManifestEntries)(options); +} +exports.getManifest = getManifest; diff --git a/node_modules/workbox-build/build/index.d.ts b/node_modules/workbox-build/build/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2bba846df479175282341d3eb60184a4258c65be --- /dev/null +++ b/node_modules/workbox-build/build/index.d.ts @@ -0,0 +1,10 @@ +import { copyWorkboxLibraries } from './lib/copy-workbox-libraries'; +import { getModuleURL } from './lib/cdn-utils'; +import { generateSW } from './generate-sw'; +import { getManifest } from './get-manifest'; +import { injectManifest } from './inject-manifest'; +/** + * @module workbox-build + */ +export { copyWorkboxLibraries, generateSW, getManifest, getModuleURL, injectManifest, }; +export * from './types'; diff --git a/node_modules/workbox-build/build/index.js b/node_modules/workbox-build/build/index.js new file mode 100644 index 0000000000000000000000000000000000000000..78dfdd014e7c07b7df32a351876df64b394878c4 --- /dev/null +++ b/node_modules/workbox-build/build/index.js @@ -0,0 +1,35 @@ +"use strict"; +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.injectManifest = exports.getModuleURL = exports.getManifest = exports.generateSW = exports.copyWorkboxLibraries = void 0; +const copy_workbox_libraries_1 = require("./lib/copy-workbox-libraries"); +Object.defineProperty(exports, "copyWorkboxLibraries", { enumerable: true, get: function () { return copy_workbox_libraries_1.copyWorkboxLibraries; } }); +const cdn_utils_1 = require("./lib/cdn-utils"); +Object.defineProperty(exports, "getModuleURL", { enumerable: true, get: function () { return cdn_utils_1.getModuleURL; } }); +const generate_sw_1 = require("./generate-sw"); +Object.defineProperty(exports, "generateSW", { enumerable: true, get: function () { return generate_sw_1.generateSW; } }); +const get_manifest_1 = require("./get-manifest"); +Object.defineProperty(exports, "getManifest", { enumerable: true, get: function () { return get_manifest_1.getManifest; } }); +const inject_manifest_1 = require("./inject-manifest"); +Object.defineProperty(exports, "injectManifest", { enumerable: true, get: function () { return inject_manifest_1.injectManifest; } }); +__exportStar(require("./types"), exports); diff --git a/node_modules/workbox-build/build/inject-manifest.d.ts b/node_modules/workbox-build/build/inject-manifest.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..07a463fee4609398cfc6642d7e89b16ec12f46b5 --- /dev/null +++ b/node_modules/workbox-build/build/inject-manifest.d.ts @@ -0,0 +1,30 @@ +import { BuildResult, InjectManifestOptions } from './types'; +/** + * This method creates a list of URLs to precache, referred to as a "precache + * manifest", based on the options you provide. + * + * The manifest is injected into the `swSrc` file, and the placeholder string + * `injectionPoint` determines where in the file the manifest should go. + * + * The final service worker file, with the manifest injected, is written to + * disk at `swDest`. + * + * This method will not compile or bundle your `swSrc` file; it just handles + * injecting the manifest. + * + * ``` + * // The following lists some common options; see the rest of the documentation + * // for the full set of options and defaults. + * const {count, size, warnings} = await injectManifest({ + * dontCacheBustURLsMatching: [new RegExp('...')], + * globDirectory: '...', + * globPatterns: ['...', '...'], + * maximumFileSizeToCacheInBytes: ..., + * swDest: '...', + * swSrc: '...', + * }); + * ``` + * + * @memberof workbox-build + */ +export declare function injectManifest(config: InjectManifestOptions): Promise; diff --git a/node_modules/workbox-build/build/inject-manifest.js b/node_modules/workbox-build/build/inject-manifest.js new file mode 100644 index 0000000000000000000000000000000000000000..60e3d2bb51c11a19fbbedbad65e101082ec41c36 --- /dev/null +++ b/node_modules/workbox-build/build/inject-manifest.js @@ -0,0 +1,133 @@ +"use strict"; +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.injectManifest = void 0; +const assert_1 = __importDefault(require("assert")); +const fs_extra_1 = __importDefault(require("fs-extra")); +const fast_json_stable_stringify_1 = __importDefault(require("fast-json-stable-stringify")); +const upath_1 = __importDefault(require("upath")); +const errors_1 = require("./lib/errors"); +const escape_regexp_1 = require("./lib/escape-regexp"); +const get_file_manifest_entries_1 = require("./lib/get-file-manifest-entries"); +const get_source_map_url_1 = require("./lib/get-source-map-url"); +const rebase_path_1 = require("./lib/rebase-path"); +const replace_and_update_source_map_1 = require("./lib/replace-and-update-source-map"); +const translate_url_to_sourcemap_paths_1 = require("./lib/translate-url-to-sourcemap-paths"); +const validate_options_1 = require("./lib/validate-options"); +/** + * This method creates a list of URLs to precache, referred to as a "precache + * manifest", based on the options you provide. + * + * The manifest is injected into the `swSrc` file, and the placeholder string + * `injectionPoint` determines where in the file the manifest should go. + * + * The final service worker file, with the manifest injected, is written to + * disk at `swDest`. + * + * This method will not compile or bundle your `swSrc` file; it just handles + * injecting the manifest. + * + * ``` + * // The following lists some common options; see the rest of the documentation + * // for the full set of options and defaults. + * const {count, size, warnings} = await injectManifest({ + * dontCacheBustURLsMatching: [new RegExp('...')], + * globDirectory: '...', + * globPatterns: ['...', '...'], + * maximumFileSizeToCacheInBytes: ..., + * swDest: '...', + * swSrc: '...', + * }); + * ``` + * + * @memberof workbox-build + */ +async function injectManifest(config) { + const options = (0, validate_options_1.validateInjectManifestOptions)(config); + // Make sure we leave swSrc and swDest out of the precache manifest. + for (const file of [options.swSrc, options.swDest]) { + options.globIgnores.push((0, rebase_path_1.rebasePath)({ + file, + baseDirectory: options.globDirectory, + })); + } + const globalRegexp = new RegExp((0, escape_regexp_1.escapeRegExp)(options.injectionPoint), 'g'); + const { count, size, manifestEntries, warnings } = await (0, get_file_manifest_entries_1.getFileManifestEntries)(options); + let swFileContents; + try { + swFileContents = await fs_extra_1.default.readFile(options.swSrc, 'utf8'); + } + catch (error) { + throw new Error(`${errors_1.errors['invalid-sw-src']} ${error instanceof Error && error.message ? error.message : ''}`); + } + const injectionResults = swFileContents.match(globalRegexp); + // See https://github.com/GoogleChrome/workbox/issues/2230 + const injectionPoint = options.injectionPoint ? options.injectionPoint : ''; + if (!injectionResults) { + if (upath_1.default.resolve(options.swSrc) === upath_1.default.resolve(options.swDest)) { + throw new Error(`${errors_1.errors['same-src-and-dest']} ${injectionPoint}`); + } + throw new Error(`${errors_1.errors['injection-point-not-found']} ${injectionPoint}`); + } + (0, assert_1.default)(injectionResults.length === 1, `${errors_1.errors['multiple-injection-points']} ${injectionPoint}`); + const manifestString = (0, fast_json_stable_stringify_1.default)(manifestEntries); + const filesToWrite = {}; + const url = (0, get_source_map_url_1.getSourceMapURL)(swFileContents); + // See https://github.com/GoogleChrome/workbox/issues/2957 + const { destPath, srcPath, warning } = (0, translate_url_to_sourcemap_paths_1.translateURLToSourcemapPaths)(url, options.swSrc, options.swDest); + if (warning) { + warnings.push(warning); + } + // If our swSrc file contains a sourcemap, we would invalidate that + // mapping if we just replaced injectionPoint with the stringified manifest. + // Instead, we need to update the swDest contents as well as the sourcemap + // (assuming it's a real file, not a data: URL) at the same time. + // See https://github.com/GoogleChrome/workbox/issues/2235 + // and https://github.com/GoogleChrome/workbox/issues/2648 + if (srcPath && destPath) { + const originalMap = (await fs_extra_1.default.readJSON(srcPath, { + encoding: 'utf8', + })); + const { map, source } = await (0, replace_and_update_source_map_1.replaceAndUpdateSourceMap)({ + originalMap, + jsFilename: upath_1.default.basename(options.swDest), + originalSource: swFileContents, + replaceString: manifestString, + searchString: options.injectionPoint, + }); + filesToWrite[options.swDest] = source; + filesToWrite[destPath] = map; + } + else { + // If there's no sourcemap associated with swSrc, a simple string + // replacement will suffice. + filesToWrite[options.swDest] = swFileContents.replace(globalRegexp, manifestString); + } + for (const [file, contents] of Object.entries(filesToWrite)) { + try { + await fs_extra_1.default.mkdirp(upath_1.default.dirname(file)); + } + catch (error) { + throw new Error(errors_1.errors['unable-to-make-sw-directory'] + + ` '${error instanceof Error && error.message ? error.message : ''}'`); + } + await fs_extra_1.default.writeFile(file, contents); + } + return { + count, + size, + warnings, + // Use upath.resolve() to make all the paths absolute. + filePaths: Object.keys(filesToWrite).map((f) => upath_1.default.resolve(f)), + }; +} +exports.injectManifest = injectManifest; diff --git a/node_modules/workbox-build/build/lib/additional-manifest-entries-transform.d.ts b/node_modules/workbox-build/build/lib/additional-manifest-entries-transform.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..566c70ac0b4edca6460acdd3d6dde8205a78c3a8 --- /dev/null +++ b/node_modules/workbox-build/build/lib/additional-manifest-entries-transform.d.ts @@ -0,0 +1,13 @@ +import { ManifestEntry } from '../types'; +type AdditionalManifestEntriesTransform = { + (manifest: Array): { + manifest: Array; + warnings: string[]; + }; +}; +export declare function additionalManifestEntriesTransform(additionalManifestEntries: Array): AdditionalManifestEntriesTransform; +export {}; diff --git a/node_modules/workbox-build/build/lib/additional-manifest-entries-transform.js b/node_modules/workbox-build/build/lib/additional-manifest-entries-transform.js new file mode 100644 index 0000000000000000000000000000000000000000..454025ba22c10967ad44d647a880dda862786742 --- /dev/null +++ b/node_modules/workbox-build/build/lib/additional-manifest-entries-transform.js @@ -0,0 +1,47 @@ +"use strict"; +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.additionalManifestEntriesTransform = void 0; +const errors_1 = require("./errors"); +function additionalManifestEntriesTransform(additionalManifestEntries) { + return (manifest) => { + const warnings = []; + const stringEntries = new Set(); + for (const additionalEntry of additionalManifestEntries) { + // Warn about either a string or an object that lacks a revision property. + // (An object with a revision property set to null is okay.) + if (typeof additionalEntry === 'string') { + stringEntries.add(additionalEntry); + manifest.push({ + revision: null, + size: 0, + url: additionalEntry, + }); + } + else { + if (additionalEntry && additionalEntry.revision === undefined) { + stringEntries.add(additionalEntry.url); + } + manifest.push(Object.assign({ size: 0 }, additionalEntry)); + } + } + if (stringEntries.size > 0) { + let urls = '\n'; + for (const stringEntry of stringEntries) { + urls += ` - ${stringEntry}\n`; + } + warnings.push(errors_1.errors['string-entry-warning'] + urls); + } + return { + manifest, + warnings, + }; + }; +} +exports.additionalManifestEntriesTransform = additionalManifestEntriesTransform; diff --git a/node_modules/workbox-build/build/lib/bundle.d.ts b/node_modules/workbox-build/build/lib/bundle.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6f336f6eb154dd26b15ee063e418aba0ab715ce1 --- /dev/null +++ b/node_modules/workbox-build/build/lib/bundle.d.ts @@ -0,0 +1,9 @@ +import { GeneratePartial, RequiredSWDestPartial } from '../types'; +interface NameAndContents { + contents: string | Uint8Array; + name: string; +} +export declare function bundle({ babelPresetEnvTargets, inlineWorkboxRuntime, mode, sourcemap, swDest, unbundledCode, }: Omit & RequiredSWDestPartial & { + unbundledCode: string; +}): Promise>; +export {}; diff --git a/node_modules/workbox-build/build/lib/bundle.js b/node_modules/workbox-build/build/lib/bundle.js new file mode 100644 index 0000000000000000000000000000000000000000..f31d54eefaca68c5ef8f3819f442504017b067dd --- /dev/null +++ b/node_modules/workbox-build/build/lib/bundle.js @@ -0,0 +1,133 @@ +"use strict"; +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.bundle = void 0; +const plugin_babel_1 = require("@rollup/plugin-babel"); +const plugin_node_resolve_1 = require("@rollup/plugin-node-resolve"); +const rollup_1 = require("rollup"); +const plugin_terser_1 = __importDefault(require("@rollup/plugin-terser")); +const fs_extra_1 = require("fs-extra"); +const rollup_plugin_off_main_thread_1 = __importDefault(require("@trickfilm400/rollup-plugin-off-main-thread")); +const preset_env_1 = __importDefault(require("@babel/preset-env")); +const plugin_replace_1 = __importDefault(require("@rollup/plugin-replace")); +const tempy_1 = __importDefault(require("tempy")); +const upath_1 = __importDefault(require("upath")); +async function bundle({ babelPresetEnvTargets, inlineWorkboxRuntime, mode, sourcemap, swDest, unbundledCode, }) { + // We need to write this to the "real" file system, as Rollup won't read from + // a custom file system. + const { dir, base } = upath_1.default.parse(swDest); + const temporaryFile = tempy_1.default.file({ name: base }); + await (0, fs_extra_1.writeFile)(temporaryFile, unbundledCode); + const plugins = [ + (0, plugin_node_resolve_1.nodeResolve)(), + (0, plugin_replace_1.default)({ + // See https://github.com/GoogleChrome/workbox/issues/2769 + 'preventAssignment': true, + 'process.env.NODE_ENV': JSON.stringify(mode), + }), + (0, plugin_babel_1.babel)({ + babelHelpers: 'bundled', + // Disable the logic that checks for local Babel config files: + // https://github.com/GoogleChrome/workbox/issues/2111 + babelrc: false, + configFile: false, + presets: [ + [ + preset_env_1.default, + { + targets: { + browsers: babelPresetEnvTargets, + }, + loose: true, + }, + ], + ], + }), + ]; + if (mode === 'production') { + plugins.push((0, plugin_terser_1.default)({ + mangle: { + toplevel: true, + properties: { + regex: /(^_|_$)/, + }, + }, + })); + } + const rollupConfig = { + plugins, + input: temporaryFile, + }; + // Rollup will inline the runtime by default. If we don't want that, we need + // to add in some additional config. + if (!inlineWorkboxRuntime) { + // No lint for omt(), library has no types. + // eslint-disable-next-line @typescript-eslint/no-unsafe-call + rollupConfig.plugins.unshift((0, rollup_plugin_off_main_thread_1.default)()); + } + const bundle = await (0, rollup_1.rollup)(rollupConfig); + const outputOptions = { + sourcemap, + // Using an external Workbox runtime requires 'amd'. + format: inlineWorkboxRuntime ? 'es' : 'amd', + }; + if (!inlineWorkboxRuntime) { + outputOptions.manualChunks = (id) => { + return id.includes('workbox') ? 'workbox' : undefined; + }; + outputOptions.hashCharacters = 'hex'; + } + const { output } = await bundle.generate(outputOptions); + const files = []; + for (const chunkOrAsset of output) { + if (chunkOrAsset.type === 'asset') { + if (!files.some((f) => f.name === chunkOrAsset.fileName)) { + files.push({ + name: chunkOrAsset.fileName, + contents: chunkOrAsset.source, + }); + } + } + else { + let code = chunkOrAsset.code; + if (chunkOrAsset.map) { + const sourceMapFile = chunkOrAsset.fileName + '.map'; + code += `//# sourceMappingURL=${sourceMapFile}\n`; + if (!files.some((f) => f.name === sourceMapFile)) { + files.push({ + name: sourceMapFile, + contents: chunkOrAsset.map.toString(), + }); + } + } + if (!files.some((f) => f.name === chunkOrAsset.fileName)) { + files.push({ + name: chunkOrAsset.fileName, + contents: code, + }); + } + } + } + // Make sure that if there was a directory portion included in swDest, it's + // preprended to all of the generated files. + return files.map((file) => { + file.name = upath_1.default.format({ + dir, + base: file.name, + ext: '', + name: '', + root: '', + }); + return file; + }); +} +exports.bundle = bundle; diff --git a/node_modules/workbox-build/build/lib/cdn-utils.d.ts b/node_modules/workbox-build/build/lib/cdn-utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..39f86fc0ed77cec09e0892a9de7c5f0abc9b8e06 --- /dev/null +++ b/node_modules/workbox-build/build/lib/cdn-utils.d.ts @@ -0,0 +1,2 @@ +import { BuildType } from '../types'; +export declare function getModuleURL(moduleName: string, buildType: BuildType): string; diff --git a/node_modules/workbox-build/build/lib/cdn-utils.js b/node_modules/workbox-build/build/lib/cdn-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..80ddc97f990545328fc46173f92bb09dd9f7aa56 --- /dev/null +++ b/node_modules/workbox-build/build/lib/cdn-utils.js @@ -0,0 +1,57 @@ +"use strict"; +/* + Copyright 2021 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getModuleURL = void 0; +const assert_1 = require("assert"); +const errors_1 = require("./errors"); +const cdn = __importStar(require("../cdn-details.json")); +function getVersionedURL() { + return `${getCDNPrefix()}/${cdn.latestVersion}`; +} +function getCDNPrefix() { + return `${cdn.origin}/${cdn.bucketName}/${cdn.releasesDir}`; +} +function getModuleURL(moduleName, buildType) { + (0, assert_1.ok)(moduleName, errors_1.errors['no-module-name']); + if (buildType) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const pkgJson = require(`${moduleName}/package.json`); + if (buildType === 'dev' && pkgJson.workbox && pkgJson.workbox.prodOnly) { + // This is not due to a public-facing exception, so just throw an Error(), + // without creating an entry in errors.js. + throw Error(`The 'dev' build of ${moduleName} is not available.`); + } + return `${getVersionedURL()}/${moduleName}.${buildType.slice(0, 4)}.js`; + } + return `${getVersionedURL()}/${moduleName}.js`; +} +exports.getModuleURL = getModuleURL; diff --git a/node_modules/workbox-build/build/lib/copy-workbox-libraries.d.ts b/node_modules/workbox-build/build/lib/copy-workbox-libraries.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4906368cb25cc2e5b044303fbb53e006c003bf10 --- /dev/null +++ b/node_modules/workbox-build/build/lib/copy-workbox-libraries.d.ts @@ -0,0 +1,20 @@ +/** + * This copies over a set of runtime libraries used by Workbox into a + * local directory, which should be deployed alongside your service worker file. + * + * As an alternative to deploying these local copies, you could instead use + * Workbox from its official CDN URL. + * + * This method is exposed for the benefit of developers using + * {@link workbox-build.injectManifest} who would + * prefer not to use the CDN copies of Workbox. Developers using + * {@link workbox-build.generateSW} don't need to + * explicitly call this method. + * + * @param {string} destDirectory The path to the parent directory under which + * the new directory of libraries will be created. + * @return {Promise} The name of the newly created directory. + * + * @alias workbox-build.copyWorkboxLibraries + */ +export declare function copyWorkboxLibraries(destDirectory: string): Promise; diff --git a/node_modules/workbox-build/build/lib/copy-workbox-libraries.js b/node_modules/workbox-build/build/lib/copy-workbox-libraries.js new file mode 100644 index 0000000000000000000000000000000000000000..5d58a9efe75c67a63df51cac66bd896e32ada1ce --- /dev/null +++ b/node_modules/workbox-build/build/lib/copy-workbox-libraries.js @@ -0,0 +1,69 @@ +"use strict"; +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.copyWorkboxLibraries = void 0; +const fs_extra_1 = __importDefault(require("fs-extra")); +const upath_1 = __importDefault(require("upath")); +const errors_1 = require("./errors"); +// Used to filter the libraries to copy based on our package.json dependencies. +const WORKBOX_PREFIX = 'workbox-'; +// The directory within each package containing the final bundles. +const BUILD_DIR = 'build'; +/** + * This copies over a set of runtime libraries used by Workbox into a + * local directory, which should be deployed alongside your service worker file. + * + * As an alternative to deploying these local copies, you could instead use + * Workbox from its official CDN URL. + * + * This method is exposed for the benefit of developers using + * {@link workbox-build.injectManifest} who would + * prefer not to use the CDN copies of Workbox. Developers using + * {@link workbox-build.generateSW} don't need to + * explicitly call this method. + * + * @param {string} destDirectory The path to the parent directory under which + * the new directory of libraries will be created. + * @return {Promise} The name of the newly created directory. + * + * @alias workbox-build.copyWorkboxLibraries + */ +async function copyWorkboxLibraries(destDirectory) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const thisPkg = require('../../package.json'); + // Use the version string from workbox-build in the name of the parent + // directory. This should be safe, because lerna will bump workbox-build's + // pkg.version whenever one of the dependent libraries gets bumped, and we + // care about versioning the dependent libraries. + const workboxDirectoryName = `workbox-v${thisPkg.version ? thisPkg.version : ''}`; + const workboxDirectoryPath = upath_1.default.join(destDirectory, workboxDirectoryName); + await fs_extra_1.default.ensureDir(workboxDirectoryPath); + const copyPromises = []; + const librariesToCopy = Object.keys(thisPkg.dependencies || {}).filter((dependency) => dependency.startsWith(WORKBOX_PREFIX)); + for (const library of librariesToCopy) { + // Get the path to the package on the user's filesystem by require-ing + // the package's `package.json` file via the node resolution algorithm. + const libraryPath = upath_1.default.dirname(require.resolve(`${library}/package.json`)); + const buildPath = upath_1.default.join(libraryPath, BUILD_DIR); + // fse.copy() copies all the files in a directory, not the directory itself. + // See https://github.com/jprichardson/node-fs-extra/blob/master/docs/copy.md#copysrc-dest-options-callback + copyPromises.push(fs_extra_1.default.copy(buildPath, workboxDirectoryPath)); + } + try { + await Promise.all(copyPromises); + return workboxDirectoryName; + } + catch (error) { + throw Error(`${errors_1.errors['unable-to-copy-workbox-libraries']} ${error instanceof Error ? error.toString() : ''}`); + } +} +exports.copyWorkboxLibraries = copyWorkboxLibraries; diff --git a/node_modules/workbox-build/build/lib/errors.d.ts b/node_modules/workbox-build/build/lib/errors.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..31b1642d164ff945ff65e709dcd835c1b12f84d7 --- /dev/null +++ b/node_modules/workbox-build/build/lib/errors.d.ts @@ -0,0 +1,61 @@ +export declare const errors: { + 'unable-to-get-rootdir': string; + 'no-extension': string; + 'invalid-file-manifest-name': string; + 'unable-to-get-file-manifest-name': string; + 'invalid-sw-dest': string; + 'unable-to-get-sw-name': string; + 'unable-to-get-save-config': string; + 'unable-to-get-file-hash': string; + 'unable-to-get-file-size': string; + 'unable-to-glob-files': string; + 'unable-to-make-manifest-directory': string; + 'read-manifest-template-failure': string; + 'populating-manifest-tmpl-failed': string; + 'manifest-file-write-failure': string; + 'unable-to-make-sw-directory': string; + 'read-sw-template-failure': string; + 'sw-write-failure': string; + 'sw-write-failure-directory': string; + 'unable-to-copy-workbox-libraries': string; + 'invalid-generate-sw-input': string; + 'invalid-glob-directory': string; + 'invalid-dont-cache-bust': string; + 'invalid-exclude-files': string; + 'invalid-get-manifest-entries-input': string; + 'invalid-manifest-path': string; + 'invalid-manifest-entries': string; + 'invalid-manifest-format': string; + 'invalid-static-file-globs': string; + 'invalid-templated-urls': string; + 'templated-url-matches-glob': string; + 'invalid-glob-ignores': string; + 'manifest-entry-bad-url': string; + 'modify-url-prefix-bad-prefixes': string; + 'invalid-inject-manifest-arg': string; + 'injection-point-not-found': string; + 'multiple-injection-points': string; + 'populating-sw-tmpl-failed': string; + 'useless-glob-pattern': string; + 'bad-template-urls-asset': string; + 'invalid-runtime-caching': string; + 'static-file-globs-deprecated': string; + 'dynamic-url-deprecated': string; + 'urlPattern-is-required': string; + 'handler-is-required': string; + 'invalid-generate-file-manifest-arg': string; + 'invalid-sw-src': string; + 'same-src-and-dest': string; + 'only-regexp-routes-supported': string; + 'bad-runtime-caching-config': string; + 'invalid-network-timeout-seconds': string; + 'no-module-name': string; + 'bad-manifest-transforms-return-value': string; + 'string-entry-warning': string; + 'no-manifest-entries-or-runtime-caching': string; + 'cant-find-sourcemap': string; + 'nav-preload-runtime-caching': string; + 'cache-name-required': string; + 'manifest-transforms': string; + 'invalid-handler-string': string; +}; diff --git a/node_modules/workbox-build/build/lib/errors.js b/node_modules/workbox-build/build/lib/errors.js new file mode 100644 index 0000000000000000000000000000000000000000..bb28236a38a7a547d6c4950c98f4cbdab442288e --- /dev/null +++ b/node_modules/workbox-build/build/lib/errors.js @@ -0,0 +1,125 @@ +"use strict"; +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.errors = void 0; +const common_tags_1 = require("common-tags"); +exports.errors = { + 'unable-to-get-rootdir': `Unable to get the root directory of your web app.`, + 'no-extension': (0, common_tags_1.oneLine) `Unable to detect a usable extension for a file in your web + app directory.`, + 'invalid-file-manifest-name': (0, common_tags_1.oneLine) `The File Manifest Name must have at least one + character.`, + 'unable-to-get-file-manifest-name': 'Unable to get a file manifest name.', + 'invalid-sw-dest': `The 'swDest' value must be a valid path.`, + 'unable-to-get-sw-name': 'Unable to get a service worker file name.', + 'unable-to-get-save-config': (0, common_tags_1.oneLine) `An error occurred when asking to save details + in a config file.`, + 'unable-to-get-file-hash': (0, common_tags_1.oneLine) `An error occurred when attempting to create a + file hash.`, + 'unable-to-get-file-size': (0, common_tags_1.oneLine) `An error occurred when attempting to get a file + size.`, + 'unable-to-glob-files': 'An error occurred when globbing for files.', + 'unable-to-make-manifest-directory': (0, common_tags_1.oneLine) `Unable to make output directory for + file manifest.`, + 'read-manifest-template-failure': 'Unable to read template for file manifest', + 'populating-manifest-tmpl-failed': (0, common_tags_1.oneLine) `An error occurred when populating the + file manifest template.`, + 'manifest-file-write-failure': 'Unable to write the file manifest.', + 'unable-to-make-sw-directory': (0, common_tags_1.oneLine) `Unable to make the directories to output + the service worker path.`, + 'read-sw-template-failure': (0, common_tags_1.oneLine) `Unable to read the service worker template + file.`, + 'sw-write-failure': 'Unable to write the service worker file.', + 'sw-write-failure-directory': (0, common_tags_1.oneLine) `Unable to write the service worker file; + 'swDest' should be a full path to the file, not a path to a directory.`, + 'unable-to-copy-workbox-libraries': (0, common_tags_1.oneLine) `One or more of the Workbox libraries + could not be copied over to the destination directory: `, + 'invalid-generate-sw-input': (0, common_tags_1.oneLine) `The input to generateSW() must be an object.`, + 'invalid-glob-directory': (0, common_tags_1.oneLine) `The supplied globDirectory must be a path as a + string.`, + 'invalid-dont-cache-bust': (0, common_tags_1.oneLine) `The supplied 'dontCacheBustURLsMatching' + parameter must be a RegExp.`, + 'invalid-exclude-files': 'The excluded files should be an array of strings.', + 'invalid-get-manifest-entries-input': (0, common_tags_1.oneLine) `The input to + 'getFileManifestEntries()' must be an object.`, + 'invalid-manifest-path': (0, common_tags_1.oneLine) `The supplied manifest path is not a string with + at least one character.`, + 'invalid-manifest-entries': (0, common_tags_1.oneLine) `The manifest entries must be an array of + strings or JavaScript objects containing a url parameter.`, + 'invalid-manifest-format': (0, common_tags_1.oneLine) `The value of the 'format' option passed to + generateFileManifest() must be either 'iife' (the default) or 'es'.`, + 'invalid-static-file-globs': (0, common_tags_1.oneLine) `The 'globPatterns' value must be an array + of strings.`, + 'invalid-templated-urls': (0, common_tags_1.oneLine) `The 'templatedURLs' value should be an object + that maps URLs to either a string, or to an array of glob patterns.`, + 'templated-url-matches-glob': (0, common_tags_1.oneLine) `One of the 'templatedURLs' URLs is already + being tracked via 'globPatterns': `, + 'invalid-glob-ignores': (0, common_tags_1.oneLine) `The 'globIgnores' parameter must be an array of + glob pattern strings.`, + 'manifest-entry-bad-url': (0, common_tags_1.oneLine) `The generated manifest contains an entry without + a URL string. This is likely an error with workbox-build.`, + 'modify-url-prefix-bad-prefixes': (0, common_tags_1.oneLine) `The 'modifyURLPrefix' parameter must be + an object with string key value pairs.`, + 'invalid-inject-manifest-arg': (0, common_tags_1.oneLine) `The input to 'injectManifest()' must be an + object.`, + 'injection-point-not-found': (0, common_tags_1.oneLine) `Unable to find a place to inject the manifest. + Please ensure that your service worker file contains the following: `, + 'multiple-injection-points': (0, common_tags_1.oneLine) `Please ensure that your 'swSrc' file contains + only one match for the following: `, + 'populating-sw-tmpl-failed': (0, common_tags_1.oneLine) `Unable to generate service worker from + template.`, + 'useless-glob-pattern': (0, common_tags_1.oneLine) `One of the glob patterns doesn't match any files. + Please remove or fix the following: `, + 'bad-template-urls-asset': (0, common_tags_1.oneLine) `There was an issue using one of the provided + 'templatedURLs'.`, + 'invalid-runtime-caching': (0, common_tags_1.oneLine) `The 'runtimeCaching' parameter must an an + array of objects with at least a 'urlPattern' and 'handler'.`, + 'static-file-globs-deprecated': (0, common_tags_1.oneLine) `'staticFileGlobs' is deprecated. + Please use 'globPatterns' instead.`, + 'dynamic-url-deprecated': (0, common_tags_1.oneLine) `'dynamicURLToDependencies' is deprecated. + Please use 'templatedURLs' instead.`, + 'urlPattern-is-required': (0, common_tags_1.oneLine) `The 'urlPattern' option is required when using + 'runtimeCaching'.`, + 'handler-is-required': (0, common_tags_1.oneLine) `The 'handler' option is required when using + runtimeCaching.`, + 'invalid-generate-file-manifest-arg': (0, common_tags_1.oneLine) `The input to generateFileManifest() + must be an Object.`, + 'invalid-sw-src': `The 'swSrc' file can't be read.`, + 'same-src-and-dest': (0, common_tags_1.oneLine) `Unable to find a place to inject the manifest. This is + likely because swSrc and swDest are configured to the same file. + Please ensure that your swSrc file contains the following:`, + 'only-regexp-routes-supported': (0, common_tags_1.oneLine) `Please use a regular expression object as + the urlPattern parameter. (Express-style routes are not currently + supported.)`, + 'bad-runtime-caching-config': (0, common_tags_1.oneLine) `An unknown configuration option was used + with runtimeCaching: `, + 'invalid-network-timeout-seconds': (0, common_tags_1.oneLine) `When using networkTimeoutSeconds, you + must set the handler to 'NetworkFirst'.`, + 'no-module-name': (0, common_tags_1.oneLine) `You must provide a moduleName parameter when calling + getModuleURL().`, + 'bad-manifest-transforms-return-value': (0, common_tags_1.oneLine) `The return value from a + manifestTransform should be an object with 'manifest' and optionally + 'warnings' properties.`, + 'string-entry-warning': (0, common_tags_1.oneLine) `Some items were passed to additionalManifestEntries + without revisioning info. This is generally NOT safe. Learn more at + https://bit.ly/wb-precache.`, + 'no-manifest-entries-or-runtime-caching': (0, common_tags_1.oneLine) `Couldn't find configuration for + either precaching or runtime caching. Please ensure that the various glob + options are set to match one or more files, and/or configure the + runtimeCaching option.`, + 'cant-find-sourcemap': (0, common_tags_1.oneLine) `The swSrc file refers to a sourcemap that can't be + opened:`, + 'nav-preload-runtime-caching': (0, common_tags_1.oneLine) `When using navigationPreload, you must also + configure a runtimeCaching route that will use the preloaded response.`, + 'cache-name-required': (0, common_tags_1.oneLine) `When using cache expiration, you must also + configure a custom cacheName.`, + 'manifest-transforms': (0, common_tags_1.oneLine) `When using manifestTransforms, you must provide + an array of functions.`, + 'invalid-handler-string': (0, common_tags_1.oneLine) `The handler name provided is not valid: `, +}; diff --git a/node_modules/workbox-build/build/lib/escape-regexp.d.ts b/node_modules/workbox-build/build/lib/escape-regexp.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e2ab07babd7f730546975d9b8d9857f66c3cc11a --- /dev/null +++ b/node_modules/workbox-build/build/lib/escape-regexp.d.ts @@ -0,0 +1 @@ +export declare function escapeRegExp(str: string): string; diff --git a/node_modules/workbox-build/build/lib/escape-regexp.js b/node_modules/workbox-build/build/lib/escape-regexp.js new file mode 100644 index 0000000000000000000000000000000000000000..c7291ac92825b3a2cff98b51b99be92bfa416f5d --- /dev/null +++ b/node_modules/workbox-build/build/lib/escape-regexp.js @@ -0,0 +1,15 @@ +"use strict"; +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.escapeRegExp = void 0; +// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions +function escapeRegExp(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} +exports.escapeRegExp = escapeRegExp; diff --git a/node_modules/workbox-build/build/lib/get-composite-details.d.ts b/node_modules/workbox-build/build/lib/get-composite-details.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c40ede5e7974363fa54b1b318092ffc596c2c8cb --- /dev/null +++ b/node_modules/workbox-build/build/lib/get-composite-details.d.ts @@ -0,0 +1,2 @@ +import { FileDetails } from '../types'; +export declare function getCompositeDetails(compositeURL: string, dependencyDetails: Array): FileDetails; diff --git a/node_modules/workbox-build/build/lib/get-composite-details.js b/node_modules/workbox-build/build/lib/get-composite-details.js new file mode 100644 index 0000000000000000000000000000000000000000..17f4e877748b76889a4ea443b884b964e1cb498a --- /dev/null +++ b/node_modules/workbox-build/build/lib/get-composite-details.js @@ -0,0 +1,31 @@ +"use strict"; +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getCompositeDetails = void 0; +const crypto_1 = __importDefault(require("crypto")); +function getCompositeDetails(compositeURL, dependencyDetails) { + let totalSize = 0; + let compositeHash = ''; + for (const fileDetails of dependencyDetails) { + totalSize += fileDetails.size; + compositeHash += fileDetails.hash; + } + const md5 = crypto_1.default.createHash('md5'); + md5.update(compositeHash); + const hashOfHashes = md5.digest('hex'); + return { + file: compositeURL, + hash: hashOfHashes, + size: totalSize, + }; +} +exports.getCompositeDetails = getCompositeDetails; diff --git a/node_modules/workbox-build/build/lib/get-file-details.d.ts b/node_modules/workbox-build/build/lib/get-file-details.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..eb7460ddb9c74e9182b68d6b7f724fa63f2d60a0 --- /dev/null +++ b/node_modules/workbox-build/build/lib/get-file-details.d.ts @@ -0,0 +1,14 @@ +import { GlobPartial } from '../types'; +interface FileDetails { + file: string; + hash: string; + size: number; +} +export declare function getFileDetails({ globDirectory, globFollow, globIgnores, globPattern, }: Omit & { + globDirectory: string; + globPattern: string; +}): { + globbedFileDetails: Array; + warning: string; +}; +export {}; diff --git a/node_modules/workbox-build/build/lib/get-file-details.js b/node_modules/workbox-build/build/lib/get-file-details.js new file mode 100644 index 0000000000000000000000000000000000000000..0287db05f57e3168cbcf734602dcda6640af32cb --- /dev/null +++ b/node_modules/workbox-build/build/lib/get-file-details.js @@ -0,0 +1,54 @@ +"use strict"; +/* + Copyright 2021 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getFileDetails = void 0; +const glob_1 = require("glob"); +const upath_1 = __importDefault(require("upath")); +const errors_1 = require("./errors"); +const get_file_size_1 = require("./get-file-size"); +const get_file_hash_1 = require("./get-file-hash"); +function getFileDetails({ globDirectory, globFollow, globIgnores, globPattern, }) { + let globbedFiles; + let warning = ''; + try { + globbedFiles = (0, glob_1.globSync)(globPattern, { + cwd: globDirectory, + follow: globFollow, + ignore: globIgnores, + }); + } + catch (err) { + throw new Error(errors_1.errors['unable-to-glob-files'] + + ` '${err instanceof Error && err.message ? err.message : ''}'`); + } + if (globbedFiles.length === 0) { + warning = + errors_1.errors['useless-glob-pattern'] + + ' ' + + JSON.stringify({ globDirectory, globPattern, globIgnores }, null, 2); + } + const globbedFileDetails = []; + for (const file of globbedFiles) { + const fullPath = upath_1.default.join(globDirectory, file); + const fileSize = (0, get_file_size_1.getFileSize)(fullPath); + if (fileSize !== null) { + const fileHash = (0, get_file_hash_1.getFileHash)(fullPath); + globbedFileDetails.push({ + file: `${upath_1.default.relative(globDirectory, fullPath)}`, + hash: fileHash, + size: fileSize, + }); + } + } + return { globbedFileDetails, warning }; +} +exports.getFileDetails = getFileDetails; diff --git a/node_modules/workbox-build/build/lib/get-file-hash.d.ts b/node_modules/workbox-build/build/lib/get-file-hash.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3b2973fc67244a493ebce5305c3266d9ee86d711 --- /dev/null +++ b/node_modules/workbox-build/build/lib/get-file-hash.d.ts @@ -0,0 +1 @@ +export declare function getFileHash(file: string): string; diff --git a/node_modules/workbox-build/build/lib/get-file-hash.js b/node_modules/workbox-build/build/lib/get-file-hash.js new file mode 100644 index 0000000000000000000000000000000000000000..4371484bfd72dee8604656d66c4bb4b5cebe65e2 --- /dev/null +++ b/node_modules/workbox-build/build/lib/get-file-hash.js @@ -0,0 +1,27 @@ +"use strict"; +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getFileHash = void 0; +const fs_extra_1 = __importDefault(require("fs-extra")); +const get_string_hash_1 = require("./get-string-hash"); +const errors_1 = require("./errors"); +function getFileHash(file) { + try { + const buffer = fs_extra_1.default.readFileSync(file); + return (0, get_string_hash_1.getStringHash)(buffer); + } + catch (err) { + throw new Error(errors_1.errors['unable-to-get-file-hash'] + + ` '${err instanceof Error && err.message ? err.message : ''}'`); + } +} +exports.getFileHash = getFileHash; diff --git a/node_modules/workbox-build/build/lib/get-file-manifest-entries.d.ts b/node_modules/workbox-build/build/lib/get-file-manifest-entries.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..87789f4dc01c264fbd6ca32b67d37b333baf17a2 --- /dev/null +++ b/node_modules/workbox-build/build/lib/get-file-manifest-entries.d.ts @@ -0,0 +1,2 @@ +import { GetManifestResult, GetManifestOptions } from '../types'; +export declare function getFileManifestEntries({ additionalManifestEntries, dontCacheBustURLsMatching, globDirectory, globFollow, globIgnores, globPatterns, manifestTransforms, maximumFileSizeToCacheInBytes, modifyURLPrefix, templatedURLs, }: GetManifestOptions): Promise; diff --git a/node_modules/workbox-build/build/lib/get-file-manifest-entries.js b/node_modules/workbox-build/build/lib/get-file-manifest-entries.js new file mode 100644 index 0000000000000000000000000000000000000000..3b550f72e0c4909d917b2cfd0f6393c6ac8ae971 --- /dev/null +++ b/node_modules/workbox-build/build/lib/get-file-manifest-entries.js @@ -0,0 +1,96 @@ +"use strict"; +/* + Copyright 2021 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getFileManifestEntries = void 0; +const assert_1 = __importDefault(require("assert")); +const errors_1 = require("./errors"); +const get_composite_details_1 = require("./get-composite-details"); +const get_file_details_1 = require("./get-file-details"); +const get_string_details_1 = require("./get-string-details"); +const transform_manifest_1 = require("./transform-manifest"); +async function getFileManifestEntries({ additionalManifestEntries, dontCacheBustURLsMatching, globDirectory, globFollow, globIgnores, globPatterns = [], manifestTransforms, maximumFileSizeToCacheInBytes, modifyURLPrefix, templatedURLs, }) { + const warnings = []; + const allFileDetails = new Map(); + try { + for (const globPattern of globPatterns) { + const { globbedFileDetails, warning } = (0, get_file_details_1.getFileDetails)({ + globDirectory, + globFollow, + globIgnores, + globPattern, + }); + if (warning) { + warnings.push(warning); + } + for (const details of globbedFileDetails) { + if (details && !allFileDetails.has(details.file)) { + allFileDetails.set(details.file, details); + } + } + } + } + catch (error) { + // If there's an exception thrown while globbing, then report + // it back as a warning, and don't consider it fatal. + if (error instanceof Error && error.message) { + warnings.push(error.message); + } + } + if (templatedURLs) { + for (const url of Object.keys(templatedURLs)) { + (0, assert_1.default)(!allFileDetails.has(url), errors_1.errors['templated-url-matches-glob']); + const dependencies = templatedURLs[url]; + if (Array.isArray(dependencies)) { + const details = dependencies.reduce((previous, globPattern) => { + try { + const { globbedFileDetails, warning } = (0, get_file_details_1.getFileDetails)({ + globDirectory, + globFollow, + globIgnores, + globPattern, + }); + if (warning) { + warnings.push(warning); + } + return previous.concat(globbedFileDetails); + } + catch (error) { + const debugObj = {}; + debugObj[url] = dependencies; + throw new Error(`${errors_1.errors['bad-template-urls-asset']} ` + + `'${globPattern}' from '${JSON.stringify(debugObj)}':\n` + + `${error instanceof Error ? error.toString() : ''}`); + } + }, []); + if (details.length === 0) { + throw new Error(`${errors_1.errors['bad-template-urls-asset']} The glob ` + + `pattern '${dependencies.toString()}' did not match anything.`); + } + allFileDetails.set(url, (0, get_composite_details_1.getCompositeDetails)(url, details)); + } + else if (typeof dependencies === 'string') { + allFileDetails.set(url, (0, get_string_details_1.getStringDetails)(url, dependencies)); + } + } + } + const transformedManifest = await (0, transform_manifest_1.transformManifest)({ + additionalManifestEntries, + dontCacheBustURLsMatching, + manifestTransforms, + maximumFileSizeToCacheInBytes, + modifyURLPrefix, + fileDetails: Array.from(allFileDetails.values()), + }); + transformedManifest.warnings.push(...warnings); + return transformedManifest; +} +exports.getFileManifestEntries = getFileManifestEntries; diff --git a/node_modules/workbox-build/build/lib/get-file-size.d.ts b/node_modules/workbox-build/build/lib/get-file-size.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..76462b33a8bf70d59a936ba0b2b6b12d236b1ce3 --- /dev/null +++ b/node_modules/workbox-build/build/lib/get-file-size.d.ts @@ -0,0 +1 @@ +export declare function getFileSize(file: string): number | null; diff --git a/node_modules/workbox-build/build/lib/get-file-size.js b/node_modules/workbox-build/build/lib/get-file-size.js new file mode 100644 index 0000000000000000000000000000000000000000..cb9dd1e19d55e34f3fc4cd8bfae61928e93915d7 --- /dev/null +++ b/node_modules/workbox-build/build/lib/get-file-size.js @@ -0,0 +1,29 @@ +"use strict"; +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getFileSize = void 0; +const fs_extra_1 = __importDefault(require("fs-extra")); +const errors_1 = require("./errors"); +function getFileSize(file) { + try { + const stat = fs_extra_1.default.statSync(file); + if (!stat.isFile()) { + return null; + } + return stat.size; + } + catch (err) { + throw new Error(errors_1.errors['unable-to-get-file-size'] + + ` '${err instanceof Error && err.message ? err.message : ''}'`); + } +} +exports.getFileSize = getFileSize; diff --git a/node_modules/workbox-build/build/lib/get-source-map-url.d.ts b/node_modules/workbox-build/build/lib/get-source-map-url.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f08b5165de6c60fe693b2c8ec4b011f999c12b14 --- /dev/null +++ b/node_modules/workbox-build/build/lib/get-source-map-url.d.ts @@ -0,0 +1 @@ +export declare function getSourceMapURL(srcContents: string): string | null; diff --git a/node_modules/workbox-build/build/lib/get-source-map-url.js b/node_modules/workbox-build/build/lib/get-source-map-url.js new file mode 100644 index 0000000000000000000000000000000000000000..f62fea9b7c68f6f1b68d28529fd3b4142c7c986c --- /dev/null +++ b/node_modules/workbox-build/build/lib/get-source-map-url.js @@ -0,0 +1,32 @@ +"use strict"; +/* + Copyright 2022 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getSourceMapURL = void 0; +// Adapted from https://github.com/lydell/source-map-url/blob/master/source-map-url.js +// See https://github.com/GoogleChrome/workbox/issues/3019 +const innerRegex = /[#@] sourceMappingURL=([^\s'"]*)/; +const regex = RegExp('(?:' + + '/\\*' + + '(?:\\s*\r?\n(?://)?)?' + + '(?:' + + innerRegex.source + + ')' + + '\\s*' + + '\\*/' + + '|' + + '//(?:' + + innerRegex.source + + ')' + + ')' + + '\\s*'); +function getSourceMapURL(srcContents) { + const match = srcContents.match(regex); + return match ? match[1] || match[2] || '' : null; +} +exports.getSourceMapURL = getSourceMapURL; diff --git a/node_modules/workbox-build/build/lib/get-string-details.d.ts b/node_modules/workbox-build/build/lib/get-string-details.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bcfa96c0798d7e4821e3060124e982d82b78b9b5 --- /dev/null +++ b/node_modules/workbox-build/build/lib/get-string-details.d.ts @@ -0,0 +1,2 @@ +import { FileDetails } from '../types'; +export declare function getStringDetails(url: string, str: string): FileDetails; diff --git a/node_modules/workbox-build/build/lib/get-string-details.js b/node_modules/workbox-build/build/lib/get-string-details.js new file mode 100644 index 0000000000000000000000000000000000000000..8d1a86ff74b9d8bc7f785e40c93d18d7b07c4a13 --- /dev/null +++ b/node_modules/workbox-build/build/lib/get-string-details.js @@ -0,0 +1,19 @@ +"use strict"; +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getStringDetails = void 0; +const get_string_hash_1 = require("./get-string-hash"); +function getStringDetails(url, str) { + return { + file: url, + hash: (0, get_string_hash_1.getStringHash)(str), + size: str.length, + }; +} +exports.getStringDetails = getStringDetails; diff --git a/node_modules/workbox-build/build/lib/get-string-hash.d.ts b/node_modules/workbox-build/build/lib/get-string-hash.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..149f324fb45a076975d547ec12460e7c2cb6b210 --- /dev/null +++ b/node_modules/workbox-build/build/lib/get-string-hash.d.ts @@ -0,0 +1,3 @@ +/// +import crypto from 'crypto'; +export declare function getStringHash(input: crypto.BinaryLike): string; diff --git a/node_modules/workbox-build/build/lib/get-string-hash.js b/node_modules/workbox-build/build/lib/get-string-hash.js new file mode 100644 index 0000000000000000000000000000000000000000..645e285b75864de6261826a138fda4cd3c5fe3ca --- /dev/null +++ b/node_modules/workbox-build/build/lib/get-string-hash.js @@ -0,0 +1,20 @@ +"use strict"; +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getStringHash = void 0; +const crypto_1 = __importDefault(require("crypto")); +function getStringHash(input) { + const md5 = crypto_1.default.createHash('md5'); + md5.update(input); + return md5.digest('hex'); +} +exports.getStringHash = getStringHash; diff --git a/node_modules/workbox-build/build/lib/maximum-size-transform.d.ts b/node_modules/workbox-build/build/lib/maximum-size-transform.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8b2a5f5d6bffd4d41d3d338333e3e16544438b26 --- /dev/null +++ b/node_modules/workbox-build/build/lib/maximum-size-transform.d.ts @@ -0,0 +1,2 @@ +import { ManifestTransform } from '../types'; +export declare function maximumSizeTransform(maximumFileSizeToCacheInBytes: number): ManifestTransform; diff --git a/node_modules/workbox-build/build/lib/maximum-size-transform.js b/node_modules/workbox-build/build/lib/maximum-size-transform.js new file mode 100644 index 0000000000000000000000000000000000000000..f0ee5c91c957cf527b819698fbac000fe07d66c7 --- /dev/null +++ b/node_modules/workbox-build/build/lib/maximum-size-transform.js @@ -0,0 +1,30 @@ +"use strict"; +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.maximumSizeTransform = void 0; +const pretty_bytes_1 = __importDefault(require("pretty-bytes")); +function maximumSizeTransform(maximumFileSizeToCacheInBytes) { + return (originalManifest) => { + const warnings = []; + const manifest = originalManifest.filter((entry) => { + if (entry.size <= maximumFileSizeToCacheInBytes) { + return true; + } + warnings.push(`${entry.url} is ${(0, pretty_bytes_1.default)(entry.size)}, and won't ` + + `be precached. Configure maximumFileSizeToCacheInBytes to change ` + + `this limit.`); + return false; + }); + return { manifest, warnings }; + }; +} +exports.maximumSizeTransform = maximumSizeTransform; diff --git a/node_modules/workbox-build/build/lib/modify-url-prefix-transform.d.ts b/node_modules/workbox-build/build/lib/modify-url-prefix-transform.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..85bfa453850bbebe775af88fbdcf434ddded22c2 --- /dev/null +++ b/node_modules/workbox-build/build/lib/modify-url-prefix-transform.d.ts @@ -0,0 +1,4 @@ +import { ManifestTransform } from '../types'; +export declare function modifyURLPrefixTransform(modifyURLPrefix: { + [key: string]: string; +}): ManifestTransform; diff --git a/node_modules/workbox-build/build/lib/modify-url-prefix-transform.js b/node_modules/workbox-build/build/lib/modify-url-prefix-transform.js new file mode 100644 index 0000000000000000000000000000000000000000..714d8a963595bfed30ebea9404a42758091f15e1 --- /dev/null +++ b/node_modules/workbox-build/build/lib/modify-url-prefix-transform.js @@ -0,0 +1,51 @@ +"use strict"; +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.modifyURLPrefixTransform = void 0; +const errors_1 = require("./errors"); +const escape_regexp_1 = require("./escape-regexp"); +function modifyURLPrefixTransform(modifyURLPrefix) { + if (!modifyURLPrefix || + typeof modifyURLPrefix !== 'object' || + Array.isArray(modifyURLPrefix)) { + throw new Error(errors_1.errors['modify-url-prefix-bad-prefixes']); + } + // If there are no entries in modifyURLPrefix, just return an identity + // function as a shortcut. + if (Object.keys(modifyURLPrefix).length === 0) { + return (manifest) => { + return { manifest }; + }; + } + for (const key of Object.keys(modifyURLPrefix)) { + if (typeof modifyURLPrefix[key] !== 'string') { + throw new Error(errors_1.errors['modify-url-prefix-bad-prefixes']); + } + } + // Escape the user input so it's safe to use in a regex. + const safeModifyURLPrefixes = Object.keys(modifyURLPrefix).map(escape_regexp_1.escapeRegExp); + // Join all the `modifyURLPrefix` keys so a single regex can be used. + const prefixMatchesStrings = safeModifyURLPrefixes.join('|'); + // Add `^` to the front the prefix matches so it only matches the start of + // a string. + const modifyRegex = new RegExp(`^(${prefixMatchesStrings})`); + return (originalManifest) => { + const manifest = originalManifest.map((entry) => { + if (typeof entry.url !== 'string') { + throw new Error(errors_1.errors['manifest-entry-bad-url']); + } + entry.url = entry.url.replace(modifyRegex, (match) => { + return modifyURLPrefix[match]; + }); + return entry; + }); + return { manifest }; + }; +} +exports.modifyURLPrefixTransform = modifyURLPrefixTransform; diff --git a/node_modules/workbox-build/build/lib/module-registry.d.ts b/node_modules/workbox-build/build/lib/module-registry.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..52fd0c1b29c51a0bca22ba5def3bbc88dcd87f69 --- /dev/null +++ b/node_modules/workbox-build/build/lib/module-registry.d.ts @@ -0,0 +1,33 @@ +/** + * Class for keeping track of which Workbox modules are used by the generated + * service worker script. + * + * @private + */ +export declare class ModuleRegistry { + private readonly _modulesUsed; + /** + * @private + */ + constructor(); + /** + * @return {Array} A list of all of the import statements that are + * needed for the modules being used. + * @private + */ + getImportStatements(): Array; + /** + * @param {string} pkg The workbox package that the module belongs to. + * @param {string} moduleName The name of the module to import. + * @return {string} The local variable name that corresponds to that module. + * @private + */ + getLocalName(pkg: string, moduleName: string): string; + /** + * @param {string} pkg The workbox package that the module belongs to. + * @param {string} moduleName The name of the module to import. + * @return {string} The local variable name that corresponds to that module. + * @private + */ + use(pkg: string, moduleName: string): string; +} diff --git a/node_modules/workbox-build/build/lib/module-registry.js b/node_modules/workbox-build/build/lib/module-registry.js new file mode 100644 index 0000000000000000000000000000000000000000..9a34dd9d97965ad89e95da4af6ae74042b7fccaf --- /dev/null +++ b/node_modules/workbox-build/build/lib/module-registry.js @@ -0,0 +1,70 @@ +"use strict"; +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ModuleRegistry = void 0; +const common_tags_1 = require("common-tags"); +const upath_1 = __importDefault(require("upath")); +/** + * Class for keeping track of which Workbox modules are used by the generated + * service worker script. + * + * @private + */ +class ModuleRegistry { + /** + * @private + */ + constructor() { + this._modulesUsed = new Map(); + } + /** + * @return {Array} A list of all of the import statements that are + * needed for the modules being used. + * @private + */ + getImportStatements() { + const workboxModuleImports = []; + for (const [localName, { moduleName, pkg }] of this._modulesUsed) { + // By default require.resolve returns the resolved path of the 'main' + // field, which might be deeper than the package root. To work around + // this, we can find the package's root by resolving its package.json and + // strip the '/package.json' from the resolved path. + const pkgJsonPath = require.resolve(`${pkg}/package.json`); + const pkgRoot = upath_1.default.dirname(pkgJsonPath); + const importStatement = (0, common_tags_1.oneLine) `import {${moduleName} as ${localName}} from + '${pkgRoot}/${moduleName}.mjs';`; + workboxModuleImports.push(importStatement); + } + return workboxModuleImports; + } + /** + * @param {string} pkg The workbox package that the module belongs to. + * @param {string} moduleName The name of the module to import. + * @return {string} The local variable name that corresponds to that module. + * @private + */ + getLocalName(pkg, moduleName) { + return `${pkg.replace(/-/g, '_')}_${moduleName}`; + } + /** + * @param {string} pkg The workbox package that the module belongs to. + * @param {string} moduleName The name of the module to import. + * @return {string} The local variable name that corresponds to that module. + * @private + */ + use(pkg, moduleName) { + const localName = this.getLocalName(pkg, moduleName); + this._modulesUsed.set(localName, { moduleName, pkg }); + return localName; + } +} +exports.ModuleRegistry = ModuleRegistry; diff --git a/node_modules/workbox-build/build/lib/no-revision-for-urls-matching-transform.d.ts b/node_modules/workbox-build/build/lib/no-revision-for-urls-matching-transform.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..268704529e355f51a20d784621659e6791a2afe7 --- /dev/null +++ b/node_modules/workbox-build/build/lib/no-revision-for-urls-matching-transform.d.ts @@ -0,0 +1,2 @@ +import { ManifestTransform } from '../types'; +export declare function noRevisionForURLsMatchingTransform(regexp: RegExp): ManifestTransform; diff --git a/node_modules/workbox-build/build/lib/no-revision-for-urls-matching-transform.js b/node_modules/workbox-build/build/lib/no-revision-for-urls-matching-transform.js new file mode 100644 index 0000000000000000000000000000000000000000..46a3eead9a4e800f92511a979c5a9855c86d2bb1 --- /dev/null +++ b/node_modules/workbox-build/build/lib/no-revision-for-urls-matching-transform.js @@ -0,0 +1,29 @@ +"use strict"; +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.noRevisionForURLsMatchingTransform = void 0; +const errors_1 = require("./errors"); +function noRevisionForURLsMatchingTransform(regexp) { + if (!(regexp instanceof RegExp)) { + throw new Error(errors_1.errors['invalid-dont-cache-bust']); + } + return (originalManifest) => { + const manifest = originalManifest.map((entry) => { + if (typeof entry.url !== 'string') { + throw new Error(errors_1.errors['manifest-entry-bad-url']); + } + if (entry.url.match(regexp)) { + entry.revision = null; + } + return entry; + }); + return { manifest }; + }; +} +exports.noRevisionForURLsMatchingTransform = noRevisionForURLsMatchingTransform; diff --git a/node_modules/workbox-build/build/lib/populate-sw-template.d.ts b/node_modules/workbox-build/build/lib/populate-sw-template.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..debf1491dc0734bed70c7428f116cd6ca5e945b9 --- /dev/null +++ b/node_modules/workbox-build/build/lib/populate-sw-template.d.ts @@ -0,0 +1,4 @@ +import { GeneratePartial, ManifestEntry } from '../types'; +export declare function populateSWTemplate({ cacheId, cleanupOutdatedCaches, clientsClaim, directoryIndex, disableDevLogs, ignoreURLParametersMatching, importScripts, manifestEntries, navigateFallback, navigateFallbackDenylist, navigateFallbackAllowlist, navigationPreload, offlineGoogleAnalytics, runtimeCaching, skipWaiting, }: GeneratePartial & { + manifestEntries?: Array; +}): string; diff --git a/node_modules/workbox-build/build/lib/populate-sw-template.js b/node_modules/workbox-build/build/lib/populate-sw-template.js new file mode 100644 index 0000000000000000000000000000000000000000..d20bf720b4a1d85b2a02bd6891d7ab3dfbf5d676 --- /dev/null +++ b/node_modules/workbox-build/build/lib/populate-sw-template.js @@ -0,0 +1,80 @@ +"use strict"; +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.populateSWTemplate = void 0; +const eta_1 = require("eta"); +const errors_1 = require("./errors"); +const module_registry_1 = require("./module-registry"); +const runtime_caching_converter_1 = require("./runtime-caching-converter"); +const stringify_without_comments_1 = require("./stringify-without-comments"); +const sw_template_1 = require("../templates/sw-template"); +const eta = new eta_1.Eta({ + useWith: true, + autoEscape: false, +}); +function populateSWTemplate({ cacheId, cleanupOutdatedCaches, clientsClaim, directoryIndex, disableDevLogs, ignoreURLParametersMatching, importScripts, manifestEntries = [], navigateFallback, navigateFallbackDenylist, navigateFallbackAllowlist, navigationPreload, offlineGoogleAnalytics, runtimeCaching = [], skipWaiting, }) { + // There needs to be at least something to precache, or else runtime caching. + if (!((manifestEntries === null || manifestEntries === void 0 ? void 0 : manifestEntries.length) > 0 || runtimeCaching.length > 0)) { + throw new Error(errors_1.errors['no-manifest-entries-or-runtime-caching']); + } + // These are all options that can be passed to the precacheAndRoute() method. + const precacheOptions = { + directoryIndex, + // An array of RegExp objects can't be serialized by JSON.stringify()'s + // default behavior, so if it's given, convert it manually. + ignoreURLParametersMatching: ignoreURLParametersMatching + ? [] + : undefined, + }; + let precacheOptionsString = JSON.stringify(precacheOptions, null, 2); + if (ignoreURLParametersMatching) { + precacheOptionsString = precacheOptionsString.replace(`"ignoreURLParametersMatching": []`, `"ignoreURLParametersMatching": [` + + `${ignoreURLParametersMatching.join(', ')}]`); + } + let offlineAnalyticsConfigString = undefined; + if (offlineGoogleAnalytics) { + // If offlineGoogleAnalytics is a truthy value, we need to convert it to the + // format expected by the template. + offlineAnalyticsConfigString = + offlineGoogleAnalytics === true + ? // If it's the literal value true, then use an empty config string. + '{}' + : // Otherwise, convert the config object into a more complex string, taking + // into account the fact that functions might need to be stringified. + (0, stringify_without_comments_1.stringifyWithoutComments)(offlineGoogleAnalytics); + } + const moduleRegistry = new module_registry_1.ModuleRegistry(); + try { + const populatedTemplate = eta.renderString(sw_template_1.swTemplate, { + cacheId, + cleanupOutdatedCaches, + clientsClaim, + disableDevLogs, + importScripts, + manifestEntries, + navigateFallback, + navigateFallbackDenylist, + navigateFallbackAllowlist, + navigationPreload, + offlineAnalyticsConfigString, + precacheOptionsString, + runtimeCaching: (0, runtime_caching_converter_1.runtimeCachingConverter)(moduleRegistry, runtimeCaching), + skipWaiting, + use: moduleRegistry.use.bind(moduleRegistry), + }); + const workboxImportStatements = moduleRegistry.getImportStatements(); + // We need the import statements for all of the Workbox runtime modules + // prepended, so that the correct bundle can be created. + return workboxImportStatements.join('\n') + populatedTemplate; + } + catch (error) { + throw new Error(`${errors_1.errors['populating-sw-tmpl-failed']} '${error instanceof Error && error.message ? error.message : ''}'`); + } +} +exports.populateSWTemplate = populateSWTemplate; diff --git a/node_modules/workbox-build/build/lib/rebase-path.d.ts b/node_modules/workbox-build/build/lib/rebase-path.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..450e652b9ffd335945963b0e55b332bfa50c7e27 --- /dev/null +++ b/node_modules/workbox-build/build/lib/rebase-path.d.ts @@ -0,0 +1,4 @@ +export declare function rebasePath({ baseDirectory, file, }: { + baseDirectory: string; + file: string; +}): string; diff --git a/node_modules/workbox-build/build/lib/rebase-path.js b/node_modules/workbox-build/build/lib/rebase-path.js new file mode 100644 index 0000000000000000000000000000000000000000..dd55c1c588a45828512f58df80ac8ca2b8a74eec --- /dev/null +++ b/node_modules/workbox-build/build/lib/rebase-path.js @@ -0,0 +1,24 @@ +"use strict"; +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.rebasePath = void 0; +const upath_1 = __importDefault(require("upath")); +function rebasePath({ baseDirectory, file, }) { + // The initial path is relative to the current directory, so make it absolute. + const absolutePath = upath_1.default.resolve(file); + // Convert the absolute path so that it's relative to the baseDirectory. + const relativePath = upath_1.default.relative(baseDirectory, absolutePath); + // Remove any leading ./ as it won't work in a glob pattern. + const normalizedPath = upath_1.default.normalize(relativePath); + return normalizedPath; +} +exports.rebasePath = rebasePath; diff --git a/node_modules/workbox-build/build/lib/replace-and-update-source-map.d.ts b/node_modules/workbox-build/build/lib/replace-and-update-source-map.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d81855d26e1aee302a1e87c7891d6e7674012549 --- /dev/null +++ b/node_modules/workbox-build/build/lib/replace-and-update-source-map.d.ts @@ -0,0 +1,30 @@ +import { RawSourceMap } from 'source-map'; +/** + * Adapted from https://github.com/nsams/sourcemap-aware-replace, with modern + * JavaScript updates, along with additional properties copied from originalMap. + * + * @param {Object} options + * @param {string} options.jsFilename The name for the file whose contents + * correspond to originalSource. + * @param {Object} options.originalMap The sourcemap for originalSource, + * prior to any replacements. + * @param {string} options.originalSource The source code, prior to any + * replacements. + * @param {string} options.replaceString A string to swap in for searchString. + * @param {string} options.searchString A string in originalSource to replace. + * Only the first occurrence will be replaced. + * @return {{source: string, map: string}} An object containing both + * originalSource with the replacement applied, and the modified originalMap. + * + * @private + */ +export declare function replaceAndUpdateSourceMap({ jsFilename, originalMap, originalSource, replaceString, searchString, }: { + jsFilename: string; + originalMap: RawSourceMap; + originalSource: string; + replaceString: string; + searchString: string; +}): Promise<{ + map: string; + source: string; +}>; diff --git a/node_modules/workbox-build/build/lib/replace-and-update-source-map.js b/node_modules/workbox-build/build/lib/replace-and-update-source-map.js new file mode 100644 index 0000000000000000000000000000000000000000..80f15bc6b7264515baa5d55be23d5036b157a3f9 --- /dev/null +++ b/node_modules/workbox-build/build/lib/replace-and-update-source-map.js @@ -0,0 +1,98 @@ +"use strict"; +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.replaceAndUpdateSourceMap = void 0; +const source_map_1 = require("source-map"); +/** + * Adapted from https://github.com/nsams/sourcemap-aware-replace, with modern + * JavaScript updates, along with additional properties copied from originalMap. + * + * @param {Object} options + * @param {string} options.jsFilename The name for the file whose contents + * correspond to originalSource. + * @param {Object} options.originalMap The sourcemap for originalSource, + * prior to any replacements. + * @param {string} options.originalSource The source code, prior to any + * replacements. + * @param {string} options.replaceString A string to swap in for searchString. + * @param {string} options.searchString A string in originalSource to replace. + * Only the first occurrence will be replaced. + * @return {{source: string, map: string}} An object containing both + * originalSource with the replacement applied, and the modified originalMap. + * + * @private + */ +async function replaceAndUpdateSourceMap({ jsFilename, originalMap, originalSource, replaceString, searchString, }) { + const generator = new source_map_1.SourceMapGenerator({ + file: jsFilename, + }); + const consumer = await new source_map_1.SourceMapConsumer(originalMap); + let pos; + let src = originalSource; + const replacements = []; + let lineNum = 0; + let filePos = 0; + const lines = src.split('\n'); + for (let line of lines) { + lineNum++; + let searchPos = 0; + while ((pos = line.indexOf(searchString, searchPos)) !== -1) { + src = + src.substring(0, filePos + pos) + + replaceString + + src.substring(filePos + pos + searchString.length); + line = + line.substring(0, pos) + + replaceString + + line.substring(pos + searchString.length); + replacements.push({ line: lineNum, column: pos }); + searchPos = pos + replaceString.length; + } + filePos += line.length + 1; + } + replacements.reverse(); + consumer.eachMapping((mapping) => { + for (const replacement of replacements) { + if (replacement.line === mapping.generatedLine && + mapping.generatedColumn > replacement.column) { + const offset = searchString.length - replaceString.length; + mapping.generatedColumn -= offset; + } + } + if (mapping.source) { + const newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn, + }, + original: { + line: mapping.originalLine, + column: mapping.originalColumn, + }, + source: mapping.source, + }; + return generator.addMapping(newMapping); + } + return mapping; + }); + consumer.destroy(); + // JSON.parse returns any. + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const updatedSourceMap = Object.assign(JSON.parse(generator.toString()), { + names: originalMap.names, + sourceRoot: originalMap.sourceRoot, + sources: originalMap.sources, + sourcesContent: originalMap.sourcesContent, + }); + return { + map: JSON.stringify(updatedSourceMap), + source: src, + }; +} +exports.replaceAndUpdateSourceMap = replaceAndUpdateSourceMap; diff --git a/node_modules/workbox-build/build/lib/runtime-caching-converter.d.ts b/node_modules/workbox-build/build/lib/runtime-caching-converter.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..79640a34817f32cf61980f3bc893b12152589b2f --- /dev/null +++ b/node_modules/workbox-build/build/lib/runtime-caching-converter.d.ts @@ -0,0 +1,3 @@ +import { ModuleRegistry } from './module-registry'; +import { RuntimeCaching } from '../types'; +export declare function runtimeCachingConverter(moduleRegistry: ModuleRegistry, runtimeCaching: Array): Array; diff --git a/node_modules/workbox-build/build/lib/runtime-caching-converter.js b/node_modules/workbox-build/build/lib/runtime-caching-converter.js new file mode 100644 index 0000000000000000000000000000000000000000..76d78924a5604fbcdf5de19286cb4443b3ac8e29 --- /dev/null +++ b/node_modules/workbox-build/build/lib/runtime-caching-converter.js @@ -0,0 +1,142 @@ +"use strict"; +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.runtimeCachingConverter = void 0; +const common_tags_1 = require("common-tags"); +const errors_1 = require("./errors"); +const stringify_without_comments_1 = require("./stringify-without-comments"); +/** + * Given a set of options that configures runtime caching behavior, convert it + * to the equivalent Workbox method calls. + * + * @param {ModuleRegistry} moduleRegistry + * @param {Object} options See + * https://developers.google.com/web/tools/workbox/modules/workbox-build#generateSW-runtimeCaching + * @return {string} A JSON string representing the equivalent options. + * + * @private + */ +function getOptionsString(moduleRegistry, options = {}) { + const plugins = []; + const handlerOptions = {}; + for (const optionName of Object.keys(options)) { + if (options[optionName] === undefined) { + continue; + } + switch (optionName) { + // Using a library here because JSON.stringify won't handle functions. + case 'plugins': { + plugins.push(...options.plugins.map(stringify_without_comments_1.stringifyWithoutComments)); + break; + } + // These are the option properties that we want to pull out, so that + // they're passed to the handler constructor. + case 'cacheName': + case 'networkTimeoutSeconds': + case 'fetchOptions': + case 'matchOptions': { + handlerOptions[optionName] = options[optionName]; + break; + } + // The following cases are all shorthands for creating a plugin with a + // given configuration. + case 'backgroundSync': { + const name = options.backgroundSync.name; + const plugin = moduleRegistry.use('workbox-background-sync', 'BackgroundSyncPlugin'); + let pluginCode = `new ${plugin}(${JSON.stringify(name)}`; + if (options.backgroundSync.options) { + pluginCode += `, ${(0, stringify_without_comments_1.stringifyWithoutComments)(options.backgroundSync.options)}`; + } + pluginCode += `)`; + plugins.push(pluginCode); + break; + } + case 'broadcastUpdate': { + const channelName = options.broadcastUpdate.channelName; + const opts = Object.assign({ channelName }, options.broadcastUpdate.options); + const plugin = moduleRegistry.use('workbox-broadcast-update', 'BroadcastUpdatePlugin'); + plugins.push(`new ${plugin}(${(0, stringify_without_comments_1.stringifyWithoutComments)(opts)})`); + break; + } + case 'cacheableResponse': { + const plugin = moduleRegistry.use('workbox-cacheable-response', 'CacheableResponsePlugin'); + plugins.push(`new ${plugin}(${(0, stringify_without_comments_1.stringifyWithoutComments)(options.cacheableResponse)})`); + break; + } + case 'expiration': { + const plugin = moduleRegistry.use('workbox-expiration', 'ExpirationPlugin'); + plugins.push(`new ${plugin}(${(0, stringify_without_comments_1.stringifyWithoutComments)(options.expiration)})`); + break; + } + case 'precacheFallback': { + const plugin = moduleRegistry.use('workbox-precaching', 'PrecacheFallbackPlugin'); + plugins.push(`new ${plugin}(${(0, stringify_without_comments_1.stringifyWithoutComments)(options.precacheFallback)})`); + break; + } + case 'rangeRequests': { + const plugin = moduleRegistry.use('workbox-range-requests', 'RangeRequestsPlugin'); + // There are no configuration options for the constructor. + plugins.push(`new ${plugin}()`); + break; + } + default: { + throw new Error( + // In the default case optionName is typed as 'never'. + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + `${errors_1.errors['bad-runtime-caching-config']} ${optionName}`); + } + } + } + if (Object.keys(handlerOptions).length > 0 || plugins.length > 0) { + const optionsString = JSON.stringify(handlerOptions).slice(1, -1); + return (0, common_tags_1.oneLine) `{ + ${optionsString ? optionsString + ',' : ''} + plugins: [${plugins.join(', ')}] + }`; + } + else { + return ''; + } +} +function runtimeCachingConverter(moduleRegistry, runtimeCaching) { + return runtimeCaching + .map((entry) => { + const method = entry.method || 'GET'; + if (!entry.urlPattern) { + throw new Error(errors_1.errors['urlPattern-is-required']); + } + if (!entry.handler) { + throw new Error(errors_1.errors['handler-is-required']); + } + if (entry.options && + entry.options.networkTimeoutSeconds && + entry.handler !== 'NetworkFirst') { + throw new Error(errors_1.errors['invalid-network-timeout-seconds']); + } + // urlPattern might be a string, a RegExp object, or a function. + // If it's a string, it needs to be quoted. + const matcher = typeof entry.urlPattern === 'string' + ? JSON.stringify(entry.urlPattern) + : entry.urlPattern; + const registerRoute = moduleRegistry.use('workbox-routing', 'registerRoute'); + if (typeof entry.handler === 'string') { + const optionsString = getOptionsString(moduleRegistry, entry.options); + const handler = moduleRegistry.use('workbox-strategies', entry.handler); + const strategyString = `new ${handler}(${optionsString})`; + return `${registerRoute}(${matcher.toString()}, ${strategyString}, '${method}');\n`; + } + else if (typeof entry.handler === 'function') { + return `${registerRoute}(${matcher.toString()}, ${entry.handler.toString()}, '${method}');\n`; + } + // '' will be filtered out. + return ''; + }) + .filter((entry) => Boolean(entry)); +} +exports.runtimeCachingConverter = runtimeCachingConverter; diff --git a/node_modules/workbox-build/build/lib/stringify-without-comments.d.ts b/node_modules/workbox-build/build/lib/stringify-without-comments.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b0b073350ecffe9b258a2fc0f65fbfa412f6625a --- /dev/null +++ b/node_modules/workbox-build/build/lib/stringify-without-comments.d.ts @@ -0,0 +1,3 @@ +export declare function stringifyWithoutComments(obj: { + [key: string]: any; +}): string; diff --git a/node_modules/workbox-build/build/lib/stringify-without-comments.js b/node_modules/workbox-build/build/lib/stringify-without-comments.js new file mode 100644 index 0000000000000000000000000000000000000000..4c7e393e89448b058814bb56d7802ff1c17e6f86 --- /dev/null +++ b/node_modules/workbox-build/build/lib/stringify-without-comments.js @@ -0,0 +1,28 @@ +"use strict"; +/* + Copyright 2021 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.stringifyWithoutComments = void 0; +const stringify_object_1 = __importDefault(require("stringify-object")); +const strip_comments_1 = __importDefault(require("strip-comments")); +function stringifyWithoutComments(obj) { + return (0, stringify_object_1.default)(obj, { + // See https://github.com/yeoman/stringify-object#transformobject-property-originalresult + transform: (_obj, _prop, str) => { + if (typeof _prop !== 'symbol' && typeof _obj[_prop] === 'function') { + // Can't typify correctly stripComments + return (0, strip_comments_1.default)(str); // eslint-disable-line + } + return str; + }, + }); +} +exports.stringifyWithoutComments = stringifyWithoutComments; diff --git a/node_modules/workbox-build/build/lib/transform-manifest.d.ts b/node_modules/workbox-build/build/lib/transform-manifest.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..48343a233015fda375337d348a13c464e8a8581d --- /dev/null +++ b/node_modules/workbox-build/build/lib/transform-manifest.d.ts @@ -0,0 +1,63 @@ +import { BasePartial, FileDetails, ManifestEntry } from '../types'; +/** + * A `ManifestTransform` function can be used to modify the modify the `url` or + * `revision` properties of some or all of the + * {@link workbox-build.ManifestEntry} in the manifest. + * + * Deleting the `revision` property of an entry will cause + * the corresponding `url` to be precached without cache-busting parameters + * applied, which is to say, it implies that the URL itself contains + * proper versioning info. If the `revision` property is present, it must be + * set to a string. + * + * @example A transformation that prepended the origin of a CDN for any + * URL starting with '/assets/' could be implemented as: + * + * const cdnTransform = async (manifestEntries) => { + * const manifest = manifestEntries.map(entry => { + * const cdnOrigin = 'https://example.com'; + * if (entry.url.startsWith('/assets/')) { + * entry.url = cdnOrigin + entry.url; + * } + * return entry; + * }); + * return {manifest, warnings: []}; + * }; + * + * @example A transformation that nulls the revision field when the + * URL contains an 8-character hash surrounded by '.', indicating that it + * already contains revision information: + * + * const removeRevisionTransform = async (manifestEntries) => { + * const manifest = manifestEntries.map(entry => { + * const hashRegExp = /\.\w{8}\./; + * if (entry.url.match(hashRegExp)) { + * entry.revision = null; + * } + * return entry; + * }); + * return {manifest, warnings: []}; + * }; + * + * @callback ManifestTransform + * @param {Array} manifestEntries The full + * array of entries, prior to the current transformation. + * @param {Object} [compilation] When used in the webpack plugins, this param + * will be set to the current `compilation`. + * @return {Promise} + * The array of entries with the transformation applied, and optionally, any + * warnings that should be reported back to the build tool. + * + * @memberof workbox-build + */ +interface ManifestTransformResultWithWarnings { + count: number; + size: number; + manifestEntries: ManifestEntry[]; + warnings: string[]; +} +export declare function transformManifest({ additionalManifestEntries, dontCacheBustURLsMatching, fileDetails, manifestTransforms, maximumFileSizeToCacheInBytes, modifyURLPrefix, transformParam, }: BasePartial & { + fileDetails: Array; + transformParam?: unknown; +}): Promise; +export {}; diff --git a/node_modules/workbox-build/build/lib/transform-manifest.js b/node_modules/workbox-build/build/lib/transform-manifest.js new file mode 100644 index 0000000000000000000000000000000000000000..82baf46d532e4738f20155f5482b695ba0e7fe23 --- /dev/null +++ b/node_modules/workbox-build/build/lib/transform-manifest.js @@ -0,0 +1,69 @@ +"use strict"; +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.transformManifest = void 0; +const additional_manifest_entries_transform_1 = require("./additional-manifest-entries-transform"); +const errors_1 = require("./errors"); +const maximum_size_transform_1 = require("./maximum-size-transform"); +const modify_url_prefix_transform_1 = require("./modify-url-prefix-transform"); +const no_revision_for_urls_matching_transform_1 = require("./no-revision-for-urls-matching-transform"); +async function transformManifest({ additionalManifestEntries, dontCacheBustURLsMatching, fileDetails, manifestTransforms, maximumFileSizeToCacheInBytes, modifyURLPrefix, transformParam, }) { + const allWarnings = []; + // Take the array of fileDetail objects and convert it into an array of + // {url, revision, size} objects, with \ replaced with /. + const normalizedManifest = fileDetails.map((fileDetails) => { + return { + url: fileDetails.file.replace(/\\/g, '/'), + revision: fileDetails.hash, + size: fileDetails.size, + }; + }); + const transformsToApply = []; + if (maximumFileSizeToCacheInBytes) { + transformsToApply.push((0, maximum_size_transform_1.maximumSizeTransform)(maximumFileSizeToCacheInBytes)); + } + if (modifyURLPrefix) { + transformsToApply.push((0, modify_url_prefix_transform_1.modifyURLPrefixTransform)(modifyURLPrefix)); + } + if (dontCacheBustURLsMatching) { + transformsToApply.push((0, no_revision_for_urls_matching_transform_1.noRevisionForURLsMatchingTransform)(dontCacheBustURLsMatching)); + } + // Run any manifestTransforms functions second-to-last. + if (manifestTransforms) { + transformsToApply.push(...manifestTransforms); + } + // Run additionalManifestEntriesTransform last. + if (additionalManifestEntries) { + transformsToApply.push((0, additional_manifest_entries_transform_1.additionalManifestEntriesTransform)(additionalManifestEntries)); + } + let transformedManifest = normalizedManifest; + for (const transform of transformsToApply) { + const result = await transform(transformedManifest, transformParam); + if (!('manifest' in result)) { + throw new Error(errors_1.errors['bad-manifest-transforms-return-value']); + } + transformedManifest = result.manifest; + allWarnings.push(...(result.warnings || [])); + } + // Generate some metadata about the manifest before we clear out the size + // properties from each entry. + const count = transformedManifest.length; + let size = 0; + for (const manifestEntry of transformedManifest) { + size += manifestEntry.size || 0; + delete manifestEntry.size; + } + return { + count, + size, + manifestEntries: transformedManifest, + warnings: allWarnings, + }; +} +exports.transformManifest = transformManifest; diff --git a/node_modules/workbox-build/build/lib/translate-url-to-sourcemap-paths.d.ts b/node_modules/workbox-build/build/lib/translate-url-to-sourcemap-paths.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3b7413b20e284fe2543d437364fbe7f849c684f6 --- /dev/null +++ b/node_modules/workbox-build/build/lib/translate-url-to-sourcemap-paths.d.ts @@ -0,0 +1,5 @@ +export declare function translateURLToSourcemapPaths(url: string | null, swSrc: string, swDest: string): { + destPath: string | undefined; + srcPath: string | undefined; + warning: string | undefined; +}; diff --git a/node_modules/workbox-build/build/lib/translate-url-to-sourcemap-paths.js b/node_modules/workbox-build/build/lib/translate-url-to-sourcemap-paths.js new file mode 100644 index 0000000000000000000000000000000000000000..3220c5474eeac6e8a56ca9b2ac2bd9be48529e43 --- /dev/null +++ b/node_modules/workbox-build/build/lib/translate-url-to-sourcemap-paths.js @@ -0,0 +1,33 @@ +"use strict"; +/* + Copyright 2021 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.translateURLToSourcemapPaths = void 0; +const fs_extra_1 = __importDefault(require("fs-extra")); +const upath_1 = __importDefault(require("upath")); +const errors_1 = require("./errors"); +function translateURLToSourcemapPaths(url, swSrc, swDest) { + let destPath = undefined; + let srcPath = undefined; + let warning = undefined; + if (url && !url.startsWith('data:')) { + const possibleSrcPath = upath_1.default.resolve(upath_1.default.dirname(swSrc), url); + if (fs_extra_1.default.existsSync(possibleSrcPath)) { + srcPath = possibleSrcPath; + destPath = upath_1.default.resolve(upath_1.default.dirname(swDest), url); + } + else { + warning = `${errors_1.errors['cant-find-sourcemap']} ${possibleSrcPath}`; + } + } + return { destPath, srcPath, warning }; +} +exports.translateURLToSourcemapPaths = translateURLToSourcemapPaths; diff --git a/node_modules/workbox-build/build/lib/validate-options.d.ts b/node_modules/workbox-build/build/lib/validate-options.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bf4b549f06b500cde1e29b132607508886269bcf --- /dev/null +++ b/node_modules/workbox-build/build/lib/validate-options.d.ts @@ -0,0 +1,9 @@ +import { GenerateSWOptions, GetManifestOptions, InjectManifestOptions, WebpackGenerateSWOptions, WebpackInjectManifestOptions } from '../types'; +export declare class WorkboxConfigError extends Error { + constructor(message?: string); +} +export declare function validateGenerateSWOptions(input: unknown): GenerateSWOptions; +export declare function validateGetManifestOptions(input: unknown): GetManifestOptions; +export declare function validateInjectManifestOptions(input: unknown): InjectManifestOptions; +export declare function validateWebpackGenerateSWOptions(input: unknown): WebpackGenerateSWOptions; +export declare function validateWebpackInjectManifestOptions(input: unknown): WebpackInjectManifestOptions; diff --git a/node_modules/workbox-build/build/lib/validate-options.js b/node_modules/workbox-build/build/lib/validate-options.js new file mode 100644 index 0000000000000000000000000000000000000000..1266c75aa8323760dd821cfe7835b6ce0e311422 --- /dev/null +++ b/node_modules/workbox-build/build/lib/validate-options.js @@ -0,0 +1,147 @@ +"use strict"; +/* + Copyright 2021 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateWebpackInjectManifestOptions = exports.validateWebpackGenerateSWOptions = exports.validateInjectManifestOptions = exports.validateGetManifestOptions = exports.validateGenerateSWOptions = exports.WorkboxConfigError = void 0; +const better_ajv_errors_1 = require("@apideck/better-ajv-errors"); +const common_tags_1 = require("common-tags"); +const ajv_1 = __importDefault(require("ajv")); +const errors_1 = require("./errors"); +const ajv = new ajv_1.default({ + useDefaults: true, +}); +const DEFAULT_EXCLUDE_VALUE = [/\.map$/, /^manifest.*\.js$/]; +class WorkboxConfigError extends Error { + constructor(message) { + super(message); + Object.setPrototypeOf(this, new.target.prototype); + } +} +exports.WorkboxConfigError = WorkboxConfigError; +// Some methods need to do follow-up validation using the JSON schema, +// so return both the validated options and then schema. +function validate(input, methodName) { + // Don't mutate input: https://github.com/GoogleChrome/workbox/issues/2158 + const inputCopy = Object.assign({}, input); + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const jsonSchema = require(`../schema/${methodName}Options.json`); + const validate = ajv.compile(jsonSchema); + if (validate(inputCopy)) { + // All methods support manifestTransforms, so validate it here. + ensureValidManifestTransforms(inputCopy); + return [inputCopy, jsonSchema]; + } + const betterErrors = (0, better_ajv_errors_1.betterAjvErrors)({ + basePath: methodName, + data: input, + errors: validate.errors, + // This is needed as JSONSchema6 is expected, but JSONSchemaType works. + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + schema: jsonSchema, + }); + const messages = betterErrors.map((err) => (0, common_tags_1.oneLine) `[${err.path}] ${err.message}. + ${err.suggestion ? err.suggestion : ''}`); + throw new WorkboxConfigError(messages.join('\n\n')); +} +function ensureValidManifestTransforms(options) { + if ('manifestTransforms' in options && + !(Array.isArray(options.manifestTransforms) && + options.manifestTransforms.every((item) => typeof item === 'function'))) { + throw new WorkboxConfigError(errors_1.errors['manifest-transforms']); + } +} +function ensureValidNavigationPreloadConfig(options) { + if (options.navigationPreload && + (!Array.isArray(options.runtimeCaching) || + options.runtimeCaching.length === 0)) { + throw new WorkboxConfigError(errors_1.errors['nav-preload-runtime-caching']); + } +} +function ensureValidCacheExpiration(options) { + var _a, _b; + for (const runtimeCaching of options.runtimeCaching || []) { + if (((_a = runtimeCaching.options) === null || _a === void 0 ? void 0 : _a.expiration) && + !((_b = runtimeCaching.options) === null || _b === void 0 ? void 0 : _b.cacheName)) { + throw new WorkboxConfigError(errors_1.errors['cache-name-required']); + } + } +} +function ensureValidRuntimeCachingOrGlobDirectory(options) { + if (!options.globDirectory && + (!Array.isArray(options.runtimeCaching) || + options.runtimeCaching.length === 0)) { + throw new WorkboxConfigError(errors_1.errors['no-manifest-entries-or-runtime-caching']); + } +} +// This is... messy, because we can't rely on the built-in ajv validation for +// runtimeCaching.handler, as it needs to accept {} (i.e. any) due to +// https://github.com/GoogleChrome/workbox/pull/2899 +// So we need to perform validation when a string (not a function) is used. +function ensureValidStringHandler(options, jsonSchema) { + var _a, _b, _c, _d; + let validHandlers = []; + /* eslint-disable */ + for (const handler of ((_d = (_c = (_b = (_a = jsonSchema.definitions) === null || _a === void 0 ? void 0 : _a.RuntimeCaching) === null || _b === void 0 ? void 0 : _b.properties) === null || _c === void 0 ? void 0 : _c.handler) === null || _d === void 0 ? void 0 : _d.anyOf) || []) { + if ('enum' in handler) { + validHandlers = handler.enum; + break; + } + } + /* eslint-enable */ + for (const runtimeCaching of options.runtimeCaching || []) { + if (typeof runtimeCaching.handler === 'string' && + !validHandlers.includes(runtimeCaching.handler)) { + throw new WorkboxConfigError(errors_1.errors['invalid-handler-string'] + runtimeCaching.handler); + } + } +} +function validateGenerateSWOptions(input) { + const [validatedOptions, jsonSchema] = validate(input, 'GenerateSW'); + ensureValidNavigationPreloadConfig(validatedOptions); + ensureValidCacheExpiration(validatedOptions); + ensureValidRuntimeCachingOrGlobDirectory(validatedOptions); + ensureValidStringHandler(validatedOptions, jsonSchema); + return validatedOptions; +} +exports.validateGenerateSWOptions = validateGenerateSWOptions; +function validateGetManifestOptions(input) { + const [validatedOptions] = validate(input, 'GetManifest'); + return validatedOptions; +} +exports.validateGetManifestOptions = validateGetManifestOptions; +function validateInjectManifestOptions(input) { + const [validatedOptions] = validate(input, 'InjectManifest'); + return validatedOptions; +} +exports.validateInjectManifestOptions = validateInjectManifestOptions; +// The default `exclude: [/\.map$/, /^manifest.*\.js$/]` value can't be +// represented in the JSON schema, so manually set it for the webpack options. +function validateWebpackGenerateSWOptions(input) { + const inputWithExcludeDefault = Object.assign({ + // Make a copy, as exclude can be mutated when used. + exclude: Array.from(DEFAULT_EXCLUDE_VALUE), + }, input); + const [validatedOptions, jsonSchema] = validate(inputWithExcludeDefault, 'WebpackGenerateSW'); + ensureValidNavigationPreloadConfig(validatedOptions); + ensureValidCacheExpiration(validatedOptions); + ensureValidStringHandler(validatedOptions, jsonSchema); + return validatedOptions; +} +exports.validateWebpackGenerateSWOptions = validateWebpackGenerateSWOptions; +function validateWebpackInjectManifestOptions(input) { + const inputWithExcludeDefault = Object.assign({ + // Make a copy, as exclude can be mutated when used. + exclude: Array.from(DEFAULT_EXCLUDE_VALUE), + }, input); + const [validatedOptions] = validate(inputWithExcludeDefault, 'WebpackInjectManifest'); + return validatedOptions; +} +exports.validateWebpackInjectManifestOptions = validateWebpackInjectManifestOptions; diff --git a/node_modules/workbox-build/build/lib/write-sw-using-default-template.d.ts b/node_modules/workbox-build/build/lib/write-sw-using-default-template.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bcf04962c68e9412ee0c944a591f1a944d9a9a80 --- /dev/null +++ b/node_modules/workbox-build/build/lib/write-sw-using-default-template.d.ts @@ -0,0 +1,4 @@ +import { GenerateSWOptions, ManifestEntry } from '../types'; +export declare function writeSWUsingDefaultTemplate({ babelPresetEnvTargets, cacheId, cleanupOutdatedCaches, clientsClaim, directoryIndex, disableDevLogs, ignoreURLParametersMatching, importScripts, inlineWorkboxRuntime, manifestEntries, mode, navigateFallback, navigateFallbackDenylist, navigateFallbackAllowlist, navigationPreload, offlineGoogleAnalytics, runtimeCaching, skipWaiting, sourcemap, swDest, }: GenerateSWOptions & { + manifestEntries: Array; +}): Promise>; diff --git a/node_modules/workbox-build/build/lib/write-sw-using-default-template.js b/node_modules/workbox-build/build/lib/write-sw-using-default-template.js new file mode 100644 index 0000000000000000000000000000000000000000..77b34c843d4188fa2adb2573819d1a4ec2ebc055 --- /dev/null +++ b/node_modules/workbox-build/build/lib/write-sw-using-default-template.js @@ -0,0 +1,71 @@ +"use strict"; +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.writeSWUsingDefaultTemplate = void 0; +const fs_extra_1 = __importDefault(require("fs-extra")); +const upath_1 = __importDefault(require("upath")); +const bundle_1 = require("./bundle"); +const errors_1 = require("./errors"); +const populate_sw_template_1 = require("./populate-sw-template"); +async function writeSWUsingDefaultTemplate({ babelPresetEnvTargets, cacheId, cleanupOutdatedCaches, clientsClaim, directoryIndex, disableDevLogs, ignoreURLParametersMatching, importScripts, inlineWorkboxRuntime, manifestEntries, mode, navigateFallback, navigateFallbackDenylist, navigateFallbackAllowlist, navigationPreload, offlineGoogleAnalytics, runtimeCaching, skipWaiting, sourcemap, swDest, }) { + const outputDir = upath_1.default.dirname(swDest); + try { + await fs_extra_1.default.mkdirp(outputDir); + } + catch (error) { + throw new Error(`${errors_1.errors['unable-to-make-sw-directory']}. ` + + `'${error instanceof Error && error.message ? error.message : ''}'`); + } + const unbundledCode = (0, populate_sw_template_1.populateSWTemplate)({ + cacheId, + cleanupOutdatedCaches, + clientsClaim, + directoryIndex, + disableDevLogs, + ignoreURLParametersMatching, + importScripts, + manifestEntries, + navigateFallback, + navigateFallbackDenylist, + navigateFallbackAllowlist, + navigationPreload, + offlineGoogleAnalytics, + runtimeCaching, + skipWaiting, + }); + try { + const files = await (0, bundle_1.bundle)({ + babelPresetEnvTargets, + inlineWorkboxRuntime, + mode, + sourcemap, + swDest, + unbundledCode, + }); + const filePaths = []; + for (const file of files) { + const filePath = upath_1.default.resolve(file.name); + filePaths.push(filePath); + await fs_extra_1.default.writeFile(filePath, file.contents); + } + return filePaths; + } + catch (error) { + const err = error; + if (err.code === 'EISDIR') { + // See https://github.com/GoogleChrome/workbox/issues/612 + throw new Error(errors_1.errors['sw-write-failure-directory']); + } + throw new Error(`${errors_1.errors['sw-write-failure']} '${err.message}'`); + } +} +exports.writeSWUsingDefaultTemplate = writeSWUsingDefaultTemplate; diff --git a/node_modules/workbox-build/build/schema/GenerateSWOptions.json b/node_modules/workbox-build/build/schema/GenerateSWOptions.json new file mode 100644 index 0000000000000000000000000000000000000000..500a4eab86054bdadc3488442c1178423fc72d3b --- /dev/null +++ b/node_modules/workbox-build/build/schema/GenerateSWOptions.json @@ -0,0 +1,878 @@ +{ + "additionalProperties": false, + "type": "object", + "properties": { + "additionalManifestEntries": { + "description": "A list of entries to be precached, in addition to any entries that are\ngenerated as part of the build configuration.", + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/definitions/ManifestEntry" + }, + { + "type": "string" + } + ] + } + }, + "dontCacheBustURLsMatching": { + "description": "Assets that match this will be assumed to be uniquely versioned via their\nURL, and exempted from the normal HTTP cache-busting that's done when\npopulating the precache. While not required, it's recommended that if your\nexisting build process already inserts a `[hash]` value into each filename,\nyou provide a RegExp that will detect that, as it will reduce the bandwidth\nconsumed when precaching.", + "$ref": "#/definitions/RegExp" + }, + "manifestTransforms": { + "description": "One or more functions which will be applied sequentially against the\ngenerated manifest. If `modifyURLPrefix` or `dontCacheBustURLsMatching` are\nalso specified, their corresponding transformations will be applied first.", + "type": "array", + "items": {} + }, + "maximumFileSizeToCacheInBytes": { + "description": "This value can be used to determine the maximum size of files that will be\nprecached. This prevents you from inadvertently precaching very large files\nthat might have accidentally matched one of your patterns.", + "default": 2097152, + "type": "number" + }, + "modifyURLPrefix": { + "description": "An object mapping string prefixes to replacement string values. This can be\nused to, e.g., remove or add a path prefix from a manifest entry if your\nweb hosting setup doesn't match your local filesystem setup. As an\nalternative with more flexibility, you can use the `manifestTransforms`\noption and provide a function that modifies the entries in the manifest\nusing whatever logic you provide.\n\nExample usage:\n\n```\n// Replace a '/dist/' prefix with '/', and also prepend\n// '/static' to every URL.\nmodifyURLPrefix: {\n '/dist/': '/',\n '': '/static',\n}\n```", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "globFollow": { + "description": "Determines whether or not symlinks are followed when generating the\nprecache manifest. For more information, see the definition of `follow` in\nthe `glob` [documentation](https://github.com/isaacs/node-glob#options).", + "default": true, + "type": "boolean" + }, + "globIgnores": { + "description": "A set of patterns matching files to always exclude when generating the\nprecache manifest. For more information, see the definition of `ignore` in\nthe `glob` [documentation](https://github.com/isaacs/node-glob#options).", + "default": [ + "**/node_modules/**/*" + ], + "type": "array", + "items": { + "type": "string" + } + }, + "globPatterns": { + "description": "Files matching any of these patterns will be included in the precache\nmanifest. For more information, see the\n[`glob` primer](https://github.com/isaacs/node-glob#glob-primer).", + "default": [ + "**/*.{js,wasm,css,html}" + ], + "type": "array", + "items": { + "type": "string" + } + }, + "templatedURLs": { + "description": "If a URL is rendered based on some server-side logic, its contents may\ndepend on multiple files or on some other unique string value. The keys in\nthis object are server-rendered URLs. If the values are an array of\nstrings, they will be interpreted as `glob` patterns, and the contents of\nany files matching the patterns will be used to uniquely version the URL.\nIf used with a single string, it will be interpreted as unique versioning\ninformation that you've generated for a given URL.", + "type": "object", + "additionalProperties": { + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string" + } + ] + } + }, + "babelPresetEnvTargets": { + "description": "The [targets](https://babeljs.io/docs/en/babel-preset-env#targets) to pass\nto `babel-preset-env` when transpiling the service worker bundle.", + "default": [ + "chrome >= 56" + ], + "type": "array", + "items": { + "type": "string" + } + }, + "cacheId": { + "description": "An optional ID to be prepended to cache names. This is primarily useful for\nlocal development where multiple sites may be served from the same\n`http://localhost:port` origin.", + "type": [ + "null", + "string" + ] + }, + "cleanupOutdatedCaches": { + "description": "Whether or not Workbox should attempt to identify and delete any precaches\ncreated by older, incompatible versions.", + "default": false, + "type": "boolean" + }, + "clientsClaim": { + "description": "Whether or not the service worker should [start controlling](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#clientsclaim)\nany existing clients as soon as it activates.", + "default": false, + "type": "boolean" + }, + "directoryIndex": { + "description": "If a navigation request for a URL ending in `/` fails to match a precached\nURL, this value will be appended to the URL and that will be checked for a\nprecache match. This should be set to what your web server is using for its\ndirectory index.", + "type": [ + "null", + "string" + ] + }, + "disableDevLogs": { + "default": false, + "type": "boolean" + }, + "ignoreURLParametersMatching": { + "description": "Any search parameter names that match against one of the RegExp in this\narray will be removed before looking for a precache match. This is useful\nif your users might request URLs that contain, for example, URL parameters\nused to track the source of the traffic. If not provided, the default value\nis `[/^utm_/, /^fbclid$/]`.", + "type": "array", + "items": { + "$ref": "#/definitions/RegExp" + } + }, + "importScripts": { + "description": "A list of JavaScript files that should be passed to\n[`importScripts()`](https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts)\ninside the generated service worker file. This is useful when you want to\nlet Workbox create your top-level service worker file, but want to include\nsome additional code, such as a push event listener.", + "type": "array", + "items": { + "type": "string" + } + }, + "inlineWorkboxRuntime": { + "description": "Whether the runtime code for the Workbox library should be included in the\ntop-level service worker, or split into a separate file that needs to be\ndeployed alongside the service worker. Keeping the runtime separate means\nthat users will not have to re-download the Workbox code each time your\ntop-level service worker changes.", + "default": false, + "type": "boolean" + }, + "mode": { + "description": "If set to 'production', then an optimized service worker bundle that\nexcludes debugging info will be produced. If not explicitly configured\nhere, the `process.env.NODE_ENV` value will be used, and failing that, it\nwill fall back to `'production'`.", + "default": "production", + "type": [ + "null", + "string" + ] + }, + "navigateFallback": { + "description": "If specified, all\n[navigation requests](https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests)\nfor URLs that aren't precached will be fulfilled with the HTML at the URL\nprovided. You must pass in the URL of an HTML document that is listed in\nyour precache manifest. This is meant to be used in a Single Page App\nscenario, in which you want all navigations to use common\n[App Shell HTML](https://developers.google.com/web/fundamentals/architecture/app-shell).", + "default": null, + "type": [ + "null", + "string" + ] + }, + "navigateFallbackAllowlist": { + "description": "An optional array of regular expressions that restricts which URLs the\nconfigured `navigateFallback` behavior applies to. This is useful if only a\nsubset of your site's URLs should be treated as being part of a\n[Single Page App](https://en.wikipedia.org/wiki/Single-page_application).\nIf both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are\nconfigured, the denylist takes precedent.\n\n*Note*: These RegExps may be evaluated against every destination URL during\na navigation. Avoid using\n[complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077),\nor else your users may see delays when navigating your site.", + "type": "array", + "items": { + "$ref": "#/definitions/RegExp" + } + }, + "navigateFallbackDenylist": { + "description": "An optional array of regular expressions that restricts which URLs the\nconfigured `navigateFallback` behavior applies to. This is useful if only a\nsubset of your site's URLs should be treated as being part of a\n[Single Page App](https://en.wikipedia.org/wiki/Single-page_application).\nIf both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are\nconfigured, the denylist takes precedence.\n\n*Note*: These RegExps may be evaluated against every destination URL during\na navigation. Avoid using\n[complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077),\nor else your users may see delays when navigating your site.", + "type": "array", + "items": { + "$ref": "#/definitions/RegExp" + } + }, + "navigationPreload": { + "description": "Whether or not to enable\n[navigation preload](https://developers.google.com/web/tools/workbox/modules/workbox-navigation-preload)\nin the generated service worker. When set to true, you must also use\n`runtimeCaching` to set up an appropriate response strategy that will match\nnavigation requests, and make use of the preloaded response.", + "default": false, + "type": "boolean" + }, + "offlineGoogleAnalytics": { + "description": "Controls whether or not to include support for\n[offline Google Analytics](https://developers.google.com/web/tools/workbox/guides/enable-offline-analytics).\nWhen `true`, the call to `workbox-google-analytics`'s `initialize()` will\nbe added to your generated service worker. When set to an `Object`, that\nobject will be passed in to the `initialize()` call, allowing you to\ncustomize the behavior.", + "default": false, + "anyOf": [ + { + "$ref": "#/definitions/GoogleAnalyticsInitializeOptions" + }, + { + "type": "boolean" + } + ] + }, + "runtimeCaching": { + "description": "When using Workbox's build tools to generate your service worker, you can\nspecify one or more runtime caching configurations. These are then\ntranslated to {@link workbox-routing.registerRoute} calls using the match\nand handler configuration you define.\n\nFor all of the options, see the {@link workbox-build.RuntimeCaching}\ndocumentation. The example below shows a typical configuration, with two\nruntime routes defined:", + "type": "array", + "items": { + "$ref": "#/definitions/RuntimeCaching" + } + }, + "skipWaiting": { + "description": "Whether to add an unconditional call to [`skipWaiting()`](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#skip_the_waiting_phase)\nto the generated service worker. If `false`, then a `message` listener will\nbe added instead, allowing client pages to trigger `skipWaiting()` by\ncalling `postMessage({type: 'SKIP_WAITING'})` on a waiting service worker.", + "default": false, + "type": "boolean" + }, + "sourcemap": { + "description": "Whether to create a sourcemap for the generated service worker files.", + "default": true, + "type": "boolean" + }, + "swDest": { + "description": "The path and filename of the service worker file that will be created by\nthe build process, relative to the current working directory. It must end\nin '.js'.", + "type": "string" + }, + "globDirectory": { + "description": "The local directory you wish to match `globPatterns` against. The path is\nrelative to the current directory.", + "type": "string" + } + }, + "required": [ + "swDest" + ], + "definitions": { + "ManifestEntry": { + "type": "object", + "properties": { + "integrity": { + "type": "string" + }, + "revision": { + "type": [ + "null", + "string" + ] + }, + "url": { + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "revision", + "url" + ] + }, + "RegExp": { + "type": "object", + "properties": { + "source": { + "type": "string" + }, + "global": { + "type": "boolean" + }, + "ignoreCase": { + "type": "boolean" + }, + "multiline": { + "type": "boolean" + }, + "lastIndex": { + "type": "number" + }, + "flags": { + "type": "string" + }, + "sticky": { + "type": "boolean" + }, + "unicode": { + "type": "boolean" + }, + "dotAll": { + "type": "boolean" + }, + "hasIndices": { + "type": "boolean" + } + }, + "additionalProperties": false, + "required": [ + "dotAll", + "flags", + "global", + "hasIndices", + "ignoreCase", + "lastIndex", + "multiline", + "source", + "sticky", + "unicode" + ] + }, + "GoogleAnalyticsInitializeOptions": { + "type": "object", + "properties": { + "cacheName": { + "type": "string" + }, + "parameterOverrides": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "hitFilter": { + "type": "object", + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "RuntimeCaching": { + "type": "object", + "properties": { + "handler": { + "description": "This determines how the runtime route will generate a response.\nTo use one of the built-in {@link workbox-strategies}, provide its name,\nlike `'NetworkFirst'`.\nAlternatively, this can be a {@link workbox-core.RouteHandler} callback\nfunction with custom response logic.", + "anyOf": [ + { + "$ref": "#/definitions/RouteHandlerCallback" + }, + { + "$ref": "#/definitions/RouteHandlerObject" + }, + { + "enum": [ + "CacheFirst", + "CacheOnly", + "NetworkFirst", + "NetworkOnly", + "StaleWhileRevalidate" + ], + "type": "string" + } + ] + }, + "method": { + "description": "The HTTP method to match against. The default value of `'GET'` is normally\nsufficient, unless you explicitly need to match `'POST'`, `'PUT'`, or\nanother type of request.", + "default": "GET", + "enum": [ + "DELETE", + "GET", + "HEAD", + "PATCH", + "POST", + "PUT" + ], + "type": "string" + }, + "options": { + "type": "object", + "properties": { + "backgroundSync": { + "description": "Configuring this will add a\n{@link workbox-background-sync.BackgroundSyncPlugin} instance to the\n{@link workbox-strategies} configured in `handler`.", + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "options": { + "$ref": "#/definitions/QueueOptions" + } + }, + "additionalProperties": false, + "required": [ + "name" + ] + }, + "broadcastUpdate": { + "description": "Configuring this will add a\n{@link workbox-broadcast-update.BroadcastUpdatePlugin} instance to the\n{@link workbox-strategies} configured in `handler`.", + "type": "object", + "properties": { + "channelName": { + "type": "string" + }, + "options": { + "$ref": "#/definitions/BroadcastCacheUpdateOptions" + } + }, + "additionalProperties": false, + "required": [ + "options" + ] + }, + "cacheableResponse": { + "description": "Configuring this will add a\n{@link workbox-cacheable-response.CacheableResponsePlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", + "$ref": "#/definitions/CacheableResponseOptions" + }, + "cacheName": { + "description": "If provided, this will set the `cacheName` property of the\n{@link workbox-strategies} configured in `handler`.", + "type": [ + "null", + "string" + ] + }, + "expiration": { + "description": "Configuring this will add a\n{@link workbox-expiration.ExpirationPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", + "$ref": "#/definitions/ExpirationPluginOptions" + }, + "networkTimeoutSeconds": { + "description": "If provided, this will set the `networkTimeoutSeconds` property of the\n{@link workbox-strategies} configured in `handler`. Note that only\n`'NetworkFirst'` and `'NetworkOnly'` support `networkTimeoutSeconds`.", + "type": "number" + }, + "plugins": { + "description": "Configuring this allows the use of one or more Workbox plugins that\ndon't have \"shortcut\" options (like `expiration` for\n{@link workbox-expiration.ExpirationPlugin}). The plugins provided here\nwill be added to the {@link workbox-strategies} configured in `handler`.", + "type": "array", + "items": { + "$ref": "#/definitions/WorkboxPlugin" + } + }, + "precacheFallback": { + "description": "Configuring this will add a\n{@link workbox-precaching.PrecacheFallbackPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", + "type": "object", + "properties": { + "fallbackURL": { + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "fallbackURL" + ] + }, + "rangeRequests": { + "description": "Enabling this will add a\n{@link workbox-range-requests.RangeRequestsPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", + "type": "boolean" + }, + "fetchOptions": { + "description": "Configuring this will pass along the `fetchOptions` value to\nthe {@link workbox-strategies} configured in `handler`.", + "$ref": "#/definitions/RequestInit" + }, + "matchOptions": { + "description": "Configuring this will pass along the `matchOptions` value to\nthe {@link workbox-strategies} configured in `handler`.", + "$ref": "#/definitions/CacheQueryOptions" + } + }, + "additionalProperties": false + }, + "urlPattern": { + "description": "This match criteria determines whether the configured handler will\ngenerate a response for any requests that don't match one of the precached\nURLs. If multiple `RuntimeCaching` routes are defined, then the first one\nwhose `urlPattern` matches will be the one that responds.\n\nThis value directly maps to the first parameter passed to\n{@link workbox-routing.registerRoute}. It's recommended to use a\n{@link workbox-core.RouteMatchCallback} function for greatest flexibility.", + "anyOf": [ + { + "$ref": "#/definitions/RegExp" + }, + { + "$ref": "#/definitions/RouteMatchCallback" + }, + { + "type": "string" + } + ] + } + }, + "additionalProperties": false, + "required": [ + "handler", + "urlPattern" + ] + }, + "RouteHandlerCallback": {}, + "RouteHandlerObject": { + "description": "An object with a `handle` method of type `RouteHandlerCallback`.\n\nA `Route` object can be created with either an `RouteHandlerCallback`\nfunction or this `RouteHandler` object. The benefit of the `RouteHandler`\nis it can be extended (as is done by the `workbox-strategies` package).", + "type": "object", + "properties": { + "handle": { + "$ref": "#/definitions/RouteHandlerCallback" + } + }, + "additionalProperties": false, + "required": [ + "handle" + ] + }, + "QueueOptions": { + "type": "object", + "properties": { + "forceSyncFallback": { + "type": "boolean" + }, + "maxRetentionTime": { + "type": "number" + }, + "onSync": { + "$ref": "#/definitions/OnSyncCallback" + } + }, + "additionalProperties": false + }, + "OnSyncCallback": {}, + "BroadcastCacheUpdateOptions": { + "type": "object", + "properties": { + "headersToCheck": { + "type": "array", + "items": { + "type": "string" + } + }, + "generatePayload": { + "type": "object", + "additionalProperties": false + }, + "notifyAllClients": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "CacheableResponseOptions": { + "type": "object", + "properties": { + "statuses": { + "type": "array", + "items": { + "type": "number" + } + }, + "headers": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "additionalProperties": false + }, + "ExpirationPluginOptions": { + "type": "object", + "properties": { + "maxEntries": { + "type": "number" + }, + "maxAgeSeconds": { + "type": "number" + }, + "matchOptions": { + "$ref": "#/definitions/CacheQueryOptions" + }, + "purgeOnQuotaError": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "CacheQueryOptions": { + "type": "object", + "properties": { + "ignoreMethod": { + "type": "boolean" + }, + "ignoreSearch": { + "type": "boolean" + }, + "ignoreVary": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "WorkboxPlugin": { + "description": "An object with optional lifecycle callback properties for the fetch and\ncache operations.", + "type": "object", + "properties": { + "cacheDidUpdate": {}, + "cachedResponseWillBeUsed": {}, + "cacheKeyWillBeUsed": {}, + "cacheWillUpdate": {}, + "fetchDidFail": {}, + "fetchDidSucceed": {}, + "handlerDidComplete": {}, + "handlerDidError": {}, + "handlerDidRespond": {}, + "handlerWillRespond": {}, + "handlerWillStart": {}, + "requestWillFetch": {} + }, + "additionalProperties": false + }, + "CacheDidUpdateCallback": { + "type": "object", + "additionalProperties": false + }, + "CachedResponseWillBeUsedCallback": { + "type": "object", + "additionalProperties": false + }, + "CacheKeyWillBeUsedCallback": { + "type": "object", + "additionalProperties": false + }, + "CacheWillUpdateCallback": { + "type": "object", + "additionalProperties": false + }, + "FetchDidFailCallback": { + "type": "object", + "additionalProperties": false + }, + "FetchDidSucceedCallback": { + "type": "object", + "additionalProperties": false + }, + "HandlerDidCompleteCallback": { + "type": "object", + "additionalProperties": false + }, + "HandlerDidErrorCallback": { + "type": "object", + "additionalProperties": false + }, + "HandlerDidRespondCallback": { + "type": "object", + "additionalProperties": false + }, + "HandlerWillRespondCallback": { + "type": "object", + "additionalProperties": false + }, + "HandlerWillStartCallback": { + "type": "object", + "additionalProperties": false + }, + "RequestWillFetchCallback": { + "type": "object", + "additionalProperties": false + }, + "RequestInit": { + "type": "object", + "properties": { + "body": { + "anyOf": [ + { + "$ref": "#/definitions/ArrayBuffer" + }, + { + "$ref": "#/definitions/ArrayBufferView" + }, + { + "$ref": "#/definitions/ReadableStream" + }, + { + "$ref": "#/definitions/Blob" + }, + { + "$ref": "#/definitions/FormData" + }, + { + "$ref": "#/definitions/URLSearchParams" + }, + { + "type": [ + "null", + "string" + ] + } + ] + }, + "cache": { + "enum": [ + "default", + "force-cache", + "no-cache", + "no-store", + "only-if-cached", + "reload" + ], + "type": "string" + }, + "credentials": { + "enum": [ + "include", + "omit", + "same-origin" + ], + "type": "string" + }, + "headers": { + "anyOf": [ + { + "$ref": "#/definitions/Record" + }, + { + "type": "array", + "items": { + "type": "array", + "items": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "minItems": 2, + "maxItems": 2 + } + }, + { + "$ref": "#/definitions/Headers" + } + ] + }, + "integrity": { + "type": "string" + }, + "keepalive": { + "type": "boolean" + }, + "method": { + "type": "string" + }, + "mode": { + "enum": [ + "cors", + "navigate", + "no-cors", + "same-origin" + ], + "type": "string" + }, + "redirect": { + "enum": [ + "error", + "follow", + "manual" + ], + "type": "string" + }, + "referrer": { + "type": "string" + }, + "referrerPolicy": { + "enum": [ + "", + "no-referrer", + "no-referrer-when-downgrade", + "origin", + "origin-when-cross-origin", + "same-origin", + "strict-origin", + "strict-origin-when-cross-origin", + "unsafe-url" + ], + "type": "string" + }, + "signal": { + "anyOf": [ + { + "$ref": "#/definitions/AbortSignal" + }, + { + "type": "null" + } + ] + }, + "window": { + "type": "null" + } + }, + "additionalProperties": false + }, + "ArrayBuffer": { + "type": "object", + "properties": { + "byteLength": { + "type": "number" + }, + "__@toStringTag@32": { + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "__@toStringTag@32", + "byteLength" + ] + }, + "ArrayBufferView": { + "type": "object", + "properties": { + "buffer": { + "$ref": "#/definitions/ArrayBufferLike" + }, + "byteLength": { + "type": "number" + }, + "byteOffset": { + "type": "number" + } + }, + "additionalProperties": false, + "required": [ + "buffer", + "byteLength", + "byteOffset" + ] + }, + "ArrayBufferLike": { + "anyOf": [ + { + "$ref": "#/definitions/ArrayBuffer" + }, + { + "$ref": "#/definitions/SharedArrayBuffer" + } + ] + }, + "SharedArrayBuffer": { + "type": "object", + "properties": { + "byteLength": { + "type": "number" + }, + "__@species@492": { + "$ref": "#/definitions/SharedArrayBuffer" + }, + "__@toStringTag@32": { + "type": "string", + "const": "SharedArrayBuffer" + } + }, + "additionalProperties": false, + "required": [ + "__@species@492", + "__@toStringTag@32", + "byteLength" + ] + }, + "ReadableStream": { + "type": "object", + "properties": { + "locked": { + "type": "boolean" + } + }, + "additionalProperties": false, + "required": [ + "locked" + ] + }, + "Blob": { + "type": "object", + "properties": { + "size": { + "type": "number" + }, + "type": { + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "size", + "type" + ] + }, + "FormData": { + "type": "object", + "additionalProperties": false + }, + "URLSearchParams": { + "type": "object", + "properties": { + "size": { + "description": "The total number of parameter entries.", + "type": "number" + } + }, + "additionalProperties": false, + "required": [ + "size" + ] + }, + "Record": { + "type": "object", + "additionalProperties": false + }, + "Headers": { + "type": "object", + "additionalProperties": false + }, + "AbortSignal": {}, + "RouteMatchCallback": {} + }, + "$schema": "http://json-schema.org/draft-07/schema#" +} diff --git a/node_modules/workbox-build/build/schema/GetManifestOptions.json b/node_modules/workbox-build/build/schema/GetManifestOptions.json new file mode 100644 index 0000000000000000000000000000000000000000..e569ddba18ff3e1d9e8d0f5d97cd7c7755f574af --- /dev/null +++ b/node_modules/workbox-build/build/schema/GetManifestOptions.json @@ -0,0 +1,163 @@ +{ + "additionalProperties": false, + "type": "object", + "properties": { + "additionalManifestEntries": { + "description": "A list of entries to be precached, in addition to any entries that are\ngenerated as part of the build configuration.", + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/definitions/ManifestEntry" + }, + { + "type": "string" + } + ] + } + }, + "dontCacheBustURLsMatching": { + "description": "Assets that match this will be assumed to be uniquely versioned via their\nURL, and exempted from the normal HTTP cache-busting that's done when\npopulating the precache. While not required, it's recommended that if your\nexisting build process already inserts a `[hash]` value into each filename,\nyou provide a RegExp that will detect that, as it will reduce the bandwidth\nconsumed when precaching.", + "$ref": "#/definitions/RegExp" + }, + "manifestTransforms": { + "description": "One or more functions which will be applied sequentially against the\ngenerated manifest. If `modifyURLPrefix` or `dontCacheBustURLsMatching` are\nalso specified, their corresponding transformations will be applied first.", + "type": "array", + "items": {} + }, + "maximumFileSizeToCacheInBytes": { + "description": "This value can be used to determine the maximum size of files that will be\nprecached. This prevents you from inadvertently precaching very large files\nthat might have accidentally matched one of your patterns.", + "default": 2097152, + "type": "number" + }, + "modifyURLPrefix": { + "description": "An object mapping string prefixes to replacement string values. This can be\nused to, e.g., remove or add a path prefix from a manifest entry if your\nweb hosting setup doesn't match your local filesystem setup. As an\nalternative with more flexibility, you can use the `manifestTransforms`\noption and provide a function that modifies the entries in the manifest\nusing whatever logic you provide.\n\nExample usage:\n\n```\n// Replace a '/dist/' prefix with '/', and also prepend\n// '/static' to every URL.\nmodifyURLPrefix: {\n '/dist/': '/',\n '': '/static',\n}\n```", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "globFollow": { + "description": "Determines whether or not symlinks are followed when generating the\nprecache manifest. For more information, see the definition of `follow` in\nthe `glob` [documentation](https://github.com/isaacs/node-glob#options).", + "default": true, + "type": "boolean" + }, + "globIgnores": { + "description": "A set of patterns matching files to always exclude when generating the\nprecache manifest. For more information, see the definition of `ignore` in\nthe `glob` [documentation](https://github.com/isaacs/node-glob#options).", + "default": [ + "**/node_modules/**/*" + ], + "type": "array", + "items": { + "type": "string" + } + }, + "globPatterns": { + "description": "Files matching any of these patterns will be included in the precache\nmanifest. For more information, see the\n[`glob` primer](https://github.com/isaacs/node-glob#glob-primer).", + "default": [ + "**/*.{js,wasm,css,html}" + ], + "type": "array", + "items": { + "type": "string" + } + }, + "templatedURLs": { + "description": "If a URL is rendered based on some server-side logic, its contents may\ndepend on multiple files or on some other unique string value. The keys in\nthis object are server-rendered URLs. If the values are an array of\nstrings, they will be interpreted as `glob` patterns, and the contents of\nany files matching the patterns will be used to uniquely version the URL.\nIf used with a single string, it will be interpreted as unique versioning\ninformation that you've generated for a given URL.", + "type": "object", + "additionalProperties": { + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string" + } + ] + } + }, + "globDirectory": { + "description": "The local directory you wish to match `globPatterns` against. The path is\nrelative to the current directory.", + "type": "string" + } + }, + "required": [ + "globDirectory" + ], + "definitions": { + "ManifestEntry": { + "type": "object", + "properties": { + "integrity": { + "type": "string" + }, + "revision": { + "type": [ + "null", + "string" + ] + }, + "url": { + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "revision", + "url" + ] + }, + "RegExp": { + "type": "object", + "properties": { + "source": { + "type": "string" + }, + "global": { + "type": "boolean" + }, + "ignoreCase": { + "type": "boolean" + }, + "multiline": { + "type": "boolean" + }, + "lastIndex": { + "type": "number" + }, + "flags": { + "type": "string" + }, + "sticky": { + "type": "boolean" + }, + "unicode": { + "type": "boolean" + }, + "dotAll": { + "type": "boolean" + }, + "hasIndices": { + "type": "boolean" + } + }, + "additionalProperties": false, + "required": [ + "dotAll", + "flags", + "global", + "hasIndices", + "ignoreCase", + "lastIndex", + "multiline", + "source", + "sticky", + "unicode" + ] + } + }, + "$schema": "http://json-schema.org/draft-07/schema#" +} diff --git a/node_modules/workbox-build/build/schema/InjectManifestOptions.json b/node_modules/workbox-build/build/schema/InjectManifestOptions.json new file mode 100644 index 0000000000000000000000000000000000000000..403d2a4a218528ece216aebec83c25f8edc952bf --- /dev/null +++ b/node_modules/workbox-build/build/schema/InjectManifestOptions.json @@ -0,0 +1,178 @@ +{ + "additionalProperties": false, + "type": "object", + "properties": { + "additionalManifestEntries": { + "description": "A list of entries to be precached, in addition to any entries that are\ngenerated as part of the build configuration.", + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/definitions/ManifestEntry" + }, + { + "type": "string" + } + ] + } + }, + "dontCacheBustURLsMatching": { + "description": "Assets that match this will be assumed to be uniquely versioned via their\nURL, and exempted from the normal HTTP cache-busting that's done when\npopulating the precache. While not required, it's recommended that if your\nexisting build process already inserts a `[hash]` value into each filename,\nyou provide a RegExp that will detect that, as it will reduce the bandwidth\nconsumed when precaching.", + "$ref": "#/definitions/RegExp" + }, + "manifestTransforms": { + "description": "One or more functions which will be applied sequentially against the\ngenerated manifest. If `modifyURLPrefix` or `dontCacheBustURLsMatching` are\nalso specified, their corresponding transformations will be applied first.", + "type": "array", + "items": {} + }, + "maximumFileSizeToCacheInBytes": { + "description": "This value can be used to determine the maximum size of files that will be\nprecached. This prevents you from inadvertently precaching very large files\nthat might have accidentally matched one of your patterns.", + "default": 2097152, + "type": "number" + }, + "modifyURLPrefix": { + "description": "An object mapping string prefixes to replacement string values. This can be\nused to, e.g., remove or add a path prefix from a manifest entry if your\nweb hosting setup doesn't match your local filesystem setup. As an\nalternative with more flexibility, you can use the `manifestTransforms`\noption and provide a function that modifies the entries in the manifest\nusing whatever logic you provide.\n\nExample usage:\n\n```\n// Replace a '/dist/' prefix with '/', and also prepend\n// '/static' to every URL.\nmodifyURLPrefix: {\n '/dist/': '/',\n '': '/static',\n}\n```", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "globFollow": { + "description": "Determines whether or not symlinks are followed when generating the\nprecache manifest. For more information, see the definition of `follow` in\nthe `glob` [documentation](https://github.com/isaacs/node-glob#options).", + "default": true, + "type": "boolean" + }, + "globIgnores": { + "description": "A set of patterns matching files to always exclude when generating the\nprecache manifest. For more information, see the definition of `ignore` in\nthe `glob` [documentation](https://github.com/isaacs/node-glob#options).", + "default": [ + "**/node_modules/**/*" + ], + "type": "array", + "items": { + "type": "string" + } + }, + "globPatterns": { + "description": "Files matching any of these patterns will be included in the precache\nmanifest. For more information, see the\n[`glob` primer](https://github.com/isaacs/node-glob#glob-primer).", + "default": [ + "**/*.{js,wasm,css,html}" + ], + "type": "array", + "items": { + "type": "string" + } + }, + "templatedURLs": { + "description": "If a URL is rendered based on some server-side logic, its contents may\ndepend on multiple files or on some other unique string value. The keys in\nthis object are server-rendered URLs. If the values are an array of\nstrings, they will be interpreted as `glob` patterns, and the contents of\nany files matching the patterns will be used to uniquely version the URL.\nIf used with a single string, it will be interpreted as unique versioning\ninformation that you've generated for a given URL.", + "type": "object", + "additionalProperties": { + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string" + } + ] + } + }, + "injectionPoint": { + "description": "The string to find inside of the `swSrc` file. Once found, it will be\nreplaced by the generated precache manifest.", + "default": "self.__WB_MANIFEST", + "type": "string" + }, + "swSrc": { + "description": "The path and filename of the service worker file that will be read during\nthe build process, relative to the current working directory.", + "type": "string" + }, + "swDest": { + "description": "The path and filename of the service worker file that will be created by\nthe build process, relative to the current working directory. It must end\nin '.js'.", + "type": "string" + }, + "globDirectory": { + "description": "The local directory you wish to match `globPatterns` against. The path is\nrelative to the current directory.", + "type": "string" + } + }, + "required": [ + "globDirectory", + "swDest", + "swSrc" + ], + "definitions": { + "ManifestEntry": { + "type": "object", + "properties": { + "integrity": { + "type": "string" + }, + "revision": { + "type": [ + "null", + "string" + ] + }, + "url": { + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "revision", + "url" + ] + }, + "RegExp": { + "type": "object", + "properties": { + "source": { + "type": "string" + }, + "global": { + "type": "boolean" + }, + "ignoreCase": { + "type": "boolean" + }, + "multiline": { + "type": "boolean" + }, + "lastIndex": { + "type": "number" + }, + "flags": { + "type": "string" + }, + "sticky": { + "type": "boolean" + }, + "unicode": { + "type": "boolean" + }, + "dotAll": { + "type": "boolean" + }, + "hasIndices": { + "type": "boolean" + } + }, + "additionalProperties": false, + "required": [ + "dotAll", + "flags", + "global", + "hasIndices", + "ignoreCase", + "lastIndex", + "multiline", + "source", + "sticky", + "unicode" + ] + } + }, + "$schema": "http://json-schema.org/draft-07/schema#" +} diff --git a/node_modules/workbox-build/build/schema/WebpackGenerateSWOptions.json b/node_modules/workbox-build/build/schema/WebpackGenerateSWOptions.json new file mode 100644 index 0000000000000000000000000000000000000000..ef797d6a92597d95cb08340406bc48d8c0c94f50 --- /dev/null +++ b/node_modules/workbox-build/build/schema/WebpackGenerateSWOptions.json @@ -0,0 +1,861 @@ +{ + "additionalProperties": false, + "type": "object", + "properties": { + "additionalManifestEntries": { + "description": "A list of entries to be precached, in addition to any entries that are\ngenerated as part of the build configuration.", + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/definitions/ManifestEntry" + }, + { + "type": "string" + } + ] + } + }, + "dontCacheBustURLsMatching": { + "description": "Assets that match this will be assumed to be uniquely versioned via their\nURL, and exempted from the normal HTTP cache-busting that's done when\npopulating the precache. While not required, it's recommended that if your\nexisting build process already inserts a `[hash]` value into each filename,\nyou provide a RegExp that will detect that, as it will reduce the bandwidth\nconsumed when precaching.", + "$ref": "#/definitions/RegExp" + }, + "manifestTransforms": { + "description": "One or more functions which will be applied sequentially against the\ngenerated manifest. If `modifyURLPrefix` or `dontCacheBustURLsMatching` are\nalso specified, their corresponding transformations will be applied first.", + "type": "array", + "items": {} + }, + "maximumFileSizeToCacheInBytes": { + "description": "This value can be used to determine the maximum size of files that will be\nprecached. This prevents you from inadvertently precaching very large files\nthat might have accidentally matched one of your patterns.", + "default": 2097152, + "type": "number" + }, + "modifyURLPrefix": { + "description": "An object mapping string prefixes to replacement string values. This can be\nused to, e.g., remove or add a path prefix from a manifest entry if your\nweb hosting setup doesn't match your local filesystem setup. As an\nalternative with more flexibility, you can use the `manifestTransforms`\noption and provide a function that modifies the entries in the manifest\nusing whatever logic you provide.\n\nExample usage:\n\n```\n// Replace a '/dist/' prefix with '/', and also prepend\n// '/static' to every URL.\nmodifyURLPrefix: {\n '/dist/': '/',\n '': '/static',\n}\n```", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "chunks": { + "description": "One or more chunk names whose corresponding output files should be included\nin the precache manifest.", + "type": "array", + "items": { + "type": "string" + } + }, + "exclude": { + "description": "One or more specifiers used to exclude assets from the precache manifest.\nThis is interpreted following\n[the same rules](https://webpack.js.org/configuration/module/#condition)\nas `webpack`'s standard `exclude` option.\nIf not provided, the default value is `[/\\.map$/, /^manifest.*\\.js$]`.", + "type": "array", + "items": {} + }, + "excludeChunks": { + "description": "One or more chunk names whose corresponding output files should be excluded\nfrom the precache manifest.", + "type": "array", + "items": { + "type": "string" + } + }, + "include": { + "description": "One or more specifiers used to include assets in the precache manifest.\nThis is interpreted following\n[the same rules](https://webpack.js.org/configuration/module/#condition)\nas `webpack`'s standard `include` option.", + "type": "array", + "items": {} + }, + "mode": { + "description": "If set to 'production', then an optimized service worker bundle that\nexcludes debugging info will be produced. If not explicitly configured\nhere, the `process.env.NODE_ENV` value will be used, and failing that, it\nwill fall back to `'production'`.", + "default": "production", + "type": [ + "null", + "string" + ] + }, + "babelPresetEnvTargets": { + "description": "The [targets](https://babeljs.io/docs/en/babel-preset-env#targets) to pass\nto `babel-preset-env` when transpiling the service worker bundle.", + "default": [ + "chrome >= 56" + ], + "type": "array", + "items": { + "type": "string" + } + }, + "cacheId": { + "description": "An optional ID to be prepended to cache names. This is primarily useful for\nlocal development where multiple sites may be served from the same\n`http://localhost:port` origin.", + "type": [ + "null", + "string" + ] + }, + "cleanupOutdatedCaches": { + "description": "Whether or not Workbox should attempt to identify and delete any precaches\ncreated by older, incompatible versions.", + "default": false, + "type": "boolean" + }, + "clientsClaim": { + "description": "Whether or not the service worker should [start controlling](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#clientsclaim)\nany existing clients as soon as it activates.", + "default": false, + "type": "boolean" + }, + "directoryIndex": { + "description": "If a navigation request for a URL ending in `/` fails to match a precached\nURL, this value will be appended to the URL and that will be checked for a\nprecache match. This should be set to what your web server is using for its\ndirectory index.", + "type": [ + "null", + "string" + ] + }, + "disableDevLogs": { + "default": false, + "type": "boolean" + }, + "ignoreURLParametersMatching": { + "description": "Any search parameter names that match against one of the RegExp in this\narray will be removed before looking for a precache match. This is useful\nif your users might request URLs that contain, for example, URL parameters\nused to track the source of the traffic. If not provided, the default value\nis `[/^utm_/, /^fbclid$/]`.", + "type": "array", + "items": { + "$ref": "#/definitions/RegExp" + } + }, + "importScripts": { + "description": "A list of JavaScript files that should be passed to\n[`importScripts()`](https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts)\ninside the generated service worker file. This is useful when you want to\nlet Workbox create your top-level service worker file, but want to include\nsome additional code, such as a push event listener.", + "type": "array", + "items": { + "type": "string" + } + }, + "inlineWorkboxRuntime": { + "description": "Whether the runtime code for the Workbox library should be included in the\ntop-level service worker, or split into a separate file that needs to be\ndeployed alongside the service worker. Keeping the runtime separate means\nthat users will not have to re-download the Workbox code each time your\ntop-level service worker changes.", + "default": false, + "type": "boolean" + }, + "navigateFallback": { + "description": "If specified, all\n[navigation requests](https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests)\nfor URLs that aren't precached will be fulfilled with the HTML at the URL\nprovided. You must pass in the URL of an HTML document that is listed in\nyour precache manifest. This is meant to be used in a Single Page App\nscenario, in which you want all navigations to use common\n[App Shell HTML](https://developers.google.com/web/fundamentals/architecture/app-shell).", + "default": null, + "type": [ + "null", + "string" + ] + }, + "navigateFallbackAllowlist": { + "description": "An optional array of regular expressions that restricts which URLs the\nconfigured `navigateFallback` behavior applies to. This is useful if only a\nsubset of your site's URLs should be treated as being part of a\n[Single Page App](https://en.wikipedia.org/wiki/Single-page_application).\nIf both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are\nconfigured, the denylist takes precedent.\n\n*Note*: These RegExps may be evaluated against every destination URL during\na navigation. Avoid using\n[complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077),\nor else your users may see delays when navigating your site.", + "type": "array", + "items": { + "$ref": "#/definitions/RegExp" + } + }, + "navigateFallbackDenylist": { + "description": "An optional array of regular expressions that restricts which URLs the\nconfigured `navigateFallback` behavior applies to. This is useful if only a\nsubset of your site's URLs should be treated as being part of a\n[Single Page App](https://en.wikipedia.org/wiki/Single-page_application).\nIf both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are\nconfigured, the denylist takes precedence.\n\n*Note*: These RegExps may be evaluated against every destination URL during\na navigation. Avoid using\n[complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077),\nor else your users may see delays when navigating your site.", + "type": "array", + "items": { + "$ref": "#/definitions/RegExp" + } + }, + "navigationPreload": { + "description": "Whether or not to enable\n[navigation preload](https://developers.google.com/web/tools/workbox/modules/workbox-navigation-preload)\nin the generated service worker. When set to true, you must also use\n`runtimeCaching` to set up an appropriate response strategy that will match\nnavigation requests, and make use of the preloaded response.", + "default": false, + "type": "boolean" + }, + "offlineGoogleAnalytics": { + "description": "Controls whether or not to include support for\n[offline Google Analytics](https://developers.google.com/web/tools/workbox/guides/enable-offline-analytics).\nWhen `true`, the call to `workbox-google-analytics`'s `initialize()` will\nbe added to your generated service worker. When set to an `Object`, that\nobject will be passed in to the `initialize()` call, allowing you to\ncustomize the behavior.", + "default": false, + "anyOf": [ + { + "$ref": "#/definitions/GoogleAnalyticsInitializeOptions" + }, + { + "type": "boolean" + } + ] + }, + "runtimeCaching": { + "description": "When using Workbox's build tools to generate your service worker, you can\nspecify one or more runtime caching configurations. These are then\ntranslated to {@link workbox-routing.registerRoute} calls using the match\nand handler configuration you define.\n\nFor all of the options, see the {@link workbox-build.RuntimeCaching}\ndocumentation. The example below shows a typical configuration, with two\nruntime routes defined:", + "type": "array", + "items": { + "$ref": "#/definitions/RuntimeCaching" + } + }, + "skipWaiting": { + "description": "Whether to add an unconditional call to [`skipWaiting()`](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#skip_the_waiting_phase)\nto the generated service worker. If `false`, then a `message` listener will\nbe added instead, allowing client pages to trigger `skipWaiting()` by\ncalling `postMessage({type: 'SKIP_WAITING'})` on a waiting service worker.", + "default": false, + "type": "boolean" + }, + "sourcemap": { + "description": "Whether to create a sourcemap for the generated service worker files.", + "default": true, + "type": "boolean" + }, + "importScriptsViaChunks": { + "description": "One or more names of webpack chunks. The content of those chunks will be\nincluded in the generated service worker, via a call to `importScripts()`.", + "type": "array", + "items": { + "type": "string" + } + }, + "swDest": { + "description": "The asset name of the service worker file created by this plugin.", + "default": "service-worker.js", + "type": "string" + } + }, + "definitions": { + "ManifestEntry": { + "type": "object", + "properties": { + "integrity": { + "type": "string" + }, + "revision": { + "type": [ + "null", + "string" + ] + }, + "url": { + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "revision", + "url" + ] + }, + "RegExp": { + "type": "object", + "properties": { + "source": { + "type": "string" + }, + "global": { + "type": "boolean" + }, + "ignoreCase": { + "type": "boolean" + }, + "multiline": { + "type": "boolean" + }, + "lastIndex": { + "type": "number" + }, + "flags": { + "type": "string" + }, + "sticky": { + "type": "boolean" + }, + "unicode": { + "type": "boolean" + }, + "dotAll": { + "type": "boolean" + }, + "hasIndices": { + "type": "boolean" + } + }, + "additionalProperties": false, + "required": [ + "dotAll", + "flags", + "global", + "hasIndices", + "ignoreCase", + "lastIndex", + "multiline", + "source", + "sticky", + "unicode" + ] + }, + "GoogleAnalyticsInitializeOptions": { + "type": "object", + "properties": { + "cacheName": { + "type": "string" + }, + "parameterOverrides": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "hitFilter": { + "type": "object", + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "RuntimeCaching": { + "type": "object", + "properties": { + "handler": { + "description": "This determines how the runtime route will generate a response.\nTo use one of the built-in {@link workbox-strategies}, provide its name,\nlike `'NetworkFirst'`.\nAlternatively, this can be a {@link workbox-core.RouteHandler} callback\nfunction with custom response logic.", + "anyOf": [ + { + "$ref": "#/definitions/RouteHandlerCallback" + }, + { + "$ref": "#/definitions/RouteHandlerObject" + }, + { + "enum": [ + "CacheFirst", + "CacheOnly", + "NetworkFirst", + "NetworkOnly", + "StaleWhileRevalidate" + ], + "type": "string" + } + ] + }, + "method": { + "description": "The HTTP method to match against. The default value of `'GET'` is normally\nsufficient, unless you explicitly need to match `'POST'`, `'PUT'`, or\nanother type of request.", + "default": "GET", + "enum": [ + "DELETE", + "GET", + "HEAD", + "PATCH", + "POST", + "PUT" + ], + "type": "string" + }, + "options": { + "type": "object", + "properties": { + "backgroundSync": { + "description": "Configuring this will add a\n{@link workbox-background-sync.BackgroundSyncPlugin} instance to the\n{@link workbox-strategies} configured in `handler`.", + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "options": { + "$ref": "#/definitions/QueueOptions" + } + }, + "additionalProperties": false, + "required": [ + "name" + ] + }, + "broadcastUpdate": { + "description": "Configuring this will add a\n{@link workbox-broadcast-update.BroadcastUpdatePlugin} instance to the\n{@link workbox-strategies} configured in `handler`.", + "type": "object", + "properties": { + "channelName": { + "type": "string" + }, + "options": { + "$ref": "#/definitions/BroadcastCacheUpdateOptions" + } + }, + "additionalProperties": false, + "required": [ + "options" + ] + }, + "cacheableResponse": { + "description": "Configuring this will add a\n{@link workbox-cacheable-response.CacheableResponsePlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", + "$ref": "#/definitions/CacheableResponseOptions" + }, + "cacheName": { + "description": "If provided, this will set the `cacheName` property of the\n{@link workbox-strategies} configured in `handler`.", + "type": [ + "null", + "string" + ] + }, + "expiration": { + "description": "Configuring this will add a\n{@link workbox-expiration.ExpirationPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", + "$ref": "#/definitions/ExpirationPluginOptions" + }, + "networkTimeoutSeconds": { + "description": "If provided, this will set the `networkTimeoutSeconds` property of the\n{@link workbox-strategies} configured in `handler`. Note that only\n`'NetworkFirst'` and `'NetworkOnly'` support `networkTimeoutSeconds`.", + "type": "number" + }, + "plugins": { + "description": "Configuring this allows the use of one or more Workbox plugins that\ndon't have \"shortcut\" options (like `expiration` for\n{@link workbox-expiration.ExpirationPlugin}). The plugins provided here\nwill be added to the {@link workbox-strategies} configured in `handler`.", + "type": "array", + "items": { + "$ref": "#/definitions/WorkboxPlugin" + } + }, + "precacheFallback": { + "description": "Configuring this will add a\n{@link workbox-precaching.PrecacheFallbackPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", + "type": "object", + "properties": { + "fallbackURL": { + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "fallbackURL" + ] + }, + "rangeRequests": { + "description": "Enabling this will add a\n{@link workbox-range-requests.RangeRequestsPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", + "type": "boolean" + }, + "fetchOptions": { + "description": "Configuring this will pass along the `fetchOptions` value to\nthe {@link workbox-strategies} configured in `handler`.", + "$ref": "#/definitions/RequestInit" + }, + "matchOptions": { + "description": "Configuring this will pass along the `matchOptions` value to\nthe {@link workbox-strategies} configured in `handler`.", + "$ref": "#/definitions/CacheQueryOptions" + } + }, + "additionalProperties": false + }, + "urlPattern": { + "description": "This match criteria determines whether the configured handler will\ngenerate a response for any requests that don't match one of the precached\nURLs. If multiple `RuntimeCaching` routes are defined, then the first one\nwhose `urlPattern` matches will be the one that responds.\n\nThis value directly maps to the first parameter passed to\n{@link workbox-routing.registerRoute}. It's recommended to use a\n{@link workbox-core.RouteMatchCallback} function for greatest flexibility.", + "anyOf": [ + { + "$ref": "#/definitions/RegExp" + }, + { + "$ref": "#/definitions/RouteMatchCallback" + }, + { + "type": "string" + } + ] + } + }, + "additionalProperties": false, + "required": [ + "handler", + "urlPattern" + ] + }, + "RouteHandlerCallback": {}, + "RouteHandlerObject": { + "description": "An object with a `handle` method of type `RouteHandlerCallback`.\n\nA `Route` object can be created with either an `RouteHandlerCallback`\nfunction or this `RouteHandler` object. The benefit of the `RouteHandler`\nis it can be extended (as is done by the `workbox-strategies` package).", + "type": "object", + "properties": { + "handle": { + "$ref": "#/definitions/RouteHandlerCallback" + } + }, + "additionalProperties": false, + "required": [ + "handle" + ] + }, + "QueueOptions": { + "type": "object", + "properties": { + "forceSyncFallback": { + "type": "boolean" + }, + "maxRetentionTime": { + "type": "number" + }, + "onSync": { + "$ref": "#/definitions/OnSyncCallback" + } + }, + "additionalProperties": false + }, + "OnSyncCallback": {}, + "BroadcastCacheUpdateOptions": { + "type": "object", + "properties": { + "headersToCheck": { + "type": "array", + "items": { + "type": "string" + } + }, + "generatePayload": { + "type": "object", + "additionalProperties": false + }, + "notifyAllClients": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "CacheableResponseOptions": { + "type": "object", + "properties": { + "statuses": { + "type": "array", + "items": { + "type": "number" + } + }, + "headers": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "additionalProperties": false + }, + "ExpirationPluginOptions": { + "type": "object", + "properties": { + "maxEntries": { + "type": "number" + }, + "maxAgeSeconds": { + "type": "number" + }, + "matchOptions": { + "$ref": "#/definitions/CacheQueryOptions" + }, + "purgeOnQuotaError": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "CacheQueryOptions": { + "type": "object", + "properties": { + "ignoreMethod": { + "type": "boolean" + }, + "ignoreSearch": { + "type": "boolean" + }, + "ignoreVary": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "WorkboxPlugin": { + "description": "An object with optional lifecycle callback properties for the fetch and\ncache operations.", + "type": "object", + "properties": { + "cacheDidUpdate": {}, + "cachedResponseWillBeUsed": {}, + "cacheKeyWillBeUsed": {}, + "cacheWillUpdate": {}, + "fetchDidFail": {}, + "fetchDidSucceed": {}, + "handlerDidComplete": {}, + "handlerDidError": {}, + "handlerDidRespond": {}, + "handlerWillRespond": {}, + "handlerWillStart": {}, + "requestWillFetch": {} + }, + "additionalProperties": false + }, + "CacheDidUpdateCallback": { + "type": "object", + "additionalProperties": false + }, + "CachedResponseWillBeUsedCallback": { + "type": "object", + "additionalProperties": false + }, + "CacheKeyWillBeUsedCallback": { + "type": "object", + "additionalProperties": false + }, + "CacheWillUpdateCallback": { + "type": "object", + "additionalProperties": false + }, + "FetchDidFailCallback": { + "type": "object", + "additionalProperties": false + }, + "FetchDidSucceedCallback": { + "type": "object", + "additionalProperties": false + }, + "HandlerDidCompleteCallback": { + "type": "object", + "additionalProperties": false + }, + "HandlerDidErrorCallback": { + "type": "object", + "additionalProperties": false + }, + "HandlerDidRespondCallback": { + "type": "object", + "additionalProperties": false + }, + "HandlerWillRespondCallback": { + "type": "object", + "additionalProperties": false + }, + "HandlerWillStartCallback": { + "type": "object", + "additionalProperties": false + }, + "RequestWillFetchCallback": { + "type": "object", + "additionalProperties": false + }, + "RequestInit": { + "type": "object", + "properties": { + "body": { + "anyOf": [ + { + "$ref": "#/definitions/ArrayBuffer" + }, + { + "$ref": "#/definitions/ArrayBufferView" + }, + { + "$ref": "#/definitions/ReadableStream" + }, + { + "$ref": "#/definitions/Blob" + }, + { + "$ref": "#/definitions/FormData" + }, + { + "$ref": "#/definitions/URLSearchParams" + }, + { + "type": [ + "null", + "string" + ] + } + ] + }, + "cache": { + "enum": [ + "default", + "force-cache", + "no-cache", + "no-store", + "only-if-cached", + "reload" + ], + "type": "string" + }, + "credentials": { + "enum": [ + "include", + "omit", + "same-origin" + ], + "type": "string" + }, + "headers": { + "anyOf": [ + { + "$ref": "#/definitions/Record" + }, + { + "type": "array", + "items": { + "type": "array", + "items": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "minItems": 2, + "maxItems": 2 + } + }, + { + "$ref": "#/definitions/Headers" + } + ] + }, + "integrity": { + "type": "string" + }, + "keepalive": { + "type": "boolean" + }, + "method": { + "type": "string" + }, + "mode": { + "enum": [ + "cors", + "navigate", + "no-cors", + "same-origin" + ], + "type": "string" + }, + "redirect": { + "enum": [ + "error", + "follow", + "manual" + ], + "type": "string" + }, + "referrer": { + "type": "string" + }, + "referrerPolicy": { + "enum": [ + "", + "no-referrer", + "no-referrer-when-downgrade", + "origin", + "origin-when-cross-origin", + "same-origin", + "strict-origin", + "strict-origin-when-cross-origin", + "unsafe-url" + ], + "type": "string" + }, + "signal": { + "anyOf": [ + { + "$ref": "#/definitions/AbortSignal" + }, + { + "type": "null" + } + ] + }, + "window": { + "type": "null" + } + }, + "additionalProperties": false + }, + "ArrayBuffer": { + "type": "object", + "properties": { + "byteLength": { + "type": "number" + }, + "__@toStringTag@32": { + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "__@toStringTag@32", + "byteLength" + ] + }, + "ArrayBufferView": { + "type": "object", + "properties": { + "buffer": { + "$ref": "#/definitions/ArrayBufferLike" + }, + "byteLength": { + "type": "number" + }, + "byteOffset": { + "type": "number" + } + }, + "additionalProperties": false, + "required": [ + "buffer", + "byteLength", + "byteOffset" + ] + }, + "ArrayBufferLike": { + "anyOf": [ + { + "$ref": "#/definitions/ArrayBuffer" + }, + { + "$ref": "#/definitions/SharedArrayBuffer" + } + ] + }, + "SharedArrayBuffer": { + "type": "object", + "properties": { + "byteLength": { + "type": "number" + }, + "__@species@492": { + "$ref": "#/definitions/SharedArrayBuffer" + }, + "__@toStringTag@32": { + "type": "string", + "const": "SharedArrayBuffer" + } + }, + "additionalProperties": false, + "required": [ + "__@species@492", + "__@toStringTag@32", + "byteLength" + ] + }, + "ReadableStream": { + "type": "object", + "properties": { + "locked": { + "type": "boolean" + } + }, + "additionalProperties": false, + "required": [ + "locked" + ] + }, + "Blob": { + "type": "object", + "properties": { + "size": { + "type": "number" + }, + "type": { + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "size", + "type" + ] + }, + "FormData": { + "type": "object", + "additionalProperties": false + }, + "URLSearchParams": { + "type": "object", + "properties": { + "size": { + "description": "The total number of parameter entries.", + "type": "number" + } + }, + "additionalProperties": false, + "required": [ + "size" + ] + }, + "Record": { + "type": "object", + "additionalProperties": false + }, + "Headers": { + "type": "object", + "additionalProperties": false + }, + "AbortSignal": {}, + "RouteMatchCallback": {} + }, + "$schema": "http://json-schema.org/draft-07/schema#" +} diff --git a/node_modules/workbox-build/build/schema/WebpackInjectManifestOptions.json b/node_modules/workbox-build/build/schema/WebpackInjectManifestOptions.json new file mode 100644 index 0000000000000000000000000000000000000000..afd5703cbef2e8f2e0ea9c3ceb55ea15cbbca498 --- /dev/null +++ b/node_modules/workbox-build/build/schema/WebpackInjectManifestOptions.json @@ -0,0 +1,171 @@ +{ + "additionalProperties": false, + "type": "object", + "properties": { + "additionalManifestEntries": { + "description": "A list of entries to be precached, in addition to any entries that are\ngenerated as part of the build configuration.", + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/definitions/ManifestEntry" + }, + { + "type": "string" + } + ] + } + }, + "dontCacheBustURLsMatching": { + "description": "Assets that match this will be assumed to be uniquely versioned via their\nURL, and exempted from the normal HTTP cache-busting that's done when\npopulating the precache. While not required, it's recommended that if your\nexisting build process already inserts a `[hash]` value into each filename,\nyou provide a RegExp that will detect that, as it will reduce the bandwidth\nconsumed when precaching.", + "$ref": "#/definitions/RegExp" + }, + "manifestTransforms": { + "description": "One or more functions which will be applied sequentially against the\ngenerated manifest. If `modifyURLPrefix` or `dontCacheBustURLsMatching` are\nalso specified, their corresponding transformations will be applied first.", + "type": "array", + "items": {} + }, + "maximumFileSizeToCacheInBytes": { + "description": "This value can be used to determine the maximum size of files that will be\nprecached. This prevents you from inadvertently precaching very large files\nthat might have accidentally matched one of your patterns.", + "default": 2097152, + "type": "number" + }, + "modifyURLPrefix": { + "description": "An object mapping string prefixes to replacement string values. This can be\nused to, e.g., remove or add a path prefix from a manifest entry if your\nweb hosting setup doesn't match your local filesystem setup. As an\nalternative with more flexibility, you can use the `manifestTransforms`\noption and provide a function that modifies the entries in the manifest\nusing whatever logic you provide.\n\nExample usage:\n\n```\n// Replace a '/dist/' prefix with '/', and also prepend\n// '/static' to every URL.\nmodifyURLPrefix: {\n '/dist/': '/',\n '': '/static',\n}\n```", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "chunks": { + "description": "One or more chunk names whose corresponding output files should be included\nin the precache manifest.", + "type": "array", + "items": { + "type": "string" + } + }, + "exclude": { + "description": "One or more specifiers used to exclude assets from the precache manifest.\nThis is interpreted following\n[the same rules](https://webpack.js.org/configuration/module/#condition)\nas `webpack`'s standard `exclude` option.\nIf not provided, the default value is `[/\\.map$/, /^manifest.*\\.js$]`.", + "type": "array", + "items": {} + }, + "excludeChunks": { + "description": "One or more chunk names whose corresponding output files should be excluded\nfrom the precache manifest.", + "type": "array", + "items": { + "type": "string" + } + }, + "include": { + "description": "One or more specifiers used to include assets in the precache manifest.\nThis is interpreted following\n[the same rules](https://webpack.js.org/configuration/module/#condition)\nas `webpack`'s standard `include` option.", + "type": "array", + "items": {} + }, + "mode": { + "description": "If set to 'production', then an optimized service worker bundle that\nexcludes debugging info will be produced. If not explicitly configured\nhere, the `mode` value configured in the current `webpack` compilation\nwill be used.", + "type": [ + "null", + "string" + ] + }, + "injectionPoint": { + "description": "The string to find inside of the `swSrc` file. Once found, it will be\nreplaced by the generated precache manifest.", + "default": "self.__WB_MANIFEST", + "type": "string" + }, + "swSrc": { + "description": "The path and filename of the service worker file that will be read during\nthe build process, relative to the current working directory.", + "type": "string" + }, + "compileSrc": { + "description": "When `true` (the default), the `swSrc` file will be compiled by webpack.\nWhen `false`, compilation will not occur (and `webpackCompilationPlugins`\ncan't be used.) Set to `false` if you want to inject the manifest into,\ne.g., a JSON file.", + "default": true, + "type": "boolean" + }, + "swDest": { + "description": "The asset name of the service worker file that will be created by this\nplugin. If omitted, the name will be based on the `swSrc` name.", + "type": "string" + }, + "webpackCompilationPlugins": { + "description": "Optional `webpack` plugins that will be used when compiling the `swSrc`\ninput file. Only valid if `compileSrc` is `true`.", + "type": "array", + "items": {} + } + }, + "required": [ + "swSrc" + ], + "definitions": { + "ManifestEntry": { + "type": "object", + "properties": { + "integrity": { + "type": "string" + }, + "revision": { + "type": [ + "null", + "string" + ] + }, + "url": { + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "revision", + "url" + ] + }, + "RegExp": { + "type": "object", + "properties": { + "source": { + "type": "string" + }, + "global": { + "type": "boolean" + }, + "ignoreCase": { + "type": "boolean" + }, + "multiline": { + "type": "boolean" + }, + "lastIndex": { + "type": "number" + }, + "flags": { + "type": "string" + }, + "sticky": { + "type": "boolean" + }, + "unicode": { + "type": "boolean" + }, + "dotAll": { + "type": "boolean" + }, + "hasIndices": { + "type": "boolean" + } + }, + "additionalProperties": false, + "required": [ + "dotAll", + "flags", + "global", + "hasIndices", + "ignoreCase", + "lastIndex", + "multiline", + "source", + "sticky", + "unicode" + ] + } + }, + "$schema": "http://json-schema.org/draft-07/schema#" +} diff --git a/node_modules/workbox-build/build/templates/sw-template.d.ts b/node_modules/workbox-build/build/templates/sw-template.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cc99f8fba5d2aa055f71e6f0859bcec9bd2590d2 --- /dev/null +++ b/node_modules/workbox-build/build/templates/sw-template.d.ts @@ -0,0 +1 @@ +export declare const swTemplate = "/**\n * Welcome to your Workbox-powered service worker!\n *\n * You'll need to register this file in your web app.\n * See https://goo.gl/nhQhGp\n *\n * The rest of the code is auto-generated. Please don't update this file\n * directly; instead, make changes to your Workbox build configuration\n * and re-run your build process.\n * See https://goo.gl/2aRDsh\n */\n\n<% if (importScripts) { %>\nimportScripts(\n <%= importScripts.map(JSON.stringify).join(',\\n ') %>\n);\n<% } %>\n\n<% if (navigationPreload) { %><%= use('workbox-navigation-preload', 'enable') %>();<% } %>\n\n<% if (cacheId) { %><%= use('workbox-core', 'setCacheNameDetails') %>({prefix: <%= JSON.stringify(cacheId) %>});<% } %>\n\n<% if (skipWaiting) { %>\nself.skipWaiting();\n<% } else { %>\nself.addEventListener('message', (event) => {\n if (event.data && event.data.type === 'SKIP_WAITING') {\n self.skipWaiting();\n }\n});\n<% } %>\n<% if (clientsClaim) { %><%= use('workbox-core', 'clientsClaim') %>();<% } %>\n\n<% if (Array.isArray(manifestEntries) && manifestEntries.length > 0) {%>\n/**\n * The precacheAndRoute() method efficiently caches and responds to\n * requests for URLs in the manifest.\n * See https://goo.gl/S9QRab\n */\n<%= use('workbox-precaching', 'precacheAndRoute') %>(<%= JSON.stringify(manifestEntries, null, 2) %>, <%= precacheOptionsString %>);\n<% if (cleanupOutdatedCaches) { %><%= use('workbox-precaching', 'cleanupOutdatedCaches') %>();<% } %>\n<% if (navigateFallback) { %><%= use('workbox-routing', 'registerRoute') %>(new <%= use('workbox-routing', 'NavigationRoute') %>(<%= use('workbox-precaching', 'createHandlerBoundToURL') %>(<%= JSON.stringify(navigateFallback) %>)<% if (navigateFallbackAllowlist || navigateFallbackDenylist) { %>, {\n <% if (navigateFallbackAllowlist) { %>allowlist: [<%= navigateFallbackAllowlist %>],<% } %>\n <% if (navigateFallbackDenylist) { %>denylist: [<%= navigateFallbackDenylist %>],<% } %>\n}<% } %>));<% } %>\n<% } %>\n\n<% if (runtimeCaching) { runtimeCaching.forEach(runtimeCachingString => {%><%= runtimeCachingString %><% });} %>\n\n<% if (offlineAnalyticsConfigString) { %><%= use('workbox-google-analytics', 'initialize') %>(<%= offlineAnalyticsConfigString %>);<% } %>\n\n<% if (disableDevLogs) { %>self.__WB_DISABLE_DEV_LOGS = true;<% } %>"; diff --git a/node_modules/workbox-build/build/templates/sw-template.js b/node_modules/workbox-build/build/templates/sw-template.js new file mode 100644 index 0000000000000000000000000000000000000000..36adc39078f9e639ae19b5bc0d9c28cfd8cb7ecc --- /dev/null +++ b/node_modules/workbox-build/build/templates/sw-template.js @@ -0,0 +1,62 @@ +"use strict"; +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.swTemplate = void 0; +exports.swTemplate = `/** + * Welcome to your Workbox-powered service worker! + * + * You'll need to register this file in your web app. + * See https://goo.gl/nhQhGp + * + * The rest of the code is auto-generated. Please don't update this file + * directly; instead, make changes to your Workbox build configuration + * and re-run your build process. + * See https://goo.gl/2aRDsh + */ + +<% if (importScripts) { %> +importScripts( + <%= importScripts.map(JSON.stringify).join(',\\n ') %> +); +<% } %> + +<% if (navigationPreload) { %><%= use('workbox-navigation-preload', 'enable') %>();<% } %> + +<% if (cacheId) { %><%= use('workbox-core', 'setCacheNameDetails') %>({prefix: <%= JSON.stringify(cacheId) %>});<% } %> + +<% if (skipWaiting) { %> +self.skipWaiting(); +<% } else { %> +self.addEventListener('message', (event) => { + if (event.data && event.data.type === 'SKIP_WAITING') { + self.skipWaiting(); + } +}); +<% } %> +<% if (clientsClaim) { %><%= use('workbox-core', 'clientsClaim') %>();<% } %> + +<% if (Array.isArray(manifestEntries) && manifestEntries.length > 0) {%> +/** + * The precacheAndRoute() method efficiently caches and responds to + * requests for URLs in the manifest. + * See https://goo.gl/S9QRab + */ +<%= use('workbox-precaching', 'precacheAndRoute') %>(<%= JSON.stringify(manifestEntries, null, 2) %>, <%= precacheOptionsString %>); +<% if (cleanupOutdatedCaches) { %><%= use('workbox-precaching', 'cleanupOutdatedCaches') %>();<% } %> +<% if (navigateFallback) { %><%= use('workbox-routing', 'registerRoute') %>(new <%= use('workbox-routing', 'NavigationRoute') %>(<%= use('workbox-precaching', 'createHandlerBoundToURL') %>(<%= JSON.stringify(navigateFallback) %>)<% if (navigateFallbackAllowlist || navigateFallbackDenylist) { %>, { + <% if (navigateFallbackAllowlist) { %>allowlist: [<%= navigateFallbackAllowlist %>],<% } %> + <% if (navigateFallbackDenylist) { %>denylist: [<%= navigateFallbackDenylist %>],<% } %> +}<% } %>));<% } %> +<% } %> + +<% if (runtimeCaching) { runtimeCaching.forEach(runtimeCachingString => {%><%= runtimeCachingString %><% });} %> + +<% if (offlineAnalyticsConfigString) { %><%= use('workbox-google-analytics', 'initialize') %>(<%= offlineAnalyticsConfigString %>);<% } %> + +<% if (disableDevLogs) { %>self.__WB_DISABLE_DEV_LOGS = true;<% } %>`; diff --git a/node_modules/workbox-build/build/types.d.ts b/node_modules/workbox-build/build/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..647ec8fd3d5750df5a1e25c42dbec1ee328a3b7d --- /dev/null +++ b/node_modules/workbox-build/build/types.d.ts @@ -0,0 +1,520 @@ +import { PackageJson } from 'type-fest'; +import { BroadcastCacheUpdateOptions } from 'workbox-broadcast-update/BroadcastCacheUpdate'; +import { GoogleAnalyticsInitializeOptions } from 'workbox-google-analytics/initialize'; +import { HTTPMethod } from 'workbox-routing/utils/constants'; +import { QueueOptions } from 'workbox-background-sync/Queue'; +import { RouteHandler, RouteMatchCallback } from 'workbox-core/types'; +import { CacheableResponseOptions } from 'workbox-cacheable-response/CacheableResponse'; +import { ExpirationPluginOptions } from 'workbox-expiration/ExpirationPlugin'; +import { WorkboxPlugin } from 'workbox-core/types'; +export interface ManifestEntry { + integrity?: string; + revision: string | null; + url: string; +} +export type StrategyName = 'CacheFirst' | 'CacheOnly' | 'NetworkFirst' | 'NetworkOnly' | 'StaleWhileRevalidate'; +export interface RuntimeCaching { + /** + * This determines how the runtime route will generate a response. + * To use one of the built-in {@link workbox-strategies}, provide its name, + * like `'NetworkFirst'`. + * Alternatively, this can be a {@link workbox-core.RouteHandler} callback + * function with custom response logic. + */ + handler: RouteHandler | StrategyName; + /** + * The HTTP method to match against. The default value of `'GET'` is normally + * sufficient, unless you explicitly need to match `'POST'`, `'PUT'`, or + * another type of request. + * @default "GET" + */ + method?: HTTPMethod; + options?: { + /** + * Configuring this will add a + * {@link workbox-background-sync.BackgroundSyncPlugin} instance to the + * {@link workbox-strategies} configured in `handler`. + */ + backgroundSync?: { + name: string; + options?: QueueOptions; + }; + /** + * Configuring this will add a + * {@link workbox-broadcast-update.BroadcastUpdatePlugin} instance to the + * {@link workbox-strategies} configured in `handler`. + */ + broadcastUpdate?: { + channelName?: string; + options: BroadcastCacheUpdateOptions; + }; + /** + * Configuring this will add a + * {@link workbox-cacheable-response.CacheableResponsePlugin} instance to + * the {@link workbox-strategies} configured in `handler`. + */ + cacheableResponse?: CacheableResponseOptions; + /** + * If provided, this will set the `cacheName` property of the + * {@link workbox-strategies} configured in `handler`. + */ + cacheName?: string | null; + /** + * Configuring this will add a + * {@link workbox-expiration.ExpirationPlugin} instance to + * the {@link workbox-strategies} configured in `handler`. + */ + expiration?: ExpirationPluginOptions; + /** + * If provided, this will set the `networkTimeoutSeconds` property of the + * {@link workbox-strategies} configured in `handler`. Note that only + * `'NetworkFirst'` and `'NetworkOnly'` support `networkTimeoutSeconds`. + */ + networkTimeoutSeconds?: number; + /** + * Configuring this allows the use of one or more Workbox plugins that + * don't have "shortcut" options (like `expiration` for + * {@link workbox-expiration.ExpirationPlugin}). The plugins provided here + * will be added to the {@link workbox-strategies} configured in `handler`. + */ + plugins?: Array; + /** + * Configuring this will add a + * {@link workbox-precaching.PrecacheFallbackPlugin} instance to + * the {@link workbox-strategies} configured in `handler`. + */ + precacheFallback?: { + fallbackURL: string; + }; + /** + * Enabling this will add a + * {@link workbox-range-requests.RangeRequestsPlugin} instance to + * the {@link workbox-strategies} configured in `handler`. + */ + rangeRequests?: boolean; + /** + * Configuring this will pass along the `fetchOptions` value to + * the {@link workbox-strategies} configured in `handler`. + */ + fetchOptions?: RequestInit; + /** + * Configuring this will pass along the `matchOptions` value to + * the {@link workbox-strategies} configured in `handler`. + */ + matchOptions?: CacheQueryOptions; + }; + /** + * This match criteria determines whether the configured handler will + * generate a response for any requests that don't match one of the precached + * URLs. If multiple `RuntimeCaching` routes are defined, then the first one + * whose `urlPattern` matches will be the one that responds. + * + * This value directly maps to the first parameter passed to + * {@link workbox-routing.registerRoute}. It's recommended to use a + * {@link workbox-core.RouteMatchCallback} function for greatest flexibility. + */ + urlPattern: RegExp | string | RouteMatchCallback; +} +export interface ManifestTransformResult { + manifest: Array; + warnings?: Array; +} +export type ManifestTransform = (manifestEntries: Array, compilation?: unknown) => Promise | ManifestTransformResult; +export interface BasePartial { + /** + * A list of entries to be precached, in addition to any entries that are + * generated as part of the build configuration. + */ + additionalManifestEntries?: Array; + /** + * Assets that match this will be assumed to be uniquely versioned via their + * URL, and exempted from the normal HTTP cache-busting that's done when + * populating the precache. While not required, it's recommended that if your + * existing build process already inserts a `[hash]` value into each filename, + * you provide a RegExp that will detect that, as it will reduce the bandwidth + * consumed when precaching. + */ + dontCacheBustURLsMatching?: RegExp; + /** + * One or more functions which will be applied sequentially against the + * generated manifest. If `modifyURLPrefix` or `dontCacheBustURLsMatching` are + * also specified, their corresponding transformations will be applied first. + */ + manifestTransforms?: Array; + /** + * This value can be used to determine the maximum size of files that will be + * precached. This prevents you from inadvertently precaching very large files + * that might have accidentally matched one of your patterns. + * @default 2097152 + */ + maximumFileSizeToCacheInBytes?: number; + /** + * An object mapping string prefixes to replacement string values. This can be + * used to, e.g., remove or add a path prefix from a manifest entry if your + * web hosting setup doesn't match your local filesystem setup. As an + * alternative with more flexibility, you can use the `manifestTransforms` + * option and provide a function that modifies the entries in the manifest + * using whatever logic you provide. + * + * Example usage: + * + * ``` + * // Replace a '/dist/' prefix with '/', and also prepend + * // '/static' to every URL. + * modifyURLPrefix: { + * '/dist/': '/', + * '': '/static', + * } + * ``` + */ + modifyURLPrefix?: { + [key: string]: string; + }; +} +export interface GeneratePartial { + /** + * The [targets](https://babeljs.io/docs/en/babel-preset-env#targets) to pass + * to `babel-preset-env` when transpiling the service worker bundle. + * @default ["chrome >= 56"] + */ + babelPresetEnvTargets?: Array; + /** + * An optional ID to be prepended to cache names. This is primarily useful for + * local development where multiple sites may be served from the same + * `http://localhost:port` origin. + */ + cacheId?: string | null; + /** + * Whether or not Workbox should attempt to identify and delete any precaches + * created by older, incompatible versions. + * @default false + */ + cleanupOutdatedCaches?: boolean; + /** + * Whether or not the service worker should [start controlling](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#clientsclaim) + * any existing clients as soon as it activates. + * @default false + */ + clientsClaim?: boolean; + /** + * If a navigation request for a URL ending in `/` fails to match a precached + * URL, this value will be appended to the URL and that will be checked for a + * precache match. This should be set to what your web server is using for its + * directory index. + */ + directoryIndex?: string | null; + /** + * @default false + */ + disableDevLogs?: boolean; + /** + * Any search parameter names that match against one of the RegExp in this + * array will be removed before looking for a precache match. This is useful + * if your users might request URLs that contain, for example, URL parameters + * used to track the source of the traffic. If not provided, the default value + * is `[/^utm_/, /^fbclid$/]`. + * + */ + ignoreURLParametersMatching?: Array; + /** + * A list of JavaScript files that should be passed to + * [`importScripts()`](https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts) + * inside the generated service worker file. This is useful when you want to + * let Workbox create your top-level service worker file, but want to include + * some additional code, such as a push event listener. + */ + importScripts?: Array; + /** + * Whether the runtime code for the Workbox library should be included in the + * top-level service worker, or split into a separate file that needs to be + * deployed alongside the service worker. Keeping the runtime separate means + * that users will not have to re-download the Workbox code each time your + * top-level service worker changes. + * @default false + */ + inlineWorkboxRuntime?: boolean; + /** + * If set to 'production', then an optimized service worker bundle that + * excludes debugging info will be produced. If not explicitly configured + * here, the `process.env.NODE_ENV` value will be used, and failing that, it + * will fall back to `'production'`. + * @default "production" + */ + mode?: string | null; + /** + * If specified, all + * [navigation requests](https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests) + * for URLs that aren't precached will be fulfilled with the HTML at the URL + * provided. You must pass in the URL of an HTML document that is listed in + * your precache manifest. This is meant to be used in a Single Page App + * scenario, in which you want all navigations to use common + * [App Shell HTML](https://developers.google.com/web/fundamentals/architecture/app-shell). + * @default null + */ + navigateFallback?: string | null; + /** + * An optional array of regular expressions that restricts which URLs the + * configured `navigateFallback` behavior applies to. This is useful if only a + * subset of your site's URLs should be treated as being part of a + * [Single Page App](https://en.wikipedia.org/wiki/Single-page_application). + * If both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are + * configured, the denylist takes precedent. + * + * *Note*: These RegExps may be evaluated against every destination URL during + * a navigation. Avoid using + * [complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077), + * or else your users may see delays when navigating your site. + */ + navigateFallbackAllowlist?: Array; + /** + * An optional array of regular expressions that restricts which URLs the + * configured `navigateFallback` behavior applies to. This is useful if only a + * subset of your site's URLs should be treated as being part of a + * [Single Page App](https://en.wikipedia.org/wiki/Single-page_application). + * If both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are + * configured, the denylist takes precedence. + * + * *Note*: These RegExps may be evaluated against every destination URL during + * a navigation. Avoid using + * [complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077), + * or else your users may see delays when navigating your site. + */ + navigateFallbackDenylist?: Array; + /** + * Whether or not to enable + * [navigation preload](https://developers.google.com/web/tools/workbox/modules/workbox-navigation-preload) + * in the generated service worker. When set to true, you must also use + * `runtimeCaching` to set up an appropriate response strategy that will match + * navigation requests, and make use of the preloaded response. + * @default false + */ + navigationPreload?: boolean; + /** + * Controls whether or not to include support for + * [offline Google Analytics](https://developers.google.com/web/tools/workbox/guides/enable-offline-analytics). + * When `true`, the call to `workbox-google-analytics`'s `initialize()` will + * be added to your generated service worker. When set to an `Object`, that + * object will be passed in to the `initialize()` call, allowing you to + * customize the behavior. + * @default false + */ + offlineGoogleAnalytics?: boolean | GoogleAnalyticsInitializeOptions; + /** + * When using Workbox's build tools to generate your service worker, you can + * specify one or more runtime caching configurations. These are then + * translated to {@link workbox-routing.registerRoute} calls using the match + * and handler configuration you define. + * + * For all of the options, see the {@link workbox-build.RuntimeCaching} + * documentation. The example below shows a typical configuration, with two + * runtime routes defined: + * + * @example + * runtimeCaching: [{ + * urlPattern: ({url}) => url.origin === 'https://api.example.com', + * handler: 'NetworkFirst', + * options: { + * cacheName: 'api-cache', + * }, + * }, { + * urlPattern: ({request}) => request.destination === 'image', + * handler: 'StaleWhileRevalidate', + * options: { + * cacheName: 'images-cache', + * expiration: { + * maxEntries: 10, + * }, + * }, + * }] + */ + runtimeCaching?: Array; + /** + * Whether to add an unconditional call to [`skipWaiting()`](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#skip_the_waiting_phase) + * to the generated service worker. If `false`, then a `message` listener will + * be added instead, allowing client pages to trigger `skipWaiting()` by + * calling `postMessage({type: 'SKIP_WAITING'})` on a waiting service worker. + * @default false + */ + skipWaiting?: boolean; + /** + * Whether to create a sourcemap for the generated service worker files. + * @default true + */ + sourcemap?: boolean; +} +export interface RequiredGlobDirectoryPartial { + /** + * The local directory you wish to match `globPatterns` against. The path is + * relative to the current directory. + */ + globDirectory: string; +} +export interface OptionalGlobDirectoryPartial { + /** + * The local directory you wish to match `globPatterns` against. The path is + * relative to the current directory. + */ + globDirectory?: string; +} +export interface GlobPartial { + /** + * Determines whether or not symlinks are followed when generating the + * precache manifest. For more information, see the definition of `follow` in + * the `glob` [documentation](https://github.com/isaacs/node-glob#options). + * @default true + */ + globFollow?: boolean; + /** + * A set of patterns matching files to always exclude when generating the + * precache manifest. For more information, see the definition of `ignore` in + * the `glob` [documentation](https://github.com/isaacs/node-glob#options). + * @default ["**\/node_modules\/**\/*"] + */ + globIgnores?: Array; + /** + * Files matching any of these patterns will be included in the precache + * manifest. For more information, see the + * [`glob` primer](https://github.com/isaacs/node-glob#glob-primer). + * @default ["**\/*.{js,wasm,css,html}"] + */ + globPatterns?: Array; + /** + * If a URL is rendered based on some server-side logic, its contents may + * depend on multiple files or on some other unique string value. The keys in + * this object are server-rendered URLs. If the values are an array of + * strings, they will be interpreted as `glob` patterns, and the contents of + * any files matching the patterns will be used to uniquely version the URL. + * If used with a single string, it will be interpreted as unique versioning + * information that you've generated for a given URL. + */ + templatedURLs?: { + [key: string]: string | Array; + }; +} +export interface InjectPartial { + /** + * The string to find inside of the `swSrc` file. Once found, it will be + * replaced by the generated precache manifest. + * @default "self.__WB_MANIFEST" + */ + injectionPoint?: string; + /** + * The path and filename of the service worker file that will be read during + * the build process, relative to the current working directory. + */ + swSrc: string; +} +export interface WebpackPartial { + /** + * One or more chunk names whose corresponding output files should be included + * in the precache manifest. + */ + chunks?: Array; + /** + * One or more specifiers used to exclude assets from the precache manifest. + * This is interpreted following + * [the same rules](https://webpack.js.org/configuration/module/#condition) + * as `webpack`'s standard `exclude` option. + * If not provided, the default value is `[/\.map$/, /^manifest.*\.js$]`. + */ + exclude?: Array boolean)>; + /** + * One or more chunk names whose corresponding output files should be excluded + * from the precache manifest. + */ + excludeChunks?: Array; + /** + * One or more specifiers used to include assets in the precache manifest. + * This is interpreted following + * [the same rules](https://webpack.js.org/configuration/module/#condition) + * as `webpack`'s standard `include` option. + */ + include?: Array boolean)>; + /** + * If set to 'production', then an optimized service worker bundle that + * excludes debugging info will be produced. If not explicitly configured + * here, the `mode` value configured in the current `webpack` compilation + * will be used. + */ + mode?: string | null; +} +export interface RequiredSWDestPartial { + /** + * The path and filename of the service worker file that will be created by + * the build process, relative to the current working directory. It must end + * in '.js'. + */ + swDest: string; +} +export interface WebpackGenerateSWPartial { + /** + * One or more names of webpack chunks. The content of those chunks will be + * included in the generated service worker, via a call to `importScripts()`. + */ + importScriptsViaChunks?: Array; + /** + * The asset name of the service worker file created by this plugin. + * @default "service-worker.js" + */ + swDest?: string; +} +export interface WebpackInjectManifestPartial { + /** + * When `true` (the default), the `swSrc` file will be compiled by webpack. + * When `false`, compilation will not occur (and `webpackCompilationPlugins` + * can't be used.) Set to `false` if you want to inject the manifest into, + * e.g., a JSON file. + * @default true + */ + compileSrc?: boolean; + /** + * The asset name of the service worker file that will be created by this + * plugin. If omitted, the name will be based on the `swSrc` name. + */ + swDest?: string; + /** + * Optional `webpack` plugins that will be used when compiling the `swSrc` + * input file. Only valid if `compileSrc` is `true`. + */ + webpackCompilationPlugins?: Array; +} +export type GenerateSWOptions = BasePartial & GlobPartial & GeneratePartial & RequiredSWDestPartial & OptionalGlobDirectoryPartial; +export type GetManifestOptions = BasePartial & GlobPartial & RequiredGlobDirectoryPartial; +export type InjectManifestOptions = BasePartial & GlobPartial & InjectPartial & RequiredSWDestPartial & RequiredGlobDirectoryPartial; +export type WebpackGenerateSWOptions = BasePartial & WebpackPartial & GeneratePartial & WebpackGenerateSWPartial; +export type WebpackInjectManifestOptions = BasePartial & WebpackPartial & InjectPartial & WebpackInjectManifestPartial; +export interface GetManifestResult { + count: number; + manifestEntries: Array; + size: number; + warnings: Array; +} +export type BuildResult = Omit & { + filePaths: Array; +}; +/** + * @private + */ +export interface FileDetails { + file: string; + hash: string; + size: number; +} +/** + * @private + */ +export type BuildType = 'dev' | 'prod'; +/** + * @private + */ +export interface WorkboxPackageJSON extends PackageJson { + workbox?: { + browserNamespace?: string; + packageType?: string; + prodOnly?: boolean; + }; +} diff --git a/node_modules/workbox-build/build/types.js b/node_modules/workbox-build/build/types.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/workbox-build/build/types.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/workbox-build/package.json b/node_modules/workbox-build/package.json new file mode 100644 index 0000000000000000000000000000000000000000..bfced709b485a71a2a40bb44f4976643883ae73e --- /dev/null +++ b/node_modules/workbox-build/package.json @@ -0,0 +1,73 @@ +{ + "name": "workbox-build", + "version": "7.4.1", + "description": "A module that integrates into your build process, helping you generate a manifest of local files that workbox-sw should precache.", + "keywords": [ + "workbox", + "workboxjs", + "service worker", + "caching", + "fetch requests", + "offline", + "file manifest" + ], + "engines": { + "node": ">=20.0.0" + }, + "author": "Google's Web DevRel Team and Google's Aurora Team", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/googlechrome/workbox.git" + }, + "bugs": "https://github.com/GoogleChrome/workbox/issues", + "homepage": "https://github.com/GoogleChrome/workbox", + "dependencies": { + "@apideck/better-ajv-errors": "^0.3.1", + "@babel/core": "^7.24.4", + "@babel/preset-env": "^7.11.0", + "@babel/runtime": "^7.11.2", + "@rollup/plugin-babel": "^6.1.0", + "@rollup/plugin-node-resolve": "^16.0.3", + "@rollup/plugin-replace": "^6.0.3", + "@rollup/plugin-terser": "^1.0.0", + "@trickfilm400/rollup-plugin-off-main-thread": "^3.0.0-pre1", + "ajv": "^8.6.0", + "common-tags": "^1.8.0", + "eta": "^4.5.1", + "fast-json-stable-stringify": "^2.1.0", + "fs-extra": "^9.0.1", + "glob": "^11.0.1", + "pretty-bytes": "^5.3.0", + "rollup": "^4.53.3", + "source-map": "^0.8.0-beta.0", + "stringify-object": "^3.3.0", + "strip-comments": "^2.0.1", + "tempy": "^0.6.0", + "upath": "^1.2.0", + "workbox-background-sync": "7.4.1", + "workbox-broadcast-update": "7.4.1", + "workbox-cacheable-response": "7.4.1", + "workbox-core": "7.4.1", + "workbox-expiration": "7.4.1", + "workbox-google-analytics": "7.4.1", + "workbox-navigation-preload": "7.4.1", + "workbox-precaching": "7.4.1", + "workbox-range-requests": "7.4.1", + "workbox-recipes": "7.4.1", + "workbox-routing": "7.4.1", + "workbox-strategies": "7.4.1", + "workbox-streams": "7.4.1", + "workbox-sw": "7.4.1", + "workbox-window": "7.4.1" + }, + "main": "build/index.js", + "workbox": { + "packageType": "node_ts" + }, + "types": "build/index.d.ts", + "devDependencies": { + "@types/node": "^20.14.8" + }, + "gitHead": "62b9d8ba8eb3c1a2ab8aac9d84c90cda7865d6a3" +} diff --git a/node_modules/workbox-build/src/_types.js b/node_modules/workbox-build/src/_types.js new file mode 100644 index 0000000000000000000000000000000000000000..3f06f90f4575c6d64eb2804a63b6a5ad341803b3 --- /dev/null +++ b/node_modules/workbox-build/src/_types.js @@ -0,0 +1,120 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import './_version.mjs'; + +/** + * @typedef {Object} ManifestEntry + * @property {string} url The URL to the asset in the manifest. + * @property {string} revision The revision details for the file. This should be + * either a hash generated based on the file contents, or `null` if there is + * versioning already included in the URL. + * @property {string} [integrity] Integrity metadata that will be used when + * making the network request for the URL. + * + * @memberof module:workbox-build + */ + +/** + * @typedef {Object} ManifestTransformResult + * @property {Array} manifest + * @property {Array|undefined} warnings + * + * @memberof module:workbox-build + */ + +/** + * @typedef {Object} RuntimeCachingEntry + * + * @property {string|module:workbox-routing~handlerCallback} handler + * Either the name of one of the [built-in strategy classes]{@link module:workbox-strategies}, + * or custom handler callback to use when the generated route matches. + * + * @property {string|RegExp|module:workbox-routing~matchCallback} urlPattern + * The value that will be passed to [`registerRoute()`]{@link module:workbox-routing.registerRoute}, + * used to determine whether the generated route will match a given request. + * + * @property {string} [method='GET'] The + * [HTTP method](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods) that + * will match the generated route. + * + * @property {Object} [options] + * + * @property {Object} [options.backgroundSync] + * + * @property {string} [options.backgroundSync.name] The `name` property to use + * when creating the + * [`BackgroundSyncPlugin`]{@link module:workbox-background-sync.BackgroundSyncPlugin}. + * + * @property {Object} [options.backgroundSync.options] The `options` property + * to use when creating the + * [`BackgroundSyncPlugin`]{@link module:workbox-background-sync.BackgroundSyncPlugin}. + * + * @property {Object} [options.broadcastUpdate] + * + * @property {string} [options.broadcastUpdate.channelName] The `channelName` + * property to use when creating the + * [`BroadcastCacheUpdatePlugin`]{@link module:workbox-broadcast-update.BroadcastUpdatePlugin}. + * + * @property {Object} [options.broadcastUpdate.options] The `options` property + * to use when creating the + * [`BroadcastCacheUpdatePlugin`]{@link module:workbox-broadcast-update.BroadcastUpdatePlugin}. + * + * @property {Object} [options.cacheableResponse] + * + * @property {Object} [options.cacheableResponse.headers] The `headers` property + * to use when creating the + * [`CacheableResponsePlugin`]{@link module:workbox-cacheable-response.CacheableResponsePlugin}. + * + * @property {Array} [options.cacheableResponse.statuses] `statuses` + * property to use when creating the + * [`CacheableResponsePlugin`]{@link module:workbox-cacheable-response.CacheableResponsePlugin}. + * + * @property {string} [options.cacheName] The `cacheName` to use when + * constructing one of the + * [Workbox strategy classes]{@link module:workbox-strategies}. + * + * @property {Object} [options.fetchOptions] The `fetchOptions` property value + * to use when constructing one of the + * [Workbox strategy classes]{@link module:workbox-strategies}. + * + * @property {Object} [options.expiration] + * + * @property {number} [options.expiration.maxAgeSeconds] The `maxAgeSeconds` + * property to use when creating the + * [`ExpirationPlugin`]{@link module:workbox-expiration.ExpirationPlugin}. + * + * @property {number} [options.expiration.maxEntries] The `maxEntries` + * property to use when creating the + * [`ExpirationPlugin`]{@link module:workbox-expiration.ExpirationPlugin}. + * + * @property {Object} [options.precacheFallback] + * + * @property {string} [options.precacheFallback.fallbackURL] The `fallbackURL` + * property to use when creating the + * [`PrecacheFallbackPlugin`]{@link module:workbox-precaching.PrecacheFallbackPlugin}. + * + * @property {boolean} [options.rangeRequests] Set to `true` to add the + * [`RangeRequestsPlugin`]{@link module:workbox-range-requests.RangeRequestsPlugin} + * for the strategy being configured. + * + * @property {Object} [options.matchOptions] The `matchOptions` property value + * to use when constructing one of the + * [Workbox strategy classes]{@link module:workbox-strategies}. + * + * @property {number} [options.networkTimeoutSeconds] The + * `networkTimeoutSeconds` property value to use when creating a + * [`NetworkFirst`]{@link module:workbox-strategies.NetworkFirst} strategy. + * + * @property {Array} [options.plugins] + * One or more [additional plugins](https://developers.google.com/web/tools/workbox/guides/using-plugins#custom_plugins) + * to apply to the handler. Useful when you want a plugin that doesn't have a + * "shortcut" configuration. + * + * @memberof module:workbox-build + */ diff --git a/node_modules/workbox-build/src/cdn-details.json b/node_modules/workbox-build/src/cdn-details.json new file mode 100644 index 0000000000000000000000000000000000000000..63d993022c1b414311161f9c9e58bdf21517848a --- /dev/null +++ b/node_modules/workbox-build/src/cdn-details.json @@ -0,0 +1,6 @@ +{ + "origin": "https://storage.googleapis.com", + "bucketName": "workbox-cdn", + "releasesDir": "releases", + "latestVersion": "7.4.1" +} diff --git a/node_modules/workbox-build/src/generate-sw.ts b/node_modules/workbox-build/src/generate-sw.ts new file mode 100644 index 0000000000000000000000000000000000000000..85aa576f6c11212649ec9b00523fb6d4b89eb00e --- /dev/null +++ b/node_modules/workbox-build/src/generate-sw.ts @@ -0,0 +1,117 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import upath from 'upath'; + +import {BuildResult, GetManifestOptions, GenerateSWOptions} from './types'; +import {getFileManifestEntries} from './lib/get-file-manifest-entries'; +import {rebasePath} from './lib/rebase-path'; +import {validateGenerateSWOptions} from './lib/validate-options'; +import {writeSWUsingDefaultTemplate} from './lib/write-sw-using-default-template'; + +/** + * This method creates a list of URLs to precache, referred to as a "precache + * manifest", based on the options you provide. + * + * It also takes in additional options that configures the service worker's + * behavior, like any `runtimeCaching` rules it should use. + * + * Based on the precache manifest and the additional configuration, it writes + * a ready-to-use service worker file to disk at `swDest`. + * + * ``` + * // The following lists some common options; see the rest of the documentation + * // for the full set of options and defaults. + * const {count, size, warnings} = await generateSW({ + * dontCacheBustURLsMatching: [new RegExp('...')], + * globDirectory: '...', + * globPatterns: ['...', '...'], + * maximumFileSizeToCacheInBytes: ..., + * navigateFallback: '...', + * runtimeCaching: [{ + * // Routing via a matchCallback function: + * urlPattern: ({request, url}) => ..., + * handler: '...', + * options: { + * cacheName: '...', + * expiration: { + * maxEntries: ..., + * }, + * }, + * }, { + * // Routing via a RegExp: + * urlPattern: new RegExp('...'), + * handler: '...', + * options: { + * cacheName: '...', + * plugins: [..., ...], + * }, + * }], + * skipWaiting: ..., + * swDest: '...', + * }); + * ``` + * + * @memberof workbox-build + */ +export async function generateSW( + config: GenerateSWOptions, +): Promise { + const options = validateGenerateSWOptions(config); + let entriesResult; + + if (options.globDirectory) { + // Make sure we leave swDest out of the precache manifest. + options.globIgnores!.push( + rebasePath({ + baseDirectory: options.globDirectory, + file: options.swDest, + }), + ); + + // If we create an extra external runtime file, ignore that, too. + // See https://rollupjs.org/guide/en/#outputchunkfilenames for naming. + if (!options.inlineWorkboxRuntime) { + const swDestDir = upath.dirname(options.swDest); + const workboxRuntimeFile = upath.join(swDestDir, 'workbox-*.js'); + options.globIgnores!.push( + rebasePath({ + baseDirectory: options.globDirectory, + file: workboxRuntimeFile, + }), + ); + } + + // We've previously asserted that options.globDirectory is set, so this + // should be a safe cast. + entriesResult = await getFileManifestEntries(options as GetManifestOptions); + } else { + entriesResult = { + count: 0, + manifestEntries: [], + size: 0, + warnings: [], + }; + } + + const filePaths = await writeSWUsingDefaultTemplate( + Object.assign( + { + manifestEntries: entriesResult.manifestEntries, + }, + options, + ), + ); + + return { + filePaths, + count: entriesResult.count, + size: entriesResult.size, + warnings: entriesResult.warnings, + }; +} diff --git a/node_modules/workbox-build/src/get-manifest.ts b/node_modules/workbox-build/src/get-manifest.ts new file mode 100644 index 0000000000000000000000000000000000000000..c5361418e4f16727f95549931bca01e099120fd2 --- /dev/null +++ b/node_modules/workbox-build/src/get-manifest.ts @@ -0,0 +1,37 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {getFileManifestEntries} from './lib/get-file-manifest-entries'; +import {GetManifestOptions, GetManifestResult} from './types'; +import {validateGetManifestOptions} from './lib/validate-options'; + +/** + * This method returns a list of URLs to precache, referred to as a "precache + * manifest", along with details about the number of entries and their size, + * based on the options you provide. + * + * ``` + * // The following lists some common options; see the rest of the documentation + * // for the full set of options and defaults. + * const {count, manifestEntries, size, warnings} = await getManifest({ + * dontCacheBustURLsMatching: [new RegExp('...')], + * globDirectory: '...', + * globPatterns: ['...', '...'], + * maximumFileSizeToCacheInBytes: ..., + * }); + * ``` + * + * @memberof workbox-build + */ +export async function getManifest( + config: GetManifestOptions, +): Promise { + const options = validateGetManifestOptions(config); + + return await getFileManifestEntries(options); +} diff --git a/node_modules/workbox-build/src/index.ts b/node_modules/workbox-build/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..f8325fce9e704af7230a0fe1d5b31ae7d09c66a1 --- /dev/null +++ b/node_modules/workbox-build/src/index.ts @@ -0,0 +1,26 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {copyWorkboxLibraries} from './lib/copy-workbox-libraries'; +import {getModuleURL} from './lib/cdn-utils'; +import {generateSW} from './generate-sw'; +import {getManifest} from './get-manifest'; +import {injectManifest} from './inject-manifest'; + +/** + * @module workbox-build + */ +export { + copyWorkboxLibraries, + generateSW, + getManifest, + getModuleURL, + injectManifest, +}; + +export * from './types'; diff --git a/node_modules/workbox-build/src/inject-manifest.ts b/node_modules/workbox-build/src/inject-manifest.ts new file mode 100644 index 0000000000000000000000000000000000000000..8795ddcaa77aea7b0356417e4bc4b19e2b3f860c --- /dev/null +++ b/node_modules/workbox-build/src/inject-manifest.ts @@ -0,0 +1,163 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {RawSourceMap} from 'source-map'; +import assert from 'assert'; +import fse from 'fs-extra'; +import stringify from 'fast-json-stable-stringify'; +import upath from 'upath'; + +import {BuildResult, InjectManifestOptions} from './types'; +import {errors} from './lib/errors'; +import {escapeRegExp} from './lib/escape-regexp'; +import {getFileManifestEntries} from './lib/get-file-manifest-entries'; +import {getSourceMapURL} from './lib/get-source-map-url'; +import {rebasePath} from './lib/rebase-path'; +import {replaceAndUpdateSourceMap} from './lib/replace-and-update-source-map'; +import {translateURLToSourcemapPaths} from './lib/translate-url-to-sourcemap-paths'; +import {validateInjectManifestOptions} from './lib/validate-options'; + +/** + * This method creates a list of URLs to precache, referred to as a "precache + * manifest", based on the options you provide. + * + * The manifest is injected into the `swSrc` file, and the placeholder string + * `injectionPoint` determines where in the file the manifest should go. + * + * The final service worker file, with the manifest injected, is written to + * disk at `swDest`. + * + * This method will not compile or bundle your `swSrc` file; it just handles + * injecting the manifest. + * + * ``` + * // The following lists some common options; see the rest of the documentation + * // for the full set of options and defaults. + * const {count, size, warnings} = await injectManifest({ + * dontCacheBustURLsMatching: [new RegExp('...')], + * globDirectory: '...', + * globPatterns: ['...', '...'], + * maximumFileSizeToCacheInBytes: ..., + * swDest: '...', + * swSrc: '...', + * }); + * ``` + * + * @memberof workbox-build + */ +export async function injectManifest( + config: InjectManifestOptions, +): Promise { + const options = validateInjectManifestOptions(config); + + // Make sure we leave swSrc and swDest out of the precache manifest. + for (const file of [options.swSrc, options.swDest]) { + options.globIgnores!.push( + rebasePath({ + file, + baseDirectory: options.globDirectory, + }), + ); + } + + const globalRegexp = new RegExp(escapeRegExp(options.injectionPoint!), 'g'); + + const {count, size, manifestEntries, warnings} = await getFileManifestEntries( + options, + ); + let swFileContents: string; + try { + swFileContents = await fse.readFile(options.swSrc, 'utf8'); + } catch (error) { + throw new Error( + `${errors['invalid-sw-src']} ${ + error instanceof Error && error.message ? error.message : '' + }`, + ); + } + + const injectionResults = swFileContents.match(globalRegexp); + // See https://github.com/GoogleChrome/workbox/issues/2230 + const injectionPoint = options.injectionPoint ? options.injectionPoint : ''; + if (!injectionResults) { + if (upath.resolve(options.swSrc) === upath.resolve(options.swDest)) { + throw new Error(`${errors['same-src-and-dest']} ${injectionPoint}`); + } + throw new Error(`${errors['injection-point-not-found']} ${injectionPoint}`); + } + + assert( + injectionResults.length === 1, + `${errors['multiple-injection-points']} ${injectionPoint}`, + ); + + const manifestString = stringify(manifestEntries); + const filesToWrite: {[key: string]: string} = {}; + + const url = getSourceMapURL(swFileContents); + // See https://github.com/GoogleChrome/workbox/issues/2957 + const {destPath, srcPath, warning} = translateURLToSourcemapPaths( + url, + options.swSrc, + options.swDest, + ); + if (warning) { + warnings.push(warning); + } + + // If our swSrc file contains a sourcemap, we would invalidate that + // mapping if we just replaced injectionPoint with the stringified manifest. + // Instead, we need to update the swDest contents as well as the sourcemap + // (assuming it's a real file, not a data: URL) at the same time. + // See https://github.com/GoogleChrome/workbox/issues/2235 + // and https://github.com/GoogleChrome/workbox/issues/2648 + if (srcPath && destPath) { + const originalMap = (await fse.readJSON(srcPath, { + encoding: 'utf8', + })) as RawSourceMap; + + const {map, source} = await replaceAndUpdateSourceMap({ + originalMap, + jsFilename: upath.basename(options.swDest), + originalSource: swFileContents, + replaceString: manifestString, + searchString: options.injectionPoint!, + }); + + filesToWrite[options.swDest] = source; + filesToWrite[destPath] = map; + } else { + // If there's no sourcemap associated with swSrc, a simple string + // replacement will suffice. + filesToWrite[options.swDest] = swFileContents.replace( + globalRegexp, + manifestString, + ); + } + + for (const [file, contents] of Object.entries(filesToWrite)) { + try { + await fse.mkdirp(upath.dirname(file)); + } catch (error: unknown) { + throw new Error( + errors['unable-to-make-sw-directory'] + + ` '${error instanceof Error && error.message ? error.message : ''}'`, + ); + } + + await fse.writeFile(file, contents); + } + + return { + count, + size, + warnings, + // Use upath.resolve() to make all the paths absolute. + filePaths: Object.keys(filesToWrite).map((f) => upath.resolve(f)), + }; +} diff --git a/node_modules/workbox-build/src/lib/additional-manifest-entries-transform.ts b/node_modules/workbox-build/src/lib/additional-manifest-entries-transform.ts new file mode 100644 index 0000000000000000000000000000000000000000..13fc1a687a1602f00db1a0b4399bcf633cccd352 --- /dev/null +++ b/node_modules/workbox-build/src/lib/additional-manifest-entries-transform.ts @@ -0,0 +1,58 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {errors} from './errors'; +import {ManifestEntry} from '../types'; + +type AdditionalManifestEntriesTransform = { + (manifest: Array): { + manifest: Array; + warnings: string[]; + }; +}; + +export function additionalManifestEntriesTransform( + additionalManifestEntries: Array, +): AdditionalManifestEntriesTransform { + return (manifest: Array) => { + const warnings: Array = []; + const stringEntries = new Set(); + + for (const additionalEntry of additionalManifestEntries) { + // Warn about either a string or an object that lacks a revision property. + // (An object with a revision property set to null is okay.) + if (typeof additionalEntry === 'string') { + stringEntries.add(additionalEntry); + manifest.push({ + revision: null, + size: 0, + url: additionalEntry, + }); + } else { + if (additionalEntry && additionalEntry.revision === undefined) { + stringEntries.add(additionalEntry.url); + } + manifest.push(Object.assign({size: 0}, additionalEntry)); + } + } + + if (stringEntries.size > 0) { + let urls = '\n'; + for (const stringEntry of stringEntries) { + urls += ` - ${stringEntry}\n`; + } + + warnings.push(errors['string-entry-warning'] + urls); + } + + return { + manifest, + warnings, + }; + }; +} diff --git a/node_modules/workbox-build/src/lib/bundle.ts b/node_modules/workbox-build/src/lib/bundle.ts new file mode 100644 index 0000000000000000000000000000000000000000..82f50d0ca01efc06dcb476ecc59f26482c2d6e05 --- /dev/null +++ b/node_modules/workbox-build/src/lib/bundle.ts @@ -0,0 +1,167 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {babel} from '@rollup/plugin-babel'; +import {nodeResolve} from '@rollup/plugin-node-resolve'; +import {rollup, Plugin} from 'rollup'; +import terser from '@rollup/plugin-terser'; +import {writeFile} from 'fs-extra'; +import omt from '@trickfilm400/rollup-plugin-off-main-thread'; +import presetEnv from '@babel/preset-env'; +import replace from '@rollup/plugin-replace'; +import tempy from 'tempy'; +import upath from 'upath'; + +import {GeneratePartial, RequiredSWDestPartial} from '../types'; + +interface NameAndContents { + contents: string | Uint8Array; + name: string; +} + +export async function bundle({ + babelPresetEnvTargets, + inlineWorkboxRuntime, + mode, + sourcemap, + swDest, + unbundledCode, +}: Omit & + RequiredSWDestPartial & {unbundledCode: string}): Promise< + Array +> { + // We need to write this to the "real" file system, as Rollup won't read from + // a custom file system. + const {dir, base} = upath.parse(swDest); + + const temporaryFile = tempy.file({name: base}); + await writeFile(temporaryFile, unbundledCode); + + const plugins = [ + nodeResolve(), + replace({ + // See https://github.com/GoogleChrome/workbox/issues/2769 + 'preventAssignment': true, + 'process.env.NODE_ENV': JSON.stringify(mode), + }), + babel({ + babelHelpers: 'bundled', + // Disable the logic that checks for local Babel config files: + // https://github.com/GoogleChrome/workbox/issues/2111 + babelrc: false, + configFile: false, + presets: [ + [ + presetEnv, + { + targets: { + browsers: babelPresetEnvTargets, + }, + loose: true, + }, + ], + ], + }), + ]; + + if (mode === 'production') { + plugins.push( + terser({ + mangle: { + toplevel: true, + properties: { + regex: /(^_|_$)/, + }, + }, + }), + ); + } + + const rollupConfig: { + input: string; + plugins: Array; + } = { + plugins, + input: temporaryFile, + }; + + // Rollup will inline the runtime by default. If we don't want that, we need + // to add in some additional config. + if (!inlineWorkboxRuntime) { + // No lint for omt(), library has no types. + // eslint-disable-next-line @typescript-eslint/no-unsafe-call + rollupConfig.plugins.unshift(omt()); + } + + const bundle = await rollup(rollupConfig); + + const outputOptions: { + sourcemap?: boolean; + format: 'es' | 'amd'; + manualChunks?: (id: string) => string | undefined; + chunkFileNames?: string; + hashCharacters?: 'base64' | 'hex'; + } = { + sourcemap, + // Using an external Workbox runtime requires 'amd'. + format: inlineWorkboxRuntime ? 'es' : 'amd', + }; + + if (!inlineWorkboxRuntime) { + outputOptions.manualChunks = (id) => { + return id.includes('workbox') ? 'workbox' : undefined; + }; + outputOptions.hashCharacters = 'hex'; + } + + const {output} = await bundle.generate(outputOptions); + const files: Array = []; + for (const chunkOrAsset of output) { + if (chunkOrAsset.type === 'asset') { + if (!files.some((f) => f.name === chunkOrAsset.fileName)) { + files.push({ + name: chunkOrAsset.fileName, + contents: chunkOrAsset.source, + }); + } + } else { + let code = chunkOrAsset.code; + + if (chunkOrAsset.map) { + const sourceMapFile = chunkOrAsset.fileName + '.map'; + code += `//# sourceMappingURL=${sourceMapFile}\n`; + if (!files.some((f) => f.name === sourceMapFile)) { + files.push({ + name: sourceMapFile, + contents: chunkOrAsset.map.toString(), + }); + } + } + + if (!files.some((f) => f.name === chunkOrAsset.fileName)) { + files.push({ + name: chunkOrAsset.fileName, + contents: code, + }); + } + } + } + + // Make sure that if there was a directory portion included in swDest, it's + // preprended to all of the generated files. + return files.map((file) => { + file.name = upath.format({ + dir, + base: file.name, + ext: '', + name: '', + root: '', + }); + return file; + }); +} diff --git a/node_modules/workbox-build/src/lib/cdn-utils.ts b/node_modules/workbox-build/src/lib/cdn-utils.ts new file mode 100644 index 0000000000000000000000000000000000000000..b9b5a53b0f07008a3cec76079572453c0e0feb6d --- /dev/null +++ b/node_modules/workbox-build/src/lib/cdn-utils.ts @@ -0,0 +1,37 @@ +/* + Copyright 2021 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {ok} from 'assert'; + +import {BuildType, WorkboxPackageJSON} from '../types'; +import {errors} from './errors'; +import * as cdn from '../cdn-details.json'; + +function getVersionedURL(): string { + return `${getCDNPrefix()}/${cdn.latestVersion}`; +} + +function getCDNPrefix() { + return `${cdn.origin}/${cdn.bucketName}/${cdn.releasesDir}`; +} + +export function getModuleURL(moduleName: string, buildType: BuildType): string { + ok(moduleName, errors['no-module-name']); + + if (buildType) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const pkgJson: WorkboxPackageJSON = require(`${moduleName}/package.json`); + if (buildType === 'dev' && pkgJson.workbox && pkgJson.workbox.prodOnly) { + // This is not due to a public-facing exception, so just throw an Error(), + // without creating an entry in errors.js. + throw Error(`The 'dev' build of ${moduleName} is not available.`); + } + return `${getVersionedURL()}/${moduleName}.${buildType.slice(0, 4)}.js`; + } + return `${getVersionedURL()}/${moduleName}.js`; +} diff --git a/node_modules/workbox-build/src/lib/copy-workbox-libraries.ts b/node_modules/workbox-build/src/lib/copy-workbox-libraries.ts new file mode 100644 index 0000000000000000000000000000000000000000..f0dbc2f57e7a268a1da636659da10dbfa7d89250 --- /dev/null +++ b/node_modules/workbox-build/src/lib/copy-workbox-libraries.ts @@ -0,0 +1,84 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import fse from 'fs-extra'; +import upath from 'upath'; + +import {WorkboxPackageJSON} from '../types'; +import {errors} from './errors'; + +// Used to filter the libraries to copy based on our package.json dependencies. +const WORKBOX_PREFIX = 'workbox-'; + +// The directory within each package containing the final bundles. +const BUILD_DIR = 'build'; + +/** + * This copies over a set of runtime libraries used by Workbox into a + * local directory, which should be deployed alongside your service worker file. + * + * As an alternative to deploying these local copies, you could instead use + * Workbox from its official CDN URL. + * + * This method is exposed for the benefit of developers using + * {@link workbox-build.injectManifest} who would + * prefer not to use the CDN copies of Workbox. Developers using + * {@link workbox-build.generateSW} don't need to + * explicitly call this method. + * + * @param {string} destDirectory The path to the parent directory under which + * the new directory of libraries will be created. + * @return {Promise} The name of the newly created directory. + * + * @alias workbox-build.copyWorkboxLibraries + */ +export async function copyWorkboxLibraries( + destDirectory: string, +): Promise { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const thisPkg: WorkboxPackageJSON = require('../../package.json'); + // Use the version string from workbox-build in the name of the parent + // directory. This should be safe, because lerna will bump workbox-build's + // pkg.version whenever one of the dependent libraries gets bumped, and we + // care about versioning the dependent libraries. + const workboxDirectoryName = `workbox-v${ + thisPkg.version ? thisPkg.version : '' + }`; + const workboxDirectoryPath = upath.join(destDirectory, workboxDirectoryName); + await fse.ensureDir(workboxDirectoryPath); + + const copyPromises: Array> = []; + const librariesToCopy = Object.keys(thisPkg.dependencies || {}).filter( + (dependency) => dependency.startsWith(WORKBOX_PREFIX), + ); + + for (const library of librariesToCopy) { + // Get the path to the package on the user's filesystem by require-ing + // the package's `package.json` file via the node resolution algorithm. + const libraryPath = upath.dirname( + require.resolve(`${library}/package.json`), + ); + + const buildPath = upath.join(libraryPath, BUILD_DIR); + + // fse.copy() copies all the files in a directory, not the directory itself. + // See https://github.com/jprichardson/node-fs-extra/blob/master/docs/copy.md#copysrc-dest-options-callback + copyPromises.push(fse.copy(buildPath, workboxDirectoryPath)); + } + + try { + await Promise.all(copyPromises); + return workboxDirectoryName; + } catch (error) { + throw Error( + `${errors['unable-to-copy-workbox-libraries']} ${ + error instanceof Error ? error.toString() : '' + }`, + ); + } +} diff --git a/node_modules/workbox-build/src/lib/errors.ts b/node_modules/workbox-build/src/lib/errors.ts new file mode 100644 index 0000000000000000000000000000000000000000..bf24ca39287fc4bd440e6638b602752eb46fd79c --- /dev/null +++ b/node_modules/workbox-build/src/lib/errors.ts @@ -0,0 +1,124 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {oneLine as ol} from 'common-tags'; + +export const errors = { + 'unable-to-get-rootdir': `Unable to get the root directory of your web app.`, + 'no-extension': ol`Unable to detect a usable extension for a file in your web + app directory.`, + 'invalid-file-manifest-name': ol`The File Manifest Name must have at least one + character.`, + 'unable-to-get-file-manifest-name': 'Unable to get a file manifest name.', + 'invalid-sw-dest': `The 'swDest' value must be a valid path.`, + 'unable-to-get-sw-name': 'Unable to get a service worker file name.', + 'unable-to-get-save-config': ol`An error occurred when asking to save details + in a config file.`, + 'unable-to-get-file-hash': ol`An error occurred when attempting to create a + file hash.`, + 'unable-to-get-file-size': ol`An error occurred when attempting to get a file + size.`, + 'unable-to-glob-files': 'An error occurred when globbing for files.', + 'unable-to-make-manifest-directory': ol`Unable to make output directory for + file manifest.`, + 'read-manifest-template-failure': 'Unable to read template for file manifest', + 'populating-manifest-tmpl-failed': ol`An error occurred when populating the + file manifest template.`, + 'manifest-file-write-failure': 'Unable to write the file manifest.', + 'unable-to-make-sw-directory': ol`Unable to make the directories to output + the service worker path.`, + 'read-sw-template-failure': ol`Unable to read the service worker template + file.`, + 'sw-write-failure': 'Unable to write the service worker file.', + 'sw-write-failure-directory': ol`Unable to write the service worker file; + 'swDest' should be a full path to the file, not a path to a directory.`, + 'unable-to-copy-workbox-libraries': ol`One or more of the Workbox libraries + could not be copied over to the destination directory: `, + 'invalid-generate-sw-input': ol`The input to generateSW() must be an object.`, + 'invalid-glob-directory': ol`The supplied globDirectory must be a path as a + string.`, + 'invalid-dont-cache-bust': ol`The supplied 'dontCacheBustURLsMatching' + parameter must be a RegExp.`, + 'invalid-exclude-files': 'The excluded files should be an array of strings.', + 'invalid-get-manifest-entries-input': ol`The input to + 'getFileManifestEntries()' must be an object.`, + 'invalid-manifest-path': ol`The supplied manifest path is not a string with + at least one character.`, + 'invalid-manifest-entries': ol`The manifest entries must be an array of + strings or JavaScript objects containing a url parameter.`, + 'invalid-manifest-format': ol`The value of the 'format' option passed to + generateFileManifest() must be either 'iife' (the default) or 'es'.`, + 'invalid-static-file-globs': ol`The 'globPatterns' value must be an array + of strings.`, + 'invalid-templated-urls': ol`The 'templatedURLs' value should be an object + that maps URLs to either a string, or to an array of glob patterns.`, + 'templated-url-matches-glob': ol`One of the 'templatedURLs' URLs is already + being tracked via 'globPatterns': `, + 'invalid-glob-ignores': ol`The 'globIgnores' parameter must be an array of + glob pattern strings.`, + 'manifest-entry-bad-url': ol`The generated manifest contains an entry without + a URL string. This is likely an error with workbox-build.`, + 'modify-url-prefix-bad-prefixes': ol`The 'modifyURLPrefix' parameter must be + an object with string key value pairs.`, + 'invalid-inject-manifest-arg': ol`The input to 'injectManifest()' must be an + object.`, + 'injection-point-not-found': ol`Unable to find a place to inject the manifest. + Please ensure that your service worker file contains the following: `, + 'multiple-injection-points': ol`Please ensure that your 'swSrc' file contains + only one match for the following: `, + 'populating-sw-tmpl-failed': ol`Unable to generate service worker from + template.`, + 'useless-glob-pattern': ol`One of the glob patterns doesn't match any files. + Please remove or fix the following: `, + 'bad-template-urls-asset': ol`There was an issue using one of the provided + 'templatedURLs'.`, + 'invalid-runtime-caching': ol`The 'runtimeCaching' parameter must an an + array of objects with at least a 'urlPattern' and 'handler'.`, + 'static-file-globs-deprecated': ol`'staticFileGlobs' is deprecated. + Please use 'globPatterns' instead.`, + 'dynamic-url-deprecated': ol`'dynamicURLToDependencies' is deprecated. + Please use 'templatedURLs' instead.`, + 'urlPattern-is-required': ol`The 'urlPattern' option is required when using + 'runtimeCaching'.`, + 'handler-is-required': ol`The 'handler' option is required when using + runtimeCaching.`, + 'invalid-generate-file-manifest-arg': ol`The input to generateFileManifest() + must be an Object.`, + 'invalid-sw-src': `The 'swSrc' file can't be read.`, + 'same-src-and-dest': ol`Unable to find a place to inject the manifest. This is + likely because swSrc and swDest are configured to the same file. + Please ensure that your swSrc file contains the following:`, + 'only-regexp-routes-supported': ol`Please use a regular expression object as + the urlPattern parameter. (Express-style routes are not currently + supported.)`, + 'bad-runtime-caching-config': ol`An unknown configuration option was used + with runtimeCaching: `, + 'invalid-network-timeout-seconds': ol`When using networkTimeoutSeconds, you + must set the handler to 'NetworkFirst'.`, + 'no-module-name': ol`You must provide a moduleName parameter when calling + getModuleURL().`, + 'bad-manifest-transforms-return-value': ol`The return value from a + manifestTransform should be an object with 'manifest' and optionally + 'warnings' properties.`, + 'string-entry-warning': ol`Some items were passed to additionalManifestEntries + without revisioning info. This is generally NOT safe. Learn more at + https://bit.ly/wb-precache.`, + 'no-manifest-entries-or-runtime-caching': ol`Couldn't find configuration for + either precaching or runtime caching. Please ensure that the various glob + options are set to match one or more files, and/or configure the + runtimeCaching option.`, + 'cant-find-sourcemap': ol`The swSrc file refers to a sourcemap that can't be + opened:`, + 'nav-preload-runtime-caching': ol`When using navigationPreload, you must also + configure a runtimeCaching route that will use the preloaded response.`, + 'cache-name-required': ol`When using cache expiration, you must also + configure a custom cacheName.`, + 'manifest-transforms': ol`When using manifestTransforms, you must provide + an array of functions.`, + 'invalid-handler-string': ol`The handler name provided is not valid: `, +}; diff --git a/node_modules/workbox-build/src/lib/escape-regexp.ts b/node_modules/workbox-build/src/lib/escape-regexp.ts new file mode 100644 index 0000000000000000000000000000000000000000..139b12975b7589c2e1c29434be2828e839b1ae63 --- /dev/null +++ b/node_modules/workbox-build/src/lib/escape-regexp.ts @@ -0,0 +1,12 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions +export function escapeRegExp(str: string): string { + return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} diff --git a/node_modules/workbox-build/src/lib/get-composite-details.ts b/node_modules/workbox-build/src/lib/get-composite-details.ts new file mode 100644 index 0000000000000000000000000000000000000000..011ddcc75022b99f322c32629288a4b9c04f4153 --- /dev/null +++ b/node_modules/workbox-build/src/lib/get-composite-details.ts @@ -0,0 +1,34 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import crypto from 'crypto'; + +import {FileDetails} from '../types'; + +export function getCompositeDetails( + compositeURL: string, + dependencyDetails: Array, +): FileDetails { + let totalSize = 0; + let compositeHash = ''; + + for (const fileDetails of dependencyDetails) { + totalSize += fileDetails.size; + compositeHash += fileDetails.hash; + } + + const md5 = crypto.createHash('md5'); + md5.update(compositeHash); + const hashOfHashes = md5.digest('hex'); + + return { + file: compositeURL, + hash: hashOfHashes, + size: totalSize, + }; +} diff --git a/node_modules/workbox-build/src/lib/get-file-details.ts b/node_modules/workbox-build/src/lib/get-file-details.ts new file mode 100644 index 0000000000000000000000000000000000000000..c81695ab3bcdaaea5fb14e4afb55ae0a71ed3641 --- /dev/null +++ b/node_modules/workbox-build/src/lib/get-file-details.ts @@ -0,0 +1,75 @@ +/* + Copyright 2021 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {globSync} from 'glob'; +import upath from 'upath'; + +import {errors} from './errors'; +import {getFileSize} from './get-file-size'; +import {getFileHash} from './get-file-hash'; + +import {GlobPartial} from '../types'; + +interface FileDetails { + file: string; + hash: string; + size: number; +} + +export function getFileDetails({ + globDirectory, + globFollow, + globIgnores, + globPattern, +}: Omit & { + // This will only be called when globDirectory is not undefined. + globDirectory: string; + globPattern: string; +}): { + globbedFileDetails: Array; + warning: string; +} { + let globbedFiles: Array; + let warning = ''; + + try { + globbedFiles = globSync(globPattern, { + cwd: globDirectory, + follow: globFollow, + ignore: globIgnores, + }); + } catch (err) { + throw new Error( + errors['unable-to-glob-files'] + + ` '${err instanceof Error && err.message ? err.message : ''}'`, + ); + } + + if (globbedFiles.length === 0) { + warning = + errors['useless-glob-pattern'] + + ' ' + + JSON.stringify({globDirectory, globPattern, globIgnores}, null, 2); + } + + const globbedFileDetails: Array = []; + for (const file of globbedFiles) { + const fullPath = upath.join(globDirectory, file); + const fileSize = getFileSize(fullPath); + if (fileSize !== null) { + const fileHash = getFileHash(fullPath); + globbedFileDetails.push({ + file: `${upath.relative(globDirectory, fullPath)}`, + hash: fileHash, + size: fileSize, + }); + } + } + + return {globbedFileDetails, warning}; +} diff --git a/node_modules/workbox-build/src/lib/get-file-hash.ts b/node_modules/workbox-build/src/lib/get-file-hash.ts new file mode 100644 index 0000000000000000000000000000000000000000..91c15ec57b5f76a1580ab6a8de81290a1e550081 --- /dev/null +++ b/node_modules/workbox-build/src/lib/get-file-hash.ts @@ -0,0 +1,24 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import fse from 'fs-extra'; + +import {getStringHash} from './get-string-hash'; +import {errors} from './errors'; + +export function getFileHash(file: string): string { + try { + const buffer = fse.readFileSync(file); + return getStringHash(buffer); + } catch (err) { + throw new Error( + errors['unable-to-get-file-hash'] + + ` '${err instanceof Error && err.message ? err.message : ''}'`, + ); + } +} diff --git a/node_modules/workbox-build/src/lib/get-file-manifest-entries.ts b/node_modules/workbox-build/src/lib/get-file-manifest-entries.ts new file mode 100644 index 0000000000000000000000000000000000000000..680ac0c3f120a58c5afaad66d347ecc2218adf68 --- /dev/null +++ b/node_modules/workbox-build/src/lib/get-file-manifest-entries.ts @@ -0,0 +1,118 @@ +/* + Copyright 2021 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import assert from 'assert'; + +import {GetManifestResult, FileDetails, GetManifestOptions} from '../types'; +import {errors} from './errors'; +import {getCompositeDetails} from './get-composite-details'; +import {getFileDetails} from './get-file-details'; +import {getStringDetails} from './get-string-details'; +import {transformManifest} from './transform-manifest'; + +export async function getFileManifestEntries({ + additionalManifestEntries, + dontCacheBustURLsMatching, + globDirectory, + globFollow, + globIgnores, + globPatterns = [], + manifestTransforms, + maximumFileSizeToCacheInBytes, + modifyURLPrefix, + templatedURLs, +}: GetManifestOptions): Promise { + const warnings: Array = []; + const allFileDetails = new Map(); + + try { + for (const globPattern of globPatterns) { + const {globbedFileDetails, warning} = getFileDetails({ + globDirectory, + globFollow, + globIgnores, + globPattern, + }); + + if (warning) { + warnings.push(warning); + } + + for (const details of globbedFileDetails) { + if (details && !allFileDetails.has(details.file)) { + allFileDetails.set(details.file, details); + } + } + } + } catch (error) { + // If there's an exception thrown while globbing, then report + // it back as a warning, and don't consider it fatal. + if (error instanceof Error && error.message) { + warnings.push(error.message); + } + } + + if (templatedURLs) { + for (const url of Object.keys(templatedURLs)) { + assert(!allFileDetails.has(url), errors['templated-url-matches-glob']); + + const dependencies = templatedURLs[url]; + if (Array.isArray(dependencies)) { + const details = dependencies.reduce>( + (previous, globPattern) => { + try { + const {globbedFileDetails, warning} = getFileDetails({ + globDirectory, + globFollow, + globIgnores, + globPattern, + }); + + if (warning) { + warnings.push(warning); + } + + return previous.concat(globbedFileDetails); + } catch (error) { + const debugObj: {[key: string]: Array} = {}; + debugObj[url] = dependencies; + throw new Error( + `${errors['bad-template-urls-asset']} ` + + `'${globPattern}' from '${JSON.stringify(debugObj)}':\n` + + `${error instanceof Error ? error.toString() : ''}`, + ); + } + }, + [], + ); + if (details.length === 0) { + throw new Error( + `${errors['bad-template-urls-asset']} The glob ` + + `pattern '${dependencies.toString()}' did not match anything.`, + ); + } + allFileDetails.set(url, getCompositeDetails(url, details)); + } else if (typeof dependencies === 'string') { + allFileDetails.set(url, getStringDetails(url, dependencies)); + } + } + } + + const transformedManifest = await transformManifest({ + additionalManifestEntries, + dontCacheBustURLsMatching, + manifestTransforms, + maximumFileSizeToCacheInBytes, + modifyURLPrefix, + fileDetails: Array.from(allFileDetails.values()), + }); + + transformedManifest.warnings.push(...warnings); + + return transformedManifest; +} diff --git a/node_modules/workbox-build/src/lib/get-file-size.ts b/node_modules/workbox-build/src/lib/get-file-size.ts new file mode 100644 index 0000000000000000000000000000000000000000..4368043debe833345a714476191354d097d0f217 --- /dev/null +++ b/node_modules/workbox-build/src/lib/get-file-size.ts @@ -0,0 +1,26 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import fse from 'fs-extra'; + +import {errors} from './errors'; + +export function getFileSize(file: string): number | null { + try { + const stat = fse.statSync(file); + if (!stat.isFile()) { + return null; + } + return stat.size; + } catch (err) { + throw new Error( + errors['unable-to-get-file-size'] + + ` '${err instanceof Error && err.message ? err.message : ''}'`, + ); + } +} diff --git a/node_modules/workbox-build/src/lib/get-source-map-url.ts b/node_modules/workbox-build/src/lib/get-source-map-url.ts new file mode 100644 index 0000000000000000000000000000000000000000..6b0aee97bbab17600a79f32af42c9fc51d295a7c --- /dev/null +++ b/node_modules/workbox-build/src/lib/get-source-map-url.ts @@ -0,0 +1,32 @@ +/* + Copyright 2022 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +// Adapted from https://github.com/lydell/source-map-url/blob/master/source-map-url.js +// See https://github.com/GoogleChrome/workbox/issues/3019 +const innerRegex = /[#@] sourceMappingURL=([^\s'"]*)/; +const regex = RegExp( + '(?:' + + '/\\*' + + '(?:\\s*\r?\n(?://)?)?' + + '(?:' + + innerRegex.source + + ')' + + '\\s*' + + '\\*/' + + '|' + + '//(?:' + + innerRegex.source + + ')' + + ')' + + '\\s*', +); + +export function getSourceMapURL(srcContents: string): string | null { + const match = srcContents.match(regex); + return match ? match[1] || match[2] || '' : null; +} diff --git a/node_modules/workbox-build/src/lib/get-string-details.ts b/node_modules/workbox-build/src/lib/get-string-details.ts new file mode 100644 index 0000000000000000000000000000000000000000..141863e8432b84b11a15ddee58937ecdf5b6ca1e --- /dev/null +++ b/node_modules/workbox-build/src/lib/get-string-details.ts @@ -0,0 +1,18 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {FileDetails} from '../types'; +import {getStringHash} from './get-string-hash'; + +export function getStringDetails(url: string, str: string): FileDetails { + return { + file: url, + hash: getStringHash(str), + size: str.length, + }; +} diff --git a/node_modules/workbox-build/src/lib/get-string-hash.ts b/node_modules/workbox-build/src/lib/get-string-hash.ts new file mode 100644 index 0000000000000000000000000000000000000000..5ce1a5c1ca28c2d0d121213b249abc1373aac9eb --- /dev/null +++ b/node_modules/workbox-build/src/lib/get-string-hash.ts @@ -0,0 +1,15 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import crypto from 'crypto'; + +export function getStringHash(input: crypto.BinaryLike): string { + const md5 = crypto.createHash('md5'); + md5.update(input); + return md5.digest('hex'); +} diff --git a/node_modules/workbox-build/src/lib/maximum-size-transform.ts b/node_modules/workbox-build/src/lib/maximum-size-transform.ts new file mode 100644 index 0000000000000000000000000000000000000000..03a7da4e8a1e1a364d9acba3b5d6f7eb59dd470d --- /dev/null +++ b/node_modules/workbox-build/src/lib/maximum-size-transform.ts @@ -0,0 +1,33 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import prettyBytes from 'pretty-bytes'; + +import {ManifestTransform} from '../types'; + +export function maximumSizeTransform( + maximumFileSizeToCacheInBytes: number, +): ManifestTransform { + return (originalManifest) => { + const warnings: Array = []; + const manifest = originalManifest.filter((entry) => { + if (entry.size <= maximumFileSizeToCacheInBytes) { + return true; + } + + warnings.push( + `${entry.url} is ${prettyBytes(entry.size)}, and won't ` + + `be precached. Configure maximumFileSizeToCacheInBytes to change ` + + `this limit.`, + ); + return false; + }); + + return {manifest, warnings}; + }; +} diff --git a/node_modules/workbox-build/src/lib/modify-url-prefix-transform.ts b/node_modules/workbox-build/src/lib/modify-url-prefix-transform.ts new file mode 100644 index 0000000000000000000000000000000000000000..25b710de83198baafa7483c944c62a663ff743f9 --- /dev/null +++ b/node_modules/workbox-build/src/lib/modify-url-prefix-transform.ts @@ -0,0 +1,61 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {errors} from './errors'; +import {escapeRegExp} from './escape-regexp'; +import {ManifestTransform} from '../types'; + +export function modifyURLPrefixTransform(modifyURLPrefix: { + [key: string]: string; +}): ManifestTransform { + if ( + !modifyURLPrefix || + typeof modifyURLPrefix !== 'object' || + Array.isArray(modifyURLPrefix) + ) { + throw new Error(errors['modify-url-prefix-bad-prefixes']); + } + + // If there are no entries in modifyURLPrefix, just return an identity + // function as a shortcut. + if (Object.keys(modifyURLPrefix).length === 0) { + return (manifest) => { + return {manifest}; + }; + } + + for (const key of Object.keys(modifyURLPrefix)) { + if (typeof modifyURLPrefix[key] !== 'string') { + throw new Error(errors['modify-url-prefix-bad-prefixes']); + } + } + + // Escape the user input so it's safe to use in a regex. + const safeModifyURLPrefixes = Object.keys(modifyURLPrefix).map(escapeRegExp); + // Join all the `modifyURLPrefix` keys so a single regex can be used. + const prefixMatchesStrings = safeModifyURLPrefixes.join('|'); + // Add `^` to the front the prefix matches so it only matches the start of + // a string. + const modifyRegex = new RegExp(`^(${prefixMatchesStrings})`); + + return (originalManifest) => { + const manifest = originalManifest.map((entry) => { + if (typeof entry.url !== 'string') { + throw new Error(errors['manifest-entry-bad-url']); + } + + entry.url = entry.url.replace(modifyRegex, (match) => { + return modifyURLPrefix[match]; + }); + + return entry; + }); + + return {manifest}; + }; +} diff --git a/node_modules/workbox-build/src/lib/module-registry.ts b/node_modules/workbox-build/src/lib/module-registry.ts new file mode 100644 index 0000000000000000000000000000000000000000..b3dbb117402c91c7d7d38e0726fde397d2c6e44f --- /dev/null +++ b/node_modules/workbox-build/src/lib/module-registry.ts @@ -0,0 +1,73 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {oneLine as ol} from 'common-tags'; +import upath from 'upath'; + +/** + * Class for keeping track of which Workbox modules are used by the generated + * service worker script. + * + * @private + */ +export class ModuleRegistry { + private readonly _modulesUsed: Map; + /** + * @private + */ + constructor() { + this._modulesUsed = new Map(); + } + + /** + * @return {Array} A list of all of the import statements that are + * needed for the modules being used. + * @private + */ + getImportStatements(): Array { + const workboxModuleImports: Array = []; + + for (const [localName, {moduleName, pkg}] of this._modulesUsed) { + // By default require.resolve returns the resolved path of the 'main' + // field, which might be deeper than the package root. To work around + // this, we can find the package's root by resolving its package.json and + // strip the '/package.json' from the resolved path. + const pkgJsonPath = require.resolve(`${pkg}/package.json`); + const pkgRoot = upath.dirname(pkgJsonPath); + const importStatement = ol`import {${moduleName} as ${localName}} from + '${pkgRoot}/${moduleName}.mjs';`; + + workboxModuleImports.push(importStatement); + } + + return workboxModuleImports; + } + + /** + * @param {string} pkg The workbox package that the module belongs to. + * @param {string} moduleName The name of the module to import. + * @return {string} The local variable name that corresponds to that module. + * @private + */ + getLocalName(pkg: string, moduleName: string): string { + return `${pkg.replace(/-/g, '_')}_${moduleName}`; + } + + /** + * @param {string} pkg The workbox package that the module belongs to. + * @param {string} moduleName The name of the module to import. + * @return {string} The local variable name that corresponds to that module. + * @private + */ + use(pkg: string, moduleName: string): string { + const localName = this.getLocalName(pkg, moduleName); + this._modulesUsed.set(localName, {moduleName, pkg}); + + return localName; + } +} diff --git a/node_modules/workbox-build/src/lib/no-revision-for-urls-matching-transform.ts b/node_modules/workbox-build/src/lib/no-revision-for-urls-matching-transform.ts new file mode 100644 index 0000000000000000000000000000000000000000..0e14d67d2c61c5f3ee3b2ca897df14ba0595dd1c --- /dev/null +++ b/node_modules/workbox-build/src/lib/no-revision-for-urls-matching-transform.ts @@ -0,0 +1,34 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {errors} from './errors'; +import {ManifestTransform} from '../types'; + +export function noRevisionForURLsMatchingTransform( + regexp: RegExp, +): ManifestTransform { + if (!(regexp instanceof RegExp)) { + throw new Error(errors['invalid-dont-cache-bust']); + } + + return (originalManifest) => { + const manifest = originalManifest.map((entry) => { + if (typeof entry.url !== 'string') { + throw new Error(errors['manifest-entry-bad-url']); + } + + if (entry.url.match(regexp)) { + entry.revision = null; + } + + return entry; + }); + + return {manifest}; + }; +} diff --git a/node_modules/workbox-build/src/lib/populate-sw-template.ts b/node_modules/workbox-build/src/lib/populate-sw-template.ts new file mode 100644 index 0000000000000000000000000000000000000000..dca8437376cebacb6069a0a97f756ad76ef32a86 --- /dev/null +++ b/node_modules/workbox-build/src/lib/populate-sw-template.ts @@ -0,0 +1,110 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {Eta} from 'eta'; + +import {errors} from './errors'; +import {GeneratePartial, ManifestEntry} from '../types'; +import {ModuleRegistry} from './module-registry'; +import {runtimeCachingConverter} from './runtime-caching-converter'; +import {stringifyWithoutComments} from './stringify-without-comments'; +import {swTemplate} from '../templates/sw-template'; + +const eta = new Eta({ + useWith: true, + autoEscape: false, +}) + +export function populateSWTemplate({ + cacheId, + cleanupOutdatedCaches, + clientsClaim, + directoryIndex, + disableDevLogs, + ignoreURLParametersMatching, + importScripts, + manifestEntries = [], + navigateFallback, + navigateFallbackDenylist, + navigateFallbackAllowlist, + navigationPreload, + offlineGoogleAnalytics, + runtimeCaching = [], + skipWaiting, +}: GeneratePartial & {manifestEntries?: Array}): string { + // There needs to be at least something to precache, or else runtime caching. + if (!(manifestEntries?.length > 0 || runtimeCaching.length > 0)) { + throw new Error(errors['no-manifest-entries-or-runtime-caching']); + } + + // These are all options that can be passed to the precacheAndRoute() method. + const precacheOptions = { + directoryIndex, + // An array of RegExp objects can't be serialized by JSON.stringify()'s + // default behavior, so if it's given, convert it manually. + ignoreURLParametersMatching: ignoreURLParametersMatching + ? ([] as Array) + : undefined, + }; + + let precacheOptionsString = JSON.stringify(precacheOptions, null, 2); + if (ignoreURLParametersMatching) { + precacheOptionsString = precacheOptionsString.replace( + `"ignoreURLParametersMatching": []`, + `"ignoreURLParametersMatching": [` + + `${ignoreURLParametersMatching.join(', ')}]`, + ); + } + + let offlineAnalyticsConfigString: string | undefined = undefined; + if (offlineGoogleAnalytics) { + // If offlineGoogleAnalytics is a truthy value, we need to convert it to the + // format expected by the template. + offlineAnalyticsConfigString = + offlineGoogleAnalytics === true + ? // If it's the literal value true, then use an empty config string. + '{}' + : // Otherwise, convert the config object into a more complex string, taking + // into account the fact that functions might need to be stringified. + stringifyWithoutComments(offlineGoogleAnalytics); + } + + const moduleRegistry = new ModuleRegistry(); + + try { + const populatedTemplate = eta.renderString(swTemplate, { + cacheId, + cleanupOutdatedCaches, + clientsClaim, + disableDevLogs, + importScripts, + manifestEntries, + navigateFallback, + navigateFallbackDenylist, + navigateFallbackAllowlist, + navigationPreload, + offlineAnalyticsConfigString, + precacheOptionsString, + runtimeCaching: runtimeCachingConverter(moduleRegistry, runtimeCaching), + skipWaiting, + use: moduleRegistry.use.bind(moduleRegistry), + }); + + const workboxImportStatements = moduleRegistry.getImportStatements(); + + // We need the import statements for all of the Workbox runtime modules + // prepended, so that the correct bundle can be created. + return workboxImportStatements.join('\n') + populatedTemplate; + } catch (error) { + throw new Error( + `${errors['populating-sw-tmpl-failed']} '${ + error instanceof Error && error.message ? error.message : '' + }'`, + ); + } +} diff --git a/node_modules/workbox-build/src/lib/rebase-path.ts b/node_modules/workbox-build/src/lib/rebase-path.ts new file mode 100644 index 0000000000000000000000000000000000000000..6f36b282c06d08e59b453848491223f5e08b2141 --- /dev/null +++ b/node_modules/workbox-build/src/lib/rebase-path.ts @@ -0,0 +1,28 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import upath from 'upath'; + +export function rebasePath({ + baseDirectory, + file, +}: { + baseDirectory: string; + file: string; +}): string { + // The initial path is relative to the current directory, so make it absolute. + const absolutePath = upath.resolve(file); + + // Convert the absolute path so that it's relative to the baseDirectory. + const relativePath = upath.relative(baseDirectory, absolutePath); + + // Remove any leading ./ as it won't work in a glob pattern. + const normalizedPath = upath.normalize(relativePath); + + return normalizedPath; +} diff --git a/node_modules/workbox-build/src/lib/replace-and-update-source-map.ts b/node_modules/workbox-build/src/lib/replace-and-update-source-map.ts new file mode 100644 index 0000000000000000000000000000000000000000..3b5a13b4749c786ac13d875cf2df67d5d671bbd7 --- /dev/null +++ b/node_modules/workbox-build/src/lib/replace-and-update-source-map.ts @@ -0,0 +1,122 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {RawSourceMap, SourceMapConsumer, SourceMapGenerator} from 'source-map'; + +/** + * Adapted from https://github.com/nsams/sourcemap-aware-replace, with modern + * JavaScript updates, along with additional properties copied from originalMap. + * + * @param {Object} options + * @param {string} options.jsFilename The name for the file whose contents + * correspond to originalSource. + * @param {Object} options.originalMap The sourcemap for originalSource, + * prior to any replacements. + * @param {string} options.originalSource The source code, prior to any + * replacements. + * @param {string} options.replaceString A string to swap in for searchString. + * @param {string} options.searchString A string in originalSource to replace. + * Only the first occurrence will be replaced. + * @return {{source: string, map: string}} An object containing both + * originalSource with the replacement applied, and the modified originalMap. + * + * @private + */ +export async function replaceAndUpdateSourceMap({ + jsFilename, + originalMap, + originalSource, + replaceString, + searchString, +}: { + jsFilename: string; + originalMap: RawSourceMap; + originalSource: string; + replaceString: string; + searchString: string; +}): Promise<{map: string; source: string}> { + const generator = new SourceMapGenerator({ + file: jsFilename, + }); + + const consumer = await new SourceMapConsumer(originalMap); + + let pos: number; + let src = originalSource; + const replacements: Array<{line: number; column: number}> = []; + let lineNum = 0; + let filePos = 0; + + const lines = src.split('\n'); + for (let line of lines) { + lineNum++; + let searchPos = 0; + while ((pos = line.indexOf(searchString, searchPos)) !== -1) { + src = + src.substring(0, filePos + pos) + + replaceString + + src.substring(filePos + pos + searchString.length); + line = + line.substring(0, pos) + + replaceString + + line.substring(pos + searchString.length); + replacements.push({line: lineNum, column: pos}); + searchPos = pos + replaceString.length; + } + filePos += line.length + 1; + } + + replacements.reverse(); + + consumer.eachMapping((mapping) => { + for (const replacement of replacements) { + if ( + replacement.line === mapping.generatedLine && + mapping.generatedColumn > replacement.column + ) { + const offset = searchString.length - replaceString.length; + mapping.generatedColumn -= offset; + } + } + + if (mapping.source) { + const newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn, + }, + original: { + line: mapping.originalLine, + column: mapping.originalColumn, + }, + source: mapping.source, + }; + return generator.addMapping(newMapping); + } + + return mapping; + }); + + consumer.destroy(); + // JSON.parse returns any. + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const updatedSourceMap: RawSourceMap = Object.assign( + JSON.parse(generator.toString()), + { + names: originalMap.names, + sourceRoot: originalMap.sourceRoot, + sources: originalMap.sources, + sourcesContent: originalMap.sourcesContent, + }, + ); + + return { + map: JSON.stringify(updatedSourceMap), + source: src, + }; +} diff --git a/node_modules/workbox-build/src/lib/runtime-caching-converter.ts b/node_modules/workbox-build/src/lib/runtime-caching-converter.ts new file mode 100644 index 0000000000000000000000000000000000000000..b235e9e293946b2d2b6008cbd739b715ce24ceb5 --- /dev/null +++ b/node_modules/workbox-build/src/lib/runtime-caching-converter.ts @@ -0,0 +1,215 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {oneLine as ol} from 'common-tags'; + +import {errors} from './errors'; +import {ModuleRegistry} from './module-registry'; +import {RuntimeCaching} from '../types'; +import {stringifyWithoutComments} from './stringify-without-comments'; + +/** + * Given a set of options that configures runtime caching behavior, convert it + * to the equivalent Workbox method calls. + * + * @param {ModuleRegistry} moduleRegistry + * @param {Object} options See + * https://developers.google.com/web/tools/workbox/modules/workbox-build#generateSW-runtimeCaching + * @return {string} A JSON string representing the equivalent options. + * + * @private + */ +function getOptionsString( + moduleRegistry: ModuleRegistry, + options: RuntimeCaching['options'] = {}, +) { + const plugins: Array = []; + const handlerOptions: {[key in keyof typeof options]: any} = {}; + + for (const optionName of Object.keys(options) as Array< + keyof typeof options + >) { + if (options[optionName] === undefined) { + continue; + } + + switch (optionName) { + // Using a library here because JSON.stringify won't handle functions. + case 'plugins': { + plugins.push(...options.plugins!.map(stringifyWithoutComments)); + break; + } + + // These are the option properties that we want to pull out, so that + // they're passed to the handler constructor. + case 'cacheName': + case 'networkTimeoutSeconds': + case 'fetchOptions': + case 'matchOptions': { + handlerOptions[optionName] = options[optionName]; + break; + } + + // The following cases are all shorthands for creating a plugin with a + // given configuration. + case 'backgroundSync': { + const name = options.backgroundSync!.name; + const plugin = moduleRegistry.use( + 'workbox-background-sync', + 'BackgroundSyncPlugin', + ); + + let pluginCode = `new ${plugin}(${JSON.stringify(name)}`; + if (options.backgroundSync!.options) { + pluginCode += `, ${stringifyWithoutComments( + options.backgroundSync!.options, + )}`; + } + pluginCode += `)`; + + plugins.push(pluginCode); + break; + } + + case 'broadcastUpdate': { + const channelName = options.broadcastUpdate!.channelName; + const opts = Object.assign( + {channelName}, + options.broadcastUpdate!.options, + ); + const plugin = moduleRegistry.use( + 'workbox-broadcast-update', + 'BroadcastUpdatePlugin', + ); + + plugins.push(`new ${plugin}(${stringifyWithoutComments(opts)})`); + break; + } + + case 'cacheableResponse': { + const plugin = moduleRegistry.use( + 'workbox-cacheable-response', + 'CacheableResponsePlugin', + ); + + plugins.push( + `new ${plugin}(${stringifyWithoutComments( + options.cacheableResponse!, + )})`, + ); + break; + } + + case 'expiration': { + const plugin = moduleRegistry.use( + 'workbox-expiration', + 'ExpirationPlugin', + ); + + plugins.push( + `new ${plugin}(${stringifyWithoutComments(options.expiration!)})`, + ); + break; + } + + case 'precacheFallback': { + const plugin = moduleRegistry.use( + 'workbox-precaching', + 'PrecacheFallbackPlugin', + ); + + plugins.push( + `new ${plugin}(${stringifyWithoutComments( + options.precacheFallback!, + )})`, + ); + break; + } + + case 'rangeRequests': { + const plugin = moduleRegistry.use( + 'workbox-range-requests', + 'RangeRequestsPlugin', + ); + + // There are no configuration options for the constructor. + plugins.push(`new ${plugin}()`); + break; + } + + default: { + throw new Error( + // In the default case optionName is typed as 'never'. + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + `${errors['bad-runtime-caching-config']} ${optionName}`, + ); + } + } + } + + if (Object.keys(handlerOptions).length > 0 || plugins.length > 0) { + const optionsString = JSON.stringify(handlerOptions).slice(1, -1); + return ol`{ + ${optionsString ? optionsString + ',' : ''} + plugins: [${plugins.join(', ')}] + }`; + } else { + return ''; + } +} + +export function runtimeCachingConverter( + moduleRegistry: ModuleRegistry, + runtimeCaching: Array, +): Array { + return runtimeCaching + .map((entry) => { + const method = entry.method || 'GET'; + + if (!entry.urlPattern) { + throw new Error(errors['urlPattern-is-required']); + } + + if (!entry.handler) { + throw new Error(errors['handler-is-required']); + } + + if ( + entry.options && + entry.options.networkTimeoutSeconds && + entry.handler !== 'NetworkFirst' + ) { + throw new Error(errors['invalid-network-timeout-seconds']); + } + + // urlPattern might be a string, a RegExp object, or a function. + // If it's a string, it needs to be quoted. + const matcher = + typeof entry.urlPattern === 'string' + ? JSON.stringify(entry.urlPattern) + : entry.urlPattern; + + const registerRoute = moduleRegistry.use( + 'workbox-routing', + 'registerRoute', + ); + if (typeof entry.handler === 'string') { + const optionsString = getOptionsString(moduleRegistry, entry.options); + const handler = moduleRegistry.use('workbox-strategies', entry.handler); + const strategyString = `new ${handler}(${optionsString})`; + + return `${registerRoute}(${matcher.toString()}, ${strategyString}, '${method}');\n`; + } else if (typeof entry.handler === 'function') { + return `${registerRoute}(${matcher.toString()}, ${entry.handler.toString()}, '${method}');\n`; + } + + // '' will be filtered out. + return ''; + }) + .filter((entry) => Boolean(entry)); +} diff --git a/node_modules/workbox-build/src/lib/stringify-without-comments.ts b/node_modules/workbox-build/src/lib/stringify-without-comments.ts new file mode 100644 index 0000000000000000000000000000000000000000..60b803d45835d689ec97211a86c73e8824ce26a7 --- /dev/null +++ b/node_modules/workbox-build/src/lib/stringify-without-comments.ts @@ -0,0 +1,23 @@ +/* + Copyright 2021 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import objectStringify from 'stringify-object'; +import stripComments from 'strip-comments'; + +export function stringifyWithoutComments(obj: {[key: string]: any}): string { + return objectStringify(obj, { + // See https://github.com/yeoman/stringify-object#transformobject-property-originalresult + transform: (_obj: {[key: string]: any}, _prop, str) => { + if (typeof _prop !== 'symbol' && typeof _obj[_prop] === 'function') { + // Can't typify correctly stripComments + return stripComments(str); // eslint-disable-line + } + return str; + }, + }); +} diff --git a/node_modules/workbox-build/src/lib/transform-manifest.ts b/node_modules/workbox-build/src/lib/transform-manifest.ts new file mode 100644 index 0000000000000000000000000000000000000000..9ab81029198ea4c9990fe487be570bf3a8b0da22 --- /dev/null +++ b/node_modules/workbox-build/src/lib/transform-manifest.ts @@ -0,0 +1,162 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import { + BasePartial, + FileDetails, + ManifestEntry, + ManifestTransform, +} from '../types'; +import {additionalManifestEntriesTransform} from './additional-manifest-entries-transform'; +import {errors} from './errors'; +import {maximumSizeTransform} from './maximum-size-transform'; +import {modifyURLPrefixTransform} from './modify-url-prefix-transform'; +import {noRevisionForURLsMatchingTransform} from './no-revision-for-urls-matching-transform'; + +/** + * A `ManifestTransform` function can be used to modify the modify the `url` or + * `revision` properties of some or all of the + * {@link workbox-build.ManifestEntry} in the manifest. + * + * Deleting the `revision` property of an entry will cause + * the corresponding `url` to be precached without cache-busting parameters + * applied, which is to say, it implies that the URL itself contains + * proper versioning info. If the `revision` property is present, it must be + * set to a string. + * + * @example A transformation that prepended the origin of a CDN for any + * URL starting with '/assets/' could be implemented as: + * + * const cdnTransform = async (manifestEntries) => { + * const manifest = manifestEntries.map(entry => { + * const cdnOrigin = 'https://example.com'; + * if (entry.url.startsWith('/assets/')) { + * entry.url = cdnOrigin + entry.url; + * } + * return entry; + * }); + * return {manifest, warnings: []}; + * }; + * + * @example A transformation that nulls the revision field when the + * URL contains an 8-character hash surrounded by '.', indicating that it + * already contains revision information: + * + * const removeRevisionTransform = async (manifestEntries) => { + * const manifest = manifestEntries.map(entry => { + * const hashRegExp = /\.\w{8}\./; + * if (entry.url.match(hashRegExp)) { + * entry.revision = null; + * } + * return entry; + * }); + * return {manifest, warnings: []}; + * }; + * + * @callback ManifestTransform + * @param {Array} manifestEntries The full + * array of entries, prior to the current transformation. + * @param {Object} [compilation] When used in the webpack plugins, this param + * will be set to the current `compilation`. + * @return {Promise} + * The array of entries with the transformation applied, and optionally, any + * warnings that should be reported back to the build tool. + * + * @memberof workbox-build + */ + +interface ManifestTransformResultWithWarnings { + count: number; + size: number; + manifestEntries: ManifestEntry[]; + warnings: string[]; +} +export async function transformManifest({ + additionalManifestEntries, + dontCacheBustURLsMatching, + fileDetails, + manifestTransforms, + maximumFileSizeToCacheInBytes, + modifyURLPrefix, + transformParam, +}: BasePartial & { + fileDetails: Array; + // When this is called by the webpack plugin, transformParam will be the + // current webpack compilation. + transformParam?: unknown; +}): Promise { + const allWarnings: Array = []; + + // Take the array of fileDetail objects and convert it into an array of + // {url, revision, size} objects, with \ replaced with /. + const normalizedManifest = fileDetails.map((fileDetails) => { + return { + url: fileDetails.file.replace(/\\/g, '/'), + revision: fileDetails.hash, + size: fileDetails.size, + }; + }); + + const transformsToApply: Array = []; + + if (maximumFileSizeToCacheInBytes) { + transformsToApply.push(maximumSizeTransform(maximumFileSizeToCacheInBytes)); + } + + if (modifyURLPrefix) { + transformsToApply.push(modifyURLPrefixTransform(modifyURLPrefix)); + } + + if (dontCacheBustURLsMatching) { + transformsToApply.push( + noRevisionForURLsMatchingTransform(dontCacheBustURLsMatching), + ); + } + + // Run any manifestTransforms functions second-to-last. + if (manifestTransforms) { + transformsToApply.push(...manifestTransforms); + } + + // Run additionalManifestEntriesTransform last. + if (additionalManifestEntries) { + transformsToApply.push( + additionalManifestEntriesTransform(additionalManifestEntries), + ); + } + + let transformedManifest: Array = + normalizedManifest; + for (const transform of transformsToApply) { + const result = await transform(transformedManifest, transformParam); + if (!('manifest' in result)) { + throw new Error(errors['bad-manifest-transforms-return-value']); + } + + transformedManifest = result.manifest; + allWarnings.push(...(result.warnings || [])); + } + + // Generate some metadata about the manifest before we clear out the size + // properties from each entry. + const count = transformedManifest.length; + let size = 0; + for (const manifestEntry of transformedManifest as Array< + ManifestEntry & {size?: number} + >) { + size += manifestEntry.size || 0; + delete manifestEntry.size; + } + + return { + count, + size, + manifestEntries: transformedManifest as Array, + warnings: allWarnings, + }; +} diff --git a/node_modules/workbox-build/src/lib/translate-url-to-sourcemap-paths.ts b/node_modules/workbox-build/src/lib/translate-url-to-sourcemap-paths.ts new file mode 100644 index 0000000000000000000000000000000000000000..072eac40d4ef5d095a01cb7f7e392a9e034853bd --- /dev/null +++ b/node_modules/workbox-build/src/lib/translate-url-to-sourcemap-paths.ts @@ -0,0 +1,38 @@ +/* + Copyright 2021 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import fse from 'fs-extra'; +import upath from 'upath'; + +import {errors} from './errors'; + +export function translateURLToSourcemapPaths( + url: string | null, + swSrc: string, + swDest: string, +): { + destPath: string | undefined; + srcPath: string | undefined; + warning: string | undefined; +} { + let destPath: string | undefined = undefined; + let srcPath: string | undefined = undefined; + let warning: string | undefined = undefined; + + if (url && !url.startsWith('data:')) { + const possibleSrcPath = upath.resolve(upath.dirname(swSrc), url); + if (fse.existsSync(possibleSrcPath)) { + srcPath = possibleSrcPath; + destPath = upath.resolve(upath.dirname(swDest), url); + } else { + warning = `${errors['cant-find-sourcemap']} ${possibleSrcPath}`; + } + } + + return {destPath, srcPath, warning}; +} diff --git a/node_modules/workbox-build/src/lib/validate-options.ts b/node_modules/workbox-build/src/lib/validate-options.ts new file mode 100644 index 0000000000000000000000000000000000000000..6b05487b457a9c12da5dad7b9809ec8d23541761 --- /dev/null +++ b/node_modules/workbox-build/src/lib/validate-options.ts @@ -0,0 +1,235 @@ +/* + Copyright 2021 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {betterAjvErrors} from '@apideck/better-ajv-errors'; +import {oneLine as ol} from 'common-tags'; +import Ajv, {JSONSchemaType} from 'ajv'; + +import {errors} from './errors'; + +import { + GenerateSWOptions, + GetManifestOptions, + InjectManifestOptions, + WebpackGenerateSWOptions, + WebpackInjectManifestOptions, +} from '../types'; + +type MethodNames = + | 'GenerateSW' + | 'GetManifest' + | 'InjectManifest' + | 'WebpackGenerateSW' + | 'WebpackInjectManifest'; + +const ajv = new Ajv({ + useDefaults: true, +}); + +const DEFAULT_EXCLUDE_VALUE = [/\.map$/, /^manifest.*\.js$/]; + +export class WorkboxConfigError extends Error { + constructor(message?: string) { + super(message); + Object.setPrototypeOf(this, new.target.prototype); + } +} + +// Some methods need to do follow-up validation using the JSON schema, +// so return both the validated options and then schema. +function validate( + input: unknown, + methodName: MethodNames, +): [T, JSONSchemaType] { + // Don't mutate input: https://github.com/GoogleChrome/workbox/issues/2158 + const inputCopy = Object.assign({}, input); + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const jsonSchema: JSONSchemaType = require(`../schema/${methodName}Options.json`); + const validate = ajv.compile(jsonSchema); + if (validate(inputCopy)) { + // All methods support manifestTransforms, so validate it here. + ensureValidManifestTransforms(inputCopy); + return [inputCopy, jsonSchema]; + } + + const betterErrors = betterAjvErrors({ + basePath: methodName, + data: input, + errors: validate.errors, + // This is needed as JSONSchema6 is expected, but JSONSchemaType works. + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + schema: jsonSchema as any, + }); + const messages = betterErrors.map( + (err) => ol`[${err.path}] ${err.message}. + ${err.suggestion ? err.suggestion : ''}`, + ); + + throw new WorkboxConfigError(messages.join('\n\n')); +} + +function ensureValidManifestTransforms( + options: + | GenerateSWOptions + | GetManifestOptions + | InjectManifestOptions + | WebpackGenerateSWOptions + | WebpackInjectManifestOptions, +): void { + if ( + 'manifestTransforms' in options && + !( + Array.isArray(options.manifestTransforms) && + options.manifestTransforms.every((item) => typeof item === 'function') + ) + ) { + throw new WorkboxConfigError(errors['manifest-transforms']); + } +} + +function ensureValidNavigationPreloadConfig( + options: GenerateSWOptions | WebpackGenerateSWOptions, +): void { + if ( + options.navigationPreload && + (!Array.isArray(options.runtimeCaching) || + options.runtimeCaching.length === 0) + ) { + throw new WorkboxConfigError(errors['nav-preload-runtime-caching']); + } +} + +function ensureValidCacheExpiration( + options: GenerateSWOptions | WebpackGenerateSWOptions, +): void { + for (const runtimeCaching of options.runtimeCaching || []) { + if ( + runtimeCaching.options?.expiration && + !runtimeCaching.options?.cacheName + ) { + throw new WorkboxConfigError(errors['cache-name-required']); + } + } +} + +function ensureValidRuntimeCachingOrGlobDirectory( + options: GenerateSWOptions, +): void { + if ( + !options.globDirectory && + (!Array.isArray(options.runtimeCaching) || + options.runtimeCaching.length === 0) + ) { + throw new WorkboxConfigError( + errors['no-manifest-entries-or-runtime-caching'], + ); + } +} + +// This is... messy, because we can't rely on the built-in ajv validation for +// runtimeCaching.handler, as it needs to accept {} (i.e. any) due to +// https://github.com/GoogleChrome/workbox/pull/2899 +// So we need to perform validation when a string (not a function) is used. +function ensureValidStringHandler( + options: GenerateSWOptions | WebpackGenerateSWOptions, + jsonSchema: JSONSchemaType, +): void { + let validHandlers: Array = []; + /* eslint-disable */ + for (const handler of jsonSchema.definitions?.RuntimeCaching?.properties + ?.handler?.anyOf || []) { + if ('enum' in handler) { + validHandlers = handler.enum; + break; + } + } + /* eslint-enable */ + + for (const runtimeCaching of options.runtimeCaching || []) { + if ( + typeof runtimeCaching.handler === 'string' && + !validHandlers.includes(runtimeCaching.handler) + ) { + throw new WorkboxConfigError( + errors['invalid-handler-string'] + runtimeCaching.handler, + ); + } + } +} + +export function validateGenerateSWOptions(input: unknown): GenerateSWOptions { + const [validatedOptions, jsonSchema] = validate( + input, + 'GenerateSW', + ); + ensureValidNavigationPreloadConfig(validatedOptions); + ensureValidCacheExpiration(validatedOptions); + ensureValidRuntimeCachingOrGlobDirectory(validatedOptions); + ensureValidStringHandler(validatedOptions, jsonSchema); + + return validatedOptions; +} + +export function validateGetManifestOptions(input: unknown): GetManifestOptions { + const [validatedOptions] = validate(input, 'GetManifest'); + + return validatedOptions; +} + +export function validateInjectManifestOptions( + input: unknown, +): InjectManifestOptions { + const [validatedOptions] = validate( + input, + 'InjectManifest', + ); + + return validatedOptions; +} + +// The default `exclude: [/\.map$/, /^manifest.*\.js$/]` value can't be +// represented in the JSON schema, so manually set it for the webpack options. +export function validateWebpackGenerateSWOptions( + input: unknown, +): WebpackGenerateSWOptions { + const inputWithExcludeDefault = Object.assign( + { + // Make a copy, as exclude can be mutated when used. + exclude: Array.from(DEFAULT_EXCLUDE_VALUE), + }, + input, + ); + const [validatedOptions, jsonSchema] = validate( + inputWithExcludeDefault, + 'WebpackGenerateSW', + ); + + ensureValidNavigationPreloadConfig(validatedOptions); + ensureValidCacheExpiration(validatedOptions); + ensureValidStringHandler(validatedOptions, jsonSchema); + + return validatedOptions; +} + +export function validateWebpackInjectManifestOptions( + input: unknown, +): WebpackInjectManifestOptions { + const inputWithExcludeDefault = Object.assign( + { + // Make a copy, as exclude can be mutated when used. + exclude: Array.from(DEFAULT_EXCLUDE_VALUE), + }, + input, + ); + const [validatedOptions] = validate( + inputWithExcludeDefault, + 'WebpackInjectManifest', + ); + + return validatedOptions; +} diff --git a/node_modules/workbox-build/src/lib/write-sw-using-default-template.ts b/node_modules/workbox-build/src/lib/write-sw-using-default-template.ts new file mode 100644 index 0000000000000000000000000000000000000000..cd89917129661240c720e8b2c95e5ae6e2ba7202 --- /dev/null +++ b/node_modules/workbox-build/src/lib/write-sw-using-default-template.ts @@ -0,0 +1,96 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import fse from 'fs-extra'; +import upath from 'upath'; + +import {bundle} from './bundle'; +import {errors} from './errors'; +import {GenerateSWOptions, ManifestEntry} from '../types'; +import {populateSWTemplate} from './populate-sw-template'; + +export async function writeSWUsingDefaultTemplate({ + babelPresetEnvTargets, + cacheId, + cleanupOutdatedCaches, + clientsClaim, + directoryIndex, + disableDevLogs, + ignoreURLParametersMatching, + importScripts, + inlineWorkboxRuntime, + manifestEntries, + mode, + navigateFallback, + navigateFallbackDenylist, + navigateFallbackAllowlist, + navigationPreload, + offlineGoogleAnalytics, + runtimeCaching, + skipWaiting, + sourcemap, + swDest, +}: GenerateSWOptions & {manifestEntries: Array}): Promise< + Array +> { + const outputDir = upath.dirname(swDest); + try { + await fse.mkdirp(outputDir); + } catch (error) { + throw new Error( + `${errors['unable-to-make-sw-directory']}. ` + + `'${error instanceof Error && error.message ? error.message : ''}'`, + ); + } + + const unbundledCode = populateSWTemplate({ + cacheId, + cleanupOutdatedCaches, + clientsClaim, + directoryIndex, + disableDevLogs, + ignoreURLParametersMatching, + importScripts, + manifestEntries, + navigateFallback, + navigateFallbackDenylist, + navigateFallbackAllowlist, + navigationPreload, + offlineGoogleAnalytics, + runtimeCaching, + skipWaiting, + }); + + try { + const files = await bundle({ + babelPresetEnvTargets, + inlineWorkboxRuntime, + mode, + sourcemap, + swDest, + unbundledCode, + }); + + const filePaths: Array = []; + + for (const file of files) { + const filePath = upath.resolve(file.name); + filePaths.push(filePath); + await fse.writeFile(filePath, file.contents); + } + + return filePaths; + } catch (error) { + const err = error as NodeJS.ErrnoException; + if (err.code === 'EISDIR') { + // See https://github.com/GoogleChrome/workbox/issues/612 + throw new Error(errors['sw-write-failure-directory']); + } + throw new Error(`${errors['sw-write-failure']} '${err.message}'`); + } +} diff --git a/node_modules/workbox-build/src/rollup-plugin-off-main-thread.d.ts b/node_modules/workbox-build/src/rollup-plugin-off-main-thread.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..80bc49cdc2768b1087a8a022434a7c271b6ac60b --- /dev/null +++ b/node_modules/workbox-build/src/rollup-plugin-off-main-thread.d.ts @@ -0,0 +1 @@ +declare module '@trickfilm400/rollup-plugin-off-main-thread'; diff --git a/node_modules/workbox-build/src/schema/GenerateSWOptions.json b/node_modules/workbox-build/src/schema/GenerateSWOptions.json new file mode 100644 index 0000000000000000000000000000000000000000..6817de451d0207f7f725ce7dbc5a72885f1127f1 --- /dev/null +++ b/node_modules/workbox-build/src/schema/GenerateSWOptions.json @@ -0,0 +1,878 @@ +{ + "additionalProperties": false, + "type": "object", + "properties": { + "additionalManifestEntries": { + "description": "A list of entries to be precached, in addition to any entries that are\ngenerated as part of the build configuration.", + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/definitions/ManifestEntry" + }, + { + "type": "string" + } + ] + } + }, + "dontCacheBustURLsMatching": { + "description": "Assets that match this will be assumed to be uniquely versioned via their\nURL, and exempted from the normal HTTP cache-busting that's done when\npopulating the precache. While not required, it's recommended that if your\nexisting build process already inserts a `[hash]` value into each filename,\nyou provide a RegExp that will detect that, as it will reduce the bandwidth\nconsumed when precaching.", + "$ref": "#/definitions/RegExp" + }, + "manifestTransforms": { + "description": "One or more functions which will be applied sequentially against the\ngenerated manifest. If `modifyURLPrefix` or `dontCacheBustURLsMatching` are\nalso specified, their corresponding transformations will be applied first.", + "type": "array", + "items": {} + }, + "maximumFileSizeToCacheInBytes": { + "description": "This value can be used to determine the maximum size of files that will be\nprecached. This prevents you from inadvertently precaching very large files\nthat might have accidentally matched one of your patterns.", + "default": 2097152, + "type": "number" + }, + "modifyURLPrefix": { + "description": "An object mapping string prefixes to replacement string values. This can be\nused to, e.g., remove or add a path prefix from a manifest entry if your\nweb hosting setup doesn't match your local filesystem setup. As an\nalternative with more flexibility, you can use the `manifestTransforms`\noption and provide a function that modifies the entries in the manifest\nusing whatever logic you provide.\n\nExample usage:\n\n```\n// Replace a '/dist/' prefix with '/', and also prepend\n// '/static' to every URL.\nmodifyURLPrefix: {\n '/dist/': '/',\n '': '/static',\n}\n```", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "globFollow": { + "description": "Determines whether or not symlinks are followed when generating the\nprecache manifest. For more information, see the definition of `follow` in\nthe `glob` [documentation](https://github.com/isaacs/node-glob#options).", + "default": true, + "type": "boolean" + }, + "globIgnores": { + "description": "A set of patterns matching files to always exclude when generating the\nprecache manifest. For more information, see the definition of `ignore` in\nthe `glob` [documentation](https://github.com/isaacs/node-glob#options).", + "default": [ + "**/node_modules/**/*" + ], + "type": "array", + "items": { + "type": "string" + } + }, + "globPatterns": { + "description": "Files matching any of these patterns will be included in the precache\nmanifest. For more information, see the\n[`glob` primer](https://github.com/isaacs/node-glob#glob-primer).", + "default": [ + "**/*.{js,wasm,css,html}" + ], + "type": "array", + "items": { + "type": "string" + } + }, + "templatedURLs": { + "description": "If a URL is rendered based on some server-side logic, its contents may\ndepend on multiple files or on some other unique string value. The keys in\nthis object are server-rendered URLs. If the values are an array of\nstrings, they will be interpreted as `glob` patterns, and the contents of\nany files matching the patterns will be used to uniquely version the URL.\nIf used with a single string, it will be interpreted as unique versioning\ninformation that you've generated for a given URL.", + "type": "object", + "additionalProperties": { + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string" + } + ] + } + }, + "babelPresetEnvTargets": { + "description": "The [targets](https://babeljs.io/docs/en/babel-preset-env#targets) to pass\nto `babel-preset-env` when transpiling the service worker bundle.", + "default": [ + "chrome >= 56" + ], + "type": "array", + "items": { + "type": "string" + } + }, + "cacheId": { + "description": "An optional ID to be prepended to cache names. This is primarily useful for\nlocal development where multiple sites may be served from the same\n`http://localhost:port` origin.", + "type": [ + "null", + "string" + ] + }, + "cleanupOutdatedCaches": { + "description": "Whether or not Workbox should attempt to identify and delete any precaches\ncreated by older, incompatible versions.", + "default": false, + "type": "boolean" + }, + "clientsClaim": { + "description": "Whether or not the service worker should [start controlling](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#clientsclaim)\nany existing clients as soon as it activates.", + "default": false, + "type": "boolean" + }, + "directoryIndex": { + "description": "If a navigation request for a URL ending in `/` fails to match a precached\nURL, this value will be appended to the URL and that will be checked for a\nprecache match. This should be set to what your web server is using for its\ndirectory index.", + "type": [ + "null", + "string" + ] + }, + "disableDevLogs": { + "default": false, + "type": "boolean" + }, + "ignoreURLParametersMatching": { + "description": "Any search parameter names that match against one of the RegExp in this\narray will be removed before looking for a precache match. This is useful\nif your users might request URLs that contain, for example, URL parameters\nused to track the source of the traffic. If not provided, the default value\nis `[/^utm_/, /^fbclid$/]`.", + "type": "array", + "items": { + "$ref": "#/definitions/RegExp" + } + }, + "importScripts": { + "description": "A list of JavaScript files that should be passed to\n[`importScripts()`](https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts)\ninside the generated service worker file. This is useful when you want to\nlet Workbox create your top-level service worker file, but want to include\nsome additional code, such as a push event listener.", + "type": "array", + "items": { + "type": "string" + } + }, + "inlineWorkboxRuntime": { + "description": "Whether the runtime code for the Workbox library should be included in the\ntop-level service worker, or split into a separate file that needs to be\ndeployed alongside the service worker. Keeping the runtime separate means\nthat users will not have to re-download the Workbox code each time your\ntop-level service worker changes.", + "default": false, + "type": "boolean" + }, + "mode": { + "description": "If set to 'production', then an optimized service worker bundle that\nexcludes debugging info will be produced. If not explicitly configured\nhere, the `process.env.NODE_ENV` value will be used, and failing that, it\nwill fall back to `'production'`.", + "default": "production", + "type": [ + "null", + "string" + ] + }, + "navigateFallback": { + "description": "If specified, all\n[navigation requests](https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests)\nfor URLs that aren't precached will be fulfilled with the HTML at the URL\nprovided. You must pass in the URL of an HTML document that is listed in\nyour precache manifest. This is meant to be used in a Single Page App\nscenario, in which you want all navigations to use common\n[App Shell HTML](https://developers.google.com/web/fundamentals/architecture/app-shell).", + "default": null, + "type": [ + "null", + "string" + ] + }, + "navigateFallbackAllowlist": { + "description": "An optional array of regular expressions that restricts which URLs the\nconfigured `navigateFallback` behavior applies to. This is useful if only a\nsubset of your site's URLs should be treated as being part of a\n[Single Page App](https://en.wikipedia.org/wiki/Single-page_application).\nIf both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are\nconfigured, the denylist takes precedent.\n\n*Note*: These RegExps may be evaluated against every destination URL during\na navigation. Avoid using\n[complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077),\nor else your users may see delays when navigating your site.", + "type": "array", + "items": { + "$ref": "#/definitions/RegExp" + } + }, + "navigateFallbackDenylist": { + "description": "An optional array of regular expressions that restricts which URLs the\nconfigured `navigateFallback` behavior applies to. This is useful if only a\nsubset of your site's URLs should be treated as being part of a\n[Single Page App](https://en.wikipedia.org/wiki/Single-page_application).\nIf both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are\nconfigured, the denylist takes precedence.\n\n*Note*: These RegExps may be evaluated against every destination URL during\na navigation. Avoid using\n[complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077),\nor else your users may see delays when navigating your site.", + "type": "array", + "items": { + "$ref": "#/definitions/RegExp" + } + }, + "navigationPreload": { + "description": "Whether or not to enable\n[navigation preload](https://developers.google.com/web/tools/workbox/modules/workbox-navigation-preload)\nin the generated service worker. When set to true, you must also use\n`runtimeCaching` to set up an appropriate response strategy that will match\nnavigation requests, and make use of the preloaded response.", + "default": false, + "type": "boolean" + }, + "offlineGoogleAnalytics": { + "description": "Controls whether or not to include support for\n[offline Google Analytics](https://developers.google.com/web/tools/workbox/guides/enable-offline-analytics).\nWhen `true`, the call to `workbox-google-analytics`'s `initialize()` will\nbe added to your generated service worker. When set to an `Object`, that\nobject will be passed in to the `initialize()` call, allowing you to\ncustomize the behavior.", + "default": false, + "anyOf": [ + { + "$ref": "#/definitions/GoogleAnalyticsInitializeOptions" + }, + { + "type": "boolean" + } + ] + }, + "runtimeCaching": { + "description": "When using Workbox's build tools to generate your service worker, you can\nspecify one or more runtime caching configurations. These are then\ntranslated to {@link workbox-routing.registerRoute} calls using the match\nand handler configuration you define.\n\nFor all of the options, see the {@link workbox-build.RuntimeCaching}\ndocumentation. The example below shows a typical configuration, with two\nruntime routes defined:", + "type": "array", + "items": { + "$ref": "#/definitions/RuntimeCaching" + } + }, + "skipWaiting": { + "description": "Whether to add an unconditional call to [`skipWaiting()`](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#skip_the_waiting_phase)\nto the generated service worker. If `false`, then a `message` listener will\nbe added instead, allowing client pages to trigger `skipWaiting()` by\ncalling `postMessage({type: 'SKIP_WAITING'})` on a waiting service worker.", + "default": false, + "type": "boolean" + }, + "sourcemap": { + "description": "Whether to create a sourcemap for the generated service worker files.", + "default": true, + "type": "boolean" + }, + "swDest": { + "description": "The path and filename of the service worker file that will be created by\nthe build process, relative to the current working directory. It must end\nin '.js'.", + "type": "string" + }, + "globDirectory": { + "description": "The local directory you wish to match `globPatterns` against. The path is\nrelative to the current directory.", + "type": "string" + } + }, + "required": [ + "swDest" + ], + "definitions": { + "ManifestEntry": { + "type": "object", + "properties": { + "integrity": { + "type": "string" + }, + "revision": { + "type": [ + "null", + "string" + ] + }, + "url": { + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "revision", + "url" + ] + }, + "RegExp": { + "type": "object", + "properties": { + "source": { + "type": "string" + }, + "global": { + "type": "boolean" + }, + "ignoreCase": { + "type": "boolean" + }, + "multiline": { + "type": "boolean" + }, + "lastIndex": { + "type": "number" + }, + "flags": { + "type": "string" + }, + "sticky": { + "type": "boolean" + }, + "unicode": { + "type": "boolean" + }, + "dotAll": { + "type": "boolean" + }, + "hasIndices": { + "type": "boolean" + } + }, + "additionalProperties": false, + "required": [ + "dotAll", + "flags", + "global", + "hasIndices", + "ignoreCase", + "lastIndex", + "multiline", + "source", + "sticky", + "unicode" + ] + }, + "GoogleAnalyticsInitializeOptions": { + "type": "object", + "properties": { + "cacheName": { + "type": "string" + }, + "parameterOverrides": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "hitFilter": { + "type": "object", + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "RuntimeCaching": { + "type": "object", + "properties": { + "handler": { + "description": "This determines how the runtime route will generate a response.\nTo use one of the built-in {@link workbox-strategies}, provide its name,\nlike `'NetworkFirst'`.\nAlternatively, this can be a {@link workbox-core.RouteHandler} callback\nfunction with custom response logic.", + "anyOf": [ + { + "$ref": "#/definitions/RouteHandlerCallback" + }, + { + "$ref": "#/definitions/RouteHandlerObject" + }, + { + "enum": [ + "CacheFirst", + "CacheOnly", + "NetworkFirst", + "NetworkOnly", + "StaleWhileRevalidate" + ], + "type": "string" + } + ] + }, + "method": { + "description": "The HTTP method to match against. The default value of `'GET'` is normally\nsufficient, unless you explicitly need to match `'POST'`, `'PUT'`, or\nanother type of request.", + "default": "GET", + "enum": [ + "DELETE", + "GET", + "HEAD", + "PATCH", + "POST", + "PUT" + ], + "type": "string" + }, + "options": { + "type": "object", + "properties": { + "backgroundSync": { + "description": "Configuring this will add a\n{@link workbox-background-sync.BackgroundSyncPlugin} instance to the\n{@link workbox-strategies} configured in `handler`.", + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "options": { + "$ref": "#/definitions/QueueOptions" + } + }, + "additionalProperties": false, + "required": [ + "name" + ] + }, + "broadcastUpdate": { + "description": "Configuring this will add a\n{@link workbox-broadcast-update.BroadcastUpdatePlugin} instance to the\n{@link workbox-strategies} configured in `handler`.", + "type": "object", + "properties": { + "channelName": { + "type": "string" + }, + "options": { + "$ref": "#/definitions/BroadcastCacheUpdateOptions" + } + }, + "additionalProperties": false, + "required": [ + "options" + ] + }, + "cacheableResponse": { + "description": "Configuring this will add a\n{@link workbox-cacheable-response.CacheableResponsePlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", + "$ref": "#/definitions/CacheableResponseOptions" + }, + "cacheName": { + "description": "If provided, this will set the `cacheName` property of the\n{@link workbox-strategies} configured in `handler`.", + "type": [ + "null", + "string" + ] + }, + "expiration": { + "description": "Configuring this will add a\n{@link workbox-expiration.ExpirationPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", + "$ref": "#/definitions/ExpirationPluginOptions" + }, + "networkTimeoutSeconds": { + "description": "If provided, this will set the `networkTimeoutSeconds` property of the\n{@link workbox-strategies} configured in `handler`. Note that only\n`'NetworkFirst'` and `'NetworkOnly'` support `networkTimeoutSeconds`.", + "type": "number" + }, + "plugins": { + "description": "Configuring this allows the use of one or more Workbox plugins that\ndon't have \"shortcut\" options (like `expiration` for\n{@link workbox-expiration.ExpirationPlugin}). The plugins provided here\nwill be added to the {@link workbox-strategies} configured in `handler`.", + "type": "array", + "items": { + "$ref": "#/definitions/WorkboxPlugin" + } + }, + "precacheFallback": { + "description": "Configuring this will add a\n{@link workbox-precaching.PrecacheFallbackPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", + "type": "object", + "properties": { + "fallbackURL": { + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "fallbackURL" + ] + }, + "rangeRequests": { + "description": "Enabling this will add a\n{@link workbox-range-requests.RangeRequestsPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", + "type": "boolean" + }, + "fetchOptions": { + "description": "Configuring this will pass along the `fetchOptions` value to\nthe {@link workbox-strategies} configured in `handler`.", + "$ref": "#/definitions/RequestInit" + }, + "matchOptions": { + "description": "Configuring this will pass along the `matchOptions` value to\nthe {@link workbox-strategies} configured in `handler`.", + "$ref": "#/definitions/CacheQueryOptions" + } + }, + "additionalProperties": false + }, + "urlPattern": { + "description": "This match criteria determines whether the configured handler will\ngenerate a response for any requests that don't match one of the precached\nURLs. If multiple `RuntimeCaching` routes are defined, then the first one\nwhose `urlPattern` matches will be the one that responds.\n\nThis value directly maps to the first parameter passed to\n{@link workbox-routing.registerRoute}. It's recommended to use a\n{@link workbox-core.RouteMatchCallback} function for greatest flexibility.", + "anyOf": [ + { + "$ref": "#/definitions/RegExp" + }, + { + "$ref": "#/definitions/RouteMatchCallback" + }, + { + "type": "string" + } + ] + } + }, + "additionalProperties": false, + "required": [ + "handler", + "urlPattern" + ] + }, + "RouteHandlerCallback": {}, + "RouteHandlerObject": { + "description": "An object with a `handle` method of type `RouteHandlerCallback`.\n\nA `Route` object can be created with either an `RouteHandlerCallback`\nfunction or this `RouteHandler` object. The benefit of the `RouteHandler`\nis it can be extended (as is done by the `workbox-strategies` package).", + "type": "object", + "properties": { + "handle": { + "$ref": "#/definitions/RouteHandlerCallback" + } + }, + "additionalProperties": false, + "required": [ + "handle" + ] + }, + "QueueOptions": { + "type": "object", + "properties": { + "forceSyncFallback": { + "type": "boolean" + }, + "maxRetentionTime": { + "type": "number" + }, + "onSync": { + "$ref": "#/definitions/OnSyncCallback" + } + }, + "additionalProperties": false + }, + "OnSyncCallback": {}, + "BroadcastCacheUpdateOptions": { + "type": "object", + "properties": { + "headersToCheck": { + "type": "array", + "items": { + "type": "string" + } + }, + "generatePayload": { + "type": "object", + "additionalProperties": false + }, + "notifyAllClients": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "CacheableResponseOptions": { + "type": "object", + "properties": { + "statuses": { + "type": "array", + "items": { + "type": "number" + } + }, + "headers": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "additionalProperties": false + }, + "ExpirationPluginOptions": { + "type": "object", + "properties": { + "maxEntries": { + "type": "number" + }, + "maxAgeSeconds": { + "type": "number" + }, + "matchOptions": { + "$ref": "#/definitions/CacheQueryOptions" + }, + "purgeOnQuotaError": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "CacheQueryOptions": { + "type": "object", + "properties": { + "ignoreMethod": { + "type": "boolean" + }, + "ignoreSearch": { + "type": "boolean" + }, + "ignoreVary": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "WorkboxPlugin": { + "description": "An object with optional lifecycle callback properties for the fetch and\ncache operations.", + "type": "object", + "properties": { + "cacheDidUpdate": {}, + "cachedResponseWillBeUsed": {}, + "cacheKeyWillBeUsed": {}, + "cacheWillUpdate": {}, + "fetchDidFail": {}, + "fetchDidSucceed": {}, + "handlerDidComplete": {}, + "handlerDidError": {}, + "handlerDidRespond": {}, + "handlerWillRespond": {}, + "handlerWillStart": {}, + "requestWillFetch": {} + }, + "additionalProperties": false + }, + "CacheDidUpdateCallback": { + "type": "object", + "additionalProperties": false + }, + "CachedResponseWillBeUsedCallback": { + "type": "object", + "additionalProperties": false + }, + "CacheKeyWillBeUsedCallback": { + "type": "object", + "additionalProperties": false + }, + "CacheWillUpdateCallback": { + "type": "object", + "additionalProperties": false + }, + "FetchDidFailCallback": { + "type": "object", + "additionalProperties": false + }, + "FetchDidSucceedCallback": { + "type": "object", + "additionalProperties": false + }, + "HandlerDidCompleteCallback": { + "type": "object", + "additionalProperties": false + }, + "HandlerDidErrorCallback": { + "type": "object", + "additionalProperties": false + }, + "HandlerDidRespondCallback": { + "type": "object", + "additionalProperties": false + }, + "HandlerWillRespondCallback": { + "type": "object", + "additionalProperties": false + }, + "HandlerWillStartCallback": { + "type": "object", + "additionalProperties": false + }, + "RequestWillFetchCallback": { + "type": "object", + "additionalProperties": false + }, + "RequestInit": { + "type": "object", + "properties": { + "body": { + "anyOf": [ + { + "$ref": "#/definitions/ArrayBuffer" + }, + { + "$ref": "#/definitions/ArrayBufferView" + }, + { + "$ref": "#/definitions/ReadableStream" + }, + { + "$ref": "#/definitions/Blob" + }, + { + "$ref": "#/definitions/FormData" + }, + { + "$ref": "#/definitions/URLSearchParams" + }, + { + "type": [ + "null", + "string" + ] + } + ] + }, + "cache": { + "enum": [ + "default", + "force-cache", + "no-cache", + "no-store", + "only-if-cached", + "reload" + ], + "type": "string" + }, + "credentials": { + "enum": [ + "include", + "omit", + "same-origin" + ], + "type": "string" + }, + "headers": { + "anyOf": [ + { + "$ref": "#/definitions/Record" + }, + { + "type": "array", + "items": { + "type": "array", + "items": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "minItems": 2, + "maxItems": 2 + } + }, + { + "$ref": "#/definitions/Headers" + } + ] + }, + "integrity": { + "type": "string" + }, + "keepalive": { + "type": "boolean" + }, + "method": { + "type": "string" + }, + "mode": { + "enum": [ + "cors", + "navigate", + "no-cors", + "same-origin" + ], + "type": "string" + }, + "redirect": { + "enum": [ + "error", + "follow", + "manual" + ], + "type": "string" + }, + "referrer": { + "type": "string" + }, + "referrerPolicy": { + "enum": [ + "", + "no-referrer", + "no-referrer-when-downgrade", + "origin", + "origin-when-cross-origin", + "same-origin", + "strict-origin", + "strict-origin-when-cross-origin", + "unsafe-url" + ], + "type": "string" + }, + "signal": { + "anyOf": [ + { + "$ref": "#/definitions/AbortSignal" + }, + { + "type": "null" + } + ] + }, + "window": { + "type": "null" + } + }, + "additionalProperties": false + }, + "ArrayBuffer": { + "type": "object", + "properties": { + "byteLength": { + "type": "number" + }, + "__@toStringTag@32": { + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "__@toStringTag@32", + "byteLength" + ] + }, + "ArrayBufferView": { + "type": "object", + "properties": { + "buffer": { + "$ref": "#/definitions/ArrayBufferLike" + }, + "byteLength": { + "type": "number" + }, + "byteOffset": { + "type": "number" + } + }, + "additionalProperties": false, + "required": [ + "buffer", + "byteLength", + "byteOffset" + ] + }, + "ArrayBufferLike": { + "anyOf": [ + { + "$ref": "#/definitions/ArrayBuffer" + }, + { + "$ref": "#/definitions/SharedArrayBuffer" + } + ] + }, + "SharedArrayBuffer": { + "type": "object", + "properties": { + "byteLength": { + "type": "number" + }, + "__@species@492": { + "$ref": "#/definitions/SharedArrayBuffer" + }, + "__@toStringTag@32": { + "type": "string", + "const": "SharedArrayBuffer" + } + }, + "additionalProperties": false, + "required": [ + "__@species@492", + "__@toStringTag@32", + "byteLength" + ] + }, + "ReadableStream": { + "type": "object", + "properties": { + "locked": { + "type": "boolean" + } + }, + "additionalProperties": false, + "required": [ + "locked" + ] + }, + "Blob": { + "type": "object", + "properties": { + "size": { + "type": "number" + }, + "type": { + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "size", + "type" + ] + }, + "FormData": { + "type": "object", + "additionalProperties": false + }, + "URLSearchParams": { + "type": "object", + "properties": { + "size": { + "description": "The total number of parameter entries.", + "type": "number" + } + }, + "additionalProperties": false, + "required": [ + "size" + ] + }, + "Record": { + "type": "object", + "additionalProperties": false + }, + "Headers": { + "type": "object", + "additionalProperties": false + }, + "AbortSignal": {}, + "RouteMatchCallback": {} + }, + "$schema": "http://json-schema.org/draft-07/schema#" +} diff --git a/node_modules/workbox-build/src/schema/GetManifestOptions.json b/node_modules/workbox-build/src/schema/GetManifestOptions.json new file mode 100644 index 0000000000000000000000000000000000000000..d072599350b1011e38e0b6ded48ab26c903d4e8e --- /dev/null +++ b/node_modules/workbox-build/src/schema/GetManifestOptions.json @@ -0,0 +1,163 @@ +{ + "additionalProperties": false, + "type": "object", + "properties": { + "additionalManifestEntries": { + "description": "A list of entries to be precached, in addition to any entries that are\ngenerated as part of the build configuration.", + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/definitions/ManifestEntry" + }, + { + "type": "string" + } + ] + } + }, + "dontCacheBustURLsMatching": { + "description": "Assets that match this will be assumed to be uniquely versioned via their\nURL, and exempted from the normal HTTP cache-busting that's done when\npopulating the precache. While not required, it's recommended that if your\nexisting build process already inserts a `[hash]` value into each filename,\nyou provide a RegExp that will detect that, as it will reduce the bandwidth\nconsumed when precaching.", + "$ref": "#/definitions/RegExp" + }, + "manifestTransforms": { + "description": "One or more functions which will be applied sequentially against the\ngenerated manifest. If `modifyURLPrefix` or `dontCacheBustURLsMatching` are\nalso specified, their corresponding transformations will be applied first.", + "type": "array", + "items": {} + }, + "maximumFileSizeToCacheInBytes": { + "description": "This value can be used to determine the maximum size of files that will be\nprecached. This prevents you from inadvertently precaching very large files\nthat might have accidentally matched one of your patterns.", + "default": 2097152, + "type": "number" + }, + "modifyURLPrefix": { + "description": "An object mapping string prefixes to replacement string values. This can be\nused to, e.g., remove or add a path prefix from a manifest entry if your\nweb hosting setup doesn't match your local filesystem setup. As an\nalternative with more flexibility, you can use the `manifestTransforms`\noption and provide a function that modifies the entries in the manifest\nusing whatever logic you provide.\n\nExample usage:\n\n```\n// Replace a '/dist/' prefix with '/', and also prepend\n// '/static' to every URL.\nmodifyURLPrefix: {\n '/dist/': '/',\n '': '/static',\n}\n```", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "globFollow": { + "description": "Determines whether or not symlinks are followed when generating the\nprecache manifest. For more information, see the definition of `follow` in\nthe `glob` [documentation](https://github.com/isaacs/node-glob#options).", + "default": true, + "type": "boolean" + }, + "globIgnores": { + "description": "A set of patterns matching files to always exclude when generating the\nprecache manifest. For more information, see the definition of `ignore` in\nthe `glob` [documentation](https://github.com/isaacs/node-glob#options).", + "default": [ + "**/node_modules/**/*" + ], + "type": "array", + "items": { + "type": "string" + } + }, + "globPatterns": { + "description": "Files matching any of these patterns will be included in the precache\nmanifest. For more information, see the\n[`glob` primer](https://github.com/isaacs/node-glob#glob-primer).", + "default": [ + "**/*.{js,wasm,css,html}" + ], + "type": "array", + "items": { + "type": "string" + } + }, + "templatedURLs": { + "description": "If a URL is rendered based on some server-side logic, its contents may\ndepend on multiple files or on some other unique string value. The keys in\nthis object are server-rendered URLs. If the values are an array of\nstrings, they will be interpreted as `glob` patterns, and the contents of\nany files matching the patterns will be used to uniquely version the URL.\nIf used with a single string, it will be interpreted as unique versioning\ninformation that you've generated for a given URL.", + "type": "object", + "additionalProperties": { + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string" + } + ] + } + }, + "globDirectory": { + "description": "The local directory you wish to match `globPatterns` against. The path is\nrelative to the current directory.", + "type": "string" + } + }, + "required": [ + "globDirectory" + ], + "definitions": { + "ManifestEntry": { + "type": "object", + "properties": { + "integrity": { + "type": "string" + }, + "revision": { + "type": [ + "null", + "string" + ] + }, + "url": { + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "revision", + "url" + ] + }, + "RegExp": { + "type": "object", + "properties": { + "source": { + "type": "string" + }, + "global": { + "type": "boolean" + }, + "ignoreCase": { + "type": "boolean" + }, + "multiline": { + "type": "boolean" + }, + "lastIndex": { + "type": "number" + }, + "flags": { + "type": "string" + }, + "sticky": { + "type": "boolean" + }, + "unicode": { + "type": "boolean" + }, + "dotAll": { + "type": "boolean" + }, + "hasIndices": { + "type": "boolean" + } + }, + "additionalProperties": false, + "required": [ + "dotAll", + "flags", + "global", + "hasIndices", + "ignoreCase", + "lastIndex", + "multiline", + "source", + "sticky", + "unicode" + ] + } + }, + "$schema": "http://json-schema.org/draft-07/schema#" +} diff --git a/node_modules/workbox-build/src/schema/InjectManifestOptions.json b/node_modules/workbox-build/src/schema/InjectManifestOptions.json new file mode 100644 index 0000000000000000000000000000000000000000..2e65506bf8151b1bdfaff3b2f58397dd2b90110d --- /dev/null +++ b/node_modules/workbox-build/src/schema/InjectManifestOptions.json @@ -0,0 +1,178 @@ +{ + "additionalProperties": false, + "type": "object", + "properties": { + "additionalManifestEntries": { + "description": "A list of entries to be precached, in addition to any entries that are\ngenerated as part of the build configuration.", + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/definitions/ManifestEntry" + }, + { + "type": "string" + } + ] + } + }, + "dontCacheBustURLsMatching": { + "description": "Assets that match this will be assumed to be uniquely versioned via their\nURL, and exempted from the normal HTTP cache-busting that's done when\npopulating the precache. While not required, it's recommended that if your\nexisting build process already inserts a `[hash]` value into each filename,\nyou provide a RegExp that will detect that, as it will reduce the bandwidth\nconsumed when precaching.", + "$ref": "#/definitions/RegExp" + }, + "manifestTransforms": { + "description": "One or more functions which will be applied sequentially against the\ngenerated manifest. If `modifyURLPrefix` or `dontCacheBustURLsMatching` are\nalso specified, their corresponding transformations will be applied first.", + "type": "array", + "items": {} + }, + "maximumFileSizeToCacheInBytes": { + "description": "This value can be used to determine the maximum size of files that will be\nprecached. This prevents you from inadvertently precaching very large files\nthat might have accidentally matched one of your patterns.", + "default": 2097152, + "type": "number" + }, + "modifyURLPrefix": { + "description": "An object mapping string prefixes to replacement string values. This can be\nused to, e.g., remove or add a path prefix from a manifest entry if your\nweb hosting setup doesn't match your local filesystem setup. As an\nalternative with more flexibility, you can use the `manifestTransforms`\noption and provide a function that modifies the entries in the manifest\nusing whatever logic you provide.\n\nExample usage:\n\n```\n// Replace a '/dist/' prefix with '/', and also prepend\n// '/static' to every URL.\nmodifyURLPrefix: {\n '/dist/': '/',\n '': '/static',\n}\n```", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "globFollow": { + "description": "Determines whether or not symlinks are followed when generating the\nprecache manifest. For more information, see the definition of `follow` in\nthe `glob` [documentation](https://github.com/isaacs/node-glob#options).", + "default": true, + "type": "boolean" + }, + "globIgnores": { + "description": "A set of patterns matching files to always exclude when generating the\nprecache manifest. For more information, see the definition of `ignore` in\nthe `glob` [documentation](https://github.com/isaacs/node-glob#options).", + "default": [ + "**/node_modules/**/*" + ], + "type": "array", + "items": { + "type": "string" + } + }, + "globPatterns": { + "description": "Files matching any of these patterns will be included in the precache\nmanifest. For more information, see the\n[`glob` primer](https://github.com/isaacs/node-glob#glob-primer).", + "default": [ + "**/*.{js,wasm,css,html}" + ], + "type": "array", + "items": { + "type": "string" + } + }, + "templatedURLs": { + "description": "If a URL is rendered based on some server-side logic, its contents may\ndepend on multiple files or on some other unique string value. The keys in\nthis object are server-rendered URLs. If the values are an array of\nstrings, they will be interpreted as `glob` patterns, and the contents of\nany files matching the patterns will be used to uniquely version the URL.\nIf used with a single string, it will be interpreted as unique versioning\ninformation that you've generated for a given URL.", + "type": "object", + "additionalProperties": { + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string" + } + ] + } + }, + "injectionPoint": { + "description": "The string to find inside of the `swSrc` file. Once found, it will be\nreplaced by the generated precache manifest.", + "default": "self.__WB_MANIFEST", + "type": "string" + }, + "swSrc": { + "description": "The path and filename of the service worker file that will be read during\nthe build process, relative to the current working directory.", + "type": "string" + }, + "swDest": { + "description": "The path and filename of the service worker file that will be created by\nthe build process, relative to the current working directory. It must end\nin '.js'.", + "type": "string" + }, + "globDirectory": { + "description": "The local directory you wish to match `globPatterns` against. The path is\nrelative to the current directory.", + "type": "string" + } + }, + "required": [ + "globDirectory", + "swDest", + "swSrc" + ], + "definitions": { + "ManifestEntry": { + "type": "object", + "properties": { + "integrity": { + "type": "string" + }, + "revision": { + "type": [ + "null", + "string" + ] + }, + "url": { + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "revision", + "url" + ] + }, + "RegExp": { + "type": "object", + "properties": { + "source": { + "type": "string" + }, + "global": { + "type": "boolean" + }, + "ignoreCase": { + "type": "boolean" + }, + "multiline": { + "type": "boolean" + }, + "lastIndex": { + "type": "number" + }, + "flags": { + "type": "string" + }, + "sticky": { + "type": "boolean" + }, + "unicode": { + "type": "boolean" + }, + "dotAll": { + "type": "boolean" + }, + "hasIndices": { + "type": "boolean" + } + }, + "additionalProperties": false, + "required": [ + "dotAll", + "flags", + "global", + "hasIndices", + "ignoreCase", + "lastIndex", + "multiline", + "source", + "sticky", + "unicode" + ] + } + }, + "$schema": "http://json-schema.org/draft-07/schema#" +} diff --git a/node_modules/workbox-build/src/schema/WebpackGenerateSWOptions.json b/node_modules/workbox-build/src/schema/WebpackGenerateSWOptions.json new file mode 100644 index 0000000000000000000000000000000000000000..818f57e7be7a06d5bee3e6eb9747e42fb36d1a8b --- /dev/null +++ b/node_modules/workbox-build/src/schema/WebpackGenerateSWOptions.json @@ -0,0 +1,861 @@ +{ + "additionalProperties": false, + "type": "object", + "properties": { + "additionalManifestEntries": { + "description": "A list of entries to be precached, in addition to any entries that are\ngenerated as part of the build configuration.", + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/definitions/ManifestEntry" + }, + { + "type": "string" + } + ] + } + }, + "dontCacheBustURLsMatching": { + "description": "Assets that match this will be assumed to be uniquely versioned via their\nURL, and exempted from the normal HTTP cache-busting that's done when\npopulating the precache. While not required, it's recommended that if your\nexisting build process already inserts a `[hash]` value into each filename,\nyou provide a RegExp that will detect that, as it will reduce the bandwidth\nconsumed when precaching.", + "$ref": "#/definitions/RegExp" + }, + "manifestTransforms": { + "description": "One or more functions which will be applied sequentially against the\ngenerated manifest. If `modifyURLPrefix` or `dontCacheBustURLsMatching` are\nalso specified, their corresponding transformations will be applied first.", + "type": "array", + "items": {} + }, + "maximumFileSizeToCacheInBytes": { + "description": "This value can be used to determine the maximum size of files that will be\nprecached. This prevents you from inadvertently precaching very large files\nthat might have accidentally matched one of your patterns.", + "default": 2097152, + "type": "number" + }, + "modifyURLPrefix": { + "description": "An object mapping string prefixes to replacement string values. This can be\nused to, e.g., remove or add a path prefix from a manifest entry if your\nweb hosting setup doesn't match your local filesystem setup. As an\nalternative with more flexibility, you can use the `manifestTransforms`\noption and provide a function that modifies the entries in the manifest\nusing whatever logic you provide.\n\nExample usage:\n\n```\n// Replace a '/dist/' prefix with '/', and also prepend\n// '/static' to every URL.\nmodifyURLPrefix: {\n '/dist/': '/',\n '': '/static',\n}\n```", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "chunks": { + "description": "One or more chunk names whose corresponding output files should be included\nin the precache manifest.", + "type": "array", + "items": { + "type": "string" + } + }, + "exclude": { + "description": "One or more specifiers used to exclude assets from the precache manifest.\nThis is interpreted following\n[the same rules](https://webpack.js.org/configuration/module/#condition)\nas `webpack`'s standard `exclude` option.\nIf not provided, the default value is `[/\\.map$/, /^manifest.*\\.js$]`.", + "type": "array", + "items": {} + }, + "excludeChunks": { + "description": "One or more chunk names whose corresponding output files should be excluded\nfrom the precache manifest.", + "type": "array", + "items": { + "type": "string" + } + }, + "include": { + "description": "One or more specifiers used to include assets in the precache manifest.\nThis is interpreted following\n[the same rules](https://webpack.js.org/configuration/module/#condition)\nas `webpack`'s standard `include` option.", + "type": "array", + "items": {} + }, + "mode": { + "description": "If set to 'production', then an optimized service worker bundle that\nexcludes debugging info will be produced. If not explicitly configured\nhere, the `process.env.NODE_ENV` value will be used, and failing that, it\nwill fall back to `'production'`.", + "default": "production", + "type": [ + "null", + "string" + ] + }, + "babelPresetEnvTargets": { + "description": "The [targets](https://babeljs.io/docs/en/babel-preset-env#targets) to pass\nto `babel-preset-env` when transpiling the service worker bundle.", + "default": [ + "chrome >= 56" + ], + "type": "array", + "items": { + "type": "string" + } + }, + "cacheId": { + "description": "An optional ID to be prepended to cache names. This is primarily useful for\nlocal development where multiple sites may be served from the same\n`http://localhost:port` origin.", + "type": [ + "null", + "string" + ] + }, + "cleanupOutdatedCaches": { + "description": "Whether or not Workbox should attempt to identify and delete any precaches\ncreated by older, incompatible versions.", + "default": false, + "type": "boolean" + }, + "clientsClaim": { + "description": "Whether or not the service worker should [start controlling](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#clientsclaim)\nany existing clients as soon as it activates.", + "default": false, + "type": "boolean" + }, + "directoryIndex": { + "description": "If a navigation request for a URL ending in `/` fails to match a precached\nURL, this value will be appended to the URL and that will be checked for a\nprecache match. This should be set to what your web server is using for its\ndirectory index.", + "type": [ + "null", + "string" + ] + }, + "disableDevLogs": { + "default": false, + "type": "boolean" + }, + "ignoreURLParametersMatching": { + "description": "Any search parameter names that match against one of the RegExp in this\narray will be removed before looking for a precache match. This is useful\nif your users might request URLs that contain, for example, URL parameters\nused to track the source of the traffic. If not provided, the default value\nis `[/^utm_/, /^fbclid$/]`.", + "type": "array", + "items": { + "$ref": "#/definitions/RegExp" + } + }, + "importScripts": { + "description": "A list of JavaScript files that should be passed to\n[`importScripts()`](https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts)\ninside the generated service worker file. This is useful when you want to\nlet Workbox create your top-level service worker file, but want to include\nsome additional code, such as a push event listener.", + "type": "array", + "items": { + "type": "string" + } + }, + "inlineWorkboxRuntime": { + "description": "Whether the runtime code for the Workbox library should be included in the\ntop-level service worker, or split into a separate file that needs to be\ndeployed alongside the service worker. Keeping the runtime separate means\nthat users will not have to re-download the Workbox code each time your\ntop-level service worker changes.", + "default": false, + "type": "boolean" + }, + "navigateFallback": { + "description": "If specified, all\n[navigation requests](https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests)\nfor URLs that aren't precached will be fulfilled with the HTML at the URL\nprovided. You must pass in the URL of an HTML document that is listed in\nyour precache manifest. This is meant to be used in a Single Page App\nscenario, in which you want all navigations to use common\n[App Shell HTML](https://developers.google.com/web/fundamentals/architecture/app-shell).", + "default": null, + "type": [ + "null", + "string" + ] + }, + "navigateFallbackAllowlist": { + "description": "An optional array of regular expressions that restricts which URLs the\nconfigured `navigateFallback` behavior applies to. This is useful if only a\nsubset of your site's URLs should be treated as being part of a\n[Single Page App](https://en.wikipedia.org/wiki/Single-page_application).\nIf both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are\nconfigured, the denylist takes precedent.\n\n*Note*: These RegExps may be evaluated against every destination URL during\na navigation. Avoid using\n[complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077),\nor else your users may see delays when navigating your site.", + "type": "array", + "items": { + "$ref": "#/definitions/RegExp" + } + }, + "navigateFallbackDenylist": { + "description": "An optional array of regular expressions that restricts which URLs the\nconfigured `navigateFallback` behavior applies to. This is useful if only a\nsubset of your site's URLs should be treated as being part of a\n[Single Page App](https://en.wikipedia.org/wiki/Single-page_application).\nIf both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are\nconfigured, the denylist takes precedence.\n\n*Note*: These RegExps may be evaluated against every destination URL during\na navigation. Avoid using\n[complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077),\nor else your users may see delays when navigating your site.", + "type": "array", + "items": { + "$ref": "#/definitions/RegExp" + } + }, + "navigationPreload": { + "description": "Whether or not to enable\n[navigation preload](https://developers.google.com/web/tools/workbox/modules/workbox-navigation-preload)\nin the generated service worker. When set to true, you must also use\n`runtimeCaching` to set up an appropriate response strategy that will match\nnavigation requests, and make use of the preloaded response.", + "default": false, + "type": "boolean" + }, + "offlineGoogleAnalytics": { + "description": "Controls whether or not to include support for\n[offline Google Analytics](https://developers.google.com/web/tools/workbox/guides/enable-offline-analytics).\nWhen `true`, the call to `workbox-google-analytics`'s `initialize()` will\nbe added to your generated service worker. When set to an `Object`, that\nobject will be passed in to the `initialize()` call, allowing you to\ncustomize the behavior.", + "default": false, + "anyOf": [ + { + "$ref": "#/definitions/GoogleAnalyticsInitializeOptions" + }, + { + "type": "boolean" + } + ] + }, + "runtimeCaching": { + "description": "When using Workbox's build tools to generate your service worker, you can\nspecify one or more runtime caching configurations. These are then\ntranslated to {@link workbox-routing.registerRoute} calls using the match\nand handler configuration you define.\n\nFor all of the options, see the {@link workbox-build.RuntimeCaching}\ndocumentation. The example below shows a typical configuration, with two\nruntime routes defined:", + "type": "array", + "items": { + "$ref": "#/definitions/RuntimeCaching" + } + }, + "skipWaiting": { + "description": "Whether to add an unconditional call to [`skipWaiting()`](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#skip_the_waiting_phase)\nto the generated service worker. If `false`, then a `message` listener will\nbe added instead, allowing client pages to trigger `skipWaiting()` by\ncalling `postMessage({type: 'SKIP_WAITING'})` on a waiting service worker.", + "default": false, + "type": "boolean" + }, + "sourcemap": { + "description": "Whether to create a sourcemap for the generated service worker files.", + "default": true, + "type": "boolean" + }, + "importScriptsViaChunks": { + "description": "One or more names of webpack chunks. The content of those chunks will be\nincluded in the generated service worker, via a call to `importScripts()`.", + "type": "array", + "items": { + "type": "string" + } + }, + "swDest": { + "description": "The asset name of the service worker file created by this plugin.", + "default": "service-worker.js", + "type": "string" + } + }, + "definitions": { + "ManifestEntry": { + "type": "object", + "properties": { + "integrity": { + "type": "string" + }, + "revision": { + "type": [ + "null", + "string" + ] + }, + "url": { + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "revision", + "url" + ] + }, + "RegExp": { + "type": "object", + "properties": { + "source": { + "type": "string" + }, + "global": { + "type": "boolean" + }, + "ignoreCase": { + "type": "boolean" + }, + "multiline": { + "type": "boolean" + }, + "lastIndex": { + "type": "number" + }, + "flags": { + "type": "string" + }, + "sticky": { + "type": "boolean" + }, + "unicode": { + "type": "boolean" + }, + "dotAll": { + "type": "boolean" + }, + "hasIndices": { + "type": "boolean" + } + }, + "additionalProperties": false, + "required": [ + "dotAll", + "flags", + "global", + "hasIndices", + "ignoreCase", + "lastIndex", + "multiline", + "source", + "sticky", + "unicode" + ] + }, + "GoogleAnalyticsInitializeOptions": { + "type": "object", + "properties": { + "cacheName": { + "type": "string" + }, + "parameterOverrides": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "hitFilter": { + "type": "object", + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "RuntimeCaching": { + "type": "object", + "properties": { + "handler": { + "description": "This determines how the runtime route will generate a response.\nTo use one of the built-in {@link workbox-strategies}, provide its name,\nlike `'NetworkFirst'`.\nAlternatively, this can be a {@link workbox-core.RouteHandler} callback\nfunction with custom response logic.", + "anyOf": [ + { + "$ref": "#/definitions/RouteHandlerCallback" + }, + { + "$ref": "#/definitions/RouteHandlerObject" + }, + { + "enum": [ + "CacheFirst", + "CacheOnly", + "NetworkFirst", + "NetworkOnly", + "StaleWhileRevalidate" + ], + "type": "string" + } + ] + }, + "method": { + "description": "The HTTP method to match against. The default value of `'GET'` is normally\nsufficient, unless you explicitly need to match `'POST'`, `'PUT'`, or\nanother type of request.", + "default": "GET", + "enum": [ + "DELETE", + "GET", + "HEAD", + "PATCH", + "POST", + "PUT" + ], + "type": "string" + }, + "options": { + "type": "object", + "properties": { + "backgroundSync": { + "description": "Configuring this will add a\n{@link workbox-background-sync.BackgroundSyncPlugin} instance to the\n{@link workbox-strategies} configured in `handler`.", + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "options": { + "$ref": "#/definitions/QueueOptions" + } + }, + "additionalProperties": false, + "required": [ + "name" + ] + }, + "broadcastUpdate": { + "description": "Configuring this will add a\n{@link workbox-broadcast-update.BroadcastUpdatePlugin} instance to the\n{@link workbox-strategies} configured in `handler`.", + "type": "object", + "properties": { + "channelName": { + "type": "string" + }, + "options": { + "$ref": "#/definitions/BroadcastCacheUpdateOptions" + } + }, + "additionalProperties": false, + "required": [ + "options" + ] + }, + "cacheableResponse": { + "description": "Configuring this will add a\n{@link workbox-cacheable-response.CacheableResponsePlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", + "$ref": "#/definitions/CacheableResponseOptions" + }, + "cacheName": { + "description": "If provided, this will set the `cacheName` property of the\n{@link workbox-strategies} configured in `handler`.", + "type": [ + "null", + "string" + ] + }, + "expiration": { + "description": "Configuring this will add a\n{@link workbox-expiration.ExpirationPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", + "$ref": "#/definitions/ExpirationPluginOptions" + }, + "networkTimeoutSeconds": { + "description": "If provided, this will set the `networkTimeoutSeconds` property of the\n{@link workbox-strategies} configured in `handler`. Note that only\n`'NetworkFirst'` and `'NetworkOnly'` support `networkTimeoutSeconds`.", + "type": "number" + }, + "plugins": { + "description": "Configuring this allows the use of one or more Workbox plugins that\ndon't have \"shortcut\" options (like `expiration` for\n{@link workbox-expiration.ExpirationPlugin}). The plugins provided here\nwill be added to the {@link workbox-strategies} configured in `handler`.", + "type": "array", + "items": { + "$ref": "#/definitions/WorkboxPlugin" + } + }, + "precacheFallback": { + "description": "Configuring this will add a\n{@link workbox-precaching.PrecacheFallbackPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", + "type": "object", + "properties": { + "fallbackURL": { + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "fallbackURL" + ] + }, + "rangeRequests": { + "description": "Enabling this will add a\n{@link workbox-range-requests.RangeRequestsPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", + "type": "boolean" + }, + "fetchOptions": { + "description": "Configuring this will pass along the `fetchOptions` value to\nthe {@link workbox-strategies} configured in `handler`.", + "$ref": "#/definitions/RequestInit" + }, + "matchOptions": { + "description": "Configuring this will pass along the `matchOptions` value to\nthe {@link workbox-strategies} configured in `handler`.", + "$ref": "#/definitions/CacheQueryOptions" + } + }, + "additionalProperties": false + }, + "urlPattern": { + "description": "This match criteria determines whether the configured handler will\ngenerate a response for any requests that don't match one of the precached\nURLs. If multiple `RuntimeCaching` routes are defined, then the first one\nwhose `urlPattern` matches will be the one that responds.\n\nThis value directly maps to the first parameter passed to\n{@link workbox-routing.registerRoute}. It's recommended to use a\n{@link workbox-core.RouteMatchCallback} function for greatest flexibility.", + "anyOf": [ + { + "$ref": "#/definitions/RegExp" + }, + { + "$ref": "#/definitions/RouteMatchCallback" + }, + { + "type": "string" + } + ] + } + }, + "additionalProperties": false, + "required": [ + "handler", + "urlPattern" + ] + }, + "RouteHandlerCallback": {}, + "RouteHandlerObject": { + "description": "An object with a `handle` method of type `RouteHandlerCallback`.\n\nA `Route` object can be created with either an `RouteHandlerCallback`\nfunction or this `RouteHandler` object. The benefit of the `RouteHandler`\nis it can be extended (as is done by the `workbox-strategies` package).", + "type": "object", + "properties": { + "handle": { + "$ref": "#/definitions/RouteHandlerCallback" + } + }, + "additionalProperties": false, + "required": [ + "handle" + ] + }, + "QueueOptions": { + "type": "object", + "properties": { + "forceSyncFallback": { + "type": "boolean" + }, + "maxRetentionTime": { + "type": "number" + }, + "onSync": { + "$ref": "#/definitions/OnSyncCallback" + } + }, + "additionalProperties": false + }, + "OnSyncCallback": {}, + "BroadcastCacheUpdateOptions": { + "type": "object", + "properties": { + "headersToCheck": { + "type": "array", + "items": { + "type": "string" + } + }, + "generatePayload": { + "type": "object", + "additionalProperties": false + }, + "notifyAllClients": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "CacheableResponseOptions": { + "type": "object", + "properties": { + "statuses": { + "type": "array", + "items": { + "type": "number" + } + }, + "headers": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "additionalProperties": false + }, + "ExpirationPluginOptions": { + "type": "object", + "properties": { + "maxEntries": { + "type": "number" + }, + "maxAgeSeconds": { + "type": "number" + }, + "matchOptions": { + "$ref": "#/definitions/CacheQueryOptions" + }, + "purgeOnQuotaError": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "CacheQueryOptions": { + "type": "object", + "properties": { + "ignoreMethod": { + "type": "boolean" + }, + "ignoreSearch": { + "type": "boolean" + }, + "ignoreVary": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "WorkboxPlugin": { + "description": "An object with optional lifecycle callback properties for the fetch and\ncache operations.", + "type": "object", + "properties": { + "cacheDidUpdate": {}, + "cachedResponseWillBeUsed": {}, + "cacheKeyWillBeUsed": {}, + "cacheWillUpdate": {}, + "fetchDidFail": {}, + "fetchDidSucceed": {}, + "handlerDidComplete": {}, + "handlerDidError": {}, + "handlerDidRespond": {}, + "handlerWillRespond": {}, + "handlerWillStart": {}, + "requestWillFetch": {} + }, + "additionalProperties": false + }, + "CacheDidUpdateCallback": { + "type": "object", + "additionalProperties": false + }, + "CachedResponseWillBeUsedCallback": { + "type": "object", + "additionalProperties": false + }, + "CacheKeyWillBeUsedCallback": { + "type": "object", + "additionalProperties": false + }, + "CacheWillUpdateCallback": { + "type": "object", + "additionalProperties": false + }, + "FetchDidFailCallback": { + "type": "object", + "additionalProperties": false + }, + "FetchDidSucceedCallback": { + "type": "object", + "additionalProperties": false + }, + "HandlerDidCompleteCallback": { + "type": "object", + "additionalProperties": false + }, + "HandlerDidErrorCallback": { + "type": "object", + "additionalProperties": false + }, + "HandlerDidRespondCallback": { + "type": "object", + "additionalProperties": false + }, + "HandlerWillRespondCallback": { + "type": "object", + "additionalProperties": false + }, + "HandlerWillStartCallback": { + "type": "object", + "additionalProperties": false + }, + "RequestWillFetchCallback": { + "type": "object", + "additionalProperties": false + }, + "RequestInit": { + "type": "object", + "properties": { + "body": { + "anyOf": [ + { + "$ref": "#/definitions/ArrayBuffer" + }, + { + "$ref": "#/definitions/ArrayBufferView" + }, + { + "$ref": "#/definitions/ReadableStream" + }, + { + "$ref": "#/definitions/Blob" + }, + { + "$ref": "#/definitions/FormData" + }, + { + "$ref": "#/definitions/URLSearchParams" + }, + { + "type": [ + "null", + "string" + ] + } + ] + }, + "cache": { + "enum": [ + "default", + "force-cache", + "no-cache", + "no-store", + "only-if-cached", + "reload" + ], + "type": "string" + }, + "credentials": { + "enum": [ + "include", + "omit", + "same-origin" + ], + "type": "string" + }, + "headers": { + "anyOf": [ + { + "$ref": "#/definitions/Record" + }, + { + "type": "array", + "items": { + "type": "array", + "items": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "minItems": 2, + "maxItems": 2 + } + }, + { + "$ref": "#/definitions/Headers" + } + ] + }, + "integrity": { + "type": "string" + }, + "keepalive": { + "type": "boolean" + }, + "method": { + "type": "string" + }, + "mode": { + "enum": [ + "cors", + "navigate", + "no-cors", + "same-origin" + ], + "type": "string" + }, + "redirect": { + "enum": [ + "error", + "follow", + "manual" + ], + "type": "string" + }, + "referrer": { + "type": "string" + }, + "referrerPolicy": { + "enum": [ + "", + "no-referrer", + "no-referrer-when-downgrade", + "origin", + "origin-when-cross-origin", + "same-origin", + "strict-origin", + "strict-origin-when-cross-origin", + "unsafe-url" + ], + "type": "string" + }, + "signal": { + "anyOf": [ + { + "$ref": "#/definitions/AbortSignal" + }, + { + "type": "null" + } + ] + }, + "window": { + "type": "null" + } + }, + "additionalProperties": false + }, + "ArrayBuffer": { + "type": "object", + "properties": { + "byteLength": { + "type": "number" + }, + "__@toStringTag@32": { + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "__@toStringTag@32", + "byteLength" + ] + }, + "ArrayBufferView": { + "type": "object", + "properties": { + "buffer": { + "$ref": "#/definitions/ArrayBufferLike" + }, + "byteLength": { + "type": "number" + }, + "byteOffset": { + "type": "number" + } + }, + "additionalProperties": false, + "required": [ + "buffer", + "byteLength", + "byteOffset" + ] + }, + "ArrayBufferLike": { + "anyOf": [ + { + "$ref": "#/definitions/ArrayBuffer" + }, + { + "$ref": "#/definitions/SharedArrayBuffer" + } + ] + }, + "SharedArrayBuffer": { + "type": "object", + "properties": { + "byteLength": { + "type": "number" + }, + "__@species@492": { + "$ref": "#/definitions/SharedArrayBuffer" + }, + "__@toStringTag@32": { + "type": "string", + "const": "SharedArrayBuffer" + } + }, + "additionalProperties": false, + "required": [ + "__@species@492", + "__@toStringTag@32", + "byteLength" + ] + }, + "ReadableStream": { + "type": "object", + "properties": { + "locked": { + "type": "boolean" + } + }, + "additionalProperties": false, + "required": [ + "locked" + ] + }, + "Blob": { + "type": "object", + "properties": { + "size": { + "type": "number" + }, + "type": { + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "size", + "type" + ] + }, + "FormData": { + "type": "object", + "additionalProperties": false + }, + "URLSearchParams": { + "type": "object", + "properties": { + "size": { + "description": "The total number of parameter entries.", + "type": "number" + } + }, + "additionalProperties": false, + "required": [ + "size" + ] + }, + "Record": { + "type": "object", + "additionalProperties": false + }, + "Headers": { + "type": "object", + "additionalProperties": false + }, + "AbortSignal": {}, + "RouteMatchCallback": {} + }, + "$schema": "http://json-schema.org/draft-07/schema#" +} diff --git a/node_modules/workbox-build/src/schema/WebpackInjectManifestOptions.json b/node_modules/workbox-build/src/schema/WebpackInjectManifestOptions.json new file mode 100644 index 0000000000000000000000000000000000000000..01c6967335c2a8e98e5b09afea0f2f4d886a6e1b --- /dev/null +++ b/node_modules/workbox-build/src/schema/WebpackInjectManifestOptions.json @@ -0,0 +1,171 @@ +{ + "additionalProperties": false, + "type": "object", + "properties": { + "additionalManifestEntries": { + "description": "A list of entries to be precached, in addition to any entries that are\ngenerated as part of the build configuration.", + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/definitions/ManifestEntry" + }, + { + "type": "string" + } + ] + } + }, + "dontCacheBustURLsMatching": { + "description": "Assets that match this will be assumed to be uniquely versioned via their\nURL, and exempted from the normal HTTP cache-busting that's done when\npopulating the precache. While not required, it's recommended that if your\nexisting build process already inserts a `[hash]` value into each filename,\nyou provide a RegExp that will detect that, as it will reduce the bandwidth\nconsumed when precaching.", + "$ref": "#/definitions/RegExp" + }, + "manifestTransforms": { + "description": "One or more functions which will be applied sequentially against the\ngenerated manifest. If `modifyURLPrefix` or `dontCacheBustURLsMatching` are\nalso specified, their corresponding transformations will be applied first.", + "type": "array", + "items": {} + }, + "maximumFileSizeToCacheInBytes": { + "description": "This value can be used to determine the maximum size of files that will be\nprecached. This prevents you from inadvertently precaching very large files\nthat might have accidentally matched one of your patterns.", + "default": 2097152, + "type": "number" + }, + "modifyURLPrefix": { + "description": "An object mapping string prefixes to replacement string values. This can be\nused to, e.g., remove or add a path prefix from a manifest entry if your\nweb hosting setup doesn't match your local filesystem setup. As an\nalternative with more flexibility, you can use the `manifestTransforms`\noption and provide a function that modifies the entries in the manifest\nusing whatever logic you provide.\n\nExample usage:\n\n```\n// Replace a '/dist/' prefix with '/', and also prepend\n// '/static' to every URL.\nmodifyURLPrefix: {\n '/dist/': '/',\n '': '/static',\n}\n```", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "chunks": { + "description": "One or more chunk names whose corresponding output files should be included\nin the precache manifest.", + "type": "array", + "items": { + "type": "string" + } + }, + "exclude": { + "description": "One or more specifiers used to exclude assets from the precache manifest.\nThis is interpreted following\n[the same rules](https://webpack.js.org/configuration/module/#condition)\nas `webpack`'s standard `exclude` option.\nIf not provided, the default value is `[/\\.map$/, /^manifest.*\\.js$]`.", + "type": "array", + "items": {} + }, + "excludeChunks": { + "description": "One or more chunk names whose corresponding output files should be excluded\nfrom the precache manifest.", + "type": "array", + "items": { + "type": "string" + } + }, + "include": { + "description": "One or more specifiers used to include assets in the precache manifest.\nThis is interpreted following\n[the same rules](https://webpack.js.org/configuration/module/#condition)\nas `webpack`'s standard `include` option.", + "type": "array", + "items": {} + }, + "mode": { + "description": "If set to 'production', then an optimized service worker bundle that\nexcludes debugging info will be produced. If not explicitly configured\nhere, the `mode` value configured in the current `webpack` compilation\nwill be used.", + "type": [ + "null", + "string" + ] + }, + "injectionPoint": { + "description": "The string to find inside of the `swSrc` file. Once found, it will be\nreplaced by the generated precache manifest.", + "default": "self.__WB_MANIFEST", + "type": "string" + }, + "swSrc": { + "description": "The path and filename of the service worker file that will be read during\nthe build process, relative to the current working directory.", + "type": "string" + }, + "compileSrc": { + "description": "When `true` (the default), the `swSrc` file will be compiled by webpack.\nWhen `false`, compilation will not occur (and `webpackCompilationPlugins`\ncan't be used.) Set to `false` if you want to inject the manifest into,\ne.g., a JSON file.", + "default": true, + "type": "boolean" + }, + "swDest": { + "description": "The asset name of the service worker file that will be created by this\nplugin. If omitted, the name will be based on the `swSrc` name.", + "type": "string" + }, + "webpackCompilationPlugins": { + "description": "Optional `webpack` plugins that will be used when compiling the `swSrc`\ninput file. Only valid if `compileSrc` is `true`.", + "type": "array", + "items": {} + } + }, + "required": [ + "swSrc" + ], + "definitions": { + "ManifestEntry": { + "type": "object", + "properties": { + "integrity": { + "type": "string" + }, + "revision": { + "type": [ + "null", + "string" + ] + }, + "url": { + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "revision", + "url" + ] + }, + "RegExp": { + "type": "object", + "properties": { + "source": { + "type": "string" + }, + "global": { + "type": "boolean" + }, + "ignoreCase": { + "type": "boolean" + }, + "multiline": { + "type": "boolean" + }, + "lastIndex": { + "type": "number" + }, + "flags": { + "type": "string" + }, + "sticky": { + "type": "boolean" + }, + "unicode": { + "type": "boolean" + }, + "dotAll": { + "type": "boolean" + }, + "hasIndices": { + "type": "boolean" + } + }, + "additionalProperties": false, + "required": [ + "dotAll", + "flags", + "global", + "hasIndices", + "ignoreCase", + "lastIndex", + "multiline", + "source", + "sticky", + "unicode" + ] + } + }, + "$schema": "http://json-schema.org/draft-07/schema#" +} diff --git a/node_modules/workbox-build/src/strip-comments.d.ts b/node_modules/workbox-build/src/strip-comments.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3d681f453c5d460d4771e9036a21ab8a233da9f8 --- /dev/null +++ b/node_modules/workbox-build/src/strip-comments.d.ts @@ -0,0 +1 @@ +declare module 'strip-comments'; diff --git a/node_modules/workbox-build/src/templates/sw-template.ts b/node_modules/workbox-build/src/templates/sw-template.ts new file mode 100644 index 0000000000000000000000000000000000000000..dacfaef89be7cc0405526bd5f93271ca91a3aa81 --- /dev/null +++ b/node_modules/workbox-build/src/templates/sw-template.ts @@ -0,0 +1,60 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +export const swTemplate = `/** + * Welcome to your Workbox-powered service worker! + * + * You'll need to register this file in your web app. + * See https://goo.gl/nhQhGp + * + * The rest of the code is auto-generated. Please don't update this file + * directly; instead, make changes to your Workbox build configuration + * and re-run your build process. + * See https://goo.gl/2aRDsh + */ + +<% if (importScripts) { %> +importScripts( + <%= importScripts.map(JSON.stringify).join(',\\n ') %> +); +<% } %> + +<% if (navigationPreload) { %><%= use('workbox-navigation-preload', 'enable') %>();<% } %> + +<% if (cacheId) { %><%= use('workbox-core', 'setCacheNameDetails') %>({prefix: <%= JSON.stringify(cacheId) %>});<% } %> + +<% if (skipWaiting) { %> +self.skipWaiting(); +<% } else { %> +self.addEventListener('message', (event) => { + if (event.data && event.data.type === 'SKIP_WAITING') { + self.skipWaiting(); + } +}); +<% } %> +<% if (clientsClaim) { %><%= use('workbox-core', 'clientsClaim') %>();<% } %> + +<% if (Array.isArray(manifestEntries) && manifestEntries.length > 0) {%> +/** + * The precacheAndRoute() method efficiently caches and responds to + * requests for URLs in the manifest. + * See https://goo.gl/S9QRab + */ +<%= use('workbox-precaching', 'precacheAndRoute') %>(<%= JSON.stringify(manifestEntries, null, 2) %>, <%= precacheOptionsString %>); +<% if (cleanupOutdatedCaches) { %><%= use('workbox-precaching', 'cleanupOutdatedCaches') %>();<% } %> +<% if (navigateFallback) { %><%= use('workbox-routing', 'registerRoute') %>(new <%= use('workbox-routing', 'NavigationRoute') %>(<%= use('workbox-precaching', 'createHandlerBoundToURL') %>(<%= JSON.stringify(navigateFallback) %>)<% if (navigateFallbackAllowlist || navigateFallbackDenylist) { %>, { + <% if (navigateFallbackAllowlist) { %>allowlist: [<%= navigateFallbackAllowlist %>],<% } %> + <% if (navigateFallbackDenylist) { %>denylist: [<%= navigateFallbackDenylist %>],<% } %> +}<% } %>));<% } %> +<% } %> + +<% if (runtimeCaching) { runtimeCaching.forEach(runtimeCachingString => {%><%= runtimeCachingString %><% });} %> + +<% if (offlineAnalyticsConfigString) { %><%= use('workbox-google-analytics', 'initialize') %>(<%= offlineAnalyticsConfigString %>);<% } %> + +<% if (disableDevLogs) { %>self.__WB_DISABLE_DEV_LOGS = true;<% } %>`; diff --git a/node_modules/workbox-build/src/types.ts b/node_modules/workbox-build/src/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..36e9d4800fdacf52da1759a68d8db47dfa8cac65 --- /dev/null +++ b/node_modules/workbox-build/src/types.ts @@ -0,0 +1,584 @@ +import {PackageJson} from 'type-fest'; + +import {BroadcastCacheUpdateOptions} from 'workbox-broadcast-update/BroadcastCacheUpdate'; +import {GoogleAnalyticsInitializeOptions} from 'workbox-google-analytics/initialize'; +import {HTTPMethod} from 'workbox-routing/utils/constants'; +import {QueueOptions} from 'workbox-background-sync/Queue'; +import {RouteHandler, RouteMatchCallback} from 'workbox-core/types'; +import {CacheableResponseOptions} from 'workbox-cacheable-response/CacheableResponse'; +import {ExpirationPluginOptions} from 'workbox-expiration/ExpirationPlugin'; +import {WorkboxPlugin} from 'workbox-core/types'; + +export interface ManifestEntry { + integrity?: string; + revision: string | null; + url: string; +} + +export type StrategyName = + | 'CacheFirst' + | 'CacheOnly' + | 'NetworkFirst' + | 'NetworkOnly' + | 'StaleWhileRevalidate'; + +export interface RuntimeCaching { + /** + * This determines how the runtime route will generate a response. + * To use one of the built-in {@link workbox-strategies}, provide its name, + * like `'NetworkFirst'`. + * Alternatively, this can be a {@link workbox-core.RouteHandler} callback + * function with custom response logic. + */ + handler: RouteHandler | StrategyName; + /** + * The HTTP method to match against. The default value of `'GET'` is normally + * sufficient, unless you explicitly need to match `'POST'`, `'PUT'`, or + * another type of request. + * @default "GET" + */ + method?: HTTPMethod; + options?: { + /** + * Configuring this will add a + * {@link workbox-background-sync.BackgroundSyncPlugin} instance to the + * {@link workbox-strategies} configured in `handler`. + */ + backgroundSync?: { + name: string; + options?: QueueOptions; + }; + /** + * Configuring this will add a + * {@link workbox-broadcast-update.BroadcastUpdatePlugin} instance to the + * {@link workbox-strategies} configured in `handler`. + */ + broadcastUpdate?: { + // TODO: This option is ignored since we switched to using postMessage(). + // Remove it in the next major release. + channelName?: string; + options: BroadcastCacheUpdateOptions; + }; + /** + * Configuring this will add a + * {@link workbox-cacheable-response.CacheableResponsePlugin} instance to + * the {@link workbox-strategies} configured in `handler`. + */ + cacheableResponse?: CacheableResponseOptions; + /** + * If provided, this will set the `cacheName` property of the + * {@link workbox-strategies} configured in `handler`. + */ + cacheName?: string | null; + /** + * Configuring this will add a + * {@link workbox-expiration.ExpirationPlugin} instance to + * the {@link workbox-strategies} configured in `handler`. + */ + expiration?: ExpirationPluginOptions; + /** + * If provided, this will set the `networkTimeoutSeconds` property of the + * {@link workbox-strategies} configured in `handler`. Note that only + * `'NetworkFirst'` and `'NetworkOnly'` support `networkTimeoutSeconds`. + */ + networkTimeoutSeconds?: number; + /** + * Configuring this allows the use of one or more Workbox plugins that + * don't have "shortcut" options (like `expiration` for + * {@link workbox-expiration.ExpirationPlugin}). The plugins provided here + * will be added to the {@link workbox-strategies} configured in `handler`. + */ + plugins?: Array; + /** + * Configuring this will add a + * {@link workbox-precaching.PrecacheFallbackPlugin} instance to + * the {@link workbox-strategies} configured in `handler`. + */ + precacheFallback?: { + fallbackURL: string; + }; + /** + * Enabling this will add a + * {@link workbox-range-requests.RangeRequestsPlugin} instance to + * the {@link workbox-strategies} configured in `handler`. + */ + rangeRequests?: boolean; + /** + * Configuring this will pass along the `fetchOptions` value to + * the {@link workbox-strategies} configured in `handler`. + */ + fetchOptions?: RequestInit; + /** + * Configuring this will pass along the `matchOptions` value to + * the {@link workbox-strategies} configured in `handler`. + */ + matchOptions?: CacheQueryOptions; + }; + /** + * This match criteria determines whether the configured handler will + * generate a response for any requests that don't match one of the precached + * URLs. If multiple `RuntimeCaching` routes are defined, then the first one + * whose `urlPattern` matches will be the one that responds. + * + * This value directly maps to the first parameter passed to + * {@link workbox-routing.registerRoute}. It's recommended to use a + * {@link workbox-core.RouteMatchCallback} function for greatest flexibility. + */ + urlPattern: RegExp | string | RouteMatchCallback; +} + +export interface ManifestTransformResult { + manifest: Array; + warnings?: Array; +} + +export type ManifestTransform = ( + manifestEntries: Array, + compilation?: unknown, +) => Promise | ManifestTransformResult; + +export interface BasePartial { + /** + * A list of entries to be precached, in addition to any entries that are + * generated as part of the build configuration. + */ + additionalManifestEntries?: Array; + /** + * Assets that match this will be assumed to be uniquely versioned via their + * URL, and exempted from the normal HTTP cache-busting that's done when + * populating the precache. While not required, it's recommended that if your + * existing build process already inserts a `[hash]` value into each filename, + * you provide a RegExp that will detect that, as it will reduce the bandwidth + * consumed when precaching. + */ + dontCacheBustURLsMatching?: RegExp; + /** + * One or more functions which will be applied sequentially against the + * generated manifest. If `modifyURLPrefix` or `dontCacheBustURLsMatching` are + * also specified, their corresponding transformations will be applied first. + */ + manifestTransforms?: Array; + /** + * This value can be used to determine the maximum size of files that will be + * precached. This prevents you from inadvertently precaching very large files + * that might have accidentally matched one of your patterns. + * @default 2097152 + */ + maximumFileSizeToCacheInBytes?: number; + /** + * An object mapping string prefixes to replacement string values. This can be + * used to, e.g., remove or add a path prefix from a manifest entry if your + * web hosting setup doesn't match your local filesystem setup. As an + * alternative with more flexibility, you can use the `manifestTransforms` + * option and provide a function that modifies the entries in the manifest + * using whatever logic you provide. + * + * Example usage: + * + * ``` + * // Replace a '/dist/' prefix with '/', and also prepend + * // '/static' to every URL. + * modifyURLPrefix: { + * '/dist/': '/', + * '': '/static', + * } + * ``` + */ + modifyURLPrefix?: { + [key: string]: string; + }; +} + +export interface GeneratePartial { + /** + * The [targets](https://babeljs.io/docs/en/babel-preset-env#targets) to pass + * to `babel-preset-env` when transpiling the service worker bundle. + * @default ["chrome >= 56"] + */ + babelPresetEnvTargets?: Array; + /** + * An optional ID to be prepended to cache names. This is primarily useful for + * local development where multiple sites may be served from the same + * `http://localhost:port` origin. + */ + cacheId?: string | null; + /** + * Whether or not Workbox should attempt to identify and delete any precaches + * created by older, incompatible versions. + * @default false + */ + cleanupOutdatedCaches?: boolean; + /** + * Whether or not the service worker should [start controlling](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#clientsclaim) + * any existing clients as soon as it activates. + * @default false + */ + clientsClaim?: boolean; + /** + * If a navigation request for a URL ending in `/` fails to match a precached + * URL, this value will be appended to the URL and that will be checked for a + * precache match. This should be set to what your web server is using for its + * directory index. + */ + directoryIndex?: string | null; + /** + * @default false + */ + disableDevLogs?: boolean; + // We can't use the @default annotation here to assign the value via AJV, as + // an Array can't be serialized into JSON. + /** + * Any search parameter names that match against one of the RegExp in this + * array will be removed before looking for a precache match. This is useful + * if your users might request URLs that contain, for example, URL parameters + * used to track the source of the traffic. If not provided, the default value + * is `[/^utm_/, /^fbclid$/]`. + * + */ + ignoreURLParametersMatching?: Array; + /** + * A list of JavaScript files that should be passed to + * [`importScripts()`](https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts) + * inside the generated service worker file. This is useful when you want to + * let Workbox create your top-level service worker file, but want to include + * some additional code, such as a push event listener. + */ + importScripts?: Array; + /** + * Whether the runtime code for the Workbox library should be included in the + * top-level service worker, or split into a separate file that needs to be + * deployed alongside the service worker. Keeping the runtime separate means + * that users will not have to re-download the Workbox code each time your + * top-level service worker changes. + * @default false + */ + inlineWorkboxRuntime?: boolean; + /** + * If set to 'production', then an optimized service worker bundle that + * excludes debugging info will be produced. If not explicitly configured + * here, the `process.env.NODE_ENV` value will be used, and failing that, it + * will fall back to `'production'`. + * @default "production" + */ + mode?: string | null; + /** + * If specified, all + * [navigation requests](https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests) + * for URLs that aren't precached will be fulfilled with the HTML at the URL + * provided. You must pass in the URL of an HTML document that is listed in + * your precache manifest. This is meant to be used in a Single Page App + * scenario, in which you want all navigations to use common + * [App Shell HTML](https://developers.google.com/web/fundamentals/architecture/app-shell). + * @default null + */ + navigateFallback?: string | null; + /** + * An optional array of regular expressions that restricts which URLs the + * configured `navigateFallback` behavior applies to. This is useful if only a + * subset of your site's URLs should be treated as being part of a + * [Single Page App](https://en.wikipedia.org/wiki/Single-page_application). + * If both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are + * configured, the denylist takes precedent. + * + * *Note*: These RegExps may be evaluated against every destination URL during + * a navigation. Avoid using + * [complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077), + * or else your users may see delays when navigating your site. + */ + navigateFallbackAllowlist?: Array; + /** + * An optional array of regular expressions that restricts which URLs the + * configured `navigateFallback` behavior applies to. This is useful if only a + * subset of your site's URLs should be treated as being part of a + * [Single Page App](https://en.wikipedia.org/wiki/Single-page_application). + * If both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are + * configured, the denylist takes precedence. + * + * *Note*: These RegExps may be evaluated against every destination URL during + * a navigation. Avoid using + * [complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077), + * or else your users may see delays when navigating your site. + */ + navigateFallbackDenylist?: Array; + /** + * Whether or not to enable + * [navigation preload](https://developers.google.com/web/tools/workbox/modules/workbox-navigation-preload) + * in the generated service worker. When set to true, you must also use + * `runtimeCaching` to set up an appropriate response strategy that will match + * navigation requests, and make use of the preloaded response. + * @default false + */ + navigationPreload?: boolean; + /** + * Controls whether or not to include support for + * [offline Google Analytics](https://developers.google.com/web/tools/workbox/guides/enable-offline-analytics). + * When `true`, the call to `workbox-google-analytics`'s `initialize()` will + * be added to your generated service worker. When set to an `Object`, that + * object will be passed in to the `initialize()` call, allowing you to + * customize the behavior. + * @default false + */ + offlineGoogleAnalytics?: boolean | GoogleAnalyticsInitializeOptions; + /** + * When using Workbox's build tools to generate your service worker, you can + * specify one or more runtime caching configurations. These are then + * translated to {@link workbox-routing.registerRoute} calls using the match + * and handler configuration you define. + * + * For all of the options, see the {@link workbox-build.RuntimeCaching} + * documentation. The example below shows a typical configuration, with two + * runtime routes defined: + * + * @example + * runtimeCaching: [{ + * urlPattern: ({url}) => url.origin === 'https://api.example.com', + * handler: 'NetworkFirst', + * options: { + * cacheName: 'api-cache', + * }, + * }, { + * urlPattern: ({request}) => request.destination === 'image', + * handler: 'StaleWhileRevalidate', + * options: { + * cacheName: 'images-cache', + * expiration: { + * maxEntries: 10, + * }, + * }, + * }] + */ + runtimeCaching?: Array; + /** + * Whether to add an unconditional call to [`skipWaiting()`](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#skip_the_waiting_phase) + * to the generated service worker. If `false`, then a `message` listener will + * be added instead, allowing client pages to trigger `skipWaiting()` by + * calling `postMessage({type: 'SKIP_WAITING'})` on a waiting service worker. + * @default false + */ + skipWaiting?: boolean; + /** + * Whether to create a sourcemap for the generated service worker files. + * @default true + */ + sourcemap?: boolean; +} + +// This needs to be set when using GetManifest or InjectManifest, but is +// optional when using GenerateSW if runtimeCaching is also used. This is +// enforced via runtime validation, and needs to be documented. +export interface RequiredGlobDirectoryPartial { + /** + * The local directory you wish to match `globPatterns` against. The path is + * relative to the current directory. + */ + globDirectory: string; +} + +export interface OptionalGlobDirectoryPartial { + /** + * The local directory you wish to match `globPatterns` against. The path is + * relative to the current directory. + */ + globDirectory?: string; +} + +export interface GlobPartial { + /** + * Determines whether or not symlinks are followed when generating the + * precache manifest. For more information, see the definition of `follow` in + * the `glob` [documentation](https://github.com/isaacs/node-glob#options). + * @default true + */ + globFollow?: boolean; + /** + * A set of patterns matching files to always exclude when generating the + * precache manifest. For more information, see the definition of `ignore` in + * the `glob` [documentation](https://github.com/isaacs/node-glob#options). + * @default ["**\/node_modules\/**\/*"] + */ + globIgnores?: Array; + /** + * Files matching any of these patterns will be included in the precache + * manifest. For more information, see the + * [`glob` primer](https://github.com/isaacs/node-glob#glob-primer). + * @default ["**\/*.{js,wasm,css,html}"] + */ + globPatterns?: Array; + /** + * If a URL is rendered based on some server-side logic, its contents may + * depend on multiple files or on some other unique string value. The keys in + * this object are server-rendered URLs. If the values are an array of + * strings, they will be interpreted as `glob` patterns, and the contents of + * any files matching the patterns will be used to uniquely version the URL. + * If used with a single string, it will be interpreted as unique versioning + * information that you've generated for a given URL. + */ + templatedURLs?: { + [key: string]: string | Array; + }; +} + +export interface InjectPartial { + /** + * The string to find inside of the `swSrc` file. Once found, it will be + * replaced by the generated precache manifest. + * @default "self.__WB_MANIFEST" + */ + injectionPoint?: string; + /** + * The path and filename of the service worker file that will be read during + * the build process, relative to the current working directory. + */ + swSrc: string; +} + +export interface WebpackPartial { + /** + * One or more chunk names whose corresponding output files should be included + * in the precache manifest. + */ + chunks?: Array; + // We can't use the @default annotation here to assign the value via AJV, as + // an Array can't be serialized into JSON. + // The default value of [/\.map$/, /^manifest.*\.js$/] will be assigned by + // the validation function, and we need to reflect that in the docs. + /** + * One or more specifiers used to exclude assets from the precache manifest. + * This is interpreted following + * [the same rules](https://webpack.js.org/configuration/module/#condition) + * as `webpack`'s standard `exclude` option. + * If not provided, the default value is `[/\.map$/, /^manifest.*\.js$]`. + */ + //eslint-disable-next-line @typescript-eslint/ban-types + exclude?: Array boolean)>; + /** + * One or more chunk names whose corresponding output files should be excluded + * from the precache manifest. + */ + excludeChunks?: Array; + /** + * One or more specifiers used to include assets in the precache manifest. + * This is interpreted following + * [the same rules](https://webpack.js.org/configuration/module/#condition) + * as `webpack`'s standard `include` option. + */ + //eslint-disable-next-line @typescript-eslint/ban-types + include?: Array boolean)>; + /** + * If set to 'production', then an optimized service worker bundle that + * excludes debugging info will be produced. If not explicitly configured + * here, the `mode` value configured in the current `webpack` compilation + * will be used. + */ + mode?: string | null; +} + +export interface RequiredSWDestPartial { + /** + * The path and filename of the service worker file that will be created by + * the build process, relative to the current working directory. It must end + * in '.js'. + */ + swDest: string; +} + +export interface WebpackGenerateSWPartial { + /** + * One or more names of webpack chunks. The content of those chunks will be + * included in the generated service worker, via a call to `importScripts()`. + */ + importScriptsViaChunks?: Array; + /** + * The asset name of the service worker file created by this plugin. + * @default "service-worker.js" + */ + swDest?: string; +} + +export interface WebpackInjectManifestPartial { + /** + * When `true` (the default), the `swSrc` file will be compiled by webpack. + * When `false`, compilation will not occur (and `webpackCompilationPlugins` + * can't be used.) Set to `false` if you want to inject the manifest into, + * e.g., a JSON file. + * @default true + */ + compileSrc?: boolean; + // This doesn't have a hardcoded default value; instead, the default will be + // set at runtime to the swSrc basename, with the hardcoded extension .js. + /** + * The asset name of the service worker file that will be created by this + * plugin. If omitted, the name will be based on the `swSrc` name. + */ + swDest?: string; + // This can only be set if compileSrc is true, but that restriction can't be + // represented in TypeScript. It's enforced via custom runtime validation + // logic and needs to be documented. + /** + * Optional `webpack` plugins that will be used when compiling the `swSrc` + * input file. Only valid if `compileSrc` is `true`. + */ + webpackCompilationPlugins?: Array; +} + +export type GenerateSWOptions = BasePartial & + GlobPartial & + GeneratePartial & + RequiredSWDestPartial & + OptionalGlobDirectoryPartial; + +export type GetManifestOptions = BasePartial & + GlobPartial & + RequiredGlobDirectoryPartial; + +export type InjectManifestOptions = BasePartial & + GlobPartial & + InjectPartial & + RequiredSWDestPartial & + RequiredGlobDirectoryPartial; + +export type WebpackGenerateSWOptions = BasePartial & + WebpackPartial & + GeneratePartial & + WebpackGenerateSWPartial; + +export type WebpackInjectManifestOptions = BasePartial & + WebpackPartial & + InjectPartial & + WebpackInjectManifestPartial; + +export interface GetManifestResult { + count: number; + manifestEntries: Array; + size: number; + warnings: Array; +} + +export type BuildResult = Omit & { + filePaths: Array; +}; + +/** + * @private + */ +export interface FileDetails { + file: string; + hash: string; + size: number; +} + +/** + * @private + */ +export type BuildType = 'dev' | 'prod'; + +/** + * @private + */ +export interface WorkboxPackageJSON extends PackageJson { + workbox?: { + browserNamespace?: string; + packageType?: string; + prodOnly?: boolean; + }; +} diff --git a/node_modules/workbox-build/tsconfig.json b/node_modules/workbox-build/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..ade16ea7c704f07d278ba0660671f7de1f00e489 --- /dev/null +++ b/node_modules/workbox-build/tsconfig.json @@ -0,0 +1,23 @@ +{ + "extends": "../../tsconfig", + "compilerOptions": { + "composite": true, + "esModuleInterop": true, + "module": "CommonJS", + "outDir": "./build", + "resolveJsonModule": true, + "rootDir": "./src", + "target": "ES2018", + "tsBuildInfoFile": "./tsconfig.tsbuildinfo" + }, + "files": ["src/cdn-details.json"], + "include": ["src/**/*.ts", "src/schema/*.json"], + "references": [ + {"path": "../workbox-background-sync/"}, + {"path": "../workbox-broadcast-update/"}, + {"path": "../workbox-cacheable-response/"}, + {"path": "../workbox-core/"}, + {"path": "../workbox-expiration/"}, + {"path": "../workbox-google-analytics/"} + ] +} diff --git a/node_modules/workbox-cacheable-response/CacheableResponse.d.ts b/node_modules/workbox-cacheable-response/CacheableResponse.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a08cb13b53013702dd1cdd87535748cca23487bb --- /dev/null +++ b/node_modules/workbox-cacheable-response/CacheableResponse.d.ts @@ -0,0 +1,45 @@ +import './_version.js'; +export interface CacheableResponseOptions { + statuses?: number[]; + headers?: { + [headerName: string]: string; + }; +} +/** + * This class allows you to set up rules determining what + * status codes and/or headers need to be present in order for a + * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) + * to be considered cacheable. + * + * @memberof workbox-cacheable-response + */ +declare class CacheableResponse { + private readonly _statuses?; + private readonly _headers?; + /** + * To construct a new CacheableResponse instance you must provide at least + * one of the `config` properties. + * + * If both `statuses` and `headers` are specified, then both conditions must + * be met for the `Response` to be considered cacheable. + * + * @param {Object} config + * @param {Array} [config.statuses] One or more status codes that a + * `Response` can have and be considered cacheable. + * @param {Object} [config.headers] A mapping of header names + * and expected values that a `Response` can have and be considered cacheable. + * If multiple headers are provided, only one needs to be present. + */ + constructor(config?: CacheableResponseOptions); + /** + * Checks a response to see whether it's cacheable or not, based on this + * object's configuration. + * + * @param {Response} response The response whose cacheability is being + * checked. + * @return {boolean} `true` if the `Response` is cacheable, and `false` + * otherwise. + */ + isResponseCacheable(response: Response): boolean; +} +export { CacheableResponse }; diff --git a/node_modules/workbox-cacheable-response/CacheableResponse.js b/node_modules/workbox-cacheable-response/CacheableResponse.js new file mode 100644 index 0000000000000000000000000000000000000000..dcc3bfb6a2842b22d3fa42c79cf877d6c608873d --- /dev/null +++ b/node_modules/workbox-cacheable-response/CacheableResponse.js @@ -0,0 +1,119 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { assert } from 'workbox-core/_private/assert.js'; +import { WorkboxError } from 'workbox-core/_private/WorkboxError.js'; +import { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js'; +import { logger } from 'workbox-core/_private/logger.js'; +import './_version.js'; +/** + * This class allows you to set up rules determining what + * status codes and/or headers need to be present in order for a + * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) + * to be considered cacheable. + * + * @memberof workbox-cacheable-response + */ +class CacheableResponse { + /** + * To construct a new CacheableResponse instance you must provide at least + * one of the `config` properties. + * + * If both `statuses` and `headers` are specified, then both conditions must + * be met for the `Response` to be considered cacheable. + * + * @param {Object} config + * @param {Array} [config.statuses] One or more status codes that a + * `Response` can have and be considered cacheable. + * @param {Object} [config.headers] A mapping of header names + * and expected values that a `Response` can have and be considered cacheable. + * If multiple headers are provided, only one needs to be present. + */ + constructor(config = {}) { + if (process.env.NODE_ENV !== 'production') { + if (!(config.statuses || config.headers)) { + throw new WorkboxError('statuses-or-headers-required', { + moduleName: 'workbox-cacheable-response', + className: 'CacheableResponse', + funcName: 'constructor', + }); + } + if (config.statuses) { + assert.isArray(config.statuses, { + moduleName: 'workbox-cacheable-response', + className: 'CacheableResponse', + funcName: 'constructor', + paramName: 'config.statuses', + }); + } + if (config.headers) { + assert.isType(config.headers, 'object', { + moduleName: 'workbox-cacheable-response', + className: 'CacheableResponse', + funcName: 'constructor', + paramName: 'config.headers', + }); + } + } + this._statuses = config.statuses; + this._headers = config.headers; + } + /** + * Checks a response to see whether it's cacheable or not, based on this + * object's configuration. + * + * @param {Response} response The response whose cacheability is being + * checked. + * @return {boolean} `true` if the `Response` is cacheable, and `false` + * otherwise. + */ + isResponseCacheable(response) { + if (process.env.NODE_ENV !== 'production') { + assert.isInstance(response, Response, { + moduleName: 'workbox-cacheable-response', + className: 'CacheableResponse', + funcName: 'isResponseCacheable', + paramName: 'response', + }); + } + let cacheable = true; + if (this._statuses) { + cacheable = this._statuses.includes(response.status); + } + if (this._headers && cacheable) { + cacheable = Object.keys(this._headers).some((headerName) => { + return response.headers.get(headerName) === this._headers[headerName]; + }); + } + if (process.env.NODE_ENV !== 'production') { + if (!cacheable) { + logger.groupCollapsed(`The request for ` + + `'${getFriendlyURL(response.url)}' returned a response that does ` + + `not meet the criteria for being cached.`); + logger.groupCollapsed(`View cacheability criteria here.`); + logger.log(`Cacheable statuses: ` + JSON.stringify(this._statuses)); + logger.log(`Cacheable headers: ` + JSON.stringify(this._headers, null, 2)); + logger.groupEnd(); + const logFriendlyHeaders = {}; + response.headers.forEach((value, key) => { + logFriendlyHeaders[key] = value; + }); + logger.groupCollapsed(`View response status and headers here.`); + logger.log(`Response status: ${response.status}`); + logger.log(`Response headers: ` + JSON.stringify(logFriendlyHeaders, null, 2)); + logger.groupEnd(); + logger.groupCollapsed(`View full response details here.`); + logger.log(response.headers); + logger.log(response); + logger.groupEnd(); + logger.groupEnd(); + } + } + return cacheable; + } +} +export { CacheableResponse }; diff --git a/node_modules/workbox-cacheable-response/CacheableResponse.mjs b/node_modules/workbox-cacheable-response/CacheableResponse.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ead6373906fc98b2201ea4b8eb7be62e4623e6d9 --- /dev/null +++ b/node_modules/workbox-cacheable-response/CacheableResponse.mjs @@ -0,0 +1 @@ +export * from './CacheableResponse.js'; \ No newline at end of file diff --git a/node_modules/workbox-cacheable-response/CacheableResponsePlugin.d.ts b/node_modules/workbox-cacheable-response/CacheableResponsePlugin.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5eb998583cee482e936dae9919900906241daa76 --- /dev/null +++ b/node_modules/workbox-cacheable-response/CacheableResponsePlugin.d.ts @@ -0,0 +1,36 @@ +import { WorkboxPlugin } from 'workbox-core/types.js'; +import { CacheableResponseOptions } from './CacheableResponse.js'; +import './_version.js'; +/** + * A class implementing the `cacheWillUpdate` lifecycle callback. This makes it + * easier to add in cacheability checks to requests made via Workbox's built-in + * strategies. + * + * @memberof workbox-cacheable-response + */ +declare class CacheableResponsePlugin implements WorkboxPlugin { + private readonly _cacheableResponse; + /** + * To construct a new CacheableResponsePlugin instance you must provide at + * least one of the `config` properties. + * + * If both `statuses` and `headers` are specified, then both conditions must + * be met for the `Response` to be considered cacheable. + * + * @param {Object} config + * @param {Array} [config.statuses] One or more status codes that a + * `Response` can have and be considered cacheable. + * @param {Object} [config.headers] A mapping of header names + * and expected values that a `Response` can have and be considered cacheable. + * If multiple headers are provided, only one needs to be present. + */ + constructor(config: CacheableResponseOptions); + /** + * @param {Object} options + * @param {Response} options.response + * @return {Response|null} + * @private + */ + cacheWillUpdate: WorkboxPlugin['cacheWillUpdate']; +} +export { CacheableResponsePlugin }; diff --git a/node_modules/workbox-cacheable-response/CacheableResponsePlugin.js b/node_modules/workbox-cacheable-response/CacheableResponsePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..695f9fb3c2c9ae8f35c26742901a5a3b86f82aeb --- /dev/null +++ b/node_modules/workbox-cacheable-response/CacheableResponsePlugin.js @@ -0,0 +1,48 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { CacheableResponse, } from './CacheableResponse.js'; +import './_version.js'; +/** + * A class implementing the `cacheWillUpdate` lifecycle callback. This makes it + * easier to add in cacheability checks to requests made via Workbox's built-in + * strategies. + * + * @memberof workbox-cacheable-response + */ +class CacheableResponsePlugin { + /** + * To construct a new CacheableResponsePlugin instance you must provide at + * least one of the `config` properties. + * + * If both `statuses` and `headers` are specified, then both conditions must + * be met for the `Response` to be considered cacheable. + * + * @param {Object} config + * @param {Array} [config.statuses] One or more status codes that a + * `Response` can have and be considered cacheable. + * @param {Object} [config.headers] A mapping of header names + * and expected values that a `Response` can have and be considered cacheable. + * If multiple headers are provided, only one needs to be present. + */ + constructor(config) { + /** + * @param {Object} options + * @param {Response} options.response + * @return {Response|null} + * @private + */ + this.cacheWillUpdate = async ({ response }) => { + if (this._cacheableResponse.isResponseCacheable(response)) { + return response; + } + return null; + }; + this._cacheableResponse = new CacheableResponse(config); + } +} +export { CacheableResponsePlugin }; diff --git a/node_modules/workbox-cacheable-response/CacheableResponsePlugin.mjs b/node_modules/workbox-cacheable-response/CacheableResponsePlugin.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d2c521840125c45c2ea8d7cdea9a9f0e762b5f6c --- /dev/null +++ b/node_modules/workbox-cacheable-response/CacheableResponsePlugin.mjs @@ -0,0 +1 @@ +export * from './CacheableResponsePlugin.js'; \ No newline at end of file diff --git a/node_modules/workbox-cacheable-response/LICENSE b/node_modules/workbox-cacheable-response/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..845b545fd0f5031a944cda8cf9018eb066500040 --- /dev/null +++ b/node_modules/workbox-cacheable-response/LICENSE @@ -0,0 +1,19 @@ +Copyright 2018 Google LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/workbox-cacheable-response/README.md b/node_modules/workbox-cacheable-response/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5a4dbdca7459d095c26fdeff2617579676c80b7f --- /dev/null +++ b/node_modules/workbox-cacheable-response/README.md @@ -0,0 +1 @@ +This module's documentation can be found at https://developers.google.com/web/tools/workbox/modules/workbox-cacheable-response diff --git a/node_modules/workbox-cacheable-response/_version.d.ts b/node_modules/workbox-cacheable-response/_version.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/workbox-cacheable-response/_version.js b/node_modules/workbox-cacheable-response/_version.js new file mode 100644 index 0000000000000000000000000000000000000000..9944ea576c398e3c9fa1c52b79feb9e93a923f79 --- /dev/null +++ b/node_modules/workbox-cacheable-response/_version.js @@ -0,0 +1,6 @@ +"use strict"; +// @ts-ignore +try { + self['workbox:cacheable-response:7.4.0'] && _(); +} +catch (e) { } diff --git a/node_modules/workbox-cacheable-response/_version.mjs b/node_modules/workbox-cacheable-response/_version.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c8b0398d8e01d84fa263140b895bed8ada45ab19 --- /dev/null +++ b/node_modules/workbox-cacheable-response/_version.mjs @@ -0,0 +1 @@ +try{self['workbox:cacheable-response:7.4.1']&&_()}catch(e){}// eslint-disable-line \ No newline at end of file diff --git a/node_modules/workbox-cacheable-response/build/workbox-cacheable-response.dev.js b/node_modules/workbox-cacheable-response/build/workbox-cacheable-response.dev.js new file mode 100644 index 0000000000000000000000000000000000000000..f2d2f9ff81dbbf4a467ee371cf69ade3bdd81953 --- /dev/null +++ b/node_modules/workbox-cacheable-response/build/workbox-cacheable-response.dev.js @@ -0,0 +1,176 @@ +this.workbox = this.workbox || {}; +this.workbox.cacheableResponse = (function (exports, assert_js, WorkboxError_js, getFriendlyURL_js, logger_js) { + 'use strict'; + + // @ts-ignore + try { + self['workbox:cacheable-response:7.4.0'] && _(); + } catch (e) {} + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * This class allows you to set up rules determining what + * status codes and/or headers need to be present in order for a + * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) + * to be considered cacheable. + * + * @memberof workbox-cacheable-response + */ + class CacheableResponse { + /** + * To construct a new CacheableResponse instance you must provide at least + * one of the `config` properties. + * + * If both `statuses` and `headers` are specified, then both conditions must + * be met for the `Response` to be considered cacheable. + * + * @param {Object} config + * @param {Array} [config.statuses] One or more status codes that a + * `Response` can have and be considered cacheable. + * @param {Object} [config.headers] A mapping of header names + * and expected values that a `Response` can have and be considered cacheable. + * If multiple headers are provided, only one needs to be present. + */ + constructor(config = {}) { + { + if (!(config.statuses || config.headers)) { + throw new WorkboxError_js.WorkboxError('statuses-or-headers-required', { + moduleName: 'workbox-cacheable-response', + className: 'CacheableResponse', + funcName: 'constructor' + }); + } + if (config.statuses) { + assert_js.assert.isArray(config.statuses, { + moduleName: 'workbox-cacheable-response', + className: 'CacheableResponse', + funcName: 'constructor', + paramName: 'config.statuses' + }); + } + if (config.headers) { + assert_js.assert.isType(config.headers, 'object', { + moduleName: 'workbox-cacheable-response', + className: 'CacheableResponse', + funcName: 'constructor', + paramName: 'config.headers' + }); + } + } + this._statuses = config.statuses; + this._headers = config.headers; + } + /** + * Checks a response to see whether it's cacheable or not, based on this + * object's configuration. + * + * @param {Response} response The response whose cacheability is being + * checked. + * @return {boolean} `true` if the `Response` is cacheable, and `false` + * otherwise. + */ + isResponseCacheable(response) { + { + assert_js.assert.isInstance(response, Response, { + moduleName: 'workbox-cacheable-response', + className: 'CacheableResponse', + funcName: 'isResponseCacheable', + paramName: 'response' + }); + } + let cacheable = true; + if (this._statuses) { + cacheable = this._statuses.includes(response.status); + } + if (this._headers && cacheable) { + cacheable = Object.keys(this._headers).some(headerName => { + return response.headers.get(headerName) === this._headers[headerName]; + }); + } + { + if (!cacheable) { + logger_js.logger.groupCollapsed(`The request for ` + `'${getFriendlyURL_js.getFriendlyURL(response.url)}' returned a response that does ` + `not meet the criteria for being cached.`); + logger_js.logger.groupCollapsed(`View cacheability criteria here.`); + logger_js.logger.log(`Cacheable statuses: ` + JSON.stringify(this._statuses)); + logger_js.logger.log(`Cacheable headers: ` + JSON.stringify(this._headers, null, 2)); + logger_js.logger.groupEnd(); + const logFriendlyHeaders = {}; + response.headers.forEach((value, key) => { + logFriendlyHeaders[key] = value; + }); + logger_js.logger.groupCollapsed(`View response status and headers here.`); + logger_js.logger.log(`Response status: ${response.status}`); + logger_js.logger.log(`Response headers: ` + JSON.stringify(logFriendlyHeaders, null, 2)); + logger_js.logger.groupEnd(); + logger_js.logger.groupCollapsed(`View full response details here.`); + logger_js.logger.log(response.headers); + logger_js.logger.log(response); + logger_js.logger.groupEnd(); + logger_js.logger.groupEnd(); + } + } + return cacheable; + } + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * A class implementing the `cacheWillUpdate` lifecycle callback. This makes it + * easier to add in cacheability checks to requests made via Workbox's built-in + * strategies. + * + * @memberof workbox-cacheable-response + */ + class CacheableResponsePlugin { + /** + * To construct a new CacheableResponsePlugin instance you must provide at + * least one of the `config` properties. + * + * If both `statuses` and `headers` are specified, then both conditions must + * be met for the `Response` to be considered cacheable. + * + * @param {Object} config + * @param {Array} [config.statuses] One or more status codes that a + * `Response` can have and be considered cacheable. + * @param {Object} [config.headers] A mapping of header names + * and expected values that a `Response` can have and be considered cacheable. + * If multiple headers are provided, only one needs to be present. + */ + constructor(config) { + /** + * @param {Object} options + * @param {Response} options.response + * @return {Response|null} + * @private + */ + this.cacheWillUpdate = async ({ + response + }) => { + if (this._cacheableResponse.isResponseCacheable(response)) { + return response; + } + return null; + }; + this._cacheableResponse = new CacheableResponse(config); + } + } + + exports.CacheableResponse = CacheableResponse; + exports.CacheableResponsePlugin = CacheableResponsePlugin; + + return exports; + +})({}, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private); +//# sourceMappingURL=workbox-cacheable-response.dev.js.map diff --git a/node_modules/workbox-cacheable-response/build/workbox-cacheable-response.dev.js.map b/node_modules/workbox-cacheable-response/build/workbox-cacheable-response.dev.js.map new file mode 100644 index 0000000000000000000000000000000000000000..7c0b6516eb5f5c031bb8217f93b4195a6ebe76fd --- /dev/null +++ b/node_modules/workbox-cacheable-response/build/workbox-cacheable-response.dev.js.map @@ -0,0 +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:7.4.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 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} [config.statuses] One or more status codes that a\n * `Response` can have and be considered cacheable.\n * @param {Object} [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: ` + JSON.stringify(this._statuses));\n logger.log(`Cacheable headers: ` + 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: ` + 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 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} [config.statuses] One or more status codes that a\n * `Response` can have and be considered cacheable.\n * @param {Object} [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":";;;;IACA;IACA,IAAI;IACAA,EAAAA,IAAI,CAAC,kCAAkC,CAAC,IAAIC,CAAC,EAAE;IACnD,CAAC,CACD,OAAOC,CAAC,EAAE,CAAE;;ICLZ;IACA;;IAEA;IACA;IACA;IACA;IAMA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,MAAMC,iBAAiB,CAAC;IACpB;IACJ;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACIC,EAAAA,WAAWA,CAACC,MAAM,GAAG,EAAE,EAAE;IACrB,IAA2C;UACvC,IAAI,EAAEA,MAAM,CAACC,QAAQ,IAAID,MAAM,CAACE,OAAO,CAAC,EAAE;IACtC,QAAA,MAAM,IAAIC,4BAAY,CAAC,8BAA8B,EAAE;IACnDC,UAAAA,UAAU,EAAE,4BAA4B;IACxCC,UAAAA,SAAS,EAAE,mBAAmB;IAC9BC,UAAAA,QAAQ,EAAE;IACd,SAAC,CAAC;IACN,MAAA;UACA,IAAIN,MAAM,CAACC,QAAQ,EAAE;I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,EAAE,CAAC,CAAC,CAAC;YAC9ER,gBAAM,CAACO,QAAQ,EAAE;IACjBP,QAAAA,gBAAM,CAACC,cAAc,CAAE,CAAA,gCAAA,CAAiC,CAAC;IACzDD,QAAAA,gBAAM,CAACI,GAAG,CAACf,QAAQ,CAACZ,OAAO,CAAC;IAC5BuB,QAAAA,gBAAM,CAACI,GAAG,CAACf,QAAQ,CAAC;YACpBW,gBAAM,CAACO,QAAQ,EAAE;YACjBP,gBAAM,CAACO,QAAQ,EAAE;IACrB,MAAA;IACJ,IAAA;IACA,IAAA,OAAOf,SAAS;IACpB,EAAA;IACJ;;ICrHA;IACA;;IAEA;IACA;IACA;IACA;IAGA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,MAAMoB,uBAAuB,CAAC;IAC1B;IACJ;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;MACItC,WAAWA,CAACC,MAAM,EAAE;IAChB;IACR;IACA;IACA;IACA;IACA;QACQ,IAAI,CAACsC,eAAe,GAAG,OAAO;IAAExB,MAAAA;IAAS,KAAC,KAAK;UAC3C,IAAI,IAAI,CAACyB,kBAAkB,CAAC1B,mBAAmB,CAACC,QAAQ,CAAC,EAAE;IACvD,QAAA,OAAOA,QAAQ;IACnB,MAAA;IACA,MAAA,OAAO,IAAI;QACf,CAAC;IACD,IAAA,IAAI,CAACyB,kBAAkB,GAAG,IAAIzC,iBAAiB,CAACE,MAAM,CAAC;IAC3D,EAAA;IACJ;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/workbox-cacheable-response/build/workbox-cacheable-response.prod.js b/node_modules/workbox-cacheable-response/build/workbox-cacheable-response.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..7cea515d24c0673498c93e3c4f2c0fe159de6594 --- /dev/null +++ b/node_modules/workbox-cacheable-response/build/workbox-cacheable-response.prod.js @@ -0,0 +1,2 @@ +this.workbox=this.workbox||{},this.workbox.cacheableResponse=function(s){"use strict";try{self["workbox:cacheable-response:7.4.0"]&&_()}catch(s){}class t{constructor(s={}){this.ss=s.statuses,this.ts=s.headers}isResponseCacheable(s){let t=!0;return this.ss&&(t=this.ss.includes(s.status)),this.ts&&t&&(t=Object.keys(this.ts).some((t=>s.headers.get(t)===this.ts[t]))),t}}return s.CacheableResponse=t,s.CacheableResponsePlugin=class{constructor(s){this.cacheWillUpdate=async({response:s})=>this.hs.isResponseCacheable(s)?s:null,this.hs=new t(s)}},s}({}); +//# sourceMappingURL=workbox-cacheable-response.prod.js.map diff --git a/node_modules/workbox-cacheable-response/build/workbox-cacheable-response.prod.js.map b/node_modules/workbox-cacheable-response/build/workbox-cacheable-response.prod.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d19f92b807165576a31145a1a4f136b476367b27 --- /dev/null +++ b/node_modules/workbox-cacheable-response/build/workbox-cacheable-response.prod.js.map @@ -0,0 +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:7.4.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 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} [config.statuses] One or more status codes that a\n * `Response` can have and be considered cacheable.\n * @param {Object} [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: ` + JSON.stringify(this._statuses));\n logger.log(`Cacheable headers: ` + 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: ` + 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 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} [config.statuses] One or more status codes that a\n * `Response` can have and be considered cacheable.\n * @param {Object} [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","this","_statuses","statuses","_headers","headers","isResponseCacheable","response","cacheable","includes","status","Object","keys","some","headerName","get","cacheWillUpdate","async","_cacheableResponse"],"mappings":"sFAEA,IACIA,KAAK,qCAAuCC,GAChD,CACA,MAAOC,GAAK,CCeZ,MAAMC,EAeFC,YAAYC,EAAS,IA0BjBC,KAAKC,GAAYF,EAAOG,SACxBF,KAAKG,GAAWJ,EAAOK,OAC3B,CAUAC,oBAAoBC,GAShB,IAAIC,GAAY,EAiChB,OAhCIP,KAAKC,KACLM,EAAYP,KAAKC,GAAUO,SAASF,EAASG,SAE7CT,KAAKG,IAAYI,IACjBA,EAAYG,OAAOC,KAAKX,KAAKG,IAAUS,MAAMC,GAClCP,EAASF,QAAQU,IAAID,KAAgBb,KAAKG,GAASU,MA2B3DN,CACX,yDCpGJ,MAeIT,YAAYC,GAORC,KAAKe,gBAAkBC,OAASV,cACxBN,KAAKiB,GAAmBZ,oBAAoBC,GACrCA,EAEJ,KAEXN,KAAKiB,GAAqB,IAAIpB,EAAkBE,EACpD"} \ No newline at end of file diff --git a/node_modules/workbox-cacheable-response/index.d.ts b/node_modules/workbox-cacheable-response/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c8da5b7b6deb02845dd0e9c5f94829742f6eb6d6 --- /dev/null +++ b/node_modules/workbox-cacheable-response/index.d.ts @@ -0,0 +1,7 @@ +import { CacheableResponse, CacheableResponseOptions } from './CacheableResponse.js'; +import { CacheableResponsePlugin } from './CacheableResponsePlugin.js'; +import './_version.js'; +/** + * @module workbox-cacheable-response + */ +export { CacheableResponse, CacheableResponseOptions, CacheableResponsePlugin }; diff --git a/node_modules/workbox-cacheable-response/index.js b/node_modules/workbox-cacheable-response/index.js new file mode 100644 index 0000000000000000000000000000000000000000..67361df1179f20894c68b0a36c5a6ea103054316 --- /dev/null +++ b/node_modules/workbox-cacheable-response/index.js @@ -0,0 +1,14 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { CacheableResponse, } from './CacheableResponse.js'; +import { CacheableResponsePlugin } from './CacheableResponsePlugin.js'; +import './_version.js'; +/** + * @module workbox-cacheable-response + */ +export { CacheableResponse, CacheableResponsePlugin }; diff --git a/node_modules/workbox-cacheable-response/index.mjs b/node_modules/workbox-cacheable-response/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..833b6a2f3226fec78490a3b7a622dc5146f94b53 --- /dev/null +++ b/node_modules/workbox-cacheable-response/index.mjs @@ -0,0 +1 @@ +export * from './index.js'; \ No newline at end of file diff --git a/node_modules/workbox-cacheable-response/package.json b/node_modules/workbox-cacheable-response/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1e1c4cf39ba6f68d5fde21145e2876fe9df026c7 --- /dev/null +++ b/node_modules/workbox-cacheable-response/package.json @@ -0,0 +1,31 @@ +{ + "name": "workbox-cacheable-response", + "version": "7.4.1", + "license": "MIT", + "author": "Google's Web DevRel Team and Google's Aurora Team", + "description": "This library takes a Response object and determines whether it's cacheable based on a specific configuration.", + "repository": { + "type": "git", + "url": "git+https://github.com/googlechrome/workbox.git" + }, + "bugs": "https://github.com/googlechrome/workbox/issues", + "homepage": "https://github.com/GoogleChrome/workbox", + "keywords": [ + "workbox", + "workboxjs", + "service worker", + "sw", + "workbox-plugin" + ], + "workbox": { + "browserNamespace": "workbox.cacheableResponse", + "packageType": "sw" + }, + "main": "index.js", + "module": "index.mjs", + "types": "index.d.ts", + "dependencies": { + "workbox-core": "7.4.1" + }, + "gitHead": "62b9d8ba8eb3c1a2ab8aac9d84c90cda7865d6a3" +} diff --git a/node_modules/workbox-cacheable-response/src/CacheableResponse.ts b/node_modules/workbox-cacheable-response/src/CacheableResponse.ts new file mode 100644 index 0000000000000000000000000000000000000000..f33cef9319df2f3e29079682132d0d00f5d38ccf --- /dev/null +++ b/node_modules/workbox-cacheable-response/src/CacheableResponse.ts @@ -0,0 +1,150 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {assert} from 'workbox-core/_private/assert.js'; +import {WorkboxError} from 'workbox-core/_private/WorkboxError.js'; +import {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.js'; +import {logger} from 'workbox-core/_private/logger.js'; +import './_version.js'; + +export interface CacheableResponseOptions { + statuses?: number[]; + headers?: {[headerName: string]: string}; +} + +/** + * This class allows you to set up rules determining what + * status codes and/or headers need to be present in order for a + * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) + * to be considered cacheable. + * + * @memberof workbox-cacheable-response + */ +class CacheableResponse { + private readonly _statuses?: CacheableResponseOptions['statuses']; + private readonly _headers?: CacheableResponseOptions['headers']; + + /** + * To construct a new CacheableResponse instance you must provide at least + * one of the `config` properties. + * + * If both `statuses` and `headers` are specified, then both conditions must + * be met for the `Response` to be considered cacheable. + * + * @param {Object} config + * @param {Array} [config.statuses] One or more status codes that a + * `Response` can have and be considered cacheable. + * @param {Object} [config.headers] A mapping of header names + * and expected values that a `Response` can have and be considered cacheable. + * If multiple headers are provided, only one needs to be present. + */ + constructor(config: CacheableResponseOptions = {}) { + if (process.env.NODE_ENV !== 'production') { + if (!(config.statuses || config.headers)) { + throw new WorkboxError('statuses-or-headers-required', { + moduleName: 'workbox-cacheable-response', + className: 'CacheableResponse', + funcName: 'constructor', + }); + } + + if (config.statuses) { + assert!.isArray(config.statuses, { + moduleName: 'workbox-cacheable-response', + className: 'CacheableResponse', + funcName: 'constructor', + paramName: 'config.statuses', + }); + } + + if (config.headers) { + assert!.isType(config.headers, 'object', { + moduleName: 'workbox-cacheable-response', + className: 'CacheableResponse', + funcName: 'constructor', + paramName: 'config.headers', + }); + } + } + + this._statuses = config.statuses; + this._headers = config.headers; + } + + /** + * Checks a response to see whether it's cacheable or not, based on this + * object's configuration. + * + * @param {Response} response The response whose cacheability is being + * checked. + * @return {boolean} `true` if the `Response` is cacheable, and `false` + * otherwise. + */ + isResponseCacheable(response: Response): boolean { + if (process.env.NODE_ENV !== 'production') { + assert!.isInstance(response, Response, { + moduleName: 'workbox-cacheable-response', + className: 'CacheableResponse', + funcName: 'isResponseCacheable', + paramName: 'response', + }); + } + + let cacheable = true; + + if (this._statuses) { + cacheable = this._statuses.includes(response.status); + } + + if (this._headers && cacheable) { + cacheable = Object.keys(this._headers).some((headerName) => { + return response.headers.get(headerName) === this._headers![headerName]; + }); + } + + if (process.env.NODE_ENV !== 'production') { + if (!cacheable) { + logger.groupCollapsed( + `The request for ` + + `'${getFriendlyURL(response.url)}' returned a response that does ` + + `not meet the criteria for being cached.`, + ); + + logger.groupCollapsed(`View cacheability criteria here.`); + logger.log(`Cacheable statuses: ` + JSON.stringify(this._statuses)); + logger.log( + `Cacheable headers: ` + JSON.stringify(this._headers, null, 2), + ); + logger.groupEnd(); + + const logFriendlyHeaders: {[key: string]: string} = {}; + response.headers.forEach((value, key) => { + logFriendlyHeaders[key] = value; + }); + + logger.groupCollapsed(`View response status and headers here.`); + logger.log(`Response status: ${response.status}`); + logger.log( + `Response headers: ` + JSON.stringify(logFriendlyHeaders, null, 2), + ); + logger.groupEnd(); + + logger.groupCollapsed(`View full response details here.`); + logger.log(response.headers); + logger.log(response); + logger.groupEnd(); + + logger.groupEnd(); + } + } + + return cacheable; + } +} + +export {CacheableResponse}; diff --git a/node_modules/workbox-cacheable-response/src/CacheableResponsePlugin.ts b/node_modules/workbox-cacheable-response/src/CacheableResponsePlugin.ts new file mode 100644 index 0000000000000000000000000000000000000000..ea82becda461ead026202f77db29ed1732cb9d68 --- /dev/null +++ b/node_modules/workbox-cacheable-response/src/CacheableResponsePlugin.ts @@ -0,0 +1,58 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {WorkboxPlugin} from 'workbox-core/types.js'; +import { + CacheableResponse, + CacheableResponseOptions, +} from './CacheableResponse.js'; +import './_version.js'; + +/** + * A class implementing the `cacheWillUpdate` lifecycle callback. This makes it + * easier to add in cacheability checks to requests made via Workbox's built-in + * strategies. + * + * @memberof workbox-cacheable-response + */ +class CacheableResponsePlugin implements WorkboxPlugin { + private readonly _cacheableResponse: CacheableResponse; + + /** + * To construct a new CacheableResponsePlugin instance you must provide at + * least one of the `config` properties. + * + * If both `statuses` and `headers` are specified, then both conditions must + * be met for the `Response` to be considered cacheable. + * + * @param {Object} config + * @param {Array} [config.statuses] One or more status codes that a + * `Response` can have and be considered cacheable. + * @param {Object} [config.headers] A mapping of header names + * and expected values that a `Response` can have and be considered cacheable. + * If multiple headers are provided, only one needs to be present. + */ + constructor(config: CacheableResponseOptions) { + this._cacheableResponse = new CacheableResponse(config); + } + + /** + * @param {Object} options + * @param {Response} options.response + * @return {Response|null} + * @private + */ + cacheWillUpdate: WorkboxPlugin['cacheWillUpdate'] = async ({response}) => { + if (this._cacheableResponse.isResponseCacheable(response)) { + return response; + } + return null; + }; +} + +export {CacheableResponsePlugin}; diff --git a/node_modules/workbox-cacheable-response/src/_version.ts b/node_modules/workbox-cacheable-response/src/_version.ts new file mode 100644 index 0000000000000000000000000000000000000000..91800248682acda1bb4aecaca10ddc8be337444e --- /dev/null +++ b/node_modules/workbox-cacheable-response/src/_version.ts @@ -0,0 +1,2 @@ +// @ts-ignore +try{self['workbox:cacheable-response:7.4.1']&&_()}catch(e){} \ No newline at end of file diff --git a/node_modules/workbox-cacheable-response/src/index.ts b/node_modules/workbox-cacheable-response/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..365728ca26f59ad7e124bde1e5658623941e76cb --- /dev/null +++ b/node_modules/workbox-cacheable-response/src/index.ts @@ -0,0 +1,21 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import { + CacheableResponse, + CacheableResponseOptions, +} from './CacheableResponse.js'; +import {CacheableResponsePlugin} from './CacheableResponsePlugin.js'; + +import './_version.js'; + +/** + * @module workbox-cacheable-response + */ + +export {CacheableResponse, CacheableResponseOptions, CacheableResponsePlugin}; diff --git a/node_modules/workbox-cacheable-response/tsconfig.json b/node_modules/workbox-cacheable-response/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..3bb2772b586c4d0ceee3d014e64dba7aafbdd570 --- /dev/null +++ b/node_modules/workbox-cacheable-response/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tsconfig", + "compilerOptions": { + "composite": true, + "outDir": "./", + "rootDir": "./src", + "tsBuildInfoFile": "./tsconfig.tsbuildinfo" + }, + "include": ["src/**/*.ts"], + "references": [{"path": "../workbox-core/"}] +} diff --git a/node_modules/workbox-core/LICENSE b/node_modules/workbox-core/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..845b545fd0f5031a944cda8cf9018eb066500040 --- /dev/null +++ b/node_modules/workbox-core/LICENSE @@ -0,0 +1,19 @@ +Copyright 2018 Google LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/workbox-core/README.md b/node_modules/workbox-core/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0cd4cfea663e20a6758e920241fd505b9a5ee53e --- /dev/null +++ b/node_modules/workbox-core/README.md @@ -0,0 +1 @@ +This module's documentation can be found at https://developers.google.com/web/tools/workbox/modules/workbox-core diff --git a/node_modules/workbox-core/_private.d.ts b/node_modules/workbox-core/_private.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bd2cf9a1d2a89400fe9afe184444c0bd54c038f5 --- /dev/null +++ b/node_modules/workbox-core/_private.d.ts @@ -0,0 +1,16 @@ +import { assert } from './_private/assert.js'; +import { cacheNames } from './_private/cacheNames.js'; +import { cacheMatchIgnoreParams } from './_private/cacheMatchIgnoreParams.js'; +import { canConstructReadableStream } from './_private/canConstructReadableStream.js'; +import { canConstructResponseFromBodyStream } from './_private/canConstructResponseFromBodyStream.js'; +import { dontWaitFor } from './_private/dontWaitFor.js'; +import { Deferred } from './_private/Deferred.js'; +import { executeQuotaErrorCallbacks } from './_private/executeQuotaErrorCallbacks.js'; +import { getFriendlyURL } from './_private/getFriendlyURL.js'; +import { logger } from './_private/logger.js'; +import { resultingClientExists } from './_private/resultingClientExists.js'; +import { timeout } from './_private/timeout.js'; +import { waitUntil } from './_private/waitUntil.js'; +import { WorkboxError } from './_private/WorkboxError.js'; +import './_version.js'; +export { assert, cacheMatchIgnoreParams, cacheNames, canConstructReadableStream, canConstructResponseFromBodyStream, dontWaitFor, Deferred, executeQuotaErrorCallbacks, getFriendlyURL, logger, resultingClientExists, timeout, waitUntil, WorkboxError, }; diff --git a/node_modules/workbox-core/_private.js b/node_modules/workbox-core/_private.js new file mode 100644 index 0000000000000000000000000000000000000000..10d62445f3d599c527a558449d012bc7dfe22348 --- /dev/null +++ b/node_modules/workbox-core/_private.js @@ -0,0 +1,24 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +// We either expose defaults or we expose every named export. +import { assert } from './_private/assert.js'; +import { cacheNames } from './_private/cacheNames.js'; +import { cacheMatchIgnoreParams } from './_private/cacheMatchIgnoreParams.js'; +import { canConstructReadableStream } from './_private/canConstructReadableStream.js'; +import { canConstructResponseFromBodyStream } from './_private/canConstructResponseFromBodyStream.js'; +import { dontWaitFor } from './_private/dontWaitFor.js'; +import { Deferred } from './_private/Deferred.js'; +import { executeQuotaErrorCallbacks } from './_private/executeQuotaErrorCallbacks.js'; +import { getFriendlyURL } from './_private/getFriendlyURL.js'; +import { logger } from './_private/logger.js'; +import { resultingClientExists } from './_private/resultingClientExists.js'; +import { timeout } from './_private/timeout.js'; +import { waitUntil } from './_private/waitUntil.js'; +import { WorkboxError } from './_private/WorkboxError.js'; +import './_version.js'; +export { assert, cacheMatchIgnoreParams, cacheNames, canConstructReadableStream, canConstructResponseFromBodyStream, dontWaitFor, Deferred, executeQuotaErrorCallbacks, getFriendlyURL, logger, resultingClientExists, timeout, waitUntil, WorkboxError, }; diff --git a/node_modules/workbox-core/_private.mjs b/node_modules/workbox-core/_private.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0d186c40b69a5ad0a321a84391bd49bf1062defc --- /dev/null +++ b/node_modules/workbox-core/_private.mjs @@ -0,0 +1 @@ +export * from './_private.js'; \ No newline at end of file diff --git a/node_modules/workbox-core/_private/Deferred.d.ts b/node_modules/workbox-core/_private/Deferred.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..eef1ce6af53c06803ff44a3beac982189d87dfa5 --- /dev/null +++ b/node_modules/workbox-core/_private/Deferred.d.ts @@ -0,0 +1,19 @@ +import '../_version.js'; +/** + * The Deferred class composes Promises in a way that allows for them to be + * resolved or rejected from outside the constructor. In most cases promises + * should be used directly, but Deferreds can be necessary when the logic to + * resolve a promise must be separate. + * + * @private + */ +declare class Deferred { + promise: Promise; + resolve: (value: T) => void; + reject: (reason?: any) => void; + /** + * Creates a promise and exposes its resolve and reject functions as methods. + */ + constructor(); +} +export { Deferred }; diff --git a/node_modules/workbox-core/_private/Deferred.js b/node_modules/workbox-core/_private/Deferred.js new file mode 100644 index 0000000000000000000000000000000000000000..5d7a61ccf01fa4331cbcc7acbbad157b70a3046a --- /dev/null +++ b/node_modules/workbox-core/_private/Deferred.js @@ -0,0 +1,28 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import '../_version.js'; +/** + * The Deferred class composes Promises in a way that allows for them to be + * resolved or rejected from outside the constructor. In most cases promises + * should be used directly, but Deferreds can be necessary when the logic to + * resolve a promise must be separate. + * + * @private + */ +class Deferred { + /** + * Creates a promise and exposes its resolve and reject functions as methods. + */ + constructor() { + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + } +} +export { Deferred }; diff --git a/node_modules/workbox-core/_private/Deferred.mjs b/node_modules/workbox-core/_private/Deferred.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d9339cc2c3b5fd5cc0db68ef69cdbea34454d664 --- /dev/null +++ b/node_modules/workbox-core/_private/Deferred.mjs @@ -0,0 +1 @@ +export * from './Deferred.js'; \ No newline at end of file diff --git a/node_modules/workbox-core/_private/WorkboxError.d.ts b/node_modules/workbox-core/_private/WorkboxError.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c94eac7c0bdc412eb51b958bfd865eab20b3c0dd --- /dev/null +++ b/node_modules/workbox-core/_private/WorkboxError.d.ts @@ -0,0 +1,24 @@ +import { MapLikeObject } from '../types.js'; +import '../_version.js'; +/** + * Workbox errors should be thrown with this class. + * This allows use to ensure the type easily in tests, + * helps developers identify errors from workbox + * easily and allows use to optimise error + * messages correctly. + * + * @private + */ +declare class WorkboxError extends Error { + details?: MapLikeObject; + /** + * + * @param {string} errorCode The error code that + * identifies this particular error. + * @param {Object=} details Any relevant arguments + * that will help developers identify issues should + * be added as a key on the context object. + */ + constructor(errorCode: string, details?: MapLikeObject); +} +export { WorkboxError }; diff --git a/node_modules/workbox-core/_private/WorkboxError.js b/node_modules/workbox-core/_private/WorkboxError.js new file mode 100644 index 0000000000000000000000000000000000000000..be8257e3734accd21c7616c18d2f5416c692abc3 --- /dev/null +++ b/node_modules/workbox-core/_private/WorkboxError.js @@ -0,0 +1,35 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { messageGenerator } from '../models/messages/messageGenerator.js'; +import '../_version.js'; +/** + * Workbox errors should be thrown with this class. + * This allows use to ensure the type easily in tests, + * helps developers identify errors from workbox + * easily and allows use to optimise error + * messages correctly. + * + * @private + */ +class WorkboxError extends Error { + /** + * + * @param {string} errorCode The error code that + * identifies this particular error. + * @param {Object=} details Any relevant arguments + * that will help developers identify issues should + * be added as a key on the context object. + */ + constructor(errorCode, details) { + const message = messageGenerator(errorCode, details); + super(message); + this.name = errorCode; + this.details = details; + } +} +export { WorkboxError }; diff --git a/node_modules/workbox-core/_private/WorkboxError.mjs b/node_modules/workbox-core/_private/WorkboxError.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a138ba46bbaab1b827df64b5815f1de0c1b095a2 --- /dev/null +++ b/node_modules/workbox-core/_private/WorkboxError.mjs @@ -0,0 +1 @@ +export * from './WorkboxError.js'; \ No newline at end of file diff --git a/node_modules/workbox-core/_private/assert.d.ts b/node_modules/workbox-core/_private/assert.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c15247ac39de46b620a713b35defb4945daa5c20 --- /dev/null +++ b/node_modules/workbox-core/_private/assert.d.ts @@ -0,0 +1,11 @@ +import { MapLikeObject } from '../types.js'; +import '../_version.js'; +declare const finalAssertExports: { + hasMethod: (object: MapLikeObject, expectedMethod: string, details: MapLikeObject) => void; + isArray: (value: any[], details: MapLikeObject) => void; + isInstance: (object: unknown, expectedClass: Function, details: MapLikeObject) => void; + isOneOf: (value: any, validValues: any[], details: MapLikeObject) => void; + isType: (object: unknown, expectedType: string, details: MapLikeObject) => void; + isArrayOfClass: (value: any, expectedClass: Function, details: MapLikeObject) => void; +} | null; +export { finalAssertExports as assert }; diff --git a/node_modules/workbox-core/_private/assert.js b/node_modules/workbox-core/_private/assert.js new file mode 100644 index 0000000000000000000000000000000000000000..117b135273e2049bc6ef1e864f4d193866b90fb0 --- /dev/null +++ b/node_modules/workbox-core/_private/assert.js @@ -0,0 +1,73 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { WorkboxError } from '../_private/WorkboxError.js'; +import '../_version.js'; +/* + * This method throws if the supplied value is not an array. + * The destructed values are required to produce a meaningful error for users. + * The destructed and restructured object is so it's clear what is + * needed. + */ +const isArray = (value, details) => { + if (!Array.isArray(value)) { + throw new WorkboxError('not-an-array', details); + } +}; +const hasMethod = (object, expectedMethod, details) => { + const type = typeof object[expectedMethod]; + if (type !== 'function') { + details['expectedMethod'] = expectedMethod; + throw new WorkboxError('missing-a-method', details); + } +}; +const isType = (object, expectedType, details) => { + if (typeof object !== expectedType) { + details['expectedType'] = expectedType; + throw new WorkboxError('incorrect-type', details); + } +}; +const isInstance = (object, +// Need the general type to do the check later. +// eslint-disable-next-line @typescript-eslint/ban-types +expectedClass, details) => { + if (!(object instanceof expectedClass)) { + details['expectedClassName'] = expectedClass.name; + throw new WorkboxError('incorrect-class', details); + } +}; +const isOneOf = (value, validValues, details) => { + if (!validValues.includes(value)) { + details['validValueDescription'] = `Valid values are ${JSON.stringify(validValues)}.`; + throw new WorkboxError('invalid-value', details); + } +}; +const isArrayOfClass = (value, +// Need general type to do check later. +expectedClass, // eslint-disable-line +details) => { + const error = new WorkboxError('not-array-of-class', details); + if (!Array.isArray(value)) { + throw error; + } + for (const item of value) { + if (!(item instanceof expectedClass)) { + throw error; + } + } +}; +const finalAssertExports = process.env.NODE_ENV === 'production' + ? null + : { + hasMethod, + isArray, + isInstance, + isOneOf, + isType, + isArrayOfClass, + }; +export { finalAssertExports as assert }; diff --git a/node_modules/workbox-core/_private/assert.mjs b/node_modules/workbox-core/_private/assert.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8be2e15998aa40225a0fc7776333163d5b62fbe2 --- /dev/null +++ b/node_modules/workbox-core/_private/assert.mjs @@ -0,0 +1 @@ +export * from './assert.js'; \ No newline at end of file diff --git a/node_modules/workbox-core/_private/cacheMatchIgnoreParams.d.ts b/node_modules/workbox-core/_private/cacheMatchIgnoreParams.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5ccd85d68b03c2420963cac16cf8ddd0fa8f1d79 --- /dev/null +++ b/node_modules/workbox-core/_private/cacheMatchIgnoreParams.d.ts @@ -0,0 +1,15 @@ +import '../_version.js'; +/** + * Matches an item in the cache, ignoring specific URL params. This is similar + * to the `ignoreSearch` option, but it allows you to ignore just specific + * params (while continuing to match on the others). + * + * @private + * @param {Cache} cache + * @param {Request} request + * @param {Object} matchOptions + * @param {Array} ignoreParams + * @return {Promise} + */ +declare function cacheMatchIgnoreParams(cache: Cache, request: Request, ignoreParams: string[], matchOptions?: CacheQueryOptions): Promise; +export { cacheMatchIgnoreParams }; diff --git a/node_modules/workbox-core/_private/cacheMatchIgnoreParams.js b/node_modules/workbox-core/_private/cacheMatchIgnoreParams.js new file mode 100644 index 0000000000000000000000000000000000000000..1aabbb9073c204e27c43cf2a3b7808879b42f9d6 --- /dev/null +++ b/node_modules/workbox-core/_private/cacheMatchIgnoreParams.js @@ -0,0 +1,44 @@ +/* + Copyright 2020 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import '../_version.js'; +function stripParams(fullURL, ignoreParams) { + const strippedURL = new URL(fullURL); + for (const param of ignoreParams) { + strippedURL.searchParams.delete(param); + } + return strippedURL.href; +} +/** + * Matches an item in the cache, ignoring specific URL params. This is similar + * to the `ignoreSearch` option, but it allows you to ignore just specific + * params (while continuing to match on the others). + * + * @private + * @param {Cache} cache + * @param {Request} request + * @param {Object} matchOptions + * @param {Array} ignoreParams + * @return {Promise} + */ +async function cacheMatchIgnoreParams(cache, request, ignoreParams, matchOptions) { + const strippedRequestURL = stripParams(request.url, ignoreParams); + // If the request doesn't include any ignored params, match as normal. + if (request.url === strippedRequestURL) { + return cache.match(request, matchOptions); + } + // Otherwise, match by comparing keys + const keysOptions = Object.assign(Object.assign({}, matchOptions), { ignoreSearch: true }); + const cacheKeys = await cache.keys(request, keysOptions); + for (const cacheKey of cacheKeys) { + const strippedCacheKeyURL = stripParams(cacheKey.url, ignoreParams); + if (strippedRequestURL === strippedCacheKeyURL) { + return cache.match(cacheKey, matchOptions); + } + } + return; +} +export { cacheMatchIgnoreParams }; diff --git a/node_modules/workbox-core/_private/cacheMatchIgnoreParams.mjs b/node_modules/workbox-core/_private/cacheMatchIgnoreParams.mjs new file mode 100644 index 0000000000000000000000000000000000000000..cc981efbb7059ef58d57c7a856c1da80f322cc6b --- /dev/null +++ b/node_modules/workbox-core/_private/cacheMatchIgnoreParams.mjs @@ -0,0 +1 @@ +export * from './cacheMatchIgnoreParams.js'; \ No newline at end of file diff --git a/node_modules/workbox-core/_private/cacheNames.d.ts b/node_modules/workbox-core/_private/cacheNames.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..414308e31b40bd1699159419f8d0f145a18de6af --- /dev/null +++ b/node_modules/workbox-core/_private/cacheNames.d.ts @@ -0,0 +1,20 @@ +import '../_version.js'; +export interface CacheNameDetails { + googleAnalytics: string; + precache: string; + prefix: string; + runtime: string; + suffix: string; +} +export interface PartialCacheNameDetails { + [propName: string]: string; +} +export type CacheNameDetailsProp = 'googleAnalytics' | 'precache' | 'prefix' | 'runtime' | 'suffix'; +export declare const cacheNames: { + updateDetails: (details: PartialCacheNameDetails) => void; + getGoogleAnalyticsName: (userCacheName?: string) => string; + getPrecacheName: (userCacheName?: string) => string; + getPrefix: () => string; + getRuntimeName: (userCacheName?: string) => string; + getSuffix: () => string; +}; diff --git a/node_modules/workbox-core/_private/cacheNames.js b/node_modules/workbox-core/_private/cacheNames.js new file mode 100644 index 0000000000000000000000000000000000000000..76124b17b4c6a663331e57b73687869dfc35cbcb --- /dev/null +++ b/node_modules/workbox-core/_private/cacheNames.js @@ -0,0 +1,49 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import '../_version.js'; +const _cacheNameDetails = { + googleAnalytics: 'googleAnalytics', + precache: 'precache-v2', + prefix: 'workbox', + runtime: 'runtime', + suffix: typeof registration !== 'undefined' ? registration.scope : '', +}; +const _createCacheName = (cacheName) => { + return [_cacheNameDetails.prefix, cacheName, _cacheNameDetails.suffix] + .filter((value) => value && value.length > 0) + .join('-'); +}; +const eachCacheNameDetail = (fn) => { + for (const key of Object.keys(_cacheNameDetails)) { + fn(key); + } +}; +export const cacheNames = { + updateDetails: (details) => { + eachCacheNameDetail((key) => { + if (typeof details[key] === 'string') { + _cacheNameDetails[key] = details[key]; + } + }); + }, + getGoogleAnalyticsName: (userCacheName) => { + return userCacheName || _createCacheName(_cacheNameDetails.googleAnalytics); + }, + getPrecacheName: (userCacheName) => { + return userCacheName || _createCacheName(_cacheNameDetails.precache); + }, + getPrefix: () => { + return _cacheNameDetails.prefix; + }, + getRuntimeName: (userCacheName) => { + return userCacheName || _createCacheName(_cacheNameDetails.runtime); + }, + getSuffix: () => { + return _cacheNameDetails.suffix; + }, +}; diff --git a/node_modules/workbox-core/_private/cacheNames.mjs b/node_modules/workbox-core/_private/cacheNames.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2a299372164250b06c59b7f4a227ec39793abfa2 --- /dev/null +++ b/node_modules/workbox-core/_private/cacheNames.mjs @@ -0,0 +1 @@ +export * from './cacheNames.js'; \ No newline at end of file diff --git a/node_modules/workbox-core/_private/canConstructReadableStream.d.ts b/node_modules/workbox-core/_private/canConstructReadableStream.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..da18a82a73b5bdb3f49743a3828c1feb83836e27 --- /dev/null +++ b/node_modules/workbox-core/_private/canConstructReadableStream.d.ts @@ -0,0 +1,13 @@ +import '../_version.js'; +/** + * A utility function that determines whether the current browser supports + * constructing a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream) + * object. + * + * @return {boolean} `true`, if the current browser can successfully + * construct a `ReadableStream`, `false` otherwise. + * + * @private + */ +declare function canConstructReadableStream(): boolean; +export { canConstructReadableStream }; diff --git a/node_modules/workbox-core/_private/canConstructReadableStream.js b/node_modules/workbox-core/_private/canConstructReadableStream.js new file mode 100644 index 0000000000000000000000000000000000000000..7fc3e06305a615891eca2eda50b935ae3f4f46fc --- /dev/null +++ b/node_modules/workbox-core/_private/canConstructReadableStream.js @@ -0,0 +1,33 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import '../_version.js'; +let supportStatus; +/** + * A utility function that determines whether the current browser supports + * constructing a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream) + * object. + * + * @return {boolean} `true`, if the current browser can successfully + * construct a `ReadableStream`, `false` otherwise. + * + * @private + */ +function canConstructReadableStream() { + if (supportStatus === undefined) { + // See https://github.com/GoogleChrome/workbox/issues/1473 + try { + new ReadableStream({ start() { } }); + supportStatus = true; + } + catch (error) { + supportStatus = false; + } + } + return supportStatus; +} +export { canConstructReadableStream }; diff --git a/node_modules/workbox-core/_private/canConstructReadableStream.mjs b/node_modules/workbox-core/_private/canConstructReadableStream.mjs new file mode 100644 index 0000000000000000000000000000000000000000..317ede690ce65ed3c780ff6ad326db29cc3dc3d7 --- /dev/null +++ b/node_modules/workbox-core/_private/canConstructReadableStream.mjs @@ -0,0 +1 @@ +export * from './canConstructReadableStream.js'; \ No newline at end of file diff --git a/node_modules/workbox-core/_private/canConstructResponseFromBodyStream.d.ts b/node_modules/workbox-core/_private/canConstructResponseFromBodyStream.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2cf6f849dd7bd881b24771fbec5a460c6f9f5e06 --- /dev/null +++ b/node_modules/workbox-core/_private/canConstructResponseFromBodyStream.d.ts @@ -0,0 +1,12 @@ +import '../_version.js'; +/** + * A utility function that determines whether the current browser supports + * constructing a new `Response` from a `response.body` stream. + * + * @return {boolean} `true`, if the current browser can successfully + * construct a `Response` from a `response.body` stream, `false` otherwise. + * + * @private + */ +declare function canConstructResponseFromBodyStream(): boolean; +export { canConstructResponseFromBodyStream }; diff --git a/node_modules/workbox-core/_private/canConstructResponseFromBodyStream.js b/node_modules/workbox-core/_private/canConstructResponseFromBodyStream.js new file mode 100644 index 0000000000000000000000000000000000000000..d48d436f1207447b369ec372ea5e58b03388ab2f --- /dev/null +++ b/node_modules/workbox-core/_private/canConstructResponseFromBodyStream.js @@ -0,0 +1,35 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import '../_version.js'; +let supportStatus; +/** + * A utility function that determines whether the current browser supports + * constructing a new `Response` from a `response.body` stream. + * + * @return {boolean} `true`, if the current browser can successfully + * construct a `Response` from a `response.body` stream, `false` otherwise. + * + * @private + */ +function canConstructResponseFromBodyStream() { + if (supportStatus === undefined) { + const testResponse = new Response(''); + if ('body' in testResponse) { + try { + new Response(testResponse.body); + supportStatus = true; + } + catch (error) { + supportStatus = false; + } + } + supportStatus = false; + } + return supportStatus; +} +export { canConstructResponseFromBodyStream }; diff --git a/node_modules/workbox-core/_private/canConstructResponseFromBodyStream.mjs b/node_modules/workbox-core/_private/canConstructResponseFromBodyStream.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5022eb686066b6c92330c04278352b5ccbb0fa84 --- /dev/null +++ b/node_modules/workbox-core/_private/canConstructResponseFromBodyStream.mjs @@ -0,0 +1 @@ +export * from './canConstructResponseFromBodyStream.js'; \ No newline at end of file diff --git a/node_modules/workbox-core/_private/dontWaitFor.d.ts b/node_modules/workbox-core/_private/dontWaitFor.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..07e784836f95a5988cf70e54601b802b49942934 --- /dev/null +++ b/node_modules/workbox-core/_private/dontWaitFor.d.ts @@ -0,0 +1,7 @@ +import '../_version.js'; +/** + * A helper function that prevents a promise from being flagged as unused. + * + * @private + **/ +export declare function dontWaitFor(promise: Promise): void; diff --git a/node_modules/workbox-core/_private/dontWaitFor.js b/node_modules/workbox-core/_private/dontWaitFor.js new file mode 100644 index 0000000000000000000000000000000000000000..98ad7b602b27229d307c391546adfec88acee416 --- /dev/null +++ b/node_modules/workbox-core/_private/dontWaitFor.js @@ -0,0 +1,16 @@ +/* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import '../_version.js'; +/** + * A helper function that prevents a promise from being flagged as unused. + * + * @private + **/ +export function dontWaitFor(promise) { + // Effective no-op. + void promise.then(() => { }); +} diff --git a/node_modules/workbox-core/_private/dontWaitFor.mjs b/node_modules/workbox-core/_private/dontWaitFor.mjs new file mode 100644 index 0000000000000000000000000000000000000000..cc94c4d31739ca4a4c81054db41c48eb2d046cc8 --- /dev/null +++ b/node_modules/workbox-core/_private/dontWaitFor.mjs @@ -0,0 +1 @@ +export * from './dontWaitFor.js'; \ No newline at end of file diff --git a/node_modules/workbox-core/_private/executeQuotaErrorCallbacks.d.ts b/node_modules/workbox-core/_private/executeQuotaErrorCallbacks.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..15aa4d59423624dc38e67febcc61dd3f19162ee2 --- /dev/null +++ b/node_modules/workbox-core/_private/executeQuotaErrorCallbacks.d.ts @@ -0,0 +1,10 @@ +import '../_version.js'; +/** + * Runs all of the callback functions, one at a time sequentially, in the order + * in which they were registered. + * + * @memberof workbox-core + * @private + */ +declare function executeQuotaErrorCallbacks(): Promise; +export { executeQuotaErrorCallbacks }; diff --git a/node_modules/workbox-core/_private/executeQuotaErrorCallbacks.js b/node_modules/workbox-core/_private/executeQuotaErrorCallbacks.js new file mode 100644 index 0000000000000000000000000000000000000000..ec783c70a0af7dc4f05e3def090637e4ee6e4dc3 --- /dev/null +++ b/node_modules/workbox-core/_private/executeQuotaErrorCallbacks.js @@ -0,0 +1,33 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { logger } from '../_private/logger.js'; +import { quotaErrorCallbacks } from '../models/quotaErrorCallbacks.js'; +import '../_version.js'; +/** + * Runs all of the callback functions, one at a time sequentially, in the order + * in which they were registered. + * + * @memberof workbox-core + * @private + */ +async function executeQuotaErrorCallbacks() { + if (process.env.NODE_ENV !== 'production') { + logger.log(`About to run ${quotaErrorCallbacks.size} ` + + `callbacks to clean up caches.`); + } + for (const callback of quotaErrorCallbacks) { + await callback(); + if (process.env.NODE_ENV !== 'production') { + logger.log(callback, 'is complete.'); + } + } + if (process.env.NODE_ENV !== 'production') { + logger.log('Finished running callbacks.'); + } +} +export { executeQuotaErrorCallbacks }; diff --git a/node_modules/workbox-core/_private/executeQuotaErrorCallbacks.mjs b/node_modules/workbox-core/_private/executeQuotaErrorCallbacks.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9cfadb415aba0446bc4d106928eaaef266f2834e --- /dev/null +++ b/node_modules/workbox-core/_private/executeQuotaErrorCallbacks.mjs @@ -0,0 +1 @@ +export * from './executeQuotaErrorCallbacks.js'; \ No newline at end of file diff --git a/node_modules/workbox-core/_private/getFriendlyURL.d.ts b/node_modules/workbox-core/_private/getFriendlyURL.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..acfb844d0339ee1261c1612a0ea2d2c44ef6fdef --- /dev/null +++ b/node_modules/workbox-core/_private/getFriendlyURL.d.ts @@ -0,0 +1,3 @@ +import '../_version.js'; +declare const getFriendlyURL: (url: URL | string) => string; +export { getFriendlyURL }; diff --git a/node_modules/workbox-core/_private/getFriendlyURL.js b/node_modules/workbox-core/_private/getFriendlyURL.js new file mode 100644 index 0000000000000000000000000000000000000000..d7cbe44a966413520c152905c722511215683786 --- /dev/null +++ b/node_modules/workbox-core/_private/getFriendlyURL.js @@ -0,0 +1,15 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import '../_version.js'; +const getFriendlyURL = (url) => { + const urlObj = new URL(String(url), location.href); + // See https://github.com/GoogleChrome/workbox/issues/2323 + // We want to include everything, except for the origin if it's same-origin. + return urlObj.href.replace(new RegExp(`^${location.origin}`), ''); +}; +export { getFriendlyURL }; diff --git a/node_modules/workbox-core/_private/getFriendlyURL.mjs b/node_modules/workbox-core/_private/getFriendlyURL.mjs new file mode 100644 index 0000000000000000000000000000000000000000..aa37fe86f016625d3a31cf46c3b9b01c081b8e92 --- /dev/null +++ b/node_modules/workbox-core/_private/getFriendlyURL.mjs @@ -0,0 +1 @@ +export * from './getFriendlyURL.js'; \ No newline at end of file diff --git a/node_modules/workbox-core/_private/logger.d.ts b/node_modules/workbox-core/_private/logger.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..41fb738d5fe2760be11729177bfbe1fd55d959cf --- /dev/null +++ b/node_modules/workbox-core/_private/logger.d.ts @@ -0,0 +1,11 @@ +import '../_version.js'; +declare global { + interface WorkerGlobalScope { + __WB_DISABLE_DEV_LOGS: boolean; + } + interface Window { + __WB_DISABLE_DEV_LOGS: boolean; + } +} +declare const logger: Console; +export { logger }; diff --git a/node_modules/workbox-core/_private/logger.js b/node_modules/workbox-core/_private/logger.js new file mode 100644 index 0000000000000000000000000000000000000000..05876ff67194cf1e16992bad31d7c6eb48f6e499 --- /dev/null +++ b/node_modules/workbox-core/_private/logger.js @@ -0,0 +1,65 @@ +/* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import '../_version.js'; +const logger = (process.env.NODE_ENV === 'production' + ? null + : (() => { + // Don't overwrite this value if it's already set. + // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923 + if (!('__WB_DISABLE_DEV_LOGS' in globalThis)) { + self.__WB_DISABLE_DEV_LOGS = false; + } + let inGroup = false; + const methodToColorMap = { + debug: `#7f8c8d`, + log: `#2ecc71`, + warn: `#f39c12`, + error: `#c0392b`, + groupCollapsed: `#3498db`, + groupEnd: null, // No colored prefix on groupEnd + }; + const print = function (method, args) { + if (self.__WB_DISABLE_DEV_LOGS) { + return; + } + if (method === 'groupCollapsed') { + // Safari doesn't print all console.groupCollapsed() arguments: + // https://bugs.webkit.org/show_bug.cgi?id=182754 + if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) { + console[method](...args); + return; + } + } + 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. + const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')]; + console[method](...logPrefix, ...args); + if (method === 'groupCollapsed') { + inGroup = true; + } + if (method === 'groupEnd') { + inGroup = false; + } + }; + // eslint-disable-next-line @typescript-eslint/ban-types + const api = {}; + const loggerMethods = Object.keys(methodToColorMap); + for (const key of loggerMethods) { + const method = key; + api[method] = (...args) => { + print(method, args); + }; + } + return api; + })()); +export { logger }; diff --git a/node_modules/workbox-core/_private/logger.mjs b/node_modules/workbox-core/_private/logger.mjs new file mode 100644 index 0000000000000000000000000000000000000000..826d1a6c0f89e2408a23fdb6556701b313ec54f2 --- /dev/null +++ b/node_modules/workbox-core/_private/logger.mjs @@ -0,0 +1 @@ +export * from './logger.js'; \ No newline at end of file diff --git a/node_modules/workbox-core/_private/resultingClientExists.d.ts b/node_modules/workbox-core/_private/resultingClientExists.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e0e092189799cdc1229c1b02b9efea986038fa09 --- /dev/null +++ b/node_modules/workbox-core/_private/resultingClientExists.d.ts @@ -0,0 +1,12 @@ +import '../_version.js'; +/** + * Returns a promise that resolves to a window client matching the passed + * `resultingClientId`. For browsers that don't support `resultingClientId` + * or if waiting for the resulting client to apper takes too long, resolve to + * `undefined`. + * + * @param {string} [resultingClientId] + * @return {Promise} + * @private + */ +export declare function resultingClientExists(resultingClientId?: string): Promise; diff --git a/node_modules/workbox-core/_private/resultingClientExists.js b/node_modules/workbox-core/_private/resultingClientExists.js new file mode 100644 index 0000000000000000000000000000000000000000..334627860deffe9be87e5127901001bde11eec91 --- /dev/null +++ b/node_modules/workbox-core/_private/resultingClientExists.js @@ -0,0 +1,48 @@ +/* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { timeout } from './timeout.js'; +import '../_version.js'; +const MAX_RETRY_TIME = 2000; +/** + * Returns a promise that resolves to a window client matching the passed + * `resultingClientId`. For browsers that don't support `resultingClientId` + * or if waiting for the resulting client to apper takes too long, resolve to + * `undefined`. + * + * @param {string} [resultingClientId] + * @return {Promise} + * @private + */ +export async function resultingClientExists(resultingClientId) { + if (!resultingClientId) { + return; + } + let existingWindows = await self.clients.matchAll({ type: 'window' }); + const existingWindowIds = new Set(existingWindows.map((w) => w.id)); + let resultingWindow; + const startTime = performance.now(); + // Only wait up to `MAX_RETRY_TIME` to find a matching client. + while (performance.now() - startTime < MAX_RETRY_TIME) { + existingWindows = await self.clients.matchAll({ type: 'window' }); + resultingWindow = existingWindows.find((w) => { + if (resultingClientId) { + // If we have a `resultingClientId`, we can match on that. + return w.id === resultingClientId; + } + else { + // Otherwise match on finding a window not in `existingWindowIds`. + return !existingWindowIds.has(w.id); + } + }); + if (resultingWindow) { + break; + } + // Sleep for 100ms and retry. + await timeout(100); + } + return resultingWindow; +} diff --git a/node_modules/workbox-core/_private/resultingClientExists.mjs b/node_modules/workbox-core/_private/resultingClientExists.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9276bae7028d841de2ababbf977c8a905fac85d6 --- /dev/null +++ b/node_modules/workbox-core/_private/resultingClientExists.mjs @@ -0,0 +1 @@ +export * from './resultingClientExists.js'; \ No newline at end of file diff --git a/node_modules/workbox-core/_private/timeout.d.ts b/node_modules/workbox-core/_private/timeout.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1497ca18cd084556bec0ea5f4c6651680ceff2dd --- /dev/null +++ b/node_modules/workbox-core/_private/timeout.d.ts @@ -0,0 +1,10 @@ +import '../_version.js'; +/** + * Returns a promise that resolves and the passed number of milliseconds. + * This utility is an async/await-friendly version of `setTimeout`. + * + * @param {number} ms + * @return {Promise} + * @private + */ +export declare function timeout(ms: number): Promise; diff --git a/node_modules/workbox-core/_private/timeout.js b/node_modules/workbox-core/_private/timeout.js new file mode 100644 index 0000000000000000000000000000000000000000..640c52b8fb466645a9cbf44313d2c62fa0c9754e --- /dev/null +++ b/node_modules/workbox-core/_private/timeout.js @@ -0,0 +1,18 @@ +/* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import '../_version.js'; +/** + * Returns a promise that resolves and the passed number of milliseconds. + * This utility is an async/await-friendly version of `setTimeout`. + * + * @param {number} ms + * @return {Promise} + * @private + */ +export function timeout(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} diff --git a/node_modules/workbox-core/_private/timeout.mjs b/node_modules/workbox-core/_private/timeout.mjs new file mode 100644 index 0000000000000000000000000000000000000000..88473c41349a56736911af70a8f9573d44e0ce6b --- /dev/null +++ b/node_modules/workbox-core/_private/timeout.mjs @@ -0,0 +1 @@ +export * from './timeout.js'; \ No newline at end of file diff --git a/node_modules/workbox-core/_private/waitUntil.d.ts b/node_modules/workbox-core/_private/waitUntil.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..44acfa476ff01f74764c21c9d79887f51398cc5e --- /dev/null +++ b/node_modules/workbox-core/_private/waitUntil.d.ts @@ -0,0 +1,12 @@ +import '../_version.js'; +/** + * A utility method that makes it easier to use `event.waitUntil` with + * async functions and return the result. + * + * @param {ExtendableEvent} event + * @param {Function} asyncFn + * @return {Function} + * @private + */ +declare function waitUntil(event: ExtendableEvent, asyncFn: () => Promise): Promise; +export { waitUntil }; diff --git a/node_modules/workbox-core/_private/waitUntil.js b/node_modules/workbox-core/_private/waitUntil.js new file mode 100644 index 0000000000000000000000000000000000000000..80d1df19a8c0e9c7a389973b63dae462a5870e87 --- /dev/null +++ b/node_modules/workbox-core/_private/waitUntil.js @@ -0,0 +1,22 @@ +/* + Copyright 2020 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import '../_version.js'; +/** + * A utility method that makes it easier to use `event.waitUntil` with + * async functions and return the result. + * + * @param {ExtendableEvent} event + * @param {Function} asyncFn + * @return {Function} + * @private + */ +function waitUntil(event, asyncFn) { + const returnPromise = asyncFn(); + event.waitUntil(returnPromise); + return returnPromise; +} +export { waitUntil }; diff --git a/node_modules/workbox-core/_private/waitUntil.mjs b/node_modules/workbox-core/_private/waitUntil.mjs new file mode 100644 index 0000000000000000000000000000000000000000..53dadf2ad25a4b845826ba2311152121d2ecf960 --- /dev/null +++ b/node_modules/workbox-core/_private/waitUntil.mjs @@ -0,0 +1 @@ +export * from './waitUntil.js'; \ No newline at end of file diff --git a/node_modules/workbox-core/_version.d.ts b/node_modules/workbox-core/_version.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/workbox-core/_version.js b/node_modules/workbox-core/_version.js new file mode 100644 index 0000000000000000000000000000000000000000..1776910e36ff94fba9166edbfd04734fc6389c4f --- /dev/null +++ b/node_modules/workbox-core/_version.js @@ -0,0 +1,6 @@ +"use strict"; +// @ts-ignore +try { + self['workbox:core:7.4.0'] && _(); +} +catch (e) { } diff --git a/node_modules/workbox-core/_version.mjs b/node_modules/workbox-core/_version.mjs new file mode 100644 index 0000000000000000000000000000000000000000..431f82592459b7c77eafbc35830c87c77d746fa6 --- /dev/null +++ b/node_modules/workbox-core/_version.mjs @@ -0,0 +1 @@ +try{self['workbox:core:7.4.1']&&_()}catch(e){}// eslint-disable-line \ No newline at end of file diff --git a/node_modules/workbox-core/build/workbox-core.dev.js b/node_modules/workbox-core/build/workbox-core.dev.js new file mode 100644 index 0000000000000000000000000000000000000000..c8a79aa016da21c20a7c4f8a99dfc2eb8c72dc9e --- /dev/null +++ b/node_modules/workbox-core/build/workbox-core.dev.js @@ -0,0 +1,1060 @@ +this.workbox = this.workbox || {}; +this.workbox.core = (function (exports) { + 'use strict'; + + // @ts-ignore + try { + self['workbox:core:7.4.0'] && _(); + } catch (e) {} + + /* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + const logger = (() => { + // Don't overwrite this value if it's already set. + // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923 + if (!('__WB_DISABLE_DEV_LOGS' in globalThis)) { + self.__WB_DISABLE_DEV_LOGS = false; + } + let inGroup = false; + const methodToColorMap = { + debug: `#7f8c8d`, + log: `#2ecc71`, + warn: `#f39c12`, + error: `#c0392b`, + groupCollapsed: `#3498db`, + groupEnd: null // No colored prefix on groupEnd + }; + const print = function (method, args) { + if (self.__WB_DISABLE_DEV_LOGS) { + return; + } + if (method === 'groupCollapsed') { + // Safari doesn't print all console.groupCollapsed() arguments: + // https://bugs.webkit.org/show_bug.cgi?id=182754 + if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) { + console[method](...args); + return; + } + } + 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. + const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')]; + console[method](...logPrefix, ...args); + if (method === 'groupCollapsed') { + inGroup = true; + } + if (method === 'groupEnd') { + inGroup = false; + } + }; + // eslint-disable-next-line @typescript-eslint/ban-types + const api = {}; + const loggerMethods = Object.keys(methodToColorMap); + for (const key of loggerMethods) { + const method = key; + api[method] = (...args) => { + print(method, args); + }; + } + return api; + })(); + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + const messages = { + 'invalid-value': ({ + paramName, + validValueDescription, + value + }) => { + if (!paramName || !validValueDescription) { + throw new Error(`Unexpected input to 'invalid-value' error.`); + } + return `The '${paramName}' parameter was given a value with an ` + `unexpected value. ${validValueDescription} Received a value of ` + `${JSON.stringify(value)}.`; + }, + 'not-an-array': ({ + moduleName, + className, + funcName, + paramName + }) => { + if (!moduleName || !className || !funcName || !paramName) { + throw new Error(`Unexpected input to 'not-an-array' error.`); + } + return `The parameter '${paramName}' passed into ` + `'${moduleName}.${className}.${funcName}()' must be an array.`; + }, + 'incorrect-type': ({ + expectedType, + paramName, + moduleName, + className, + funcName + }) => { + if (!expectedType || !paramName || !moduleName || !funcName) { + throw new Error(`Unexpected input to 'incorrect-type' error.`); + } + const classNameStr = className ? `${className}.` : ''; + return `The parameter '${paramName}' passed into ` + `'${moduleName}.${classNameStr}` + `${funcName}()' must be of type ${expectedType}.`; + }, + 'incorrect-class': ({ + expectedClassName, + paramName, + moduleName, + className, + funcName, + isReturnValueProblem + }) => { + if (!expectedClassName || !moduleName || !funcName) { + throw new Error(`Unexpected input to 'incorrect-class' error.`); + } + const classNameStr = className ? `${className}.` : ''; + if (isReturnValueProblem) { + return `The return value from ` + `'${moduleName}.${classNameStr}${funcName}()' ` + `must be an instance of class ${expectedClassName}.`; + } + return `The parameter '${paramName}' passed into ` + `'${moduleName}.${classNameStr}${funcName}()' ` + `must be an instance of class ${expectedClassName}.`; + }, + 'missing-a-method': ({ + expectedMethod, + paramName, + moduleName, + className, + funcName + }) => { + if (!expectedMethod || !paramName || !moduleName || !className || !funcName) { + throw new Error(`Unexpected input to 'missing-a-method' error.`); + } + return `${moduleName}.${className}.${funcName}() expected the ` + `'${paramName}' parameter to expose a '${expectedMethod}' method.`; + }, + 'add-to-cache-list-unexpected-type': ({ + entry + }) => { + 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.`; + }, + 'add-to-cache-list-conflicting-entries': ({ + firstEntry, + secondEntry + }) => { + if (!firstEntry || !secondEntry) { + throw new Error(`Unexpected input to ` + `'add-to-cache-list-duplicate-entries' error.`); + } + return `Two of the entries passed to ` + `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` + `${firstEntry} but different revision details. Workbox is ` + `unable to cache and version the asset correctly. Please remove one ` + `of the entries.`; + }, + 'plugin-error-request-will-fetch': ({ + thrownErrorMessage + }) => { + if (!thrownErrorMessage) { + throw new Error(`Unexpected input to ` + `'plugin-error-request-will-fetch', error.`); + } + return `An error was thrown by a plugins 'requestWillFetch()' method. ` + `The thrown error message was: '${thrownErrorMessage}'.`; + }, + 'invalid-cache-name': ({ + cacheNameId, + value + }) => { + if (!cacheNameId) { + throw new Error(`Expected a 'cacheNameId' for error 'invalid-cache-name'`); + } + return `You must provide a name containing at least one character for ` + `setCacheDetails({${cacheNameId}: '...'}). Received a value of ` + `'${JSON.stringify(value)}'`; + }, + 'unregister-route-but-not-found-with-method': ({ + method + }) => { + if (!method) { + throw new Error(`Unexpected input to ` + `'unregister-route-but-not-found-with-method' error.`); + } + return `The route you're trying to unregister was not previously ` + `registered for the method type '${method}'.`; + }, + 'unregister-route-route-not-registered': () => { + return `The route you're trying to unregister was not previously ` + `registered.`; + }, + 'queue-replay-failed': ({ + name + }) => { + return `Replaying the background sync queue '${name}' failed.`; + }, + 'duplicate-queue-name': ({ + name + }) => { + return `The Queue name '${name}' is already being used. ` + `All instances of backgroundSync.Queue must be given unique names.`; + }, + 'expired-test-without-max-age': ({ + methodName, + paramName + }) => { + return `The '${methodName}()' method can only be used when the ` + `'${paramName}' is used in the constructor.`; + }, + 'unsupported-route-type': ({ + moduleName, + className, + funcName, + paramName + }) => { + return `The supplied '${paramName}' parameter was an unsupported type. ` + `Please check the docs for ${moduleName}.${className}.${funcName} for ` + `valid input types.`; + }, + 'not-array-of-class': ({ + value, + expectedClass, + moduleName, + className, + funcName, + paramName + }) => { + 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.`; + }, + 'max-entries-or-age-required': ({ + moduleName, + className, + funcName + }) => { + return `You must define either config.maxEntries or config.maxAgeSeconds` + `in ${moduleName}.${className}.${funcName}`; + }, + 'statuses-or-headers-required': ({ + moduleName, + className, + funcName + }) => { + return `You must define either config.statuses or config.headers` + `in ${moduleName}.${className}.${funcName}`; + }, + 'invalid-string': ({ + moduleName, + funcName, + paramName + }) => { + if (!paramName || !moduleName || !funcName) { + throw new Error(`Unexpected input to 'invalid-string' error.`); + } + 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.`; + }, + 'channel-name-required': () => { + return `You must provide a channelName to construct a ` + `BroadcastCacheUpdate instance.`; + }, + 'invalid-responses-are-same-args': () => { + return `The arguments passed into responsesAreSame() appear to be ` + `invalid. Please ensure valid Responses are used.`; + }, + 'expire-custom-caches-only': () => { + return `You must provide a 'cacheName' property when using the ` + `expiration plugin with a runtime caching strategy.`; + }, + 'unit-must-be-bytes': ({ + normalizedRangeHeader + }) => { + if (!normalizedRangeHeader) { + throw new Error(`Unexpected input to 'unit-must-be-bytes' error.`); + } + return `The 'unit' portion of the Range header must be set to 'bytes'. ` + `The Range header provided was "${normalizedRangeHeader}"`; + }, + 'single-range-only': ({ + normalizedRangeHeader + }) => { + if (!normalizedRangeHeader) { + throw new Error(`Unexpected input to 'single-range-only' error.`); + } + return `Multiple ranges are not supported. Please use a single start ` + `value, and optional end value. The Range header provided was ` + `"${normalizedRangeHeader}"`; + }, + 'invalid-range-values': ({ + normalizedRangeHeader + }) => { + if (!normalizedRangeHeader) { + throw new Error(`Unexpected input to 'invalid-range-values' error.`); + } + 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}"`; + }, + 'no-range-header': () => { + return `No Range header was found in the Request provided.`; + }, + 'range-not-satisfiable': ({ + size, + start, + end + }) => { + return `The start (${start}) and end (${end}) values in the Range are ` + `not satisfiable by the cached response, which is ${size} bytes.`; + }, + 'attempt-to-cache-non-get-request': ({ + url, + method + }) => { + return `Unable to cache '${url}' because it is a '${method}' request and ` + `only 'GET' requests can be cached.`; + }, + 'cache-put-with-no-response': ({ + url + }) => { + return `There was an attempt to cache '${url}' but the response was not ` + `defined.`; + }, + 'no-response': ({ + url, + error + }) => { + let message = `The strategy could not generate a response for '${url}'.`; + if (error) { + message += ` The underlying error is ${error}.`; + } + return message; + }, + 'bad-precaching-response': ({ + url, + status + }) => { + return `The precaching request for '${url}' failed` + (status ? ` with an HTTP status of ${status}.` : `.`); + }, + 'non-precached-url': ({ + url + }) => { + return `createHandlerBoundToURL('${url}') was called, but that URL is ` + `not precached. Please pass in a URL that is precached instead.`; + }, + 'add-to-cache-list-conflicting-integrities': ({ + url + }) => { + return `Two of the entries passed to ` + `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` + `${url} with different integrity values. Please remove one of them.`; + }, + 'missing-precache-entry': ({ + cacheName, + url + }) => { + return `Unable to find a precached response in ${cacheName} for ${url}.`; + }, + 'cross-origin-copy-response': ({ + origin + }) => { + return `workbox-core.copyResponse() can only be used with same-origin ` + `responses. It was passed a response with origin ${origin}.`; + }, + 'opaque-streams-source': ({ + type + }) => { + const message = `One of the workbox-streams sources resulted in an ` + `'${type}' response.`; + if (type === 'opaqueredirect') { + return `${message} Please do not use a navigation request that results ` + `in a redirect as a source.`; + } + return `${message} Please ensure your sources are CORS-enabled.`; + } + }; + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + const generatorFunction = (code, details = {}) => { + const message = messages[code]; + if (!message) { + throw new Error(`Unable to find message for code '${code}'.`); + } + return message(details); + }; + const messageGenerator = generatorFunction; + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Workbox errors should be thrown with this class. + * This allows use to ensure the type easily in tests, + * helps developers identify errors from workbox + * easily and allows use to optimise error + * messages correctly. + * + * @private + */ + class WorkboxError extends Error { + /** + * + * @param {string} errorCode The error code that + * identifies this particular error. + * @param {Object=} details Any relevant arguments + * that will help developers identify issues should + * be added as a key on the context object. + */ + constructor(errorCode, details) { + const message = messageGenerator(errorCode, details); + super(message); + this.name = errorCode; + this.details = details; + } + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /* + * This method throws if the supplied value is not an array. + * The destructed values are required to produce a meaningful error for users. + * The destructed and restructured object is so it's clear what is + * needed. + */ + const isArray = (value, details) => { + if (!Array.isArray(value)) { + throw new WorkboxError('not-an-array', details); + } + }; + const hasMethod = (object, expectedMethod, details) => { + const type = typeof object[expectedMethod]; + if (type !== 'function') { + details['expectedMethod'] = expectedMethod; + throw new WorkboxError('missing-a-method', details); + } + }; + const isType = (object, expectedType, details) => { + if (typeof object !== expectedType) { + details['expectedType'] = expectedType; + throw new WorkboxError('incorrect-type', details); + } + }; + const isInstance = (object, + // Need the general type to do the check later. + // eslint-disable-next-line @typescript-eslint/ban-types + expectedClass, details) => { + if (!(object instanceof expectedClass)) { + details['expectedClassName'] = expectedClass.name; + throw new WorkboxError('incorrect-class', details); + } + }; + const isOneOf = (value, validValues, details) => { + if (!validValues.includes(value)) { + details['validValueDescription'] = `Valid values are ${JSON.stringify(validValues)}.`; + throw new WorkboxError('invalid-value', details); + } + }; + const isArrayOfClass = (value, + // Need general type to do check later. + expectedClass, + // eslint-disable-line + details) => { + const error = new WorkboxError('not-array-of-class', details); + if (!Array.isArray(value)) { + throw error; + } + for (const item of value) { + if (!(item instanceof expectedClass)) { + throw error; + } + } + }; + const finalAssertExports = { + hasMethod, + isArray, + isInstance, + isOneOf, + isType, + isArrayOfClass + }; + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + // Callbacks to be executed whenever there's a quota error. + // Can't change Function type right now. + // eslint-disable-next-line @typescript-eslint/ban-types + const quotaErrorCallbacks = new Set(); + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Adds a function to the set of quotaErrorCallbacks that will be executed if + * there's a quota error. + * + * @param {Function} callback + * @memberof workbox-core + */ + // Can't change Function type + // eslint-disable-next-line @typescript-eslint/ban-types + function registerQuotaErrorCallback(callback) { + { + finalAssertExports.isType(callback, 'function', { + moduleName: 'workbox-core', + funcName: 'register', + paramName: 'callback' + }); + } + quotaErrorCallbacks.add(callback); + { + logger.log('Registered a callback to respond to quota errors.', callback); + } + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + const _cacheNameDetails = { + googleAnalytics: 'googleAnalytics', + precache: 'precache-v2', + prefix: 'workbox', + runtime: 'runtime', + suffix: typeof registration !== 'undefined' ? registration.scope : '' + }; + const _createCacheName = cacheName => { + return [_cacheNameDetails.prefix, cacheName, _cacheNameDetails.suffix].filter(value => value && value.length > 0).join('-'); + }; + const eachCacheNameDetail = fn => { + for (const key of Object.keys(_cacheNameDetails)) { + fn(key); + } + }; + const cacheNames$1 = { + updateDetails: details => { + eachCacheNameDetail(key => { + if (typeof details[key] === 'string') { + _cacheNameDetails[key] = details[key]; + } + }); + }, + getGoogleAnalyticsName: userCacheName => { + return userCacheName || _createCacheName(_cacheNameDetails.googleAnalytics); + }, + getPrecacheName: userCacheName => { + return userCacheName || _createCacheName(_cacheNameDetails.precache); + }, + getPrefix: () => { + return _cacheNameDetails.prefix; + }, + getRuntimeName: userCacheName => { + return userCacheName || _createCacheName(_cacheNameDetails.runtime); + }, + getSuffix: () => { + return _cacheNameDetails.suffix; + } + }; + + /* + Copyright 2020 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + function stripParams(fullURL, ignoreParams) { + const strippedURL = new URL(fullURL); + for (const param of ignoreParams) { + strippedURL.searchParams.delete(param); + } + return strippedURL.href; + } + /** + * Matches an item in the cache, ignoring specific URL params. This is similar + * to the `ignoreSearch` option, but it allows you to ignore just specific + * params (while continuing to match on the others). + * + * @private + * @param {Cache} cache + * @param {Request} request + * @param {Object} matchOptions + * @param {Array} ignoreParams + * @return {Promise} + */ + async function cacheMatchIgnoreParams(cache, request, ignoreParams, matchOptions) { + const strippedRequestURL = stripParams(request.url, ignoreParams); + // If the request doesn't include any ignored params, match as normal. + if (request.url === strippedRequestURL) { + return cache.match(request, matchOptions); + } + // Otherwise, match by comparing keys + const keysOptions = Object.assign(Object.assign({}, matchOptions), { + ignoreSearch: true + }); + const cacheKeys = await cache.keys(request, keysOptions); + for (const cacheKey of cacheKeys) { + const strippedCacheKeyURL = stripParams(cacheKey.url, ignoreParams); + if (strippedRequestURL === strippedCacheKeyURL) { + return cache.match(cacheKey, matchOptions); + } + } + return; + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + let supportStatus$1; + /** + * A utility function that determines whether the current browser supports + * constructing a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream) + * object. + * + * @return {boolean} `true`, if the current browser can successfully + * construct a `ReadableStream`, `false` otherwise. + * + * @private + */ + function canConstructReadableStream() { + if (supportStatus$1 === undefined) { + // See https://github.com/GoogleChrome/workbox/issues/1473 + try { + new ReadableStream({ + start() {} + }); + supportStatus$1 = true; + } catch (error) { + supportStatus$1 = false; + } + } + return supportStatus$1; + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + let supportStatus; + /** + * A utility function that determines whether the current browser supports + * constructing a new `Response` from a `response.body` stream. + * + * @return {boolean} `true`, if the current browser can successfully + * construct a `Response` from a `response.body` stream, `false` otherwise. + * + * @private + */ + function canConstructResponseFromBodyStream() { + if (supportStatus === undefined) { + const testResponse = new Response(''); + if ('body' in testResponse) { + try { + new Response(testResponse.body); + supportStatus = true; + } catch (error) { + supportStatus = false; + } + } + supportStatus = false; + } + return supportStatus; + } + + /* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * A helper function that prevents a promise from being flagged as unused. + * + * @private + **/ + function dontWaitFor(promise) { + // Effective no-op. + void promise.then(() => {}); + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * The Deferred class composes Promises in a way that allows for them to be + * resolved or rejected from outside the constructor. In most cases promises + * should be used directly, but Deferreds can be necessary when the logic to + * resolve a promise must be separate. + * + * @private + */ + class Deferred { + /** + * Creates a promise and exposes its resolve and reject functions as methods. + */ + constructor() { + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + } + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Runs all of the callback functions, one at a time sequentially, in the order + * in which they were registered. + * + * @memberof workbox-core + * @private + */ + async function executeQuotaErrorCallbacks() { + { + logger.log(`About to run ${quotaErrorCallbacks.size} ` + `callbacks to clean up caches.`); + } + for (const callback of quotaErrorCallbacks) { + await callback(); + { + logger.log(callback, 'is complete.'); + } + } + { + logger.log('Finished running callbacks.'); + } + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + const getFriendlyURL = url => { + const urlObj = new URL(String(url), location.href); + // See https://github.com/GoogleChrome/workbox/issues/2323 + // We want to include everything, except for the origin if it's same-origin. + return urlObj.href.replace(new RegExp(`^${location.origin}`), ''); + }; + + /* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Returns a promise that resolves and the passed number of milliseconds. + * This utility is an async/await-friendly version of `setTimeout`. + * + * @param {number} ms + * @return {Promise} + * @private + */ + function timeout(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); + } + + /* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + const MAX_RETRY_TIME = 2000; + /** + * Returns a promise that resolves to a window client matching the passed + * `resultingClientId`. For browsers that don't support `resultingClientId` + * or if waiting for the resulting client to apper takes too long, resolve to + * `undefined`. + * + * @param {string} [resultingClientId] + * @return {Promise} + * @private + */ + async function resultingClientExists(resultingClientId) { + if (!resultingClientId) { + return; + } + let existingWindows = await self.clients.matchAll({ + type: 'window' + }); + const existingWindowIds = new Set(existingWindows.map(w => w.id)); + let resultingWindow; + const startTime = performance.now(); + // Only wait up to `MAX_RETRY_TIME` to find a matching client. + while (performance.now() - startTime < MAX_RETRY_TIME) { + existingWindows = await self.clients.matchAll({ + type: 'window' + }); + resultingWindow = existingWindows.find(w => { + if (resultingClientId) { + // If we have a `resultingClientId`, we can match on that. + return w.id === resultingClientId; + } else { + // Otherwise match on finding a window not in `existingWindowIds`. + return !existingWindowIds.has(w.id); + } + }); + if (resultingWindow) { + break; + } + // Sleep for 100ms and retry. + await timeout(100); + } + return resultingWindow; + } + + /* + Copyright 2020 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * A utility method that makes it easier to use `event.waitUntil` with + * async functions and return the result. + * + * @param {ExtendableEvent} event + * @param {Function} asyncFn + * @return {Function} + * @private + */ + function waitUntil(event, asyncFn) { + const returnPromise = asyncFn(); + event.waitUntil(returnPromise); + return returnPromise; + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + // We either expose defaults or we expose every named export. + + var _private = /*#__PURE__*/Object.freeze({ + __proto__: null, + Deferred: Deferred, + WorkboxError: WorkboxError, + assert: finalAssertExports, + cacheMatchIgnoreParams: cacheMatchIgnoreParams, + cacheNames: cacheNames$1, + canConstructReadableStream: canConstructReadableStream, + canConstructResponseFromBodyStream: canConstructResponseFromBodyStream, + dontWaitFor: dontWaitFor, + executeQuotaErrorCallbacks: executeQuotaErrorCallbacks, + getFriendlyURL: getFriendlyURL, + logger: logger, + resultingClientExists: resultingClientExists, + timeout: timeout, + waitUntil: waitUntil + }); + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Get the current cache names and prefix/suffix used by Workbox. + * + * `cacheNames.precache` is used for precached assets, + * `cacheNames.googleAnalytics` is used by `workbox-google-analytics` to + * store `analytics.js`, and `cacheNames.runtime` is used for everything else. + * + * `cacheNames.prefix` can be used to retrieve just the current prefix value. + * `cacheNames.suffix` can be used to retrieve just the current suffix value. + * + * @return {Object} An object with `precache`, `runtime`, `prefix`, and + * `googleAnalytics` properties. + * + * @memberof workbox-core + */ + const cacheNames = { + get googleAnalytics() { + return cacheNames$1.getGoogleAnalyticsName(); + }, + get precache() { + return cacheNames$1.getPrecacheName(); + }, + get prefix() { + return cacheNames$1.getPrefix(); + }, + get runtime() { + return cacheNames$1.getRuntimeName(); + }, + get suffix() { + return cacheNames$1.getSuffix(); + } + }; + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Allows developers to copy a response and modify its `headers`, `status`, + * or `statusText` values (the values settable via a + * [`ResponseInit`]{@link https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#Syntax} + * object in the constructor). + * To modify these values, pass a function as the second argument. That + * function will be invoked with a single object with the response properties + * `{headers, status, statusText}`. The return value of this function will + * be used as the `ResponseInit` for the new `Response`. To change the values + * either modify the passed parameter(s) and return it, or return a totally + * new object. + * + * This method is intentionally limited to same-origin responses, regardless of + * whether CORS was used or not. + * + * @param {Response} response + * @param {Function} modifier + * @memberof workbox-core + */ + async function copyResponse(response, modifier) { + let origin = null; + // If response.url isn't set, assume it's cross-origin and keep origin null. + if (response.url) { + const responseURL = new URL(response.url); + origin = responseURL.origin; + } + if (origin !== self.location.origin) { + throw new WorkboxError('cross-origin-copy-response', { + origin + }); + } + const clonedResponse = response.clone(); + // Create a fresh `ResponseInit` object by cloning the headers. + const responseInit = { + headers: new Headers(clonedResponse.headers), + status: clonedResponse.status, + statusText: clonedResponse.statusText + }; + // Apply any user modifications. + const modifiedResponseInit = modifier ? modifier(responseInit) : responseInit; + // Create the new response from the body stream and `ResponseInit` + // modifications. Note: not all browsers support the Response.body stream, + // so fall back to reading the entire body into memory as a blob. + const body = canConstructResponseFromBodyStream() ? clonedResponse.body : await clonedResponse.blob(); + return new Response(body, modifiedResponseInit); + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Claim any currently available clients once the service worker + * becomes active. This is normally used in conjunction with `skipWaiting()`. + * + * @memberof workbox-core + */ + function clientsClaim() { + self.addEventListener('activate', () => self.clients.claim()); + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Modifies the default cache names used by the Workbox packages. + * Cache names are generated as `--`. + * + * @param {Object} details + * @param {Object} [details.prefix] The string to add to the beginning of + * the precache and runtime cache names. + * @param {Object} [details.suffix] The string to add to the end of + * the precache and runtime cache names. + * @param {Object} [details.precache] The cache name to use for precache + * caching. + * @param {Object} [details.runtime] The cache name to use for runtime caching. + * @param {Object} [details.googleAnalytics] The cache name to use for + * `workbox-google-analytics` caching. + * + * @memberof workbox-core + */ + function setCacheNameDetails(details) { + { + Object.keys(details).forEach(key => { + finalAssertExports.isType(details[key], 'string', { + moduleName: 'workbox-core', + funcName: 'setCacheNameDetails', + paramName: `details.${key}` + }); + }); + if ('precache' in details && details['precache'].length === 0) { + throw new WorkboxError('invalid-cache-name', { + cacheNameId: 'precache', + value: details['precache'] + }); + } + if ('runtime' in details && details['runtime'].length === 0) { + throw new WorkboxError('invalid-cache-name', { + cacheNameId: 'runtime', + value: details['runtime'] + }); + } + if ('googleAnalytics' in details && details['googleAnalytics'].length === 0) { + throw new WorkboxError('invalid-cache-name', { + cacheNameId: 'googleAnalytics', + value: details['googleAnalytics'] + }); + } + } + cacheNames$1.updateDetails(details); + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * This method is deprecated, and will be removed in Workbox v7. + * + * Calling self.skipWaiting() is equivalent, and should be used instead. + * + * @memberof workbox-core + */ + function skipWaiting() { + // Just call self.skipWaiting() directly. + // See https://github.com/GoogleChrome/workbox/issues/2525 + { + logger.warn(`skipWaiting() from workbox-core is no longer recommended ` + `and will be removed in Workbox v7. Using self.skipWaiting() instead ` + `is equivalent.`); + } + void self.skipWaiting(); + } + + exports._private = _private; + exports.cacheNames = cacheNames; + exports.clientsClaim = clientsClaim; + exports.copyResponse = copyResponse; + exports.registerQuotaErrorCallback = registerQuotaErrorCallback; + exports.setCacheNameDetails = setCacheNameDetails; + exports.skipWaiting = skipWaiting; + + return exports; + +})({}); +//# sourceMappingURL=workbox-core.dev.js.map diff --git a/node_modules/workbox-core/build/workbox-core.dev.js.map b/node_modules/workbox-core/build/workbox-core.dev.js.map new file mode 100644 index 0000000000000000000000000000000000000000..697b2601e045d6a5a03abd486c698a70b8d7b109 --- /dev/null +++ b/node_modules/workbox-core/build/workbox-core.dev.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-core.dev.js","sources":["../_version.js","../_private/logger.js","../models/messages/messages.js","../models/messages/messageGenerator.js","../_private/WorkboxError.js","../_private/assert.js","../models/quotaErrorCallbacks.js","../registerQuotaErrorCallback.js","../_private/cacheNames.js","../_private/cacheMatchIgnoreParams.js","../_private/canConstructReadableStream.js","../_private/canConstructResponseFromBodyStream.js","../_private/dontWaitFor.js","../_private/Deferred.js","../_private/executeQuotaErrorCallbacks.js","../_private/getFriendlyURL.js","../_private/timeout.js","../_private/resultingClientExists.js","../_private/waitUntil.js","../_private.js","../cacheNames.js","../copyResponse.js","../clientsClaim.js","../setCacheNameDetails.js","../skipWaiting.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:core:7.4.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2019 Google LLC\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';\nconst logger = (process.env.NODE_ENV === 'production'\n ? null\n : (() => {\n // Don't overwrite this value if it's already set.\n // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923\n if (!('__WB_DISABLE_DEV_LOGS' in globalThis)) {\n self.__WB_DISABLE_DEV_LOGS = false;\n }\n let inGroup = false;\n const methodToColorMap = {\n debug: `#7f8c8d`,\n log: `#2ecc71`,\n warn: `#f39c12`,\n error: `#c0392b`,\n groupCollapsed: `#3498db`,\n groupEnd: null, // No colored prefix on groupEnd\n };\n const print = function (method, args) {\n if (self.__WB_DISABLE_DEV_LOGS) {\n return;\n }\n if (method === 'groupCollapsed') {\n // Safari doesn't print all console.groupCollapsed() arguments:\n // https://bugs.webkit.org/show_bug.cgi?id=182754\n if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {\n console[method](...args);\n return;\n }\n }\n const styles = [\n `background: ${methodToColorMap[method]}`,\n `border-radius: 0.5em`,\n `color: white`,\n `font-weight: bold`,\n `padding: 2px 0.5em`,\n ];\n // When in a group, the workbox prefix is not displayed.\n const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')];\n console[method](...logPrefix, ...args);\n if (method === 'groupCollapsed') {\n inGroup = true;\n }\n if (method === 'groupEnd') {\n inGroup = false;\n }\n };\n // eslint-disable-next-line @typescript-eslint/ban-types\n const api = {};\n const loggerMethods = Object.keys(methodToColorMap);\n for (const key of loggerMethods) {\n const method = key;\n api[method] = (...args) => {\n print(method, args);\n };\n }\n return api;\n })());\nexport { logger };\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 messages = {\n 'invalid-value': ({ paramName, validValueDescription, value }) => {\n if (!paramName || !validValueDescription) {\n throw new Error(`Unexpected input to 'invalid-value' error.`);\n }\n return (`The '${paramName}' parameter was given a value with an ` +\n `unexpected value. ${validValueDescription} Received a value of ` +\n `${JSON.stringify(value)}.`);\n },\n 'not-an-array': ({ moduleName, className, funcName, paramName }) => {\n if (!moduleName || !className || !funcName || !paramName) {\n throw new Error(`Unexpected input to 'not-an-array' error.`);\n }\n return (`The parameter '${paramName}' passed into ` +\n `'${moduleName}.${className}.${funcName}()' must be an array.`);\n },\n 'incorrect-type': ({ expectedType, paramName, moduleName, className, funcName, }) => {\n if (!expectedType || !paramName || !moduleName || !funcName) {\n throw new Error(`Unexpected input to 'incorrect-type' error.`);\n }\n const classNameStr = className ? `${className}.` : '';\n return (`The parameter '${paramName}' passed into ` +\n `'${moduleName}.${classNameStr}` +\n `${funcName}()' must be of type ${expectedType}.`);\n },\n 'incorrect-class': ({ expectedClassName, paramName, moduleName, className, funcName, isReturnValueProblem, }) => {\n if (!expectedClassName || !moduleName || !funcName) {\n throw new Error(`Unexpected input to 'incorrect-class' error.`);\n }\n const classNameStr = className ? `${className}.` : '';\n if (isReturnValueProblem) {\n return (`The return value from ` +\n `'${moduleName}.${classNameStr}${funcName}()' ` +\n `must be an instance of class ${expectedClassName}.`);\n }\n return (`The parameter '${paramName}' passed into ` +\n `'${moduleName}.${classNameStr}${funcName}()' ` +\n `must be an instance of class ${expectedClassName}.`);\n },\n 'missing-a-method': ({ expectedMethod, paramName, moduleName, className, funcName, }) => {\n if (!expectedMethod ||\n !paramName ||\n !moduleName ||\n !className ||\n !funcName) {\n throw new Error(`Unexpected input to 'missing-a-method' error.`);\n }\n return (`${moduleName}.${className}.${funcName}() expected the ` +\n `'${paramName}' parameter to expose a '${expectedMethod}' method.`);\n },\n 'add-to-cache-list-unexpected-type': ({ entry }) => {\n return (`An unexpected entry was passed to ` +\n `'workbox-precaching.PrecacheController.addToCacheList()' The entry ` +\n `'${JSON.stringify(entry)}' isn't supported. You must supply an array of ` +\n `strings with one or more characters, objects with a url property or ` +\n `Request objects.`);\n },\n 'add-to-cache-list-conflicting-entries': ({ firstEntry, secondEntry }) => {\n if (!firstEntry || !secondEntry) {\n throw new Error(`Unexpected input to ` + `'add-to-cache-list-duplicate-entries' error.`);\n }\n return (`Two of the entries passed to ` +\n `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` +\n `${firstEntry} but different revision details. Workbox is ` +\n `unable to cache and version the asset correctly. Please remove one ` +\n `of the entries.`);\n },\n 'plugin-error-request-will-fetch': ({ thrownErrorMessage }) => {\n if (!thrownErrorMessage) {\n throw new Error(`Unexpected input to ` + `'plugin-error-request-will-fetch', error.`);\n }\n return (`An error was thrown by a plugins 'requestWillFetch()' method. ` +\n `The thrown error message was: '${thrownErrorMessage}'.`);\n },\n 'invalid-cache-name': ({ cacheNameId, value }) => {\n if (!cacheNameId) {\n throw new Error(`Expected a 'cacheNameId' for error 'invalid-cache-name'`);\n }\n return (`You must provide a name containing at least one character for ` +\n `setCacheDetails({${cacheNameId}: '...'}). Received a value of ` +\n `'${JSON.stringify(value)}'`);\n },\n 'unregister-route-but-not-found-with-method': ({ method }) => {\n if (!method) {\n throw new Error(`Unexpected input to ` +\n `'unregister-route-but-not-found-with-method' error.`);\n }\n return (`The route you're trying to unregister was not previously ` +\n `registered for the method type '${method}'.`);\n },\n 'unregister-route-route-not-registered': () => {\n return (`The route you're trying to unregister was not previously ` +\n `registered.`);\n },\n 'queue-replay-failed': ({ name }) => {\n return `Replaying the background sync queue '${name}' failed.`;\n },\n 'duplicate-queue-name': ({ name }) => {\n return (`The Queue name '${name}' is already being used. ` +\n `All instances of backgroundSync.Queue must be given unique names.`);\n },\n 'expired-test-without-max-age': ({ methodName, paramName }) => {\n return (`The '${methodName}()' method can only be used when the ` +\n `'${paramName}' is used in the constructor.`);\n },\n 'unsupported-route-type': ({ moduleName, className, funcName, paramName }) => {\n return (`The supplied '${paramName}' parameter was an unsupported type. ` +\n `Please check the docs for ${moduleName}.${className}.${funcName} for ` +\n `valid input types.`);\n },\n 'not-array-of-class': ({ value, expectedClass, moduleName, className, funcName, paramName, }) => {\n return (`The supplied '${paramName}' parameter must be an array of ` +\n `'${expectedClass}' objects. Received '${JSON.stringify(value)},'. ` +\n `Please check the call to ${moduleName}.${className}.${funcName}() ` +\n `to fix the issue.`);\n },\n 'max-entries-or-age-required': ({ moduleName, className, funcName }) => {\n return (`You must define either config.maxEntries or config.maxAgeSeconds` +\n `in ${moduleName}.${className}.${funcName}`);\n },\n 'statuses-or-headers-required': ({ moduleName, className, funcName }) => {\n return (`You must define either config.statuses or config.headers` +\n `in ${moduleName}.${className}.${funcName}`);\n },\n 'invalid-string': ({ moduleName, funcName, paramName }) => {\n if (!paramName || !moduleName || !funcName) {\n throw new Error(`Unexpected input to 'invalid-string' error.`);\n }\n return (`When using strings, the '${paramName}' parameter must start with ` +\n `'http' (for cross-origin matches) or '/' (for same-origin matches). ` +\n `Please see the docs for ${moduleName}.${funcName}() for ` +\n `more info.`);\n },\n 'channel-name-required': () => {\n return (`You must provide a channelName to construct a ` +\n `BroadcastCacheUpdate instance.`);\n },\n 'invalid-responses-are-same-args': () => {\n return (`The arguments passed into responsesAreSame() appear to be ` +\n `invalid. Please ensure valid Responses are used.`);\n },\n 'expire-custom-caches-only': () => {\n return (`You must provide a 'cacheName' property when using the ` +\n `expiration plugin with a runtime caching strategy.`);\n },\n 'unit-must-be-bytes': ({ normalizedRangeHeader }) => {\n if (!normalizedRangeHeader) {\n throw new Error(`Unexpected input to 'unit-must-be-bytes' error.`);\n }\n return (`The 'unit' portion of the Range header must be set to 'bytes'. ` +\n `The Range header provided was \"${normalizedRangeHeader}\"`);\n },\n 'single-range-only': ({ normalizedRangeHeader }) => {\n if (!normalizedRangeHeader) {\n throw new Error(`Unexpected input to 'single-range-only' error.`);\n }\n return (`Multiple ranges are not supported. Please use a single start ` +\n `value, and optional end value. The Range header provided was ` +\n `\"${normalizedRangeHeader}\"`);\n },\n 'invalid-range-values': ({ normalizedRangeHeader }) => {\n if (!normalizedRangeHeader) {\n throw new Error(`Unexpected input to 'invalid-range-values' error.`);\n }\n return (`The Range header is missing both start and end values. At least ` +\n `one of those values is needed. The Range header provided was ` +\n `\"${normalizedRangeHeader}\"`);\n },\n 'no-range-header': () => {\n return `No Range header was found in the Request provided.`;\n },\n 'range-not-satisfiable': ({ size, start, end }) => {\n return (`The start (${start}) and end (${end}) values in the Range are ` +\n `not satisfiable by the cached response, which is ${size} bytes.`);\n },\n 'attempt-to-cache-non-get-request': ({ url, method }) => {\n return (`Unable to cache '${url}' because it is a '${method}' request and ` +\n `only 'GET' requests can be cached.`);\n },\n 'cache-put-with-no-response': ({ url }) => {\n return (`There was an attempt to cache '${url}' but the response was not ` +\n `defined.`);\n },\n 'no-response': ({ url, error }) => {\n let message = `The strategy could not generate a response for '${url}'.`;\n if (error) {\n message += ` The underlying error is ${error}.`;\n }\n return message;\n },\n 'bad-precaching-response': ({ url, status }) => {\n return (`The precaching request for '${url}' failed` +\n (status ? ` with an HTTP status of ${status}.` : `.`));\n },\n 'non-precached-url': ({ url }) => {\n return (`createHandlerBoundToURL('${url}') was called, but that URL is ` +\n `not precached. Please pass in a URL that is precached instead.`);\n },\n 'add-to-cache-list-conflicting-integrities': ({ url }) => {\n return (`Two of the entries passed to ` +\n `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` +\n `${url} with different integrity values. Please remove one of them.`);\n },\n 'missing-precache-entry': ({ cacheName, url }) => {\n return `Unable to find a precached response in ${cacheName} for ${url}.`;\n },\n 'cross-origin-copy-response': ({ origin }) => {\n return (`workbox-core.copyResponse() can only be used with same-origin ` +\n `responses. It was passed a response with origin ${origin}.`);\n },\n 'opaque-streams-source': ({ type }) => {\n const message = `One of the workbox-streams sources resulted in an ` +\n `'${type}' response.`;\n if (type === 'opaqueredirect') {\n return (`${message} Please do not use a navigation request that results ` +\n `in a redirect as a source.`);\n }\n return `${message} Please ensure your sources are CORS-enabled.`;\n },\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 { messages } from './messages.js';\nimport '../../_version.js';\nconst fallback = (code, ...args) => {\n let msg = code;\n if (args.length > 0) {\n msg += ` :: ${JSON.stringify(args)}`;\n }\n return msg;\n};\nconst generatorFunction = (code, details = {}) => {\n const message = messages[code];\n if (!message) {\n throw new Error(`Unable to find message for code '${code}'.`);\n }\n return message(details);\n};\nexport const messageGenerator = process.env.NODE_ENV === 'production' ? fallback : generatorFunction;\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 { messageGenerator } from '../models/messages/messageGenerator.js';\nimport '../_version.js';\n/**\n * Workbox errors should be thrown with this class.\n * This allows use to ensure the type easily in tests,\n * helps developers identify errors from workbox\n * easily and allows use to optimise error\n * messages correctly.\n *\n * @private\n */\nclass WorkboxError extends Error {\n /**\n *\n * @param {string} errorCode The error code that\n * identifies this particular error.\n * @param {Object=} details Any relevant arguments\n * that will help developers identify issues should\n * be added as a key on the context object.\n */\n constructor(errorCode, details) {\n const message = messageGenerator(errorCode, details);\n super(message);\n this.name = errorCode;\n this.details = details;\n }\n}\nexport { WorkboxError };\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 '../_private/WorkboxError.js';\nimport '../_version.js';\n/*\n * This method throws if the supplied value is not an array.\n * The destructed values are required to produce a meaningful error for users.\n * The destructed and restructured object is so it's clear what is\n * needed.\n */\nconst isArray = (value, details) => {\n if (!Array.isArray(value)) {\n throw new WorkboxError('not-an-array', details);\n }\n};\nconst hasMethod = (object, expectedMethod, details) => {\n const type = typeof object[expectedMethod];\n if (type !== 'function') {\n details['expectedMethod'] = expectedMethod;\n throw new WorkboxError('missing-a-method', details);\n }\n};\nconst isType = (object, expectedType, details) => {\n if (typeof object !== expectedType) {\n details['expectedType'] = expectedType;\n throw new WorkboxError('incorrect-type', details);\n }\n};\nconst isInstance = (object, \n// Need the general type to do the check later.\n// eslint-disable-next-line @typescript-eslint/ban-types\nexpectedClass, details) => {\n if (!(object instanceof expectedClass)) {\n details['expectedClassName'] = expectedClass.name;\n throw new WorkboxError('incorrect-class', details);\n }\n};\nconst isOneOf = (value, validValues, details) => {\n if (!validValues.includes(value)) {\n details['validValueDescription'] = `Valid values are ${JSON.stringify(validValues)}.`;\n throw new WorkboxError('invalid-value', details);\n }\n};\nconst isArrayOfClass = (value, \n// Need general type to do check later.\nexpectedClass, // eslint-disable-line\ndetails) => {\n const error = new WorkboxError('not-array-of-class', details);\n if (!Array.isArray(value)) {\n throw error;\n }\n for (const item of value) {\n if (!(item instanceof expectedClass)) {\n throw error;\n }\n }\n};\nconst finalAssertExports = process.env.NODE_ENV === 'production'\n ? null\n : {\n hasMethod,\n isArray,\n isInstance,\n isOneOf,\n isType,\n isArrayOfClass,\n };\nexport { finalAssertExports as assert };\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';\n// Callbacks to be executed whenever there's a quota error.\n// Can't change Function type right now.\n// eslint-disable-next-line @typescript-eslint/ban-types\nconst quotaErrorCallbacks = new Set();\nexport { quotaErrorCallbacks };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { logger } from './_private/logger.js';\nimport { assert } from './_private/assert.js';\nimport { quotaErrorCallbacks } from './models/quotaErrorCallbacks.js';\nimport './_version.js';\n/**\n * Adds a function to the set of quotaErrorCallbacks that will be executed if\n * there's a quota error.\n *\n * @param {Function} callback\n * @memberof workbox-core\n */\n// Can't change Function type\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction registerQuotaErrorCallback(callback) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(callback, 'function', {\n moduleName: 'workbox-core',\n funcName: 'register',\n paramName: 'callback',\n });\n }\n quotaErrorCallbacks.add(callback);\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Registered a callback to respond to quota errors.', callback);\n }\n}\nexport { registerQuotaErrorCallback };\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';\nconst _cacheNameDetails = {\n googleAnalytics: 'googleAnalytics',\n precache: 'precache-v2',\n prefix: 'workbox',\n runtime: 'runtime',\n suffix: typeof registration !== 'undefined' ? registration.scope : '',\n};\nconst _createCacheName = (cacheName) => {\n return [_cacheNameDetails.prefix, cacheName, _cacheNameDetails.suffix]\n .filter((value) => value && value.length > 0)\n .join('-');\n};\nconst eachCacheNameDetail = (fn) => {\n for (const key of Object.keys(_cacheNameDetails)) {\n fn(key);\n }\n};\nexport const cacheNames = {\n updateDetails: (details) => {\n eachCacheNameDetail((key) => {\n if (typeof details[key] === 'string') {\n _cacheNameDetails[key] = details[key];\n }\n });\n },\n getGoogleAnalyticsName: (userCacheName) => {\n return userCacheName || _createCacheName(_cacheNameDetails.googleAnalytics);\n },\n getPrecacheName: (userCacheName) => {\n return userCacheName || _createCacheName(_cacheNameDetails.precache);\n },\n getPrefix: () => {\n return _cacheNameDetails.prefix;\n },\n getRuntimeName: (userCacheName) => {\n return userCacheName || _createCacheName(_cacheNameDetails.runtime);\n },\n getSuffix: () => {\n return _cacheNameDetails.suffix;\n },\n};\n","/*\n Copyright 2020 Google LLC\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';\nfunction stripParams(fullURL, ignoreParams) {\n const strippedURL = new URL(fullURL);\n for (const param of ignoreParams) {\n strippedURL.searchParams.delete(param);\n }\n return strippedURL.href;\n}\n/**\n * Matches an item in the cache, ignoring specific URL params. This is similar\n * to the `ignoreSearch` option, but it allows you to ignore just specific\n * params (while continuing to match on the others).\n *\n * @private\n * @param {Cache} cache\n * @param {Request} request\n * @param {Object} matchOptions\n * @param {Array} ignoreParams\n * @return {Promise}\n */\nasync function cacheMatchIgnoreParams(cache, request, ignoreParams, matchOptions) {\n const strippedRequestURL = stripParams(request.url, ignoreParams);\n // If the request doesn't include any ignored params, match as normal.\n if (request.url === strippedRequestURL) {\n return cache.match(request, matchOptions);\n }\n // Otherwise, match by comparing keys\n const keysOptions = Object.assign(Object.assign({}, matchOptions), { ignoreSearch: true });\n const cacheKeys = await cache.keys(request, keysOptions);\n for (const cacheKey of cacheKeys) {\n const strippedCacheKeyURL = stripParams(cacheKey.url, ignoreParams);\n if (strippedRequestURL === strippedCacheKeyURL) {\n return cache.match(cacheKey, matchOptions);\n }\n }\n return;\n}\nexport { cacheMatchIgnoreParams };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\nlet supportStatus;\n/**\n * A utility function that determines whether the current browser supports\n * constructing a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream)\n * object.\n *\n * @return {boolean} `true`, if the current browser can successfully\n * construct a `ReadableStream`, `false` otherwise.\n *\n * @private\n */\nfunction canConstructReadableStream() {\n if (supportStatus === undefined) {\n // See https://github.com/GoogleChrome/workbox/issues/1473\n try {\n new ReadableStream({ start() { } });\n supportStatus = true;\n }\n catch (error) {\n supportStatus = false;\n }\n }\n return supportStatus;\n}\nexport { canConstructReadableStream };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\nlet supportStatus;\n/**\n * A utility function that determines whether the current browser supports\n * constructing a new `Response` from a `response.body` stream.\n *\n * @return {boolean} `true`, if the current browser can successfully\n * construct a `Response` from a `response.body` stream, `false` otherwise.\n *\n * @private\n */\nfunction canConstructResponseFromBodyStream() {\n if (supportStatus === undefined) {\n const testResponse = new Response('');\n if ('body' in testResponse) {\n try {\n new Response(testResponse.body);\n supportStatus = true;\n }\n catch (error) {\n supportStatus = false;\n }\n }\n supportStatus = false;\n }\n return supportStatus;\n}\nexport { canConstructResponseFromBodyStream };\n","/*\n Copyright 2019 Google LLC\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';\n/**\n * A helper function that prevents a promise from being flagged as unused.\n *\n * @private\n **/\nexport function dontWaitFor(promise) {\n // Effective no-op.\n void promise.then(() => { });\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 '../_version.js';\n/**\n * The Deferred class composes Promises in a way that allows for them to be\n * resolved or rejected from outside the constructor. In most cases promises\n * should be used directly, but Deferreds can be necessary when the logic to\n * resolve a promise must be separate.\n *\n * @private\n */\nclass Deferred {\n /**\n * Creates a promise and exposes its resolve and reject functions as methods.\n */\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\nexport { Deferred };\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 { logger } from '../_private/logger.js';\nimport { quotaErrorCallbacks } from '../models/quotaErrorCallbacks.js';\nimport '../_version.js';\n/**\n * Runs all of the callback functions, one at a time sequentially, in the order\n * in which they were registered.\n *\n * @memberof workbox-core\n * @private\n */\nasync function executeQuotaErrorCallbacks() {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`About to run ${quotaErrorCallbacks.size} ` +\n `callbacks to clean up caches.`);\n }\n for (const callback of quotaErrorCallbacks) {\n await callback();\n if (process.env.NODE_ENV !== 'production') {\n logger.log(callback, 'is complete.');\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Finished running callbacks.');\n }\n}\nexport { executeQuotaErrorCallbacks };\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';\nconst getFriendlyURL = (url) => {\n const urlObj = new URL(String(url), location.href);\n // See https://github.com/GoogleChrome/workbox/issues/2323\n // We want to include everything, except for the origin if it's same-origin.\n return urlObj.href.replace(new RegExp(`^${location.origin}`), '');\n};\nexport { getFriendlyURL };\n","/*\n Copyright 2019 Google LLC\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';\n/**\n * Returns a promise that resolves and the passed number of milliseconds.\n * This utility is an async/await-friendly version of `setTimeout`.\n *\n * @param {number} ms\n * @return {Promise}\n * @private\n */\nexport function timeout(ms) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","/*\n Copyright 2019 Google LLC\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 { timeout } from './timeout.js';\nimport '../_version.js';\nconst MAX_RETRY_TIME = 2000;\n/**\n * Returns a promise that resolves to a window client matching the passed\n * `resultingClientId`. For browsers that don't support `resultingClientId`\n * or if waiting for the resulting client to apper takes too long, resolve to\n * `undefined`.\n *\n * @param {string} [resultingClientId]\n * @return {Promise}\n * @private\n */\nexport async function resultingClientExists(resultingClientId) {\n if (!resultingClientId) {\n return;\n }\n let existingWindows = await self.clients.matchAll({ type: 'window' });\n const existingWindowIds = new Set(existingWindows.map((w) => w.id));\n let resultingWindow;\n const startTime = performance.now();\n // Only wait up to `MAX_RETRY_TIME` to find a matching client.\n while (performance.now() - startTime < MAX_RETRY_TIME) {\n existingWindows = await self.clients.matchAll({ type: 'window' });\n resultingWindow = existingWindows.find((w) => {\n if (resultingClientId) {\n // If we have a `resultingClientId`, we can match on that.\n return w.id === resultingClientId;\n }\n else {\n // Otherwise match on finding a window not in `existingWindowIds`.\n return !existingWindowIds.has(w.id);\n }\n });\n if (resultingWindow) {\n break;\n }\n // Sleep for 100ms and retry.\n await timeout(100);\n }\n return resultingWindow;\n}\n","/*\n Copyright 2020 Google LLC\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';\n/**\n * A utility method that makes it easier to use `event.waitUntil` with\n * async functions and return the result.\n *\n * @param {ExtendableEvent} event\n * @param {Function} asyncFn\n * @return {Function}\n * @private\n */\nfunction waitUntil(event, asyncFn) {\n const returnPromise = asyncFn();\n event.waitUntil(returnPromise);\n return returnPromise;\n}\nexport { waitUntil };\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*/\n// We either expose defaults or we expose every named export.\nimport { assert } from './_private/assert.js';\nimport { cacheNames } from './_private/cacheNames.js';\nimport { cacheMatchIgnoreParams } from './_private/cacheMatchIgnoreParams.js';\nimport { canConstructReadableStream } from './_private/canConstructReadableStream.js';\nimport { canConstructResponseFromBodyStream } from './_private/canConstructResponseFromBodyStream.js';\nimport { dontWaitFor } from './_private/dontWaitFor.js';\nimport { Deferred } from './_private/Deferred.js';\nimport { executeQuotaErrorCallbacks } from './_private/executeQuotaErrorCallbacks.js';\nimport { getFriendlyURL } from './_private/getFriendlyURL.js';\nimport { logger } from './_private/logger.js';\nimport { resultingClientExists } from './_private/resultingClientExists.js';\nimport { timeout } from './_private/timeout.js';\nimport { waitUntil } from './_private/waitUntil.js';\nimport { WorkboxError } from './_private/WorkboxError.js';\nimport './_version.js';\nexport { assert, cacheMatchIgnoreParams, cacheNames, canConstructReadableStream, canConstructResponseFromBodyStream, dontWaitFor, Deferred, executeQuotaErrorCallbacks, getFriendlyURL, logger, resultingClientExists, timeout, waitUntil, WorkboxError, };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { cacheNames as _cacheNames } from './_private/cacheNames.js';\nimport './_version.js';\n/**\n * Get the current cache names and prefix/suffix used by Workbox.\n *\n * `cacheNames.precache` is used for precached assets,\n * `cacheNames.googleAnalytics` is used by `workbox-google-analytics` to\n * store `analytics.js`, and `cacheNames.runtime` is used for everything else.\n *\n * `cacheNames.prefix` can be used to retrieve just the current prefix value.\n * `cacheNames.suffix` can be used to retrieve just the current suffix value.\n *\n * @return {Object} An object with `precache`, `runtime`, `prefix`, and\n * `googleAnalytics` properties.\n *\n * @memberof workbox-core\n */\nconst cacheNames = {\n get googleAnalytics() {\n return _cacheNames.getGoogleAnalyticsName();\n },\n get precache() {\n return _cacheNames.getPrecacheName();\n },\n get prefix() {\n return _cacheNames.getPrefix();\n },\n get runtime() {\n return _cacheNames.getRuntimeName();\n },\n get suffix() {\n return _cacheNames.getSuffix();\n },\n};\nexport { cacheNames };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { canConstructResponseFromBodyStream } from './_private/canConstructResponseFromBodyStream.js';\nimport { WorkboxError } from './_private/WorkboxError.js';\nimport './_version.js';\n/**\n * Allows developers to copy a response and modify its `headers`, `status`,\n * or `statusText` values (the values settable via a\n * [`ResponseInit`]{@link https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#Syntax}\n * object in the constructor).\n * To modify these values, pass a function as the second argument. That\n * function will be invoked with a single object with the response properties\n * `{headers, status, statusText}`. The return value of this function will\n * be used as the `ResponseInit` for the new `Response`. To change the values\n * either modify the passed parameter(s) and return it, or return a totally\n * new object.\n *\n * This method is intentionally limited to same-origin responses, regardless of\n * whether CORS was used or not.\n *\n * @param {Response} response\n * @param {Function} modifier\n * @memberof workbox-core\n */\nasync function copyResponse(response, modifier) {\n let origin = null;\n // If response.url isn't set, assume it's cross-origin and keep origin null.\n if (response.url) {\n const responseURL = new URL(response.url);\n origin = responseURL.origin;\n }\n if (origin !== self.location.origin) {\n throw new WorkboxError('cross-origin-copy-response', { origin });\n }\n const clonedResponse = response.clone();\n // Create a fresh `ResponseInit` object by cloning the headers.\n const responseInit = {\n headers: new Headers(clonedResponse.headers),\n status: clonedResponse.status,\n statusText: clonedResponse.statusText,\n };\n // Apply any user modifications.\n const modifiedResponseInit = modifier ? modifier(responseInit) : responseInit;\n // Create the new response from the body stream and `ResponseInit`\n // modifications. Note: not all browsers support the Response.body stream,\n // so fall back to reading the entire body into memory as a blob.\n const body = canConstructResponseFromBodyStream()\n ? clonedResponse.body\n : await clonedResponse.blob();\n return new Response(body, modifiedResponseInit);\n}\nexport { copyResponse };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport './_version.js';\n/**\n * Claim any currently available clients once the service worker\n * becomes active. This is normally used in conjunction with `skipWaiting()`.\n *\n * @memberof workbox-core\n */\nfunction clientsClaim() {\n self.addEventListener('activate', () => self.clients.claim());\n}\nexport { clientsClaim };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from './_private/assert.js';\nimport { cacheNames } from './_private/cacheNames.js';\nimport { WorkboxError } from './_private/WorkboxError.js';\nimport './_version.js';\n/**\n * Modifies the default cache names used by the Workbox packages.\n * Cache names are generated as `--`.\n *\n * @param {Object} details\n * @param {Object} [details.prefix] The string to add to the beginning of\n * the precache and runtime cache names.\n * @param {Object} [details.suffix] The string to add to the end of\n * the precache and runtime cache names.\n * @param {Object} [details.precache] The cache name to use for precache\n * caching.\n * @param {Object} [details.runtime] The cache name to use for runtime caching.\n * @param {Object} [details.googleAnalytics] The cache name to use for\n * `workbox-google-analytics` caching.\n *\n * @memberof workbox-core\n */\nfunction setCacheNameDetails(details) {\n if (process.env.NODE_ENV !== 'production') {\n Object.keys(details).forEach((key) => {\n assert.isType(details[key], 'string', {\n moduleName: 'workbox-core',\n funcName: 'setCacheNameDetails',\n paramName: `details.${key}`,\n });\n });\n if ('precache' in details && details['precache'].length === 0) {\n throw new WorkboxError('invalid-cache-name', {\n cacheNameId: 'precache',\n value: details['precache'],\n });\n }\n if ('runtime' in details && details['runtime'].length === 0) {\n throw new WorkboxError('invalid-cache-name', {\n cacheNameId: 'runtime',\n value: details['runtime'],\n });\n }\n if ('googleAnalytics' in details &&\n details['googleAnalytics'].length === 0) {\n throw new WorkboxError('invalid-cache-name', {\n cacheNameId: 'googleAnalytics',\n value: details['googleAnalytics'],\n });\n }\n }\n cacheNames.updateDetails(details);\n}\nexport { setCacheNameDetails };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { logger } from './_private/logger.js';\nimport './_version.js';\n/**\n * This method is deprecated, and will be removed in Workbox v7.\n *\n * Calling self.skipWaiting() is equivalent, and should be used instead.\n *\n * @memberof workbox-core\n */\nfunction skipWaiting() {\n // Just call self.skipWaiting() directly.\n // See https://github.com/GoogleChrome/workbox/issues/2525\n if (process.env.NODE_ENV !== 'production') {\n logger.warn(`skipWaiting() from workbox-core is no longer recommended ` +\n `and will be removed in Workbox v7. Using self.skipWaiting() instead ` +\n `is equivalent.`);\n }\n void self.skipWaiting();\n}\nexport { skipWaiting };\n"],"names":["self","_","e","logger","globalThis","__WB_DISABLE_DEV_LOGS","inGroup","methodToColorMap","debug","log","warn","error","groupCollapsed","groupEnd","print","method","args","test","navigator","userAgent","console","styles","logPrefix","join","api","loggerMethods","Object","keys","key","messages","invalid-value","paramName","validValueDescription","value","Error","JSON","stringify","not-an-array","moduleName","className","funcName","incorrect-type","expectedType","classNameStr","incorrect-class","expectedClassName","isReturnValueProblem","missing-a-method","expectedMethod","add-to-cache-list-unexpected-type","entry","add-to-cache-list-conflicting-entries","firstEntry","secondEntry","plugin-error-request-will-fetch","thrownErrorMessage","invalid-cache-name","cacheNameId","unregister-route-but-not-found-with-method","unregister-route-route-not-registered","queue-replay-failed","name","duplicate-queue-name","expired-test-without-max-age","methodName","unsupported-route-type","not-array-of-class","expectedClass","max-entries-or-age-required","statuses-or-headers-required","invalid-string","channel-name-required","invalid-responses-are-same-args","expire-custom-caches-only","unit-must-be-bytes","normalizedRangeHeader","single-range-only","invalid-range-values","no-range-header","range-not-satisfiable","size","start","end","attempt-to-cache-non-get-request","url","cache-put-with-no-response","no-response","message","bad-precaching-response","status","non-precached-url","add-to-cache-list-conflicting-integrities","missing-precache-entry","cacheName","cross-origin-copy-response","origin","opaque-streams-source","type","generatorFunction","code","details","messageGenerator","WorkboxError","constructor","errorCode","isArray","Array","hasMethod","object","isType","isInstance","isOneOf","validValues","includes","isArrayOfClass","item","finalAssertExports","quotaErrorCallbacks","Set","registerQuotaErrorCallback","callback","assert","add","_cacheNameDetails","googleAnalytics","precache","prefix","runtime","suffix","registration","scope","_createCacheName","filter","length","eachCacheNameDetail","fn","cacheNames","updateDetails","getGoogleAnalyticsName","userCacheName","getPrecacheName","getPrefix","getRuntimeName","getSuffix","stripParams","fullURL","ignoreParams","strippedURL","URL","param","searchParams","delete","href","cacheMatchIgnoreParams","cache","request","matchOptions","strippedRequestURL","match","keysOptions","assign","ignoreSearch","cacheKeys","cacheKey","strippedCacheKeyURL","supportStatus","canConstructReadableStream","undefined","ReadableStream","canConstructResponseFromBodyStream","testResponse","Response","body","dontWaitFor","promise","then","Deferred","Promise","resolve","reject","executeQuotaErrorCallbacks","getFriendlyURL","urlObj","String","location","replace","RegExp","timeout","ms","setTimeout","MAX_RETRY_TIME","resultingClientExists","resultingClientId","existingWindows","clients","matchAll","existingWindowIds","map","w","id","resultingWindow","startTime","performance","now","find","has","waitUntil","event","asyncFn","returnPromise","_cacheNames","copyResponse","response","modifier","responseURL","clonedResponse","clone","responseInit","headers","Headers","statusText","modifiedResponseInit","blob","clientsClaim","addEventListener","claim","setCacheNameDetails","forEach","skipWaiting"],"mappings":";;;;IACA;IACA,IAAI;IACAA,EAAAA,IAAI,CAAC,oBAAoB,CAAC,IAAIC,CAAC,EAAE;IACrC,CAAC,CACD,OAAOC,CAAC,EAAE,CAAE;;ICLZ;IACA;IACA;IACA;IACA;IACA;IAEA,MAAMC,MAAM,GAEN,CAAC,MAAM;IACL;IACA;IACA,EAAA,IAAI,EAAE,uBAAuB,IAAIC,UAAU,CAAC,EAAE;QAC1CJ,IAAI,CAACK,qBAAqB,GAAG,KAAK;IACtC,EAAA;MACA,IAAIC,OAAO,GAAG,KAAK;IACnB,EAAA,MAAMC,gBAAgB,GAAG;IACrBC,IAAAA,KAAK,EAAG,CAAA,OAAA,CAAQ;IAChBC,IAAAA,GAAG,EAAG,CAAA,OAAA,CAAQ;IACdC,IAAAA,IAAI,EAAG,CAAA,OAAA,CAAQ;IACfC,IAAAA,KAAK,EAAG,CAAA,OAAA,CAAQ;IAChBC,IAAAA,cAAc,EAAG,CAAA,OAAA,CAAQ;QACzBC,QAAQ,EAAE,IAAI;OACjB;IACD,EAAA,MAAMC,KAAK,GAAG,UAAUC,MAAM,EAAEC,IAAI,EAAE;QAClC,IAAIhB,IAAI,CAACK,qBAAqB,EAAE;IAC5B,MAAA;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A;IACJ,EAAA;IACAoC,EAAAA,YAAU,CAACC,aAAa,CAACrC,OAAO,CAAC;IACrC;;IC1DA;IACA;;IAEA;IACA;IACA;IACA;IAGA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,SAASgI,WAAWA,GAAG;IACnB;IACA;IACA,EAA2C;QACvCjO,MAAM,CAACO,IAAI,CAAE,CAAA,yDAAA,CAA0D,GAClE,CAAA,oEAAA,CAAqE,GACrE,gBAAe,CAAC;IACzB,EAAA;IACA,EAAA,KAAKV,IAAI,CAACoO,WAAW,EAAE;IAC3B;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/workbox-core/build/workbox-core.prod.js b/node_modules/workbox-core/build/workbox-core.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..92f71756466f002a243adc27715bad0fd1d86561 --- /dev/null +++ b/node_modules/workbox-core/build/workbox-core.prod.js @@ -0,0 +1,2 @@ +this.workbox=this.workbox||{},this.workbox.core=function(t){"use strict";try{self["workbox:core:7.4.0"]&&_()}catch(t){}const e=(t,...e)=>{let n=t;return e.length>0&&(n+=` :: ${JSON.stringify(e)}`),n};class n extends Error{constructor(t,n){super(e(t,n)),this.name=t,this.details=n}}const r=new Set;const o={googleAnalytics:"googleAnalytics",precache:"precache-v2",prefix:"workbox",runtime:"runtime",suffix:"undefined"!=typeof registration?registration.scope:""},s=t=>[o.prefix,t,o.suffix].filter((t=>t&&t.length>0)).join("-"),i={updateDetails:t=>{(t=>{for(const e of Object.keys(o))t(e)})((e=>{"string"==typeof t[e]&&(o[e]=t[e])}))},getGoogleAnalyticsName:t=>t||s(o.googleAnalytics),getPrecacheName:t=>t||s(o.precache),getPrefix:()=>o.prefix,getRuntimeName:t=>t||s(o.runtime),getSuffix:()=>o.suffix};function c(t,e){const n=new URL(t);for(const t of e)n.searchParams.delete(t);return n.href}let a,u;function f(){if(void 0===u){const t=new Response("");if("body"in t)try{new Response(t.body),u=!0}catch(t){u=!1}u=!1}return u}function l(t){return new Promise((e=>setTimeout(e,t)))}var g=Object.freeze({__proto__:null,Deferred:class{constructor(){this.promise=new Promise(((t,e)=>{this.resolve=t,this.reject=e}))}},WorkboxError:n,assert:null,cacheMatchIgnoreParams:async function(t,e,n,r){const o=c(e.url,n);if(e.url===o)return t.match(e,r);const s=Object.assign(Object.assign({},r),{ignoreSearch:!0}),i=await t.keys(e,s);for(const e of i){if(o===c(e.url,n))return t.match(e,r)}},cacheNames:i,canConstructReadableStream:function(){if(void 0===a)try{new ReadableStream({start(){}}),a=!0}catch(t){a=!1}return a},canConstructResponseFromBodyStream:f,dontWaitFor:function(t){t.then((()=>{}))},executeQuotaErrorCallbacks:async function(){for(const t of r)await t()},getFriendlyURL:t=>new URL(String(t),location.href).href.replace(new RegExp(`^${location.origin}`),""),logger:null,resultingClientExists:async function(t){if(!t)return;let e=await self.clients.matchAll({type:"window"});const n=new Set(e.map((t=>t.id)));let r;const o=performance.now();for(;performance.now()-o<2e3&&(e=await self.clients.matchAll({type:"window"}),r=e.find((e=>t?e.id===t:!n.has(e.id))),!r);)await l(100);return r},timeout:l,waitUntil:function(t,e){const n=e();return t.waitUntil(n),n}});const w={get googleAnalytics(){return i.getGoogleAnalyticsName()},get precache(){return i.getPrecacheName()},get prefix(){return i.getPrefix()},get runtime(){return i.getRuntimeName()},get suffix(){return i.getSuffix()}};return t._private=g,t.cacheNames=w,t.clientsClaim=function(){self.addEventListener("activate",(()=>self.clients.claim()))},t.copyResponse=async function(t,e){let r=null;if(t.url){r=new URL(t.url).origin}if(r!==self.location.origin)throw new n("cross-origin-copy-response",{origin:r});const o=t.clone(),s={headers:new Headers(o.headers),status:o.status,statusText:o.statusText},i=e?e(s):s,c=f()?o.body:await o.blob();return new Response(c,i)},t.registerQuotaErrorCallback=function(t){r.add(t)},t.setCacheNameDetails=function(t){i.updateDetails(t)},t.skipWaiting=function(){self.skipWaiting()},t}({}); +//# sourceMappingURL=workbox-core.prod.js.map diff --git a/node_modules/workbox-core/build/workbox-core.prod.js.map b/node_modules/workbox-core/build/workbox-core.prod.js.map new file mode 100644 index 0000000000000000000000000000000000000000..0be80bd70080a9067d16a34020a4bce4d5bb943c --- /dev/null +++ b/node_modules/workbox-core/build/workbox-core.prod.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-core.prod.js","sources":["../_version.js","../_private/logger.js","../models/messages/messageGenerator.js","../_private/WorkboxError.js","../_private/assert.js","../models/quotaErrorCallbacks.js","../_private/cacheNames.js","../_private/cacheMatchIgnoreParams.js","../_private/canConstructReadableStream.js","../_private/canConstructResponseFromBodyStream.js","../_private/timeout.js","../_private/Deferred.js","../_private/dontWaitFor.js","../_private/executeQuotaErrorCallbacks.js","../_private/getFriendlyURL.js","../_private/resultingClientExists.js","../_private/waitUntil.js","../cacheNames.js","../clientsClaim.js","../copyResponse.js","../registerQuotaErrorCallback.js","../setCacheNameDetails.js","../skipWaiting.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:core:7.4.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2019 Google LLC\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';\nconst logger = (process.env.NODE_ENV === 'production'\n ? null\n : (() => {\n // Don't overwrite this value if it's already set.\n // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923\n if (!('__WB_DISABLE_DEV_LOGS' in globalThis)) {\n self.__WB_DISABLE_DEV_LOGS = false;\n }\n let inGroup = false;\n const methodToColorMap = {\n debug: `#7f8c8d`,\n log: `#2ecc71`,\n warn: `#f39c12`,\n error: `#c0392b`,\n groupCollapsed: `#3498db`,\n groupEnd: null, // No colored prefix on groupEnd\n };\n const print = function (method, args) {\n if (self.__WB_DISABLE_DEV_LOGS) {\n return;\n }\n if (method === 'groupCollapsed') {\n // Safari doesn't print all console.groupCollapsed() arguments:\n // https://bugs.webkit.org/show_bug.cgi?id=182754\n if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {\n console[method](...args);\n return;\n }\n }\n const styles = [\n `background: ${methodToColorMap[method]}`,\n `border-radius: 0.5em`,\n `color: white`,\n `font-weight: bold`,\n `padding: 2px 0.5em`,\n ];\n // When in a group, the workbox prefix is not displayed.\n const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')];\n console[method](...logPrefix, ...args);\n if (method === 'groupCollapsed') {\n inGroup = true;\n }\n if (method === 'groupEnd') {\n inGroup = false;\n }\n };\n // eslint-disable-next-line @typescript-eslint/ban-types\n const api = {};\n const loggerMethods = Object.keys(methodToColorMap);\n for (const key of loggerMethods) {\n const method = key;\n api[method] = (...args) => {\n print(method, args);\n };\n }\n return api;\n })());\nexport { logger };\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 { messages } from './messages.js';\nimport '../../_version.js';\nconst fallback = (code, ...args) => {\n let msg = code;\n if (args.length > 0) {\n msg += ` :: ${JSON.stringify(args)}`;\n }\n return msg;\n};\nconst generatorFunction = (code, details = {}) => {\n const message = messages[code];\n if (!message) {\n throw new Error(`Unable to find message for code '${code}'.`);\n }\n return message(details);\n};\nexport const messageGenerator = process.env.NODE_ENV === 'production' ? fallback : generatorFunction;\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 { messageGenerator } from '../models/messages/messageGenerator.js';\nimport '../_version.js';\n/**\n * Workbox errors should be thrown with this class.\n * This allows use to ensure the type easily in tests,\n * helps developers identify errors from workbox\n * easily and allows use to optimise error\n * messages correctly.\n *\n * @private\n */\nclass WorkboxError extends Error {\n /**\n *\n * @param {string} errorCode The error code that\n * identifies this particular error.\n * @param {Object=} details Any relevant arguments\n * that will help developers identify issues should\n * be added as a key on the context object.\n */\n constructor(errorCode, details) {\n const message = messageGenerator(errorCode, details);\n super(message);\n this.name = errorCode;\n this.details = details;\n }\n}\nexport { WorkboxError };\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 '../_private/WorkboxError.js';\nimport '../_version.js';\n/*\n * This method throws if the supplied value is not an array.\n * The destructed values are required to produce a meaningful error for users.\n * The destructed and restructured object is so it's clear what is\n * needed.\n */\nconst isArray = (value, details) => {\n if (!Array.isArray(value)) {\n throw new WorkboxError('not-an-array', details);\n }\n};\nconst hasMethod = (object, expectedMethod, details) => {\n const type = typeof object[expectedMethod];\n if (type !== 'function') {\n details['expectedMethod'] = expectedMethod;\n throw new WorkboxError('missing-a-method', details);\n }\n};\nconst isType = (object, expectedType, details) => {\n if (typeof object !== expectedType) {\n details['expectedType'] = expectedType;\n throw new WorkboxError('incorrect-type', details);\n }\n};\nconst isInstance = (object, \n// Need the general type to do the check later.\n// eslint-disable-next-line @typescript-eslint/ban-types\nexpectedClass, details) => {\n if (!(object instanceof expectedClass)) {\n details['expectedClassName'] = expectedClass.name;\n throw new WorkboxError('incorrect-class', details);\n }\n};\nconst isOneOf = (value, validValues, details) => {\n if (!validValues.includes(value)) {\n details['validValueDescription'] = `Valid values are ${JSON.stringify(validValues)}.`;\n throw new WorkboxError('invalid-value', details);\n }\n};\nconst isArrayOfClass = (value, \n// Need general type to do check later.\nexpectedClass, // eslint-disable-line\ndetails) => {\n const error = new WorkboxError('not-array-of-class', details);\n if (!Array.isArray(value)) {\n throw error;\n }\n for (const item of value) {\n if (!(item instanceof expectedClass)) {\n throw error;\n }\n }\n};\nconst finalAssertExports = process.env.NODE_ENV === 'production'\n ? null\n : {\n hasMethod,\n isArray,\n isInstance,\n isOneOf,\n isType,\n isArrayOfClass,\n };\nexport { finalAssertExports as assert };\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';\n// Callbacks to be executed whenever there's a quota error.\n// Can't change Function type right now.\n// eslint-disable-next-line @typescript-eslint/ban-types\nconst quotaErrorCallbacks = new Set();\nexport { quotaErrorCallbacks };\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';\nconst _cacheNameDetails = {\n googleAnalytics: 'googleAnalytics',\n precache: 'precache-v2',\n prefix: 'workbox',\n runtime: 'runtime',\n suffix: typeof registration !== 'undefined' ? registration.scope : '',\n};\nconst _createCacheName = (cacheName) => {\n return [_cacheNameDetails.prefix, cacheName, _cacheNameDetails.suffix]\n .filter((value) => value && value.length > 0)\n .join('-');\n};\nconst eachCacheNameDetail = (fn) => {\n for (const key of Object.keys(_cacheNameDetails)) {\n fn(key);\n }\n};\nexport const cacheNames = {\n updateDetails: (details) => {\n eachCacheNameDetail((key) => {\n if (typeof details[key] === 'string') {\n _cacheNameDetails[key] = details[key];\n }\n });\n },\n getGoogleAnalyticsName: (userCacheName) => {\n return userCacheName || _createCacheName(_cacheNameDetails.googleAnalytics);\n },\n getPrecacheName: (userCacheName) => {\n return userCacheName || _createCacheName(_cacheNameDetails.precache);\n },\n getPrefix: () => {\n return _cacheNameDetails.prefix;\n },\n getRuntimeName: (userCacheName) => {\n return userCacheName || _createCacheName(_cacheNameDetails.runtime);\n },\n getSuffix: () => {\n return _cacheNameDetails.suffix;\n },\n};\n","/*\n Copyright 2020 Google LLC\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';\nfunction stripParams(fullURL, ignoreParams) {\n const strippedURL = new URL(fullURL);\n for (const param of ignoreParams) {\n strippedURL.searchParams.delete(param);\n }\n return strippedURL.href;\n}\n/**\n * Matches an item in the cache, ignoring specific URL params. This is similar\n * to the `ignoreSearch` option, but it allows you to ignore just specific\n * params (while continuing to match on the others).\n *\n * @private\n * @param {Cache} cache\n * @param {Request} request\n * @param {Object} matchOptions\n * @param {Array} ignoreParams\n * @return {Promise}\n */\nasync function cacheMatchIgnoreParams(cache, request, ignoreParams, matchOptions) {\n const strippedRequestURL = stripParams(request.url, ignoreParams);\n // If the request doesn't include any ignored params, match as normal.\n if (request.url === strippedRequestURL) {\n return cache.match(request, matchOptions);\n }\n // Otherwise, match by comparing keys\n const keysOptions = Object.assign(Object.assign({}, matchOptions), { ignoreSearch: true });\n const cacheKeys = await cache.keys(request, keysOptions);\n for (const cacheKey of cacheKeys) {\n const strippedCacheKeyURL = stripParams(cacheKey.url, ignoreParams);\n if (strippedRequestURL === strippedCacheKeyURL) {\n return cache.match(cacheKey, matchOptions);\n }\n }\n return;\n}\nexport { cacheMatchIgnoreParams };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\nlet supportStatus;\n/**\n * A utility function that determines whether the current browser supports\n * constructing a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream)\n * object.\n *\n * @return {boolean} `true`, if the current browser can successfully\n * construct a `ReadableStream`, `false` otherwise.\n *\n * @private\n */\nfunction canConstructReadableStream() {\n if (supportStatus === undefined) {\n // See https://github.com/GoogleChrome/workbox/issues/1473\n try {\n new ReadableStream({ start() { } });\n supportStatus = true;\n }\n catch (error) {\n supportStatus = false;\n }\n }\n return supportStatus;\n}\nexport { canConstructReadableStream };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\nlet supportStatus;\n/**\n * A utility function that determines whether the current browser supports\n * constructing a new `Response` from a `response.body` stream.\n *\n * @return {boolean} `true`, if the current browser can successfully\n * construct a `Response` from a `response.body` stream, `false` otherwise.\n *\n * @private\n */\nfunction canConstructResponseFromBodyStream() {\n if (supportStatus === undefined) {\n const testResponse = new Response('');\n if ('body' in testResponse) {\n try {\n new Response(testResponse.body);\n supportStatus = true;\n }\n catch (error) {\n supportStatus = false;\n }\n }\n supportStatus = false;\n }\n return supportStatus;\n}\nexport { canConstructResponseFromBodyStream };\n","/*\n Copyright 2019 Google LLC\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';\n/**\n * Returns a promise that resolves and the passed number of milliseconds.\n * This utility is an async/await-friendly version of `setTimeout`.\n *\n * @param {number} ms\n * @return {Promise}\n * @private\n */\nexport function timeout(ms) {\n return new Promise((resolve) => setTimeout(resolve, ms));\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 '../_version.js';\n/**\n * The Deferred class composes Promises in a way that allows for them to be\n * resolved or rejected from outside the constructor. In most cases promises\n * should be used directly, but Deferreds can be necessary when the logic to\n * resolve a promise must be separate.\n *\n * @private\n */\nclass Deferred {\n /**\n * Creates a promise and exposes its resolve and reject functions as methods.\n */\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\nexport { Deferred };\n","/*\n Copyright 2019 Google LLC\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';\n/**\n * A helper function that prevents a promise from being flagged as unused.\n *\n * @private\n **/\nexport function dontWaitFor(promise) {\n // Effective no-op.\n void promise.then(() => { });\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 { logger } from '../_private/logger.js';\nimport { quotaErrorCallbacks } from '../models/quotaErrorCallbacks.js';\nimport '../_version.js';\n/**\n * Runs all of the callback functions, one at a time sequentially, in the order\n * in which they were registered.\n *\n * @memberof workbox-core\n * @private\n */\nasync function executeQuotaErrorCallbacks() {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`About to run ${quotaErrorCallbacks.size} ` +\n `callbacks to clean up caches.`);\n }\n for (const callback of quotaErrorCallbacks) {\n await callback();\n if (process.env.NODE_ENV !== 'production') {\n logger.log(callback, 'is complete.');\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Finished running callbacks.');\n }\n}\nexport { executeQuotaErrorCallbacks };\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';\nconst getFriendlyURL = (url) => {\n const urlObj = new URL(String(url), location.href);\n // See https://github.com/GoogleChrome/workbox/issues/2323\n // We want to include everything, except for the origin if it's same-origin.\n return urlObj.href.replace(new RegExp(`^${location.origin}`), '');\n};\nexport { getFriendlyURL };\n","/*\n Copyright 2019 Google LLC\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 { timeout } from './timeout.js';\nimport '../_version.js';\nconst MAX_RETRY_TIME = 2000;\n/**\n * Returns a promise that resolves to a window client matching the passed\n * `resultingClientId`. For browsers that don't support `resultingClientId`\n * or if waiting for the resulting client to apper takes too long, resolve to\n * `undefined`.\n *\n * @param {string} [resultingClientId]\n * @return {Promise}\n * @private\n */\nexport async function resultingClientExists(resultingClientId) {\n if (!resultingClientId) {\n return;\n }\n let existingWindows = await self.clients.matchAll({ type: 'window' });\n const existingWindowIds = new Set(existingWindows.map((w) => w.id));\n let resultingWindow;\n const startTime = performance.now();\n // Only wait up to `MAX_RETRY_TIME` to find a matching client.\n while (performance.now() - startTime < MAX_RETRY_TIME) {\n existingWindows = await self.clients.matchAll({ type: 'window' });\n resultingWindow = existingWindows.find((w) => {\n if (resultingClientId) {\n // If we have a `resultingClientId`, we can match on that.\n return w.id === resultingClientId;\n }\n else {\n // Otherwise match on finding a window not in `existingWindowIds`.\n return !existingWindowIds.has(w.id);\n }\n });\n if (resultingWindow) {\n break;\n }\n // Sleep for 100ms and retry.\n await timeout(100);\n }\n return resultingWindow;\n}\n","/*\n Copyright 2020 Google LLC\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';\n/**\n * A utility method that makes it easier to use `event.waitUntil` with\n * async functions and return the result.\n *\n * @param {ExtendableEvent} event\n * @param {Function} asyncFn\n * @return {Function}\n * @private\n */\nfunction waitUntil(event, asyncFn) {\n const returnPromise = asyncFn();\n event.waitUntil(returnPromise);\n return returnPromise;\n}\nexport { waitUntil };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { cacheNames as _cacheNames } from './_private/cacheNames.js';\nimport './_version.js';\n/**\n * Get the current cache names and prefix/suffix used by Workbox.\n *\n * `cacheNames.precache` is used for precached assets,\n * `cacheNames.googleAnalytics` is used by `workbox-google-analytics` to\n * store `analytics.js`, and `cacheNames.runtime` is used for everything else.\n *\n * `cacheNames.prefix` can be used to retrieve just the current prefix value.\n * `cacheNames.suffix` can be used to retrieve just the current suffix value.\n *\n * @return {Object} An object with `precache`, `runtime`, `prefix`, and\n * `googleAnalytics` properties.\n *\n * @memberof workbox-core\n */\nconst cacheNames = {\n get googleAnalytics() {\n return _cacheNames.getGoogleAnalyticsName();\n },\n get precache() {\n return _cacheNames.getPrecacheName();\n },\n get prefix() {\n return _cacheNames.getPrefix();\n },\n get runtime() {\n return _cacheNames.getRuntimeName();\n },\n get suffix() {\n return _cacheNames.getSuffix();\n },\n};\nexport { cacheNames };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport './_version.js';\n/**\n * Claim any currently available clients once the service worker\n * becomes active. This is normally used in conjunction with `skipWaiting()`.\n *\n * @memberof workbox-core\n */\nfunction clientsClaim() {\n self.addEventListener('activate', () => self.clients.claim());\n}\nexport { clientsClaim };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { canConstructResponseFromBodyStream } from './_private/canConstructResponseFromBodyStream.js';\nimport { WorkboxError } from './_private/WorkboxError.js';\nimport './_version.js';\n/**\n * Allows developers to copy a response and modify its `headers`, `status`,\n * or `statusText` values (the values settable via a\n * [`ResponseInit`]{@link https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#Syntax}\n * object in the constructor).\n * To modify these values, pass a function as the second argument. That\n * function will be invoked with a single object with the response properties\n * `{headers, status, statusText}`. The return value of this function will\n * be used as the `ResponseInit` for the new `Response`. To change the values\n * either modify the passed parameter(s) and return it, or return a totally\n * new object.\n *\n * This method is intentionally limited to same-origin responses, regardless of\n * whether CORS was used or not.\n *\n * @param {Response} response\n * @param {Function} modifier\n * @memberof workbox-core\n */\nasync function copyResponse(response, modifier) {\n let origin = null;\n // If response.url isn't set, assume it's cross-origin and keep origin null.\n if (response.url) {\n const responseURL = new URL(response.url);\n origin = responseURL.origin;\n }\n if (origin !== self.location.origin) {\n throw new WorkboxError('cross-origin-copy-response', { origin });\n }\n const clonedResponse = response.clone();\n // Create a fresh `ResponseInit` object by cloning the headers.\n const responseInit = {\n headers: new Headers(clonedResponse.headers),\n status: clonedResponse.status,\n statusText: clonedResponse.statusText,\n };\n // Apply any user modifications.\n const modifiedResponseInit = modifier ? modifier(responseInit) : responseInit;\n // Create the new response from the body stream and `ResponseInit`\n // modifications. Note: not all browsers support the Response.body stream,\n // so fall back to reading the entire body into memory as a blob.\n const body = canConstructResponseFromBodyStream()\n ? clonedResponse.body\n : await clonedResponse.blob();\n return new Response(body, modifiedResponseInit);\n}\nexport { copyResponse };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { logger } from './_private/logger.js';\nimport { assert } from './_private/assert.js';\nimport { quotaErrorCallbacks } from './models/quotaErrorCallbacks.js';\nimport './_version.js';\n/**\n * Adds a function to the set of quotaErrorCallbacks that will be executed if\n * there's a quota error.\n *\n * @param {Function} callback\n * @memberof workbox-core\n */\n// Can't change Function type\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction registerQuotaErrorCallback(callback) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(callback, 'function', {\n moduleName: 'workbox-core',\n funcName: 'register',\n paramName: 'callback',\n });\n }\n quotaErrorCallbacks.add(callback);\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Registered a callback to respond to quota errors.', callback);\n }\n}\nexport { registerQuotaErrorCallback };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from './_private/assert.js';\nimport { cacheNames } from './_private/cacheNames.js';\nimport { WorkboxError } from './_private/WorkboxError.js';\nimport './_version.js';\n/**\n * Modifies the default cache names used by the Workbox packages.\n * Cache names are generated as `--`.\n *\n * @param {Object} details\n * @param {Object} [details.prefix] The string to add to the beginning of\n * the precache and runtime cache names.\n * @param {Object} [details.suffix] The string to add to the end of\n * the precache and runtime cache names.\n * @param {Object} [details.precache] The cache name to use for precache\n * caching.\n * @param {Object} [details.runtime] The cache name to use for runtime caching.\n * @param {Object} [details.googleAnalytics] The cache name to use for\n * `workbox-google-analytics` caching.\n *\n * @memberof workbox-core\n */\nfunction setCacheNameDetails(details) {\n if (process.env.NODE_ENV !== 'production') {\n Object.keys(details).forEach((key) => {\n assert.isType(details[key], 'string', {\n moduleName: 'workbox-core',\n funcName: 'setCacheNameDetails',\n paramName: `details.${key}`,\n });\n });\n if ('precache' in details && details['precache'].length === 0) {\n throw new WorkboxError('invalid-cache-name', {\n cacheNameId: 'precache',\n value: details['precache'],\n });\n }\n if ('runtime' in details && details['runtime'].length === 0) {\n throw new WorkboxError('invalid-cache-name', {\n cacheNameId: 'runtime',\n value: details['runtime'],\n });\n }\n if ('googleAnalytics' in details &&\n details['googleAnalytics'].length === 0) {\n throw new WorkboxError('invalid-cache-name', {\n cacheNameId: 'googleAnalytics',\n value: details['googleAnalytics'],\n });\n }\n }\n cacheNames.updateDetails(details);\n}\nexport { setCacheNameDetails };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { logger } from './_private/logger.js';\nimport './_version.js';\n/**\n * This method is deprecated, and will be removed in Workbox v7.\n *\n * Calling self.skipWaiting() is equivalent, and should be used instead.\n *\n * @memberof workbox-core\n */\nfunction skipWaiting() {\n // Just call self.skipWaiting() directly.\n // See https://github.com/GoogleChrome/workbox/issues/2525\n if (process.env.NODE_ENV !== 'production') {\n logger.warn(`skipWaiting() from workbox-core is no longer recommended ` +\n `and will be removed in Workbox v7. Using self.skipWaiting() instead ` +\n `is equivalent.`);\n }\n void self.skipWaiting();\n}\nexport { skipWaiting };\n"],"names":["self","_","e","messageGenerator","fallback","code","args","msg","length","JSON","stringify","WorkboxError","Error","constructor","errorCode","details","super","this","name","quotaErrorCallbacks","Set","_cacheNameDetails","googleAnalytics","precache","prefix","runtime","suffix","registration","scope","_createCacheName","cacheName","filter","value","join","cacheNames","updateDetails","fn","key","Object","keys","eachCacheNameDetail","getGoogleAnalyticsName","userCacheName","getPrecacheName","getPrefix","getRuntimeName","getSuffix","stripParams","fullURL","ignoreParams","strippedURL","URL","param","searchParams","delete","href","supportStatus","canConstructResponseFromBodyStream","undefined","testResponse","Response","body","error","timeout","ms","Promise","resolve","setTimeout","promise","reject","async","cache","request","matchOptions","strippedRequestURL","url","match","keysOptions","assign","ignoreSearch","cacheKeys","cacheKey","ReadableStream","start","then","callback","String","location","replace","RegExp","origin","resultingClientId","existingWindows","clients","matchAll","type","existingWindowIds","map","w","id","resultingWindow","startTime","performance","now","find","has","event","asyncFn","returnPromise","waitUntil","_cacheNames","addEventListener","claim","response","modifier","clonedResponse","clone","responseInit","headers","Headers","status","statusText","modifiedResponseInit","blob","add","skipWaiting"],"mappings":"yEAEA,IACIA,KAAK,uBAAyBC,GAClC,CACA,MAAOC,GAAK,CCEZ,MCgBaC,EAdIC,CAACC,KAASC,KACvB,IAAIC,EAAMF,EAIV,OAHIC,EAAKE,OAAS,IACdD,GAAQ,OAAME,KAAKC,UAAUJ,MAE1BC,CAAG,ECId,MAAMI,UAAqBC,MASvBC,YAAYC,EAAWC,GAEnBC,MADgBb,EAAiBW,EAAWC,IAE5CE,KAAKC,KAAOJ,EACZG,KAAKF,QAAUA,CACnB,EC8BJ,MCnDMI,EAAsB,IAAIC,ICHhC,MAAMC,EAAoB,CACtBC,gBAAiB,kBACjBC,SAAU,cACVC,OAAQ,UACRC,QAAS,UACTC,OAAgC,oBAAjBC,aAA+BA,aAAaC,MAAQ,IAEjEC,EAAoBC,GACf,CAACT,EAAkBG,OAAQM,EAAWT,EAAkBK,QAC1DK,QAAQC,GAAUA,GAASA,EAAMxB,OAAS,IAC1CyB,KAAK,KAODC,EAAa,CACtBC,cAAgBpB,IANSqB,KACzB,IAAK,MAAMC,KAAOC,OAAOC,KAAKlB,GAC1Be,EAAGC,EACP,EAIIG,EAAqBH,IACW,iBAAjBtB,EAAQsB,KACfhB,EAAkBgB,GAAOtB,EAAQsB,GACrC,GACF,EAENI,uBAAyBC,GACdA,GAAiBb,EAAiBR,EAAkBC,iBAE/DqB,gBAAkBD,GACPA,GAAiBb,EAAiBR,EAAkBE,UAE/DqB,UAAWA,IACAvB,EAAkBG,OAE7BqB,eAAiBH,GACNA,GAAiBb,EAAiBR,EAAkBI,SAE/DqB,UAAWA,IACAzB,EAAkBK,QCvCjC,SAASqB,EAAYC,EAASC,GAC1B,MAAMC,EAAc,IAAIC,IAAIH,GAC5B,IAAK,MAAMI,KAASH,EAChBC,EAAYG,aAAaC,OAAOF,GAEpC,OAAOF,EAAYK,IACvB,CCLA,IAAIC,EC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5B,wBCJA,SAA6BtE,GA6BzBmB,EAAWC,cAAcpB,EAC7B,gBC1CA,WAQSf,KAAK6H,aACd"} \ No newline at end of file diff --git a/node_modules/workbox-core/cacheNames.d.ts b/node_modules/workbox-core/cacheNames.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ef6029c91d0a38c48ff202048e198392dae2c26a --- /dev/null +++ b/node_modules/workbox-core/cacheNames.d.ts @@ -0,0 +1,24 @@ +import './_version.js'; +/** + * Get the current cache names and prefix/suffix used by Workbox. + * + * `cacheNames.precache` is used for precached assets, + * `cacheNames.googleAnalytics` is used by `workbox-google-analytics` to + * store `analytics.js`, and `cacheNames.runtime` is used for everything else. + * + * `cacheNames.prefix` can be used to retrieve just the current prefix value. + * `cacheNames.suffix` can be used to retrieve just the current suffix value. + * + * @return {Object} An object with `precache`, `runtime`, `prefix`, and + * `googleAnalytics` properties. + * + * @memberof workbox-core + */ +declare const cacheNames: { + readonly googleAnalytics: string; + readonly precache: string; + readonly prefix: string; + readonly runtime: string; + readonly suffix: string; +}; +export { cacheNames }; diff --git a/node_modules/workbox-core/cacheNames.js b/node_modules/workbox-core/cacheNames.js new file mode 100644 index 0000000000000000000000000000000000000000..4295c36aa96d3186f824e433b38f272c38488dee --- /dev/null +++ b/node_modules/workbox-core/cacheNames.js @@ -0,0 +1,42 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { cacheNames as _cacheNames } from './_private/cacheNames.js'; +import './_version.js'; +/** + * Get the current cache names and prefix/suffix used by Workbox. + * + * `cacheNames.precache` is used for precached assets, + * `cacheNames.googleAnalytics` is used by `workbox-google-analytics` to + * store `analytics.js`, and `cacheNames.runtime` is used for everything else. + * + * `cacheNames.prefix` can be used to retrieve just the current prefix value. + * `cacheNames.suffix` can be used to retrieve just the current suffix value. + * + * @return {Object} An object with `precache`, `runtime`, `prefix`, and + * `googleAnalytics` properties. + * + * @memberof workbox-core + */ +const cacheNames = { + get googleAnalytics() { + return _cacheNames.getGoogleAnalyticsName(); + }, + get precache() { + return _cacheNames.getPrecacheName(); + }, + get prefix() { + return _cacheNames.getPrefix(); + }, + get runtime() { + return _cacheNames.getRuntimeName(); + }, + get suffix() { + return _cacheNames.getSuffix(); + }, +}; +export { cacheNames }; diff --git a/node_modules/workbox-core/cacheNames.mjs b/node_modules/workbox-core/cacheNames.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2a299372164250b06c59b7f4a227ec39793abfa2 --- /dev/null +++ b/node_modules/workbox-core/cacheNames.mjs @@ -0,0 +1 @@ +export * from './cacheNames.js'; \ No newline at end of file diff --git a/node_modules/workbox-core/clientsClaim.d.ts b/node_modules/workbox-core/clientsClaim.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..61e75f51cd7d3c665c29f768197922a1ebe52784 --- /dev/null +++ b/node_modules/workbox-core/clientsClaim.d.ts @@ -0,0 +1,9 @@ +import './_version.js'; +/** + * Claim any currently available clients once the service worker + * becomes active. This is normally used in conjunction with `skipWaiting()`. + * + * @memberof workbox-core + */ +declare function clientsClaim(): void; +export { clientsClaim }; diff --git a/node_modules/workbox-core/clientsClaim.js b/node_modules/workbox-core/clientsClaim.js new file mode 100644 index 0000000000000000000000000000000000000000..5764bd180849d89c72ccad8edf864f57312fbf6e --- /dev/null +++ b/node_modules/workbox-core/clientsClaim.js @@ -0,0 +1,18 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import './_version.js'; +/** + * Claim any currently available clients once the service worker + * becomes active. This is normally used in conjunction with `skipWaiting()`. + * + * @memberof workbox-core + */ +function clientsClaim() { + self.addEventListener('activate', () => self.clients.claim()); +} +export { clientsClaim }; diff --git a/node_modules/workbox-core/clientsClaim.mjs b/node_modules/workbox-core/clientsClaim.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7cf3dc83e12d2a11341387d6e5b94a68420ed1bd --- /dev/null +++ b/node_modules/workbox-core/clientsClaim.mjs @@ -0,0 +1 @@ +export * from './clientsClaim.js'; \ No newline at end of file diff --git a/node_modules/workbox-core/copyResponse.d.ts b/node_modules/workbox-core/copyResponse.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2d07c4ef8b2d58f9fc2de844d797c14be51499bd --- /dev/null +++ b/node_modules/workbox-core/copyResponse.d.ts @@ -0,0 +1,22 @@ +import './_version.js'; +/** + * Allows developers to copy a response and modify its `headers`, `status`, + * or `statusText` values (the values settable via a + * [`ResponseInit`]{@link https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#Syntax} + * object in the constructor). + * To modify these values, pass a function as the second argument. That + * function will be invoked with a single object with the response properties + * `{headers, status, statusText}`. The return value of this function will + * be used as the `ResponseInit` for the new `Response`. To change the values + * either modify the passed parameter(s) and return it, or return a totally + * new object. + * + * This method is intentionally limited to same-origin responses, regardless of + * whether CORS was used or not. + * + * @param {Response} response + * @param {Function} modifier + * @memberof workbox-core + */ +declare function copyResponse(response: Response, modifier?: (responseInit: ResponseInit) => ResponseInit): Promise; +export { copyResponse }; diff --git a/node_modules/workbox-core/copyResponse.js b/node_modules/workbox-core/copyResponse.js new file mode 100644 index 0000000000000000000000000000000000000000..eaf23f1552596625910236b54395259c9fecba2c --- /dev/null +++ b/node_modules/workbox-core/copyResponse.js @@ -0,0 +1,57 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { canConstructResponseFromBodyStream } from './_private/canConstructResponseFromBodyStream.js'; +import { WorkboxError } from './_private/WorkboxError.js'; +import './_version.js'; +/** + * Allows developers to copy a response and modify its `headers`, `status`, + * or `statusText` values (the values settable via a + * [`ResponseInit`]{@link https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#Syntax} + * object in the constructor). + * To modify these values, pass a function as the second argument. That + * function will be invoked with a single object with the response properties + * `{headers, status, statusText}`. The return value of this function will + * be used as the `ResponseInit` for the new `Response`. To change the values + * either modify the passed parameter(s) and return it, or return a totally + * new object. + * + * This method is intentionally limited to same-origin responses, regardless of + * whether CORS was used or not. + * + * @param {Response} response + * @param {Function} modifier + * @memberof workbox-core + */ +async function copyResponse(response, modifier) { + let origin = null; + // If response.url isn't set, assume it's cross-origin and keep origin null. + if (response.url) { + const responseURL = new URL(response.url); + origin = responseURL.origin; + } + if (origin !== self.location.origin) { + throw new WorkboxError('cross-origin-copy-response', { origin }); + } + const clonedResponse = response.clone(); + // Create a fresh `ResponseInit` object by cloning the headers. + const responseInit = { + headers: new Headers(clonedResponse.headers), + status: clonedResponse.status, + statusText: clonedResponse.statusText, + }; + // Apply any user modifications. + const modifiedResponseInit = modifier ? modifier(responseInit) : responseInit; + // Create the new response from the body stream and `ResponseInit` + // modifications. Note: not all browsers support the Response.body stream, + // so fall back to reading the entire body into memory as a blob. + const body = canConstructResponseFromBodyStream() + ? clonedResponse.body + : await clonedResponse.blob(); + return new Response(body, modifiedResponseInit); +} +export { copyResponse }; diff --git a/node_modules/workbox-core/copyResponse.mjs b/node_modules/workbox-core/copyResponse.mjs new file mode 100644 index 0000000000000000000000000000000000000000..03b1304e04691b74acd7b5ff4205305d3095d522 --- /dev/null +++ b/node_modules/workbox-core/copyResponse.mjs @@ -0,0 +1 @@ +export * from './copyResponse.js'; \ No newline at end of file diff --git a/node_modules/workbox-core/index.d.ts b/node_modules/workbox-core/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..24363024973a4903462c6213f44801d0aafd73e6 --- /dev/null +++ b/node_modules/workbox-core/index.d.ts @@ -0,0 +1,17 @@ +import { registerQuotaErrorCallback } from './registerQuotaErrorCallback.js'; +import * as _private from './_private.js'; +import { cacheNames } from './cacheNames.js'; +import { copyResponse } from './copyResponse.js'; +import { clientsClaim } from './clientsClaim.js'; +import { setCacheNameDetails } from './setCacheNameDetails.js'; +import { skipWaiting } from './skipWaiting.js'; +import './_version.js'; +/** + * All of the Workbox service worker libraries use workbox-core for shared + * code as well as setting default values that need to be shared (like cache + * names). + * + * @module workbox-core + */ +export { _private, cacheNames, clientsClaim, copyResponse, registerQuotaErrorCallback, setCacheNameDetails, skipWaiting, }; +export * from './types.js'; diff --git a/node_modules/workbox-core/index.js b/node_modules/workbox-core/index.js new file mode 100644 index 0000000000000000000000000000000000000000..eb1bac8b443a60fddc63ffacfa8164f998b2c4ef --- /dev/null +++ b/node_modules/workbox-core/index.js @@ -0,0 +1,24 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { registerQuotaErrorCallback } from './registerQuotaErrorCallback.js'; +import * as _private from './_private.js'; +import { cacheNames } from './cacheNames.js'; +import { copyResponse } from './copyResponse.js'; +import { clientsClaim } from './clientsClaim.js'; +import { setCacheNameDetails } from './setCacheNameDetails.js'; +import { skipWaiting } from './skipWaiting.js'; +import './_version.js'; +/** + * All of the Workbox service worker libraries use workbox-core for shared + * code as well as setting default values that need to be shared (like cache + * names). + * + * @module workbox-core + */ +export { _private, cacheNames, clientsClaim, copyResponse, registerQuotaErrorCallback, setCacheNameDetails, skipWaiting, }; +export * from './types.js'; diff --git a/node_modules/workbox-core/index.mjs b/node_modules/workbox-core/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..833b6a2f3226fec78490a3b7a622dc5146f94b53 --- /dev/null +++ b/node_modules/workbox-core/index.mjs @@ -0,0 +1 @@ +export * from './index.js'; \ No newline at end of file diff --git a/node_modules/workbox-core/models/messages/messageGenerator.d.ts b/node_modules/workbox-core/models/messages/messageGenerator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d4f63577d18568398e4648220147603ae043fe03 --- /dev/null +++ b/node_modules/workbox-core/models/messages/messageGenerator.d.ts @@ -0,0 +1,2 @@ +import '../../_version.js'; +export declare const messageGenerator: ((code: string, ...args: any[]) => string) | ((code: string, details?: {}) => string); diff --git a/node_modules/workbox-core/models/messages/messageGenerator.js b/node_modules/workbox-core/models/messages/messageGenerator.js new file mode 100644 index 0000000000000000000000000000000000000000..6cb49824fa09c00c95f3571778cbcff42b77df37 --- /dev/null +++ b/node_modules/workbox-core/models/messages/messageGenerator.js @@ -0,0 +1,24 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { messages } from './messages.js'; +import '../../_version.js'; +const fallback = (code, ...args) => { + let msg = code; + if (args.length > 0) { + msg += ` :: ${JSON.stringify(args)}`; + } + return msg; +}; +const generatorFunction = (code, details = {}) => { + const message = messages[code]; + if (!message) { + throw new Error(`Unable to find message for code '${code}'.`); + } + return message(details); +}; +export const messageGenerator = process.env.NODE_ENV === 'production' ? fallback : generatorFunction; diff --git a/node_modules/workbox-core/models/messages/messageGenerator.mjs b/node_modules/workbox-core/models/messages/messageGenerator.mjs new file mode 100644 index 0000000000000000000000000000000000000000..586814254108b2a14910fe25d7be8690b666fe36 --- /dev/null +++ b/node_modules/workbox-core/models/messages/messageGenerator.mjs @@ -0,0 +1 @@ +export * from './messageGenerator.js'; \ No newline at end of file diff --git a/node_modules/workbox-core/models/messages/messages.d.ts b/node_modules/workbox-core/models/messages/messages.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1d9c63e41bf84ceca4336928c2d8168b4005ec47 --- /dev/null +++ b/node_modules/workbox-core/models/messages/messages.d.ts @@ -0,0 +1,9 @@ +import '../../_version.js'; +interface LoggableObject { + [key: string]: string | number; +} +interface MessageMap { + [messageID: string]: (param: LoggableObject) => string; +} +export declare const messages: MessageMap; +export {}; diff --git a/node_modules/workbox-core/models/messages/messages.js b/node_modules/workbox-core/models/messages/messages.js new file mode 100644 index 0000000000000000000000000000000000000000..1ed5821158565175d2adce2b82a84a48f360a74d --- /dev/null +++ b/node_modules/workbox-core/models/messages/messages.js @@ -0,0 +1,228 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import '../../_version.js'; +export const messages = { + 'invalid-value': ({ paramName, validValueDescription, value }) => { + if (!paramName || !validValueDescription) { + throw new Error(`Unexpected input to 'invalid-value' error.`); + } + return (`The '${paramName}' parameter was given a value with an ` + + `unexpected value. ${validValueDescription} Received a value of ` + + `${JSON.stringify(value)}.`); + }, + 'not-an-array': ({ moduleName, className, funcName, paramName }) => { + if (!moduleName || !className || !funcName || !paramName) { + throw new Error(`Unexpected input to 'not-an-array' error.`); + } + return (`The parameter '${paramName}' passed into ` + + `'${moduleName}.${className}.${funcName}()' must be an array.`); + }, + 'incorrect-type': ({ expectedType, paramName, moduleName, className, funcName, }) => { + if (!expectedType || !paramName || !moduleName || !funcName) { + throw new Error(`Unexpected input to 'incorrect-type' error.`); + } + const classNameStr = className ? `${className}.` : ''; + return (`The parameter '${paramName}' passed into ` + + `'${moduleName}.${classNameStr}` + + `${funcName}()' must be of type ${expectedType}.`); + }, + 'incorrect-class': ({ expectedClassName, paramName, moduleName, className, funcName, isReturnValueProblem, }) => { + if (!expectedClassName || !moduleName || !funcName) { + throw new Error(`Unexpected input to 'incorrect-class' error.`); + } + const classNameStr = className ? `${className}.` : ''; + if (isReturnValueProblem) { + return (`The return value from ` + + `'${moduleName}.${classNameStr}${funcName}()' ` + + `must be an instance of class ${expectedClassName}.`); + } + return (`The parameter '${paramName}' passed into ` + + `'${moduleName}.${classNameStr}${funcName}()' ` + + `must be an instance of class ${expectedClassName}.`); + }, + 'missing-a-method': ({ expectedMethod, paramName, moduleName, className, funcName, }) => { + if (!expectedMethod || + !paramName || + !moduleName || + !className || + !funcName) { + throw new Error(`Unexpected input to 'missing-a-method' error.`); + } + return (`${moduleName}.${className}.${funcName}() expected the ` + + `'${paramName}' parameter to expose a '${expectedMethod}' method.`); + }, + 'add-to-cache-list-unexpected-type': ({ entry }) => { + 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.`); + }, + 'add-to-cache-list-conflicting-entries': ({ firstEntry, secondEntry }) => { + if (!firstEntry || !secondEntry) { + throw new Error(`Unexpected input to ` + `'add-to-cache-list-duplicate-entries' error.`); + } + return (`Two of the entries passed to ` + + `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` + + `${firstEntry} but different revision details. Workbox is ` + + `unable to cache and version the asset correctly. Please remove one ` + + `of the entries.`); + }, + 'plugin-error-request-will-fetch': ({ thrownErrorMessage }) => { + if (!thrownErrorMessage) { + throw new Error(`Unexpected input to ` + `'plugin-error-request-will-fetch', error.`); + } + return (`An error was thrown by a plugins 'requestWillFetch()' method. ` + + `The thrown error message was: '${thrownErrorMessage}'.`); + }, + 'invalid-cache-name': ({ cacheNameId, value }) => { + if (!cacheNameId) { + throw new Error(`Expected a 'cacheNameId' for error 'invalid-cache-name'`); + } + return (`You must provide a name containing at least one character for ` + + `setCacheDetails({${cacheNameId}: '...'}). Received a value of ` + + `'${JSON.stringify(value)}'`); + }, + 'unregister-route-but-not-found-with-method': ({ method }) => { + if (!method) { + throw new Error(`Unexpected input to ` + + `'unregister-route-but-not-found-with-method' error.`); + } + return (`The route you're trying to unregister was not previously ` + + `registered for the method type '${method}'.`); + }, + 'unregister-route-route-not-registered': () => { + return (`The route you're trying to unregister was not previously ` + + `registered.`); + }, + 'queue-replay-failed': ({ name }) => { + return `Replaying the background sync queue '${name}' failed.`; + }, + 'duplicate-queue-name': ({ name }) => { + return (`The Queue name '${name}' is already being used. ` + + `All instances of backgroundSync.Queue must be given unique names.`); + }, + 'expired-test-without-max-age': ({ methodName, paramName }) => { + return (`The '${methodName}()' method can only be used when the ` + + `'${paramName}' is used in the constructor.`); + }, + 'unsupported-route-type': ({ moduleName, className, funcName, paramName }) => { + return (`The supplied '${paramName}' parameter was an unsupported type. ` + + `Please check the docs for ${moduleName}.${className}.${funcName} for ` + + `valid input types.`); + }, + 'not-array-of-class': ({ value, expectedClass, moduleName, className, funcName, paramName, }) => { + 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.`); + }, + 'max-entries-or-age-required': ({ moduleName, className, funcName }) => { + return (`You must define either config.maxEntries or config.maxAgeSeconds` + + `in ${moduleName}.${className}.${funcName}`); + }, + 'statuses-or-headers-required': ({ moduleName, className, funcName }) => { + return (`You must define either config.statuses or config.headers` + + `in ${moduleName}.${className}.${funcName}`); + }, + 'invalid-string': ({ moduleName, funcName, paramName }) => { + if (!paramName || !moduleName || !funcName) { + throw new Error(`Unexpected input to 'invalid-string' error.`); + } + 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.`); + }, + 'channel-name-required': () => { + return (`You must provide a channelName to construct a ` + + `BroadcastCacheUpdate instance.`); + }, + 'invalid-responses-are-same-args': () => { + return (`The arguments passed into responsesAreSame() appear to be ` + + `invalid. Please ensure valid Responses are used.`); + }, + 'expire-custom-caches-only': () => { + return (`You must provide a 'cacheName' property when using the ` + + `expiration plugin with a runtime caching strategy.`); + }, + 'unit-must-be-bytes': ({ normalizedRangeHeader }) => { + if (!normalizedRangeHeader) { + throw new Error(`Unexpected input to 'unit-must-be-bytes' error.`); + } + return (`The 'unit' portion of the Range header must be set to 'bytes'. ` + + `The Range header provided was "${normalizedRangeHeader}"`); + }, + 'single-range-only': ({ normalizedRangeHeader }) => { + if (!normalizedRangeHeader) { + throw new Error(`Unexpected input to 'single-range-only' error.`); + } + return (`Multiple ranges are not supported. Please use a single start ` + + `value, and optional end value. The Range header provided was ` + + `"${normalizedRangeHeader}"`); + }, + 'invalid-range-values': ({ normalizedRangeHeader }) => { + if (!normalizedRangeHeader) { + throw new Error(`Unexpected input to 'invalid-range-values' error.`); + } + 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}"`); + }, + 'no-range-header': () => { + return `No Range header was found in the Request provided.`; + }, + 'range-not-satisfiable': ({ size, start, end }) => { + return (`The start (${start}) and end (${end}) values in the Range are ` + + `not satisfiable by the cached response, which is ${size} bytes.`); + }, + 'attempt-to-cache-non-get-request': ({ url, method }) => { + return (`Unable to cache '${url}' because it is a '${method}' request and ` + + `only 'GET' requests can be cached.`); + }, + 'cache-put-with-no-response': ({ url }) => { + return (`There was an attempt to cache '${url}' but the response was not ` + + `defined.`); + }, + 'no-response': ({ url, error }) => { + let message = `The strategy could not generate a response for '${url}'.`; + if (error) { + message += ` The underlying error is ${error}.`; + } + return message; + }, + 'bad-precaching-response': ({ url, status }) => { + return (`The precaching request for '${url}' failed` + + (status ? ` with an HTTP status of ${status}.` : `.`)); + }, + 'non-precached-url': ({ url }) => { + return (`createHandlerBoundToURL('${url}') was called, but that URL is ` + + `not precached. Please pass in a URL that is precached instead.`); + }, + 'add-to-cache-list-conflicting-integrities': ({ url }) => { + return (`Two of the entries passed to ` + + `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` + + `${url} with different integrity values. Please remove one of them.`); + }, + 'missing-precache-entry': ({ cacheName, url }) => { + return `Unable to find a precached response in ${cacheName} for ${url}.`; + }, + 'cross-origin-copy-response': ({ origin }) => { + return (`workbox-core.copyResponse() can only be used with same-origin ` + + `responses. It was passed a response with origin ${origin}.`); + }, + 'opaque-streams-source': ({ type }) => { + const message = `One of the workbox-streams sources resulted in an ` + + `'${type}' response.`; + if (type === 'opaqueredirect') { + return (`${message} Please do not use a navigation request that results ` + + `in a redirect as a source.`); + } + return `${message} Please ensure your sources are CORS-enabled.`; + }, +}; diff --git a/node_modules/workbox-core/models/messages/messages.mjs b/node_modules/workbox-core/models/messages/messages.mjs new file mode 100644 index 0000000000000000000000000000000000000000..fcad226c2238011ab36b9799e8999b5109083c3e --- /dev/null +++ b/node_modules/workbox-core/models/messages/messages.mjs @@ -0,0 +1 @@ +export * from './messages.js'; \ No newline at end of file diff --git a/node_modules/workbox-core/models/pluginEvents.d.ts b/node_modules/workbox-core/models/pluginEvents.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dfd5077e1631b493ce91556796d0e6e744dc372c --- /dev/null +++ b/node_modules/workbox-core/models/pluginEvents.d.ts @@ -0,0 +1,10 @@ +import '../_version.js'; +export declare const enum pluginEvents { + CACHE_DID_UPDATE = "cacheDidUpdate", + CACHE_KEY_WILL_BE_USED = "cacheKeyWillBeUsed", + CACHE_WILL_UPDATE = "cacheWillUpdate", + CACHED_RESPONSE_WILL_BE_USED = "cachedResponseWillBeUsed", + FETCH_DID_FAIL = "fetchDidFail", + FETCH_DID_SUCCEED = "fetchDidSucceed", + REQUEST_WILL_FETCH = "requestWillFetch" +} diff --git a/node_modules/workbox-core/models/pluginEvents.js b/node_modules/workbox-core/models/pluginEvents.js new file mode 100644 index 0000000000000000000000000000000000000000..4db5bbd99a29d3906d9f54ccee1fd984bca2d0a9 --- /dev/null +++ b/node_modules/workbox-core/models/pluginEvents.js @@ -0,0 +1,18 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import '../_version.js'; +export var pluginEvents; +(function (pluginEvents) { + pluginEvents["CACHE_DID_UPDATE"] = "cacheDidUpdate"; + pluginEvents["CACHE_KEY_WILL_BE_USED"] = "cacheKeyWillBeUsed"; + pluginEvents["CACHE_WILL_UPDATE"] = "cacheWillUpdate"; + pluginEvents["CACHED_RESPONSE_WILL_BE_USED"] = "cachedResponseWillBeUsed"; + pluginEvents["FETCH_DID_FAIL"] = "fetchDidFail"; + pluginEvents["FETCH_DID_SUCCEED"] = "fetchDidSucceed"; + pluginEvents["REQUEST_WILL_FETCH"] = "requestWillFetch"; +})(pluginEvents || (pluginEvents = {})); diff --git a/node_modules/workbox-core/models/pluginEvents.mjs b/node_modules/workbox-core/models/pluginEvents.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d9cdbe66bb5cc9c182e2c31dde0c66d5be08ee7b --- /dev/null +++ b/node_modules/workbox-core/models/pluginEvents.mjs @@ -0,0 +1 @@ +export * from './pluginEvents.js'; \ No newline at end of file diff --git a/node_modules/workbox-core/models/quotaErrorCallbacks.d.ts b/node_modules/workbox-core/models/quotaErrorCallbacks.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b179075840132768eaa15a6611859e7eb77b5660 --- /dev/null +++ b/node_modules/workbox-core/models/quotaErrorCallbacks.d.ts @@ -0,0 +1,3 @@ +import '../_version.js'; +declare const quotaErrorCallbacks: Set; +export { quotaErrorCallbacks }; diff --git a/node_modules/workbox-core/models/quotaErrorCallbacks.js b/node_modules/workbox-core/models/quotaErrorCallbacks.js new file mode 100644 index 0000000000000000000000000000000000000000..f0b9b2251728b6c412b3e964bd29db4b8733dc11 --- /dev/null +++ b/node_modules/workbox-core/models/quotaErrorCallbacks.js @@ -0,0 +1,13 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import '../_version.js'; +// Callbacks to be executed whenever there's a quota error. +// Can't change Function type right now. +// eslint-disable-next-line @typescript-eslint/ban-types +const quotaErrorCallbacks = new Set(); +export { quotaErrorCallbacks }; diff --git a/node_modules/workbox-core/models/quotaErrorCallbacks.mjs b/node_modules/workbox-core/models/quotaErrorCallbacks.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b5e60ec663da2a72ac4af5e0f6f6e1be31327ca5 --- /dev/null +++ b/node_modules/workbox-core/models/quotaErrorCallbacks.mjs @@ -0,0 +1 @@ +export * from './quotaErrorCallbacks.js'; \ No newline at end of file diff --git a/node_modules/workbox-core/package.json b/node_modules/workbox-core/package.json new file mode 100644 index 0000000000000000000000000000000000000000..7368969fb9cc8571e12cf7848b53b4a1bb20aba9 --- /dev/null +++ b/node_modules/workbox-core/package.json @@ -0,0 +1,27 @@ +{ + "name": "workbox-core", + "version": "7.4.1", + "license": "MIT", + "author": "Google's Web DevRel Team and Google's Aurora Team", + "description": "This module is used by a number of the other Workbox modules to share common code.", + "repository": { + "type": "git", + "url": "git+https://github.com/googlechrome/workbox.git" + }, + "bugs": "https://github.com/googlechrome/workbox/issues", + "homepage": "https://github.com/GoogleChrome/workbox", + "keywords": [ + "workbox", + "workboxjs", + "service worker", + "sw" + ], + "workbox": { + "browserNamespace": "workbox.core", + "packageType": "sw" + }, + "main": "index.js", + "module": "index.mjs", + "types": "index.d.ts", + "gitHead": "62b9d8ba8eb3c1a2ab8aac9d84c90cda7865d6a3" +} diff --git a/node_modules/workbox-core/registerQuotaErrorCallback.d.ts b/node_modules/workbox-core/registerQuotaErrorCallback.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a8bd4683c672b9a31d2ad1ff235a5525b15ba68a --- /dev/null +++ b/node_modules/workbox-core/registerQuotaErrorCallback.d.ts @@ -0,0 +1,10 @@ +import './_version.js'; +/** + * Adds a function to the set of quotaErrorCallbacks that will be executed if + * there's a quota error. + * + * @param {Function} callback + * @memberof workbox-core + */ +declare function registerQuotaErrorCallback(callback: Function): void; +export { registerQuotaErrorCallback }; diff --git a/node_modules/workbox-core/registerQuotaErrorCallback.js b/node_modules/workbox-core/registerQuotaErrorCallback.js new file mode 100644 index 0000000000000000000000000000000000000000..0aed841c1662b167e4e06fef63d61ef245d10d4e --- /dev/null +++ b/node_modules/workbox-core/registerQuotaErrorCallback.js @@ -0,0 +1,34 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { logger } from './_private/logger.js'; +import { assert } from './_private/assert.js'; +import { quotaErrorCallbacks } from './models/quotaErrorCallbacks.js'; +import './_version.js'; +/** + * Adds a function to the set of quotaErrorCallbacks that will be executed if + * there's a quota error. + * + * @param {Function} callback + * @memberof workbox-core + */ +// Can't change Function type +// eslint-disable-next-line @typescript-eslint/ban-types +function registerQuotaErrorCallback(callback) { + if (process.env.NODE_ENV !== 'production') { + assert.isType(callback, 'function', { + moduleName: 'workbox-core', + funcName: 'register', + paramName: 'callback', + }); + } + quotaErrorCallbacks.add(callback); + if (process.env.NODE_ENV !== 'production') { + logger.log('Registered a callback to respond to quota errors.', callback); + } +} +export { registerQuotaErrorCallback }; diff --git a/node_modules/workbox-core/registerQuotaErrorCallback.mjs b/node_modules/workbox-core/registerQuotaErrorCallback.mjs new file mode 100644 index 0000000000000000000000000000000000000000..95a6522a4b4a45ddb1c9165b1bd79d114b75b011 --- /dev/null +++ b/node_modules/workbox-core/registerQuotaErrorCallback.mjs @@ -0,0 +1 @@ +export * from './registerQuotaErrorCallback.js'; \ No newline at end of file diff --git a/node_modules/workbox-core/setCacheNameDetails.d.ts b/node_modules/workbox-core/setCacheNameDetails.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..68ec8ec44aa67a13e48b19907774c1c9eea69860 --- /dev/null +++ b/node_modules/workbox-core/setCacheNameDetails.d.ts @@ -0,0 +1,21 @@ +import { PartialCacheNameDetails } from './_private/cacheNames.js'; +import './_version.js'; +/** + * Modifies the default cache names used by the Workbox packages. + * Cache names are generated as `--`. + * + * @param {Object} details + * @param {Object} [details.prefix] The string to add to the beginning of + * the precache and runtime cache names. + * @param {Object} [details.suffix] The string to add to the end of + * the precache and runtime cache names. + * @param {Object} [details.precache] The cache name to use for precache + * caching. + * @param {Object} [details.runtime] The cache name to use for runtime caching. + * @param {Object} [details.googleAnalytics] The cache name to use for + * `workbox-google-analytics` caching. + * + * @memberof workbox-core + */ +declare function setCacheNameDetails(details: PartialCacheNameDetails): void; +export { setCacheNameDetails }; diff --git a/node_modules/workbox-core/setCacheNameDetails.js b/node_modules/workbox-core/setCacheNameDetails.js new file mode 100644 index 0000000000000000000000000000000000000000..4857f1ce173eb3a421b63dc275c90f50f420dea3 --- /dev/null +++ b/node_modules/workbox-core/setCacheNameDetails.js @@ -0,0 +1,60 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { assert } from './_private/assert.js'; +import { cacheNames } from './_private/cacheNames.js'; +import { WorkboxError } from './_private/WorkboxError.js'; +import './_version.js'; +/** + * Modifies the default cache names used by the Workbox packages. + * Cache names are generated as `--`. + * + * @param {Object} details + * @param {Object} [details.prefix] The string to add to the beginning of + * the precache and runtime cache names. + * @param {Object} [details.suffix] The string to add to the end of + * the precache and runtime cache names. + * @param {Object} [details.precache] The cache name to use for precache + * caching. + * @param {Object} [details.runtime] The cache name to use for runtime caching. + * @param {Object} [details.googleAnalytics] The cache name to use for + * `workbox-google-analytics` caching. + * + * @memberof workbox-core + */ +function setCacheNameDetails(details) { + if (process.env.NODE_ENV !== 'production') { + Object.keys(details).forEach((key) => { + assert.isType(details[key], 'string', { + moduleName: 'workbox-core', + funcName: 'setCacheNameDetails', + paramName: `details.${key}`, + }); + }); + if ('precache' in details && details['precache'].length === 0) { + throw new WorkboxError('invalid-cache-name', { + cacheNameId: 'precache', + value: details['precache'], + }); + } + if ('runtime' in details && details['runtime'].length === 0) { + throw new WorkboxError('invalid-cache-name', { + cacheNameId: 'runtime', + value: details['runtime'], + }); + } + if ('googleAnalytics' in details && + details['googleAnalytics'].length === 0) { + throw new WorkboxError('invalid-cache-name', { + cacheNameId: 'googleAnalytics', + value: details['googleAnalytics'], + }); + } + } + cacheNames.updateDetails(details); +} +export { setCacheNameDetails }; diff --git a/node_modules/workbox-core/setCacheNameDetails.mjs b/node_modules/workbox-core/setCacheNameDetails.mjs new file mode 100644 index 0000000000000000000000000000000000000000..bee80bc9a7c268d7c84d2f5ed1bef6d5af7408b2 --- /dev/null +++ b/node_modules/workbox-core/setCacheNameDetails.mjs @@ -0,0 +1 @@ +export * from './setCacheNameDetails.js'; \ No newline at end of file diff --git a/node_modules/workbox-core/skipWaiting.d.ts b/node_modules/workbox-core/skipWaiting.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4162fb145039815c6abcb444e863ba0770102b83 --- /dev/null +++ b/node_modules/workbox-core/skipWaiting.d.ts @@ -0,0 +1,10 @@ +import './_version.js'; +/** + * This method is deprecated, and will be removed in Workbox v7. + * + * Calling self.skipWaiting() is equivalent, and should be used instead. + * + * @memberof workbox-core + */ +declare function skipWaiting(): void; +export { skipWaiting }; diff --git a/node_modules/workbox-core/skipWaiting.js b/node_modules/workbox-core/skipWaiting.js new file mode 100644 index 0000000000000000000000000000000000000000..765893683727ecb883b1211f34d02a154ddf8eed --- /dev/null +++ b/node_modules/workbox-core/skipWaiting.js @@ -0,0 +1,27 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { logger } from './_private/logger.js'; +import './_version.js'; +/** + * This method is deprecated, and will be removed in Workbox v7. + * + * Calling self.skipWaiting() is equivalent, and should be used instead. + * + * @memberof workbox-core + */ +function skipWaiting() { + // Just call self.skipWaiting() directly. + // See https://github.com/GoogleChrome/workbox/issues/2525 + if (process.env.NODE_ENV !== 'production') { + logger.warn(`skipWaiting() from workbox-core is no longer recommended ` + + `and will be removed in Workbox v7. Using self.skipWaiting() instead ` + + `is equivalent.`); + } + void self.skipWaiting(); +} +export { skipWaiting }; diff --git a/node_modules/workbox-core/skipWaiting.mjs b/node_modules/workbox-core/skipWaiting.mjs new file mode 100644 index 0000000000000000000000000000000000000000..47fb97da2bbe8fd548312c24421980a4cc509e0d --- /dev/null +++ b/node_modules/workbox-core/skipWaiting.mjs @@ -0,0 +1 @@ +export * from './skipWaiting.js'; \ No newline at end of file diff --git a/node_modules/workbox-core/src/_private.ts b/node_modules/workbox-core/src/_private.ts new file mode 100644 index 0000000000000000000000000000000000000000..455b7cd08f965279b5b1a374d0fcf7ed5ccb58ec --- /dev/null +++ b/node_modules/workbox-core/src/_private.ts @@ -0,0 +1,42 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +// We either expose defaults or we expose every named export. +import {assert} from './_private/assert.js'; +import {cacheNames} from './_private/cacheNames.js'; +import {cacheMatchIgnoreParams} from './_private/cacheMatchIgnoreParams.js'; +import {canConstructReadableStream} from './_private/canConstructReadableStream.js'; +import {canConstructResponseFromBodyStream} from './_private/canConstructResponseFromBodyStream.js'; +import {dontWaitFor} from './_private/dontWaitFor.js'; +import {Deferred} from './_private/Deferred.js'; +import {executeQuotaErrorCallbacks} from './_private/executeQuotaErrorCallbacks.js'; +import {getFriendlyURL} from './_private/getFriendlyURL.js'; +import {logger} from './_private/logger.js'; +import {resultingClientExists} from './_private/resultingClientExists.js'; +import {timeout} from './_private/timeout.js'; +import {waitUntil} from './_private/waitUntil.js'; +import {WorkboxError} from './_private/WorkboxError.js'; + +import './_version.js'; + +export { + assert, + cacheMatchIgnoreParams, + cacheNames, + canConstructReadableStream, + canConstructResponseFromBodyStream, + dontWaitFor, + Deferred, + executeQuotaErrorCallbacks, + getFriendlyURL, + logger, + resultingClientExists, + timeout, + waitUntil, + WorkboxError, +}; diff --git a/node_modules/workbox-core/src/_private/Deferred.ts b/node_modules/workbox-core/src/_private/Deferred.ts new file mode 100644 index 0000000000000000000000000000000000000000..66f2197410e3562a8b4d1b56577d88c126ae46cf --- /dev/null +++ b/node_modules/workbox-core/src/_private/Deferred.ts @@ -0,0 +1,35 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import '../_version.js'; + +/** + * The Deferred class composes Promises in a way that allows for them to be + * resolved or rejected from outside the constructor. In most cases promises + * should be used directly, but Deferreds can be necessary when the logic to + * resolve a promise must be separate. + * + * @private + */ +class Deferred { + promise: Promise; + resolve!: (value: T) => void; + reject!: (reason?: any) => void; + + /** + * Creates a promise and exposes its resolve and reject functions as methods. + */ + constructor() { + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + } +} + +export {Deferred}; diff --git a/node_modules/workbox-core/src/_private/WorkboxError.ts b/node_modules/workbox-core/src/_private/WorkboxError.ts new file mode 100644 index 0000000000000000000000000000000000000000..edc4214344531ee4dfc3b5e5dc7aca0524edf607 --- /dev/null +++ b/node_modules/workbox-core/src/_private/WorkboxError.ts @@ -0,0 +1,43 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {messageGenerator} from '../models/messages/messageGenerator.js'; +import {MapLikeObject} from '../types.js'; +import '../_version.js'; + +/** + * Workbox errors should be thrown with this class. + * This allows use to ensure the type easily in tests, + * helps developers identify errors from workbox + * easily and allows use to optimise error + * messages correctly. + * + * @private + */ +class WorkboxError extends Error { + details?: MapLikeObject; + + /** + * + * @param {string} errorCode The error code that + * identifies this particular error. + * @param {Object=} details Any relevant arguments + * that will help developers identify issues should + * be added as a key on the context object. + */ + constructor(errorCode: string, details?: MapLikeObject) { + const message = messageGenerator(errorCode, details); + + super(message); + + this.name = errorCode; + this.details = details; + } +} + +export {WorkboxError}; diff --git a/node_modules/workbox-core/src/_private/assert.ts b/node_modules/workbox-core/src/_private/assert.ts new file mode 100644 index 0000000000000000000000000000000000000000..025f96062c12457219e5c0b1a2d24b218a5c10bf --- /dev/null +++ b/node_modules/workbox-core/src/_private/assert.ts @@ -0,0 +1,100 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {WorkboxError} from '../_private/WorkboxError.js'; +import {MapLikeObject} from '../types.js'; +import '../_version.js'; + +/* + * This method throws if the supplied value is not an array. + * The destructed values are required to produce a meaningful error for users. + * The destructed and restructured object is so it's clear what is + * needed. + */ +const isArray = (value: any[], details: MapLikeObject) => { + if (!Array.isArray(value)) { + throw new WorkboxError('not-an-array', details); + } +}; + +const hasMethod = ( + object: MapLikeObject, + expectedMethod: string, + details: MapLikeObject, +) => { + const type = typeof object[expectedMethod]; + if (type !== 'function') { + details['expectedMethod'] = expectedMethod; + throw new WorkboxError('missing-a-method', details); + } +}; + +const isType = ( + object: unknown, + expectedType: string, + details: MapLikeObject, +) => { + if (typeof object !== expectedType) { + details['expectedType'] = expectedType; + throw new WorkboxError('incorrect-type', details); + } +}; + +const isInstance = ( + object: unknown, + // Need the general type to do the check later. + // eslint-disable-next-line @typescript-eslint/ban-types + expectedClass: Function, + details: MapLikeObject, +) => { + if (!(object instanceof expectedClass)) { + details['expectedClassName'] = expectedClass.name; + throw new WorkboxError('incorrect-class', details); + } +}; + +const isOneOf = (value: any, validValues: any[], details: MapLikeObject) => { + if (!validValues.includes(value)) { + details['validValueDescription'] = `Valid values are ${JSON.stringify( + validValues, + )}.`; + throw new WorkboxError('invalid-value', details); + } +}; + +const isArrayOfClass = ( + value: any, + // Need general type to do check later. + expectedClass: Function, // eslint-disable-line + details: MapLikeObject, +) => { + const error = new WorkboxError('not-array-of-class', details); + if (!Array.isArray(value)) { + throw error; + } + + for (const item of value) { + if (!(item instanceof expectedClass)) { + throw error; + } + } +}; + +const finalAssertExports = + process.env.NODE_ENV === 'production' + ? null + : { + hasMethod, + isArray, + isInstance, + isOneOf, + isType, + isArrayOfClass, + }; + +export {finalAssertExports as assert}; diff --git a/node_modules/workbox-core/src/_private/cacheMatchIgnoreParams.ts b/node_modules/workbox-core/src/_private/cacheMatchIgnoreParams.ts new file mode 100644 index 0000000000000000000000000000000000000000..93c7126825a70e4aacd80cabc7fc2bc47a8bb61c --- /dev/null +++ b/node_modules/workbox-core/src/_private/cacheMatchIgnoreParams.ts @@ -0,0 +1,56 @@ +/* + Copyright 2020 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import '../_version.js'; + +function stripParams(fullURL: string, ignoreParams: string[]) { + const strippedURL = new URL(fullURL); + for (const param of ignoreParams) { + strippedURL.searchParams.delete(param); + } + return strippedURL.href; +} + +/** + * Matches an item in the cache, ignoring specific URL params. This is similar + * to the `ignoreSearch` option, but it allows you to ignore just specific + * params (while continuing to match on the others). + * + * @private + * @param {Cache} cache + * @param {Request} request + * @param {Object} matchOptions + * @param {Array} ignoreParams + * @return {Promise} + */ +async function cacheMatchIgnoreParams( + cache: Cache, + request: Request, + ignoreParams: string[], + matchOptions?: CacheQueryOptions, +): Promise { + const strippedRequestURL = stripParams(request.url, ignoreParams); + + // If the request doesn't include any ignored params, match as normal. + if (request.url === strippedRequestURL) { + return cache.match(request, matchOptions); + } + + // Otherwise, match by comparing keys + const keysOptions = {...matchOptions, ignoreSearch: true}; + const cacheKeys = await cache.keys(request, keysOptions); + + for (const cacheKey of cacheKeys) { + const strippedCacheKeyURL = stripParams(cacheKey.url, ignoreParams); + if (strippedRequestURL === strippedCacheKeyURL) { + return cache.match(cacheKey, matchOptions); + } + } + return; +} + +export {cacheMatchIgnoreParams}; diff --git a/node_modules/workbox-core/src/_private/cacheNames.ts b/node_modules/workbox-core/src/_private/cacheNames.ts new file mode 100644 index 0000000000000000000000000000000000000000..6a4a5cb564396670faceeb0913e000953fe6f940 --- /dev/null +++ b/node_modules/workbox-core/src/_private/cacheNames.ts @@ -0,0 +1,75 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import '../_version.js'; + +declare let registration: ServiceWorkerRegistration | undefined; + +export interface CacheNameDetails { + googleAnalytics: string; + precache: string; + prefix: string; + runtime: string; + suffix: string; +} + +export interface PartialCacheNameDetails { + [propName: string]: string; +} + +export type CacheNameDetailsProp = + | 'googleAnalytics' + | 'precache' + | 'prefix' + | 'runtime' + | 'suffix'; + +const _cacheNameDetails: CacheNameDetails = { + googleAnalytics: 'googleAnalytics', + precache: 'precache-v2', + prefix: 'workbox', + runtime: 'runtime', + suffix: typeof registration !== 'undefined' ? registration.scope : '', +}; + +const _createCacheName = (cacheName: string): string => { + return [_cacheNameDetails.prefix, cacheName, _cacheNameDetails.suffix] + .filter((value) => value && value.length > 0) + .join('-'); +}; + +const eachCacheNameDetail = (fn: (key: CacheNameDetailsProp) => void): void => { + for (const key of Object.keys(_cacheNameDetails)) { + fn(key as CacheNameDetailsProp); + } +}; + +export const cacheNames = { + updateDetails: (details: PartialCacheNameDetails): void => { + eachCacheNameDetail((key: CacheNameDetailsProp): void => { + if (typeof details[key] === 'string') { + _cacheNameDetails[key] = details[key]; + } + }); + }, + getGoogleAnalyticsName: (userCacheName?: string): string => { + return userCacheName || _createCacheName(_cacheNameDetails.googleAnalytics); + }, + getPrecacheName: (userCacheName?: string): string => { + return userCacheName || _createCacheName(_cacheNameDetails.precache); + }, + getPrefix: (): string => { + return _cacheNameDetails.prefix; + }, + getRuntimeName: (userCacheName?: string): string => { + return userCacheName || _createCacheName(_cacheNameDetails.runtime); + }, + getSuffix: (): string => { + return _cacheNameDetails.suffix; + }, +}; diff --git a/node_modules/workbox-core/src/_private/canConstructReadableStream.ts b/node_modules/workbox-core/src/_private/canConstructReadableStream.ts new file mode 100644 index 0000000000000000000000000000000000000000..dc839089e7fb3a2c4764da2047667fbcadfe5d90 --- /dev/null +++ b/node_modules/workbox-core/src/_private/canConstructReadableStream.ts @@ -0,0 +1,37 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import '../_version.js'; + +let supportStatus: boolean | undefined; + +/** + * A utility function that determines whether the current browser supports + * constructing a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream) + * object. + * + * @return {boolean} `true`, if the current browser can successfully + * construct a `ReadableStream`, `false` otherwise. + * + * @private + */ +function canConstructReadableStream(): boolean { + if (supportStatus === undefined) { + // See https://github.com/GoogleChrome/workbox/issues/1473 + try { + new ReadableStream({start() {}}); + supportStatus = true; + } catch (error) { + supportStatus = false; + } + } + + return supportStatus; +} + +export {canConstructReadableStream}; diff --git a/node_modules/workbox-core/src/_private/canConstructResponseFromBodyStream.ts b/node_modules/workbox-core/src/_private/canConstructResponseFromBodyStream.ts new file mode 100644 index 0000000000000000000000000000000000000000..00aa901be380e43b64a82c8bf9a72c9bfa66b37c --- /dev/null +++ b/node_modules/workbox-core/src/_private/canConstructResponseFromBodyStream.ts @@ -0,0 +1,40 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import '../_version.js'; + +let supportStatus: boolean | undefined; + +/** + * A utility function that determines whether the current browser supports + * constructing a new `Response` from a `response.body` stream. + * + * @return {boolean} `true`, if the current browser can successfully + * construct a `Response` from a `response.body` stream, `false` otherwise. + * + * @private + */ +function canConstructResponseFromBodyStream(): boolean { + if (supportStatus === undefined) { + const testResponse = new Response(''); + + if ('body' in testResponse) { + try { + new Response(testResponse.body); + supportStatus = true; + } catch (error) { + supportStatus = false; + } + } + supportStatus = false; + } + + return supportStatus; +} + +export {canConstructResponseFromBodyStream}; diff --git a/node_modules/workbox-core/src/_private/dontWaitFor.ts b/node_modules/workbox-core/src/_private/dontWaitFor.ts new file mode 100644 index 0000000000000000000000000000000000000000..a2f731aa501fbd5f1dd5423a91cba6a57a1ce176 --- /dev/null +++ b/node_modules/workbox-core/src/_private/dontWaitFor.ts @@ -0,0 +1,18 @@ +/* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import '../_version.js'; + +/** + * A helper function that prevents a promise from being flagged as unused. + * + * @private + **/ +export function dontWaitFor(promise: Promise): void { + // Effective no-op. + void promise.then(() => {}); +} diff --git a/node_modules/workbox-core/src/_private/executeQuotaErrorCallbacks.ts b/node_modules/workbox-core/src/_private/executeQuotaErrorCallbacks.ts new file mode 100644 index 0000000000000000000000000000000000000000..a299af170ef6534b3212d7e0a4741b6ad0766763 --- /dev/null +++ b/node_modules/workbox-core/src/_private/executeQuotaErrorCallbacks.ts @@ -0,0 +1,40 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {logger} from '../_private/logger.js'; +import {quotaErrorCallbacks} from '../models/quotaErrorCallbacks.js'; +import '../_version.js'; + +/** + * Runs all of the callback functions, one at a time sequentially, in the order + * in which they were registered. + * + * @memberof workbox-core + * @private + */ +async function executeQuotaErrorCallbacks(): Promise { + if (process.env.NODE_ENV !== 'production') { + logger.log( + `About to run ${quotaErrorCallbacks.size} ` + + `callbacks to clean up caches.`, + ); + } + + for (const callback of quotaErrorCallbacks) { + await callback(); + if (process.env.NODE_ENV !== 'production') { + logger.log(callback, 'is complete.'); + } + } + + if (process.env.NODE_ENV !== 'production') { + logger.log('Finished running callbacks.'); + } +} + +export {executeQuotaErrorCallbacks}; diff --git a/node_modules/workbox-core/src/_private/getFriendlyURL.ts b/node_modules/workbox-core/src/_private/getFriendlyURL.ts new file mode 100644 index 0000000000000000000000000000000000000000..0890c8e74e0de89fd50a3ac17c405be2efebc289 --- /dev/null +++ b/node_modules/workbox-core/src/_private/getFriendlyURL.ts @@ -0,0 +1,18 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import '../_version.js'; + +const getFriendlyURL = (url: URL | string): string => { + const urlObj = new URL(String(url), location.href); + // See https://github.com/GoogleChrome/workbox/issues/2323 + // We want to include everything, except for the origin if it's same-origin. + return urlObj.href.replace(new RegExp(`^${location.origin}`), ''); +}; + +export {getFriendlyURL}; diff --git a/node_modules/workbox-core/src/_private/logger.ts b/node_modules/workbox-core/src/_private/logger.ts new file mode 100644 index 0000000000000000000000000000000000000000..0334c461435ddec635efbd449603e91c60ecc3a5 --- /dev/null +++ b/node_modules/workbox-core/src/_private/logger.ts @@ -0,0 +1,100 @@ +/* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import '../_version.js'; + +// logger is used inside of both service workers and the window global scope. +declare global { + interface WorkerGlobalScope { + __WB_DISABLE_DEV_LOGS: boolean; + } + + interface Window { + __WB_DISABLE_DEV_LOGS: boolean; + } +} + +type LoggerMethods = + | 'debug' + | 'log' + | 'warn' + | 'error' + | 'groupCollapsed' + | 'groupEnd'; + +const logger = ( + process.env.NODE_ENV === 'production' + ? null + : (() => { + // Don't overwrite this value if it's already set. + // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923 + if (!('__WB_DISABLE_DEV_LOGS' in globalThis)) { + self.__WB_DISABLE_DEV_LOGS = false; + } + + let inGroup = false; + + const methodToColorMap: {[methodName: string]: string | null} = { + debug: `#7f8c8d`, // Gray + log: `#2ecc71`, // Green + warn: `#f39c12`, // Yellow + error: `#c0392b`, // Red + groupCollapsed: `#3498db`, // Blue + groupEnd: null, // No colored prefix on groupEnd + }; + + const print = function (method: LoggerMethods, args: any[]) { + if (self.__WB_DISABLE_DEV_LOGS) { + return; + } + + if (method === 'groupCollapsed') { + // Safari doesn't print all console.groupCollapsed() arguments: + // https://bugs.webkit.org/show_bug.cgi?id=182754 + if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) { + console[method](...args); + return; + } + } + + 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. + const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')]; + + console[method](...logPrefix, ...args); + + if (method === 'groupCollapsed') { + inGroup = true; + } + if (method === 'groupEnd') { + inGroup = false; + } + }; + // eslint-disable-next-line @typescript-eslint/ban-types + const api: {[methodName: string]: Function} = {}; + const loggerMethods = Object.keys(methodToColorMap); + + for (const key of loggerMethods) { + const method = key as LoggerMethods; + + api[method] = (...args: any[]) => { + print(method, args); + }; + } + + return api as unknown; + })() +) as Console; + +export {logger}; diff --git a/node_modules/workbox-core/src/_private/resultingClientExists.ts b/node_modules/workbox-core/src/_private/resultingClientExists.ts new file mode 100644 index 0000000000000000000000000000000000000000..b5decc6fd12f72400fc22a9438d3e764da422929 --- /dev/null +++ b/node_modules/workbox-core/src/_private/resultingClientExists.ts @@ -0,0 +1,62 @@ +/* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {timeout} from './timeout.js'; +import '../_version.js'; + +// Give TypeScript the correct global. +declare let self: ServiceWorkerGlobalScope; + +const MAX_RETRY_TIME = 2000; + +/** + * Returns a promise that resolves to a window client matching the passed + * `resultingClientId`. For browsers that don't support `resultingClientId` + * or if waiting for the resulting client to apper takes too long, resolve to + * `undefined`. + * + * @param {string} [resultingClientId] + * @return {Promise} + * @private + */ +export async function resultingClientExists( + resultingClientId?: string, +): Promise { + if (!resultingClientId) { + return; + } + + let existingWindows = await self.clients.matchAll({type: 'window'}); + const existingWindowIds = new Set(existingWindows.map((w) => w.id)); + + let resultingWindow; + const startTime = performance.now(); + + // Only wait up to `MAX_RETRY_TIME` to find a matching client. + while (performance.now() - startTime < MAX_RETRY_TIME) { + existingWindows = await self.clients.matchAll({type: 'window'}); + + resultingWindow = existingWindows.find((w) => { + if (resultingClientId) { + // If we have a `resultingClientId`, we can match on that. + return w.id === resultingClientId; + } else { + // Otherwise match on finding a window not in `existingWindowIds`. + return !existingWindowIds.has(w.id); + } + }); + + if (resultingWindow) { + break; + } + + // Sleep for 100ms and retry. + await timeout(100); + } + + return resultingWindow; +} diff --git a/node_modules/workbox-core/src/_private/timeout.ts b/node_modules/workbox-core/src/_private/timeout.ts new file mode 100644 index 0000000000000000000000000000000000000000..aa675f4142936515687f7538bc16749305f30c88 --- /dev/null +++ b/node_modules/workbox-core/src/_private/timeout.ts @@ -0,0 +1,21 @@ +/* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import '../_version.js'; + +/** + * Returns a promise that resolves and the passed number of milliseconds. + * This utility is an async/await-friendly version of `setTimeout`. + * + * @param {number} ms + * @return {Promise} + * @private + */ + +export function timeout(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} diff --git a/node_modules/workbox-core/src/_private/waitUntil.ts b/node_modules/workbox-core/src/_private/waitUntil.ts new file mode 100644 index 0000000000000000000000000000000000000000..3cde66be525a1a6950756798cc116293a4a31d14 --- /dev/null +++ b/node_modules/workbox-core/src/_private/waitUntil.ts @@ -0,0 +1,28 @@ +/* + Copyright 2020 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import '../_version.js'; + +/** + * A utility method that makes it easier to use `event.waitUntil` with + * async functions and return the result. + * + * @param {ExtendableEvent} event + * @param {Function} asyncFn + * @return {Function} + * @private + */ +function waitUntil( + event: ExtendableEvent, + asyncFn: () => Promise, +): Promise { + const returnPromise = asyncFn(); + event.waitUntil(returnPromise); + return returnPromise; +} + +export {waitUntil}; diff --git a/node_modules/workbox-core/src/_version.ts b/node_modules/workbox-core/src/_version.ts new file mode 100644 index 0000000000000000000000000000000000000000..3acb82af6ad94c79b5af04c84754daf80b37d3ef --- /dev/null +++ b/node_modules/workbox-core/src/_version.ts @@ -0,0 +1,2 @@ +// @ts-ignore +try{self['workbox:core:7.4.1']&&_()}catch(e){} \ No newline at end of file diff --git a/node_modules/workbox-core/src/cacheNames.ts b/node_modules/workbox-core/src/cacheNames.ts new file mode 100644 index 0000000000000000000000000000000000000000..858d4c2b79521e5c87e3c60834d11c9b415ac814 --- /dev/null +++ b/node_modules/workbox-core/src/cacheNames.ts @@ -0,0 +1,45 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {cacheNames as _cacheNames} from './_private/cacheNames.js'; +import './_version.js'; + +/** + * Get the current cache names and prefix/suffix used by Workbox. + * + * `cacheNames.precache` is used for precached assets, + * `cacheNames.googleAnalytics` is used by `workbox-google-analytics` to + * store `analytics.js`, and `cacheNames.runtime` is used for everything else. + * + * `cacheNames.prefix` can be used to retrieve just the current prefix value. + * `cacheNames.suffix` can be used to retrieve just the current suffix value. + * + * @return {Object} An object with `precache`, `runtime`, `prefix`, and + * `googleAnalytics` properties. + * + * @memberof workbox-core + */ +const cacheNames = { + get googleAnalytics(): string { + return _cacheNames.getGoogleAnalyticsName(); + }, + get precache(): string { + return _cacheNames.getPrecacheName(); + }, + get prefix(): string { + return _cacheNames.getPrefix(); + }, + get runtime(): string { + return _cacheNames.getRuntimeName(); + }, + get suffix(): string { + return _cacheNames.getSuffix(); + }, +}; + +export {cacheNames}; diff --git a/node_modules/workbox-core/src/clientsClaim.ts b/node_modules/workbox-core/src/clientsClaim.ts new file mode 100644 index 0000000000000000000000000000000000000000..717688b6c2530894c216eb6397f78c813142dad8 --- /dev/null +++ b/node_modules/workbox-core/src/clientsClaim.ts @@ -0,0 +1,24 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import './_version.js'; + +// Give TypeScript the correct global. +declare let self: ServiceWorkerGlobalScope; + +/** + * Claim any currently available clients once the service worker + * becomes active. This is normally used in conjunction with `skipWaiting()`. + * + * @memberof workbox-core + */ +function clientsClaim(): void { + self.addEventListener('activate', () => self.clients.claim()); +} + +export {clientsClaim}; diff --git a/node_modules/workbox-core/src/copyResponse.ts b/node_modules/workbox-core/src/copyResponse.ts new file mode 100644 index 0000000000000000000000000000000000000000..b9c520b844f3bcd726e9a253cf00732b8f51d1b6 --- /dev/null +++ b/node_modules/workbox-core/src/copyResponse.ts @@ -0,0 +1,70 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {canConstructResponseFromBodyStream} from './_private/canConstructResponseFromBodyStream.js'; +import {WorkboxError} from './_private/WorkboxError.js'; + +import './_version.js'; + +/** + * Allows developers to copy a response and modify its `headers`, `status`, + * or `statusText` values (the values settable via a + * [`ResponseInit`]{@link https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#Syntax} + * object in the constructor). + * To modify these values, pass a function as the second argument. That + * function will be invoked with a single object with the response properties + * `{headers, status, statusText}`. The return value of this function will + * be used as the `ResponseInit` for the new `Response`. To change the values + * either modify the passed parameter(s) and return it, or return a totally + * new object. + * + * This method is intentionally limited to same-origin responses, regardless of + * whether CORS was used or not. + * + * @param {Response} response + * @param {Function} modifier + * @memberof workbox-core + */ +async function copyResponse( + response: Response, + modifier?: (responseInit: ResponseInit) => ResponseInit, +): Promise { + let origin = null; + // If response.url isn't set, assume it's cross-origin and keep origin null. + if (response.url) { + const responseURL = new URL(response.url); + origin = responseURL.origin; + } + + if (origin !== self.location.origin) { + throw new WorkboxError('cross-origin-copy-response', {origin}); + } + + const clonedResponse = response.clone(); + + // Create a fresh `ResponseInit` object by cloning the headers. + const responseInit: ResponseInit = { + headers: new Headers(clonedResponse.headers), + status: clonedResponse.status, + statusText: clonedResponse.statusText, + }; + + // Apply any user modifications. + const modifiedResponseInit = modifier ? modifier(responseInit) : responseInit; + + // Create the new response from the body stream and `ResponseInit` + // modifications. Note: not all browsers support the Response.body stream, + // so fall back to reading the entire body into memory as a blob. + const body = canConstructResponseFromBodyStream() + ? clonedResponse.body + : await clonedResponse.blob(); + + return new Response(body, modifiedResponseInit); +} + +export {copyResponse}; diff --git a/node_modules/workbox-core/src/index.ts b/node_modules/workbox-core/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..111d15fcbf6836cee6c0800f16a8632696f447c3 --- /dev/null +++ b/node_modules/workbox-core/src/index.ts @@ -0,0 +1,35 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {registerQuotaErrorCallback} from './registerQuotaErrorCallback.js'; +import * as _private from './_private.js'; +import {cacheNames} from './cacheNames.js'; +import {copyResponse} from './copyResponse.js'; +import {clientsClaim} from './clientsClaim.js'; +import {setCacheNameDetails} from './setCacheNameDetails.js'; +import {skipWaiting} from './skipWaiting.js'; +import './_version.js'; + +/** + * All of the Workbox service worker libraries use workbox-core for shared + * code as well as setting default values that need to be shared (like cache + * names). + * + * @module workbox-core + */ +export { + _private, + cacheNames, + clientsClaim, + copyResponse, + registerQuotaErrorCallback, + setCacheNameDetails, + skipWaiting, +}; + +export * from './types.js'; diff --git a/node_modules/workbox-core/src/models/messages/messageGenerator.ts b/node_modules/workbox-core/src/models/messages/messageGenerator.ts new file mode 100644 index 0000000000000000000000000000000000000000..aba95368d26e3c68e04736ace15a87d7ae4811cd --- /dev/null +++ b/node_modules/workbox-core/src/models/messages/messageGenerator.ts @@ -0,0 +1,30 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {messages} from './messages.js'; +import '../../_version.js'; + +const fallback = (code: string, ...args: any[]) => { + let msg = code; + if (args.length > 0) { + msg += ` :: ${JSON.stringify(args)}`; + } + return msg; +}; + +const generatorFunction = (code: string, details = {}) => { + const message = messages[code]; + if (!message) { + throw new Error(`Unable to find message for code '${code}'.`); + } + + return message(details); +}; + +export const messageGenerator = + process.env.NODE_ENV === 'production' ? fallback : generatorFunction; diff --git a/node_modules/workbox-core/src/models/messages/messages.ts b/node_modules/workbox-core/src/models/messages/messages.ts new file mode 100644 index 0000000000000000000000000000000000000000..96c118ecede43d9bf04ceef905c2099e46ddec07 --- /dev/null +++ b/node_modules/workbox-core/src/models/messages/messages.ts @@ -0,0 +1,382 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import '../../_version.js'; + +interface LoggableObject { + [key: string]: string | number; +} +interface MessageMap { + [messageID: string]: (param: LoggableObject) => string; +} + +export const messages: MessageMap = { + 'invalid-value': ({paramName, validValueDescription, value}) => { + if (!paramName || !validValueDescription) { + throw new Error(`Unexpected input to 'invalid-value' error.`); + } + return ( + `The '${paramName}' parameter was given a value with an ` + + `unexpected value. ${validValueDescription} Received a value of ` + + `${JSON.stringify(value)}.` + ); + }, + + 'not-an-array': ({moduleName, className, funcName, paramName}) => { + if (!moduleName || !className || !funcName || !paramName) { + throw new Error(`Unexpected input to 'not-an-array' error.`); + } + return ( + `The parameter '${paramName}' passed into ` + + `'${moduleName}.${className}.${funcName}()' must be an array.` + ); + }, + + 'incorrect-type': ({ + expectedType, + paramName, + moduleName, + className, + funcName, + }) => { + if (!expectedType || !paramName || !moduleName || !funcName) { + throw new Error(`Unexpected input to 'incorrect-type' error.`); + } + const classNameStr = className ? `${className}.` : ''; + return ( + `The parameter '${paramName}' passed into ` + + `'${moduleName}.${classNameStr}` + + `${funcName}()' must be of type ${expectedType}.` + ); + }, + + 'incorrect-class': ({ + expectedClassName, + paramName, + moduleName, + className, + funcName, + isReturnValueProblem, + }) => { + if (!expectedClassName || !moduleName || !funcName) { + throw new Error(`Unexpected input to 'incorrect-class' error.`); + } + const classNameStr = className ? `${className}.` : ''; + if (isReturnValueProblem) { + return ( + `The return value from ` + + `'${moduleName}.${classNameStr}${funcName}()' ` + + `must be an instance of class ${expectedClassName}.` + ); + } + + return ( + `The parameter '${paramName}' passed into ` + + `'${moduleName}.${classNameStr}${funcName}()' ` + + `must be an instance of class ${expectedClassName}.` + ); + }, + + 'missing-a-method': ({ + expectedMethod, + paramName, + moduleName, + className, + funcName, + }) => { + if ( + !expectedMethod || + !paramName || + !moduleName || + !className || + !funcName + ) { + throw new Error(`Unexpected input to 'missing-a-method' error.`); + } + return ( + `${moduleName}.${className}.${funcName}() expected the ` + + `'${paramName}' parameter to expose a '${expectedMethod}' method.` + ); + }, + + 'add-to-cache-list-unexpected-type': ({entry}) => { + 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.` + ); + }, + + 'add-to-cache-list-conflicting-entries': ({firstEntry, secondEntry}) => { + if (!firstEntry || !secondEntry) { + throw new Error( + `Unexpected input to ` + `'add-to-cache-list-duplicate-entries' error.`, + ); + } + + return ( + `Two of the entries passed to ` + + `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` + + `${firstEntry} but different revision details. Workbox is ` + + `unable to cache and version the asset correctly. Please remove one ` + + `of the entries.` + ); + }, + + 'plugin-error-request-will-fetch': ({thrownErrorMessage}) => { + if (!thrownErrorMessage) { + throw new Error( + `Unexpected input to ` + `'plugin-error-request-will-fetch', error.`, + ); + } + + return ( + `An error was thrown by a plugins 'requestWillFetch()' method. ` + + `The thrown error message was: '${thrownErrorMessage}'.` + ); + }, + + 'invalid-cache-name': ({cacheNameId, value}) => { + if (!cacheNameId) { + throw new Error( + `Expected a 'cacheNameId' for error 'invalid-cache-name'`, + ); + } + + return ( + `You must provide a name containing at least one character for ` + + `setCacheDetails({${cacheNameId}: '...'}). Received a value of ` + + `'${JSON.stringify(value)}'` + ); + }, + + 'unregister-route-but-not-found-with-method': ({method}) => { + if (!method) { + throw new Error( + `Unexpected input to ` + + `'unregister-route-but-not-found-with-method' error.`, + ); + } + + return ( + `The route you're trying to unregister was not previously ` + + `registered for the method type '${method}'.` + ); + }, + + 'unregister-route-route-not-registered': () => { + return ( + `The route you're trying to unregister was not previously ` + + `registered.` + ); + }, + + 'queue-replay-failed': ({name}) => { + return `Replaying the background sync queue '${name}' failed.`; + }, + + 'duplicate-queue-name': ({name}) => { + return ( + `The Queue name '${name}' is already being used. ` + + `All instances of backgroundSync.Queue must be given unique names.` + ); + }, + + 'expired-test-without-max-age': ({methodName, paramName}) => { + return ( + `The '${methodName}()' method can only be used when the ` + + `'${paramName}' is used in the constructor.` + ); + }, + + 'unsupported-route-type': ({moduleName, className, funcName, paramName}) => { + return ( + `The supplied '${paramName}' parameter was an unsupported type. ` + + `Please check the docs for ${moduleName}.${className}.${funcName} for ` + + `valid input types.` + ); + }, + + 'not-array-of-class': ({ + value, + expectedClass, + moduleName, + className, + funcName, + paramName, + }) => { + 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.` + ); + }, + + 'max-entries-or-age-required': ({moduleName, className, funcName}) => { + return ( + `You must define either config.maxEntries or config.maxAgeSeconds` + + `in ${moduleName}.${className}.${funcName}` + ); + }, + + 'statuses-or-headers-required': ({moduleName, className, funcName}) => { + return ( + `You must define either config.statuses or config.headers` + + `in ${moduleName}.${className}.${funcName}` + ); + }, + + 'invalid-string': ({moduleName, funcName, paramName}) => { + if (!paramName || !moduleName || !funcName) { + throw new Error(`Unexpected input to 'invalid-string' error.`); + } + 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.` + ); + }, + + 'channel-name-required': () => { + return ( + `You must provide a channelName to construct a ` + + `BroadcastCacheUpdate instance.` + ); + }, + + 'invalid-responses-are-same-args': () => { + return ( + `The arguments passed into responsesAreSame() appear to be ` + + `invalid. Please ensure valid Responses are used.` + ); + }, + + 'expire-custom-caches-only': () => { + return ( + `You must provide a 'cacheName' property when using the ` + + `expiration plugin with a runtime caching strategy.` + ); + }, + + 'unit-must-be-bytes': ({normalizedRangeHeader}) => { + if (!normalizedRangeHeader) { + throw new Error(`Unexpected input to 'unit-must-be-bytes' error.`); + } + return ( + `The 'unit' portion of the Range header must be set to 'bytes'. ` + + `The Range header provided was "${normalizedRangeHeader}"` + ); + }, + + 'single-range-only': ({normalizedRangeHeader}) => { + if (!normalizedRangeHeader) { + throw new Error(`Unexpected input to 'single-range-only' error.`); + } + return ( + `Multiple ranges are not supported. Please use a single start ` + + `value, and optional end value. The Range header provided was ` + + `"${normalizedRangeHeader}"` + ); + }, + + 'invalid-range-values': ({normalizedRangeHeader}) => { + if (!normalizedRangeHeader) { + throw new Error(`Unexpected input to 'invalid-range-values' error.`); + } + 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}"` + ); + }, + + 'no-range-header': () => { + return `No Range header was found in the Request provided.`; + }, + + 'range-not-satisfiable': ({size, start, end}) => { + return ( + `The start (${start}) and end (${end}) values in the Range are ` + + `not satisfiable by the cached response, which is ${size} bytes.` + ); + }, + + 'attempt-to-cache-non-get-request': ({url, method}) => { + return ( + `Unable to cache '${url}' because it is a '${method}' request and ` + + `only 'GET' requests can be cached.` + ); + }, + + 'cache-put-with-no-response': ({url}) => { + return ( + `There was an attempt to cache '${url}' but the response was not ` + + `defined.` + ); + }, + + 'no-response': ({url, error}) => { + let message = `The strategy could not generate a response for '${url}'.`; + if (error) { + message += ` The underlying error is ${error}.`; + } + return message; + }, + + 'bad-precaching-response': ({url, status}) => { + return ( + `The precaching request for '${url}' failed` + + (status ? ` with an HTTP status of ${status}.` : `.`) + ); + }, + + 'non-precached-url': ({url}) => { + return ( + `createHandlerBoundToURL('${url}') was called, but that URL is ` + + `not precached. Please pass in a URL that is precached instead.` + ); + }, + + 'add-to-cache-list-conflicting-integrities': ({url}) => { + return ( + `Two of the entries passed to ` + + `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` + + `${url} with different integrity values. Please remove one of them.` + ); + }, + + 'missing-precache-entry': ({cacheName, url}) => { + return `Unable to find a precached response in ${cacheName} for ${url}.`; + }, + + 'cross-origin-copy-response': ({origin}) => { + return ( + `workbox-core.copyResponse() can only be used with same-origin ` + + `responses. It was passed a response with origin ${origin}.` + ); + }, + + 'opaque-streams-source': ({type}) => { + const message = + `One of the workbox-streams sources resulted in an ` + + `'${type}' response.`; + if (type === 'opaqueredirect') { + return ( + `${message} Please do not use a navigation request that results ` + + `in a redirect as a source.` + ); + } + return `${message} Please ensure your sources are CORS-enabled.`; + }, +}; diff --git a/node_modules/workbox-core/src/models/pluginEvents.ts b/node_modules/workbox-core/src/models/pluginEvents.ts new file mode 100644 index 0000000000000000000000000000000000000000..6690df46a4d90c3e0076342161297291cfe83cd1 --- /dev/null +++ b/node_modules/workbox-core/src/models/pluginEvents.ts @@ -0,0 +1,19 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import '../_version.js'; + +export const enum pluginEvents { + CACHE_DID_UPDATE = 'cacheDidUpdate', + CACHE_KEY_WILL_BE_USED = 'cacheKeyWillBeUsed', + CACHE_WILL_UPDATE = 'cacheWillUpdate', + CACHED_RESPONSE_WILL_BE_USED = 'cachedResponseWillBeUsed', + FETCH_DID_FAIL = 'fetchDidFail', + FETCH_DID_SUCCEED = 'fetchDidSucceed', + REQUEST_WILL_FETCH = 'requestWillFetch', +} diff --git a/node_modules/workbox-core/src/models/quotaErrorCallbacks.ts b/node_modules/workbox-core/src/models/quotaErrorCallbacks.ts new file mode 100644 index 0000000000000000000000000000000000000000..0d3f9d0d2263bcf48fd9eac1ae468efabc4e496d --- /dev/null +++ b/node_modules/workbox-core/src/models/quotaErrorCallbacks.ts @@ -0,0 +1,16 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import '../_version.js'; + +// Callbacks to be executed whenever there's a quota error. +// Can't change Function type right now. +// eslint-disable-next-line @typescript-eslint/ban-types +const quotaErrorCallbacks: Set = new Set(); + +export {quotaErrorCallbacks}; diff --git a/node_modules/workbox-core/src/registerQuotaErrorCallback.ts b/node_modules/workbox-core/src/registerQuotaErrorCallback.ts new file mode 100644 index 0000000000000000000000000000000000000000..f94e804a3d0587e3315bd51a4eb7ea0c1de7f61a --- /dev/null +++ b/node_modules/workbox-core/src/registerQuotaErrorCallback.ts @@ -0,0 +1,39 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {logger} from './_private/logger.js'; +import {assert} from './_private/assert.js'; +import {quotaErrorCallbacks} from './models/quotaErrorCallbacks.js'; +import './_version.js'; + +/** + * Adds a function to the set of quotaErrorCallbacks that will be executed if + * there's a quota error. + * + * @param {Function} callback + * @memberof workbox-core + */ +// Can't change Function type +// eslint-disable-next-line @typescript-eslint/ban-types +function registerQuotaErrorCallback(callback: Function): void { + if (process.env.NODE_ENV !== 'production') { + assert!.isType(callback, 'function', { + moduleName: 'workbox-core', + funcName: 'register', + paramName: 'callback', + }); + } + + quotaErrorCallbacks.add(callback); + + if (process.env.NODE_ENV !== 'production') { + logger.log('Registered a callback to respond to quota errors.', callback); + } +} + +export {registerQuotaErrorCallback}; diff --git a/node_modules/workbox-core/src/setCacheNameDetails.ts b/node_modules/workbox-core/src/setCacheNameDetails.ts new file mode 100644 index 0000000000000000000000000000000000000000..f24a06b4063428e3830a3fb3a96556a5710611f5 --- /dev/null +++ b/node_modules/workbox-core/src/setCacheNameDetails.ts @@ -0,0 +1,69 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {assert} from './_private/assert.js'; +import {cacheNames, PartialCacheNameDetails} from './_private/cacheNames.js'; +import {WorkboxError} from './_private/WorkboxError.js'; +import './_version.js'; + +/** + * Modifies the default cache names used by the Workbox packages. + * Cache names are generated as `--`. + * + * @param {Object} details + * @param {Object} [details.prefix] The string to add to the beginning of + * the precache and runtime cache names. + * @param {Object} [details.suffix] The string to add to the end of + * the precache and runtime cache names. + * @param {Object} [details.precache] The cache name to use for precache + * caching. + * @param {Object} [details.runtime] The cache name to use for runtime caching. + * @param {Object} [details.googleAnalytics] The cache name to use for + * `workbox-google-analytics` caching. + * + * @memberof workbox-core + */ +function setCacheNameDetails(details: PartialCacheNameDetails): void { + if (process.env.NODE_ENV !== 'production') { + Object.keys(details).forEach((key) => { + assert!.isType(details[key], 'string', { + moduleName: 'workbox-core', + funcName: 'setCacheNameDetails', + paramName: `details.${key}`, + }); + }); + + if ('precache' in details && details['precache']!.length === 0) { + throw new WorkboxError('invalid-cache-name', { + cacheNameId: 'precache', + value: details['precache'], + }); + } + + if ('runtime' in details && details['runtime']!.length === 0) { + throw new WorkboxError('invalid-cache-name', { + cacheNameId: 'runtime', + value: details['runtime'], + }); + } + + if ( + 'googleAnalytics' in details && + details['googleAnalytics'].length === 0 + ) { + throw new WorkboxError('invalid-cache-name', { + cacheNameId: 'googleAnalytics', + value: details['googleAnalytics'], + }); + } + } + + cacheNames.updateDetails(details); +} + +export {setCacheNameDetails}; diff --git a/node_modules/workbox-core/src/skipWaiting.ts b/node_modules/workbox-core/src/skipWaiting.ts new file mode 100644 index 0000000000000000000000000000000000000000..5fc833fc186b5dcf8e25ec20b2706ae18904c7c8 --- /dev/null +++ b/node_modules/workbox-core/src/skipWaiting.ts @@ -0,0 +1,37 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {logger} from './_private/logger.js'; + +import './_version.js'; + +// Give TypeScript the correct global. +declare let self: ServiceWorkerGlobalScope; + +/** + * This method is deprecated, and will be removed in Workbox v7. + * + * Calling self.skipWaiting() is equivalent, and should be used instead. + * + * @memberof workbox-core + */ +function skipWaiting(): void { + // Just call self.skipWaiting() directly. + // See https://github.com/GoogleChrome/workbox/issues/2525 + if (process.env.NODE_ENV !== 'production') { + logger.warn( + `skipWaiting() from workbox-core is no longer recommended ` + + `and will be removed in Workbox v7. Using self.skipWaiting() instead ` + + `is equivalent.`, + ); + } + + void self.skipWaiting(); +} + +export {skipWaiting}; diff --git a/node_modules/workbox-core/src/types.ts b/node_modules/workbox-core/src/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..7a8642f136ada58a5948ecf7de3df3c4f55617b4 --- /dev/null +++ b/node_modules/workbox-core/src/types.ts @@ -0,0 +1,282 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import './_version.js'; + +export interface MapLikeObject { + [key: string]: any; +} + +/** + * Using a plain `MapLikeObject` for now, but could extend/restrict this + * in the future. + */ +export type PluginState = MapLikeObject; + +/** + * Options passed to a `RouteMatchCallback` function. + */ +export interface RouteMatchCallbackOptions { + event: ExtendableEvent; + request: Request; + sameOrigin: boolean; + url: URL; +} + +/** + * The "match" callback is used to determine if a `Route` should apply for a + * particular URL and request. When matching occurs in response to a fetch + * event from the client, the `event` object is also supplied. However, since + * the match callback can be invoked outside of a fetch event, matching logic + * should not assume the `event` object will always be available. + * If the match callback returns a truthy value, the matching route's + * `RouteHandlerCallback` will be invoked immediately. If the value returned + * is a non-empty array or object, that value will be set on the handler's + * `options.params` argument. + */ +export interface RouteMatchCallback { + (options: RouteMatchCallbackOptions): any; +} + +/** + * Options passed to a `RouteHandlerCallback` function. + */ +export declare interface RouteHandlerCallbackOptions { + event: ExtendableEvent; + request: Request; + url: URL; + params?: string[] | MapLikeObject; +} + +/** + * Options passed to a `ManualHandlerCallback` function. + */ +export interface ManualHandlerCallbackOptions { + event: ExtendableEvent; + request: Request | string; +} + +export type HandlerCallbackOptions = + | RouteHandlerCallbackOptions + | ManualHandlerCallbackOptions; + +/** + * The "handler" callback is invoked whenever a `Router` matches a URL/Request + * to a `Route` via its `RouteMatchCallback`. This handler callback should + * return a `Promise` that resolves with a `Response`. + * + * If a non-empty array or object is returned by the `RouteMatchCallback` it + * will be passed in as this handler's `options.params` argument. + */ +export interface RouteHandlerCallback { + (options: RouteHandlerCallbackOptions): Promise; +} + +/** + * The "handler" callback is invoked whenever a `Router` matches a URL/Request + * to a `Route` via its `RouteMatchCallback`. This handler callback should + * return a `Promise` that resolves with a `Response`. + * + * If a non-empty array or object is returned by the `RouteMatchCallback` it + * will be passed in as this handler's `options.params` argument. + */ +export interface ManualHandlerCallback { + (options: ManualHandlerCallbackOptions): Promise; +} + +/** + * An object with a `handle` method of type `RouteHandlerCallback`. + * + * A `Route` object can be created with either an `RouteHandlerCallback` + * function or this `RouteHandler` object. The benefit of the `RouteHandler` + * is it can be extended (as is done by the `workbox-strategies` package). + */ +export interface RouteHandlerObject { + handle: RouteHandlerCallback; +} + +/** + * Either a `RouteHandlerCallback` or a `RouteHandlerObject`. + * Most APIs in `workbox-routing` that accept route handlers take either. + */ +export type RouteHandler = RouteHandlerCallback | RouteHandlerObject; + +export interface HandlerWillStartCallbackParam { + request: Request; + event: ExtendableEvent; + state?: PluginState; +} + +export interface HandlerWillStartCallback { + (param: HandlerWillStartCallbackParam): Promise; +} + +export interface CacheDidUpdateCallbackParam { + cacheName: string; + newResponse: Response; + request: Request; + event: ExtendableEvent; + oldResponse?: Response | null; + state?: PluginState; +} + +export interface CacheDidUpdateCallback { + (param: CacheDidUpdateCallbackParam): Promise; +} + +export interface CacheKeyWillBeUsedCallbackParam { + mode: string; + request: Request; + event: ExtendableEvent; + params?: any; + state?: PluginState; +} + +export interface CacheKeyWillBeUsedCallback { + (param: CacheKeyWillBeUsedCallbackParam): Promise; +} + +export interface CacheWillUpdateCallbackParam { + request: Request; + response: Response; + event: ExtendableEvent; + state?: PluginState; +} + +export interface CacheWillUpdateCallback { + (param: CacheWillUpdateCallbackParam): Promise< + Response | void | null | undefined + >; +} + +export interface CachedResponseWillBeUsedCallbackParam { + cacheName: string; + request: Request; + cachedResponse?: Response; + event: ExtendableEvent; + matchOptions?: CacheQueryOptions; + state?: PluginState; +} + +export interface CachedResponseWillBeUsedCallback { + (param: CachedResponseWillBeUsedCallbackParam): Promise< + Response | void | null | undefined + >; +} + +export interface FetchDidFailCallbackParam { + error: Error; + originalRequest: Request; + request: Request; + event: ExtendableEvent; + state?: PluginState; +} + +export interface FetchDidFailCallback { + (param: FetchDidFailCallbackParam): Promise; +} + +export interface FetchDidSucceedCallbackParam { + request: Request; + response: Response; + event: ExtendableEvent; + state?: PluginState; +} + +export interface FetchDidSucceedCallback { + (param: FetchDidSucceedCallbackParam): Promise; +} + +export interface RequestWillFetchCallbackParam { + request: Request; + event: ExtendableEvent; + state?: PluginState; +} + +export interface RequestWillFetchCallback { + (param: RequestWillFetchCallbackParam): Promise; +} + +export interface HandlerWillRespondCallbackParam { + request: Request; + response: Response; + event: ExtendableEvent; + state?: PluginState; +} + +export interface HandlerWillRespondCallback { + (param: HandlerWillRespondCallbackParam): Promise; +} + +export interface HandlerDidErrorCallbackParam { + request: Request; + event: ExtendableEvent; + error: Error; + state?: PluginState; +} + +export interface HandlerDidErrorCallback { + (param: HandlerDidErrorCallbackParam): Promise; +} + +export interface HandlerDidRespondCallbackParam { + request: Request; + event: ExtendableEvent; + response?: Response; + state?: PluginState; +} + +export interface HandlerDidRespondCallback { + (param: HandlerDidRespondCallbackParam): Promise; +} + +export interface HandlerDidCompleteCallbackParam { + request: Request; + error?: Error; + event: ExtendableEvent; + response?: Response; + state?: PluginState; +} + +export interface HandlerDidCompleteCallback { + (param: HandlerDidCompleteCallbackParam): Promise; +} + +/** + * An object with optional lifecycle callback properties for the fetch and + * cache operations. + */ +export declare interface WorkboxPlugin { + cacheDidUpdate?: CacheDidUpdateCallback; + cachedResponseWillBeUsed?: CachedResponseWillBeUsedCallback; + cacheKeyWillBeUsed?: CacheKeyWillBeUsedCallback; + cacheWillUpdate?: CacheWillUpdateCallback; + fetchDidFail?: FetchDidFailCallback; + fetchDidSucceed?: FetchDidSucceedCallback; + handlerDidComplete?: HandlerDidCompleteCallback; + handlerDidError?: HandlerDidErrorCallback; + handlerDidRespond?: HandlerDidRespondCallback; + handlerWillRespond?: HandlerWillRespondCallback; + handlerWillStart?: HandlerWillStartCallback; + requestWillFetch?: RequestWillFetchCallback; +} + +export interface WorkboxPluginCallbackParam { + cacheDidUpdate: CacheDidUpdateCallbackParam; + cachedResponseWillBeUsed: CachedResponseWillBeUsedCallbackParam; + cacheKeyWillBeUsed: CacheKeyWillBeUsedCallbackParam; + cacheWillUpdate: CacheWillUpdateCallbackParam; + fetchDidFail: FetchDidFailCallbackParam; + fetchDidSucceed: FetchDidSucceedCallbackParam; + handlerDidComplete: HandlerDidCompleteCallbackParam; + handlerDidError: HandlerDidErrorCallbackParam; + handlerDidRespond: HandlerDidRespondCallbackParam; + handlerWillRespond: HandlerWillRespondCallbackParam; + handlerWillStart: HandlerWillStartCallbackParam; + requestWillFetch: RequestWillFetchCallbackParam; +} diff --git a/node_modules/workbox-core/src/utils/pluginUtils.ts b/node_modules/workbox-core/src/utils/pluginUtils.ts new file mode 100644 index 0000000000000000000000000000000000000000..4fa8515440e4870c339a008b4c41bd1808794ff8 --- /dev/null +++ b/node_modules/workbox-core/src/utils/pluginUtils.ts @@ -0,0 +1,16 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {WorkboxPlugin} from '../types.js'; +import '../_version.js'; + +export const pluginUtils = { + filter: (plugins: WorkboxPlugin[], callbackName: string): WorkboxPlugin[] => { + return plugins.filter((plugin) => callbackName in plugin); + }, +}; diff --git a/node_modules/workbox-core/src/utils/welcome.ts b/node_modules/workbox-core/src/utils/welcome.ts new file mode 100644 index 0000000000000000000000000000000000000000..8dfde13b3cf03d76d1b7c6535456a9ec2e3bb7a6 --- /dev/null +++ b/node_modules/workbox-core/src/utils/welcome.ts @@ -0,0 +1,35 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {logger} from '../_private/logger.js'; +import '../_version.js'; + +// A WorkboxCore instance must be exported before we can use the logger. +// This is so it can get the current log level. +if (process.env.NODE_ENV !== 'production') { + const padding = ' '; + logger.groupCollapsed('Welcome to Workbox!'); + logger.log( + `You are currently using a development build. ` + + `By default this will switch to prod builds when not on localhost. ` + + `You can force this with workbox.setConfig({debug: true|false}).`, + ); + logger.log( + `📖 Read the guides and documentation\n` + + `${padding}https://developers.google.com/web/tools/workbox/`, + ); + logger.log( + `❓ Use the [workbox] tag on Stack Overflow to ask questions\n` + + `${padding}https://stackoverflow.com/questions/ask?tags=workbox`, + ); + logger.log( + `🐛 Found a bug? Report it on GitHub\n` + + `${padding}https://github.com/GoogleChrome/workbox/issues/new`, + ); + logger.groupEnd(); +} diff --git a/node_modules/workbox-core/tsconfig.json b/node_modules/workbox-core/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..2a5af270c34a08b0a0d1f4a5fcd91fd96ee7d569 --- /dev/null +++ b/node_modules/workbox-core/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig", + "compilerOptions": { + "composite": true, + "outDir": "./", + "rootDir": "./src", + "tsBuildInfoFile": "./tsconfig.tsbuildinfo" + }, + "include": ["src/**/*.ts"] +} diff --git a/node_modules/workbox-core/types.d.ts b/node_modules/workbox-core/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..feefe0ceebd20114f22ee130fffb6f6b3b78dcd1 --- /dev/null +++ b/node_modules/workbox-core/types.d.ts @@ -0,0 +1,231 @@ +import './_version.js'; +export interface MapLikeObject { + [key: string]: any; +} +/** + * Using a plain `MapLikeObject` for now, but could extend/restrict this + * in the future. + */ +export type PluginState = MapLikeObject; +/** + * Options passed to a `RouteMatchCallback` function. + */ +export interface RouteMatchCallbackOptions { + event: ExtendableEvent; + request: Request; + sameOrigin: boolean; + url: URL; +} +/** + * The "match" callback is used to determine if a `Route` should apply for a + * particular URL and request. When matching occurs in response to a fetch + * event from the client, the `event` object is also supplied. However, since + * the match callback can be invoked outside of a fetch event, matching logic + * should not assume the `event` object will always be available. + * If the match callback returns a truthy value, the matching route's + * `RouteHandlerCallback` will be invoked immediately. If the value returned + * is a non-empty array or object, that value will be set on the handler's + * `options.params` argument. + */ +export interface RouteMatchCallback { + (options: RouteMatchCallbackOptions): any; +} +/** + * Options passed to a `RouteHandlerCallback` function. + */ +export declare interface RouteHandlerCallbackOptions { + event: ExtendableEvent; + request: Request; + url: URL; + params?: string[] | MapLikeObject; +} +/** + * Options passed to a `ManualHandlerCallback` function. + */ +export interface ManualHandlerCallbackOptions { + event: ExtendableEvent; + request: Request | string; +} +export type HandlerCallbackOptions = RouteHandlerCallbackOptions | ManualHandlerCallbackOptions; +/** + * The "handler" callback is invoked whenever a `Router` matches a URL/Request + * to a `Route` via its `RouteMatchCallback`. This handler callback should + * return a `Promise` that resolves with a `Response`. + * + * If a non-empty array or object is returned by the `RouteMatchCallback` it + * will be passed in as this handler's `options.params` argument. + */ +export interface RouteHandlerCallback { + (options: RouteHandlerCallbackOptions): Promise; +} +/** + * The "handler" callback is invoked whenever a `Router` matches a URL/Request + * to a `Route` via its `RouteMatchCallback`. This handler callback should + * return a `Promise` that resolves with a `Response`. + * + * If a non-empty array or object is returned by the `RouteMatchCallback` it + * will be passed in as this handler's `options.params` argument. + */ +export interface ManualHandlerCallback { + (options: ManualHandlerCallbackOptions): Promise; +} +/** + * An object with a `handle` method of type `RouteHandlerCallback`. + * + * A `Route` object can be created with either an `RouteHandlerCallback` + * function or this `RouteHandler` object. The benefit of the `RouteHandler` + * is it can be extended (as is done by the `workbox-strategies` package). + */ +export interface RouteHandlerObject { + handle: RouteHandlerCallback; +} +/** + * Either a `RouteHandlerCallback` or a `RouteHandlerObject`. + * Most APIs in `workbox-routing` that accept route handlers take either. + */ +export type RouteHandler = RouteHandlerCallback | RouteHandlerObject; +export interface HandlerWillStartCallbackParam { + request: Request; + event: ExtendableEvent; + state?: PluginState; +} +export interface HandlerWillStartCallback { + (param: HandlerWillStartCallbackParam): Promise; +} +export interface CacheDidUpdateCallbackParam { + cacheName: string; + newResponse: Response; + request: Request; + event: ExtendableEvent; + oldResponse?: Response | null; + state?: PluginState; +} +export interface CacheDidUpdateCallback { + (param: CacheDidUpdateCallbackParam): Promise; +} +export interface CacheKeyWillBeUsedCallbackParam { + mode: string; + request: Request; + event: ExtendableEvent; + params?: any; + state?: PluginState; +} +export interface CacheKeyWillBeUsedCallback { + (param: CacheKeyWillBeUsedCallbackParam): Promise; +} +export interface CacheWillUpdateCallbackParam { + request: Request; + response: Response; + event: ExtendableEvent; + state?: PluginState; +} +export interface CacheWillUpdateCallback { + (param: CacheWillUpdateCallbackParam): Promise; +} +export interface CachedResponseWillBeUsedCallbackParam { + cacheName: string; + request: Request; + cachedResponse?: Response; + event: ExtendableEvent; + matchOptions?: CacheQueryOptions; + state?: PluginState; +} +export interface CachedResponseWillBeUsedCallback { + (param: CachedResponseWillBeUsedCallbackParam): Promise; +} +export interface FetchDidFailCallbackParam { + error: Error; + originalRequest: Request; + request: Request; + event: ExtendableEvent; + state?: PluginState; +} +export interface FetchDidFailCallback { + (param: FetchDidFailCallbackParam): Promise; +} +export interface FetchDidSucceedCallbackParam { + request: Request; + response: Response; + event: ExtendableEvent; + state?: PluginState; +} +export interface FetchDidSucceedCallback { + (param: FetchDidSucceedCallbackParam): Promise; +} +export interface RequestWillFetchCallbackParam { + request: Request; + event: ExtendableEvent; + state?: PluginState; +} +export interface RequestWillFetchCallback { + (param: RequestWillFetchCallbackParam): Promise; +} +export interface HandlerWillRespondCallbackParam { + request: Request; + response: Response; + event: ExtendableEvent; + state?: PluginState; +} +export interface HandlerWillRespondCallback { + (param: HandlerWillRespondCallbackParam): Promise; +} +export interface HandlerDidErrorCallbackParam { + request: Request; + event: ExtendableEvent; + error: Error; + state?: PluginState; +} +export interface HandlerDidErrorCallback { + (param: HandlerDidErrorCallbackParam): Promise; +} +export interface HandlerDidRespondCallbackParam { + request: Request; + event: ExtendableEvent; + response?: Response; + state?: PluginState; +} +export interface HandlerDidRespondCallback { + (param: HandlerDidRespondCallbackParam): Promise; +} +export interface HandlerDidCompleteCallbackParam { + request: Request; + error?: Error; + event: ExtendableEvent; + response?: Response; + state?: PluginState; +} +export interface HandlerDidCompleteCallback { + (param: HandlerDidCompleteCallbackParam): Promise; +} +/** + * An object with optional lifecycle callback properties for the fetch and + * cache operations. + */ +export declare interface WorkboxPlugin { + cacheDidUpdate?: CacheDidUpdateCallback; + cachedResponseWillBeUsed?: CachedResponseWillBeUsedCallback; + cacheKeyWillBeUsed?: CacheKeyWillBeUsedCallback; + cacheWillUpdate?: CacheWillUpdateCallback; + fetchDidFail?: FetchDidFailCallback; + fetchDidSucceed?: FetchDidSucceedCallback; + handlerDidComplete?: HandlerDidCompleteCallback; + handlerDidError?: HandlerDidErrorCallback; + handlerDidRespond?: HandlerDidRespondCallback; + handlerWillRespond?: HandlerWillRespondCallback; + handlerWillStart?: HandlerWillStartCallback; + requestWillFetch?: RequestWillFetchCallback; +} +export interface WorkboxPluginCallbackParam { + cacheDidUpdate: CacheDidUpdateCallbackParam; + cachedResponseWillBeUsed: CachedResponseWillBeUsedCallbackParam; + cacheKeyWillBeUsed: CacheKeyWillBeUsedCallbackParam; + cacheWillUpdate: CacheWillUpdateCallbackParam; + fetchDidFail: FetchDidFailCallbackParam; + fetchDidSucceed: FetchDidSucceedCallbackParam; + handlerDidComplete: HandlerDidCompleteCallbackParam; + handlerDidError: HandlerDidErrorCallbackParam; + handlerDidRespond: HandlerDidRespondCallbackParam; + handlerWillRespond: HandlerWillRespondCallbackParam; + handlerWillStart: HandlerWillStartCallbackParam; + requestWillFetch: RequestWillFetchCallbackParam; +} diff --git a/node_modules/workbox-core/types.js b/node_modules/workbox-core/types.js new file mode 100644 index 0000000000000000000000000000000000000000..49de87b42b8868039022123f24c28be28fce527f --- /dev/null +++ b/node_modules/workbox-core/types.js @@ -0,0 +1,8 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import './_version.js'; diff --git a/node_modules/workbox-core/types.mjs b/node_modules/workbox-core/types.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8234c6c66d449dc48f9750e84bb1d48ae0207673 --- /dev/null +++ b/node_modules/workbox-core/types.mjs @@ -0,0 +1 @@ +export * from './types.js'; \ No newline at end of file diff --git a/node_modules/workbox-core/utils/pluginUtils.d.ts b/node_modules/workbox-core/utils/pluginUtils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..aeb8812dfeb63c3efbbb63fe482e3610f330ea4d --- /dev/null +++ b/node_modules/workbox-core/utils/pluginUtils.d.ts @@ -0,0 +1,5 @@ +import { WorkboxPlugin } from '../types.js'; +import '../_version.js'; +export declare const pluginUtils: { + filter: (plugins: WorkboxPlugin[], callbackName: string) => WorkboxPlugin[]; +}; diff --git a/node_modules/workbox-core/utils/pluginUtils.js b/node_modules/workbox-core/utils/pluginUtils.js new file mode 100644 index 0000000000000000000000000000000000000000..10d20f165fd44724eb97209194714d8b0ed7bdcb --- /dev/null +++ b/node_modules/workbox-core/utils/pluginUtils.js @@ -0,0 +1,13 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import '../_version.js'; +export const pluginUtils = { + filter: (plugins, callbackName) => { + return plugins.filter((plugin) => callbackName in plugin); + }, +}; diff --git a/node_modules/workbox-core/utils/pluginUtils.mjs b/node_modules/workbox-core/utils/pluginUtils.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ceace2c3201ad9e2c51f5859fb7dfd81c286cfe2 --- /dev/null +++ b/node_modules/workbox-core/utils/pluginUtils.mjs @@ -0,0 +1 @@ +export * from './pluginUtils.js'; \ No newline at end of file diff --git a/node_modules/workbox-core/utils/welcome.d.ts b/node_modules/workbox-core/utils/welcome.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6886ce2389d4577da196a9cbd6dc44d787f81016 --- /dev/null +++ b/node_modules/workbox-core/utils/welcome.d.ts @@ -0,0 +1 @@ +import '../_version.js'; diff --git a/node_modules/workbox-core/utils/welcome.js b/node_modules/workbox-core/utils/welcome.js new file mode 100644 index 0000000000000000000000000000000000000000..8f65d4e85758f7c589363969ecf38911f944bf5f --- /dev/null +++ b/node_modules/workbox-core/utils/welcome.js @@ -0,0 +1,25 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { logger } from '../_private/logger.js'; +import '../_version.js'; +// A WorkboxCore instance must be exported before we can use the logger. +// This is so it can get the current log level. +if (process.env.NODE_ENV !== 'production') { + const padding = ' '; + logger.groupCollapsed('Welcome to Workbox!'); + logger.log(`You are currently using a development build. ` + + `By default this will switch to prod builds when not on localhost. ` + + `You can force this with workbox.setConfig({debug: true|false}).`); + logger.log(`📖 Read the guides and documentation\n` + + `${padding}https://developers.google.com/web/tools/workbox/`); + logger.log(`❓ Use the [workbox] tag on Stack Overflow to ask questions\n` + + `${padding}https://stackoverflow.com/questions/ask?tags=workbox`); + logger.log(`🐛 Found a bug? Report it on GitHub\n` + + `${padding}https://github.com/GoogleChrome/workbox/issues/new`); + logger.groupEnd(); +} diff --git a/node_modules/workbox-core/utils/welcome.mjs b/node_modules/workbox-core/utils/welcome.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c23bdfc0bf2e89d87921e1acebf9d72b36cc09ac --- /dev/null +++ b/node_modules/workbox-core/utils/welcome.mjs @@ -0,0 +1 @@ +export * from './welcome.js'; \ No newline at end of file diff --git a/node_modules/workbox-expiration/CacheExpiration.d.ts b/node_modules/workbox-expiration/CacheExpiration.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f066df5c0b84d9b61d293374f77333fe036780a8 --- /dev/null +++ b/node_modules/workbox-expiration/CacheExpiration.d.ts @@ -0,0 +1,66 @@ +import './_version.js'; +interface CacheExpirationConfig { + maxEntries?: number; + maxAgeSeconds?: number; + matchOptions?: CacheQueryOptions; +} +/** + * The `CacheExpiration` class allows you define an expiration and / or + * limit on the number of responses stored in a + * [`Cache`](https://developer.mozilla.org/en-US/docs/Web/API/Cache). + * + * @memberof workbox-expiration + */ +declare class CacheExpiration { + private _isRunning; + private _rerunRequested; + private readonly _maxEntries?; + private readonly _maxAgeSeconds?; + private readonly _matchOptions?; + private readonly _cacheName; + private readonly _timestampModel; + /** + * To construct a new CacheExpiration instance you must provide at least + * one of the `config` properties. + * + * @param {string} cacheName Name of the cache to apply restrictions to. + * @param {Object} config + * @param {number} [config.maxEntries] The maximum number of entries to cache. + * Entries used the least will be removed as the maximum is reached. + * @param {number} [config.maxAgeSeconds] The maximum age of an entry before + * it's treated as stale and removed. + * @param {Object} [config.matchOptions] The [`CacheQueryOptions`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete#Parameters) + * that will be used when calling `delete()` on the cache. + */ + constructor(cacheName: string, config?: CacheExpirationConfig); + /** + * Expires entries for the given cache and given criteria. + */ + expireEntries(): Promise; + /** + * Update the timestamp for the given URL. This ensures the when + * removing entries based on maximum entries, most recently used + * is accurate or when expiring, the timestamp is up-to-date. + * + * @param {string} url + */ + updateTimestamp(url: string): Promise; + /** + * Can be used to check if a URL has expired or not before it's used. + * + * This requires a look up from IndexedDB, so can be slow. + * + * Note: This method will not remove the cached entry, call + * `expireEntries()` to remove indexedDB and Cache entries. + * + * @param {string} url + * @return {boolean} + */ + isURLExpired(url: string): Promise; + /** + * Removes the IndexedDB object store used to keep track of cache expiration + * metadata. + */ + delete(): Promise; +} +export { CacheExpiration }; diff --git a/node_modules/workbox-expiration/CacheExpiration.js b/node_modules/workbox-expiration/CacheExpiration.js new file mode 100644 index 0000000000000000000000000000000000000000..45947959a96696f04f7256b7de65ab7e89fb38d1 --- /dev/null +++ b/node_modules/workbox-expiration/CacheExpiration.js @@ -0,0 +1,169 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { assert } from 'workbox-core/_private/assert.js'; +import { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js'; +import { logger } from 'workbox-core/_private/logger.js'; +import { WorkboxError } from 'workbox-core/_private/WorkboxError.js'; +import { CacheTimestampsModel } from './models/CacheTimestampsModel.js'; +import './_version.js'; +/** + * The `CacheExpiration` class allows you define an expiration and / or + * limit on the number of responses stored in a + * [`Cache`](https://developer.mozilla.org/en-US/docs/Web/API/Cache). + * + * @memberof workbox-expiration + */ +class CacheExpiration { + /** + * To construct a new CacheExpiration instance you must provide at least + * one of the `config` properties. + * + * @param {string} cacheName Name of the cache to apply restrictions to. + * @param {Object} config + * @param {number} [config.maxEntries] The maximum number of entries to cache. + * Entries used the least will be removed as the maximum is reached. + * @param {number} [config.maxAgeSeconds] The maximum age of an entry before + * it's treated as stale and removed. + * @param {Object} [config.matchOptions] The [`CacheQueryOptions`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete#Parameters) + * that will be used when calling `delete()` on the cache. + */ + constructor(cacheName, config = {}) { + this._isRunning = false; + this._rerunRequested = false; + if (process.env.NODE_ENV !== 'production') { + assert.isType(cacheName, 'string', { + moduleName: 'workbox-expiration', + className: 'CacheExpiration', + funcName: 'constructor', + paramName: 'cacheName', + }); + if (!(config.maxEntries || config.maxAgeSeconds)) { + throw new WorkboxError('max-entries-or-age-required', { + moduleName: 'workbox-expiration', + className: 'CacheExpiration', + funcName: 'constructor', + }); + } + if (config.maxEntries) { + assert.isType(config.maxEntries, 'number', { + moduleName: 'workbox-expiration', + className: 'CacheExpiration', + funcName: 'constructor', + paramName: 'config.maxEntries', + }); + } + if (config.maxAgeSeconds) { + assert.isType(config.maxAgeSeconds, 'number', { + moduleName: 'workbox-expiration', + className: 'CacheExpiration', + funcName: 'constructor', + paramName: 'config.maxAgeSeconds', + }); + } + } + this._maxEntries = config.maxEntries; + this._maxAgeSeconds = config.maxAgeSeconds; + this._matchOptions = config.matchOptions; + this._cacheName = cacheName; + this._timestampModel = new CacheTimestampsModel(cacheName); + } + /** + * Expires entries for the given cache and given criteria. + */ + async expireEntries() { + if (this._isRunning) { + this._rerunRequested = true; + return; + } + this._isRunning = true; + const minTimestamp = this._maxAgeSeconds + ? Date.now() - this._maxAgeSeconds * 1000 + : 0; + const urlsExpired = await this._timestampModel.expireEntries(minTimestamp, this._maxEntries); + // Delete URLs from the cache + const cache = await self.caches.open(this._cacheName); + for (const url of urlsExpired) { + await cache.delete(url, this._matchOptions); + } + if (process.env.NODE_ENV !== 'production') { + if (urlsExpired.length > 0) { + logger.groupCollapsed(`Expired ${urlsExpired.length} ` + + `${urlsExpired.length === 1 ? 'entry' : 'entries'} and removed ` + + `${urlsExpired.length === 1 ? 'it' : 'them'} from the ` + + `'${this._cacheName}' cache.`); + logger.log(`Expired the following ${urlsExpired.length === 1 ? 'URL' : 'URLs'}:`); + urlsExpired.forEach((url) => logger.log(` ${url}`)); + logger.groupEnd(); + } + else { + logger.debug(`Cache expiration ran and found no entries to remove.`); + } + } + this._isRunning = false; + if (this._rerunRequested) { + this._rerunRequested = false; + dontWaitFor(this.expireEntries()); + } + } + /** + * Update the timestamp for the given URL. This ensures the when + * removing entries based on maximum entries, most recently used + * is accurate or when expiring, the timestamp is up-to-date. + * + * @param {string} url + */ + async updateTimestamp(url) { + if (process.env.NODE_ENV !== 'production') { + assert.isType(url, 'string', { + moduleName: 'workbox-expiration', + className: 'CacheExpiration', + funcName: 'updateTimestamp', + paramName: 'url', + }); + } + await this._timestampModel.setTimestamp(url, Date.now()); + } + /** + * Can be used to check if a URL has expired or not before it's used. + * + * This requires a look up from IndexedDB, so can be slow. + * + * Note: This method will not remove the cached entry, call + * `expireEntries()` to remove indexedDB and Cache entries. + * + * @param {string} url + * @return {boolean} + */ + async isURLExpired(url) { + if (!this._maxAgeSeconds) { + if (process.env.NODE_ENV !== 'production') { + throw new WorkboxError(`expired-test-without-max-age`, { + methodName: 'isURLExpired', + paramName: 'maxAgeSeconds', + }); + } + return false; + } + else { + const timestamp = await this._timestampModel.getTimestamp(url); + const expireOlderThan = Date.now() - this._maxAgeSeconds * 1000; + return timestamp !== undefined ? timestamp < expireOlderThan : true; + } + } + /** + * Removes the IndexedDB object store used to keep track of cache expiration + * metadata. + */ + async delete() { + // Make sure we don't attempt another rerun if we're called in the middle of + // a cache expiration. + this._rerunRequested = false; + await this._timestampModel.expireEntries(Infinity); // Expires all. + } +} +export { CacheExpiration }; diff --git a/node_modules/workbox-expiration/CacheExpiration.mjs b/node_modules/workbox-expiration/CacheExpiration.mjs new file mode 100644 index 0000000000000000000000000000000000000000..528bff2c1b624395d772cfddd5e8e40f320cbb5a --- /dev/null +++ b/node_modules/workbox-expiration/CacheExpiration.mjs @@ -0,0 +1 @@ +export * from './CacheExpiration.js'; \ No newline at end of file diff --git a/node_modules/workbox-expiration/ExpirationPlugin.d.ts b/node_modules/workbox-expiration/ExpirationPlugin.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c307639d31b047951c57497b03fc11e992408bc --- /dev/null +++ b/node_modules/workbox-expiration/ExpirationPlugin.d.ts @@ -0,0 +1,122 @@ +import { WorkboxPlugin } from 'workbox-core/types.js'; +import './_version.js'; +export interface ExpirationPluginOptions { + maxEntries?: number; + maxAgeSeconds?: number; + matchOptions?: CacheQueryOptions; + purgeOnQuotaError?: boolean; +} +/** + * This plugin can be used in a `workbox-strategy` to regularly enforce a + * limit on the age and / or the number of cached requests. + * + * It can only be used with `workbox-strategy` instances that have a + * [custom `cacheName` property set](/web/tools/workbox/guides/configure-workbox#custom_cache_names_in_strategies). + * In other words, it can't be used to expire entries in strategy that uses the + * default runtime cache name. + * + * Whenever a cached response is used or updated, this plugin will look + * at the associated cache and remove any old or extra responses. + * + * When using `maxAgeSeconds`, responses may be used *once* after expiring + * because the expiration clean up will not have occurred until *after* the + * cached response has been used. If the response has a "Date" header, then + * a light weight expiration check is performed and the response will not be + * used immediately. + * + * When using `maxEntries`, the entry least-recently requested will be removed + * from the cache first. + * + * @memberof workbox-expiration + */ +declare class ExpirationPlugin implements WorkboxPlugin { + private readonly _config; + private readonly _maxAgeSeconds?; + private _cacheExpirations; + /** + * @param {ExpirationPluginOptions} config + * @param {number} [config.maxEntries] The maximum number of entries to cache. + * Entries used the least will be removed as the maximum is reached. + * @param {number} [config.maxAgeSeconds] The maximum age of an entry before + * it's treated as stale and removed. + * @param {Object} [config.matchOptions] The [`CacheQueryOptions`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete#Parameters) + * that will be used when calling `delete()` on the cache. + * @param {boolean} [config.purgeOnQuotaError] Whether to opt this cache in to + * automatic deletion if the available storage quota has been exceeded. + */ + constructor(config?: ExpirationPluginOptions); + /** + * A simple helper method to return a CacheExpiration instance for a given + * cache name. + * + * @param {string} cacheName + * @return {CacheExpiration} + * + * @private + */ + private _getCacheExpiration; + /** + * A "lifecycle" callback that will be triggered automatically by the + * `workbox-strategies` handlers when a `Response` is about to be returned + * from a [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache) to + * the handler. It allows the `Response` to be inspected for freshness and + * prevents it from being used if the `Response`'s `Date` header value is + * older than the configured `maxAgeSeconds`. + * + * @param {Object} options + * @param {string} options.cacheName Name of the cache the response is in. + * @param {Response} options.cachedResponse The `Response` object that's been + * read from a cache and whose freshness should be checked. + * @return {Response} Either the `cachedResponse`, if it's + * fresh, or `null` if the `Response` is older than `maxAgeSeconds`. + * + * @private + */ + cachedResponseWillBeUsed: WorkboxPlugin['cachedResponseWillBeUsed']; + /** + * @param {Response} cachedResponse + * @return {boolean} + * + * @private + */ + private _isResponseDateFresh; + /** + * This method will extract the data header and parse it into a useful + * value. + * + * @param {Response} cachedResponse + * @return {number|null} + * + * @private + */ + private _getDateHeaderTimestamp; + /** + * A "lifecycle" callback that will be triggered automatically by the + * `workbox-strategies` handlers when an entry is added to a cache. + * + * @param {Object} options + * @param {string} options.cacheName Name of the cache that was updated. + * @param {string} options.request The Request for the cached entry. + * + * @private + */ + cacheDidUpdate: WorkboxPlugin['cacheDidUpdate']; + /** + * This is a helper method that performs two operations: + * + * - Deletes *all* the underlying Cache instances associated with this plugin + * instance, by calling caches.delete() on your behalf. + * - Deletes the metadata from IndexedDB used to keep track of expiration + * details for each Cache instance. + * + * When using cache expiration, calling this method is preferable to calling + * `caches.delete()` directly, since this will ensure that the IndexedDB + * metadata is also cleanly removed and open IndexedDB instances are deleted. + * + * Note that if you're *not* using cache expiration for a given cache, calling + * `caches.delete()` and passing in the cache's name should be sufficient. + * There is no Workbox-specific method needed for cleanup in that case. + */ + deleteCacheAndMetadata(): Promise; +} +export { ExpirationPlugin }; diff --git a/node_modules/workbox-expiration/ExpirationPlugin.js b/node_modules/workbox-expiration/ExpirationPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..2d7a46e482679d03fd7d3421b7309c907493760f --- /dev/null +++ b/node_modules/workbox-expiration/ExpirationPlugin.js @@ -0,0 +1,254 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { assert } from 'workbox-core/_private/assert.js'; +import { cacheNames } from 'workbox-core/_private/cacheNames.js'; +import { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js'; +import { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js'; +import { logger } from 'workbox-core/_private/logger.js'; +import { registerQuotaErrorCallback } from 'workbox-core/registerQuotaErrorCallback.js'; +import { WorkboxError } from 'workbox-core/_private/WorkboxError.js'; +import { CacheExpiration } from './CacheExpiration.js'; +import './_version.js'; +/** + * This plugin can be used in a `workbox-strategy` to regularly enforce a + * limit on the age and / or the number of cached requests. + * + * It can only be used with `workbox-strategy` instances that have a + * [custom `cacheName` property set](/web/tools/workbox/guides/configure-workbox#custom_cache_names_in_strategies). + * In other words, it can't be used to expire entries in strategy that uses the + * default runtime cache name. + * + * Whenever a cached response is used or updated, this plugin will look + * at the associated cache and remove any old or extra responses. + * + * When using `maxAgeSeconds`, responses may be used *once* after expiring + * because the expiration clean up will not have occurred until *after* the + * cached response has been used. If the response has a "Date" header, then + * a light weight expiration check is performed and the response will not be + * used immediately. + * + * When using `maxEntries`, the entry least-recently requested will be removed + * from the cache first. + * + * @memberof workbox-expiration + */ +class ExpirationPlugin { + /** + * @param {ExpirationPluginOptions} config + * @param {number} [config.maxEntries] The maximum number of entries to cache. + * Entries used the least will be removed as the maximum is reached. + * @param {number} [config.maxAgeSeconds] The maximum age of an entry before + * it's treated as stale and removed. + * @param {Object} [config.matchOptions] The [`CacheQueryOptions`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete#Parameters) + * that will be used when calling `delete()` on the cache. + * @param {boolean} [config.purgeOnQuotaError] Whether to opt this cache in to + * automatic deletion if the available storage quota has been exceeded. + */ + constructor(config = {}) { + /** + * A "lifecycle" callback that will be triggered automatically by the + * `workbox-strategies` handlers when a `Response` is about to be returned + * from a [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache) to + * the handler. It allows the `Response` to be inspected for freshness and + * prevents it from being used if the `Response`'s `Date` header value is + * older than the configured `maxAgeSeconds`. + * + * @param {Object} options + * @param {string} options.cacheName Name of the cache the response is in. + * @param {Response} options.cachedResponse The `Response` object that's been + * read from a cache and whose freshness should be checked. + * @return {Response} Either the `cachedResponse`, if it's + * fresh, or `null` if the `Response` is older than `maxAgeSeconds`. + * + * @private + */ + this.cachedResponseWillBeUsed = async ({ event, request, cacheName, cachedResponse, }) => { + if (!cachedResponse) { + return null; + } + const isFresh = this._isResponseDateFresh(cachedResponse); + // Expire entries to ensure that even if the expiration date has + // expired, it'll only be used once. + const cacheExpiration = this._getCacheExpiration(cacheName); + dontWaitFor(cacheExpiration.expireEntries()); + // Update the metadata for the request URL to the current timestamp, + // but don't `await` it as we don't want to block the response. + const updateTimestampDone = cacheExpiration.updateTimestamp(request.url); + if (event) { + try { + event.waitUntil(updateTimestampDone); + } + catch (error) { + if (process.env.NODE_ENV !== 'production') { + // The event may not be a fetch event; only log the URL if it is. + if ('request' in event) { + logger.warn(`Unable to ensure service worker stays alive when ` + + `updating cache entry for ` + + `'${getFriendlyURL(event.request.url)}'.`); + } + } + } + } + return isFresh ? cachedResponse : null; + }; + /** + * A "lifecycle" callback that will be triggered automatically by the + * `workbox-strategies` handlers when an entry is added to a cache. + * + * @param {Object} options + * @param {string} options.cacheName Name of the cache that was updated. + * @param {string} options.request The Request for the cached entry. + * + * @private + */ + this.cacheDidUpdate = async ({ cacheName, request, }) => { + if (process.env.NODE_ENV !== 'production') { + assert.isType(cacheName, 'string', { + moduleName: 'workbox-expiration', + className: 'Plugin', + funcName: 'cacheDidUpdate', + paramName: 'cacheName', + }); + assert.isInstance(request, Request, { + moduleName: 'workbox-expiration', + className: 'Plugin', + funcName: 'cacheDidUpdate', + paramName: 'request', + }); + } + const cacheExpiration = this._getCacheExpiration(cacheName); + await cacheExpiration.updateTimestamp(request.url); + await cacheExpiration.expireEntries(); + }; + if (process.env.NODE_ENV !== 'production') { + if (!(config.maxEntries || config.maxAgeSeconds)) { + throw new WorkboxError('max-entries-or-age-required', { + moduleName: 'workbox-expiration', + className: 'Plugin', + funcName: 'constructor', + }); + } + if (config.maxEntries) { + assert.isType(config.maxEntries, 'number', { + moduleName: 'workbox-expiration', + className: 'Plugin', + funcName: 'constructor', + paramName: 'config.maxEntries', + }); + } + if (config.maxAgeSeconds) { + assert.isType(config.maxAgeSeconds, 'number', { + moduleName: 'workbox-expiration', + className: 'Plugin', + funcName: 'constructor', + paramName: 'config.maxAgeSeconds', + }); + } + } + this._config = config; + this._maxAgeSeconds = config.maxAgeSeconds; + this._cacheExpirations = new Map(); + if (config.purgeOnQuotaError) { + registerQuotaErrorCallback(() => this.deleteCacheAndMetadata()); + } + } + /** + * A simple helper method to return a CacheExpiration instance for a given + * cache name. + * + * @param {string} cacheName + * @return {CacheExpiration} + * + * @private + */ + _getCacheExpiration(cacheName) { + if (cacheName === cacheNames.getRuntimeName()) { + throw new WorkboxError('expire-custom-caches-only'); + } + let cacheExpiration = this._cacheExpirations.get(cacheName); + if (!cacheExpiration) { + cacheExpiration = new CacheExpiration(cacheName, this._config); + this._cacheExpirations.set(cacheName, cacheExpiration); + } + return cacheExpiration; + } + /** + * @param {Response} cachedResponse + * @return {boolean} + * + * @private + */ + _isResponseDateFresh(cachedResponse) { + if (!this._maxAgeSeconds) { + // We aren't expiring by age, so return true, it's fresh + return true; + } + // Check if the 'date' header will suffice a quick expiration check. + // See https://github.com/GoogleChromeLabs/sw-toolbox/issues/164 for + // discussion. + const dateHeaderTimestamp = this._getDateHeaderTimestamp(cachedResponse); + if (dateHeaderTimestamp === null) { + // Unable to parse date, so assume it's fresh. + return true; + } + // If we have a valid headerTime, then our response is fresh iff the + // headerTime plus maxAgeSeconds is greater than the current time. + const now = Date.now(); + return dateHeaderTimestamp >= now - this._maxAgeSeconds * 1000; + } + /** + * This method will extract the data header and parse it into a useful + * value. + * + * @param {Response} cachedResponse + * @return {number|null} + * + * @private + */ + _getDateHeaderTimestamp(cachedResponse) { + if (!cachedResponse.headers.has('date')) { + return null; + } + const dateHeader = cachedResponse.headers.get('date'); + const parsedDate = new Date(dateHeader); + const headerTime = parsedDate.getTime(); + // If the Date header was invalid for some reason, parsedDate.getTime() + // will return NaN. + if (isNaN(headerTime)) { + return null; + } + return headerTime; + } + /** + * This is a helper method that performs two operations: + * + * - Deletes *all* the underlying Cache instances associated with this plugin + * instance, by calling caches.delete() on your behalf. + * - Deletes the metadata from IndexedDB used to keep track of expiration + * details for each Cache instance. + * + * When using cache expiration, calling this method is preferable to calling + * `caches.delete()` directly, since this will ensure that the IndexedDB + * metadata is also cleanly removed and open IndexedDB instances are deleted. + * + * Note that if you're *not* using cache expiration for a given cache, calling + * `caches.delete()` and passing in the cache's name should be sufficient. + * There is no Workbox-specific method needed for cleanup in that case. + */ + async deleteCacheAndMetadata() { + // Do this one at a time instead of all at once via `Promise.all()` to + // reduce the chance of inconsistency if a promise rejects. + for (const [cacheName, cacheExpiration] of this._cacheExpirations) { + await self.caches.delete(cacheName); + await cacheExpiration.delete(); + } + // Reset this._cacheExpirations to its initial state. + this._cacheExpirations = new Map(); + } +} +export { ExpirationPlugin }; diff --git a/node_modules/workbox-expiration/ExpirationPlugin.mjs b/node_modules/workbox-expiration/ExpirationPlugin.mjs new file mode 100644 index 0000000000000000000000000000000000000000..505c404cf9d731b63bbe31b37925dc89637b2ce5 --- /dev/null +++ b/node_modules/workbox-expiration/ExpirationPlugin.mjs @@ -0,0 +1 @@ +export * from './ExpirationPlugin.js'; \ No newline at end of file diff --git a/node_modules/workbox-expiration/LICENSE b/node_modules/workbox-expiration/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..845b545fd0f5031a944cda8cf9018eb066500040 --- /dev/null +++ b/node_modules/workbox-expiration/LICENSE @@ -0,0 +1,19 @@ +Copyright 2018 Google LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/workbox-expiration/README.md b/node_modules/workbox-expiration/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9f3b1962771f4b7fc28fe5e256d5d7e57a4d26b8 --- /dev/null +++ b/node_modules/workbox-expiration/README.md @@ -0,0 +1 @@ +This module's documentation can be found at https://developers.google.com/web/tools/workbox/modules/workbox-expiration diff --git a/node_modules/workbox-expiration/_version.d.ts b/node_modules/workbox-expiration/_version.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/workbox-expiration/_version.js b/node_modules/workbox-expiration/_version.js new file mode 100644 index 0000000000000000000000000000000000000000..a223a66467ee7ddfb7d5b9d068a6a287ae21c655 --- /dev/null +++ b/node_modules/workbox-expiration/_version.js @@ -0,0 +1,6 @@ +"use strict"; +// @ts-ignore +try { + self['workbox:expiration:7.4.0'] && _(); +} +catch (e) { } diff --git a/node_modules/workbox-expiration/_version.mjs b/node_modules/workbox-expiration/_version.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f9d8bae4842f12230b5ccc58521a47a443c1ab6a --- /dev/null +++ b/node_modules/workbox-expiration/_version.mjs @@ -0,0 +1 @@ +try{self['workbox:expiration:7.4.1']&&_()}catch(e){}// eslint-disable-line \ No newline at end of file diff --git a/node_modules/workbox-expiration/build/workbox-expiration.dev.js b/node_modules/workbox-expiration/build/workbox-expiration.dev.js new file mode 100644 index 0000000000000000000000000000000000000000..bb392bd4f89a7eb62c985f572a1a71aa67b86bbd --- /dev/null +++ b/node_modules/workbox-expiration/build/workbox-expiration.dev.js @@ -0,0 +1,848 @@ +this.workbox = this.workbox || {}; +this.workbox.expiration = (function (exports, assert_js, dontWaitFor_js, logger_js, WorkboxError_js, cacheNames_js, getFriendlyURL_js, registerQuotaErrorCallback_js) { + 'use strict'; + + function _extends() { + return _extends = Object.assign ? Object.assign.bind() : function (n) { + for (var e = 1; e < arguments.length; e++) { + var t = arguments[e]; + for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); + } + return n; + }, _extends.apply(null, arguments); + } + + const instanceOfAny = (object, constructors) => constructors.some(c => object instanceof c); + let idbProxyableTypes; + let cursorAdvanceMethods; + // This is a function to prevent it throwing up in node environments. + function getIdbProxyableTypes() { + return idbProxyableTypes || (idbProxyableTypes = [IDBDatabase, IDBObjectStore, IDBIndex, IDBCursor, IDBTransaction]); + } + // This is a function to prevent it throwing up in node environments. + function getCursorAdvanceMethods() { + return cursorAdvanceMethods || (cursorAdvanceMethods = [IDBCursor.prototype.advance, IDBCursor.prototype.continue, IDBCursor.prototype.continuePrimaryKey]); + } + const cursorRequestMap = new WeakMap(); + const transactionDoneMap = new WeakMap(); + const transactionStoreNamesMap = new WeakMap(); + const transformCache = new WeakMap(); + const reverseTransformCache = new WeakMap(); + function promisifyRequest(request) { + const promise = new Promise((resolve, reject) => { + const unlisten = () => { + request.removeEventListener('success', success); + request.removeEventListener('error', error); + }; + const success = () => { + resolve(wrap(request.result)); + unlisten(); + }; + const error = () => { + reject(request.error); + unlisten(); + }; + request.addEventListener('success', success); + request.addEventListener('error', error); + }); + promise.then(value => { + // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval + // (see wrapFunction). + if (value instanceof IDBCursor) { + cursorRequestMap.set(value, request); + } + // Catching to avoid "Uncaught Promise exceptions" + }).catch(() => {}); + // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This + // is because we create many promises from a single IDBRequest. + reverseTransformCache.set(promise, request); + return promise; + } + function cacheDonePromiseForTransaction(tx) { + // Early bail if we've already created a done promise for this transaction. + if (transactionDoneMap.has(tx)) return; + const done = new Promise((resolve, reject) => { + const unlisten = () => { + tx.removeEventListener('complete', complete); + tx.removeEventListener('error', error); + tx.removeEventListener('abort', error); + }; + const complete = () => { + resolve(); + unlisten(); + }; + const error = () => { + reject(tx.error || new DOMException('AbortError', 'AbortError')); + unlisten(); + }; + tx.addEventListener('complete', complete); + tx.addEventListener('error', error); + tx.addEventListener('abort', error); + }); + // Cache it for later retrieval. + transactionDoneMap.set(tx, done); + } + let idbProxyTraps = { + get(target, prop, receiver) { + if (target instanceof IDBTransaction) { + // Special handling for transaction.done. + if (prop === 'done') return transactionDoneMap.get(target); + // Polyfill for objectStoreNames because of Edge. + if (prop === 'objectStoreNames') { + return target.objectStoreNames || transactionStoreNamesMap.get(target); + } + // Make tx.store return the only store in the transaction, or undefined if there are many. + if (prop === 'store') { + return receiver.objectStoreNames[1] ? undefined : receiver.objectStore(receiver.objectStoreNames[0]); + } + } + // Else transform whatever we get back. + return wrap(target[prop]); + }, + set(target, prop, value) { + target[prop] = value; + return true; + }, + has(target, prop) { + if (target instanceof IDBTransaction && (prop === 'done' || prop === 'store')) { + return true; + } + return prop in target; + } + }; + function replaceTraps(callback) { + idbProxyTraps = callback(idbProxyTraps); + } + function wrapFunction(func) { + // Due to expected object equality (which is enforced by the caching in `wrap`), we + // only create one new func per func. + // Edge doesn't support objectStoreNames (booo), so we polyfill it here. + if (func === IDBDatabase.prototype.transaction && !('objectStoreNames' in IDBTransaction.prototype)) { + return function (storeNames, ...args) { + const tx = func.call(unwrap(this), storeNames, ...args); + transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]); + return wrap(tx); + }; + } + // Cursor methods are special, as the behaviour is a little more different to standard IDB. In + // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the + // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense + // with real promises, so each advance methods returns a new promise for the cursor object, or + // undefined if the end of the cursor has been reached. + if (getCursorAdvanceMethods().includes(func)) { + return function (...args) { + // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use + // the original object. + func.apply(unwrap(this), args); + return wrap(cursorRequestMap.get(this)); + }; + } + return function (...args) { + // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use + // the original object. + return wrap(func.apply(unwrap(this), args)); + }; + } + function transformCachableValue(value) { + if (typeof value === 'function') return wrapFunction(value); + // This doesn't return, it just creates a 'done' promise for the transaction, + // which is later returned for transaction.done (see idbObjectHandler). + if (value instanceof IDBTransaction) cacheDonePromiseForTransaction(value); + if (instanceOfAny(value, getIdbProxyableTypes())) return new Proxy(value, idbProxyTraps); + // Return the same value back if we're not going to transform it. + return value; + } + function wrap(value) { + // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because + // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached. + if (value instanceof IDBRequest) return promisifyRequest(value); + // If we've already transformed this value before, reuse the transformed value. + // This is faster, but it also provides object equality. + if (transformCache.has(value)) return transformCache.get(value); + const newValue = transformCachableValue(value); + // Not all types are transformed. + // These may be primitive types, so they can't be WeakMap keys. + if (newValue !== value) { + transformCache.set(value, newValue); + reverseTransformCache.set(newValue, value); + } + return newValue; + } + const unwrap = value => reverseTransformCache.get(value); + + /** + * Open a database. + * + * @param name Name of the database. + * @param version Schema version. + * @param callbacks Additional callbacks. + */ + function openDB(name, version, { + blocked, + upgrade, + blocking, + terminated + } = {}) { + const request = indexedDB.open(name, version); + const openPromise = wrap(request); + if (upgrade) { + request.addEventListener('upgradeneeded', event => { + upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction)); + }); + } + if (blocked) request.addEventListener('blocked', () => blocked()); + openPromise.then(db => { + if (terminated) db.addEventListener('close', () => terminated()); + if (blocking) db.addEventListener('versionchange', () => blocking()); + }).catch(() => {}); + return openPromise; + } + /** + * Delete a database. + * + * @param name Name of the database. + */ + function deleteDB(name, { + blocked + } = {}) { + const request = indexedDB.deleteDatabase(name); + if (blocked) request.addEventListener('blocked', () => blocked()); + return wrap(request).then(() => undefined); + } + const readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count']; + const writeMethods = ['put', 'add', 'delete', 'clear']; + const cachedMethods = new Map(); + function getMethod(target, prop) { + if (!(target instanceof IDBDatabase && !(prop in target) && typeof prop === 'string')) { + return; + } + if (cachedMethods.get(prop)) return cachedMethods.get(prop); + const targetFuncName = prop.replace(/FromIndex$/, ''); + const useIndex = prop !== targetFuncName; + const isWrite = writeMethods.includes(targetFuncName); + if ( + // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge. + !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) || !(isWrite || readMethods.includes(targetFuncName))) { + return; + } + const method = async function (storeName, ...args) { + // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :( + const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly'); + let target = tx.store; + if (useIndex) target = target.index(args.shift()); + // Must reject if op rejects. + // If it's a write operation, must reject if tx.done rejects. + // Must reject with op rejection first. + // Must resolve with op value. + // Must handle both promises (no unhandled rejections) + return (await Promise.all([target[targetFuncName](...args), isWrite && tx.done]))[0]; + }; + cachedMethods.set(prop, method); + return method; + } + replaceTraps(oldTraps => _extends({}, oldTraps, { + get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver), + has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop) + })); + + // @ts-ignore + try { + self['workbox:expiration:7.4.0'] && _(); + } catch (e) {} + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + const DB_NAME = 'workbox-expiration'; + const CACHE_OBJECT_STORE = 'cache-entries'; + const normalizeURL = unNormalizedUrl => { + const url = new URL(unNormalizedUrl, location.href); + url.hash = ''; + return url.href; + }; + /** + * Returns the timestamp model. + * + * @private + */ + class CacheTimestampsModel { + /** + * + * @param {string} cacheName + * + * @private + */ + constructor(cacheName) { + this._db = null; + this._cacheName = cacheName; + } + /** + * Performs an upgrade of indexedDB. + * + * @param {IDBPDatabase} db + * + * @private + */ + _upgradeDb(db) { + // TODO(philipwalton): EdgeHTML doesn't support arrays as a keyPath, so we + // have to use the `id` keyPath here and create our own values (a + // concatenation of `url + cacheName`) instead of simply using + // `keyPath: ['url', 'cacheName']`, which is supported in other browsers. + const objStore = db.createObjectStore(CACHE_OBJECT_STORE, { + keyPath: 'id' + }); + // TODO(philipwalton): once we don't have to support EdgeHTML, we can + // create a single index with the keyPath `['cacheName', 'timestamp']` + // instead of doing both these indexes. + objStore.createIndex('cacheName', 'cacheName', { + unique: false + }); + objStore.createIndex('timestamp', 'timestamp', { + unique: false + }); + } + /** + * Performs an upgrade of indexedDB and deletes deprecated DBs. + * + * @param {IDBPDatabase} db + * + * @private + */ + _upgradeDbAndDeleteOldDbs(db) { + this._upgradeDb(db); + if (this._cacheName) { + void deleteDB(this._cacheName); + } + } + /** + * @param {string} url + * @param {number} timestamp + * + * @private + */ + async setTimestamp(url, timestamp) { + url = normalizeURL(url); + const entry = { + url, + timestamp, + cacheName: this._cacheName, + // Creating an ID from the URL and cache name won't be necessary once + // Edge switches to Chromium and all browsers we support work with + // array keyPaths. + id: this._getId(url) + }; + const db = await this.getDb(); + const tx = db.transaction(CACHE_OBJECT_STORE, 'readwrite', { + durability: 'relaxed' + }); + await tx.store.put(entry); + await tx.done; + } + /** + * Returns the timestamp stored for a given URL. + * + * @param {string} url + * @return {number | undefined} + * + * @private + */ + async getTimestamp(url) { + const db = await this.getDb(); + const entry = await db.get(CACHE_OBJECT_STORE, this._getId(url)); + return entry === null || entry === void 0 ? void 0 : entry.timestamp; + } + /** + * Iterates through all the entries in the object store (from newest to + * oldest) and removes entries once either `maxCount` is reached or the + * entry's timestamp is less than `minTimestamp`. + * + * @param {number} minTimestamp + * @param {number} maxCount + * @return {Array} + * + * @private + */ + async expireEntries(minTimestamp, maxCount) { + const db = await this.getDb(); + let cursor = await db.transaction(CACHE_OBJECT_STORE).store.index('timestamp').openCursor(null, 'prev'); + const entriesToDelete = []; + let entriesNotDeletedCount = 0; + while (cursor) { + const result = cursor.value; + // TODO(philipwalton): once we can use a multi-key index, we + // won't have to check `cacheName` here. + if (result.cacheName === this._cacheName) { + // Delete an entry if it's older than the max age or + // if we already have the max number allowed. + if (minTimestamp && result.timestamp < minTimestamp || maxCount && entriesNotDeletedCount >= maxCount) { + // TODO(philipwalton): we should be able to delete the + // entry right here, but doing so causes an iteration + // bug in Safari stable (fixed in TP). Instead we can + // store the keys of the entries to delete, and then + // delete the separate transactions. + // https://github.com/GoogleChrome/workbox/issues/1978 + // cursor.delete(); + // We only need to return the URL, not the whole entry. + entriesToDelete.push(cursor.value); + } else { + entriesNotDeletedCount++; + } + } + cursor = await cursor.continue(); + } + // TODO(philipwalton): once the Safari bug in the following issue is fixed, + // we should be able to remove this loop and do the entry deletion in the + // cursor loop above: + // https://github.com/GoogleChrome/workbox/issues/1978 + const urlsDeleted = []; + for (const entry of entriesToDelete) { + await db.delete(CACHE_OBJECT_STORE, entry.id); + urlsDeleted.push(entry.url); + } + return urlsDeleted; + } + /** + * Takes a URL and returns an ID that will be unique in the object store. + * + * @param {string} url + * @return {string} + * + * @private + */ + _getId(url) { + // Creating an ID from the URL and cache name won't be necessary once + // Edge switches to Chromium and all browsers we support work with + // array keyPaths. + return this._cacheName + '|' + normalizeURL(url); + } + /** + * Returns an open connection to the database. + * + * @private + */ + async getDb() { + if (!this._db) { + this._db = await openDB(DB_NAME, 1, { + upgrade: this._upgradeDbAndDeleteOldDbs.bind(this) + }); + } + return this._db; + } + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * The `CacheExpiration` class allows you define an expiration and / or + * limit on the number of responses stored in a + * [`Cache`](https://developer.mozilla.org/en-US/docs/Web/API/Cache). + * + * @memberof workbox-expiration + */ + class CacheExpiration { + /** + * To construct a new CacheExpiration instance you must provide at least + * one of the `config` properties. + * + * @param {string} cacheName Name of the cache to apply restrictions to. + * @param {Object} config + * @param {number} [config.maxEntries] The maximum number of entries to cache. + * Entries used the least will be removed as the maximum is reached. + * @param {number} [config.maxAgeSeconds] The maximum age of an entry before + * it's treated as stale and removed. + * @param {Object} [config.matchOptions] The [`CacheQueryOptions`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete#Parameters) + * that will be used when calling `delete()` on the cache. + */ + constructor(cacheName, config = {}) { + this._isRunning = false; + this._rerunRequested = false; + { + assert_js.assert.isType(cacheName, 'string', { + moduleName: 'workbox-expiration', + className: 'CacheExpiration', + funcName: 'constructor', + paramName: 'cacheName' + }); + if (!(config.maxEntries || config.maxAgeSeconds)) { + throw new WorkboxError_js.WorkboxError('max-entries-or-age-required', { + moduleName: 'workbox-expiration', + className: 'CacheExpiration', + funcName: 'constructor' + }); + } + if (config.maxEntries) { + assert_js.assert.isType(config.maxEntries, 'number', { + moduleName: 'workbox-expiration', + className: 'CacheExpiration', + funcName: 'constructor', + paramName: 'config.maxEntries' + }); + } + if (config.maxAgeSeconds) { + assert_js.assert.isType(config.maxAgeSeconds, 'number', { + moduleName: 'workbox-expiration', + className: 'CacheExpiration', + funcName: 'constructor', + paramName: 'config.maxAgeSeconds' + }); + } + } + this._maxEntries = config.maxEntries; + this._maxAgeSeconds = config.maxAgeSeconds; + this._matchOptions = config.matchOptions; + this._cacheName = cacheName; + this._timestampModel = new CacheTimestampsModel(cacheName); + } + /** + * Expires entries for the given cache and given criteria. + */ + async expireEntries() { + if (this._isRunning) { + this._rerunRequested = true; + return; + } + this._isRunning = true; + const minTimestamp = this._maxAgeSeconds ? Date.now() - this._maxAgeSeconds * 1000 : 0; + const urlsExpired = await this._timestampModel.expireEntries(minTimestamp, this._maxEntries); + // Delete URLs from the cache + const cache = await self.caches.open(this._cacheName); + for (const url of urlsExpired) { + await cache.delete(url, this._matchOptions); + } + { + if (urlsExpired.length > 0) { + logger_js.logger.groupCollapsed(`Expired ${urlsExpired.length} ` + `${urlsExpired.length === 1 ? 'entry' : 'entries'} and removed ` + `${urlsExpired.length === 1 ? 'it' : 'them'} from the ` + `'${this._cacheName}' cache.`); + logger_js.logger.log(`Expired the following ${urlsExpired.length === 1 ? 'URL' : 'URLs'}:`); + urlsExpired.forEach(url => logger_js.logger.log(` ${url}`)); + logger_js.logger.groupEnd(); + } else { + logger_js.logger.debug(`Cache expiration ran and found no entries to remove.`); + } + } + this._isRunning = false; + if (this._rerunRequested) { + this._rerunRequested = false; + dontWaitFor_js.dontWaitFor(this.expireEntries()); + } + } + /** + * Update the timestamp for the given URL. This ensures the when + * removing entries based on maximum entries, most recently used + * is accurate or when expiring, the timestamp is up-to-date. + * + * @param {string} url + */ + async updateTimestamp(url) { + { + assert_js.assert.isType(url, 'string', { + moduleName: 'workbox-expiration', + className: 'CacheExpiration', + funcName: 'updateTimestamp', + paramName: 'url' + }); + } + await this._timestampModel.setTimestamp(url, Date.now()); + } + /** + * Can be used to check if a URL has expired or not before it's used. + * + * This requires a look up from IndexedDB, so can be slow. + * + * Note: This method will not remove the cached entry, call + * `expireEntries()` to remove indexedDB and Cache entries. + * + * @param {string} url + * @return {boolean} + */ + async isURLExpired(url) { + if (!this._maxAgeSeconds) { + { + throw new WorkboxError_js.WorkboxError(`expired-test-without-max-age`, { + methodName: 'isURLExpired', + paramName: 'maxAgeSeconds' + }); + } + } else { + const timestamp = await this._timestampModel.getTimestamp(url); + const expireOlderThan = Date.now() - this._maxAgeSeconds * 1000; + return timestamp !== undefined ? timestamp < expireOlderThan : true; + } + } + /** + * Removes the IndexedDB object store used to keep track of cache expiration + * metadata. + */ + async delete() { + // Make sure we don't attempt another rerun if we're called in the middle of + // a cache expiration. + this._rerunRequested = false; + await this._timestampModel.expireEntries(Infinity); // Expires all. + } + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * This plugin can be used in a `workbox-strategy` to regularly enforce a + * limit on the age and / or the number of cached requests. + * + * It can only be used with `workbox-strategy` instances that have a + * [custom `cacheName` property set](/web/tools/workbox/guides/configure-workbox#custom_cache_names_in_strategies). + * In other words, it can't be used to expire entries in strategy that uses the + * default runtime cache name. + * + * Whenever a cached response is used or updated, this plugin will look + * at the associated cache and remove any old or extra responses. + * + * When using `maxAgeSeconds`, responses may be used *once* after expiring + * because the expiration clean up will not have occurred until *after* the + * cached response has been used. If the response has a "Date" header, then + * a light weight expiration check is performed and the response will not be + * used immediately. + * + * When using `maxEntries`, the entry least-recently requested will be removed + * from the cache first. + * + * @memberof workbox-expiration + */ + class ExpirationPlugin { + /** + * @param {ExpirationPluginOptions} config + * @param {number} [config.maxEntries] The maximum number of entries to cache. + * Entries used the least will be removed as the maximum is reached. + * @param {number} [config.maxAgeSeconds] The maximum age of an entry before + * it's treated as stale and removed. + * @param {Object} [config.matchOptions] The [`CacheQueryOptions`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete#Parameters) + * that will be used when calling `delete()` on the cache. + * @param {boolean} [config.purgeOnQuotaError] Whether to opt this cache in to + * automatic deletion if the available storage quota has been exceeded. + */ + constructor(config = {}) { + /** + * A "lifecycle" callback that will be triggered automatically by the + * `workbox-strategies` handlers when a `Response` is about to be returned + * from a [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache) to + * the handler. It allows the `Response` to be inspected for freshness and + * prevents it from being used if the `Response`'s `Date` header value is + * older than the configured `maxAgeSeconds`. + * + * @param {Object} options + * @param {string} options.cacheName Name of the cache the response is in. + * @param {Response} options.cachedResponse The `Response` object that's been + * read from a cache and whose freshness should be checked. + * @return {Response} Either the `cachedResponse`, if it's + * fresh, or `null` if the `Response` is older than `maxAgeSeconds`. + * + * @private + */ + this.cachedResponseWillBeUsed = async ({ + event, + request, + cacheName, + cachedResponse + }) => { + if (!cachedResponse) { + return null; + } + const isFresh = this._isResponseDateFresh(cachedResponse); + // Expire entries to ensure that even if the expiration date has + // expired, it'll only be used once. + const cacheExpiration = this._getCacheExpiration(cacheName); + dontWaitFor_js.dontWaitFor(cacheExpiration.expireEntries()); + // Update the metadata for the request URL to the current timestamp, + // but don't `await` it as we don't want to block the response. + const updateTimestampDone = cacheExpiration.updateTimestamp(request.url); + if (event) { + try { + event.waitUntil(updateTimestampDone); + } catch (error) { + { + // The event may not be a fetch event; only log the URL if it is. + if ('request' in event) { + logger_js.logger.warn(`Unable to ensure service worker stays alive when ` + `updating cache entry for ` + `'${getFriendlyURL_js.getFriendlyURL(event.request.url)}'.`); + } + } + } + } + return isFresh ? cachedResponse : null; + }; + /** + * A "lifecycle" callback that will be triggered automatically by the + * `workbox-strategies` handlers when an entry is added to a cache. + * + * @param {Object} options + * @param {string} options.cacheName Name of the cache that was updated. + * @param {string} options.request The Request for the cached entry. + * + * @private + */ + this.cacheDidUpdate = async ({ + cacheName, + request + }) => { + { + assert_js.assert.isType(cacheName, 'string', { + moduleName: 'workbox-expiration', + className: 'Plugin', + funcName: 'cacheDidUpdate', + paramName: 'cacheName' + }); + assert_js.assert.isInstance(request, Request, { + moduleName: 'workbox-expiration', + className: 'Plugin', + funcName: 'cacheDidUpdate', + paramName: 'request' + }); + } + const cacheExpiration = this._getCacheExpiration(cacheName); + await cacheExpiration.updateTimestamp(request.url); + await cacheExpiration.expireEntries(); + }; + { + if (!(config.maxEntries || config.maxAgeSeconds)) { + throw new WorkboxError_js.WorkboxError('max-entries-or-age-required', { + moduleName: 'workbox-expiration', + className: 'Plugin', + funcName: 'constructor' + }); + } + if (config.maxEntries) { + assert_js.assert.isType(config.maxEntries, 'number', { + moduleName: 'workbox-expiration', + className: 'Plugin', + funcName: 'constructor', + paramName: 'config.maxEntries' + }); + } + if (config.maxAgeSeconds) { + assert_js.assert.isType(config.maxAgeSeconds, 'number', { + moduleName: 'workbox-expiration', + className: 'Plugin', + funcName: 'constructor', + paramName: 'config.maxAgeSeconds' + }); + } + } + this._config = config; + this._maxAgeSeconds = config.maxAgeSeconds; + this._cacheExpirations = new Map(); + if (config.purgeOnQuotaError) { + registerQuotaErrorCallback_js.registerQuotaErrorCallback(() => this.deleteCacheAndMetadata()); + } + } + /** + * A simple helper method to return a CacheExpiration instance for a given + * cache name. + * + * @param {string} cacheName + * @return {CacheExpiration} + * + * @private + */ + _getCacheExpiration(cacheName) { + if (cacheName === cacheNames_js.cacheNames.getRuntimeName()) { + throw new WorkboxError_js.WorkboxError('expire-custom-caches-only'); + } + let cacheExpiration = this._cacheExpirations.get(cacheName); + if (!cacheExpiration) { + cacheExpiration = new CacheExpiration(cacheName, this._config); + this._cacheExpirations.set(cacheName, cacheExpiration); + } + return cacheExpiration; + } + /** + * @param {Response} cachedResponse + * @return {boolean} + * + * @private + */ + _isResponseDateFresh(cachedResponse) { + if (!this._maxAgeSeconds) { + // We aren't expiring by age, so return true, it's fresh + return true; + } + // Check if the 'date' header will suffice a quick expiration check. + // See https://github.com/GoogleChromeLabs/sw-toolbox/issues/164 for + // discussion. + const dateHeaderTimestamp = this._getDateHeaderTimestamp(cachedResponse); + if (dateHeaderTimestamp === null) { + // Unable to parse date, so assume it's fresh. + return true; + } + // If we have a valid headerTime, then our response is fresh iff the + // headerTime plus maxAgeSeconds is greater than the current time. + const now = Date.now(); + return dateHeaderTimestamp >= now - this._maxAgeSeconds * 1000; + } + /** + * This method will extract the data header and parse it into a useful + * value. + * + * @param {Response} cachedResponse + * @return {number|null} + * + * @private + */ + _getDateHeaderTimestamp(cachedResponse) { + if (!cachedResponse.headers.has('date')) { + return null; + } + const dateHeader = cachedResponse.headers.get('date'); + const parsedDate = new Date(dateHeader); + const headerTime = parsedDate.getTime(); + // If the Date header was invalid for some reason, parsedDate.getTime() + // will return NaN. + if (isNaN(headerTime)) { + return null; + } + return headerTime; + } + /** + * This is a helper method that performs two operations: + * + * - Deletes *all* the underlying Cache instances associated with this plugin + * instance, by calling caches.delete() on your behalf. + * - Deletes the metadata from IndexedDB used to keep track of expiration + * details for each Cache instance. + * + * When using cache expiration, calling this method is preferable to calling + * `caches.delete()` directly, since this will ensure that the IndexedDB + * metadata is also cleanly removed and open IndexedDB instances are deleted. + * + * Note that if you're *not* using cache expiration for a given cache, calling + * `caches.delete()` and passing in the cache's name should be sufficient. + * There is no Workbox-specific method needed for cleanup in that case. + */ + async deleteCacheAndMetadata() { + // Do this one at a time instead of all at once via `Promise.all()` to + // reduce the chance of inconsistency if a promise rejects. + for (const [cacheName, cacheExpiration] of this._cacheExpirations) { + await self.caches.delete(cacheName); + await cacheExpiration.delete(); + } + // Reset this._cacheExpirations to its initial state. + this._cacheExpirations = new Map(); + } + } + + exports.CacheExpiration = CacheExpiration; + exports.ExpirationPlugin = ExpirationPlugin; + + return exports; + +})({}, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core); +//# sourceMappingURL=workbox-expiration.dev.js.map diff --git a/node_modules/workbox-expiration/build/workbox-expiration.dev.js.map b/node_modules/workbox-expiration/build/workbox-expiration.dev.js.map new file mode 100644 index 0000000000000000000000000000000000000000..36795d2103c550b2acf607156a042b6e6d1e51ef --- /dev/null +++ b/node_modules/workbox-expiration/build/workbox-expiration.dev.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-expiration.dev.js","sources":["../node_modules/idb/build/wrap-idb-value.js","../node_modules/idb/build/index.js","../_version.js","../models/CacheTimestampsModel.js","../CacheExpiration.js","../ExpirationPlugin.js"],"sourcesContent":["const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n promise\n .then((value) => {\n // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n // (see wrapFunction).\n if (value instanceof IDBCursor) {\n cursorRequestMap.set(value, request);\n }\n // Catching to avoid \"Uncaught Promise exceptions\"\n })\n .catch(() => { });\n // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Polyfill for objectStoreNames because of Edge.\n if (prop === 'objectStoreNames') {\n return target.objectStoreNames || transactionStoreNamesMap.get(target);\n }\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n if (func === IDBDatabase.prototype.transaction &&\n !('objectStoreNames' in IDBTransaction.prototype)) {\n return function (storeNames, ...args) {\n const tx = func.call(unwrap(this), storeNames, ...args);\n transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n return wrap(tx);\n };\n }\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(cursorRequestMap.get(this));\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n","import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction));\n });\n }\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking)\n db.addEventListener('versionchange', () => blocking());\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n","\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:expiration:7.4.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 { openDB, deleteDB } from 'idb';\nimport '../_version.js';\nconst DB_NAME = 'workbox-expiration';\nconst CACHE_OBJECT_STORE = 'cache-entries';\nconst normalizeURL = (unNormalizedUrl) => {\n const url = new URL(unNormalizedUrl, location.href);\n url.hash = '';\n return url.href;\n};\n/**\n * Returns the timestamp model.\n *\n * @private\n */\nclass CacheTimestampsModel {\n /**\n *\n * @param {string} cacheName\n *\n * @private\n */\n constructor(cacheName) {\n this._db = null;\n this._cacheName = cacheName;\n }\n /**\n * Performs an upgrade of indexedDB.\n *\n * @param {IDBPDatabase} db\n *\n * @private\n */\n _upgradeDb(db) {\n // TODO(philipwalton): EdgeHTML doesn't support arrays as a keyPath, so we\n // have to use the `id` keyPath here and create our own values (a\n // concatenation of `url + cacheName`) instead of simply using\n // `keyPath: ['url', 'cacheName']`, which is supported in other browsers.\n const objStore = db.createObjectStore(CACHE_OBJECT_STORE, { keyPath: 'id' });\n // TODO(philipwalton): once we don't have to support EdgeHTML, we can\n // create a single index with the keyPath `['cacheName', 'timestamp']`\n // instead of doing both these indexes.\n objStore.createIndex('cacheName', 'cacheName', { unique: false });\n objStore.createIndex('timestamp', 'timestamp', { unique: false });\n }\n /**\n * Performs an upgrade of indexedDB and deletes deprecated DBs.\n *\n * @param {IDBPDatabase} db\n *\n * @private\n */\n _upgradeDbAndDeleteOldDbs(db) {\n this._upgradeDb(db);\n if (this._cacheName) {\n void deleteDB(this._cacheName);\n }\n }\n /**\n * @param {string} url\n * @param {number} timestamp\n *\n * @private\n */\n async setTimestamp(url, timestamp) {\n url = normalizeURL(url);\n const entry = {\n url,\n timestamp,\n cacheName: this._cacheName,\n // Creating an ID from the URL and cache name won't be necessary once\n // Edge switches to Chromium and all browsers we support work with\n // array keyPaths.\n id: this._getId(url),\n };\n const db = await this.getDb();\n const tx = db.transaction(CACHE_OBJECT_STORE, 'readwrite', {\n durability: 'relaxed',\n });\n await tx.store.put(entry);\n await tx.done;\n }\n /**\n * Returns the timestamp stored for a given URL.\n *\n * @param {string} url\n * @return {number | undefined}\n *\n * @private\n */\n async getTimestamp(url) {\n const db = await this.getDb();\n const entry = await db.get(CACHE_OBJECT_STORE, this._getId(url));\n return entry === null || entry === void 0 ? void 0 : entry.timestamp;\n }\n /**\n * Iterates through all the entries in the object store (from newest to\n * oldest) and removes entries once either `maxCount` is reached or the\n * entry's timestamp is less than `minTimestamp`.\n *\n * @param {number} minTimestamp\n * @param {number} maxCount\n * @return {Array}\n *\n * @private\n */\n async expireEntries(minTimestamp, maxCount) {\n const db = await this.getDb();\n let cursor = await db\n .transaction(CACHE_OBJECT_STORE)\n .store.index('timestamp')\n .openCursor(null, 'prev');\n const entriesToDelete = [];\n let entriesNotDeletedCount = 0;\n while (cursor) {\n const result = cursor.value;\n // TODO(philipwalton): once we can use a multi-key index, we\n // won't have to check `cacheName` here.\n if (result.cacheName === this._cacheName) {\n // Delete an entry if it's older than the max age or\n // if we already have the max number allowed.\n if ((minTimestamp && result.timestamp < minTimestamp) ||\n (maxCount && entriesNotDeletedCount >= maxCount)) {\n // TODO(philipwalton): we should be able to delete the\n // entry right here, but doing so causes an iteration\n // bug in Safari stable (fixed in TP). Instead we can\n // store the keys of the entries to delete, and then\n // delete the separate transactions.\n // https://github.com/GoogleChrome/workbox/issues/1978\n // cursor.delete();\n // We only need to return the URL, not the whole entry.\n entriesToDelete.push(cursor.value);\n }\n else {\n entriesNotDeletedCount++;\n }\n }\n cursor = await cursor.continue();\n }\n // TODO(philipwalton): once the Safari bug in the following issue is fixed,\n // we should be able to remove this loop and do the entry deletion in the\n // cursor loop above:\n // https://github.com/GoogleChrome/workbox/issues/1978\n const urlsDeleted = [];\n for (const entry of entriesToDelete) {\n await db.delete(CACHE_OBJECT_STORE, entry.id);\n urlsDeleted.push(entry.url);\n }\n return urlsDeleted;\n }\n /**\n * Takes a URL and returns an ID that will be unique in the object store.\n *\n * @param {string} url\n * @return {string}\n *\n * @private\n */\n _getId(url) {\n // Creating an ID from the URL and cache name won't be necessary once\n // Edge switches to Chromium and all browsers we support work with\n // array keyPaths.\n return this._cacheName + '|' + normalizeURL(url);\n }\n /**\n * Returns an open connection to the database.\n *\n * @private\n */\n async getDb() {\n if (!this._db) {\n this._db = await openDB(DB_NAME, 1, {\n upgrade: this._upgradeDbAndDeleteOldDbs.bind(this),\n });\n }\n return this._db;\n }\n}\nexport { CacheTimestampsModel };\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 { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { CacheTimestampsModel } from './models/CacheTimestampsModel.js';\nimport './_version.js';\n/**\n * The `CacheExpiration` class allows you define an expiration and / or\n * limit on the number of responses stored in a\n * [`Cache`](https://developer.mozilla.org/en-US/docs/Web/API/Cache).\n *\n * @memberof workbox-expiration\n */\nclass CacheExpiration {\n /**\n * To construct a new CacheExpiration instance you must provide at least\n * one of the `config` properties.\n *\n * @param {string} cacheName Name of the cache to apply restrictions to.\n * @param {Object} config\n * @param {number} [config.maxEntries] The maximum number of entries to cache.\n * Entries used the least will be removed as the maximum is reached.\n * @param {number} [config.maxAgeSeconds] The maximum age of an entry before\n * it's treated as stale and removed.\n * @param {Object} [config.matchOptions] The [`CacheQueryOptions`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete#Parameters)\n * that will be used when calling `delete()` on the cache.\n */\n constructor(cacheName, config = {}) {\n this._isRunning = false;\n this._rerunRequested = false;\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(cacheName, 'string', {\n moduleName: 'workbox-expiration',\n className: 'CacheExpiration',\n funcName: 'constructor',\n paramName: 'cacheName',\n });\n if (!(config.maxEntries || config.maxAgeSeconds)) {\n throw new WorkboxError('max-entries-or-age-required', {\n moduleName: 'workbox-expiration',\n className: 'CacheExpiration',\n funcName: 'constructor',\n });\n }\n if (config.maxEntries) {\n assert.isType(config.maxEntries, 'number', {\n moduleName: 'workbox-expiration',\n className: 'CacheExpiration',\n funcName: 'constructor',\n paramName: 'config.maxEntries',\n });\n }\n if (config.maxAgeSeconds) {\n assert.isType(config.maxAgeSeconds, 'number', {\n moduleName: 'workbox-expiration',\n className: 'CacheExpiration',\n funcName: 'constructor',\n paramName: 'config.maxAgeSeconds',\n });\n }\n }\n this._maxEntries = config.maxEntries;\n this._maxAgeSeconds = config.maxAgeSeconds;\n this._matchOptions = config.matchOptions;\n this._cacheName = cacheName;\n this._timestampModel = new CacheTimestampsModel(cacheName);\n }\n /**\n * Expires entries for the given cache and given criteria.\n */\n async expireEntries() {\n if (this._isRunning) {\n this._rerunRequested = true;\n return;\n }\n this._isRunning = true;\n const minTimestamp = this._maxAgeSeconds\n ? Date.now() - this._maxAgeSeconds * 1000\n : 0;\n const urlsExpired = await this._timestampModel.expireEntries(minTimestamp, this._maxEntries);\n // Delete URLs from the cache\n const cache = await self.caches.open(this._cacheName);\n for (const url of urlsExpired) {\n await cache.delete(url, this._matchOptions);\n }\n if (process.env.NODE_ENV !== 'production') {\n if (urlsExpired.length > 0) {\n logger.groupCollapsed(`Expired ${urlsExpired.length} ` +\n `${urlsExpired.length === 1 ? 'entry' : 'entries'} and removed ` +\n `${urlsExpired.length === 1 ? 'it' : 'them'} from the ` +\n `'${this._cacheName}' cache.`);\n logger.log(`Expired the following ${urlsExpired.length === 1 ? 'URL' : 'URLs'}:`);\n urlsExpired.forEach((url) => logger.log(` ${url}`));\n logger.groupEnd();\n }\n else {\n logger.debug(`Cache expiration ran and found no entries to remove.`);\n }\n }\n this._isRunning = false;\n if (this._rerunRequested) {\n this._rerunRequested = false;\n dontWaitFor(this.expireEntries());\n }\n }\n /**\n * Update the timestamp for the given URL. This ensures the when\n * removing entries based on maximum entries, most recently used\n * is accurate or when expiring, the timestamp is up-to-date.\n *\n * @param {string} url\n */\n async updateTimestamp(url) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(url, 'string', {\n moduleName: 'workbox-expiration',\n className: 'CacheExpiration',\n funcName: 'updateTimestamp',\n paramName: 'url',\n });\n }\n await this._timestampModel.setTimestamp(url, Date.now());\n }\n /**\n * Can be used to check if a URL has expired or not before it's used.\n *\n * This requires a look up from IndexedDB, so can be slow.\n *\n * Note: This method will not remove the cached entry, call\n * `expireEntries()` to remove indexedDB and Cache entries.\n *\n * @param {string} url\n * @return {boolean}\n */\n async isURLExpired(url) {\n if (!this._maxAgeSeconds) {\n if (process.env.NODE_ENV !== 'production') {\n throw new WorkboxError(`expired-test-without-max-age`, {\n methodName: 'isURLExpired',\n paramName: 'maxAgeSeconds',\n });\n }\n return false;\n }\n else {\n const timestamp = await this._timestampModel.getTimestamp(url);\n const expireOlderThan = Date.now() - this._maxAgeSeconds * 1000;\n return timestamp !== undefined ? timestamp < expireOlderThan : true;\n }\n }\n /**\n * Removes the IndexedDB object store used to keep track of cache expiration\n * metadata.\n */\n async delete() {\n // Make sure we don't attempt another rerun if we're called in the middle of\n // a cache expiration.\n this._rerunRequested = false;\n await this._timestampModel.expireEntries(Infinity); // Expires all.\n }\n}\nexport { CacheExpiration };\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 { cacheNames } from 'workbox-core/_private/cacheNames.js';\nimport { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { registerQuotaErrorCallback } from 'workbox-core/registerQuotaErrorCallback.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { CacheExpiration } from './CacheExpiration.js';\nimport './_version.js';\n/**\n * This plugin can be used in a `workbox-strategy` to regularly enforce a\n * limit on the age and / or the number of cached requests.\n *\n * It can only be used with `workbox-strategy` instances that have a\n * [custom `cacheName` property set](/web/tools/workbox/guides/configure-workbox#custom_cache_names_in_strategies).\n * In other words, it can't be used to expire entries in strategy that uses the\n * default runtime cache name.\n *\n * Whenever a cached response is used or updated, this plugin will look\n * at the associated cache and remove any old or extra responses.\n *\n * When using `maxAgeSeconds`, responses may be used *once* after expiring\n * because the expiration clean up will not have occurred until *after* the\n * cached response has been used. If the response has a \"Date\" header, then\n * a light weight expiration check is performed and the response will not be\n * used immediately.\n *\n * When using `maxEntries`, the entry least-recently requested will be removed\n * from the cache first.\n *\n * @memberof workbox-expiration\n */\nclass ExpirationPlugin {\n /**\n * @param {ExpirationPluginOptions} config\n * @param {number} [config.maxEntries] The maximum number of entries to cache.\n * Entries used the least will be removed as the maximum is reached.\n * @param {number} [config.maxAgeSeconds] The maximum age of an entry before\n * it's treated as stale and removed.\n * @param {Object} [config.matchOptions] The [`CacheQueryOptions`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete#Parameters)\n * that will be used when calling `delete()` on the cache.\n * @param {boolean} [config.purgeOnQuotaError] Whether to opt this cache in to\n * automatic deletion if the available storage quota has been exceeded.\n */\n constructor(config = {}) {\n /**\n * A \"lifecycle\" callback that will be triggered automatically by the\n * `workbox-strategies` handlers when a `Response` is about to be returned\n * from a [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache) to\n * the handler. It allows the `Response` to be inspected for freshness and\n * prevents it from being used if the `Response`'s `Date` header value is\n * older than the configured `maxAgeSeconds`.\n *\n * @param {Object} options\n * @param {string} options.cacheName Name of the cache the response is in.\n * @param {Response} options.cachedResponse The `Response` object that's been\n * read from a cache and whose freshness should be checked.\n * @return {Response} Either the `cachedResponse`, if it's\n * fresh, or `null` if the `Response` is older than `maxAgeSeconds`.\n *\n * @private\n */\n this.cachedResponseWillBeUsed = async ({ event, request, cacheName, cachedResponse, }) => {\n if (!cachedResponse) {\n return null;\n }\n const isFresh = this._isResponseDateFresh(cachedResponse);\n // Expire entries to ensure that even if the expiration date has\n // expired, it'll only be used once.\n const cacheExpiration = this._getCacheExpiration(cacheName);\n dontWaitFor(cacheExpiration.expireEntries());\n // Update the metadata for the request URL to the current timestamp,\n // but don't `await` it as we don't want to block the response.\n const updateTimestampDone = cacheExpiration.updateTimestamp(request.url);\n if (event) {\n try {\n event.waitUntil(updateTimestampDone);\n }\n catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n // The event may not be a fetch event; only log the URL if it is.\n if ('request' in event) {\n logger.warn(`Unable to ensure service worker stays alive when ` +\n `updating cache entry for ` +\n `'${getFriendlyURL(event.request.url)}'.`);\n }\n }\n }\n }\n return isFresh ? cachedResponse : null;\n };\n /**\n * A \"lifecycle\" callback that will be triggered automatically by the\n * `workbox-strategies` handlers when an entry is added to a cache.\n *\n * @param {Object} options\n * @param {string} options.cacheName Name of the cache that was updated.\n * @param {string} options.request The Request for the cached entry.\n *\n * @private\n */\n this.cacheDidUpdate = async ({ cacheName, request, }) => {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(cacheName, 'string', {\n moduleName: 'workbox-expiration',\n className: 'Plugin',\n funcName: 'cacheDidUpdate',\n paramName: 'cacheName',\n });\n assert.isInstance(request, Request, {\n moduleName: 'workbox-expiration',\n className: 'Plugin',\n funcName: 'cacheDidUpdate',\n paramName: 'request',\n });\n }\n const cacheExpiration = this._getCacheExpiration(cacheName);\n await cacheExpiration.updateTimestamp(request.url);\n await cacheExpiration.expireEntries();\n };\n if (process.env.NODE_ENV !== 'production') {\n if (!(config.maxEntries || config.maxAgeSeconds)) {\n throw new WorkboxError('max-entries-or-age-required', {\n moduleName: 'workbox-expiration',\n className: 'Plugin',\n funcName: 'constructor',\n });\n }\n if (config.maxEntries) {\n assert.isType(config.maxEntries, 'number', {\n moduleName: 'workbox-expiration',\n className: 'Plugin',\n funcName: 'constructor',\n paramName: 'config.maxEntries',\n });\n }\n if (config.maxAgeSeconds) {\n assert.isType(config.maxAgeSeconds, 'number', {\n moduleName: 'workbox-expiration',\n className: 'Plugin',\n funcName: 'constructor',\n paramName: 'config.maxAgeSeconds',\n });\n }\n }\n this._config = config;\n this._maxAgeSeconds = config.maxAgeSeconds;\n this._cacheExpirations = new Map();\n if (config.purgeOnQuotaError) {\n registerQuotaErrorCallback(() => this.deleteCacheAndMetadata());\n }\n }\n /**\n * A simple helper method to return a CacheExpiration instance for a given\n * cache name.\n *\n * @param {string} cacheName\n * @return {CacheExpiration}\n *\n * @private\n */\n _getCacheExpiration(cacheName) {\n if (cacheName === cacheNames.getRuntimeName()) {\n throw new WorkboxError('expire-custom-caches-only');\n }\n let cacheExpiration = this._cacheExpirations.get(cacheName);\n if (!cacheExpiration) {\n cacheExpiration = new CacheExpiration(cacheName, this._config);\n this._cacheExpirations.set(cacheName, cacheExpiration);\n }\n return cacheExpiration;\n }\n /**\n * @param {Response} cachedResponse\n * @return {boolean}\n *\n * @private\n */\n _isResponseDateFresh(cachedResponse) {\n if (!this._maxAgeSeconds) {\n // We aren't expiring by age, so return true, it's fresh\n return true;\n }\n // Check if the 'date' header will suffice a quick expiration check.\n // See https://github.com/GoogleChromeLabs/sw-toolbox/issues/164 for\n // discussion.\n const dateHeaderTimestamp = this._getDateHeaderTimestamp(cachedResponse);\n if (dateHeaderTimestamp === null) {\n // Unable to parse date, so assume it's fresh.\n return true;\n }\n // If we have a valid headerTime, then our response is fresh iff the\n // headerTime plus maxAgeSeconds is greater than the current time.\n const now = Date.now();\n return dateHeaderTimestamp >= now - this._maxAgeSeconds * 1000;\n }\n /**\n * This method will extract the data header and parse it into a useful\n * value.\n *\n * @param {Response} cachedResponse\n * @return {number|null}\n *\n * @private\n */\n _getDateHeaderTimestamp(cachedResponse) {\n if (!cachedResponse.headers.has('date')) {\n return null;\n }\n const dateHeader = cachedResponse.headers.get('date');\n const parsedDate = new Date(dateHeader);\n const headerTime = parsedDate.getTime();\n // If the Date header was invalid for some reason, parsedDate.getTime()\n // will return NaN.\n if (isNaN(headerTime)) {\n return null;\n }\n return headerTime;\n }\n /**\n * This is a helper method that performs two operations:\n *\n * - Deletes *all* the underlying Cache instances associated with this plugin\n * instance, by calling caches.delete() on your behalf.\n * - Deletes the metadata from IndexedDB used to keep track of expiration\n * details for each Cache instance.\n *\n * When using cache expiration, calling this method is preferable to calling\n * `caches.delete()` directly, since this will ensure that the IndexedDB\n * metadata is also cleanly removed and open IndexedDB instances are deleted.\n *\n * Note that if you're *not* using cache expiration for a given cache, calling\n * `caches.delete()` and passing in the cache's name should be sufficient.\n * There is no Workbox-specific method needed for cleanup in that case.\n */\n async deleteCacheAndMetadata() {\n // Do this one at a time instead of all at once via `Promise.all()` to\n // reduce the chance of inconsistency if a promise rejects.\n for (const [cacheName, cacheExpiration] of this._cacheExpirations) {\n await self.caches.delete(cacheName);\n await cacheExpiration.delete();\n }\n // Reset this._cacheExpirations to its initial state.\n this._cacheExpirations = new Map();\n }\n}\nexport { ExpirationPlugin };\n"],"names":["instanceOfAny","object","constructors","some","c","idbProxyableTypes","cursorAdvanceMethods","getIdbProxyableTypes","IDBDatabase","IDBObjectStore","IDBIndex","IDBCursor","IDBTransaction","getCursorAdvanceMethods","prototype","advance","continue","continuePrimaryKey","cursorRequestMap","WeakMap","transactionDoneMap","transactionStoreNamesMap","transformCache","reverseTransformCache","promisifyRequest","request","promise","Promise","resolve","reject","unlisten","removeEventListener","success","error","wrap","result","addEventListener","then","value","set","catch","cacheDonePromiseForTransaction","tx","has","done","complete","DOMException","idbProxyTraps","get","target","prop","receiver","objectStoreNames","undefined","objectStore","replaceTraps","callback","wrapFunction","func","transaction","storeNames","args","call","unwrap","sort","includes","apply","transformCachableValue","Proxy","IDBRequest","newValue","openDB","name","version","blocked","upgrade","blocking","terminated","indexedDB","open","openPromise","event","oldVersion","newVersion","db","deleteDB","deleteDatabase","readMethods","writeMethods","cachedMethods","Map","getMethod","targetFuncName","replace","useIndex","isWrite","method","storeName","store","index","shift","all","oldTraps","_extends","self","_","e","DB_NAME","CACHE_OBJECT_STORE","normalizeURL","unNormalizedUrl","url","URL","location","href","hash","CacheTimestampsModel","constructor","cacheName","_db","_cacheName","_upgradeDb","objStore","createObjectStore","keyPath","createIndex","unique","_upgradeDbAndDeleteOldDbs","setTimestamp","timestamp","entry","id","_getId","getDb","durability","put","getTimestamp","expireEntries","minTimestamp","maxCount","cursor","openCursor","entriesToDelete","entriesNotDeletedCount","push","urlsDeleted","delete","bind","CacheExpiration","config","_isRunning","_rerunRequested","assert","isType","moduleName","className","funcName","paramName","maxEntries","maxAgeSeconds","WorkboxError","_maxEntries","_maxAgeSeconds","_matchOptions","matchOptions","_timestampModel","Date","now","urlsExpired","cache","caches","length","logger","groupCollapsed","log","forEach","groupEnd","debug","dontWaitFor","updateTimestamp","isURLExpired","methodName","expireOlderThan","Infinity","ExpirationPlugin","cachedResponseWillBeUsed","cachedResponse","isFresh","_isResponseDateFresh","cacheExpiration","_getCacheExpiration","updateTimestampDone","waitUntil","warn","getFriendlyURL","cacheDidUpdate","isInstance","Request","_config","_cacheExpirations","purgeOnQuotaError","registerQuotaErrorCallback","deleteCacheAndMetadata","cacheNames","getRuntimeName","dateHeaderTimestamp","_getDateHeaderTimestamp","headers","dateHeader","parsedDate","headerTime","getTime","isNaN"],"mappings":";;;;;;;;;;;;;;EAAA,MAAMA,aAAa,GAAGA,CAACC,MAAM,EAAEC,YAAY,KAAKA,YAAY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E;MACtB,OAAOsC,mBAAmB,IAAItC,GAAG,GAAG,IAAI,CAACL,cAAc,GAAG,IAAI;EAClE,EAAA;EACA;EACJ;EACA;EACA;EACA;EACA;EACA;EACA;EACA;IACI4C,uBAAuBA,CAACpB,cAAc,EAAE;MACpC,IAAI,CAACA,cAAc,CAACqB,OAAO,CAACpK,GAAG,CAAC,MAAM,CAAC,EAAE;EACrC,MAAA,OAAO,IAAI;EACf,IAAA;MACA,MAAMqK,UAAU,GAAGtB,cAAc,CAACqB,OAAO,CAAC/J,GAAG,CAAC,MAAM,CAAC;EACrD,IAAA,MAAMiK,UAAU,GAAG,IAAI3C,IAAI,CAAC0C,UAAU,CAAC;EACvC,IAAA,MAAME,UAAU,GAAGD,UAAU,CAACE,OAAO,EAAE;EACvC;EACA;EACA,IAAA,IAAIC,KAAK,CAACF,UAAU,CAAC,EAAE;EACnB,MAAA,OAAO,IAAI;EACf,IAAA;EACA,IAAA,OAAOA,UAAU;EACrB,EAAA;EACA;EACJ;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;IACI,MAAMR,sBAAsBA,GAAG;EAC3B;EACA;MACA,KAAK,MAAM,CAACpF,SAAS,EAAEuE,eAAe,CAAC,IAAI,IAAI,CAACU,iBAAiB,EAAE;EAC/D,MAAA,MAAM/F,IAAI,CAACkE,MAAM,CAACxB,MAAM,CAAC5B,SAAS,CAAC;EACnC,MAAA,MAAMuE,eAAe,CAAC3C,MAAM,EAAE;EAClC,IAAA;EACA;EACA,IAAA,IAAI,CAACqD,iBAAiB,GAAG,IAAI7G,GAAG,EAAE;EACtC,EAAA;EACJ;;;;;;;;;;;","x_google_ignoreList":[0,1]} \ No newline at end of file diff --git a/node_modules/workbox-expiration/build/workbox-expiration.prod.js b/node_modules/workbox-expiration/build/workbox-expiration.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..f7f36f24f93f2fbe045a59662b3f1ed509a6081b --- /dev/null +++ b/node_modules/workbox-expiration/build/workbox-expiration.prod.js @@ -0,0 +1,2 @@ +this.workbox=this.workbox||{},this.workbox.expiration=function(t,e,n,s,i){"use strict";function r(){return r=Object.assign?Object.assign.bind():function(t){for(var e=1;ee.some((e=>t instanceof e));let o,c;const u=new WeakMap,h=new WeakMap,f=new WeakMap,l=new WeakMap,d=new WeakMap;let w={get(t,e,n){if(t instanceof IDBTransaction){if("done"===e)return h.get(t);if("objectStoreNames"===e)return t.objectStoreNames||f.get(t);if("store"===e)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return m(t[e])},set:(t,e,n)=>(t[e]=n,!0),has:(t,e)=>t instanceof IDBTransaction&&("done"===e||"store"===e)||e in t};function p(t){return t!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(c||(c=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(t)?function(...e){return t.apply(b(this),e),m(u.get(this))}:function(...e){return m(t.apply(b(this),e))}:function(e,...n){const s=t.call(b(this),e,...n);return f.set(s,e.sort?e.sort():[e]),m(s)}}function D(t){return"function"==typeof t?p(t):(t instanceof IDBTransaction&&function(t){if(h.has(t))return;const e=new Promise(((e,n)=>{const s=()=>{t.removeEventListener("complete",i),t.removeEventListener("error",r),t.removeEventListener("abort",r)},i=()=>{e(),s()},r=()=>{n(t.error||new DOMException("AbortError","AbortError")),s()};t.addEventListener("complete",i),t.addEventListener("error",r),t.addEventListener("abort",r)}));h.set(t,e)}(t),a(t,o||(o=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(t,w):t)}function m(t){if(t instanceof IDBRequest)return function(t){const e=new Promise(((e,n)=>{const s=()=>{t.removeEventListener("success",i),t.removeEventListener("error",r)},i=()=>{e(m(t.result)),s()},r=()=>{n(t.error),s()};t.addEventListener("success",i),t.addEventListener("error",r)}));return e.then((e=>{e instanceof IDBCursor&&u.set(e,t)})).catch((()=>{})),d.set(e,t),e}(t);if(l.has(t))return l.get(t);const e=D(t);return e!==t&&(l.set(t,e),d.set(e,t)),e}const b=t=>d.get(t);const y=["get","getKey","getAll","getAllKeys","count"],I=["put","add","delete","clear"],B=new Map;function g(t,e){if(!(t instanceof IDBDatabase)||e in t||"string"!=typeof e)return;if(B.get(e))return B.get(e);const n=e.replace(/FromIndex$/,""),s=e!==n,i=I.includes(n);if(!(n in(s?IDBIndex:IDBObjectStore).prototype)||!i&&!y.includes(n))return;const r=async function(t,...e){const r=this.transaction(t,i?"readwrite":"readonly");let a=r.store;return s&&(a=a.index(e.shift())),(await Promise.all([a[n](...e),i&&r.done]))[0]};return B.set(e,r),r}w=(t=>r({},t,{get:(e,n,s)=>g(e,n)||t.get(e,n,s),has:(e,n)=>!!g(e,n)||t.has(e,n)}))(w);try{self["workbox:expiration:7.4.0"]&&_()}catch(t){}const x="cache-entries",k=t=>{const e=new URL(t,location.href);return e.hash="",e.href};class v{constructor(t){this.A=null,this.G=t}J(t){const e=t.createObjectStore(x,{keyPath:"id"});e.createIndex("cacheName","cacheName",{unique:!1}),e.createIndex("timestamp","timestamp",{unique:!1})}V(t){this.J(t),this.G&&function(t,{blocked:e}={}){const n=indexedDB.deleteDatabase(t);e&&n.addEventListener("blocked",(()=>e())),m(n).then((()=>{}))}(this.G)}async setTimestamp(t,e){const n={url:t=k(t),timestamp:e,cacheName:this.G,id:this.X(t)},s=(await this.getDb()).transaction(x,"readwrite",{durability:"relaxed"});await s.store.put(n),await s.done}async getTimestamp(t){const e=await this.getDb(),n=await e.get(x,this.X(t));return null==n?void 0:n.timestamp}async expireEntries(t,e){const n=await this.getDb();let s=await n.transaction(x).store.index("timestamp").openCursor(null,"prev");const i=[];let r=0;for(;s;){const n=s.value;n.cacheName===this.G&&(t&&n.timestamp=e?i.push(s.value):r++),s=await s.continue()}const a=[];for(const t of i)await n.delete(x,t.id),a.push(t.url);return a}X(t){return this.G+"|"+k(t)}async getDb(){return this.A||(this.A=await function(t,e,{blocked:n,upgrade:s,blocking:i,terminated:r}={}){const a=indexedDB.open(t,e),o=m(a);return s&&a.addEventListener("upgradeneeded",(t=>{s(m(a.result),t.oldVersion,t.newVersion,m(a.transaction))})),n&&a.addEventListener("blocked",(()=>n())),o.then((t=>{r&&t.addEventListener("close",(()=>r())),i&&t.addEventListener("versionchange",(()=>i()))})).catch((()=>{})),o}("workbox-expiration",1,{upgrade:this.V.bind(this)})),this.A}}class M{constructor(t,e={}){this.Y=!1,this.Z=!1,this.tt=e.maxEntries,this.et=e.maxAgeSeconds,this.nt=e.matchOptions,this.G=t,this.st=new v(t)}async expireEntries(){if(this.Y)return void(this.Z=!0);this.Y=!0;const t=this.et?Date.now()-1e3*this.et:0,n=await this.st.expireEntries(t,this.tt),s=await self.caches.open(this.G);for(const t of n)await s.delete(t,this.nt);this.Y=!1,this.Z&&(this.Z=!1,e.dontWaitFor(this.expireEntries()))}async updateTimestamp(t){await this.st.setTimestamp(t,Date.now())}async isURLExpired(t){if(this.et){const e=await this.st.getTimestamp(t),n=Date.now()-1e3*this.et;return void 0===e||e{if(!i)return null;const r=this.it(i),a=this.rt(s);e.dontWaitFor(a.expireEntries());const o=a.updateTimestamp(n.url);if(t)try{t.waitUntil(o)}catch(t){}return r?i:null},this.cacheDidUpdate=async({cacheName:t,request:e})=>{const n=this.rt(t);await n.updateTimestamp(e.url),await n.expireEntries()},this.ot=t,this.et=t.maxAgeSeconds,this.ct=new Map,t.purgeOnQuotaError&&s.registerQuotaErrorCallback((()=>this.deleteCacheAndMetadata()))}rt(t){if(t===n.cacheNames.getRuntimeName())throw new i.WorkboxError("expire-custom-caches-only");let e=this.ct.get(t);return e||(e=new M(t,this.ot),this.ct.set(t,e)),e}it(t){if(!this.et)return!0;const e=this.ut(t);if(null===e)return!0;return e>=Date.now()-1e3*this.et}ut(t){if(!t.headers.has("date"))return null;const e=t.headers.get("date"),n=new Date(e).getTime();return isNaN(n)?null:n}async deleteCacheAndMetadata(){for(const[t,e]of this.ct)await self.caches.delete(t),await e.delete();this.ct=new Map}},t}({},workbox.core._private,workbox.core._private,workbox.core,workbox.core._private); +//# sourceMappingURL=workbox-expiration.prod.js.map diff --git a/node_modules/workbox-expiration/build/workbox-expiration.prod.js.map b/node_modules/workbox-expiration/build/workbox-expiration.prod.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a171c0c42b99c929fceefa031b23a81b3b30ca97 --- /dev/null +++ b/node_modules/workbox-expiration/build/workbox-expiration.prod.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-expiration.prod.js","sources":["../node_modules/idb/build/wrap-idb-value.js","../node_modules/idb/build/index.js","../_version.js","../models/CacheTimestampsModel.js","../CacheExpiration.js","../ExpirationPlugin.js"],"sourcesContent":["const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n promise\n .then((value) => {\n // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n // (see wrapFunction).\n if (value instanceof IDBCursor) {\n cursorRequestMap.set(value, request);\n }\n // Catching to avoid \"Uncaught Promise exceptions\"\n })\n .catch(() => { });\n // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Polyfill for objectStoreNames because of Edge.\n if (prop === 'objectStoreNames') {\n return target.objectStoreNames || transactionStoreNamesMap.get(target);\n }\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n if (func === IDBDatabase.prototype.transaction &&\n !('objectStoreNames' in IDBTransaction.prototype)) {\n return function (storeNames, ...args) {\n const tx = func.call(unwrap(this), storeNames, ...args);\n transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n return wrap(tx);\n };\n }\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(cursorRequestMap.get(this));\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n","import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction));\n });\n }\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking)\n db.addEventListener('versionchange', () => blocking());\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n","\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:expiration:7.4.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 { openDB, deleteDB } from 'idb';\nimport '../_version.js';\nconst DB_NAME = 'workbox-expiration';\nconst CACHE_OBJECT_STORE = 'cache-entries';\nconst normalizeURL = (unNormalizedUrl) => {\n const url = new URL(unNormalizedUrl, location.href);\n url.hash = '';\n return url.href;\n};\n/**\n * Returns the timestamp model.\n *\n * @private\n */\nclass CacheTimestampsModel {\n /**\n *\n * @param {string} cacheName\n *\n * @private\n */\n constructor(cacheName) {\n this._db = null;\n this._cacheName = cacheName;\n }\n /**\n * Performs an upgrade of indexedDB.\n *\n * @param {IDBPDatabase} db\n *\n * @private\n */\n _upgradeDb(db) {\n // TODO(philipwalton): EdgeHTML doesn't support arrays as a keyPath, so we\n // have to use the `id` keyPath here and create our own values (a\n // concatenation of `url + cacheName`) instead of simply using\n // `keyPath: ['url', 'cacheName']`, which is supported in other browsers.\n const objStore = db.createObjectStore(CACHE_OBJECT_STORE, { keyPath: 'id' });\n // TODO(philipwalton): once we don't have to support EdgeHTML, we can\n // create a single index with the keyPath `['cacheName', 'timestamp']`\n // instead of doing both these indexes.\n objStore.createIndex('cacheName', 'cacheName', { unique: false });\n objStore.createIndex('timestamp', 'timestamp', { unique: false });\n }\n /**\n * Performs an upgrade of indexedDB and deletes deprecated DBs.\n *\n * @param {IDBPDatabase} db\n *\n * @private\n */\n _upgradeDbAndDeleteOldDbs(db) {\n this._upgradeDb(db);\n if (this._cacheName) {\n void deleteDB(this._cacheName);\n }\n }\n /**\n * @param {string} url\n * @param {number} timestamp\n *\n * @private\n */\n async setTimestamp(url, timestamp) {\n url = normalizeURL(url);\n const entry = {\n url,\n timestamp,\n cacheName: this._cacheName,\n // Creating an ID from the URL and cache name won't be necessary once\n // Edge switches to Chromium and all browsers we support work with\n // array keyPaths.\n id: this._getId(url),\n };\n const db = await this.getDb();\n const tx = db.transaction(CACHE_OBJECT_STORE, 'readwrite', {\n durability: 'relaxed',\n });\n await tx.store.put(entry);\n await tx.done;\n }\n /**\n * Returns the timestamp stored for a given URL.\n *\n * @param {string} url\n * @return {number | undefined}\n *\n * @private\n */\n async getTimestamp(url) {\n const db = await this.getDb();\n const entry = await db.get(CACHE_OBJECT_STORE, this._getId(url));\n return entry === null || entry === void 0 ? void 0 : entry.timestamp;\n }\n /**\n * Iterates through all the entries in the object store (from newest to\n * oldest) and removes entries once either `maxCount` is reached or the\n * entry's timestamp is less than `minTimestamp`.\n *\n * @param {number} minTimestamp\n * @param {number} maxCount\n * @return {Array}\n *\n * @private\n */\n async expireEntries(minTimestamp, maxCount) {\n const db = await this.getDb();\n let cursor = await db\n .transaction(CACHE_OBJECT_STORE)\n .store.index('timestamp')\n .openCursor(null, 'prev');\n const entriesToDelete = [];\n let entriesNotDeletedCount = 0;\n while (cursor) {\n const result = cursor.value;\n // TODO(philipwalton): once we can use a multi-key index, we\n // won't have to check `cacheName` here.\n if (result.cacheName === this._cacheName) {\n // Delete an entry if it's older than the max age or\n // if we already have the max number allowed.\n if ((minTimestamp && result.timestamp < minTimestamp) ||\n (maxCount && entriesNotDeletedCount >= maxCount)) {\n // TODO(philipwalton): we should be able to delete the\n // entry right here, but doing so causes an iteration\n // bug in Safari stable (fixed in TP). Instead we can\n // store the keys of the entries to delete, and then\n // delete the separate transactions.\n // https://github.com/GoogleChrome/workbox/issues/1978\n // cursor.delete();\n // We only need to return the URL, not the whole entry.\n entriesToDelete.push(cursor.value);\n }\n else {\n entriesNotDeletedCount++;\n }\n }\n cursor = await cursor.continue();\n }\n // TODO(philipwalton): once the Safari bug in the following issue is fixed,\n // we should be able to remove this loop and do the entry deletion in the\n // cursor loop above:\n // https://github.com/GoogleChrome/workbox/issues/1978\n const urlsDeleted = [];\n for (const entry of entriesToDelete) {\n await db.delete(CACHE_OBJECT_STORE, entry.id);\n urlsDeleted.push(entry.url);\n }\n return urlsDeleted;\n }\n /**\n * Takes a URL and returns an ID that will be unique in the object store.\n *\n * @param {string} url\n * @return {string}\n *\n * @private\n */\n _getId(url) {\n // Creating an ID from the URL and cache name won't be necessary once\n // Edge switches to Chromium and all browsers we support work with\n // array keyPaths.\n return this._cacheName + '|' + normalizeURL(url);\n }\n /**\n * Returns an open connection to the database.\n *\n * @private\n */\n async getDb() {\n if (!this._db) {\n this._db = await openDB(DB_NAME, 1, {\n upgrade: this._upgradeDbAndDeleteOldDbs.bind(this),\n });\n }\n return this._db;\n }\n}\nexport { CacheTimestampsModel };\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 { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { CacheTimestampsModel } from './models/CacheTimestampsModel.js';\nimport './_version.js';\n/**\n * The `CacheExpiration` class allows you define an expiration and / or\n * limit on the number of responses stored in a\n * [`Cache`](https://developer.mozilla.org/en-US/docs/Web/API/Cache).\n *\n * @memberof workbox-expiration\n */\nclass CacheExpiration {\n /**\n * To construct a new CacheExpiration instance you must provide at least\n * one of the `config` properties.\n *\n * @param {string} cacheName Name of the cache to apply restrictions to.\n * @param {Object} config\n * @param {number} [config.maxEntries] The maximum number of entries to cache.\n * Entries used the least will be removed as the maximum is reached.\n * @param {number} [config.maxAgeSeconds] The maximum age of an entry before\n * it's treated as stale and removed.\n * @param {Object} [config.matchOptions] The [`CacheQueryOptions`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete#Parameters)\n * that will be used when calling `delete()` on the cache.\n */\n constructor(cacheName, config = {}) {\n this._isRunning = false;\n this._rerunRequested = false;\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(cacheName, 'string', {\n moduleName: 'workbox-expiration',\n className: 'CacheExpiration',\n funcName: 'constructor',\n paramName: 'cacheName',\n });\n if (!(config.maxEntries || config.maxAgeSeconds)) {\n throw new WorkboxError('max-entries-or-age-required', {\n moduleName: 'workbox-expiration',\n className: 'CacheExpiration',\n funcName: 'constructor',\n });\n }\n if (config.maxEntries) {\n assert.isType(config.maxEntries, 'number', {\n moduleName: 'workbox-expiration',\n className: 'CacheExpiration',\n funcName: 'constructor',\n paramName: 'config.maxEntries',\n });\n }\n if (config.maxAgeSeconds) {\n assert.isType(config.maxAgeSeconds, 'number', {\n moduleName: 'workbox-expiration',\n className: 'CacheExpiration',\n funcName: 'constructor',\n paramName: 'config.maxAgeSeconds',\n });\n }\n }\n this._maxEntries = config.maxEntries;\n this._maxAgeSeconds = config.maxAgeSeconds;\n this._matchOptions = config.matchOptions;\n this._cacheName = cacheName;\n this._timestampModel = new CacheTimestampsModel(cacheName);\n }\n /**\n * Expires entries for the given cache and given criteria.\n */\n async expireEntries() {\n if (this._isRunning) {\n this._rerunRequested = true;\n return;\n }\n this._isRunning = true;\n const minTimestamp = this._maxAgeSeconds\n ? Date.now() - this._maxAgeSeconds * 1000\n : 0;\n const urlsExpired = await this._timestampModel.expireEntries(minTimestamp, this._maxEntries);\n // Delete URLs from the cache\n const cache = await self.caches.open(this._cacheName);\n for (const url of urlsExpired) {\n await cache.delete(url, this._matchOptions);\n }\n if (process.env.NODE_ENV !== 'production') {\n if (urlsExpired.length > 0) {\n logger.groupCollapsed(`Expired ${urlsExpired.length} ` +\n `${urlsExpired.length === 1 ? 'entry' : 'entries'} and removed ` +\n `${urlsExpired.length === 1 ? 'it' : 'them'} from the ` +\n `'${this._cacheName}' cache.`);\n logger.log(`Expired the following ${urlsExpired.length === 1 ? 'URL' : 'URLs'}:`);\n urlsExpired.forEach((url) => logger.log(` ${url}`));\n logger.groupEnd();\n }\n else {\n logger.debug(`Cache expiration ran and found no entries to remove.`);\n }\n }\n this._isRunning = false;\n if (this._rerunRequested) {\n this._rerunRequested = false;\n dontWaitFor(this.expireEntries());\n }\n }\n /**\n * Update the timestamp for the given URL. This ensures the when\n * removing entries based on maximum entries, most recently used\n * is accurate or when expiring, the timestamp is up-to-date.\n *\n * @param {string} url\n */\n async updateTimestamp(url) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(url, 'string', {\n moduleName: 'workbox-expiration',\n className: 'CacheExpiration',\n funcName: 'updateTimestamp',\n paramName: 'url',\n });\n }\n await this._timestampModel.setTimestamp(url, Date.now());\n }\n /**\n * Can be used to check if a URL has expired or not before it's used.\n *\n * This requires a look up from IndexedDB, so can be slow.\n *\n * Note: This method will not remove the cached entry, call\n * `expireEntries()` to remove indexedDB and Cache entries.\n *\n * @param {string} url\n * @return {boolean}\n */\n async isURLExpired(url) {\n if (!this._maxAgeSeconds) {\n if (process.env.NODE_ENV !== 'production') {\n throw new WorkboxError(`expired-test-without-max-age`, {\n methodName: 'isURLExpired',\n paramName: 'maxAgeSeconds',\n });\n }\n return false;\n }\n else {\n const timestamp = await this._timestampModel.getTimestamp(url);\n const expireOlderThan = Date.now() - this._maxAgeSeconds * 1000;\n return timestamp !== undefined ? timestamp < expireOlderThan : true;\n }\n }\n /**\n * Removes the IndexedDB object store used to keep track of cache expiration\n * metadata.\n */\n async delete() {\n // Make sure we don't attempt another rerun if we're called in the middle of\n // a cache expiration.\n this._rerunRequested = false;\n await this._timestampModel.expireEntries(Infinity); // Expires all.\n }\n}\nexport { CacheExpiration };\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 { cacheNames } from 'workbox-core/_private/cacheNames.js';\nimport { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { registerQuotaErrorCallback } from 'workbox-core/registerQuotaErrorCallback.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { CacheExpiration } from './CacheExpiration.js';\nimport './_version.js';\n/**\n * This plugin can be used in a `workbox-strategy` to regularly enforce a\n * limit on the age and / or the number of cached requests.\n *\n * It can only be used with `workbox-strategy` instances that have a\n * [custom `cacheName` property set](/web/tools/workbox/guides/configure-workbox#custom_cache_names_in_strategies).\n * In other words, it can't be used to expire entries in strategy that uses the\n * default runtime cache name.\n *\n * Whenever a cached response is used or updated, this plugin will look\n * at the associated cache and remove any old or extra responses.\n *\n * When using `maxAgeSeconds`, responses may be used *once* after expiring\n * because the expiration clean up will not have occurred until *after* the\n * cached response has been used. If the response has a \"Date\" header, then\n * a light weight expiration check is performed and the response will not be\n * used immediately.\n *\n * When using `maxEntries`, the entry least-recently requested will be removed\n * from the cache first.\n *\n * @memberof workbox-expiration\n */\nclass ExpirationPlugin {\n /**\n * @param {ExpirationPluginOptions} config\n * @param {number} [config.maxEntries] The maximum number of entries to cache.\n * Entries used the least will be removed as the maximum is reached.\n * @param {number} [config.maxAgeSeconds] The maximum age of an entry before\n * it's treated as stale and removed.\n * @param {Object} [config.matchOptions] The [`CacheQueryOptions`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete#Parameters)\n * that will be used when calling `delete()` on the cache.\n * @param {boolean} [config.purgeOnQuotaError] Whether to opt this cache in to\n * automatic deletion if the available storage quota has been exceeded.\n */\n constructor(config = {}) {\n /**\n * A \"lifecycle\" callback that will be triggered automatically by the\n * `workbox-strategies` handlers when a `Response` is about to be returned\n * from a [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache) to\n * the handler. It allows the `Response` to be inspected for freshness and\n * prevents it from being used if the `Response`'s `Date` header value is\n * older than the configured `maxAgeSeconds`.\n *\n * @param {Object} options\n * @param {string} options.cacheName Name of the cache the response is in.\n * @param {Response} options.cachedResponse The `Response` object that's been\n * read from a cache and whose freshness should be checked.\n * @return {Response} Either the `cachedResponse`, if it's\n * fresh, or `null` if the `Response` is older than `maxAgeSeconds`.\n *\n * @private\n */\n this.cachedResponseWillBeUsed = async ({ event, request, cacheName, cachedResponse, }) => {\n if (!cachedResponse) {\n return null;\n }\n const isFresh = this._isResponseDateFresh(cachedResponse);\n // Expire entries to ensure that even if the expiration date has\n // expired, it'll only be used once.\n const cacheExpiration = this._getCacheExpiration(cacheName);\n dontWaitFor(cacheExpiration.expireEntries());\n // Update the metadata for the request URL to the current timestamp,\n // but don't `await` it as we don't want to block the response.\n const updateTimestampDone = cacheExpiration.updateTimestamp(request.url);\n if (event) {\n try {\n event.waitUntil(updateTimestampDone);\n }\n catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n // The event may not be a fetch event; only log the URL if it is.\n if ('request' in event) {\n logger.warn(`Unable to ensure service worker stays alive when ` +\n `updating cache entry for ` +\n `'${getFriendlyURL(event.request.url)}'.`);\n }\n }\n }\n }\n return isFresh ? cachedResponse : null;\n };\n /**\n * A \"lifecycle\" callback that will be triggered automatically by the\n * `workbox-strategies` handlers when an entry is added to a cache.\n *\n * @param {Object} options\n * @param {string} options.cacheName Name of the cache that was updated.\n * @param {string} options.request The Request for the cached entry.\n *\n * @private\n */\n this.cacheDidUpdate = async ({ cacheName, request, }) => {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(cacheName, 'string', {\n moduleName: 'workbox-expiration',\n className: 'Plugin',\n funcName: 'cacheDidUpdate',\n paramName: 'cacheName',\n });\n assert.isInstance(request, Request, {\n moduleName: 'workbox-expiration',\n className: 'Plugin',\n funcName: 'cacheDidUpdate',\n paramName: 'request',\n });\n }\n const cacheExpiration = this._getCacheExpiration(cacheName);\n await cacheExpiration.updateTimestamp(request.url);\n await cacheExpiration.expireEntries();\n };\n if (process.env.NODE_ENV !== 'production') {\n if (!(config.maxEntries || config.maxAgeSeconds)) {\n throw new WorkboxError('max-entries-or-age-required', {\n moduleName: 'workbox-expiration',\n className: 'Plugin',\n funcName: 'constructor',\n });\n }\n if (config.maxEntries) {\n assert.isType(config.maxEntries, 'number', {\n moduleName: 'workbox-expiration',\n className: 'Plugin',\n funcName: 'constructor',\n paramName: 'config.maxEntries',\n });\n }\n if (config.maxAgeSeconds) {\n assert.isType(config.maxAgeSeconds, 'number', {\n moduleName: 'workbox-expiration',\n className: 'Plugin',\n funcName: 'constructor',\n paramName: 'config.maxAgeSeconds',\n });\n }\n }\n this._config = config;\n this._maxAgeSeconds = config.maxAgeSeconds;\n this._cacheExpirations = new Map();\n if (config.purgeOnQuotaError) {\n registerQuotaErrorCallback(() => this.deleteCacheAndMetadata());\n }\n }\n /**\n * A simple helper method to return a CacheExpiration instance for a given\n * cache name.\n *\n * @param {string} cacheName\n * @return {CacheExpiration}\n *\n * @private\n */\n _getCacheExpiration(cacheName) {\n if (cacheName === cacheNames.getRuntimeName()) {\n throw new WorkboxError('expire-custom-caches-only');\n }\n let cacheExpiration = this._cacheExpirations.get(cacheName);\n if (!cacheExpiration) {\n cacheExpiration = new CacheExpiration(cacheName, this._config);\n this._cacheExpirations.set(cacheName, cacheExpiration);\n }\n return cacheExpiration;\n }\n /**\n * @param {Response} cachedResponse\n * @return {boolean}\n *\n * @private\n */\n _isResponseDateFresh(cachedResponse) {\n if (!this._maxAgeSeconds) {\n // We aren't expiring by age, so return true, it's fresh\n return true;\n }\n // Check if the 'date' header will suffice a quick expiration check.\n // See https://github.com/GoogleChromeLabs/sw-toolbox/issues/164 for\n // discussion.\n const dateHeaderTimestamp = this._getDateHeaderTimestamp(cachedResponse);\n if (dateHeaderTimestamp === null) {\n // Unable to parse date, so assume it's fresh.\n return true;\n }\n // If we have a valid headerTime, then our response is fresh iff the\n // headerTime plus maxAgeSeconds is greater than the current time.\n const now = Date.now();\n return dateHeaderTimestamp >= now - this._maxAgeSeconds * 1000;\n }\n /**\n * This method will extract the data header and parse it into a useful\n * value.\n *\n * @param {Response} cachedResponse\n * @return {number|null}\n *\n * @private\n */\n _getDateHeaderTimestamp(cachedResponse) {\n if (!cachedResponse.headers.has('date')) {\n return null;\n }\n const dateHeader = cachedResponse.headers.get('date');\n const parsedDate = new Date(dateHeader);\n const headerTime = parsedDate.getTime();\n // If the Date header was invalid for some reason, parsedDate.getTime()\n // will return NaN.\n if (isNaN(headerTime)) {\n return null;\n }\n return headerTime;\n }\n /**\n * This is a helper method that performs two operations:\n *\n * - Deletes *all* the underlying Cache instances associated with this plugin\n * instance, by calling caches.delete() on your behalf.\n * - Deletes the metadata from IndexedDB used to keep track of expiration\n * details for each Cache instance.\n *\n * When using cache expiration, calling this method is preferable to calling\n * `caches.delete()` directly, since this will ensure that the IndexedDB\n * metadata is also cleanly removed and open IndexedDB instances are deleted.\n *\n * Note that if you're *not* using cache expiration for a given cache, calling\n * `caches.delete()` and passing in the cache's name should be sufficient.\n * There is no Workbox-specific method needed for cleanup in that case.\n */\n async deleteCacheAndMetadata() {\n // Do this one at a time instead of all at once via `Promise.all()` to\n // reduce the chance of inconsistency if a promise rejects.\n for (const [cacheName, cacheExpiration] of this._cacheExpirations) {\n await self.caches.delete(cacheName);\n await cacheExpiration.delete();\n }\n // Reset this._cacheExpirations to its initial state.\n this._cacheExpirations = new Map();\n }\n}\nexport { ExpirationPlugin };\n"],"names":["instanceOfAny","object","constructors","some","c","idbProxyableTypes","cursorAdvanceMethods","cursorRequestMap","WeakMap","transactionDoneMap","transactionStoreNamesMap","transformCache","reverseTransformCache","idbProxyTraps","get","target","prop","receiver","IDBTransaction","objectStoreNames","undefined","objectStore","wrap","set","value","has","wrapFunction","func","IDBDatabase","prototype","transaction","IDBCursor","advance","continue","continuePrimaryKey","includes","args","apply","unwrap","this","storeNames","tx","call","sort","transformCachableValue","done","Promise","resolve","reject","unlisten","removeEventListener","complete","error","DOMException","addEventListener","cacheDonePromiseForTransaction","IDBObjectStore","IDBIndex","Proxy","IDBRequest","request","promise","success","result","then","catch","promisifyRequest","newValue","readMethods","writeMethods","cachedMethods","Map","getMethod","targetFuncName","replace","useIndex","isWrite","method","async","storeName","store","index","shift","all","oldTraps","_extends","callback","self","_","e","CACHE_OBJECT_STORE","normalizeURL","unNormalizedUrl","url","URL","location","href","hash","CacheTimestampsModel","constructor","cacheName","_db","_cacheName","_upgradeDb","db","objStore","createObjectStore","keyPath","createIndex","unique","_upgradeDbAndDeleteOldDbs","name","blocked","indexedDB","deleteDatabase","deleteDB","timestamp","entry","id","_getId","getDb","durability","put","minTimestamp","maxCount","cursor","openCursor","entriesToDelete","entriesNotDeletedCount","push","urlsDeleted","delete","version","upgrade","blocking","terminated","open","openPromise","event","oldVersion","newVersion","openDB","bind","CacheExpiration","config","_isRunning","_rerunRequested","_maxEntries","maxEntries","_maxAgeSeconds","maxAgeSeconds","_matchOptions","matchOptions","_timestampModel","Date","now","urlsExpired","expireEntries","cache","caches","dontWaitFor","setTimestamp","getTimestamp","expireOlderThan","Infinity","cachedResponseWillBeUsed","cachedResponse","isFresh","_isResponseDateFresh","cacheExpiration","_getCacheExpiration","updateTimestampDone","updateTimestamp","waitUntil","cacheDidUpdate","_config","_cacheExpirations","purgeOnQuotaError","registerQuotaErrorCallback","deleteCacheAndMetadata","cacheNames","getRuntimeName","WorkboxError","dateHeaderTimestamp","_getDateHeaderTimestamp","headers","dateHeader","headerTime","getTime","isNaN"],"mappings":"+SAAA,MAAMA,EAAgBA,CAACC,EAAQC,IAAiBA,EAAaC,MAAMC,GAAMH,aAAkBG,IAE3F,IAAIC,EACAC,EAqBJ,MAAMC,EAAmB,IAAIC,QACvBC,EAAqB,IAAID,QACzBE,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,EA2BzCtH,KAAKwI,GAAU/B,EACfzG,KAAK8G,GAAiBL,EAAOM,cAC7B/G,KAAKyI,GAAoB,IAAIzG,IACzByE,EAAOiC,mBACPC,8BAA2B,IAAM3I,KAAK4I,0BAE9C,CAUAT,GAAoBtE,GAChB,GAAIA,IAAcgF,aAAWC,iBACzB,MAAM,IAAIC,EAAAA,aAAa,6BAE3B,IAAIb,EAAkBlI,KAAKyI,GAAkBlK,IAAIsF,GAKjD,OAJKqE,IACDA,EAAkB,IAAI1B,EAAgB3C,EAAW7D,KAAKwI,IACtDxI,KAAKyI,GAAkBzJ,IAAI6E,EAAWqE,IAEnCA,CACX,CAOAD,GAAqBF,GACjB,IAAK/H,KAAK8G,GAEN,OAAO,EAKX,MAAMkC,EAAsBhJ,KAAKiJ,GAAwBlB,GACzD,GAA4B,OAAxBiB,EAEA,OAAO,EAKX,OAAOA,GADK7B,KAAKC,MACyC,IAAtBpH,KAAK8G,EAC7C,CAUAmC,GAAwBlB,GACpB,IAAKA,EAAemB,QAAQhK,IAAI,QAC5B,OAAO,KAEX,MAAMiK,EAAapB,EAAemB,QAAQ3K,IAAI,QAExC6K,EADa,IAAIjC,KAAKgC,GACEE,UAG9B,OAAIC,MAAMF,GACC,KAEJA,CACX,CAiBA7G,+BAGI,IAAK,MAAOsB,EAAWqE,KAAoBlI,KAAKyI,SACtCzF,KAAKwE,OAAO5B,OAAO/B,SACnBqE,EAAgBtC,SAG1B5F,KAAKyI,GAAoB,IAAIzG,GACjC","x_google_ignoreList":[0,1]} \ No newline at end of file diff --git a/node_modules/workbox-expiration/index.d.ts b/node_modules/workbox-expiration/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3b9a9b0518bf4bb51eefc4fe60c70d968cc98384 --- /dev/null +++ b/node_modules/workbox-expiration/index.d.ts @@ -0,0 +1,7 @@ +import { CacheExpiration } from './CacheExpiration.js'; +import { ExpirationPlugin, ExpirationPluginOptions } from './ExpirationPlugin.js'; +import './_version.js'; +/** + * @module workbox-expiration + */ +export { CacheExpiration, ExpirationPlugin, ExpirationPluginOptions }; diff --git a/node_modules/workbox-expiration/index.js b/node_modules/workbox-expiration/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2a5a0729cb598355d05bfc4c3e5bcfb3788b1bde --- /dev/null +++ b/node_modules/workbox-expiration/index.js @@ -0,0 +1,14 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { CacheExpiration } from './CacheExpiration.js'; +import { ExpirationPlugin } from './ExpirationPlugin.js'; +import './_version.js'; +/** + * @module workbox-expiration + */ +export { CacheExpiration, ExpirationPlugin }; diff --git a/node_modules/workbox-expiration/index.mjs b/node_modules/workbox-expiration/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..833b6a2f3226fec78490a3b7a622dc5146f94b53 --- /dev/null +++ b/node_modules/workbox-expiration/index.mjs @@ -0,0 +1 @@ +export * from './index.js'; \ No newline at end of file diff --git a/node_modules/workbox-expiration/models/CacheTimestampsModel.d.ts b/node_modules/workbox-expiration/models/CacheTimestampsModel.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a392ee5e8a208d3ce6982e852d06e59a86a36bd4 --- /dev/null +++ b/node_modules/workbox-expiration/models/CacheTimestampsModel.d.ts @@ -0,0 +1,77 @@ +import '../_version.js'; +/** + * Returns the timestamp model. + * + * @private + */ +declare class CacheTimestampsModel { + private readonly _cacheName; + private _db; + /** + * + * @param {string} cacheName + * + * @private + */ + constructor(cacheName: string); + /** + * Performs an upgrade of indexedDB. + * + * @param {IDBPDatabase} db + * + * @private + */ + private _upgradeDb; + /** + * Performs an upgrade of indexedDB and deletes deprecated DBs. + * + * @param {IDBPDatabase} db + * + * @private + */ + private _upgradeDbAndDeleteOldDbs; + /** + * @param {string} url + * @param {number} timestamp + * + * @private + */ + setTimestamp(url: string, timestamp: number): Promise; + /** + * Returns the timestamp stored for a given URL. + * + * @param {string} url + * @return {number | undefined} + * + * @private + */ + getTimestamp(url: string): Promise; + /** + * Iterates through all the entries in the object store (from newest to + * oldest) and removes entries once either `maxCount` is reached or the + * entry's timestamp is less than `minTimestamp`. + * + * @param {number} minTimestamp + * @param {number} maxCount + * @return {Array} + * + * @private + */ + expireEntries(minTimestamp: number, maxCount?: number): Promise; + /** + * Takes a URL and returns an ID that will be unique in the object store. + * + * @param {string} url + * @return {string} + * + * @private + */ + private _getId; + /** + * Returns an open connection to the database. + * + * @private + */ + private getDb; +} +export { CacheTimestampsModel }; diff --git a/node_modules/workbox-expiration/models/CacheTimestampsModel.js b/node_modules/workbox-expiration/models/CacheTimestampsModel.js new file mode 100644 index 0000000000000000000000000000000000000000..1206e76b46e8e88d065f3eee3a7c4046a76fc847 --- /dev/null +++ b/node_modules/workbox-expiration/models/CacheTimestampsModel.js @@ -0,0 +1,185 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { openDB, deleteDB } from 'idb'; +import '../_version.js'; +const DB_NAME = 'workbox-expiration'; +const CACHE_OBJECT_STORE = 'cache-entries'; +const normalizeURL = (unNormalizedUrl) => { + const url = new URL(unNormalizedUrl, location.href); + url.hash = ''; + return url.href; +}; +/** + * Returns the timestamp model. + * + * @private + */ +class CacheTimestampsModel { + /** + * + * @param {string} cacheName + * + * @private + */ + constructor(cacheName) { + this._db = null; + this._cacheName = cacheName; + } + /** + * Performs an upgrade of indexedDB. + * + * @param {IDBPDatabase} db + * + * @private + */ + _upgradeDb(db) { + // TODO(philipwalton): EdgeHTML doesn't support arrays as a keyPath, so we + // have to use the `id` keyPath here and create our own values (a + // concatenation of `url + cacheName`) instead of simply using + // `keyPath: ['url', 'cacheName']`, which is supported in other browsers. + const objStore = db.createObjectStore(CACHE_OBJECT_STORE, { keyPath: 'id' }); + // TODO(philipwalton): once we don't have to support EdgeHTML, we can + // create a single index with the keyPath `['cacheName', 'timestamp']` + // instead of doing both these indexes. + objStore.createIndex('cacheName', 'cacheName', { unique: false }); + objStore.createIndex('timestamp', 'timestamp', { unique: false }); + } + /** + * Performs an upgrade of indexedDB and deletes deprecated DBs. + * + * @param {IDBPDatabase} db + * + * @private + */ + _upgradeDbAndDeleteOldDbs(db) { + this._upgradeDb(db); + if (this._cacheName) { + void deleteDB(this._cacheName); + } + } + /** + * @param {string} url + * @param {number} timestamp + * + * @private + */ + async setTimestamp(url, timestamp) { + url = normalizeURL(url); + const entry = { + url, + timestamp, + cacheName: this._cacheName, + // Creating an ID from the URL and cache name won't be necessary once + // Edge switches to Chromium and all browsers we support work with + // array keyPaths. + id: this._getId(url), + }; + const db = await this.getDb(); + const tx = db.transaction(CACHE_OBJECT_STORE, 'readwrite', { + durability: 'relaxed', + }); + await tx.store.put(entry); + await tx.done; + } + /** + * Returns the timestamp stored for a given URL. + * + * @param {string} url + * @return {number | undefined} + * + * @private + */ + async getTimestamp(url) { + const db = await this.getDb(); + const entry = await db.get(CACHE_OBJECT_STORE, this._getId(url)); + return entry === null || entry === void 0 ? void 0 : entry.timestamp; + } + /** + * Iterates through all the entries in the object store (from newest to + * oldest) and removes entries once either `maxCount` is reached or the + * entry's timestamp is less than `minTimestamp`. + * + * @param {number} minTimestamp + * @param {number} maxCount + * @return {Array} + * + * @private + */ + async expireEntries(minTimestamp, maxCount) { + const db = await this.getDb(); + let cursor = await db + .transaction(CACHE_OBJECT_STORE) + .store.index('timestamp') + .openCursor(null, 'prev'); + const entriesToDelete = []; + let entriesNotDeletedCount = 0; + while (cursor) { + const result = cursor.value; + // TODO(philipwalton): once we can use a multi-key index, we + // won't have to check `cacheName` here. + if (result.cacheName === this._cacheName) { + // Delete an entry if it's older than the max age or + // if we already have the max number allowed. + if ((minTimestamp && result.timestamp < minTimestamp) || + (maxCount && entriesNotDeletedCount >= maxCount)) { + // TODO(philipwalton): we should be able to delete the + // entry right here, but doing so causes an iteration + // bug in Safari stable (fixed in TP). Instead we can + // store the keys of the entries to delete, and then + // delete the separate transactions. + // https://github.com/GoogleChrome/workbox/issues/1978 + // cursor.delete(); + // We only need to return the URL, not the whole entry. + entriesToDelete.push(cursor.value); + } + else { + entriesNotDeletedCount++; + } + } + cursor = await cursor.continue(); + } + // TODO(philipwalton): once the Safari bug in the following issue is fixed, + // we should be able to remove this loop and do the entry deletion in the + // cursor loop above: + // https://github.com/GoogleChrome/workbox/issues/1978 + const urlsDeleted = []; + for (const entry of entriesToDelete) { + await db.delete(CACHE_OBJECT_STORE, entry.id); + urlsDeleted.push(entry.url); + } + return urlsDeleted; + } + /** + * Takes a URL and returns an ID that will be unique in the object store. + * + * @param {string} url + * @return {string} + * + * @private + */ + _getId(url) { + // Creating an ID from the URL and cache name won't be necessary once + // Edge switches to Chromium and all browsers we support work with + // array keyPaths. + return this._cacheName + '|' + normalizeURL(url); + } + /** + * Returns an open connection to the database. + * + * @private + */ + async getDb() { + if (!this._db) { + this._db = await openDB(DB_NAME, 1, { + upgrade: this._upgradeDbAndDeleteOldDbs.bind(this), + }); + } + return this._db; + } +} +export { CacheTimestampsModel }; diff --git a/node_modules/workbox-expiration/models/CacheTimestampsModel.mjs b/node_modules/workbox-expiration/models/CacheTimestampsModel.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a0292d8239695a5b2d0261660c715fddf8f6bfda --- /dev/null +++ b/node_modules/workbox-expiration/models/CacheTimestampsModel.mjs @@ -0,0 +1 @@ +export * from './CacheTimestampsModel.js'; \ No newline at end of file diff --git a/node_modules/workbox-expiration/package.json b/node_modules/workbox-expiration/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b58cddac88d3c12a27e32b6fae9db91a0826860e --- /dev/null +++ b/node_modules/workbox-expiration/package.json @@ -0,0 +1,32 @@ +{ + "name": "workbox-expiration", + "version": "7.4.1", + "license": "MIT", + "author": "Google's Web DevRel Team and Google's Aurora Team", + "description": "A service worker helper library that expires cached responses based on age or maximum number of entries.", + "repository": { + "type": "git", + "url": "git+https://github.com/googlechrome/workbox.git" + }, + "bugs": "https://github.com/googlechrome/workbox/issues", + "homepage": "https://github.com/GoogleChrome/workbox", + "keywords": [ + "workbox", + "workboxjs", + "service worker", + "sw", + "workbox-plugin" + ], + "workbox": { + "browserNamespace": "workbox.expiration", + "packageType": "sw" + }, + "main": "index.js", + "module": "index.mjs", + "types": "index.d.ts", + "dependencies": { + "idb": "^7.0.1", + "workbox-core": "7.4.1" + }, + "gitHead": "62b9d8ba8eb3c1a2ab8aac9d84c90cda7865d6a3" +} diff --git a/node_modules/workbox-expiration/src/CacheExpiration.ts b/node_modules/workbox-expiration/src/CacheExpiration.ts new file mode 100644 index 0000000000000000000000000000000000000000..954f4305dbb13f4202b5e214db4dcdc91c804b69 --- /dev/null +++ b/node_modules/workbox-expiration/src/CacheExpiration.ts @@ -0,0 +1,205 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {assert} from 'workbox-core/_private/assert.js'; +import {dontWaitFor} from 'workbox-core/_private/dontWaitFor.js'; +import {logger} from 'workbox-core/_private/logger.js'; +import {WorkboxError} from 'workbox-core/_private/WorkboxError.js'; + +import {CacheTimestampsModel} from './models/CacheTimestampsModel.js'; + +import './_version.js'; + +interface CacheExpirationConfig { + maxEntries?: number; + maxAgeSeconds?: number; + matchOptions?: CacheQueryOptions; +} + +/** + * The `CacheExpiration` class allows you define an expiration and / or + * limit on the number of responses stored in a + * [`Cache`](https://developer.mozilla.org/en-US/docs/Web/API/Cache). + * + * @memberof workbox-expiration + */ +class CacheExpiration { + private _isRunning = false; + private _rerunRequested = false; + private readonly _maxEntries?: number; + private readonly _maxAgeSeconds?: number; + private readonly _matchOptions?: CacheQueryOptions; + private readonly _cacheName: string; + private readonly _timestampModel: CacheTimestampsModel; + + /** + * To construct a new CacheExpiration instance you must provide at least + * one of the `config` properties. + * + * @param {string} cacheName Name of the cache to apply restrictions to. + * @param {Object} config + * @param {number} [config.maxEntries] The maximum number of entries to cache. + * Entries used the least will be removed as the maximum is reached. + * @param {number} [config.maxAgeSeconds] The maximum age of an entry before + * it's treated as stale and removed. + * @param {Object} [config.matchOptions] The [`CacheQueryOptions`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete#Parameters) + * that will be used when calling `delete()` on the cache. + */ + constructor(cacheName: string, config: CacheExpirationConfig = {}) { + if (process.env.NODE_ENV !== 'production') { + assert!.isType(cacheName, 'string', { + moduleName: 'workbox-expiration', + className: 'CacheExpiration', + funcName: 'constructor', + paramName: 'cacheName', + }); + + if (!(config.maxEntries || config.maxAgeSeconds)) { + throw new WorkboxError('max-entries-or-age-required', { + moduleName: 'workbox-expiration', + className: 'CacheExpiration', + funcName: 'constructor', + }); + } + + if (config.maxEntries) { + assert!.isType(config.maxEntries, 'number', { + moduleName: 'workbox-expiration', + className: 'CacheExpiration', + funcName: 'constructor', + paramName: 'config.maxEntries', + }); + } + + if (config.maxAgeSeconds) { + assert!.isType(config.maxAgeSeconds, 'number', { + moduleName: 'workbox-expiration', + className: 'CacheExpiration', + funcName: 'constructor', + paramName: 'config.maxAgeSeconds', + }); + } + } + + this._maxEntries = config.maxEntries; + this._maxAgeSeconds = config.maxAgeSeconds; + this._matchOptions = config.matchOptions; + this._cacheName = cacheName; + this._timestampModel = new CacheTimestampsModel(cacheName); + } + + /** + * Expires entries for the given cache and given criteria. + */ + async expireEntries(): Promise { + if (this._isRunning) { + this._rerunRequested = true; + return; + } + this._isRunning = true; + + const minTimestamp = this._maxAgeSeconds + ? Date.now() - this._maxAgeSeconds * 1000 + : 0; + + const urlsExpired = await this._timestampModel.expireEntries( + minTimestamp, + this._maxEntries, + ); + + // Delete URLs from the cache + const cache = await self.caches.open(this._cacheName); + for (const url of urlsExpired) { + await cache.delete(url, this._matchOptions); + } + + if (process.env.NODE_ENV !== 'production') { + if (urlsExpired.length > 0) { + logger.groupCollapsed( + `Expired ${urlsExpired.length} ` + + `${urlsExpired.length === 1 ? 'entry' : 'entries'} and removed ` + + `${urlsExpired.length === 1 ? 'it' : 'them'} from the ` + + `'${this._cacheName}' cache.`, + ); + logger.log( + `Expired the following ${urlsExpired.length === 1 ? 'URL' : 'URLs'}:`, + ); + urlsExpired.forEach((url) => logger.log(` ${url}`)); + logger.groupEnd(); + } else { + logger.debug(`Cache expiration ran and found no entries to remove.`); + } + } + + this._isRunning = false; + if (this._rerunRequested) { + this._rerunRequested = false; + dontWaitFor(this.expireEntries()); + } + } + + /** + * Update the timestamp for the given URL. This ensures the when + * removing entries based on maximum entries, most recently used + * is accurate or when expiring, the timestamp is up-to-date. + * + * @param {string} url + */ + async updateTimestamp(url: string): Promise { + if (process.env.NODE_ENV !== 'production') { + assert!.isType(url, 'string', { + moduleName: 'workbox-expiration', + className: 'CacheExpiration', + funcName: 'updateTimestamp', + paramName: 'url', + }); + } + + await this._timestampModel.setTimestamp(url, Date.now()); + } + + /** + * Can be used to check if a URL has expired or not before it's used. + * + * This requires a look up from IndexedDB, so can be slow. + * + * Note: This method will not remove the cached entry, call + * `expireEntries()` to remove indexedDB and Cache entries. + * + * @param {string} url + * @return {boolean} + */ + async isURLExpired(url: string): Promise { + if (!this._maxAgeSeconds) { + if (process.env.NODE_ENV !== 'production') { + throw new WorkboxError(`expired-test-without-max-age`, { + methodName: 'isURLExpired', + paramName: 'maxAgeSeconds', + }); + } + return false; + } else { + const timestamp = await this._timestampModel.getTimestamp(url); + const expireOlderThan = Date.now() - this._maxAgeSeconds * 1000; + return timestamp !== undefined ? timestamp < expireOlderThan : true; + } + } + + /** + * Removes the IndexedDB object store used to keep track of cache expiration + * metadata. + */ + async delete(): Promise { + // Make sure we don't attempt another rerun if we're called in the middle of + // a cache expiration. + this._rerunRequested = false; + await this._timestampModel.expireEntries(Infinity); // Expires all. + } +} + +export {CacheExpiration}; diff --git a/node_modules/workbox-expiration/src/ExpirationPlugin.ts b/node_modules/workbox-expiration/src/ExpirationPlugin.ts new file mode 100644 index 0000000000000000000000000000000000000000..dd646d96e8f35bd43d9094404544675e53626d3c --- /dev/null +++ b/node_modules/workbox-expiration/src/ExpirationPlugin.ts @@ -0,0 +1,302 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {assert} from 'workbox-core/_private/assert.js'; +import {cacheNames} from 'workbox-core/_private/cacheNames.js'; +import {dontWaitFor} from 'workbox-core/_private/dontWaitFor.js'; +import {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.js'; +import {logger} from 'workbox-core/_private/logger.js'; +import {registerQuotaErrorCallback} from 'workbox-core/registerQuotaErrorCallback.js'; +import {WorkboxError} from 'workbox-core/_private/WorkboxError.js'; +import {WorkboxPlugin} from 'workbox-core/types.js'; + +import {CacheExpiration} from './CacheExpiration.js'; + +import './_version.js'; + +export interface ExpirationPluginOptions { + maxEntries?: number; + maxAgeSeconds?: number; + matchOptions?: CacheQueryOptions; + purgeOnQuotaError?: boolean; +} + +/** + * This plugin can be used in a `workbox-strategy` to regularly enforce a + * limit on the age and / or the number of cached requests. + * + * It can only be used with `workbox-strategy` instances that have a + * [custom `cacheName` property set](/web/tools/workbox/guides/configure-workbox#custom_cache_names_in_strategies). + * In other words, it can't be used to expire entries in strategy that uses the + * default runtime cache name. + * + * Whenever a cached response is used or updated, this plugin will look + * at the associated cache and remove any old or extra responses. + * + * When using `maxAgeSeconds`, responses may be used *once* after expiring + * because the expiration clean up will not have occurred until *after* the + * cached response has been used. If the response has a "Date" header, then + * a light weight expiration check is performed and the response will not be + * used immediately. + * + * When using `maxEntries`, the entry least-recently requested will be removed + * from the cache first. + * + * @memberof workbox-expiration + */ +class ExpirationPlugin implements WorkboxPlugin { + private readonly _config: ExpirationPluginOptions; + private readonly _maxAgeSeconds?: number; + private _cacheExpirations: Map; + + /** + * @param {ExpirationPluginOptions} config + * @param {number} [config.maxEntries] The maximum number of entries to cache. + * Entries used the least will be removed as the maximum is reached. + * @param {number} [config.maxAgeSeconds] The maximum age of an entry before + * it's treated as stale and removed. + * @param {Object} [config.matchOptions] The [`CacheQueryOptions`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete#Parameters) + * that will be used when calling `delete()` on the cache. + * @param {boolean} [config.purgeOnQuotaError] Whether to opt this cache in to + * automatic deletion if the available storage quota has been exceeded. + */ + constructor(config: ExpirationPluginOptions = {}) { + if (process.env.NODE_ENV !== 'production') { + if (!(config.maxEntries || config.maxAgeSeconds)) { + throw new WorkboxError('max-entries-or-age-required', { + moduleName: 'workbox-expiration', + className: 'Plugin', + funcName: 'constructor', + }); + } + + if (config.maxEntries) { + assert!.isType(config.maxEntries, 'number', { + moduleName: 'workbox-expiration', + className: 'Plugin', + funcName: 'constructor', + paramName: 'config.maxEntries', + }); + } + + if (config.maxAgeSeconds) { + assert!.isType(config.maxAgeSeconds, 'number', { + moduleName: 'workbox-expiration', + className: 'Plugin', + funcName: 'constructor', + paramName: 'config.maxAgeSeconds', + }); + } + } + + this._config = config; + this._maxAgeSeconds = config.maxAgeSeconds; + this._cacheExpirations = new Map(); + + if (config.purgeOnQuotaError) { + registerQuotaErrorCallback(() => this.deleteCacheAndMetadata()); + } + } + + /** + * A simple helper method to return a CacheExpiration instance for a given + * cache name. + * + * @param {string} cacheName + * @return {CacheExpiration} + * + * @private + */ + private _getCacheExpiration(cacheName: string): CacheExpiration { + if (cacheName === cacheNames.getRuntimeName()) { + throw new WorkboxError('expire-custom-caches-only'); + } + + let cacheExpiration = this._cacheExpirations.get(cacheName); + if (!cacheExpiration) { + cacheExpiration = new CacheExpiration(cacheName, this._config); + this._cacheExpirations.set(cacheName, cacheExpiration); + } + return cacheExpiration; + } + + /** + * A "lifecycle" callback that will be triggered automatically by the + * `workbox-strategies` handlers when a `Response` is about to be returned + * from a [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache) to + * the handler. It allows the `Response` to be inspected for freshness and + * prevents it from being used if the `Response`'s `Date` header value is + * older than the configured `maxAgeSeconds`. + * + * @param {Object} options + * @param {string} options.cacheName Name of the cache the response is in. + * @param {Response} options.cachedResponse The `Response` object that's been + * read from a cache and whose freshness should be checked. + * @return {Response} Either the `cachedResponse`, if it's + * fresh, or `null` if the `Response` is older than `maxAgeSeconds`. + * + * @private + */ + cachedResponseWillBeUsed: WorkboxPlugin['cachedResponseWillBeUsed'] = async ({ + event, + request, + cacheName, + cachedResponse, + }) => { + if (!cachedResponse) { + return null; + } + + const isFresh = this._isResponseDateFresh(cachedResponse); + + // Expire entries to ensure that even if the expiration date has + // expired, it'll only be used once. + const cacheExpiration = this._getCacheExpiration(cacheName); + dontWaitFor(cacheExpiration.expireEntries()); + + // Update the metadata for the request URL to the current timestamp, + // but don't `await` it as we don't want to block the response. + const updateTimestampDone = cacheExpiration.updateTimestamp(request.url); + if (event) { + try { + event.waitUntil(updateTimestampDone); + } catch (error) { + if (process.env.NODE_ENV !== 'production') { + // The event may not be a fetch event; only log the URL if it is. + if ('request' in event) { + logger.warn( + `Unable to ensure service worker stays alive when ` + + `updating cache entry for ` + + `'${getFriendlyURL((event as FetchEvent).request.url)}'.`, + ); + } + } + } + } + + return isFresh ? cachedResponse : null; + }; + + /** + * @param {Response} cachedResponse + * @return {boolean} + * + * @private + */ + private _isResponseDateFresh(cachedResponse: Response): boolean { + if (!this._maxAgeSeconds) { + // We aren't expiring by age, so return true, it's fresh + return true; + } + + // Check if the 'date' header will suffice a quick expiration check. + // See https://github.com/GoogleChromeLabs/sw-toolbox/issues/164 for + // discussion. + const dateHeaderTimestamp = this._getDateHeaderTimestamp(cachedResponse); + if (dateHeaderTimestamp === null) { + // Unable to parse date, so assume it's fresh. + return true; + } + + // If we have a valid headerTime, then our response is fresh iff the + // headerTime plus maxAgeSeconds is greater than the current time. + const now = Date.now(); + return dateHeaderTimestamp >= now - this._maxAgeSeconds * 1000; + } + + /** + * This method will extract the data header and parse it into a useful + * value. + * + * @param {Response} cachedResponse + * @return {number|null} + * + * @private + */ + private _getDateHeaderTimestamp(cachedResponse: Response): number | null { + if (!cachedResponse.headers.has('date')) { + return null; + } + + const dateHeader = cachedResponse.headers.get('date'); + const parsedDate = new Date(dateHeader!); + const headerTime = parsedDate.getTime(); + + // If the Date header was invalid for some reason, parsedDate.getTime() + // will return NaN. + if (isNaN(headerTime)) { + return null; + } + + return headerTime; + } + + /** + * A "lifecycle" callback that will be triggered automatically by the + * `workbox-strategies` handlers when an entry is added to a cache. + * + * @param {Object} options + * @param {string} options.cacheName Name of the cache that was updated. + * @param {string} options.request The Request for the cached entry. + * + * @private + */ + cacheDidUpdate: WorkboxPlugin['cacheDidUpdate'] = async ({ + cacheName, + request, + }) => { + if (process.env.NODE_ENV !== 'production') { + assert!.isType(cacheName, 'string', { + moduleName: 'workbox-expiration', + className: 'Plugin', + funcName: 'cacheDidUpdate', + paramName: 'cacheName', + }); + assert!.isInstance(request, Request, { + moduleName: 'workbox-expiration', + className: 'Plugin', + funcName: 'cacheDidUpdate', + paramName: 'request', + }); + } + + const cacheExpiration = this._getCacheExpiration(cacheName); + await cacheExpiration.updateTimestamp(request.url); + await cacheExpiration.expireEntries(); + }; + + /** + * This is a helper method that performs two operations: + * + * - Deletes *all* the underlying Cache instances associated with this plugin + * instance, by calling caches.delete() on your behalf. + * - Deletes the metadata from IndexedDB used to keep track of expiration + * details for each Cache instance. + * + * When using cache expiration, calling this method is preferable to calling + * `caches.delete()` directly, since this will ensure that the IndexedDB + * metadata is also cleanly removed and open IndexedDB instances are deleted. + * + * Note that if you're *not* using cache expiration for a given cache, calling + * `caches.delete()` and passing in the cache's name should be sufficient. + * There is no Workbox-specific method needed for cleanup in that case. + */ + async deleteCacheAndMetadata(): Promise { + // Do this one at a time instead of all at once via `Promise.all()` to + // reduce the chance of inconsistency if a promise rejects. + for (const [cacheName, cacheExpiration] of this._cacheExpirations) { + await self.caches.delete(cacheName); + await cacheExpiration.delete(); + } + + // Reset this._cacheExpirations to its initial state. + this._cacheExpirations = new Map(); + } +} + +export {ExpirationPlugin}; diff --git a/node_modules/workbox-expiration/src/_version.ts b/node_modules/workbox-expiration/src/_version.ts new file mode 100644 index 0000000000000000000000000000000000000000..309c0f9e2eec964a924527ff1375e9bb791da716 --- /dev/null +++ b/node_modules/workbox-expiration/src/_version.ts @@ -0,0 +1,2 @@ +// @ts-ignore +try{self['workbox:expiration:7.4.1']&&_()}catch(e){} \ No newline at end of file diff --git a/node_modules/workbox-expiration/src/index.ts b/node_modules/workbox-expiration/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..398b5106d37e2d8dcbb92a8d3f918179b511c446 --- /dev/null +++ b/node_modules/workbox-expiration/src/index.ts @@ -0,0 +1,18 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {CacheExpiration} from './CacheExpiration.js'; +import {ExpirationPlugin, ExpirationPluginOptions} from './ExpirationPlugin.js'; + +import './_version.js'; + +/** + * @module workbox-expiration + */ + +export {CacheExpiration, ExpirationPlugin, ExpirationPluginOptions}; diff --git a/node_modules/workbox-expiration/src/models/CacheTimestampsModel.ts b/node_modules/workbox-expiration/src/models/CacheTimestampsModel.ts new file mode 100644 index 0000000000000000000000000000000000000000..44229258baac34e8859175a3f44119aa60e3ec0c --- /dev/null +++ b/node_modules/workbox-expiration/src/models/CacheTimestampsModel.ts @@ -0,0 +1,224 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {openDB, DBSchema, IDBPDatabase, deleteDB} from 'idb'; +import '../_version.js'; + +const DB_NAME = 'workbox-expiration'; +const CACHE_OBJECT_STORE = 'cache-entries'; + +const normalizeURL = (unNormalizedUrl: string) => { + const url = new URL(unNormalizedUrl, location.href); + url.hash = ''; + + return url.href; +}; + +interface CacheTimestampsModelEntry { + id: string; + cacheName: string; + url: string; + timestamp: number; +} + +interface CacheDbSchema extends DBSchema { + 'cache-entries': { + key: string; + value: CacheTimestampsModelEntry; + indexes: {cacheName: string; timestamp: number}; + }; +} + +/** + * Returns the timestamp model. + * + * @private + */ +class CacheTimestampsModel { + private readonly _cacheName: string; + private _db: IDBPDatabase | null = null; + + /** + * + * @param {string} cacheName + * + * @private + */ + constructor(cacheName: string) { + this._cacheName = cacheName; + } + + /** + * Performs an upgrade of indexedDB. + * + * @param {IDBPDatabase} db + * + * @private + */ + private _upgradeDb(db: IDBPDatabase) { + // TODO(philipwalton): EdgeHTML doesn't support arrays as a keyPath, so we + // have to use the `id` keyPath here and create our own values (a + // concatenation of `url + cacheName`) instead of simply using + // `keyPath: ['url', 'cacheName']`, which is supported in other browsers. + const objStore = db.createObjectStore(CACHE_OBJECT_STORE, {keyPath: 'id'}); + + // TODO(philipwalton): once we don't have to support EdgeHTML, we can + // create a single index with the keyPath `['cacheName', 'timestamp']` + // instead of doing both these indexes. + objStore.createIndex('cacheName', 'cacheName', {unique: false}); + objStore.createIndex('timestamp', 'timestamp', {unique: false}); + } + + /** + * Performs an upgrade of indexedDB and deletes deprecated DBs. + * + * @param {IDBPDatabase} db + * + * @private + */ + private _upgradeDbAndDeleteOldDbs(db: IDBPDatabase) { + this._upgradeDb(db); + if (this._cacheName) { + void deleteDB(this._cacheName); + } + } + + /** + * @param {string} url + * @param {number} timestamp + * + * @private + */ + async setTimestamp(url: string, timestamp: number): Promise { + url = normalizeURL(url); + + const entry: CacheTimestampsModelEntry = { + url, + timestamp, + cacheName: this._cacheName, + // Creating an ID from the URL and cache name won't be necessary once + // Edge switches to Chromium and all browsers we support work with + // array keyPaths. + id: this._getId(url), + }; + const db = await this.getDb(); + const tx = db.transaction(CACHE_OBJECT_STORE, 'readwrite', { + durability: 'relaxed', + }); + await tx.store.put(entry); + await tx.done; + } + + /** + * Returns the timestamp stored for a given URL. + * + * @param {string} url + * @return {number | undefined} + * + * @private + */ + async getTimestamp(url: string): Promise { + const db = await this.getDb(); + const entry = await db.get(CACHE_OBJECT_STORE, this._getId(url)); + return entry?.timestamp; + } + + /** + * Iterates through all the entries in the object store (from newest to + * oldest) and removes entries once either `maxCount` is reached or the + * entry's timestamp is less than `minTimestamp`. + * + * @param {number} minTimestamp + * @param {number} maxCount + * @return {Array} + * + * @private + */ + async expireEntries( + minTimestamp: number, + maxCount?: number, + ): Promise { + const db = await this.getDb(); + let cursor = await db + .transaction(CACHE_OBJECT_STORE) + .store.index('timestamp') + .openCursor(null, 'prev'); + const entriesToDelete: CacheTimestampsModelEntry[] = []; + let entriesNotDeletedCount = 0; + while (cursor) { + const result = cursor.value; + // TODO(philipwalton): once we can use a multi-key index, we + // won't have to check `cacheName` here. + if (result.cacheName === this._cacheName) { + // Delete an entry if it's older than the max age or + // if we already have the max number allowed. + if ( + (minTimestamp && result.timestamp < minTimestamp) || + (maxCount && entriesNotDeletedCount >= maxCount) + ) { + // TODO(philipwalton): we should be able to delete the + // entry right here, but doing so causes an iteration + // bug in Safari stable (fixed in TP). Instead we can + // store the keys of the entries to delete, and then + // delete the separate transactions. + // https://github.com/GoogleChrome/workbox/issues/1978 + // cursor.delete(); + + // We only need to return the URL, not the whole entry. + entriesToDelete.push(cursor.value); + } else { + entriesNotDeletedCount++; + } + } + cursor = await cursor.continue(); + } + + // TODO(philipwalton): once the Safari bug in the following issue is fixed, + // we should be able to remove this loop and do the entry deletion in the + // cursor loop above: + // https://github.com/GoogleChrome/workbox/issues/1978 + const urlsDeleted: string[] = []; + for (const entry of entriesToDelete) { + await db.delete(CACHE_OBJECT_STORE, entry.id); + urlsDeleted.push(entry.url); + } + + return urlsDeleted; + } + + /** + * Takes a URL and returns an ID that will be unique in the object store. + * + * @param {string} url + * @return {string} + * + * @private + */ + private _getId(url: string): string { + // Creating an ID from the URL and cache name won't be necessary once + // Edge switches to Chromium and all browsers we support work with + // array keyPaths. + return this._cacheName + '|' + normalizeURL(url); + } + + /** + * Returns an open connection to the database. + * + * @private + */ + private async getDb() { + if (!this._db) { + this._db = await openDB(DB_NAME, 1, { + upgrade: this._upgradeDbAndDeleteOldDbs.bind(this), + }); + } + return this._db; + } +} + +export {CacheTimestampsModel}; diff --git a/node_modules/workbox-expiration/tsconfig.json b/node_modules/workbox-expiration/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..3bb2772b586c4d0ceee3d014e64dba7aafbdd570 --- /dev/null +++ b/node_modules/workbox-expiration/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tsconfig", + "compilerOptions": { + "composite": true, + "outDir": "./", + "rootDir": "./src", + "tsBuildInfoFile": "./tsconfig.tsbuildinfo" + }, + "include": ["src/**/*.ts"], + "references": [{"path": "../workbox-core/"}] +} diff --git a/node_modules/workbox-google-analytics/LICENSE b/node_modules/workbox-google-analytics/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..845b545fd0f5031a944cda8cf9018eb066500040 --- /dev/null +++ b/node_modules/workbox-google-analytics/LICENSE @@ -0,0 +1,19 @@ +Copyright 2018 Google LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/workbox-google-analytics/README.md b/node_modules/workbox-google-analytics/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3678fb2f6c292278d821f7dbe92df1c020b211fb --- /dev/null +++ b/node_modules/workbox-google-analytics/README.md @@ -0,0 +1 @@ +This module's documentation can be found at https://developers.google.com/web/tools/workbox/modules/workbox-google-analytics diff --git a/node_modules/workbox-google-analytics/_version.d.ts b/node_modules/workbox-google-analytics/_version.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/workbox-google-analytics/_version.js b/node_modules/workbox-google-analytics/_version.js new file mode 100644 index 0000000000000000000000000000000000000000..efe1bbb494d386d4523b32c0c93e5515bb4c4719 --- /dev/null +++ b/node_modules/workbox-google-analytics/_version.js @@ -0,0 +1,6 @@ +"use strict"; +// @ts-ignore +try { + self['workbox:google-analytics:7.4.0'] && _(); +} +catch (e) { } diff --git a/node_modules/workbox-google-analytics/_version.mjs b/node_modules/workbox-google-analytics/_version.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4d800b8449e0997a24c308ddc7f309a994737ea5 --- /dev/null +++ b/node_modules/workbox-google-analytics/_version.mjs @@ -0,0 +1 @@ +try{self['workbox:google-analytics:7.4.1']&&_()}catch(e){}// eslint-disable-line \ No newline at end of file diff --git a/node_modules/workbox-google-analytics/build/workbox-offline-ga.dev.js b/node_modules/workbox-google-analytics/build/workbox-offline-ga.dev.js new file mode 100644 index 0000000000000000000000000000000000000000..e6160f29c5955d0f6d24dda87849e2098e2dc0fc --- /dev/null +++ b/node_modules/workbox-google-analytics/build/workbox-offline-ga.dev.js @@ -0,0 +1,210 @@ +this.workbox = this.workbox || {}; +this.workbox.googleAnalytics = (function (exports, BackgroundSyncPlugin_js, cacheNames_js, getFriendlyURL_js, logger_js, Route_js, Router_js, NetworkFirst_js, NetworkOnly_js) { + 'use strict'; + + // @ts-ignore + try { + self['workbox:google-analytics:7.4.0'] && _(); + } catch (e) {} + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + const QUEUE_NAME = 'workbox-google-analytics'; + const MAX_RETENTION_TIME = 60 * 48; // Two days in minutes + const GOOGLE_ANALYTICS_HOST = 'www.google-analytics.com'; + const GTM_HOST = 'www.googletagmanager.com'; + const ANALYTICS_JS_PATH = '/analytics.js'; + const GTAG_JS_PATH = '/gtag/js'; + const GTM_JS_PATH = '/gtm.js'; + // This RegExp matches all known Measurement Protocol single-hit collect + // endpoints. Most of the time the default path (/collect) is used, but + // occasionally an experimental endpoint is used when testing new features, + // (e.g. /r/collect or /j/collect) + const COLLECT_PATHS_REGEX = /^\/(\w+\/)?collect/; + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Creates the requestWillDequeue callback to be used with the background + * sync plugin. The callback takes the failed request and adds the + * `qt` param based on the current time, as well as applies any other + * user-defined hit modifications. + * + * @param {Object} config See {@link workbox-google-analytics.initialize}. + * @return {Function} The requestWillDequeue callback function. + * + * @private + */ + const createOnSyncCallback = config => { + return async ({ + queue + }) => { + let entry; + while (entry = await queue.shiftRequest()) { + const { + request, + timestamp + } = entry; + const url = new URL(request.url); + try { + // Measurement protocol requests can set their payload parameters in + // either the URL query string (for GET requests) or the POST body. + const params = request.method === 'POST' ? new URLSearchParams(await request.clone().text()) : url.searchParams; + // Calculate the qt param, accounting for the fact that an existing + // qt param may be present and should be updated rather than replaced. + const originalHitTime = timestamp - (Number(params.get('qt')) || 0); + const queueTime = Date.now() - originalHitTime; + // Set the qt param prior to applying hitFilter or parameterOverrides. + params.set('qt', String(queueTime)); + // Apply `parameterOverrides`, if set. + if (config.parameterOverrides) { + for (const param of Object.keys(config.parameterOverrides)) { + const value = config.parameterOverrides[param]; + params.set(param, value); + } + } + // Apply `hitFilter`, if set. + if (typeof config.hitFilter === 'function') { + config.hitFilter.call(null, params); + } + // Retry the fetch. Ignore URL search params from the URL as they're + // now in the post body. + await fetch(new Request(url.origin + url.pathname, { + body: params.toString(), + method: 'POST', + mode: 'cors', + credentials: 'omit', + headers: { + 'Content-Type': 'text/plain' + } + })); + if ("dev" !== 'production') { + logger_js.logger.log(`Request for '${getFriendlyURL_js.getFriendlyURL(url.href)}' ` + `has been replayed`); + } + } catch (err) { + await queue.unshiftRequest(entry); + { + logger_js.logger.log(`Request for '${getFriendlyURL_js.getFriendlyURL(url.href)}' ` + `failed to replay, putting it back in the queue.`); + } + throw err; + } + } + { + logger_js.logger.log(`All Google Analytics request successfully replayed; ` + `the queue is now empty!`); + } + }; + }; + /** + * Creates GET and POST routes to catch failed Measurement Protocol hits. + * + * @param {BackgroundSyncPlugin} bgSyncPlugin + * @return {Array} The created routes. + * + * @private + */ + const createCollectRoutes = bgSyncPlugin => { + const match = ({ + url + }) => url.hostname === GOOGLE_ANALYTICS_HOST && COLLECT_PATHS_REGEX.test(url.pathname); + const handler = new NetworkOnly_js.NetworkOnly({ + plugins: [bgSyncPlugin] + }); + return [new Route_js.Route(match, handler, 'GET'), new Route_js.Route(match, handler, 'POST')]; + }; + /** + * Creates a route with a network first strategy for the analytics.js script. + * + * @param {string} cacheName + * @return {Route} The created route. + * + * @private + */ + const createAnalyticsJsRoute = cacheName => { + const match = ({ + url + }) => url.hostname === GOOGLE_ANALYTICS_HOST && url.pathname === ANALYTICS_JS_PATH; + const handler = new NetworkFirst_js.NetworkFirst({ + cacheName + }); + return new Route_js.Route(match, handler, 'GET'); + }; + /** + * Creates a route with a network first strategy for the gtag.js script. + * + * @param {string} cacheName + * @return {Route} The created route. + * + * @private + */ + const createGtagJsRoute = cacheName => { + const match = ({ + url + }) => url.hostname === GTM_HOST && url.pathname === GTAG_JS_PATH; + const handler = new NetworkFirst_js.NetworkFirst({ + cacheName + }); + return new Route_js.Route(match, handler, 'GET'); + }; + /** + * Creates a route with a network first strategy for the gtm.js script. + * + * @param {string} cacheName + * @return {Route} The created route. + * + * @private + */ + const createGtmJsRoute = cacheName => { + const match = ({ + url + }) => url.hostname === GTM_HOST && url.pathname === GTM_JS_PATH; + const handler = new NetworkFirst_js.NetworkFirst({ + cacheName + }); + return new Route_js.Route(match, handler, 'GET'); + }; + /** + * @param {Object=} [options] + * @param {Object} [options.cacheName] The cache name to store and retrieve + * analytics.js. Defaults to the cache names provided by `workbox-core`. + * @param {Object} [options.parameterOverrides] + * [Measurement Protocol parameters](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters), + * expressed as key/value pairs, to be added to replayed Google Analytics + * requests. This can be used to, e.g., set a custom dimension indicating + * that the request was replayed. + * @param {Function} [options.hitFilter] A function that allows you to modify + * the hit parameters prior to replaying + * the hit. The function is invoked with the original hit's URLSearchParams + * object as its only argument. + * + * @memberof workbox-google-analytics + */ + const initialize = (options = {}) => { + const cacheName = cacheNames_js.cacheNames.getGoogleAnalyticsName(options.cacheName); + const bgSyncPlugin = new BackgroundSyncPlugin_js.BackgroundSyncPlugin(QUEUE_NAME, { + maxRetentionTime: MAX_RETENTION_TIME, + onSync: createOnSyncCallback(options) + }); + const routes = [createGtmJsRoute(cacheName), createAnalyticsJsRoute(cacheName), createGtagJsRoute(cacheName), ...createCollectRoutes(bgSyncPlugin)]; + const router = new Router_js.Router(); + for (const route of routes) { + router.registerRoute(route); + } + router.addFetchListener(); + }; + + exports.initialize = initialize; + + return exports; + +})({}, workbox.backgroundSync, workbox.core._private, workbox.core._private, workbox.core._private, workbox.routing, workbox.routing, workbox.strategies, workbox.strategies); +//# sourceMappingURL=workbox-offline-ga.dev.js.map diff --git a/node_modules/workbox-google-analytics/build/workbox-offline-ga.dev.js.map b/node_modules/workbox-google-analytics/build/workbox-offline-ga.dev.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d2bc783b78da2d4c491ee04408c06377e8c4d06a --- /dev/null +++ b/node_modules/workbox-google-analytics/build/workbox-offline-ga.dev.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-offline-ga.dev.js","sources":["../_version.js","../utils/constants.js","../initialize.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:google-analytics:7.4.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 '../_version.js';\nexport const QUEUE_NAME = 'workbox-google-analytics';\nexport const MAX_RETENTION_TIME = 60 * 48; // Two days in minutes\nexport const GOOGLE_ANALYTICS_HOST = 'www.google-analytics.com';\nexport const GTM_HOST = 'www.googletagmanager.com';\nexport const ANALYTICS_JS_PATH = '/analytics.js';\nexport const GTAG_JS_PATH = '/gtag/js';\nexport const GTM_JS_PATH = '/gtm.js';\nexport const COLLECT_DEFAULT_PATH = '/collect';\n// This RegExp matches all known Measurement Protocol single-hit collect\n// endpoints. Most of the time the default path (/collect) is used, but\n// occasionally an experimental endpoint is used when testing new features,\n// (e.g. /r/collect or /j/collect)\nexport const COLLECT_PATHS_REGEX = /^\\/(\\w+\\/)?collect/;\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 { BackgroundSyncPlugin } from 'workbox-background-sync/BackgroundSyncPlugin.js';\nimport { cacheNames } from 'workbox-core/_private/cacheNames.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { Route } from 'workbox-routing/Route.js';\nimport { Router } from 'workbox-routing/Router.js';\nimport { NetworkFirst } from 'workbox-strategies/NetworkFirst.js';\nimport { NetworkOnly } from 'workbox-strategies/NetworkOnly.js';\nimport { QUEUE_NAME, MAX_RETENTION_TIME, GOOGLE_ANALYTICS_HOST, GTM_HOST, ANALYTICS_JS_PATH, GTAG_JS_PATH, GTM_JS_PATH, COLLECT_PATHS_REGEX, } from './utils/constants.js';\nimport './_version.js';\n/**\n * Creates the requestWillDequeue callback to be used with the background\n * sync plugin. The callback takes the failed request and adds the\n * `qt` param based on the current time, as well as applies any other\n * user-defined hit modifications.\n *\n * @param {Object} config See {@link workbox-google-analytics.initialize}.\n * @return {Function} The requestWillDequeue callback function.\n *\n * @private\n */\nconst createOnSyncCallback = (config) => {\n return async ({ queue }) => {\n let entry;\n while ((entry = await queue.shiftRequest())) {\n const { request, timestamp } = entry;\n const url = new URL(request.url);\n try {\n // Measurement protocol requests can set their payload parameters in\n // either the URL query string (for GET requests) or the POST body.\n const params = request.method === 'POST'\n ? new URLSearchParams(await request.clone().text())\n : url.searchParams;\n // Calculate the qt param, accounting for the fact that an existing\n // qt param may be present and should be updated rather than replaced.\n const originalHitTime = timestamp - (Number(params.get('qt')) || 0);\n const queueTime = Date.now() - originalHitTime;\n // Set the qt param prior to applying hitFilter or parameterOverrides.\n params.set('qt', String(queueTime));\n // Apply `parameterOverrides`, if set.\n if (config.parameterOverrides) {\n for (const param of Object.keys(config.parameterOverrides)) {\n const value = config.parameterOverrides[param];\n params.set(param, value);\n }\n }\n // Apply `hitFilter`, if set.\n if (typeof config.hitFilter === 'function') {\n config.hitFilter.call(null, params);\n }\n // Retry the fetch. Ignore URL search params from the URL as they're\n // now in the post body.\n await fetch(new Request(url.origin + url.pathname, {\n body: params.toString(),\n method: 'POST',\n mode: 'cors',\n credentials: 'omit',\n headers: { 'Content-Type': 'text/plain' },\n }));\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Request for '${getFriendlyURL(url.href)}' ` + `has been replayed`);\n }\n }\n catch (err) {\n await queue.unshiftRequest(entry);\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Request for '${getFriendlyURL(url.href)}' ` +\n `failed to replay, putting it back in the queue.`);\n }\n throw err;\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`All Google Analytics request successfully replayed; ` +\n `the queue is now empty!`);\n }\n };\n};\n/**\n * Creates GET and POST routes to catch failed Measurement Protocol hits.\n *\n * @param {BackgroundSyncPlugin} bgSyncPlugin\n * @return {Array} The created routes.\n *\n * @private\n */\nconst createCollectRoutes = (bgSyncPlugin) => {\n const match = ({ url }) => url.hostname === GOOGLE_ANALYTICS_HOST &&\n COLLECT_PATHS_REGEX.test(url.pathname);\n const handler = new NetworkOnly({\n plugins: [bgSyncPlugin],\n });\n return [new Route(match, handler, 'GET'), new Route(match, handler, 'POST')];\n};\n/**\n * Creates a route with a network first strategy for the analytics.js script.\n *\n * @param {string} cacheName\n * @return {Route} The created route.\n *\n * @private\n */\nconst createAnalyticsJsRoute = (cacheName) => {\n const match = ({ url }) => url.hostname === GOOGLE_ANALYTICS_HOST &&\n url.pathname === ANALYTICS_JS_PATH;\n const handler = new NetworkFirst({ cacheName });\n return new Route(match, handler, 'GET');\n};\n/**\n * Creates a route with a network first strategy for the gtag.js script.\n *\n * @param {string} cacheName\n * @return {Route} The created route.\n *\n * @private\n */\nconst createGtagJsRoute = (cacheName) => {\n const match = ({ url }) => url.hostname === GTM_HOST && url.pathname === GTAG_JS_PATH;\n const handler = new NetworkFirst({ cacheName });\n return new Route(match, handler, 'GET');\n};\n/**\n * Creates a route with a network first strategy for the gtm.js script.\n *\n * @param {string} cacheName\n * @return {Route} The created route.\n *\n * @private\n */\nconst createGtmJsRoute = (cacheName) => {\n const match = ({ url }) => url.hostname === GTM_HOST && url.pathname === GTM_JS_PATH;\n const handler = new NetworkFirst({ cacheName });\n return new Route(match, handler, 'GET');\n};\n/**\n * @param {Object=} [options]\n * @param {Object} [options.cacheName] The cache name to store and retrieve\n * analytics.js. Defaults to the cache names provided by `workbox-core`.\n * @param {Object} [options.parameterOverrides]\n * [Measurement Protocol parameters](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters),\n * expressed as key/value pairs, to be added to replayed Google Analytics\n * requests. This can be used to, e.g., set a custom dimension indicating\n * that the request was replayed.\n * @param {Function} [options.hitFilter] A function that allows you to modify\n * the hit parameters prior to replaying\n * the hit. The function is invoked with the original hit's URLSearchParams\n * object as its only argument.\n *\n * @memberof workbox-google-analytics\n */\nconst initialize = (options = {}) => {\n const cacheName = cacheNames.getGoogleAnalyticsName(options.cacheName);\n const bgSyncPlugin = new BackgroundSyncPlugin(QUEUE_NAME, {\n maxRetentionTime: MAX_RETENTION_TIME,\n onSync: createOnSyncCallback(options),\n });\n const routes = [\n createGtmJsRoute(cacheName),\n createAnalyticsJsRoute(cacheName),\n createGtagJsRoute(cacheName),\n ...createCollectRoutes(bgSyncPlugin),\n ];\n const router = new Router();\n for (const route of routes) {\n router.registerRoute(route);\n }\n router.addFetchListener();\n};\nexport { initialize };\n"],"names":["self","_","e","QUEUE_NAME","MAX_RETENTION_TIME","GOOGLE_ANALYTICS_HOST","GTM_HOST","ANALYTICS_JS_PATH","GTAG_JS_PATH","GTM_JS_PATH","COLLECT_PATHS_REGEX","createOnSyncCallback","config","queue","entry","shiftRequest","request","timestamp","url","URL","params","method","URLSearchParams","clone","text","searchParams","originalHitTime","Number","get","queueTime","Date","now","set","String","parameterOverrides","param","Object","keys","value","hitFilter","call","fetch","Request","origin","pathname","body","toString","mode","credentials","headers","process","logger","log","getFriendlyURL","href","err","unshiftRequest","createCollectRoutes","bgSyncPlugin","match","hostname","test","handler","NetworkOnly","plugins","Route","createAnalyticsJsRoute","cacheName","NetworkFirst","createGtagJsRoute","createGtmJsRoute","initialize","options","cacheNames","getGoogleAnalyticsName","BackgroundSyncPlugin","maxRetentionTime","onSync","routes","router","Router","route","registerRoute","addFetchListener"],"mappings":";;;;IACA;IACA,IAAI;IACAA,EAAAA,IAAI,CAAC,gCAAgC,CAAC,IAAIC,CAAC,EAAE;IACjD,CAAC,CACD,OAAOC,CAAC,EAAE,CAAE;;ICLZ;IACA;;IAEA;IACA;IACA;IACA;IAEO,MAAMC,UAAU,GAAG,0BAA0B;IAC7C,MAAMC,kBAAkB,GAAG,EAAE,GAAG,EAAE,CAAC;IACnC,MAAMC,qBAAqB,GAAG,0BAA0B;IACxD,MAAMC,QAAQ,GAAG,0BAA0B;IAC3C,MAAMC,iBAAiB,GAAG,eAAe;IACzC,MAAMC,YAAY,GAAG,UAAU;IAC/B,MAAMC,WAAW,GAA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;IACA;IACA,MAAMQ,gBAAgB,GAAIH,SAAS,IAAK;MACpC,MAAMR,KAAK,GAAGA,CAAC;IAAEzC,IAAAA;OAAK,KAAKA,GAAG,CAAC0C,QAAQ,KAAKtD,QAAQ,IAAIY,GAAG,CAAC0B,QAAQ,KAAKnC,WAAW;IACpF,EAAA,MAAMqD,OAAO,GAAG,IAAIM,4BAAY,CAAC;IAAED,IAAAA;IAAU,GAAC,CAAC;MAC/C,OAAO,IAAIF,cAAK,CAACN,KAAK,EAAEG,OAAO,EAAE,KAAK,CAAC;IAC3C,CAAC;IACD;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;AACA,UAAMS,UAAU,GAAGA,CAACC,OAAO,GAAG,EAAE,KAAK;MACjC,MAAML,SAAS,GAAGM,wBAAU,CAACC,sBAAsB,CAACF,OAAO,CAACL,SAAS,CAAC;IACtE,EAAA,MAAMT,YAAY,GAAG,IAAIiB,4CAAoB,CAACxE,UAAU,EAAE;IACtDyE,IAAAA,gBAAgB,EAAExE,kBAAkB;QACpCyE,MAAM,EAAElE,oBAAoB,CAAC6D,OAAO;IACxC,GAAC,CAAC;MACF,MAAMM,MAAM,GAAG,CACXR,gBAAgB,CAACH,SAAS,CAAC,EAC3BD,sBAAsB,CAACC,SAAS,CAAC,EACjCE,iBAAiB,CAACF,SAAS,CAAC,EAC5B,GAAGV,mBAAmB,CAACC,YAAY,CAAC,CACvC;IACD,EAAA,MAAMqB,MAAM,GAAG,IAAIC,gBAAM,EAAE;IAC3B,EAAA,KAAK,MAAMC,KAAK,IAAIH,MAAM,EAAE;IACxBC,IAAAA,MAAM,CAACG,aAAa,CAACD,KAAK,CAAC;IAC/B,EAAA;MACAF,MAAM,CAACI,gBAAgB,EAAE;IAC7B;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/workbox-google-analytics/build/workbox-offline-ga.prod.js b/node_modules/workbox-google-analytics/build/workbox-offline-ga.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..5c0a4d8c6d63a80e670a7adfc4c7847ec947c1e3 --- /dev/null +++ b/node_modules/workbox-google-analytics/build/workbox-offline-ga.prod.js @@ -0,0 +1,2 @@ +this.workbox=this.workbox||{},this.workbox.googleAnalytics=function(t,e,o,n,r,c,a,w,s){"use strict";try{self["workbox:google-analytics:7.4.0"]&&_()}catch(t){}const i="www.google-analytics.com",l="www.googletagmanager.com",u=/^\/(\w+\/)?collect/,m=t=>{const e=({url:t})=>t.hostname===i&&u.test(t.pathname),o=new s.NetworkOnly({plugins:[t]});return[new c.Route(e,o,"GET"),new c.Route(e,o,"POST")]},g=t=>{const e=new w.NetworkFirst({cacheName:t});return new c.Route((({url:t})=>t.hostname===i&&"/analytics.js"===t.pathname),e,"GET")},h=t=>{const e=new w.NetworkFirst({cacheName:t});return new c.Route((({url:t})=>t.hostname===l&&"/gtag/js"===t.pathname),e,"GET")},b=t=>{const e=new w.NetworkFirst({cacheName:t});return new c.Route((({url:t})=>t.hostname===l&&"/gtm.js"===t.pathname),e,"GET")};return t.initialize=(t={})=>{const n=o.cacheNames.getGoogleAnalyticsName(t.cacheName),r=new e.BackgroundSyncPlugin("workbox-google-analytics",{maxRetentionTime:2880,onSync:(c=t,async({queue:t})=>{let e;for(;e=await t.shiftRequest();){const{request:o,timestamp:n}=e,r=new URL(o.url);try{const t="POST"===o.method?new URLSearchParams(await o.clone().text()):r.searchParams,e=n-(Number(t.get("qt"))||0),a=Date.now()-e;if(t.set("qt",String(a)),c.parameterOverrides)for(const e of Object.keys(c.parameterOverrides)){const o=c.parameterOverrides[e];t.set(e,o)}"function"==typeof c.hitFilter&&c.hitFilter.call(null,t),await fetch(new Request(r.origin+r.pathname,{body:t.toString(),method:"POST",mode:"cors",credentials:"omit",headers:{"Content-Type":"text/plain"}}))}catch(o){throw await t.unshiftRequest(e),o}}})});var c;const w=[b(n),g(n),h(n),...m(r)],s=new a.Router;for(const t of w)s.registerRoute(t);s.addFetchListener()},t}({},workbox.backgroundSync,workbox.core._private,workbox.core._private,workbox.core._private,workbox.routing,workbox.routing,workbox.strategies,workbox.strategies); +//# sourceMappingURL=workbox-offline-ga.prod.js.map diff --git a/node_modules/workbox-google-analytics/build/workbox-offline-ga.prod.js.map b/node_modules/workbox-google-analytics/build/workbox-offline-ga.prod.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a97567b2433d00fbf71bf416faf69b68632d63b2 --- /dev/null +++ b/node_modules/workbox-google-analytics/build/workbox-offline-ga.prod.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-offline-ga.prod.js","sources":["../_version.js","../utils/constants.js","../initialize.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:google-analytics:7.4.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 '../_version.js';\nexport const QUEUE_NAME = 'workbox-google-analytics';\nexport const MAX_RETENTION_TIME = 60 * 48; // Two days in minutes\nexport const GOOGLE_ANALYTICS_HOST = 'www.google-analytics.com';\nexport const GTM_HOST = 'www.googletagmanager.com';\nexport const ANALYTICS_JS_PATH = '/analytics.js';\nexport const GTAG_JS_PATH = '/gtag/js';\nexport const GTM_JS_PATH = '/gtm.js';\nexport const COLLECT_DEFAULT_PATH = '/collect';\n// This RegExp matches all known Measurement Protocol single-hit collect\n// endpoints. Most of the time the default path (/collect) is used, but\n// occasionally an experimental endpoint is used when testing new features,\n// (e.g. /r/collect or /j/collect)\nexport const COLLECT_PATHS_REGEX = /^\\/(\\w+\\/)?collect/;\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 { BackgroundSyncPlugin } from 'workbox-background-sync/BackgroundSyncPlugin.js';\nimport { cacheNames } from 'workbox-core/_private/cacheNames.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { Route } from 'workbox-routing/Route.js';\nimport { Router } from 'workbox-routing/Router.js';\nimport { NetworkFirst } from 'workbox-strategies/NetworkFirst.js';\nimport { NetworkOnly } from 'workbox-strategies/NetworkOnly.js';\nimport { QUEUE_NAME, MAX_RETENTION_TIME, GOOGLE_ANALYTICS_HOST, GTM_HOST, ANALYTICS_JS_PATH, GTAG_JS_PATH, GTM_JS_PATH, COLLECT_PATHS_REGEX, } from './utils/constants.js';\nimport './_version.js';\n/**\n * Creates the requestWillDequeue callback to be used with the background\n * sync plugin. The callback takes the failed request and adds the\n * `qt` param based on the current time, as well as applies any other\n * user-defined hit modifications.\n *\n * @param {Object} config See {@link workbox-google-analytics.initialize}.\n * @return {Function} The requestWillDequeue callback function.\n *\n * @private\n */\nconst createOnSyncCallback = (config) => {\n return async ({ queue }) => {\n let entry;\n while ((entry = await queue.shiftRequest())) {\n const { request, timestamp } = entry;\n const url = new URL(request.url);\n try {\n // Measurement protocol requests can set their payload parameters in\n // either the URL query string (for GET requests) or the POST body.\n const params = request.method === 'POST'\n ? new URLSearchParams(await request.clone().text())\n : url.searchParams;\n // Calculate the qt param, accounting for the fact that an existing\n // qt param may be present and should be updated rather than replaced.\n const originalHitTime = timestamp - (Number(params.get('qt')) || 0);\n const queueTime = Date.now() - originalHitTime;\n // Set the qt param prior to applying hitFilter or parameterOverrides.\n params.set('qt', String(queueTime));\n // Apply `parameterOverrides`, if set.\n if (config.parameterOverrides) {\n for (const param of Object.keys(config.parameterOverrides)) {\n const value = config.parameterOverrides[param];\n params.set(param, value);\n }\n }\n // Apply `hitFilter`, if set.\n if (typeof config.hitFilter === 'function') {\n config.hitFilter.call(null, params);\n }\n // Retry the fetch. Ignore URL search params from the URL as they're\n // now in the post body.\n await fetch(new Request(url.origin + url.pathname, {\n body: params.toString(),\n method: 'POST',\n mode: 'cors',\n credentials: 'omit',\n headers: { 'Content-Type': 'text/plain' },\n }));\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Request for '${getFriendlyURL(url.href)}' ` + `has been replayed`);\n }\n }\n catch (err) {\n await queue.unshiftRequest(entry);\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Request for '${getFriendlyURL(url.href)}' ` +\n `failed to replay, putting it back in the queue.`);\n }\n throw err;\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`All Google Analytics request successfully replayed; ` +\n `the queue is now empty!`);\n }\n };\n};\n/**\n * Creates GET and POST routes to catch failed Measurement Protocol hits.\n *\n * @param {BackgroundSyncPlugin} bgSyncPlugin\n * @return {Array} The created routes.\n *\n * @private\n */\nconst createCollectRoutes = (bgSyncPlugin) => {\n const match = ({ url }) => url.hostname === GOOGLE_ANALYTICS_HOST &&\n COLLECT_PATHS_REGEX.test(url.pathname);\n const handler = new NetworkOnly({\n plugins: [bgSyncPlugin],\n });\n return [new Route(match, handler, 'GET'), new Route(match, handler, 'POST')];\n};\n/**\n * Creates a route with a network first strategy for the analytics.js script.\n *\n * @param {string} cacheName\n * @return {Route} The created route.\n *\n * @private\n */\nconst createAnalyticsJsRoute = (cacheName) => {\n const match = ({ url }) => url.hostname === GOOGLE_ANALYTICS_HOST &&\n url.pathname === ANALYTICS_JS_PATH;\n const handler = new NetworkFirst({ cacheName });\n return new Route(match, handler, 'GET');\n};\n/**\n * Creates a route with a network first strategy for the gtag.js script.\n *\n * @param {string} cacheName\n * @return {Route} The created route.\n *\n * @private\n */\nconst createGtagJsRoute = (cacheName) => {\n const match = ({ url }) => url.hostname === GTM_HOST && url.pathname === GTAG_JS_PATH;\n const handler = new NetworkFirst({ cacheName });\n return new Route(match, handler, 'GET');\n};\n/**\n * Creates a route with a network first strategy for the gtm.js script.\n *\n * @param {string} cacheName\n * @return {Route} The created route.\n *\n * @private\n */\nconst createGtmJsRoute = (cacheName) => {\n const match = ({ url }) => url.hostname === GTM_HOST && url.pathname === GTM_JS_PATH;\n const handler = new NetworkFirst({ cacheName });\n return new Route(match, handler, 'GET');\n};\n/**\n * @param {Object=} [options]\n * @param {Object} [options.cacheName] The cache name to store and retrieve\n * analytics.js. Defaults to the cache names provided by `workbox-core`.\n * @param {Object} [options.parameterOverrides]\n * [Measurement Protocol parameters](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters),\n * expressed as key/value pairs, to be added to replayed Google Analytics\n * requests. This can be used to, e.g., set a custom dimension indicating\n * that the request was replayed.\n * @param {Function} [options.hitFilter] A function that allows you to modify\n * the hit parameters prior to replaying\n * the hit. The function is invoked with the original hit's URLSearchParams\n * object as its only argument.\n *\n * @memberof workbox-google-analytics\n */\nconst initialize = (options = {}) => {\n const cacheName = cacheNames.getGoogleAnalyticsName(options.cacheName);\n const bgSyncPlugin = new BackgroundSyncPlugin(QUEUE_NAME, {\n maxRetentionTime: MAX_RETENTION_TIME,\n onSync: createOnSyncCallback(options),\n });\n const routes = [\n createGtmJsRoute(cacheName),\n createAnalyticsJsRoute(cacheName),\n createGtagJsRoute(cacheName),\n ...createCollectRoutes(bgSyncPlugin),\n ];\n const router = new Router();\n for (const route of routes) {\n router.registerRoute(route);\n }\n router.addFetchListener();\n};\nexport { initialize };\n"],"names":["self","_","e","GOOGLE_ANALYTICS_HOST","GTM_HOST","COLLECT_PATHS_REGEX","createCollectRoutes","bgSyncPlugin","match","url","hostname","test","pathname","handler","NetworkOnly","plugins","Route","createAnalyticsJsRoute","cacheName","NetworkFirst","createGtagJsRoute","createGtmJsRoute","initialize","options","cacheNames","getGoogleAnalyticsName","BackgroundSyncPlugin","maxRetentionTime","onSync","config","async","queue","entry","shiftRequest","request","timestamp","URL","params","method","URLSearchParams","clone","text","searchParams","originalHitTime","Number","get","queueTime","Date","now","set","String","parameterOverrides","param","Object","keys","value","hitFilter","call","fetch","Request","origin","body","toString","mode","credentials","headers","err","unshiftRequest","routes","router","Router","route","registerRoute","addFetchListener"],"mappings":"oGAEA,IACIA,KAAK,mCAAqCC,GAC9C,CACA,MAAOC,GAAK,CCGL,MA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DC,EAAYC,KAAKC,MAAQL,EAI/B,GAFAN,EAAOY,IAAI,KAAMC,OAAOJ,IAEpBjB,EAAOsB,mBACP,IAAK,MAAMC,KAASC,OAAOC,KAAKzB,EAAOsB,oBAAqB,CACxD,MAAMI,EAAQ1B,EAAOsB,mBAAmBC,GACxCf,EAAOY,IAAIG,EAAOG,EACtB,CAG4B,mBAArB1B,EAAO2B,WACd3B,EAAO2B,UAAUC,KAAK,KAAMpB,SAI1BqB,MAAM,IAAIC,QAAQlD,EAAImD,OAASnD,EAAIG,SAAU,CAC/CiD,KAAMxB,EAAOyB,WACbxB,OAAQ,OACRyB,KAAM,OACNC,YAAa,OACbC,QAAS,CAAE,eAAgB,gBAKnC,CACA,MAAOC,GAMH,YALMnC,EAAMoC,eAAenC,GAKrBkC,CACV,CACJ,MAlDsBrC,MAuI1B,MAAMuC,EAAS,CACX/C,EAAiBH,GACjBD,EAAuBC,GACvBE,EAAkBF,MACfZ,EAAoBC,IAErB8D,EAAS,IAAIC,SACnB,IAAK,MAAMC,KAASH,EAChBC,EAAOG,cAAcD,GAEzBF,EAAOI,kBAAkB"} \ No newline at end of file diff --git a/node_modules/workbox-google-analytics/index.d.ts b/node_modules/workbox-google-analytics/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2229d296d7ff1f4421c8b4304bb6ed07ce3a8cf2 --- /dev/null +++ b/node_modules/workbox-google-analytics/index.d.ts @@ -0,0 +1,6 @@ +import { initialize, GoogleAnalyticsInitializeOptions } from './initialize.js'; +import './_version.js'; +/** + * @module workbox-google-analytics + */ +export { initialize, GoogleAnalyticsInitializeOptions }; diff --git a/node_modules/workbox-google-analytics/index.js b/node_modules/workbox-google-analytics/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e84c7f8dbe476954b40231b3d7d811e597949913 --- /dev/null +++ b/node_modules/workbox-google-analytics/index.js @@ -0,0 +1,13 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { initialize } from './initialize.js'; +import './_version.js'; +/** + * @module workbox-google-analytics + */ +export { initialize }; diff --git a/node_modules/workbox-google-analytics/index.mjs b/node_modules/workbox-google-analytics/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..833b6a2f3226fec78490a3b7a622dc5146f94b53 --- /dev/null +++ b/node_modules/workbox-google-analytics/index.mjs @@ -0,0 +1 @@ +export * from './index.js'; \ No newline at end of file diff --git a/node_modules/workbox-google-analytics/initialize.d.ts b/node_modules/workbox-google-analytics/initialize.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..019ae487d379fb9b265aba1653b5b8bec5fd6bc1 --- /dev/null +++ b/node_modules/workbox-google-analytics/initialize.d.ts @@ -0,0 +1,26 @@ +import './_version.js'; +export interface GoogleAnalyticsInitializeOptions { + cacheName?: string; + parameterOverrides?: { + [paramName: string]: string; + }; + hitFilter?: (params: URLSearchParams) => void; +} +/** + * @param {Object=} [options] + * @param {Object} [options.cacheName] The cache name to store and retrieve + * analytics.js. Defaults to the cache names provided by `workbox-core`. + * @param {Object} [options.parameterOverrides] + * [Measurement Protocol parameters](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters), + * expressed as key/value pairs, to be added to replayed Google Analytics + * requests. This can be used to, e.g., set a custom dimension indicating + * that the request was replayed. + * @param {Function} [options.hitFilter] A function that allows you to modify + * the hit parameters prior to replaying + * the hit. The function is invoked with the original hit's URLSearchParams + * object as its only argument. + * + * @memberof workbox-google-analytics + */ +declare const initialize: (options?: GoogleAnalyticsInitializeOptions) => void; +export { initialize }; diff --git a/node_modules/workbox-google-analytics/initialize.js b/node_modules/workbox-google-analytics/initialize.js new file mode 100644 index 0000000000000000000000000000000000000000..65c30eb0cf159c5a204262f9a3cb587ad664daee --- /dev/null +++ b/node_modules/workbox-google-analytics/initialize.js @@ -0,0 +1,176 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { BackgroundSyncPlugin } from 'workbox-background-sync/BackgroundSyncPlugin.js'; +import { cacheNames } from 'workbox-core/_private/cacheNames.js'; +import { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js'; +import { logger } from 'workbox-core/_private/logger.js'; +import { Route } from 'workbox-routing/Route.js'; +import { Router } from 'workbox-routing/Router.js'; +import { NetworkFirst } from 'workbox-strategies/NetworkFirst.js'; +import { NetworkOnly } from 'workbox-strategies/NetworkOnly.js'; +import { QUEUE_NAME, MAX_RETENTION_TIME, GOOGLE_ANALYTICS_HOST, GTM_HOST, ANALYTICS_JS_PATH, GTAG_JS_PATH, GTM_JS_PATH, COLLECT_PATHS_REGEX, } from './utils/constants.js'; +import './_version.js'; +/** + * Creates the requestWillDequeue callback to be used with the background + * sync plugin. The callback takes the failed request and adds the + * `qt` param based on the current time, as well as applies any other + * user-defined hit modifications. + * + * @param {Object} config See {@link workbox-google-analytics.initialize}. + * @return {Function} The requestWillDequeue callback function. + * + * @private + */ +const createOnSyncCallback = (config) => { + return async ({ queue }) => { + let entry; + while ((entry = await queue.shiftRequest())) { + const { request, timestamp } = entry; + const url = new URL(request.url); + try { + // Measurement protocol requests can set their payload parameters in + // either the URL query string (for GET requests) or the POST body. + const params = request.method === 'POST' + ? new URLSearchParams(await request.clone().text()) + : url.searchParams; + // Calculate the qt param, accounting for the fact that an existing + // qt param may be present and should be updated rather than replaced. + const originalHitTime = timestamp - (Number(params.get('qt')) || 0); + const queueTime = Date.now() - originalHitTime; + // Set the qt param prior to applying hitFilter or parameterOverrides. + params.set('qt', String(queueTime)); + // Apply `parameterOverrides`, if set. + if (config.parameterOverrides) { + for (const param of Object.keys(config.parameterOverrides)) { + const value = config.parameterOverrides[param]; + params.set(param, value); + } + } + // Apply `hitFilter`, if set. + if (typeof config.hitFilter === 'function') { + config.hitFilter.call(null, params); + } + // Retry the fetch. Ignore URL search params from the URL as they're + // now in the post body. + await fetch(new Request(url.origin + url.pathname, { + body: params.toString(), + method: 'POST', + mode: 'cors', + credentials: 'omit', + headers: { 'Content-Type': 'text/plain' }, + })); + if (process.env.NODE_ENV !== 'production') { + logger.log(`Request for '${getFriendlyURL(url.href)}' ` + `has been replayed`); + } + } + catch (err) { + await queue.unshiftRequest(entry); + if (process.env.NODE_ENV !== 'production') { + logger.log(`Request for '${getFriendlyURL(url.href)}' ` + + `failed to replay, putting it back in the queue.`); + } + throw err; + } + } + if (process.env.NODE_ENV !== 'production') { + logger.log(`All Google Analytics request successfully replayed; ` + + `the queue is now empty!`); + } + }; +}; +/** + * Creates GET and POST routes to catch failed Measurement Protocol hits. + * + * @param {BackgroundSyncPlugin} bgSyncPlugin + * @return {Array} The created routes. + * + * @private + */ +const createCollectRoutes = (bgSyncPlugin) => { + const match = ({ url }) => url.hostname === GOOGLE_ANALYTICS_HOST && + COLLECT_PATHS_REGEX.test(url.pathname); + const handler = new NetworkOnly({ + plugins: [bgSyncPlugin], + }); + return [new Route(match, handler, 'GET'), new Route(match, handler, 'POST')]; +}; +/** + * Creates a route with a network first strategy for the analytics.js script. + * + * @param {string} cacheName + * @return {Route} The created route. + * + * @private + */ +const createAnalyticsJsRoute = (cacheName) => { + const match = ({ url }) => url.hostname === GOOGLE_ANALYTICS_HOST && + url.pathname === ANALYTICS_JS_PATH; + const handler = new NetworkFirst({ cacheName }); + return new Route(match, handler, 'GET'); +}; +/** + * Creates a route with a network first strategy for the gtag.js script. + * + * @param {string} cacheName + * @return {Route} The created route. + * + * @private + */ +const createGtagJsRoute = (cacheName) => { + const match = ({ url }) => url.hostname === GTM_HOST && url.pathname === GTAG_JS_PATH; + const handler = new NetworkFirst({ cacheName }); + return new Route(match, handler, 'GET'); +}; +/** + * Creates a route with a network first strategy for the gtm.js script. + * + * @param {string} cacheName + * @return {Route} The created route. + * + * @private + */ +const createGtmJsRoute = (cacheName) => { + const match = ({ url }) => url.hostname === GTM_HOST && url.pathname === GTM_JS_PATH; + const handler = new NetworkFirst({ cacheName }); + return new Route(match, handler, 'GET'); +}; +/** + * @param {Object=} [options] + * @param {Object} [options.cacheName] The cache name to store and retrieve + * analytics.js. Defaults to the cache names provided by `workbox-core`. + * @param {Object} [options.parameterOverrides] + * [Measurement Protocol parameters](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters), + * expressed as key/value pairs, to be added to replayed Google Analytics + * requests. This can be used to, e.g., set a custom dimension indicating + * that the request was replayed. + * @param {Function} [options.hitFilter] A function that allows you to modify + * the hit parameters prior to replaying + * the hit. The function is invoked with the original hit's URLSearchParams + * object as its only argument. + * + * @memberof workbox-google-analytics + */ +const initialize = (options = {}) => { + const cacheName = cacheNames.getGoogleAnalyticsName(options.cacheName); + const bgSyncPlugin = new BackgroundSyncPlugin(QUEUE_NAME, { + maxRetentionTime: MAX_RETENTION_TIME, + onSync: createOnSyncCallback(options), + }); + const routes = [ + createGtmJsRoute(cacheName), + createAnalyticsJsRoute(cacheName), + createGtagJsRoute(cacheName), + ...createCollectRoutes(bgSyncPlugin), + ]; + const router = new Router(); + for (const route of routes) { + router.registerRoute(route); + } + router.addFetchListener(); +}; +export { initialize }; diff --git a/node_modules/workbox-google-analytics/initialize.mjs b/node_modules/workbox-google-analytics/initialize.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e195c24b0c6637971e74e53227e53e56c79bfa54 --- /dev/null +++ b/node_modules/workbox-google-analytics/initialize.mjs @@ -0,0 +1 @@ +export * from './initialize.js'; \ No newline at end of file diff --git a/node_modules/workbox-google-analytics/package.json b/node_modules/workbox-google-analytics/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a0f558a12136789bc16a2ecc1056ea567c60c585 --- /dev/null +++ b/node_modules/workbox-google-analytics/package.json @@ -0,0 +1,37 @@ +{ + "name": "workbox-google-analytics", + "version": "7.4.1", + "license": "MIT", + "author": "Google's Web DevRel Team and Google's Aurora Team", + "description": "Queues failed requests and uses the Background Sync API to replay them when the network is available", + "repository": { + "type": "git", + "url": "git+https://github.com/googlechrome/workbox.git" + }, + "bugs": "https://github.com/googlechrome/workbox/issues", + "homepage": "https://github.com/GoogleChrome/workbox", + "keywords": [ + "workbox", + "workboxjs", + "service worker", + "sw", + "offline", + "google", + "analytics" + ], + "workbox": { + "browserNamespace": "workbox.googleAnalytics", + "outputFilename": "workbox-offline-ga", + "packageType": "sw" + }, + "main": "index.js", + "module": "index.mjs", + "types": "index.d.ts", + "dependencies": { + "workbox-background-sync": "7.4.1", + "workbox-core": "7.4.1", + "workbox-routing": "7.4.1", + "workbox-strategies": "7.4.1" + }, + "gitHead": "62b9d8ba8eb3c1a2ab8aac9d84c90cda7865d6a3" +} diff --git a/node_modules/workbox-google-analytics/src/_version.ts b/node_modules/workbox-google-analytics/src/_version.ts new file mode 100644 index 0000000000000000000000000000000000000000..07d2251e5338a3e5a6251820c07b814d1a132e82 --- /dev/null +++ b/node_modules/workbox-google-analytics/src/_version.ts @@ -0,0 +1,2 @@ +// @ts-ignore +try{self['workbox:google-analytics:7.4.1']&&_()}catch(e){} \ No newline at end of file diff --git a/node_modules/workbox-google-analytics/src/index.ts b/node_modules/workbox-google-analytics/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..6f7b3fe5ac47eee0c784b9a3ccfe91a9f2401a0d --- /dev/null +++ b/node_modules/workbox-google-analytics/src/index.ts @@ -0,0 +1,17 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {initialize, GoogleAnalyticsInitializeOptions} from './initialize.js'; + +import './_version.js'; + +/** + * @module workbox-google-analytics + */ + +export {initialize, GoogleAnalyticsInitializeOptions}; diff --git a/node_modules/workbox-google-analytics/src/initialize.ts b/node_modules/workbox-google-analytics/src/initialize.ts new file mode 100644 index 0000000000000000000000000000000000000000..89bf5567cf452ad430320802cbe8c890ab83346a --- /dev/null +++ b/node_modules/workbox-google-analytics/src/initialize.ts @@ -0,0 +1,233 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {BackgroundSyncPlugin} from 'workbox-background-sync/BackgroundSyncPlugin.js'; +import {Queue} from 'workbox-background-sync/Queue.js'; +import {cacheNames} from 'workbox-core/_private/cacheNames.js'; +import {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.js'; +import {logger} from 'workbox-core/_private/logger.js'; +import {RouteMatchCallbackOptions} from 'workbox-core/types.js'; +import {Route} from 'workbox-routing/Route.js'; +import {Router} from 'workbox-routing/Router.js'; +import {NetworkFirst} from 'workbox-strategies/NetworkFirst.js'; +import {NetworkOnly} from 'workbox-strategies/NetworkOnly.js'; +import { + QUEUE_NAME, + MAX_RETENTION_TIME, + GOOGLE_ANALYTICS_HOST, + GTM_HOST, + ANALYTICS_JS_PATH, + GTAG_JS_PATH, + GTM_JS_PATH, + COLLECT_PATHS_REGEX, +} from './utils/constants.js'; +import './_version.js'; + +export interface GoogleAnalyticsInitializeOptions { + cacheName?: string; + parameterOverrides?: {[paramName: string]: string}; + hitFilter?: (params: URLSearchParams) => void; +} + +/** + * Creates the requestWillDequeue callback to be used with the background + * sync plugin. The callback takes the failed request and adds the + * `qt` param based on the current time, as well as applies any other + * user-defined hit modifications. + * + * @param {Object} config See {@link workbox-google-analytics.initialize}. + * @return {Function} The requestWillDequeue callback function. + * + * @private + */ +const createOnSyncCallback = (config: GoogleAnalyticsInitializeOptions) => { + return async ({queue}: {queue: Queue}) => { + let entry; + while ((entry = await queue.shiftRequest())) { + const {request, timestamp} = entry; + const url = new URL(request.url); + + try { + // Measurement protocol requests can set their payload parameters in + // either the URL query string (for GET requests) or the POST body. + const params = + request.method === 'POST' + ? new URLSearchParams(await request.clone().text()) + : url.searchParams; + + // Calculate the qt param, accounting for the fact that an existing + // qt param may be present and should be updated rather than replaced. + const originalHitTime = timestamp! - (Number(params.get('qt')) || 0); + const queueTime = Date.now() - originalHitTime; + + // Set the qt param prior to applying hitFilter or parameterOverrides. + params.set('qt', String(queueTime)); + + // Apply `parameterOverrides`, if set. + if (config.parameterOverrides) { + for (const param of Object.keys(config.parameterOverrides)) { + const value = config.parameterOverrides[param]; + params.set(param, value); + } + } + + // Apply `hitFilter`, if set. + if (typeof config.hitFilter === 'function') { + config.hitFilter.call(null, params); + } + + // Retry the fetch. Ignore URL search params from the URL as they're + // now in the post body. + await fetch( + new Request(url.origin + url.pathname, { + body: params.toString(), + method: 'POST', + mode: 'cors', + credentials: 'omit', + headers: {'Content-Type': 'text/plain'}, + }), + ); + + if (process.env.NODE_ENV !== 'production') { + logger.log( + `Request for '${getFriendlyURL(url.href)}' ` + `has been replayed`, + ); + } + } catch (err) { + await queue.unshiftRequest(entry); + + if (process.env.NODE_ENV !== 'production') { + logger.log( + `Request for '${getFriendlyURL(url.href)}' ` + + `failed to replay, putting it back in the queue.`, + ); + } + throw err; + } + } + if (process.env.NODE_ENV !== 'production') { + logger.log( + `All Google Analytics request successfully replayed; ` + + `the queue is now empty!`, + ); + } + }; +}; + +/** + * Creates GET and POST routes to catch failed Measurement Protocol hits. + * + * @param {BackgroundSyncPlugin} bgSyncPlugin + * @return {Array} The created routes. + * + * @private + */ +const createCollectRoutes = (bgSyncPlugin: BackgroundSyncPlugin) => { + const match = ({url}: RouteMatchCallbackOptions) => + url.hostname === GOOGLE_ANALYTICS_HOST && + COLLECT_PATHS_REGEX.test(url.pathname); + + const handler = new NetworkOnly({ + plugins: [bgSyncPlugin], + }); + + return [new Route(match, handler, 'GET'), new Route(match, handler, 'POST')]; +}; + +/** + * Creates a route with a network first strategy for the analytics.js script. + * + * @param {string} cacheName + * @return {Route} The created route. + * + * @private + */ +const createAnalyticsJsRoute = (cacheName: string) => { + const match = ({url}: RouteMatchCallbackOptions) => + url.hostname === GOOGLE_ANALYTICS_HOST && + url.pathname === ANALYTICS_JS_PATH; + + const handler = new NetworkFirst({cacheName}); + + return new Route(match, handler, 'GET'); +}; + +/** + * Creates a route with a network first strategy for the gtag.js script. + * + * @param {string} cacheName + * @return {Route} The created route. + * + * @private + */ +const createGtagJsRoute = (cacheName: string) => { + const match = ({url}: RouteMatchCallbackOptions) => + url.hostname === GTM_HOST && url.pathname === GTAG_JS_PATH; + + const handler = new NetworkFirst({cacheName}); + + return new Route(match, handler, 'GET'); +}; + +/** + * Creates a route with a network first strategy for the gtm.js script. + * + * @param {string} cacheName + * @return {Route} The created route. + * + * @private + */ +const createGtmJsRoute = (cacheName: string) => { + const match = ({url}: RouteMatchCallbackOptions) => + url.hostname === GTM_HOST && url.pathname === GTM_JS_PATH; + + const handler = new NetworkFirst({cacheName}); + + return new Route(match, handler, 'GET'); +}; + +/** + * @param {Object=} [options] + * @param {Object} [options.cacheName] The cache name to store and retrieve + * analytics.js. Defaults to the cache names provided by `workbox-core`. + * @param {Object} [options.parameterOverrides] + * [Measurement Protocol parameters](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters), + * expressed as key/value pairs, to be added to replayed Google Analytics + * requests. This can be used to, e.g., set a custom dimension indicating + * that the request was replayed. + * @param {Function} [options.hitFilter] A function that allows you to modify + * the hit parameters prior to replaying + * the hit. The function is invoked with the original hit's URLSearchParams + * object as its only argument. + * + * @memberof workbox-google-analytics + */ +const initialize = (options: GoogleAnalyticsInitializeOptions = {}): void => { + const cacheName = cacheNames.getGoogleAnalyticsName(options.cacheName); + + const bgSyncPlugin = new BackgroundSyncPlugin(QUEUE_NAME, { + maxRetentionTime: MAX_RETENTION_TIME, + onSync: createOnSyncCallback(options), + }); + + const routes = [ + createGtmJsRoute(cacheName), + createAnalyticsJsRoute(cacheName), + createGtagJsRoute(cacheName), + ...createCollectRoutes(bgSyncPlugin), + ]; + + const router = new Router(); + for (const route of routes) { + router.registerRoute(route); + } + + router.addFetchListener(); +}; + +export {initialize}; diff --git a/node_modules/workbox-google-analytics/src/utils/constants.ts b/node_modules/workbox-google-analytics/src/utils/constants.ts new file mode 100644 index 0000000000000000000000000000000000000000..b2baac2e00d9052a15529127f18caea4333eb33f --- /dev/null +++ b/node_modules/workbox-google-analytics/src/utils/constants.ts @@ -0,0 +1,24 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import '../_version.js'; + +export const QUEUE_NAME = 'workbox-google-analytics'; +export const MAX_RETENTION_TIME = 60 * 48; // Two days in minutes +export const GOOGLE_ANALYTICS_HOST = 'www.google-analytics.com'; +export const GTM_HOST = 'www.googletagmanager.com'; +export const ANALYTICS_JS_PATH = '/analytics.js'; +export const GTAG_JS_PATH = '/gtag/js'; +export const GTM_JS_PATH = '/gtm.js'; +export const COLLECT_DEFAULT_PATH = '/collect'; + +// This RegExp matches all known Measurement Protocol single-hit collect +// endpoints. Most of the time the default path (/collect) is used, but +// occasionally an experimental endpoint is used when testing new features, +// (e.g. /r/collect or /j/collect) +export const COLLECT_PATHS_REGEX = /^\/(\w+\/)?collect/; diff --git a/node_modules/workbox-google-analytics/tsconfig.json b/node_modules/workbox-google-analytics/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..255f4fa204ed42f362281129c76694ceabaf346b --- /dev/null +++ b/node_modules/workbox-google-analytics/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "../../tsconfig", + "compilerOptions": { + "composite": true, + "outDir": "./", + "rootDir": "./src", + "tsBuildInfoFile": "./tsconfig.tsbuildinfo" + }, + "include": ["src/**/*.ts"], + "references": [ + {"path": "../workbox-background-sync/"}, + {"path": "../workbox-core/"}, + {"path": "../workbox-routing/"}, + {"path": "../workbox-strategies/"} + ] +} diff --git a/node_modules/workbox-google-analytics/utils/constants.d.ts b/node_modules/workbox-google-analytics/utils/constants.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fd9c629ed90d1dbc8025c8732ba381c307429756 --- /dev/null +++ b/node_modules/workbox-google-analytics/utils/constants.d.ts @@ -0,0 +1,10 @@ +import '../_version.js'; +export declare const QUEUE_NAME = "workbox-google-analytics"; +export declare const MAX_RETENTION_TIME: number; +export declare const GOOGLE_ANALYTICS_HOST = "www.google-analytics.com"; +export declare const GTM_HOST = "www.googletagmanager.com"; +export declare const ANALYTICS_JS_PATH = "/analytics.js"; +export declare const GTAG_JS_PATH = "/gtag/js"; +export declare const GTM_JS_PATH = "/gtm.js"; +export declare const COLLECT_DEFAULT_PATH = "/collect"; +export declare const COLLECT_PATHS_REGEX: RegExp; diff --git a/node_modules/workbox-google-analytics/utils/constants.js b/node_modules/workbox-google-analytics/utils/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..24c7b66e6c7244651d659b78e50761fb85d476f6 --- /dev/null +++ b/node_modules/workbox-google-analytics/utils/constants.js @@ -0,0 +1,21 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import '../_version.js'; +export const QUEUE_NAME = 'workbox-google-analytics'; +export const MAX_RETENTION_TIME = 60 * 48; // Two days in minutes +export const GOOGLE_ANALYTICS_HOST = 'www.google-analytics.com'; +export const GTM_HOST = 'www.googletagmanager.com'; +export const ANALYTICS_JS_PATH = '/analytics.js'; +export const GTAG_JS_PATH = '/gtag/js'; +export const GTM_JS_PATH = '/gtm.js'; +export const COLLECT_DEFAULT_PATH = '/collect'; +// This RegExp matches all known Measurement Protocol single-hit collect +// endpoints. Most of the time the default path (/collect) is used, but +// occasionally an experimental endpoint is used when testing new features, +// (e.g. /r/collect or /j/collect) +export const COLLECT_PATHS_REGEX = /^\/(\w+\/)?collect/; diff --git a/node_modules/workbox-google-analytics/utils/constants.mjs b/node_modules/workbox-google-analytics/utils/constants.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f3f4c8f2658cad983ad14478588d456cb83091d0 --- /dev/null +++ b/node_modules/workbox-google-analytics/utils/constants.mjs @@ -0,0 +1 @@ +export * from './constants.js'; \ No newline at end of file diff --git a/node_modules/workbox-navigation-preload/LICENSE b/node_modules/workbox-navigation-preload/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..845b545fd0f5031a944cda8cf9018eb066500040 --- /dev/null +++ b/node_modules/workbox-navigation-preload/LICENSE @@ -0,0 +1,19 @@ +Copyright 2018 Google LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/workbox-navigation-preload/README.md b/node_modules/workbox-navigation-preload/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ff61ae45c8504fd6ed3116fa07132b25ef19d626 --- /dev/null +++ b/node_modules/workbox-navigation-preload/README.md @@ -0,0 +1 @@ +This module's documentation can be found at https://developers.google.com/web/tools/workbox/modules/workbox-navigation-preload diff --git a/node_modules/workbox-navigation-preload/_version.d.ts b/node_modules/workbox-navigation-preload/_version.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/workbox-navigation-preload/_version.js b/node_modules/workbox-navigation-preload/_version.js new file mode 100644 index 0000000000000000000000000000000000000000..64184db60440d8a222df554b6b17a8911cd4fc91 --- /dev/null +++ b/node_modules/workbox-navigation-preload/_version.js @@ -0,0 +1,6 @@ +"use strict"; +// @ts-ignore +try { + self['workbox:navigation-preload:7.4.0'] && _(); +} +catch (e) { } diff --git a/node_modules/workbox-navigation-preload/_version.mjs b/node_modules/workbox-navigation-preload/_version.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4ee684c1205ef69913d49e446545181b127058a3 --- /dev/null +++ b/node_modules/workbox-navigation-preload/_version.mjs @@ -0,0 +1 @@ +try{self['workbox:navigation-preload:7.4.1']&&_()}catch(e){}// eslint-disable-line \ No newline at end of file diff --git a/node_modules/workbox-navigation-preload/build/workbox-navigation-preload.dev.js b/node_modules/workbox-navigation-preload/build/workbox-navigation-preload.dev.js new file mode 100644 index 0000000000000000000000000000000000000000..637ae1343090d70ea2084be91621b82fa479c8ca --- /dev/null +++ b/node_modules/workbox-navigation-preload/build/workbox-navigation-preload.dev.js @@ -0,0 +1,99 @@ +this.workbox = this.workbox || {}; +this.workbox.navigationPreload = (function (exports, logger_js) { + 'use strict'; + + // @ts-ignore + try { + self['workbox:navigation-preload:7.4.0'] && _(); + } catch (e) {} + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * @return {boolean} Whether or not the current browser supports enabling + * navigation preload. + * + * @memberof workbox-navigation-preload + */ + function isSupported() { + return Boolean(self.registration && self.registration.navigationPreload); + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * If the browser supports Navigation Preload, then this will disable it. + * + * @memberof workbox-navigation-preload + */ + function disable() { + if (isSupported()) { + self.addEventListener('activate', event => { + event.waitUntil(self.registration.navigationPreload.disable().then(() => { + { + logger_js.logger.log(`Navigation preload is disabled.`); + } + })); + }); + } else { + { + logger_js.logger.log(`Navigation preload is not supported in this browser.`); + } + } + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * If the browser supports Navigation Preload, then this will enable it. + * + * @param {string} [headerValue] Optionally, allows developers to + * [override](https://developers.google.com/web/updates/2017/02/navigation-preload#changing_the_header) + * the value of the `Service-Worker-Navigation-Preload` header which will be + * sent to the server when making the navigation request. + * + * @memberof workbox-navigation-preload + */ + function enable(headerValue) { + if (isSupported()) { + self.addEventListener('activate', event => { + event.waitUntil(self.registration.navigationPreload.enable().then(() => { + // Defaults to Service-Worker-Navigation-Preload: true if not set. + if (headerValue) { + void self.registration.navigationPreload.setHeaderValue(headerValue); + } + { + logger_js.logger.log(`Navigation preload is enabled.`); + } + })); + }); + } else { + { + logger_js.logger.log(`Navigation preload is not supported in this browser.`); + } + } + } + + exports.disable = disable; + exports.enable = enable; + exports.isSupported = isSupported; + + return exports; + +})({}, workbox.core._private); +//# sourceMappingURL=workbox-navigation-preload.dev.js.map diff --git a/node_modules/workbox-navigation-preload/build/workbox-navigation-preload.dev.js.map b/node_modules/workbox-navigation-preload/build/workbox-navigation-preload.dev.js.map new file mode 100644 index 0000000000000000000000000000000000000000..5f8fb4c2a714898440a7219adf262f4d7033c068 --- /dev/null +++ b/node_modules/workbox-navigation-preload/build/workbox-navigation-preload.dev.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-navigation-preload.dev.js","sources":["../_version.js","../isSupported.js","../disable.js","../enable.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:navigation-preload:7.4.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 './_version.js';\n/**\n * @return {boolean} Whether or not the current browser supports enabling\n * navigation preload.\n *\n * @memberof workbox-navigation-preload\n */\nfunction isSupported() {\n return Boolean(self.registration && self.registration.navigationPreload);\n}\nexport { isSupported };\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 { logger } from 'workbox-core/_private/logger.js';\nimport { isSupported } from './isSupported.js';\nimport './_version.js';\n/**\n * If the browser supports Navigation Preload, then this will disable it.\n *\n * @memberof workbox-navigation-preload\n */\nfunction disable() {\n if (isSupported()) {\n self.addEventListener('activate', (event) => {\n event.waitUntil(self.registration.navigationPreload.disable().then(() => {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Navigation preload is disabled.`);\n }\n }));\n });\n }\n else {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Navigation preload is not supported in this browser.`);\n }\n }\n}\nexport { disable };\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 { logger } from 'workbox-core/_private/logger.js';\nimport { isSupported } from './isSupported.js';\nimport './_version.js';\n/**\n * If the browser supports Navigation Preload, then this will enable it.\n *\n * @param {string} [headerValue] Optionally, allows developers to\n * [override](https://developers.google.com/web/updates/2017/02/navigation-preload#changing_the_header)\n * the value of the `Service-Worker-Navigation-Preload` header which will be\n * sent to the server when making the navigation request.\n *\n * @memberof workbox-navigation-preload\n */\nfunction enable(headerValue) {\n if (isSupported()) {\n self.addEventListener('activate', (event) => {\n event.waitUntil(self.registration.navigationPreload.enable().then(() => {\n // Defaults to Service-Worker-Navigation-Preload: true if not set.\n if (headerValue) {\n void self.registration.navigationPreload.setHeaderValue(headerValue);\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Navigation preload is enabled.`);\n }\n }));\n });\n }\n else {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Navigation preload is not supported in this browser.`);\n }\n }\n}\nexport { enable };\n"],"names":["self","_","e","isSupported","Boolean","registration","navigationPreload","disable","addEventListener","event","waitUntil","then","logger","log","enable","headerValue","setHeaderValue"],"mappings":";;;;IACA;IACA,IAAI;IACAA,EAAAA,IAAI,CAAC,kCAAkC,CAAC,IAAIC,CAAC,EAAE;IACnD,CAAC,CACD,OAAOC,CAAC,EAAE,C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,UAAAA,gBAAM,CAACC,GAAG,CAAE,CAAA,8BAAA,CAA+B,CAAC;IAChD,QAAA;IACJ,MAAA,CAAC,CAAC,CAAC;IACP,IAAA,CAAC,CAAC;IACN,EAAA,CAAC,MACI;IACD,IAA2C;IACvCD,MAAAA,gBAAM,CAACC,GAAG,CAAE,CAAA,oDAAA,CAAqD,CAAC;IACtE,IAAA;IACJ,EAAA;IACJ;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/workbox-navigation-preload/build/workbox-navigation-preload.prod.js b/node_modules/workbox-navigation-preload/build/workbox-navigation-preload.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..23d9af2a637b080150d0312034fb2cef14b5de68 --- /dev/null +++ b/node_modules/workbox-navigation-preload/build/workbox-navigation-preload.prod.js @@ -0,0 +1,2 @@ +this.workbox=this.workbox||{},this.workbox.navigationPreload=function(t){"use strict";try{self["workbox:navigation-preload:7.4.0"]&&_()}catch(t){}function e(){return Boolean(self.registration&&self.registration.navigationPreload)}return t.disable=function(){e()&&self.addEventListener("activate",(t=>{t.waitUntil(self.registration.navigationPreload.disable().then((()=>{})))}))},t.enable=function(t){e()&&self.addEventListener("activate",(e=>{e.waitUntil(self.registration.navigationPreload.enable().then((()=>{t&&self.registration.navigationPreload.setHeaderValue(t)})))}))},t.isSupported=e,t}({}); +//# sourceMappingURL=workbox-navigation-preload.prod.js.map diff --git a/node_modules/workbox-navigation-preload/build/workbox-navigation-preload.prod.js.map b/node_modules/workbox-navigation-preload/build/workbox-navigation-preload.prod.js.map new file mode 100644 index 0000000000000000000000000000000000000000..9f8d7c3c35fa8f32ee23dacf0f8e28f15dc293d0 --- /dev/null +++ b/node_modules/workbox-navigation-preload/build/workbox-navigation-preload.prod.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-navigation-preload.prod.js","sources":["../_version.js","../isSupported.js","../disable.js","../enable.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:navigation-preload:7.4.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 './_version.js';\n/**\n * @return {boolean} Whether or not the current browser supports enabling\n * navigation preload.\n *\n * @memberof workbox-navigation-preload\n */\nfunction isSupported() {\n return Boolean(self.registration && self.registration.navigationPreload);\n}\nexport { isSupported };\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 { logger } from 'workbox-core/_private/logger.js';\nimport { isSupported } from './isSupported.js';\nimport './_version.js';\n/**\n * If the browser supports Navigation Preload, then this will disable it.\n *\n * @memberof workbox-navigation-preload\n */\nfunction disable() {\n if (isSupported()) {\n self.addEventListener('activate', (event) => {\n event.waitUntil(self.registration.navigationPreload.disable().then(() => {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Navigation preload is disabled.`);\n }\n }));\n });\n }\n else {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Navigation preload is not supported in this browser.`);\n }\n }\n}\nexport { disable };\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 { logger } from 'workbox-core/_private/logger.js';\nimport { isSupported } from './isSupported.js';\nimport './_version.js';\n/**\n * If the browser supports Navigation Preload, then this will enable it.\n *\n * @param {string} [headerValue] Optionally, allows developers to\n * [override](https://developers.google.com/web/updates/2017/02/navigation-preload#changing_the_header)\n * the value of the `Service-Worker-Navigation-Preload` header which will be\n * sent to the server when making the navigation request.\n *\n * @memberof workbox-navigation-preload\n */\nfunction enable(headerValue) {\n if (isSupported()) {\n self.addEventListener('activate', (event) => {\n event.waitUntil(self.registration.navigationPreload.enable().then(() => {\n // Defaults to Service-Worker-Navigation-Preload: true if not set.\n if (headerValue) {\n void self.registration.navigationPreload.setHeaderValue(headerValue);\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Navigation preload is enabled.`);\n }\n }));\n });\n }\n else {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Navigation preload is not supported in this browser.`);\n }\n }\n}\nexport { enable };\n"],"names":["self","_","e","isSupported","Boolean","registration","navigationPreload","addEventListener","event","waitUntil","disable","then","headerValue","enable","setHeaderValue"],"mappings":"sFAEA,IACIA,KAAK,qCAAuCC,GAChD,CACA,MAAOC,GAAK,CCSZ,SAASC,IACL,OAAOC,QAAQJ,KAAKK,cAAgBL,KAAKK,aAAaC,kBAC1D,kBCDA,WACQH,KACAH,KAAKO,iBAAiB,YAAaC,IAC/BA,EAAMC,UAAUT,KAAKK,aAAaC,kBAAkBI,UAAUC,MAAK,SAIhE,GAQf,WCVA,SAAgBC,GACRT,KACAH,KAAKO,iBAAiB,YAAaC,IAC/BA,EAAMC,UAAUT,KAAKK,aAAaC,kBAAkBO,SAASF,MAAK,KAE1DC,GACKZ,KAAKK,aAAaC,kBAAkBQ,eAAeF,EAC5D,IAID,GAQf"} \ No newline at end of file diff --git a/node_modules/workbox-navigation-preload/disable.d.ts b/node_modules/workbox-navigation-preload/disable.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3dd67843050d5db9ad912c00736a91aa1f7409f4 --- /dev/null +++ b/node_modules/workbox-navigation-preload/disable.d.ts @@ -0,0 +1,8 @@ +import './_version.js'; +/** + * If the browser supports Navigation Preload, then this will disable it. + * + * @memberof workbox-navigation-preload + */ +declare function disable(): void; +export { disable }; diff --git a/node_modules/workbox-navigation-preload/disable.js b/node_modules/workbox-navigation-preload/disable.js new file mode 100644 index 0000000000000000000000000000000000000000..2fd44b4421772186d0bde89649e4b374c365040d --- /dev/null +++ b/node_modules/workbox-navigation-preload/disable.js @@ -0,0 +1,32 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { logger } from 'workbox-core/_private/logger.js'; +import { isSupported } from './isSupported.js'; +import './_version.js'; +/** + * If the browser supports Navigation Preload, then this will disable it. + * + * @memberof workbox-navigation-preload + */ +function disable() { + if (isSupported()) { + self.addEventListener('activate', (event) => { + event.waitUntil(self.registration.navigationPreload.disable().then(() => { + if (process.env.NODE_ENV !== 'production') { + logger.log(`Navigation preload is disabled.`); + } + })); + }); + } + else { + if (process.env.NODE_ENV !== 'production') { + logger.log(`Navigation preload is not supported in this browser.`); + } + } +} +export { disable }; diff --git a/node_modules/workbox-navigation-preload/disable.mjs b/node_modules/workbox-navigation-preload/disable.mjs new file mode 100644 index 0000000000000000000000000000000000000000..dd602111641207f36d186c2e9e4650677ed56665 --- /dev/null +++ b/node_modules/workbox-navigation-preload/disable.mjs @@ -0,0 +1 @@ +export * from './disable.js'; \ No newline at end of file diff --git a/node_modules/workbox-navigation-preload/enable.d.ts b/node_modules/workbox-navigation-preload/enable.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1359a8912dfec2b06c4c9702e824a1c82957fe03 --- /dev/null +++ b/node_modules/workbox-navigation-preload/enable.d.ts @@ -0,0 +1,13 @@ +import './_version.js'; +/** + * If the browser supports Navigation Preload, then this will enable it. + * + * @param {string} [headerValue] Optionally, allows developers to + * [override](https://developers.google.com/web/updates/2017/02/navigation-preload#changing_the_header) + * the value of the `Service-Worker-Navigation-Preload` header which will be + * sent to the server when making the navigation request. + * + * @memberof workbox-navigation-preload + */ +declare function enable(headerValue?: string): void; +export { enable }; diff --git a/node_modules/workbox-navigation-preload/enable.js b/node_modules/workbox-navigation-preload/enable.js new file mode 100644 index 0000000000000000000000000000000000000000..85b3428eafb663b04f8517cf7a824ce1bd7e45a0 --- /dev/null +++ b/node_modules/workbox-navigation-preload/enable.js @@ -0,0 +1,41 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { logger } from 'workbox-core/_private/logger.js'; +import { isSupported } from './isSupported.js'; +import './_version.js'; +/** + * If the browser supports Navigation Preload, then this will enable it. + * + * @param {string} [headerValue] Optionally, allows developers to + * [override](https://developers.google.com/web/updates/2017/02/navigation-preload#changing_the_header) + * the value of the `Service-Worker-Navigation-Preload` header which will be + * sent to the server when making the navigation request. + * + * @memberof workbox-navigation-preload + */ +function enable(headerValue) { + if (isSupported()) { + self.addEventListener('activate', (event) => { + event.waitUntil(self.registration.navigationPreload.enable().then(() => { + // Defaults to Service-Worker-Navigation-Preload: true if not set. + if (headerValue) { + void self.registration.navigationPreload.setHeaderValue(headerValue); + } + if (process.env.NODE_ENV !== 'production') { + logger.log(`Navigation preload is enabled.`); + } + })); + }); + } + else { + if (process.env.NODE_ENV !== 'production') { + logger.log(`Navigation preload is not supported in this browser.`); + } + } +} +export { enable }; diff --git a/node_modules/workbox-navigation-preload/enable.mjs b/node_modules/workbox-navigation-preload/enable.mjs new file mode 100644 index 0000000000000000000000000000000000000000..636344a9859041e583ea850093ea8d48214b0d80 --- /dev/null +++ b/node_modules/workbox-navigation-preload/enable.mjs @@ -0,0 +1 @@ +export * from './enable.js'; \ No newline at end of file diff --git a/node_modules/workbox-navigation-preload/index.d.ts b/node_modules/workbox-navigation-preload/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..880e643e5d6a953210350701be4532f41e63a00d --- /dev/null +++ b/node_modules/workbox-navigation-preload/index.d.ts @@ -0,0 +1,23 @@ +import { disable } from './disable.js'; +import { enable } from './enable.js'; +import { isSupported } from './isSupported.js'; +import './_version.js'; +interface NavigationPreloadState { + enabled?: boolean; + headerValue?: string; +} +interface NavigationPreloadManager { + disable(): Promise; + enable(): Promise; + getState(): Promise; + setHeaderValue(value: string): Promise; +} +declare global { + interface ServiceWorkerRegistration { + readonly navigationPreload: NavigationPreloadManager; + } +} +/** + * @module workbox-navigation-preload + */ +export { disable, enable, isSupported }; diff --git a/node_modules/workbox-navigation-preload/index.js b/node_modules/workbox-navigation-preload/index.js new file mode 100644 index 0000000000000000000000000000000000000000..cf40ed0c157144c0c1c3681a4309b37976f54d92 --- /dev/null +++ b/node_modules/workbox-navigation-preload/index.js @@ -0,0 +1,15 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { disable } from './disable.js'; +import { enable } from './enable.js'; +import { isSupported } from './isSupported.js'; +import './_version.js'; +/** + * @module workbox-navigation-preload + */ +export { disable, enable, isSupported }; diff --git a/node_modules/workbox-navigation-preload/index.mjs b/node_modules/workbox-navigation-preload/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..833b6a2f3226fec78490a3b7a622dc5146f94b53 --- /dev/null +++ b/node_modules/workbox-navigation-preload/index.mjs @@ -0,0 +1 @@ +export * from './index.js'; \ No newline at end of file diff --git a/node_modules/workbox-navigation-preload/isSupported.d.ts b/node_modules/workbox-navigation-preload/isSupported.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e6a2dab1e867394724941752e8f3bb876406fccc --- /dev/null +++ b/node_modules/workbox-navigation-preload/isSupported.d.ts @@ -0,0 +1,9 @@ +import './_version.js'; +/** + * @return {boolean} Whether or not the current browser supports enabling + * navigation preload. + * + * @memberof workbox-navigation-preload + */ +declare function isSupported(): boolean; +export { isSupported }; diff --git a/node_modules/workbox-navigation-preload/isSupported.js b/node_modules/workbox-navigation-preload/isSupported.js new file mode 100644 index 0000000000000000000000000000000000000000..787eb070a98a8fede64571997ff8f87648d4f6c3 --- /dev/null +++ b/node_modules/workbox-navigation-preload/isSupported.js @@ -0,0 +1,18 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import './_version.js'; +/** + * @return {boolean} Whether or not the current browser supports enabling + * navigation preload. + * + * @memberof workbox-navigation-preload + */ +function isSupported() { + return Boolean(self.registration && self.registration.navigationPreload); +} +export { isSupported }; diff --git a/node_modules/workbox-navigation-preload/isSupported.mjs b/node_modules/workbox-navigation-preload/isSupported.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e4ec954938b7476095238ddcdab20e8f49b69f0b --- /dev/null +++ b/node_modules/workbox-navigation-preload/isSupported.mjs @@ -0,0 +1 @@ +export * from './isSupported.js'; \ No newline at end of file diff --git a/node_modules/workbox-navigation-preload/package.json b/node_modules/workbox-navigation-preload/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6c05f51e0b090f6d8c35a66f29800e4a046e4964 --- /dev/null +++ b/node_modules/workbox-navigation-preload/package.json @@ -0,0 +1,31 @@ +{ + "name": "workbox-navigation-preload", + "version": "7.4.1", + "license": "MIT", + "author": "Google's Web DevRel Team and Google's Aurora Team", + "description": "This library allows developers to opt-in to using Navigation Preload in their service worker.", + "repository": { + "type": "git", + "url": "git+https://github.com/googlechrome/workbox.git" + }, + "bugs": "https://github.com/googlechrome/workbox/issues", + "homepage": "https://github.com/GoogleChrome/workbox", + "keywords": [ + "workbox", + "workboxjs", + "service worker", + "sw", + "navigation" + ], + "workbox": { + "browserNamespace": "workbox.navigationPreload", + "packageType": "sw" + }, + "main": "index.js", + "module": "index.mjs", + "types": "index.d.ts", + "dependencies": { + "workbox-core": "7.4.1" + }, + "gitHead": "62b9d8ba8eb3c1a2ab8aac9d84c90cda7865d6a3" +} diff --git a/node_modules/workbox-navigation-preload/src/_version.ts b/node_modules/workbox-navigation-preload/src/_version.ts new file mode 100644 index 0000000000000000000000000000000000000000..8f0e8a7ef36bbb3b9d9379ec8d77042cefca0491 --- /dev/null +++ b/node_modules/workbox-navigation-preload/src/_version.ts @@ -0,0 +1,2 @@ +// @ts-ignore +try{self['workbox:navigation-preload:7.4.1']&&_()}catch(e){} \ No newline at end of file diff --git a/node_modules/workbox-navigation-preload/src/disable.ts b/node_modules/workbox-navigation-preload/src/disable.ts new file mode 100644 index 0000000000000000000000000000000000000000..2255045802eff499396668d58270af13b828655b --- /dev/null +++ b/node_modules/workbox-navigation-preload/src/disable.ts @@ -0,0 +1,39 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {logger} from 'workbox-core/_private/logger.js'; +import {isSupported} from './isSupported.js'; +import './_version.js'; + +// Give TypeScript the correct global. +declare let self: ServiceWorkerGlobalScope; + +/** + * If the browser supports Navigation Preload, then this will disable it. + * + * @memberof workbox-navigation-preload + */ +function disable(): void { + if (isSupported()) { + self.addEventListener('activate', (event: ExtendableEvent) => { + event.waitUntil( + self.registration.navigationPreload.disable().then(() => { + if (process.env.NODE_ENV !== 'production') { + logger.log(`Navigation preload is disabled.`); + } + }), + ); + }); + } else { + if (process.env.NODE_ENV !== 'production') { + logger.log(`Navigation preload is not supported in this browser.`); + } + } +} + +export {disable}; diff --git a/node_modules/workbox-navigation-preload/src/enable.ts b/node_modules/workbox-navigation-preload/src/enable.ts new file mode 100644 index 0000000000000000000000000000000000000000..b33cdc6c17b52455680242dd033a1b6962a6ed9b --- /dev/null +++ b/node_modules/workbox-navigation-preload/src/enable.ts @@ -0,0 +1,51 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {logger} from 'workbox-core/_private/logger.js'; +import {isSupported} from './isSupported.js'; +import './_version.js'; + +// Give TypeScript the correct global. +declare let self: ServiceWorkerGlobalScope; + +/** + * If the browser supports Navigation Preload, then this will enable it. + * + * @param {string} [headerValue] Optionally, allows developers to + * [override](https://developers.google.com/web/updates/2017/02/navigation-preload#changing_the_header) + * the value of the `Service-Worker-Navigation-Preload` header which will be + * sent to the server when making the navigation request. + * + * @memberof workbox-navigation-preload + */ +function enable(headerValue?: string): void { + if (isSupported()) { + self.addEventListener('activate', (event: ExtendableEvent) => { + event.waitUntil( + self.registration.navigationPreload.enable().then(() => { + // Defaults to Service-Worker-Navigation-Preload: true if not set. + if (headerValue) { + void self.registration.navigationPreload.setHeaderValue( + headerValue, + ); + } + + if (process.env.NODE_ENV !== 'production') { + logger.log(`Navigation preload is enabled.`); + } + }), + ); + }); + } else { + if (process.env.NODE_ENV !== 'production') { + logger.log(`Navigation preload is not supported in this browser.`); + } + } +} + +export {enable}; diff --git a/node_modules/workbox-navigation-preload/src/index.ts b/node_modules/workbox-navigation-preload/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..18feaa57ba46f638737923b4fd091343e9ba4d4e --- /dev/null +++ b/node_modules/workbox-navigation-preload/src/index.ts @@ -0,0 +1,37 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {disable} from './disable.js'; +import {enable} from './enable.js'; +import {isSupported} from './isSupported.js'; +import './_version.js'; + +// See https://github.com/GoogleChrome/workbox/issues/2946 +interface NavigationPreloadState { + enabled?: boolean; + headerValue?: string; +} + +interface NavigationPreloadManager { + disable(): Promise; + enable(): Promise; + getState(): Promise; + setHeaderValue(value: string): Promise; +} + +declare global { + interface ServiceWorkerRegistration { + readonly navigationPreload: NavigationPreloadManager; + } +} + +/** + * @module workbox-navigation-preload + */ + +export {disable, enable, isSupported}; diff --git a/node_modules/workbox-navigation-preload/src/isSupported.ts b/node_modules/workbox-navigation-preload/src/isSupported.ts new file mode 100644 index 0000000000000000000000000000000000000000..9319d68203fedbd193b0c72d5bb4fcd1db7d35ad --- /dev/null +++ b/node_modules/workbox-navigation-preload/src/isSupported.ts @@ -0,0 +1,24 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import './_version.js'; + +// Give TypeScript the correct global. +declare let self: ServiceWorkerGlobalScope; + +/** + * @return {boolean} Whether or not the current browser supports enabling + * navigation preload. + * + * @memberof workbox-navigation-preload + */ +function isSupported(): boolean { + return Boolean(self.registration && self.registration.navigationPreload); +} + +export {isSupported}; diff --git a/node_modules/workbox-navigation-preload/tsconfig.json b/node_modules/workbox-navigation-preload/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..2457eadcf8e39664b6315f538007e7de076be21d --- /dev/null +++ b/node_modules/workbox-navigation-preload/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig", + "compilerOptions": { + "outDir": "./", + "rootDir": "./src", + "tsBuildInfoFile": "./tsconfig.tsbuildinfo" + }, + "include": ["src/**/*.ts"], + "references": [{"path": "../workbox-core/"}] +} diff --git a/node_modules/workbox-precaching/LICENSE b/node_modules/workbox-precaching/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..845b545fd0f5031a944cda8cf9018eb066500040 --- /dev/null +++ b/node_modules/workbox-precaching/LICENSE @@ -0,0 +1,19 @@ +Copyright 2018 Google LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/workbox-precaching/PrecacheController.d.ts b/node_modules/workbox-precaching/PrecacheController.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bc48e4b14fdd39552e3d2573f1e8a9f5d2ba0cdb --- /dev/null +++ b/node_modules/workbox-precaching/PrecacheController.d.ts @@ -0,0 +1,142 @@ +import { Strategy } from 'workbox-strategies/Strategy.js'; +import { RouteHandlerCallback, WorkboxPlugin } from 'workbox-core/types.js'; +import { PrecacheEntry, InstallResult, CleanupResult } from './_types.js'; +import './_version.js'; +declare global { + interface ServiceWorkerGlobalScope { + __WB_MANIFEST: Array; + } +} +interface PrecacheControllerOptions { + cacheName?: string; + plugins?: WorkboxPlugin[]; + fallbackToNetwork?: boolean; +} +/** + * Performs efficient precaching of assets. + * + * @memberof workbox-precaching + */ +declare class PrecacheController { + private _installAndActiveListenersAdded?; + private readonly _strategy; + private readonly _urlsToCacheKeys; + private readonly _urlsToCacheModes; + private readonly _cacheKeysToIntegrities; + /** + * Create a new PrecacheController. + * + * @param {Object} [options] + * @param {string} [options.cacheName] The cache to use for precaching. + * @param {string} [options.plugins] Plugins to use when precaching as well + * as responding to fetch events for precached assets. + * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to + * get the response from the network if there's a precache miss. + */ + constructor({ cacheName, plugins, fallbackToNetwork, }?: PrecacheControllerOptions); + /** + * @type {workbox-precaching.PrecacheStrategy} The strategy created by this controller and + * used to cache assets and respond to fetch events. + */ + get strategy(): Strategy; + /** + * Adds items to the precache list, removing any duplicates and + * stores the files in the + * {@link workbox-core.cacheNames|"precache cache"} when the service + * worker installs. + * + * This method can be called multiple times. + * + * @param {Array} [entries=[]] Array of entries to precache. + */ + precache(entries: Array): void; + /** + * This method will add items to the precache list, removing duplicates + * and ensuring the information is valid. + * + * @param {Array} entries + * Array of entries to precache. + */ + addToCacheList(entries: Array): void; + /** + * Precaches new and updated assets. Call this method from the service worker + * install event. + * + * Note: this method calls `event.waitUntil()` for you, so you do not need + * to call it yourself in your event handlers. + * + * @param {ExtendableEvent} event + * @return {Promise} + */ + install(event: ExtendableEvent): Promise; + /** + * Deletes assets that are no longer present in the current precache manifest. + * Call this method from the service worker activate event. + * + * Note: this method calls `event.waitUntil()` for you, so you do not need + * to call it yourself in your event handlers. + * + * @param {ExtendableEvent} event + * @return {Promise} + */ + activate(event: ExtendableEvent): Promise; + /** + * Returns a mapping of a precached URL to the corresponding cache key, taking + * into account the revision information for the URL. + * + * @return {Map} A URL to cache key mapping. + */ + getURLsToCacheKeys(): Map; + /** + * Returns a list of all the URLs that have been precached by the current + * service worker. + * + * @return {Array} The precached URLs. + */ + getCachedURLs(): Array; + /** + * Returns the cache key used for storing a given URL. If that URL is + * unversioned, like `/index.html', then the cache key will be the original + * URL with a search parameter appended to it. + * + * @param {string} url A URL whose cache key you want to look up. + * @return {string} The versioned URL that corresponds to a cache key + * for the original URL, or undefined if that URL isn't precached. + */ + getCacheKeyForURL(url: string): string | undefined; + /** + * @param {string} url A cache key whose SRI you want to look up. + * @return {string} The subresource integrity associated with the cache key, + * or undefined if it's not set. + */ + getIntegrityForCacheKey(cacheKey: string): string | undefined; + /** + * This acts as a drop-in replacement for + * [`cache.match()`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/match) + * with the following differences: + * + * - It knows what the name of the precache is, and only checks in that cache. + * - It allows you to pass in an "original" URL without versioning parameters, + * and it will automatically look up the correct cache key for the currently + * active revision of that URL. + * + * E.g., `matchPrecache('index.html')` will find the correct precached + * response for the currently active service worker, even if the actual cache + * key is `'/index.html?__WB_REVISION__=1234abcd'`. + * + * @param {string|Request} request The key (without revisioning parameters) + * to look up in the precache. + * @return {Promise} + */ + matchPrecache(request: string | Request): Promise; + /** + * Returns a function that looks up `url` in the precache (taking into + * account revision information), and returns the corresponding `Response`. + * + * @param {string} url The precached URL which will be used to lookup the + * `Response`. + * @return {workbox-routing~handlerCallback} + */ + createHandlerBoundToURL(url: string): RouteHandlerCallback; +} +export { PrecacheController }; diff --git a/node_modules/workbox-precaching/PrecacheController.js b/node_modules/workbox-precaching/PrecacheController.js new file mode 100644 index 0000000000000000000000000000000000000000..e00975e3762dc6382c39bebee04a89a651aae3d0 --- /dev/null +++ b/node_modules/workbox-precaching/PrecacheController.js @@ -0,0 +1,292 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { assert } from 'workbox-core/_private/assert.js'; +import { cacheNames } from 'workbox-core/_private/cacheNames.js'; +import { logger } from 'workbox-core/_private/logger.js'; +import { WorkboxError } from 'workbox-core/_private/WorkboxError.js'; +import { waitUntil } from 'workbox-core/_private/waitUntil.js'; +import { createCacheKey } from './utils/createCacheKey.js'; +import { PrecacheInstallReportPlugin } from './utils/PrecacheInstallReportPlugin.js'; +import { PrecacheCacheKeyPlugin } from './utils/PrecacheCacheKeyPlugin.js'; +import { printCleanupDetails } from './utils/printCleanupDetails.js'; +import { printInstallDetails } from './utils/printInstallDetails.js'; +import { PrecacheStrategy } from './PrecacheStrategy.js'; +import './_version.js'; +/** + * Performs efficient precaching of assets. + * + * @memberof workbox-precaching + */ +class PrecacheController { + /** + * Create a new PrecacheController. + * + * @param {Object} [options] + * @param {string} [options.cacheName] The cache to use for precaching. + * @param {string} [options.plugins] Plugins to use when precaching as well + * as responding to fetch events for precached assets. + * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to + * get the response from the network if there's a precache miss. + */ + constructor({ cacheName, plugins = [], fallbackToNetwork = true, } = {}) { + this._urlsToCacheKeys = new Map(); + this._urlsToCacheModes = new Map(); + this._cacheKeysToIntegrities = new Map(); + this._strategy = new PrecacheStrategy({ + cacheName: cacheNames.getPrecacheName(cacheName), + plugins: [ + ...plugins, + new PrecacheCacheKeyPlugin({ precacheController: this }), + ], + fallbackToNetwork, + }); + // Bind the install and activate methods to the instance. + this.install = this.install.bind(this); + this.activate = this.activate.bind(this); + } + /** + * @type {workbox-precaching.PrecacheStrategy} The strategy created by this controller and + * used to cache assets and respond to fetch events. + */ + get strategy() { + return this._strategy; + } + /** + * Adds items to the precache list, removing any duplicates and + * stores the files in the + * {@link workbox-core.cacheNames|"precache cache"} when the service + * worker installs. + * + * This method can be called multiple times. + * + * @param {Array} [entries=[]] Array of entries to precache. + */ + precache(entries) { + this.addToCacheList(entries); + if (!this._installAndActiveListenersAdded) { + self.addEventListener('install', this.install); + self.addEventListener('activate', this.activate); + this._installAndActiveListenersAdded = true; + } + } + /** + * This method will add items to the precache list, removing duplicates + * and ensuring the information is valid. + * + * @param {Array} entries + * Array of entries to precache. + */ + addToCacheList(entries) { + if (process.env.NODE_ENV !== 'production') { + assert.isArray(entries, { + moduleName: 'workbox-precaching', + className: 'PrecacheController', + funcName: 'addToCacheList', + paramName: 'entries', + }); + } + const urlsToWarnAbout = []; + for (const entry of entries) { + // See https://github.com/GoogleChrome/workbox/issues/2259 + if (typeof entry === 'string') { + urlsToWarnAbout.push(entry); + } + else if (entry && entry.revision === undefined) { + urlsToWarnAbout.push(entry.url); + } + const { cacheKey, url } = createCacheKey(entry); + const cacheMode = typeof entry !== 'string' && entry.revision ? 'reload' : 'default'; + if (this._urlsToCacheKeys.has(url) && + this._urlsToCacheKeys.get(url) !== cacheKey) { + throw new WorkboxError('add-to-cache-list-conflicting-entries', { + firstEntry: this._urlsToCacheKeys.get(url), + secondEntry: cacheKey, + }); + } + if (typeof entry !== 'string' && entry.integrity) { + if (this._cacheKeysToIntegrities.has(cacheKey) && + this._cacheKeysToIntegrities.get(cacheKey) !== entry.integrity) { + throw new WorkboxError('add-to-cache-list-conflicting-integrities', { + url, + }); + } + this._cacheKeysToIntegrities.set(cacheKey, entry.integrity); + } + this._urlsToCacheKeys.set(url, cacheKey); + this._urlsToCacheModes.set(url, cacheMode); + if (urlsToWarnAbout.length > 0) { + const warningMessage = `Workbox is precaching URLs without revision ` + + `info: ${urlsToWarnAbout.join(', ')}\nThis is generally NOT safe. ` + + `Learn more at https://bit.ly/wb-precache`; + if (process.env.NODE_ENV === 'production') { + // Use console directly to display this warning without bloating + // bundle sizes by pulling in all of the logger codebase in prod. + console.warn(warningMessage); + } + else { + logger.warn(warningMessage); + } + } + } + } + /** + * Precaches new and updated assets. Call this method from the service worker + * install event. + * + * Note: this method calls `event.waitUntil()` for you, so you do not need + * to call it yourself in your event handlers. + * + * @param {ExtendableEvent} event + * @return {Promise} + */ + install(event) { + // waitUntil returns Promise + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return waitUntil(event, async () => { + const installReportPlugin = new PrecacheInstallReportPlugin(); + this.strategy.plugins.push(installReportPlugin); + // Cache entries one at a time. + // See https://github.com/GoogleChrome/workbox/issues/2528 + for (const [url, cacheKey] of this._urlsToCacheKeys) { + const integrity = this._cacheKeysToIntegrities.get(cacheKey); + const cacheMode = this._urlsToCacheModes.get(url); + const request = new Request(url, { + integrity, + cache: cacheMode, + credentials: 'same-origin', + }); + await Promise.all(this.strategy.handleAll({ + params: { cacheKey }, + request, + event, + })); + } + const { updatedURLs, notUpdatedURLs } = installReportPlugin; + if (process.env.NODE_ENV !== 'production') { + printInstallDetails(updatedURLs, notUpdatedURLs); + } + return { updatedURLs, notUpdatedURLs }; + }); + } + /** + * Deletes assets that are no longer present in the current precache manifest. + * Call this method from the service worker activate event. + * + * Note: this method calls `event.waitUntil()` for you, so you do not need + * to call it yourself in your event handlers. + * + * @param {ExtendableEvent} event + * @return {Promise} + */ + activate(event) { + // waitUntil returns Promise + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return waitUntil(event, async () => { + const cache = await self.caches.open(this.strategy.cacheName); + const currentlyCachedRequests = await cache.keys(); + const expectedCacheKeys = new Set(this._urlsToCacheKeys.values()); + const deletedURLs = []; + for (const request of currentlyCachedRequests) { + if (!expectedCacheKeys.has(request.url)) { + await cache.delete(request); + deletedURLs.push(request.url); + } + } + if (process.env.NODE_ENV !== 'production') { + printCleanupDetails(deletedURLs); + } + return { deletedURLs }; + }); + } + /** + * Returns a mapping of a precached URL to the corresponding cache key, taking + * into account the revision information for the URL. + * + * @return {Map} A URL to cache key mapping. + */ + getURLsToCacheKeys() { + return this._urlsToCacheKeys; + } + /** + * Returns a list of all the URLs that have been precached by the current + * service worker. + * + * @return {Array} The precached URLs. + */ + getCachedURLs() { + return [...this._urlsToCacheKeys.keys()]; + } + /** + * Returns the cache key used for storing a given URL. If that URL is + * unversioned, like `/index.html', then the cache key will be the original + * URL with a search parameter appended to it. + * + * @param {string} url A URL whose cache key you want to look up. + * @return {string} The versioned URL that corresponds to a cache key + * for the original URL, or undefined if that URL isn't precached. + */ + getCacheKeyForURL(url) { + const urlObject = new URL(url, location.href); + return this._urlsToCacheKeys.get(urlObject.href); + } + /** + * @param {string} url A cache key whose SRI you want to look up. + * @return {string} The subresource integrity associated with the cache key, + * or undefined if it's not set. + */ + getIntegrityForCacheKey(cacheKey) { + return this._cacheKeysToIntegrities.get(cacheKey); + } + /** + * This acts as a drop-in replacement for + * [`cache.match()`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/match) + * with the following differences: + * + * - It knows what the name of the precache is, and only checks in that cache. + * - It allows you to pass in an "original" URL without versioning parameters, + * and it will automatically look up the correct cache key for the currently + * active revision of that URL. + * + * E.g., `matchPrecache('index.html')` will find the correct precached + * response for the currently active service worker, even if the actual cache + * key is `'/index.html?__WB_REVISION__=1234abcd'`. + * + * @param {string|Request} request The key (without revisioning parameters) + * to look up in the precache. + * @return {Promise} + */ + async matchPrecache(request) { + const url = request instanceof Request ? request.url : request; + const cacheKey = this.getCacheKeyForURL(url); + if (cacheKey) { + const cache = await self.caches.open(this.strategy.cacheName); + return cache.match(cacheKey); + } + return undefined; + } + /** + * Returns a function that looks up `url` in the precache (taking into + * account revision information), and returns the corresponding `Response`. + * + * @param {string} url The precached URL which will be used to lookup the + * `Response`. + * @return {workbox-routing~handlerCallback} + */ + createHandlerBoundToURL(url) { + const cacheKey = this.getCacheKeyForURL(url); + if (!cacheKey) { + throw new WorkboxError('non-precached-url', { url }); + } + return (options) => { + options.request = new Request(url); + options.params = Object.assign({ cacheKey }, options.params); + return this.strategy.handle(options); + }; + } +} +export { PrecacheController }; diff --git a/node_modules/workbox-precaching/PrecacheController.mjs b/node_modules/workbox-precaching/PrecacheController.mjs new file mode 100644 index 0000000000000000000000000000000000000000..94dfd0f46a16292ecf61113679a36abe67dc0b43 --- /dev/null +++ b/node_modules/workbox-precaching/PrecacheController.mjs @@ -0,0 +1 @@ +export * from './PrecacheController.js'; \ No newline at end of file diff --git a/node_modules/workbox-precaching/PrecacheFallbackPlugin.d.ts b/node_modules/workbox-precaching/PrecacheFallbackPlugin.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5f7eeb4d02282a69d795def5562e9a3b990422ea --- /dev/null +++ b/node_modules/workbox-precaching/PrecacheFallbackPlugin.d.ts @@ -0,0 +1,42 @@ +import { WorkboxPlugin } from 'workbox-core/types.js'; +import { PrecacheController } from './PrecacheController.js'; +import './_version.js'; +/** + * `PrecacheFallbackPlugin` allows you to specify an "offline fallback" + * response to be used when a given strategy is unable to generate a response. + * + * It does this by intercepting the `handlerDidError` plugin callback + * and returning a precached response, taking the expected revision parameter + * into account automatically. + * + * Unless you explicitly pass in a `PrecacheController` instance to the + * constructor, the default instance will be used. Generally speaking, most + * developers will end up using the default. + * + * @memberof workbox-precaching + */ +declare class PrecacheFallbackPlugin implements WorkboxPlugin { + private readonly _fallbackURL; + private readonly _precacheController; + /** + * Constructs a new PrecacheFallbackPlugin with the associated fallbackURL. + * + * @param {Object} config + * @param {string} config.fallbackURL A precached URL to use as the fallback + * if the associated strategy can't generate a response. + * @param {PrecacheController} [config.precacheController] An optional + * PrecacheController instance. If not provided, the default + * PrecacheController will be used. + */ + constructor({ fallbackURL, precacheController, }: { + fallbackURL: string; + precacheController?: PrecacheController; + }); + /** + * @return {Promise} The precache response for the fallback URL. + * + * @private + */ + handlerDidError: WorkboxPlugin['handlerDidError']; +} +export { PrecacheFallbackPlugin }; diff --git a/node_modules/workbox-precaching/PrecacheFallbackPlugin.js b/node_modules/workbox-precaching/PrecacheFallbackPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..e3a9dedaa3b6768c9f16e61230787e6ebb1c7722 --- /dev/null +++ b/node_modules/workbox-precaching/PrecacheFallbackPlugin.js @@ -0,0 +1,47 @@ +/* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js'; +import './_version.js'; +/** + * `PrecacheFallbackPlugin` allows you to specify an "offline fallback" + * response to be used when a given strategy is unable to generate a response. + * + * It does this by intercepting the `handlerDidError` plugin callback + * and returning a precached response, taking the expected revision parameter + * into account automatically. + * + * Unless you explicitly pass in a `PrecacheController` instance to the + * constructor, the default instance will be used. Generally speaking, most + * developers will end up using the default. + * + * @memberof workbox-precaching + */ +class PrecacheFallbackPlugin { + /** + * Constructs a new PrecacheFallbackPlugin with the associated fallbackURL. + * + * @param {Object} config + * @param {string} config.fallbackURL A precached URL to use as the fallback + * if the associated strategy can't generate a response. + * @param {PrecacheController} [config.precacheController] An optional + * PrecacheController instance. If not provided, the default + * PrecacheController will be used. + */ + constructor({ fallbackURL, precacheController, }) { + /** + * @return {Promise} The precache response for the fallback URL. + * + * @private + */ + this.handlerDidError = () => this._precacheController.matchPrecache(this._fallbackURL); + this._fallbackURL = fallbackURL; + this._precacheController = + precacheController || getOrCreatePrecacheController(); + } +} +export { PrecacheFallbackPlugin }; diff --git a/node_modules/workbox-precaching/PrecacheFallbackPlugin.mjs b/node_modules/workbox-precaching/PrecacheFallbackPlugin.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6d8c04b21b745bdef28f14342f8c695fccf5a657 --- /dev/null +++ b/node_modules/workbox-precaching/PrecacheFallbackPlugin.mjs @@ -0,0 +1 @@ +export * from './PrecacheFallbackPlugin.js'; \ No newline at end of file diff --git a/node_modules/workbox-precaching/PrecacheRoute.d.ts b/node_modules/workbox-precaching/PrecacheRoute.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..01a43c10221a66992e63ddcbba069f8a22ebf63c --- /dev/null +++ b/node_modules/workbox-precaching/PrecacheRoute.d.ts @@ -0,0 +1,33 @@ +import { Route } from 'workbox-routing/Route.js'; +import { PrecacheRouteOptions } from './_types.js'; +import { PrecacheController } from './PrecacheController.js'; +import './_version.js'; +/** + * A subclass of {@link workbox-routing.Route} that takes a + * {@link workbox-precaching.PrecacheController} + * instance and uses it to match incoming requests and handle fetching + * responses from the precache. + * + * @memberof workbox-precaching + * @extends workbox-routing.Route + */ +declare class PrecacheRoute extends Route { + /** + * @param {PrecacheController} precacheController A `PrecacheController` + * instance used to both match requests and respond to fetch events. + * @param {Object} [options] Options to control how requests are matched + * against the list of precached URLs. + * @param {string} [options.directoryIndex=index.html] The `directoryIndex` will + * check cache entries for a URLs ending with '/' to see if there is a hit when + * appending the `directoryIndex` value. + * @param {Array} [options.ignoreURLParametersMatching=[/^utm_/, /^fbclid$/]] An + * array of regex's to remove search params when looking for a cache match. + * @param {boolean} [options.cleanURLs=true] The `cleanURLs` option will + * check the cache for the URL with a `.html` added to the end of the end. + * @param {workbox-precaching~urlManipulation} [options.urlManipulation] + * This is a function that should take a URL and return an array of + * alternative URLs that should be checked for precache matches. + */ + constructor(precacheController: PrecacheController, options?: PrecacheRouteOptions); +} +export { PrecacheRoute }; diff --git a/node_modules/workbox-precaching/PrecacheRoute.js b/node_modules/workbox-precaching/PrecacheRoute.js new file mode 100644 index 0000000000000000000000000000000000000000..bf2e9caee51af773af0b85966311a3be8f70cb1b --- /dev/null +++ b/node_modules/workbox-precaching/PrecacheRoute.js @@ -0,0 +1,57 @@ +/* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { logger } from 'workbox-core/_private/logger.js'; +import { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js'; +import { Route } from 'workbox-routing/Route.js'; +import { generateURLVariations } from './utils/generateURLVariations.js'; +import './_version.js'; +/** + * A subclass of {@link workbox-routing.Route} that takes a + * {@link workbox-precaching.PrecacheController} + * instance and uses it to match incoming requests and handle fetching + * responses from the precache. + * + * @memberof workbox-precaching + * @extends workbox-routing.Route + */ +class PrecacheRoute extends Route { + /** + * @param {PrecacheController} precacheController A `PrecacheController` + * instance used to both match requests and respond to fetch events. + * @param {Object} [options] Options to control how requests are matched + * against the list of precached URLs. + * @param {string} [options.directoryIndex=index.html] The `directoryIndex` will + * check cache entries for a URLs ending with '/' to see if there is a hit when + * appending the `directoryIndex` value. + * @param {Array} [options.ignoreURLParametersMatching=[/^utm_/, /^fbclid$/]] An + * array of regex's to remove search params when looking for a cache match. + * @param {boolean} [options.cleanURLs=true] The `cleanURLs` option will + * check the cache for the URL with a `.html` added to the end of the end. + * @param {workbox-precaching~urlManipulation} [options.urlManipulation] + * This is a function that should take a URL and return an array of + * alternative URLs that should be checked for precache matches. + */ + constructor(precacheController, options) { + const match = ({ request, }) => { + const urlsToCacheKeys = precacheController.getURLsToCacheKeys(); + for (const possibleURL of generateURLVariations(request.url, options)) { + const cacheKey = urlsToCacheKeys.get(possibleURL); + if (cacheKey) { + const integrity = precacheController.getIntegrityForCacheKey(cacheKey); + return { cacheKey, integrity }; + } + } + if (process.env.NODE_ENV !== 'production') { + logger.debug(`Precaching did not find a match for ` + getFriendlyURL(request.url)); + } + return; + }; + super(match, precacheController.strategy); + } +} +export { PrecacheRoute }; diff --git a/node_modules/workbox-precaching/PrecacheRoute.mjs b/node_modules/workbox-precaching/PrecacheRoute.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4e81c0621ac37f0ab633f4cebc81ce617a5d38e3 --- /dev/null +++ b/node_modules/workbox-precaching/PrecacheRoute.mjs @@ -0,0 +1 @@ +export * from './PrecacheRoute.js'; \ No newline at end of file diff --git a/node_modules/workbox-precaching/PrecacheStrategy.d.ts b/node_modules/workbox-precaching/PrecacheStrategy.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..000e177ef7d04cc89f9d94f9efb00adfc7122df1 --- /dev/null +++ b/node_modules/workbox-precaching/PrecacheStrategy.d.ts @@ -0,0 +1,81 @@ +import { WorkboxPlugin } from 'workbox-core/types.js'; +import { Strategy, StrategyOptions } from 'workbox-strategies/Strategy.js'; +import { StrategyHandler } from 'workbox-strategies/StrategyHandler.js'; +import './_version.js'; +interface PrecacheStrategyOptions extends StrategyOptions { + fallbackToNetwork?: boolean; +} +/** + * A {@link workbox-strategies.Strategy} implementation + * specifically designed to work with + * {@link workbox-precaching.PrecacheController} + * to both cache and fetch precached assets. + * + * Note: an instance of this class is created automatically when creating a + * `PrecacheController`; it's generally not necessary to create this yourself. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-precaching + */ +declare class PrecacheStrategy extends Strategy { + private readonly _fallbackToNetwork; + static readonly defaultPrecacheCacheabilityPlugin: WorkboxPlugin; + static readonly copyRedirectedCacheableResponsesPlugin: WorkboxPlugin; + /** + * + * @param {Object} [options] + * @param {string} [options.cacheName] Cache name to store and retrieve + * requests. Defaults to the cache names provided by + * {@link workbox-core.cacheNames}. + * @param {Array} [options.plugins] {@link https://developers.google.com/web/tools/workbox/guides/using-plugins|Plugins} + * to use in conjunction with this caching strategy. + * @param {Object} [options.fetchOptions] Values passed along to the + * {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters|init} + * of all fetch() requests made by this strategy. + * @param {Object} [options.matchOptions] The + * {@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions|CacheQueryOptions} + * for any `cache.match()` or `cache.put()` calls made by this strategy. + * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to + * get the response from the network if there's a precache miss. + */ + constructor(options?: PrecacheStrategyOptions); + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + _handle(request: Request, handler: StrategyHandler): Promise; + _handleFetch(request: Request, handler: StrategyHandler): Promise; + _handleInstall(request: Request, handler: StrategyHandler): Promise; + /** + * This method is complex, as there a number of things to account for: + * + * The `plugins` array can be set at construction, and/or it might be added to + * to at any time before the strategy is used. + * + * At the time the strategy is used (i.e. during an `install` event), there + * needs to be at least one plugin that implements `cacheWillUpdate` in the + * array, other than `copyRedirectedCacheableResponsesPlugin`. + * + * - If this method is called and there are no suitable `cacheWillUpdate` + * plugins, we need to add `defaultPrecacheCacheabilityPlugin`. + * + * - If this method is called and there is exactly one `cacheWillUpdate`, then + * we don't have to do anything (this might be a previously added + * `defaultPrecacheCacheabilityPlugin`, or it might be a custom plugin). + * + * - If this method is called and there is more than one `cacheWillUpdate`, + * then we need to check if one is `defaultPrecacheCacheabilityPlugin`. If so, + * we need to remove it. (This situation is unlikely, but it could happen if + * the strategy is used multiple times, the first without a `cacheWillUpdate`, + * and then later on after manually adding a custom `cacheWillUpdate`.) + * + * See https://github.com/GoogleChrome/workbox/issues/2737 for more context. + * + * @private + */ + _useDefaultCacheabilityPluginIfNeeded(): void; +} +export { PrecacheStrategy }; diff --git a/node_modules/workbox-precaching/PrecacheStrategy.js b/node_modules/workbox-precaching/PrecacheStrategy.js new file mode 100644 index 0000000000000000000000000000000000000000..736853a631ae41f39c8db36f550f75fe779b07df --- /dev/null +++ b/node_modules/workbox-precaching/PrecacheStrategy.js @@ -0,0 +1,223 @@ +/* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { copyResponse } from 'workbox-core/copyResponse.js'; +import { cacheNames } from 'workbox-core/_private/cacheNames.js'; +import { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js'; +import { logger } from 'workbox-core/_private/logger.js'; +import { WorkboxError } from 'workbox-core/_private/WorkboxError.js'; +import { Strategy } from 'workbox-strategies/Strategy.js'; +import './_version.js'; +/** + * A {@link workbox-strategies.Strategy} implementation + * specifically designed to work with + * {@link workbox-precaching.PrecacheController} + * to both cache and fetch precached assets. + * + * Note: an instance of this class is created automatically when creating a + * `PrecacheController`; it's generally not necessary to create this yourself. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-precaching + */ +class PrecacheStrategy extends Strategy { + /** + * + * @param {Object} [options] + * @param {string} [options.cacheName] Cache name to store and retrieve + * requests. Defaults to the cache names provided by + * {@link workbox-core.cacheNames}. + * @param {Array} [options.plugins] {@link https://developers.google.com/web/tools/workbox/guides/using-plugins|Plugins} + * to use in conjunction with this caching strategy. + * @param {Object} [options.fetchOptions] Values passed along to the + * {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters|init} + * of all fetch() requests made by this strategy. + * @param {Object} [options.matchOptions] The + * {@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions|CacheQueryOptions} + * for any `cache.match()` or `cache.put()` calls made by this strategy. + * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to + * get the response from the network if there's a precache miss. + */ + constructor(options = {}) { + options.cacheName = cacheNames.getPrecacheName(options.cacheName); + super(options); + this._fallbackToNetwork = + options.fallbackToNetwork === false ? false : true; + // Redirected responses cannot be used to satisfy a navigation request, so + // any redirected response must be "copied" rather than cloned, so the new + // response doesn't contain the `redirected` flag. See: + // https://bugs.chromium.org/p/chromium/issues/detail?id=669363&desc=2#c1 + this.plugins.push(PrecacheStrategy.copyRedirectedCacheableResponsesPlugin); + } + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + async _handle(request, handler) { + const response = await handler.cacheMatch(request); + if (response) { + return response; + } + // If this is an `install` event for an entry that isn't already cached, + // then populate the cache. + if (handler.event && handler.event.type === 'install') { + return await this._handleInstall(request, handler); + } + // Getting here means something went wrong. An entry that should have been + // precached wasn't found in the cache. + return await this._handleFetch(request, handler); + } + async _handleFetch(request, handler) { + let response; + const params = (handler.params || {}); + // Fall back to the network if we're configured to do so. + if (this._fallbackToNetwork) { + if (process.env.NODE_ENV !== 'production') { + logger.warn(`The precached response for ` + + `${getFriendlyURL(request.url)} in ${this.cacheName} was not ` + + `found. Falling back to the network.`); + } + const integrityInManifest = params.integrity; + const integrityInRequest = request.integrity; + const noIntegrityConflict = !integrityInRequest || integrityInRequest === integrityInManifest; + // Do not add integrity if the original request is no-cors + // See https://github.com/GoogleChrome/workbox/issues/3096 + response = await handler.fetch(new Request(request, { + integrity: request.mode !== 'no-cors' + ? integrityInRequest || integrityInManifest + : undefined, + })); + // It's only "safe" to repair the cache if we're using SRI to guarantee + // that the response matches the precache manifest's expectations, + // and there's either a) no integrity property in the incoming request + // or b) there is an integrity, and it matches the precache manifest. + // See https://github.com/GoogleChrome/workbox/issues/2858 + // Also if the original request users no-cors we don't use integrity. + // See https://github.com/GoogleChrome/workbox/issues/3096 + if (integrityInManifest && + noIntegrityConflict && + request.mode !== 'no-cors') { + this._useDefaultCacheabilityPluginIfNeeded(); + const wasCached = await handler.cachePut(request, response.clone()); + if (process.env.NODE_ENV !== 'production') { + if (wasCached) { + logger.log(`A response for ${getFriendlyURL(request.url)} ` + + `was used to "repair" the precache.`); + } + } + } + } + else { + // This shouldn't normally happen, but there are edge cases: + // https://github.com/GoogleChrome/workbox/issues/1441 + throw new WorkboxError('missing-precache-entry', { + cacheName: this.cacheName, + url: request.url, + }); + } + if (process.env.NODE_ENV !== 'production') { + const cacheKey = params.cacheKey || (await handler.getCacheKey(request, 'read')); + // Workbox is going to handle the route. + // print the routing details to the console. + logger.groupCollapsed(`Precaching is responding to: ` + getFriendlyURL(request.url)); + logger.log(`Serving the precached url: ${getFriendlyURL(cacheKey instanceof Request ? cacheKey.url : cacheKey)}`); + logger.groupCollapsed(`View request details here.`); + logger.log(request); + logger.groupEnd(); + logger.groupCollapsed(`View response details here.`); + logger.log(response); + logger.groupEnd(); + logger.groupEnd(); + } + return response; + } + async _handleInstall(request, handler) { + this._useDefaultCacheabilityPluginIfNeeded(); + const response = await handler.fetch(request); + // Make sure we defer cachePut() until after we know the response + // should be cached; see https://github.com/GoogleChrome/workbox/issues/2737 + const wasCached = await handler.cachePut(request, response.clone()); + if (!wasCached) { + // Throwing here will lead to the `install` handler failing, which + // we want to do if *any* of the responses aren't safe to cache. + throw new WorkboxError('bad-precaching-response', { + url: request.url, + status: response.status, + }); + } + return response; + } + /** + * This method is complex, as there a number of things to account for: + * + * The `plugins` array can be set at construction, and/or it might be added to + * to at any time before the strategy is used. + * + * At the time the strategy is used (i.e. during an `install` event), there + * needs to be at least one plugin that implements `cacheWillUpdate` in the + * array, other than `copyRedirectedCacheableResponsesPlugin`. + * + * - If this method is called and there are no suitable `cacheWillUpdate` + * plugins, we need to add `defaultPrecacheCacheabilityPlugin`. + * + * - If this method is called and there is exactly one `cacheWillUpdate`, then + * we don't have to do anything (this might be a previously added + * `defaultPrecacheCacheabilityPlugin`, or it might be a custom plugin). + * + * - If this method is called and there is more than one `cacheWillUpdate`, + * then we need to check if one is `defaultPrecacheCacheabilityPlugin`. If so, + * we need to remove it. (This situation is unlikely, but it could happen if + * the strategy is used multiple times, the first without a `cacheWillUpdate`, + * and then later on after manually adding a custom `cacheWillUpdate`.) + * + * See https://github.com/GoogleChrome/workbox/issues/2737 for more context. + * + * @private + */ + _useDefaultCacheabilityPluginIfNeeded() { + let defaultPluginIndex = null; + let cacheWillUpdatePluginCount = 0; + for (const [index, plugin] of this.plugins.entries()) { + // Ignore the copy redirected plugin when determining what to do. + if (plugin === PrecacheStrategy.copyRedirectedCacheableResponsesPlugin) { + continue; + } + // Save the default plugin's index, in case it needs to be removed. + if (plugin === PrecacheStrategy.defaultPrecacheCacheabilityPlugin) { + defaultPluginIndex = index; + } + if (plugin.cacheWillUpdate) { + cacheWillUpdatePluginCount++; + } + } + if (cacheWillUpdatePluginCount === 0) { + this.plugins.push(PrecacheStrategy.defaultPrecacheCacheabilityPlugin); + } + else if (cacheWillUpdatePluginCount > 1 && defaultPluginIndex !== null) { + // Only remove the default plugin; multiple custom plugins are allowed. + this.plugins.splice(defaultPluginIndex, 1); + } + // Nothing needs to be done if cacheWillUpdatePluginCount is 1 + } +} +PrecacheStrategy.defaultPrecacheCacheabilityPlugin = { + async cacheWillUpdate({ response }) { + if (!response || response.status >= 400) { + return null; + } + return response; + }, +}; +PrecacheStrategy.copyRedirectedCacheableResponsesPlugin = { + async cacheWillUpdate({ response }) { + return response.redirected ? await copyResponse(response) : response; + }, +}; +export { PrecacheStrategy }; diff --git a/node_modules/workbox-precaching/PrecacheStrategy.mjs b/node_modules/workbox-precaching/PrecacheStrategy.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f6d929157560060b9b85bce1f32d7865bd5a83f6 --- /dev/null +++ b/node_modules/workbox-precaching/PrecacheStrategy.mjs @@ -0,0 +1 @@ +export * from './PrecacheStrategy.js'; \ No newline at end of file diff --git a/node_modules/workbox-precaching/README.md b/node_modules/workbox-precaching/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c1f629bc4489af62d7310b25944bbd5deb026d01 --- /dev/null +++ b/node_modules/workbox-precaching/README.md @@ -0,0 +1 @@ +This module's documentation can be found at https://developers.google.com/web/tools/workbox/modules/workbox-precaching diff --git a/node_modules/workbox-precaching/_types.d.ts b/node_modules/workbox-precaching/_types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f2b765e2f79b935c306ed1094b25fbae2ad23acd --- /dev/null +++ b/node_modules/workbox-precaching/_types.d.ts @@ -0,0 +1,63 @@ +import './_version.js'; +export interface InstallResult { + updatedURLs: string[]; + notUpdatedURLs: string[]; +} +export interface CleanupResult { + deletedCacheRequests: string[]; +} +export declare interface PrecacheEntry { + integrity?: string; + url: string; + revision?: string | null; +} +export interface PrecacheRouteOptions { + directoryIndex?: string; + ignoreURLParametersMatching?: RegExp[]; + cleanURLs?: boolean; + urlManipulation?: urlManipulation; +} +export type urlManipulation = ({ url }: { + url: URL; +}) => URL[]; +/** + * @typedef {Object} InstallResult + * @property {Array} updatedURLs List of URLs that were updated during + * installation. + * @property {Array} notUpdatedURLs List of URLs that were already up to + * date. + * + * @memberof workbox-precaching + */ +/** + * @typedef {Object} CleanupResult + * @property {Array} deletedCacheRequests List of URLs that were deleted + * while cleaning up the cache. + * + * @memberof workbox-precaching + */ +/** + * @typedef {Object} PrecacheEntry + * @property {string} url URL to precache. + * @property {string} [revision] Revision information for the URL. + * @property {string} [integrity] Integrity metadata that will be used when + * making the network request for the URL. + * + * @memberof workbox-precaching + */ +/** + * The "urlManipulation" callback can be used to determine if there are any + * additional permutations of a URL that should be used to check against + * the available precached files. + * + * For example, Workbox supports checking for '/index.html' when the URL + * '/' is provided. This callback allows additional, custom checks. + * + * @callback ~urlManipulation + * @param {Object} context + * @param {URL} context.url The request's URL. + * @return {Array} To add additional urls to test, return an Array of + * URLs. Please note that these **should not be strings**, but URL objects. + * + * @memberof workbox-precaching + */ diff --git a/node_modules/workbox-precaching/_types.js b/node_modules/workbox-precaching/_types.js new file mode 100644 index 0000000000000000000000000000000000000000..319d76a9a72225fc2b1ea5c8515b8242341061b5 --- /dev/null +++ b/node_modules/workbox-precaching/_types.js @@ -0,0 +1,55 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import './_version.js'; +// * * * IMPORTANT! * * * +// ------------------------------------------------------------------------- // +// jdsoc type definitions cannot be declared above TypeScript definitions or +// they'll be stripped from the built `.js` files, and they'll only be in the +// `d.ts` files, which aren't read by the jsdoc generator. As a result we +// have to put declare them below. +/** + * @typedef {Object} InstallResult + * @property {Array} updatedURLs List of URLs that were updated during + * installation. + * @property {Array} notUpdatedURLs List of URLs that were already up to + * date. + * + * @memberof workbox-precaching + */ +/** + * @typedef {Object} CleanupResult + * @property {Array} deletedCacheRequests List of URLs that were deleted + * while cleaning up the cache. + * + * @memberof workbox-precaching + */ +/** + * @typedef {Object} PrecacheEntry + * @property {string} url URL to precache. + * @property {string} [revision] Revision information for the URL. + * @property {string} [integrity] Integrity metadata that will be used when + * making the network request for the URL. + * + * @memberof workbox-precaching + */ +/** + * The "urlManipulation" callback can be used to determine if there are any + * additional permutations of a URL that should be used to check against + * the available precached files. + * + * For example, Workbox supports checking for '/index.html' when the URL + * '/' is provided. This callback allows additional, custom checks. + * + * @callback ~urlManipulation + * @param {Object} context + * @param {URL} context.url The request's URL. + * @return {Array} To add additional urls to test, return an Array of + * URLs. Please note that these **should not be strings**, but URL objects. + * + * @memberof workbox-precaching + */ diff --git a/node_modules/workbox-precaching/_types.mjs b/node_modules/workbox-precaching/_types.mjs new file mode 100644 index 0000000000000000000000000000000000000000..fb0ccdd9e49605f634b19eb6c43bd521a13a66ab --- /dev/null +++ b/node_modules/workbox-precaching/_types.mjs @@ -0,0 +1 @@ +export * from './_types.js'; \ No newline at end of file diff --git a/node_modules/workbox-precaching/_version.d.ts b/node_modules/workbox-precaching/_version.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/workbox-precaching/_version.js b/node_modules/workbox-precaching/_version.js new file mode 100644 index 0000000000000000000000000000000000000000..fe25a4861205edd324e51b6ab4f26f80c08d8e69 --- /dev/null +++ b/node_modules/workbox-precaching/_version.js @@ -0,0 +1,6 @@ +"use strict"; +// @ts-ignore +try { + self['workbox:precaching:7.4.0'] && _(); +} +catch (e) { } diff --git a/node_modules/workbox-precaching/_version.mjs b/node_modules/workbox-precaching/_version.mjs new file mode 100644 index 0000000000000000000000000000000000000000..07ee5cb496c86c2ebe7bc4fd2b579e52aa574260 --- /dev/null +++ b/node_modules/workbox-precaching/_version.mjs @@ -0,0 +1 @@ +try{self['workbox:precaching:7.4.1']&&_()}catch(e){}// eslint-disable-line \ No newline at end of file diff --git a/node_modules/workbox-precaching/addPlugins.d.ts b/node_modules/workbox-precaching/addPlugins.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..53150b15792d1bba9bfd3140c1c82dcfe332ea4c --- /dev/null +++ b/node_modules/workbox-precaching/addPlugins.d.ts @@ -0,0 +1,11 @@ +import { WorkboxPlugin } from 'workbox-core/types.js'; +import './_version.js'; +/** + * Adds plugins to the precaching strategy. + * + * @param {Array} plugins + * + * @memberof workbox-precaching + */ +declare function addPlugins(plugins: WorkboxPlugin[]): void; +export { addPlugins }; diff --git a/node_modules/workbox-precaching/addPlugins.js b/node_modules/workbox-precaching/addPlugins.js new file mode 100644 index 0000000000000000000000000000000000000000..5682cd006e45bf3d6190a829f9c76e05afaf64b2 --- /dev/null +++ b/node_modules/workbox-precaching/addPlugins.js @@ -0,0 +1,21 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js'; +import './_version.js'; +/** + * Adds plugins to the precaching strategy. + * + * @param {Array} plugins + * + * @memberof workbox-precaching + */ +function addPlugins(plugins) { + const precacheController = getOrCreatePrecacheController(); + precacheController.strategy.plugins.push(...plugins); +} +export { addPlugins }; diff --git a/node_modules/workbox-precaching/addPlugins.mjs b/node_modules/workbox-precaching/addPlugins.mjs new file mode 100644 index 0000000000000000000000000000000000000000..fe8b33761b0fb88ed6cf0b705db3e973e8cd89fd --- /dev/null +++ b/node_modules/workbox-precaching/addPlugins.mjs @@ -0,0 +1 @@ +export * from './addPlugins.js'; \ No newline at end of file diff --git a/node_modules/workbox-precaching/addRoute.d.ts b/node_modules/workbox-precaching/addRoute.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a2dd7c9d40ad6bc209b67caa3a62c4420a8474c1 --- /dev/null +++ b/node_modules/workbox-precaching/addRoute.d.ts @@ -0,0 +1,19 @@ +import { PrecacheRouteOptions } from './_types.js'; +import './_version.js'; +/** + * Add a `fetch` listener to the service worker that will + * respond to + * [network requests]{@link https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#Custom_responses_to_requests} + * with precached assets. + * + * Requests for assets that aren't precached, the `FetchEvent` will not be + * responded to, allowing the event to fall through to other `fetch` event + * listeners. + * + * @param {Object} [options] See the {@link workbox-precaching.PrecacheRoute} + * options. + * + * @memberof workbox-precaching + */ +declare function addRoute(options?: PrecacheRouteOptions): void; +export { addRoute }; diff --git a/node_modules/workbox-precaching/addRoute.js b/node_modules/workbox-precaching/addRoute.js new file mode 100644 index 0000000000000000000000000000000000000000..0ac3c5ec9d59e8316d806d04fc26451e4c5c616f --- /dev/null +++ b/node_modules/workbox-precaching/addRoute.js @@ -0,0 +1,31 @@ +/* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { registerRoute } from 'workbox-routing/registerRoute.js'; +import { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js'; +import { PrecacheRoute } from './PrecacheRoute.js'; +import './_version.js'; +/** + * Add a `fetch` listener to the service worker that will + * respond to + * [network requests]{@link https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#Custom_responses_to_requests} + * with precached assets. + * + * Requests for assets that aren't precached, the `FetchEvent` will not be + * responded to, allowing the event to fall through to other `fetch` event + * listeners. + * + * @param {Object} [options] See the {@link workbox-precaching.PrecacheRoute} + * options. + * + * @memberof workbox-precaching + */ +function addRoute(options) { + const precacheController = getOrCreatePrecacheController(); + const precacheRoute = new PrecacheRoute(precacheController, options); + registerRoute(precacheRoute); +} +export { addRoute }; diff --git a/node_modules/workbox-precaching/addRoute.mjs b/node_modules/workbox-precaching/addRoute.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b2edaad6da7d9c2240774431493bcd9c6d439472 --- /dev/null +++ b/node_modules/workbox-precaching/addRoute.mjs @@ -0,0 +1 @@ +export * from './addRoute.js'; \ No newline at end of file diff --git a/node_modules/workbox-precaching/build/workbox-precaching.dev.js b/node_modules/workbox-precaching/build/workbox-precaching.dev.js new file mode 100644 index 0000000000000000000000000000000000000000..93b1ca0d17972bc0fdf3872d74ef05f3002e101a --- /dev/null +++ b/node_modules/workbox-precaching/build/workbox-precaching.dev.js @@ -0,0 +1,1201 @@ +this.workbox = this.workbox || {}; +this.workbox.precaching = (function (exports, assert_js, cacheNames_js, logger_js, WorkboxError_js, waitUntil_js, copyResponse_js, getFriendlyURL_js, Strategy_js, registerRoute_js, Route_js) { + 'use strict'; + + // @ts-ignore + try { + self['workbox:precaching:7.4.0'] && _(); + } catch (e) {} + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + // Name of the search parameter used to store revision info. + const REVISION_SEARCH_PARAM = '__WB_REVISION__'; + /** + * Converts a manifest entry into a versioned URL suitable for precaching. + * + * @param {Object|string} entry + * @return {string} A URL with versioning info. + * + * @private + * @memberof workbox-precaching + */ + function createCacheKey(entry) { + if (!entry) { + throw new WorkboxError_js.WorkboxError('add-to-cache-list-unexpected-type', { + entry + }); + } + // If a precache manifest entry is a string, it's assumed to be a versioned + // URL, like '/app.abcd1234.js'. Return as-is. + if (typeof entry === 'string') { + const urlObject = new URL(entry, location.href); + return { + cacheKey: urlObject.href, + url: urlObject.href + }; + } + const { + revision, + url + } = entry; + if (!url) { + throw new WorkboxError_js.WorkboxError('add-to-cache-list-unexpected-type', { + entry + }); + } + // If there's just a URL and no revision, then it's also assumed to be a + // versioned URL. + if (!revision) { + const urlObject = new URL(url, location.href); + return { + cacheKey: urlObject.href, + url: urlObject.href + }; + } + // Otherwise, construct a properly versioned URL using the custom Workbox + // search parameter along with the revision info. + const cacheKeyURL = new URL(url, location.href); + const originalURL = new URL(url, location.href); + cacheKeyURL.searchParams.set(REVISION_SEARCH_PARAM, revision); + return { + cacheKey: cacheKeyURL.href, + url: originalURL.href + }; + } + + /* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * A plugin, designed to be used with PrecacheController, to determine the + * of assets that were updated (or not updated) during the install event. + * + * @private + */ + class PrecacheInstallReportPlugin { + constructor() { + this.updatedURLs = []; + this.notUpdatedURLs = []; + this.handlerWillStart = async ({ + request, + state + }) => { + // TODO: `state` should never be undefined... + if (state) { + state.originalRequest = request; + } + }; + this.cachedResponseWillBeUsed = async ({ + event, + state, + cachedResponse + }) => { + if (event.type === 'install') { + if (state && state.originalRequest && state.originalRequest instanceof Request) { + // TODO: `state` should never be undefined... + const url = state.originalRequest.url; + if (cachedResponse) { + this.notUpdatedURLs.push(url); + } else { + this.updatedURLs.push(url); + } + } + } + return cachedResponse; + }; + } + } + + /* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * A plugin, designed to be used with PrecacheController, to translate URLs into + * the corresponding cache key, based on the current revision info. + * + * @private + */ + class PrecacheCacheKeyPlugin { + constructor({ + precacheController + }) { + this.cacheKeyWillBeUsed = async ({ + request, + params + }) => { + // Params is type any, can't change right now. + /* eslint-disable */ + const cacheKey = (params === null || params === void 0 ? void 0 : params.cacheKey) || this._precacheController.getCacheKeyForURL(request.url); + /* eslint-enable */ + return cacheKey ? new Request(cacheKey, { + headers: request.headers + }) : request; + }; + this._precacheController = precacheController; + } + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * @param {string} groupTitle + * @param {Array} deletedURLs + * + * @private + */ + const logGroup = (groupTitle, deletedURLs) => { + logger_js.logger.groupCollapsed(groupTitle); + for (const url of deletedURLs) { + logger_js.logger.log(url); + } + logger_js.logger.groupEnd(); + }; + /** + * @param {Array} deletedURLs + * + * @private + * @memberof workbox-precaching + */ + function printCleanupDetails(deletedURLs) { + const deletionCount = deletedURLs.length; + if (deletionCount > 0) { + logger_js.logger.groupCollapsed(`During precaching cleanup, ` + `${deletionCount} cached ` + `request${deletionCount === 1 ? ' was' : 's were'} deleted.`); + logGroup('Deleted Cache Requests', deletedURLs); + logger_js.logger.groupEnd(); + } + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * @param {string} groupTitle + * @param {Array} urls + * + * @private + */ + function _nestedGroup(groupTitle, urls) { + if (urls.length === 0) { + return; + } + logger_js.logger.groupCollapsed(groupTitle); + for (const url of urls) { + logger_js.logger.log(url); + } + logger_js.logger.groupEnd(); + } + /** + * @param {Array} urlsToPrecache + * @param {Array} urlsAlreadyPrecached + * + * @private + * @memberof workbox-precaching + */ + function printInstallDetails(urlsToPrecache, urlsAlreadyPrecached) { + const precachedCount = urlsToPrecache.length; + const alreadyPrecachedCount = urlsAlreadyPrecached.length; + if (precachedCount || alreadyPrecachedCount) { + let message = `Precaching ${precachedCount} file${precachedCount === 1 ? '' : 's'}.`; + if (alreadyPrecachedCount > 0) { + message += ` ${alreadyPrecachedCount} ` + `file${alreadyPrecachedCount === 1 ? ' is' : 's are'} already cached.`; + } + logger_js.logger.groupCollapsed(message); + _nestedGroup(`View newly precached URLs.`, urlsToPrecache); + _nestedGroup(`View previously precached URLs.`, urlsAlreadyPrecached); + logger_js.logger.groupEnd(); + } + } + + /* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * A {@link workbox-strategies.Strategy} implementation + * specifically designed to work with + * {@link workbox-precaching.PrecacheController} + * to both cache and fetch precached assets. + * + * Note: an instance of this class is created automatically when creating a + * `PrecacheController`; it's generally not necessary to create this yourself. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-precaching + */ + class PrecacheStrategy extends Strategy_js.Strategy { + /** + * + * @param {Object} [options] + * @param {string} [options.cacheName] Cache name to store and retrieve + * requests. Defaults to the cache names provided by + * {@link workbox-core.cacheNames}. + * @param {Array} [options.plugins] {@link https://developers.google.com/web/tools/workbox/guides/using-plugins|Plugins} + * to use in conjunction with this caching strategy. + * @param {Object} [options.fetchOptions] Values passed along to the + * {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters|init} + * of all fetch() requests made by this strategy. + * @param {Object} [options.matchOptions] The + * {@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions|CacheQueryOptions} + * for any `cache.match()` or `cache.put()` calls made by this strategy. + * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to + * get the response from the network if there's a precache miss. + */ + constructor(options = {}) { + options.cacheName = cacheNames_js.cacheNames.getPrecacheName(options.cacheName); + super(options); + this._fallbackToNetwork = options.fallbackToNetwork === false ? false : true; + // Redirected responses cannot be used to satisfy a navigation request, so + // any redirected response must be "copied" rather than cloned, so the new + // response doesn't contain the `redirected` flag. See: + // https://bugs.chromium.org/p/chromium/issues/detail?id=669363&desc=2#c1 + this.plugins.push(PrecacheStrategy.copyRedirectedCacheableResponsesPlugin); + } + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + async _handle(request, handler) { + const response = await handler.cacheMatch(request); + if (response) { + return response; + } + // If this is an `install` event for an entry that isn't already cached, + // then populate the cache. + if (handler.event && handler.event.type === 'install') { + return await this._handleInstall(request, handler); + } + // Getting here means something went wrong. An entry that should have been + // precached wasn't found in the cache. + return await this._handleFetch(request, handler); + } + async _handleFetch(request, handler) { + let response; + const params = handler.params || {}; + // Fall back to the network if we're configured to do so. + if (this._fallbackToNetwork) { + { + logger_js.logger.warn(`The precached response for ` + `${getFriendlyURL_js.getFriendlyURL(request.url)} in ${this.cacheName} was not ` + `found. Falling back to the network.`); + } + const integrityInManifest = params.integrity; + const integrityInRequest = request.integrity; + const noIntegrityConflict = !integrityInRequest || integrityInRequest === integrityInManifest; + // Do not add integrity if the original request is no-cors + // See https://github.com/GoogleChrome/workbox/issues/3096 + response = await handler.fetch(new Request(request, { + integrity: request.mode !== 'no-cors' ? integrityInRequest || integrityInManifest : undefined + })); + // It's only "safe" to repair the cache if we're using SRI to guarantee + // that the response matches the precache manifest's expectations, + // and there's either a) no integrity property in the incoming request + // or b) there is an integrity, and it matches the precache manifest. + // See https://github.com/GoogleChrome/workbox/issues/2858 + // Also if the original request users no-cors we don't use integrity. + // See https://github.com/GoogleChrome/workbox/issues/3096 + if (integrityInManifest && noIntegrityConflict && request.mode !== 'no-cors') { + this._useDefaultCacheabilityPluginIfNeeded(); + const wasCached = await handler.cachePut(request, response.clone()); + { + if (wasCached) { + logger_js.logger.log(`A response for ${getFriendlyURL_js.getFriendlyURL(request.url)} ` + `was used to "repair" the precache.`); + } + } + } + } else { + // This shouldn't normally happen, but there are edge cases: + // https://github.com/GoogleChrome/workbox/issues/1441 + throw new WorkboxError_js.WorkboxError('missing-precache-entry', { + cacheName: this.cacheName, + url: request.url + }); + } + { + const cacheKey = params.cacheKey || (await handler.getCacheKey(request, 'read')); + // Workbox is going to handle the route. + // print the routing details to the console. + logger_js.logger.groupCollapsed(`Precaching is responding to: ` + getFriendlyURL_js.getFriendlyURL(request.url)); + logger_js.logger.log(`Serving the precached url: ${getFriendlyURL_js.getFriendlyURL(cacheKey instanceof Request ? cacheKey.url : cacheKey)}`); + logger_js.logger.groupCollapsed(`View request details here.`); + logger_js.logger.log(request); + logger_js.logger.groupEnd(); + logger_js.logger.groupCollapsed(`View response details here.`); + logger_js.logger.log(response); + logger_js.logger.groupEnd(); + logger_js.logger.groupEnd(); + } + return response; + } + async _handleInstall(request, handler) { + this._useDefaultCacheabilityPluginIfNeeded(); + const response = await handler.fetch(request); + // Make sure we defer cachePut() until after we know the response + // should be cached; see https://github.com/GoogleChrome/workbox/issues/2737 + const wasCached = await handler.cachePut(request, response.clone()); + if (!wasCached) { + // Throwing here will lead to the `install` handler failing, which + // we want to do if *any* of the responses aren't safe to cache. + throw new WorkboxError_js.WorkboxError('bad-precaching-response', { + url: request.url, + status: response.status + }); + } + return response; + } + /** + * This method is complex, as there a number of things to account for: + * + * The `plugins` array can be set at construction, and/or it might be added to + * to at any time before the strategy is used. + * + * At the time the strategy is used (i.e. during an `install` event), there + * needs to be at least one plugin that implements `cacheWillUpdate` in the + * array, other than `copyRedirectedCacheableResponsesPlugin`. + * + * - If this method is called and there are no suitable `cacheWillUpdate` + * plugins, we need to add `defaultPrecacheCacheabilityPlugin`. + * + * - If this method is called and there is exactly one `cacheWillUpdate`, then + * we don't have to do anything (this might be a previously added + * `defaultPrecacheCacheabilityPlugin`, or it might be a custom plugin). + * + * - If this method is called and there is more than one `cacheWillUpdate`, + * then we need to check if one is `defaultPrecacheCacheabilityPlugin`. If so, + * we need to remove it. (This situation is unlikely, but it could happen if + * the strategy is used multiple times, the first without a `cacheWillUpdate`, + * and then later on after manually adding a custom `cacheWillUpdate`.) + * + * See https://github.com/GoogleChrome/workbox/issues/2737 for more context. + * + * @private + */ + _useDefaultCacheabilityPluginIfNeeded() { + let defaultPluginIndex = null; + let cacheWillUpdatePluginCount = 0; + for (const [index, plugin] of this.plugins.entries()) { + // Ignore the copy redirected plugin when determining what to do. + if (plugin === PrecacheStrategy.copyRedirectedCacheableResponsesPlugin) { + continue; + } + // Save the default plugin's index, in case it needs to be removed. + if (plugin === PrecacheStrategy.defaultPrecacheCacheabilityPlugin) { + defaultPluginIndex = index; + } + if (plugin.cacheWillUpdate) { + cacheWillUpdatePluginCount++; + } + } + if (cacheWillUpdatePluginCount === 0) { + this.plugins.push(PrecacheStrategy.defaultPrecacheCacheabilityPlugin); + } else if (cacheWillUpdatePluginCount > 1 && defaultPluginIndex !== null) { + // Only remove the default plugin; multiple custom plugins are allowed. + this.plugins.splice(defaultPluginIndex, 1); + } + // Nothing needs to be done if cacheWillUpdatePluginCount is 1 + } + } + PrecacheStrategy.defaultPrecacheCacheabilityPlugin = { + async cacheWillUpdate({ + response + }) { + if (!response || response.status >= 400) { + return null; + } + return response; + } + }; + PrecacheStrategy.copyRedirectedCacheableResponsesPlugin = { + async cacheWillUpdate({ + response + }) { + return response.redirected ? await copyResponse_js.copyResponse(response) : response; + } + }; + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Performs efficient precaching of assets. + * + * @memberof workbox-precaching + */ + class PrecacheController { + /** + * Create a new PrecacheController. + * + * @param {Object} [options] + * @param {string} [options.cacheName] The cache to use for precaching. + * @param {string} [options.plugins] Plugins to use when precaching as well + * as responding to fetch events for precached assets. + * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to + * get the response from the network if there's a precache miss. + */ + constructor({ + cacheName, + plugins = [], + fallbackToNetwork = true + } = {}) { + this._urlsToCacheKeys = new Map(); + this._urlsToCacheModes = new Map(); + this._cacheKeysToIntegrities = new Map(); + this._strategy = new PrecacheStrategy({ + cacheName: cacheNames_js.cacheNames.getPrecacheName(cacheName), + plugins: [...plugins, new PrecacheCacheKeyPlugin({ + precacheController: this + })], + fallbackToNetwork + }); + // Bind the install and activate methods to the instance. + this.install = this.install.bind(this); + this.activate = this.activate.bind(this); + } + /** + * @type {workbox-precaching.PrecacheStrategy} The strategy created by this controller and + * used to cache assets and respond to fetch events. + */ + get strategy() { + return this._strategy; + } + /** + * Adds items to the precache list, removing any duplicates and + * stores the files in the + * {@link workbox-core.cacheNames|"precache cache"} when the service + * worker installs. + * + * This method can be called multiple times. + * + * @param {Array} [entries=[]] Array of entries to precache. + */ + precache(entries) { + this.addToCacheList(entries); + if (!this._installAndActiveListenersAdded) { + self.addEventListener('install', this.install); + self.addEventListener('activate', this.activate); + this._installAndActiveListenersAdded = true; + } + } + /** + * This method will add items to the precache list, removing duplicates + * and ensuring the information is valid. + * + * @param {Array} entries + * Array of entries to precache. + */ + addToCacheList(entries) { + { + assert_js.assert.isArray(entries, { + moduleName: 'workbox-precaching', + className: 'PrecacheController', + funcName: 'addToCacheList', + paramName: 'entries' + }); + } + const urlsToWarnAbout = []; + for (const entry of entries) { + // See https://github.com/GoogleChrome/workbox/issues/2259 + if (typeof entry === 'string') { + urlsToWarnAbout.push(entry); + } else if (entry && entry.revision === undefined) { + urlsToWarnAbout.push(entry.url); + } + const { + cacheKey, + url + } = createCacheKey(entry); + const cacheMode = typeof entry !== 'string' && entry.revision ? 'reload' : 'default'; + if (this._urlsToCacheKeys.has(url) && this._urlsToCacheKeys.get(url) !== cacheKey) { + throw new WorkboxError_js.WorkboxError('add-to-cache-list-conflicting-entries', { + firstEntry: this._urlsToCacheKeys.get(url), + secondEntry: cacheKey + }); + } + if (typeof entry !== 'string' && entry.integrity) { + if (this._cacheKeysToIntegrities.has(cacheKey) && this._cacheKeysToIntegrities.get(cacheKey) !== entry.integrity) { + throw new WorkboxError_js.WorkboxError('add-to-cache-list-conflicting-integrities', { + url + }); + } + this._cacheKeysToIntegrities.set(cacheKey, entry.integrity); + } + this._urlsToCacheKeys.set(url, cacheKey); + this._urlsToCacheModes.set(url, cacheMode); + if (urlsToWarnAbout.length > 0) { + const warningMessage = `Workbox is precaching URLs without revision ` + `info: ${urlsToWarnAbout.join(', ')}\nThis is generally NOT safe. ` + `Learn more at https://bit.ly/wb-precache`; + { + logger_js.logger.warn(warningMessage); + } + } + } + } + /** + * Precaches new and updated assets. Call this method from the service worker + * install event. + * + * Note: this method calls `event.waitUntil()` for you, so you do not need + * to call it yourself in your event handlers. + * + * @param {ExtendableEvent} event + * @return {Promise} + */ + install(event) { + // waitUntil returns Promise + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return waitUntil_js.waitUntil(event, async () => { + const installReportPlugin = new PrecacheInstallReportPlugin(); + this.strategy.plugins.push(installReportPlugin); + // Cache entries one at a time. + // See https://github.com/GoogleChrome/workbox/issues/2528 + for (const [url, cacheKey] of this._urlsToCacheKeys) { + const integrity = this._cacheKeysToIntegrities.get(cacheKey); + const cacheMode = this._urlsToCacheModes.get(url); + const request = new Request(url, { + integrity, + cache: cacheMode, + credentials: 'same-origin' + }); + await Promise.all(this.strategy.handleAll({ + params: { + cacheKey + }, + request, + event + })); + } + const { + updatedURLs, + notUpdatedURLs + } = installReportPlugin; + { + printInstallDetails(updatedURLs, notUpdatedURLs); + } + return { + updatedURLs, + notUpdatedURLs + }; + }); + } + /** + * Deletes assets that are no longer present in the current precache manifest. + * Call this method from the service worker activate event. + * + * Note: this method calls `event.waitUntil()` for you, so you do not need + * to call it yourself in your event handlers. + * + * @param {ExtendableEvent} event + * @return {Promise} + */ + activate(event) { + // waitUntil returns Promise + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return waitUntil_js.waitUntil(event, async () => { + const cache = await self.caches.open(this.strategy.cacheName); + const currentlyCachedRequests = await cache.keys(); + const expectedCacheKeys = new Set(this._urlsToCacheKeys.values()); + const deletedURLs = []; + for (const request of currentlyCachedRequests) { + if (!expectedCacheKeys.has(request.url)) { + await cache.delete(request); + deletedURLs.push(request.url); + } + } + { + printCleanupDetails(deletedURLs); + } + return { + deletedURLs + }; + }); + } + /** + * Returns a mapping of a precached URL to the corresponding cache key, taking + * into account the revision information for the URL. + * + * @return {Map} A URL to cache key mapping. + */ + getURLsToCacheKeys() { + return this._urlsToCacheKeys; + } + /** + * Returns a list of all the URLs that have been precached by the current + * service worker. + * + * @return {Array} The precached URLs. + */ + getCachedURLs() { + return [...this._urlsToCacheKeys.keys()]; + } + /** + * Returns the cache key used for storing a given URL. If that URL is + * unversioned, like `/index.html', then the cache key will be the original + * URL with a search parameter appended to it. + * + * @param {string} url A URL whose cache key you want to look up. + * @return {string} The versioned URL that corresponds to a cache key + * for the original URL, or undefined if that URL isn't precached. + */ + getCacheKeyForURL(url) { + const urlObject = new URL(url, location.href); + return this._urlsToCacheKeys.get(urlObject.href); + } + /** + * @param {string} url A cache key whose SRI you want to look up. + * @return {string} The subresource integrity associated with the cache key, + * or undefined if it's not set. + */ + getIntegrityForCacheKey(cacheKey) { + return this._cacheKeysToIntegrities.get(cacheKey); + } + /** + * This acts as a drop-in replacement for + * [`cache.match()`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/match) + * with the following differences: + * + * - It knows what the name of the precache is, and only checks in that cache. + * - It allows you to pass in an "original" URL without versioning parameters, + * and it will automatically look up the correct cache key for the currently + * active revision of that URL. + * + * E.g., `matchPrecache('index.html')` will find the correct precached + * response for the currently active service worker, even if the actual cache + * key is `'/index.html?__WB_REVISION__=1234abcd'`. + * + * @param {string|Request} request The key (without revisioning parameters) + * to look up in the precache. + * @return {Promise} + */ + async matchPrecache(request) { + const url = request instanceof Request ? request.url : request; + const cacheKey = this.getCacheKeyForURL(url); + if (cacheKey) { + const cache = await self.caches.open(this.strategy.cacheName); + return cache.match(cacheKey); + } + return undefined; + } + /** + * Returns a function that looks up `url` in the precache (taking into + * account revision information), and returns the corresponding `Response`. + * + * @param {string} url The precached URL which will be used to lookup the + * `Response`. + * @return {workbox-routing~handlerCallback} + */ + createHandlerBoundToURL(url) { + const cacheKey = this.getCacheKeyForURL(url); + if (!cacheKey) { + throw new WorkboxError_js.WorkboxError('non-precached-url', { + url + }); + } + return options => { + options.request = new Request(url); + options.params = Object.assign({ + cacheKey + }, options.params); + return this.strategy.handle(options); + }; + } + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + let precacheController; + /** + * @return {PrecacheController} + * @private + */ + const getOrCreatePrecacheController = () => { + if (!precacheController) { + precacheController = new PrecacheController(); + } + return precacheController; + }; + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Adds plugins to the precaching strategy. + * + * @param {Array} plugins + * + * @memberof workbox-precaching + */ + function addPlugins(plugins) { + const precacheController = getOrCreatePrecacheController(); + precacheController.strategy.plugins.push(...plugins); + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Removes any URL search parameters that should be ignored. + * + * @param {URL} urlObject The original URL. + * @param {Array} ignoreURLParametersMatching RegExps to test against + * each search parameter name. Matches mean that the search parameter should be + * ignored. + * @return {URL} The URL with any ignored search parameters removed. + * + * @private + * @memberof workbox-precaching + */ + function removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching = []) { + // Convert the iterable into an array at the start of the loop to make sure + // deletion doesn't mess up iteration. + for (const paramName of [...urlObject.searchParams.keys()]) { + if (ignoreURLParametersMatching.some(regExp => regExp.test(paramName))) { + urlObject.searchParams.delete(paramName); + } + } + return urlObject; + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Generator function that yields possible variations on the original URL to + * check, one at a time. + * + * @param {string} url + * @param {Object} options + * + * @private + * @memberof workbox-precaching + */ + function* generateURLVariations(url, { + ignoreURLParametersMatching = [/^utm_/, /^fbclid$/], + directoryIndex = 'index.html', + cleanURLs = true, + urlManipulation + } = {}) { + const urlObject = new URL(url, location.href); + urlObject.hash = ''; + yield urlObject.href; + const urlWithoutIgnoredParams = removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching); + yield urlWithoutIgnoredParams.href; + if (directoryIndex && urlWithoutIgnoredParams.pathname.endsWith('/')) { + const directoryURL = new URL(urlWithoutIgnoredParams.href); + directoryURL.pathname += directoryIndex; + yield directoryURL.href; + } + if (cleanURLs) { + const cleanURL = new URL(urlWithoutIgnoredParams.href); + cleanURL.pathname += '.html'; + yield cleanURL.href; + } + if (urlManipulation) { + const additionalURLs = urlManipulation({ + url: urlObject + }); + for (const urlToAttempt of additionalURLs) { + yield urlToAttempt.href; + } + } + } + + /* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * A subclass of {@link workbox-routing.Route} that takes a + * {@link workbox-precaching.PrecacheController} + * instance and uses it to match incoming requests and handle fetching + * responses from the precache. + * + * @memberof workbox-precaching + * @extends workbox-routing.Route + */ + class PrecacheRoute extends Route_js.Route { + /** + * @param {PrecacheController} precacheController A `PrecacheController` + * instance used to both match requests and respond to fetch events. + * @param {Object} [options] Options to control how requests are matched + * against the list of precached URLs. + * @param {string} [options.directoryIndex=index.html] The `directoryIndex` will + * check cache entries for a URLs ending with '/' to see if there is a hit when + * appending the `directoryIndex` value. + * @param {Array} [options.ignoreURLParametersMatching=[/^utm_/, /^fbclid$/]] An + * array of regex's to remove search params when looking for a cache match. + * @param {boolean} [options.cleanURLs=true] The `cleanURLs` option will + * check the cache for the URL with a `.html` added to the end of the end. + * @param {workbox-precaching~urlManipulation} [options.urlManipulation] + * This is a function that should take a URL and return an array of + * alternative URLs that should be checked for precache matches. + */ + constructor(precacheController, options) { + const match = ({ + request + }) => { + const urlsToCacheKeys = precacheController.getURLsToCacheKeys(); + for (const possibleURL of generateURLVariations(request.url, options)) { + const cacheKey = urlsToCacheKeys.get(possibleURL); + if (cacheKey) { + const integrity = precacheController.getIntegrityForCacheKey(cacheKey); + return { + cacheKey, + integrity + }; + } + } + { + logger_js.logger.debug(`Precaching did not find a match for ` + getFriendlyURL_js.getFriendlyURL(request.url)); + } + return; + }; + super(match, precacheController.strategy); + } + } + + /* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Add a `fetch` listener to the service worker that will + * respond to + * [network requests]{@link https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#Custom_responses_to_requests} + * with precached assets. + * + * Requests for assets that aren't precached, the `FetchEvent` will not be + * responded to, allowing the event to fall through to other `fetch` event + * listeners. + * + * @param {Object} [options] See the {@link workbox-precaching.PrecacheRoute} + * options. + * + * @memberof workbox-precaching + */ + function addRoute(options) { + const precacheController = getOrCreatePrecacheController(); + const precacheRoute = new PrecacheRoute(precacheController, options); + registerRoute_js.registerRoute(precacheRoute); + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + const SUBSTRING_TO_FIND = '-precache-'; + /** + * Cleans up incompatible precaches that were created by older versions of + * Workbox, by a service worker registered under the current scope. + * + * This is meant to be called as part of the `activate` event. + * + * This should be safe to use as long as you don't include `substringToFind` + * (defaulting to `-precache-`) in your non-precache cache names. + * + * @param {string} currentPrecacheName The cache name currently in use for + * precaching. This cache won't be deleted. + * @param {string} [substringToFind='-precache-'] Cache names which include this + * substring will be deleted (excluding `currentPrecacheName`). + * @return {Array} A list of all the cache names that were deleted. + * + * @private + * @memberof workbox-precaching + */ + const deleteOutdatedCaches = async (currentPrecacheName, substringToFind = SUBSTRING_TO_FIND) => { + const cacheNames = await self.caches.keys(); + const cacheNamesToDelete = cacheNames.filter(cacheName => { + return cacheName.includes(substringToFind) && cacheName.includes(self.registration.scope) && cacheName !== currentPrecacheName; + }); + await Promise.all(cacheNamesToDelete.map(cacheName => self.caches.delete(cacheName))); + return cacheNamesToDelete; + }; + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Adds an `activate` event listener which will clean up incompatible + * precaches that were created by older versions of Workbox. + * + * @memberof workbox-precaching + */ + function cleanupOutdatedCaches() { + // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705 + self.addEventListener('activate', event => { + const cacheName = cacheNames_js.cacheNames.getPrecacheName(); + event.waitUntil(deleteOutdatedCaches(cacheName).then(cachesDeleted => { + { + if (cachesDeleted.length > 0) { + logger_js.logger.log(`The following out-of-date precaches were cleaned up ` + `automatically:`, cachesDeleted); + } + } + })); + }); + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Helper function that calls + * {@link PrecacheController#createHandlerBoundToURL} on the default + * {@link PrecacheController} instance. + * + * If you are creating your own {@link PrecacheController}, then call the + * {@link PrecacheController#createHandlerBoundToURL} on that instance, + * instead of using this function. + * + * @param {string} url The precached URL which will be used to lookup the + * `Response`. + * @param {boolean} [fallbackToNetwork=true] Whether to attempt to get the + * response from the network if there's a precache miss. + * @return {workbox-routing~handlerCallback} + * + * @memberof workbox-precaching + */ + function createHandlerBoundToURL(url) { + const precacheController = getOrCreatePrecacheController(); + return precacheController.createHandlerBoundToURL(url); + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Takes in a URL, and returns the corresponding URL that could be used to + * lookup the entry in the precache. + * + * If a relative URL is provided, the location of the service worker file will + * be used as the base. + * + * For precached entries without revision information, the cache key will be the + * same as the original URL. + * + * For precached entries with revision information, the cache key will be the + * original URL with the addition of a query parameter used for keeping track of + * the revision info. + * + * @param {string} url The URL whose cache key to look up. + * @return {string} The cache key that corresponds to that URL. + * + * @memberof workbox-precaching + */ + function getCacheKeyForURL(url) { + const precacheController = getOrCreatePrecacheController(); + return precacheController.getCacheKeyForURL(url); + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Helper function that calls + * {@link PrecacheController#matchPrecache} on the default + * {@link PrecacheController} instance. + * + * If you are creating your own {@link PrecacheController}, then call + * {@link PrecacheController#matchPrecache} on that instance, + * instead of using this function. + * + * @param {string|Request} request The key (without revisioning parameters) + * to look up in the precache. + * @return {Promise} + * + * @memberof workbox-precaching + */ + function matchPrecache(request) { + const precacheController = getOrCreatePrecacheController(); + return precacheController.matchPrecache(request); + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Adds items to the precache list, removing any duplicates and + * stores the files in the + * {@link workbox-core.cacheNames|"precache cache"} when the service + * worker installs. + * + * This method can be called multiple times. + * + * Please note: This method **will not** serve any of the cached files for you. + * It only precaches files. To respond to a network request you call + * {@link workbox-precaching.addRoute}. + * + * If you have a single array of files to precache, you can just call + * {@link workbox-precaching.precacheAndRoute}. + * + * @param {Array} [entries=[]] Array of entries to precache. + * + * @memberof workbox-precaching + */ + function precache(entries) { + const precacheController = getOrCreatePrecacheController(); + precacheController.precache(entries); + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * This method will add entries to the precache list and add a route to + * respond to fetch events. + * + * This is a convenience method that will call + * {@link workbox-precaching.precache} and + * {@link workbox-precaching.addRoute} in a single call. + * + * @param {Array} entries Array of entries to precache. + * @param {Object} [options] See the + * {@link workbox-precaching.PrecacheRoute} options. + * + * @memberof workbox-precaching + */ + function precacheAndRoute(entries, options) { + precache(entries); + addRoute(options); + } + + /* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * `PrecacheFallbackPlugin` allows you to specify an "offline fallback" + * response to be used when a given strategy is unable to generate a response. + * + * It does this by intercepting the `handlerDidError` plugin callback + * and returning a precached response, taking the expected revision parameter + * into account automatically. + * + * Unless you explicitly pass in a `PrecacheController` instance to the + * constructor, the default instance will be used. Generally speaking, most + * developers will end up using the default. + * + * @memberof workbox-precaching + */ + class PrecacheFallbackPlugin { + /** + * Constructs a new PrecacheFallbackPlugin with the associated fallbackURL. + * + * @param {Object} config + * @param {string} config.fallbackURL A precached URL to use as the fallback + * if the associated strategy can't generate a response. + * @param {PrecacheController} [config.precacheController] An optional + * PrecacheController instance. If not provided, the default + * PrecacheController will be used. + */ + constructor({ + fallbackURL, + precacheController + }) { + /** + * @return {Promise} The precache response for the fallback URL. + * + * @private + */ + this.handlerDidError = () => this._precacheController.matchPrecache(this._fallbackURL); + this._fallbackURL = fallbackURL; + this._precacheController = precacheController || getOrCreatePrecacheController(); + } + } + + exports.PrecacheController = PrecacheController; + exports.PrecacheFallbackPlugin = PrecacheFallbackPlugin; + exports.PrecacheRoute = PrecacheRoute; + exports.PrecacheStrategy = PrecacheStrategy; + exports.addPlugins = addPlugins; + exports.addRoute = addRoute; + exports.cleanupOutdatedCaches = cleanupOutdatedCaches; + exports.createHandlerBoundToURL = createHandlerBoundToURL; + exports.getCacheKeyForURL = getCacheKeyForURL; + exports.matchPrecache = matchPrecache; + exports.precache = precache; + exports.precacheAndRoute = precacheAndRoute; + + return exports; + +})({}, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core, workbox.core._private, workbox.strategies, workbox.routing, workbox.routing); +//# sourceMappingURL=workbox-precaching.dev.js.map diff --git a/node_modules/workbox-precaching/build/workbox-precaching.dev.js.map b/node_modules/workbox-precaching/build/workbox-precaching.dev.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ed61f9708c51cd436d4292e8559ef4fbf883d636 --- /dev/null +++ b/node_modules/workbox-precaching/build/workbox-precaching.dev.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-precaching.dev.js","sources":["../_version.js","../utils/createCacheKey.js","../utils/PrecacheInstallReportPlugin.js","../utils/PrecacheCacheKeyPlugin.js","../utils/printCleanupDetails.js","../utils/printInstallDetails.js","../PrecacheStrategy.js","../PrecacheController.js","../utils/getOrCreatePrecacheController.js","../addPlugins.js","../utils/removeIgnoredSearchParams.js","../utils/generateURLVariations.js","../PrecacheRoute.js","../addRoute.js","../utils/deleteOutdatedCaches.js","../cleanupOutdatedCaches.js","../createHandlerBoundToURL.js","../getCacheKeyForURL.js","../matchPrecache.js","../precache.js","../precacheAndRoute.js","../PrecacheFallbackPlugin.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:precaching:7.4.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 '../_version.js';\n// Name of the search parameter used to store revision info.\nconst REVISION_SEARCH_PARAM = '__WB_REVISION__';\n/**\n * Converts a manifest entry into a versioned URL suitable for precaching.\n *\n * @param {Object|string} entry\n * @return {string} A URL with versioning info.\n *\n * @private\n * @memberof workbox-precaching\n */\nexport function createCacheKey(entry) {\n if (!entry) {\n throw new WorkboxError('add-to-cache-list-unexpected-type', { entry });\n }\n // If a precache manifest entry is a string, it's assumed to be a versioned\n // URL, like '/app.abcd1234.js'. Return as-is.\n if (typeof entry === 'string') {\n const urlObject = new URL(entry, location.href);\n return {\n cacheKey: urlObject.href,\n url: urlObject.href,\n };\n }\n const { revision, url } = entry;\n if (!url) {\n throw new WorkboxError('add-to-cache-list-unexpected-type', { entry });\n }\n // If there's just a URL and no revision, then it's also assumed to be a\n // versioned URL.\n if (!revision) {\n const urlObject = new URL(url, location.href);\n return {\n cacheKey: urlObject.href,\n url: urlObject.href,\n };\n }\n // Otherwise, construct a properly versioned URL using the custom Workbox\n // search parameter along with the revision info.\n const cacheKeyURL = new URL(url, location.href);\n const originalURL = new URL(url, location.href);\n cacheKeyURL.searchParams.set(REVISION_SEARCH_PARAM, revision);\n return {\n cacheKey: cacheKeyURL.href,\n url: originalURL.href,\n };\n}\n","/*\n Copyright 2020 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';\n/**\n * A plugin, designed to be used with PrecacheController, to determine the\n * of assets that were updated (or not updated) during the install event.\n *\n * @private\n */\nclass PrecacheInstallReportPlugin {\n constructor() {\n this.updatedURLs = [];\n this.notUpdatedURLs = [];\n this.handlerWillStart = async ({ request, state, }) => {\n // TODO: `state` should never be undefined...\n if (state) {\n state.originalRequest = request;\n }\n };\n this.cachedResponseWillBeUsed = async ({ event, state, cachedResponse, }) => {\n if (event.type === 'install') {\n if (state &&\n state.originalRequest &&\n state.originalRequest instanceof Request) {\n // TODO: `state` should never be undefined...\n const url = state.originalRequest.url;\n if (cachedResponse) {\n this.notUpdatedURLs.push(url);\n }\n else {\n this.updatedURLs.push(url);\n }\n }\n }\n return cachedResponse;\n };\n }\n}\nexport { PrecacheInstallReportPlugin };\n","/*\n Copyright 2020 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';\n/**\n * A plugin, designed to be used with PrecacheController, to translate URLs into\n * the corresponding cache key, based on the current revision info.\n *\n * @private\n */\nclass PrecacheCacheKeyPlugin {\n constructor({ precacheController }) {\n this.cacheKeyWillBeUsed = async ({ request, params, }) => {\n // Params is type any, can't change right now.\n /* eslint-disable */\n const cacheKey = (params === null || params === void 0 ? void 0 : params.cacheKey) ||\n this._precacheController.getCacheKeyForURL(request.url);\n /* eslint-enable */\n return cacheKey\n ? new Request(cacheKey, { headers: request.headers })\n : request;\n };\n this._precacheController = precacheController;\n }\n}\nexport { PrecacheCacheKeyPlugin };\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 { logger } from 'workbox-core/_private/logger.js';\nimport '../_version.js';\n/**\n * @param {string} groupTitle\n * @param {Array} deletedURLs\n *\n * @private\n */\nconst logGroup = (groupTitle, deletedURLs) => {\n logger.groupCollapsed(groupTitle);\n for (const url of deletedURLs) {\n logger.log(url);\n }\n logger.groupEnd();\n};\n/**\n * @param {Array} deletedURLs\n *\n * @private\n * @memberof workbox-precaching\n */\nexport function printCleanupDetails(deletedURLs) {\n const deletionCount = deletedURLs.length;\n if (deletionCount > 0) {\n logger.groupCollapsed(`During precaching cleanup, ` +\n `${deletionCount} cached ` +\n `request${deletionCount === 1 ? ' was' : 's were'} deleted.`);\n logGroup('Deleted Cache Requests', deletedURLs);\n logger.groupEnd();\n }\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 { logger } from 'workbox-core/_private/logger.js';\nimport '../_version.js';\n/**\n * @param {string} groupTitle\n * @param {Array} urls\n *\n * @private\n */\nfunction _nestedGroup(groupTitle, urls) {\n if (urls.length === 0) {\n return;\n }\n logger.groupCollapsed(groupTitle);\n for (const url of urls) {\n logger.log(url);\n }\n logger.groupEnd();\n}\n/**\n * @param {Array} urlsToPrecache\n * @param {Array} urlsAlreadyPrecached\n *\n * @private\n * @memberof workbox-precaching\n */\nexport function printInstallDetails(urlsToPrecache, urlsAlreadyPrecached) {\n const precachedCount = urlsToPrecache.length;\n const alreadyPrecachedCount = urlsAlreadyPrecached.length;\n if (precachedCount || alreadyPrecachedCount) {\n let message = `Precaching ${precachedCount} file${precachedCount === 1 ? '' : 's'}.`;\n if (alreadyPrecachedCount > 0) {\n message +=\n ` ${alreadyPrecachedCount} ` +\n `file${alreadyPrecachedCount === 1 ? ' is' : 's are'} already cached.`;\n }\n logger.groupCollapsed(message);\n _nestedGroup(`View newly precached URLs.`, urlsToPrecache);\n _nestedGroup(`View previously precached URLs.`, urlsAlreadyPrecached);\n logger.groupEnd();\n }\n}\n","/*\n Copyright 2020 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 { copyResponse } from 'workbox-core/copyResponse.js';\nimport { cacheNames } from 'workbox-core/_private/cacheNames.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { Strategy } from 'workbox-strategies/Strategy.js';\nimport './_version.js';\n/**\n * A {@link workbox-strategies.Strategy} implementation\n * specifically designed to work with\n * {@link workbox-precaching.PrecacheController}\n * to both cache and fetch precached assets.\n *\n * Note: an instance of this class is created automatically when creating a\n * `PrecacheController`; it's generally not necessary to create this yourself.\n *\n * @extends workbox-strategies.Strategy\n * @memberof workbox-precaching\n */\nclass PrecacheStrategy extends Strategy {\n /**\n *\n * @param {Object} [options]\n * @param {string} [options.cacheName] Cache name to store and retrieve\n * requests. Defaults to the cache names provided by\n * {@link workbox-core.cacheNames}.\n * @param {Array} [options.plugins] {@link https://developers.google.com/web/tools/workbox/guides/using-plugins|Plugins}\n * to use in conjunction with this caching strategy.\n * @param {Object} [options.fetchOptions] Values passed along to the\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters|init}\n * of all fetch() requests made by this strategy.\n * @param {Object} [options.matchOptions] The\n * {@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions|CacheQueryOptions}\n * for any `cache.match()` or `cache.put()` calls made by this strategy.\n * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to\n * get the response from the network if there's a precache miss.\n */\n constructor(options = {}) {\n options.cacheName = cacheNames.getPrecacheName(options.cacheName);\n super(options);\n this._fallbackToNetwork =\n options.fallbackToNetwork === false ? false : true;\n // Redirected responses cannot be used to satisfy a navigation request, so\n // any redirected response must be \"copied\" rather than cloned, so the new\n // response doesn't contain the `redirected` flag. See:\n // https://bugs.chromium.org/p/chromium/issues/detail?id=669363&desc=2#c1\n this.plugins.push(PrecacheStrategy.copyRedirectedCacheableResponsesPlugin);\n }\n /**\n * @private\n * @param {Request|string} request A request to run this strategy for.\n * @param {workbox-strategies.StrategyHandler} handler The event that\n * triggered the request.\n * @return {Promise}\n */\n async _handle(request, handler) {\n const response = await handler.cacheMatch(request);\n if (response) {\n return response;\n }\n // If this is an `install` event for an entry that isn't already cached,\n // then populate the cache.\n if (handler.event && handler.event.type === 'install') {\n return await this._handleInstall(request, handler);\n }\n // Getting here means something went wrong. An entry that should have been\n // precached wasn't found in the cache.\n return await this._handleFetch(request, handler);\n }\n async _handleFetch(request, handler) {\n let response;\n const params = (handler.params || {});\n // Fall back to the network if we're configured to do so.\n if (this._fallbackToNetwork) {\n if (process.env.NODE_ENV !== 'production') {\n logger.warn(`The precached response for ` +\n `${getFriendlyURL(request.url)} in ${this.cacheName} was not ` +\n `found. Falling back to the network.`);\n }\n const integrityInManifest = params.integrity;\n const integrityInRequest = request.integrity;\n const noIntegrityConflict = !integrityInRequest || integrityInRequest === integrityInManifest;\n // Do not add integrity if the original request is no-cors\n // See https://github.com/GoogleChrome/workbox/issues/3096\n response = await handler.fetch(new Request(request, {\n integrity: request.mode !== 'no-cors'\n ? integrityInRequest || integrityInManifest\n : undefined,\n }));\n // It's only \"safe\" to repair the cache if we're using SRI to guarantee\n // that the response matches the precache manifest's expectations,\n // and there's either a) no integrity property in the incoming request\n // or b) there is an integrity, and it matches the precache manifest.\n // See https://github.com/GoogleChrome/workbox/issues/2858\n // Also if the original request users no-cors we don't use integrity.\n // See https://github.com/GoogleChrome/workbox/issues/3096\n if (integrityInManifest &&\n noIntegrityConflict &&\n request.mode !== 'no-cors') {\n this._useDefaultCacheabilityPluginIfNeeded();\n const wasCached = await handler.cachePut(request, response.clone());\n if (process.env.NODE_ENV !== 'production') {\n if (wasCached) {\n logger.log(`A response for ${getFriendlyURL(request.url)} ` +\n `was used to \"repair\" the precache.`);\n }\n }\n }\n }\n else {\n // This shouldn't normally happen, but there are edge cases:\n // https://github.com/GoogleChrome/workbox/issues/1441\n throw new WorkboxError('missing-precache-entry', {\n cacheName: this.cacheName,\n url: request.url,\n });\n }\n if (process.env.NODE_ENV !== 'production') {\n const cacheKey = params.cacheKey || (await handler.getCacheKey(request, 'read'));\n // Workbox is going to handle the route.\n // print the routing details to the console.\n logger.groupCollapsed(`Precaching is responding to: ` + getFriendlyURL(request.url));\n logger.log(`Serving the precached url: ${getFriendlyURL(cacheKey instanceof Request ? cacheKey.url : cacheKey)}`);\n logger.groupCollapsed(`View request details here.`);\n logger.log(request);\n logger.groupEnd();\n logger.groupCollapsed(`View response details here.`);\n logger.log(response);\n logger.groupEnd();\n logger.groupEnd();\n }\n return response;\n }\n async _handleInstall(request, handler) {\n this._useDefaultCacheabilityPluginIfNeeded();\n const response = await handler.fetch(request);\n // Make sure we defer cachePut() until after we know the response\n // should be cached; see https://github.com/GoogleChrome/workbox/issues/2737\n const wasCached = await handler.cachePut(request, response.clone());\n if (!wasCached) {\n // Throwing here will lead to the `install` handler failing, which\n // we want to do if *any* of the responses aren't safe to cache.\n throw new WorkboxError('bad-precaching-response', {\n url: request.url,\n status: response.status,\n });\n }\n return response;\n }\n /**\n * This method is complex, as there a number of things to account for:\n *\n * The `plugins` array can be set at construction, and/or it might be added to\n * to at any time before the strategy is used.\n *\n * At the time the strategy is used (i.e. during an `install` event), there\n * needs to be at least one plugin that implements `cacheWillUpdate` in the\n * array, other than `copyRedirectedCacheableResponsesPlugin`.\n *\n * - If this method is called and there are no suitable `cacheWillUpdate`\n * plugins, we need to add `defaultPrecacheCacheabilityPlugin`.\n *\n * - If this method is called and there is exactly one `cacheWillUpdate`, then\n * we don't have to do anything (this might be a previously added\n * `defaultPrecacheCacheabilityPlugin`, or it might be a custom plugin).\n *\n * - If this method is called and there is more than one `cacheWillUpdate`,\n * then we need to check if one is `defaultPrecacheCacheabilityPlugin`. If so,\n * we need to remove it. (This situation is unlikely, but it could happen if\n * the strategy is used multiple times, the first without a `cacheWillUpdate`,\n * and then later on after manually adding a custom `cacheWillUpdate`.)\n *\n * See https://github.com/GoogleChrome/workbox/issues/2737 for more context.\n *\n * @private\n */\n _useDefaultCacheabilityPluginIfNeeded() {\n let defaultPluginIndex = null;\n let cacheWillUpdatePluginCount = 0;\n for (const [index, plugin] of this.plugins.entries()) {\n // Ignore the copy redirected plugin when determining what to do.\n if (plugin === PrecacheStrategy.copyRedirectedCacheableResponsesPlugin) {\n continue;\n }\n // Save the default plugin's index, in case it needs to be removed.\n if (plugin === PrecacheStrategy.defaultPrecacheCacheabilityPlugin) {\n defaultPluginIndex = index;\n }\n if (plugin.cacheWillUpdate) {\n cacheWillUpdatePluginCount++;\n }\n }\n if (cacheWillUpdatePluginCount === 0) {\n this.plugins.push(PrecacheStrategy.defaultPrecacheCacheabilityPlugin);\n }\n else if (cacheWillUpdatePluginCount > 1 && defaultPluginIndex !== null) {\n // Only remove the default plugin; multiple custom plugins are allowed.\n this.plugins.splice(defaultPluginIndex, 1);\n }\n // Nothing needs to be done if cacheWillUpdatePluginCount is 1\n }\n}\nPrecacheStrategy.defaultPrecacheCacheabilityPlugin = {\n async cacheWillUpdate({ response }) {\n if (!response || response.status >= 400) {\n return null;\n }\n return response;\n },\n};\nPrecacheStrategy.copyRedirectedCacheableResponsesPlugin = {\n async cacheWillUpdate({ response }) {\n return response.redirected ? await copyResponse(response) : response;\n },\n};\nexport { PrecacheStrategy };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { cacheNames } from 'workbox-core/_private/cacheNames.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { waitUntil } from 'workbox-core/_private/waitUntil.js';\nimport { createCacheKey } from './utils/createCacheKey.js';\nimport { PrecacheInstallReportPlugin } from './utils/PrecacheInstallReportPlugin.js';\nimport { PrecacheCacheKeyPlugin } from './utils/PrecacheCacheKeyPlugin.js';\nimport { printCleanupDetails } from './utils/printCleanupDetails.js';\nimport { printInstallDetails } from './utils/printInstallDetails.js';\nimport { PrecacheStrategy } from './PrecacheStrategy.js';\nimport './_version.js';\n/**\n * Performs efficient precaching of assets.\n *\n * @memberof workbox-precaching\n */\nclass PrecacheController {\n /**\n * Create a new PrecacheController.\n *\n * @param {Object} [options]\n * @param {string} [options.cacheName] The cache to use for precaching.\n * @param {string} [options.plugins] Plugins to use when precaching as well\n * as responding to fetch events for precached assets.\n * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to\n * get the response from the network if there's a precache miss.\n */\n constructor({ cacheName, plugins = [], fallbackToNetwork = true, } = {}) {\n this._urlsToCacheKeys = new Map();\n this._urlsToCacheModes = new Map();\n this._cacheKeysToIntegrities = new Map();\n this._strategy = new PrecacheStrategy({\n cacheName: cacheNames.getPrecacheName(cacheName),\n plugins: [\n ...plugins,\n new PrecacheCacheKeyPlugin({ precacheController: this }),\n ],\n fallbackToNetwork,\n });\n // Bind the install and activate methods to the instance.\n this.install = this.install.bind(this);\n this.activate = this.activate.bind(this);\n }\n /**\n * @type {workbox-precaching.PrecacheStrategy} The strategy created by this controller and\n * used to cache assets and respond to fetch events.\n */\n get strategy() {\n return this._strategy;\n }\n /**\n * Adds items to the precache list, removing any duplicates and\n * stores the files in the\n * {@link workbox-core.cacheNames|\"precache cache\"} when the service\n * worker installs.\n *\n * This method can be called multiple times.\n *\n * @param {Array} [entries=[]] Array of entries to precache.\n */\n precache(entries) {\n this.addToCacheList(entries);\n if (!this._installAndActiveListenersAdded) {\n self.addEventListener('install', this.install);\n self.addEventListener('activate', this.activate);\n this._installAndActiveListenersAdded = true;\n }\n }\n /**\n * This method will add items to the precache list, removing duplicates\n * and ensuring the information is valid.\n *\n * @param {Array} entries\n * Array of entries to precache.\n */\n addToCacheList(entries) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isArray(entries, {\n moduleName: 'workbox-precaching',\n className: 'PrecacheController',\n funcName: 'addToCacheList',\n paramName: 'entries',\n });\n }\n const urlsToWarnAbout = [];\n for (const entry of entries) {\n // See https://github.com/GoogleChrome/workbox/issues/2259\n if (typeof entry === 'string') {\n urlsToWarnAbout.push(entry);\n }\n else if (entry && entry.revision === undefined) {\n urlsToWarnAbout.push(entry.url);\n }\n const { cacheKey, url } = createCacheKey(entry);\n const cacheMode = typeof entry !== 'string' && entry.revision ? 'reload' : 'default';\n if (this._urlsToCacheKeys.has(url) &&\n this._urlsToCacheKeys.get(url) !== cacheKey) {\n throw new WorkboxError('add-to-cache-list-conflicting-entries', {\n firstEntry: this._urlsToCacheKeys.get(url),\n secondEntry: cacheKey,\n });\n }\n if (typeof entry !== 'string' && entry.integrity) {\n if (this._cacheKeysToIntegrities.has(cacheKey) &&\n this._cacheKeysToIntegrities.get(cacheKey) !== entry.integrity) {\n throw new WorkboxError('add-to-cache-list-conflicting-integrities', {\n url,\n });\n }\n this._cacheKeysToIntegrities.set(cacheKey, entry.integrity);\n }\n this._urlsToCacheKeys.set(url, cacheKey);\n this._urlsToCacheModes.set(url, cacheMode);\n if (urlsToWarnAbout.length > 0) {\n const warningMessage = `Workbox is precaching URLs without revision ` +\n `info: ${urlsToWarnAbout.join(', ')}\\nThis is generally NOT safe. ` +\n `Learn more at https://bit.ly/wb-precache`;\n if (process.env.NODE_ENV === 'production') {\n // Use console directly to display this warning without bloating\n // bundle sizes by pulling in all of the logger codebase in prod.\n console.warn(warningMessage);\n }\n else {\n logger.warn(warningMessage);\n }\n }\n }\n }\n /**\n * Precaches new and updated assets. Call this method from the service worker\n * install event.\n *\n * Note: this method calls `event.waitUntil()` for you, so you do not need\n * to call it yourself in your event handlers.\n *\n * @param {ExtendableEvent} event\n * @return {Promise}\n */\n install(event) {\n // waitUntil returns Promise\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return waitUntil(event, async () => {\n const installReportPlugin = new PrecacheInstallReportPlugin();\n this.strategy.plugins.push(installReportPlugin);\n // Cache entries one at a time.\n // See https://github.com/GoogleChrome/workbox/issues/2528\n for (const [url, cacheKey] of this._urlsToCacheKeys) {\n const integrity = this._cacheKeysToIntegrities.get(cacheKey);\n const cacheMode = this._urlsToCacheModes.get(url);\n const request = new Request(url, {\n integrity,\n cache: cacheMode,\n credentials: 'same-origin',\n });\n await Promise.all(this.strategy.handleAll({\n params: { cacheKey },\n request,\n event,\n }));\n }\n const { updatedURLs, notUpdatedURLs } = installReportPlugin;\n if (process.env.NODE_ENV !== 'production') {\n printInstallDetails(updatedURLs, notUpdatedURLs);\n }\n return { updatedURLs, notUpdatedURLs };\n });\n }\n /**\n * Deletes assets that are no longer present in the current precache manifest.\n * Call this method from the service worker activate event.\n *\n * Note: this method calls `event.waitUntil()` for you, so you do not need\n * to call it yourself in your event handlers.\n *\n * @param {ExtendableEvent} event\n * @return {Promise}\n */\n activate(event) {\n // waitUntil returns Promise\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return waitUntil(event, async () => {\n const cache = await self.caches.open(this.strategy.cacheName);\n const currentlyCachedRequests = await cache.keys();\n const expectedCacheKeys = new Set(this._urlsToCacheKeys.values());\n const deletedURLs = [];\n for (const request of currentlyCachedRequests) {\n if (!expectedCacheKeys.has(request.url)) {\n await cache.delete(request);\n deletedURLs.push(request.url);\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n printCleanupDetails(deletedURLs);\n }\n return { deletedURLs };\n });\n }\n /**\n * Returns a mapping of a precached URL to the corresponding cache key, taking\n * into account the revision information for the URL.\n *\n * @return {Map} A URL to cache key mapping.\n */\n getURLsToCacheKeys() {\n return this._urlsToCacheKeys;\n }\n /**\n * Returns a list of all the URLs that have been precached by the current\n * service worker.\n *\n * @return {Array} The precached URLs.\n */\n getCachedURLs() {\n return [...this._urlsToCacheKeys.keys()];\n }\n /**\n * Returns the cache key used for storing a given URL. If that URL is\n * unversioned, like `/index.html', then the cache key will be the original\n * URL with a search parameter appended to it.\n *\n * @param {string} url A URL whose cache key you want to look up.\n * @return {string} The versioned URL that corresponds to a cache key\n * for the original URL, or undefined if that URL isn't precached.\n */\n getCacheKeyForURL(url) {\n const urlObject = new URL(url, location.href);\n return this._urlsToCacheKeys.get(urlObject.href);\n }\n /**\n * @param {string} url A cache key whose SRI you want to look up.\n * @return {string} The subresource integrity associated with the cache key,\n * or undefined if it's not set.\n */\n getIntegrityForCacheKey(cacheKey) {\n return this._cacheKeysToIntegrities.get(cacheKey);\n }\n /**\n * This acts as a drop-in replacement for\n * [`cache.match()`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/match)\n * with the following differences:\n *\n * - It knows what the name of the precache is, and only checks in that cache.\n * - It allows you to pass in an \"original\" URL without versioning parameters,\n * and it will automatically look up the correct cache key for the currently\n * active revision of that URL.\n *\n * E.g., `matchPrecache('index.html')` will find the correct precached\n * response for the currently active service worker, even if the actual cache\n * key is `'/index.html?__WB_REVISION__=1234abcd'`.\n *\n * @param {string|Request} request The key (without revisioning parameters)\n * to look up in the precache.\n * @return {Promise}\n */\n async matchPrecache(request) {\n const url = request instanceof Request ? request.url : request;\n const cacheKey = this.getCacheKeyForURL(url);\n if (cacheKey) {\n const cache = await self.caches.open(this.strategy.cacheName);\n return cache.match(cacheKey);\n }\n return undefined;\n }\n /**\n * Returns a function that looks up `url` in the precache (taking into\n * account revision information), and returns the corresponding `Response`.\n *\n * @param {string} url The precached URL which will be used to lookup the\n * `Response`.\n * @return {workbox-routing~handlerCallback}\n */\n createHandlerBoundToURL(url) {\n const cacheKey = this.getCacheKeyForURL(url);\n if (!cacheKey) {\n throw new WorkboxError('non-precached-url', { url });\n }\n return (options) => {\n options.request = new Request(url);\n options.params = Object.assign({ cacheKey }, options.params);\n return this.strategy.handle(options);\n };\n }\n}\nexport { PrecacheController };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { PrecacheController } from '../PrecacheController.js';\nimport '../_version.js';\nlet precacheController;\n/**\n * @return {PrecacheController}\n * @private\n */\nexport const getOrCreatePrecacheController = () => {\n if (!precacheController) {\n precacheController = new PrecacheController();\n }\n return precacheController;\n};\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';\nimport './_version.js';\n/**\n * Adds plugins to the precaching strategy.\n *\n * @param {Array} plugins\n *\n * @memberof workbox-precaching\n */\nfunction addPlugins(plugins) {\n const precacheController = getOrCreatePrecacheController();\n precacheController.strategy.plugins.push(...plugins);\n}\nexport { addPlugins };\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';\n/**\n * Removes any URL search parameters that should be ignored.\n *\n * @param {URL} urlObject The original URL.\n * @param {Array} ignoreURLParametersMatching RegExps to test against\n * each search parameter name. Matches mean that the search parameter should be\n * ignored.\n * @return {URL} The URL with any ignored search parameters removed.\n *\n * @private\n * @memberof workbox-precaching\n */\nexport function removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching = []) {\n // Convert the iterable into an array at the start of the loop to make sure\n // deletion doesn't mess up iteration.\n for (const paramName of [...urlObject.searchParams.keys()]) {\n if (ignoreURLParametersMatching.some((regExp) => regExp.test(paramName))) {\n urlObject.searchParams.delete(paramName);\n }\n }\n return urlObject;\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { removeIgnoredSearchParams } from './removeIgnoredSearchParams.js';\nimport '../_version.js';\n/**\n * Generator function that yields possible variations on the original URL to\n * check, one at a time.\n *\n * @param {string} url\n * @param {Object} options\n *\n * @private\n * @memberof workbox-precaching\n */\nexport function* generateURLVariations(url, { ignoreURLParametersMatching = [/^utm_/, /^fbclid$/], directoryIndex = 'index.html', cleanURLs = true, urlManipulation, } = {}) {\n const urlObject = new URL(url, location.href);\n urlObject.hash = '';\n yield urlObject.href;\n const urlWithoutIgnoredParams = removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching);\n yield urlWithoutIgnoredParams.href;\n if (directoryIndex && urlWithoutIgnoredParams.pathname.endsWith('/')) {\n const directoryURL = new URL(urlWithoutIgnoredParams.href);\n directoryURL.pathname += directoryIndex;\n yield directoryURL.href;\n }\n if (cleanURLs) {\n const cleanURL = new URL(urlWithoutIgnoredParams.href);\n cleanURL.pathname += '.html';\n yield cleanURL.href;\n }\n if (urlManipulation) {\n const additionalURLs = urlManipulation({ url: urlObject });\n for (const urlToAttempt of additionalURLs) {\n yield urlToAttempt.href;\n }\n }\n}\n","/*\n Copyright 2020 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 { logger } from 'workbox-core/_private/logger.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { Route } from 'workbox-routing/Route.js';\nimport { generateURLVariations } from './utils/generateURLVariations.js';\nimport './_version.js';\n/**\n * A subclass of {@link workbox-routing.Route} that takes a\n * {@link workbox-precaching.PrecacheController}\n * instance and uses it to match incoming requests and handle fetching\n * responses from the precache.\n *\n * @memberof workbox-precaching\n * @extends workbox-routing.Route\n */\nclass PrecacheRoute extends Route {\n /**\n * @param {PrecacheController} precacheController A `PrecacheController`\n * instance used to both match requests and respond to fetch events.\n * @param {Object} [options] Options to control how requests are matched\n * against the list of precached URLs.\n * @param {string} [options.directoryIndex=index.html] The `directoryIndex` will\n * check cache entries for a URLs ending with '/' to see if there is a hit when\n * appending the `directoryIndex` value.\n * @param {Array} [options.ignoreURLParametersMatching=[/^utm_/, /^fbclid$/]] An\n * array of regex's to remove search params when looking for a cache match.\n * @param {boolean} [options.cleanURLs=true] The `cleanURLs` option will\n * check the cache for the URL with a `.html` added to the end of the end.\n * @param {workbox-precaching~urlManipulation} [options.urlManipulation]\n * This is a function that should take a URL and return an array of\n * alternative URLs that should be checked for precache matches.\n */\n constructor(precacheController, options) {\n const match = ({ request, }) => {\n const urlsToCacheKeys = precacheController.getURLsToCacheKeys();\n for (const possibleURL of generateURLVariations(request.url, options)) {\n const cacheKey = urlsToCacheKeys.get(possibleURL);\n if (cacheKey) {\n const integrity = precacheController.getIntegrityForCacheKey(cacheKey);\n return { cacheKey, integrity };\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`Precaching did not find a match for ` + getFriendlyURL(request.url));\n }\n return;\n };\n super(match, precacheController.strategy);\n }\n}\nexport { PrecacheRoute };\n","/*\n Copyright 2019 Google LLC\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 { registerRoute } from 'workbox-routing/registerRoute.js';\nimport { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';\nimport { PrecacheRoute } from './PrecacheRoute.js';\nimport './_version.js';\n/**\n * Add a `fetch` listener to the service worker that will\n * respond to\n * [network requests]{@link https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#Custom_responses_to_requests}\n * with precached assets.\n *\n * Requests for assets that aren't precached, the `FetchEvent` will not be\n * responded to, allowing the event to fall through to other `fetch` event\n * listeners.\n *\n * @param {Object} [options] See the {@link workbox-precaching.PrecacheRoute}\n * options.\n *\n * @memberof workbox-precaching\n */\nfunction addRoute(options) {\n const precacheController = getOrCreatePrecacheController();\n const precacheRoute = new PrecacheRoute(precacheController, options);\n registerRoute(precacheRoute);\n}\nexport { addRoute };\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';\nconst SUBSTRING_TO_FIND = '-precache-';\n/**\n * Cleans up incompatible precaches that were created by older versions of\n * Workbox, by a service worker registered under the current scope.\n *\n * This is meant to be called as part of the `activate` event.\n *\n * This should be safe to use as long as you don't include `substringToFind`\n * (defaulting to `-precache-`) in your non-precache cache names.\n *\n * @param {string} currentPrecacheName The cache name currently in use for\n * precaching. This cache won't be deleted.\n * @param {string} [substringToFind='-precache-'] Cache names which include this\n * substring will be deleted (excluding `currentPrecacheName`).\n * @return {Array} A list of all the cache names that were deleted.\n *\n * @private\n * @memberof workbox-precaching\n */\nconst deleteOutdatedCaches = async (currentPrecacheName, substringToFind = SUBSTRING_TO_FIND) => {\n const cacheNames = await self.caches.keys();\n const cacheNamesToDelete = cacheNames.filter((cacheName) => {\n return (cacheName.includes(substringToFind) &&\n cacheName.includes(self.registration.scope) &&\n cacheName !== currentPrecacheName);\n });\n await Promise.all(cacheNamesToDelete.map((cacheName) => self.caches.delete(cacheName)));\n return cacheNamesToDelete;\n};\nexport { deleteOutdatedCaches };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { cacheNames } from 'workbox-core/_private/cacheNames.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { deleteOutdatedCaches } from './utils/deleteOutdatedCaches.js';\nimport './_version.js';\n/**\n * Adds an `activate` event listener which will clean up incompatible\n * precaches that were created by older versions of Workbox.\n *\n * @memberof workbox-precaching\n */\nfunction cleanupOutdatedCaches() {\n // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705\n self.addEventListener('activate', ((event) => {\n const cacheName = cacheNames.getPrecacheName();\n event.waitUntil(deleteOutdatedCaches(cacheName).then((cachesDeleted) => {\n if (process.env.NODE_ENV !== 'production') {\n if (cachesDeleted.length > 0) {\n logger.log(`The following out-of-date precaches were cleaned up ` +\n `automatically:`, cachesDeleted);\n }\n }\n }));\n }));\n}\nexport { cleanupOutdatedCaches };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';\nimport './_version.js';\n/**\n * Helper function that calls\n * {@link PrecacheController#createHandlerBoundToURL} on the default\n * {@link PrecacheController} instance.\n *\n * If you are creating your own {@link PrecacheController}, then call the\n * {@link PrecacheController#createHandlerBoundToURL} on that instance,\n * instead of using this function.\n *\n * @param {string} url The precached URL which will be used to lookup the\n * `Response`.\n * @param {boolean} [fallbackToNetwork=true] Whether to attempt to get the\n * response from the network if there's a precache miss.\n * @return {workbox-routing~handlerCallback}\n *\n * @memberof workbox-precaching\n */\nfunction createHandlerBoundToURL(url) {\n const precacheController = getOrCreatePrecacheController();\n return precacheController.createHandlerBoundToURL(url);\n}\nexport { createHandlerBoundToURL };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';\nimport './_version.js';\n/**\n * Takes in a URL, and returns the corresponding URL that could be used to\n * lookup the entry in the precache.\n *\n * If a relative URL is provided, the location of the service worker file will\n * be used as the base.\n *\n * For precached entries without revision information, the cache key will be the\n * same as the original URL.\n *\n * For precached entries with revision information, the cache key will be the\n * original URL with the addition of a query parameter used for keeping track of\n * the revision info.\n *\n * @param {string} url The URL whose cache key to look up.\n * @return {string} The cache key that corresponds to that URL.\n *\n * @memberof workbox-precaching\n */\nfunction getCacheKeyForURL(url) {\n const precacheController = getOrCreatePrecacheController();\n return precacheController.getCacheKeyForURL(url);\n}\nexport { getCacheKeyForURL };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';\nimport './_version.js';\n/**\n * Helper function that calls\n * {@link PrecacheController#matchPrecache} on the default\n * {@link PrecacheController} instance.\n *\n * If you are creating your own {@link PrecacheController}, then call\n * {@link PrecacheController#matchPrecache} on that instance,\n * instead of using this function.\n *\n * @param {string|Request} request The key (without revisioning parameters)\n * to look up in the precache.\n * @return {Promise}\n *\n * @memberof workbox-precaching\n */\nfunction matchPrecache(request) {\n const precacheController = getOrCreatePrecacheController();\n return precacheController.matchPrecache(request);\n}\nexport { matchPrecache };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';\nimport './_version.js';\n/**\n * Adds items to the precache list, removing any duplicates and\n * stores the files in the\n * {@link workbox-core.cacheNames|\"precache cache\"} when the service\n * worker installs.\n *\n * This method can be called multiple times.\n *\n * Please note: This method **will not** serve any of the cached files for you.\n * It only precaches files. To respond to a network request you call\n * {@link workbox-precaching.addRoute}.\n *\n * If you have a single array of files to precache, you can just call\n * {@link workbox-precaching.precacheAndRoute}.\n *\n * @param {Array} [entries=[]] Array of entries to precache.\n *\n * @memberof workbox-precaching\n */\nfunction precache(entries) {\n const precacheController = getOrCreatePrecacheController();\n precacheController.precache(entries);\n}\nexport { precache };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { addRoute } from './addRoute.js';\nimport { precache } from './precache.js';\nimport './_version.js';\n/**\n * This method will add entries to the precache list and add a route to\n * respond to fetch events.\n *\n * This is a convenience method that will call\n * {@link workbox-precaching.precache} and\n * {@link workbox-precaching.addRoute} in a single call.\n *\n * @param {Array} entries Array of entries to precache.\n * @param {Object} [options] See the\n * {@link workbox-precaching.PrecacheRoute} options.\n *\n * @memberof workbox-precaching\n */\nfunction precacheAndRoute(entries, options) {\n precache(entries);\n addRoute(options);\n}\nexport { precacheAndRoute };\n","/*\n Copyright 2020 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 { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';\nimport './_version.js';\n/**\n * `PrecacheFallbackPlugin` allows you to specify an \"offline fallback\"\n * response to be used when a given strategy is unable to generate a response.\n *\n * It does this by intercepting the `handlerDidError` plugin callback\n * and returning a precached response, taking the expected revision parameter\n * into account automatically.\n *\n * Unless you explicitly pass in a `PrecacheController` instance to the\n * constructor, the default instance will be used. Generally speaking, most\n * developers will end up using the default.\n *\n * @memberof workbox-precaching\n */\nclass PrecacheFallbackPlugin {\n /**\n * Constructs a new PrecacheFallbackPlugin with the associated fallbackURL.\n *\n * @param {Object} config\n * @param {string} config.fallbackURL A precached URL to use as the fallback\n * if the associated strategy can't generate a response.\n * @param {PrecacheController} [config.precacheController] An optional\n * PrecacheController instance. If not provided, the default\n * PrecacheController will be used.\n */\n constructor({ fallbackURL, precacheController, }) {\n /**\n * @return {Promise} The precache response for the fallback URL.\n *\n * @private\n */\n this.handlerDidError = () => this._precacheController.matchPrecache(this._fallbackURL);\n this._fallbackURL = fallbackURL;\n this._precacheController =\n precacheController || getOrCreatePrecacheController();\n }\n}\nexport { PrecacheFallbackPlugin };\n"],"names":["self","_","e","REVISION_SEARCH_PARAM","createCacheKey","entry","WorkboxError","urlObject","URL","location","href","cacheKey","url","revision","cacheKeyURL","originalURL","searchParams","set","PrecacheInstallReportPlugin","constructor","updatedURLs","notUpdatedURLs","handlerWillStart","request","state","originalRequest","cachedResponseWillBeUsed","event","cachedResponse","type","Request","push","PrecacheCacheKeyPlugin","precacheController","cacheKeyWillBeUsed","params","_precacheController","getCacheKeyForURL","headers","logGroup","groupTitle","deletedURLs","logger","groupCollapsed","log","groupEnd","printCleanupDetails","deletionCount","length","_nestedGroup","urls","printInstallDetails","urlsToPrecache","urlsAlreadyPrecached","precachedCount","alreadyPrecachedCount","message","PrecacheStrategy","Strategy","options","cacheName","cacheNames","getPrecacheName","_fallbackToNetwork","fallbackToNetwork","plugins","copyRedirectedCacheableResponsesPlugin","_handle","handler","response","cacheMatch","_handleInstall","_handleFetch","warn","getFriendlyURL","integrityInManifest","integrity","integrityInRequest","noIntegrityConflict","fetch","mode","undefined","_useDefaultCacheabilityPluginIfNeeded","wasCached","cachePut","clone","getCacheKey","status","defaultPluginIndex","cacheWillUpdatePluginCount","index","plugin","entries","defaultPrecacheCacheabilityPlugin","cacheWillUpdate","splice","redirected","copyResponse","PrecacheController","_urlsToCacheKeys","Map","_urlsToCacheModes","_cacheKeysToIntegrities","_strategy","install","bind","activate","strategy","precache","addToCacheList","_installAndActiveListenersAdded","addEventListener","assert","isArray","moduleName","className","funcName","paramName","urlsToWarnAbout","cacheMode","has","get","firstEntry","secondEntry","warningMessage","join","waitUntil","installReportPlugin","cache","credentials","Promise","all","handleAll","caches","open","currentlyCachedRequests","keys","expectedCacheKeys","Set","values","delete","getURLsToCacheKeys","getCachedURLs","getIntegrityForCacheKey","matchPrecache","match","createHandlerBoundToURL","Object","assign","handle","getOrCreatePrecacheController","addPlugins","removeIgnoredSearchParams","ignoreURLParametersMatching","some","regExp","test","generateURLVariations","directoryIndex","cleanURLs","urlManipulation","hash","urlWithoutIgnoredParams","pathname","endsWith","directoryURL","cleanURL","additionalURLs","urlToAttempt","PrecacheRoute","Route","urlsToCacheKeys","possibleURL","debug","addRoute","precacheRoute","registerRoute","SUBSTRING_TO_FIND","deleteOutdatedCaches","currentPrecacheName","substringToFind","cacheNamesToDelete","filter","includes","registration","scope","map","cleanupOutdatedCaches","then","cachesDeleted","precacheAndRoute","PrecacheFallbackPlugin","fallbackURL","handlerDidError","_fallbackURL"],"mappings":";;;;IACA;IACA,IAAI;IACAA,EAAAA,IAAI,CAAC,0BAA0B,CAAC,IAAIC,CAAC,EAAE;IAC3C,CAAC,CACD,OAAOC,CAAC,EAAE,CAAE;;ICLZ;IACA;;IAEA;IACA;IACA;IACA;IAGA;IACA,MAAMC,qBAAqB,GAAG,iBAAiB;IAC/C;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACO,SAASC,cAAcA,CAACC,KAAK,EAAE;MAClC,IAAI,CAACA,KAAK,EAAE;IACR,IAAA,MAAM,IAAIC,4BAAY,CAAC,mCAAmC,EAAE;IAAED,MAAAA;IAAM,KAAC,CAAC;IAC1E,EAAA;IACA;IACA;IACA,EAAA,IAAI,OAAOA,KAAK,KAAK,QAAQ,EAAE;QAC3B,MAAME,SAAS,GAAG,IAAIC,GAAG,CAACH,KAAK,EAAEI,QAAQ,CAACC,IAAI,CAAC;QAC/C,OAAO;UACHC,QAAQ,EAAEJ,SAAS,CAACG,IAAI;UACxBE,GAAG,EAAEL,SAAS,CAACG;SAClB;IACL,EAAA;MACA,MAAM;QAAEG,QAAQ;IAAED,IAAAA;IAAI,GAAC,GAAGP,KAAK;MAC/B,IAAI,CAACO,GAAG,EAAE;IACN,IAAA,MAAM,IAAIN,4BAAY,CAAC,mCAAmC,EAAE;IAAED,MAAAA;IAAM,KAAC,CAAC;IAC1E,EAAA;IACA;IACA;MACA,IAAI,CAACQ,QAAQ,EAAE;QACX,MAAMN,SAAS,GAAG,IAAIC,GAAG,CAACI,GAAG,EAAEH,QAAQ,CAACC,IAAI,CAAC;QAC7C,OAAO;UACHC,QAAQ,EAAEJ,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IACA;IAGA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,SAASoI,aAAaA,CAACzH,OAAO,EAAE;IAC5B,EAAA,MAAMU,kBAAkB,GAAGqH,6BAA6B,EAAE;IAC1D,EAAA,OAAOrH,kBAAkB,CAAC+G,aAAa,CAACzH,OAAO,CAAC;IACpD;;IC3BA;IACA;;IAEA;IACA;IACA;IACA;IAGA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,SAASqF,QAAQA,CAAChB,OAAO,EAAE;IACvB,EAAA,MAAM3D,kBAAkB,GAAGqH,6BAA6B,EAAE;IAC1DrH,EAAAA,kBAAkB,CAAC2E,QAAQ,CAAChB,OAAO,CAAC;IACxC;;IC/BA;IACA;;IAEA;IACA;IACA;IACA;IAIA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,SAASkG,gBAAgBA,CAAClG,OAAO,EAAEjC,OAAO,EAAE;MACxCiD,QAAQ,CAAChB,OAAO,CAAC;MACjBkF,QAAQ,CAACnH,OAAO,CAAC;IACrB;;IC3BA;IACA;;IAEA;IACA;IACA;IACA;IAGA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,MAAMoI,sBAAsB,CAAC;IACzB;IACJ;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACI5K,EAAAA,WAAWA,CAAC;QAAE6K,WAAW;IAAE/J,IAAAA;IAAoB,GAAC,EAAE;IAC9C;IACR;IACA;IACA;IACA;IACQ,IAAA,IAAI,CAACgK,eAAe,GAAG,MAAM,IAAI,CAAC7J,mBAAmB,CAAC4G,aAAa,CAAC,IAAI,CAACkD,YAAY,CAAC;QACtF,IAAI,CAACA,YAAY,GAAGF,WAAW;IAC/B,IAAA,IAAI,CAAC5J,mBAAmB,GACpBH,kBAAkB,IAAIqH,6BAA6B,EAAE;IAC7D,EAAA;IACJ;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/workbox-precaching/build/workbox-precaching.prod.js b/node_modules/workbox-precaching/build/workbox-precaching.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..9e90d8cdae023c06cee62043229fe12190390393 --- /dev/null +++ b/node_modules/workbox-precaching/build/workbox-precaching.prod.js @@ -0,0 +1,2 @@ +this.workbox=this.workbox||{},this.workbox.precaching=function(t,e,s,n,i,c,r,o){"use strict";try{self["workbox:precaching:7.4.0"]&&_()}catch(t){}function a(t){if(!t)throw new s.WorkboxError("add-to-cache-list-unexpected-type",{entry:t});if("string"==typeof t){const e=new URL(t,location.href);return{cacheKey:e.href,url:e.href}}const{revision:e,url:n}=t;if(!n)throw new s.WorkboxError("add-to-cache-list-unexpected-type",{entry:t});if(!e){const t=new URL(n,location.href);return{cacheKey:t.href,url:t.href}}const i=new URL(n,location.href),c=new URL(n,location.href);return i.searchParams.set("__WB_REVISION__",e),{cacheKey:i.href,url:c.href}}class h{constructor(){this.updatedURLs=[],this.notUpdatedURLs=[],this.handlerWillStart=async({request:t,state:e})=>{e&&(e.originalRequest=t)},this.cachedResponseWillBeUsed=async({event:t,state:e,cachedResponse:s})=>{if("install"===t.type&&e&&e.originalRequest&&e.originalRequest instanceof Request){const t=e.originalRequest.url;s?this.notUpdatedURLs.push(t):this.updatedURLs.push(t)}return s}}}class l{constructor({precacheController:t}){this.cacheKeyWillBeUsed=async({request:t,params:e})=>{const s=(null==e?void 0:e.cacheKey)||this.U.getCacheKeyForURL(t.url);return s?new Request(s,{headers:t.headers}):t},this.U=t}}class u extends c.Strategy{constructor(t={}){t.cacheName=e.cacheNames.getPrecacheName(t.cacheName),super(t),this.K=!1!==t.fallbackToNetwork,this.plugins.push(u.copyRedirectedCacheableResponsesPlugin)}async _handle(t,e){const s=await e.cacheMatch(t);return s||(e.event&&"install"===e.event.type?await this.T(t,e):await this.I(t,e))}async I(t,e){let n;const i=e.params||{};if(!this.K)throw new s.WorkboxError("missing-precache-entry",{cacheName:this.cacheName,url:t.url});{const s=i.integrity,c=t.integrity,r=!c||c===s;n=await e.fetch(new Request(t,{integrity:"no-cors"!==t.mode?c||s:void 0})),s&&r&&"no-cors"!==t.mode&&(this.P(),await e.cachePut(t,n.clone()))}return n}async T(t,e){this.P();const n=await e.fetch(t);if(!await e.cachePut(t,n.clone()))throw new s.WorkboxError("bad-precaching-response",{url:t.url,status:n.status});return n}P(){let t=null,e=0;for(const[s,n]of this.plugins.entries())n!==u.copyRedirectedCacheableResponsesPlugin&&(n===u.defaultPrecacheCacheabilityPlugin&&(t=s),n.cacheWillUpdate&&e++);0===e?this.plugins.push(u.defaultPrecacheCacheabilityPlugin):e>1&&null!==t&&this.plugins.splice(t,1)}}u.defaultPrecacheCacheabilityPlugin={cacheWillUpdate:async({response:t})=>!t||t.status>=400?null:t},u.copyRedirectedCacheableResponsesPlugin={cacheWillUpdate:async({response:t})=>t.redirected?await i.copyResponse(t):t};class f{constructor({cacheName:t,plugins:s=[],fallbackToNetwork:n=!0}={}){this.F=new Map,this.B=new Map,this.S=new Map,this.u=new u({cacheName:e.cacheNames.getPrecacheName(t),plugins:[...s,new l({precacheController:this})],fallbackToNetwork:n}),this.install=this.install.bind(this),this.activate=this.activate.bind(this)}get strategy(){return this.u}precache(t){this.addToCacheList(t),this.$||(self.addEventListener("install",this.install),self.addEventListener("activate",this.activate),this.$=!0)}addToCacheList(t){const e=[];for(const n of t){"string"==typeof n?e.push(n):n&&void 0===n.revision&&e.push(n.url);const{cacheKey:t,url:i}=a(n),c="string"!=typeof n&&n.revision?"reload":"default";if(this.F.has(i)&&this.F.get(i)!==t)throw new s.WorkboxError("add-to-cache-list-conflicting-entries",{firstEntry:this.F.get(i),secondEntry:t});if("string"!=typeof n&&n.integrity){if(this.S.has(t)&&this.S.get(t)!==n.integrity)throw new s.WorkboxError("add-to-cache-list-conflicting-integrities",{url:i});this.S.set(t,n.integrity)}if(this.F.set(i,t),this.B.set(i,c),e.length>0){const t=`Workbox is precaching URLs without revision info: ${e.join(", ")}\nThis is generally NOT safe. Learn more at https://bit.ly/wb-precache`;console.warn(t)}}}install(t){return n.waitUntil(t,(async()=>{const e=new h;this.strategy.plugins.push(e);for(const[e,s]of this.F){const n=this.S.get(s),i=this.B.get(e),c=new Request(e,{integrity:n,cache:i,credentials:"same-origin"});await Promise.all(this.strategy.handleAll({params:{cacheKey:s},request:c,event:t}))}const{updatedURLs:s,notUpdatedURLs:n}=e;return{updatedURLs:s,notUpdatedURLs:n}}))}activate(t){return n.waitUntil(t,(async()=>{const t=await self.caches.open(this.strategy.cacheName),e=await t.keys(),s=new Set(this.F.values()),n=[];for(const i of e)s.has(i.url)||(await t.delete(i),n.push(i.url));return{deletedURLs:n}}))}getURLsToCacheKeys(){return this.F}getCachedURLs(){return[...this.F.keys()]}getCacheKeyForURL(t){const e=new URL(t,location.href);return this.F.get(e.href)}getIntegrityForCacheKey(t){return this.S.get(t)}async matchPrecache(t){const e=t instanceof Request?t.url:t,s=this.getCacheKeyForURL(e);if(s){return(await self.caches.open(this.strategy.cacheName)).match(s)}}createHandlerBoundToURL(t){const e=this.getCacheKeyForURL(t);if(!e)throw new s.WorkboxError("non-precached-url",{url:t});return s=>(s.request=new Request(t),s.params=Object.assign({cacheKey:e},s.params),this.strategy.handle(s))}}let w;const d=()=>(w||(w=new f),w);class y extends o.Route{constructor(t,e){super((({request:s})=>{const n=t.getURLsToCacheKeys();for(const i of function*(t,{ignoreURLParametersMatching:e=[/^utm_/,/^fbclid$/],directoryIndex:s="index.html",cleanURLs:n=!0,urlManipulation:i}={}){const c=new URL(t,location.href);c.hash="",yield c.href;const r=function(t,e=[]){for(const s of[...t.searchParams.keys()])e.some((t=>t.test(s)))&&t.searchParams.delete(s);return t}(c,e);if(yield r.href,s&&r.pathname.endsWith("/")){const t=new URL(r.href);t.pathname+=s,yield t.href}if(n){const t=new URL(r.href);t.pathname+=".html",yield t.href}if(i){const t=i({url:c});for(const e of t)yield e.href}}(s.url,e)){const e=n.get(i);if(e){return{cacheKey:e,integrity:t.getIntegrityForCacheKey(e)}}}}),t.strategy)}}function p(t){const e=d(),s=new y(e,t);r.registerRoute(s)}function R(t){d().precache(t)}return t.PrecacheController=f,t.PrecacheFallbackPlugin=class{constructor({fallbackURL:t,precacheController:e}){this.handlerDidError=()=>this.U.matchPrecache(this.D),this.D=t,this.U=e||d()}},t.PrecacheRoute=y,t.PrecacheStrategy=u,t.addPlugins=function(t){d().strategy.plugins.push(...t)},t.addRoute=p,t.cleanupOutdatedCaches=function(){self.addEventListener("activate",(t=>{const s=e.cacheNames.getPrecacheName();t.waitUntil((async(t,e="-precache-")=>{const s=(await self.caches.keys()).filter((s=>s.includes(e)&&s.includes(self.registration.scope)&&s!==t));return await Promise.all(s.map((t=>self.caches.delete(t)))),s})(s).then((t=>{})))}))},t.createHandlerBoundToURL=function(t){return d().createHandlerBoundToURL(t)},t.getCacheKeyForURL=function(t){return d().getCacheKeyForURL(t)},t.matchPrecache=function(t){return d().matchPrecache(t)},t.precache=R,t.precacheAndRoute=function(t,e){R(t),p(e)},t}({},workbox.core._private,workbox.core._private,workbox.core._private,workbox.core,workbox.strategies,workbox.routing,workbox.routing); +//# sourceMappingURL=workbox-precaching.prod.js.map diff --git a/node_modules/workbox-precaching/build/workbox-precaching.prod.js.map b/node_modules/workbox-precaching/build/workbox-precaching.prod.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a975e28dd6b998664c783dd72eb00472aabe562b --- /dev/null +++ b/node_modules/workbox-precaching/build/workbox-precaching.prod.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-precaching.prod.js","sources":["../_version.js","../utils/createCacheKey.js","../utils/PrecacheInstallReportPlugin.js","../utils/PrecacheCacheKeyPlugin.js","../PrecacheStrategy.js","../PrecacheController.js","../utils/getOrCreatePrecacheController.js","../PrecacheRoute.js","../utils/generateURLVariations.js","../utils/removeIgnoredSearchParams.js","../addRoute.js","../precache.js","../PrecacheFallbackPlugin.js","../addPlugins.js","../cleanupOutdatedCaches.js","../utils/deleteOutdatedCaches.js","../createHandlerBoundToURL.js","../getCacheKeyForURL.js","../matchPrecache.js","../precacheAndRoute.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:precaching:7.4.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 '../_version.js';\n// Name of the search parameter used to store revision info.\nconst REVISION_SEARCH_PARAM = '__WB_REVISION__';\n/**\n * Converts a manifest entry into a versioned URL suitable for precaching.\n *\n * @param {Object|string} entry\n * @return {string} A URL with versioning info.\n *\n * @private\n * @memberof workbox-precaching\n */\nexport function createCacheKey(entry) {\n if (!entry) {\n throw new WorkboxError('add-to-cache-list-unexpected-type', { entry });\n }\n // If a precache manifest entry is a string, it's assumed to be a versioned\n // URL, like '/app.abcd1234.js'. Return as-is.\n if (typeof entry === 'string') {\n const urlObject = new URL(entry, location.href);\n return {\n cacheKey: urlObject.href,\n url: urlObject.href,\n };\n }\n const { revision, url } = entry;\n if (!url) {\n throw new WorkboxError('add-to-cache-list-unexpected-type', { entry });\n }\n // If there's just a URL and no revision, then it's also assumed to be a\n // versioned URL.\n if (!revision) {\n const urlObject = new URL(url, location.href);\n return {\n cacheKey: urlObject.href,\n url: urlObject.href,\n };\n }\n // Otherwise, construct a properly versioned URL using the custom Workbox\n // search parameter along with the revision info.\n const cacheKeyURL = new URL(url, location.href);\n const originalURL = new URL(url, location.href);\n cacheKeyURL.searchParams.set(REVISION_SEARCH_PARAM, revision);\n return {\n cacheKey: cacheKeyURL.href,\n url: originalURL.href,\n };\n}\n","/*\n Copyright 2020 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';\n/**\n * A plugin, designed to be used with PrecacheController, to determine the\n * of assets that were updated (or not updated) during the install event.\n *\n * @private\n */\nclass PrecacheInstallReportPlugin {\n constructor() {\n this.updatedURLs = [];\n this.notUpdatedURLs = [];\n this.handlerWillStart = async ({ request, state, }) => {\n // TODO: `state` should never be undefined...\n if (state) {\n state.originalRequest = request;\n }\n };\n this.cachedResponseWillBeUsed = async ({ event, state, cachedResponse, }) => {\n if (event.type === 'install') {\n if (state &&\n state.originalRequest &&\n state.originalRequest instanceof Request) {\n // TODO: `state` should never be undefined...\n const url = state.originalRequest.url;\n if (cachedResponse) {\n this.notUpdatedURLs.push(url);\n }\n else {\n this.updatedURLs.push(url);\n }\n }\n }\n return cachedResponse;\n };\n }\n}\nexport { PrecacheInstallReportPlugin };\n","/*\n Copyright 2020 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';\n/**\n * A plugin, designed to be used with PrecacheController, to translate URLs into\n * the corresponding cache key, based on the current revision info.\n *\n * @private\n */\nclass PrecacheCacheKeyPlugin {\n constructor({ precacheController }) {\n this.cacheKeyWillBeUsed = async ({ request, params, }) => {\n // Params is type any, can't change right now.\n /* eslint-disable */\n const cacheKey = (params === null || params === void 0 ? void 0 : params.cacheKey) ||\n this._precacheController.getCacheKeyForURL(request.url);\n /* eslint-enable */\n return cacheKey\n ? new Request(cacheKey, { headers: request.headers })\n : request;\n };\n this._precacheController = precacheController;\n }\n}\nexport { PrecacheCacheKeyPlugin };\n","/*\n Copyright 2020 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 { copyResponse } from 'workbox-core/copyResponse.js';\nimport { cacheNames } from 'workbox-core/_private/cacheNames.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { Strategy } from 'workbox-strategies/Strategy.js';\nimport './_version.js';\n/**\n * A {@link workbox-strategies.Strategy} implementation\n * specifically designed to work with\n * {@link workbox-precaching.PrecacheController}\n * to both cache and fetch precached assets.\n *\n * Note: an instance of this class is created automatically when creating a\n * `PrecacheController`; it's generally not necessary to create this yourself.\n *\n * @extends workbox-strategies.Strategy\n * @memberof workbox-precaching\n */\nclass PrecacheStrategy extends Strategy {\n /**\n *\n * @param {Object} [options]\n * @param {string} [options.cacheName] Cache name to store and retrieve\n * requests. Defaults to the cache names provided by\n * {@link workbox-core.cacheNames}.\n * @param {Array} [options.plugins] {@link https://developers.google.com/web/tools/workbox/guides/using-plugins|Plugins}\n * to use in conjunction with this caching strategy.\n * @param {Object} [options.fetchOptions] Values passed along to the\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters|init}\n * of all fetch() requests made by this strategy.\n * @param {Object} [options.matchOptions] The\n * {@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions|CacheQueryOptions}\n * for any `cache.match()` or `cache.put()` calls made by this strategy.\n * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to\n * get the response from the network if there's a precache miss.\n */\n constructor(options = {}) {\n options.cacheName = cacheNames.getPrecacheName(options.cacheName);\n super(options);\n this._fallbackToNetwork =\n options.fallbackToNetwork === false ? false : true;\n // Redirected responses cannot be used to satisfy a navigation request, so\n // any redirected response must be \"copied\" rather than cloned, so the new\n // response doesn't contain the `redirected` flag. See:\n // https://bugs.chromium.org/p/chromium/issues/detail?id=669363&desc=2#c1\n this.plugins.push(PrecacheStrategy.copyRedirectedCacheableResponsesPlugin);\n }\n /**\n * @private\n * @param {Request|string} request A request to run this strategy for.\n * @param {workbox-strategies.StrategyHandler} handler The event that\n * triggered the request.\n * @return {Promise}\n */\n async _handle(request, handler) {\n const response = await handler.cacheMatch(request);\n if (response) {\n return response;\n }\n // If this is an `install` event for an entry that isn't already cached,\n // then populate the cache.\n if (handler.event && handler.event.type === 'install') {\n return await this._handleInstall(request, handler);\n }\n // Getting here means something went wrong. An entry that should have been\n // precached wasn't found in the cache.\n return await this._handleFetch(request, handler);\n }\n async _handleFetch(request, handler) {\n let response;\n const params = (handler.params || {});\n // Fall back to the network if we're configured to do so.\n if (this._fallbackToNetwork) {\n if (process.env.NODE_ENV !== 'production') {\n logger.warn(`The precached response for ` +\n `${getFriendlyURL(request.url)} in ${this.cacheName} was not ` +\n `found. Falling back to the network.`);\n }\n const integrityInManifest = params.integrity;\n const integrityInRequest = request.integrity;\n const noIntegrityConflict = !integrityInRequest || integrityInRequest === integrityInManifest;\n // Do not add integrity if the original request is no-cors\n // See https://github.com/GoogleChrome/workbox/issues/3096\n response = await handler.fetch(new Request(request, {\n integrity: request.mode !== 'no-cors'\n ? integrityInRequest || integrityInManifest\n : undefined,\n }));\n // It's only \"safe\" to repair the cache if we're using SRI to guarantee\n // that the response matches the precache manifest's expectations,\n // and there's either a) no integrity property in the incoming request\n // or b) there is an integrity, and it matches the precache manifest.\n // See https://github.com/GoogleChrome/workbox/issues/2858\n // Also if the original request users no-cors we don't use integrity.\n // See https://github.com/GoogleChrome/workbox/issues/3096\n if (integrityInManifest &&\n noIntegrityConflict &&\n request.mode !== 'no-cors') {\n this._useDefaultCacheabilityPluginIfNeeded();\n const wasCached = await handler.cachePut(request, response.clone());\n if (process.env.NODE_ENV !== 'production') {\n if (wasCached) {\n logger.log(`A response for ${getFriendlyURL(request.url)} ` +\n `was used to \"repair\" the precache.`);\n }\n }\n }\n }\n else {\n // This shouldn't normally happen, but there are edge cases:\n // https://github.com/GoogleChrome/workbox/issues/1441\n throw new WorkboxError('missing-precache-entry', {\n cacheName: this.cacheName,\n url: request.url,\n });\n }\n if (process.env.NODE_ENV !== 'production') {\n const cacheKey = params.cacheKey || (await handler.getCacheKey(request, 'read'));\n // Workbox is going to handle the route.\n // print the routing details to the console.\n logger.groupCollapsed(`Precaching is responding to: ` + getFriendlyURL(request.url));\n logger.log(`Serving the precached url: ${getFriendlyURL(cacheKey instanceof Request ? cacheKey.url : cacheKey)}`);\n logger.groupCollapsed(`View request details here.`);\n logger.log(request);\n logger.groupEnd();\n logger.groupCollapsed(`View response details here.`);\n logger.log(response);\n logger.groupEnd();\n logger.groupEnd();\n }\n return response;\n }\n async _handleInstall(request, handler) {\n this._useDefaultCacheabilityPluginIfNeeded();\n const response = await handler.fetch(request);\n // Make sure we defer cachePut() until after we know the response\n // should be cached; see https://github.com/GoogleChrome/workbox/issues/2737\n const wasCached = await handler.cachePut(request, response.clone());\n if (!wasCached) {\n // Throwing here will lead to the `install` handler failing, which\n // we want to do if *any* of the responses aren't safe to cache.\n throw new WorkboxError('bad-precaching-response', {\n url: request.url,\n status: response.status,\n });\n }\n return response;\n }\n /**\n * This method is complex, as there a number of things to account for:\n *\n * The `plugins` array can be set at construction, and/or it might be added to\n * to at any time before the strategy is used.\n *\n * At the time the strategy is used (i.e. during an `install` event), there\n * needs to be at least one plugin that implements `cacheWillUpdate` in the\n * array, other than `copyRedirectedCacheableResponsesPlugin`.\n *\n * - If this method is called and there are no suitable `cacheWillUpdate`\n * plugins, we need to add `defaultPrecacheCacheabilityPlugin`.\n *\n * - If this method is called and there is exactly one `cacheWillUpdate`, then\n * we don't have to do anything (this might be a previously added\n * `defaultPrecacheCacheabilityPlugin`, or it might be a custom plugin).\n *\n * - If this method is called and there is more than one `cacheWillUpdate`,\n * then we need to check if one is `defaultPrecacheCacheabilityPlugin`. If so,\n * we need to remove it. (This situation is unlikely, but it could happen if\n * the strategy is used multiple times, the first without a `cacheWillUpdate`,\n * and then later on after manually adding a custom `cacheWillUpdate`.)\n *\n * See https://github.com/GoogleChrome/workbox/issues/2737 for more context.\n *\n * @private\n */\n _useDefaultCacheabilityPluginIfNeeded() {\n let defaultPluginIndex = null;\n let cacheWillUpdatePluginCount = 0;\n for (const [index, plugin] of this.plugins.entries()) {\n // Ignore the copy redirected plugin when determining what to do.\n if (plugin === PrecacheStrategy.copyRedirectedCacheableResponsesPlugin) {\n continue;\n }\n // Save the default plugin's index, in case it needs to be removed.\n if (plugin === PrecacheStrategy.defaultPrecacheCacheabilityPlugin) {\n defaultPluginIndex = index;\n }\n if (plugin.cacheWillUpdate) {\n cacheWillUpdatePluginCount++;\n }\n }\n if (cacheWillUpdatePluginCount === 0) {\n this.plugins.push(PrecacheStrategy.defaultPrecacheCacheabilityPlugin);\n }\n else if (cacheWillUpdatePluginCount > 1 && defaultPluginIndex !== null) {\n // Only remove the default plugin; multiple custom plugins are allowed.\n this.plugins.splice(defaultPluginIndex, 1);\n }\n // Nothing needs to be done if cacheWillUpdatePluginCount is 1\n }\n}\nPrecacheStrategy.defaultPrecacheCacheabilityPlugin = {\n async cacheWillUpdate({ response }) {\n if (!response || response.status >= 400) {\n return null;\n }\n return response;\n },\n};\nPrecacheStrategy.copyRedirectedCacheableResponsesPlugin = {\n async cacheWillUpdate({ response }) {\n return response.redirected ? await copyResponse(response) : response;\n },\n};\nexport { PrecacheStrategy };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { cacheNames } from 'workbox-core/_private/cacheNames.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { waitUntil } from 'workbox-core/_private/waitUntil.js';\nimport { createCacheKey } from './utils/createCacheKey.js';\nimport { PrecacheInstallReportPlugin } from './utils/PrecacheInstallReportPlugin.js';\nimport { PrecacheCacheKeyPlugin } from './utils/PrecacheCacheKeyPlugin.js';\nimport { printCleanupDetails } from './utils/printCleanupDetails.js';\nimport { printInstallDetails } from './utils/printInstallDetails.js';\nimport { PrecacheStrategy } from './PrecacheStrategy.js';\nimport './_version.js';\n/**\n * Performs efficient precaching of assets.\n *\n * @memberof workbox-precaching\n */\nclass PrecacheController {\n /**\n * Create a new PrecacheController.\n *\n * @param {Object} [options]\n * @param {string} [options.cacheName] The cache to use for precaching.\n * @param {string} [options.plugins] Plugins to use when precaching as well\n * as responding to fetch events for precached assets.\n * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to\n * get the response from the network if there's a precache miss.\n */\n constructor({ cacheName, plugins = [], fallbackToNetwork = true, } = {}) {\n this._urlsToCacheKeys = new Map();\n this._urlsToCacheModes = new Map();\n this._cacheKeysToIntegrities = new Map();\n this._strategy = new PrecacheStrategy({\n cacheName: cacheNames.getPrecacheName(cacheName),\n plugins: [\n ...plugins,\n new PrecacheCacheKeyPlugin({ precacheController: this }),\n ],\n fallbackToNetwork,\n });\n // Bind the install and activate methods to the instance.\n this.install = this.install.bind(this);\n this.activate = this.activate.bind(this);\n }\n /**\n * @type {workbox-precaching.PrecacheStrategy} The strategy created by this controller and\n * used to cache assets and respond to fetch events.\n */\n get strategy() {\n return this._strategy;\n }\n /**\n * Adds items to the precache list, removing any duplicates and\n * stores the files in the\n * {@link workbox-core.cacheNames|\"precache cache\"} when the service\n * worker installs.\n *\n * This method can be called multiple times.\n *\n * @param {Array} [entries=[]] Array of entries to precache.\n */\n precache(entries) {\n this.addToCacheList(entries);\n if (!this._installAndActiveListenersAdded) {\n self.addEventListener('install', this.install);\n self.addEventListener('activate', this.activate);\n this._installAndActiveListenersAdded = true;\n }\n }\n /**\n * This method will add items to the precache list, removing duplicates\n * and ensuring the information is valid.\n *\n * @param {Array} entries\n * Array of entries to precache.\n */\n addToCacheList(entries) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isArray(entries, {\n moduleName: 'workbox-precaching',\n className: 'PrecacheController',\n funcName: 'addToCacheList',\n paramName: 'entries',\n });\n }\n const urlsToWarnAbout = [];\n for (const entry of entries) {\n // See https://github.com/GoogleChrome/workbox/issues/2259\n if (typeof entry === 'string') {\n urlsToWarnAbout.push(entry);\n }\n else if (entry && entry.revision === undefined) {\n urlsToWarnAbout.push(entry.url);\n }\n const { cacheKey, url } = createCacheKey(entry);\n const cacheMode = typeof entry !== 'string' && entry.revision ? 'reload' : 'default';\n if (this._urlsToCacheKeys.has(url) &&\n this._urlsToCacheKeys.get(url) !== cacheKey) {\n throw new WorkboxError('add-to-cache-list-conflicting-entries', {\n firstEntry: this._urlsToCacheKeys.get(url),\n secondEntry: cacheKey,\n });\n }\n if (typeof entry !== 'string' && entry.integrity) {\n if (this._cacheKeysToIntegrities.has(cacheKey) &&\n this._cacheKeysToIntegrities.get(cacheKey) !== entry.integrity) {\n throw new WorkboxError('add-to-cache-list-conflicting-integrities', {\n url,\n });\n }\n this._cacheKeysToIntegrities.set(cacheKey, entry.integrity);\n }\n this._urlsToCacheKeys.set(url, cacheKey);\n this._urlsToCacheModes.set(url, cacheMode);\n if (urlsToWarnAbout.length > 0) {\n const warningMessage = `Workbox is precaching URLs without revision ` +\n `info: ${urlsToWarnAbout.join(', ')}\\nThis is generally NOT safe. ` +\n `Learn more at https://bit.ly/wb-precache`;\n if (process.env.NODE_ENV === 'production') {\n // Use console directly to display this warning without bloating\n // bundle sizes by pulling in all of the logger codebase in prod.\n console.warn(warningMessage);\n }\n else {\n logger.warn(warningMessage);\n }\n }\n }\n }\n /**\n * Precaches new and updated assets. Call this method from the service worker\n * install event.\n *\n * Note: this method calls `event.waitUntil()` for you, so you do not need\n * to call it yourself in your event handlers.\n *\n * @param {ExtendableEvent} event\n * @return {Promise}\n */\n install(event) {\n // waitUntil returns Promise\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return waitUntil(event, async () => {\n const installReportPlugin = new PrecacheInstallReportPlugin();\n this.strategy.plugins.push(installReportPlugin);\n // Cache entries one at a time.\n // See https://github.com/GoogleChrome/workbox/issues/2528\n for (const [url, cacheKey] of this._urlsToCacheKeys) {\n const integrity = this._cacheKeysToIntegrities.get(cacheKey);\n const cacheMode = this._urlsToCacheModes.get(url);\n const request = new Request(url, {\n integrity,\n cache: cacheMode,\n credentials: 'same-origin',\n });\n await Promise.all(this.strategy.handleAll({\n params: { cacheKey },\n request,\n event,\n }));\n }\n const { updatedURLs, notUpdatedURLs } = installReportPlugin;\n if (process.env.NODE_ENV !== 'production') {\n printInstallDetails(updatedURLs, notUpdatedURLs);\n }\n return { updatedURLs, notUpdatedURLs };\n });\n }\n /**\n * Deletes assets that are no longer present in the current precache manifest.\n * Call this method from the service worker activate event.\n *\n * Note: this method calls `event.waitUntil()` for you, so you do not need\n * to call it yourself in your event handlers.\n *\n * @param {ExtendableEvent} event\n * @return {Promise}\n */\n activate(event) {\n // waitUntil returns Promise\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return waitUntil(event, async () => {\n const cache = await self.caches.open(this.strategy.cacheName);\n const currentlyCachedRequests = await cache.keys();\n const expectedCacheKeys = new Set(this._urlsToCacheKeys.values());\n const deletedURLs = [];\n for (const request of currentlyCachedRequests) {\n if (!expectedCacheKeys.has(request.url)) {\n await cache.delete(request);\n deletedURLs.push(request.url);\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n printCleanupDetails(deletedURLs);\n }\n return { deletedURLs };\n });\n }\n /**\n * Returns a mapping of a precached URL to the corresponding cache key, taking\n * into account the revision information for the URL.\n *\n * @return {Map} A URL to cache key mapping.\n */\n getURLsToCacheKeys() {\n return this._urlsToCacheKeys;\n }\n /**\n * Returns a list of all the URLs that have been precached by the current\n * service worker.\n *\n * @return {Array} The precached URLs.\n */\n getCachedURLs() {\n return [...this._urlsToCacheKeys.keys()];\n }\n /**\n * Returns the cache key used for storing a given URL. If that URL is\n * unversioned, like `/index.html', then the cache key will be the original\n * URL with a search parameter appended to it.\n *\n * @param {string} url A URL whose cache key you want to look up.\n * @return {string} The versioned URL that corresponds to a cache key\n * for the original URL, or undefined if that URL isn't precached.\n */\n getCacheKeyForURL(url) {\n const urlObject = new URL(url, location.href);\n return this._urlsToCacheKeys.get(urlObject.href);\n }\n /**\n * @param {string} url A cache key whose SRI you want to look up.\n * @return {string} The subresource integrity associated with the cache key,\n * or undefined if it's not set.\n */\n getIntegrityForCacheKey(cacheKey) {\n return this._cacheKeysToIntegrities.get(cacheKey);\n }\n /**\n * This acts as a drop-in replacement for\n * [`cache.match()`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/match)\n * with the following differences:\n *\n * - It knows what the name of the precache is, and only checks in that cache.\n * - It allows you to pass in an \"original\" URL without versioning parameters,\n * and it will automatically look up the correct cache key for the currently\n * active revision of that URL.\n *\n * E.g., `matchPrecache('index.html')` will find the correct precached\n * response for the currently active service worker, even if the actual cache\n * key is `'/index.html?__WB_REVISION__=1234abcd'`.\n *\n * @param {string|Request} request The key (without revisioning parameters)\n * to look up in the precache.\n * @return {Promise}\n */\n async matchPrecache(request) {\n const url = request instanceof Request ? request.url : request;\n const cacheKey = this.getCacheKeyForURL(url);\n if (cacheKey) {\n const cache = await self.caches.open(this.strategy.cacheName);\n return cache.match(cacheKey);\n }\n return undefined;\n }\n /**\n * Returns a function that looks up `url` in the precache (taking into\n * account revision information), and returns the corresponding `Response`.\n *\n * @param {string} url The precached URL which will be used to lookup the\n * `Response`.\n * @return {workbox-routing~handlerCallback}\n */\n createHandlerBoundToURL(url) {\n const cacheKey = this.getCacheKeyForURL(url);\n if (!cacheKey) {\n throw new WorkboxError('non-precached-url', { url });\n }\n return (options) => {\n options.request = new Request(url);\n options.params = Object.assign({ cacheKey }, options.params);\n return this.strategy.handle(options);\n };\n }\n}\nexport { PrecacheController };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { PrecacheController } from '../PrecacheController.js';\nimport '../_version.js';\nlet precacheController;\n/**\n * @return {PrecacheController}\n * @private\n */\nexport const getOrCreatePrecacheController = () => {\n if (!precacheController) {\n precacheController = new PrecacheController();\n }\n return precacheController;\n};\n","/*\n Copyright 2020 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 { logger } from 'workbox-core/_private/logger.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { Route } from 'workbox-routing/Route.js';\nimport { generateURLVariations } from './utils/generateURLVariations.js';\nimport './_version.js';\n/**\n * A subclass of {@link workbox-routing.Route} that takes a\n * {@link workbox-precaching.PrecacheController}\n * instance and uses it to match incoming requests and handle fetching\n * responses from the precache.\n *\n * @memberof workbox-precaching\n * @extends workbox-routing.Route\n */\nclass PrecacheRoute extends Route {\n /**\n * @param {PrecacheController} precacheController A `PrecacheController`\n * instance used to both match requests and respond to fetch events.\n * @param {Object} [options] Options to control how requests are matched\n * against the list of precached URLs.\n * @param {string} [options.directoryIndex=index.html] The `directoryIndex` will\n * check cache entries for a URLs ending with '/' to see if there is a hit when\n * appending the `directoryIndex` value.\n * @param {Array} [options.ignoreURLParametersMatching=[/^utm_/, /^fbclid$/]] An\n * array of regex's to remove search params when looking for a cache match.\n * @param {boolean} [options.cleanURLs=true] The `cleanURLs` option will\n * check the cache for the URL with a `.html` added to the end of the end.\n * @param {workbox-precaching~urlManipulation} [options.urlManipulation]\n * This is a function that should take a URL and return an array of\n * alternative URLs that should be checked for precache matches.\n */\n constructor(precacheController, options) {\n const match = ({ request, }) => {\n const urlsToCacheKeys = precacheController.getURLsToCacheKeys();\n for (const possibleURL of generateURLVariations(request.url, options)) {\n const cacheKey = urlsToCacheKeys.get(possibleURL);\n if (cacheKey) {\n const integrity = precacheController.getIntegrityForCacheKey(cacheKey);\n return { cacheKey, integrity };\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`Precaching did not find a match for ` + getFriendlyURL(request.url));\n }\n return;\n };\n super(match, precacheController.strategy);\n }\n}\nexport { PrecacheRoute };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { removeIgnoredSearchParams } from './removeIgnoredSearchParams.js';\nimport '../_version.js';\n/**\n * Generator function that yields possible variations on the original URL to\n * check, one at a time.\n *\n * @param {string} url\n * @param {Object} options\n *\n * @private\n * @memberof workbox-precaching\n */\nexport function* generateURLVariations(url, { ignoreURLParametersMatching = [/^utm_/, /^fbclid$/], directoryIndex = 'index.html', cleanURLs = true, urlManipulation, } = {}) {\n const urlObject = new URL(url, location.href);\n urlObject.hash = '';\n yield urlObject.href;\n const urlWithoutIgnoredParams = removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching);\n yield urlWithoutIgnoredParams.href;\n if (directoryIndex && urlWithoutIgnoredParams.pathname.endsWith('/')) {\n const directoryURL = new URL(urlWithoutIgnoredParams.href);\n directoryURL.pathname += directoryIndex;\n yield directoryURL.href;\n }\n if (cleanURLs) {\n const cleanURL = new URL(urlWithoutIgnoredParams.href);\n cleanURL.pathname += '.html';\n yield cleanURL.href;\n }\n if (urlManipulation) {\n const additionalURLs = urlManipulation({ url: urlObject });\n for (const urlToAttempt of additionalURLs) {\n yield urlToAttempt.href;\n }\n }\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 '../_version.js';\n/**\n * Removes any URL search parameters that should be ignored.\n *\n * @param {URL} urlObject The original URL.\n * @param {Array} ignoreURLParametersMatching RegExps to test against\n * each search parameter name. Matches mean that the search parameter should be\n * ignored.\n * @return {URL} The URL with any ignored search parameters removed.\n *\n * @private\n * @memberof workbox-precaching\n */\nexport function removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching = []) {\n // Convert the iterable into an array at the start of the loop to make sure\n // deletion doesn't mess up iteration.\n for (const paramName of [...urlObject.searchParams.keys()]) {\n if (ignoreURLParametersMatching.some((regExp) => regExp.test(paramName))) {\n urlObject.searchParams.delete(paramName);\n }\n }\n return urlObject;\n}\n","/*\n Copyright 2019 Google LLC\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 { registerRoute } from 'workbox-routing/registerRoute.js';\nimport { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';\nimport { PrecacheRoute } from './PrecacheRoute.js';\nimport './_version.js';\n/**\n * Add a `fetch` listener to the service worker that will\n * respond to\n * [network requests]{@link https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#Custom_responses_to_requests}\n * with precached assets.\n *\n * Requests for assets that aren't precached, the `FetchEvent` will not be\n * responded to, allowing the event to fall through to other `fetch` event\n * listeners.\n *\n * @param {Object} [options] See the {@link workbox-precaching.PrecacheRoute}\n * options.\n *\n * @memberof workbox-precaching\n */\nfunction addRoute(options) {\n const precacheController = getOrCreatePrecacheController();\n const precacheRoute = new PrecacheRoute(precacheController, options);\n registerRoute(precacheRoute);\n}\nexport { addRoute };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';\nimport './_version.js';\n/**\n * Adds items to the precache list, removing any duplicates and\n * stores the files in the\n * {@link workbox-core.cacheNames|\"precache cache\"} when the service\n * worker installs.\n *\n * This method can be called multiple times.\n *\n * Please note: This method **will not** serve any of the cached files for you.\n * It only precaches files. To respond to a network request you call\n * {@link workbox-precaching.addRoute}.\n *\n * If you have a single array of files to precache, you can just call\n * {@link workbox-precaching.precacheAndRoute}.\n *\n * @param {Array} [entries=[]] Array of entries to precache.\n *\n * @memberof workbox-precaching\n */\nfunction precache(entries) {\n const precacheController = getOrCreatePrecacheController();\n precacheController.precache(entries);\n}\nexport { precache };\n","/*\n Copyright 2020 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 { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';\nimport './_version.js';\n/**\n * `PrecacheFallbackPlugin` allows you to specify an \"offline fallback\"\n * response to be used when a given strategy is unable to generate a response.\n *\n * It does this by intercepting the `handlerDidError` plugin callback\n * and returning a precached response, taking the expected revision parameter\n * into account automatically.\n *\n * Unless you explicitly pass in a `PrecacheController` instance to the\n * constructor, the default instance will be used. Generally speaking, most\n * developers will end up using the default.\n *\n * @memberof workbox-precaching\n */\nclass PrecacheFallbackPlugin {\n /**\n * Constructs a new PrecacheFallbackPlugin with the associated fallbackURL.\n *\n * @param {Object} config\n * @param {string} config.fallbackURL A precached URL to use as the fallback\n * if the associated strategy can't generate a response.\n * @param {PrecacheController} [config.precacheController] An optional\n * PrecacheController instance. If not provided, the default\n * PrecacheController will be used.\n */\n constructor({ fallbackURL, precacheController, }) {\n /**\n * @return {Promise} The precache response for the fallback URL.\n *\n * @private\n */\n this.handlerDidError = () => this._precacheController.matchPrecache(this._fallbackURL);\n this._fallbackURL = fallbackURL;\n this._precacheController =\n precacheController || getOrCreatePrecacheController();\n }\n}\nexport { PrecacheFallbackPlugin };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';\nimport './_version.js';\n/**\n * Adds plugins to the precaching strategy.\n *\n * @param {Array} plugins\n *\n * @memberof workbox-precaching\n */\nfunction addPlugins(plugins) {\n const precacheController = getOrCreatePrecacheController();\n precacheController.strategy.plugins.push(...plugins);\n}\nexport { addPlugins };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { cacheNames } from 'workbox-core/_private/cacheNames.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { deleteOutdatedCaches } from './utils/deleteOutdatedCaches.js';\nimport './_version.js';\n/**\n * Adds an `activate` event listener which will clean up incompatible\n * precaches that were created by older versions of Workbox.\n *\n * @memberof workbox-precaching\n */\nfunction cleanupOutdatedCaches() {\n // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705\n self.addEventListener('activate', ((event) => {\n const cacheName = cacheNames.getPrecacheName();\n event.waitUntil(deleteOutdatedCaches(cacheName).then((cachesDeleted) => {\n if (process.env.NODE_ENV !== 'production') {\n if (cachesDeleted.length > 0) {\n logger.log(`The following out-of-date precaches were cleaned up ` +\n `automatically:`, cachesDeleted);\n }\n }\n }));\n }));\n}\nexport { cleanupOutdatedCaches };\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';\nconst SUBSTRING_TO_FIND = '-precache-';\n/**\n * Cleans up incompatible precaches that were created by older versions of\n * Workbox, by a service worker registered under the current scope.\n *\n * This is meant to be called as part of the `activate` event.\n *\n * This should be safe to use as long as you don't include `substringToFind`\n * (defaulting to `-precache-`) in your non-precache cache names.\n *\n * @param {string} currentPrecacheName The cache name currently in use for\n * precaching. This cache won't be deleted.\n * @param {string} [substringToFind='-precache-'] Cache names which include this\n * substring will be deleted (excluding `currentPrecacheName`).\n * @return {Array} A list of all the cache names that were deleted.\n *\n * @private\n * @memberof workbox-precaching\n */\nconst deleteOutdatedCaches = async (currentPrecacheName, substringToFind = SUBSTRING_TO_FIND) => {\n const cacheNames = await self.caches.keys();\n const cacheNamesToDelete = cacheNames.filter((cacheName) => {\n return (cacheName.includes(substringToFind) &&\n cacheName.includes(self.registration.scope) &&\n cacheName !== currentPrecacheName);\n });\n await Promise.all(cacheNamesToDelete.map((cacheName) => self.caches.delete(cacheName)));\n return cacheNamesToDelete;\n};\nexport { deleteOutdatedCaches };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';\nimport './_version.js';\n/**\n * Helper function that calls\n * {@link PrecacheController#createHandlerBoundToURL} on the default\n * {@link PrecacheController} instance.\n *\n * If you are creating your own {@link PrecacheController}, then call the\n * {@link PrecacheController#createHandlerBoundToURL} on that instance,\n * instead of using this function.\n *\n * @param {string} url The precached URL which will be used to lookup the\n * `Response`.\n * @param {boolean} [fallbackToNetwork=true] Whether to attempt to get the\n * response from the network if there's a precache miss.\n * @return {workbox-routing~handlerCallback}\n *\n * @memberof workbox-precaching\n */\nfunction createHandlerBoundToURL(url) {\n const precacheController = getOrCreatePrecacheController();\n return precacheController.createHandlerBoundToURL(url);\n}\nexport { createHandlerBoundToURL };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';\nimport './_version.js';\n/**\n * Takes in a URL, and returns the corresponding URL that could be used to\n * lookup the entry in the precache.\n *\n * If a relative URL is provided, the location of the service worker file will\n * be used as the base.\n *\n * For precached entries without revision information, the cache key will be the\n * same as the original URL.\n *\n * For precached entries with revision information, the cache key will be the\n * original URL with the addition of a query parameter used for keeping track of\n * the revision info.\n *\n * @param {string} url The URL whose cache key to look up.\n * @return {string} The cache key that corresponds to that URL.\n *\n * @memberof workbox-precaching\n */\nfunction getCacheKeyForURL(url) {\n const precacheController = getOrCreatePrecacheController();\n return precacheController.getCacheKeyForURL(url);\n}\nexport { getCacheKeyForURL };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';\nimport './_version.js';\n/**\n * Helper function that calls\n * {@link PrecacheController#matchPrecache} on the default\n * {@link PrecacheController} instance.\n *\n * If you are creating your own {@link PrecacheController}, then call\n * {@link PrecacheController#matchPrecache} on that instance,\n * instead of using this function.\n *\n * @param {string|Request} request The key (without revisioning parameters)\n * to look up in the precache.\n * @return {Promise}\n *\n * @memberof workbox-precaching\n */\nfunction matchPrecache(request) {\n const precacheController = getOrCreatePrecacheController();\n return precacheController.matchPrecache(request);\n}\nexport { matchPrecache };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { addRoute } from './addRoute.js';\nimport { precache } from './precache.js';\nimport './_version.js';\n/**\n * This method will add entries to the precache list and add a route to\n * respond to fetch events.\n *\n * This is a convenience method that will call\n * {@link workbox-precaching.precache} and\n * {@link workbox-precaching.addRoute} in a single call.\n *\n * @param {Array} entries Array of entries to precache.\n * @param {Object} [options] See the\n * {@link workbox-precaching.PrecacheRoute} options.\n *\n * @memberof workbox-precaching\n */\nfunction precacheAndRoute(entries, options) {\n precache(entries);\n addRoute(options);\n}\nexport { precacheAndRoute };\n"],"names":["self","_","e","createCacheKey","entry","WorkboxError","urlObject","URL","location","href","cacheKey","url","revision","cacheKeyURL","originalURL","searchParams","set","PrecacheInstallReportPlugin","constructor","this","updatedURLs","notUpdatedURLs","handlerWillStart","async","request","state","originalRequest","cachedResponseWillBeUsed","event","cachedResponse","type","Request","push","PrecacheCacheKeyPlugin","precacheController","cacheKeyWillBeUsed","params","_precacheController","getCacheKeyForURL","headers","PrecacheStrategy","Strategy","options","cacheName","cacheNames","getPrecacheName","super","_fallbackToNetwork","fallbackToNetwork","plugins","copyRedirectedCacheableResponsesPlugin","handler","response","cacheMatch","_handleInstall","_handleFetch","integrityInManifest","integrity","integrityInRequest","noIntegrityConflict","fetch","mode","undefined","_useDefaultCacheabilityPluginIfNeeded","cachePut","clone","status","defaultPluginIndex","cacheWillUpdatePluginCount","index","plugin","entries","defaultPrecacheCacheabilityPlugin","cacheWillUpdate","splice","redirected","copyResponse","PrecacheController","_urlsToCacheKeys","Map","_urlsToCacheModes","_cacheKeysToIntegrities","_strategy","install","bind","activate","strategy","precache","addToCacheList","_installAndActiveListenersAdded","addEventListener","urlsToWarnAbout","cacheMode","has","get","firstEntry","secondEntry","length","warningMessage","join","console","warn","waitUntil","installReportPlugin","cache","credentials","Promise","all","handleAll","caches","open","currentlyCachedRequests","keys","expectedCacheKeys","Set","values","deletedURLs","delete","getURLsToCacheKeys","getCachedURLs","getIntegrityForCacheKey","match","createHandlerBoundToURL","Object","assign","handle","getOrCreatePrecacheController","PrecacheRoute","Route","urlsToCacheKeys","possibleURL","ignoreURLParametersMatching","directoryIndex","cleanURLs","urlManipulation","hash","urlWithoutIgnoredParams","paramName","some","regExp","test","removeIgnoredSearchParams","pathname","endsWith","directoryURL","cleanURL","additionalURLs","urlToAttempt","generateURLVariations","addRoute","precacheRoute","registerRoute","fallbackURL","handlerDidError","matchPrecache","_fallbackURL","currentPrecacheName","substringToFind","cacheNamesToDelete","filter","includes","registration","scope","map","deleteOutdatedCaches","then","cachesDeleted"],"mappings":"6FAEA,IACIA,KAAK,6BAA+BC,GACxC,CACA,MAAOC,GAAK,CCeL,SAASC,EAAeC,GAC3B,IAAKA,EACD,MAAM,IAAIC,EAAAA,aAAa,oCAAqC,CAAED,UAIlE,GAAqB,iBAAVA,EAAoB,CAC3B,MAAME,EAAY,IAAIC,IAAIH,EAAOI,SAASC,MAC1C,MAAO,CACHC,SAAUJ,EAAUG,KACpBE,IAAKL,EAAUG,KAEvB,CACA,MAAMG,SAAEA,EAAQD,IAAEA,GAAQP,EAC1B,IAAKO,EACD,MAAM,IAAIN,EAAAA,aAAa,oCAAqC,CAAED,UAIlE,IAAKQ,EAAU,CACX,MAAMN,EAAY,IAAIC,IAAII,EAAKH,SAASC,MACxC,MAAO,CACHC,SAAUJ,EAAUG,KACpBE,IAAKL,EAAUG,KAEvB,CAGA,MAAMI,EAAc,IAAIN,IAAII,EAAKH,SAASC,MACpCK,EAAc,IAAIP,IAAII,EAAKH,SAASC,MAE1C,OADAI,EAAYE,aAAaC,IAxCC,kBAwC0BJ,GAC7C,CACHF,SAAUG,EAAYJ,KACtBE,IAAKG,EAAYL,KAEzB,CCzCA,MAAMQ,EACFC,cACIC,KAAKC,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QC,IAAImD,EAAmBK,KAAKxH,GAAc3C,KAAK6G,OAAOQ,OAAO1E,MACpEmH,CAAkB,EDdLM,CAAqBzH,GAAW0H,MAAMC,QAOnD,GAEX,4BEJA,SAAiC3J,GAE7B,OAD2BmH,IACDJ,wBAAwB/G,EACtD,sBCDA,SAA2BA,GAEvB,OAD2BmH,IACDxF,kBAAkB3B,EAChD,kBCPA,SAAuBa,GAEnB,OAD2BsG,IACD4B,cAAclI,EAC5C,kCCHA,SAA0B+C,EAAS7B,GAC/B6C,EAAShB,GACT8E,EAAS3G,EACb"} \ No newline at end of file diff --git a/node_modules/workbox-precaching/cleanupOutdatedCaches.d.ts b/node_modules/workbox-precaching/cleanupOutdatedCaches.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3686945896bdbd52fca09a6fc259741f3c75c32a --- /dev/null +++ b/node_modules/workbox-precaching/cleanupOutdatedCaches.d.ts @@ -0,0 +1,9 @@ +import './_version.js'; +/** + * Adds an `activate` event listener which will clean up incompatible + * precaches that were created by older versions of Workbox. + * + * @memberof workbox-precaching + */ +declare function cleanupOutdatedCaches(): void; +export { cleanupOutdatedCaches }; diff --git a/node_modules/workbox-precaching/cleanupOutdatedCaches.js b/node_modules/workbox-precaching/cleanupOutdatedCaches.js new file mode 100644 index 0000000000000000000000000000000000000000..36fc50158d152cca2ae0779084748a9d14fb328c --- /dev/null +++ b/node_modules/workbox-precaching/cleanupOutdatedCaches.js @@ -0,0 +1,32 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { cacheNames } from 'workbox-core/_private/cacheNames.js'; +import { logger } from 'workbox-core/_private/logger.js'; +import { deleteOutdatedCaches } from './utils/deleteOutdatedCaches.js'; +import './_version.js'; +/** + * Adds an `activate` event listener which will clean up incompatible + * precaches that were created by older versions of Workbox. + * + * @memberof workbox-precaching + */ +function cleanupOutdatedCaches() { + // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705 + self.addEventListener('activate', ((event) => { + const cacheName = cacheNames.getPrecacheName(); + event.waitUntil(deleteOutdatedCaches(cacheName).then((cachesDeleted) => { + if (process.env.NODE_ENV !== 'production') { + if (cachesDeleted.length > 0) { + logger.log(`The following out-of-date precaches were cleaned up ` + + `automatically:`, cachesDeleted); + } + } + })); + })); +} +export { cleanupOutdatedCaches }; diff --git a/node_modules/workbox-precaching/cleanupOutdatedCaches.mjs b/node_modules/workbox-precaching/cleanupOutdatedCaches.mjs new file mode 100644 index 0000000000000000000000000000000000000000..51228ab8ee7d53f3a58257607362717ac42ae59c --- /dev/null +++ b/node_modules/workbox-precaching/cleanupOutdatedCaches.mjs @@ -0,0 +1 @@ +export * from './cleanupOutdatedCaches.js'; \ No newline at end of file diff --git a/node_modules/workbox-precaching/createHandlerBoundToURL.d.ts b/node_modules/workbox-precaching/createHandlerBoundToURL.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..58a54c8acc5fe5d6fcb57ae8012cc3dd9e23ceaf --- /dev/null +++ b/node_modules/workbox-precaching/createHandlerBoundToURL.d.ts @@ -0,0 +1,21 @@ +import { RouteHandlerCallback } from 'workbox-core/types.js'; +import './_version.js'; +/** + * Helper function that calls + * {@link PrecacheController#createHandlerBoundToURL} on the default + * {@link PrecacheController} instance. + * + * If you are creating your own {@link PrecacheController}, then call the + * {@link PrecacheController#createHandlerBoundToURL} on that instance, + * instead of using this function. + * + * @param {string} url The precached URL which will be used to lookup the + * `Response`. + * @param {boolean} [fallbackToNetwork=true] Whether to attempt to get the + * response from the network if there's a precache miss. + * @return {workbox-routing~handlerCallback} + * + * @memberof workbox-precaching + */ +declare function createHandlerBoundToURL(url: string): RouteHandlerCallback; +export { createHandlerBoundToURL }; diff --git a/node_modules/workbox-precaching/createHandlerBoundToURL.js b/node_modules/workbox-precaching/createHandlerBoundToURL.js new file mode 100644 index 0000000000000000000000000000000000000000..113d503fe0dc1e3861ce92f9268ae8cecb72a0ec --- /dev/null +++ b/node_modules/workbox-precaching/createHandlerBoundToURL.js @@ -0,0 +1,31 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js'; +import './_version.js'; +/** + * Helper function that calls + * {@link PrecacheController#createHandlerBoundToURL} on the default + * {@link PrecacheController} instance. + * + * If you are creating your own {@link PrecacheController}, then call the + * {@link PrecacheController#createHandlerBoundToURL} on that instance, + * instead of using this function. + * + * @param {string} url The precached URL which will be used to lookup the + * `Response`. + * @param {boolean} [fallbackToNetwork=true] Whether to attempt to get the + * response from the network if there's a precache miss. + * @return {workbox-routing~handlerCallback} + * + * @memberof workbox-precaching + */ +function createHandlerBoundToURL(url) { + const precacheController = getOrCreatePrecacheController(); + return precacheController.createHandlerBoundToURL(url); +} +export { createHandlerBoundToURL }; diff --git a/node_modules/workbox-precaching/createHandlerBoundToURL.mjs b/node_modules/workbox-precaching/createHandlerBoundToURL.mjs new file mode 100644 index 0000000000000000000000000000000000000000..430fb8d59e4933a7c636726bb928063bc1a6f1eb --- /dev/null +++ b/node_modules/workbox-precaching/createHandlerBoundToURL.mjs @@ -0,0 +1 @@ +export * from './createHandlerBoundToURL.js'; \ No newline at end of file diff --git a/node_modules/workbox-precaching/getCacheKeyForURL.d.ts b/node_modules/workbox-precaching/getCacheKeyForURL.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e1131a709ecbdfb0ee2f7a0cce80f454f585e361 --- /dev/null +++ b/node_modules/workbox-precaching/getCacheKeyForURL.d.ts @@ -0,0 +1,22 @@ +import './_version.js'; +/** + * Takes in a URL, and returns the corresponding URL that could be used to + * lookup the entry in the precache. + * + * If a relative URL is provided, the location of the service worker file will + * be used as the base. + * + * For precached entries without revision information, the cache key will be the + * same as the original URL. + * + * For precached entries with revision information, the cache key will be the + * original URL with the addition of a query parameter used for keeping track of + * the revision info. + * + * @param {string} url The URL whose cache key to look up. + * @return {string} The cache key that corresponds to that URL. + * + * @memberof workbox-precaching + */ +declare function getCacheKeyForURL(url: string): string | undefined; +export { getCacheKeyForURL }; diff --git a/node_modules/workbox-precaching/getCacheKeyForURL.js b/node_modules/workbox-precaching/getCacheKeyForURL.js new file mode 100644 index 0000000000000000000000000000000000000000..d2012b3a2ece39d3e6d43052d626ccd53b5d78e7 --- /dev/null +++ b/node_modules/workbox-precaching/getCacheKeyForURL.js @@ -0,0 +1,33 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js'; +import './_version.js'; +/** + * Takes in a URL, and returns the corresponding URL that could be used to + * lookup the entry in the precache. + * + * If a relative URL is provided, the location of the service worker file will + * be used as the base. + * + * For precached entries without revision information, the cache key will be the + * same as the original URL. + * + * For precached entries with revision information, the cache key will be the + * original URL with the addition of a query parameter used for keeping track of + * the revision info. + * + * @param {string} url The URL whose cache key to look up. + * @return {string} The cache key that corresponds to that URL. + * + * @memberof workbox-precaching + */ +function getCacheKeyForURL(url) { + const precacheController = getOrCreatePrecacheController(); + return precacheController.getCacheKeyForURL(url); +} +export { getCacheKeyForURL }; diff --git a/node_modules/workbox-precaching/getCacheKeyForURL.mjs b/node_modules/workbox-precaching/getCacheKeyForURL.mjs new file mode 100644 index 0000000000000000000000000000000000000000..04413e30927761b5be55f080a991e5466ae5178e --- /dev/null +++ b/node_modules/workbox-precaching/getCacheKeyForURL.mjs @@ -0,0 +1 @@ +export * from './getCacheKeyForURL.js'; \ No newline at end of file diff --git a/node_modules/workbox-precaching/index.d.ts b/node_modules/workbox-precaching/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e5c18e786ca149e898371dc9ea06fcc140933112 --- /dev/null +++ b/node_modules/workbox-precaching/index.d.ts @@ -0,0 +1,27 @@ +import { addPlugins } from './addPlugins.js'; +import { addRoute } from './addRoute.js'; +import { cleanupOutdatedCaches } from './cleanupOutdatedCaches.js'; +import { createHandlerBoundToURL } from './createHandlerBoundToURL.js'; +import { getCacheKeyForURL } from './getCacheKeyForURL.js'; +import { matchPrecache } from './matchPrecache.js'; +import { precache } from './precache.js'; +import { precacheAndRoute } from './precacheAndRoute.js'; +import { PrecacheController } from './PrecacheController.js'; +import { PrecacheRoute } from './PrecacheRoute.js'; +import { PrecacheStrategy } from './PrecacheStrategy.js'; +import { PrecacheFallbackPlugin } from './PrecacheFallbackPlugin.js'; +import './_version.js'; +/** + * Most consumers of this module will want to use the + * {@link workbox-precaching.precacheAndRoute} + * method to add assets to the cache and respond to network requests with these + * cached assets. + * + * If you require more control over caching and routing, you can use the + * {@link workbox-precaching.PrecacheController} + * interface. + * + * @module workbox-precaching + */ +export { addPlugins, addRoute, cleanupOutdatedCaches, createHandlerBoundToURL, getCacheKeyForURL, matchPrecache, precache, precacheAndRoute, PrecacheController, PrecacheRoute, PrecacheStrategy, PrecacheFallbackPlugin, }; +export * from './_types.js'; diff --git a/node_modules/workbox-precaching/index.js b/node_modules/workbox-precaching/index.js new file mode 100644 index 0000000000000000000000000000000000000000..db098a6997929510892c323d37e5d88fcaee165c --- /dev/null +++ b/node_modules/workbox-precaching/index.js @@ -0,0 +1,34 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { addPlugins } from './addPlugins.js'; +import { addRoute } from './addRoute.js'; +import { cleanupOutdatedCaches } from './cleanupOutdatedCaches.js'; +import { createHandlerBoundToURL } from './createHandlerBoundToURL.js'; +import { getCacheKeyForURL } from './getCacheKeyForURL.js'; +import { matchPrecache } from './matchPrecache.js'; +import { precache } from './precache.js'; +import { precacheAndRoute } from './precacheAndRoute.js'; +import { PrecacheController } from './PrecacheController.js'; +import { PrecacheRoute } from './PrecacheRoute.js'; +import { PrecacheStrategy } from './PrecacheStrategy.js'; +import { PrecacheFallbackPlugin } from './PrecacheFallbackPlugin.js'; +import './_version.js'; +/** + * Most consumers of this module will want to use the + * {@link workbox-precaching.precacheAndRoute} + * method to add assets to the cache and respond to network requests with these + * cached assets. + * + * If you require more control over caching and routing, you can use the + * {@link workbox-precaching.PrecacheController} + * interface. + * + * @module workbox-precaching + */ +export { addPlugins, addRoute, cleanupOutdatedCaches, createHandlerBoundToURL, getCacheKeyForURL, matchPrecache, precache, precacheAndRoute, PrecacheController, PrecacheRoute, PrecacheStrategy, PrecacheFallbackPlugin, }; +export * from './_types.js'; diff --git a/node_modules/workbox-precaching/index.mjs b/node_modules/workbox-precaching/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..833b6a2f3226fec78490a3b7a622dc5146f94b53 --- /dev/null +++ b/node_modules/workbox-precaching/index.mjs @@ -0,0 +1 @@ +export * from './index.js'; \ No newline at end of file diff --git a/node_modules/workbox-precaching/matchPrecache.d.ts b/node_modules/workbox-precaching/matchPrecache.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b491d659302e53a16ebd174e90910f66aad18115 --- /dev/null +++ b/node_modules/workbox-precaching/matchPrecache.d.ts @@ -0,0 +1,18 @@ +import './_version.js'; +/** + * Helper function that calls + * {@link PrecacheController#matchPrecache} on the default + * {@link PrecacheController} instance. + * + * If you are creating your own {@link PrecacheController}, then call + * {@link PrecacheController#matchPrecache} on that instance, + * instead of using this function. + * + * @param {string|Request} request The key (without revisioning parameters) + * to look up in the precache. + * @return {Promise} + * + * @memberof workbox-precaching + */ +declare function matchPrecache(request: string | Request): Promise; +export { matchPrecache }; diff --git a/node_modules/workbox-precaching/matchPrecache.js b/node_modules/workbox-precaching/matchPrecache.js new file mode 100644 index 0000000000000000000000000000000000000000..c889b90b5e289eb01980942455ccc329dc003a06 --- /dev/null +++ b/node_modules/workbox-precaching/matchPrecache.js @@ -0,0 +1,29 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js'; +import './_version.js'; +/** + * Helper function that calls + * {@link PrecacheController#matchPrecache} on the default + * {@link PrecacheController} instance. + * + * If you are creating your own {@link PrecacheController}, then call + * {@link PrecacheController#matchPrecache} on that instance, + * instead of using this function. + * + * @param {string|Request} request The key (without revisioning parameters) + * to look up in the precache. + * @return {Promise} + * + * @memberof workbox-precaching + */ +function matchPrecache(request) { + const precacheController = getOrCreatePrecacheController(); + return precacheController.matchPrecache(request); +} +export { matchPrecache }; diff --git a/node_modules/workbox-precaching/matchPrecache.mjs b/node_modules/workbox-precaching/matchPrecache.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2695d17d5e6996e8e0bc7ff26f33354c4ea437a8 --- /dev/null +++ b/node_modules/workbox-precaching/matchPrecache.mjs @@ -0,0 +1 @@ +export * from './matchPrecache.js'; \ No newline at end of file diff --git a/node_modules/workbox-precaching/package.json b/node_modules/workbox-precaching/package.json new file mode 100644 index 0000000000000000000000000000000000000000..59b2972b1d3a24ccda3341ebf95dde9fea7c7fd7 --- /dev/null +++ b/node_modules/workbox-precaching/package.json @@ -0,0 +1,32 @@ +{ + "name": "workbox-precaching", + "version": "7.4.1", + "license": "MIT", + "author": "Google's Web DevRel Team and Google's Aurora Team", + "description": "This module efficiently precaches assets.", + "repository": { + "type": "git", + "url": "git+https://github.com/googlechrome/workbox.git" + }, + "bugs": "https://github.com/googlechrome/workbox/issues", + "homepage": "https://github.com/GoogleChrome/workbox", + "keywords": [ + "workbox", + "workboxjs", + "service worker", + "sw" + ], + "workbox": { + "browserNamespace": "workbox.precaching", + "packageType": "sw" + }, + "main": "index.js", + "module": "index.mjs", + "types": "index.d.ts", + "dependencies": { + "workbox-core": "7.4.1", + "workbox-routing": "7.4.1", + "workbox-strategies": "7.4.1" + }, + "gitHead": "62b9d8ba8eb3c1a2ab8aac9d84c90cda7865d6a3" +} diff --git a/node_modules/workbox-precaching/precache.d.ts b/node_modules/workbox-precaching/precache.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c2f8cdfbe285d27c93d757cc46652413082cdfa4 --- /dev/null +++ b/node_modules/workbox-precaching/precache.d.ts @@ -0,0 +1,23 @@ +import { PrecacheEntry } from './_types.js'; +import './_version.js'; +/** + * Adds items to the precache list, removing any duplicates and + * stores the files in the + * {@link workbox-core.cacheNames|"precache cache"} when the service + * worker installs. + * + * This method can be called multiple times. + * + * Please note: This method **will not** serve any of the cached files for you. + * It only precaches files. To respond to a network request you call + * {@link workbox-precaching.addRoute}. + * + * If you have a single array of files to precache, you can just call + * {@link workbox-precaching.precacheAndRoute}. + * + * @param {Array} [entries=[]] Array of entries to precache. + * + * @memberof workbox-precaching + */ +declare function precache(entries: Array): void; +export { precache }; diff --git a/node_modules/workbox-precaching/precache.js b/node_modules/workbox-precaching/precache.js new file mode 100644 index 0000000000000000000000000000000000000000..b6848f3d455cfdb473d36ea45959724989e895c1 --- /dev/null +++ b/node_modules/workbox-precaching/precache.js @@ -0,0 +1,33 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js'; +import './_version.js'; +/** + * Adds items to the precache list, removing any duplicates and + * stores the files in the + * {@link workbox-core.cacheNames|"precache cache"} when the service + * worker installs. + * + * This method can be called multiple times. + * + * Please note: This method **will not** serve any of the cached files for you. + * It only precaches files. To respond to a network request you call + * {@link workbox-precaching.addRoute}. + * + * If you have a single array of files to precache, you can just call + * {@link workbox-precaching.precacheAndRoute}. + * + * @param {Array} [entries=[]] Array of entries to precache. + * + * @memberof workbox-precaching + */ +function precache(entries) { + const precacheController = getOrCreatePrecacheController(); + precacheController.precache(entries); +} +export { precache }; diff --git a/node_modules/workbox-precaching/precache.mjs b/node_modules/workbox-precaching/precache.mjs new file mode 100644 index 0000000000000000000000000000000000000000..78d8e7e82312b2ab8fed2116ba89f349dfeb04d2 --- /dev/null +++ b/node_modules/workbox-precaching/precache.mjs @@ -0,0 +1 @@ +export * from './precache.js'; \ No newline at end of file diff --git a/node_modules/workbox-precaching/precacheAndRoute.d.ts b/node_modules/workbox-precaching/precacheAndRoute.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..35d87a24133fce42ac88ef6db30a7d6cfd5d6a79 --- /dev/null +++ b/node_modules/workbox-precaching/precacheAndRoute.d.ts @@ -0,0 +1,18 @@ +import { PrecacheRouteOptions, PrecacheEntry } from './_types.js'; +import './_version.js'; +/** + * This method will add entries to the precache list and add a route to + * respond to fetch events. + * + * This is a convenience method that will call + * {@link workbox-precaching.precache} and + * {@link workbox-precaching.addRoute} in a single call. + * + * @param {Array} entries Array of entries to precache. + * @param {Object} [options] See the + * {@link workbox-precaching.PrecacheRoute} options. + * + * @memberof workbox-precaching + */ +declare function precacheAndRoute(entries: Array, options?: PrecacheRouteOptions): void; +export { precacheAndRoute }; diff --git a/node_modules/workbox-precaching/precacheAndRoute.js b/node_modules/workbox-precaching/precacheAndRoute.js new file mode 100644 index 0000000000000000000000000000000000000000..258f9e682e793ec2e18c9ffabb190d18ace71ad4 --- /dev/null +++ b/node_modules/workbox-precaching/precacheAndRoute.js @@ -0,0 +1,29 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { addRoute } from './addRoute.js'; +import { precache } from './precache.js'; +import './_version.js'; +/** + * This method will add entries to the precache list and add a route to + * respond to fetch events. + * + * This is a convenience method that will call + * {@link workbox-precaching.precache} and + * {@link workbox-precaching.addRoute} in a single call. + * + * @param {Array} entries Array of entries to precache. + * @param {Object} [options] See the + * {@link workbox-precaching.PrecacheRoute} options. + * + * @memberof workbox-precaching + */ +function precacheAndRoute(entries, options) { + precache(entries); + addRoute(options); +} +export { precacheAndRoute }; diff --git a/node_modules/workbox-precaching/precacheAndRoute.mjs b/node_modules/workbox-precaching/precacheAndRoute.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8d65e6b8fb990792a53cc0bfc654073b96c50e62 --- /dev/null +++ b/node_modules/workbox-precaching/precacheAndRoute.mjs @@ -0,0 +1 @@ +export * from './precacheAndRoute.js'; \ No newline at end of file diff --git a/node_modules/workbox-precaching/src/PrecacheController.ts b/node_modules/workbox-precaching/src/PrecacheController.ts new file mode 100644 index 0000000000000000000000000000000000000000..bb7f97e59926dc60b528a8f5fbd61f21a42414f9 --- /dev/null +++ b/node_modules/workbox-precaching/src/PrecacheController.ts @@ -0,0 +1,366 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {assert} from 'workbox-core/_private/assert.js'; +import {cacheNames} from 'workbox-core/_private/cacheNames.js'; +import {logger} from 'workbox-core/_private/logger.js'; +import {WorkboxError} from 'workbox-core/_private/WorkboxError.js'; +import {waitUntil} from 'workbox-core/_private/waitUntil.js'; +import {Strategy} from 'workbox-strategies/Strategy.js'; +import {RouteHandlerCallback, WorkboxPlugin} from 'workbox-core/types.js'; + +import {createCacheKey} from './utils/createCacheKey.js'; +import {PrecacheInstallReportPlugin} from './utils/PrecacheInstallReportPlugin.js'; +import {PrecacheCacheKeyPlugin} from './utils/PrecacheCacheKeyPlugin.js'; +import {printCleanupDetails} from './utils/printCleanupDetails.js'; +import {printInstallDetails} from './utils/printInstallDetails.js'; +import {PrecacheStrategy} from './PrecacheStrategy.js'; +import {PrecacheEntry, InstallResult, CleanupResult} from './_types.js'; +import './_version.js'; + +// Give TypeScript the correct global. +declare let self: ServiceWorkerGlobalScope; + +declare global { + interface ServiceWorkerGlobalScope { + __WB_MANIFEST: Array; + } +} + +interface PrecacheControllerOptions { + cacheName?: string; + plugins?: WorkboxPlugin[]; + fallbackToNetwork?: boolean; +} + +/** + * Performs efficient precaching of assets. + * + * @memberof workbox-precaching + */ +class PrecacheController { + private _installAndActiveListenersAdded?: boolean; + private readonly _strategy: Strategy; + private readonly _urlsToCacheKeys: Map = new Map(); + private readonly _urlsToCacheModes: Map< + string, + | 'reload' + | 'default' + | 'no-store' + | 'no-cache' + | 'force-cache' + | 'only-if-cached' + > = new Map(); + private readonly _cacheKeysToIntegrities: Map = new Map(); + + /** + * Create a new PrecacheController. + * + * @param {Object} [options] + * @param {string} [options.cacheName] The cache to use for precaching. + * @param {string} [options.plugins] Plugins to use when precaching as well + * as responding to fetch events for precached assets. + * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to + * get the response from the network if there's a precache miss. + */ + constructor({ + cacheName, + plugins = [], + fallbackToNetwork = true, + }: PrecacheControllerOptions = {}) { + this._strategy = new PrecacheStrategy({ + cacheName: cacheNames.getPrecacheName(cacheName), + plugins: [ + ...plugins, + new PrecacheCacheKeyPlugin({precacheController: this}), + ], + fallbackToNetwork, + }); + + // Bind the install and activate methods to the instance. + this.install = this.install.bind(this); + this.activate = this.activate.bind(this); + } + + /** + * @type {workbox-precaching.PrecacheStrategy} The strategy created by this controller and + * used to cache assets and respond to fetch events. + */ + get strategy(): Strategy { + return this._strategy; + } + + /** + * Adds items to the precache list, removing any duplicates and + * stores the files in the + * {@link workbox-core.cacheNames|"precache cache"} when the service + * worker installs. + * + * This method can be called multiple times. + * + * @param {Array} [entries=[]] Array of entries to precache. + */ + precache(entries: Array): void { + this.addToCacheList(entries); + + if (!this._installAndActiveListenersAdded) { + self.addEventListener('install', this.install); + self.addEventListener('activate', this.activate); + this._installAndActiveListenersAdded = true; + } + } + + /** + * This method will add items to the precache list, removing duplicates + * and ensuring the information is valid. + * + * @param {Array} entries + * Array of entries to precache. + */ + addToCacheList(entries: Array): void { + if (process.env.NODE_ENV !== 'production') { + assert!.isArray(entries, { + moduleName: 'workbox-precaching', + className: 'PrecacheController', + funcName: 'addToCacheList', + paramName: 'entries', + }); + } + + const urlsToWarnAbout: string[] = []; + for (const entry of entries) { + // See https://github.com/GoogleChrome/workbox/issues/2259 + if (typeof entry === 'string') { + urlsToWarnAbout.push(entry); + } else if (entry && entry.revision === undefined) { + urlsToWarnAbout.push(entry.url); + } + + const {cacheKey, url} = createCacheKey(entry); + const cacheMode = + typeof entry !== 'string' && entry.revision ? 'reload' : 'default'; + + if ( + this._urlsToCacheKeys.has(url) && + this._urlsToCacheKeys.get(url) !== cacheKey + ) { + throw new WorkboxError('add-to-cache-list-conflicting-entries', { + firstEntry: this._urlsToCacheKeys.get(url), + secondEntry: cacheKey, + }); + } + + if (typeof entry !== 'string' && entry.integrity) { + if ( + this._cacheKeysToIntegrities.has(cacheKey) && + this._cacheKeysToIntegrities.get(cacheKey) !== entry.integrity + ) { + throw new WorkboxError('add-to-cache-list-conflicting-integrities', { + url, + }); + } + this._cacheKeysToIntegrities.set(cacheKey, entry.integrity); + } + + this._urlsToCacheKeys.set(url, cacheKey); + this._urlsToCacheModes.set(url, cacheMode); + + if (urlsToWarnAbout.length > 0) { + const warningMessage = + `Workbox is precaching URLs without revision ` + + `info: ${urlsToWarnAbout.join(', ')}\nThis is generally NOT safe. ` + + `Learn more at https://bit.ly/wb-precache`; + if (process.env.NODE_ENV === 'production') { + // Use console directly to display this warning without bloating + // bundle sizes by pulling in all of the logger codebase in prod. + console.warn(warningMessage); + } else { + logger.warn(warningMessage); + } + } + } + } + + /** + * Precaches new and updated assets. Call this method from the service worker + * install event. + * + * Note: this method calls `event.waitUntil()` for you, so you do not need + * to call it yourself in your event handlers. + * + * @param {ExtendableEvent} event + * @return {Promise} + */ + install(event: ExtendableEvent): Promise { + // waitUntil returns Promise + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return waitUntil(event, async () => { + const installReportPlugin = new PrecacheInstallReportPlugin(); + this.strategy.plugins.push(installReportPlugin); + + // Cache entries one at a time. + // See https://github.com/GoogleChrome/workbox/issues/2528 + for (const [url, cacheKey] of this._urlsToCacheKeys) { + const integrity = this._cacheKeysToIntegrities.get(cacheKey); + const cacheMode = this._urlsToCacheModes.get(url); + + const request = new Request(url, { + integrity, + cache: cacheMode, + credentials: 'same-origin', + }); + + await Promise.all( + this.strategy.handleAll({ + params: {cacheKey}, + request, + event, + }), + ); + } + + const {updatedURLs, notUpdatedURLs} = installReportPlugin; + + if (process.env.NODE_ENV !== 'production') { + printInstallDetails(updatedURLs, notUpdatedURLs); + } + + return {updatedURLs, notUpdatedURLs}; + }); + } + + /** + * Deletes assets that are no longer present in the current precache manifest. + * Call this method from the service worker activate event. + * + * Note: this method calls `event.waitUntil()` for you, so you do not need + * to call it yourself in your event handlers. + * + * @param {ExtendableEvent} event + * @return {Promise} + */ + activate(event: ExtendableEvent): Promise { + // waitUntil returns Promise + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return waitUntil(event, async () => { + const cache = await self.caches.open(this.strategy.cacheName); + const currentlyCachedRequests = await cache.keys(); + const expectedCacheKeys = new Set(this._urlsToCacheKeys.values()); + + const deletedURLs = []; + for (const request of currentlyCachedRequests) { + if (!expectedCacheKeys.has(request.url)) { + await cache.delete(request); + deletedURLs.push(request.url); + } + } + + if (process.env.NODE_ENV !== 'production') { + printCleanupDetails(deletedURLs); + } + + return {deletedURLs}; + }); + } + + /** + * Returns a mapping of a precached URL to the corresponding cache key, taking + * into account the revision information for the URL. + * + * @return {Map} A URL to cache key mapping. + */ + getURLsToCacheKeys(): Map { + return this._urlsToCacheKeys; + } + + /** + * Returns a list of all the URLs that have been precached by the current + * service worker. + * + * @return {Array} The precached URLs. + */ + getCachedURLs(): Array { + return [...this._urlsToCacheKeys.keys()]; + } + + /** + * Returns the cache key used for storing a given URL. If that URL is + * unversioned, like `/index.html', then the cache key will be the original + * URL with a search parameter appended to it. + * + * @param {string} url A URL whose cache key you want to look up. + * @return {string} The versioned URL that corresponds to a cache key + * for the original URL, or undefined if that URL isn't precached. + */ + getCacheKeyForURL(url: string): string | undefined { + const urlObject = new URL(url, location.href); + return this._urlsToCacheKeys.get(urlObject.href); + } + + /** + * @param {string} url A cache key whose SRI you want to look up. + * @return {string} The subresource integrity associated with the cache key, + * or undefined if it's not set. + */ + getIntegrityForCacheKey(cacheKey: string): string | undefined { + return this._cacheKeysToIntegrities.get(cacheKey); + } + + /** + * This acts as a drop-in replacement for + * [`cache.match()`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/match) + * with the following differences: + * + * - It knows what the name of the precache is, and only checks in that cache. + * - It allows you to pass in an "original" URL without versioning parameters, + * and it will automatically look up the correct cache key for the currently + * active revision of that URL. + * + * E.g., `matchPrecache('index.html')` will find the correct precached + * response for the currently active service worker, even if the actual cache + * key is `'/index.html?__WB_REVISION__=1234abcd'`. + * + * @param {string|Request} request The key (without revisioning parameters) + * to look up in the precache. + * @return {Promise} + */ + async matchPrecache( + request: string | Request, + ): Promise { + const url = request instanceof Request ? request.url : request; + const cacheKey = this.getCacheKeyForURL(url); + if (cacheKey) { + const cache = await self.caches.open(this.strategy.cacheName); + return cache.match(cacheKey); + } + return undefined; + } + + /** + * Returns a function that looks up `url` in the precache (taking into + * account revision information), and returns the corresponding `Response`. + * + * @param {string} url The precached URL which will be used to lookup the + * `Response`. + * @return {workbox-routing~handlerCallback} + */ + createHandlerBoundToURL(url: string): RouteHandlerCallback { + const cacheKey = this.getCacheKeyForURL(url); + if (!cacheKey) { + throw new WorkboxError('non-precached-url', {url}); + } + return (options) => { + options.request = new Request(url); + options.params = {cacheKey, ...options.params}; + + return this.strategy.handle(options); + }; + } +} + +export {PrecacheController}; diff --git a/node_modules/workbox-precaching/src/PrecacheFallbackPlugin.ts b/node_modules/workbox-precaching/src/PrecacheFallbackPlugin.ts new file mode 100644 index 0000000000000000000000000000000000000000..0c3dfa12e05445d380235293968068574b795dbb --- /dev/null +++ b/node_modules/workbox-precaching/src/PrecacheFallbackPlugin.ts @@ -0,0 +1,65 @@ +/* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {WorkboxPlugin} from 'workbox-core/types.js'; + +import {getOrCreatePrecacheController} from './utils/getOrCreatePrecacheController.js'; +import {PrecacheController} from './PrecacheController.js'; + +import './_version.js'; + +/** + * `PrecacheFallbackPlugin` allows you to specify an "offline fallback" + * response to be used when a given strategy is unable to generate a response. + * + * It does this by intercepting the `handlerDidError` plugin callback + * and returning a precached response, taking the expected revision parameter + * into account automatically. + * + * Unless you explicitly pass in a `PrecacheController` instance to the + * constructor, the default instance will be used. Generally speaking, most + * developers will end up using the default. + * + * @memberof workbox-precaching + */ +class PrecacheFallbackPlugin implements WorkboxPlugin { + private readonly _fallbackURL: string; + private readonly _precacheController: PrecacheController; + + /** + * Constructs a new PrecacheFallbackPlugin with the associated fallbackURL. + * + * @param {Object} config + * @param {string} config.fallbackURL A precached URL to use as the fallback + * if the associated strategy can't generate a response. + * @param {PrecacheController} [config.precacheController] An optional + * PrecacheController instance. If not provided, the default + * PrecacheController will be used. + */ + constructor({ + fallbackURL, + precacheController, + }: { + fallbackURL: string; + precacheController?: PrecacheController; + }) { + this._fallbackURL = fallbackURL; + this._precacheController = + precacheController || getOrCreatePrecacheController(); + } + + /** + * @return {Promise} The precache response for the fallback URL. + * + * @private + */ + handlerDidError: WorkboxPlugin['handlerDidError'] = () => + this._precacheController.matchPrecache(this._fallbackURL); +} + +export {PrecacheFallbackPlugin}; diff --git a/node_modules/workbox-precaching/src/PrecacheRoute.ts b/node_modules/workbox-precaching/src/PrecacheRoute.ts new file mode 100644 index 0000000000000000000000000000000000000000..63c31720dd763d519de2e3f4d3836e90fbae200d --- /dev/null +++ b/node_modules/workbox-precaching/src/PrecacheRoute.ts @@ -0,0 +1,77 @@ +/* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {logger} from 'workbox-core/_private/logger.js'; +import {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.js'; +import { + RouteMatchCallback, + RouteMatchCallbackOptions, +} from 'workbox-core/types.js'; +import {Route} from 'workbox-routing/Route.js'; + +import {PrecacheRouteOptions} from './_types.js'; +import {PrecacheController} from './PrecacheController.js'; +import {generateURLVariations} from './utils/generateURLVariations.js'; + +import './_version.js'; + +/** + * A subclass of {@link workbox-routing.Route} that takes a + * {@link workbox-precaching.PrecacheController} + * instance and uses it to match incoming requests and handle fetching + * responses from the precache. + * + * @memberof workbox-precaching + * @extends workbox-routing.Route + */ +class PrecacheRoute extends Route { + /** + * @param {PrecacheController} precacheController A `PrecacheController` + * instance used to both match requests and respond to fetch events. + * @param {Object} [options] Options to control how requests are matched + * against the list of precached URLs. + * @param {string} [options.directoryIndex=index.html] The `directoryIndex` will + * check cache entries for a URLs ending with '/' to see if there is a hit when + * appending the `directoryIndex` value. + * @param {Array} [options.ignoreURLParametersMatching=[/^utm_/, /^fbclid$/]] An + * array of regex's to remove search params when looking for a cache match. + * @param {boolean} [options.cleanURLs=true] The `cleanURLs` option will + * check the cache for the URL with a `.html` added to the end of the end. + * @param {workbox-precaching~urlManipulation} [options.urlManipulation] + * This is a function that should take a URL and return an array of + * alternative URLs that should be checked for precache matches. + */ + constructor( + precacheController: PrecacheController, + options?: PrecacheRouteOptions, + ) { + const match: RouteMatchCallback = ({ + request, + }: RouteMatchCallbackOptions) => { + const urlsToCacheKeys = precacheController.getURLsToCacheKeys(); + for (const possibleURL of generateURLVariations(request.url, options)) { + const cacheKey = urlsToCacheKeys.get(possibleURL); + if (cacheKey) { + const integrity = + precacheController.getIntegrityForCacheKey(cacheKey); + return {cacheKey, integrity}; + } + } + if (process.env.NODE_ENV !== 'production') { + logger.debug( + `Precaching did not find a match for ` + getFriendlyURL(request.url), + ); + } + return; + }; + + super(match, precacheController.strategy); + } +} + +export {PrecacheRoute}; diff --git a/node_modules/workbox-precaching/src/PrecacheStrategy.ts b/node_modules/workbox-precaching/src/PrecacheStrategy.ts new file mode 100644 index 0000000000000000000000000000000000000000..a5e2173f2a832edfd628d86b9b1bedf1e731bb75 --- /dev/null +++ b/node_modules/workbox-precaching/src/PrecacheStrategy.ts @@ -0,0 +1,287 @@ +/* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {copyResponse} from 'workbox-core/copyResponse.js'; +import {cacheNames} from 'workbox-core/_private/cacheNames.js'; +import {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.js'; +import {logger} from 'workbox-core/_private/logger.js'; +import {WorkboxError} from 'workbox-core/_private/WorkboxError.js'; +import {WorkboxPlugin} from 'workbox-core/types.js'; +import {Strategy, StrategyOptions} from 'workbox-strategies/Strategy.js'; +import {StrategyHandler} from 'workbox-strategies/StrategyHandler.js'; + +import './_version.js'; + +interface PrecacheStrategyOptions extends StrategyOptions { + fallbackToNetwork?: boolean; +} + +/** + * A {@link workbox-strategies.Strategy} implementation + * specifically designed to work with + * {@link workbox-precaching.PrecacheController} + * to both cache and fetch precached assets. + * + * Note: an instance of this class is created automatically when creating a + * `PrecacheController`; it's generally not necessary to create this yourself. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-precaching + */ +class PrecacheStrategy extends Strategy { + private readonly _fallbackToNetwork: boolean; + + static readonly defaultPrecacheCacheabilityPlugin: WorkboxPlugin = { + async cacheWillUpdate({response}) { + if (!response || response.status >= 400) { + return null; + } + + return response; + }, + }; + + static readonly copyRedirectedCacheableResponsesPlugin: WorkboxPlugin = { + async cacheWillUpdate({response}) { + return response.redirected ? await copyResponse(response) : response; + }, + }; + + /** + * + * @param {Object} [options] + * @param {string} [options.cacheName] Cache name to store and retrieve + * requests. Defaults to the cache names provided by + * {@link workbox-core.cacheNames}. + * @param {Array} [options.plugins] {@link https://developers.google.com/web/tools/workbox/guides/using-plugins|Plugins} + * to use in conjunction with this caching strategy. + * @param {Object} [options.fetchOptions] Values passed along to the + * {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters|init} + * of all fetch() requests made by this strategy. + * @param {Object} [options.matchOptions] The + * {@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions|CacheQueryOptions} + * for any `cache.match()` or `cache.put()` calls made by this strategy. + * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to + * get the response from the network if there's a precache miss. + */ + constructor(options: PrecacheStrategyOptions = {}) { + options.cacheName = cacheNames.getPrecacheName(options.cacheName); + super(options); + + this._fallbackToNetwork = + options.fallbackToNetwork === false ? false : true; + + // Redirected responses cannot be used to satisfy a navigation request, so + // any redirected response must be "copied" rather than cloned, so the new + // response doesn't contain the `redirected` flag. See: + // https://bugs.chromium.org/p/chromium/issues/detail?id=669363&desc=2#c1 + this.plugins.push(PrecacheStrategy.copyRedirectedCacheableResponsesPlugin); + } + + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + async _handle(request: Request, handler: StrategyHandler): Promise { + const response = await handler.cacheMatch(request); + if (response) { + return response; + } + + // If this is an `install` event for an entry that isn't already cached, + // then populate the cache. + if (handler.event && handler.event.type === 'install') { + return await this._handleInstall(request, handler); + } + + // Getting here means something went wrong. An entry that should have been + // precached wasn't found in the cache. + return await this._handleFetch(request, handler); + } + + async _handleFetch( + request: Request, + handler: StrategyHandler, + ): Promise { + let response; + const params = (handler.params || {}) as { + cacheKey?: string; + integrity?: string; + }; + + // Fall back to the network if we're configured to do so. + if (this._fallbackToNetwork) { + if (process.env.NODE_ENV !== 'production') { + logger.warn( + `The precached response for ` + + `${getFriendlyURL(request.url)} in ${this.cacheName} was not ` + + `found. Falling back to the network.`, + ); + } + + const integrityInManifest = params.integrity; + const integrityInRequest = request.integrity; + const noIntegrityConflict = + !integrityInRequest || integrityInRequest === integrityInManifest; + + // Do not add integrity if the original request is no-cors + // See https://github.com/GoogleChrome/workbox/issues/3096 + response = await handler.fetch( + new Request(request, { + integrity: + request.mode !== 'no-cors' + ? integrityInRequest || integrityInManifest + : undefined, + }), + ); + + // It's only "safe" to repair the cache if we're using SRI to guarantee + // that the response matches the precache manifest's expectations, + // and there's either a) no integrity property in the incoming request + // or b) there is an integrity, and it matches the precache manifest. + // See https://github.com/GoogleChrome/workbox/issues/2858 + // Also if the original request users no-cors we don't use integrity. + // See https://github.com/GoogleChrome/workbox/issues/3096 + if ( + integrityInManifest && + noIntegrityConflict && + request.mode !== 'no-cors' + ) { + this._useDefaultCacheabilityPluginIfNeeded(); + const wasCached = await handler.cachePut(request, response.clone()); + if (process.env.NODE_ENV !== 'production') { + if (wasCached) { + logger.log( + `A response for ${getFriendlyURL(request.url)} ` + + `was used to "repair" the precache.`, + ); + } + } + } + } else { + // This shouldn't normally happen, but there are edge cases: + // https://github.com/GoogleChrome/workbox/issues/1441 + throw new WorkboxError('missing-precache-entry', { + cacheName: this.cacheName, + url: request.url, + }); + } + + if (process.env.NODE_ENV !== 'production') { + const cacheKey = + params.cacheKey || (await handler.getCacheKey(request, 'read')); + + // Workbox is going to handle the route. + // print the routing details to the console. + logger.groupCollapsed( + `Precaching is responding to: ` + getFriendlyURL(request.url), + ); + logger.log( + `Serving the precached url: ${getFriendlyURL( + cacheKey instanceof Request ? cacheKey.url : cacheKey, + )}`, + ); + + logger.groupCollapsed(`View request details here.`); + logger.log(request); + logger.groupEnd(); + + logger.groupCollapsed(`View response details here.`); + logger.log(response); + logger.groupEnd(); + + logger.groupEnd(); + } + + return response; + } + + async _handleInstall( + request: Request, + handler: StrategyHandler, + ): Promise { + this._useDefaultCacheabilityPluginIfNeeded(); + + const response = await handler.fetch(request); + + // Make sure we defer cachePut() until after we know the response + // should be cached; see https://github.com/GoogleChrome/workbox/issues/2737 + const wasCached = await handler.cachePut(request, response.clone()); + if (!wasCached) { + // Throwing here will lead to the `install` handler failing, which + // we want to do if *any* of the responses aren't safe to cache. + throw new WorkboxError('bad-precaching-response', { + url: request.url, + status: response.status, + }); + } + + return response; + } + + /** + * This method is complex, as there a number of things to account for: + * + * The `plugins` array can be set at construction, and/or it might be added to + * to at any time before the strategy is used. + * + * At the time the strategy is used (i.e. during an `install` event), there + * needs to be at least one plugin that implements `cacheWillUpdate` in the + * array, other than `copyRedirectedCacheableResponsesPlugin`. + * + * - If this method is called and there are no suitable `cacheWillUpdate` + * plugins, we need to add `defaultPrecacheCacheabilityPlugin`. + * + * - If this method is called and there is exactly one `cacheWillUpdate`, then + * we don't have to do anything (this might be a previously added + * `defaultPrecacheCacheabilityPlugin`, or it might be a custom plugin). + * + * - If this method is called and there is more than one `cacheWillUpdate`, + * then we need to check if one is `defaultPrecacheCacheabilityPlugin`. If so, + * we need to remove it. (This situation is unlikely, but it could happen if + * the strategy is used multiple times, the first without a `cacheWillUpdate`, + * and then later on after manually adding a custom `cacheWillUpdate`.) + * + * See https://github.com/GoogleChrome/workbox/issues/2737 for more context. + * + * @private + */ + _useDefaultCacheabilityPluginIfNeeded(): void { + let defaultPluginIndex: number | null = null; + let cacheWillUpdatePluginCount = 0; + + for (const [index, plugin] of this.plugins.entries()) { + // Ignore the copy redirected plugin when determining what to do. + if (plugin === PrecacheStrategy.copyRedirectedCacheableResponsesPlugin) { + continue; + } + + // Save the default plugin's index, in case it needs to be removed. + if (plugin === PrecacheStrategy.defaultPrecacheCacheabilityPlugin) { + defaultPluginIndex = index; + } + + if (plugin.cacheWillUpdate) { + cacheWillUpdatePluginCount++; + } + } + + if (cacheWillUpdatePluginCount === 0) { + this.plugins.push(PrecacheStrategy.defaultPrecacheCacheabilityPlugin); + } else if (cacheWillUpdatePluginCount > 1 && defaultPluginIndex !== null) { + // Only remove the default plugin; multiple custom plugins are allowed. + this.plugins.splice(defaultPluginIndex, 1); + } + // Nothing needs to be done if cacheWillUpdatePluginCount is 1 + } +} + +export {PrecacheStrategy}; diff --git a/node_modules/workbox-precaching/src/_types.ts b/node_modules/workbox-precaching/src/_types.ts new file mode 100644 index 0000000000000000000000000000000000000000..506d1bc2387e8a24c72df71c8cac74ae1fdabb65 --- /dev/null +++ b/node_modules/workbox-precaching/src/_types.ts @@ -0,0 +1,85 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import './_version.js'; + +export interface InstallResult { + updatedURLs: string[]; + notUpdatedURLs: string[]; +} + +export interface CleanupResult { + deletedCacheRequests: string[]; +} + +export declare interface PrecacheEntry { + integrity?: string; + url: string; + revision?: string | null; +} + +export interface PrecacheRouteOptions { + directoryIndex?: string; + ignoreURLParametersMatching?: RegExp[]; + cleanURLs?: boolean; + urlManipulation?: urlManipulation; +} + +export type urlManipulation = ({url}: {url: URL}) => URL[]; + +// * * * IMPORTANT! * * * +// ------------------------------------------------------------------------- // +// jdsoc type definitions cannot be declared above TypeScript definitions or +// they'll be stripped from the built `.js` files, and they'll only be in the +// `d.ts` files, which aren't read by the jsdoc generator. As a result we +// have to put declare them below. + +/** + * @typedef {Object} InstallResult + * @property {Array} updatedURLs List of URLs that were updated during + * installation. + * @property {Array} notUpdatedURLs List of URLs that were already up to + * date. + * + * @memberof workbox-precaching + */ + +/** + * @typedef {Object} CleanupResult + * @property {Array} deletedCacheRequests List of URLs that were deleted + * while cleaning up the cache. + * + * @memberof workbox-precaching + */ + +/** + * @typedef {Object} PrecacheEntry + * @property {string} url URL to precache. + * @property {string} [revision] Revision information for the URL. + * @property {string} [integrity] Integrity metadata that will be used when + * making the network request for the URL. + * + * @memberof workbox-precaching + */ + +/** + * The "urlManipulation" callback can be used to determine if there are any + * additional permutations of a URL that should be used to check against + * the available precached files. + * + * For example, Workbox supports checking for '/index.html' when the URL + * '/' is provided. This callback allows additional, custom checks. + * + * @callback ~urlManipulation + * @param {Object} context + * @param {URL} context.url The request's URL. + * @return {Array} To add additional urls to test, return an Array of + * URLs. Please note that these **should not be strings**, but URL objects. + * + * @memberof workbox-precaching + */ diff --git a/node_modules/workbox-precaching/src/_version.ts b/node_modules/workbox-precaching/src/_version.ts new file mode 100644 index 0000000000000000000000000000000000000000..d93d5d58f503498247c4d249d3ee40a229fc9ef0 --- /dev/null +++ b/node_modules/workbox-precaching/src/_version.ts @@ -0,0 +1,2 @@ +// @ts-ignore +try{self['workbox:precaching:7.4.1']&&_()}catch(e){} \ No newline at end of file diff --git a/node_modules/workbox-precaching/src/addPlugins.ts b/node_modules/workbox-precaching/src/addPlugins.ts new file mode 100644 index 0000000000000000000000000000000000000000..f4651a6003a688977e9d20c0fa264fae2d1860dd --- /dev/null +++ b/node_modules/workbox-precaching/src/addPlugins.ts @@ -0,0 +1,25 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {WorkboxPlugin} from 'workbox-core/types.js'; +import {getOrCreatePrecacheController} from './utils/getOrCreatePrecacheController.js'; +import './_version.js'; + +/** + * Adds plugins to the precaching strategy. + * + * @param {Array} plugins + * + * @memberof workbox-precaching + */ +function addPlugins(plugins: WorkboxPlugin[]): void { + const precacheController = getOrCreatePrecacheController(); + precacheController.strategy.plugins.push(...plugins); +} + +export {addPlugins}; diff --git a/node_modules/workbox-precaching/src/addRoute.ts b/node_modules/workbox-precaching/src/addRoute.ts new file mode 100644 index 0000000000000000000000000000000000000000..a3899c5bbe2c74623939d5b202efbce36058ba77 --- /dev/null +++ b/node_modules/workbox-precaching/src/addRoute.ts @@ -0,0 +1,38 @@ +/* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {registerRoute} from 'workbox-routing/registerRoute.js'; + +import {getOrCreatePrecacheController} from './utils/getOrCreatePrecacheController.js'; +import {PrecacheRoute} from './PrecacheRoute.js'; +import {PrecacheRouteOptions} from './_types.js'; + +import './_version.js'; + +/** + * Add a `fetch` listener to the service worker that will + * respond to + * [network requests]{@link https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#Custom_responses_to_requests} + * with precached assets. + * + * Requests for assets that aren't precached, the `FetchEvent` will not be + * responded to, allowing the event to fall through to other `fetch` event + * listeners. + * + * @param {Object} [options] See the {@link workbox-precaching.PrecacheRoute} + * options. + * + * @memberof workbox-precaching + */ +function addRoute(options?: PrecacheRouteOptions): void { + const precacheController = getOrCreatePrecacheController(); + + const precacheRoute = new PrecacheRoute(precacheController, options); + registerRoute(precacheRoute); +} + +export {addRoute}; diff --git a/node_modules/workbox-precaching/src/cleanupOutdatedCaches.ts b/node_modules/workbox-precaching/src/cleanupOutdatedCaches.ts new file mode 100644 index 0000000000000000000000000000000000000000..319cc75a70e24f0b162bcd4ed0755334391ee40c --- /dev/null +++ b/node_modules/workbox-precaching/src/cleanupOutdatedCaches.ts @@ -0,0 +1,41 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {cacheNames} from 'workbox-core/_private/cacheNames.js'; +import {logger} from 'workbox-core/_private/logger.js'; +import {deleteOutdatedCaches} from './utils/deleteOutdatedCaches.js'; +import './_version.js'; + +/** + * Adds an `activate` event listener which will clean up incompatible + * precaches that were created by older versions of Workbox. + * + * @memberof workbox-precaching + */ +function cleanupOutdatedCaches(): void { + // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705 + self.addEventListener('activate', ((event: ExtendableEvent) => { + const cacheName = cacheNames.getPrecacheName(); + + event.waitUntil( + deleteOutdatedCaches(cacheName).then((cachesDeleted) => { + if (process.env.NODE_ENV !== 'production') { + if (cachesDeleted.length > 0) { + logger.log( + `The following out-of-date precaches were cleaned up ` + + `automatically:`, + cachesDeleted, + ); + } + } + }), + ); + }) as EventListener); +} + +export {cleanupOutdatedCaches}; diff --git a/node_modules/workbox-precaching/src/createHandlerBoundToURL.ts b/node_modules/workbox-precaching/src/createHandlerBoundToURL.ts new file mode 100644 index 0000000000000000000000000000000000000000..a5694c22424e75c51bf35712138af1dd1eaed0e7 --- /dev/null +++ b/node_modules/workbox-precaching/src/createHandlerBoundToURL.ts @@ -0,0 +1,35 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {getOrCreatePrecacheController} from './utils/getOrCreatePrecacheController.js'; +import {RouteHandlerCallback} from 'workbox-core/types.js'; +import './_version.js'; + +/** + * Helper function that calls + * {@link PrecacheController#createHandlerBoundToURL} on the default + * {@link PrecacheController} instance. + * + * If you are creating your own {@link PrecacheController}, then call the + * {@link PrecacheController#createHandlerBoundToURL} on that instance, + * instead of using this function. + * + * @param {string} url The precached URL which will be used to lookup the + * `Response`. + * @param {boolean} [fallbackToNetwork=true] Whether to attempt to get the + * response from the network if there's a precache miss. + * @return {workbox-routing~handlerCallback} + * + * @memberof workbox-precaching + */ +function createHandlerBoundToURL(url: string): RouteHandlerCallback { + const precacheController = getOrCreatePrecacheController(); + return precacheController.createHandlerBoundToURL(url); +} + +export {createHandlerBoundToURL}; diff --git a/node_modules/workbox-precaching/src/getCacheKeyForURL.ts b/node_modules/workbox-precaching/src/getCacheKeyForURL.ts new file mode 100644 index 0000000000000000000000000000000000000000..1a73806c5f8fd0290162517c221152116711e3bf --- /dev/null +++ b/node_modules/workbox-precaching/src/getCacheKeyForURL.ts @@ -0,0 +1,36 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {getOrCreatePrecacheController} from './utils/getOrCreatePrecacheController.js'; +import './_version.js'; + +/** + * Takes in a URL, and returns the corresponding URL that could be used to + * lookup the entry in the precache. + * + * If a relative URL is provided, the location of the service worker file will + * be used as the base. + * + * For precached entries without revision information, the cache key will be the + * same as the original URL. + * + * For precached entries with revision information, the cache key will be the + * original URL with the addition of a query parameter used for keeping track of + * the revision info. + * + * @param {string} url The URL whose cache key to look up. + * @return {string} The cache key that corresponds to that URL. + * + * @memberof workbox-precaching + */ +function getCacheKeyForURL(url: string): string | undefined { + const precacheController = getOrCreatePrecacheController(); + return precacheController.getCacheKeyForURL(url); +} + +export {getCacheKeyForURL}; diff --git a/node_modules/workbox-precaching/src/index.ts b/node_modules/workbox-precaching/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..d4d140c5670e53e8dadf712a384c08dc0dd1eacf --- /dev/null +++ b/node_modules/workbox-precaching/src/index.ts @@ -0,0 +1,52 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {addPlugins} from './addPlugins.js'; +import {addRoute} from './addRoute.js'; +import {cleanupOutdatedCaches} from './cleanupOutdatedCaches.js'; +import {createHandlerBoundToURL} from './createHandlerBoundToURL.js'; +import {getCacheKeyForURL} from './getCacheKeyForURL.js'; +import {matchPrecache} from './matchPrecache.js'; +import {precache} from './precache.js'; +import {precacheAndRoute} from './precacheAndRoute.js'; +import {PrecacheController} from './PrecacheController.js'; +import {PrecacheRoute} from './PrecacheRoute.js'; +import {PrecacheStrategy} from './PrecacheStrategy.js'; +import {PrecacheFallbackPlugin} from './PrecacheFallbackPlugin.js'; + +import './_version.js'; + +/** + * Most consumers of this module will want to use the + * {@link workbox-precaching.precacheAndRoute} + * method to add assets to the cache and respond to network requests with these + * cached assets. + * + * If you require more control over caching and routing, you can use the + * {@link workbox-precaching.PrecacheController} + * interface. + * + * @module workbox-precaching + */ + +export { + addPlugins, + addRoute, + cleanupOutdatedCaches, + createHandlerBoundToURL, + getCacheKeyForURL, + matchPrecache, + precache, + precacheAndRoute, + PrecacheController, + PrecacheRoute, + PrecacheStrategy, + PrecacheFallbackPlugin, +}; + +export * from './_types.js'; diff --git a/node_modules/workbox-precaching/src/matchPrecache.ts b/node_modules/workbox-precaching/src/matchPrecache.ts new file mode 100644 index 0000000000000000000000000000000000000000..3c64cce3912a3ab4bbe48b6fa5523389b2a311ff --- /dev/null +++ b/node_modules/workbox-precaching/src/matchPrecache.ts @@ -0,0 +1,35 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {getOrCreatePrecacheController} from './utils/getOrCreatePrecacheController.js'; + +import './_version.js'; + +/** + * Helper function that calls + * {@link PrecacheController#matchPrecache} on the default + * {@link PrecacheController} instance. + * + * If you are creating your own {@link PrecacheController}, then call + * {@link PrecacheController#matchPrecache} on that instance, + * instead of using this function. + * + * @param {string|Request} request The key (without revisioning parameters) + * to look up in the precache. + * @return {Promise} + * + * @memberof workbox-precaching + */ +function matchPrecache( + request: string | Request, +): Promise { + const precacheController = getOrCreatePrecacheController(); + return precacheController.matchPrecache(request); +} + +export {matchPrecache}; diff --git a/node_modules/workbox-precaching/src/precache.ts b/node_modules/workbox-precaching/src/precache.ts new file mode 100644 index 0000000000000000000000000000000000000000..45c8d7e8220c06a5dde498a2181e00dedff049a7 --- /dev/null +++ b/node_modules/workbox-precaching/src/precache.ts @@ -0,0 +1,37 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {getOrCreatePrecacheController} from './utils/getOrCreatePrecacheController.js'; +import {PrecacheEntry} from './_types.js'; +import './_version.js'; + +/** + * Adds items to the precache list, removing any duplicates and + * stores the files in the + * {@link workbox-core.cacheNames|"precache cache"} when the service + * worker installs. + * + * This method can be called multiple times. + * + * Please note: This method **will not** serve any of the cached files for you. + * It only precaches files. To respond to a network request you call + * {@link workbox-precaching.addRoute}. + * + * If you have a single array of files to precache, you can just call + * {@link workbox-precaching.precacheAndRoute}. + * + * @param {Array} [entries=[]] Array of entries to precache. + * + * @memberof workbox-precaching + */ +function precache(entries: Array): void { + const precacheController = getOrCreatePrecacheController(); + precacheController.precache(entries); +} + +export {precache}; diff --git a/node_modules/workbox-precaching/src/precacheAndRoute.ts b/node_modules/workbox-precaching/src/precacheAndRoute.ts new file mode 100644 index 0000000000000000000000000000000000000000..7167a01cdccf6b57b5dafc1d3c6f1f601a07fafb --- /dev/null +++ b/node_modules/workbox-precaching/src/precacheAndRoute.ts @@ -0,0 +1,36 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {addRoute} from './addRoute.js'; +import {precache} from './precache.js'; +import {PrecacheRouteOptions, PrecacheEntry} from './_types.js'; +import './_version.js'; + +/** + * This method will add entries to the precache list and add a route to + * respond to fetch events. + * + * This is a convenience method that will call + * {@link workbox-precaching.precache} and + * {@link workbox-precaching.addRoute} in a single call. + * + * @param {Array} entries Array of entries to precache. + * @param {Object} [options] See the + * {@link workbox-precaching.PrecacheRoute} options. + * + * @memberof workbox-precaching + */ +function precacheAndRoute( + entries: Array, + options?: PrecacheRouteOptions, +): void { + precache(entries); + addRoute(options); +} + +export {precacheAndRoute}; diff --git a/node_modules/workbox-precaching/src/utils/PrecacheCacheKeyPlugin.ts b/node_modules/workbox-precaching/src/utils/PrecacheCacheKeyPlugin.ts new file mode 100644 index 0000000000000000000000000000000000000000..d6c4e4ae19db44d33a12bdf71b8972232d63187a --- /dev/null +++ b/node_modules/workbox-precaching/src/utils/PrecacheCacheKeyPlugin.ts @@ -0,0 +1,45 @@ +/* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {WorkboxPlugin, WorkboxPluginCallbackParam} from 'workbox-core/types.js'; + +import {PrecacheController} from '../PrecacheController.js'; + +import '../_version.js'; + +/** + * A plugin, designed to be used with PrecacheController, to translate URLs into + * the corresponding cache key, based on the current revision info. + * + * @private + */ +class PrecacheCacheKeyPlugin implements WorkboxPlugin { + private readonly _precacheController: PrecacheController; + + constructor({precacheController}: {precacheController: PrecacheController}) { + this._precacheController = precacheController; + } + + cacheKeyWillBeUsed: WorkboxPlugin['cacheKeyWillBeUsed'] = async ({ + request, + params, + }: WorkboxPluginCallbackParam['cacheKeyWillBeUsed']) => { + // Params is type any, can't change right now. + /* eslint-disable */ + const cacheKey = + params?.cacheKey || + this._precacheController.getCacheKeyForURL(request.url); + /* eslint-enable */ + + return cacheKey + ? new Request(cacheKey, {headers: request.headers}) + : request; + }; +} + +export {PrecacheCacheKeyPlugin}; diff --git a/node_modules/workbox-precaching/src/utils/PrecacheInstallReportPlugin.ts b/node_modules/workbox-precaching/src/utils/PrecacheInstallReportPlugin.ts new file mode 100644 index 0000000000000000000000000000000000000000..97970c58a3478cd0f094c9d2627493cc8b58962e --- /dev/null +++ b/node_modules/workbox-precaching/src/utils/PrecacheInstallReportPlugin.ts @@ -0,0 +1,58 @@ +/* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {WorkboxPlugin, WorkboxPluginCallbackParam} from 'workbox-core/types.js'; + +import '../_version.js'; + +/** + * A plugin, designed to be used with PrecacheController, to determine the + * of assets that were updated (or not updated) during the install event. + * + * @private + */ +class PrecacheInstallReportPlugin implements WorkboxPlugin { + updatedURLs: string[] = []; + notUpdatedURLs: string[] = []; + + handlerWillStart: WorkboxPlugin['handlerWillStart'] = async ({ + request, + state, + }: WorkboxPluginCallbackParam['handlerWillStart']) => { + // TODO: `state` should never be undefined... + if (state) { + state.originalRequest = request; + } + }; + + cachedResponseWillBeUsed: WorkboxPlugin['cachedResponseWillBeUsed'] = async ({ + event, + state, + cachedResponse, + }: WorkboxPluginCallbackParam['cachedResponseWillBeUsed']) => { + if (event.type === 'install') { + if ( + state && + state.originalRequest && + state.originalRequest instanceof Request + ) { + // TODO: `state` should never be undefined... + const url = state.originalRequest.url; + + if (cachedResponse) { + this.notUpdatedURLs.push(url); + } else { + this.updatedURLs.push(url); + } + } + } + return cachedResponse; + }; +} + +export {PrecacheInstallReportPlugin}; diff --git a/node_modules/workbox-precaching/src/utils/createCacheKey.ts b/node_modules/workbox-precaching/src/utils/createCacheKey.ts new file mode 100644 index 0000000000000000000000000000000000000000..b0045b90564bbd7e2bd716ebf37410ff1f404faa --- /dev/null +++ b/node_modules/workbox-precaching/src/utils/createCacheKey.ts @@ -0,0 +1,69 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {WorkboxError} from 'workbox-core/_private/WorkboxError.js'; +import {PrecacheEntry} from '../_types.js'; +import '../_version.js'; + +interface CacheKey { + cacheKey: string; + url: string; +} + +// Name of the search parameter used to store revision info. +const REVISION_SEARCH_PARAM = '__WB_REVISION__'; + +/** + * Converts a manifest entry into a versioned URL suitable for precaching. + * + * @param {Object|string} entry + * @return {string} A URL with versioning info. + * + * @private + * @memberof workbox-precaching + */ +export function createCacheKey(entry: PrecacheEntry | string): CacheKey { + if (!entry) { + throw new WorkboxError('add-to-cache-list-unexpected-type', {entry}); + } + + // If a precache manifest entry is a string, it's assumed to be a versioned + // URL, like '/app.abcd1234.js'. Return as-is. + if (typeof entry === 'string') { + const urlObject = new URL(entry, location.href); + return { + cacheKey: urlObject.href, + url: urlObject.href, + }; + } + + const {revision, url} = entry; + if (!url) { + throw new WorkboxError('add-to-cache-list-unexpected-type', {entry}); + } + + // If there's just a URL and no revision, then it's also assumed to be a + // versioned URL. + if (!revision) { + const urlObject = new URL(url, location.href); + return { + cacheKey: urlObject.href, + url: urlObject.href, + }; + } + + // Otherwise, construct a properly versioned URL using the custom Workbox + // search parameter along with the revision info. + const cacheKeyURL = new URL(url, location.href); + const originalURL = new URL(url, location.href); + cacheKeyURL.searchParams.set(REVISION_SEARCH_PARAM, revision); + return { + cacheKey: cacheKeyURL.href, + url: originalURL.href, + }; +} diff --git a/node_modules/workbox-precaching/src/utils/deleteOutdatedCaches.ts b/node_modules/workbox-precaching/src/utils/deleteOutdatedCaches.ts new file mode 100644 index 0000000000000000000000000000000000000000..f37c62bbdeb81992ed28bea4ab4a1b0cf3be6c8b --- /dev/null +++ b/node_modules/workbox-precaching/src/utils/deleteOutdatedCaches.ts @@ -0,0 +1,55 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import '../_version.js'; + +// Give TypeScript the correct global. +declare let self: ServiceWorkerGlobalScope; + +const SUBSTRING_TO_FIND = '-precache-'; + +/** + * Cleans up incompatible precaches that were created by older versions of + * Workbox, by a service worker registered under the current scope. + * + * This is meant to be called as part of the `activate` event. + * + * This should be safe to use as long as you don't include `substringToFind` + * (defaulting to `-precache-`) in your non-precache cache names. + * + * @param {string} currentPrecacheName The cache name currently in use for + * precaching. This cache won't be deleted. + * @param {string} [substringToFind='-precache-'] Cache names which include this + * substring will be deleted (excluding `currentPrecacheName`). + * @return {Array} A list of all the cache names that were deleted. + * + * @private + * @memberof workbox-precaching + */ +const deleteOutdatedCaches = async ( + currentPrecacheName: string, + substringToFind: string = SUBSTRING_TO_FIND, +): Promise => { + const cacheNames = await self.caches.keys(); + + const cacheNamesToDelete = cacheNames.filter((cacheName) => { + return ( + cacheName.includes(substringToFind) && + cacheName.includes(self.registration.scope) && + cacheName !== currentPrecacheName + ); + }); + + await Promise.all( + cacheNamesToDelete.map((cacheName) => self.caches.delete(cacheName)), + ); + + return cacheNamesToDelete; +}; + +export {deleteOutdatedCaches}; diff --git a/node_modules/workbox-precaching/src/utils/generateURLVariations.ts b/node_modules/workbox-precaching/src/utils/generateURLVariations.ts new file mode 100644 index 0000000000000000000000000000000000000000..aa17d404254eeda3dbd0b50ba746ebc1e1b4ecd2 --- /dev/null +++ b/node_modules/workbox-precaching/src/utils/generateURLVariations.ts @@ -0,0 +1,60 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {removeIgnoredSearchParams} from './removeIgnoredSearchParams.js'; +import {PrecacheRouteOptions} from '../_types.js'; +import '../_version.js'; + +/** + * Generator function that yields possible variations on the original URL to + * check, one at a time. + * + * @param {string} url + * @param {Object} options + * + * @private + * @memberof workbox-precaching + */ +export function* generateURLVariations( + url: string, + { + ignoreURLParametersMatching = [/^utm_/, /^fbclid$/], + directoryIndex = 'index.html', + cleanURLs = true, + urlManipulation, + }: PrecacheRouteOptions = {}, +): Generator { + const urlObject = new URL(url, location.href); + urlObject.hash = ''; + yield urlObject.href; + + const urlWithoutIgnoredParams = removeIgnoredSearchParams( + urlObject, + ignoreURLParametersMatching, + ); + yield urlWithoutIgnoredParams.href; + + if (directoryIndex && urlWithoutIgnoredParams.pathname.endsWith('/')) { + const directoryURL = new URL(urlWithoutIgnoredParams.href); + directoryURL.pathname += directoryIndex; + yield directoryURL.href; + } + + if (cleanURLs) { + const cleanURL = new URL(urlWithoutIgnoredParams.href); + cleanURL.pathname += '.html'; + yield cleanURL.href; + } + + if (urlManipulation) { + const additionalURLs = urlManipulation({url: urlObject}); + for (const urlToAttempt of additionalURLs) { + yield urlToAttempt.href; + } + } +} diff --git a/node_modules/workbox-precaching/src/utils/getCacheKeyForURL.ts b/node_modules/workbox-precaching/src/utils/getCacheKeyForURL.ts new file mode 100644 index 0000000000000000000000000000000000000000..b58c41752107c1b0f9a2fa4471ec9a20d53a4c5d --- /dev/null +++ b/node_modules/workbox-precaching/src/utils/getCacheKeyForURL.ts @@ -0,0 +1,38 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {getOrCreatePrecacheController} from './getOrCreatePrecacheController.js'; +import {generateURLVariations} from './generateURLVariations.js'; +import {PrecacheRouteOptions} from '../_types.js'; +import '../_version.js'; + +/** + * This function will take the request URL and manipulate it based on the + * configuration options. + * + * @param {string} url + * @param {Object} options + * @return {string} Returns the URL in the cache that matches the request, + * if possible. + * + * @private + */ +export const getCacheKeyForURL = ( + url: string, + options: PrecacheRouteOptions, +): string | void => { + const precacheController = getOrCreatePrecacheController(); + + const urlsToCacheKeys = precacheController.getURLsToCacheKeys(); + for (const possibleURL of generateURLVariations(url, options)) { + const possibleCacheKey = urlsToCacheKeys.get(possibleURL); + if (possibleCacheKey) { + return possibleCacheKey; + } + } +}; diff --git a/node_modules/workbox-precaching/src/utils/getOrCreatePrecacheController.ts b/node_modules/workbox-precaching/src/utils/getOrCreatePrecacheController.ts new file mode 100644 index 0000000000000000000000000000000000000000..429650d44ada2ac960c72c0bc28a0dca51595947 --- /dev/null +++ b/node_modules/workbox-precaching/src/utils/getOrCreatePrecacheController.ts @@ -0,0 +1,23 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {PrecacheController} from '../PrecacheController.js'; +import '../_version.js'; + +let precacheController: PrecacheController | undefined; + +/** + * @return {PrecacheController} + * @private + */ +export const getOrCreatePrecacheController = (): PrecacheController => { + if (!precacheController) { + precacheController = new PrecacheController(); + } + return precacheController; +}; diff --git a/node_modules/workbox-precaching/src/utils/printCleanupDetails.ts b/node_modules/workbox-precaching/src/utils/printCleanupDetails.ts new file mode 100644 index 0000000000000000000000000000000000000000..68df0feeb7cb968d23e523cd615eafd6620eed28 --- /dev/null +++ b/node_modules/workbox-precaching/src/utils/printCleanupDetails.ts @@ -0,0 +1,45 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {logger} from 'workbox-core/_private/logger.js'; +import '../_version.js'; + +/** + * @param {string} groupTitle + * @param {Array} deletedURLs + * + * @private + */ +const logGroup = (groupTitle: string, deletedURLs: string[]) => { + logger.groupCollapsed(groupTitle); + + for (const url of deletedURLs) { + logger.log(url); + } + + logger.groupEnd(); +}; + +/** + * @param {Array} deletedURLs + * + * @private + * @memberof workbox-precaching + */ +export function printCleanupDetails(deletedURLs: string[]): void { + const deletionCount = deletedURLs.length; + if (deletionCount > 0) { + logger.groupCollapsed( + `During precaching cleanup, ` + + `${deletionCount} cached ` + + `request${deletionCount === 1 ? ' was' : 's were'} deleted.`, + ); + logGroup('Deleted Cache Requests', deletedURLs); + logger.groupEnd(); + } +} diff --git a/node_modules/workbox-precaching/src/utils/printInstallDetails.ts b/node_modules/workbox-precaching/src/utils/printInstallDetails.ts new file mode 100644 index 0000000000000000000000000000000000000000..8f74c58a320bafc87cf12e840f312ffa15632ae9 --- /dev/null +++ b/node_modules/workbox-precaching/src/utils/printInstallDetails.ts @@ -0,0 +1,63 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {logger} from 'workbox-core/_private/logger.js'; +import '../_version.js'; + +/** + * @param {string} groupTitle + * @param {Array} urls + * + * @private + */ +function _nestedGroup(groupTitle: string, urls: string[]): void { + if (urls.length === 0) { + return; + } + + logger.groupCollapsed(groupTitle); + + for (const url of urls) { + logger.log(url); + } + + logger.groupEnd(); +} + +/** + * @param {Array} urlsToPrecache + * @param {Array} urlsAlreadyPrecached + * + * @private + * @memberof workbox-precaching + */ +export function printInstallDetails( + urlsToPrecache: string[], + urlsAlreadyPrecached: string[], +): void { + const precachedCount = urlsToPrecache.length; + const alreadyPrecachedCount = urlsAlreadyPrecached.length; + + if (precachedCount || alreadyPrecachedCount) { + let message = `Precaching ${precachedCount} file${ + precachedCount === 1 ? '' : 's' + }.`; + + if (alreadyPrecachedCount > 0) { + message += + ` ${alreadyPrecachedCount} ` + + `file${alreadyPrecachedCount === 1 ? ' is' : 's are'} already cached.`; + } + + logger.groupCollapsed(message); + + _nestedGroup(`View newly precached URLs.`, urlsToPrecache); + _nestedGroup(`View previously precached URLs.`, urlsAlreadyPrecached); + logger.groupEnd(); + } +} diff --git a/node_modules/workbox-precaching/src/utils/removeIgnoredSearchParams.ts b/node_modules/workbox-precaching/src/utils/removeIgnoredSearchParams.ts new file mode 100644 index 0000000000000000000000000000000000000000..1b02dfe7041d6b7b87bcf640e1edea828bb782f7 --- /dev/null +++ b/node_modules/workbox-precaching/src/utils/removeIgnoredSearchParams.ts @@ -0,0 +1,36 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import '../_version.js'; + +/** + * Removes any URL search parameters that should be ignored. + * + * @param {URL} urlObject The original URL. + * @param {Array} ignoreURLParametersMatching RegExps to test against + * each search parameter name. Matches mean that the search parameter should be + * ignored. + * @return {URL} The URL with any ignored search parameters removed. + * + * @private + * @memberof workbox-precaching + */ +export function removeIgnoredSearchParams( + urlObject: URL, + ignoreURLParametersMatching: RegExp[] = [], +): URL { + // Convert the iterable into an array at the start of the loop to make sure + // deletion doesn't mess up iteration. + for (const paramName of [...urlObject.searchParams.keys()]) { + if (ignoreURLParametersMatching.some((regExp) => regExp.test(paramName))) { + urlObject.searchParams.delete(paramName); + } + } + + return urlObject; +} diff --git a/node_modules/workbox-precaching/tsconfig.json b/node_modules/workbox-precaching/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..ff2b28d5b864204f1e20b69d0250b2b2f48535c0 --- /dev/null +++ b/node_modules/workbox-precaching/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../tsconfig", + "compilerOptions": { + "outDir": "./", + "rootDir": "./src", + "tsBuildInfoFile": "./tsconfig.tsbuildinfo" + }, + "include": ["src/**/*.ts"], + "references": [ + {"path": "../workbox-core/"}, + {"path": "../workbox-routing/"}, + {"path": "../workbox-strategies/"} + ] +} diff --git a/node_modules/workbox-precaching/utils/PrecacheCacheKeyPlugin.d.ts b/node_modules/workbox-precaching/utils/PrecacheCacheKeyPlugin.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4159082c6d7e7b40590802a0e669feb38f8fb070 --- /dev/null +++ b/node_modules/workbox-precaching/utils/PrecacheCacheKeyPlugin.d.ts @@ -0,0 +1,17 @@ +import { WorkboxPlugin } from 'workbox-core/types.js'; +import { PrecacheController } from '../PrecacheController.js'; +import '../_version.js'; +/** + * A plugin, designed to be used with PrecacheController, to translate URLs into + * the corresponding cache key, based on the current revision info. + * + * @private + */ +declare class PrecacheCacheKeyPlugin implements WorkboxPlugin { + private readonly _precacheController; + constructor({ precacheController }: { + precacheController: PrecacheController; + }); + cacheKeyWillBeUsed: WorkboxPlugin['cacheKeyWillBeUsed']; +} +export { PrecacheCacheKeyPlugin }; diff --git a/node_modules/workbox-precaching/utils/PrecacheCacheKeyPlugin.js b/node_modules/workbox-precaching/utils/PrecacheCacheKeyPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..70007446012f48874ebd8924c82af8f6acdec94b --- /dev/null +++ b/node_modules/workbox-precaching/utils/PrecacheCacheKeyPlugin.js @@ -0,0 +1,30 @@ +/* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import '../_version.js'; +/** + * A plugin, designed to be used with PrecacheController, to translate URLs into + * the corresponding cache key, based on the current revision info. + * + * @private + */ +class PrecacheCacheKeyPlugin { + constructor({ precacheController }) { + this.cacheKeyWillBeUsed = async ({ request, params, }) => { + // Params is type any, can't change right now. + /* eslint-disable */ + const cacheKey = (params === null || params === void 0 ? void 0 : params.cacheKey) || + this._precacheController.getCacheKeyForURL(request.url); + /* eslint-enable */ + return cacheKey + ? new Request(cacheKey, { headers: request.headers }) + : request; + }; + this._precacheController = precacheController; + } +} +export { PrecacheCacheKeyPlugin }; diff --git a/node_modules/workbox-precaching/utils/PrecacheCacheKeyPlugin.mjs b/node_modules/workbox-precaching/utils/PrecacheCacheKeyPlugin.mjs new file mode 100644 index 0000000000000000000000000000000000000000..579827e9e0be8804d68076f915fea3244779162c --- /dev/null +++ b/node_modules/workbox-precaching/utils/PrecacheCacheKeyPlugin.mjs @@ -0,0 +1 @@ +export * from './PrecacheCacheKeyPlugin.js'; \ No newline at end of file diff --git a/node_modules/workbox-precaching/utils/PrecacheInstallReportPlugin.d.ts b/node_modules/workbox-precaching/utils/PrecacheInstallReportPlugin.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fb152b9dd3cf3ea62544678c6a1ea8c23f23048a --- /dev/null +++ b/node_modules/workbox-precaching/utils/PrecacheInstallReportPlugin.d.ts @@ -0,0 +1,15 @@ +import { WorkboxPlugin } from 'workbox-core/types.js'; +import '../_version.js'; +/** + * A plugin, designed to be used with PrecacheController, to determine the + * of assets that were updated (or not updated) during the install event. + * + * @private + */ +declare class PrecacheInstallReportPlugin implements WorkboxPlugin { + updatedURLs: string[]; + notUpdatedURLs: string[]; + handlerWillStart: WorkboxPlugin['handlerWillStart']; + cachedResponseWillBeUsed: WorkboxPlugin['cachedResponseWillBeUsed']; +} +export { PrecacheInstallReportPlugin }; diff --git a/node_modules/workbox-precaching/utils/PrecacheInstallReportPlugin.js b/node_modules/workbox-precaching/utils/PrecacheInstallReportPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..3fb1cb696bfdcc29fd9d3ee1e748a5a515af2e41 --- /dev/null +++ b/node_modules/workbox-precaching/utils/PrecacheInstallReportPlugin.js @@ -0,0 +1,44 @@ +/* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import '../_version.js'; +/** + * A plugin, designed to be used with PrecacheController, to determine the + * of assets that were updated (or not updated) during the install event. + * + * @private + */ +class PrecacheInstallReportPlugin { + constructor() { + this.updatedURLs = []; + this.notUpdatedURLs = []; + this.handlerWillStart = async ({ request, state, }) => { + // TODO: `state` should never be undefined... + if (state) { + state.originalRequest = request; + } + }; + this.cachedResponseWillBeUsed = async ({ event, state, cachedResponse, }) => { + if (event.type === 'install') { + if (state && + state.originalRequest && + state.originalRequest instanceof Request) { + // TODO: `state` should never be undefined... + const url = state.originalRequest.url; + if (cachedResponse) { + this.notUpdatedURLs.push(url); + } + else { + this.updatedURLs.push(url); + } + } + } + return cachedResponse; + }; + } +} +export { PrecacheInstallReportPlugin }; diff --git a/node_modules/workbox-precaching/utils/PrecacheInstallReportPlugin.mjs b/node_modules/workbox-precaching/utils/PrecacheInstallReportPlugin.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2fd1a14ee3ccf688c4d80558a6c40528f9cfdb82 --- /dev/null +++ b/node_modules/workbox-precaching/utils/PrecacheInstallReportPlugin.mjs @@ -0,0 +1 @@ +export * from './PrecacheInstallReportPlugin.js'; \ No newline at end of file diff --git a/node_modules/workbox-precaching/utils/createCacheKey.d.ts b/node_modules/workbox-precaching/utils/createCacheKey.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4b9596c77a23e38724cea75a89cdc4e983b2cfac --- /dev/null +++ b/node_modules/workbox-precaching/utils/createCacheKey.d.ts @@ -0,0 +1,17 @@ +import { PrecacheEntry } from '../_types.js'; +import '../_version.js'; +interface CacheKey { + cacheKey: string; + url: string; +} +/** + * Converts a manifest entry into a versioned URL suitable for precaching. + * + * @param {Object|string} entry + * @return {string} A URL with versioning info. + * + * @private + * @memberof workbox-precaching + */ +export declare function createCacheKey(entry: PrecacheEntry | string): CacheKey; +export {}; diff --git a/node_modules/workbox-precaching/utils/createCacheKey.js b/node_modules/workbox-precaching/utils/createCacheKey.js new file mode 100644 index 0000000000000000000000000000000000000000..a4f20cdcafd00a1bfddd55ae3690f3cd67d3eb62 --- /dev/null +++ b/node_modules/workbox-precaching/utils/createCacheKey.js @@ -0,0 +1,56 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { WorkboxError } from 'workbox-core/_private/WorkboxError.js'; +import '../_version.js'; +// Name of the search parameter used to store revision info. +const REVISION_SEARCH_PARAM = '__WB_REVISION__'; +/** + * Converts a manifest entry into a versioned URL suitable for precaching. + * + * @param {Object|string} entry + * @return {string} A URL with versioning info. + * + * @private + * @memberof workbox-precaching + */ +export function createCacheKey(entry) { + if (!entry) { + throw new WorkboxError('add-to-cache-list-unexpected-type', { entry }); + } + // If a precache manifest entry is a string, it's assumed to be a versioned + // URL, like '/app.abcd1234.js'. Return as-is. + if (typeof entry === 'string') { + const urlObject = new URL(entry, location.href); + return { + cacheKey: urlObject.href, + url: urlObject.href, + }; + } + const { revision, url } = entry; + if (!url) { + throw new WorkboxError('add-to-cache-list-unexpected-type', { entry }); + } + // If there's just a URL and no revision, then it's also assumed to be a + // versioned URL. + if (!revision) { + const urlObject = new URL(url, location.href); + return { + cacheKey: urlObject.href, + url: urlObject.href, + }; + } + // Otherwise, construct a properly versioned URL using the custom Workbox + // search parameter along with the revision info. + const cacheKeyURL = new URL(url, location.href); + const originalURL = new URL(url, location.href); + cacheKeyURL.searchParams.set(REVISION_SEARCH_PARAM, revision); + return { + cacheKey: cacheKeyURL.href, + url: originalURL.href, + }; +} diff --git a/node_modules/workbox-precaching/utils/createCacheKey.mjs b/node_modules/workbox-precaching/utils/createCacheKey.mjs new file mode 100644 index 0000000000000000000000000000000000000000..559f584ac6114996bc8410ac6d0551d2fb259618 --- /dev/null +++ b/node_modules/workbox-precaching/utils/createCacheKey.mjs @@ -0,0 +1 @@ +export * from './createCacheKey.js'; \ No newline at end of file diff --git a/node_modules/workbox-precaching/utils/deleteOutdatedCaches.d.ts b/node_modules/workbox-precaching/utils/deleteOutdatedCaches.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2f5ae807efbdf15464e0a43aecf6b4913975752e --- /dev/null +++ b/node_modules/workbox-precaching/utils/deleteOutdatedCaches.d.ts @@ -0,0 +1,21 @@ +import '../_version.js'; +/** + * Cleans up incompatible precaches that were created by older versions of + * Workbox, by a service worker registered under the current scope. + * + * This is meant to be called as part of the `activate` event. + * + * This should be safe to use as long as you don't include `substringToFind` + * (defaulting to `-precache-`) in your non-precache cache names. + * + * @param {string} currentPrecacheName The cache name currently in use for + * precaching. This cache won't be deleted. + * @param {string} [substringToFind='-precache-'] Cache names which include this + * substring will be deleted (excluding `currentPrecacheName`). + * @return {Array} A list of all the cache names that were deleted. + * + * @private + * @memberof workbox-precaching + */ +declare const deleteOutdatedCaches: (currentPrecacheName: string, substringToFind?: string) => Promise; +export { deleteOutdatedCaches }; diff --git a/node_modules/workbox-precaching/utils/deleteOutdatedCaches.js b/node_modules/workbox-precaching/utils/deleteOutdatedCaches.js new file mode 100644 index 0000000000000000000000000000000000000000..aeef71383d2306399cff01044df658e3c829246e --- /dev/null +++ b/node_modules/workbox-precaching/utils/deleteOutdatedCaches.js @@ -0,0 +1,38 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import '../_version.js'; +const SUBSTRING_TO_FIND = '-precache-'; +/** + * Cleans up incompatible precaches that were created by older versions of + * Workbox, by a service worker registered under the current scope. + * + * This is meant to be called as part of the `activate` event. + * + * This should be safe to use as long as you don't include `substringToFind` + * (defaulting to `-precache-`) in your non-precache cache names. + * + * @param {string} currentPrecacheName The cache name currently in use for + * precaching. This cache won't be deleted. + * @param {string} [substringToFind='-precache-'] Cache names which include this + * substring will be deleted (excluding `currentPrecacheName`). + * @return {Array} A list of all the cache names that were deleted. + * + * @private + * @memberof workbox-precaching + */ +const deleteOutdatedCaches = async (currentPrecacheName, substringToFind = SUBSTRING_TO_FIND) => { + const cacheNames = await self.caches.keys(); + const cacheNamesToDelete = cacheNames.filter((cacheName) => { + return (cacheName.includes(substringToFind) && + cacheName.includes(self.registration.scope) && + cacheName !== currentPrecacheName); + }); + await Promise.all(cacheNamesToDelete.map((cacheName) => self.caches.delete(cacheName))); + return cacheNamesToDelete; +}; +export { deleteOutdatedCaches }; diff --git a/node_modules/workbox-precaching/utils/deleteOutdatedCaches.mjs b/node_modules/workbox-precaching/utils/deleteOutdatedCaches.mjs new file mode 100644 index 0000000000000000000000000000000000000000..03cbf0907f0be1f7f9bea03f28123dc7f044bf18 --- /dev/null +++ b/node_modules/workbox-precaching/utils/deleteOutdatedCaches.mjs @@ -0,0 +1 @@ +export * from './deleteOutdatedCaches.js'; \ No newline at end of file diff --git a/node_modules/workbox-precaching/utils/generateURLVariations.d.ts b/node_modules/workbox-precaching/utils/generateURLVariations.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b7f9b6a4d78f86141072270695d9220382d9279b --- /dev/null +++ b/node_modules/workbox-precaching/utils/generateURLVariations.d.ts @@ -0,0 +1,13 @@ +import { PrecacheRouteOptions } from '../_types.js'; +import '../_version.js'; +/** + * Generator function that yields possible variations on the original URL to + * check, one at a time. + * + * @param {string} url + * @param {Object} options + * + * @private + * @memberof workbox-precaching + */ +export declare function generateURLVariations(url: string, { ignoreURLParametersMatching, directoryIndex, cleanURLs, urlManipulation, }?: PrecacheRouteOptions): Generator; diff --git a/node_modules/workbox-precaching/utils/generateURLVariations.js b/node_modules/workbox-precaching/utils/generateURLVariations.js new file mode 100644 index 0000000000000000000000000000000000000000..eddb6ce51d7839f7dd3fe793911a0fc1d6ca042a --- /dev/null +++ b/node_modules/workbox-precaching/utils/generateURLVariations.js @@ -0,0 +1,42 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { removeIgnoredSearchParams } from './removeIgnoredSearchParams.js'; +import '../_version.js'; +/** + * Generator function that yields possible variations on the original URL to + * check, one at a time. + * + * @param {string} url + * @param {Object} options + * + * @private + * @memberof workbox-precaching + */ +export function* generateURLVariations(url, { ignoreURLParametersMatching = [/^utm_/, /^fbclid$/], directoryIndex = 'index.html', cleanURLs = true, urlManipulation, } = {}) { + const urlObject = new URL(url, location.href); + urlObject.hash = ''; + yield urlObject.href; + const urlWithoutIgnoredParams = removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching); + yield urlWithoutIgnoredParams.href; + if (directoryIndex && urlWithoutIgnoredParams.pathname.endsWith('/')) { + const directoryURL = new URL(urlWithoutIgnoredParams.href); + directoryURL.pathname += directoryIndex; + yield directoryURL.href; + } + if (cleanURLs) { + const cleanURL = new URL(urlWithoutIgnoredParams.href); + cleanURL.pathname += '.html'; + yield cleanURL.href; + } + if (urlManipulation) { + const additionalURLs = urlManipulation({ url: urlObject }); + for (const urlToAttempt of additionalURLs) { + yield urlToAttempt.href; + } + } +} diff --git a/node_modules/workbox-precaching/utils/generateURLVariations.mjs b/node_modules/workbox-precaching/utils/generateURLVariations.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b936b1ea0fc0ab15e147fd90fcbcafcae5dbf0f1 --- /dev/null +++ b/node_modules/workbox-precaching/utils/generateURLVariations.mjs @@ -0,0 +1 @@ +export * from './generateURLVariations.js'; \ No newline at end of file diff --git a/node_modules/workbox-precaching/utils/getCacheKeyForURL.d.ts b/node_modules/workbox-precaching/utils/getCacheKeyForURL.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8612f7db99dd89b75cad114237fa411fb5238004 --- /dev/null +++ b/node_modules/workbox-precaching/utils/getCacheKeyForURL.d.ts @@ -0,0 +1,14 @@ +import { PrecacheRouteOptions } from '../_types.js'; +import '../_version.js'; +/** + * This function will take the request URL and manipulate it based on the + * configuration options. + * + * @param {string} url + * @param {Object} options + * @return {string} Returns the URL in the cache that matches the request, + * if possible. + * + * @private + */ +export declare const getCacheKeyForURL: (url: string, options: PrecacheRouteOptions) => string | void; diff --git a/node_modules/workbox-precaching/utils/getCacheKeyForURL.js b/node_modules/workbox-precaching/utils/getCacheKeyForURL.js new file mode 100644 index 0000000000000000000000000000000000000000..f83276e67eedc4784ef49a16c7a5213ec8eaaa73 --- /dev/null +++ b/node_modules/workbox-precaching/utils/getCacheKeyForURL.js @@ -0,0 +1,31 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { getOrCreatePrecacheController } from './getOrCreatePrecacheController.js'; +import { generateURLVariations } from './generateURLVariations.js'; +import '../_version.js'; +/** + * This function will take the request URL and manipulate it based on the + * configuration options. + * + * @param {string} url + * @param {Object} options + * @return {string} Returns the URL in the cache that matches the request, + * if possible. + * + * @private + */ +export const getCacheKeyForURL = (url, options) => { + const precacheController = getOrCreatePrecacheController(); + const urlsToCacheKeys = precacheController.getURLsToCacheKeys(); + for (const possibleURL of generateURLVariations(url, options)) { + const possibleCacheKey = urlsToCacheKeys.get(possibleURL); + if (possibleCacheKey) { + return possibleCacheKey; + } + } +}; diff --git a/node_modules/workbox-precaching/utils/getCacheKeyForURL.mjs b/node_modules/workbox-precaching/utils/getCacheKeyForURL.mjs new file mode 100644 index 0000000000000000000000000000000000000000..04413e30927761b5be55f080a991e5466ae5178e --- /dev/null +++ b/node_modules/workbox-precaching/utils/getCacheKeyForURL.mjs @@ -0,0 +1 @@ +export * from './getCacheKeyForURL.js'; \ No newline at end of file diff --git a/node_modules/workbox-precaching/utils/getOrCreatePrecacheController.d.ts b/node_modules/workbox-precaching/utils/getOrCreatePrecacheController.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c8524fe4ac447a065650e1f0ee6ba1c419b5a87d --- /dev/null +++ b/node_modules/workbox-precaching/utils/getOrCreatePrecacheController.d.ts @@ -0,0 +1,7 @@ +import { PrecacheController } from '../PrecacheController.js'; +import '../_version.js'; +/** + * @return {PrecacheController} + * @private + */ +export declare const getOrCreatePrecacheController: () => PrecacheController; diff --git a/node_modules/workbox-precaching/utils/getOrCreatePrecacheController.js b/node_modules/workbox-precaching/utils/getOrCreatePrecacheController.js new file mode 100644 index 0000000000000000000000000000000000000000..8fbf3a17fdc6b7d4cfbc2f07261c918247c8b6db --- /dev/null +++ b/node_modules/workbox-precaching/utils/getOrCreatePrecacheController.js @@ -0,0 +1,20 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { PrecacheController } from '../PrecacheController.js'; +import '../_version.js'; +let precacheController; +/** + * @return {PrecacheController} + * @private + */ +export const getOrCreatePrecacheController = () => { + if (!precacheController) { + precacheController = new PrecacheController(); + } + return precacheController; +}; diff --git a/node_modules/workbox-precaching/utils/getOrCreatePrecacheController.mjs b/node_modules/workbox-precaching/utils/getOrCreatePrecacheController.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c8b64d28e0a2346f628310cf482663f171f62af5 --- /dev/null +++ b/node_modules/workbox-precaching/utils/getOrCreatePrecacheController.mjs @@ -0,0 +1 @@ +export * from './getOrCreatePrecacheController.js'; \ No newline at end of file diff --git a/node_modules/workbox-precaching/utils/printCleanupDetails.d.ts b/node_modules/workbox-precaching/utils/printCleanupDetails.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0ed415ef6ba4ca0a7c8b54b36b123f645b46ac67 --- /dev/null +++ b/node_modules/workbox-precaching/utils/printCleanupDetails.d.ts @@ -0,0 +1,8 @@ +import '../_version.js'; +/** + * @param {Array} deletedURLs + * + * @private + * @memberof workbox-precaching + */ +export declare function printCleanupDetails(deletedURLs: string[]): void; diff --git a/node_modules/workbox-precaching/utils/printCleanupDetails.js b/node_modules/workbox-precaching/utils/printCleanupDetails.js new file mode 100644 index 0000000000000000000000000000000000000000..f6da6b3780d15c6424d5324e073101928f993f42 --- /dev/null +++ b/node_modules/workbox-precaching/utils/printCleanupDetails.js @@ -0,0 +1,38 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { logger } from 'workbox-core/_private/logger.js'; +import '../_version.js'; +/** + * @param {string} groupTitle + * @param {Array} deletedURLs + * + * @private + */ +const logGroup = (groupTitle, deletedURLs) => { + logger.groupCollapsed(groupTitle); + for (const url of deletedURLs) { + logger.log(url); + } + logger.groupEnd(); +}; +/** + * @param {Array} deletedURLs + * + * @private + * @memberof workbox-precaching + */ +export function printCleanupDetails(deletedURLs) { + const deletionCount = deletedURLs.length; + if (deletionCount > 0) { + logger.groupCollapsed(`During precaching cleanup, ` + + `${deletionCount} cached ` + + `request${deletionCount === 1 ? ' was' : 's were'} deleted.`); + logGroup('Deleted Cache Requests', deletedURLs); + logger.groupEnd(); + } +} diff --git a/node_modules/workbox-precaching/utils/printCleanupDetails.mjs b/node_modules/workbox-precaching/utils/printCleanupDetails.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3bd27e1eb2aeab1dd1eb5f81ae395891eda2c605 --- /dev/null +++ b/node_modules/workbox-precaching/utils/printCleanupDetails.mjs @@ -0,0 +1 @@ +export * from './printCleanupDetails.js'; \ No newline at end of file diff --git a/node_modules/workbox-precaching/utils/printInstallDetails.d.ts b/node_modules/workbox-precaching/utils/printInstallDetails.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f6f4bb90ae988232826703386c8a44470dd1d6da --- /dev/null +++ b/node_modules/workbox-precaching/utils/printInstallDetails.d.ts @@ -0,0 +1,9 @@ +import '../_version.js'; +/** + * @param {Array} urlsToPrecache + * @param {Array} urlsAlreadyPrecached + * + * @private + * @memberof workbox-precaching + */ +export declare function printInstallDetails(urlsToPrecache: string[], urlsAlreadyPrecached: string[]): void; diff --git a/node_modules/workbox-precaching/utils/printInstallDetails.js b/node_modules/workbox-precaching/utils/printInstallDetails.js new file mode 100644 index 0000000000000000000000000000000000000000..e2c0b90ae37ce798dc9d143c34326bd101e5189c --- /dev/null +++ b/node_modules/workbox-precaching/utils/printInstallDetails.js @@ -0,0 +1,48 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { logger } from 'workbox-core/_private/logger.js'; +import '../_version.js'; +/** + * @param {string} groupTitle + * @param {Array} urls + * + * @private + */ +function _nestedGroup(groupTitle, urls) { + if (urls.length === 0) { + return; + } + logger.groupCollapsed(groupTitle); + for (const url of urls) { + logger.log(url); + } + logger.groupEnd(); +} +/** + * @param {Array} urlsToPrecache + * @param {Array} urlsAlreadyPrecached + * + * @private + * @memberof workbox-precaching + */ +export function printInstallDetails(urlsToPrecache, urlsAlreadyPrecached) { + const precachedCount = urlsToPrecache.length; + const alreadyPrecachedCount = urlsAlreadyPrecached.length; + if (precachedCount || alreadyPrecachedCount) { + let message = `Precaching ${precachedCount} file${precachedCount === 1 ? '' : 's'}.`; + if (alreadyPrecachedCount > 0) { + message += + ` ${alreadyPrecachedCount} ` + + `file${alreadyPrecachedCount === 1 ? ' is' : 's are'} already cached.`; + } + logger.groupCollapsed(message); + _nestedGroup(`View newly precached URLs.`, urlsToPrecache); + _nestedGroup(`View previously precached URLs.`, urlsAlreadyPrecached); + logger.groupEnd(); + } +} diff --git a/node_modules/workbox-precaching/utils/printInstallDetails.mjs b/node_modules/workbox-precaching/utils/printInstallDetails.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7427057bc6d433932bf253b192fac55580e1b37b --- /dev/null +++ b/node_modules/workbox-precaching/utils/printInstallDetails.mjs @@ -0,0 +1 @@ +export * from './printInstallDetails.js'; \ No newline at end of file diff --git a/node_modules/workbox-precaching/utils/removeIgnoredSearchParams.d.ts b/node_modules/workbox-precaching/utils/removeIgnoredSearchParams.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0202c891683e0c714a8fa592f1292d33ccfdc9ad --- /dev/null +++ b/node_modules/workbox-precaching/utils/removeIgnoredSearchParams.d.ts @@ -0,0 +1,14 @@ +import '../_version.js'; +/** + * Removes any URL search parameters that should be ignored. + * + * @param {URL} urlObject The original URL. + * @param {Array} ignoreURLParametersMatching RegExps to test against + * each search parameter name. Matches mean that the search parameter should be + * ignored. + * @return {URL} The URL with any ignored search parameters removed. + * + * @private + * @memberof workbox-precaching + */ +export declare function removeIgnoredSearchParams(urlObject: URL, ignoreURLParametersMatching?: RegExp[]): URL; diff --git a/node_modules/workbox-precaching/utils/removeIgnoredSearchParams.js b/node_modules/workbox-precaching/utils/removeIgnoredSearchParams.js new file mode 100644 index 0000000000000000000000000000000000000000..d783ba8825bd374cbd3e18238b38751820fd7122 --- /dev/null +++ b/node_modules/workbox-precaching/utils/removeIgnoredSearchParams.js @@ -0,0 +1,30 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import '../_version.js'; +/** + * Removes any URL search parameters that should be ignored. + * + * @param {URL} urlObject The original URL. + * @param {Array} ignoreURLParametersMatching RegExps to test against + * each search parameter name. Matches mean that the search parameter should be + * ignored. + * @return {URL} The URL with any ignored search parameters removed. + * + * @private + * @memberof workbox-precaching + */ +export function removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching = []) { + // Convert the iterable into an array at the start of the loop to make sure + // deletion doesn't mess up iteration. + for (const paramName of [...urlObject.searchParams.keys()]) { + if (ignoreURLParametersMatching.some((regExp) => regExp.test(paramName))) { + urlObject.searchParams.delete(paramName); + } + } + return urlObject; +} diff --git a/node_modules/workbox-precaching/utils/removeIgnoredSearchParams.mjs b/node_modules/workbox-precaching/utils/removeIgnoredSearchParams.mjs new file mode 100644 index 0000000000000000000000000000000000000000..82105f9bc3e6b5a6c9fdb8df6e309f9e8383a907 --- /dev/null +++ b/node_modules/workbox-precaching/utils/removeIgnoredSearchParams.mjs @@ -0,0 +1 @@ +export * from './removeIgnoredSearchParams.js'; \ No newline at end of file diff --git a/node_modules/workbox-range-requests/LICENSE b/node_modules/workbox-range-requests/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..845b545fd0f5031a944cda8cf9018eb066500040 --- /dev/null +++ b/node_modules/workbox-range-requests/LICENSE @@ -0,0 +1,19 @@ +Copyright 2018 Google LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/workbox-range-requests/README.md b/node_modules/workbox-range-requests/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ac4afc6fd88dbff78f75a6a32a27983ada6b43a3 --- /dev/null +++ b/node_modules/workbox-range-requests/README.md @@ -0,0 +1 @@ +This module's documentation can be found at https://developers.google.com/web/tools/workbox/modules/workbox-range-requests diff --git a/node_modules/workbox-range-requests/RangeRequestsPlugin.d.ts b/node_modules/workbox-range-requests/RangeRequestsPlugin.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..35e241aa0fd4a50f2357d7aa1f16ff0b18641437 --- /dev/null +++ b/node_modules/workbox-range-requests/RangeRequestsPlugin.d.ts @@ -0,0 +1,26 @@ +import { WorkboxPlugin } from 'workbox-core/types.js'; +import './_version.js'; +/** + * The range request plugin makes it easy for a request with a 'Range' header to + * be fulfilled by a cached response. + * + * It does this by intercepting the `cachedResponseWillBeUsed` plugin callback + * and returning the appropriate subset of the cached response body. + * + * @memberof workbox-range-requests + */ +declare class RangeRequestsPlugin implements WorkboxPlugin { + /** + * @param {Object} options + * @param {Request} options.request The original request, which may or may not + * contain a Range: header. + * @param {Response} options.cachedResponse The complete cached response. + * @return {Promise} If request contains a 'Range' header, then a + * new response with status 206 whose body is a subset of `cachedResponse` is + * returned. Otherwise, `cachedResponse` is returned as-is. + * + * @private + */ + cachedResponseWillBeUsed: WorkboxPlugin['cachedResponseWillBeUsed']; +} +export { RangeRequestsPlugin }; diff --git a/node_modules/workbox-range-requests/RangeRequestsPlugin.js b/node_modules/workbox-range-requests/RangeRequestsPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..35d77877c347c5745577aeae650919de2fb3ad9b --- /dev/null +++ b/node_modules/workbox-range-requests/RangeRequestsPlugin.js @@ -0,0 +1,44 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { createPartialResponse } from './createPartialResponse.js'; +import './_version.js'; +/** + * The range request plugin makes it easy for a request with a 'Range' header to + * be fulfilled by a cached response. + * + * It does this by intercepting the `cachedResponseWillBeUsed` plugin callback + * and returning the appropriate subset of the cached response body. + * + * @memberof workbox-range-requests + */ +class RangeRequestsPlugin { + constructor() { + /** + * @param {Object} options + * @param {Request} options.request The original request, which may or may not + * contain a Range: header. + * @param {Response} options.cachedResponse The complete cached response. + * @return {Promise} If request contains a 'Range' header, then a + * new response with status 206 whose body is a subset of `cachedResponse` is + * returned. Otherwise, `cachedResponse` is returned as-is. + * + * @private + */ + this.cachedResponseWillBeUsed = async ({ request, cachedResponse, }) => { + // Only return a sliced response if there's something valid in the cache, + // and there's a Range: header in the request. + if (cachedResponse && request.headers.has('range')) { + return await createPartialResponse(request, cachedResponse); + } + // If there was no Range: header, or if cachedResponse wasn't valid, just + // pass it through as-is. + return cachedResponse; + }; + } +} +export { RangeRequestsPlugin }; diff --git a/node_modules/workbox-range-requests/RangeRequestsPlugin.mjs b/node_modules/workbox-range-requests/RangeRequestsPlugin.mjs new file mode 100644 index 0000000000000000000000000000000000000000..10aa495d58ec8d2e8a07ccef99591edac6280a58 --- /dev/null +++ b/node_modules/workbox-range-requests/RangeRequestsPlugin.mjs @@ -0,0 +1 @@ +export * from './RangeRequestsPlugin.js'; \ No newline at end of file diff --git a/node_modules/workbox-range-requests/_version.d.ts b/node_modules/workbox-range-requests/_version.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/workbox-range-requests/_version.js b/node_modules/workbox-range-requests/_version.js new file mode 100644 index 0000000000000000000000000000000000000000..869636eb16bf0d8af299739fb4a413da3cfd4b8f --- /dev/null +++ b/node_modules/workbox-range-requests/_version.js @@ -0,0 +1,6 @@ +"use strict"; +// @ts-ignore +try { + self['workbox:range-requests:7.4.0'] && _(); +} +catch (e) { } diff --git a/node_modules/workbox-range-requests/_version.mjs b/node_modules/workbox-range-requests/_version.mjs new file mode 100644 index 0000000000000000000000000000000000000000..eea9088de15fce8500b25af6336738244b85a22a --- /dev/null +++ b/node_modules/workbox-range-requests/_version.mjs @@ -0,0 +1 @@ +try{self['workbox:range-requests:7.4.1']&&_()}catch(e){}// eslint-disable-line \ No newline at end of file diff --git a/node_modules/workbox-range-requests/build/workbox-range-requests.dev.js b/node_modules/workbox-range-requests/build/workbox-range-requests.dev.js new file mode 100644 index 0000000000000000000000000000000000000000..9225f0065ad1030eae10c86ff973fb4d737b2715 --- /dev/null +++ b/node_modules/workbox-range-requests/build/workbox-range-requests.dev.js @@ -0,0 +1,242 @@ +this.workbox = this.workbox || {}; +this.workbox.rangeRequests = (function (exports, WorkboxError_js, assert_js, logger_js) { + 'use strict'; + + // @ts-ignore + try { + self['workbox:range-requests:7.4.0'] && _(); + } catch (e) {} + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * @param {Blob} blob A source blob. + * @param {number} [start] The offset to use as the start of the + * slice. + * @param {number} [end] The offset to use as the end of the slice. + * @return {Object} An object with `start` and `end` properties, reflecting + * the effective boundaries to use given the size of the blob. + * + * @private + */ + function calculateEffectiveBoundaries(blob, start, end) { + { + assert_js.assert.isInstance(blob, Blob, { + moduleName: 'workbox-range-requests', + funcName: 'calculateEffectiveBoundaries', + paramName: 'blob' + }); + } + const blobSize = blob.size; + if (end && end > blobSize || start && start < 0) { + throw new WorkboxError_js.WorkboxError('range-not-satisfiable', { + size: blobSize, + end, + start + }); + } + let effectiveStart; + let effectiveEnd; + if (start !== undefined && end !== undefined) { + effectiveStart = start; + // Range values are inclusive, so add 1 to the value. + effectiveEnd = end + 1; + } else if (start !== undefined && end === undefined) { + effectiveStart = start; + effectiveEnd = blobSize; + } else if (end !== undefined && start === undefined) { + effectiveStart = blobSize - end; + effectiveEnd = blobSize; + } + return { + start: effectiveStart, + end: effectiveEnd + }; + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * @param {string} rangeHeader A Range: header value. + * @return {Object} An object with `start` and `end` properties, reflecting + * the parsed value of the Range: header. If either the `start` or `end` are + * omitted, then `null` will be returned. + * + * @private + */ + function parseRangeHeader(rangeHeader) { + { + assert_js.assert.isType(rangeHeader, 'string', { + moduleName: 'workbox-range-requests', + funcName: 'parseRangeHeader', + paramName: 'rangeHeader' + }); + } + const normalizedRangeHeader = rangeHeader.trim().toLowerCase(); + if (!normalizedRangeHeader.startsWith('bytes=')) { + throw new WorkboxError_js.WorkboxError('unit-must-be-bytes', { + normalizedRangeHeader + }); + } + // Specifying multiple ranges separate by commas is valid syntax, but this + // library only attempts to handle a single, contiguous sequence of bytes. + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range#Syntax + if (normalizedRangeHeader.includes(',')) { + throw new WorkboxError_js.WorkboxError('single-range-only', { + normalizedRangeHeader + }); + } + const rangeParts = /(\d*)-(\d*)/.exec(normalizedRangeHeader); + // We need either at least one of the start or end values. + if (!rangeParts || !(rangeParts[1] || rangeParts[2])) { + throw new WorkboxError_js.WorkboxError('invalid-range-values', { + normalizedRangeHeader + }); + } + return { + start: rangeParts[1] === '' ? undefined : Number(rangeParts[1]), + end: rangeParts[2] === '' ? undefined : Number(rangeParts[2]) + }; + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Given a `Request` and `Response` objects as input, this will return a + * promise for a new `Response`. + * + * If the original `Response` already contains partial content (i.e. it has + * a status of 206), then this assumes it already fulfills the `Range:` + * requirements, and will return it as-is. + * + * @param {Request} request A request, which should contain a Range: + * header. + * @param {Response} originalResponse A response. + * @return {Promise} Either a `206 Partial Content` response, with + * the response body set to the slice of content specified by the request's + * `Range:` header, or a `416 Range Not Satisfiable` response if the + * conditions of the `Range:` header can't be met. + * + * @memberof workbox-range-requests + */ + async function createPartialResponse(request, originalResponse) { + try { + if ("dev" !== 'production') { + assert_js.assert.isInstance(request, Request, { + moduleName: 'workbox-range-requests', + funcName: 'createPartialResponse', + paramName: 'request' + }); + assert_js.assert.isInstance(originalResponse, Response, { + moduleName: 'workbox-range-requests', + funcName: 'createPartialResponse', + paramName: 'originalResponse' + }); + } + if (originalResponse.status === 206) { + // If we already have a 206, then just pass it through as-is; + // see https://github.com/GoogleChrome/workbox/issues/1720 + return originalResponse; + } + const rangeHeader = request.headers.get('range'); + if (!rangeHeader) { + throw new WorkboxError_js.WorkboxError('no-range-header'); + } + const boundaries = parseRangeHeader(rangeHeader); + const originalBlob = await originalResponse.blob(); + const effectiveBoundaries = calculateEffectiveBoundaries(originalBlob, boundaries.start, boundaries.end); + const slicedBlob = originalBlob.slice(effectiveBoundaries.start, effectiveBoundaries.end); + const slicedBlobSize = slicedBlob.size; + const slicedResponse = new Response(slicedBlob, { + // Status code 206 is for a Partial Content response. + // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/206 + status: 206, + statusText: 'Partial Content', + headers: originalResponse.headers + }); + slicedResponse.headers.set('Content-Length', String(slicedBlobSize)); + slicedResponse.headers.set('Content-Range', `bytes ${effectiveBoundaries.start}-${effectiveBoundaries.end - 1}/` + `${originalBlob.size}`); + return slicedResponse; + } catch (error) { + { + logger_js.logger.warn(`Unable to construct a partial response; returning a ` + `416 Range Not Satisfiable response instead.`); + logger_js.logger.groupCollapsed(`View details here.`); + logger_js.logger.log(error); + logger_js.logger.log(request); + logger_js.logger.log(originalResponse); + logger_js.logger.groupEnd(); + } + return new Response('', { + status: 416, + statusText: 'Range Not Satisfiable' + }); + } + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * The range request plugin makes it easy for a request with a 'Range' header to + * be fulfilled by a cached response. + * + * It does this by intercepting the `cachedResponseWillBeUsed` plugin callback + * and returning the appropriate subset of the cached response body. + * + * @memberof workbox-range-requests + */ + class RangeRequestsPlugin { + constructor() { + /** + * @param {Object} options + * @param {Request} options.request The original request, which may or may not + * contain a Range: header. + * @param {Response} options.cachedResponse The complete cached response. + * @return {Promise} If request contains a 'Range' header, then a + * new response with status 206 whose body is a subset of `cachedResponse` is + * returned. Otherwise, `cachedResponse` is returned as-is. + * + * @private + */ + this.cachedResponseWillBeUsed = async ({ + request, + cachedResponse + }) => { + // Only return a sliced response if there's something valid in the cache, + // and there's a Range: header in the request. + if (cachedResponse && request.headers.has('range')) { + return await createPartialResponse(request, cachedResponse); + } + // If there was no Range: header, or if cachedResponse wasn't valid, just + // pass it through as-is. + return cachedResponse; + }; + } + } + + exports.RangeRequestsPlugin = RangeRequestsPlugin; + exports.createPartialResponse = createPartialResponse; + + return exports; + +})({}, workbox.core._private, workbox.core._private, workbox.core._private); +//# sourceMappingURL=workbox-range-requests.dev.js.map diff --git a/node_modules/workbox-range-requests/build/workbox-range-requests.dev.js.map b/node_modules/workbox-range-requests/build/workbox-range-requests.dev.js.map new file mode 100644 index 0000000000000000000000000000000000000000..80fd0a30253604722f5c9107fcadbc35c06b2d1b --- /dev/null +++ b/node_modules/workbox-range-requests/build/workbox-range-requests.dev.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-range-requests.dev.js","sources":["../_version.js","../utils/calculateEffectiveBoundaries.js","../utils/parseRangeHeader.js","../createPartialResponse.js","../RangeRequestsPlugin.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:range-requests:7.4.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 { assert } from 'workbox-core/_private/assert.js';\nimport '../_version.js';\n/**\n * @param {Blob} blob A source blob.\n * @param {number} [start] The offset to use as the start of the\n * slice.\n * @param {number} [end] The offset to use as the end of the slice.\n * @return {Object} An object with `start` and `end` properties, reflecting\n * the effective boundaries to use given the size of the blob.\n *\n * @private\n */\nfunction calculateEffectiveBoundaries(blob, start, end) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(blob, Blob, {\n moduleName: 'workbox-range-requests',\n funcName: 'calculateEffectiveBoundaries',\n paramName: 'blob',\n });\n }\n const blobSize = blob.size;\n if ((end && end > blobSize) || (start && start < 0)) {\n throw new WorkboxError('range-not-satisfiable', {\n size: blobSize,\n end,\n start,\n });\n }\n let effectiveStart;\n let effectiveEnd;\n if (start !== undefined && end !== undefined) {\n effectiveStart = start;\n // Range values are inclusive, so add 1 to the value.\n effectiveEnd = end + 1;\n }\n else if (start !== undefined && end === undefined) {\n effectiveStart = start;\n effectiveEnd = blobSize;\n }\n else if (end !== undefined && start === undefined) {\n effectiveStart = blobSize - end;\n effectiveEnd = blobSize;\n }\n return {\n start: effectiveStart,\n end: effectiveEnd,\n };\n}\nexport { calculateEffectiveBoundaries };\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 { assert } from 'workbox-core/_private/assert.js';\nimport '../_version.js';\n/**\n * @param {string} rangeHeader A Range: header value.\n * @return {Object} An object with `start` and `end` properties, reflecting\n * the parsed value of the Range: header. If either the `start` or `end` are\n * omitted, then `null` will be returned.\n *\n * @private\n */\nfunction parseRangeHeader(rangeHeader) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(rangeHeader, 'string', {\n moduleName: 'workbox-range-requests',\n funcName: 'parseRangeHeader',\n paramName: 'rangeHeader',\n });\n }\n const normalizedRangeHeader = rangeHeader.trim().toLowerCase();\n if (!normalizedRangeHeader.startsWith('bytes=')) {\n throw new WorkboxError('unit-must-be-bytes', { normalizedRangeHeader });\n }\n // Specifying multiple ranges separate by commas is valid syntax, but this\n // library only attempts to handle a single, contiguous sequence of bytes.\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range#Syntax\n if (normalizedRangeHeader.includes(',')) {\n throw new WorkboxError('single-range-only', { normalizedRangeHeader });\n }\n const rangeParts = /(\\d*)-(\\d*)/.exec(normalizedRangeHeader);\n // We need either at least one of the start or end values.\n if (!rangeParts || !(rangeParts[1] || rangeParts[2])) {\n throw new WorkboxError('invalid-range-values', { normalizedRangeHeader });\n }\n return {\n start: rangeParts[1] === '' ? undefined : Number(rangeParts[1]),\n end: rangeParts[2] === '' ? undefined : Number(rangeParts[2]),\n };\n}\nexport { parseRangeHeader };\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 { assert } from 'workbox-core/_private/assert.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { calculateEffectiveBoundaries } from './utils/calculateEffectiveBoundaries.js';\nimport { parseRangeHeader } from './utils/parseRangeHeader.js';\nimport './_version.js';\n/**\n * Given a `Request` and `Response` objects as input, this will return a\n * promise for a new `Response`.\n *\n * If the original `Response` already contains partial content (i.e. it has\n * a status of 206), then this assumes it already fulfills the `Range:`\n * requirements, and will return it as-is.\n *\n * @param {Request} request A request, which should contain a Range:\n * header.\n * @param {Response} originalResponse A response.\n * @return {Promise} Either a `206 Partial Content` response, with\n * the response body set to the slice of content specified by the request's\n * `Range:` header, or a `416 Range Not Satisfiable` response if the\n * conditions of the `Range:` header can't be met.\n *\n * @memberof workbox-range-requests\n */\nasync function createPartialResponse(request, originalResponse) {\n try {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(request, Request, {\n moduleName: 'workbox-range-requests',\n funcName: 'createPartialResponse',\n paramName: 'request',\n });\n assert.isInstance(originalResponse, Response, {\n moduleName: 'workbox-range-requests',\n funcName: 'createPartialResponse',\n paramName: 'originalResponse',\n });\n }\n if (originalResponse.status === 206) {\n // If we already have a 206, then just pass it through as-is;\n // see https://github.com/GoogleChrome/workbox/issues/1720\n return originalResponse;\n }\n const rangeHeader = request.headers.get('range');\n if (!rangeHeader) {\n throw new WorkboxError('no-range-header');\n }\n const boundaries = parseRangeHeader(rangeHeader);\n const originalBlob = await originalResponse.blob();\n const effectiveBoundaries = calculateEffectiveBoundaries(originalBlob, boundaries.start, boundaries.end);\n const slicedBlob = originalBlob.slice(effectiveBoundaries.start, effectiveBoundaries.end);\n const slicedBlobSize = slicedBlob.size;\n const slicedResponse = new Response(slicedBlob, {\n // Status code 206 is for a Partial Content response.\n // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/206\n status: 206,\n statusText: 'Partial Content',\n headers: originalResponse.headers,\n });\n slicedResponse.headers.set('Content-Length', String(slicedBlobSize));\n slicedResponse.headers.set('Content-Range', `bytes ${effectiveBoundaries.start}-${effectiveBoundaries.end - 1}/` +\n `${originalBlob.size}`);\n return slicedResponse;\n }\n catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n logger.warn(`Unable to construct a partial response; returning a ` +\n `416 Range Not Satisfiable response instead.`);\n logger.groupCollapsed(`View details here.`);\n logger.log(error);\n logger.log(request);\n logger.log(originalResponse);\n logger.groupEnd();\n }\n return new Response('', {\n status: 416,\n statusText: 'Range Not Satisfiable',\n });\n }\n}\nexport { createPartialResponse };\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 { createPartialResponse } from './createPartialResponse.js';\nimport './_version.js';\n/**\n * The range request plugin makes it easy for a request with a 'Range' header to\n * be fulfilled by a cached response.\n *\n * It does this by intercepting the `cachedResponseWillBeUsed` plugin callback\n * and returning the appropriate subset of the cached response body.\n *\n * @memberof workbox-range-requests\n */\nclass RangeRequestsPlugin {\n constructor() {\n /**\n * @param {Object} options\n * @param {Request} options.request The original request, which may or may not\n * contain a Range: header.\n * @param {Response} options.cachedResponse The complete cached response.\n * @return {Promise} If request contains a 'Range' header, then a\n * new response with status 206 whose body is a subset of `cachedResponse` is\n * returned. Otherwise, `cachedResponse` is returned as-is.\n *\n * @private\n */\n this.cachedResponseWillBeUsed = async ({ request, cachedResponse, }) => {\n // Only return a sliced response if there's something valid in the cache,\n // and there's a Range: header in the request.\n if (cachedResponse && request.headers.has('range')) {\n return await createPartialResponse(request, cachedResponse);\n }\n // If there was no Range: header, or if cachedResponse wasn't valid, just\n // pass it through as-is.\n return cachedResponse;\n };\n }\n}\nexport { RangeRequestsPlugin };\n"],"names":["self","_","e","calculateEffectiveBoundaries","blob","start","end","assert","isInstance","Blob","moduleName","funcName","paramName","blobSize","size","WorkboxError","effectiveStart","effectiveEnd","undefined","parseRangeHeader","rangeHeader","isType","normalizedRangeHeader","trim","toLowerCase","startsWith","includes","rangeParts","exec","Number","createPartialResponse","request","originalResponse","process","Request","Response","status","headers","get","boundaries","originalBlob","effectiveBoundaries","slicedBlob","slice","slicedBlobSize","slicedResponse","statusText","set","String","error","logger","warn","groupCollapsed","log","groupEnd","RangeRequestsPlugin","constructor","cachedResponseWillBeUsed","cachedResponse","has"],"mappings":";;;;IACA;IACA,IAAI;IACAA,EAAAA,IAAI,CAAC,8BAA8B,CAAC,IAAIC,CAAC,EAAE;IAC/C,CAAC,CACD,OAAOC,CAAC,EAAE,CAAE;;ICLZ;IACA;;IAEA;IACA;IACA;IACA;IAIA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,SAASC,4BAA4BA,CAACC,IAAI,EAAEC,KAAK,EAAEC,GAAG,EAAE;IACpD,EAA2C;IACvCC,IAAAA,gBAAM,CAACC,UAAU,CAACJ,IAAI,EAAEK,IAAI,EAAE;IAC1BC,MAAAA,UAAU,EAAE,wBAAwB;IACpCC,MAAAA,QAAQ,EAAE,8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ACA,IAAIA,cAAc,IAAI3B,OAAO,CAACM,OAAO,CAACsB,GAAG,CAAC,OAAO,CAAC,EAAE;IAChD,QAAA,OAAO,MAAM7B,qBAAqB,CAACC,OAAO,EAAE2B,cAAc,CAAC;IAC/D,MAAA;IACA;IACA;IACA,MAAA,OAAOA,cAAc;QACzB,CAAC;IACL,EAAA;IACJ;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/workbox-range-requests/build/workbox-range-requests.prod.js b/node_modules/workbox-range-requests/build/workbox-range-requests.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..b336ada0f712c22ef65fab4f19069c0eeca4b3dc --- /dev/null +++ b/node_modules/workbox-range-requests/build/workbox-range-requests.prod.js @@ -0,0 +1,2 @@ +this.workbox=this.workbox||{},this.workbox.rangeRequests=function(t,e,n){"use strict";try{self["workbox:range-requests:7.4.0"]&&_()}catch(t){}async function r(t,n){try{if(206===n.status)return n;const r=t.headers.get("range");if(!r)throw new e.WorkboxError("no-range-header");const s=function(t){const n=t.trim().toLowerCase();if(!n.startsWith("bytes="))throw new e.WorkboxError("unit-must-be-bytes",{normalizedRangeHeader:n});if(n.includes(","))throw new e.WorkboxError("single-range-only",{normalizedRangeHeader:n});const r=/(\d*)-(\d*)/.exec(n);if(!r||!r[1]&&!r[2])throw new e.WorkboxError("invalid-range-values",{normalizedRangeHeader:n});return{start:""===r[1]?void 0:Number(r[1]),end:""===r[2]?void 0:Number(r[2])}}(r),a=await n.blob(),o=function(t,n,r){const s=t.size;if(r&&r>s||n&&n<0)throw new e.WorkboxError("range-not-satisfiable",{size:s,end:r,start:n});let a,o;return void 0!==n&&void 0!==r?(a=n,o=r+1):void 0!==n&&void 0===r?(a=n,o=s):void 0!==r&&void 0===n&&(a=s-r,o=s),{start:a,end:o}}(a,s.start,s.end),i=a.slice(o.start,o.end),d=i.size,u=new Response(i,{status:206,statusText:"Partial Content",headers:n.headers});return u.headers.set("Content-Length",String(d)),u.headers.set("Content-Range",`bytes ${o.start}-${o.end-1}/${a.size}`),u}catch(t){return new Response("",{status:416,statusText:"Range Not Satisfiable"})}}return t.RangeRequestsPlugin=class{constructor(){this.cachedResponseWillBeUsed=async({request:t,cachedResponse:e})=>e&&t.headers.has("range")?await r(t,e):e}},t.createPartialResponse=r,t}({},workbox.core._private,workbox.core._private); +//# sourceMappingURL=workbox-range-requests.prod.js.map diff --git a/node_modules/workbox-range-requests/build/workbox-range-requests.prod.js.map b/node_modules/workbox-range-requests/build/workbox-range-requests.prod.js.map new file mode 100644 index 0000000000000000000000000000000000000000..c6fe2c4c98bebf15326b3892af00fd85dd5a8194 --- /dev/null +++ b/node_modules/workbox-range-requests/build/workbox-range-requests.prod.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-range-requests.prod.js","sources":["../_version.js","../createPartialResponse.js","../utils/parseRangeHeader.js","../utils/calculateEffectiveBoundaries.js","../RangeRequestsPlugin.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:range-requests:7.4.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 { assert } from 'workbox-core/_private/assert.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { calculateEffectiveBoundaries } from './utils/calculateEffectiveBoundaries.js';\nimport { parseRangeHeader } from './utils/parseRangeHeader.js';\nimport './_version.js';\n/**\n * Given a `Request` and `Response` objects as input, this will return a\n * promise for a new `Response`.\n *\n * If the original `Response` already contains partial content (i.e. it has\n * a status of 206), then this assumes it already fulfills the `Range:`\n * requirements, and will return it as-is.\n *\n * @param {Request} request A request, which should contain a Range:\n * header.\n * @param {Response} originalResponse A response.\n * @return {Promise} Either a `206 Partial Content` response, with\n * the response body set to the slice of content specified by the request's\n * `Range:` header, or a `416 Range Not Satisfiable` response if the\n * conditions of the `Range:` header can't be met.\n *\n * @memberof workbox-range-requests\n */\nasync function createPartialResponse(request, originalResponse) {\n try {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(request, Request, {\n moduleName: 'workbox-range-requests',\n funcName: 'createPartialResponse',\n paramName: 'request',\n });\n assert.isInstance(originalResponse, Response, {\n moduleName: 'workbox-range-requests',\n funcName: 'createPartialResponse',\n paramName: 'originalResponse',\n });\n }\n if (originalResponse.status === 206) {\n // If we already have a 206, then just pass it through as-is;\n // see https://github.com/GoogleChrome/workbox/issues/1720\n return originalResponse;\n }\n const rangeHeader = request.headers.get('range');\n if (!rangeHeader) {\n throw new WorkboxError('no-range-header');\n }\n const boundaries = parseRangeHeader(rangeHeader);\n const originalBlob = await originalResponse.blob();\n const effectiveBoundaries = calculateEffectiveBoundaries(originalBlob, boundaries.start, boundaries.end);\n const slicedBlob = originalBlob.slice(effectiveBoundaries.start, effectiveBoundaries.end);\n const slicedBlobSize = slicedBlob.size;\n const slicedResponse = new Response(slicedBlob, {\n // Status code 206 is for a Partial Content response.\n // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/206\n status: 206,\n statusText: 'Partial Content',\n headers: originalResponse.headers,\n });\n slicedResponse.headers.set('Content-Length', String(slicedBlobSize));\n slicedResponse.headers.set('Content-Range', `bytes ${effectiveBoundaries.start}-${effectiveBoundaries.end - 1}/` +\n `${originalBlob.size}`);\n return slicedResponse;\n }\n catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n logger.warn(`Unable to construct a partial response; returning a ` +\n `416 Range Not Satisfiable response instead.`);\n logger.groupCollapsed(`View details here.`);\n logger.log(error);\n logger.log(request);\n logger.log(originalResponse);\n logger.groupEnd();\n }\n return new Response('', {\n status: 416,\n statusText: 'Range Not Satisfiable',\n });\n }\n}\nexport { createPartialResponse };\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 { assert } from 'workbox-core/_private/assert.js';\nimport '../_version.js';\n/**\n * @param {string} rangeHeader A Range: header value.\n * @return {Object} An object with `start` and `end` properties, reflecting\n * the parsed value of the Range: header. If either the `start` or `end` are\n * omitted, then `null` will be returned.\n *\n * @private\n */\nfunction parseRangeHeader(rangeHeader) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(rangeHeader, 'string', {\n moduleName: 'workbox-range-requests',\n funcName: 'parseRangeHeader',\n paramName: 'rangeHeader',\n });\n }\n const normalizedRangeHeader = rangeHeader.trim().toLowerCase();\n if (!normalizedRangeHeader.startsWith('bytes=')) {\n throw new WorkboxError('unit-must-be-bytes', { normalizedRangeHeader });\n }\n // Specifying multiple ranges separate by commas is valid syntax, but this\n // library only attempts to handle a single, contiguous sequence of bytes.\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range#Syntax\n if (normalizedRangeHeader.includes(',')) {\n throw new WorkboxError('single-range-only', { normalizedRangeHeader });\n }\n const rangeParts = /(\\d*)-(\\d*)/.exec(normalizedRangeHeader);\n // We need either at least one of the start or end values.\n if (!rangeParts || !(rangeParts[1] || rangeParts[2])) {\n throw new WorkboxError('invalid-range-values', { normalizedRangeHeader });\n }\n return {\n start: rangeParts[1] === '' ? undefined : Number(rangeParts[1]),\n end: rangeParts[2] === '' ? undefined : Number(rangeParts[2]),\n };\n}\nexport { parseRangeHeader };\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 { assert } from 'workbox-core/_private/assert.js';\nimport '../_version.js';\n/**\n * @param {Blob} blob A source blob.\n * @param {number} [start] The offset to use as the start of the\n * slice.\n * @param {number} [end] The offset to use as the end of the slice.\n * @return {Object} An object with `start` and `end` properties, reflecting\n * the effective boundaries to use given the size of the blob.\n *\n * @private\n */\nfunction calculateEffectiveBoundaries(blob, start, end) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(blob, Blob, {\n moduleName: 'workbox-range-requests',\n funcName: 'calculateEffectiveBoundaries',\n paramName: 'blob',\n });\n }\n const blobSize = blob.size;\n if ((end && end > blobSize) || (start && start < 0)) {\n throw new WorkboxError('range-not-satisfiable', {\n size: blobSize,\n end,\n start,\n });\n }\n let effectiveStart;\n let effectiveEnd;\n if (start !== undefined && end !== undefined) {\n effectiveStart = start;\n // Range values are inclusive, so add 1 to the value.\n effectiveEnd = end + 1;\n }\n else if (start !== undefined && end === undefined) {\n effectiveStart = start;\n effectiveEnd = blobSize;\n }\n else if (end !== undefined && start === undefined) {\n effectiveStart = blobSize - end;\n effectiveEnd = blobSize;\n }\n return {\n start: effectiveStart,\n end: effectiveEnd,\n };\n}\nexport { calculateEffectiveBoundaries };\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 { createPartialResponse } from './createPartialResponse.js';\nimport './_version.js';\n/**\n * The range request plugin makes it easy for a request with a 'Range' header to\n * be fulfilled by a cached response.\n *\n * It does this by intercepting the `cachedResponseWillBeUsed` plugin callback\n * and returning the appropriate subset of the cached response body.\n *\n * @memberof workbox-range-requests\n */\nclass RangeRequestsPlugin {\n constructor() {\n /**\n * @param {Object} options\n * @param {Request} options.request The original request, which may or may not\n * contain a Range: header.\n * @param {Response} options.cachedResponse The complete cached response.\n * @return {Promise} If request contains a 'Range' header, then a\n * new response with status 206 whose body is a subset of `cachedResponse` is\n * returned. Otherwise, `cachedResponse` is returned as-is.\n *\n * @private\n */\n this.cachedResponseWillBeUsed = async ({ request, cachedResponse, }) => {\n // Only return a sliced response if there's something valid in the cache,\n // and there's a Range: header in the request.\n if (cachedResponse && request.headers.has('range')) {\n return await createPartialResponse(request, cachedResponse);\n }\n // If there was no Range: header, or if cachedResponse wasn't valid, just\n // pass it through as-is.\n return cachedResponse;\n };\n }\n}\nexport { RangeRequestsPlugin };\n"],"names":["self","_","e","async","createPartialResponse","request","originalResponse","status","rangeHeader","headers","get","WorkboxError","boundaries","normalizedRangeHeader","trim","toLowerCase","startsWith","includes","rangeParts","exec","start","undefined","Number","end","parseRangeHeader","originalBlob","blob","effectiveBoundaries","blobSize","size","effectiveStart","effectiveEnd","calculateEffectiveBoundaries","slicedBlob","slice","slicedBlobSize","slicedResponse","Response","statusText","set","String","error","constructor","this","cachedResponseWillBeUsed","cachedResponse","has"],"mappings":"sFAEA,IACIA,KAAK,iCAAmCC,GAC5C,CACA,MAAOC,GAAK,CC0BZC,eAAeC,EAAsBC,EAASC,GAC1C,IAaI,GAAgC,MAA5BA,EAAiBC,OAGjB,OAAOD,EAEX,MAAME,EAAcH,EAAQI,QAAQC,IAAI,SACxC,IAAKF,EACD,MAAM,IAAIG,EAAAA,aAAa,mBAE3B,MAAMC,ECpCd,SAA0BJ,GAQtB,MAAMK,EAAwBL,EAAYM,OAAOC,cACjD,IAAKF,EAAsBG,WAAW,UAClC,MAAM,IAAIL,EAAAA,aAAa,qBAAsB,CAAEE,0BAKnD,GAAIA,EAAsBI,SAAS,KAC/B,MAAM,IAAIN,EAAAA,aAAa,oBAAqB,CAAEE,0BAElD,MAAMK,EAAa,cAAcC,KAAKN,GAEtC,IAAKK,IAAgBA,EAAW,KAAMA,EAAW,GAC7C,MAAM,IAAIP,EAAAA,aAAa,uBAAwB,CAAEE,0BAErD,MAAO,CACHO,MAAyB,KAAlBF,EAAW,QAAYG,EAAYC,OAAOJ,EAAW,IAC5DK,IAAuB,KAAlBL,EAAW,QAAYG,EAAYC,OAAOJ,EAAW,IAElE,CDS2BM,CAAiBhB,GAC9BiB,QAAqBnB,EAAiBoB,OACtCC,EEpCd,SAAsCD,EAAMN,EAAOG,GAQ/C,MAAMK,EAAWF,EAAKG,KACtB,GAAKN,GAAOA,EAAMK,GAAcR,GAASA,EAAQ,EAC7C,MAAM,IAAIT,EAAAA,aAAa,wBAAyB,CAC5CkB,KAAMD,EACNL,MACAH,UAGR,IAAIU,EACAC,EAcJ,YAbcV,IAAVD,QAA+BC,IAARE,GACvBO,EAAiBV,EAEjBW,EAAeR,EAAM,QAENF,IAAVD,QAA+BC,IAARE,GAC5BO,EAAiBV,EACjBW,EAAeH,QAEFP,IAARE,QAA+BF,IAAVD,IAC1BU,EAAiBF,EAAWL,EAC5BQ,EAAeH,GAEZ,CACHR,MAAOU,EACPP,IAAKQ,EAEb,CFCoCC,CAA6BP,EAAcb,EAAWQ,MAAOR,EAAWW,KAC9FU,EAAaR,EAAaS,MAAMP,EAAoBP,MAAOO,EAAoBJ,KAC/EY,EAAiBF,EAAWJ,KAC5BO,EAAiB,IAAIC,SAASJ,EAAY,CAG5C1B,OAAQ,IACR+B,WAAY,kBACZ7B,QAASH,EAAiBG,UAK9B,OAHA2B,EAAe3B,QAAQ8B,IAAI,iBAAkBC,OAAOL,IACpDC,EAAe3B,QAAQ8B,IAAI,gBAAkB,SAAQZ,EAAoBP,SAASO,EAAoBJ,IAAM,KACrGE,EAAaI,QACbO,CACX,CACA,MAAOK,GAUH,OAAO,IAAIJ,SAAS,GAAI,CACpB9B,OAAQ,IACR+B,WAAY,yBAEpB,CACJ,8BGpEA,MACII,cAYIC,KAAKC,yBAA2BzC,OAASE,UAASwC,oBAG1CA,GAAkBxC,EAAQI,QAAQqC,IAAI,eACzB1C,EAAsBC,EAASwC,GAIzCA,CAEf"} \ No newline at end of file diff --git a/node_modules/workbox-range-requests/createPartialResponse.d.ts b/node_modules/workbox-range-requests/createPartialResponse.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e2f050ed494768a5ed971131f10012aff0ca77aa --- /dev/null +++ b/node_modules/workbox-range-requests/createPartialResponse.d.ts @@ -0,0 +1,21 @@ +import './_version.js'; +/** + * Given a `Request` and `Response` objects as input, this will return a + * promise for a new `Response`. + * + * If the original `Response` already contains partial content (i.e. it has + * a status of 206), then this assumes it already fulfills the `Range:` + * requirements, and will return it as-is. + * + * @param {Request} request A request, which should contain a Range: + * header. + * @param {Response} originalResponse A response. + * @return {Promise} Either a `206 Partial Content` response, with + * the response body set to the slice of content specified by the request's + * `Range:` header, or a `416 Range Not Satisfiable` response if the + * conditions of the `Range:` header can't be met. + * + * @memberof workbox-range-requests + */ +declare function createPartialResponse(request: Request, originalResponse: Response): Promise; +export { createPartialResponse }; diff --git a/node_modules/workbox-range-requests/createPartialResponse.js b/node_modules/workbox-range-requests/createPartialResponse.js new file mode 100644 index 0000000000000000000000000000000000000000..2bbf3f5c3ed51fc85e862b1c220b47d12e24fb61 --- /dev/null +++ b/node_modules/workbox-range-requests/createPartialResponse.js @@ -0,0 +1,88 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { WorkboxError } from 'workbox-core/_private/WorkboxError.js'; +import { assert } from 'workbox-core/_private/assert.js'; +import { logger } from 'workbox-core/_private/logger.js'; +import { calculateEffectiveBoundaries } from './utils/calculateEffectiveBoundaries.js'; +import { parseRangeHeader } from './utils/parseRangeHeader.js'; +import './_version.js'; +/** + * Given a `Request` and `Response` objects as input, this will return a + * promise for a new `Response`. + * + * If the original `Response` already contains partial content (i.e. it has + * a status of 206), then this assumes it already fulfills the `Range:` + * requirements, and will return it as-is. + * + * @param {Request} request A request, which should contain a Range: + * header. + * @param {Response} originalResponse A response. + * @return {Promise} Either a `206 Partial Content` response, with + * the response body set to the slice of content specified by the request's + * `Range:` header, or a `416 Range Not Satisfiable` response if the + * conditions of the `Range:` header can't be met. + * + * @memberof workbox-range-requests + */ +async function createPartialResponse(request, originalResponse) { + try { + if (process.env.NODE_ENV !== 'production') { + assert.isInstance(request, Request, { + moduleName: 'workbox-range-requests', + funcName: 'createPartialResponse', + paramName: 'request', + }); + assert.isInstance(originalResponse, Response, { + moduleName: 'workbox-range-requests', + funcName: 'createPartialResponse', + paramName: 'originalResponse', + }); + } + if (originalResponse.status === 206) { + // If we already have a 206, then just pass it through as-is; + // see https://github.com/GoogleChrome/workbox/issues/1720 + return originalResponse; + } + const rangeHeader = request.headers.get('range'); + if (!rangeHeader) { + throw new WorkboxError('no-range-header'); + } + const boundaries = parseRangeHeader(rangeHeader); + const originalBlob = await originalResponse.blob(); + const effectiveBoundaries = calculateEffectiveBoundaries(originalBlob, boundaries.start, boundaries.end); + const slicedBlob = originalBlob.slice(effectiveBoundaries.start, effectiveBoundaries.end); + const slicedBlobSize = slicedBlob.size; + const slicedResponse = new Response(slicedBlob, { + // Status code 206 is for a Partial Content response. + // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/206 + status: 206, + statusText: 'Partial Content', + headers: originalResponse.headers, + }); + slicedResponse.headers.set('Content-Length', String(slicedBlobSize)); + slicedResponse.headers.set('Content-Range', `bytes ${effectiveBoundaries.start}-${effectiveBoundaries.end - 1}/` + + `${originalBlob.size}`); + return slicedResponse; + } + catch (error) { + if (process.env.NODE_ENV !== 'production') { + logger.warn(`Unable to construct a partial response; returning a ` + + `416 Range Not Satisfiable response instead.`); + logger.groupCollapsed(`View details here.`); + logger.log(error); + logger.log(request); + logger.log(originalResponse); + logger.groupEnd(); + } + return new Response('', { + status: 416, + statusText: 'Range Not Satisfiable', + }); + } +} +export { createPartialResponse }; diff --git a/node_modules/workbox-range-requests/createPartialResponse.mjs b/node_modules/workbox-range-requests/createPartialResponse.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9ba6eda307a12002d5ab066c0636a6cf8cdbed0d --- /dev/null +++ b/node_modules/workbox-range-requests/createPartialResponse.mjs @@ -0,0 +1 @@ +export * from './createPartialResponse.js'; \ No newline at end of file diff --git a/node_modules/workbox-range-requests/index.d.ts b/node_modules/workbox-range-requests/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c6ea160e8ab36b7591570252a30a51791af2a979 --- /dev/null +++ b/node_modules/workbox-range-requests/index.d.ts @@ -0,0 +1,7 @@ +import { createPartialResponse } from './createPartialResponse.js'; +import { RangeRequestsPlugin } from './RangeRequestsPlugin.js'; +import './_version.js'; +/** + * @module workbox-range-requests + */ +export { createPartialResponse, RangeRequestsPlugin }; diff --git a/node_modules/workbox-range-requests/index.js b/node_modules/workbox-range-requests/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5912fccad7910aa91bfc07d5322c830127b03ec4 --- /dev/null +++ b/node_modules/workbox-range-requests/index.js @@ -0,0 +1,14 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { createPartialResponse } from './createPartialResponse.js'; +import { RangeRequestsPlugin } from './RangeRequestsPlugin.js'; +import './_version.js'; +/** + * @module workbox-range-requests + */ +export { createPartialResponse, RangeRequestsPlugin }; diff --git a/node_modules/workbox-range-requests/index.mjs b/node_modules/workbox-range-requests/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..833b6a2f3226fec78490a3b7a622dc5146f94b53 --- /dev/null +++ b/node_modules/workbox-range-requests/index.mjs @@ -0,0 +1 @@ +export * from './index.js'; \ No newline at end of file diff --git a/node_modules/workbox-range-requests/package.json b/node_modules/workbox-range-requests/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6be70b0d3910afad68ec73ae90f4a999498404ed --- /dev/null +++ b/node_modules/workbox-range-requests/package.json @@ -0,0 +1,35 @@ +{ + "name": "workbox-range-requests", + "version": "7.4.1", + "license": "MIT", + "author": "Google's Web DevRel Team and Google's Aurora Team", + "description": "This library creates a new Response, given a source Response and a Range header value.", + "repository": { + "type": "git", + "url": "git+https://github.com/googlechrome/workbox.git" + }, + "bugs": "https://github.com/googlechrome/workbox/issues", + "homepage": "https://github.com/GoogleChrome/workbox", + "keywords": [ + "workbox", + "workboxjs", + "service worker", + "sw", + "caching", + "cache", + "range", + "media", + "workbox-plugin" + ], + "workbox": { + "browserNamespace": "workbox.rangeRequests", + "packageType": "sw" + }, + "main": "index.js", + "module": "index.mjs", + "types": "index.d.ts", + "dependencies": { + "workbox-core": "7.4.1" + }, + "gitHead": "62b9d8ba8eb3c1a2ab8aac9d84c90cda7865d6a3" +} diff --git a/node_modules/workbox-range-requests/src/RangeRequestsPlugin.ts b/node_modules/workbox-range-requests/src/RangeRequestsPlugin.ts new file mode 100644 index 0000000000000000000000000000000000000000..80b06982518ba631769a2cf1f8aa2b1665338de4 --- /dev/null +++ b/node_modules/workbox-range-requests/src/RangeRequestsPlugin.ts @@ -0,0 +1,50 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {WorkboxPlugin} from 'workbox-core/types.js'; +import {createPartialResponse} from './createPartialResponse.js'; +import './_version.js'; + +/** + * The range request plugin makes it easy for a request with a 'Range' header to + * be fulfilled by a cached response. + * + * It does this by intercepting the `cachedResponseWillBeUsed` plugin callback + * and returning the appropriate subset of the cached response body. + * + * @memberof workbox-range-requests + */ +class RangeRequestsPlugin implements WorkboxPlugin { + /** + * @param {Object} options + * @param {Request} options.request The original request, which may or may not + * contain a Range: header. + * @param {Response} options.cachedResponse The complete cached response. + * @return {Promise} If request contains a 'Range' header, then a + * new response with status 206 whose body is a subset of `cachedResponse` is + * returned. Otherwise, `cachedResponse` is returned as-is. + * + * @private + */ + cachedResponseWillBeUsed: WorkboxPlugin['cachedResponseWillBeUsed'] = async ({ + request, + cachedResponse, + }) => { + // Only return a sliced response if there's something valid in the cache, + // and there's a Range: header in the request. + if (cachedResponse && request.headers.has('range')) { + return await createPartialResponse(request, cachedResponse); + } + + // If there was no Range: header, or if cachedResponse wasn't valid, just + // pass it through as-is. + return cachedResponse; + }; +} + +export {RangeRequestsPlugin}; diff --git a/node_modules/workbox-range-requests/src/_version.ts b/node_modules/workbox-range-requests/src/_version.ts new file mode 100644 index 0000000000000000000000000000000000000000..a1d14bb325cc144fca7e835188692f36c77a1697 --- /dev/null +++ b/node_modules/workbox-range-requests/src/_version.ts @@ -0,0 +1,2 @@ +// @ts-ignore +try{self['workbox:range-requests:7.4.1']&&_()}catch(e){} \ No newline at end of file diff --git a/node_modules/workbox-range-requests/src/createPartialResponse.ts b/node_modules/workbox-range-requests/src/createPartialResponse.ts new file mode 100644 index 0000000000000000000000000000000000000000..e7eca6f28f18954252061ea75b0decfebb42355a --- /dev/null +++ b/node_modules/workbox-range-requests/src/createPartialResponse.ts @@ -0,0 +1,115 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {WorkboxError} from 'workbox-core/_private/WorkboxError.js'; +import {assert} from 'workbox-core/_private/assert.js'; +import {logger} from 'workbox-core/_private/logger.js'; +import {calculateEffectiveBoundaries} from './utils/calculateEffectiveBoundaries.js'; +import {parseRangeHeader} from './utils/parseRangeHeader.js'; +import './_version.js'; + +/** + * Given a `Request` and `Response` objects as input, this will return a + * promise for a new `Response`. + * + * If the original `Response` already contains partial content (i.e. it has + * a status of 206), then this assumes it already fulfills the `Range:` + * requirements, and will return it as-is. + * + * @param {Request} request A request, which should contain a Range: + * header. + * @param {Response} originalResponse A response. + * @return {Promise} Either a `206 Partial Content` response, with + * the response body set to the slice of content specified by the request's + * `Range:` header, or a `416 Range Not Satisfiable` response if the + * conditions of the `Range:` header can't be met. + * + * @memberof workbox-range-requests + */ +async function createPartialResponse( + request: Request, + originalResponse: Response, +): Promise { + try { + if (process.env.NODE_ENV !== 'production') { + assert!.isInstance(request, Request, { + moduleName: 'workbox-range-requests', + funcName: 'createPartialResponse', + paramName: 'request', + }); + + assert!.isInstance(originalResponse, Response, { + moduleName: 'workbox-range-requests', + funcName: 'createPartialResponse', + paramName: 'originalResponse', + }); + } + + if (originalResponse.status === 206) { + // If we already have a 206, then just pass it through as-is; + // see https://github.com/GoogleChrome/workbox/issues/1720 + return originalResponse; + } + + const rangeHeader = request.headers.get('range'); + if (!rangeHeader) { + throw new WorkboxError('no-range-header'); + } + + const boundaries = parseRangeHeader(rangeHeader); + const originalBlob = await originalResponse.blob(); + + const effectiveBoundaries = calculateEffectiveBoundaries( + originalBlob, + boundaries.start, + boundaries.end, + ); + + const slicedBlob = originalBlob.slice( + effectiveBoundaries.start, + effectiveBoundaries.end, + ); + const slicedBlobSize = slicedBlob.size; + + const slicedResponse = new Response(slicedBlob, { + // Status code 206 is for a Partial Content response. + // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/206 + status: 206, + statusText: 'Partial Content', + headers: originalResponse.headers, + }); + + slicedResponse.headers.set('Content-Length', String(slicedBlobSize)); + slicedResponse.headers.set( + 'Content-Range', + `bytes ${effectiveBoundaries.start}-${effectiveBoundaries.end - 1}/` + + `${originalBlob.size}`, + ); + + return slicedResponse; + } catch (error) { + if (process.env.NODE_ENV !== 'production') { + logger.warn( + `Unable to construct a partial response; returning a ` + + `416 Range Not Satisfiable response instead.`, + ); + logger.groupCollapsed(`View details here.`); + logger.log(error); + logger.log(request); + logger.log(originalResponse); + logger.groupEnd(); + } + + return new Response('', { + status: 416, + statusText: 'Range Not Satisfiable', + }); + } +} + +export {createPartialResponse}; diff --git a/node_modules/workbox-range-requests/src/index.ts b/node_modules/workbox-range-requests/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..52e4c9caf5946a227f33095586575e4ff35e98db --- /dev/null +++ b/node_modules/workbox-range-requests/src/index.ts @@ -0,0 +1,17 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {createPartialResponse} from './createPartialResponse.js'; +import {RangeRequestsPlugin} from './RangeRequestsPlugin.js'; +import './_version.js'; + +/** + * @module workbox-range-requests + */ + +export {createPartialResponse, RangeRequestsPlugin}; diff --git a/node_modules/workbox-range-requests/src/utils/calculateEffectiveBoundaries.ts b/node_modules/workbox-range-requests/src/utils/calculateEffectiveBoundaries.ts new file mode 100644 index 0000000000000000000000000000000000000000..d4cb72478b657d4a858e5bb936047dec2fd296a6 --- /dev/null +++ b/node_modules/workbox-range-requests/src/utils/calculateEffectiveBoundaries.ts @@ -0,0 +1,67 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {WorkboxError} from 'workbox-core/_private/WorkboxError.js'; +import {assert} from 'workbox-core/_private/assert.js'; +import '../_version.js'; + +/** + * @param {Blob} blob A source blob. + * @param {number} [start] The offset to use as the start of the + * slice. + * @param {number} [end] The offset to use as the end of the slice. + * @return {Object} An object with `start` and `end` properties, reflecting + * the effective boundaries to use given the size of the blob. + * + * @private + */ +function calculateEffectiveBoundaries( + blob: Blob, + start?: number, + end?: number, +): {start: number; end: number} { + if (process.env.NODE_ENV !== 'production') { + assert!.isInstance(blob, Blob, { + moduleName: 'workbox-range-requests', + funcName: 'calculateEffectiveBoundaries', + paramName: 'blob', + }); + } + + const blobSize = blob.size; + + if ((end && end > blobSize) || (start && start < 0)) { + throw new WorkboxError('range-not-satisfiable', { + size: blobSize, + end, + start, + }); + } + + let effectiveStart: number; + let effectiveEnd: number; + + if (start !== undefined && end !== undefined) { + effectiveStart = start; + // Range values are inclusive, so add 1 to the value. + effectiveEnd = end + 1; + } else if (start !== undefined && end === undefined) { + effectiveStart = start; + effectiveEnd = blobSize; + } else if (end !== undefined && start === undefined) { + effectiveStart = blobSize - end; + effectiveEnd = blobSize; + } + + return { + start: effectiveStart!, + end: effectiveEnd!, + }; +} + +export {calculateEffectiveBoundaries}; diff --git a/node_modules/workbox-range-requests/src/utils/parseRangeHeader.ts b/node_modules/workbox-range-requests/src/utils/parseRangeHeader.ts new file mode 100644 index 0000000000000000000000000000000000000000..c3e1d02ed50d1d1e22b661bf00b5b4e689406034 --- /dev/null +++ b/node_modules/workbox-range-requests/src/utils/parseRangeHeader.ts @@ -0,0 +1,54 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {WorkboxError} from 'workbox-core/_private/WorkboxError.js'; +import {assert} from 'workbox-core/_private/assert.js'; +import '../_version.js'; + +/** + * @param {string} rangeHeader A Range: header value. + * @return {Object} An object with `start` and `end` properties, reflecting + * the parsed value of the Range: header. If either the `start` or `end` are + * omitted, then `null` will be returned. + * + * @private + */ +function parseRangeHeader(rangeHeader: string): {start?: number; end?: number} { + if (process.env.NODE_ENV !== 'production') { + assert!.isType(rangeHeader, 'string', { + moduleName: 'workbox-range-requests', + funcName: 'parseRangeHeader', + paramName: 'rangeHeader', + }); + } + + const normalizedRangeHeader = rangeHeader.trim().toLowerCase(); + if (!normalizedRangeHeader.startsWith('bytes=')) { + throw new WorkboxError('unit-must-be-bytes', {normalizedRangeHeader}); + } + + // Specifying multiple ranges separate by commas is valid syntax, but this + // library only attempts to handle a single, contiguous sequence of bytes. + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range#Syntax + if (normalizedRangeHeader.includes(',')) { + throw new WorkboxError('single-range-only', {normalizedRangeHeader}); + } + + const rangeParts = /(\d*)-(\d*)/.exec(normalizedRangeHeader); + // We need either at least one of the start or end values. + if (!rangeParts || !(rangeParts[1] || rangeParts[2])) { + throw new WorkboxError('invalid-range-values', {normalizedRangeHeader}); + } + + return { + start: rangeParts[1] === '' ? undefined : Number(rangeParts[1]), + end: rangeParts[2] === '' ? undefined : Number(rangeParts[2]), + }; +} + +export {parseRangeHeader}; diff --git a/node_modules/workbox-range-requests/tsconfig.json b/node_modules/workbox-range-requests/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..2457eadcf8e39664b6315f538007e7de076be21d --- /dev/null +++ b/node_modules/workbox-range-requests/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig", + "compilerOptions": { + "outDir": "./", + "rootDir": "./src", + "tsBuildInfoFile": "./tsconfig.tsbuildinfo" + }, + "include": ["src/**/*.ts"], + "references": [{"path": "../workbox-core/"}] +} diff --git a/node_modules/workbox-range-requests/utils/calculateEffectiveBoundaries.d.ts b/node_modules/workbox-range-requests/utils/calculateEffectiveBoundaries.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0f16da43012fe1d31dfff3445c873aee2d6411f8 --- /dev/null +++ b/node_modules/workbox-range-requests/utils/calculateEffectiveBoundaries.d.ts @@ -0,0 +1,16 @@ +import '../_version.js'; +/** + * @param {Blob} blob A source blob. + * @param {number} [start] The offset to use as the start of the + * slice. + * @param {number} [end] The offset to use as the end of the slice. + * @return {Object} An object with `start` and `end` properties, reflecting + * the effective boundaries to use given the size of the blob. + * + * @private + */ +declare function calculateEffectiveBoundaries(blob: Blob, start?: number, end?: number): { + start: number; + end: number; +}; +export { calculateEffectiveBoundaries }; diff --git a/node_modules/workbox-range-requests/utils/calculateEffectiveBoundaries.js b/node_modules/workbox-range-requests/utils/calculateEffectiveBoundaries.js new file mode 100644 index 0000000000000000000000000000000000000000..14014b02759bab52b334c1bc9830ec88f550df99 --- /dev/null +++ b/node_modules/workbox-range-requests/utils/calculateEffectiveBoundaries.js @@ -0,0 +1,57 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { WorkboxError } from 'workbox-core/_private/WorkboxError.js'; +import { assert } from 'workbox-core/_private/assert.js'; +import '../_version.js'; +/** + * @param {Blob} blob A source blob. + * @param {number} [start] The offset to use as the start of the + * slice. + * @param {number} [end] The offset to use as the end of the slice. + * @return {Object} An object with `start` and `end` properties, reflecting + * the effective boundaries to use given the size of the blob. + * + * @private + */ +function calculateEffectiveBoundaries(blob, start, end) { + if (process.env.NODE_ENV !== 'production') { + assert.isInstance(blob, Blob, { + moduleName: 'workbox-range-requests', + funcName: 'calculateEffectiveBoundaries', + paramName: 'blob', + }); + } + const blobSize = blob.size; + if ((end && end > blobSize) || (start && start < 0)) { + throw new WorkboxError('range-not-satisfiable', { + size: blobSize, + end, + start, + }); + } + let effectiveStart; + let effectiveEnd; + if (start !== undefined && end !== undefined) { + effectiveStart = start; + // Range values are inclusive, so add 1 to the value. + effectiveEnd = end + 1; + } + else if (start !== undefined && end === undefined) { + effectiveStart = start; + effectiveEnd = blobSize; + } + else if (end !== undefined && start === undefined) { + effectiveStart = blobSize - end; + effectiveEnd = blobSize; + } + return { + start: effectiveStart, + end: effectiveEnd, + }; +} +export { calculateEffectiveBoundaries }; diff --git a/node_modules/workbox-range-requests/utils/calculateEffectiveBoundaries.mjs b/node_modules/workbox-range-requests/utils/calculateEffectiveBoundaries.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2d136076e18928e50d64ec9ee1aba48e42b0ce8d --- /dev/null +++ b/node_modules/workbox-range-requests/utils/calculateEffectiveBoundaries.mjs @@ -0,0 +1 @@ +export * from './calculateEffectiveBoundaries.js'; \ No newline at end of file diff --git a/node_modules/workbox-range-requests/utils/parseRangeHeader.d.ts b/node_modules/workbox-range-requests/utils/parseRangeHeader.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..549a67e99de34ad5c7c65ea07ad515192a5317c9 --- /dev/null +++ b/node_modules/workbox-range-requests/utils/parseRangeHeader.d.ts @@ -0,0 +1,14 @@ +import '../_version.js'; +/** + * @param {string} rangeHeader A Range: header value. + * @return {Object} An object with `start` and `end` properties, reflecting + * the parsed value of the Range: header. If either the `start` or `end` are + * omitted, then `null` will be returned. + * + * @private + */ +declare function parseRangeHeader(rangeHeader: string): { + start?: number; + end?: number; +}; +export { parseRangeHeader }; diff --git a/node_modules/workbox-range-requests/utils/parseRangeHeader.js b/node_modules/workbox-range-requests/utils/parseRangeHeader.js new file mode 100644 index 0000000000000000000000000000000000000000..2909d27e17e9898b95d63b6eb4a15ce0690da47b --- /dev/null +++ b/node_modules/workbox-range-requests/utils/parseRangeHeader.js @@ -0,0 +1,47 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { WorkboxError } from 'workbox-core/_private/WorkboxError.js'; +import { assert } from 'workbox-core/_private/assert.js'; +import '../_version.js'; +/** + * @param {string} rangeHeader A Range: header value. + * @return {Object} An object with `start` and `end` properties, reflecting + * the parsed value of the Range: header. If either the `start` or `end` are + * omitted, then `null` will be returned. + * + * @private + */ +function parseRangeHeader(rangeHeader) { + if (process.env.NODE_ENV !== 'production') { + assert.isType(rangeHeader, 'string', { + moduleName: 'workbox-range-requests', + funcName: 'parseRangeHeader', + paramName: 'rangeHeader', + }); + } + const normalizedRangeHeader = rangeHeader.trim().toLowerCase(); + if (!normalizedRangeHeader.startsWith('bytes=')) { + throw new WorkboxError('unit-must-be-bytes', { normalizedRangeHeader }); + } + // Specifying multiple ranges separate by commas is valid syntax, but this + // library only attempts to handle a single, contiguous sequence of bytes. + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range#Syntax + if (normalizedRangeHeader.includes(',')) { + throw new WorkboxError('single-range-only', { normalizedRangeHeader }); + } + const rangeParts = /(\d*)-(\d*)/.exec(normalizedRangeHeader); + // We need either at least one of the start or end values. + if (!rangeParts || !(rangeParts[1] || rangeParts[2])) { + throw new WorkboxError('invalid-range-values', { normalizedRangeHeader }); + } + return { + start: rangeParts[1] === '' ? undefined : Number(rangeParts[1]), + end: rangeParts[2] === '' ? undefined : Number(rangeParts[2]), + }; +} +export { parseRangeHeader }; diff --git a/node_modules/workbox-range-requests/utils/parseRangeHeader.mjs b/node_modules/workbox-range-requests/utils/parseRangeHeader.mjs new file mode 100644 index 0000000000000000000000000000000000000000..cb298de106d69f68d4cee0f6c591628b1d169da2 --- /dev/null +++ b/node_modules/workbox-range-requests/utils/parseRangeHeader.mjs @@ -0,0 +1 @@ +export * from './parseRangeHeader.js'; \ No newline at end of file diff --git a/node_modules/workbox-recipes/LICENSE b/node_modules/workbox-recipes/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..845b545fd0f5031a944cda8cf9018eb066500040 --- /dev/null +++ b/node_modules/workbox-recipes/LICENSE @@ -0,0 +1,19 @@ +Copyright 2018 Google LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/workbox-recipes/README.md b/node_modules/workbox-recipes/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7c1f2728b9c87ed9c15659313b1ec6f3f63f1886 --- /dev/null +++ b/node_modules/workbox-recipes/README.md @@ -0,0 +1 @@ +This module's documentation can be found at https://developers.google.com/web/tools/workbox/modules/workbox-recipes diff --git a/node_modules/workbox-recipes/_version.d.ts b/node_modules/workbox-recipes/_version.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/workbox-recipes/_version.js b/node_modules/workbox-recipes/_version.js new file mode 100644 index 0000000000000000000000000000000000000000..d8450dec93690b6f2af0daff690ef051d9a92237 --- /dev/null +++ b/node_modules/workbox-recipes/_version.js @@ -0,0 +1,6 @@ +"use strict"; +// @ts-ignore +try { + self['workbox:recipes:7.4.0'] && _(); +} +catch (e) { } diff --git a/node_modules/workbox-recipes/_version.mjs b/node_modules/workbox-recipes/_version.mjs new file mode 100644 index 0000000000000000000000000000000000000000..716dee4ff7280d029e1369185af8dff81da8620f --- /dev/null +++ b/node_modules/workbox-recipes/_version.mjs @@ -0,0 +1 @@ +try{self['workbox:recipes:7.4.1']&&_()}catch(e){}// eslint-disable-line \ No newline at end of file diff --git a/node_modules/workbox-recipes/build/workbox-recipes.dev.js b/node_modules/workbox-recipes/build/workbox-recipes.dev.js new file mode 100644 index 0000000000000000000000000000000000000000..44d2cd25c85f34abaa98c4e57f65d60fc1dca42c --- /dev/null +++ b/node_modules/workbox-recipes/build/workbox-recipes.dev.js @@ -0,0 +1,268 @@ +this.workbox = this.workbox || {}; +this.workbox.recipes = (function (exports, registerRoute_js, StaleWhileRevalidate_js, CacheFirst_js, CacheableResponsePlugin_js, ExpirationPlugin_js, NetworkFirst_js, setCatchHandler_js, matchPrecache_js) { + 'use strict'; + + // @ts-ignore + try { + self['workbox:recipes:7.4.0'] && _(); + } catch (e) {} + + /* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * An implementation of the [Google fonts]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#google_fonts} caching recipe + * + * @memberof workbox-recipes + * + * @param {Object} [options] + * @param {string} [options.cachePrefix] Cache prefix for caching stylesheets and webfonts. Defaults to google-fonts + * @param {number} [options.maxAgeSeconds] Maximum age, in seconds, that font entries will be cached for. Defaults to 1 year + * @param {number} [options.maxEntries] Maximum number of fonts that will be cached. Defaults to 30 + */ + function googleFontsCache(options = {}) { + const sheetCacheName = `${options.cachePrefix || 'google-fonts'}-stylesheets`; + const fontCacheName = `${options.cachePrefix || 'google-fonts'}-webfonts`; + const maxAgeSeconds = options.maxAgeSeconds || 60 * 60 * 24 * 365; + const maxEntries = options.maxEntries || 30; + // Cache the Google Fonts stylesheets with a stale-while-revalidate strategy. + registerRoute_js.registerRoute(({ + url + }) => url.origin === 'https://fonts.googleapis.com', new StaleWhileRevalidate_js.StaleWhileRevalidate({ + cacheName: sheetCacheName + })); + // Cache the underlying font files with a cache-first strategy for 1 year. + registerRoute_js.registerRoute(({ + url + }) => url.origin === 'https://fonts.gstatic.com', new CacheFirst_js.CacheFirst({ + cacheName: fontCacheName, + plugins: [new CacheableResponsePlugin_js.CacheableResponsePlugin({ + statuses: [0, 200] + }), new ExpirationPlugin_js.ExpirationPlugin({ + maxAgeSeconds, + maxEntries + })] + })); + } + + /** + * @memberof workbox-recipes + + * @param {Object} options + * @param {string[]} options.urls Paths to warm the strategy's cache with + * @param {Strategy} options.strategy Strategy to use + */ + function warmStrategyCache(options) { + self.addEventListener('install', event => { + const done = options.urls.map(path => options.strategy.handleAll({ + event, + request: new Request(path) + })[1]); + event.waitUntil(Promise.all(done)); + }); + } + + /* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * An implementation of the [image caching recipe]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#caching_images} + * + * @memberof workbox-recipes + * + * @param {Object} [options] + * @param {string} [options.cacheName] Name for cache. Defaults to images + * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.destination === 'image'; + * @param {number} [options.maxAgeSeconds] Maximum age, in seconds, that font entries will be cached for. Defaults to 30 days + * @param {number} [options.maxEntries] Maximum number of images that will be cached. Defaults to 60 + * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe + * @param {string[]} [options.warmCache] Paths to call to use to warm this cache + */ + function imageCache(options = {}) { + const defaultMatchCallback = ({ + request + }) => request.destination === 'image'; + const cacheName = options.cacheName || 'images'; + const matchCallback = options.matchCallback || defaultMatchCallback; + const maxAgeSeconds = options.maxAgeSeconds || 30 * 24 * 60 * 60; + const maxEntries = options.maxEntries || 60; + const plugins = options.plugins || []; + plugins.push(new CacheableResponsePlugin_js.CacheableResponsePlugin({ + statuses: [0, 200] + })); + plugins.push(new ExpirationPlugin_js.ExpirationPlugin({ + maxEntries, + maxAgeSeconds + })); + const strategy = new CacheFirst_js.CacheFirst({ + cacheName, + plugins + }); + registerRoute_js.registerRoute(matchCallback, strategy); + // Warms the cache + if (options.warmCache) { + warmStrategyCache({ + urls: options.warmCache, + strategy + }); + } + } + + /* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * An implementation of the [CSS and JavaScript files recipe]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#cache_css_and_javascript_files} + * + * @memberof workbox-recipes + * + * @param {Object} [options] + * @param {string} [options.cacheName] Name for cache. Defaults to static-resources + * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.destination === 'style' || request.destination === 'script' || request.destination === 'worker'; + * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe + * @param {string[]} [options.warmCache] Paths to call to use to warm this cache + */ + function staticResourceCache(options = {}) { + const defaultMatchCallback = ({ + request + }) => request.destination === 'style' || request.destination === 'script' || request.destination === 'worker'; + const cacheName = options.cacheName || 'static-resources'; + const matchCallback = options.matchCallback || defaultMatchCallback; + const plugins = options.plugins || []; + plugins.push(new CacheableResponsePlugin_js.CacheableResponsePlugin({ + statuses: [0, 200] + })); + const strategy = new StaleWhileRevalidate_js.StaleWhileRevalidate({ + cacheName, + plugins + }); + registerRoute_js.registerRoute(matchCallback, strategy); + // Warms the cache + if (options.warmCache) { + warmStrategyCache({ + urls: options.warmCache, + strategy + }); + } + } + + /* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * An implementation of a page caching recipe with a network timeout + * + * @memberof workbox-recipes + * + * @param {Object} [options] + * @param {string} [options.cacheName] Name for cache. Defaults to pages + * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.mode === 'navigate'; + * @param {number} [options.networkTimoutSeconds] Maximum amount of time, in seconds, to wait on the network before falling back to cache. Defaults to 3 + * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe + * @param {string[]} [options.warmCache] Paths to call to use to warm this cache + */ + function pageCache(options = {}) { + const defaultMatchCallback = ({ + request + }) => request.mode === 'navigate'; + const cacheName = options.cacheName || 'pages'; + const matchCallback = options.matchCallback || defaultMatchCallback; + const networkTimeoutSeconds = options.networkTimeoutSeconds || 3; + const plugins = options.plugins || []; + plugins.push(new CacheableResponsePlugin_js.CacheableResponsePlugin({ + statuses: [0, 200] + })); + const strategy = new NetworkFirst_js.NetworkFirst({ + networkTimeoutSeconds, + cacheName, + plugins + }); + // Registers the route + registerRoute_js.registerRoute(matchCallback, strategy); + // Warms the cache + if (options.warmCache) { + warmStrategyCache({ + urls: options.warmCache, + strategy + }); + } + } + + /* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * An implementation of the [comprehensive fallbacks recipe]{@link https://developers.google.com/web/tools/workbox/guides/advanced-recipes#comprehensive_fallbacks}. Be sure to include the fallbacks in your precache injection + * + * @memberof workbox-recipes + * + * @param {Object} [options] + * @param {string} [options.pageFallback] Precache name to match for pag fallbacks. Defaults to offline.html + * @param {string} [options.imageFallback] Precache name to match for image fallbacks. + * @param {string} [options.fontFallback] Precache name to match for font fallbacks. + */ + function offlineFallback(options = {}) { + const pageFallback = options.pageFallback || 'offline.html'; + const imageFallback = options.imageFallback || false; + const fontFallback = options.fontFallback || false; + self.addEventListener('install', event => { + const files = [pageFallback]; + if (imageFallback) { + files.push(imageFallback); + } + if (fontFallback) { + files.push(fontFallback); + } + event.waitUntil(self.caches.open('workbox-offline-fallbacks').then(cache => cache.addAll(files))); + }); + const handler = async options => { + const dest = options.request.destination; + const cache = await self.caches.open('workbox-offline-fallbacks'); + if (dest === 'document') { + const match = (await matchPrecache_js.matchPrecache(pageFallback)) || (await cache.match(pageFallback)); + return match || Response.error(); + } + if (dest === 'image' && imageFallback !== false) { + const match = (await matchPrecache_js.matchPrecache(imageFallback)) || (await cache.match(imageFallback)); + return match || Response.error(); + } + if (dest === 'font' && fontFallback !== false) { + const match = (await matchPrecache_js.matchPrecache(fontFallback)) || (await cache.match(fontFallback)); + return match || Response.error(); + } + return Response.error(); + }; + setCatchHandler_js.setCatchHandler(handler); + } + + exports.googleFontsCache = googleFontsCache; + exports.imageCache = imageCache; + exports.offlineFallback = offlineFallback; + exports.pageCache = pageCache; + exports.staticResourceCache = staticResourceCache; + exports.warmStrategyCache = warmStrategyCache; + + return exports; + +})({}, workbox.routing, workbox.strategies, workbox.strategies, workbox.cacheableResponse, workbox.expiration, workbox.strategies, workbox.routing, workbox.precaching); +//# sourceMappingURL=workbox-recipes.dev.js.map diff --git a/node_modules/workbox-recipes/build/workbox-recipes.dev.js.map b/node_modules/workbox-recipes/build/workbox-recipes.dev.js.map new file mode 100644 index 0000000000000000000000000000000000000000..2aeac245c518db44e45ee6ba48c26a2a1c1de084 --- /dev/null +++ b/node_modules/workbox-recipes/build/workbox-recipes.dev.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-recipes.dev.js","sources":["../_version.js","../googleFontsCache.js","../warmStrategyCache.js","../imageCache.js","../staticResourceCache.js","../pageCache.js","../offlineFallback.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:recipes:7.4.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2020 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 { registerRoute } from 'workbox-routing/registerRoute.js';\nimport { StaleWhileRevalidate } from 'workbox-strategies/StaleWhileRevalidate.js';\nimport { CacheFirst } from 'workbox-strategies/CacheFirst.js';\nimport { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin.js';\nimport { ExpirationPlugin } from 'workbox-expiration/ExpirationPlugin.js';\nimport './_version.js';\n/**\n * An implementation of the [Google fonts]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#google_fonts} caching recipe\n *\n * @memberof workbox-recipes\n *\n * @param {Object} [options]\n * @param {string} [options.cachePrefix] Cache prefix for caching stylesheets and webfonts. Defaults to google-fonts\n * @param {number} [options.maxAgeSeconds] Maximum age, in seconds, that font entries will be cached for. Defaults to 1 year\n * @param {number} [options.maxEntries] Maximum number of fonts that will be cached. Defaults to 30\n */\nfunction googleFontsCache(options = {}) {\n const sheetCacheName = `${options.cachePrefix || 'google-fonts'}-stylesheets`;\n const fontCacheName = `${options.cachePrefix || 'google-fonts'}-webfonts`;\n const maxAgeSeconds = options.maxAgeSeconds || 60 * 60 * 24 * 365;\n const maxEntries = options.maxEntries || 30;\n // Cache the Google Fonts stylesheets with a stale-while-revalidate strategy.\n registerRoute(({ url }) => url.origin === 'https://fonts.googleapis.com', new StaleWhileRevalidate({\n cacheName: sheetCacheName,\n }));\n // Cache the underlying font files with a cache-first strategy for 1 year.\n registerRoute(({ url }) => url.origin === 'https://fonts.gstatic.com', new CacheFirst({\n cacheName: fontCacheName,\n plugins: [\n new CacheableResponsePlugin({\n statuses: [0, 200],\n }),\n new ExpirationPlugin({\n maxAgeSeconds,\n maxEntries,\n }),\n ],\n }));\n}\nexport { googleFontsCache };\n","import './_version.js';\n/**\n * @memberof workbox-recipes\n \n * @param {Object} options\n * @param {string[]} options.urls Paths to warm the strategy's cache with\n * @param {Strategy} options.strategy Strategy to use\n */\nfunction warmStrategyCache(options) {\n self.addEventListener('install', (event) => {\n const done = options.urls.map((path) => options.strategy.handleAll({\n event,\n request: new Request(path),\n })[1]);\n event.waitUntil(Promise.all(done));\n });\n}\nexport { warmStrategyCache };\n","/*\n Copyright 2020 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 { warmStrategyCache } from './warmStrategyCache';\nimport { registerRoute } from 'workbox-routing/registerRoute.js';\nimport { CacheFirst } from 'workbox-strategies/CacheFirst.js';\nimport { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin.js';\nimport { ExpirationPlugin } from 'workbox-expiration/ExpirationPlugin.js';\nimport './_version.js';\n/**\n * An implementation of the [image caching recipe]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#caching_images}\n *\n * @memberof workbox-recipes\n *\n * @param {Object} [options]\n * @param {string} [options.cacheName] Name for cache. Defaults to images\n * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.destination === 'image';\n * @param {number} [options.maxAgeSeconds] Maximum age, in seconds, that font entries will be cached for. Defaults to 30 days\n * @param {number} [options.maxEntries] Maximum number of images that will be cached. Defaults to 60\n * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe\n * @param {string[]} [options.warmCache] Paths to call to use to warm this cache\n */\nfunction imageCache(options = {}) {\n const defaultMatchCallback = ({ request }) => request.destination === 'image';\n const cacheName = options.cacheName || 'images';\n const matchCallback = options.matchCallback || defaultMatchCallback;\n const maxAgeSeconds = options.maxAgeSeconds || 30 * 24 * 60 * 60;\n const maxEntries = options.maxEntries || 60;\n const plugins = options.plugins || [];\n plugins.push(new CacheableResponsePlugin({\n statuses: [0, 200],\n }));\n plugins.push(new ExpirationPlugin({\n maxEntries,\n maxAgeSeconds,\n }));\n const strategy = new CacheFirst({\n cacheName,\n plugins,\n });\n registerRoute(matchCallback, strategy);\n // Warms the cache\n if (options.warmCache) {\n warmStrategyCache({ urls: options.warmCache, strategy });\n }\n}\nexport { imageCache };\n","/*\n Copyright 2020 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 { warmStrategyCache } from './warmStrategyCache';\nimport { registerRoute } from 'workbox-routing/registerRoute.js';\nimport { StaleWhileRevalidate } from 'workbox-strategies/StaleWhileRevalidate.js';\nimport { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin.js';\nimport './_version.js';\n/**\n * An implementation of the [CSS and JavaScript files recipe]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#cache_css_and_javascript_files}\n *\n * @memberof workbox-recipes\n *\n * @param {Object} [options]\n * @param {string} [options.cacheName] Name for cache. Defaults to static-resources\n * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.destination === 'style' || request.destination === 'script' || request.destination === 'worker';\n * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe\n * @param {string[]} [options.warmCache] Paths to call to use to warm this cache\n */\nfunction staticResourceCache(options = {}) {\n const defaultMatchCallback = ({ request }) => request.destination === 'style' ||\n request.destination === 'script' ||\n request.destination === 'worker';\n const cacheName = options.cacheName || 'static-resources';\n const matchCallback = options.matchCallback || defaultMatchCallback;\n const plugins = options.plugins || [];\n plugins.push(new CacheableResponsePlugin({\n statuses: [0, 200],\n }));\n const strategy = new StaleWhileRevalidate({\n cacheName,\n plugins,\n });\n registerRoute(matchCallback, strategy);\n // Warms the cache\n if (options.warmCache) {\n warmStrategyCache({ urls: options.warmCache, strategy });\n }\n}\nexport { staticResourceCache };\n","/*\n Copyright 2020 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 { warmStrategyCache } from './warmStrategyCache';\nimport { registerRoute } from 'workbox-routing/registerRoute.js';\nimport { NetworkFirst } from 'workbox-strategies/NetworkFirst.js';\nimport { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin.js';\nimport './_version.js';\n/**\n * An implementation of a page caching recipe with a network timeout\n *\n * @memberof workbox-recipes\n *\n * @param {Object} [options]\n * @param {string} [options.cacheName] Name for cache. Defaults to pages\n * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.mode === 'navigate';\n * @param {number} [options.networkTimoutSeconds] Maximum amount of time, in seconds, to wait on the network before falling back to cache. Defaults to 3\n * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe\n * @param {string[]} [options.warmCache] Paths to call to use to warm this cache\n */\nfunction pageCache(options = {}) {\n const defaultMatchCallback = ({ request }) => request.mode === 'navigate';\n const cacheName = options.cacheName || 'pages';\n const matchCallback = options.matchCallback || defaultMatchCallback;\n const networkTimeoutSeconds = options.networkTimeoutSeconds || 3;\n const plugins = options.plugins || [];\n plugins.push(new CacheableResponsePlugin({\n statuses: [0, 200],\n }));\n const strategy = new NetworkFirst({\n networkTimeoutSeconds,\n cacheName,\n plugins,\n });\n // Registers the route\n registerRoute(matchCallback, strategy);\n // Warms the cache\n if (options.warmCache) {\n warmStrategyCache({ urls: options.warmCache, strategy });\n }\n}\nexport { pageCache };\n","/*\n Copyright 2020 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 { setCatchHandler } from 'workbox-routing/setCatchHandler.js';\nimport { matchPrecache } from 'workbox-precaching/matchPrecache.js';\nimport './_version.js';\n/**\n * An implementation of the [comprehensive fallbacks recipe]{@link https://developers.google.com/web/tools/workbox/guides/advanced-recipes#comprehensive_fallbacks}. Be sure to include the fallbacks in your precache injection\n *\n * @memberof workbox-recipes\n *\n * @param {Object} [options]\n * @param {string} [options.pageFallback] Precache name to match for pag fallbacks. Defaults to offline.html\n * @param {string} [options.imageFallback] Precache name to match for image fallbacks.\n * @param {string} [options.fontFallback] Precache name to match for font fallbacks.\n */\nfunction offlineFallback(options = {}) {\n const pageFallback = options.pageFallback || 'offline.html';\n const imageFallback = options.imageFallback || false;\n const fontFallback = options.fontFallback || false;\n self.addEventListener('install', (event) => {\n const files = [pageFallback];\n if (imageFallback) {\n files.push(imageFallback);\n }\n if (fontFallback) {\n files.push(fontFallback);\n }\n event.waitUntil(self.caches\n .open('workbox-offline-fallbacks')\n .then((cache) => cache.addAll(files)));\n });\n const handler = async (options) => {\n const dest = options.request.destination;\n const cache = await self.caches.open('workbox-offline-fallbacks');\n if (dest === 'document') {\n const match = (await matchPrecache(pageFallback)) ||\n (await cache.match(pageFallback));\n return match || Response.error();\n }\n if (dest === 'image' && imageFallback !== false) {\n const match = (await matchPrecache(imageFallback)) ||\n (await cache.match(imageFallback));\n return match || Response.error();\n }\n if (dest === 'font' && fontFallback !== false) {\n const match = (await matchPrecache(fontFallback)) ||\n (await cache.match(fontFallback));\n return match || Response.error();\n }\n return Response.error();\n };\n setCatchHandler(handler);\n}\nexport { offlineFallback };\n"],"names":["self","_","e","googleFontsCache","options","sheetCacheName","cachePrefix","fontCacheName","maxAgeSeconds","maxEntries","registerRoute","url","origin","StaleWhileRevalidate","cacheName","CacheFirst","plugins","CacheableResponsePlugin","statuses","ExpirationPlugin","warmStrategyCache","addEventListener","event","done","urls","map","path","strategy","handleAll","request","Request","waitUntil","Promise","all","imageCache","defaultMatchCallback","destination","matchCallback","push","warmCache","staticResourceCache","pageCache","mode","networkTimeoutSeconds","NetworkFirst","offlineFallback","pageFallback","imageFallback","fontFallback","files","caches","open","then","cache","addAll","handler","dest","match","matchPrecache","Response","error","setCatchHandler"],"mappings":";;;;IACA;IACA,IAAI;IACAA,EAAAA,IAAI,CAAC,uBAAuB,CAAC,IAAIC,CAAC,EAAE;IACxC,CAAC,CACD,OAAOC,CAAC,EAAE,CAAE;;ICLZ;IACA;;IAEA;IACA;IACA;IACA;IAOA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,SAASC,gBAAgBA,CAACC,OAAO,GAAG,EAAE,EAAE;MACpC,MAAMC,cAAc,GAAI,CAAA,EAAED,OAAO,CAACE,WAAW,IAAI,cAAe,CAAA,YAAA,CAAa;MAC7E,MAAMC,aAAa,GAAI,CAAA,EAAEH,OAAO,CAACE,WAAW,IAAI,cAAe,CAAA,SAAA,CAAU;IACzE,EAAA,MAAME,aAAa,GAAGJ,OAAO,CAACI,aAAa,IAAI,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,GAAG;IACjE,EAAA,MAAMC,UAAU,GAAGL,OAAO,CAACK,UAAU,IAAI,EAAE;IAC3C;IACAC,EAAAA,8BAAa,CAAC,CAAC;IAAEC,I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AACC,MAAM,CAACL,KAAK,CAAC,CAAC,CAAC;IAC9C,EAAA,CAAC,CAAC;IACF,EAAA,MAAMM,OAAO,GAAG,MAAOnD,OAAO,IAAK;IAC/B,IAAA,MAAMoD,IAAI,GAAGpD,OAAO,CAACyB,OAAO,CAACO,WAAW;QACxC,MAAMiB,KAAK,GAAG,MAAMrD,IAAI,CAACkD,MAAM,CAACC,IAAI,CAAC,2BAA2B,CAAC;QACjE,IAAIK,IAAI,KAAK,UAAU,EAAE;IACrB,MAAA,MAAMC,KAAK,GAAG,CAAC,MAAMC,8BAAa,CAACZ,YAAY,CAAC,MAC3C,MAAMO,KAAK,CAACI,KAAK,CAACX,YAAY,CAAC,CAAC;IACrC,MAAA,OAAOW,KAAK,IAAIE,QAAQ,CAACC,KAAK,EAAE;IACpC,IAAA;IACA,IAAA,IAAIJ,IAAI,KAAK,OAAO,IAAIT,aAAa,KAAK,KAAK,EAAE;IAC7C,MAAA,MAAMU,KAAK,GAAG,CAAC,MAAMC,8BAAa,CAACX,aAAa,CAAC,MAC5C,MAAMM,KAAK,CAACI,KAAK,CAACV,aAAa,CAAC,CAAC;IACtC,MAAA,OAAOU,KAAK,IAAIE,QAAQ,CAACC,KAAK,EAAE;IACpC,IAAA;IACA,IAAA,IAAIJ,IAAI,KAAK,MAAM,IAAIR,YAAY,KAAK,KAAK,EAAE;IAC3C,MAAA,MAAMS,KAAK,GAAG,CAAC,MAAMC,8BAAa,CAACV,YAAY,CAAC,MAC3C,MAAMK,KAAK,CAACI,KAAK,CAACT,YAAY,CAAC,CAAC;IACrC,MAAA,OAAOS,KAAK,IAAIE,QAAQ,CAACC,KAAK,EAAE;IACpC,IAAA;IACA,IAAA,OAAOD,QAAQ,CAACC,KAAK,EAAE;MAC3B,CAAC;MACDC,kCAAe,CAACN,OAAO,CAAC;IAC5B;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/workbox-recipes/build/workbox-recipes.prod.js b/node_modules/workbox-recipes/build/workbox-recipes.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..e4cc163feaf156caa32ce736e46d1a9be085bebe --- /dev/null +++ b/node_modules/workbox-recipes/build/workbox-recipes.prod.js @@ -0,0 +1,2 @@ +this.workbox=this.workbox||{},this.workbox.recipes=function(e,s,t,n,o,a,c,r,i){"use strict";try{self["workbox:recipes:7.4.0"]&&_()}catch(e){}function u(e){self.addEventListener("install",(s=>{const t=e.urls.map((t=>e.strategy.handleAll({event:s,request:new Request(t)})[1]));s.waitUntil(Promise.all(t))}))}return e.googleFontsCache=function(e={}){const c=`${e.cachePrefix||"google-fonts"}-stylesheets`,r=`${e.cachePrefix||"google-fonts"}-webfonts`,i=e.maxAgeSeconds||31536e3,u=e.maxEntries||30;s.registerRoute((({url:e})=>"https://fonts.googleapis.com"===e.origin),new t.StaleWhileRevalidate({cacheName:c})),s.registerRoute((({url:e})=>"https://fonts.gstatic.com"===e.origin),new n.CacheFirst({cacheName:r,plugins:[new o.CacheableResponsePlugin({statuses:[0,200]}),new a.ExpirationPlugin({maxAgeSeconds:i,maxEntries:u})]}))},e.imageCache=function(e={}){const t=e.cacheName||"images",c=e.matchCallback||(({request:e})=>"image"===e.destination),r=e.maxAgeSeconds||2592e3,i=e.maxEntries||60,w=e.plugins||[];w.push(new o.CacheableResponsePlugin({statuses:[0,200]})),w.push(new a.ExpirationPlugin({maxEntries:i,maxAgeSeconds:r}));const l=new n.CacheFirst({cacheName:t,plugins:w});s.registerRoute(c,l),e.warmCache&&u({urls:e.warmCache,strategy:l})},e.offlineFallback=function(e={}){const s=e.pageFallback||"offline.html",t=e.imageFallback||!1,n=e.fontFallback||!1;self.addEventListener("install",(e=>{const o=[s];t&&o.push(t),n&&o.push(n),e.waitUntil(self.caches.open("workbox-offline-fallbacks").then((e=>e.addAll(o))))})),r.setCatchHandler((async e=>{const o=e.request.destination,a=await self.caches.open("workbox-offline-fallbacks");if("document"===o){return await i.matchPrecache(s)||await a.match(s)||Response.error()}if("image"===o&&!1!==t){return await i.matchPrecache(t)||await a.match(t)||Response.error()}if("font"===o&&!1!==n){return await i.matchPrecache(n)||await a.match(n)||Response.error()}return Response.error()}))},e.pageCache=function(e={}){const t=e.cacheName||"pages",n=e.matchCallback||(({request:e})=>"navigate"===e.mode),a=e.networkTimeoutSeconds||3,r=e.plugins||[];r.push(new o.CacheableResponsePlugin({statuses:[0,200]}));const i=new c.NetworkFirst({networkTimeoutSeconds:a,cacheName:t,plugins:r});s.registerRoute(n,i),e.warmCache&&u({urls:e.warmCache,strategy:i})},e.staticResourceCache=function(e={}){const n=e.cacheName||"static-resources",a=e.matchCallback||(({request:e})=>"style"===e.destination||"script"===e.destination||"worker"===e.destination),c=e.plugins||[];c.push(new o.CacheableResponsePlugin({statuses:[0,200]}));const r=new t.StaleWhileRevalidate({cacheName:n,plugins:c});s.registerRoute(a,r),e.warmCache&&u({urls:e.warmCache,strategy:r})},e.warmStrategyCache=u,e}({},workbox.routing,workbox.strategies,workbox.strategies,workbox.cacheableResponse,workbox.expiration,workbox.strategies,workbox.routing,workbox.precaching); +//# sourceMappingURL=workbox-recipes.prod.js.map diff --git a/node_modules/workbox-recipes/build/workbox-recipes.prod.js.map b/node_modules/workbox-recipes/build/workbox-recipes.prod.js.map new file mode 100644 index 0000000000000000000000000000000000000000..41c8672aee5e34db3af41ba15a9fcb58b907df6b --- /dev/null +++ b/node_modules/workbox-recipes/build/workbox-recipes.prod.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-recipes.prod.js","sources":["../_version.js","../warmStrategyCache.js","../googleFontsCache.js","../imageCache.js","../offlineFallback.js","../pageCache.js","../staticResourceCache.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:recipes:7.4.0'] && _();\n}\ncatch (e) { }\n","import './_version.js';\n/**\n * @memberof workbox-recipes\n \n * @param {Object} options\n * @param {string[]} options.urls Paths to warm the strategy's cache with\n * @param {Strategy} options.strategy Strategy to use\n */\nfunction warmStrategyCache(options) {\n self.addEventListener('install', (event) => {\n const done = options.urls.map((path) => options.strategy.handleAll({\n event,\n request: new Request(path),\n })[1]);\n event.waitUntil(Promise.all(done));\n });\n}\nexport { warmStrategyCache };\n","/*\n Copyright 2020 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 { registerRoute } from 'workbox-routing/registerRoute.js';\nimport { StaleWhileRevalidate } from 'workbox-strategies/StaleWhileRevalidate.js';\nimport { CacheFirst } from 'workbox-strategies/CacheFirst.js';\nimport { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin.js';\nimport { ExpirationPlugin } from 'workbox-expiration/ExpirationPlugin.js';\nimport './_version.js';\n/**\n * An implementation of the [Google fonts]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#google_fonts} caching recipe\n *\n * @memberof workbox-recipes\n *\n * @param {Object} [options]\n * @param {string} [options.cachePrefix] Cache prefix for caching stylesheets and webfonts. Defaults to google-fonts\n * @param {number} [options.maxAgeSeconds] Maximum age, in seconds, that font entries will be cached for. Defaults to 1 year\n * @param {number} [options.maxEntries] Maximum number of fonts that will be cached. Defaults to 30\n */\nfunction googleFontsCache(options = {}) {\n const sheetCacheName = `${options.cachePrefix || 'google-fonts'}-stylesheets`;\n const fontCacheName = `${options.cachePrefix || 'google-fonts'}-webfonts`;\n const maxAgeSeconds = options.maxAgeSeconds || 60 * 60 * 24 * 365;\n const maxEntries = options.maxEntries || 30;\n // Cache the Google Fonts stylesheets with a stale-while-revalidate strategy.\n registerRoute(({ url }) => url.origin === 'https://fonts.googleapis.com', new StaleWhileRevalidate({\n cacheName: sheetCacheName,\n }));\n // Cache the underlying font files with a cache-first strategy for 1 year.\n registerRoute(({ url }) => url.origin === 'https://fonts.gstatic.com', new CacheFirst({\n cacheName: fontCacheName,\n plugins: [\n new CacheableResponsePlugin({\n statuses: [0, 200],\n }),\n new ExpirationPlugin({\n maxAgeSeconds,\n maxEntries,\n }),\n ],\n }));\n}\nexport { googleFontsCache };\n","/*\n Copyright 2020 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 { warmStrategyCache } from './warmStrategyCache';\nimport { registerRoute } from 'workbox-routing/registerRoute.js';\nimport { CacheFirst } from 'workbox-strategies/CacheFirst.js';\nimport { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin.js';\nimport { ExpirationPlugin } from 'workbox-expiration/ExpirationPlugin.js';\nimport './_version.js';\n/**\n * An implementation of the [image caching recipe]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#caching_images}\n *\n * @memberof workbox-recipes\n *\n * @param {Object} [options]\n * @param {string} [options.cacheName] Name for cache. Defaults to images\n * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.destination === 'image';\n * @param {number} [options.maxAgeSeconds] Maximum age, in seconds, that font entries will be cached for. Defaults to 30 days\n * @param {number} [options.maxEntries] Maximum number of images that will be cached. Defaults to 60\n * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe\n * @param {string[]} [options.warmCache] Paths to call to use to warm this cache\n */\nfunction imageCache(options = {}) {\n const defaultMatchCallback = ({ request }) => request.destination === 'image';\n const cacheName = options.cacheName || 'images';\n const matchCallback = options.matchCallback || defaultMatchCallback;\n const maxAgeSeconds = options.maxAgeSeconds || 30 * 24 * 60 * 60;\n const maxEntries = options.maxEntries || 60;\n const plugins = options.plugins || [];\n plugins.push(new CacheableResponsePlugin({\n statuses: [0, 200],\n }));\n plugins.push(new ExpirationPlugin({\n maxEntries,\n maxAgeSeconds,\n }));\n const strategy = new CacheFirst({\n cacheName,\n plugins,\n });\n registerRoute(matchCallback, strategy);\n // Warms the cache\n if (options.warmCache) {\n warmStrategyCache({ urls: options.warmCache, strategy });\n }\n}\nexport { imageCache };\n","/*\n Copyright 2020 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 { setCatchHandler } from 'workbox-routing/setCatchHandler.js';\nimport { matchPrecache } from 'workbox-precaching/matchPrecache.js';\nimport './_version.js';\n/**\n * An implementation of the [comprehensive fallbacks recipe]{@link https://developers.google.com/web/tools/workbox/guides/advanced-recipes#comprehensive_fallbacks}. Be sure to include the fallbacks in your precache injection\n *\n * @memberof workbox-recipes\n *\n * @param {Object} [options]\n * @param {string} [options.pageFallback] Precache name to match for pag fallbacks. Defaults to offline.html\n * @param {string} [options.imageFallback] Precache name to match for image fallbacks.\n * @param {string} [options.fontFallback] Precache name to match for font fallbacks.\n */\nfunction offlineFallback(options = {}) {\n const pageFallback = options.pageFallback || 'offline.html';\n const imageFallback = options.imageFallback || false;\n const fontFallback = options.fontFallback || false;\n self.addEventListener('install', (event) => {\n const files = [pageFallback];\n if (imageFallback) {\n files.push(imageFallback);\n }\n if (fontFallback) {\n files.push(fontFallback);\n }\n event.waitUntil(self.caches\n .open('workbox-offline-fallbacks')\n .then((cache) => cache.addAll(files)));\n });\n const handler = async (options) => {\n const dest = options.request.destination;\n const cache = await self.caches.open('workbox-offline-fallbacks');\n if (dest === 'document') {\n const match = (await matchPrecache(pageFallback)) ||\n (await cache.match(pageFallback));\n return match || Response.error();\n }\n if (dest === 'image' && imageFallback !== false) {\n const match = (await matchPrecache(imageFallback)) ||\n (await cache.match(imageFallback));\n return match || Response.error();\n }\n if (dest === 'font' && fontFallback !== false) {\n const match = (await matchPrecache(fontFallback)) ||\n (await cache.match(fontFallback));\n return match || Response.error();\n }\n return Response.error();\n };\n setCatchHandler(handler);\n}\nexport { offlineFallback };\n","/*\n Copyright 2020 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 { warmStrategyCache } from './warmStrategyCache';\nimport { registerRoute } from 'workbox-routing/registerRoute.js';\nimport { NetworkFirst } from 'workbox-strategies/NetworkFirst.js';\nimport { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin.js';\nimport './_version.js';\n/**\n * An implementation of a page caching recipe with a network timeout\n *\n * @memberof workbox-recipes\n *\n * @param {Object} [options]\n * @param {string} [options.cacheName] Name for cache. Defaults to pages\n * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.mode === 'navigate';\n * @param {number} [options.networkTimoutSeconds] Maximum amount of time, in seconds, to wait on the network before falling back to cache. Defaults to 3\n * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe\n * @param {string[]} [options.warmCache] Paths to call to use to warm this cache\n */\nfunction pageCache(options = {}) {\n const defaultMatchCallback = ({ request }) => request.mode === 'navigate';\n const cacheName = options.cacheName || 'pages';\n const matchCallback = options.matchCallback || defaultMatchCallback;\n const networkTimeoutSeconds = options.networkTimeoutSeconds || 3;\n const plugins = options.plugins || [];\n plugins.push(new CacheableResponsePlugin({\n statuses: [0, 200],\n }));\n const strategy = new NetworkFirst({\n networkTimeoutSeconds,\n cacheName,\n plugins,\n });\n // Registers the route\n registerRoute(matchCallback, strategy);\n // Warms the cache\n if (options.warmCache) {\n warmStrategyCache({ urls: options.warmCache, strategy });\n }\n}\nexport { pageCache };\n","/*\n Copyright 2020 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 { warmStrategyCache } from './warmStrategyCache';\nimport { registerRoute } from 'workbox-routing/registerRoute.js';\nimport { StaleWhileRevalidate } from 'workbox-strategies/StaleWhileRevalidate.js';\nimport { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin.js';\nimport './_version.js';\n/**\n * An implementation of the [CSS and JavaScript files recipe]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#cache_css_and_javascript_files}\n *\n * @memberof workbox-recipes\n *\n * @param {Object} [options]\n * @param {string} [options.cacheName] Name for cache. Defaults to static-resources\n * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.destination === 'style' || request.destination === 'script' || request.destination === 'worker';\n * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe\n * @param {string[]} [options.warmCache] Paths to call to use to warm this cache\n */\nfunction staticResourceCache(options = {}) {\n const defaultMatchCallback = ({ request }) => request.destination === 'style' ||\n request.destination === 'script' ||\n request.destination === 'worker';\n const cacheName = options.cacheName || 'static-resources';\n const matchCallback = options.matchCallback || defaultMatchCallback;\n const plugins = options.plugins || [];\n plugins.push(new CacheableResponsePlugin({\n statuses: [0, 200],\n }));\n const strategy = new StaleWhileRevalidate({\n cacheName,\n plugins,\n });\n registerRoute(matchCallback, strategy);\n // Warms the cache\n if (options.warmCache) {\n warmStrategyCache({ urls: options.warmCache, strategy });\n }\n}\nexport { staticResourceCache };\n"],"names":["self","_","e","warmStrategyCache","options","addEventListener","event","done","urls","map","path","strategy","handleAll","request","Request","waitUntil","Promise","all","sheetCacheName","cachePrefix","fontCacheName","maxAgeSeconds","maxEntries","registerRoute","url","origin","StaleWhileRevalidate","cacheName","CacheFirst","plugins","CacheableResponsePlugin","statuses","ExpirationPlugin","matchCallback","defaultMatchCallback","destination","push","warmCache","pageFallback","imageFallback","fontFallback","files","caches","open","then","cache","addAll","setCatchHandler","async","dest","matchPrecache","match","Response","error","mode","networkTimeoutSeconds","NetworkFirst"],"mappings":"4FAEA,IACIA,KAAK,0BAA4BC,GACrC,CACA,MAAOC,GAAK,CCGZ,SAASC,EAAkBC,GACvBJ,KAAKK,iBAAiB,WAAYC,IAC9B,MAAMC,EAAOH,EAAQI,KAAKC,KAAKC,GAASN,EAAQO,SAASC,UAAU,CAC/DN,QACAO,QAAS,IAAIC,QAAQJ,KACtB,KACHJ,EAAMS,UAAUC,QAAQC,IAAIV,GAAM,GAE1C,2BCOA,SAA0BH,EAAU,IAChC,MAAMc,EAAkB,GAAEd,EAAQe,aAAe,6BAC3CC,EAAiB,GAAEhB,EAAQe,aAAe,0BAC1CE,EAAgBjB,EAAQiB,eAAiB,QACzCC,EAAalB,EAA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AATM,EAAqB,CAGrB,aAFqBC,gBAAcZ,UACxBO,EAAMM,MAAMb,IACPc,SAASC,OAC7B,CACA,GAAa,UAATJ,IAAsC,IAAlBV,EAAyB,CAG7C,aAFqBW,gBAAcX,UACxBM,EAAMM,MAAMZ,IACPa,SAASC,OAC7B,CACA,GAAa,SAATJ,IAAoC,IAAjBT,EAAwB,CAG3C,aAFqBU,gBAAcV,UACxBK,EAAMM,MAAMX,IACPY,SAASC,OAC7B,CACA,OAAOD,SAASC,OAAO,GAG/B,cCjCA,SAAmBjD,EAAU,IACzB,MACMuB,EAAYvB,EAAQuB,WAAa,QACjCM,EAAgB7B,EAAQ6B,eAFDC,GAAGrB,aAA+B,aAAjBA,EAAQyC,MAGhDC,EAAwBnD,EAAQmD,uBAAyB,EACzD1B,EAAUzB,EAAQyB,SAAW,GACnCA,EAAQO,KAAK,IAAIN,0BAAwB,CACrCC,SAAU,CAAC,EAAG,QAElB,MAAMpB,EAAW,IAAI6C,eAAa,CAC9BD,wBACA5B,YACAE,YAGJN,EAAAA,cAAcU,EAAetB,GAEzBP,EAAQiC,WACRlC,EAAkB,CAAEK,KAAMJ,EAAQiC,UAAW1B,YAErD,wBCrBA,SAA6BP,EAAU,IACnC,MAGMuB,EAAYvB,EAAQuB,WAAa,mBACjCM,EAAgB7B,EAAQ6B,eAJDC,GAAGrB,aAAsC,UAAxBA,EAAQsB,aAC1B,WAAxBtB,EAAQsB,aACgB,WAAxBtB,EAAQsB,aAGNN,EAAUzB,EAAQyB,SAAW,GACnCA,EAAQO,KAAK,IAAIN,0BAAwB,CACrCC,SAAU,CAAC,EAAG,QAElB,MAAMpB,EAAW,IAAIe,uBAAqB,CACtCC,YACAE,YAEJN,EAAAA,cAAcU,EAAetB,GAEzBP,EAAQiC,WACRlC,EAAkB,CAAEK,KAAMJ,EAAQiC,UAAW1B,YAErD"} \ No newline at end of file diff --git a/node_modules/workbox-recipes/googleFontsCache.d.ts b/node_modules/workbox-recipes/googleFontsCache.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c2a15ac757be35e5d83439e1b1285ecd1f399f45 --- /dev/null +++ b/node_modules/workbox-recipes/googleFontsCache.d.ts @@ -0,0 +1,18 @@ +import './_version.js'; +export interface GoogleFontCacheOptions { + cachePrefix?: string; + maxAgeSeconds?: number; + maxEntries?: number; +} +/** + * An implementation of the [Google fonts]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#google_fonts} caching recipe + * + * @memberof workbox-recipes + * + * @param {Object} [options] + * @param {string} [options.cachePrefix] Cache prefix for caching stylesheets and webfonts. Defaults to google-fonts + * @param {number} [options.maxAgeSeconds] Maximum age, in seconds, that font entries will be cached for. Defaults to 1 year + * @param {number} [options.maxEntries] Maximum number of fonts that will be cached. Defaults to 30 + */ +declare function googleFontsCache(options?: GoogleFontCacheOptions): void; +export { googleFontsCache }; diff --git a/node_modules/workbox-recipes/googleFontsCache.js b/node_modules/workbox-recipes/googleFontsCache.js new file mode 100644 index 0000000000000000000000000000000000000000..137745b2fc0c9b8c0b049f826234d7efc035ad58 --- /dev/null +++ b/node_modules/workbox-recipes/googleFontsCache.js @@ -0,0 +1,47 @@ +/* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { registerRoute } from 'workbox-routing/registerRoute.js'; +import { StaleWhileRevalidate } from 'workbox-strategies/StaleWhileRevalidate.js'; +import { CacheFirst } from 'workbox-strategies/CacheFirst.js'; +import { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin.js'; +import { ExpirationPlugin } from 'workbox-expiration/ExpirationPlugin.js'; +import './_version.js'; +/** + * An implementation of the [Google fonts]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#google_fonts} caching recipe + * + * @memberof workbox-recipes + * + * @param {Object} [options] + * @param {string} [options.cachePrefix] Cache prefix for caching stylesheets and webfonts. Defaults to google-fonts + * @param {number} [options.maxAgeSeconds] Maximum age, in seconds, that font entries will be cached for. Defaults to 1 year + * @param {number} [options.maxEntries] Maximum number of fonts that will be cached. Defaults to 30 + */ +function googleFontsCache(options = {}) { + const sheetCacheName = `${options.cachePrefix || 'google-fonts'}-stylesheets`; + const fontCacheName = `${options.cachePrefix || 'google-fonts'}-webfonts`; + const maxAgeSeconds = options.maxAgeSeconds || 60 * 60 * 24 * 365; + const maxEntries = options.maxEntries || 30; + // Cache the Google Fonts stylesheets with a stale-while-revalidate strategy. + registerRoute(({ url }) => url.origin === 'https://fonts.googleapis.com', new StaleWhileRevalidate({ + cacheName: sheetCacheName, + })); + // Cache the underlying font files with a cache-first strategy for 1 year. + registerRoute(({ url }) => url.origin === 'https://fonts.gstatic.com', new CacheFirst({ + cacheName: fontCacheName, + plugins: [ + new CacheableResponsePlugin({ + statuses: [0, 200], + }), + new ExpirationPlugin({ + maxAgeSeconds, + maxEntries, + }), + ], + })); +} +export { googleFontsCache }; diff --git a/node_modules/workbox-recipes/googleFontsCache.mjs b/node_modules/workbox-recipes/googleFontsCache.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5d504b3422b2b3b1cf6bd9e7dbc876c02190d9be --- /dev/null +++ b/node_modules/workbox-recipes/googleFontsCache.mjs @@ -0,0 +1 @@ +export * from './googleFontsCache.js'; \ No newline at end of file diff --git a/node_modules/workbox-recipes/imageCache.d.ts b/node_modules/workbox-recipes/imageCache.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..15409253fe4c40f6ebc4685de975e70fcdb19a85 --- /dev/null +++ b/node_modules/workbox-recipes/imageCache.d.ts @@ -0,0 +1,25 @@ +import { RouteMatchCallback, WorkboxPlugin } from 'workbox-core/types.js'; +import './_version.js'; +export interface ImageCacheOptions { + cacheName?: string; + matchCallback?: RouteMatchCallback; + maxAgeSeconds?: number; + maxEntries?: number; + plugins?: Array; + warmCache?: Array; +} +/** + * An implementation of the [image caching recipe]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#caching_images} + * + * @memberof workbox-recipes + * + * @param {Object} [options] + * @param {string} [options.cacheName] Name for cache. Defaults to images + * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.destination === 'image'; + * @param {number} [options.maxAgeSeconds] Maximum age, in seconds, that font entries will be cached for. Defaults to 30 days + * @param {number} [options.maxEntries] Maximum number of images that will be cached. Defaults to 60 + * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe + * @param {string[]} [options.warmCache] Paths to call to use to warm this cache + */ +declare function imageCache(options?: ImageCacheOptions): void; +export { imageCache }; diff --git a/node_modules/workbox-recipes/imageCache.js b/node_modules/workbox-recipes/imageCache.js new file mode 100644 index 0000000000000000000000000000000000000000..009398e108095414f75d9eb6c7beb9dbf04a846c --- /dev/null +++ b/node_modules/workbox-recipes/imageCache.js @@ -0,0 +1,51 @@ +/* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { warmStrategyCache } from './warmStrategyCache'; +import { registerRoute } from 'workbox-routing/registerRoute.js'; +import { CacheFirst } from 'workbox-strategies/CacheFirst.js'; +import { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin.js'; +import { ExpirationPlugin } from 'workbox-expiration/ExpirationPlugin.js'; +import './_version.js'; +/** + * An implementation of the [image caching recipe]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#caching_images} + * + * @memberof workbox-recipes + * + * @param {Object} [options] + * @param {string} [options.cacheName] Name for cache. Defaults to images + * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.destination === 'image'; + * @param {number} [options.maxAgeSeconds] Maximum age, in seconds, that font entries will be cached for. Defaults to 30 days + * @param {number} [options.maxEntries] Maximum number of images that will be cached. Defaults to 60 + * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe + * @param {string[]} [options.warmCache] Paths to call to use to warm this cache + */ +function imageCache(options = {}) { + const defaultMatchCallback = ({ request }) => request.destination === 'image'; + const cacheName = options.cacheName || 'images'; + const matchCallback = options.matchCallback || defaultMatchCallback; + const maxAgeSeconds = options.maxAgeSeconds || 30 * 24 * 60 * 60; + const maxEntries = options.maxEntries || 60; + const plugins = options.plugins || []; + plugins.push(new CacheableResponsePlugin({ + statuses: [0, 200], + })); + plugins.push(new ExpirationPlugin({ + maxEntries, + maxAgeSeconds, + })); + const strategy = new CacheFirst({ + cacheName, + plugins, + }); + registerRoute(matchCallback, strategy); + // Warms the cache + if (options.warmCache) { + warmStrategyCache({ urls: options.warmCache, strategy }); + } +} +export { imageCache }; diff --git a/node_modules/workbox-recipes/imageCache.mjs b/node_modules/workbox-recipes/imageCache.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b730b267e3caa41d693533229846be3a1ef207cc --- /dev/null +++ b/node_modules/workbox-recipes/imageCache.mjs @@ -0,0 +1 @@ +export * from './imageCache.js'; \ No newline at end of file diff --git a/node_modules/workbox-recipes/index.d.ts b/node_modules/workbox-recipes/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dae01e0428201ddc15e988eda8193684964261d7 --- /dev/null +++ b/node_modules/workbox-recipes/index.d.ts @@ -0,0 +1,11 @@ +import { googleFontsCache, GoogleFontCacheOptions } from './googleFontsCache'; +import { imageCache, ImageCacheOptions } from './imageCache'; +import { staticResourceCache, StaticResourceOptions } from './staticResourceCache'; +import { pageCache, PageCacheOptions } from './pageCache'; +import { offlineFallback, OfflineFallbackOptions } from './offlineFallback'; +import { warmStrategyCache, WarmStrategyCacheOptions } from './warmStrategyCache'; +import './_version.js'; +/** + * @module workbox-recipes + */ +export { GoogleFontCacheOptions, googleFontsCache, imageCache, ImageCacheOptions, offlineFallback, OfflineFallbackOptions, pageCache, PageCacheOptions, staticResourceCache, StaticResourceOptions, warmStrategyCache, WarmStrategyCacheOptions, }; diff --git a/node_modules/workbox-recipes/index.js b/node_modules/workbox-recipes/index.js new file mode 100644 index 0000000000000000000000000000000000000000..53031a9470d1613fc1a4bb78cc97fce9fc4eecf0 --- /dev/null +++ b/node_modules/workbox-recipes/index.js @@ -0,0 +1,18 @@ +/* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { googleFontsCache } from './googleFontsCache'; +import { imageCache } from './imageCache'; +import { staticResourceCache, } from './staticResourceCache'; +import { pageCache } from './pageCache'; +import { offlineFallback } from './offlineFallback'; +import { warmStrategyCache } from './warmStrategyCache'; +import './_version.js'; +/** + * @module workbox-recipes + */ +export { googleFontsCache, imageCache, offlineFallback, pageCache, staticResourceCache, warmStrategyCache, }; diff --git a/node_modules/workbox-recipes/index.mjs b/node_modules/workbox-recipes/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..833b6a2f3226fec78490a3b7a622dc5146f94b53 --- /dev/null +++ b/node_modules/workbox-recipes/index.mjs @@ -0,0 +1 @@ +export * from './index.js'; \ No newline at end of file diff --git a/node_modules/workbox-recipes/offlineFallback.d.ts b/node_modules/workbox-recipes/offlineFallback.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b540b2fa6a3624c9387a3232d3d1e8323e435918 --- /dev/null +++ b/node_modules/workbox-recipes/offlineFallback.d.ts @@ -0,0 +1,18 @@ +import './_version.js'; +export interface OfflineFallbackOptions { + pageFallback?: string; + imageFallback?: string; + fontFallback?: string; +} +/** + * An implementation of the [comprehensive fallbacks recipe]{@link https://developers.google.com/web/tools/workbox/guides/advanced-recipes#comprehensive_fallbacks}. Be sure to include the fallbacks in your precache injection + * + * @memberof workbox-recipes + * + * @param {Object} [options] + * @param {string} [options.pageFallback] Precache name to match for pag fallbacks. Defaults to offline.html + * @param {string} [options.imageFallback] Precache name to match for image fallbacks. + * @param {string} [options.fontFallback] Precache name to match for font fallbacks. + */ +declare function offlineFallback(options?: OfflineFallbackOptions): void; +export { offlineFallback }; diff --git a/node_modules/workbox-recipes/offlineFallback.js b/node_modules/workbox-recipes/offlineFallback.js new file mode 100644 index 0000000000000000000000000000000000000000..00f7ed86b151b3c98251444defaee08ec3498435 --- /dev/null +++ b/node_modules/workbox-recipes/offlineFallback.js @@ -0,0 +1,59 @@ +/* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { setCatchHandler } from 'workbox-routing/setCatchHandler.js'; +import { matchPrecache } from 'workbox-precaching/matchPrecache.js'; +import './_version.js'; +/** + * An implementation of the [comprehensive fallbacks recipe]{@link https://developers.google.com/web/tools/workbox/guides/advanced-recipes#comprehensive_fallbacks}. Be sure to include the fallbacks in your precache injection + * + * @memberof workbox-recipes + * + * @param {Object} [options] + * @param {string} [options.pageFallback] Precache name to match for pag fallbacks. Defaults to offline.html + * @param {string} [options.imageFallback] Precache name to match for image fallbacks. + * @param {string} [options.fontFallback] Precache name to match for font fallbacks. + */ +function offlineFallback(options = {}) { + const pageFallback = options.pageFallback || 'offline.html'; + const imageFallback = options.imageFallback || false; + const fontFallback = options.fontFallback || false; + self.addEventListener('install', (event) => { + const files = [pageFallback]; + if (imageFallback) { + files.push(imageFallback); + } + if (fontFallback) { + files.push(fontFallback); + } + event.waitUntil(self.caches + .open('workbox-offline-fallbacks') + .then((cache) => cache.addAll(files))); + }); + const handler = async (options) => { + const dest = options.request.destination; + const cache = await self.caches.open('workbox-offline-fallbacks'); + if (dest === 'document') { + const match = (await matchPrecache(pageFallback)) || + (await cache.match(pageFallback)); + return match || Response.error(); + } + if (dest === 'image' && imageFallback !== false) { + const match = (await matchPrecache(imageFallback)) || + (await cache.match(imageFallback)); + return match || Response.error(); + } + if (dest === 'font' && fontFallback !== false) { + const match = (await matchPrecache(fontFallback)) || + (await cache.match(fontFallback)); + return match || Response.error(); + } + return Response.error(); + }; + setCatchHandler(handler); +} +export { offlineFallback }; diff --git a/node_modules/workbox-recipes/offlineFallback.mjs b/node_modules/workbox-recipes/offlineFallback.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1a9c311a083ff1b7c86d8d27c13e59c23a3e219a --- /dev/null +++ b/node_modules/workbox-recipes/offlineFallback.mjs @@ -0,0 +1 @@ +export * from './offlineFallback.js'; \ No newline at end of file diff --git a/node_modules/workbox-recipes/package.json b/node_modules/workbox-recipes/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a64615f6040eb4b702cadffb34d74ee0b7e3d50c --- /dev/null +++ b/node_modules/workbox-recipes/package.json @@ -0,0 +1,37 @@ +{ + "name": "workbox-recipes", + "version": "7.4.1", + "license": "MIT", + "author": "Google's Web DevRel Team and Google's Aurora Team", + "description": "A service worker helper library to manage common request and caching patterns", + "repository": { + "type": "git", + "url": "git+https://github.com/googlechrome/workbox.git" + }, + "bugs": "https://github.com/googlechrome/workbox/issues", + "homepage": "https://github.com/GoogleChrome/workbox", + "keywords": [ + "workbox", + "workboxjs", + "service worker", + "sw", + "router", + "routing" + ], + "workbox": { + "browserNamespace": "workbox.recipes", + "packageType": "sw" + }, + "main": "index.js", + "module": "index.mjs", + "types": "index.d.ts", + "dependencies": { + "workbox-cacheable-response": "7.4.1", + "workbox-core": "7.4.1", + "workbox-expiration": "7.4.1", + "workbox-precaching": "7.4.1", + "workbox-routing": "7.4.1", + "workbox-strategies": "7.4.1" + }, + "gitHead": "62b9d8ba8eb3c1a2ab8aac9d84c90cda7865d6a3" +} diff --git a/node_modules/workbox-recipes/pageCache.d.ts b/node_modules/workbox-recipes/pageCache.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5f38f78caed10837dafc0355df8a53beb5d748bc --- /dev/null +++ b/node_modules/workbox-recipes/pageCache.d.ts @@ -0,0 +1,23 @@ +import { RouteMatchCallback, WorkboxPlugin } from 'workbox-core/types.js'; +import './_version.js'; +export interface PageCacheOptions { + cacheName?: string; + matchCallback?: RouteMatchCallback; + networkTimeoutSeconds?: number; + plugins?: Array; + warmCache?: Array; +} +/** + * An implementation of a page caching recipe with a network timeout + * + * @memberof workbox-recipes + * + * @param {Object} [options] + * @param {string} [options.cacheName] Name for cache. Defaults to pages + * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.mode === 'navigate'; + * @param {number} [options.networkTimoutSeconds] Maximum amount of time, in seconds, to wait on the network before falling back to cache. Defaults to 3 + * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe + * @param {string[]} [options.warmCache] Paths to call to use to warm this cache + */ +declare function pageCache(options?: PageCacheOptions): void; +export { pageCache }; diff --git a/node_modules/workbox-recipes/pageCache.js b/node_modules/workbox-recipes/pageCache.js new file mode 100644 index 0000000000000000000000000000000000000000..3aa4f9c84b4129ba3be923f1cda00be072bc66db --- /dev/null +++ b/node_modules/workbox-recipes/pageCache.js @@ -0,0 +1,46 @@ +/* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { warmStrategyCache } from './warmStrategyCache'; +import { registerRoute } from 'workbox-routing/registerRoute.js'; +import { NetworkFirst } from 'workbox-strategies/NetworkFirst.js'; +import { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin.js'; +import './_version.js'; +/** + * An implementation of a page caching recipe with a network timeout + * + * @memberof workbox-recipes + * + * @param {Object} [options] + * @param {string} [options.cacheName] Name for cache. Defaults to pages + * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.mode === 'navigate'; + * @param {number} [options.networkTimoutSeconds] Maximum amount of time, in seconds, to wait on the network before falling back to cache. Defaults to 3 + * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe + * @param {string[]} [options.warmCache] Paths to call to use to warm this cache + */ +function pageCache(options = {}) { + const defaultMatchCallback = ({ request }) => request.mode === 'navigate'; + const cacheName = options.cacheName || 'pages'; + const matchCallback = options.matchCallback || defaultMatchCallback; + const networkTimeoutSeconds = options.networkTimeoutSeconds || 3; + const plugins = options.plugins || []; + plugins.push(new CacheableResponsePlugin({ + statuses: [0, 200], + })); + const strategy = new NetworkFirst({ + networkTimeoutSeconds, + cacheName, + plugins, + }); + // Registers the route + registerRoute(matchCallback, strategy); + // Warms the cache + if (options.warmCache) { + warmStrategyCache({ urls: options.warmCache, strategy }); + } +} +export { pageCache }; diff --git a/node_modules/workbox-recipes/pageCache.mjs b/node_modules/workbox-recipes/pageCache.mjs new file mode 100644 index 0000000000000000000000000000000000000000..875aab883267ec46528fa2dffe27b8f23db4e4a7 --- /dev/null +++ b/node_modules/workbox-recipes/pageCache.mjs @@ -0,0 +1 @@ +export * from './pageCache.js'; \ No newline at end of file diff --git a/node_modules/workbox-recipes/src/_version.ts b/node_modules/workbox-recipes/src/_version.ts new file mode 100644 index 0000000000000000000000000000000000000000..1580d828ad2617bdc32369aed9e358eeb46f17ca --- /dev/null +++ b/node_modules/workbox-recipes/src/_version.ts @@ -0,0 +1,2 @@ +// @ts-ignore +try{self['workbox:recipes:7.4.1']&&_()}catch(e){} \ No newline at end of file diff --git a/node_modules/workbox-recipes/src/googleFontsCache.ts b/node_modules/workbox-recipes/src/googleFontsCache.ts new file mode 100644 index 0000000000000000000000000000000000000000..6fd48665bb1886cc968fad4a3ca2a6fc2551bae9 --- /dev/null +++ b/node_modules/workbox-recipes/src/googleFontsCache.ts @@ -0,0 +1,64 @@ +/* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import {registerRoute} from 'workbox-routing/registerRoute.js'; +import {StaleWhileRevalidate} from 'workbox-strategies/StaleWhileRevalidate.js'; +import {CacheFirst} from 'workbox-strategies/CacheFirst.js'; +import {CacheableResponsePlugin} from 'workbox-cacheable-response/CacheableResponsePlugin.js'; +import {ExpirationPlugin} from 'workbox-expiration/ExpirationPlugin.js'; + +import './_version.js'; + +export interface GoogleFontCacheOptions { + cachePrefix?: string; + maxAgeSeconds?: number; + maxEntries?: number; +} + +/** + * An implementation of the [Google fonts]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#google_fonts} caching recipe + * + * @memberof workbox-recipes + * + * @param {Object} [options] + * @param {string} [options.cachePrefix] Cache prefix for caching stylesheets and webfonts. Defaults to google-fonts + * @param {number} [options.maxAgeSeconds] Maximum age, in seconds, that font entries will be cached for. Defaults to 1 year + * @param {number} [options.maxEntries] Maximum number of fonts that will be cached. Defaults to 30 + */ +function googleFontsCache(options: GoogleFontCacheOptions = {}): void { + const sheetCacheName = `${options.cachePrefix || 'google-fonts'}-stylesheets`; + const fontCacheName = `${options.cachePrefix || 'google-fonts'}-webfonts`; + const maxAgeSeconds = options.maxAgeSeconds || 60 * 60 * 24 * 365; + const maxEntries = options.maxEntries || 30; + + // Cache the Google Fonts stylesheets with a stale-while-revalidate strategy. + registerRoute( + ({url}) => url.origin === 'https://fonts.googleapis.com', + new StaleWhileRevalidate({ + cacheName: sheetCacheName, + }), + ); + + // Cache the underlying font files with a cache-first strategy for 1 year. + registerRoute( + ({url}) => url.origin === 'https://fonts.gstatic.com', + new CacheFirst({ + cacheName: fontCacheName, + plugins: [ + new CacheableResponsePlugin({ + statuses: [0, 200], + }), + new ExpirationPlugin({ + maxAgeSeconds, + maxEntries, + }), + ], + }), + ); +} + +export {googleFontsCache}; diff --git a/node_modules/workbox-recipes/src/imageCache.ts b/node_modules/workbox-recipes/src/imageCache.ts new file mode 100644 index 0000000000000000000000000000000000000000..42be8ccef34e458534ec14c10e68212760823108 --- /dev/null +++ b/node_modules/workbox-recipes/src/imageCache.ts @@ -0,0 +1,77 @@ +/* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import {warmStrategyCache} from './warmStrategyCache'; +import {registerRoute} from 'workbox-routing/registerRoute.js'; +import {CacheFirst} from 'workbox-strategies/CacheFirst.js'; +import {CacheableResponsePlugin} from 'workbox-cacheable-response/CacheableResponsePlugin.js'; +import {ExpirationPlugin} from 'workbox-expiration/ExpirationPlugin.js'; +import { + RouteMatchCallback, + RouteMatchCallbackOptions, + WorkboxPlugin, +} from 'workbox-core/types.js'; + +import './_version.js'; + +export interface ImageCacheOptions { + cacheName?: string; + matchCallback?: RouteMatchCallback; + maxAgeSeconds?: number; + maxEntries?: number; + plugins?: Array; + warmCache?: Array; +} + +/** + * An implementation of the [image caching recipe]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#caching_images} + * + * @memberof workbox-recipes + * + * @param {Object} [options] + * @param {string} [options.cacheName] Name for cache. Defaults to images + * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.destination === 'image'; + * @param {number} [options.maxAgeSeconds] Maximum age, in seconds, that font entries will be cached for. Defaults to 30 days + * @param {number} [options.maxEntries] Maximum number of images that will be cached. Defaults to 60 + * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe + * @param {string[]} [options.warmCache] Paths to call to use to warm this cache + */ +function imageCache(options: ImageCacheOptions = {}): void { + const defaultMatchCallback = ({request}: RouteMatchCallbackOptions) => + request.destination === 'image'; + + const cacheName = options.cacheName || 'images'; + const matchCallback = options.matchCallback || defaultMatchCallback; + const maxAgeSeconds = options.maxAgeSeconds || 30 * 24 * 60 * 60; + const maxEntries = options.maxEntries || 60; + const plugins = options.plugins || []; + plugins.push( + new CacheableResponsePlugin({ + statuses: [0, 200], + }), + ); + plugins.push( + new ExpirationPlugin({ + maxEntries, + maxAgeSeconds, + }), + ); + + const strategy = new CacheFirst({ + cacheName, + plugins, + }); + + registerRoute(matchCallback, strategy); + + // Warms the cache + if (options.warmCache) { + warmStrategyCache({urls: options.warmCache, strategy}); + } +} + +export {imageCache}; diff --git a/node_modules/workbox-recipes/src/index.ts b/node_modules/workbox-recipes/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..702e50e7a7b63842a365924a5569a35077ed78ca --- /dev/null +++ b/node_modules/workbox-recipes/src/index.ts @@ -0,0 +1,38 @@ +/* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {googleFontsCache, GoogleFontCacheOptions} from './googleFontsCache'; +import {imageCache, ImageCacheOptions} from './imageCache'; +import { + staticResourceCache, + StaticResourceOptions, +} from './staticResourceCache'; +import {pageCache, PageCacheOptions} from './pageCache'; +import {offlineFallback, OfflineFallbackOptions} from './offlineFallback'; +import {warmStrategyCache, WarmStrategyCacheOptions} from './warmStrategyCache'; + +import './_version.js'; + +/** + * @module workbox-recipes + */ + +export { + GoogleFontCacheOptions, + googleFontsCache, + imageCache, + ImageCacheOptions, + offlineFallback, + OfflineFallbackOptions, + pageCache, + PageCacheOptions, + staticResourceCache, + StaticResourceOptions, + warmStrategyCache, + WarmStrategyCacheOptions, +}; diff --git a/node_modules/workbox-recipes/src/offlineFallback.ts b/node_modules/workbox-recipes/src/offlineFallback.ts new file mode 100644 index 0000000000000000000000000000000000000000..0b6572f62ce59b81ab8ca1e089f935422cae1170 --- /dev/null +++ b/node_modules/workbox-recipes/src/offlineFallback.ts @@ -0,0 +1,87 @@ +/* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import {setCatchHandler} from 'workbox-routing/setCatchHandler.js'; +import {matchPrecache} from 'workbox-precaching/matchPrecache.js'; +import {RouteHandler, RouteHandlerCallbackOptions} from 'workbox-core/types.js'; + +import './_version.js'; + +export interface OfflineFallbackOptions { + pageFallback?: string; + imageFallback?: string; + fontFallback?: string; +} + +// Give TypeScript the correct global. +declare let self: ServiceWorkerGlobalScope; + +/** + * An implementation of the [comprehensive fallbacks recipe]{@link https://developers.google.com/web/tools/workbox/guides/advanced-recipes#comprehensive_fallbacks}. Be sure to include the fallbacks in your precache injection + * + * @memberof workbox-recipes + * + * @param {Object} [options] + * @param {string} [options.pageFallback] Precache name to match for pag fallbacks. Defaults to offline.html + * @param {string} [options.imageFallback] Precache name to match for image fallbacks. + * @param {string} [options.fontFallback] Precache name to match for font fallbacks. + */ +function offlineFallback(options: OfflineFallbackOptions = {}): void { + const pageFallback = options.pageFallback || 'offline.html'; + const imageFallback = options.imageFallback || false; + const fontFallback = options.fontFallback || false; + + self.addEventListener('install', (event) => { + const files = [pageFallback]; + if (imageFallback) { + files.push(imageFallback); + } + if (fontFallback) { + files.push(fontFallback); + } + + event.waitUntil( + self.caches + .open('workbox-offline-fallbacks') + .then((cache) => cache.addAll(files)), + ); + }); + + const handler: RouteHandler = async ( + options: RouteHandlerCallbackOptions, + ) => { + const dest = options.request.destination; + const cache = await self.caches.open('workbox-offline-fallbacks'); + + if (dest === 'document') { + const match = + (await matchPrecache(pageFallback)) || + (await cache.match(pageFallback)); + return match || Response.error(); + } + + if (dest === 'image' && imageFallback !== false) { + const match = + (await matchPrecache(imageFallback)) || + (await cache.match(imageFallback)); + return match || Response.error(); + } + + if (dest === 'font' && fontFallback !== false) { + const match = + (await matchPrecache(fontFallback)) || + (await cache.match(fontFallback)); + return match || Response.error(); + } + + return Response.error(); + }; + + setCatchHandler(handler); +} + +export {offlineFallback}; diff --git a/node_modules/workbox-recipes/src/pageCache.ts b/node_modules/workbox-recipes/src/pageCache.ts new file mode 100644 index 0000000000000000000000000000000000000000..6c6782c058ddf26d8820c4e2d6a455d0ed87e97a --- /dev/null +++ b/node_modules/workbox-recipes/src/pageCache.ts @@ -0,0 +1,69 @@ +/* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import {warmStrategyCache} from './warmStrategyCache'; +import {registerRoute} from 'workbox-routing/registerRoute.js'; +import {NetworkFirst} from 'workbox-strategies/NetworkFirst.js'; +import {CacheableResponsePlugin} from 'workbox-cacheable-response/CacheableResponsePlugin.js'; +import { + RouteMatchCallback, + RouteMatchCallbackOptions, + WorkboxPlugin, +} from 'workbox-core/types.js'; + +import './_version.js'; + +export interface PageCacheOptions { + cacheName?: string; + matchCallback?: RouteMatchCallback; + networkTimeoutSeconds?: number; + plugins?: Array; + warmCache?: Array; +} + +/** + * An implementation of a page caching recipe with a network timeout + * + * @memberof workbox-recipes + * + * @param {Object} [options] + * @param {string} [options.cacheName] Name for cache. Defaults to pages + * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.mode === 'navigate'; + * @param {number} [options.networkTimoutSeconds] Maximum amount of time, in seconds, to wait on the network before falling back to cache. Defaults to 3 + * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe + * @param {string[]} [options.warmCache] Paths to call to use to warm this cache + */ +function pageCache(options: PageCacheOptions = {}): void { + const defaultMatchCallback = ({request}: RouteMatchCallbackOptions) => + request.mode === 'navigate'; + + const cacheName = options.cacheName || 'pages'; + const matchCallback = options.matchCallback || defaultMatchCallback; + const networkTimeoutSeconds = options.networkTimeoutSeconds || 3; + const plugins = options.plugins || []; + plugins.push( + new CacheableResponsePlugin({ + statuses: [0, 200], + }), + ); + + const strategy = new NetworkFirst({ + networkTimeoutSeconds, + cacheName, + plugins, + }); + + // Registers the route + registerRoute(matchCallback, strategy); + + // Warms the cache + if (options.warmCache) { + warmStrategyCache({urls: options.warmCache, strategy}); + } +} + +export {pageCache}; diff --git a/node_modules/workbox-recipes/src/staticResourceCache.ts b/node_modules/workbox-recipes/src/staticResourceCache.ts new file mode 100644 index 0000000000000000000000000000000000000000..915866baf562254a02ad6f81ba843885196f5f54 --- /dev/null +++ b/node_modules/workbox-recipes/src/staticResourceCache.ts @@ -0,0 +1,66 @@ +/* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import {warmStrategyCache} from './warmStrategyCache'; +import {registerRoute} from 'workbox-routing/registerRoute.js'; +import {StaleWhileRevalidate} from 'workbox-strategies/StaleWhileRevalidate.js'; +import {CacheableResponsePlugin} from 'workbox-cacheable-response/CacheableResponsePlugin.js'; +import { + RouteMatchCallback, + RouteMatchCallbackOptions, + WorkboxPlugin, +} from 'workbox-core/types.js'; + +import './_version.js'; + +export interface StaticResourceOptions { + cacheName?: string; + matchCallback?: RouteMatchCallback; + plugins?: Array; + warmCache?: Array; +} + +/** + * An implementation of the [CSS and JavaScript files recipe]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#cache_css_and_javascript_files} + * + * @memberof workbox-recipes + * + * @param {Object} [options] + * @param {string} [options.cacheName] Name for cache. Defaults to static-resources + * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.destination === 'style' || request.destination === 'script' || request.destination === 'worker'; + * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe + * @param {string[]} [options.warmCache] Paths to call to use to warm this cache + */ +function staticResourceCache(options: StaticResourceOptions = {}): void { + const defaultMatchCallback = ({request}: RouteMatchCallbackOptions) => + request.destination === 'style' || + request.destination === 'script' || + request.destination === 'worker'; + + const cacheName = options.cacheName || 'static-resources'; + const matchCallback = options.matchCallback || defaultMatchCallback; + const plugins = options.plugins || []; + plugins.push( + new CacheableResponsePlugin({ + statuses: [0, 200], + }), + ); + + const strategy = new StaleWhileRevalidate({ + cacheName, + plugins, + }); + + registerRoute(matchCallback, strategy); + + // Warms the cache + if (options.warmCache) { + warmStrategyCache({urls: options.warmCache, strategy}); + } +} + +export {staticResourceCache}; diff --git a/node_modules/workbox-recipes/src/warmStrategyCache.ts b/node_modules/workbox-recipes/src/warmStrategyCache.ts new file mode 100644 index 0000000000000000000000000000000000000000..1847a237840e1255775514e62220c3d50f9febbb --- /dev/null +++ b/node_modules/workbox-recipes/src/warmStrategyCache.ts @@ -0,0 +1,34 @@ +import {Strategy} from 'workbox-strategies/Strategy.js'; + +import './_version.js'; + +export interface WarmStrategyCacheOptions { + urls: Array; + strategy: Strategy; +} + +// Give TypeScript the correct global. +declare let self: ServiceWorkerGlobalScope; + +/** + * @memberof workbox-recipes + + * @param {Object} options + * @param {string[]} options.urls Paths to warm the strategy's cache with + * @param {Strategy} options.strategy Strategy to use + */ +function warmStrategyCache(options: WarmStrategyCacheOptions): void { + self.addEventListener('install', (event) => { + const done = options.urls.map( + (path) => + options.strategy.handleAll({ + event, + request: new Request(path), + })[1], + ); + + event.waitUntil(Promise.all(done)); + }); +} + +export {warmStrategyCache}; diff --git a/node_modules/workbox-recipes/staticResourceCache.d.ts b/node_modules/workbox-recipes/staticResourceCache.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..64cf27db43fb4e324d90e70e84a81c16e8b05505 --- /dev/null +++ b/node_modules/workbox-recipes/staticResourceCache.d.ts @@ -0,0 +1,21 @@ +import { RouteMatchCallback, WorkboxPlugin } from 'workbox-core/types.js'; +import './_version.js'; +export interface StaticResourceOptions { + cacheName?: string; + matchCallback?: RouteMatchCallback; + plugins?: Array; + warmCache?: Array; +} +/** + * An implementation of the [CSS and JavaScript files recipe]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#cache_css_and_javascript_files} + * + * @memberof workbox-recipes + * + * @param {Object} [options] + * @param {string} [options.cacheName] Name for cache. Defaults to static-resources + * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.destination === 'style' || request.destination === 'script' || request.destination === 'worker'; + * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe + * @param {string[]} [options.warmCache] Paths to call to use to warm this cache + */ +declare function staticResourceCache(options?: StaticResourceOptions): void; +export { staticResourceCache }; diff --git a/node_modules/workbox-recipes/staticResourceCache.js b/node_modules/workbox-recipes/staticResourceCache.js new file mode 100644 index 0000000000000000000000000000000000000000..1338ce0da4ee0c2b3d9fb3dad07c708b2b5529aa --- /dev/null +++ b/node_modules/workbox-recipes/staticResourceCache.js @@ -0,0 +1,44 @@ +/* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { warmStrategyCache } from './warmStrategyCache'; +import { registerRoute } from 'workbox-routing/registerRoute.js'; +import { StaleWhileRevalidate } from 'workbox-strategies/StaleWhileRevalidate.js'; +import { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin.js'; +import './_version.js'; +/** + * An implementation of the [CSS and JavaScript files recipe]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#cache_css_and_javascript_files} + * + * @memberof workbox-recipes + * + * @param {Object} [options] + * @param {string} [options.cacheName] Name for cache. Defaults to static-resources + * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.destination === 'style' || request.destination === 'script' || request.destination === 'worker'; + * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe + * @param {string[]} [options.warmCache] Paths to call to use to warm this cache + */ +function staticResourceCache(options = {}) { + const defaultMatchCallback = ({ request }) => request.destination === 'style' || + request.destination === 'script' || + request.destination === 'worker'; + const cacheName = options.cacheName || 'static-resources'; + const matchCallback = options.matchCallback || defaultMatchCallback; + const plugins = options.plugins || []; + plugins.push(new CacheableResponsePlugin({ + statuses: [0, 200], + })); + const strategy = new StaleWhileRevalidate({ + cacheName, + plugins, + }); + registerRoute(matchCallback, strategy); + // Warms the cache + if (options.warmCache) { + warmStrategyCache({ urls: options.warmCache, strategy }); + } +} +export { staticResourceCache }; diff --git a/node_modules/workbox-recipes/staticResourceCache.mjs b/node_modules/workbox-recipes/staticResourceCache.mjs new file mode 100644 index 0000000000000000000000000000000000000000..89f66e79ba8045ce42bf7bfb20b7f3ccebc6e0a5 --- /dev/null +++ b/node_modules/workbox-recipes/staticResourceCache.mjs @@ -0,0 +1 @@ +export * from './staticResourceCache.js'; \ No newline at end of file diff --git a/node_modules/workbox-recipes/tsconfig.json b/node_modules/workbox-recipes/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..22f8f82b305d99fc1d6e85ed02a34654ac82ab8f --- /dev/null +++ b/node_modules/workbox-recipes/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../tsconfig", + "compilerOptions": { + "outDir": "./", + "rootDir": "./src", + "tsBuildInfoFile": "./tsconfig.tsbuildinfo" + }, + "include": ["src/**/*.ts"], + "references": [ + {"path": "../workbox-core/"}, + {"path": "../workbox-routing/"}, + {"path": "../workbox-strategies/"}, + {"path": "../workbox-cacheable-response/"}, + {"path": "../workbox-expiration/"}, + {"path": "../workbox-precaching/"} + ] +} diff --git a/node_modules/workbox-recipes/warmStrategyCache.d.ts b/node_modules/workbox-recipes/warmStrategyCache.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2ab9b62975aaecd9d4f7b594d37dbf68b5d449d7 --- /dev/null +++ b/node_modules/workbox-recipes/warmStrategyCache.d.ts @@ -0,0 +1,15 @@ +import { Strategy } from 'workbox-strategies/Strategy.js'; +import './_version.js'; +export interface WarmStrategyCacheOptions { + urls: Array; + strategy: Strategy; +} +/** + * @memberof workbox-recipes + + * @param {Object} options + * @param {string[]} options.urls Paths to warm the strategy's cache with + * @param {Strategy} options.strategy Strategy to use + */ +declare function warmStrategyCache(options: WarmStrategyCacheOptions): void; +export { warmStrategyCache }; diff --git a/node_modules/workbox-recipes/warmStrategyCache.js b/node_modules/workbox-recipes/warmStrategyCache.js new file mode 100644 index 0000000000000000000000000000000000000000..b34884827a1947e22a76fdf9da0cc976bc4c3a1c --- /dev/null +++ b/node_modules/workbox-recipes/warmStrategyCache.js @@ -0,0 +1,18 @@ +import './_version.js'; +/** + * @memberof workbox-recipes + + * @param {Object} options + * @param {string[]} options.urls Paths to warm the strategy's cache with + * @param {Strategy} options.strategy Strategy to use + */ +function warmStrategyCache(options) { + self.addEventListener('install', (event) => { + const done = options.urls.map((path) => options.strategy.handleAll({ + event, + request: new Request(path), + })[1]); + event.waitUntil(Promise.all(done)); + }); +} +export { warmStrategyCache }; diff --git a/node_modules/workbox-recipes/warmStrategyCache.mjs b/node_modules/workbox-recipes/warmStrategyCache.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ded7db71b4feaa2ac73aa0e88257661fd835a284 --- /dev/null +++ b/node_modules/workbox-recipes/warmStrategyCache.mjs @@ -0,0 +1 @@ +export * from './warmStrategyCache.js'; \ No newline at end of file diff --git a/node_modules/workbox-routing/LICENSE b/node_modules/workbox-routing/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..845b545fd0f5031a944cda8cf9018eb066500040 --- /dev/null +++ b/node_modules/workbox-routing/LICENSE @@ -0,0 +1,19 @@ +Copyright 2018 Google LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/workbox-routing/NavigationRoute.d.ts b/node_modules/workbox-routing/NavigationRoute.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5add7e5803ab8c9c48b1741f30656b076015e0a0 --- /dev/null +++ b/node_modules/workbox-routing/NavigationRoute.d.ts @@ -0,0 +1,63 @@ +import { RouteHandler } from 'workbox-core/types.js'; +import { Route } from './Route.js'; +import './_version.js'; +export interface NavigationRouteMatchOptions { + allowlist?: RegExp[]; + denylist?: RegExp[]; +} +/** + * NavigationRoute makes it easy to create a + * {@link workbox-routing.Route} that matches for browser + * [navigation requests]{@link https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests}. + * + * It will only match incoming Requests whose + * {@link https://fetch.spec.whatwg.org/#concept-request-mode|mode} + * is set to `navigate`. + * + * You can optionally only apply this route to a subset of navigation requests + * by using one or both of the `denylist` and `allowlist` parameters. + * + * @memberof workbox-routing + * @extends workbox-routing.Route + */ +declare class NavigationRoute extends Route { + private readonly _allowlist; + private readonly _denylist; + /** + * If both `denylist` and `allowlist` are provided, the `denylist` will + * take precedence and the request will not match this route. + * + * The regular expressions in `allowlist` and `denylist` + * are matched against the concatenated + * [`pathname`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/pathname} + * and [`search`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search} + * portions of the requested URL. + * + * *Note*: These RegExps may be evaluated against every destination URL during + * a navigation. Avoid using + * [complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077), + * or else your users may see delays when navigating your site. + * + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + * @param {Object} options + * @param {Array} [options.denylist] If any of these patterns match, + * the route will not handle the request (even if a allowlist RegExp matches). + * @param {Array} [options.allowlist=[/./]] If any of these patterns + * match the URL's pathname and search parameter, the route will handle the + * request (assuming the denylist doesn't match). + */ + constructor(handler: RouteHandler, { allowlist, denylist }?: NavigationRouteMatchOptions); + /** + * Routes match handler. + * + * @param {Object} options + * @param {URL} options.url + * @param {Request} options.request + * @return {boolean} + * + * @private + */ + private _match; +} +export { NavigationRoute }; diff --git a/node_modules/workbox-routing/NavigationRoute.js b/node_modules/workbox-routing/NavigationRoute.js new file mode 100644 index 0000000000000000000000000000000000000000..692ac3a5d43e10f188285f823d9532f4db92f1e7 --- /dev/null +++ b/node_modules/workbox-routing/NavigationRoute.js @@ -0,0 +1,110 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { assert } from 'workbox-core/_private/assert.js'; +import { logger } from 'workbox-core/_private/logger.js'; +import { Route } from './Route.js'; +import './_version.js'; +/** + * NavigationRoute makes it easy to create a + * {@link workbox-routing.Route} that matches for browser + * [navigation requests]{@link https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests}. + * + * It will only match incoming Requests whose + * {@link https://fetch.spec.whatwg.org/#concept-request-mode|mode} + * is set to `navigate`. + * + * You can optionally only apply this route to a subset of navigation requests + * by using one or both of the `denylist` and `allowlist` parameters. + * + * @memberof workbox-routing + * @extends workbox-routing.Route + */ +class NavigationRoute extends Route { + /** + * If both `denylist` and `allowlist` are provided, the `denylist` will + * take precedence and the request will not match this route. + * + * The regular expressions in `allowlist` and `denylist` + * are matched against the concatenated + * [`pathname`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/pathname} + * and [`search`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search} + * portions of the requested URL. + * + * *Note*: These RegExps may be evaluated against every destination URL during + * a navigation. Avoid using + * [complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077), + * or else your users may see delays when navigating your site. + * + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + * @param {Object} options + * @param {Array} [options.denylist] If any of these patterns match, + * the route will not handle the request (even if a allowlist RegExp matches). + * @param {Array} [options.allowlist=[/./]] If any of these patterns + * match the URL's pathname and search parameter, the route will handle the + * request (assuming the denylist doesn't match). + */ + constructor(handler, { allowlist = [/./], denylist = [] } = {}) { + if (process.env.NODE_ENV !== 'production') { + assert.isArrayOfClass(allowlist, RegExp, { + moduleName: 'workbox-routing', + className: 'NavigationRoute', + funcName: 'constructor', + paramName: 'options.allowlist', + }); + assert.isArrayOfClass(denylist, RegExp, { + moduleName: 'workbox-routing', + className: 'NavigationRoute', + funcName: 'constructor', + paramName: 'options.denylist', + }); + } + super((options) => this._match(options), handler); + this._allowlist = allowlist; + this._denylist = denylist; + } + /** + * Routes match handler. + * + * @param {Object} options + * @param {URL} options.url + * @param {Request} options.request + * @return {boolean} + * + * @private + */ + _match({ url, request }) { + if (request && request.mode !== 'navigate') { + return false; + } + const pathnameAndSearch = url.pathname + url.search; + for (const regExp of this._denylist) { + if (regExp.test(pathnameAndSearch)) { + if (process.env.NODE_ENV !== 'production') { + logger.log(`The navigation route ${pathnameAndSearch} is not ` + + `being used, since the URL matches this denylist pattern: ` + + `${regExp.toString()}`); + } + return false; + } + } + if (this._allowlist.some((regExp) => regExp.test(pathnameAndSearch))) { + if (process.env.NODE_ENV !== 'production') { + logger.debug(`The navigation route ${pathnameAndSearch} ` + `is being used.`); + } + return true; + } + if (process.env.NODE_ENV !== 'production') { + logger.log(`The navigation route ${pathnameAndSearch} is not ` + + `being used, since the URL being navigated to doesn't ` + + `match the allowlist.`); + } + return false; + } +} +export { NavigationRoute }; diff --git a/node_modules/workbox-routing/NavigationRoute.mjs b/node_modules/workbox-routing/NavigationRoute.mjs new file mode 100644 index 0000000000000000000000000000000000000000..23432c2be12d740ebb620fbbab9f3d05c452277d --- /dev/null +++ b/node_modules/workbox-routing/NavigationRoute.mjs @@ -0,0 +1 @@ +export * from './NavigationRoute.js'; \ No newline at end of file diff --git a/node_modules/workbox-routing/README.md b/node_modules/workbox-routing/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0c19ecc1f9712bd42ce264233062a0873053c202 --- /dev/null +++ b/node_modules/workbox-routing/README.md @@ -0,0 +1 @@ +This module's documentation can be found at https://developers.google.com/web/tools/workbox/modules/workbox-routing diff --git a/node_modules/workbox-routing/RegExpRoute.d.ts b/node_modules/workbox-routing/RegExpRoute.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..77a1d4f356953405e57640d7186cd924bb3143b4 --- /dev/null +++ b/node_modules/workbox-routing/RegExpRoute.d.ts @@ -0,0 +1,32 @@ +import { RouteHandler } from 'workbox-core/types.js'; +import { HTTPMethod } from './utils/constants.js'; +import { Route } from './Route.js'; +import './_version.js'; +/** + * RegExpRoute makes it easy to create a regular expression based + * {@link workbox-routing.Route}. + * + * For same-origin requests the RegExp only needs to match part of the URL. For + * requests against third-party servers, you must define a RegExp that matches + * the start of the URL. + * + * @memberof workbox-routing + * @extends workbox-routing.Route + */ +declare class RegExpRoute extends Route { + /** + * If the regular expression contains + * [capture groups]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references}, + * the captured values will be passed to the + * {@link workbox-routing~handlerCallback} `params` + * argument. + * + * @param {RegExp} regExp The regular expression to match against URLs. + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + * @param {string} [method='GET'] The HTTP method to match the Route + * against. + */ + constructor(regExp: RegExp, handler: RouteHandler, method?: HTTPMethod); +} +export { RegExpRoute }; diff --git a/node_modules/workbox-routing/RegExpRoute.js b/node_modules/workbox-routing/RegExpRoute.js new file mode 100644 index 0000000000000000000000000000000000000000..9bf0365b6a7e498aed7bcaf16157c544de0a71d7 --- /dev/null +++ b/node_modules/workbox-routing/RegExpRoute.js @@ -0,0 +1,73 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { assert } from 'workbox-core/_private/assert.js'; +import { logger } from 'workbox-core/_private/logger.js'; +import { Route } from './Route.js'; +import './_version.js'; +/** + * RegExpRoute makes it easy to create a regular expression based + * {@link workbox-routing.Route}. + * + * For same-origin requests the RegExp only needs to match part of the URL. For + * requests against third-party servers, you must define a RegExp that matches + * the start of the URL. + * + * @memberof workbox-routing + * @extends workbox-routing.Route + */ +class RegExpRoute extends Route { + /** + * If the regular expression contains + * [capture groups]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references}, + * the captured values will be passed to the + * {@link workbox-routing~handlerCallback} `params` + * argument. + * + * @param {RegExp} regExp The regular expression to match against URLs. + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + * @param {string} [method='GET'] The HTTP method to match the Route + * against. + */ + constructor(regExp, handler, method) { + if (process.env.NODE_ENV !== 'production') { + assert.isInstance(regExp, RegExp, { + moduleName: 'workbox-routing', + className: 'RegExpRoute', + funcName: 'constructor', + paramName: 'pattern', + }); + } + const match = ({ url }) => { + const result = regExp.exec(url.href); + // Return immediately if there's no match. + if (!result) { + return; + } + // Require that the match start at the first character in the URL string + // if it's a cross-origin request. + // See https://github.com/GoogleChrome/workbox/issues/281 for the context + // behind this behavior. + if (url.origin !== location.origin && result.index !== 0) { + if (process.env.NODE_ENV !== 'production') { + logger.debug(`The regular expression '${regExp.toString()}' only partially matched ` + + `against the cross-origin URL '${url.toString()}'. RegExpRoute's will only ` + + `handle cross-origin requests if they match the entire URL.`); + } + return; + } + // If the route matches, but there aren't any capture groups defined, then + // this will return [], which is truthy and therefore sufficient to + // indicate a match. + // If there are capture groups, then it will return their values. + return result.slice(1); + }; + super(match, handler, method); + } +} +export { RegExpRoute }; diff --git a/node_modules/workbox-routing/RegExpRoute.mjs b/node_modules/workbox-routing/RegExpRoute.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d17e49239bdbcc13e53fefc8b485ef3a4defef47 --- /dev/null +++ b/node_modules/workbox-routing/RegExpRoute.mjs @@ -0,0 +1 @@ +export * from './RegExpRoute.js'; \ No newline at end of file diff --git a/node_modules/workbox-routing/Route.d.ts b/node_modules/workbox-routing/Route.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..39b1ec4d2b5c8169e344a98e9abf8ca9a307f8fd --- /dev/null +++ b/node_modules/workbox-routing/Route.d.ts @@ -0,0 +1,37 @@ +import { HTTPMethod } from './utils/constants.js'; +import { RouteHandler, RouteHandlerObject, RouteMatchCallback } from 'workbox-core/types.js'; +import './_version.js'; +/** + * A `Route` consists of a pair of callback functions, "match" and "handler". + * The "match" callback determine if a route should be used to "handle" a + * request by returning a non-falsy value if it can. The "handler" callback + * is called when there is a match and should return a Promise that resolves + * to a `Response`. + * + * @memberof workbox-routing + */ +declare class Route { + handler: RouteHandlerObject; + match: RouteMatchCallback; + method: HTTPMethod; + catchHandler?: RouteHandlerObject; + /** + * Constructor for Route class. + * + * @param {workbox-routing~matchCallback} match + * A callback function that determines whether the route matches a given + * `fetch` event by returning a non-falsy value. + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resolving to a Response. + * @param {string} [method='GET'] The HTTP method to match the Route + * against. + */ + constructor(match: RouteMatchCallback, handler: RouteHandler, method?: HTTPMethod); + /** + * + * @param {workbox-routing-handlerCallback} handler A callback + * function that returns a Promise resolving to a Response + */ + setCatchHandler(handler: RouteHandler): void; +} +export { Route }; diff --git a/node_modules/workbox-routing/Route.js b/node_modules/workbox-routing/Route.js new file mode 100644 index 0000000000000000000000000000000000000000..c269922b0a0715300e35884a9262292e2bc51a35 --- /dev/null +++ b/node_modules/workbox-routing/Route.js @@ -0,0 +1,60 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { assert } from 'workbox-core/_private/assert.js'; +import { defaultMethod, validMethods } from './utils/constants.js'; +import { normalizeHandler } from './utils/normalizeHandler.js'; +import './_version.js'; +/** + * A `Route` consists of a pair of callback functions, "match" and "handler". + * The "match" callback determine if a route should be used to "handle" a + * request by returning a non-falsy value if it can. The "handler" callback + * is called when there is a match and should return a Promise that resolves + * to a `Response`. + * + * @memberof workbox-routing + */ +class Route { + /** + * Constructor for Route class. + * + * @param {workbox-routing~matchCallback} match + * A callback function that determines whether the route matches a given + * `fetch` event by returning a non-falsy value. + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resolving to a Response. + * @param {string} [method='GET'] The HTTP method to match the Route + * against. + */ + constructor(match, handler, method = defaultMethod) { + if (process.env.NODE_ENV !== 'production') { + assert.isType(match, 'function', { + moduleName: 'workbox-routing', + className: 'Route', + funcName: 'constructor', + paramName: 'match', + }); + if (method) { + assert.isOneOf(method, validMethods, { paramName: 'method' }); + } + } + // These values are referenced directly by Router so cannot be + // altered by minificaton. + this.handler = normalizeHandler(handler); + this.match = match; + this.method = method; + } + /** + * + * @param {workbox-routing-handlerCallback} handler A callback + * function that returns a Promise resolving to a Response + */ + setCatchHandler(handler) { + this.catchHandler = normalizeHandler(handler); + } +} +export { Route }; diff --git a/node_modules/workbox-routing/Route.mjs b/node_modules/workbox-routing/Route.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4c008d63ac7b2912fe5462b8887d582e775bf42c --- /dev/null +++ b/node_modules/workbox-routing/Route.mjs @@ -0,0 +1 @@ +export * from './Route.js'; \ No newline at end of file diff --git a/node_modules/workbox-routing/Router.d.ts b/node_modules/workbox-routing/Router.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a5c21d09dd1cf3a4dc0d4de54f25f26d9ece4845 --- /dev/null +++ b/node_modules/workbox-routing/Router.d.ts @@ -0,0 +1,135 @@ +import { RouteHandler, RouteHandlerCallbackOptions, RouteMatchCallbackOptions } from 'workbox-core/types.js'; +import { HTTPMethod } from './utils/constants.js'; +import { Route } from './Route.js'; +import './_version.js'; +/** + * The Router can be used to process a `FetchEvent` using one or more + * {@link workbox-routing.Route}, responding with a `Response` if + * a matching route exists. + * + * If no route matches a given a request, the Router will use a "default" + * handler if one is defined. + * + * Should the matching Route throw an error, the Router will use a "catch" + * handler if one is defined to gracefully deal with issues and respond with a + * Request. + * + * If a request matches multiple routes, the **earliest** registered route will + * be used to respond to the request. + * + * @memberof workbox-routing + */ +declare class Router { + private readonly _routes; + private readonly _defaultHandlerMap; + private _catchHandler?; + /** + * Initializes a new Router. + */ + constructor(); + /** + * @return {Map>} routes A `Map` of HTTP + * method name ('GET', etc.) to an array of all the corresponding `Route` + * instances that are registered. + */ + get routes(): Map; + /** + * Adds a fetch event listener to respond to events when a route matches + * the event's request. + */ + addFetchListener(): void; + /** + * Adds a message event listener for URLs to cache from the window. + * This is useful to cache resources loaded on the page prior to when the + * service worker started controlling it. + * + * The format of the message data sent from the window should be as follows. + * Where the `urlsToCache` array may consist of URL strings or an array of + * URL string + `requestInit` object (the same as you'd pass to `fetch()`). + * + * ``` + * { + * type: 'CACHE_URLS', + * payload: { + * urlsToCache: [ + * './script1.js', + * './script2.js', + * ['./script3.js', {mode: 'no-cors'}], + * ], + * }, + * } + * ``` + */ + addCacheListener(): void; + /** + * Apply the routing rules to a FetchEvent object to get a Response from an + * appropriate Route's handler. + * + * @param {Object} options + * @param {Request} options.request The request to handle. + * @param {ExtendableEvent} options.event The event that triggered the + * request. + * @return {Promise|undefined} A promise is returned if a + * registered route can handle the request. If there is no matching + * route and there's no `defaultHandler`, `undefined` is returned. + */ + handleRequest({ request, event, }: { + request: Request; + event: ExtendableEvent; + }): Promise | undefined; + /** + * Checks a request and URL (and optionally an event) against the list of + * registered routes, and if there's a match, returns the corresponding + * route along with any params generated by the match. + * + * @param {Object} options + * @param {URL} options.url + * @param {boolean} options.sameOrigin The result of comparing `url.origin` + * against the current origin. + * @param {Request} options.request The request to match. + * @param {Event} options.event The corresponding event. + * @return {Object} An object with `route` and `params` properties. + * They are populated if a matching route was found or `undefined` + * otherwise. + */ + findMatchingRoute({ url, sameOrigin, request, event, }: RouteMatchCallbackOptions): { + route?: Route; + params?: RouteHandlerCallbackOptions['params']; + }; + /** + * Define a default `handler` that's called when no routes explicitly + * match the incoming request. + * + * Each HTTP method ('GET', 'POST', etc.) gets its own default handler. + * + * Without a default handler, unmatched requests will go against the + * network as if there were no service worker present. + * + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + * @param {string} [method='GET'] The HTTP method to associate with this + * default handler. Each method has its own default. + */ + setDefaultHandler(handler: RouteHandler, method?: HTTPMethod): void; + /** + * If a Route throws an error while handling a request, this `handler` + * will be called and given a chance to provide a response. + * + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + */ + setCatchHandler(handler: RouteHandler): void; + /** + * Registers a route with the router. + * + * @param {workbox-routing.Route} route The route to register. + */ + registerRoute(route: Route): void; + /** + * Unregisters a route with the router. + * + * @param {workbox-routing.Route} route The route to unregister. + */ + unregisterRoute(route: Route): void; +} +export { Router }; diff --git a/node_modules/workbox-routing/Router.js b/node_modules/workbox-routing/Router.js new file mode 100644 index 0000000000000000000000000000000000000000..3e94f088a0f7f6e86a14889633446bf090f3d0ae --- /dev/null +++ b/node_modules/workbox-routing/Router.js @@ -0,0 +1,393 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { assert } from 'workbox-core/_private/assert.js'; +import { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js'; +import { defaultMethod } from './utils/constants.js'; +import { logger } from 'workbox-core/_private/logger.js'; +import { normalizeHandler } from './utils/normalizeHandler.js'; +import { WorkboxError } from 'workbox-core/_private/WorkboxError.js'; +import './_version.js'; +/** + * The Router can be used to process a `FetchEvent` using one or more + * {@link workbox-routing.Route}, responding with a `Response` if + * a matching route exists. + * + * If no route matches a given a request, the Router will use a "default" + * handler if one is defined. + * + * Should the matching Route throw an error, the Router will use a "catch" + * handler if one is defined to gracefully deal with issues and respond with a + * Request. + * + * If a request matches multiple routes, the **earliest** registered route will + * be used to respond to the request. + * + * @memberof workbox-routing + */ +class Router { + /** + * Initializes a new Router. + */ + constructor() { + this._routes = new Map(); + this._defaultHandlerMap = new Map(); + } + /** + * @return {Map>} routes A `Map` of HTTP + * method name ('GET', etc.) to an array of all the corresponding `Route` + * instances that are registered. + */ + get routes() { + return this._routes; + } + /** + * Adds a fetch event listener to respond to events when a route matches + * the event's request. + */ + addFetchListener() { + // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705 + self.addEventListener('fetch', ((event) => { + const { request } = event; + const responsePromise = this.handleRequest({ request, event }); + if (responsePromise) { + event.respondWith(responsePromise); + } + })); + } + /** + * Adds a message event listener for URLs to cache from the window. + * This is useful to cache resources loaded on the page prior to when the + * service worker started controlling it. + * + * The format of the message data sent from the window should be as follows. + * Where the `urlsToCache` array may consist of URL strings or an array of + * URL string + `requestInit` object (the same as you'd pass to `fetch()`). + * + * ``` + * { + * type: 'CACHE_URLS', + * payload: { + * urlsToCache: [ + * './script1.js', + * './script2.js', + * ['./script3.js', {mode: 'no-cors'}], + * ], + * }, + * } + * ``` + */ + addCacheListener() { + // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705 + self.addEventListener('message', ((event) => { + // event.data is type 'any' + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (event.data && event.data.type === 'CACHE_URLS') { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const { payload } = event.data; + if (process.env.NODE_ENV !== 'production') { + logger.debug(`Caching URLs from the window`, payload.urlsToCache); + } + const requestPromises = Promise.all(payload.urlsToCache.map((entry) => { + if (typeof entry === 'string') { + entry = [entry]; + } + const request = new Request(...entry); + return this.handleRequest({ request, event }); + // TODO(philipwalton): TypeScript errors without this typecast for + // some reason (probably a bug). The real type here should work but + // doesn't: `Array | undefined>`. + })); // TypeScript + event.waitUntil(requestPromises); + // If a MessageChannel was used, reply to the message on success. + if (event.ports && event.ports[0]) { + void requestPromises.then(() => event.ports[0].postMessage(true)); + } + } + })); + } + /** + * Apply the routing rules to a FetchEvent object to get a Response from an + * appropriate Route's handler. + * + * @param {Object} options + * @param {Request} options.request The request to handle. + * @param {ExtendableEvent} options.event The event that triggered the + * request. + * @return {Promise|undefined} A promise is returned if a + * registered route can handle the request. If there is no matching + * route and there's no `defaultHandler`, `undefined` is returned. + */ + handleRequest({ request, event, }) { + if (process.env.NODE_ENV !== 'production') { + assert.isInstance(request, Request, { + moduleName: 'workbox-routing', + className: 'Router', + funcName: 'handleRequest', + paramName: 'options.request', + }); + } + const url = new URL(request.url, location.href); + if (!url.protocol.startsWith('http')) { + if (process.env.NODE_ENV !== 'production') { + logger.debug(`Workbox Router only supports URLs that start with 'http'.`); + } + return; + } + const sameOrigin = url.origin === location.origin; + const { params, route } = this.findMatchingRoute({ + event, + request, + sameOrigin, + url, + }); + let handler = route && route.handler; + const debugMessages = []; + if (process.env.NODE_ENV !== 'production') { + if (handler) { + debugMessages.push([`Found a route to handle this request:`, route]); + if (params) { + debugMessages.push([ + `Passing the following params to the route's handler:`, + params, + ]); + } + } + } + // If we don't have a handler because there was no matching route, then + // fall back to defaultHandler if that's defined. + const method = request.method; + if (!handler && this._defaultHandlerMap.has(method)) { + if (process.env.NODE_ENV !== 'production') { + debugMessages.push(`Failed to find a matching route. Falling ` + + `back to the default handler for ${method}.`); + } + handler = this._defaultHandlerMap.get(method); + } + if (!handler) { + if (process.env.NODE_ENV !== 'production') { + // No handler so Workbox will do nothing. If logs is set of debug + // i.e. verbose, we should print out this information. + logger.debug(`No route found for: ${getFriendlyURL(url)}`); + } + return; + } + if (process.env.NODE_ENV !== 'production') { + // We have a handler, meaning Workbox is going to handle the route. + // print the routing details to the console. + logger.groupCollapsed(`Router is responding to: ${getFriendlyURL(url)}`); + debugMessages.forEach((msg) => { + if (Array.isArray(msg)) { + logger.log(...msg); + } + else { + logger.log(msg); + } + }); + logger.groupEnd(); + } + // Wrap in try and catch in case the handle method throws a synchronous + // error. It should still callback to the catch handler. + let responsePromise; + try { + responsePromise = handler.handle({ url, request, event, params }); + } + catch (err) { + responsePromise = Promise.reject(err); + } + // Get route's catch handler, if it exists + const catchHandler = route && route.catchHandler; + if (responsePromise instanceof Promise && + (this._catchHandler || catchHandler)) { + responsePromise = responsePromise.catch(async (err) => { + // If there's a route catch handler, process that first + if (catchHandler) { + if (process.env.NODE_ENV !== 'production') { + // Still include URL here as it will be async from the console group + // and may not make sense without the URL + logger.groupCollapsed(`Error thrown when responding to: ` + + ` ${getFriendlyURL(url)}. Falling back to route's Catch Handler.`); + logger.error(`Error thrown by:`, route); + logger.error(err); + logger.groupEnd(); + } + try { + return await catchHandler.handle({ url, request, event, params }); + } + catch (catchErr) { + if (catchErr instanceof Error) { + err = catchErr; + } + } + } + if (this._catchHandler) { + if (process.env.NODE_ENV !== 'production') { + // Still include URL here as it will be async from the console group + // and may not make sense without the URL + logger.groupCollapsed(`Error thrown when responding to: ` + + ` ${getFriendlyURL(url)}. Falling back to global Catch Handler.`); + logger.error(`Error thrown by:`, route); + logger.error(err); + logger.groupEnd(); + } + return this._catchHandler.handle({ url, request, event }); + } + throw err; + }); + } + return responsePromise; + } + /** + * Checks a request and URL (and optionally an event) against the list of + * registered routes, and if there's a match, returns the corresponding + * route along with any params generated by the match. + * + * @param {Object} options + * @param {URL} options.url + * @param {boolean} options.sameOrigin The result of comparing `url.origin` + * against the current origin. + * @param {Request} options.request The request to match. + * @param {Event} options.event The corresponding event. + * @return {Object} An object with `route` and `params` properties. + * They are populated if a matching route was found or `undefined` + * otherwise. + */ + findMatchingRoute({ url, sameOrigin, request, event, }) { + const routes = this._routes.get(request.method) || []; + for (const route of routes) { + let params; + // route.match returns type any, not possible to change right now. + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const matchResult = route.match({ url, sameOrigin, request, event }); + if (matchResult) { + if (process.env.NODE_ENV !== 'production') { + // Warn developers that using an async matchCallback is almost always + // not the right thing to do. + if (matchResult instanceof Promise) { + logger.warn(`While routing ${getFriendlyURL(url)}, an async ` + + `matchCallback function was used. Please convert the ` + + `following route to use a synchronous matchCallback function:`, route); + } + } + // See https://github.com/GoogleChrome/workbox/issues/2079 + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + params = matchResult; + if (Array.isArray(params) && params.length === 0) { + // Instead of passing an empty array in as params, use undefined. + params = undefined; + } + else if (matchResult.constructor === Object && // eslint-disable-line + Object.keys(matchResult).length === 0) { + // Instead of passing an empty object in as params, use undefined. + params = undefined; + } + else if (typeof matchResult === 'boolean') { + // For the boolean value true (rather than just something truth-y), + // don't set params. + // See https://github.com/GoogleChrome/workbox/pull/2134#issuecomment-513924353 + params = undefined; + } + // Return early if have a match. + return { route, params }; + } + } + // If no match was found above, return and empty object. + return {}; + } + /** + * Define a default `handler` that's called when no routes explicitly + * match the incoming request. + * + * Each HTTP method ('GET', 'POST', etc.) gets its own default handler. + * + * Without a default handler, unmatched requests will go against the + * network as if there were no service worker present. + * + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + * @param {string} [method='GET'] The HTTP method to associate with this + * default handler. Each method has its own default. + */ + setDefaultHandler(handler, method = defaultMethod) { + this._defaultHandlerMap.set(method, normalizeHandler(handler)); + } + /** + * If a Route throws an error while handling a request, this `handler` + * will be called and given a chance to provide a response. + * + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + */ + setCatchHandler(handler) { + this._catchHandler = normalizeHandler(handler); + } + /** + * Registers a route with the router. + * + * @param {workbox-routing.Route} route The route to register. + */ + registerRoute(route) { + if (process.env.NODE_ENV !== 'production') { + assert.isType(route, 'object', { + moduleName: 'workbox-routing', + className: 'Router', + funcName: 'registerRoute', + paramName: 'route', + }); + assert.hasMethod(route, 'match', { + moduleName: 'workbox-routing', + className: 'Router', + funcName: 'registerRoute', + paramName: 'route', + }); + assert.isType(route.handler, 'object', { + moduleName: 'workbox-routing', + className: 'Router', + funcName: 'registerRoute', + paramName: 'route', + }); + assert.hasMethod(route.handler, 'handle', { + moduleName: 'workbox-routing', + className: 'Router', + funcName: 'registerRoute', + paramName: 'route.handler', + }); + assert.isType(route.method, 'string', { + moduleName: 'workbox-routing', + className: 'Router', + funcName: 'registerRoute', + paramName: 'route.method', + }); + } + if (!this._routes.has(route.method)) { + this._routes.set(route.method, []); + } + // Give precedence to all of the earlier routes by adding this additional + // route to the end of the array. + this._routes.get(route.method).push(route); + } + /** + * Unregisters a route with the router. + * + * @param {workbox-routing.Route} route The route to unregister. + */ + unregisterRoute(route) { + if (!this._routes.has(route.method)) { + throw new WorkboxError('unregister-route-but-not-found-with-method', { + method: route.method, + }); + } + const routeIndex = this._routes.get(route.method).indexOf(route); + if (routeIndex > -1) { + this._routes.get(route.method).splice(routeIndex, 1); + } + else { + throw new WorkboxError('unregister-route-route-not-registered'); + } + } +} +export { Router }; diff --git a/node_modules/workbox-routing/Router.mjs b/node_modules/workbox-routing/Router.mjs new file mode 100644 index 0000000000000000000000000000000000000000..dce65f82864555fd38c5396970d7cbda147d5b9d --- /dev/null +++ b/node_modules/workbox-routing/Router.mjs @@ -0,0 +1 @@ +export * from './Router.js'; \ No newline at end of file diff --git a/node_modules/workbox-routing/_types.d.ts b/node_modules/workbox-routing/_types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cec08a5dcfae4b44e424805edc0368209013e6d3 --- /dev/null +++ b/node_modules/workbox-routing/_types.d.ts @@ -0,0 +1,49 @@ +import './_version.js'; +/** + * The "match" callback is used to determine if a `Route` should apply for a + * particular URL. When matching occurs in response to a fetch event from the + * client, the `event` object is supplied in addition to the `url`, `request`, + * and `sameOrigin` value. However, since the match callback can be invoked + * outside of a fetch event, matching logic should not assume the `event` + * object will always be available. + * + * If the match callback returns a truthy value, the matching route's + * {@link workbox-routing~handlerCallback} will be + * invoked immediately. If the value returned is a non-empty array or object, + * that value will be set on the handler's `context.params` argument. + * + * @callback ~matchCallback + * @param {Object} context + * @param {Request} context.request The corresponding request. + * @param {URL} context.url The request's URL. + * @param {ExtendableEvent} context.event The corresponding event that triggered + * the request. + * @param {boolean} context.sameOrigin The result of comparing `url.origin` + * against the current origin. + * @return {*} To signify a match, return a truthy value. + * + * @memberof workbox-routing + */ +/** + * The "handler" callback is invoked whenever a `Router` matches a URL to a + * `Route` via its {@link workbox-routing~matchCallback} + * callback. This callback should return a Promise that resolves with a + * `Response`. + * + * If a non-empty array or object is returned by the + * {@link workbox-routing~matchCallback} it + * will be passed in as the handler's `context.params` argument. + * + * @callback ~handlerCallback + * @param {Object} context + * @param {Request|string} context.request The corresponding request. + * @param {URL} context.url The URL that matched, if available. + * @param {ExtendableEvent} context.event The corresponding event that triggered + * the request. + * @param {Object} [context.params] Array or Object parameters returned by the + * Route's {@link workbox-routing~matchCallback}. + * This will be undefined if an empty array or object were returned. + * @return {Promise} The response that will fulfill the request. + * + * @memberof workbox-routing + */ diff --git a/node_modules/workbox-routing/_types.js b/node_modules/workbox-routing/_types.js new file mode 100644 index 0000000000000000000000000000000000000000..0c6448d7fbe538ce8fd01a47a57642c8e69526c0 --- /dev/null +++ b/node_modules/workbox-routing/_types.js @@ -0,0 +1,62 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import './_version.js'; +// * * * IMPORTANT! * * * +// ------------------------------------------------------------------------- // +// jdsoc type definitions cannot be declared above TypeScript definitions or +// they'll be stripped from the built `.js` files, and they'll only be in the +// `d.ts` files, which aren't read by the jsdoc generator. As a result we +// have to put declare them below. +/** + * The "match" callback is used to determine if a `Route` should apply for a + * particular URL. When matching occurs in response to a fetch event from the + * client, the `event` object is supplied in addition to the `url`, `request`, + * and `sameOrigin` value. However, since the match callback can be invoked + * outside of a fetch event, matching logic should not assume the `event` + * object will always be available. + * + * If the match callback returns a truthy value, the matching route's + * {@link workbox-routing~handlerCallback} will be + * invoked immediately. If the value returned is a non-empty array or object, + * that value will be set on the handler's `context.params` argument. + * + * @callback ~matchCallback + * @param {Object} context + * @param {Request} context.request The corresponding request. + * @param {URL} context.url The request's URL. + * @param {ExtendableEvent} context.event The corresponding event that triggered + * the request. + * @param {boolean} context.sameOrigin The result of comparing `url.origin` + * against the current origin. + * @return {*} To signify a match, return a truthy value. + * + * @memberof workbox-routing + */ +/** + * The "handler" callback is invoked whenever a `Router` matches a URL to a + * `Route` via its {@link workbox-routing~matchCallback} + * callback. This callback should return a Promise that resolves with a + * `Response`. + * + * If a non-empty array or object is returned by the + * {@link workbox-routing~matchCallback} it + * will be passed in as the handler's `context.params` argument. + * + * @callback ~handlerCallback + * @param {Object} context + * @param {Request|string} context.request The corresponding request. + * @param {URL} context.url The URL that matched, if available. + * @param {ExtendableEvent} context.event The corresponding event that triggered + * the request. + * @param {Object} [context.params] Array or Object parameters returned by the + * Route's {@link workbox-routing~matchCallback}. + * This will be undefined if an empty array or object were returned. + * @return {Promise} The response that will fulfill the request. + * + * @memberof workbox-routing + */ diff --git a/node_modules/workbox-routing/_types.mjs b/node_modules/workbox-routing/_types.mjs new file mode 100644 index 0000000000000000000000000000000000000000..fb0ccdd9e49605f634b19eb6c43bd521a13a66ab --- /dev/null +++ b/node_modules/workbox-routing/_types.mjs @@ -0,0 +1 @@ +export * from './_types.js'; \ No newline at end of file diff --git a/node_modules/workbox-routing/_version.d.ts b/node_modules/workbox-routing/_version.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/workbox-routing/_version.js b/node_modules/workbox-routing/_version.js new file mode 100644 index 0000000000000000000000000000000000000000..ad2f0bed03521e5fe51b58f18a441b8ab95b3ae9 --- /dev/null +++ b/node_modules/workbox-routing/_version.js @@ -0,0 +1,6 @@ +"use strict"; +// @ts-ignore +try { + self['workbox:routing:7.4.0'] && _(); +} +catch (e) { } diff --git a/node_modules/workbox-routing/_version.mjs b/node_modules/workbox-routing/_version.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e44777514faaa97c9a3ebb0c39bc9a3a3fa12f05 --- /dev/null +++ b/node_modules/workbox-routing/_version.mjs @@ -0,0 +1 @@ +try{self['workbox:routing:7.4.1']&&_()}catch(e){}// eslint-disable-line \ No newline at end of file diff --git a/node_modules/workbox-routing/build/workbox-routing.dev.js b/node_modules/workbox-routing/build/workbox-routing.dev.js new file mode 100644 index 0000000000000000000000000000000000000000..62c5b2b924ad39445de3744fd010bddad175ab34 --- /dev/null +++ b/node_modules/workbox-routing/build/workbox-routing.dev.js @@ -0,0 +1,884 @@ +this.workbox = this.workbox || {}; +this.workbox.routing = (function (exports, assert_js, logger_js, WorkboxError_js, getFriendlyURL_js) { + 'use strict'; + + // @ts-ignore + try { + self['workbox:routing:7.4.0'] && _(); + } catch (e) {} + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * The default HTTP method, 'GET', used when there's no specific method + * configured for a route. + * + * @type {string} + * + * @private + */ + const defaultMethod = 'GET'; + /** + * The list of valid HTTP methods associated with requests that could be routed. + * + * @type {Array} + * + * @private + */ + const validMethods = ['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT']; + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * @param {function()|Object} handler Either a function, or an object with a + * 'handle' method. + * @return {Object} An object with a handle method. + * + * @private + */ + const normalizeHandler = handler => { + if (handler && typeof handler === 'object') { + { + assert_js.assert.hasMethod(handler, 'handle', { + moduleName: 'workbox-routing', + className: 'Route', + funcName: 'constructor', + paramName: 'handler' + }); + } + return handler; + } else { + { + assert_js.assert.isType(handler, 'function', { + moduleName: 'workbox-routing', + className: 'Route', + funcName: 'constructor', + paramName: 'handler' + }); + } + return { + handle: handler + }; + } + }; + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * A `Route` consists of a pair of callback functions, "match" and "handler". + * The "match" callback determine if a route should be used to "handle" a + * request by returning a non-falsy value if it can. The "handler" callback + * is called when there is a match and should return a Promise that resolves + * to a `Response`. + * + * @memberof workbox-routing + */ + class Route { + /** + * Constructor for Route class. + * + * @param {workbox-routing~matchCallback} match + * A callback function that determines whether the route matches a given + * `fetch` event by returning a non-falsy value. + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resolving to a Response. + * @param {string} [method='GET'] The HTTP method to match the Route + * against. + */ + constructor(match, handler, method = defaultMethod) { + { + assert_js.assert.isType(match, 'function', { + moduleName: 'workbox-routing', + className: 'Route', + funcName: 'constructor', + paramName: 'match' + }); + if (method) { + assert_js.assert.isOneOf(method, validMethods, { + paramName: 'method' + }); + } + } + // These values are referenced directly by Router so cannot be + // altered by minificaton. + this.handler = normalizeHandler(handler); + this.match = match; + this.method = method; + } + /** + * + * @param {workbox-routing-handlerCallback} handler A callback + * function that returns a Promise resolving to a Response + */ + setCatchHandler(handler) { + this.catchHandler = normalizeHandler(handler); + } + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * NavigationRoute makes it easy to create a + * {@link workbox-routing.Route} that matches for browser + * [navigation requests]{@link https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests}. + * + * It will only match incoming Requests whose + * {@link https://fetch.spec.whatwg.org/#concept-request-mode|mode} + * is set to `navigate`. + * + * You can optionally only apply this route to a subset of navigation requests + * by using one or both of the `denylist` and `allowlist` parameters. + * + * @memberof workbox-routing + * @extends workbox-routing.Route + */ + class NavigationRoute extends Route { + /** + * If both `denylist` and `allowlist` are provided, the `denylist` will + * take precedence and the request will not match this route. + * + * The regular expressions in `allowlist` and `denylist` + * are matched against the concatenated + * [`pathname`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/pathname} + * and [`search`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search} + * portions of the requested URL. + * + * *Note*: These RegExps may be evaluated against every destination URL during + * a navigation. Avoid using + * [complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077), + * or else your users may see delays when navigating your site. + * + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + * @param {Object} options + * @param {Array} [options.denylist] If any of these patterns match, + * the route will not handle the request (even if a allowlist RegExp matches). + * @param {Array} [options.allowlist=[/./]] If any of these patterns + * match the URL's pathname and search parameter, the route will handle the + * request (assuming the denylist doesn't match). + */ + constructor(handler, { + allowlist = [/./], + denylist = [] + } = {}) { + { + assert_js.assert.isArrayOfClass(allowlist, RegExp, { + moduleName: 'workbox-routing', + className: 'NavigationRoute', + funcName: 'constructor', + paramName: 'options.allowlist' + }); + assert_js.assert.isArrayOfClass(denylist, RegExp, { + moduleName: 'workbox-routing', + className: 'NavigationRoute', + funcName: 'constructor', + paramName: 'options.denylist' + }); + } + super(options => this._match(options), handler); + this._allowlist = allowlist; + this._denylist = denylist; + } + /** + * Routes match handler. + * + * @param {Object} options + * @param {URL} options.url + * @param {Request} options.request + * @return {boolean} + * + * @private + */ + _match({ + url, + request + }) { + if (request && request.mode !== 'navigate') { + return false; + } + const pathnameAndSearch = url.pathname + url.search; + for (const regExp of this._denylist) { + if (regExp.test(pathnameAndSearch)) { + { + logger_js.logger.log(`The navigation route ${pathnameAndSearch} is not ` + `being used, since the URL matches this denylist pattern: ` + `${regExp.toString()}`); + } + return false; + } + } + if (this._allowlist.some(regExp => regExp.test(pathnameAndSearch))) { + { + logger_js.logger.debug(`The navigation route ${pathnameAndSearch} ` + `is being used.`); + } + return true; + } + { + logger_js.logger.log(`The navigation route ${pathnameAndSearch} is not ` + `being used, since the URL being navigated to doesn't ` + `match the allowlist.`); + } + return false; + } + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * RegExpRoute makes it easy to create a regular expression based + * {@link workbox-routing.Route}. + * + * For same-origin requests the RegExp only needs to match part of the URL. For + * requests against third-party servers, you must define a RegExp that matches + * the start of the URL. + * + * @memberof workbox-routing + * @extends workbox-routing.Route + */ + class RegExpRoute extends Route { + /** + * If the regular expression contains + * [capture groups]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references}, + * the captured values will be passed to the + * {@link workbox-routing~handlerCallback} `params` + * argument. + * + * @param {RegExp} regExp The regular expression to match against URLs. + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + * @param {string} [method='GET'] The HTTP method to match the Route + * against. + */ + constructor(regExp, handler, method) { + { + assert_js.assert.isInstance(regExp, RegExp, { + moduleName: 'workbox-routing', + className: 'RegExpRoute', + funcName: 'constructor', + paramName: 'pattern' + }); + } + const match = ({ + url + }) => { + const result = regExp.exec(url.href); + // Return immediately if there's no match. + if (!result) { + return; + } + // Require that the match start at the first character in the URL string + // if it's a cross-origin request. + // See https://github.com/GoogleChrome/workbox/issues/281 for the context + // behind this behavior. + if (url.origin !== location.origin && result.index !== 0) { + { + logger_js.logger.debug(`The regular expression '${regExp.toString()}' only partially matched ` + `against the cross-origin URL '${url.toString()}'. RegExpRoute's will only ` + `handle cross-origin requests if they match the entire URL.`); + } + return; + } + // If the route matches, but there aren't any capture groups defined, then + // this will return [], which is truthy and therefore sufficient to + // indicate a match. + // If there are capture groups, then it will return their values. + return result.slice(1); + }; + super(match, handler, method); + } + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * The Router can be used to process a `FetchEvent` using one or more + * {@link workbox-routing.Route}, responding with a `Response` if + * a matching route exists. + * + * If no route matches a given a request, the Router will use a "default" + * handler if one is defined. + * + * Should the matching Route throw an error, the Router will use a "catch" + * handler if one is defined to gracefully deal with issues and respond with a + * Request. + * + * If a request matches multiple routes, the **earliest** registered route will + * be used to respond to the request. + * + * @memberof workbox-routing + */ + class Router { + /** + * Initializes a new Router. + */ + constructor() { + this._routes = new Map(); + this._defaultHandlerMap = new Map(); + } + /** + * @return {Map>} routes A `Map` of HTTP + * method name ('GET', etc.) to an array of all the corresponding `Route` + * instances that are registered. + */ + get routes() { + return this._routes; + } + /** + * Adds a fetch event listener to respond to events when a route matches + * the event's request. + */ + addFetchListener() { + // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705 + self.addEventListener('fetch', event => { + const { + request + } = event; + const responsePromise = this.handleRequest({ + request, + event + }); + if (responsePromise) { + event.respondWith(responsePromise); + } + }); + } + /** + * Adds a message event listener for URLs to cache from the window. + * This is useful to cache resources loaded on the page prior to when the + * service worker started controlling it. + * + * The format of the message data sent from the window should be as follows. + * Where the `urlsToCache` array may consist of URL strings or an array of + * URL string + `requestInit` object (the same as you'd pass to `fetch()`). + * + * ``` + * { + * type: 'CACHE_URLS', + * payload: { + * urlsToCache: [ + * './script1.js', + * './script2.js', + * ['./script3.js', {mode: 'no-cors'}], + * ], + * }, + * } + * ``` + */ + addCacheListener() { + // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705 + self.addEventListener('message', event => { + // event.data is type 'any' + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (event.data && event.data.type === 'CACHE_URLS') { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const { + payload + } = event.data; + { + logger_js.logger.debug(`Caching URLs from the window`, payload.urlsToCache); + } + const requestPromises = Promise.all(payload.urlsToCache.map(entry => { + if (typeof entry === 'string') { + entry = [entry]; + } + const request = new Request(...entry); + return this.handleRequest({ + request, + event + }); + // TODO(philipwalton): TypeScript errors without this typecast for + // some reason (probably a bug). The real type here should work but + // doesn't: `Array | undefined>`. + })); // TypeScript + event.waitUntil(requestPromises); + // If a MessageChannel was used, reply to the message on success. + if (event.ports && event.ports[0]) { + void requestPromises.then(() => event.ports[0].postMessage(true)); + } + } + }); + } + /** + * Apply the routing rules to a FetchEvent object to get a Response from an + * appropriate Route's handler. + * + * @param {Object} options + * @param {Request} options.request The request to handle. + * @param {ExtendableEvent} options.event The event that triggered the + * request. + * @return {Promise|undefined} A promise is returned if a + * registered route can handle the request. If there is no matching + * route and there's no `defaultHandler`, `undefined` is returned. + */ + handleRequest({ + request, + event + }) { + { + assert_js.assert.isInstance(request, Request, { + moduleName: 'workbox-routing', + className: 'Router', + funcName: 'handleRequest', + paramName: 'options.request' + }); + } + const url = new URL(request.url, location.href); + if (!url.protocol.startsWith('http')) { + { + logger_js.logger.debug(`Workbox Router only supports URLs that start with 'http'.`); + } + return; + } + const sameOrigin = url.origin === location.origin; + const { + params, + route + } = this.findMatchingRoute({ + event, + request, + sameOrigin, + url + }); + let handler = route && route.handler; + const debugMessages = []; + { + if (handler) { + debugMessages.push([`Found a route to handle this request:`, route]); + if (params) { + debugMessages.push([`Passing the following params to the route's handler:`, params]); + } + } + } + // If we don't have a handler because there was no matching route, then + // fall back to defaultHandler if that's defined. + const method = request.method; + if (!handler && this._defaultHandlerMap.has(method)) { + { + debugMessages.push(`Failed to find a matching route. Falling ` + `back to the default handler for ${method}.`); + } + handler = this._defaultHandlerMap.get(method); + } + if (!handler) { + { + // No handler so Workbox will do nothing. If logs is set of debug + // i.e. verbose, we should print out this information. + logger_js.logger.debug(`No route found for: ${getFriendlyURL_js.getFriendlyURL(url)}`); + } + return; + } + { + // We have a handler, meaning Workbox is going to handle the route. + // print the routing details to the console. + logger_js.logger.groupCollapsed(`Router is responding to: ${getFriendlyURL_js.getFriendlyURL(url)}`); + debugMessages.forEach(msg => { + if (Array.isArray(msg)) { + logger_js.logger.log(...msg); + } else { + logger_js.logger.log(msg); + } + }); + logger_js.logger.groupEnd(); + } + // Wrap in try and catch in case the handle method throws a synchronous + // error. It should still callback to the catch handler. + let responsePromise; + try { + responsePromise = handler.handle({ + url, + request, + event, + params + }); + } catch (err) { + responsePromise = Promise.reject(err); + } + // Get route's catch handler, if it exists + const catchHandler = route && route.catchHandler; + if (responsePromise instanceof Promise && (this._catchHandler || catchHandler)) { + responsePromise = responsePromise.catch(async err => { + // If there's a route catch handler, process that first + if (catchHandler) { + { + // Still include URL here as it will be async from the console group + // and may not make sense without the URL + logger_js.logger.groupCollapsed(`Error thrown when responding to: ` + ` ${getFriendlyURL_js.getFriendlyURL(url)}. Falling back to route's Catch Handler.`); + logger_js.logger.error(`Error thrown by:`, route); + logger_js.logger.error(err); + logger_js.logger.groupEnd(); + } + try { + return await catchHandler.handle({ + url, + request, + event, + params + }); + } catch (catchErr) { + if (catchErr instanceof Error) { + err = catchErr; + } + } + } + if (this._catchHandler) { + { + // Still include URL here as it will be async from the console group + // and may not make sense without the URL + logger_js.logger.groupCollapsed(`Error thrown when responding to: ` + ` ${getFriendlyURL_js.getFriendlyURL(url)}. Falling back to global Catch Handler.`); + logger_js.logger.error(`Error thrown by:`, route); + logger_js.logger.error(err); + logger_js.logger.groupEnd(); + } + return this._catchHandler.handle({ + url, + request, + event + }); + } + throw err; + }); + } + return responsePromise; + } + /** + * Checks a request and URL (and optionally an event) against the list of + * registered routes, and if there's a match, returns the corresponding + * route along with any params generated by the match. + * + * @param {Object} options + * @param {URL} options.url + * @param {boolean} options.sameOrigin The result of comparing `url.origin` + * against the current origin. + * @param {Request} options.request The request to match. + * @param {Event} options.event The corresponding event. + * @return {Object} An object with `route` and `params` properties. + * They are populated if a matching route was found or `undefined` + * otherwise. + */ + findMatchingRoute({ + url, + sameOrigin, + request, + event + }) { + const routes = this._routes.get(request.method) || []; + for (const route of routes) { + let params; + // route.match returns type any, not possible to change right now. + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const matchResult = route.match({ + url, + sameOrigin, + request, + event + }); + if (matchResult) { + { + // Warn developers that using an async matchCallback is almost always + // not the right thing to do. + if (matchResult instanceof Promise) { + logger_js.logger.warn(`While routing ${getFriendlyURL_js.getFriendlyURL(url)}, an async ` + `matchCallback function was used. Please convert the ` + `following route to use a synchronous matchCallback function:`, route); + } + } + // See https://github.com/GoogleChrome/workbox/issues/2079 + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + params = matchResult; + if (Array.isArray(params) && params.length === 0) { + // Instead of passing an empty array in as params, use undefined. + params = undefined; + } else if (matchResult.constructor === Object && + // eslint-disable-line + Object.keys(matchResult).length === 0) { + // Instead of passing an empty object in as params, use undefined. + params = undefined; + } else if (typeof matchResult === 'boolean') { + // For the boolean value true (rather than just something truth-y), + // don't set params. + // See https://github.com/GoogleChrome/workbox/pull/2134#issuecomment-513924353 + params = undefined; + } + // Return early if have a match. + return { + route, + params + }; + } + } + // If no match was found above, return and empty object. + return {}; + } + /** + * Define a default `handler` that's called when no routes explicitly + * match the incoming request. + * + * Each HTTP method ('GET', 'POST', etc.) gets its own default handler. + * + * Without a default handler, unmatched requests will go against the + * network as if there were no service worker present. + * + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + * @param {string} [method='GET'] The HTTP method to associate with this + * default handler. Each method has its own default. + */ + setDefaultHandler(handler, method = defaultMethod) { + this._defaultHandlerMap.set(method, normalizeHandler(handler)); + } + /** + * If a Route throws an error while handling a request, this `handler` + * will be called and given a chance to provide a response. + * + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + */ + setCatchHandler(handler) { + this._catchHandler = normalizeHandler(handler); + } + /** + * Registers a route with the router. + * + * @param {workbox-routing.Route} route The route to register. + */ + registerRoute(route) { + { + assert_js.assert.isType(route, 'object', { + moduleName: 'workbox-routing', + className: 'Router', + funcName: 'registerRoute', + paramName: 'route' + }); + assert_js.assert.hasMethod(route, 'match', { + moduleName: 'workbox-routing', + className: 'Router', + funcName: 'registerRoute', + paramName: 'route' + }); + assert_js.assert.isType(route.handler, 'object', { + moduleName: 'workbox-routing', + className: 'Router', + funcName: 'registerRoute', + paramName: 'route' + }); + assert_js.assert.hasMethod(route.handler, 'handle', { + moduleName: 'workbox-routing', + className: 'Router', + funcName: 'registerRoute', + paramName: 'route.handler' + }); + assert_js.assert.isType(route.method, 'string', { + moduleName: 'workbox-routing', + className: 'Router', + funcName: 'registerRoute', + paramName: 'route.method' + }); + } + if (!this._routes.has(route.method)) { + this._routes.set(route.method, []); + } + // Give precedence to all of the earlier routes by adding this additional + // route to the end of the array. + this._routes.get(route.method).push(route); + } + /** + * Unregisters a route with the router. + * + * @param {workbox-routing.Route} route The route to unregister. + */ + unregisterRoute(route) { + if (!this._routes.has(route.method)) { + throw new WorkboxError_js.WorkboxError('unregister-route-but-not-found-with-method', { + method: route.method + }); + } + const routeIndex = this._routes.get(route.method).indexOf(route); + if (routeIndex > -1) { + this._routes.get(route.method).splice(routeIndex, 1); + } else { + throw new WorkboxError_js.WorkboxError('unregister-route-route-not-registered'); + } + } + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + let defaultRouter; + /** + * Creates a new, singleton Router instance if one does not exist. If one + * does already exist, that instance is returned. + * + * @private + * @return {Router} + */ + const getOrCreateDefaultRouter = () => { + if (!defaultRouter) { + defaultRouter = new Router(); + // The helpers that use the default Router assume these listeners exist. + defaultRouter.addFetchListener(); + defaultRouter.addCacheListener(); + } + return defaultRouter; + }; + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Easily register a RegExp, string, or function with a caching + * strategy to a singleton Router instance. + * + * This method will generate a Route for you if needed and + * call {@link workbox-routing.Router#registerRoute}. + * + * @param {RegExp|string|workbox-routing.Route~matchCallback|workbox-routing.Route} capture + * If the capture param is a `Route`, all other arguments will be ignored. + * @param {workbox-routing~handlerCallback} [handler] A callback + * function that returns a Promise resulting in a Response. This parameter + * is required if `capture` is not a `Route` object. + * @param {string} [method='GET'] The HTTP method to match the Route + * against. + * @return {workbox-routing.Route} The generated `Route`. + * + * @memberof workbox-routing + */ + function registerRoute(capture, handler, method) { + let route; + if (typeof capture === 'string') { + const captureUrl = new URL(capture, location.href); + { + if (!(capture.startsWith('/') || capture.startsWith('http'))) { + throw new WorkboxError_js.WorkboxError('invalid-string', { + moduleName: 'workbox-routing', + funcName: 'registerRoute', + paramName: 'capture' + }); + } + // We want to check if Express-style wildcards are in the pathname only. + // TODO: Remove this log message in v4. + const valueToCheck = capture.startsWith('http') ? captureUrl.pathname : capture; + // See https://github.com/pillarjs/path-to-regexp#parameters + const wildcards = '[*:?+]'; + if (new RegExp(`${wildcards}`).exec(valueToCheck)) { + logger_js.logger.debug(`The '$capture' parameter contains an Express-style wildcard ` + `character (${wildcards}). Strings are now always interpreted as ` + `exact matches; use a RegExp for partial or wildcard matches.`); + } + } + const matchCallback = ({ + url + }) => { + { + if (url.pathname === captureUrl.pathname && url.origin !== captureUrl.origin) { + logger_js.logger.debug(`${capture} only partially matches the cross-origin URL ` + `${url.toString()}. This route will only handle cross-origin requests ` + `if they match the entire URL.`); + } + } + return url.href === captureUrl.href; + }; + // If `capture` is a string then `handler` and `method` must be present. + route = new Route(matchCallback, handler, method); + } else if (capture instanceof RegExp) { + // If `capture` is a `RegExp` then `handler` and `method` must be present. + route = new RegExpRoute(capture, handler, method); + } else if (typeof capture === 'function') { + // If `capture` is a function then `handler` and `method` must be present. + route = new Route(capture, handler, method); + } else if (capture instanceof Route) { + route = capture; + } else { + throw new WorkboxError_js.WorkboxError('unsupported-route-type', { + moduleName: 'workbox-routing', + funcName: 'registerRoute', + paramName: 'capture' + }); + } + const defaultRouter = getOrCreateDefaultRouter(); + defaultRouter.registerRoute(route); + return route; + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * If a Route throws an error while handling a request, this `handler` + * will be called and given a chance to provide a response. + * + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + * + * @memberof workbox-routing + */ + function setCatchHandler(handler) { + const defaultRouter = getOrCreateDefaultRouter(); + defaultRouter.setCatchHandler(handler); + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Define a default `handler` that's called when no routes explicitly + * match the incoming request. + * + * Without a default handler, unmatched requests will go against the + * network as if there were no service worker present. + * + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + * + * @memberof workbox-routing + */ + function setDefaultHandler(handler) { + const defaultRouter = getOrCreateDefaultRouter(); + defaultRouter.setDefaultHandler(handler); + } + + exports.NavigationRoute = NavigationRoute; + exports.RegExpRoute = RegExpRoute; + exports.Route = Route; + exports.Router = Router; + exports.registerRoute = registerRoute; + exports.setCatchHandler = setCatchHandler; + exports.setDefaultHandler = setDefaultHandler; + + return exports; + +})({}, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private); +//# sourceMappingURL=workbox-routing.dev.js.map diff --git a/node_modules/workbox-routing/build/workbox-routing.dev.js.map b/node_modules/workbox-routing/build/workbox-routing.dev.js.map new file mode 100644 index 0000000000000000000000000000000000000000..7e0bfbce0094c935ea2cdba0ab7d0c6e88b0df80 --- /dev/null +++ b/node_modules/workbox-routing/build/workbox-routing.dev.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-routing.dev.js","sources":["../_version.js","../utils/constants.js","../utils/normalizeHandler.js","../Route.js","../NavigationRoute.js","../RegExpRoute.js","../Router.js","../utils/getOrCreateDefaultRouter.js","../registerRoute.js","../setCatchHandler.js","../setDefaultHandler.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:routing:7.4.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 '../_version.js';\n/**\n * The default HTTP method, 'GET', used when there's no specific method\n * configured for a route.\n *\n * @type {string}\n *\n * @private\n */\nexport const defaultMethod = 'GET';\n/**\n * The list of valid HTTP methods associated with requests that could be routed.\n *\n * @type {Array}\n *\n * @private\n */\nexport const validMethods = [\n 'DELETE',\n 'GET',\n 'HEAD',\n 'PATCH',\n 'POST',\n 'PUT',\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 '../_version.js';\n/**\n * @param {function()|Object} handler Either a function, or an object with a\n * 'handle' method.\n * @return {Object} An object with a handle method.\n *\n * @private\n */\nexport const normalizeHandler = (handler) => {\n if (handler && typeof handler === 'object') {\n if (process.env.NODE_ENV !== 'production') {\n assert.hasMethod(handler, 'handle', {\n moduleName: 'workbox-routing',\n className: 'Route',\n funcName: 'constructor',\n paramName: 'handler',\n });\n }\n return handler;\n }\n else {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(handler, 'function', {\n moduleName: 'workbox-routing',\n className: 'Route',\n funcName: 'constructor',\n paramName: 'handler',\n });\n }\n return { handle: handler };\n }\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 { defaultMethod, validMethods } from './utils/constants.js';\nimport { normalizeHandler } from './utils/normalizeHandler.js';\nimport './_version.js';\n/**\n * A `Route` consists of a pair of callback functions, \"match\" and \"handler\".\n * The \"match\" callback determine if a route should be used to \"handle\" a\n * request by returning a non-falsy value if it can. The \"handler\" callback\n * is called when there is a match and should return a Promise that resolves\n * to a `Response`.\n *\n * @memberof workbox-routing\n */\nclass Route {\n /**\n * Constructor for Route class.\n *\n * @param {workbox-routing~matchCallback} match\n * A callback function that determines whether the route matches a given\n * `fetch` event by returning a non-falsy value.\n * @param {workbox-routing~handlerCallback} handler A callback\n * function that returns a Promise resolving to a Response.\n * @param {string} [method='GET'] The HTTP method to match the Route\n * against.\n */\n constructor(match, handler, method = defaultMethod) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(match, 'function', {\n moduleName: 'workbox-routing',\n className: 'Route',\n funcName: 'constructor',\n paramName: 'match',\n });\n if (method) {\n assert.isOneOf(method, validMethods, { paramName: 'method' });\n }\n }\n // These values are referenced directly by Router so cannot be\n // altered by minificaton.\n this.handler = normalizeHandler(handler);\n this.match = match;\n this.method = method;\n }\n /**\n *\n * @param {workbox-routing-handlerCallback} handler A callback\n * function that returns a Promise resolving to a Response\n */\n setCatchHandler(handler) {\n this.catchHandler = normalizeHandler(handler);\n }\n}\nexport { Route };\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 { logger } from 'workbox-core/_private/logger.js';\nimport { Route } from './Route.js';\nimport './_version.js';\n/**\n * NavigationRoute makes it easy to create a\n * {@link workbox-routing.Route} that matches for browser\n * [navigation requests]{@link https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests}.\n *\n * It will only match incoming Requests whose\n * {@link https://fetch.spec.whatwg.org/#concept-request-mode|mode}\n * is set to `navigate`.\n *\n * You can optionally only apply this route to a subset of navigation requests\n * by using one or both of the `denylist` and `allowlist` parameters.\n *\n * @memberof workbox-routing\n * @extends workbox-routing.Route\n */\nclass NavigationRoute extends Route {\n /**\n * If both `denylist` and `allowlist` are provided, the `denylist` will\n * take precedence and the request will not match this route.\n *\n * The regular expressions in `allowlist` and `denylist`\n * are matched against the concatenated\n * [`pathname`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/pathname}\n * and [`search`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search}\n * portions of the requested URL.\n *\n * *Note*: These RegExps may be evaluated against every destination URL during\n * a navigation. Avoid using\n * [complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077),\n * or else your users may see delays when navigating your site.\n *\n * @param {workbox-routing~handlerCallback} handler A callback\n * function that returns a Promise resulting in a Response.\n * @param {Object} options\n * @param {Array} [options.denylist] If any of these patterns match,\n * the route will not handle the request (even if a allowlist RegExp matches).\n * @param {Array} [options.allowlist=[/./]] If any of these patterns\n * match the URL's pathname and search parameter, the route will handle the\n * request (assuming the denylist doesn't match).\n */\n constructor(handler, { allowlist = [/./], denylist = [] } = {}) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isArrayOfClass(allowlist, RegExp, {\n moduleName: 'workbox-routing',\n className: 'NavigationRoute',\n funcName: 'constructor',\n paramName: 'options.allowlist',\n });\n assert.isArrayOfClass(denylist, RegExp, {\n moduleName: 'workbox-routing',\n className: 'NavigationRoute',\n funcName: 'constructor',\n paramName: 'options.denylist',\n });\n }\n super((options) => this._match(options), handler);\n this._allowlist = allowlist;\n this._denylist = denylist;\n }\n /**\n * Routes match handler.\n *\n * @param {Object} options\n * @param {URL} options.url\n * @param {Request} options.request\n * @return {boolean}\n *\n * @private\n */\n _match({ url, request }) {\n if (request && request.mode !== 'navigate') {\n return false;\n }\n const pathnameAndSearch = url.pathname + url.search;\n for (const regExp of this._denylist) {\n if (regExp.test(pathnameAndSearch)) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`The navigation route ${pathnameAndSearch} is not ` +\n `being used, since the URL matches this denylist pattern: ` +\n `${regExp.toString()}`);\n }\n return false;\n }\n }\n if (this._allowlist.some((regExp) => regExp.test(pathnameAndSearch))) {\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`The navigation route ${pathnameAndSearch} ` + `is being used.`);\n }\n return true;\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`The navigation route ${pathnameAndSearch} is not ` +\n `being used, since the URL being navigated to doesn't ` +\n `match the allowlist.`);\n }\n return false;\n }\n}\nexport { NavigationRoute };\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 { logger } from 'workbox-core/_private/logger.js';\nimport { Route } from './Route.js';\nimport './_version.js';\n/**\n * RegExpRoute makes it easy to create a regular expression based\n * {@link workbox-routing.Route}.\n *\n * For same-origin requests the RegExp only needs to match part of the URL. For\n * requests against third-party servers, you must define a RegExp that matches\n * the start of the URL.\n *\n * @memberof workbox-routing\n * @extends workbox-routing.Route\n */\nclass RegExpRoute extends Route {\n /**\n * If the regular expression contains\n * [capture groups]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references},\n * the captured values will be passed to the\n * {@link workbox-routing~handlerCallback} `params`\n * argument.\n *\n * @param {RegExp} regExp The regular expression to match against URLs.\n * @param {workbox-routing~handlerCallback} handler A callback\n * function that returns a Promise resulting in a Response.\n * @param {string} [method='GET'] The HTTP method to match the Route\n * against.\n */\n constructor(regExp, handler, method) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(regExp, RegExp, {\n moduleName: 'workbox-routing',\n className: 'RegExpRoute',\n funcName: 'constructor',\n paramName: 'pattern',\n });\n }\n const match = ({ url }) => {\n const result = regExp.exec(url.href);\n // Return immediately if there's no match.\n if (!result) {\n return;\n }\n // Require that the match start at the first character in the URL string\n // if it's a cross-origin request.\n // See https://github.com/GoogleChrome/workbox/issues/281 for the context\n // behind this behavior.\n if (url.origin !== location.origin && result.index !== 0) {\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`The regular expression '${regExp.toString()}' only partially matched ` +\n `against the cross-origin URL '${url.toString()}'. RegExpRoute's will only ` +\n `handle cross-origin requests if they match the entire URL.`);\n }\n return;\n }\n // If the route matches, but there aren't any capture groups defined, then\n // this will return [], which is truthy and therefore sufficient to\n // indicate a match.\n // If there are capture groups, then it will return their values.\n return result.slice(1);\n };\n super(match, handler, method);\n }\n}\nexport { RegExpRoute };\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 { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { defaultMethod } from './utils/constants.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { normalizeHandler } from './utils/normalizeHandler.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport './_version.js';\n/**\n * The Router can be used to process a `FetchEvent` using one or more\n * {@link workbox-routing.Route}, responding with a `Response` if\n * a matching route exists.\n *\n * If no route matches a given a request, the Router will use a \"default\"\n * handler if one is defined.\n *\n * Should the matching Route throw an error, the Router will use a \"catch\"\n * handler if one is defined to gracefully deal with issues and respond with a\n * Request.\n *\n * If a request matches multiple routes, the **earliest** registered route will\n * be used to respond to the request.\n *\n * @memberof workbox-routing\n */\nclass Router {\n /**\n * Initializes a new Router.\n */\n constructor() {\n this._routes = new Map();\n this._defaultHandlerMap = new Map();\n }\n /**\n * @return {Map>} routes A `Map` of HTTP\n * method name ('GET', etc.) to an array of all the corresponding `Route`\n * instances that are registered.\n */\n get routes() {\n return this._routes;\n }\n /**\n * Adds a fetch event listener to respond to events when a route matches\n * the event's request.\n */\n addFetchListener() {\n // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705\n self.addEventListener('fetch', ((event) => {\n const { request } = event;\n const responsePromise = this.handleRequest({ request, event });\n if (responsePromise) {\n event.respondWith(responsePromise);\n }\n }));\n }\n /**\n * Adds a message event listener for URLs to cache from the window.\n * This is useful to cache resources loaded on the page prior to when the\n * service worker started controlling it.\n *\n * The format of the message data sent from the window should be as follows.\n * Where the `urlsToCache` array may consist of URL strings or an array of\n * URL string + `requestInit` object (the same as you'd pass to `fetch()`).\n *\n * ```\n * {\n * type: 'CACHE_URLS',\n * payload: {\n * urlsToCache: [\n * './script1.js',\n * './script2.js',\n * ['./script3.js', {mode: 'no-cors'}],\n * ],\n * },\n * }\n * ```\n */\n addCacheListener() {\n // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705\n self.addEventListener('message', ((event) => {\n // event.data is type 'any'\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (event.data && event.data.type === 'CACHE_URLS') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const { payload } = event.data;\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`Caching URLs from the window`, payload.urlsToCache);\n }\n const requestPromises = Promise.all(payload.urlsToCache.map((entry) => {\n if (typeof entry === 'string') {\n entry = [entry];\n }\n const request = new Request(...entry);\n return this.handleRequest({ request, event });\n // TODO(philipwalton): TypeScript errors without this typecast for\n // some reason (probably a bug). The real type here should work but\n // doesn't: `Array | undefined>`.\n })); // TypeScript\n event.waitUntil(requestPromises);\n // If a MessageChannel was used, reply to the message on success.\n if (event.ports && event.ports[0]) {\n void requestPromises.then(() => event.ports[0].postMessage(true));\n }\n }\n }));\n }\n /**\n * Apply the routing rules to a FetchEvent object to get a Response from an\n * appropriate Route's handler.\n *\n * @param {Object} options\n * @param {Request} options.request The request to handle.\n * @param {ExtendableEvent} options.event The event that triggered the\n * request.\n * @return {Promise|undefined} A promise is returned if a\n * registered route can handle the request. If there is no matching\n * route and there's no `defaultHandler`, `undefined` is returned.\n */\n handleRequest({ request, event, }) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(request, Request, {\n moduleName: 'workbox-routing',\n className: 'Router',\n funcName: 'handleRequest',\n paramName: 'options.request',\n });\n }\n const url = new URL(request.url, location.href);\n if (!url.protocol.startsWith('http')) {\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`Workbox Router only supports URLs that start with 'http'.`);\n }\n return;\n }\n const sameOrigin = url.origin === location.origin;\n const { params, route } = this.findMatchingRoute({\n event,\n request,\n sameOrigin,\n url,\n });\n let handler = route && route.handler;\n const debugMessages = [];\n if (process.env.NODE_ENV !== 'production') {\n if (handler) {\n debugMessages.push([`Found a route to handle this request:`, route]);\n if (params) {\n debugMessages.push([\n `Passing the following params to the route's handler:`,\n params,\n ]);\n }\n }\n }\n // If we don't have a handler because there was no matching route, then\n // fall back to defaultHandler if that's defined.\n const method = request.method;\n if (!handler && this._defaultHandlerMap.has(method)) {\n if (process.env.NODE_ENV !== 'production') {\n debugMessages.push(`Failed to find a matching route. Falling ` +\n `back to the default handler for ${method}.`);\n }\n handler = this._defaultHandlerMap.get(method);\n }\n if (!handler) {\n if (process.env.NODE_ENV !== 'production') {\n // No handler so Workbox will do nothing. If logs is set of debug\n // i.e. verbose, we should print out this information.\n logger.debug(`No route found for: ${getFriendlyURL(url)}`);\n }\n return;\n }\n if (process.env.NODE_ENV !== 'production') {\n // We have a handler, meaning Workbox is going to handle the route.\n // print the routing details to the console.\n logger.groupCollapsed(`Router is responding to: ${getFriendlyURL(url)}`);\n debugMessages.forEach((msg) => {\n if (Array.isArray(msg)) {\n logger.log(...msg);\n }\n else {\n logger.log(msg);\n }\n });\n logger.groupEnd();\n }\n // Wrap in try and catch in case the handle method throws a synchronous\n // error. It should still callback to the catch handler.\n let responsePromise;\n try {\n responsePromise = handler.handle({ url, request, event, params });\n }\n catch (err) {\n responsePromise = Promise.reject(err);\n }\n // Get route's catch handler, if it exists\n const catchHandler = route && route.catchHandler;\n if (responsePromise instanceof Promise &&\n (this._catchHandler || catchHandler)) {\n responsePromise = responsePromise.catch(async (err) => {\n // If there's a route catch handler, process that first\n if (catchHandler) {\n if (process.env.NODE_ENV !== 'production') {\n // Still include URL here as it will be async from the console group\n // and may not make sense without the URL\n logger.groupCollapsed(`Error thrown when responding to: ` +\n ` ${getFriendlyURL(url)}. Falling back to route's Catch Handler.`);\n logger.error(`Error thrown by:`, route);\n logger.error(err);\n logger.groupEnd();\n }\n try {\n return await catchHandler.handle({ url, request, event, params });\n }\n catch (catchErr) {\n if (catchErr instanceof Error) {\n err = catchErr;\n }\n }\n }\n if (this._catchHandler) {\n if (process.env.NODE_ENV !== 'production') {\n // Still include URL here as it will be async from the console group\n // and may not make sense without the URL\n logger.groupCollapsed(`Error thrown when responding to: ` +\n ` ${getFriendlyURL(url)}. Falling back to global Catch Handler.`);\n logger.error(`Error thrown by:`, route);\n logger.error(err);\n logger.groupEnd();\n }\n return this._catchHandler.handle({ url, request, event });\n }\n throw err;\n });\n }\n return responsePromise;\n }\n /**\n * Checks a request and URL (and optionally an event) against the list of\n * registered routes, and if there's a match, returns the corresponding\n * route along with any params generated by the match.\n *\n * @param {Object} options\n * @param {URL} options.url\n * @param {boolean} options.sameOrigin The result of comparing `url.origin`\n * against the current origin.\n * @param {Request} options.request The request to match.\n * @param {Event} options.event The corresponding event.\n * @return {Object} An object with `route` and `params` properties.\n * They are populated if a matching route was found or `undefined`\n * otherwise.\n */\n findMatchingRoute({ url, sameOrigin, request, event, }) {\n const routes = this._routes.get(request.method) || [];\n for (const route of routes) {\n let params;\n // route.match returns type any, not possible to change right now.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const matchResult = route.match({ url, sameOrigin, request, event });\n if (matchResult) {\n if (process.env.NODE_ENV !== 'production') {\n // Warn developers that using an async matchCallback is almost always\n // not the right thing to do.\n if (matchResult instanceof Promise) {\n logger.warn(`While routing ${getFriendlyURL(url)}, an async ` +\n `matchCallback function was used. Please convert the ` +\n `following route to use a synchronous matchCallback function:`, route);\n }\n }\n // See https://github.com/GoogleChrome/workbox/issues/2079\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n params = matchResult;\n if (Array.isArray(params) && params.length === 0) {\n // Instead of passing an empty array in as params, use undefined.\n params = undefined;\n }\n else if (matchResult.constructor === Object && // eslint-disable-line\n Object.keys(matchResult).length === 0) {\n // Instead of passing an empty object in as params, use undefined.\n params = undefined;\n }\n else if (typeof matchResult === 'boolean') {\n // For the boolean value true (rather than just something truth-y),\n // don't set params.\n // See https://github.com/GoogleChrome/workbox/pull/2134#issuecomment-513924353\n params = undefined;\n }\n // Return early if have a match.\n return { route, params };\n }\n }\n // If no match was found above, return and empty object.\n return {};\n }\n /**\n * Define a default `handler` that's called when no routes explicitly\n * match the incoming request.\n *\n * Each HTTP method ('GET', 'POST', etc.) gets its own default handler.\n *\n * Without a default handler, unmatched requests will go against the\n * network as if there were no service worker present.\n *\n * @param {workbox-routing~handlerCallback} handler A callback\n * function that returns a Promise resulting in a Response.\n * @param {string} [method='GET'] The HTTP method to associate with this\n * default handler. Each method has its own default.\n */\n setDefaultHandler(handler, method = defaultMethod) {\n this._defaultHandlerMap.set(method, normalizeHandler(handler));\n }\n /**\n * If a Route throws an error while handling a request, this `handler`\n * will be called and given a chance to provide a response.\n *\n * @param {workbox-routing~handlerCallback} handler A callback\n * function that returns a Promise resulting in a Response.\n */\n setCatchHandler(handler) {\n this._catchHandler = normalizeHandler(handler);\n }\n /**\n * Registers a route with the router.\n *\n * @param {workbox-routing.Route} route The route to register.\n */\n registerRoute(route) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(route, 'object', {\n moduleName: 'workbox-routing',\n className: 'Router',\n funcName: 'registerRoute',\n paramName: 'route',\n });\n assert.hasMethod(route, 'match', {\n moduleName: 'workbox-routing',\n className: 'Router',\n funcName: 'registerRoute',\n paramName: 'route',\n });\n assert.isType(route.handler, 'object', {\n moduleName: 'workbox-routing',\n className: 'Router',\n funcName: 'registerRoute',\n paramName: 'route',\n });\n assert.hasMethod(route.handler, 'handle', {\n moduleName: 'workbox-routing',\n className: 'Router',\n funcName: 'registerRoute',\n paramName: 'route.handler',\n });\n assert.isType(route.method, 'string', {\n moduleName: 'workbox-routing',\n className: 'Router',\n funcName: 'registerRoute',\n paramName: 'route.method',\n });\n }\n if (!this._routes.has(route.method)) {\n this._routes.set(route.method, []);\n }\n // Give precedence to all of the earlier routes by adding this additional\n // route to the end of the array.\n this._routes.get(route.method).push(route);\n }\n /**\n * Unregisters a route with the router.\n *\n * @param {workbox-routing.Route} route The route to unregister.\n */\n unregisterRoute(route) {\n if (!this._routes.has(route.method)) {\n throw new WorkboxError('unregister-route-but-not-found-with-method', {\n method: route.method,\n });\n }\n const routeIndex = this._routes.get(route.method).indexOf(route);\n if (routeIndex > -1) {\n this._routes.get(route.method).splice(routeIndex, 1);\n }\n else {\n throw new WorkboxError('unregister-route-route-not-registered');\n }\n }\n}\nexport { Router };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { Router } from '../Router.js';\nimport '../_version.js';\nlet defaultRouter;\n/**\n * Creates a new, singleton Router instance if one does not exist. If one\n * does already exist, that instance is returned.\n *\n * @private\n * @return {Router}\n */\nexport const getOrCreateDefaultRouter = () => {\n if (!defaultRouter) {\n defaultRouter = new Router();\n // The helpers that use the default Router assume these listeners exist.\n defaultRouter.addFetchListener();\n defaultRouter.addCacheListener();\n }\n return defaultRouter;\n};\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { Route } from './Route.js';\nimport { RegExpRoute } from './RegExpRoute.js';\nimport { getOrCreateDefaultRouter } from './utils/getOrCreateDefaultRouter.js';\nimport './_version.js';\n/**\n * Easily register a RegExp, string, or function with a caching\n * strategy to a singleton Router instance.\n *\n * This method will generate a Route for you if needed and\n * call {@link workbox-routing.Router#registerRoute}.\n *\n * @param {RegExp|string|workbox-routing.Route~matchCallback|workbox-routing.Route} capture\n * If the capture param is a `Route`, all other arguments will be ignored.\n * @param {workbox-routing~handlerCallback} [handler] A callback\n * function that returns a Promise resulting in a Response. This parameter\n * is required if `capture` is not a `Route` object.\n * @param {string} [method='GET'] The HTTP method to match the Route\n * against.\n * @return {workbox-routing.Route} The generated `Route`.\n *\n * @memberof workbox-routing\n */\nfunction registerRoute(capture, handler, method) {\n let route;\n if (typeof capture === 'string') {\n const captureUrl = new URL(capture, location.href);\n if (process.env.NODE_ENV !== 'production') {\n if (!(capture.startsWith('/') || capture.startsWith('http'))) {\n throw new WorkboxError('invalid-string', {\n moduleName: 'workbox-routing',\n funcName: 'registerRoute',\n paramName: 'capture',\n });\n }\n // We want to check if Express-style wildcards are in the pathname only.\n // TODO: Remove this log message in v4.\n const valueToCheck = capture.startsWith('http')\n ? captureUrl.pathname\n : capture;\n // See https://github.com/pillarjs/path-to-regexp#parameters\n const wildcards = '[*:?+]';\n if (new RegExp(`${wildcards}`).exec(valueToCheck)) {\n logger.debug(`The '$capture' parameter contains an Express-style wildcard ` +\n `character (${wildcards}). Strings are now always interpreted as ` +\n `exact matches; use a RegExp for partial or wildcard matches.`);\n }\n }\n const matchCallback = ({ url }) => {\n if (process.env.NODE_ENV !== 'production') {\n if (url.pathname === captureUrl.pathname &&\n url.origin !== captureUrl.origin) {\n logger.debug(`${capture} only partially matches the cross-origin URL ` +\n `${url.toString()}. This route will only handle cross-origin requests ` +\n `if they match the entire URL.`);\n }\n }\n return url.href === captureUrl.href;\n };\n // If `capture` is a string then `handler` and `method` must be present.\n route = new Route(matchCallback, handler, method);\n }\n else if (capture instanceof RegExp) {\n // If `capture` is a `RegExp` then `handler` and `method` must be present.\n route = new RegExpRoute(capture, handler, method);\n }\n else if (typeof capture === 'function') {\n // If `capture` is a function then `handler` and `method` must be present.\n route = new Route(capture, handler, method);\n }\n else if (capture instanceof Route) {\n route = capture;\n }\n else {\n throw new WorkboxError('unsupported-route-type', {\n moduleName: 'workbox-routing',\n funcName: 'registerRoute',\n paramName: 'capture',\n });\n }\n const defaultRouter = getOrCreateDefaultRouter();\n defaultRouter.registerRoute(route);\n return route;\n}\nexport { registerRoute };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreateDefaultRouter } from './utils/getOrCreateDefaultRouter.js';\nimport './_version.js';\n/**\n * If a Route throws an error while handling a request, this `handler`\n * will be called and given a chance to provide a response.\n *\n * @param {workbox-routing~handlerCallback} handler A callback\n * function that returns a Promise resulting in a Response.\n *\n * @memberof workbox-routing\n */\nfunction setCatchHandler(handler) {\n const defaultRouter = getOrCreateDefaultRouter();\n defaultRouter.setCatchHandler(handler);\n}\nexport { setCatchHandler };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreateDefaultRouter } from './utils/getOrCreateDefaultRouter.js';\nimport './_version.js';\n/**\n * Define a default `handler` that's called when no routes explicitly\n * match the incoming request.\n *\n * Without a default handler, unmatched requests will go against the\n * network as if there were no service worker present.\n *\n * @param {workbox-routing~handlerCallback} handler A callback\n * function that returns a Promise resulting in a Response.\n *\n * @memberof workbox-routing\n */\nfunction setDefaultHandler(handler) {\n const defaultRouter = getOrCreateDefaultRouter();\n defaultRouter.setDefaultHandler(handler);\n}\nexport { setDefaultHandler };\n"],"names":["self","_","e","defaultMethod","validMethods","normalizeHandler","handler","assert","hasMethod","moduleName","className","funcName","paramName","isType","handle","Route","constructor","match","method","isOneOf","setCatchHandler","catchHandler","NavigationRoute","allowlist","denylist","isArrayOfClass","RegExp","options","_match","_allowlist","_denylist","url","request","mode","pathnameAndSearch","pathname","search","regExp","test","logger","log","toString","some","debug","RegExpRoute","isInstance","result","exec","href","origin","location","index","slice","Router","_routes","Map","_defaultHandlerMap","routes","addFetchListener","addEventListener","event","responsePromise","handleRequest","respondWith","addCacheListener","data","type","payload","urlsToCache","requestPromises","Promise","all","map","entry","Request","waitUntil","ports","then","postMessage","URL","protocol","startsWith","sameOrigin","params","route","findMatchingRoute","debugMessages","push","has","get","getFriendlyURL","groupCollapsed","forEach","msg","Array","isArray","groupEnd","err","reject","_catchHandler","catch","error","catchErr","Error","matchResult","warn","length","undefined","Object","keys","setDefaultHandler","set","registerRoute","unregisterRoute","WorkboxError","routeIndex","indexOf","splice","defaultRouter","getOrCreateDefaultRouter","capture","captureUrl","valueToCheck","wildcards","matchCallback"],"mappings":";;;;IACA;IACA,IAAI;IACAA,EAAAA,IAAI,CAAC,uBAAuB,CAAC,IAAIC,CAAC,EAAE;IACxC,CAAC,CACD,OAAOC,CAAC,EAAE,CAAE;;ICLZ;IACA;;IAEA;IACA;IACA;IACA;IAEA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACO,MAAMC,aAAa,GAAG,KAAK;IAClC;IACA;IACA;IACA;IACA;IACA;IACA;IACO,MAAMC,YAAY,GAAG,CACxB,QAAQ,EACR,KAAK,EACL,MAAM,EACN,OAAO,EACP,MAAM,EACN,KAAK,CACR;;IC/BD;IACA;;IAEA;IACA;IACA;IACA;IAGA;IACA;IACA;IACA;IACA;IACA;IACA;IACO,MAAMC,gBAAgB,GAAIC,OAAO,IAAK;IACzC,EAAA,IAAIA,OAAO,IAAI,OAAOA,OAAO,KAAK,QAAQ,EAAE;IACxC,IAA2C;IACvCC,MAAAA,gB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,EAAE;IAC/BqE,IAAAA,KAAK,GAAGoC,OAAO;IACnB,EAAA,CAAC,MACI;IACD,IAAA,MAAM,IAAIN,4BAAY,CAAC,wBAAwB,EAAE;IAC7CzG,MAAAA,UAAU,EAAE,iBAAiB;IAC7BE,MAAAA,QAAQ,EAAE,eAAe;IACzBC,MAAAA,SAAS,EAAE;IACf,KAAC,CAAC;IACN,EAAA;IACA,EAAA,MAAM0G,aAAa,GAAGC,wBAAwB,EAAE;IAChDD,EAAAA,aAAa,CAACN,aAAa,CAAC5B,KAAK,CAAC;IAClC,EAAA,OAAOA,KAAK;IAChB;;IC3FA;IACA;;IAEA;IACA;IACA;IACA;IAGA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,SAAShE,eAAeA,CAACd,OAAO,EAAE;IAC9B,EAAA,MAAMgH,aAAa,GAAGC,wBAAwB,EAAE;IAChDD,EAAAA,aAAa,CAAClG,eAAe,CAACd,OAAO,CAAC;IAC1C;;ICrBA;IACA;;IAEA;IACA;IACA;IACA;IAGA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,SAASwG,iBAAiBA,CAACxG,OAAO,EAAE;IAChC,EAAA,MAAMgH,aAAa,GAAGC,wBAAwB,EAAE;IAChDD,EAAAA,aAAa,CAACR,iBAAiB,CAACxG,OAAO,CAAC;IAC5C;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/workbox-routing/build/workbox-routing.prod.js b/node_modules/workbox-routing/build/workbox-routing.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..06a91ddced3fa48d4d19b64da7edc8ec6c2d77bb --- /dev/null +++ b/node_modules/workbox-routing/build/workbox-routing.prod.js @@ -0,0 +1,2 @@ +this.workbox=this.workbox||{},this.workbox.routing=function(t,e){"use strict";try{self["workbox:routing:7.4.0"]&&_()}catch(t){}const s=t=>t&&"object"==typeof t?t:{handle:t};class r{constructor(t,e,r="GET"){this.handler=s(e),this.match=t,this.method=r}setCatchHandler(t){this.catchHandler=s(t)}}class n extends r{constructor(t,e,s){super((({url:e})=>{const s=t.exec(e.href);if(s&&(e.origin===location.origin||0===s.index))return s.slice(1)}),e,s)}}class i{constructor(){this.C=new Map,this.L=new Map}get routes(){return this.C}addFetchListener(){self.addEventListener("fetch",(t=>{const{request:e}=t,s=this.handleRequest({request:e,event:t});s&&t.respondWith(s)}))}addCacheListener(){self.addEventListener("message",(t=>{if(t.data&&"CACHE_URLS"===t.data.type){const{payload:e}=t.data,s=Promise.all(e.urlsToCache.map((e=>{"string"==typeof e&&(e=[e]);const s=new Request(...e);return this.handleRequest({request:s,event:t})})));t.waitUntil(s),t.ports&&t.ports[0]&&s.then((()=>t.ports[0].postMessage(!0)))}}))}handleRequest({request:t,event:e}){const s=new URL(t.url,location.href);if(!s.protocol.startsWith("http"))return;const r=s.origin===location.origin,{params:n,route:i}=this.findMatchingRoute({event:e,request:t,sameOrigin:r,url:s});let o=i&&i.handler;const u=t.method;if(!o&&this.L.has(u)&&(o=this.L.get(u)),!o)return;let c;try{c=o.handle({url:s,request:t,event:e,params:n})}catch(t){c=Promise.reject(t)}const a=i&&i.catchHandler;return c instanceof Promise&&(this.H||a)&&(c=c.catch((async r=>{if(a)try{return await a.handle({url:s,request:t,event:e,params:n})}catch(t){t instanceof Error&&(r=t)}if(this.H)return this.H.handle({url:s,request:t,event:e});throw r}))),c}findMatchingRoute({url:t,sameOrigin:e,request:s,event:r}){const n=this.C.get(s.method)||[];for(const i of n){let n;const o=i.match({url:t,sameOrigin:e,request:s,event:r});if(o)return n=o,(Array.isArray(n)&&0===n.length||o.constructor===Object&&0===Object.keys(o).length||"boolean"==typeof o)&&(n=void 0),{route:i,params:n}}return{}}setDefaultHandler(t,e="GET"){this.L.set(e,s(t))}setCatchHandler(t){this.H=s(t)}registerRoute(t){this.C.has(t.method)||this.C.set(t.method,[]),this.C.get(t.method).push(t)}unregisterRoute(t){if(!this.C.has(t.method))throw new e.WorkboxError("unregister-route-but-not-found-with-method",{method:t.method});const s=this.C.get(t.method).indexOf(t);if(!(s>-1))throw new e.WorkboxError("unregister-route-route-not-registered");this.C.get(t.method).splice(s,1)}}let o;const u=()=>(o||(o=new i,o.addFetchListener(),o.addCacheListener()),o);return t.NavigationRoute=class extends r{constructor(t,{allowlist:e=[/./],denylist:s=[]}={}){super((t=>this.j(t)),t),this.M=e,this.N=s}j({url:t,request:e}){if(e&&"navigate"!==e.mode)return!1;const s=t.pathname+t.search;for(const t of this.N)if(t.test(s))return!1;return!!this.M.some((t=>t.test(s)))}},t.RegExpRoute=n,t.Route=r,t.Router=i,t.registerRoute=function(t,s,i){let o;if("string"==typeof t){const e=new URL(t,location.href);o=new r((({url:t})=>t.href===e.href),s,i)}else if(t instanceof RegExp)o=new n(t,s,i);else if("function"==typeof t)o=new r(t,s,i);else{if(!(t instanceof r))throw new e.WorkboxError("unsupported-route-type",{moduleName:"workbox-routing",funcName:"registerRoute",paramName:"capture"});o=t}return u().registerRoute(o),o},t.setCatchHandler=function(t){u().setCatchHandler(t)},t.setDefaultHandler=function(t){u().setDefaultHandler(t)},t}({},workbox.core._private); +//# sourceMappingURL=workbox-routing.prod.js.map diff --git a/node_modules/workbox-routing/build/workbox-routing.prod.js.map b/node_modules/workbox-routing/build/workbox-routing.prod.js.map new file mode 100644 index 0000000000000000000000000000000000000000..04123ca0dce70539e0f99e57d4b53fb686d052af --- /dev/null +++ b/node_modules/workbox-routing/build/workbox-routing.prod.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-routing.prod.js","sources":["../_version.js","../utils/constants.js","../utils/normalizeHandler.js","../Route.js","../RegExpRoute.js","../Router.js","../utils/getOrCreateDefaultRouter.js","../NavigationRoute.js","../registerRoute.js","../setCatchHandler.js","../setDefaultHandler.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:routing:7.4.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 '../_version.js';\n/**\n * The default HTTP method, 'GET', used when there's no specific method\n * configured for a route.\n *\n * @type {string}\n *\n * @private\n */\nexport const defaultMethod = 'GET';\n/**\n * The list of valid HTTP methods associated with requests that could be routed.\n *\n * @type {Array}\n *\n * @private\n */\nexport const validMethods = [\n 'DELETE',\n 'GET',\n 'HEAD',\n 'PATCH',\n 'POST',\n 'PUT',\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 '../_version.js';\n/**\n * @param {function()|Object} handler Either a function, or an object with a\n * 'handle' method.\n * @return {Object} An object with a handle method.\n *\n * @private\n */\nexport const normalizeHandler = (handler) => {\n if (handler && typeof handler === 'object') {\n if (process.env.NODE_ENV !== 'production') {\n assert.hasMethod(handler, 'handle', {\n moduleName: 'workbox-routing',\n className: 'Route',\n funcName: 'constructor',\n paramName: 'handler',\n });\n }\n return handler;\n }\n else {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(handler, 'function', {\n moduleName: 'workbox-routing',\n className: 'Route',\n funcName: 'constructor',\n paramName: 'handler',\n });\n }\n return { handle: handler };\n }\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 { defaultMethod, validMethods } from './utils/constants.js';\nimport { normalizeHandler } from './utils/normalizeHandler.js';\nimport './_version.js';\n/**\n * A `Route` consists of a pair of callback functions, \"match\" and \"handler\".\n * The \"match\" callback determine if a route should be used to \"handle\" a\n * request by returning a non-falsy value if it can. The \"handler\" callback\n * is called when there is a match and should return a Promise that resolves\n * to a `Response`.\n *\n * @memberof workbox-routing\n */\nclass Route {\n /**\n * Constructor for Route class.\n *\n * @param {workbox-routing~matchCallback} match\n * A callback function that determines whether the route matches a given\n * `fetch` event by returning a non-falsy value.\n * @param {workbox-routing~handlerCallback} handler A callback\n * function that returns a Promise resolving to a Response.\n * @param {string} [method='GET'] The HTTP method to match the Route\n * against.\n */\n constructor(match, handler, method = defaultMethod) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(match, 'function', {\n moduleName: 'workbox-routing',\n className: 'Route',\n funcName: 'constructor',\n paramName: 'match',\n });\n if (method) {\n assert.isOneOf(method, validMethods, { paramName: 'method' });\n }\n }\n // These values are referenced directly by Router so cannot be\n // altered by minificaton.\n this.handler = normalizeHandler(handler);\n this.match = match;\n this.method = method;\n }\n /**\n *\n * @param {workbox-routing-handlerCallback} handler A callback\n * function that returns a Promise resolving to a Response\n */\n setCatchHandler(handler) {\n this.catchHandler = normalizeHandler(handler);\n }\n}\nexport { Route };\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 { logger } from 'workbox-core/_private/logger.js';\nimport { Route } from './Route.js';\nimport './_version.js';\n/**\n * RegExpRoute makes it easy to create a regular expression based\n * {@link workbox-routing.Route}.\n *\n * For same-origin requests the RegExp only needs to match part of the URL. For\n * requests against third-party servers, you must define a RegExp that matches\n * the start of the URL.\n *\n * @memberof workbox-routing\n * @extends workbox-routing.Route\n */\nclass RegExpRoute extends Route {\n /**\n * If the regular expression contains\n * [capture groups]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references},\n * the captured values will be passed to the\n * {@link workbox-routing~handlerCallback} `params`\n * argument.\n *\n * @param {RegExp} regExp The regular expression to match against URLs.\n * @param {workbox-routing~handlerCallback} handler A callback\n * function that returns a Promise resulting in a Response.\n * @param {string} [method='GET'] The HTTP method to match the Route\n * against.\n */\n constructor(regExp, handler, method) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(regExp, RegExp, {\n moduleName: 'workbox-routing',\n className: 'RegExpRoute',\n funcName: 'constructor',\n paramName: 'pattern',\n });\n }\n const match = ({ url }) => {\n const result = regExp.exec(url.href);\n // Return immediately if there's no match.\n if (!result) {\n return;\n }\n // Require that the match start at the first character in the URL string\n // if it's a cross-origin request.\n // See https://github.com/GoogleChrome/workbox/issues/281 for the context\n // behind this behavior.\n if (url.origin !== location.origin && result.index !== 0) {\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`The regular expression '${regExp.toString()}' only partially matched ` +\n `against the cross-origin URL '${url.toString()}'. RegExpRoute's will only ` +\n `handle cross-origin requests if they match the entire URL.`);\n }\n return;\n }\n // If the route matches, but there aren't any capture groups defined, then\n // this will return [], which is truthy and therefore sufficient to\n // indicate a match.\n // If there are capture groups, then it will return their values.\n return result.slice(1);\n };\n super(match, handler, method);\n }\n}\nexport { RegExpRoute };\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 { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { defaultMethod } from './utils/constants.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { normalizeHandler } from './utils/normalizeHandler.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport './_version.js';\n/**\n * The Router can be used to process a `FetchEvent` using one or more\n * {@link workbox-routing.Route}, responding with a `Response` if\n * a matching route exists.\n *\n * If no route matches a given a request, the Router will use a \"default\"\n * handler if one is defined.\n *\n * Should the matching Route throw an error, the Router will use a \"catch\"\n * handler if one is defined to gracefully deal with issues and respond with a\n * Request.\n *\n * If a request matches multiple routes, the **earliest** registered route will\n * be used to respond to the request.\n *\n * @memberof workbox-routing\n */\nclass Router {\n /**\n * Initializes a new Router.\n */\n constructor() {\n this._routes = new Map();\n this._defaultHandlerMap = new Map();\n }\n /**\n * @return {Map>} routes A `Map` of HTTP\n * method name ('GET', etc.) to an array of all the corresponding `Route`\n * instances that are registered.\n */\n get routes() {\n return this._routes;\n }\n /**\n * Adds a fetch event listener to respond to events when a route matches\n * the event's request.\n */\n addFetchListener() {\n // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705\n self.addEventListener('fetch', ((event) => {\n const { request } = event;\n const responsePromise = this.handleRequest({ request, event });\n if (responsePromise) {\n event.respondWith(responsePromise);\n }\n }));\n }\n /**\n * Adds a message event listener for URLs to cache from the window.\n * This is useful to cache resources loaded on the page prior to when the\n * service worker started controlling it.\n *\n * The format of the message data sent from the window should be as follows.\n * Where the `urlsToCache` array may consist of URL strings or an array of\n * URL string + `requestInit` object (the same as you'd pass to `fetch()`).\n *\n * ```\n * {\n * type: 'CACHE_URLS',\n * payload: {\n * urlsToCache: [\n * './script1.js',\n * './script2.js',\n * ['./script3.js', {mode: 'no-cors'}],\n * ],\n * },\n * }\n * ```\n */\n addCacheListener() {\n // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705\n self.addEventListener('message', ((event) => {\n // event.data is type 'any'\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (event.data && event.data.type === 'CACHE_URLS') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const { payload } = event.data;\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`Caching URLs from the window`, payload.urlsToCache);\n }\n const requestPromises = Promise.all(payload.urlsToCache.map((entry) => {\n if (typeof entry === 'string') {\n entry = [entry];\n }\n const request = new Request(...entry);\n return this.handleRequest({ request, event });\n // TODO(philipwalton): TypeScript errors without this typecast for\n // some reason (probably a bug). The real type here should work but\n // doesn't: `Array | undefined>`.\n })); // TypeScript\n event.waitUntil(requestPromises);\n // If a MessageChannel was used, reply to the message on success.\n if (event.ports && event.ports[0]) {\n void requestPromises.then(() => event.ports[0].postMessage(true));\n }\n }\n }));\n }\n /**\n * Apply the routing rules to a FetchEvent object to get a Response from an\n * appropriate Route's handler.\n *\n * @param {Object} options\n * @param {Request} options.request The request to handle.\n * @param {ExtendableEvent} options.event The event that triggered the\n * request.\n * @return {Promise|undefined} A promise is returned if a\n * registered route can handle the request. If there is no matching\n * route and there's no `defaultHandler`, `undefined` is returned.\n */\n handleRequest({ request, event, }) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(request, Request, {\n moduleName: 'workbox-routing',\n className: 'Router',\n funcName: 'handleRequest',\n paramName: 'options.request',\n });\n }\n const url = new URL(request.url, location.href);\n if (!url.protocol.startsWith('http')) {\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`Workbox Router only supports URLs that start with 'http'.`);\n }\n return;\n }\n const sameOrigin = url.origin === location.origin;\n const { params, route } = this.findMatchingRoute({\n event,\n request,\n sameOrigin,\n url,\n });\n let handler = route && route.handler;\n const debugMessages = [];\n if (process.env.NODE_ENV !== 'production') {\n if (handler) {\n debugMessages.push([`Found a route to handle this request:`, route]);\n if (params) {\n debugMessages.push([\n `Passing the following params to the route's handler:`,\n params,\n ]);\n }\n }\n }\n // If we don't have a handler because there was no matching route, then\n // fall back to defaultHandler if that's defined.\n const method = request.method;\n if (!handler && this._defaultHandlerMap.has(method)) {\n if (process.env.NODE_ENV !== 'production') {\n debugMessages.push(`Failed to find a matching route. Falling ` +\n `back to the default handler for ${method}.`);\n }\n handler = this._defaultHandlerMap.get(method);\n }\n if (!handler) {\n if (process.env.NODE_ENV !== 'production') {\n // No handler so Workbox will do nothing. If logs is set of debug\n // i.e. verbose, we should print out this information.\n logger.debug(`No route found for: ${getFriendlyURL(url)}`);\n }\n return;\n }\n if (process.env.NODE_ENV !== 'production') {\n // We have a handler, meaning Workbox is going to handle the route.\n // print the routing details to the console.\n logger.groupCollapsed(`Router is responding to: ${getFriendlyURL(url)}`);\n debugMessages.forEach((msg) => {\n if (Array.isArray(msg)) {\n logger.log(...msg);\n }\n else {\n logger.log(msg);\n }\n });\n logger.groupEnd();\n }\n // Wrap in try and catch in case the handle method throws a synchronous\n // error. It should still callback to the catch handler.\n let responsePromise;\n try {\n responsePromise = handler.handle({ url, request, event, params });\n }\n catch (err) {\n responsePromise = Promise.reject(err);\n }\n // Get route's catch handler, if it exists\n const catchHandler = route && route.catchHandler;\n if (responsePromise instanceof Promise &&\n (this._catchHandler || catchHandler)) {\n responsePromise = responsePromise.catch(async (err) => {\n // If there's a route catch handler, process that first\n if (catchHandler) {\n if (process.env.NODE_ENV !== 'production') {\n // Still include URL here as it will be async from the console group\n // and may not make sense without the URL\n logger.groupCollapsed(`Error thrown when responding to: ` +\n ` ${getFriendlyURL(url)}. Falling back to route's Catch Handler.`);\n logger.error(`Error thrown by:`, route);\n logger.error(err);\n logger.groupEnd();\n }\n try {\n return await catchHandler.handle({ url, request, event, params });\n }\n catch (catchErr) {\n if (catchErr instanceof Error) {\n err = catchErr;\n }\n }\n }\n if (this._catchHandler) {\n if (process.env.NODE_ENV !== 'production') {\n // Still include URL here as it will be async from the console group\n // and may not make sense without the URL\n logger.groupCollapsed(`Error thrown when responding to: ` +\n ` ${getFriendlyURL(url)}. Falling back to global Catch Handler.`);\n logger.error(`Error thrown by:`, route);\n logger.error(err);\n logger.groupEnd();\n }\n return this._catchHandler.handle({ url, request, event });\n }\n throw err;\n });\n }\n return responsePromise;\n }\n /**\n * Checks a request and URL (and optionally an event) against the list of\n * registered routes, and if there's a match, returns the corresponding\n * route along with any params generated by the match.\n *\n * @param {Object} options\n * @param {URL} options.url\n * @param {boolean} options.sameOrigin The result of comparing `url.origin`\n * against the current origin.\n * @param {Request} options.request The request to match.\n * @param {Event} options.event The corresponding event.\n * @return {Object} An object with `route` and `params` properties.\n * They are populated if a matching route was found or `undefined`\n * otherwise.\n */\n findMatchingRoute({ url, sameOrigin, request, event, }) {\n const routes = this._routes.get(request.method) || [];\n for (const route of routes) {\n let params;\n // route.match returns type any, not possible to change right now.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const matchResult = route.match({ url, sameOrigin, request, event });\n if (matchResult) {\n if (process.env.NODE_ENV !== 'production') {\n // Warn developers that using an async matchCallback is almost always\n // not the right thing to do.\n if (matchResult instanceof Promise) {\n logger.warn(`While routing ${getFriendlyURL(url)}, an async ` +\n `matchCallback function was used. Please convert the ` +\n `following route to use a synchronous matchCallback function:`, route);\n }\n }\n // See https://github.com/GoogleChrome/workbox/issues/2079\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n params = matchResult;\n if (Array.isArray(params) && params.length === 0) {\n // Instead of passing an empty array in as params, use undefined.\n params = undefined;\n }\n else if (matchResult.constructor === Object && // eslint-disable-line\n Object.keys(matchResult).length === 0) {\n // Instead of passing an empty object in as params, use undefined.\n params = undefined;\n }\n else if (typeof matchResult === 'boolean') {\n // For the boolean value true (rather than just something truth-y),\n // don't set params.\n // See https://github.com/GoogleChrome/workbox/pull/2134#issuecomment-513924353\n params = undefined;\n }\n // Return early if have a match.\n return { route, params };\n }\n }\n // If no match was found above, return and empty object.\n return {};\n }\n /**\n * Define a default `handler` that's called when no routes explicitly\n * match the incoming request.\n *\n * Each HTTP method ('GET', 'POST', etc.) gets its own default handler.\n *\n * Without a default handler, unmatched requests will go against the\n * network as if there were no service worker present.\n *\n * @param {workbox-routing~handlerCallback} handler A callback\n * function that returns a Promise resulting in a Response.\n * @param {string} [method='GET'] The HTTP method to associate with this\n * default handler. Each method has its own default.\n */\n setDefaultHandler(handler, method = defaultMethod) {\n this._defaultHandlerMap.set(method, normalizeHandler(handler));\n }\n /**\n * If a Route throws an error while handling a request, this `handler`\n * will be called and given a chance to provide a response.\n *\n * @param {workbox-routing~handlerCallback} handler A callback\n * function that returns a Promise resulting in a Response.\n */\n setCatchHandler(handler) {\n this._catchHandler = normalizeHandler(handler);\n }\n /**\n * Registers a route with the router.\n *\n * @param {workbox-routing.Route} route The route to register.\n */\n registerRoute(route) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(route, 'object', {\n moduleName: 'workbox-routing',\n className: 'Router',\n funcName: 'registerRoute',\n paramName: 'route',\n });\n assert.hasMethod(route, 'match', {\n moduleName: 'workbox-routing',\n className: 'Router',\n funcName: 'registerRoute',\n paramName: 'route',\n });\n assert.isType(route.handler, 'object', {\n moduleName: 'workbox-routing',\n className: 'Router',\n funcName: 'registerRoute',\n paramName: 'route',\n });\n assert.hasMethod(route.handler, 'handle', {\n moduleName: 'workbox-routing',\n className: 'Router',\n funcName: 'registerRoute',\n paramName: 'route.handler',\n });\n assert.isType(route.method, 'string', {\n moduleName: 'workbox-routing',\n className: 'Router',\n funcName: 'registerRoute',\n paramName: 'route.method',\n });\n }\n if (!this._routes.has(route.method)) {\n this._routes.set(route.method, []);\n }\n // Give precedence to all of the earlier routes by adding this additional\n // route to the end of the array.\n this._routes.get(route.method).push(route);\n }\n /**\n * Unregisters a route with the router.\n *\n * @param {workbox-routing.Route} route The route to unregister.\n */\n unregisterRoute(route) {\n if (!this._routes.has(route.method)) {\n throw new WorkboxError('unregister-route-but-not-found-with-method', {\n method: route.method,\n });\n }\n const routeIndex = this._routes.get(route.method).indexOf(route);\n if (routeIndex > -1) {\n this._routes.get(route.method).splice(routeIndex, 1);\n }\n else {\n throw new WorkboxError('unregister-route-route-not-registered');\n }\n }\n}\nexport { Router };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { Router } from '../Router.js';\nimport '../_version.js';\nlet defaultRouter;\n/**\n * Creates a new, singleton Router instance if one does not exist. If one\n * does already exist, that instance is returned.\n *\n * @private\n * @return {Router}\n */\nexport const getOrCreateDefaultRouter = () => {\n if (!defaultRouter) {\n defaultRouter = new Router();\n // The helpers that use the default Router assume these listeners exist.\n defaultRouter.addFetchListener();\n defaultRouter.addCacheListener();\n }\n return defaultRouter;\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 { logger } from 'workbox-core/_private/logger.js';\nimport { Route } from './Route.js';\nimport './_version.js';\n/**\n * NavigationRoute makes it easy to create a\n * {@link workbox-routing.Route} that matches for browser\n * [navigation requests]{@link https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests}.\n *\n * It will only match incoming Requests whose\n * {@link https://fetch.spec.whatwg.org/#concept-request-mode|mode}\n * is set to `navigate`.\n *\n * You can optionally only apply this route to a subset of navigation requests\n * by using one or both of the `denylist` and `allowlist` parameters.\n *\n * @memberof workbox-routing\n * @extends workbox-routing.Route\n */\nclass NavigationRoute extends Route {\n /**\n * If both `denylist` and `allowlist` are provided, the `denylist` will\n * take precedence and the request will not match this route.\n *\n * The regular expressions in `allowlist` and `denylist`\n * are matched against the concatenated\n * [`pathname`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/pathname}\n * and [`search`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search}\n * portions of the requested URL.\n *\n * *Note*: These RegExps may be evaluated against every destination URL during\n * a navigation. Avoid using\n * [complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077),\n * or else your users may see delays when navigating your site.\n *\n * @param {workbox-routing~handlerCallback} handler A callback\n * function that returns a Promise resulting in a Response.\n * @param {Object} options\n * @param {Array} [options.denylist] If any of these patterns match,\n * the route will not handle the request (even if a allowlist RegExp matches).\n * @param {Array} [options.allowlist=[/./]] If any of these patterns\n * match the URL's pathname and search parameter, the route will handle the\n * request (assuming the denylist doesn't match).\n */\n constructor(handler, { allowlist = [/./], denylist = [] } = {}) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isArrayOfClass(allowlist, RegExp, {\n moduleName: 'workbox-routing',\n className: 'NavigationRoute',\n funcName: 'constructor',\n paramName: 'options.allowlist',\n });\n assert.isArrayOfClass(denylist, RegExp, {\n moduleName: 'workbox-routing',\n className: 'NavigationRoute',\n funcName: 'constructor',\n paramName: 'options.denylist',\n });\n }\n super((options) => this._match(options), handler);\n this._allowlist = allowlist;\n this._denylist = denylist;\n }\n /**\n * Routes match handler.\n *\n * @param {Object} options\n * @param {URL} options.url\n * @param {Request} options.request\n * @return {boolean}\n *\n * @private\n */\n _match({ url, request }) {\n if (request && request.mode !== 'navigate') {\n return false;\n }\n const pathnameAndSearch = url.pathname + url.search;\n for (const regExp of this._denylist) {\n if (regExp.test(pathnameAndSearch)) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`The navigation route ${pathnameAndSearch} is not ` +\n `being used, since the URL matches this denylist pattern: ` +\n `${regExp.toString()}`);\n }\n return false;\n }\n }\n if (this._allowlist.some((regExp) => regExp.test(pathnameAndSearch))) {\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`The navigation route ${pathnameAndSearch} ` + `is being used.`);\n }\n return true;\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`The navigation route ${pathnameAndSearch} is not ` +\n `being used, since the URL being navigated to doesn't ` +\n `match the allowlist.`);\n }\n return false;\n }\n}\nexport { NavigationRoute };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { Route } from './Route.js';\nimport { RegExpRoute } from './RegExpRoute.js';\nimport { getOrCreateDefaultRouter } from './utils/getOrCreateDefaultRouter.js';\nimport './_version.js';\n/**\n * Easily register a RegExp, string, or function with a caching\n * strategy to a singleton Router instance.\n *\n * This method will generate a Route for you if needed and\n * call {@link workbox-routing.Router#registerRoute}.\n *\n * @param {RegExp|string|workbox-routing.Route~matchCallback|workbox-routing.Route} capture\n * If the capture param is a `Route`, all other arguments will be ignored.\n * @param {workbox-routing~handlerCallback} [handler] A callback\n * function that returns a Promise resulting in a Response. This parameter\n * is required if `capture` is not a `Route` object.\n * @param {string} [method='GET'] The HTTP method to match the Route\n * against.\n * @return {workbox-routing.Route} The generated `Route`.\n *\n * @memberof workbox-routing\n */\nfunction registerRoute(capture, handler, method) {\n let route;\n if (typeof capture === 'string') {\n const captureUrl = new URL(capture, location.href);\n if (process.env.NODE_ENV !== 'production') {\n if (!(capture.startsWith('/') || capture.startsWith('http'))) {\n throw new WorkboxError('invalid-string', {\n moduleName: 'workbox-routing',\n funcName: 'registerRoute',\n paramName: 'capture',\n });\n }\n // We want to check if Express-style wildcards are in the pathname only.\n // TODO: Remove this log message in v4.\n const valueToCheck = capture.startsWith('http')\n ? captureUrl.pathname\n : capture;\n // See https://github.com/pillarjs/path-to-regexp#parameters\n const wildcards = '[*:?+]';\n if (new RegExp(`${wildcards}`).exec(valueToCheck)) {\n logger.debug(`The '$capture' parameter contains an Express-style wildcard ` +\n `character (${wildcards}). Strings are now always interpreted as ` +\n `exact matches; use a RegExp for partial or wildcard matches.`);\n }\n }\n const matchCallback = ({ url }) => {\n if (process.env.NODE_ENV !== 'production') {\n if (url.pathname === captureUrl.pathname &&\n url.origin !== captureUrl.origin) {\n logger.debug(`${capture} only partially matches the cross-origin URL ` +\n `${url.toString()}. This route will only handle cross-origin requests ` +\n `if they match the entire URL.`);\n }\n }\n return url.href === captureUrl.href;\n };\n // If `capture` is a string then `handler` and `method` must be present.\n route = new Route(matchCallback, handler, method);\n }\n else if (capture instanceof RegExp) {\n // If `capture` is a `RegExp` then `handler` and `method` must be present.\n route = new RegExpRoute(capture, handler, method);\n }\n else if (typeof capture === 'function') {\n // If `capture` is a function then `handler` and `method` must be present.\n route = new Route(capture, handler, method);\n }\n else if (capture instanceof Route) {\n route = capture;\n }\n else {\n throw new WorkboxError('unsupported-route-type', {\n moduleName: 'workbox-routing',\n funcName: 'registerRoute',\n paramName: 'capture',\n });\n }\n const defaultRouter = getOrCreateDefaultRouter();\n defaultRouter.registerRoute(route);\n return route;\n}\nexport { registerRoute };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreateDefaultRouter } from './utils/getOrCreateDefaultRouter.js';\nimport './_version.js';\n/**\n * If a Route throws an error while handling a request, this `handler`\n * will be called and given a chance to provide a response.\n *\n * @param {workbox-routing~handlerCallback} handler A callback\n * function that returns a Promise resulting in a Response.\n *\n * @memberof workbox-routing\n */\nfunction setCatchHandler(handler) {\n const defaultRouter = getOrCreateDefaultRouter();\n defaultRouter.setCatchHandler(handler);\n}\nexport { setCatchHandler };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreateDefaultRouter } from './utils/getOrCreateDefaultRouter.js';\nimport './_version.js';\n/**\n * Define a default `handler` that's called when no routes explicitly\n * match the incoming request.\n *\n * Without a default handler, unmatched requests will go against the\n * network as if there were no service worker present.\n *\n * @param {workbox-routing~handlerCallback} handler A callback\n * function that returns a Promise resulting in a Response.\n *\n * @memberof workbox-routing\n */\nfunction setDefaultHandler(handler) {\n const defaultRouter = getOrCreateDefaultRouter();\n defaultRouter.setDefaultHandler(handler);\n}\nexport { setDefaultHandler };\n"],"names":["self","_","e","normalizeHandler","handler","handle","Route","constructor","match","method","this","setCatchHandler","catchHandler","RegExpRoute","regExp","super","url","result","exec","href","origin","location","index","slice","Router","_routes","Map","_defaultHandlerMap","routes","addFetchListener","addEventListener","event","request","responsePromise","handleRequest","respondWith","addCacheListener","data","type","payload","requestPromises","Promise","all","urlsToCache","map","entry","Request","waitUntil","ports","then","postMessage","URL","protocol","startsWith","sameOrigin","params","route","findMatchingRoute","has","get","err","reject","_catchHandler","catch","async","catchErr","Error","matchResult","Array","isArray","length","Object","keys","undefined","setDefaultHandler","set","registerRoute","push","unregisterRoute","WorkboxError","routeIndex","indexOf","splice","defaultRouter","getOrCreateDefaultRouter","allowlist","denylist","options","_match","_allowlist","_denylist","mode","pathnameAndSearch","pathname","search","test","some","capture","captureUrl","matchCallback","RegExp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aAAjBA,EAAQ2D,KACnB,OAAO,EAEX,MAAMC,EAAoB5E,EAAI6E,SAAW7E,EAAI8E,OAC7C,IAAK,MAAMhF,KAAUJ,KAAKgF,EACtB,GAAI5E,EAAOiF,KAAKH,GAMZ,OAAO,EAGf,QAAIlF,KAAK+E,EAAWO,MAAMlF,GAAWA,EAAOiF,KAAKH,IAYrD,wDC5EJ,SAAuBK,EAAS7F,EAASK,GACrC,IAAI+C,EACJ,GAAuB,iBAAZyC,EAAsB,CAC7B,MAAMC,EAAa,IAAI/C,IAAI8C,EAAS5E,SAASF,MAkC7CqC,EAAQ,IAAIlD,GAZU6F,EAAGnF,SASdA,EAAIG,OAAS+E,EAAW/E,MAGFf,EAASK,EAC9C,MACK,GAAIwF,aAAmBG,OAExB5C,EAAQ,IAAI3C,EAAYoF,EAAS7F,EAASK,QAEzC,GAAuB,mBAAZwF,EAEZzC,EAAQ,IAAIlD,EAAM2F,EAAS7F,EAASK,OAEnC,MAAIwF,aAAmB3F,GAIxB,MAAM,IAAIyE,EAAAA,aAAa,yBAA0B,CAC7CsB,WAAY,kBACZC,SAAU,gBACVC,UAAW,YANf/C,EAAQyC,CAQZ,CAGA,OAFsBb,IACRR,cAAcpB,GACrBA,CACX,oBCzEA,SAAyBpD,GACCgF,IACRzE,gBAAgBP,EAClC,sBCAA,SAA2BA,GACDgF,IACRV,kBAAkBtE,EACpC"} \ No newline at end of file diff --git a/node_modules/workbox-routing/index.d.ts b/node_modules/workbox-routing/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1139287ff9aa271b6279bc32a6d3f915d2573f39 --- /dev/null +++ b/node_modules/workbox-routing/index.d.ts @@ -0,0 +1,12 @@ +import { NavigationRoute, NavigationRouteMatchOptions } from './NavigationRoute.js'; +import { RegExpRoute } from './RegExpRoute.js'; +import { registerRoute } from './registerRoute.js'; +import { Route } from './Route.js'; +import { Router } from './Router.js'; +import { setCatchHandler } from './setCatchHandler.js'; +import { setDefaultHandler } from './setDefaultHandler.js'; +import './_version.js'; +/** + * @module workbox-routing + */ +export { NavigationRoute, RegExpRoute, registerRoute, Route, Router, setCatchHandler, setDefaultHandler, NavigationRouteMatchOptions, }; diff --git a/node_modules/workbox-routing/index.js b/node_modules/workbox-routing/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b84816eeba49baa0f3ee076f8949b95d03c5ec40 --- /dev/null +++ b/node_modules/workbox-routing/index.js @@ -0,0 +1,19 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { NavigationRoute, } from './NavigationRoute.js'; +import { RegExpRoute } from './RegExpRoute.js'; +import { registerRoute } from './registerRoute.js'; +import { Route } from './Route.js'; +import { Router } from './Router.js'; +import { setCatchHandler } from './setCatchHandler.js'; +import { setDefaultHandler } from './setDefaultHandler.js'; +import './_version.js'; +/** + * @module workbox-routing + */ +export { NavigationRoute, RegExpRoute, registerRoute, Route, Router, setCatchHandler, setDefaultHandler, }; diff --git a/node_modules/workbox-routing/index.mjs b/node_modules/workbox-routing/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..833b6a2f3226fec78490a3b7a622dc5146f94b53 --- /dev/null +++ b/node_modules/workbox-routing/index.mjs @@ -0,0 +1 @@ +export * from './index.js'; \ No newline at end of file diff --git a/node_modules/workbox-routing/package.json b/node_modules/workbox-routing/package.json new file mode 100644 index 0000000000000000000000000000000000000000..20d0471610925ad4fc2fcf5caa55750c541bbbda --- /dev/null +++ b/node_modules/workbox-routing/package.json @@ -0,0 +1,32 @@ +{ + "name": "workbox-routing", + "version": "7.4.1", + "license": "MIT", + "author": "Google's Web DevRel Team and Google's Aurora Team", + "description": "A service worker helper library to route request URLs to handlers.", + "repository": { + "type": "git", + "url": "git+https://github.com/googlechrome/workbox.git" + }, + "bugs": "https://github.com/googlechrome/workbox/issues", + "homepage": "https://github.com/GoogleChrome/workbox", + "keywords": [ + "workbox", + "workboxjs", + "service worker", + "sw", + "router", + "routing" + ], + "workbox": { + "browserNamespace": "workbox.routing", + "packageType": "sw" + }, + "main": "index.js", + "module": "index.mjs", + "types": "index.d.ts", + "dependencies": { + "workbox-core": "7.4.1" + }, + "gitHead": "62b9d8ba8eb3c1a2ab8aac9d84c90cda7865d6a3" +} diff --git a/node_modules/workbox-routing/registerRoute.d.ts b/node_modules/workbox-routing/registerRoute.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fafe5e9dce9300a17ca01ea8a39c3de378e964e9 --- /dev/null +++ b/node_modules/workbox-routing/registerRoute.d.ts @@ -0,0 +1,24 @@ +import { RouteHandler, RouteMatchCallback } from 'workbox-core/types.js'; +import { Route } from './Route.js'; +import { HTTPMethod } from './utils/constants.js'; +import './_version.js'; +/** + * Easily register a RegExp, string, or function with a caching + * strategy to a singleton Router instance. + * + * This method will generate a Route for you if needed and + * call {@link workbox-routing.Router#registerRoute}. + * + * @param {RegExp|string|workbox-routing.Route~matchCallback|workbox-routing.Route} capture + * If the capture param is a `Route`, all other arguments will be ignored. + * @param {workbox-routing~handlerCallback} [handler] A callback + * function that returns a Promise resulting in a Response. This parameter + * is required if `capture` is not a `Route` object. + * @param {string} [method='GET'] The HTTP method to match the Route + * against. + * @return {workbox-routing.Route} The generated `Route`. + * + * @memberof workbox-routing + */ +declare function registerRoute(capture: RegExp | string | RouteMatchCallback | Route, handler?: RouteHandler, method?: HTTPMethod): Route; +export { registerRoute }; diff --git a/node_modules/workbox-routing/registerRoute.js b/node_modules/workbox-routing/registerRoute.js new file mode 100644 index 0000000000000000000000000000000000000000..a766897ffd67380fa7ae8e581bec5d97901705a3 --- /dev/null +++ b/node_modules/workbox-routing/registerRoute.js @@ -0,0 +1,93 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { logger } from 'workbox-core/_private/logger.js'; +import { WorkboxError } from 'workbox-core/_private/WorkboxError.js'; +import { Route } from './Route.js'; +import { RegExpRoute } from './RegExpRoute.js'; +import { getOrCreateDefaultRouter } from './utils/getOrCreateDefaultRouter.js'; +import './_version.js'; +/** + * Easily register a RegExp, string, or function with a caching + * strategy to a singleton Router instance. + * + * This method will generate a Route for you if needed and + * call {@link workbox-routing.Router#registerRoute}. + * + * @param {RegExp|string|workbox-routing.Route~matchCallback|workbox-routing.Route} capture + * If the capture param is a `Route`, all other arguments will be ignored. + * @param {workbox-routing~handlerCallback} [handler] A callback + * function that returns a Promise resulting in a Response. This parameter + * is required if `capture` is not a `Route` object. + * @param {string} [method='GET'] The HTTP method to match the Route + * against. + * @return {workbox-routing.Route} The generated `Route`. + * + * @memberof workbox-routing + */ +function registerRoute(capture, handler, method) { + let route; + if (typeof capture === 'string') { + const captureUrl = new URL(capture, location.href); + if (process.env.NODE_ENV !== 'production') { + if (!(capture.startsWith('/') || capture.startsWith('http'))) { + throw new WorkboxError('invalid-string', { + moduleName: 'workbox-routing', + funcName: 'registerRoute', + paramName: 'capture', + }); + } + // We want to check if Express-style wildcards are in the pathname only. + // TODO: Remove this log message in v4. + const valueToCheck = capture.startsWith('http') + ? captureUrl.pathname + : capture; + // See https://github.com/pillarjs/path-to-regexp#parameters + const wildcards = '[*:?+]'; + if (new RegExp(`${wildcards}`).exec(valueToCheck)) { + logger.debug(`The '$capture' parameter contains an Express-style wildcard ` + + `character (${wildcards}). Strings are now always interpreted as ` + + `exact matches; use a RegExp for partial or wildcard matches.`); + } + } + const matchCallback = ({ url }) => { + if (process.env.NODE_ENV !== 'production') { + if (url.pathname === captureUrl.pathname && + url.origin !== captureUrl.origin) { + logger.debug(`${capture} only partially matches the cross-origin URL ` + + `${url.toString()}. This route will only handle cross-origin requests ` + + `if they match the entire URL.`); + } + } + return url.href === captureUrl.href; + }; + // If `capture` is a string then `handler` and `method` must be present. + route = new Route(matchCallback, handler, method); + } + else if (capture instanceof RegExp) { + // If `capture` is a `RegExp` then `handler` and `method` must be present. + route = new RegExpRoute(capture, handler, method); + } + else if (typeof capture === 'function') { + // If `capture` is a function then `handler` and `method` must be present. + route = new Route(capture, handler, method); + } + else if (capture instanceof Route) { + route = capture; + } + else { + throw new WorkboxError('unsupported-route-type', { + moduleName: 'workbox-routing', + funcName: 'registerRoute', + paramName: 'capture', + }); + } + const defaultRouter = getOrCreateDefaultRouter(); + defaultRouter.registerRoute(route); + return route; +} +export { registerRoute }; diff --git a/node_modules/workbox-routing/registerRoute.mjs b/node_modules/workbox-routing/registerRoute.mjs new file mode 100644 index 0000000000000000000000000000000000000000..fab0aff9ea8e378bba91efff1134af604c567366 --- /dev/null +++ b/node_modules/workbox-routing/registerRoute.mjs @@ -0,0 +1 @@ +export * from './registerRoute.js'; \ No newline at end of file diff --git a/node_modules/workbox-routing/setCatchHandler.d.ts b/node_modules/workbox-routing/setCatchHandler.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..42d4a858b6141235487c9bbe9c4af55bd4a9bb18 --- /dev/null +++ b/node_modules/workbox-routing/setCatchHandler.d.ts @@ -0,0 +1,13 @@ +import { RouteHandler } from 'workbox-core/types.js'; +import './_version.js'; +/** + * If a Route throws an error while handling a request, this `handler` + * will be called and given a chance to provide a response. + * + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + * + * @memberof workbox-routing + */ +declare function setCatchHandler(handler: RouteHandler): void; +export { setCatchHandler }; diff --git a/node_modules/workbox-routing/setCatchHandler.js b/node_modules/workbox-routing/setCatchHandler.js new file mode 100644 index 0000000000000000000000000000000000000000..b39aeb16b21c8a58120a8ec40e1f0e31ecdbc988 --- /dev/null +++ b/node_modules/workbox-routing/setCatchHandler.js @@ -0,0 +1,23 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { getOrCreateDefaultRouter } from './utils/getOrCreateDefaultRouter.js'; +import './_version.js'; +/** + * If a Route throws an error while handling a request, this `handler` + * will be called and given a chance to provide a response. + * + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + * + * @memberof workbox-routing + */ +function setCatchHandler(handler) { + const defaultRouter = getOrCreateDefaultRouter(); + defaultRouter.setCatchHandler(handler); +} +export { setCatchHandler }; diff --git a/node_modules/workbox-routing/setCatchHandler.mjs b/node_modules/workbox-routing/setCatchHandler.mjs new file mode 100644 index 0000000000000000000000000000000000000000..37013b093b6a57d801a5d56f1d2a6751ded56aed --- /dev/null +++ b/node_modules/workbox-routing/setCatchHandler.mjs @@ -0,0 +1 @@ +export * from './setCatchHandler.js'; \ No newline at end of file diff --git a/node_modules/workbox-routing/setDefaultHandler.d.ts b/node_modules/workbox-routing/setDefaultHandler.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..35811336308ff60aa975d4b98fb0e17dbb3e5aa6 --- /dev/null +++ b/node_modules/workbox-routing/setDefaultHandler.d.ts @@ -0,0 +1,16 @@ +import { RouteHandler } from 'workbox-core/types.js'; +import './_version.js'; +/** + * Define a default `handler` that's called when no routes explicitly + * match the incoming request. + * + * Without a default handler, unmatched requests will go against the + * network as if there were no service worker present. + * + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + * + * @memberof workbox-routing + */ +declare function setDefaultHandler(handler: RouteHandler): void; +export { setDefaultHandler }; diff --git a/node_modules/workbox-routing/setDefaultHandler.js b/node_modules/workbox-routing/setDefaultHandler.js new file mode 100644 index 0000000000000000000000000000000000000000..5f2892abca8ea8662d8b934d393c1e5f7ec553e3 --- /dev/null +++ b/node_modules/workbox-routing/setDefaultHandler.js @@ -0,0 +1,26 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { getOrCreateDefaultRouter } from './utils/getOrCreateDefaultRouter.js'; +import './_version.js'; +/** + * Define a default `handler` that's called when no routes explicitly + * match the incoming request. + * + * Without a default handler, unmatched requests will go against the + * network as if there were no service worker present. + * + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + * + * @memberof workbox-routing + */ +function setDefaultHandler(handler) { + const defaultRouter = getOrCreateDefaultRouter(); + defaultRouter.setDefaultHandler(handler); +} +export { setDefaultHandler }; diff --git a/node_modules/workbox-routing/setDefaultHandler.mjs b/node_modules/workbox-routing/setDefaultHandler.mjs new file mode 100644 index 0000000000000000000000000000000000000000..17e2fee413bdafea4d25a443d09bc1f61c46f65e --- /dev/null +++ b/node_modules/workbox-routing/setDefaultHandler.mjs @@ -0,0 +1 @@ +export * from './setDefaultHandler.js'; \ No newline at end of file diff --git a/node_modules/workbox-routing/src/NavigationRoute.ts b/node_modules/workbox-routing/src/NavigationRoute.ts new file mode 100644 index 0000000000000000000000000000000000000000..7c878cd7f4a38793fa99156258c66cd4249ed46d --- /dev/null +++ b/node_modules/workbox-routing/src/NavigationRoute.ts @@ -0,0 +1,143 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {assert} from 'workbox-core/_private/assert.js'; +import {logger} from 'workbox-core/_private/logger.js'; +import {RouteHandler, RouteMatchCallbackOptions} from 'workbox-core/types.js'; + +import {Route} from './Route.js'; + +import './_version.js'; + +export interface NavigationRouteMatchOptions { + allowlist?: RegExp[]; + denylist?: RegExp[]; +} + +/** + * NavigationRoute makes it easy to create a + * {@link workbox-routing.Route} that matches for browser + * [navigation requests]{@link https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests}. + * + * It will only match incoming Requests whose + * {@link https://fetch.spec.whatwg.org/#concept-request-mode|mode} + * is set to `navigate`. + * + * You can optionally only apply this route to a subset of navigation requests + * by using one or both of the `denylist` and `allowlist` parameters. + * + * @memberof workbox-routing + * @extends workbox-routing.Route + */ +class NavigationRoute extends Route { + private readonly _allowlist: RegExp[]; + private readonly _denylist: RegExp[]; + + /** + * If both `denylist` and `allowlist` are provided, the `denylist` will + * take precedence and the request will not match this route. + * + * The regular expressions in `allowlist` and `denylist` + * are matched against the concatenated + * [`pathname`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/pathname} + * and [`search`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search} + * portions of the requested URL. + * + * *Note*: These RegExps may be evaluated against every destination URL during + * a navigation. Avoid using + * [complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077), + * or else your users may see delays when navigating your site. + * + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + * @param {Object} options + * @param {Array} [options.denylist] If any of these patterns match, + * the route will not handle the request (even if a allowlist RegExp matches). + * @param {Array} [options.allowlist=[/./]] If any of these patterns + * match the URL's pathname and search parameter, the route will handle the + * request (assuming the denylist doesn't match). + */ + constructor( + handler: RouteHandler, + {allowlist = [/./], denylist = []}: NavigationRouteMatchOptions = {}, + ) { + if (process.env.NODE_ENV !== 'production') { + assert!.isArrayOfClass(allowlist, RegExp, { + moduleName: 'workbox-routing', + className: 'NavigationRoute', + funcName: 'constructor', + paramName: 'options.allowlist', + }); + assert!.isArrayOfClass(denylist, RegExp, { + moduleName: 'workbox-routing', + className: 'NavigationRoute', + funcName: 'constructor', + paramName: 'options.denylist', + }); + } + + super( + (options: RouteMatchCallbackOptions) => this._match(options), + handler, + ); + + this._allowlist = allowlist; + this._denylist = denylist; + } + + /** + * Routes match handler. + * + * @param {Object} options + * @param {URL} options.url + * @param {Request} options.request + * @return {boolean} + * + * @private + */ + private _match({url, request}: RouteMatchCallbackOptions): boolean { + if (request && request.mode !== 'navigate') { + return false; + } + + const pathnameAndSearch = url.pathname + url.search; + + for (const regExp of this._denylist) { + if (regExp.test(pathnameAndSearch)) { + if (process.env.NODE_ENV !== 'production') { + logger.log( + `The navigation route ${pathnameAndSearch} is not ` + + `being used, since the URL matches this denylist pattern: ` + + `${regExp.toString()}`, + ); + } + return false; + } + } + + if (this._allowlist.some((regExp) => regExp.test(pathnameAndSearch))) { + if (process.env.NODE_ENV !== 'production') { + logger.debug( + `The navigation route ${pathnameAndSearch} ` + `is being used.`, + ); + } + return true; + } + + if (process.env.NODE_ENV !== 'production') { + logger.log( + `The navigation route ${pathnameAndSearch} is not ` + + `being used, since the URL being navigated to doesn't ` + + `match the allowlist.`, + ); + } + return false; + } +} + +export {NavigationRoute}; diff --git a/node_modules/workbox-routing/src/RegExpRoute.ts b/node_modules/workbox-routing/src/RegExpRoute.ts new file mode 100644 index 0000000000000000000000000000000000000000..42f999cfdce6b20f55ea34338f1fddce20f0eea9 --- /dev/null +++ b/node_modules/workbox-routing/src/RegExpRoute.ts @@ -0,0 +1,92 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {assert} from 'workbox-core/_private/assert.js'; +import {logger} from 'workbox-core/_private/logger.js'; +import { + RouteHandler, + RouteMatchCallback, + RouteMatchCallbackOptions, +} from 'workbox-core/types.js'; + +import {HTTPMethod} from './utils/constants.js'; +import {Route} from './Route.js'; + +import './_version.js'; + +/** + * RegExpRoute makes it easy to create a regular expression based + * {@link workbox-routing.Route}. + * + * For same-origin requests the RegExp only needs to match part of the URL. For + * requests against third-party servers, you must define a RegExp that matches + * the start of the URL. + * + * @memberof workbox-routing + * @extends workbox-routing.Route + */ +class RegExpRoute extends Route { + /** + * If the regular expression contains + * [capture groups]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references}, + * the captured values will be passed to the + * {@link workbox-routing~handlerCallback} `params` + * argument. + * + * @param {RegExp} regExp The regular expression to match against URLs. + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + * @param {string} [method='GET'] The HTTP method to match the Route + * against. + */ + constructor(regExp: RegExp, handler: RouteHandler, method?: HTTPMethod) { + if (process.env.NODE_ENV !== 'production') { + assert!.isInstance(regExp, RegExp, { + moduleName: 'workbox-routing', + className: 'RegExpRoute', + funcName: 'constructor', + paramName: 'pattern', + }); + } + + const match: RouteMatchCallback = ({url}: RouteMatchCallbackOptions) => { + const result = regExp.exec(url.href); + + // Return immediately if there's no match. + if (!result) { + return; + } + + // Require that the match start at the first character in the URL string + // if it's a cross-origin request. + // See https://github.com/GoogleChrome/workbox/issues/281 for the context + // behind this behavior. + if (url.origin !== location.origin && result.index !== 0) { + if (process.env.NODE_ENV !== 'production') { + logger.debug( + `The regular expression '${regExp.toString()}' only partially matched ` + + `against the cross-origin URL '${url.toString()}'. RegExpRoute's will only ` + + `handle cross-origin requests if they match the entire URL.`, + ); + } + + return; + } + + // If the route matches, but there aren't any capture groups defined, then + // this will return [], which is truthy and therefore sufficient to + // indicate a match. + // If there are capture groups, then it will return their values. + return result.slice(1); + }; + + super(match, handler, method); + } +} + +export {RegExpRoute}; diff --git a/node_modules/workbox-routing/src/Route.ts b/node_modules/workbox-routing/src/Route.ts new file mode 100644 index 0000000000000000000000000000000000000000..5af836d151b8d5a2f2bc0255ee034e4520a6e8e3 --- /dev/null +++ b/node_modules/workbox-routing/src/Route.ts @@ -0,0 +1,80 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {assert} from 'workbox-core/_private/assert.js'; +import {HTTPMethod, defaultMethod, validMethods} from './utils/constants.js'; +import {normalizeHandler} from './utils/normalizeHandler.js'; +import { + RouteHandler, + RouteHandlerObject, + RouteMatchCallback, +} from 'workbox-core/types.js'; +import './_version.js'; + +/** + * A `Route` consists of a pair of callback functions, "match" and "handler". + * The "match" callback determine if a route should be used to "handle" a + * request by returning a non-falsy value if it can. The "handler" callback + * is called when there is a match and should return a Promise that resolves + * to a `Response`. + * + * @memberof workbox-routing + */ +class Route { + handler: RouteHandlerObject; + match: RouteMatchCallback; + method: HTTPMethod; + catchHandler?: RouteHandlerObject; + + /** + * Constructor for Route class. + * + * @param {workbox-routing~matchCallback} match + * A callback function that determines whether the route matches a given + * `fetch` event by returning a non-falsy value. + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resolving to a Response. + * @param {string} [method='GET'] The HTTP method to match the Route + * against. + */ + constructor( + match: RouteMatchCallback, + handler: RouteHandler, + method: HTTPMethod = defaultMethod, + ) { + if (process.env.NODE_ENV !== 'production') { + assert!.isType(match, 'function', { + moduleName: 'workbox-routing', + className: 'Route', + funcName: 'constructor', + paramName: 'match', + }); + + if (method) { + assert!.isOneOf(method, validMethods, {paramName: 'method'}); + } + } + + // These values are referenced directly by Router so cannot be + // altered by minificaton. + this.handler = normalizeHandler(handler); + this.match = match; + this.method = method; + } + + /** + * + * @param {workbox-routing-handlerCallback} handler A callback + * function that returns a Promise resolving to a Response + */ + setCatchHandler(handler: RouteHandler): void { + this.catchHandler = normalizeHandler(handler); + } +} + +export {Route}; diff --git a/node_modules/workbox-routing/src/Router.ts b/node_modules/workbox-routing/src/Router.ts new file mode 100644 index 0000000000000000000000000000000000000000..316f301590be805736b40a53be46d630c525cff2 --- /dev/null +++ b/node_modules/workbox-routing/src/Router.ts @@ -0,0 +1,489 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {assert} from 'workbox-core/_private/assert.js'; +import {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.js'; +import { + RouteHandler, + RouteHandlerObject, + RouteHandlerCallbackOptions, + RouteMatchCallbackOptions, +} from 'workbox-core/types.js'; +import {HTTPMethod, defaultMethod} from './utils/constants.js'; +import {logger} from 'workbox-core/_private/logger.js'; +import {normalizeHandler} from './utils/normalizeHandler.js'; +import {Route} from './Route.js'; +import {WorkboxError} from 'workbox-core/_private/WorkboxError.js'; + +import './_version.js'; + +type RequestArgs = string | [string, RequestInit?]; + +interface CacheURLsMessageData { + type: string; + payload: { + urlsToCache: RequestArgs[]; + }; +} + +/** + * The Router can be used to process a `FetchEvent` using one or more + * {@link workbox-routing.Route}, responding with a `Response` if + * a matching route exists. + * + * If no route matches a given a request, the Router will use a "default" + * handler if one is defined. + * + * Should the matching Route throw an error, the Router will use a "catch" + * handler if one is defined to gracefully deal with issues and respond with a + * Request. + * + * If a request matches multiple routes, the **earliest** registered route will + * be used to respond to the request. + * + * @memberof workbox-routing + */ +class Router { + private readonly _routes: Map; + private readonly _defaultHandlerMap: Map; + private _catchHandler?: RouteHandlerObject; + + /** + * Initializes a new Router. + */ + constructor() { + this._routes = new Map(); + this._defaultHandlerMap = new Map(); + } + + /** + * @return {Map>} routes A `Map` of HTTP + * method name ('GET', etc.) to an array of all the corresponding `Route` + * instances that are registered. + */ + get routes(): Map { + return this._routes; + } + + /** + * Adds a fetch event listener to respond to events when a route matches + * the event's request. + */ + addFetchListener(): void { + // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705 + self.addEventListener('fetch', ((event: FetchEvent) => { + const {request} = event; + const responsePromise = this.handleRequest({request, event}); + if (responsePromise) { + event.respondWith(responsePromise); + } + }) as EventListener); + } + + /** + * Adds a message event listener for URLs to cache from the window. + * This is useful to cache resources loaded on the page prior to when the + * service worker started controlling it. + * + * The format of the message data sent from the window should be as follows. + * Where the `urlsToCache` array may consist of URL strings or an array of + * URL string + `requestInit` object (the same as you'd pass to `fetch()`). + * + * ``` + * { + * type: 'CACHE_URLS', + * payload: { + * urlsToCache: [ + * './script1.js', + * './script2.js', + * ['./script3.js', {mode: 'no-cors'}], + * ], + * }, + * } + * ``` + */ + addCacheListener(): void { + // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705 + self.addEventListener('message', ((event: ExtendableMessageEvent) => { + // event.data is type 'any' + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (event.data && event.data.type === 'CACHE_URLS') { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const {payload}: CacheURLsMessageData = event.data; + + if (process.env.NODE_ENV !== 'production') { + logger.debug(`Caching URLs from the window`, payload.urlsToCache); + } + + const requestPromises = Promise.all( + payload.urlsToCache.map((entry: string | [string, RequestInit?]) => { + if (typeof entry === 'string') { + entry = [entry]; + } + + const request = new Request(...entry); + return this.handleRequest({request, event}); + + // TODO(philipwalton): TypeScript errors without this typecast for + // some reason (probably a bug). The real type here should work but + // doesn't: `Array | undefined>`. + }) as any[], + ); // TypeScript + + event.waitUntil(requestPromises); + + // If a MessageChannel was used, reply to the message on success. + if (event.ports && event.ports[0]) { + void requestPromises.then(() => event.ports[0].postMessage(true)); + } + } + }) as EventListener); + } + + /** + * Apply the routing rules to a FetchEvent object to get a Response from an + * appropriate Route's handler. + * + * @param {Object} options + * @param {Request} options.request The request to handle. + * @param {ExtendableEvent} options.event The event that triggered the + * request. + * @return {Promise|undefined} A promise is returned if a + * registered route can handle the request. If there is no matching + * route and there's no `defaultHandler`, `undefined` is returned. + */ + handleRequest({ + request, + event, + }: { + request: Request; + event: ExtendableEvent; + }): Promise | undefined { + if (process.env.NODE_ENV !== 'production') { + assert!.isInstance(request, Request, { + moduleName: 'workbox-routing', + className: 'Router', + funcName: 'handleRequest', + paramName: 'options.request', + }); + } + + const url = new URL(request.url, location.href); + if (!url.protocol.startsWith('http')) { + if (process.env.NODE_ENV !== 'production') { + logger.debug( + `Workbox Router only supports URLs that start with 'http'.`, + ); + } + return; + } + + const sameOrigin = url.origin === location.origin; + const {params, route} = this.findMatchingRoute({ + event, + request, + sameOrigin, + url, + }); + let handler = route && route.handler; + + const debugMessages = []; + if (process.env.NODE_ENV !== 'production') { + if (handler) { + debugMessages.push([`Found a route to handle this request:`, route]); + + if (params) { + debugMessages.push([ + `Passing the following params to the route's handler:`, + params, + ]); + } + } + } + + // If we don't have a handler because there was no matching route, then + // fall back to defaultHandler if that's defined. + const method = request.method as HTTPMethod; + if (!handler && this._defaultHandlerMap.has(method)) { + if (process.env.NODE_ENV !== 'production') { + debugMessages.push( + `Failed to find a matching route. Falling ` + + `back to the default handler for ${method}.`, + ); + } + handler = this._defaultHandlerMap.get(method); + } + + if (!handler) { + if (process.env.NODE_ENV !== 'production') { + // No handler so Workbox will do nothing. If logs is set of debug + // i.e. verbose, we should print out this information. + logger.debug(`No route found for: ${getFriendlyURL(url)}`); + } + return; + } + + if (process.env.NODE_ENV !== 'production') { + // We have a handler, meaning Workbox is going to handle the route. + // print the routing details to the console. + logger.groupCollapsed(`Router is responding to: ${getFriendlyURL(url)}`); + + debugMessages.forEach((msg) => { + if (Array.isArray(msg)) { + logger.log(...msg); + } else { + logger.log(msg); + } + }); + + logger.groupEnd(); + } + + // Wrap in try and catch in case the handle method throws a synchronous + // error. It should still callback to the catch handler. + let responsePromise; + try { + responsePromise = handler.handle({url, request, event, params}); + } catch (err) { + responsePromise = Promise.reject(err); + } + + // Get route's catch handler, if it exists + const catchHandler = route && route.catchHandler; + + if ( + responsePromise instanceof Promise && + (this._catchHandler || catchHandler) + ) { + responsePromise = responsePromise.catch(async (err) => { + // If there's a route catch handler, process that first + if (catchHandler) { + if (process.env.NODE_ENV !== 'production') { + // Still include URL here as it will be async from the console group + // and may not make sense without the URL + logger.groupCollapsed( + `Error thrown when responding to: ` + + ` ${getFriendlyURL( + url, + )}. Falling back to route's Catch Handler.`, + ); + logger.error(`Error thrown by:`, route); + logger.error(err); + logger.groupEnd(); + } + + try { + return await catchHandler.handle({url, request, event, params}); + } catch (catchErr) { + if (catchErr instanceof Error) { + err = catchErr; + } + } + } + + if (this._catchHandler) { + if (process.env.NODE_ENV !== 'production') { + // Still include URL here as it will be async from the console group + // and may not make sense without the URL + logger.groupCollapsed( + `Error thrown when responding to: ` + + ` ${getFriendlyURL( + url, + )}. Falling back to global Catch Handler.`, + ); + logger.error(`Error thrown by:`, route); + logger.error(err); + logger.groupEnd(); + } + return this._catchHandler.handle({url, request, event}); + } + + throw err; + }); + } + + return responsePromise; + } + + /** + * Checks a request and URL (and optionally an event) against the list of + * registered routes, and if there's a match, returns the corresponding + * route along with any params generated by the match. + * + * @param {Object} options + * @param {URL} options.url + * @param {boolean} options.sameOrigin The result of comparing `url.origin` + * against the current origin. + * @param {Request} options.request The request to match. + * @param {Event} options.event The corresponding event. + * @return {Object} An object with `route` and `params` properties. + * They are populated if a matching route was found or `undefined` + * otherwise. + */ + findMatchingRoute({ + url, + sameOrigin, + request, + event, + }: RouteMatchCallbackOptions): { + route?: Route; + params?: RouteHandlerCallbackOptions['params']; + } { + const routes = this._routes.get(request.method as HTTPMethod) || []; + for (const route of routes) { + let params: Promise | undefined; + // route.match returns type any, not possible to change right now. + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const matchResult = route.match({url, sameOrigin, request, event}); + if (matchResult) { + if (process.env.NODE_ENV !== 'production') { + // Warn developers that using an async matchCallback is almost always + // not the right thing to do. + if (matchResult instanceof Promise) { + logger.warn( + `While routing ${getFriendlyURL(url)}, an async ` + + `matchCallback function was used. Please convert the ` + + `following route to use a synchronous matchCallback function:`, + route, + ); + } + } + + // See https://github.com/GoogleChrome/workbox/issues/2079 + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + params = matchResult; + if (Array.isArray(params) && params.length === 0) { + // Instead of passing an empty array in as params, use undefined. + params = undefined; + } else if ( + matchResult.constructor === Object && // eslint-disable-line + Object.keys(matchResult).length === 0 + ) { + // Instead of passing an empty object in as params, use undefined. + params = undefined; + } else if (typeof matchResult === 'boolean') { + // For the boolean value true (rather than just something truth-y), + // don't set params. + // See https://github.com/GoogleChrome/workbox/pull/2134#issuecomment-513924353 + params = undefined; + } + + // Return early if have a match. + return {route, params}; + } + } + // If no match was found above, return and empty object. + return {}; + } + + /** + * Define a default `handler` that's called when no routes explicitly + * match the incoming request. + * + * Each HTTP method ('GET', 'POST', etc.) gets its own default handler. + * + * Without a default handler, unmatched requests will go against the + * network as if there were no service worker present. + * + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + * @param {string} [method='GET'] The HTTP method to associate with this + * default handler. Each method has its own default. + */ + setDefaultHandler( + handler: RouteHandler, + method: HTTPMethod = defaultMethod, + ): void { + this._defaultHandlerMap.set(method, normalizeHandler(handler)); + } + + /** + * If a Route throws an error while handling a request, this `handler` + * will be called and given a chance to provide a response. + * + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + */ + setCatchHandler(handler: RouteHandler): void { + this._catchHandler = normalizeHandler(handler); + } + + /** + * Registers a route with the router. + * + * @param {workbox-routing.Route} route The route to register. + */ + registerRoute(route: Route): void { + if (process.env.NODE_ENV !== 'production') { + assert!.isType(route, 'object', { + moduleName: 'workbox-routing', + className: 'Router', + funcName: 'registerRoute', + paramName: 'route', + }); + + assert!.hasMethod(route, 'match', { + moduleName: 'workbox-routing', + className: 'Router', + funcName: 'registerRoute', + paramName: 'route', + }); + + assert!.isType(route.handler, 'object', { + moduleName: 'workbox-routing', + className: 'Router', + funcName: 'registerRoute', + paramName: 'route', + }); + + assert!.hasMethod(route.handler, 'handle', { + moduleName: 'workbox-routing', + className: 'Router', + funcName: 'registerRoute', + paramName: 'route.handler', + }); + + assert!.isType(route.method, 'string', { + moduleName: 'workbox-routing', + className: 'Router', + funcName: 'registerRoute', + paramName: 'route.method', + }); + } + + if (!this._routes.has(route.method)) { + this._routes.set(route.method, []); + } + + // Give precedence to all of the earlier routes by adding this additional + // route to the end of the array. + this._routes.get(route.method)!.push(route); + } + + /** + * Unregisters a route with the router. + * + * @param {workbox-routing.Route} route The route to unregister. + */ + unregisterRoute(route: Route): void { + if (!this._routes.has(route.method)) { + throw new WorkboxError('unregister-route-but-not-found-with-method', { + method: route.method, + }); + } + + const routeIndex = this._routes.get(route.method)!.indexOf(route); + if (routeIndex > -1) { + this._routes.get(route.method)!.splice(routeIndex, 1); + } else { + throw new WorkboxError('unregister-route-route-not-registered'); + } + } +} + +export {Router}; diff --git a/node_modules/workbox-routing/src/_types.ts b/node_modules/workbox-routing/src/_types.ts new file mode 100644 index 0000000000000000000000000000000000000000..d798e93b5d4dff570ec8d51f4edb9fb0a6a22066 --- /dev/null +++ b/node_modules/workbox-routing/src/_types.ts @@ -0,0 +1,66 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import './_version.js'; + +// * * * IMPORTANT! * * * +// ------------------------------------------------------------------------- // +// jdsoc type definitions cannot be declared above TypeScript definitions or +// they'll be stripped from the built `.js` files, and they'll only be in the +// `d.ts` files, which aren't read by the jsdoc generator. As a result we +// have to put declare them below. + +/** + * The "match" callback is used to determine if a `Route` should apply for a + * particular URL. When matching occurs in response to a fetch event from the + * client, the `event` object is supplied in addition to the `url`, `request`, + * and `sameOrigin` value. However, since the match callback can be invoked + * outside of a fetch event, matching logic should not assume the `event` + * object will always be available. + * + * If the match callback returns a truthy value, the matching route's + * {@link workbox-routing~handlerCallback} will be + * invoked immediately. If the value returned is a non-empty array or object, + * that value will be set on the handler's `context.params` argument. + * + * @callback ~matchCallback + * @param {Object} context + * @param {Request} context.request The corresponding request. + * @param {URL} context.url The request's URL. + * @param {ExtendableEvent} context.event The corresponding event that triggered + * the request. + * @param {boolean} context.sameOrigin The result of comparing `url.origin` + * against the current origin. + * @return {*} To signify a match, return a truthy value. + * + * @memberof workbox-routing + */ + +/** + * The "handler" callback is invoked whenever a `Router` matches a URL to a + * `Route` via its {@link workbox-routing~matchCallback} + * callback. This callback should return a Promise that resolves with a + * `Response`. + * + * If a non-empty array or object is returned by the + * {@link workbox-routing~matchCallback} it + * will be passed in as the handler's `context.params` argument. + * + * @callback ~handlerCallback + * @param {Object} context + * @param {Request|string} context.request The corresponding request. + * @param {URL} context.url The URL that matched, if available. + * @param {ExtendableEvent} context.event The corresponding event that triggered + * the request. + * @param {Object} [context.params] Array or Object parameters returned by the + * Route's {@link workbox-routing~matchCallback}. + * This will be undefined if an empty array or object were returned. + * @return {Promise} The response that will fulfill the request. + * + * @memberof workbox-routing + */ diff --git a/node_modules/workbox-routing/src/_version.ts b/node_modules/workbox-routing/src/_version.ts new file mode 100644 index 0000000000000000000000000000000000000000..3f011a04a9d2bea072b85c5c6472bb9c00d828eb --- /dev/null +++ b/node_modules/workbox-routing/src/_version.ts @@ -0,0 +1,2 @@ +// @ts-ignore +try{self['workbox:routing:7.4.1']&&_()}catch(e){} \ No newline at end of file diff --git a/node_modules/workbox-routing/src/index.ts b/node_modules/workbox-routing/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..e38e29c5fdb7d7831253b6b7211905c3258da508 --- /dev/null +++ b/node_modules/workbox-routing/src/index.ts @@ -0,0 +1,35 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import { + NavigationRoute, + NavigationRouteMatchOptions, +} from './NavigationRoute.js'; +import {RegExpRoute} from './RegExpRoute.js'; +import {registerRoute} from './registerRoute.js'; +import {Route} from './Route.js'; +import {Router} from './Router.js'; +import {setCatchHandler} from './setCatchHandler.js'; +import {setDefaultHandler} from './setDefaultHandler.js'; + +import './_version.js'; + +/** + * @module workbox-routing + */ + +export { + NavigationRoute, + RegExpRoute, + registerRoute, + Route, + Router, + setCatchHandler, + setDefaultHandler, + NavigationRouteMatchOptions, +}; diff --git a/node_modules/workbox-routing/src/registerRoute.ts b/node_modules/workbox-routing/src/registerRoute.ts new file mode 100644 index 0000000000000000000000000000000000000000..54e59844f6250915fa1aa042794d0cc041274029 --- /dev/null +++ b/node_modules/workbox-routing/src/registerRoute.ts @@ -0,0 +1,115 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {logger} from 'workbox-core/_private/logger.js'; +import {WorkboxError} from 'workbox-core/_private/WorkboxError.js'; +import {RouteHandler, RouteMatchCallback} from 'workbox-core/types.js'; + +import {Route} from './Route.js'; +import {RegExpRoute} from './RegExpRoute.js'; +import {HTTPMethod} from './utils/constants.js'; +import {getOrCreateDefaultRouter} from './utils/getOrCreateDefaultRouter.js'; + +import './_version.js'; + +/** + * Easily register a RegExp, string, or function with a caching + * strategy to a singleton Router instance. + * + * This method will generate a Route for you if needed and + * call {@link workbox-routing.Router#registerRoute}. + * + * @param {RegExp|string|workbox-routing.Route~matchCallback|workbox-routing.Route} capture + * If the capture param is a `Route`, all other arguments will be ignored. + * @param {workbox-routing~handlerCallback} [handler] A callback + * function that returns a Promise resulting in a Response. This parameter + * is required if `capture` is not a `Route` object. + * @param {string} [method='GET'] The HTTP method to match the Route + * against. + * @return {workbox-routing.Route} The generated `Route`. + * + * @memberof workbox-routing + */ +function registerRoute( + capture: RegExp | string | RouteMatchCallback | Route, + handler?: RouteHandler, + method?: HTTPMethod, +): Route { + let route; + + if (typeof capture === 'string') { + const captureUrl = new URL(capture, location.href); + + if (process.env.NODE_ENV !== 'production') { + if (!(capture.startsWith('/') || capture.startsWith('http'))) { + throw new WorkboxError('invalid-string', { + moduleName: 'workbox-routing', + funcName: 'registerRoute', + paramName: 'capture', + }); + } + + // We want to check if Express-style wildcards are in the pathname only. + // TODO: Remove this log message in v4. + const valueToCheck = capture.startsWith('http') + ? captureUrl.pathname + : capture; + + // See https://github.com/pillarjs/path-to-regexp#parameters + const wildcards = '[*:?+]'; + if (new RegExp(`${wildcards}`).exec(valueToCheck)) { + logger.debug( + `The '$capture' parameter contains an Express-style wildcard ` + + `character (${wildcards}). Strings are now always interpreted as ` + + `exact matches; use a RegExp for partial or wildcard matches.`, + ); + } + } + + const matchCallback: RouteMatchCallback = ({url}) => { + if (process.env.NODE_ENV !== 'production') { + if ( + url.pathname === captureUrl.pathname && + url.origin !== captureUrl.origin + ) { + logger.debug( + `${capture} only partially matches the cross-origin URL ` + + `${url.toString()}. This route will only handle cross-origin requests ` + + `if they match the entire URL.`, + ); + } + } + + return url.href === captureUrl.href; + }; + + // If `capture` is a string then `handler` and `method` must be present. + route = new Route(matchCallback, handler!, method); + } else if (capture instanceof RegExp) { + // If `capture` is a `RegExp` then `handler` and `method` must be present. + route = new RegExpRoute(capture, handler!, method); + } else if (typeof capture === 'function') { + // If `capture` is a function then `handler` and `method` must be present. + route = new Route(capture, handler!, method); + } else if (capture instanceof Route) { + route = capture; + } else { + throw new WorkboxError('unsupported-route-type', { + moduleName: 'workbox-routing', + funcName: 'registerRoute', + paramName: 'capture', + }); + } + + const defaultRouter = getOrCreateDefaultRouter(); + defaultRouter.registerRoute(route); + + return route; +} + +export {registerRoute}; diff --git a/node_modules/workbox-routing/src/setCatchHandler.ts b/node_modules/workbox-routing/src/setCatchHandler.ts new file mode 100644 index 0000000000000000000000000000000000000000..375fe18c5ade382986119e9cdf6530b188b6532f --- /dev/null +++ b/node_modules/workbox-routing/src/setCatchHandler.ts @@ -0,0 +1,29 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {RouteHandler} from 'workbox-core/types.js'; + +import {getOrCreateDefaultRouter} from './utils/getOrCreateDefaultRouter.js'; + +import './_version.js'; + +/** + * If a Route throws an error while handling a request, this `handler` + * will be called and given a chance to provide a response. + * + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + * + * @memberof workbox-routing + */ +function setCatchHandler(handler: RouteHandler): void { + const defaultRouter = getOrCreateDefaultRouter(); + defaultRouter.setCatchHandler(handler); +} + +export {setCatchHandler}; diff --git a/node_modules/workbox-routing/src/setDefaultHandler.ts b/node_modules/workbox-routing/src/setDefaultHandler.ts new file mode 100644 index 0000000000000000000000000000000000000000..121941a2c9f85a4cd3905bbb7d7bc7a0199f64df --- /dev/null +++ b/node_modules/workbox-routing/src/setDefaultHandler.ts @@ -0,0 +1,32 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {RouteHandler} from 'workbox-core/types.js'; + +import {getOrCreateDefaultRouter} from './utils/getOrCreateDefaultRouter.js'; + +import './_version.js'; + +/** + * Define a default `handler` that's called when no routes explicitly + * match the incoming request. + * + * Without a default handler, unmatched requests will go against the + * network as if there were no service worker present. + * + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + * + * @memberof workbox-routing + */ +function setDefaultHandler(handler: RouteHandler): void { + const defaultRouter = getOrCreateDefaultRouter(); + defaultRouter.setDefaultHandler(handler); +} + +export {setDefaultHandler}; diff --git a/node_modules/workbox-routing/src/utils/constants.ts b/node_modules/workbox-routing/src/utils/constants.ts new file mode 100644 index 0000000000000000000000000000000000000000..32b54ca088c2780f50233b8632259a3e52d0056d --- /dev/null +++ b/node_modules/workbox-routing/src/utils/constants.ts @@ -0,0 +1,37 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import '../_version.js'; + +export type HTTPMethod = 'DELETE' | 'GET' | 'HEAD' | 'PATCH' | 'POST' | 'PUT'; + +/** + * The default HTTP method, 'GET', used when there's no specific method + * configured for a route. + * + * @type {string} + * + * @private + */ +export const defaultMethod: HTTPMethod = 'GET'; + +/** + * The list of valid HTTP methods associated with requests that could be routed. + * + * @type {Array} + * + * @private + */ +export const validMethods: HTTPMethod[] = [ + 'DELETE', + 'GET', + 'HEAD', + 'PATCH', + 'POST', + 'PUT', +]; diff --git a/node_modules/workbox-routing/src/utils/getOrCreateDefaultRouter.ts b/node_modules/workbox-routing/src/utils/getOrCreateDefaultRouter.ts new file mode 100644 index 0000000000000000000000000000000000000000..7d648b7686466a782892199d7aebfffaf4a93584 --- /dev/null +++ b/node_modules/workbox-routing/src/utils/getOrCreateDefaultRouter.ts @@ -0,0 +1,30 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {Router} from '../Router.js'; +import '../_version.js'; + +let defaultRouter: Router; + +/** + * Creates a new, singleton Router instance if one does not exist. If one + * does already exist, that instance is returned. + * + * @private + * @return {Router} + */ +export const getOrCreateDefaultRouter = (): Router => { + if (!defaultRouter) { + defaultRouter = new Router(); + + // The helpers that use the default Router assume these listeners exist. + defaultRouter.addFetchListener(); + defaultRouter.addCacheListener(); + } + return defaultRouter; +}; diff --git a/node_modules/workbox-routing/src/utils/normalizeHandler.ts b/node_modules/workbox-routing/src/utils/normalizeHandler.ts new file mode 100644 index 0000000000000000000000000000000000000000..e62f19f36fe48def99ea73b65920f6a4d07f0f74 --- /dev/null +++ b/node_modules/workbox-routing/src/utils/normalizeHandler.ts @@ -0,0 +1,43 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {assert} from 'workbox-core/_private/assert.js'; +import {RouteHandler, RouteHandlerObject} from 'workbox-core/types.js'; + +import '../_version.js'; + +/** + * @param {function()|Object} handler Either a function, or an object with a + * 'handle' method. + * @return {Object} An object with a handle method. + * + * @private + */ +export const normalizeHandler = (handler: RouteHandler): RouteHandlerObject => { + if (handler && typeof handler === 'object') { + if (process.env.NODE_ENV !== 'production') { + assert!.hasMethod(handler, 'handle', { + moduleName: 'workbox-routing', + className: 'Route', + funcName: 'constructor', + paramName: 'handler', + }); + } + return handler; + } else { + if (process.env.NODE_ENV !== 'production') { + assert!.isType(handler, 'function', { + moduleName: 'workbox-routing', + className: 'Route', + funcName: 'constructor', + paramName: 'handler', + }); + } + return {handle: handler}; + } +}; diff --git a/node_modules/workbox-routing/tsconfig.json b/node_modules/workbox-routing/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..3bb2772b586c4d0ceee3d014e64dba7aafbdd570 --- /dev/null +++ b/node_modules/workbox-routing/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tsconfig", + "compilerOptions": { + "composite": true, + "outDir": "./", + "rootDir": "./src", + "tsBuildInfoFile": "./tsconfig.tsbuildinfo" + }, + "include": ["src/**/*.ts"], + "references": [{"path": "../workbox-core/"}] +} diff --git a/node_modules/workbox-routing/utils/constants.d.ts b/node_modules/workbox-routing/utils/constants.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9d1068952a29c8527e860930c6e70e32a7f283a2 --- /dev/null +++ b/node_modules/workbox-routing/utils/constants.d.ts @@ -0,0 +1,19 @@ +import '../_version.js'; +export type HTTPMethod = 'DELETE' | 'GET' | 'HEAD' | 'PATCH' | 'POST' | 'PUT'; +/** + * The default HTTP method, 'GET', used when there's no specific method + * configured for a route. + * + * @type {string} + * + * @private + */ +export declare const defaultMethod: HTTPMethod; +/** + * The list of valid HTTP methods associated with requests that could be routed. + * + * @type {Array} + * + * @private + */ +export declare const validMethods: HTTPMethod[]; diff --git a/node_modules/workbox-routing/utils/constants.js b/node_modules/workbox-routing/utils/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..2404732690deee57c0d57a7af86635bca3d1611c --- /dev/null +++ b/node_modules/workbox-routing/utils/constants.js @@ -0,0 +1,32 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import '../_version.js'; +/** + * The default HTTP method, 'GET', used when there's no specific method + * configured for a route. + * + * @type {string} + * + * @private + */ +export const defaultMethod = 'GET'; +/** + * The list of valid HTTP methods associated with requests that could be routed. + * + * @type {Array} + * + * @private + */ +export const validMethods = [ + 'DELETE', + 'GET', + 'HEAD', + 'PATCH', + 'POST', + 'PUT', +]; diff --git a/node_modules/workbox-routing/utils/constants.mjs b/node_modules/workbox-routing/utils/constants.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f3f4c8f2658cad983ad14478588d456cb83091d0 --- /dev/null +++ b/node_modules/workbox-routing/utils/constants.mjs @@ -0,0 +1 @@ +export * from './constants.js'; \ No newline at end of file diff --git a/node_modules/workbox-routing/utils/getOrCreateDefaultRouter.d.ts b/node_modules/workbox-routing/utils/getOrCreateDefaultRouter.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..071082ee87b921f0cbe8a21a1bd99ab7fb65d5cb --- /dev/null +++ b/node_modules/workbox-routing/utils/getOrCreateDefaultRouter.d.ts @@ -0,0 +1,10 @@ +import { Router } from '../Router.js'; +import '../_version.js'; +/** + * Creates a new, singleton Router instance if one does not exist. If one + * does already exist, that instance is returned. + * + * @private + * @return {Router} + */ +export declare const getOrCreateDefaultRouter: () => Router; diff --git a/node_modules/workbox-routing/utils/getOrCreateDefaultRouter.js b/node_modules/workbox-routing/utils/getOrCreateDefaultRouter.js new file mode 100644 index 0000000000000000000000000000000000000000..09447168de5725553daf0d0a98b53276fd265e8d --- /dev/null +++ b/node_modules/workbox-routing/utils/getOrCreateDefaultRouter.js @@ -0,0 +1,26 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { Router } from '../Router.js'; +import '../_version.js'; +let defaultRouter; +/** + * Creates a new, singleton Router instance if one does not exist. If one + * does already exist, that instance is returned. + * + * @private + * @return {Router} + */ +export const getOrCreateDefaultRouter = () => { + if (!defaultRouter) { + defaultRouter = new Router(); + // The helpers that use the default Router assume these listeners exist. + defaultRouter.addFetchListener(); + defaultRouter.addCacheListener(); + } + return defaultRouter; +}; diff --git a/node_modules/workbox-routing/utils/getOrCreateDefaultRouter.mjs b/node_modules/workbox-routing/utils/getOrCreateDefaultRouter.mjs new file mode 100644 index 0000000000000000000000000000000000000000..09892ef9ffef2b297b6f29a912780f2479a9bf13 --- /dev/null +++ b/node_modules/workbox-routing/utils/getOrCreateDefaultRouter.mjs @@ -0,0 +1 @@ +export * from './getOrCreateDefaultRouter.js'; \ No newline at end of file diff --git a/node_modules/workbox-routing/utils/normalizeHandler.d.ts b/node_modules/workbox-routing/utils/normalizeHandler.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ae9bed5718b9e67df61794f52cb641f99aabc54a --- /dev/null +++ b/node_modules/workbox-routing/utils/normalizeHandler.d.ts @@ -0,0 +1,10 @@ +import { RouteHandler, RouteHandlerObject } from 'workbox-core/types.js'; +import '../_version.js'; +/** + * @param {function()|Object} handler Either a function, or an object with a + * 'handle' method. + * @return {Object} An object with a handle method. + * + * @private + */ +export declare const normalizeHandler: (handler: RouteHandler) => RouteHandlerObject; diff --git a/node_modules/workbox-routing/utils/normalizeHandler.js b/node_modules/workbox-routing/utils/normalizeHandler.js new file mode 100644 index 0000000000000000000000000000000000000000..bf4230439d3cf2cb6781c7f9885841d8651b2a64 --- /dev/null +++ b/node_modules/workbox-routing/utils/normalizeHandler.js @@ -0,0 +1,40 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { assert } from 'workbox-core/_private/assert.js'; +import '../_version.js'; +/** + * @param {function()|Object} handler Either a function, or an object with a + * 'handle' method. + * @return {Object} An object with a handle method. + * + * @private + */ +export const normalizeHandler = (handler) => { + if (handler && typeof handler === 'object') { + if (process.env.NODE_ENV !== 'production') { + assert.hasMethod(handler, 'handle', { + moduleName: 'workbox-routing', + className: 'Route', + funcName: 'constructor', + paramName: 'handler', + }); + } + return handler; + } + else { + if (process.env.NODE_ENV !== 'production') { + assert.isType(handler, 'function', { + moduleName: 'workbox-routing', + className: 'Route', + funcName: 'constructor', + paramName: 'handler', + }); + } + return { handle: handler }; + } +}; diff --git a/node_modules/workbox-routing/utils/normalizeHandler.mjs b/node_modules/workbox-routing/utils/normalizeHandler.mjs new file mode 100644 index 0000000000000000000000000000000000000000..061a9f2a73f65556a9c551d1723e0f78b8ce80b9 --- /dev/null +++ b/node_modules/workbox-routing/utils/normalizeHandler.mjs @@ -0,0 +1 @@ +export * from './normalizeHandler.js'; \ No newline at end of file diff --git a/node_modules/workbox-strategies/CacheFirst.d.ts b/node_modules/workbox-strategies/CacheFirst.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0e97629d4e82e23e89acf5785f07dc1888aa1432 --- /dev/null +++ b/node_modules/workbox-strategies/CacheFirst.d.ts @@ -0,0 +1,28 @@ +import { Strategy } from './Strategy.js'; +import { StrategyHandler } from './StrategyHandler.js'; +import './_version.js'; +/** + * An implementation of a [cache-first](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#cache-first-falling-back-to-network) + * request strategy. + * + * A cache first strategy is useful for assets that have been revisioned, + * such as URLs like `/styles/example.a8f5f1.css`, since they + * can be cached for long periods of time. + * + * If the network request fails, and there is no cache match, this will throw + * a `WorkboxError` exception. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-strategies + */ +declare class CacheFirst extends Strategy { + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + _handle(request: Request, handler: StrategyHandler): Promise; +} +export { CacheFirst }; diff --git a/node_modules/workbox-strategies/CacheFirst.js b/node_modules/workbox-strategies/CacheFirst.js new file mode 100644 index 0000000000000000000000000000000000000000..085628f54f4b1d13508e41c4d1fac9706122eaa7 --- /dev/null +++ b/node_modules/workbox-strategies/CacheFirst.js @@ -0,0 +1,89 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { assert } from 'workbox-core/_private/assert.js'; +import { logger } from 'workbox-core/_private/logger.js'; +import { WorkboxError } from 'workbox-core/_private/WorkboxError.js'; +import { Strategy } from './Strategy.js'; +import { messages } from './utils/messages.js'; +import './_version.js'; +/** + * An implementation of a [cache-first](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#cache-first-falling-back-to-network) + * request strategy. + * + * A cache first strategy is useful for assets that have been revisioned, + * such as URLs like `/styles/example.a8f5f1.css`, since they + * can be cached for long periods of time. + * + * If the network request fails, and there is no cache match, this will throw + * a `WorkboxError` exception. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-strategies + */ +class CacheFirst extends Strategy { + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + async _handle(request, handler) { + const logs = []; + if (process.env.NODE_ENV !== 'production') { + assert.isInstance(request, Request, { + moduleName: 'workbox-strategies', + className: this.constructor.name, + funcName: 'makeRequest', + paramName: 'request', + }); + } + let response = await handler.cacheMatch(request); + let error = undefined; + if (!response) { + if (process.env.NODE_ENV !== 'production') { + logs.push(`No response found in the '${this.cacheName}' cache. ` + + `Will respond with a network request.`); + } + try { + response = await handler.fetchAndCachePut(request); + } + catch (err) { + if (err instanceof Error) { + error = err; + } + } + if (process.env.NODE_ENV !== 'production') { + if (response) { + logs.push(`Got response from network.`); + } + else { + logs.push(`Unable to get a response from the network.`); + } + } + } + else { + if (process.env.NODE_ENV !== 'production') { + logs.push(`Found a cached response in the '${this.cacheName}' cache.`); + } + } + if (process.env.NODE_ENV !== 'production') { + logger.groupCollapsed(messages.strategyStart(this.constructor.name, request)); + for (const log of logs) { + logger.log(log); + } + messages.printFinalResponse(response); + logger.groupEnd(); + } + if (!response) { + throw new WorkboxError('no-response', { url: request.url, error }); + } + return response; + } +} +export { CacheFirst }; diff --git a/node_modules/workbox-strategies/CacheFirst.mjs b/node_modules/workbox-strategies/CacheFirst.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8387fc12f58c8a10eef1389739e5817101a191d8 --- /dev/null +++ b/node_modules/workbox-strategies/CacheFirst.mjs @@ -0,0 +1 @@ +export * from './CacheFirst.js'; \ No newline at end of file diff --git a/node_modules/workbox-strategies/CacheOnly.d.ts b/node_modules/workbox-strategies/CacheOnly.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..22bfd59d0c37987916362c85a469efc3defd8a77 --- /dev/null +++ b/node_modules/workbox-strategies/CacheOnly.d.ts @@ -0,0 +1,26 @@ +import { Strategy } from './Strategy.js'; +import { StrategyHandler } from './StrategyHandler.js'; +import './_version.js'; +/** + * An implementation of a [cache-only](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#cache-only) + * request strategy. + * + * This class is useful if you want to take advantage of any + * [Workbox plugins](https://developer.chrome.com/docs/workbox/using-plugins/). + * + * If there is no cache match, this will throw a `WorkboxError` exception. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-strategies + */ +declare class CacheOnly extends Strategy { + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + _handle(request: Request, handler: StrategyHandler): Promise; +} +export { CacheOnly }; diff --git a/node_modules/workbox-strategies/CacheOnly.js b/node_modules/workbox-strategies/CacheOnly.js new file mode 100644 index 0000000000000000000000000000000000000000..2d9d55701f470ca002dca11fcc04d12ef6ca8b99 --- /dev/null +++ b/node_modules/workbox-strategies/CacheOnly.js @@ -0,0 +1,61 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { assert } from 'workbox-core/_private/assert.js'; +import { logger } from 'workbox-core/_private/logger.js'; +import { WorkboxError } from 'workbox-core/_private/WorkboxError.js'; +import { Strategy } from './Strategy.js'; +import { messages } from './utils/messages.js'; +import './_version.js'; +/** + * An implementation of a [cache-only](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#cache-only) + * request strategy. + * + * This class is useful if you want to take advantage of any + * [Workbox plugins](https://developer.chrome.com/docs/workbox/using-plugins/). + * + * If there is no cache match, this will throw a `WorkboxError` exception. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-strategies + */ +class CacheOnly extends Strategy { + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + async _handle(request, handler) { + if (process.env.NODE_ENV !== 'production') { + assert.isInstance(request, Request, { + moduleName: 'workbox-strategies', + className: this.constructor.name, + funcName: 'makeRequest', + paramName: 'request', + }); + } + const response = await handler.cacheMatch(request); + if (process.env.NODE_ENV !== 'production') { + logger.groupCollapsed(messages.strategyStart(this.constructor.name, request)); + if (response) { + logger.log(`Found a cached response in the '${this.cacheName}' ` + `cache.`); + messages.printFinalResponse(response); + } + else { + logger.log(`No response found in the '${this.cacheName}' cache.`); + } + logger.groupEnd(); + } + if (!response) { + throw new WorkboxError('no-response', { url: request.url }); + } + return response; + } +} +export { CacheOnly }; diff --git a/node_modules/workbox-strategies/CacheOnly.mjs b/node_modules/workbox-strategies/CacheOnly.mjs new file mode 100644 index 0000000000000000000000000000000000000000..412ac7e20a7dda061107689477b5eda37981521b --- /dev/null +++ b/node_modules/workbox-strategies/CacheOnly.mjs @@ -0,0 +1 @@ +export * from './CacheOnly.js'; \ No newline at end of file diff --git a/node_modules/workbox-strategies/LICENSE b/node_modules/workbox-strategies/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..845b545fd0f5031a944cda8cf9018eb066500040 --- /dev/null +++ b/node_modules/workbox-strategies/LICENSE @@ -0,0 +1,19 @@ +Copyright 2018 Google LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/workbox-strategies/NetworkFirst.d.ts b/node_modules/workbox-strategies/NetworkFirst.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3e8097131f498dc15f392dc96b8b5b9d84a49a33 --- /dev/null +++ b/node_modules/workbox-strategies/NetworkFirst.d.ts @@ -0,0 +1,80 @@ +import { Strategy, StrategyOptions } from './Strategy.js'; +import { StrategyHandler } from './StrategyHandler.js'; +import './_version.js'; +export interface NetworkFirstOptions extends StrategyOptions { + networkTimeoutSeconds?: number; +} +/** + * An implementation of a + * [network first](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#network-first-falling-back-to-cache) + * request strategy. + * + * By default, this strategy will cache responses with a 200 status code as + * well as [opaque responses](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses). + * Opaque responses are are cross-origin requests where the response doesn't + * support [CORS](https://enable-cors.org/). + * + * If the network request fails, and there is no cache match, this will throw + * a `WorkboxError` exception. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-strategies + */ +declare class NetworkFirst extends Strategy { + private readonly _networkTimeoutSeconds; + /** + * @param {Object} [options] + * @param {string} [options.cacheName] Cache name to store and retrieve + * requests. Defaults to cache names provided by + * {@link workbox-core.cacheNames}. + * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins} + * to use in conjunction with this caching strategy. + * @param {Object} [options.fetchOptions] Values passed along to the + * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) + * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796) + * `fetch()` requests made by this strategy. + * @param {Object} [options.matchOptions] [`CacheQueryOptions`](https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions) + * @param {number} [options.networkTimeoutSeconds] If set, any network requests + * that fail to respond within the timeout will fallback to the cache. + * + * This option can be used to combat + * "[lie-fi]{@link https://developers.google.com/web/fundamentals/performance/poor-connectivity/#lie-fi}" + * scenarios. + */ + constructor(options?: NetworkFirstOptions); + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + _handle(request: Request, handler: StrategyHandler): Promise; + /** + * @param {Object} options + * @param {Request} options.request + * @param {Array} options.logs A reference to the logs array + * @param {Event} options.event + * @return {Promise} + * + * @private + */ + private _getTimeoutPromise; + /** + * @param {Object} options + * @param {number|undefined} options.timeoutId + * @param {Request} options.request + * @param {Array} options.logs A reference to the logs Array. + * @param {Event} options.event + * @return {Promise} + * + * @private + */ + _getNetworkPromise({ timeoutId, request, logs, handler, }: { + request: Request; + logs: any[]; + timeoutId?: number; + handler: StrategyHandler; + }): Promise; +} +export { NetworkFirst }; diff --git a/node_modules/workbox-strategies/NetworkFirst.js b/node_modules/workbox-strategies/NetworkFirst.js new file mode 100644 index 0000000000000000000000000000000000000000..1471537ee9371aadba3ae4cad585fb890729e3f7 --- /dev/null +++ b/node_modules/workbox-strategies/NetworkFirst.js @@ -0,0 +1,197 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { assert } from 'workbox-core/_private/assert.js'; +import { logger } from 'workbox-core/_private/logger.js'; +import { WorkboxError } from 'workbox-core/_private/WorkboxError.js'; +import { cacheOkAndOpaquePlugin } from './plugins/cacheOkAndOpaquePlugin.js'; +import { Strategy } from './Strategy.js'; +import { messages } from './utils/messages.js'; +import './_version.js'; +/** + * An implementation of a + * [network first](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#network-first-falling-back-to-cache) + * request strategy. + * + * By default, this strategy will cache responses with a 200 status code as + * well as [opaque responses](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses). + * Opaque responses are are cross-origin requests where the response doesn't + * support [CORS](https://enable-cors.org/). + * + * If the network request fails, and there is no cache match, this will throw + * a `WorkboxError` exception. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-strategies + */ +class NetworkFirst extends Strategy { + /** + * @param {Object} [options] + * @param {string} [options.cacheName] Cache name to store and retrieve + * requests. Defaults to cache names provided by + * {@link workbox-core.cacheNames}. + * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins} + * to use in conjunction with this caching strategy. + * @param {Object} [options.fetchOptions] Values passed along to the + * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) + * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796) + * `fetch()` requests made by this strategy. + * @param {Object} [options.matchOptions] [`CacheQueryOptions`](https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions) + * @param {number} [options.networkTimeoutSeconds] If set, any network requests + * that fail to respond within the timeout will fallback to the cache. + * + * This option can be used to combat + * "[lie-fi]{@link https://developers.google.com/web/fundamentals/performance/poor-connectivity/#lie-fi}" + * scenarios. + */ + constructor(options = {}) { + super(options); + // If this instance contains no plugins with a 'cacheWillUpdate' callback, + // prepend the `cacheOkAndOpaquePlugin` plugin to the plugins list. + if (!this.plugins.some((p) => 'cacheWillUpdate' in p)) { + this.plugins.unshift(cacheOkAndOpaquePlugin); + } + this._networkTimeoutSeconds = options.networkTimeoutSeconds || 0; + if (process.env.NODE_ENV !== 'production') { + if (this._networkTimeoutSeconds) { + assert.isType(this._networkTimeoutSeconds, 'number', { + moduleName: 'workbox-strategies', + className: this.constructor.name, + funcName: 'constructor', + paramName: 'networkTimeoutSeconds', + }); + } + } + } + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + async _handle(request, handler) { + const logs = []; + if (process.env.NODE_ENV !== 'production') { + assert.isInstance(request, Request, { + moduleName: 'workbox-strategies', + className: this.constructor.name, + funcName: 'handle', + paramName: 'makeRequest', + }); + } + const promises = []; + let timeoutId; + if (this._networkTimeoutSeconds) { + const { id, promise } = this._getTimeoutPromise({ request, logs, handler }); + timeoutId = id; + promises.push(promise); + } + const networkPromise = this._getNetworkPromise({ + timeoutId, + request, + logs, + handler, + }); + promises.push(networkPromise); + const response = await handler.waitUntil((async () => { + // Promise.race() will resolve as soon as the first promise resolves. + return ((await handler.waitUntil(Promise.race(promises))) || + // If Promise.race() resolved with null, it might be due to a network + // timeout + a cache miss. If that were to happen, we'd rather wait until + // the networkPromise resolves instead of returning null. + // Note that it's fine to await an already-resolved promise, so we don't + // have to check to see if it's still "in flight". + (await networkPromise)); + })()); + if (process.env.NODE_ENV !== 'production') { + logger.groupCollapsed(messages.strategyStart(this.constructor.name, request)); + for (const log of logs) { + logger.log(log); + } + messages.printFinalResponse(response); + logger.groupEnd(); + } + if (!response) { + throw new WorkboxError('no-response', { url: request.url }); + } + return response; + } + /** + * @param {Object} options + * @param {Request} options.request + * @param {Array} options.logs A reference to the logs array + * @param {Event} options.event + * @return {Promise} + * + * @private + */ + _getTimeoutPromise({ request, logs, handler, }) { + let timeoutId; + const timeoutPromise = new Promise((resolve) => { + const onNetworkTimeout = async () => { + if (process.env.NODE_ENV !== 'production') { + logs.push(`Timing out the network response at ` + + `${this._networkTimeoutSeconds} seconds.`); + } + resolve(await handler.cacheMatch(request)); + }; + timeoutId = setTimeout(onNetworkTimeout, this._networkTimeoutSeconds * 1000); + }); + return { + promise: timeoutPromise, + id: timeoutId, + }; + } + /** + * @param {Object} options + * @param {number|undefined} options.timeoutId + * @param {Request} options.request + * @param {Array} options.logs A reference to the logs Array. + * @param {Event} options.event + * @return {Promise} + * + * @private + */ + async _getNetworkPromise({ timeoutId, request, logs, handler, }) { + let error; + let response; + try { + response = await handler.fetchAndCachePut(request); + } + catch (fetchError) { + if (fetchError instanceof Error) { + error = fetchError; + } + } + if (timeoutId) { + clearTimeout(timeoutId); + } + if (process.env.NODE_ENV !== 'production') { + if (response) { + logs.push(`Got response from network.`); + } + else { + logs.push(`Unable to get a response from the network. Will respond ` + + `with a cached response.`); + } + } + if (error || !response) { + response = await handler.cacheMatch(request); + if (process.env.NODE_ENV !== 'production') { + if (response) { + logs.push(`Found a cached response in the '${this.cacheName}'` + ` cache.`); + } + else { + logs.push(`No response found in the '${this.cacheName}' cache.`); + } + } + } + return response; + } +} +export { NetworkFirst }; diff --git a/node_modules/workbox-strategies/NetworkFirst.mjs b/node_modules/workbox-strategies/NetworkFirst.mjs new file mode 100644 index 0000000000000000000000000000000000000000..28fcdb64af9d0e6bd14f00cef2f5a9523aa38253 --- /dev/null +++ b/node_modules/workbox-strategies/NetworkFirst.mjs @@ -0,0 +1 @@ +export * from './NetworkFirst.js'; \ No newline at end of file diff --git a/node_modules/workbox-strategies/NetworkOnly.d.ts b/node_modules/workbox-strategies/NetworkOnly.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..454b6e1edc8592604eaa102fc23703f958455298 --- /dev/null +++ b/node_modules/workbox-strategies/NetworkOnly.d.ts @@ -0,0 +1,43 @@ +import { Strategy, StrategyOptions } from './Strategy.js'; +import { StrategyHandler } from './StrategyHandler.js'; +import './_version.js'; +interface NetworkOnlyOptions extends Omit { + networkTimeoutSeconds?: number; +} +/** + * An implementation of a + * [network-only](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#network-only) + * request strategy. + * + * This class is useful if you want to take advantage of any + * [Workbox plugins](https://developer.chrome.com/docs/workbox/using-plugins/). + * + * If the network request fails, this will throw a `WorkboxError` exception. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-strategies + */ +declare class NetworkOnly extends Strategy { + private readonly _networkTimeoutSeconds; + /** + * @param {Object} [options] + * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins} + * to use in conjunction with this caching strategy. + * @param {Object} [options.fetchOptions] Values passed along to the + * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) + * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796) + * `fetch()` requests made by this strategy. + * @param {number} [options.networkTimeoutSeconds] If set, any network requests + * that fail to respond within the timeout will result in a network error. + */ + constructor(options?: NetworkOnlyOptions); + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + _handle(request: Request, handler: StrategyHandler): Promise; +} +export { NetworkOnly, NetworkOnlyOptions }; diff --git a/node_modules/workbox-strategies/NetworkOnly.js b/node_modules/workbox-strategies/NetworkOnly.js new file mode 100644 index 0000000000000000000000000000000000000000..991acdfa73ca022cf729ac46e2843760337a9c62 --- /dev/null +++ b/node_modules/workbox-strategies/NetworkOnly.js @@ -0,0 +1,98 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { assert } from 'workbox-core/_private/assert.js'; +import { logger } from 'workbox-core/_private/logger.js'; +import { timeout } from 'workbox-core/_private/timeout.js'; +import { WorkboxError } from 'workbox-core/_private/WorkboxError.js'; +import { Strategy } from './Strategy.js'; +import { messages } from './utils/messages.js'; +import './_version.js'; +/** + * An implementation of a + * [network-only](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#network-only) + * request strategy. + * + * This class is useful if you want to take advantage of any + * [Workbox plugins](https://developer.chrome.com/docs/workbox/using-plugins/). + * + * If the network request fails, this will throw a `WorkboxError` exception. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-strategies + */ +class NetworkOnly extends Strategy { + /** + * @param {Object} [options] + * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins} + * to use in conjunction with this caching strategy. + * @param {Object} [options.fetchOptions] Values passed along to the + * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) + * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796) + * `fetch()` requests made by this strategy. + * @param {number} [options.networkTimeoutSeconds] If set, any network requests + * that fail to respond within the timeout will result in a network error. + */ + constructor(options = {}) { + super(options); + this._networkTimeoutSeconds = options.networkTimeoutSeconds || 0; + } + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + async _handle(request, handler) { + if (process.env.NODE_ENV !== 'production') { + assert.isInstance(request, Request, { + moduleName: 'workbox-strategies', + className: this.constructor.name, + funcName: '_handle', + paramName: 'request', + }); + } + let error = undefined; + let response; + try { + const promises = [ + handler.fetch(request), + ]; + if (this._networkTimeoutSeconds) { + const timeoutPromise = timeout(this._networkTimeoutSeconds * 1000); + promises.push(timeoutPromise); + } + response = await Promise.race(promises); + if (!response) { + throw new Error(`Timed out the network response after ` + + `${this._networkTimeoutSeconds} seconds.`); + } + } + catch (err) { + if (err instanceof Error) { + error = err; + } + } + if (process.env.NODE_ENV !== 'production') { + logger.groupCollapsed(messages.strategyStart(this.constructor.name, request)); + if (response) { + logger.log(`Got response from network.`); + } + else { + logger.log(`Unable to get a response from the network.`); + } + messages.printFinalResponse(response); + logger.groupEnd(); + } + if (!response) { + throw new WorkboxError('no-response', { url: request.url, error }); + } + return response; + } +} +export { NetworkOnly }; diff --git a/node_modules/workbox-strategies/NetworkOnly.mjs b/node_modules/workbox-strategies/NetworkOnly.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ce7a2525bd0f56180218b66ad601e844bc3646a7 --- /dev/null +++ b/node_modules/workbox-strategies/NetworkOnly.mjs @@ -0,0 +1 @@ +export * from './NetworkOnly.js'; \ No newline at end of file diff --git a/node_modules/workbox-strategies/README.md b/node_modules/workbox-strategies/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d1a5ec5b4a80bb1036d3501a096aeec082aff768 --- /dev/null +++ b/node_modules/workbox-strategies/README.md @@ -0,0 +1 @@ +This module's documentation can be found at https://developers.google.com/web/tools/workbox/modules/workbox-strategies diff --git a/node_modules/workbox-strategies/StaleWhileRevalidate.d.ts b/node_modules/workbox-strategies/StaleWhileRevalidate.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..858e1a66fcb0af2949dc27805161becc6a7ab43b --- /dev/null +++ b/node_modules/workbox-strategies/StaleWhileRevalidate.d.ts @@ -0,0 +1,49 @@ +import { Strategy, StrategyOptions } from './Strategy.js'; +import { StrategyHandler } from './StrategyHandler.js'; +import './_version.js'; +/** + * An implementation of a + * [stale-while-revalidate](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#stale-while-revalidate) + * request strategy. + * + * Resources are requested from both the cache and the network in parallel. + * The strategy will respond with the cached version if available, otherwise + * wait for the network response. The cache is updated with the network response + * with each successful request. + * + * By default, this strategy will cache responses with a 200 status code as + * well as [opaque responses](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses). + * Opaque responses are cross-origin requests where the response doesn't + * support [CORS](https://enable-cors.org/). + * + * If the network request fails, and there is no cache match, this will throw + * a `WorkboxError` exception. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-strategies + */ +declare class StaleWhileRevalidate extends Strategy { + /** + * @param {Object} [options] + * @param {string} [options.cacheName] Cache name to store and retrieve + * requests. Defaults to cache names provided by + * {@link workbox-core.cacheNames}. + * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins} + * to use in conjunction with this caching strategy. + * @param {Object} [options.fetchOptions] Values passed along to the + * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) + * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796) + * `fetch()` requests made by this strategy. + * @param {Object} [options.matchOptions] [`CacheQueryOptions`](https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions) + */ + constructor(options?: StrategyOptions); + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + _handle(request: Request, handler: StrategyHandler): Promise; +} +export { StaleWhileRevalidate }; diff --git a/node_modules/workbox-strategies/StaleWhileRevalidate.js b/node_modules/workbox-strategies/StaleWhileRevalidate.js new file mode 100644 index 0000000000000000000000000000000000000000..e93e3c3ae19be6206fd995366212b51b88ab3b3a --- /dev/null +++ b/node_modules/workbox-strategies/StaleWhileRevalidate.js @@ -0,0 +1,118 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { assert } from 'workbox-core/_private/assert.js'; +import { logger } from 'workbox-core/_private/logger.js'; +import { WorkboxError } from 'workbox-core/_private/WorkboxError.js'; +import { cacheOkAndOpaquePlugin } from './plugins/cacheOkAndOpaquePlugin.js'; +import { Strategy } from './Strategy.js'; +import { messages } from './utils/messages.js'; +import './_version.js'; +/** + * An implementation of a + * [stale-while-revalidate](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#stale-while-revalidate) + * request strategy. + * + * Resources are requested from both the cache and the network in parallel. + * The strategy will respond with the cached version if available, otherwise + * wait for the network response. The cache is updated with the network response + * with each successful request. + * + * By default, this strategy will cache responses with a 200 status code as + * well as [opaque responses](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses). + * Opaque responses are cross-origin requests where the response doesn't + * support [CORS](https://enable-cors.org/). + * + * If the network request fails, and there is no cache match, this will throw + * a `WorkboxError` exception. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-strategies + */ +class StaleWhileRevalidate extends Strategy { + /** + * @param {Object} [options] + * @param {string} [options.cacheName] Cache name to store and retrieve + * requests. Defaults to cache names provided by + * {@link workbox-core.cacheNames}. + * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins} + * to use in conjunction with this caching strategy. + * @param {Object} [options.fetchOptions] Values passed along to the + * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) + * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796) + * `fetch()` requests made by this strategy. + * @param {Object} [options.matchOptions] [`CacheQueryOptions`](https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions) + */ + constructor(options = {}) { + super(options); + // If this instance contains no plugins with a 'cacheWillUpdate' callback, + // prepend the `cacheOkAndOpaquePlugin` plugin to the plugins list. + if (!this.plugins.some((p) => 'cacheWillUpdate' in p)) { + this.plugins.unshift(cacheOkAndOpaquePlugin); + } + } + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + async _handle(request, handler) { + const logs = []; + if (process.env.NODE_ENV !== 'production') { + assert.isInstance(request, Request, { + moduleName: 'workbox-strategies', + className: this.constructor.name, + funcName: 'handle', + paramName: 'request', + }); + } + const fetchAndCachePromise = handler.fetchAndCachePut(request).catch(() => { + // Swallow this error because a 'no-response' error will be thrown in + // main handler return flow. This will be in the `waitUntil()` flow. + }); + void handler.waitUntil(fetchAndCachePromise); + let response = await handler.cacheMatch(request); + let error; + if (response) { + if (process.env.NODE_ENV !== 'production') { + logs.push(`Found a cached response in the '${this.cacheName}'` + + ` cache. Will update with the network response in the background.`); + } + } + else { + if (process.env.NODE_ENV !== 'production') { + logs.push(`No response found in the '${this.cacheName}' cache. ` + + `Will wait for the network response.`); + } + try { + // NOTE(philipwalton): Really annoying that we have to type cast here. + // https://github.com/microsoft/TypeScript/issues/20006 + response = (await fetchAndCachePromise); + } + catch (err) { + if (err instanceof Error) { + error = err; + } + } + } + if (process.env.NODE_ENV !== 'production') { + logger.groupCollapsed(messages.strategyStart(this.constructor.name, request)); + for (const log of logs) { + logger.log(log); + } + messages.printFinalResponse(response); + logger.groupEnd(); + } + if (!response) { + throw new WorkboxError('no-response', { url: request.url, error }); + } + return response; + } +} +export { StaleWhileRevalidate }; diff --git a/node_modules/workbox-strategies/StaleWhileRevalidate.mjs b/node_modules/workbox-strategies/StaleWhileRevalidate.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6e1a02d2ecacf5c7fa0c00aadd8cdb65d4d33e99 --- /dev/null +++ b/node_modules/workbox-strategies/StaleWhileRevalidate.mjs @@ -0,0 +1 @@ +export * from './StaleWhileRevalidate.js'; \ No newline at end of file diff --git a/node_modules/workbox-strategies/Strategy.d.ts b/node_modules/workbox-strategies/Strategy.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1947398b5bc372111badb53fd89f491f0d44f4a3 --- /dev/null +++ b/node_modules/workbox-strategies/Strategy.d.ts @@ -0,0 +1,107 @@ +import { HandlerCallbackOptions, RouteHandlerObject, WorkboxPlugin } from 'workbox-core/types.js'; +import { StrategyHandler } from './StrategyHandler.js'; +import './_version.js'; +export interface StrategyOptions { + cacheName?: string; + plugins?: WorkboxPlugin[]; + fetchOptions?: RequestInit; + matchOptions?: CacheQueryOptions; +} +/** + * An abstract base class that all other strategy classes must extend from: + * + * @memberof workbox-strategies + */ +declare abstract class Strategy implements RouteHandlerObject { + cacheName: string; + plugins: WorkboxPlugin[]; + fetchOptions?: RequestInit; + matchOptions?: CacheQueryOptions; + protected abstract _handle(request: Request, handler: StrategyHandler): Promise; + /** + * Creates a new instance of the strategy and sets all documented option + * properties as public instance properties. + * + * Note: if a custom strategy class extends the base Strategy class and does + * not need more than these properties, it does not need to define its own + * constructor. + * + * @param {Object} [options] + * @param {string} [options.cacheName] Cache name to store and retrieve + * requests. Defaults to the cache names provided by + * {@link workbox-core.cacheNames}. + * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins} + * to use in conjunction with this caching strategy. + * @param {Object} [options.fetchOptions] Values passed along to the + * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) + * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796) + * `fetch()` requests made by this strategy. + * @param {Object} [options.matchOptions] The + * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions} + * for any `cache.match()` or `cache.put()` calls made by this strategy. + */ + constructor(options?: StrategyOptions); + /** + * Perform a request strategy and returns a `Promise` that will resolve with + * a `Response`, invoking all relevant plugin callbacks. + * + * When a strategy instance is registered with a Workbox + * {@link workbox-routing.Route}, this method is automatically + * called when the route matches. + * + * Alternatively, this method can be used in a standalone `FetchEvent` + * listener by passing it to `event.respondWith()`. + * + * @param {FetchEvent|Object} options A `FetchEvent` or an object with the + * properties listed below. + * @param {Request|string} options.request A request to run this strategy for. + * @param {ExtendableEvent} options.event The event associated with the + * request. + * @param {URL} [options.url] + * @param {*} [options.params] + */ + handle(options: FetchEvent | HandlerCallbackOptions): Promise; + /** + * Similar to {@link workbox-strategies.Strategy~handle}, but + * instead of just returning a `Promise` that resolves to a `Response` it + * it will return an tuple of `[response, done]` promises, where the former + * (`response`) is equivalent to what `handle()` returns, and the latter is a + * Promise that will resolve once any promises that were added to + * `event.waitUntil()` as part of performing the strategy have completed. + * + * You can await the `done` promise to ensure any extra work performed by + * the strategy (usually caching responses) completes successfully. + * + * @param {FetchEvent|Object} options A `FetchEvent` or an object with the + * properties listed below. + * @param {Request|string} options.request A request to run this strategy for. + * @param {ExtendableEvent} options.event The event associated with the + * request. + * @param {URL} [options.url] + * @param {*} [options.params] + * @return {Array} A tuple of [response, done] + * promises that can be used to determine when the response resolves as + * well as when the handler has completed all its work. + */ + handleAll(options: FetchEvent | HandlerCallbackOptions): [Promise, Promise]; + _getResponse(handler: StrategyHandler, request: Request, event: ExtendableEvent): Promise; + _awaitComplete(responseDone: Promise, handler: StrategyHandler, request: Request, event: ExtendableEvent): Promise; +} +export { Strategy }; +/** + * Classes extending the `Strategy` based class should implement this method, + * and leverage the {@link workbox-strategies.StrategyHandler} + * arg to perform all fetching and cache logic, which will ensure all relevant + * cache, cache options, fetch options and plugins are used (per the current + * strategy instance). + * + * @name _handle + * @instance + * @abstract + * @function + * @param {Request} request + * @param {workbox-strategies.StrategyHandler} handler + * @return {Promise} + * + * @memberof workbox-strategies.Strategy + */ diff --git a/node_modules/workbox-strategies/Strategy.js b/node_modules/workbox-strategies/Strategy.js new file mode 100644 index 0000000000000000000000000000000000000000..e81a2f67d0e9ef886bb527c7b11b38cccf3edeeb --- /dev/null +++ b/node_modules/workbox-strategies/Strategy.js @@ -0,0 +1,228 @@ +/* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { cacheNames } from 'workbox-core/_private/cacheNames.js'; +import { WorkboxError } from 'workbox-core/_private/WorkboxError.js'; +import { logger } from 'workbox-core/_private/logger.js'; +import { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js'; +import { StrategyHandler } from './StrategyHandler.js'; +import './_version.js'; +/** + * An abstract base class that all other strategy classes must extend from: + * + * @memberof workbox-strategies + */ +class Strategy { + /** + * Creates a new instance of the strategy and sets all documented option + * properties as public instance properties. + * + * Note: if a custom strategy class extends the base Strategy class and does + * not need more than these properties, it does not need to define its own + * constructor. + * + * @param {Object} [options] + * @param {string} [options.cacheName] Cache name to store and retrieve + * requests. Defaults to the cache names provided by + * {@link workbox-core.cacheNames}. + * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins} + * to use in conjunction with this caching strategy. + * @param {Object} [options.fetchOptions] Values passed along to the + * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) + * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796) + * `fetch()` requests made by this strategy. + * @param {Object} [options.matchOptions] The + * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions} + * for any `cache.match()` or `cache.put()` calls made by this strategy. + */ + constructor(options = {}) { + /** + * Cache name to store and retrieve + * requests. Defaults to the cache names provided by + * {@link workbox-core.cacheNames}. + * + * @type {string} + */ + this.cacheName = cacheNames.getRuntimeName(options.cacheName); + /** + * The list + * [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins} + * used by this strategy. + * + * @type {Array} + */ + this.plugins = options.plugins || []; + /** + * Values passed along to the + * [`init`]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters} + * of all fetch() requests made by this strategy. + * + * @type {Object} + */ + this.fetchOptions = options.fetchOptions; + /** + * The + * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions} + * for any `cache.match()` or `cache.put()` calls made by this strategy. + * + * @type {Object} + */ + this.matchOptions = options.matchOptions; + } + /** + * Perform a request strategy and returns a `Promise` that will resolve with + * a `Response`, invoking all relevant plugin callbacks. + * + * When a strategy instance is registered with a Workbox + * {@link workbox-routing.Route}, this method is automatically + * called when the route matches. + * + * Alternatively, this method can be used in a standalone `FetchEvent` + * listener by passing it to `event.respondWith()`. + * + * @param {FetchEvent|Object} options A `FetchEvent` or an object with the + * properties listed below. + * @param {Request|string} options.request A request to run this strategy for. + * @param {ExtendableEvent} options.event The event associated with the + * request. + * @param {URL} [options.url] + * @param {*} [options.params] + */ + handle(options) { + const [responseDone] = this.handleAll(options); + return responseDone; + } + /** + * Similar to {@link workbox-strategies.Strategy~handle}, but + * instead of just returning a `Promise` that resolves to a `Response` it + * it will return an tuple of `[response, done]` promises, where the former + * (`response`) is equivalent to what `handle()` returns, and the latter is a + * Promise that will resolve once any promises that were added to + * `event.waitUntil()` as part of performing the strategy have completed. + * + * You can await the `done` promise to ensure any extra work performed by + * the strategy (usually caching responses) completes successfully. + * + * @param {FetchEvent|Object} options A `FetchEvent` or an object with the + * properties listed below. + * @param {Request|string} options.request A request to run this strategy for. + * @param {ExtendableEvent} options.event The event associated with the + * request. + * @param {URL} [options.url] + * @param {*} [options.params] + * @return {Array} A tuple of [response, done] + * promises that can be used to determine when the response resolves as + * well as when the handler has completed all its work. + */ + handleAll(options) { + // Allow for flexible options to be passed. + if (options instanceof FetchEvent) { + options = { + event: options, + request: options.request, + }; + } + const event = options.event; + const request = typeof options.request === 'string' + ? new Request(options.request) + : options.request; + const params = 'params' in options ? options.params : undefined; + const handler = new StrategyHandler(this, { event, request, params }); + const responseDone = this._getResponse(handler, request, event); + const handlerDone = this._awaitComplete(responseDone, handler, request, event); + // Return an array of promises, suitable for use with Promise.all(). + return [responseDone, handlerDone]; + } + async _getResponse(handler, request, event) { + await handler.runCallbacks('handlerWillStart', { event, request }); + let response = undefined; + try { + response = await this._handle(request, handler); + // The "official" Strategy subclasses all throw this error automatically, + // but in case a third-party Strategy doesn't, ensure that we have a + // consistent failure when there's no response or an error response. + if (!response || response.type === 'error') { + throw new WorkboxError('no-response', { url: request.url }); + } + } + catch (error) { + if (error instanceof Error) { + for (const callback of handler.iterateCallbacks('handlerDidError')) { + response = await callback({ error, event, request }); + if (response) { + break; + } + } + } + if (!response) { + throw error; + } + else if (process.env.NODE_ENV !== 'production') { + logger.log(`While responding to '${getFriendlyURL(request.url)}', ` + + `an ${error instanceof Error ? error.toString() : ''} error occurred. Using a fallback response provided by ` + + `a handlerDidError plugin.`); + } + } + for (const callback of handler.iterateCallbacks('handlerWillRespond')) { + response = await callback({ event, request, response }); + } + return response; + } + async _awaitComplete(responseDone, handler, request, event) { + let response; + let error; + try { + response = await responseDone; + } + catch (error) { + // Ignore errors, as response errors should be caught via the `response` + // promise above. The `done` promise will only throw for errors in + // promises passed to `handler.waitUntil()`. + } + try { + await handler.runCallbacks('handlerDidRespond', { + event, + request, + response, + }); + await handler.doneWaiting(); + } + catch (waitUntilError) { + if (waitUntilError instanceof Error) { + error = waitUntilError; + } + } + await handler.runCallbacks('handlerDidComplete', { + event, + request, + response, + error: error, + }); + handler.destroy(); + if (error) { + throw error; + } + } +} +export { Strategy }; +/** + * Classes extending the `Strategy` based class should implement this method, + * and leverage the {@link workbox-strategies.StrategyHandler} + * arg to perform all fetching and cache logic, which will ensure all relevant + * cache, cache options, fetch options and plugins are used (per the current + * strategy instance). + * + * @name _handle + * @instance + * @abstract + * @function + * @param {Request} request + * @param {workbox-strategies.StrategyHandler} handler + * @return {Promise} + * + * @memberof workbox-strategies.Strategy + */ diff --git a/node_modules/workbox-strategies/Strategy.mjs b/node_modules/workbox-strategies/Strategy.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3a4705c03d87df6c19dd30407f39e617635f89f3 --- /dev/null +++ b/node_modules/workbox-strategies/Strategy.mjs @@ -0,0 +1 @@ +export * from './Strategy.js'; \ No newline at end of file diff --git a/node_modules/workbox-strategies/StrategyHandler.d.ts b/node_modules/workbox-strategies/StrategyHandler.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..916270e6037cd66eae9d6209ffac7d39a546d5b7 --- /dev/null +++ b/node_modules/workbox-strategies/StrategyHandler.d.ts @@ -0,0 +1,184 @@ +import { HandlerCallbackOptions, WorkboxPlugin, WorkboxPluginCallbackParam } from 'workbox-core/types.js'; +import { Strategy } from './Strategy.js'; +import './_version.js'; +/** + * A class created every time a Strategy instance calls + * {@link workbox-strategies.Strategy~handle} or + * {@link workbox-strategies.Strategy~handleAll} that wraps all fetch and + * cache actions around plugin callbacks and keeps track of when the strategy + * is "done" (i.e. all added `event.waitUntil()` promises have resolved). + * + * @memberof workbox-strategies + */ +declare class StrategyHandler { + request: Request; + url?: URL; + event: ExtendableEvent; + params?: any; + private _cacheKeys; + private readonly _strategy; + private readonly _extendLifetimePromises; + private readonly _handlerDeferred; + private readonly _plugins; + private readonly _pluginStateMap; + /** + * Creates a new instance associated with the passed strategy and event + * that's handling the request. + * + * The constructor also initializes the state that will be passed to each of + * the plugins handling this request. + * + * @param {workbox-strategies.Strategy} strategy + * @param {Object} options + * @param {Request|string} options.request A request to run this strategy for. + * @param {ExtendableEvent} options.event The event associated with the + * request. + * @param {URL} [options.url] + * @param {*} [options.params] The return value from the + * {@link workbox-routing~matchCallback} (if applicable). + */ + constructor(strategy: Strategy, options: HandlerCallbackOptions); + /** + * Fetches a given request (and invokes any applicable plugin callback + * methods) using the `fetchOptions` (for non-navigation requests) and + * `plugins` defined on the `Strategy` object. + * + * The following plugin lifecycle methods are invoked when using this method: + * - `requestWillFetch()` + * - `fetchDidSucceed()` + * - `fetchDidFail()` + * + * @param {Request|string} input The URL or request to fetch. + * @return {Promise} + */ + fetch(input: RequestInfo): Promise; + /** + * Calls `this.fetch()` and (in the background) runs `this.cachePut()` on + * the response generated by `this.fetch()`. + * + * The call to `this.cachePut()` automatically invokes `this.waitUntil()`, + * so you do not have to manually call `waitUntil()` on the event. + * + * @param {Request|string} input The request or URL to fetch and cache. + * @return {Promise} + */ + fetchAndCachePut(input: RequestInfo): Promise; + /** + * Matches a request from the cache (and invokes any applicable plugin + * callback methods) using the `cacheName`, `matchOptions`, and `plugins` + * defined on the strategy object. + * + * The following plugin lifecycle methods are invoked when using this method: + * - cacheKeyWillBeUsed() + * - cachedResponseWillBeUsed() + * + * @param {Request|string} key The Request or URL to use as the cache key. + * @return {Promise} A matching response, if found. + */ + cacheMatch(key: RequestInfo): Promise; + /** + * Puts a request/response pair in the cache (and invokes any applicable + * plugin callback methods) using the `cacheName` and `plugins` defined on + * the strategy object. + * + * The following plugin lifecycle methods are invoked when using this method: + * - cacheKeyWillBeUsed() + * - cacheWillUpdate() + * - cacheDidUpdate() + * + * @param {Request|string} key The request or URL to use as the cache key. + * @param {Response} response The response to cache. + * @return {Promise} `false` if a cacheWillUpdate caused the response + * not be cached, and `true` otherwise. + */ + cachePut(key: RequestInfo, response: Response): Promise; + /** + * Checks the list of plugins for the `cacheKeyWillBeUsed` callback, and + * executes any of those callbacks found in sequence. The final `Request` + * object returned by the last plugin is treated as the cache key for cache + * reads and/or writes. If no `cacheKeyWillBeUsed` plugin callbacks have + * been registered, the passed request is returned unmodified + * + * @param {Request} request + * @param {string} mode + * @return {Promise} + */ + getCacheKey(request: Request, mode: 'read' | 'write'): Promise; + /** + * Returns true if the strategy has at least one plugin with the given + * callback. + * + * @param {string} name The name of the callback to check for. + * @return {boolean} + */ + hasCallback(name: C): boolean; + /** + * Runs all plugin callbacks matching the given name, in order, passing the + * given param object (merged ith the current plugin state) as the only + * argument. + * + * Note: since this method runs all plugins, it's not suitable for cases + * where the return value of a callback needs to be applied prior to calling + * the next callback. See + * {@link workbox-strategies.StrategyHandler#iterateCallbacks} + * below for how to handle that case. + * + * @param {string} name The name of the callback to run within each plugin. + * @param {Object} param The object to pass as the first (and only) param + * when executing each callback. This object will be merged with the + * current plugin state prior to callback execution. + */ + runCallbacks>(name: C, param: Omit): Promise; + /** + * Accepts a callback and returns an iterable of matching plugin callbacks, + * where each callback is wrapped with the current handler state (i.e. when + * you call each callback, whatever object parameter you pass it will + * be merged with the plugin's current state). + * + * @param {string} name The name fo the callback to run + * @return {Array} + */ + iterateCallbacks(name: C): Generator>; + /** + * Adds a promise to the + * [extend lifetime promises]{@link https://w3c.github.io/ServiceWorker/#extendableevent-extend-lifetime-promises} + * of the event associated with the request being handled (usually a + * `FetchEvent`). + * + * Note: you can await + * {@link workbox-strategies.StrategyHandler~doneWaiting} + * to know when all added promises have settled. + * + * @param {Promise} promise A promise to add to the extend lifetime promises + * of the event that triggered the request. + */ + waitUntil(promise: Promise): Promise; + /** + * Returns a promise that resolves once all promises passed to + * {@link workbox-strategies.StrategyHandler~waitUntil} + * have settled. + * + * Note: any work done after `doneWaiting()` settles should be manually + * passed to an event's `waitUntil()` method (not this handler's + * `waitUntil()` method), otherwise the service worker thread may be killed + * prior to your work completing. + */ + doneWaiting(): Promise; + /** + * Stops running the strategy and immediately resolves any pending + * `waitUntil()` promises. + */ + destroy(): void; + /** + * This method will call cacheWillUpdate on the available plugins (or use + * status === 200) to determine if the Response is safe and valid to cache. + * + * @param {Request} options.request + * @param {Response} options.response + * @return {Promise} + * + * @private + */ + _ensureResponseSafeToCache(response: Response): Promise; +} +export { StrategyHandler }; diff --git a/node_modules/workbox-strategies/StrategyHandler.js b/node_modules/workbox-strategies/StrategyHandler.js new file mode 100644 index 0000000000000000000000000000000000000000..65e2199d21c4d246b027ed92fefceb87a21f0e8b --- /dev/null +++ b/node_modules/workbox-strategies/StrategyHandler.js @@ -0,0 +1,521 @@ +/* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { assert } from 'workbox-core/_private/assert.js'; +import { cacheMatchIgnoreParams } from 'workbox-core/_private/cacheMatchIgnoreParams.js'; +import { Deferred } from 'workbox-core/_private/Deferred.js'; +import { executeQuotaErrorCallbacks } from 'workbox-core/_private/executeQuotaErrorCallbacks.js'; +import { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js'; +import { logger } from 'workbox-core/_private/logger.js'; +import { timeout } from 'workbox-core/_private/timeout.js'; +import { WorkboxError } from 'workbox-core/_private/WorkboxError.js'; +import './_version.js'; +function toRequest(input) { + return typeof input === 'string' ? new Request(input) : input; +} +/** + * A class created every time a Strategy instance calls + * {@link workbox-strategies.Strategy~handle} or + * {@link workbox-strategies.Strategy~handleAll} that wraps all fetch and + * cache actions around plugin callbacks and keeps track of when the strategy + * is "done" (i.e. all added `event.waitUntil()` promises have resolved). + * + * @memberof workbox-strategies + */ +class StrategyHandler { + /** + * Creates a new instance associated with the passed strategy and event + * that's handling the request. + * + * The constructor also initializes the state that will be passed to each of + * the plugins handling this request. + * + * @param {workbox-strategies.Strategy} strategy + * @param {Object} options + * @param {Request|string} options.request A request to run this strategy for. + * @param {ExtendableEvent} options.event The event associated with the + * request. + * @param {URL} [options.url] + * @param {*} [options.params] The return value from the + * {@link workbox-routing~matchCallback} (if applicable). + */ + constructor(strategy, options) { + this._cacheKeys = {}; + /** + * The request the strategy is performing (passed to the strategy's + * `handle()` or `handleAll()` method). + * @name request + * @instance + * @type {Request} + * @memberof workbox-strategies.StrategyHandler + */ + /** + * The event associated with this request. + * @name event + * @instance + * @type {ExtendableEvent} + * @memberof workbox-strategies.StrategyHandler + */ + /** + * A `URL` instance of `request.url` (if passed to the strategy's + * `handle()` or `handleAll()` method). + * Note: the `url` param will be present if the strategy was invoked + * from a workbox `Route` object. + * @name url + * @instance + * @type {URL|undefined} + * @memberof workbox-strategies.StrategyHandler + */ + /** + * A `param` value (if passed to the strategy's + * `handle()` or `handleAll()` method). + * Note: the `param` param will be present if the strategy was invoked + * from a workbox `Route` object and the + * {@link workbox-routing~matchCallback} returned + * a truthy value (it will be that value). + * @name params + * @instance + * @type {*|undefined} + * @memberof workbox-strategies.StrategyHandler + */ + if (process.env.NODE_ENV !== 'production') { + assert.isInstance(options.event, ExtendableEvent, { + moduleName: 'workbox-strategies', + className: 'StrategyHandler', + funcName: 'constructor', + paramName: 'options.event', + }); + } + Object.assign(this, options); + this.event = options.event; + this._strategy = strategy; + this._handlerDeferred = new Deferred(); + this._extendLifetimePromises = []; + // Copy the plugins list (since it's mutable on the strategy), + // so any mutations don't affect this handler instance. + this._plugins = [...strategy.plugins]; + this._pluginStateMap = new Map(); + for (const plugin of this._plugins) { + this._pluginStateMap.set(plugin, {}); + } + this.event.waitUntil(this._handlerDeferred.promise); + } + /** + * Fetches a given request (and invokes any applicable plugin callback + * methods) using the `fetchOptions` (for non-navigation requests) and + * `plugins` defined on the `Strategy` object. + * + * The following plugin lifecycle methods are invoked when using this method: + * - `requestWillFetch()` + * - `fetchDidSucceed()` + * - `fetchDidFail()` + * + * @param {Request|string} input The URL or request to fetch. + * @return {Promise} + */ + async fetch(input) { + const { event } = this; + let request = toRequest(input); + if (request.mode === 'navigate' && + event instanceof FetchEvent && + event.preloadResponse) { + const possiblePreloadResponse = (await event.preloadResponse); + if (possiblePreloadResponse) { + if (process.env.NODE_ENV !== 'production') { + logger.log(`Using a preloaded navigation response for ` + + `'${getFriendlyURL(request.url)}'`); + } + return possiblePreloadResponse; + } + } + // If there is a fetchDidFail plugin, we need to save a clone of the + // original request before it's either modified by a requestWillFetch + // plugin or before the original request's body is consumed via fetch(). + const originalRequest = this.hasCallback('fetchDidFail') + ? request.clone() + : null; + try { + for (const cb of this.iterateCallbacks('requestWillFetch')) { + request = await cb({ request: request.clone(), event }); + } + } + catch (err) { + if (err instanceof Error) { + throw new WorkboxError('plugin-error-request-will-fetch', { + thrownErrorMessage: err.message, + }); + } + } + // The request can be altered by plugins with `requestWillFetch` making + // the original request (most likely from a `fetch` event) different + // from the Request we make. Pass both to `fetchDidFail` to aid debugging. + const pluginFilteredRequest = request.clone(); + try { + let fetchResponse; + // See https://github.com/GoogleChrome/workbox/issues/1796 + fetchResponse = await fetch(request, request.mode === 'navigate' ? undefined : this._strategy.fetchOptions); + if (process.env.NODE_ENV !== 'production') { + logger.debug(`Network request for ` + + `'${getFriendlyURL(request.url)}' returned a response with ` + + `status '${fetchResponse.status}'.`); + } + for (const callback of this.iterateCallbacks('fetchDidSucceed')) { + fetchResponse = await callback({ + event, + request: pluginFilteredRequest, + response: fetchResponse, + }); + } + return fetchResponse; + } + catch (error) { + if (process.env.NODE_ENV !== 'production') { + logger.log(`Network request for ` + + `'${getFriendlyURL(request.url)}' threw an error.`, error); + } + // `originalRequest` will only exist if a `fetchDidFail` callback + // is being used (see above). + if (originalRequest) { + await this.runCallbacks('fetchDidFail', { + error: error, + event, + originalRequest: originalRequest.clone(), + request: pluginFilteredRequest.clone(), + }); + } + throw error; + } + } + /** + * Calls `this.fetch()` and (in the background) runs `this.cachePut()` on + * the response generated by `this.fetch()`. + * + * The call to `this.cachePut()` automatically invokes `this.waitUntil()`, + * so you do not have to manually call `waitUntil()` on the event. + * + * @param {Request|string} input The request or URL to fetch and cache. + * @return {Promise} + */ + async fetchAndCachePut(input) { + const response = await this.fetch(input); + const responseClone = response.clone(); + void this.waitUntil(this.cachePut(input, responseClone)); + return response; + } + /** + * Matches a request from the cache (and invokes any applicable plugin + * callback methods) using the `cacheName`, `matchOptions`, and `plugins` + * defined on the strategy object. + * + * The following plugin lifecycle methods are invoked when using this method: + * - cacheKeyWillBeUsed() + * - cachedResponseWillBeUsed() + * + * @param {Request|string} key The Request or URL to use as the cache key. + * @return {Promise} A matching response, if found. + */ + async cacheMatch(key) { + const request = toRequest(key); + let cachedResponse; + const { cacheName, matchOptions } = this._strategy; + const effectiveRequest = await this.getCacheKey(request, 'read'); + const multiMatchOptions = Object.assign(Object.assign({}, matchOptions), { cacheName }); + cachedResponse = await caches.match(effectiveRequest, multiMatchOptions); + if (process.env.NODE_ENV !== 'production') { + if (cachedResponse) { + logger.debug(`Found a cached response in '${cacheName}'.`); + } + else { + logger.debug(`No cached response found in '${cacheName}'.`); + } + } + for (const callback of this.iterateCallbacks('cachedResponseWillBeUsed')) { + cachedResponse = + (await callback({ + cacheName, + matchOptions, + cachedResponse, + request: effectiveRequest, + event: this.event, + })) || undefined; + } + return cachedResponse; + } + /** + * Puts a request/response pair in the cache (and invokes any applicable + * plugin callback methods) using the `cacheName` and `plugins` defined on + * the strategy object. + * + * The following plugin lifecycle methods are invoked when using this method: + * - cacheKeyWillBeUsed() + * - cacheWillUpdate() + * - cacheDidUpdate() + * + * @param {Request|string} key The request or URL to use as the cache key. + * @param {Response} response The response to cache. + * @return {Promise} `false` if a cacheWillUpdate caused the response + * not be cached, and `true` otherwise. + */ + async cachePut(key, response) { + const request = toRequest(key); + // Run in the next task to avoid blocking other cache reads. + // https://github.com/w3c/ServiceWorker/issues/1397 + await timeout(0); + const effectiveRequest = await this.getCacheKey(request, 'write'); + if (process.env.NODE_ENV !== 'production') { + if (effectiveRequest.method && effectiveRequest.method !== 'GET') { + throw new WorkboxError('attempt-to-cache-non-get-request', { + url: getFriendlyURL(effectiveRequest.url), + method: effectiveRequest.method, + }); + } + // See https://github.com/GoogleChrome/workbox/issues/2818 + const vary = response.headers.get('Vary'); + if (vary) { + logger.debug(`The response for ${getFriendlyURL(effectiveRequest.url)} ` + + `has a 'Vary: ${vary}' header. ` + + `Consider setting the {ignoreVary: true} option on your strategy ` + + `to ensure cache matching and deletion works as expected.`); + } + } + if (!response) { + if (process.env.NODE_ENV !== 'production') { + logger.error(`Cannot cache non-existent response for ` + + `'${getFriendlyURL(effectiveRequest.url)}'.`); + } + throw new WorkboxError('cache-put-with-no-response', { + url: getFriendlyURL(effectiveRequest.url), + }); + } + const responseToCache = await this._ensureResponseSafeToCache(response); + if (!responseToCache) { + if (process.env.NODE_ENV !== 'production') { + logger.debug(`Response '${getFriendlyURL(effectiveRequest.url)}' ` + + `will not be cached.`, responseToCache); + } + return false; + } + const { cacheName, matchOptions } = this._strategy; + const cache = await self.caches.open(cacheName); + const hasCacheUpdateCallback = this.hasCallback('cacheDidUpdate'); + const oldResponse = hasCacheUpdateCallback + ? await cacheMatchIgnoreParams( + // TODO(philipwalton): the `__WB_REVISION__` param is a precaching + // feature. Consider into ways to only add this behavior if using + // precaching. + cache, effectiveRequest.clone(), ['__WB_REVISION__'], matchOptions) + : null; + if (process.env.NODE_ENV !== 'production') { + logger.debug(`Updating the '${cacheName}' cache with a new Response ` + + `for ${getFriendlyURL(effectiveRequest.url)}.`); + } + try { + await cache.put(effectiveRequest, hasCacheUpdateCallback ? responseToCache.clone() : responseToCache); + } + catch (error) { + if (error instanceof Error) { + // See https://developer.mozilla.org/en-US/docs/Web/API/DOMException#exception-QuotaExceededError + if (error.name === 'QuotaExceededError') { + await executeQuotaErrorCallbacks(); + } + throw error; + } + } + for (const callback of this.iterateCallbacks('cacheDidUpdate')) { + await callback({ + cacheName, + oldResponse, + newResponse: responseToCache.clone(), + request: effectiveRequest, + event: this.event, + }); + } + return true; + } + /** + * Checks the list of plugins for the `cacheKeyWillBeUsed` callback, and + * executes any of those callbacks found in sequence. The final `Request` + * object returned by the last plugin is treated as the cache key for cache + * reads and/or writes. If no `cacheKeyWillBeUsed` plugin callbacks have + * been registered, the passed request is returned unmodified + * + * @param {Request} request + * @param {string} mode + * @return {Promise} + */ + async getCacheKey(request, mode) { + const key = `${request.url} | ${mode}`; + if (!this._cacheKeys[key]) { + let effectiveRequest = request; + for (const callback of this.iterateCallbacks('cacheKeyWillBeUsed')) { + effectiveRequest = toRequest(await callback({ + mode, + request: effectiveRequest, + event: this.event, + // params has a type any can't change right now. + params: this.params, // eslint-disable-line + })); + } + this._cacheKeys[key] = effectiveRequest; + } + return this._cacheKeys[key]; + } + /** + * Returns true if the strategy has at least one plugin with the given + * callback. + * + * @param {string} name The name of the callback to check for. + * @return {boolean} + */ + hasCallback(name) { + for (const plugin of this._strategy.plugins) { + if (name in plugin) { + return true; + } + } + return false; + } + /** + * Runs all plugin callbacks matching the given name, in order, passing the + * given param object (merged ith the current plugin state) as the only + * argument. + * + * Note: since this method runs all plugins, it's not suitable for cases + * where the return value of a callback needs to be applied prior to calling + * the next callback. See + * {@link workbox-strategies.StrategyHandler#iterateCallbacks} + * below for how to handle that case. + * + * @param {string} name The name of the callback to run within each plugin. + * @param {Object} param The object to pass as the first (and only) param + * when executing each callback. This object will be merged with the + * current plugin state prior to callback execution. + */ + async runCallbacks(name, param) { + for (const callback of this.iterateCallbacks(name)) { + // TODO(philipwalton): not sure why `any` is needed. It seems like + // this should work with `as WorkboxPluginCallbackParam[C]`. + await callback(param); + } + } + /** + * Accepts a callback and returns an iterable of matching plugin callbacks, + * where each callback is wrapped with the current handler state (i.e. when + * you call each callback, whatever object parameter you pass it will + * be merged with the plugin's current state). + * + * @param {string} name The name fo the callback to run + * @return {Array} + */ + *iterateCallbacks(name) { + for (const plugin of this._strategy.plugins) { + if (typeof plugin[name] === 'function') { + const state = this._pluginStateMap.get(plugin); + const statefulCallback = (param) => { + const statefulParam = Object.assign(Object.assign({}, param), { state }); + // TODO(philipwalton): not sure why `any` is needed. It seems like + // this should work with `as WorkboxPluginCallbackParam[C]`. + return plugin[name](statefulParam); + }; + yield statefulCallback; + } + } + } + /** + * Adds a promise to the + * [extend lifetime promises]{@link https://w3c.github.io/ServiceWorker/#extendableevent-extend-lifetime-promises} + * of the event associated with the request being handled (usually a + * `FetchEvent`). + * + * Note: you can await + * {@link workbox-strategies.StrategyHandler~doneWaiting} + * to know when all added promises have settled. + * + * @param {Promise} promise A promise to add to the extend lifetime promises + * of the event that triggered the request. + */ + waitUntil(promise) { + this._extendLifetimePromises.push(promise); + return promise; + } + /** + * Returns a promise that resolves once all promises passed to + * {@link workbox-strategies.StrategyHandler~waitUntil} + * have settled. + * + * Note: any work done after `doneWaiting()` settles should be manually + * passed to an event's `waitUntil()` method (not this handler's + * `waitUntil()` method), otherwise the service worker thread may be killed + * prior to your work completing. + */ + async doneWaiting() { + while (this._extendLifetimePromises.length) { + const promises = this._extendLifetimePromises.splice(0); + const result = await Promise.allSettled(promises); + const firstRejection = result.find((i) => i.status === 'rejected'); + if (firstRejection) { + throw firstRejection.reason; + } + } + } + /** + * Stops running the strategy and immediately resolves any pending + * `waitUntil()` promises. + */ + destroy() { + this._handlerDeferred.resolve(null); + } + /** + * This method will call cacheWillUpdate on the available plugins (or use + * status === 200) to determine if the Response is safe and valid to cache. + * + * @param {Request} options.request + * @param {Response} options.response + * @return {Promise} + * + * @private + */ + async _ensureResponseSafeToCache(response) { + let responseToCache = response; + let pluginsUsed = false; + for (const callback of this.iterateCallbacks('cacheWillUpdate')) { + responseToCache = + (await callback({ + request: this.request, + response: responseToCache, + event: this.event, + })) || undefined; + pluginsUsed = true; + if (!responseToCache) { + break; + } + } + if (!pluginsUsed) { + if (responseToCache && responseToCache.status !== 200) { + responseToCache = undefined; + } + if (process.env.NODE_ENV !== 'production') { + if (responseToCache) { + if (responseToCache.status !== 200) { + if (responseToCache.status === 0) { + logger.warn(`The response for '${this.request.url}' ` + + `is an opaque response. The caching strategy that you're ` + + `using will not cache opaque responses by default.`); + } + else { + logger.debug(`The response for '${this.request.url}' ` + + `returned a status code of '${response.status}' and won't ` + + `be cached as a result.`); + } + } + } + } + } + return responseToCache; + } +} +export { StrategyHandler }; diff --git a/node_modules/workbox-strategies/StrategyHandler.mjs b/node_modules/workbox-strategies/StrategyHandler.mjs new file mode 100644 index 0000000000000000000000000000000000000000..358b2ef4ccf7767c3c98059f68db4e876f1d08e5 --- /dev/null +++ b/node_modules/workbox-strategies/StrategyHandler.mjs @@ -0,0 +1 @@ +export * from './StrategyHandler.js'; \ No newline at end of file diff --git a/node_modules/workbox-strategies/_version.d.ts b/node_modules/workbox-strategies/_version.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/workbox-strategies/_version.js b/node_modules/workbox-strategies/_version.js new file mode 100644 index 0000000000000000000000000000000000000000..dfd2ca119789c37517e5d75d5abda8b99b10fc26 --- /dev/null +++ b/node_modules/workbox-strategies/_version.js @@ -0,0 +1,6 @@ +"use strict"; +// @ts-ignore +try { + self['workbox:strategies:7.4.0'] && _(); +} +catch (e) { } diff --git a/node_modules/workbox-strategies/_version.mjs b/node_modules/workbox-strategies/_version.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a4c4cc6d02baacbeba73ab09247a4637d427cd8c --- /dev/null +++ b/node_modules/workbox-strategies/_version.mjs @@ -0,0 +1 @@ +try{self['workbox:strategies:7.4.1']&&_()}catch(e){}// eslint-disable-line \ No newline at end of file diff --git a/node_modules/workbox-strategies/build/workbox-strategies.dev.js b/node_modules/workbox-strategies/build/workbox-strategies.dev.js new file mode 100644 index 0000000000000000000000000000000000000000..cc1581fd05cdcc888c0f201381cceb742372a6df --- /dev/null +++ b/node_modules/workbox-strategies/build/workbox-strategies.dev.js @@ -0,0 +1,1338 @@ +this.workbox = this.workbox || {}; +this.workbox.strategies = (function (exports, assert_js, logger_js, WorkboxError_js, cacheNames_js, getFriendlyURL_js, cacheMatchIgnoreParams_js, Deferred_js, executeQuotaErrorCallbacks_js, timeout_js) { + 'use strict'; + + // @ts-ignore + try { + self['workbox:strategies:7.4.0'] && _(); + } catch (e) {} + + /* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + function toRequest(input) { + return typeof input === 'string' ? new Request(input) : input; + } + /** + * A class created every time a Strategy instance calls + * {@link workbox-strategies.Strategy~handle} or + * {@link workbox-strategies.Strategy~handleAll} that wraps all fetch and + * cache actions around plugin callbacks and keeps track of when the strategy + * is "done" (i.e. all added `event.waitUntil()` promises have resolved). + * + * @memberof workbox-strategies + */ + class StrategyHandler { + /** + * Creates a new instance associated with the passed strategy and event + * that's handling the request. + * + * The constructor also initializes the state that will be passed to each of + * the plugins handling this request. + * + * @param {workbox-strategies.Strategy} strategy + * @param {Object} options + * @param {Request|string} options.request A request to run this strategy for. + * @param {ExtendableEvent} options.event The event associated with the + * request. + * @param {URL} [options.url] + * @param {*} [options.params] The return value from the + * {@link workbox-routing~matchCallback} (if applicable). + */ + constructor(strategy, options) { + this._cacheKeys = {}; + /** + * The request the strategy is performing (passed to the strategy's + * `handle()` or `handleAll()` method). + * @name request + * @instance + * @type {Request} + * @memberof workbox-strategies.StrategyHandler + */ + /** + * The event associated with this request. + * @name event + * @instance + * @type {ExtendableEvent} + * @memberof workbox-strategies.StrategyHandler + */ + /** + * A `URL` instance of `request.url` (if passed to the strategy's + * `handle()` or `handleAll()` method). + * Note: the `url` param will be present if the strategy was invoked + * from a workbox `Route` object. + * @name url + * @instance + * @type {URL|undefined} + * @memberof workbox-strategies.StrategyHandler + */ + /** + * A `param` value (if passed to the strategy's + * `handle()` or `handleAll()` method). + * Note: the `param` param will be present if the strategy was invoked + * from a workbox `Route` object and the + * {@link workbox-routing~matchCallback} returned + * a truthy value (it will be that value). + * @name params + * @instance + * @type {*|undefined} + * @memberof workbox-strategies.StrategyHandler + */ + { + assert_js.assert.isInstance(options.event, ExtendableEvent, { + moduleName: 'workbox-strategies', + className: 'StrategyHandler', + funcName: 'constructor', + paramName: 'options.event' + }); + } + Object.assign(this, options); + this.event = options.event; + this._strategy = strategy; + this._handlerDeferred = new Deferred_js.Deferred(); + this._extendLifetimePromises = []; + // Copy the plugins list (since it's mutable on the strategy), + // so any mutations don't affect this handler instance. + this._plugins = [...strategy.plugins]; + this._pluginStateMap = new Map(); + for (const plugin of this._plugins) { + this._pluginStateMap.set(plugin, {}); + } + this.event.waitUntil(this._handlerDeferred.promise); + } + /** + * Fetches a given request (and invokes any applicable plugin callback + * methods) using the `fetchOptions` (for non-navigation requests) and + * `plugins` defined on the `Strategy` object. + * + * The following plugin lifecycle methods are invoked when using this method: + * - `requestWillFetch()` + * - `fetchDidSucceed()` + * - `fetchDidFail()` + * + * @param {Request|string} input The URL or request to fetch. + * @return {Promise} + */ + async fetch(input) { + const { + event + } = this; + let request = toRequest(input); + if (request.mode === 'navigate' && event instanceof FetchEvent && event.preloadResponse) { + const possiblePreloadResponse = await event.preloadResponse; + if (possiblePreloadResponse) { + { + logger_js.logger.log(`Using a preloaded navigation response for ` + `'${getFriendlyURL_js.getFriendlyURL(request.url)}'`); + } + return possiblePreloadResponse; + } + } + // If there is a fetchDidFail plugin, we need to save a clone of the + // original request before it's either modified by a requestWillFetch + // plugin or before the original request's body is consumed via fetch(). + const originalRequest = this.hasCallback('fetchDidFail') ? request.clone() : null; + try { + for (const cb of this.iterateCallbacks('requestWillFetch')) { + request = await cb({ + request: request.clone(), + event + }); + } + } catch (err) { + if (err instanceof Error) { + throw new WorkboxError_js.WorkboxError('plugin-error-request-will-fetch', { + thrownErrorMessage: err.message + }); + } + } + // The request can be altered by plugins with `requestWillFetch` making + // the original request (most likely from a `fetch` event) different + // from the Request we make. Pass both to `fetchDidFail` to aid debugging. + const pluginFilteredRequest = request.clone(); + try { + let fetchResponse; + // See https://github.com/GoogleChrome/workbox/issues/1796 + fetchResponse = await fetch(request, request.mode === 'navigate' ? undefined : this._strategy.fetchOptions); + if ("dev" !== 'production') { + logger_js.logger.debug(`Network request for ` + `'${getFriendlyURL_js.getFriendlyURL(request.url)}' returned a response with ` + `status '${fetchResponse.status}'.`); + } + for (const callback of this.iterateCallbacks('fetchDidSucceed')) { + fetchResponse = await callback({ + event, + request: pluginFilteredRequest, + response: fetchResponse + }); + } + return fetchResponse; + } catch (error) { + { + logger_js.logger.log(`Network request for ` + `'${getFriendlyURL_js.getFriendlyURL(request.url)}' threw an error.`, error); + } + // `originalRequest` will only exist if a `fetchDidFail` callback + // is being used (see above). + if (originalRequest) { + await this.runCallbacks('fetchDidFail', { + error: error, + event, + originalRequest: originalRequest.clone(), + request: pluginFilteredRequest.clone() + }); + } + throw error; + } + } + /** + * Calls `this.fetch()` and (in the background) runs `this.cachePut()` on + * the response generated by `this.fetch()`. + * + * The call to `this.cachePut()` automatically invokes `this.waitUntil()`, + * so you do not have to manually call `waitUntil()` on the event. + * + * @param {Request|string} input The request or URL to fetch and cache. + * @return {Promise} + */ + async fetchAndCachePut(input) { + const response = await this.fetch(input); + const responseClone = response.clone(); + void this.waitUntil(this.cachePut(input, responseClone)); + return response; + } + /** + * Matches a request from the cache (and invokes any applicable plugin + * callback methods) using the `cacheName`, `matchOptions`, and `plugins` + * defined on the strategy object. + * + * The following plugin lifecycle methods are invoked when using this method: + * - cacheKeyWillBeUsed() + * - cachedResponseWillBeUsed() + * + * @param {Request|string} key The Request or URL to use as the cache key. + * @return {Promise} A matching response, if found. + */ + async cacheMatch(key) { + const request = toRequest(key); + let cachedResponse; + const { + cacheName, + matchOptions + } = this._strategy; + const effectiveRequest = await this.getCacheKey(request, 'read'); + const multiMatchOptions = Object.assign(Object.assign({}, matchOptions), { + cacheName + }); + cachedResponse = await caches.match(effectiveRequest, multiMatchOptions); + { + if (cachedResponse) { + logger_js.logger.debug(`Found a cached response in '${cacheName}'.`); + } else { + logger_js.logger.debug(`No cached response found in '${cacheName}'.`); + } + } + for (const callback of this.iterateCallbacks('cachedResponseWillBeUsed')) { + cachedResponse = (await callback({ + cacheName, + matchOptions, + cachedResponse, + request: effectiveRequest, + event: this.event + })) || undefined; + } + return cachedResponse; + } + /** + * Puts a request/response pair in the cache (and invokes any applicable + * plugin callback methods) using the `cacheName` and `plugins` defined on + * the strategy object. + * + * The following plugin lifecycle methods are invoked when using this method: + * - cacheKeyWillBeUsed() + * - cacheWillUpdate() + * - cacheDidUpdate() + * + * @param {Request|string} key The request or URL to use as the cache key. + * @param {Response} response The response to cache. + * @return {Promise} `false` if a cacheWillUpdate caused the response + * not be cached, and `true` otherwise. + */ + async cachePut(key, response) { + const request = toRequest(key); + // Run in the next task to avoid blocking other cache reads. + // https://github.com/w3c/ServiceWorker/issues/1397 + await timeout_js.timeout(0); + const effectiveRequest = await this.getCacheKey(request, 'write'); + { + if (effectiveRequest.method && effectiveRequest.method !== 'GET') { + throw new WorkboxError_js.WorkboxError('attempt-to-cache-non-get-request', { + url: getFriendlyURL_js.getFriendlyURL(effectiveRequest.url), + method: effectiveRequest.method + }); + } + // See https://github.com/GoogleChrome/workbox/issues/2818 + const vary = response.headers.get('Vary'); + if (vary) { + logger_js.logger.debug(`The response for ${getFriendlyURL_js.getFriendlyURL(effectiveRequest.url)} ` + `has a 'Vary: ${vary}' header. ` + `Consider setting the {ignoreVary: true} option on your strategy ` + `to ensure cache matching and deletion works as expected.`); + } + } + if (!response) { + { + logger_js.logger.error(`Cannot cache non-existent response for ` + `'${getFriendlyURL_js.getFriendlyURL(effectiveRequest.url)}'.`); + } + throw new WorkboxError_js.WorkboxError('cache-put-with-no-response', { + url: getFriendlyURL_js.getFriendlyURL(effectiveRequest.url) + }); + } + const responseToCache = await this._ensureResponseSafeToCache(response); + if (!responseToCache) { + { + logger_js.logger.debug(`Response '${getFriendlyURL_js.getFriendlyURL(effectiveRequest.url)}' ` + `will not be cached.`, responseToCache); + } + return false; + } + const { + cacheName, + matchOptions + } = this._strategy; + const cache = await self.caches.open(cacheName); + const hasCacheUpdateCallback = this.hasCallback('cacheDidUpdate'); + const oldResponse = hasCacheUpdateCallback ? await cacheMatchIgnoreParams_js.cacheMatchIgnoreParams( + // TODO(philipwalton): the `__WB_REVISION__` param is a precaching + // feature. Consider into ways to only add this behavior if using + // precaching. + cache, effectiveRequest.clone(), ['__WB_REVISION__'], matchOptions) : null; + { + logger_js.logger.debug(`Updating the '${cacheName}' cache with a new Response ` + `for ${getFriendlyURL_js.getFriendlyURL(effectiveRequest.url)}.`); + } + try { + await cache.put(effectiveRequest, hasCacheUpdateCallback ? responseToCache.clone() : responseToCache); + } catch (error) { + if (error instanceof Error) { + // See https://developer.mozilla.org/en-US/docs/Web/API/DOMException#exception-QuotaExceededError + if (error.name === 'QuotaExceededError') { + await executeQuotaErrorCallbacks_js.executeQuotaErrorCallbacks(); + } + throw error; + } + } + for (const callback of this.iterateCallbacks('cacheDidUpdate')) { + await callback({ + cacheName, + oldResponse, + newResponse: responseToCache.clone(), + request: effectiveRequest, + event: this.event + }); + } + return true; + } + /** + * Checks the list of plugins for the `cacheKeyWillBeUsed` callback, and + * executes any of those callbacks found in sequence. The final `Request` + * object returned by the last plugin is treated as the cache key for cache + * reads and/or writes. If no `cacheKeyWillBeUsed` plugin callbacks have + * been registered, the passed request is returned unmodified + * + * @param {Request} request + * @param {string} mode + * @return {Promise} + */ + async getCacheKey(request, mode) { + const key = `${request.url} | ${mode}`; + if (!this._cacheKeys[key]) { + let effectiveRequest = request; + for (const callback of this.iterateCallbacks('cacheKeyWillBeUsed')) { + effectiveRequest = toRequest(await callback({ + mode, + request: effectiveRequest, + event: this.event, + // params has a type any can't change right now. + params: this.params // eslint-disable-line + })); + } + this._cacheKeys[key] = effectiveRequest; + } + return this._cacheKeys[key]; + } + /** + * Returns true if the strategy has at least one plugin with the given + * callback. + * + * @param {string} name The name of the callback to check for. + * @return {boolean} + */ + hasCallback(name) { + for (const plugin of this._strategy.plugins) { + if (name in plugin) { + return true; + } + } + return false; + } + /** + * Runs all plugin callbacks matching the given name, in order, passing the + * given param object (merged ith the current plugin state) as the only + * argument. + * + * Note: since this method runs all plugins, it's not suitable for cases + * where the return value of a callback needs to be applied prior to calling + * the next callback. See + * {@link workbox-strategies.StrategyHandler#iterateCallbacks} + * below for how to handle that case. + * + * @param {string} name The name of the callback to run within each plugin. + * @param {Object} param The object to pass as the first (and only) param + * when executing each callback. This object will be merged with the + * current plugin state prior to callback execution. + */ + async runCallbacks(name, param) { + for (const callback of this.iterateCallbacks(name)) { + // TODO(philipwalton): not sure why `any` is needed. It seems like + // this should work with `as WorkboxPluginCallbackParam[C]`. + await callback(param); + } + } + /** + * Accepts a callback and returns an iterable of matching plugin callbacks, + * where each callback is wrapped with the current handler state (i.e. when + * you call each callback, whatever object parameter you pass it will + * be merged with the plugin's current state). + * + * @param {string} name The name fo the callback to run + * @return {Array} + */ + *iterateCallbacks(name) { + for (const plugin of this._strategy.plugins) { + if (typeof plugin[name] === 'function') { + const state = this._pluginStateMap.get(plugin); + const statefulCallback = param => { + const statefulParam = Object.assign(Object.assign({}, param), { + state + }); + // TODO(philipwalton): not sure why `any` is needed. It seems like + // this should work with `as WorkboxPluginCallbackParam[C]`. + return plugin[name](statefulParam); + }; + yield statefulCallback; + } + } + } + /** + * Adds a promise to the + * [extend lifetime promises]{@link https://w3c.github.io/ServiceWorker/#extendableevent-extend-lifetime-promises} + * of the event associated with the request being handled (usually a + * `FetchEvent`). + * + * Note: you can await + * {@link workbox-strategies.StrategyHandler~doneWaiting} + * to know when all added promises have settled. + * + * @param {Promise} promise A promise to add to the extend lifetime promises + * of the event that triggered the request. + */ + waitUntil(promise) { + this._extendLifetimePromises.push(promise); + return promise; + } + /** + * Returns a promise that resolves once all promises passed to + * {@link workbox-strategies.StrategyHandler~waitUntil} + * have settled. + * + * Note: any work done after `doneWaiting()` settles should be manually + * passed to an event's `waitUntil()` method (not this handler's + * `waitUntil()` method), otherwise the service worker thread may be killed + * prior to your work completing. + */ + async doneWaiting() { + while (this._extendLifetimePromises.length) { + const promises = this._extendLifetimePromises.splice(0); + const result = await Promise.allSettled(promises); + const firstRejection = result.find(i => i.status === 'rejected'); + if (firstRejection) { + throw firstRejection.reason; + } + } + } + /** + * Stops running the strategy and immediately resolves any pending + * `waitUntil()` promises. + */ + destroy() { + this._handlerDeferred.resolve(null); + } + /** + * This method will call cacheWillUpdate on the available plugins (or use + * status === 200) to determine if the Response is safe and valid to cache. + * + * @param {Request} options.request + * @param {Response} options.response + * @return {Promise} + * + * @private + */ + async _ensureResponseSafeToCache(response) { + let responseToCache = response; + let pluginsUsed = false; + for (const callback of this.iterateCallbacks('cacheWillUpdate')) { + responseToCache = (await callback({ + request: this.request, + response: responseToCache, + event: this.event + })) || undefined; + pluginsUsed = true; + if (!responseToCache) { + break; + } + } + if (!pluginsUsed) { + if (responseToCache && responseToCache.status !== 200) { + responseToCache = undefined; + } + { + if (responseToCache) { + if (responseToCache.status !== 200) { + if (responseToCache.status === 0) { + logger_js.logger.warn(`The response for '${this.request.url}' ` + `is an opaque response. The caching strategy that you're ` + `using will not cache opaque responses by default.`); + } else { + logger_js.logger.debug(`The response for '${this.request.url}' ` + `returned a status code of '${response.status}' and won't ` + `be cached as a result.`); + } + } + } + } + } + return responseToCache; + } + } + + /* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * An abstract base class that all other strategy classes must extend from: + * + * @memberof workbox-strategies + */ + class Strategy { + /** + * Creates a new instance of the strategy and sets all documented option + * properties as public instance properties. + * + * Note: if a custom strategy class extends the base Strategy class and does + * not need more than these properties, it does not need to define its own + * constructor. + * + * @param {Object} [options] + * @param {string} [options.cacheName] Cache name to store and retrieve + * requests. Defaults to the cache names provided by + * {@link workbox-core.cacheNames}. + * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins} + * to use in conjunction with this caching strategy. + * @param {Object} [options.fetchOptions] Values passed along to the + * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) + * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796) + * `fetch()` requests made by this strategy. + * @param {Object} [options.matchOptions] The + * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions} + * for any `cache.match()` or `cache.put()` calls made by this strategy. + */ + constructor(options = {}) { + /** + * Cache name to store and retrieve + * requests. Defaults to the cache names provided by + * {@link workbox-core.cacheNames}. + * + * @type {string} + */ + this.cacheName = cacheNames_js.cacheNames.getRuntimeName(options.cacheName); + /** + * The list + * [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins} + * used by this strategy. + * + * @type {Array} + */ + this.plugins = options.plugins || []; + /** + * Values passed along to the + * [`init`]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters} + * of all fetch() requests made by this strategy. + * + * @type {Object} + */ + this.fetchOptions = options.fetchOptions; + /** + * The + * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions} + * for any `cache.match()` or `cache.put()` calls made by this strategy. + * + * @type {Object} + */ + this.matchOptions = options.matchOptions; + } + /** + * Perform a request strategy and returns a `Promise` that will resolve with + * a `Response`, invoking all relevant plugin callbacks. + * + * When a strategy instance is registered with a Workbox + * {@link workbox-routing.Route}, this method is automatically + * called when the route matches. + * + * Alternatively, this method can be used in a standalone `FetchEvent` + * listener by passing it to `event.respondWith()`. + * + * @param {FetchEvent|Object} options A `FetchEvent` or an object with the + * properties listed below. + * @param {Request|string} options.request A request to run this strategy for. + * @param {ExtendableEvent} options.event The event associated with the + * request. + * @param {URL} [options.url] + * @param {*} [options.params] + */ + handle(options) { + const [responseDone] = this.handleAll(options); + return responseDone; + } + /** + * Similar to {@link workbox-strategies.Strategy~handle}, but + * instead of just returning a `Promise` that resolves to a `Response` it + * it will return an tuple of `[response, done]` promises, where the former + * (`response`) is equivalent to what `handle()` returns, and the latter is a + * Promise that will resolve once any promises that were added to + * `event.waitUntil()` as part of performing the strategy have completed. + * + * You can await the `done` promise to ensure any extra work performed by + * the strategy (usually caching responses) completes successfully. + * + * @param {FetchEvent|Object} options A `FetchEvent` or an object with the + * properties listed below. + * @param {Request|string} options.request A request to run this strategy for. + * @param {ExtendableEvent} options.event The event associated with the + * request. + * @param {URL} [options.url] + * @param {*} [options.params] + * @return {Array} A tuple of [response, done] + * promises that can be used to determine when the response resolves as + * well as when the handler has completed all its work. + */ + handleAll(options) { + // Allow for flexible options to be passed. + if (options instanceof FetchEvent) { + options = { + event: options, + request: options.request + }; + } + const event = options.event; + const request = typeof options.request === 'string' ? new Request(options.request) : options.request; + const params = 'params' in options ? options.params : undefined; + const handler = new StrategyHandler(this, { + event, + request, + params + }); + const responseDone = this._getResponse(handler, request, event); + const handlerDone = this._awaitComplete(responseDone, handler, request, event); + // Return an array of promises, suitable for use with Promise.all(). + return [responseDone, handlerDone]; + } + async _getResponse(handler, request, event) { + await handler.runCallbacks('handlerWillStart', { + event, + request + }); + let response = undefined; + try { + response = await this._handle(request, handler); + // The "official" Strategy subclasses all throw this error automatically, + // but in case a third-party Strategy doesn't, ensure that we have a + // consistent failure when there's no response or an error response. + if (!response || response.type === 'error') { + throw new WorkboxError_js.WorkboxError('no-response', { + url: request.url + }); + } + } catch (error) { + if (error instanceof Error) { + for (const callback of handler.iterateCallbacks('handlerDidError')) { + response = await callback({ + error, + event, + request + }); + if (response) { + break; + } + } + } + if (!response) { + throw error; + } else { + logger_js.logger.log(`While responding to '${getFriendlyURL_js.getFriendlyURL(request.url)}', ` + `an ${error instanceof Error ? error.toString() : ''} error occurred. Using a fallback response provided by ` + `a handlerDidError plugin.`); + } + } + for (const callback of handler.iterateCallbacks('handlerWillRespond')) { + response = await callback({ + event, + request, + response + }); + } + return response; + } + async _awaitComplete(responseDone, handler, request, event) { + let response; + let error; + try { + response = await responseDone; + } catch (error) { + // Ignore errors, as response errors should be caught via the `response` + // promise above. The `done` promise will only throw for errors in + // promises passed to `handler.waitUntil()`. + } + try { + await handler.runCallbacks('handlerDidRespond', { + event, + request, + response + }); + await handler.doneWaiting(); + } catch (waitUntilError) { + if (waitUntilError instanceof Error) { + error = waitUntilError; + } + } + await handler.runCallbacks('handlerDidComplete', { + event, + request, + response, + error: error + }); + handler.destroy(); + if (error) { + throw error; + } + } + } + /** + * Classes extending the `Strategy` based class should implement this method, + * and leverage the {@link workbox-strategies.StrategyHandler} + * arg to perform all fetching and cache logic, which will ensure all relevant + * cache, cache options, fetch options and plugins are used (per the current + * strategy instance). + * + * @name _handle + * @instance + * @abstract + * @function + * @param {Request} request + * @param {workbox-strategies.StrategyHandler} handler + * @return {Promise} + * + * @memberof workbox-strategies.Strategy + */ + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + const messages = { + strategyStart: (strategyName, request) => `Using ${strategyName} to respond to '${getFriendlyURL_js.getFriendlyURL(request.url)}'`, + printFinalResponse: response => { + if (response) { + logger_js.logger.groupCollapsed(`View the final response here.`); + logger_js.logger.log(response || '[No response returned]'); + logger_js.logger.groupEnd(); + } + } + }; + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * An implementation of a [cache-first](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#cache-first-falling-back-to-network) + * request strategy. + * + * A cache first strategy is useful for assets that have been revisioned, + * such as URLs like `/styles/example.a8f5f1.css`, since they + * can be cached for long periods of time. + * + * If the network request fails, and there is no cache match, this will throw + * a `WorkboxError` exception. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-strategies + */ + class CacheFirst extends Strategy { + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + async _handle(request, handler) { + const logs = []; + { + assert_js.assert.isInstance(request, Request, { + moduleName: 'workbox-strategies', + className: this.constructor.name, + funcName: 'makeRequest', + paramName: 'request' + }); + } + let response = await handler.cacheMatch(request); + let error = undefined; + if (!response) { + { + logs.push(`No response found in the '${this.cacheName}' cache. ` + `Will respond with a network request.`); + } + try { + response = await handler.fetchAndCachePut(request); + } catch (err) { + if (err instanceof Error) { + error = err; + } + } + { + if (response) { + logs.push(`Got response from network.`); + } else { + logs.push(`Unable to get a response from the network.`); + } + } + } else { + { + logs.push(`Found a cached response in the '${this.cacheName}' cache.`); + } + } + { + logger_js.logger.groupCollapsed(messages.strategyStart(this.constructor.name, request)); + for (const log of logs) { + logger_js.logger.log(log); + } + messages.printFinalResponse(response); + logger_js.logger.groupEnd(); + } + if (!response) { + throw new WorkboxError_js.WorkboxError('no-response', { + url: request.url, + error + }); + } + return response; + } + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * An implementation of a [cache-only](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#cache-only) + * request strategy. + * + * This class is useful if you want to take advantage of any + * [Workbox plugins](https://developer.chrome.com/docs/workbox/using-plugins/). + * + * If there is no cache match, this will throw a `WorkboxError` exception. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-strategies + */ + class CacheOnly extends Strategy { + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + async _handle(request, handler) { + { + assert_js.assert.isInstance(request, Request, { + moduleName: 'workbox-strategies', + className: this.constructor.name, + funcName: 'makeRequest', + paramName: 'request' + }); + } + const response = await handler.cacheMatch(request); + { + logger_js.logger.groupCollapsed(messages.strategyStart(this.constructor.name, request)); + if (response) { + logger_js.logger.log(`Found a cached response in the '${this.cacheName}' ` + `cache.`); + messages.printFinalResponse(response); + } else { + logger_js.logger.log(`No response found in the '${this.cacheName}' cache.`); + } + logger_js.logger.groupEnd(); + } + if (!response) { + throw new WorkboxError_js.WorkboxError('no-response', { + url: request.url + }); + } + return response; + } + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + const cacheOkAndOpaquePlugin = { + /** + * Returns a valid response (to allow caching) if the status is 200 (OK) or + * 0 (opaque). + * + * @param {Object} options + * @param {Response} options.response + * @return {Response|null} + * + * @private + */ + cacheWillUpdate: async ({ + response + }) => { + if (response.status === 200 || response.status === 0) { + return response; + } + return null; + } + }; + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * An implementation of a + * [network first](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#network-first-falling-back-to-cache) + * request strategy. + * + * By default, this strategy will cache responses with a 200 status code as + * well as [opaque responses](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses). + * Opaque responses are are cross-origin requests where the response doesn't + * support [CORS](https://enable-cors.org/). + * + * If the network request fails, and there is no cache match, this will throw + * a `WorkboxError` exception. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-strategies + */ + class NetworkFirst extends Strategy { + /** + * @param {Object} [options] + * @param {string} [options.cacheName] Cache name to store and retrieve + * requests. Defaults to cache names provided by + * {@link workbox-core.cacheNames}. + * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins} + * to use in conjunction with this caching strategy. + * @param {Object} [options.fetchOptions] Values passed along to the + * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) + * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796) + * `fetch()` requests made by this strategy. + * @param {Object} [options.matchOptions] [`CacheQueryOptions`](https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions) + * @param {number} [options.networkTimeoutSeconds] If set, any network requests + * that fail to respond within the timeout will fallback to the cache. + * + * This option can be used to combat + * "[lie-fi]{@link https://developers.google.com/web/fundamentals/performance/poor-connectivity/#lie-fi}" + * scenarios. + */ + constructor(options = {}) { + super(options); + // If this instance contains no plugins with a 'cacheWillUpdate' callback, + // prepend the `cacheOkAndOpaquePlugin` plugin to the plugins list. + if (!this.plugins.some(p => 'cacheWillUpdate' in p)) { + this.plugins.unshift(cacheOkAndOpaquePlugin); + } + this._networkTimeoutSeconds = options.networkTimeoutSeconds || 0; + { + if (this._networkTimeoutSeconds) { + assert_js.assert.isType(this._networkTimeoutSeconds, 'number', { + moduleName: 'workbox-strategies', + className: this.constructor.name, + funcName: 'constructor', + paramName: 'networkTimeoutSeconds' + }); + } + } + } + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + async _handle(request, handler) { + const logs = []; + { + assert_js.assert.isInstance(request, Request, { + moduleName: 'workbox-strategies', + className: this.constructor.name, + funcName: 'handle', + paramName: 'makeRequest' + }); + } + const promises = []; + let timeoutId; + if (this._networkTimeoutSeconds) { + const { + id, + promise + } = this._getTimeoutPromise({ + request, + logs, + handler + }); + timeoutId = id; + promises.push(promise); + } + const networkPromise = this._getNetworkPromise({ + timeoutId, + request, + logs, + handler + }); + promises.push(networkPromise); + const response = await handler.waitUntil((async () => { + // Promise.race() will resolve as soon as the first promise resolves. + return (await handler.waitUntil(Promise.race(promises))) || ( + // If Promise.race() resolved with null, it might be due to a network + // timeout + a cache miss. If that were to happen, we'd rather wait until + // the networkPromise resolves instead of returning null. + // Note that it's fine to await an already-resolved promise, so we don't + // have to check to see if it's still "in flight". + await networkPromise); + })()); + { + logger_js.logger.groupCollapsed(messages.strategyStart(this.constructor.name, request)); + for (const log of logs) { + logger_js.logger.log(log); + } + messages.printFinalResponse(response); + logger_js.logger.groupEnd(); + } + if (!response) { + throw new WorkboxError_js.WorkboxError('no-response', { + url: request.url + }); + } + return response; + } + /** + * @param {Object} options + * @param {Request} options.request + * @param {Array} options.logs A reference to the logs array + * @param {Event} options.event + * @return {Promise} + * + * @private + */ + _getTimeoutPromise({ + request, + logs, + handler + }) { + let timeoutId; + const timeoutPromise = new Promise(resolve => { + const onNetworkTimeout = async () => { + { + logs.push(`Timing out the network response at ` + `${this._networkTimeoutSeconds} seconds.`); + } + resolve(await handler.cacheMatch(request)); + }; + timeoutId = setTimeout(onNetworkTimeout, this._networkTimeoutSeconds * 1000); + }); + return { + promise: timeoutPromise, + id: timeoutId + }; + } + /** + * @param {Object} options + * @param {number|undefined} options.timeoutId + * @param {Request} options.request + * @param {Array} options.logs A reference to the logs Array. + * @param {Event} options.event + * @return {Promise} + * + * @private + */ + async _getNetworkPromise({ + timeoutId, + request, + logs, + handler + }) { + let error; + let response; + try { + response = await handler.fetchAndCachePut(request); + } catch (fetchError) { + if (fetchError instanceof Error) { + error = fetchError; + } + } + if (timeoutId) { + clearTimeout(timeoutId); + } + { + if (response) { + logs.push(`Got response from network.`); + } else { + logs.push(`Unable to get a response from the network. Will respond ` + `with a cached response.`); + } + } + if (error || !response) { + response = await handler.cacheMatch(request); + { + if (response) { + logs.push(`Found a cached response in the '${this.cacheName}'` + ` cache.`); + } else { + logs.push(`No response found in the '${this.cacheName}' cache.`); + } + } + } + return response; + } + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * An implementation of a + * [network-only](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#network-only) + * request strategy. + * + * This class is useful if you want to take advantage of any + * [Workbox plugins](https://developer.chrome.com/docs/workbox/using-plugins/). + * + * If the network request fails, this will throw a `WorkboxError` exception. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-strategies + */ + class NetworkOnly extends Strategy { + /** + * @param {Object} [options] + * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins} + * to use in conjunction with this caching strategy. + * @param {Object} [options.fetchOptions] Values passed along to the + * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) + * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796) + * `fetch()` requests made by this strategy. + * @param {number} [options.networkTimeoutSeconds] If set, any network requests + * that fail to respond within the timeout will result in a network error. + */ + constructor(options = {}) { + super(options); + this._networkTimeoutSeconds = options.networkTimeoutSeconds || 0; + } + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + async _handle(request, handler) { + { + assert_js.assert.isInstance(request, Request, { + moduleName: 'workbox-strategies', + className: this.constructor.name, + funcName: '_handle', + paramName: 'request' + }); + } + let error = undefined; + let response; + try { + const promises = [handler.fetch(request)]; + if (this._networkTimeoutSeconds) { + const timeoutPromise = timeout_js.timeout(this._networkTimeoutSeconds * 1000); + promises.push(timeoutPromise); + } + response = await Promise.race(promises); + if (!response) { + throw new Error(`Timed out the network response after ` + `${this._networkTimeoutSeconds} seconds.`); + } + } catch (err) { + if (err instanceof Error) { + error = err; + } + } + { + logger_js.logger.groupCollapsed(messages.strategyStart(this.constructor.name, request)); + if (response) { + logger_js.logger.log(`Got response from network.`); + } else { + logger_js.logger.log(`Unable to get a response from the network.`); + } + messages.printFinalResponse(response); + logger_js.logger.groupEnd(); + } + if (!response) { + throw new WorkboxError_js.WorkboxError('no-response', { + url: request.url, + error + }); + } + return response; + } + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * An implementation of a + * [stale-while-revalidate](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#stale-while-revalidate) + * request strategy. + * + * Resources are requested from both the cache and the network in parallel. + * The strategy will respond with the cached version if available, otherwise + * wait for the network response. The cache is updated with the network response + * with each successful request. + * + * By default, this strategy will cache responses with a 200 status code as + * well as [opaque responses](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses). + * Opaque responses are cross-origin requests where the response doesn't + * support [CORS](https://enable-cors.org/). + * + * If the network request fails, and there is no cache match, this will throw + * a `WorkboxError` exception. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-strategies + */ + class StaleWhileRevalidate extends Strategy { + /** + * @param {Object} [options] + * @param {string} [options.cacheName] Cache name to store and retrieve + * requests. Defaults to cache names provided by + * {@link workbox-core.cacheNames}. + * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins} + * to use in conjunction with this caching strategy. + * @param {Object} [options.fetchOptions] Values passed along to the + * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) + * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796) + * `fetch()` requests made by this strategy. + * @param {Object} [options.matchOptions] [`CacheQueryOptions`](https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions) + */ + constructor(options = {}) { + super(options); + // If this instance contains no plugins with a 'cacheWillUpdate' callback, + // prepend the `cacheOkAndOpaquePlugin` plugin to the plugins list. + if (!this.plugins.some(p => 'cacheWillUpdate' in p)) { + this.plugins.unshift(cacheOkAndOpaquePlugin); + } + } + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + async _handle(request, handler) { + const logs = []; + { + assert_js.assert.isInstance(request, Request, { + moduleName: 'workbox-strategies', + className: this.constructor.name, + funcName: 'handle', + paramName: 'request' + }); + } + const fetchAndCachePromise = handler.fetchAndCachePut(request).catch(() => { + // Swallow this error because a 'no-response' error will be thrown in + // main handler return flow. This will be in the `waitUntil()` flow. + }); + void handler.waitUntil(fetchAndCachePromise); + let response = await handler.cacheMatch(request); + let error; + if (response) { + { + logs.push(`Found a cached response in the '${this.cacheName}'` + ` cache. Will update with the network response in the background.`); + } + } else { + { + logs.push(`No response found in the '${this.cacheName}' cache. ` + `Will wait for the network response.`); + } + try { + // NOTE(philipwalton): Really annoying that we have to type cast here. + // https://github.com/microsoft/TypeScript/issues/20006 + response = await fetchAndCachePromise; + } catch (err) { + if (err instanceof Error) { + error = err; + } + } + } + { + logger_js.logger.groupCollapsed(messages.strategyStart(this.constructor.name, request)); + for (const log of logs) { + logger_js.logger.log(log); + } + messages.printFinalResponse(response); + logger_js.logger.groupEnd(); + } + if (!response) { + throw new WorkboxError_js.WorkboxError('no-response', { + url: request.url, + error + }); + } + return response; + } + } + + exports.CacheFirst = CacheFirst; + exports.CacheOnly = CacheOnly; + exports.NetworkFirst = NetworkFirst; + exports.NetworkOnly = NetworkOnly; + exports.StaleWhileRevalidate = StaleWhileRevalidate; + exports.Strategy = Strategy; + exports.StrategyHandler = StrategyHandler; + + return exports; + +})({}, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private); +//# sourceMappingURL=workbox-strategies.dev.js.map diff --git a/node_modules/workbox-strategies/build/workbox-strategies.dev.js.map b/node_modules/workbox-strategies/build/workbox-strategies.dev.js.map new file mode 100644 index 0000000000000000000000000000000000000000..1d891dcb0fce5419417d6926a991e5a6b3286be5 --- /dev/null +++ b/node_modules/workbox-strategies/build/workbox-strategies.dev.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-strategies.dev.js","sources":["../_version.js","../StrategyHandler.js","../Strategy.js","../utils/messages.js","../CacheFirst.js","../CacheOnly.js","../plugins/cacheOkAndOpaquePlugin.js","../NetworkFirst.js","../NetworkOnly.js","../StaleWhileRevalidate.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:strategies:7.4.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2020 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 { cacheMatchIgnoreParams } from 'workbox-core/_private/cacheMatchIgnoreParams.js';\nimport { Deferred } from 'workbox-core/_private/Deferred.js';\nimport { executeQuotaErrorCallbacks } from 'workbox-core/_private/executeQuotaErrorCallbacks.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { timeout } from 'workbox-core/_private/timeout.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport './_version.js';\nfunction toRequest(input) {\n return typeof input === 'string' ? new Request(input) : input;\n}\n/**\n * A class created every time a Strategy instance calls\n * {@link workbox-strategies.Strategy~handle} or\n * {@link workbox-strategies.Strategy~handleAll} that wraps all fetch and\n * cache actions around plugin callbacks and keeps track of when the strategy\n * is \"done\" (i.e. all added `event.waitUntil()` promises have resolved).\n *\n * @memberof workbox-strategies\n */\nclass StrategyHandler {\n /**\n * Creates a new instance associated with the passed strategy and event\n * that's handling the request.\n *\n * The constructor also initializes the state that will be passed to each of\n * the plugins handling this request.\n *\n * @param {workbox-strategies.Strategy} strategy\n * @param {Object} options\n * @param {Request|string} options.request A request to run this strategy for.\n * @param {ExtendableEvent} options.event The event associated with the\n * request.\n * @param {URL} [options.url]\n * @param {*} [options.params] The return value from the\n * {@link workbox-routing~matchCallback} (if applicable).\n */\n constructor(strategy, options) {\n this._cacheKeys = {};\n /**\n * The request the strategy is performing (passed to the strategy's\n * `handle()` or `handleAll()` method).\n * @name request\n * @instance\n * @type {Request}\n * @memberof workbox-strategies.StrategyHandler\n */\n /**\n * The event associated with this request.\n * @name event\n * @instance\n * @type {ExtendableEvent}\n * @memberof workbox-strategies.StrategyHandler\n */\n /**\n * A `URL` instance of `request.url` (if passed to the strategy's\n * `handle()` or `handleAll()` method).\n * Note: the `url` param will be present if the strategy was invoked\n * from a workbox `Route` object.\n * @name url\n * @instance\n * @type {URL|undefined}\n * @memberof workbox-strategies.StrategyHandler\n */\n /**\n * A `param` value (if passed to the strategy's\n * `handle()` or `handleAll()` method).\n * Note: the `param` param will be present if the strategy was invoked\n * from a workbox `Route` object and the\n * {@link workbox-routing~matchCallback} returned\n * a truthy value (it will be that value).\n * @name params\n * @instance\n * @type {*|undefined}\n * @memberof workbox-strategies.StrategyHandler\n */\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(options.event, ExtendableEvent, {\n moduleName: 'workbox-strategies',\n className: 'StrategyHandler',\n funcName: 'constructor',\n paramName: 'options.event',\n });\n }\n Object.assign(this, options);\n this.event = options.event;\n this._strategy = strategy;\n this._handlerDeferred = new Deferred();\n this._extendLifetimePromises = [];\n // Copy the plugins list (since it's mutable on the strategy),\n // so any mutations don't affect this handler instance.\n this._plugins = [...strategy.plugins];\n this._pluginStateMap = new Map();\n for (const plugin of this._plugins) {\n this._pluginStateMap.set(plugin, {});\n }\n this.event.waitUntil(this._handlerDeferred.promise);\n }\n /**\n * Fetches a given request (and invokes any applicable plugin callback\n * methods) using the `fetchOptions` (for non-navigation requests) and\n * `plugins` defined on the `Strategy` object.\n *\n * The following plugin lifecycle methods are invoked when using this method:\n * - `requestWillFetch()`\n * - `fetchDidSucceed()`\n * - `fetchDidFail()`\n *\n * @param {Request|string} input The URL or request to fetch.\n * @return {Promise}\n */\n async fetch(input) {\n const { event } = this;\n let request = toRequest(input);\n if (request.mode === 'navigate' &&\n event instanceof FetchEvent &&\n event.preloadResponse) {\n const possiblePreloadResponse = (await event.preloadResponse);\n if (possiblePreloadResponse) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Using a preloaded navigation response for ` +\n `'${getFriendlyURL(request.url)}'`);\n }\n return possiblePreloadResponse;\n }\n }\n // If there is a fetchDidFail plugin, we need to save a clone of the\n // original request before it's either modified by a requestWillFetch\n // plugin or before the original request's body is consumed via fetch().\n const originalRequest = this.hasCallback('fetchDidFail')\n ? request.clone()\n : null;\n try {\n for (const cb of this.iterateCallbacks('requestWillFetch')) {\n request = await cb({ request: request.clone(), event });\n }\n }\n catch (err) {\n if (err instanceof Error) {\n throw new WorkboxError('plugin-error-request-will-fetch', {\n thrownErrorMessage: err.message,\n });\n }\n }\n // The request can be altered by plugins with `requestWillFetch` making\n // the original request (most likely from a `fetch` event) different\n // from the Request we make. Pass both to `fetchDidFail` to aid debugging.\n const pluginFilteredRequest = request.clone();\n try {\n let fetchResponse;\n // See https://github.com/GoogleChrome/workbox/issues/1796\n fetchResponse = await fetch(request, request.mode === 'navigate' ? undefined : this._strategy.fetchOptions);\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`Network request for ` +\n `'${getFriendlyURL(request.url)}' returned a response with ` +\n `status '${fetchResponse.status}'.`);\n }\n for (const callback of this.iterateCallbacks('fetchDidSucceed')) {\n fetchResponse = await callback({\n event,\n request: pluginFilteredRequest,\n response: fetchResponse,\n });\n }\n return fetchResponse;\n }\n catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Network request for ` +\n `'${getFriendlyURL(request.url)}' threw an error.`, error);\n }\n // `originalRequest` will only exist if a `fetchDidFail` callback\n // is being used (see above).\n if (originalRequest) {\n await this.runCallbacks('fetchDidFail', {\n error: error,\n event,\n originalRequest: originalRequest.clone(),\n request: pluginFilteredRequest.clone(),\n });\n }\n throw error;\n }\n }\n /**\n * Calls `this.fetch()` and (in the background) runs `this.cachePut()` on\n * the response generated by `this.fetch()`.\n *\n * The call to `this.cachePut()` automatically invokes `this.waitUntil()`,\n * so you do not have to manually call `waitUntil()` on the event.\n *\n * @param {Request|string} input The request or URL to fetch and cache.\n * @return {Promise}\n */\n async fetchAndCachePut(input) {\n const response = await this.fetch(input);\n const responseClone = response.clone();\n void this.waitUntil(this.cachePut(input, responseClone));\n return response;\n }\n /**\n * Matches a request from the cache (and invokes any applicable plugin\n * callback methods) using the `cacheName`, `matchOptions`, and `plugins`\n * defined on the strategy object.\n *\n * The following plugin lifecycle methods are invoked when using this method:\n * - cacheKeyWillBeUsed()\n * - cachedResponseWillBeUsed()\n *\n * @param {Request|string} key The Request or URL to use as the cache key.\n * @return {Promise} A matching response, if found.\n */\n async cacheMatch(key) {\n const request = toRequest(key);\n let cachedResponse;\n const { cacheName, matchOptions } = this._strategy;\n const effectiveRequest = await this.getCacheKey(request, 'read');\n const multiMatchOptions = Object.assign(Object.assign({}, matchOptions), { cacheName });\n cachedResponse = await caches.match(effectiveRequest, multiMatchOptions);\n if (process.env.NODE_ENV !== 'production') {\n if (cachedResponse) {\n logger.debug(`Found a cached response in '${cacheName}'.`);\n }\n else {\n logger.debug(`No cached response found in '${cacheName}'.`);\n }\n }\n for (const callback of this.iterateCallbacks('cachedResponseWillBeUsed')) {\n cachedResponse =\n (await callback({\n cacheName,\n matchOptions,\n cachedResponse,\n request: effectiveRequest,\n event: this.event,\n })) || undefined;\n }\n return cachedResponse;\n }\n /**\n * Puts a request/response pair in the cache (and invokes any applicable\n * plugin callback methods) using the `cacheName` and `plugins` defined on\n * the strategy object.\n *\n * The following plugin lifecycle methods are invoked when using this method:\n * - cacheKeyWillBeUsed()\n * - cacheWillUpdate()\n * - cacheDidUpdate()\n *\n * @param {Request|string} key The request or URL to use as the cache key.\n * @param {Response} response The response to cache.\n * @return {Promise} `false` if a cacheWillUpdate caused the response\n * not be cached, and `true` otherwise.\n */\n async cachePut(key, response) {\n const request = toRequest(key);\n // Run in the next task to avoid blocking other cache reads.\n // https://github.com/w3c/ServiceWorker/issues/1397\n await timeout(0);\n const effectiveRequest = await this.getCacheKey(request, 'write');\n if (process.env.NODE_ENV !== 'production') {\n if (effectiveRequest.method && effectiveRequest.method !== 'GET') {\n throw new WorkboxError('attempt-to-cache-non-get-request', {\n url: getFriendlyURL(effectiveRequest.url),\n method: effectiveRequest.method,\n });\n }\n // See https://github.com/GoogleChrome/workbox/issues/2818\n const vary = response.headers.get('Vary');\n if (vary) {\n logger.debug(`The response for ${getFriendlyURL(effectiveRequest.url)} ` +\n `has a 'Vary: ${vary}' header. ` +\n `Consider setting the {ignoreVary: true} option on your strategy ` +\n `to ensure cache matching and deletion works as expected.`);\n }\n }\n if (!response) {\n if (process.env.NODE_ENV !== 'production') {\n logger.error(`Cannot cache non-existent response for ` +\n `'${getFriendlyURL(effectiveRequest.url)}'.`);\n }\n throw new WorkboxError('cache-put-with-no-response', {\n url: getFriendlyURL(effectiveRequest.url),\n });\n }\n const responseToCache = await this._ensureResponseSafeToCache(response);\n if (!responseToCache) {\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`Response '${getFriendlyURL(effectiveRequest.url)}' ` +\n `will not be cached.`, responseToCache);\n }\n return false;\n }\n const { cacheName, matchOptions } = this._strategy;\n const cache = await self.caches.open(cacheName);\n const hasCacheUpdateCallback = this.hasCallback('cacheDidUpdate');\n const oldResponse = hasCacheUpdateCallback\n ? await cacheMatchIgnoreParams(\n // TODO(philipwalton): the `__WB_REVISION__` param is a precaching\n // feature. Consider into ways to only add this behavior if using\n // precaching.\n cache, effectiveRequest.clone(), ['__WB_REVISION__'], matchOptions)\n : null;\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`Updating the '${cacheName}' cache with a new Response ` +\n `for ${getFriendlyURL(effectiveRequest.url)}.`);\n }\n try {\n await cache.put(effectiveRequest, hasCacheUpdateCallback ? responseToCache.clone() : responseToCache);\n }\n catch (error) {\n if (error instanceof Error) {\n // See https://developer.mozilla.org/en-US/docs/Web/API/DOMException#exception-QuotaExceededError\n if (error.name === 'QuotaExceededError') {\n await executeQuotaErrorCallbacks();\n }\n throw error;\n }\n }\n for (const callback of this.iterateCallbacks('cacheDidUpdate')) {\n await callback({\n cacheName,\n oldResponse,\n newResponse: responseToCache.clone(),\n request: effectiveRequest,\n event: this.event,\n });\n }\n return true;\n }\n /**\n * Checks the list of plugins for the `cacheKeyWillBeUsed` callback, and\n * executes any of those callbacks found in sequence. The final `Request`\n * object returned by the last plugin is treated as the cache key for cache\n * reads and/or writes. If no `cacheKeyWillBeUsed` plugin callbacks have\n * been registered, the passed request is returned unmodified\n *\n * @param {Request} request\n * @param {string} mode\n * @return {Promise}\n */\n async getCacheKey(request, mode) {\n const key = `${request.url} | ${mode}`;\n if (!this._cacheKeys[key]) {\n let effectiveRequest = request;\n for (const callback of this.iterateCallbacks('cacheKeyWillBeUsed')) {\n effectiveRequest = toRequest(await callback({\n mode,\n request: effectiveRequest,\n event: this.event,\n // params has a type any can't change right now.\n params: this.params, // eslint-disable-line\n }));\n }\n this._cacheKeys[key] = effectiveRequest;\n }\n return this._cacheKeys[key];\n }\n /**\n * Returns true if the strategy has at least one plugin with the given\n * callback.\n *\n * @param {string} name The name of the callback to check for.\n * @return {boolean}\n */\n hasCallback(name) {\n for (const plugin of this._strategy.plugins) {\n if (name in plugin) {\n return true;\n }\n }\n return false;\n }\n /**\n * Runs all plugin callbacks matching the given name, in order, passing the\n * given param object (merged ith the current plugin state) as the only\n * argument.\n *\n * Note: since this method runs all plugins, it's not suitable for cases\n * where the return value of a callback needs to be applied prior to calling\n * the next callback. See\n * {@link workbox-strategies.StrategyHandler#iterateCallbacks}\n * below for how to handle that case.\n *\n * @param {string} name The name of the callback to run within each plugin.\n * @param {Object} param The object to pass as the first (and only) param\n * when executing each callback. This object will be merged with the\n * current plugin state prior to callback execution.\n */\n async runCallbacks(name, param) {\n for (const callback of this.iterateCallbacks(name)) {\n // TODO(philipwalton): not sure why `any` is needed. It seems like\n // this should work with `as WorkboxPluginCallbackParam[C]`.\n await callback(param);\n }\n }\n /**\n * Accepts a callback and returns an iterable of matching plugin callbacks,\n * where each callback is wrapped with the current handler state (i.e. when\n * you call each callback, whatever object parameter you pass it will\n * be merged with the plugin's current state).\n *\n * @param {string} name The name fo the callback to run\n * @return {Array}\n */\n *iterateCallbacks(name) {\n for (const plugin of this._strategy.plugins) {\n if (typeof plugin[name] === 'function') {\n const state = this._pluginStateMap.get(plugin);\n const statefulCallback = (param) => {\n const statefulParam = Object.assign(Object.assign({}, param), { state });\n // TODO(philipwalton): not sure why `any` is needed. It seems like\n // this should work with `as WorkboxPluginCallbackParam[C]`.\n return plugin[name](statefulParam);\n };\n yield statefulCallback;\n }\n }\n }\n /**\n * Adds a promise to the\n * [extend lifetime promises]{@link https://w3c.github.io/ServiceWorker/#extendableevent-extend-lifetime-promises}\n * of the event associated with the request being handled (usually a\n * `FetchEvent`).\n *\n * Note: you can await\n * {@link workbox-strategies.StrategyHandler~doneWaiting}\n * to know when all added promises have settled.\n *\n * @param {Promise} promise A promise to add to the extend lifetime promises\n * of the event that triggered the request.\n */\n waitUntil(promise) {\n this._extendLifetimePromises.push(promise);\n return promise;\n }\n /**\n * Returns a promise that resolves once all promises passed to\n * {@link workbox-strategies.StrategyHandler~waitUntil}\n * have settled.\n *\n * Note: any work done after `doneWaiting()` settles should be manually\n * passed to an event's `waitUntil()` method (not this handler's\n * `waitUntil()` method), otherwise the service worker thread may be killed\n * prior to your work completing.\n */\n async doneWaiting() {\n while (this._extendLifetimePromises.length) {\n const promises = this._extendLifetimePromises.splice(0);\n const result = await Promise.allSettled(promises);\n const firstRejection = result.find((i) => i.status === 'rejected');\n if (firstRejection) {\n throw firstRejection.reason;\n }\n }\n }\n /**\n * Stops running the strategy and immediately resolves any pending\n * `waitUntil()` promises.\n */\n destroy() {\n this._handlerDeferred.resolve(null);\n }\n /**\n * This method will call cacheWillUpdate on the available plugins (or use\n * status === 200) to determine if the Response is safe and valid to cache.\n *\n * @param {Request} options.request\n * @param {Response} options.response\n * @return {Promise}\n *\n * @private\n */\n async _ensureResponseSafeToCache(response) {\n let responseToCache = response;\n let pluginsUsed = false;\n for (const callback of this.iterateCallbacks('cacheWillUpdate')) {\n responseToCache =\n (await callback({\n request: this.request,\n response: responseToCache,\n event: this.event,\n })) || undefined;\n pluginsUsed = true;\n if (!responseToCache) {\n break;\n }\n }\n if (!pluginsUsed) {\n if (responseToCache && responseToCache.status !== 200) {\n responseToCache = undefined;\n }\n if (process.env.NODE_ENV !== 'production') {\n if (responseToCache) {\n if (responseToCache.status !== 200) {\n if (responseToCache.status === 0) {\n logger.warn(`The response for '${this.request.url}' ` +\n `is an opaque response. The caching strategy that you're ` +\n `using will not cache opaque responses by default.`);\n }\n else {\n logger.debug(`The response for '${this.request.url}' ` +\n `returned a status code of '${response.status}' and won't ` +\n `be cached as a result.`);\n }\n }\n }\n }\n }\n return responseToCache;\n }\n}\nexport { StrategyHandler };\n","/*\n Copyright 2020 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 { cacheNames } from 'workbox-core/_private/cacheNames.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { StrategyHandler } from './StrategyHandler.js';\nimport './_version.js';\n/**\n * An abstract base class that all other strategy classes must extend from:\n *\n * @memberof workbox-strategies\n */\nclass Strategy {\n /**\n * Creates a new instance of the strategy and sets all documented option\n * properties as public instance properties.\n *\n * Note: if a custom strategy class extends the base Strategy class and does\n * not need more than these properties, it does not need to define its own\n * constructor.\n *\n * @param {Object} [options]\n * @param {string} [options.cacheName] Cache name to store and retrieve\n * requests. Defaults to the cache names provided by\n * {@link workbox-core.cacheNames}.\n * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}\n * to use in conjunction with this caching strategy.\n * @param {Object} [options.fetchOptions] Values passed along to the\n * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)\n * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)\n * `fetch()` requests made by this strategy.\n * @param {Object} [options.matchOptions] The\n * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions}\n * for any `cache.match()` or `cache.put()` calls made by this strategy.\n */\n constructor(options = {}) {\n /**\n * Cache name to store and retrieve\n * requests. Defaults to the cache names provided by\n * {@link workbox-core.cacheNames}.\n *\n * @type {string}\n */\n this.cacheName = cacheNames.getRuntimeName(options.cacheName);\n /**\n * The list\n * [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}\n * used by this strategy.\n *\n * @type {Array}\n */\n this.plugins = options.plugins || [];\n /**\n * Values passed along to the\n * [`init`]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters}\n * of all fetch() requests made by this strategy.\n *\n * @type {Object}\n */\n this.fetchOptions = options.fetchOptions;\n /**\n * The\n * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions}\n * for any `cache.match()` or `cache.put()` calls made by this strategy.\n *\n * @type {Object}\n */\n this.matchOptions = options.matchOptions;\n }\n /**\n * Perform a request strategy and returns a `Promise` that will resolve with\n * a `Response`, invoking all relevant plugin callbacks.\n *\n * When a strategy instance is registered with a Workbox\n * {@link workbox-routing.Route}, this method is automatically\n * called when the route matches.\n *\n * Alternatively, this method can be used in a standalone `FetchEvent`\n * listener by passing it to `event.respondWith()`.\n *\n * @param {FetchEvent|Object} options A `FetchEvent` or an object with the\n * properties listed below.\n * @param {Request|string} options.request A request to run this strategy for.\n * @param {ExtendableEvent} options.event The event associated with the\n * request.\n * @param {URL} [options.url]\n * @param {*} [options.params]\n */\n handle(options) {\n const [responseDone] = this.handleAll(options);\n return responseDone;\n }\n /**\n * Similar to {@link workbox-strategies.Strategy~handle}, but\n * instead of just returning a `Promise` that resolves to a `Response` it\n * it will return an tuple of `[response, done]` promises, where the former\n * (`response`) is equivalent to what `handle()` returns, and the latter is a\n * Promise that will resolve once any promises that were added to\n * `event.waitUntil()` as part of performing the strategy have completed.\n *\n * You can await the `done` promise to ensure any extra work performed by\n * the strategy (usually caching responses) completes successfully.\n *\n * @param {FetchEvent|Object} options A `FetchEvent` or an object with the\n * properties listed below.\n * @param {Request|string} options.request A request to run this strategy for.\n * @param {ExtendableEvent} options.event The event associated with the\n * request.\n * @param {URL} [options.url]\n * @param {*} [options.params]\n * @return {Array} A tuple of [response, done]\n * promises that can be used to determine when the response resolves as\n * well as when the handler has completed all its work.\n */\n handleAll(options) {\n // Allow for flexible options to be passed.\n if (options instanceof FetchEvent) {\n options = {\n event: options,\n request: options.request,\n };\n }\n const event = options.event;\n const request = typeof options.request === 'string'\n ? new Request(options.request)\n : options.request;\n const params = 'params' in options ? options.params : undefined;\n const handler = new StrategyHandler(this, { event, request, params });\n const responseDone = this._getResponse(handler, request, event);\n const handlerDone = this._awaitComplete(responseDone, handler, request, event);\n // Return an array of promises, suitable for use with Promise.all().\n return [responseDone, handlerDone];\n }\n async _getResponse(handler, request, event) {\n await handler.runCallbacks('handlerWillStart', { event, request });\n let response = undefined;\n try {\n response = await this._handle(request, handler);\n // The \"official\" Strategy subclasses all throw this error automatically,\n // but in case a third-party Strategy doesn't, ensure that we have a\n // consistent failure when there's no response or an error response.\n if (!response || response.type === 'error') {\n throw new WorkboxError('no-response', { url: request.url });\n }\n }\n catch (error) {\n if (error instanceof Error) {\n for (const callback of handler.iterateCallbacks('handlerDidError')) {\n response = await callback({ error, event, request });\n if (response) {\n break;\n }\n }\n }\n if (!response) {\n throw error;\n }\n else if (process.env.NODE_ENV !== 'production') {\n logger.log(`While responding to '${getFriendlyURL(request.url)}', ` +\n `an ${error instanceof Error ? error.toString() : ''} error occurred. Using a fallback response provided by ` +\n `a handlerDidError plugin.`);\n }\n }\n for (const callback of handler.iterateCallbacks('handlerWillRespond')) {\n response = await callback({ event, request, response });\n }\n return response;\n }\n async _awaitComplete(responseDone, handler, request, event) {\n let response;\n let error;\n try {\n response = await responseDone;\n }\n catch (error) {\n // Ignore errors, as response errors should be caught via the `response`\n // promise above. The `done` promise will only throw for errors in\n // promises passed to `handler.waitUntil()`.\n }\n try {\n await handler.runCallbacks('handlerDidRespond', {\n event,\n request,\n response,\n });\n await handler.doneWaiting();\n }\n catch (waitUntilError) {\n if (waitUntilError instanceof Error) {\n error = waitUntilError;\n }\n }\n await handler.runCallbacks('handlerDidComplete', {\n event,\n request,\n response,\n error: error,\n });\n handler.destroy();\n if (error) {\n throw error;\n }\n }\n}\nexport { Strategy };\n/**\n * Classes extending the `Strategy` based class should implement this method,\n * and leverage the {@link workbox-strategies.StrategyHandler}\n * arg to perform all fetching and cache logic, which will ensure all relevant\n * cache, cache options, fetch options and plugins are used (per the current\n * strategy instance).\n *\n * @name _handle\n * @instance\n * @abstract\n * @function\n * @param {Request} request\n * @param {workbox-strategies.StrategyHandler} handler\n * @return {Promise}\n *\n * @memberof workbox-strategies.Strategy\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 { logger } from 'workbox-core/_private/logger.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport '../_version.js';\nexport const messages = {\n strategyStart: (strategyName, request) => `Using ${strategyName} to respond to '${getFriendlyURL(request.url)}'`,\n printFinalResponse: (response) => {\n if (response) {\n logger.groupCollapsed(`View the final response here.`);\n logger.log(response || '[No response returned]');\n logger.groupEnd();\n }\n },\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 { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { Strategy } from './Strategy.js';\nimport { messages } from './utils/messages.js';\nimport './_version.js';\n/**\n * An implementation of a [cache-first](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#cache-first-falling-back-to-network)\n * request strategy.\n *\n * A cache first strategy is useful for assets that have been revisioned,\n * such as URLs like `/styles/example.a8f5f1.css`, since they\n * can be cached for long periods of time.\n *\n * If the network request fails, and there is no cache match, this will throw\n * a `WorkboxError` exception.\n *\n * @extends workbox-strategies.Strategy\n * @memberof workbox-strategies\n */\nclass CacheFirst extends Strategy {\n /**\n * @private\n * @param {Request|string} request A request to run this strategy for.\n * @param {workbox-strategies.StrategyHandler} handler The event that\n * triggered the request.\n * @return {Promise}\n */\n async _handle(request, handler) {\n const logs = [];\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(request, Request, {\n moduleName: 'workbox-strategies',\n className: this.constructor.name,\n funcName: 'makeRequest',\n paramName: 'request',\n });\n }\n let response = await handler.cacheMatch(request);\n let error = undefined;\n if (!response) {\n if (process.env.NODE_ENV !== 'production') {\n logs.push(`No response found in the '${this.cacheName}' cache. ` +\n `Will respond with a network request.`);\n }\n try {\n response = await handler.fetchAndCachePut(request);\n }\n catch (err) {\n if (err instanceof Error) {\n error = err;\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n if (response) {\n logs.push(`Got response from network.`);\n }\n else {\n logs.push(`Unable to get a response from the network.`);\n }\n }\n }\n else {\n if (process.env.NODE_ENV !== 'production') {\n logs.push(`Found a cached response in the '${this.cacheName}' cache.`);\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));\n for (const log of logs) {\n logger.log(log);\n }\n messages.printFinalResponse(response);\n logger.groupEnd();\n }\n if (!response) {\n throw new WorkboxError('no-response', { url: request.url, error });\n }\n return response;\n }\n}\nexport { CacheFirst };\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 { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { Strategy } from './Strategy.js';\nimport { messages } from './utils/messages.js';\nimport './_version.js';\n/**\n * An implementation of a [cache-only](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#cache-only)\n * request strategy.\n *\n * This class is useful if you want to take advantage of any\n * [Workbox plugins](https://developer.chrome.com/docs/workbox/using-plugins/).\n *\n * If there is no cache match, this will throw a `WorkboxError` exception.\n *\n * @extends workbox-strategies.Strategy\n * @memberof workbox-strategies\n */\nclass CacheOnly extends Strategy {\n /**\n * @private\n * @param {Request|string} request A request to run this strategy for.\n * @param {workbox-strategies.StrategyHandler} handler The event that\n * triggered the request.\n * @return {Promise}\n */\n async _handle(request, handler) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(request, Request, {\n moduleName: 'workbox-strategies',\n className: this.constructor.name,\n funcName: 'makeRequest',\n paramName: 'request',\n });\n }\n const response = await handler.cacheMatch(request);\n if (process.env.NODE_ENV !== 'production') {\n logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));\n if (response) {\n logger.log(`Found a cached response in the '${this.cacheName}' ` + `cache.`);\n messages.printFinalResponse(response);\n }\n else {\n logger.log(`No response found in the '${this.cacheName}' cache.`);\n }\n logger.groupEnd();\n }\n if (!response) {\n throw new WorkboxError('no-response', { url: request.url });\n }\n return response;\n }\n}\nexport { CacheOnly };\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 cacheOkAndOpaquePlugin = {\n /**\n * Returns a valid response (to allow caching) if the status is 200 (OK) or\n * 0 (opaque).\n *\n * @param {Object} options\n * @param {Response} options.response\n * @return {Response|null}\n *\n * @private\n */\n cacheWillUpdate: async ({ response }) => {\n if (response.status === 200 || response.status === 0) {\n return response;\n }\n return null;\n },\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 { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { cacheOkAndOpaquePlugin } from './plugins/cacheOkAndOpaquePlugin.js';\nimport { Strategy } from './Strategy.js';\nimport { messages } from './utils/messages.js';\nimport './_version.js';\n/**\n * An implementation of a\n * [network first](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#network-first-falling-back-to-cache)\n * request strategy.\n *\n * By default, this strategy will cache responses with a 200 status code as\n * well as [opaque responses](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses).\n * Opaque responses are are cross-origin requests where the response doesn't\n * support [CORS](https://enable-cors.org/).\n *\n * If the network request fails, and there is no cache match, this will throw\n * a `WorkboxError` exception.\n *\n * @extends workbox-strategies.Strategy\n * @memberof workbox-strategies\n */\nclass NetworkFirst extends Strategy {\n /**\n * @param {Object} [options]\n * @param {string} [options.cacheName] Cache name to store and retrieve\n * requests. Defaults to cache names provided by\n * {@link workbox-core.cacheNames}.\n * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}\n * to use in conjunction with this caching strategy.\n * @param {Object} [options.fetchOptions] Values passed along to the\n * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)\n * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)\n * `fetch()` requests made by this strategy.\n * @param {Object} [options.matchOptions] [`CacheQueryOptions`](https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions)\n * @param {number} [options.networkTimeoutSeconds] If set, any network requests\n * that fail to respond within the timeout will fallback to the cache.\n *\n * This option can be used to combat\n * \"[lie-fi]{@link https://developers.google.com/web/fundamentals/performance/poor-connectivity/#lie-fi}\"\n * scenarios.\n */\n constructor(options = {}) {\n super(options);\n // If this instance contains no plugins with a 'cacheWillUpdate' callback,\n // prepend the `cacheOkAndOpaquePlugin` plugin to the plugins list.\n if (!this.plugins.some((p) => 'cacheWillUpdate' in p)) {\n this.plugins.unshift(cacheOkAndOpaquePlugin);\n }\n this._networkTimeoutSeconds = options.networkTimeoutSeconds || 0;\n if (process.env.NODE_ENV !== 'production') {\n if (this._networkTimeoutSeconds) {\n assert.isType(this._networkTimeoutSeconds, 'number', {\n moduleName: 'workbox-strategies',\n className: this.constructor.name,\n funcName: 'constructor',\n paramName: 'networkTimeoutSeconds',\n });\n }\n }\n }\n /**\n * @private\n * @param {Request|string} request A request to run this strategy for.\n * @param {workbox-strategies.StrategyHandler} handler The event that\n * triggered the request.\n * @return {Promise}\n */\n async _handle(request, handler) {\n const logs = [];\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(request, Request, {\n moduleName: 'workbox-strategies',\n className: this.constructor.name,\n funcName: 'handle',\n paramName: 'makeRequest',\n });\n }\n const promises = [];\n let timeoutId;\n if (this._networkTimeoutSeconds) {\n const { id, promise } = this._getTimeoutPromise({ request, logs, handler });\n timeoutId = id;\n promises.push(promise);\n }\n const networkPromise = this._getNetworkPromise({\n timeoutId,\n request,\n logs,\n handler,\n });\n promises.push(networkPromise);\n const response = await handler.waitUntil((async () => {\n // Promise.race() will resolve as soon as the first promise resolves.\n return ((await handler.waitUntil(Promise.race(promises))) ||\n // If Promise.race() resolved with null, it might be due to a network\n // timeout + a cache miss. If that were to happen, we'd rather wait until\n // the networkPromise resolves instead of returning null.\n // Note that it's fine to await an already-resolved promise, so we don't\n // have to check to see if it's still \"in flight\".\n (await networkPromise));\n })());\n if (process.env.NODE_ENV !== 'production') {\n logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));\n for (const log of logs) {\n logger.log(log);\n }\n messages.printFinalResponse(response);\n logger.groupEnd();\n }\n if (!response) {\n throw new WorkboxError('no-response', { url: request.url });\n }\n return response;\n }\n /**\n * @param {Object} options\n * @param {Request} options.request\n * @param {Array} options.logs A reference to the logs array\n * @param {Event} options.event\n * @return {Promise}\n *\n * @private\n */\n _getTimeoutPromise({ request, logs, handler, }) {\n let timeoutId;\n const timeoutPromise = new Promise((resolve) => {\n const onNetworkTimeout = async () => {\n if (process.env.NODE_ENV !== 'production') {\n logs.push(`Timing out the network response at ` +\n `${this._networkTimeoutSeconds} seconds.`);\n }\n resolve(await handler.cacheMatch(request));\n };\n timeoutId = setTimeout(onNetworkTimeout, this._networkTimeoutSeconds * 1000);\n });\n return {\n promise: timeoutPromise,\n id: timeoutId,\n };\n }\n /**\n * @param {Object} options\n * @param {number|undefined} options.timeoutId\n * @param {Request} options.request\n * @param {Array} options.logs A reference to the logs Array.\n * @param {Event} options.event\n * @return {Promise}\n *\n * @private\n */\n async _getNetworkPromise({ timeoutId, request, logs, handler, }) {\n let error;\n let response;\n try {\n response = await handler.fetchAndCachePut(request);\n }\n catch (fetchError) {\n if (fetchError instanceof Error) {\n error = fetchError;\n }\n }\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n if (process.env.NODE_ENV !== 'production') {\n if (response) {\n logs.push(`Got response from network.`);\n }\n else {\n logs.push(`Unable to get a response from the network. Will respond ` +\n `with a cached response.`);\n }\n }\n if (error || !response) {\n response = await handler.cacheMatch(request);\n if (process.env.NODE_ENV !== 'production') {\n if (response) {\n logs.push(`Found a cached response in the '${this.cacheName}'` + ` cache.`);\n }\n else {\n logs.push(`No response found in the '${this.cacheName}' cache.`);\n }\n }\n }\n return response;\n }\n}\nexport { NetworkFirst };\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 { logger } from 'workbox-core/_private/logger.js';\nimport { timeout } from 'workbox-core/_private/timeout.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { Strategy } from './Strategy.js';\nimport { messages } from './utils/messages.js';\nimport './_version.js';\n/**\n * An implementation of a\n * [network-only](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#network-only)\n * request strategy.\n *\n * This class is useful if you want to take advantage of any\n * [Workbox plugins](https://developer.chrome.com/docs/workbox/using-plugins/).\n *\n * If the network request fails, this will throw a `WorkboxError` exception.\n *\n * @extends workbox-strategies.Strategy\n * @memberof workbox-strategies\n */\nclass NetworkOnly extends Strategy {\n /**\n * @param {Object} [options]\n * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}\n * to use in conjunction with this caching strategy.\n * @param {Object} [options.fetchOptions] Values passed along to the\n * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)\n * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)\n * `fetch()` requests made by this strategy.\n * @param {number} [options.networkTimeoutSeconds] If set, any network requests\n * that fail to respond within the timeout will result in a network error.\n */\n constructor(options = {}) {\n super(options);\n this._networkTimeoutSeconds = options.networkTimeoutSeconds || 0;\n }\n /**\n * @private\n * @param {Request|string} request A request to run this strategy for.\n * @param {workbox-strategies.StrategyHandler} handler The event that\n * triggered the request.\n * @return {Promise}\n */\n async _handle(request, handler) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(request, Request, {\n moduleName: 'workbox-strategies',\n className: this.constructor.name,\n funcName: '_handle',\n paramName: 'request',\n });\n }\n let error = undefined;\n let response;\n try {\n const promises = [\n handler.fetch(request),\n ];\n if (this._networkTimeoutSeconds) {\n const timeoutPromise = timeout(this._networkTimeoutSeconds * 1000);\n promises.push(timeoutPromise);\n }\n response = await Promise.race(promises);\n if (!response) {\n throw new Error(`Timed out the network response after ` +\n `${this._networkTimeoutSeconds} seconds.`);\n }\n }\n catch (err) {\n if (err instanceof Error) {\n error = err;\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));\n if (response) {\n logger.log(`Got response from network.`);\n }\n else {\n logger.log(`Unable to get a response from the network.`);\n }\n messages.printFinalResponse(response);\n logger.groupEnd();\n }\n if (!response) {\n throw new WorkboxError('no-response', { url: request.url, error });\n }\n return response;\n }\n}\nexport { NetworkOnly };\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 { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { cacheOkAndOpaquePlugin } from './plugins/cacheOkAndOpaquePlugin.js';\nimport { Strategy } from './Strategy.js';\nimport { messages } from './utils/messages.js';\nimport './_version.js';\n/**\n * An implementation of a\n * [stale-while-revalidate](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#stale-while-revalidate)\n * request strategy.\n *\n * Resources are requested from both the cache and the network in parallel.\n * The strategy will respond with the cached version if available, otherwise\n * wait for the network response. The cache is updated with the network response\n * with each successful request.\n *\n * By default, this strategy will cache responses with a 200 status code as\n * well as [opaque responses](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses).\n * Opaque responses are cross-origin requests where the response doesn't\n * support [CORS](https://enable-cors.org/).\n *\n * If the network request fails, and there is no cache match, this will throw\n * a `WorkboxError` exception.\n *\n * @extends workbox-strategies.Strategy\n * @memberof workbox-strategies\n */\nclass StaleWhileRevalidate extends Strategy {\n /**\n * @param {Object} [options]\n * @param {string} [options.cacheName] Cache name to store and retrieve\n * requests. Defaults to cache names provided by\n * {@link workbox-core.cacheNames}.\n * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}\n * to use in conjunction with this caching strategy.\n * @param {Object} [options.fetchOptions] Values passed along to the\n * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)\n * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)\n * `fetch()` requests made by this strategy.\n * @param {Object} [options.matchOptions] [`CacheQueryOptions`](https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions)\n */\n constructor(options = {}) {\n super(options);\n // If this instance contains no plugins with a 'cacheWillUpdate' callback,\n // prepend the `cacheOkAndOpaquePlugin` plugin to the plugins list.\n if (!this.plugins.some((p) => 'cacheWillUpdate' in p)) {\n this.plugins.unshift(cacheOkAndOpaquePlugin);\n }\n }\n /**\n * @private\n * @param {Request|string} request A request to run this strategy for.\n * @param {workbox-strategies.StrategyHandler} handler The event that\n * triggered the request.\n * @return {Promise}\n */\n async _handle(request, handler) {\n const logs = [];\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(request, Request, {\n moduleName: 'workbox-strategies',\n className: this.constructor.name,\n funcName: 'handle',\n paramName: 'request',\n });\n }\n const fetchAndCachePromise = handler.fetchAndCachePut(request).catch(() => {\n // Swallow this error because a 'no-response' error will be thrown in\n // main handler return flow. This will be in the `waitUntil()` flow.\n });\n void handler.waitUntil(fetchAndCachePromise);\n let response = await handler.cacheMatch(request);\n let error;\n if (response) {\n if (process.env.NODE_ENV !== 'production') {\n logs.push(`Found a cached response in the '${this.cacheName}'` +\n ` cache. Will update with the network response in the background.`);\n }\n }\n else {\n if (process.env.NODE_ENV !== 'production') {\n logs.push(`No response found in the '${this.cacheName}' cache. ` +\n `Will wait for the network response.`);\n }\n try {\n // NOTE(philipwalton): Really annoying that we have to type cast here.\n // https://github.com/microsoft/TypeScript/issues/20006\n response = (await fetchAndCachePromise);\n }\n catch (err) {\n if (err instanceof Error) {\n error = err;\n }\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));\n for (const log of logs) {\n logger.log(log);\n }\n messages.printFinalResponse(response);\n logger.groupEnd();\n }\n if (!response) {\n throw new WorkboxError('no-response', { url: request.url, error });\n }\n return response;\n }\n}\nexport { StaleWhileRevalidate };\n"],"names":["self","_","e","toRequest","input","Request","StrategyHandler","constructor","strategy","options","_cacheKeys","assert","isInstance","event","ExtendableEvent","moduleName","className","funcName","paramName","Object","assign","_strategy","_handlerDeferred","Deferred","_extendLifetimePromises","_plugins","plugins","_pluginStateMap","Map","plugin","set","waitUntil","promise","fetch","request","mode","FetchEvent","preloadResponse","possiblePreloadResponse","logger","log","getFriendlyURL","url","originalRequest","hasCallback","clone","cb","iterateCallbacks","err","Error","WorkboxError","thrownErrorMessage","message","pluginFilteredRequest","fetchResponse","undefined","fetchOptions","process","debug","status","callback","response","error","runCallbacks","fetchAndCachePut","responseClone","cachePut","cacheMatch","key","cachedResponse","cacheName","matchOptions","effectiveRequest","getCacheKey","multiMatchOptions","caches","match","timeout","method","vary","headers","get","responseToCache","_ensureResponseSafeToCache","cache","open","hasCacheUpdateCallback","oldResponse","cacheMatchIgnoreParams","put","name","executeQuotaErrorCallbacks","newResponse","params","param","state","statefulCallback","statefulParam","push","doneWaiting","length","promises","splice","result","Promise","allSettled","firstRejection","find","i","reason","destroy","resolve","pluginsUsed","warn","Strategy","cacheNames","getRuntimeName","handle","responseDone","handleAll","handler","_getResponse","handlerDone","_awaitComplete","_handle","type","toString","waitUntilError","messages","strategyStart","strategyName","printFinalResponse","groupCollapsed","groupEnd","CacheFirst","logs","CacheOnly","cacheOkAndOpaquePlugin","cacheWillUpdate","NetworkFirst","some","p","unshift","_networkTimeoutSeconds","networkTimeoutSeconds","isType","timeoutId","id","_getTimeoutPromise","networkPromise","_getNetworkPromise","race","timeoutPromise","onNetworkTimeout","setTimeout","fetchError","clearTimeout","NetworkOnly","StaleWhileRevalidate","fetchAndCachePromise","catch"],"mappings":";;;;IACA;IACA,IAAI;IACAA,EAAAA,IAAI,CAAC,0BAA0B,CAAC,IAAIC,CAAC,EAAE;IAC3C,CAAC,C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GAAG,IAAI+F,IAAI,EAAE;IACpBhG,QAAAA,gBAAM,CAACC,GAAG,CAACA,GAAG,CAAC;IACnB,MAAA;IACAwF,MAAAA,QAAQ,CAACG,kBAAkB,CAACtE,QAAQ,CAAC;UACrCtB,gBAAM,CAAC8F,QAAQ,EAAE;IACrB,IAAA;QACA,IAAI,CAACxE,QAAQ,EAAE;IACX,MAAA,MAAM,IAAIX,4BAAY,CAAC,aAAa,EAAE;YAAER,GAAG,EAAER,OAAO,CAACQ,GAAG;IAAEoB,QAAAA;IAAM,OAAC,CAAC;IACtE,IAAA;IACA,IAAA,OAAOD,QAAQ;IACnB,EAAA;IACJ;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/workbox-strategies/build/workbox-strategies.prod.js b/node_modules/workbox-strategies/build/workbox-strategies.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..799f9413b212eec26f714edaf226f3879da990cc --- /dev/null +++ b/node_modules/workbox-strategies/build/workbox-strategies.prod.js @@ -0,0 +1,2 @@ +this.workbox=this.workbox||{},this.workbox.strategies=function(t,e,s,r,n,i,a,o,c){"use strict";try{self["workbox:strategies:7.4.0"]&&_()}catch(t){}function h(t){return"string"==typeof t?new Request(t):t}class l{constructor(t,e){this.l={},Object.assign(this,e),this.event=e.event,this.u=t,this.p=new n.Deferred,this.m=[],this.v=[...t.plugins],this.q=new Map;for(const t of this.v)this.q.set(t,{});this.event.waitUntil(this.p.promise)}async fetch(t){const{event:s}=this;let r=h(t);if("navigate"===r.mode&&s instanceof FetchEvent&&s.preloadResponse){const t=await s.preloadResponse;if(t)return t}const n=this.hasCallback("fetchDidFail")?r.clone():null;try{for(const t of this.iterateCallbacks("requestWillFetch"))r=await t({request:r.clone(),event:s})}catch(t){if(t instanceof Error)throw new e.WorkboxError("plugin-error-request-will-fetch",{thrownErrorMessage:t.message})}const i=r.clone();try{let t;t=await fetch(r,"navigate"===r.mode?void 0:this.u.fetchOptions);for(const e of this.iterateCallbacks("fetchDidSucceed"))t=await e({event:s,request:i,response:t});return t}catch(t){throw n&&await this.runCallbacks("fetchDidFail",{error:t,event:s,originalRequest:n.clone(),request:i.clone()}),t}}async fetchAndCachePut(t){const e=await this.fetch(t),s=e.clone();return this.waitUntil(this.cachePut(t,s)),e}async cacheMatch(t){const e=h(t);let s;const{cacheName:r,matchOptions:n}=this.u,i=await this.getCacheKey(e,"read"),a=Object.assign(Object.assign({},n),{cacheName:r});s=await caches.match(i,a);for(const t of this.iterateCallbacks("cachedResponseWillBeUsed"))s=await t({cacheName:r,matchOptions:n,cachedResponse:s,request:i,event:this.event})||void 0;return s}async cachePut(t,s){const n=h(t);await c.timeout(0);const o=await this.getCacheKey(n,"write");if(!s)throw new e.WorkboxError("cache-put-with-no-response",{url:a.getFriendlyURL(o.url)});const l=await this.g(s);if(!l)return!1;const{cacheName:w,matchOptions:u}=this.u,f=await self.caches.open(w),d=this.hasCallback("cacheDidUpdate"),p=d?await r.cacheMatchIgnoreParams(f,o.clone(),["__WB_REVISION__"],u):null;try{await f.put(o,d?l.clone():l)}catch(t){if(t instanceof Error)throw"QuotaExceededError"===t.name&&await i.executeQuotaErrorCallbacks(),t}for(const t of this.iterateCallbacks("cacheDidUpdate"))await t({cacheName:w,oldResponse:p,newResponse:l.clone(),request:o,event:this.event});return!0}async getCacheKey(t,e){const s=`${t.url} | ${e}`;if(!this.l[s]){let r=t;for(const t of this.iterateCallbacks("cacheKeyWillBeUsed"))r=h(await t({mode:e,request:r,event:this.event,params:this.params}));this.l[s]=r}return this.l[s]}hasCallback(t){for(const e of this.u.plugins)if(t in e)return!0;return!1}async runCallbacks(t,e){for(const s of this.iterateCallbacks(t))await s(e)}*iterateCallbacks(t){for(const e of this.u.plugins)if("function"==typeof e[t]){const s=this.q.get(e),r=r=>{const n=Object.assign(Object.assign({},r),{state:s});return e[t](n)};yield r}}waitUntil(t){return this.m.push(t),t}async doneWaiting(){for(;this.m.length;){const t=this.m.splice(0),e=(await Promise.allSettled(t)).find((t=>"rejected"===t.status));if(e)throw e.reason}}destroy(){this.p.resolve(null)}async g(t){let e=t,s=!1;for(const t of this.iterateCallbacks("cacheWillUpdate"))if(e=await t({request:this.request,response:e,event:this.event})||void 0,s=!0,!e)break;return s||e&&200!==e.status&&(e=void 0),e}}class w{constructor(t={}){this.cacheName=s.cacheNames.getRuntimeName(t.cacheName),this.plugins=t.plugins||[],this.fetchOptions=t.fetchOptions,this.matchOptions=t.matchOptions}handle(t){const[e]=this.handleAll(t);return e}handleAll(t){t instanceof FetchEvent&&(t={event:t,request:t.request});const e=t.event,s="string"==typeof t.request?new Request(t.request):t.request,r="params"in t?t.params:void 0,n=new l(this,{event:e,request:s,params:r}),i=this._(n,s,e);return[i,this.k(i,n,s,e)]}async _(t,s,r){let n;await t.runCallbacks("handlerWillStart",{event:r,request:s});try{if(n=await this._handle(s,t),!n||"error"===n.type)throw new e.WorkboxError("no-response",{url:s.url})}catch(e){if(e instanceof Error)for(const i of t.iterateCallbacks("handlerDidError"))if(n=await i({error:e,event:r,request:s}),n)break;if(!n)throw e}for(const e of t.iterateCallbacks("handlerWillRespond"))n=await e({event:r,request:s,response:n});return n}async k(t,e,s,r){let n,i;try{n=await t}catch(i){}try{await e.runCallbacks("handlerDidRespond",{event:r,request:s,response:n}),await e.doneWaiting()}catch(t){t instanceof Error&&(i=t)}if(await e.runCallbacks("handlerDidComplete",{event:r,request:s,response:n,error:i}),e.destroy(),i)throw i}}const u={cacheWillUpdate:async({response:t})=>200===t.status||0===t.status?t:null};return t.CacheFirst=class extends w{async _handle(t,s){let r,n=await s.cacheMatch(t);if(!n)try{n=await s.fetchAndCachePut(t)}catch(t){t instanceof Error&&(r=t)}if(!n)throw new e.WorkboxError("no-response",{url:t.url,error:r});return n}},t.CacheOnly=class extends w{async _handle(t,s){const r=await s.cacheMatch(t);if(!r)throw new e.WorkboxError("no-response",{url:t.url});return r}},t.NetworkFirst=class extends w{constructor(t={}){super(t),this.plugins.some((t=>"cacheWillUpdate"in t))||this.plugins.unshift(u),this.R=t.networkTimeoutSeconds||0}async _handle(t,s){const r=[],n=[];let i;if(this.R){const{id:e,promise:a}=this.W({request:t,logs:r,handler:s});i=e,n.push(a)}const a=this.O({timeoutId:i,request:t,logs:r,handler:s});n.push(a);const o=await s.waitUntil((async()=>await s.waitUntil(Promise.race(n))||await a)());if(!o)throw new e.WorkboxError("no-response",{url:t.url});return o}W({request:t,logs:e,handler:s}){let r;return{promise:new Promise((e=>{r=setTimeout((async()=>{e(await s.cacheMatch(t))}),1e3*this.R)})),id:r}}async O({timeoutId:t,request:e,logs:s,handler:r}){let n,i;try{i=await r.fetchAndCachePut(e)}catch(t){t instanceof Error&&(n=t)}return t&&clearTimeout(t),!n&&i||(i=await r.cacheMatch(e)),i}},t.NetworkOnly=class extends w{constructor(t={}){super(t),this.R=t.networkTimeoutSeconds||0}async _handle(t,s){let r,n;try{const e=[s.fetch(t)];if(this.R){const t=c.timeout(1e3*this.R);e.push(t)}if(n=await Promise.race(e),!n)throw new Error(`Timed out the network response after ${this.R} seconds.`)}catch(t){t instanceof Error&&(r=t)}if(!n)throw new e.WorkboxError("no-response",{url:t.url,error:r});return n}},t.StaleWhileRevalidate=class extends w{constructor(t={}){super(t),this.plugins.some((t=>"cacheWillUpdate"in t))||this.plugins.unshift(u)}async _handle(t,s){const r=s.fetchAndCachePut(t).catch((()=>{}));s.waitUntil(r);let n,i=await s.cacheMatch(t);if(i);else try{i=await r}catch(t){t instanceof Error&&(n=t)}if(!i)throw new e.WorkboxError("no-response",{url:t.url,error:n});return i}},t.Strategy=w,t.StrategyHandler=l,t}({},workbox.core._private,workbox.core._private,workbox.core._private,workbox.core._private,workbox.core._private,workbox.core._private,workbox.core._private,workbox.core._private); +//# sourceMappingURL=workbox-strategies.prod.js.map diff --git a/node_modules/workbox-strategies/build/workbox-strategies.prod.js.map b/node_modules/workbox-strategies/build/workbox-strategies.prod.js.map new file mode 100644 index 0000000000000000000000000000000000000000..7f97d8d553817ec6a39f0a39777721f383a0b2aa --- /dev/null +++ b/node_modules/workbox-strategies/build/workbox-strategies.prod.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-strategies.prod.js","sources":["../_version.js","../StrategyHandler.js","../Strategy.js","../plugins/cacheOkAndOpaquePlugin.js","../CacheFirst.js","../CacheOnly.js","../NetworkFirst.js","../NetworkOnly.js","../StaleWhileRevalidate.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:strategies:7.4.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2020 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 { cacheMatchIgnoreParams } from 'workbox-core/_private/cacheMatchIgnoreParams.js';\nimport { Deferred } from 'workbox-core/_private/Deferred.js';\nimport { executeQuotaErrorCallbacks } from 'workbox-core/_private/executeQuotaErrorCallbacks.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { timeout } from 'workbox-core/_private/timeout.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport './_version.js';\nfunction toRequest(input) {\n return typeof input === 'string' ? new Request(input) : input;\n}\n/**\n * A class created every time a Strategy instance calls\n * {@link workbox-strategies.Strategy~handle} or\n * {@link workbox-strategies.Strategy~handleAll} that wraps all fetch and\n * cache actions around plugin callbacks and keeps track of when the strategy\n * is \"done\" (i.e. all added `event.waitUntil()` promises have resolved).\n *\n * @memberof workbox-strategies\n */\nclass StrategyHandler {\n /**\n * Creates a new instance associated with the passed strategy and event\n * that's handling the request.\n *\n * The constructor also initializes the state that will be passed to each of\n * the plugins handling this request.\n *\n * @param {workbox-strategies.Strategy} strategy\n * @param {Object} options\n * @param {Request|string} options.request A request to run this strategy for.\n * @param {ExtendableEvent} options.event The event associated with the\n * request.\n * @param {URL} [options.url]\n * @param {*} [options.params] The return value from the\n * {@link workbox-routing~matchCallback} (if applicable).\n */\n constructor(strategy, options) {\n this._cacheKeys = {};\n /**\n * The request the strategy is performing (passed to the strategy's\n * `handle()` or `handleAll()` method).\n * @name request\n * @instance\n * @type {Request}\n * @memberof workbox-strategies.StrategyHandler\n */\n /**\n * The event associated with this request.\n * @name event\n * @instance\n * @type {ExtendableEvent}\n * @memberof workbox-strategies.StrategyHandler\n */\n /**\n * A `URL` instance of `request.url` (if passed to the strategy's\n * `handle()` or `handleAll()` method).\n * Note: the `url` param will be present if the strategy was invoked\n * from a workbox `Route` object.\n * @name url\n * @instance\n * @type {URL|undefined}\n * @memberof workbox-strategies.StrategyHandler\n */\n /**\n * A `param` value (if passed to the strategy's\n * `handle()` or `handleAll()` method).\n * Note: the `param` param will be present if the strategy was invoked\n * from a workbox `Route` object and the\n * {@link workbox-routing~matchCallback} returned\n * a truthy value (it will be that value).\n * @name params\n * @instance\n * @type {*|undefined}\n * @memberof workbox-strategies.StrategyHandler\n */\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(options.event, ExtendableEvent, {\n moduleName: 'workbox-strategies',\n className: 'StrategyHandler',\n funcName: 'constructor',\n paramName: 'options.event',\n });\n }\n Object.assign(this, options);\n this.event = options.event;\n this._strategy = strategy;\n this._handlerDeferred = new Deferred();\n this._extendLifetimePromises = [];\n // Copy the plugins list (since it's mutable on the strategy),\n // so any mutations don't affect this handler instance.\n this._plugins = [...strategy.plugins];\n this._pluginStateMap = new Map();\n for (const plugin of this._plugins) {\n this._pluginStateMap.set(plugin, {});\n }\n this.event.waitUntil(this._handlerDeferred.promise);\n }\n /**\n * Fetches a given request (and invokes any applicable plugin callback\n * methods) using the `fetchOptions` (for non-navigation requests) and\n * `plugins` defined on the `Strategy` object.\n *\n * The following plugin lifecycle methods are invoked when using this method:\n * - `requestWillFetch()`\n * - `fetchDidSucceed()`\n * - `fetchDidFail()`\n *\n * @param {Request|string} input The URL or request to fetch.\n * @return {Promise}\n */\n async fetch(input) {\n const { event } = this;\n let request = toRequest(input);\n if (request.mode === 'navigate' &&\n event instanceof FetchEvent &&\n event.preloadResponse) {\n const possiblePreloadResponse = (await event.preloadResponse);\n if (possiblePreloadResponse) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Using a preloaded navigation response for ` +\n `'${getFriendlyURL(request.url)}'`);\n }\n return possiblePreloadResponse;\n }\n }\n // If there is a fetchDidFail plugin, we need to save a clone of the\n // original request before it's either modified by a requestWillFetch\n // plugin or before the original request's body is consumed via fetch().\n const originalRequest = this.hasCallback('fetchDidFail')\n ? request.clone()\n : null;\n try {\n for (const cb of this.iterateCallbacks('requestWillFetch')) {\n request = await cb({ request: request.clone(), event });\n }\n }\n catch (err) {\n if (err instanceof Error) {\n throw new WorkboxError('plugin-error-request-will-fetch', {\n thrownErrorMessage: err.message,\n });\n }\n }\n // The request can be altered by plugins with `requestWillFetch` making\n // the original request (most likely from a `fetch` event) different\n // from the Request we make. Pass both to `fetchDidFail` to aid debugging.\n const pluginFilteredRequest = request.clone();\n try {\n let fetchResponse;\n // See https://github.com/GoogleChrome/workbox/issues/1796\n fetchResponse = await fetch(request, request.mode === 'navigate' ? undefined : this._strategy.fetchOptions);\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`Network request for ` +\n `'${getFriendlyURL(request.url)}' returned a response with ` +\n `status '${fetchResponse.status}'.`);\n }\n for (const callback of this.iterateCallbacks('fetchDidSucceed')) {\n fetchResponse = await callback({\n event,\n request: pluginFilteredRequest,\n response: fetchResponse,\n });\n }\n return fetchResponse;\n }\n catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Network request for ` +\n `'${getFriendlyURL(request.url)}' threw an error.`, error);\n }\n // `originalRequest` will only exist if a `fetchDidFail` callback\n // is being used (see above).\n if (originalRequest) {\n await this.runCallbacks('fetchDidFail', {\n error: error,\n event,\n originalRequest: originalRequest.clone(),\n request: pluginFilteredRequest.clone(),\n });\n }\n throw error;\n }\n }\n /**\n * Calls `this.fetch()` and (in the background) runs `this.cachePut()` on\n * the response generated by `this.fetch()`.\n *\n * The call to `this.cachePut()` automatically invokes `this.waitUntil()`,\n * so you do not have to manually call `waitUntil()` on the event.\n *\n * @param {Request|string} input The request or URL to fetch and cache.\n * @return {Promise}\n */\n async fetchAndCachePut(input) {\n const response = await this.fetch(input);\n const responseClone = response.clone();\n void this.waitUntil(this.cachePut(input, responseClone));\n return response;\n }\n /**\n * Matches a request from the cache (and invokes any applicable plugin\n * callback methods) using the `cacheName`, `matchOptions`, and `plugins`\n * defined on the strategy object.\n *\n * The following plugin lifecycle methods are invoked when using this method:\n * - cacheKeyWillBeUsed()\n * - cachedResponseWillBeUsed()\n *\n * @param {Request|string} key The Request or URL to use as the cache key.\n * @return {Promise} A matching response, if found.\n */\n async cacheMatch(key) {\n const request = toRequest(key);\n let cachedResponse;\n const { cacheName, matchOptions } = this._strategy;\n const effectiveRequest = await this.getCacheKey(request, 'read');\n const multiMatchOptions = Object.assign(Object.assign({}, matchOptions), { cacheName });\n cachedResponse = await caches.match(effectiveRequest, multiMatchOptions);\n if (process.env.NODE_ENV !== 'production') {\n if (cachedResponse) {\n logger.debug(`Found a cached response in '${cacheName}'.`);\n }\n else {\n logger.debug(`No cached response found in '${cacheName}'.`);\n }\n }\n for (const callback of this.iterateCallbacks('cachedResponseWillBeUsed')) {\n cachedResponse =\n (await callback({\n cacheName,\n matchOptions,\n cachedResponse,\n request: effectiveRequest,\n event: this.event,\n })) || undefined;\n }\n return cachedResponse;\n }\n /**\n * Puts a request/response pair in the cache (and invokes any applicable\n * plugin callback methods) using the `cacheName` and `plugins` defined on\n * the strategy object.\n *\n * The following plugin lifecycle methods are invoked when using this method:\n * - cacheKeyWillBeUsed()\n * - cacheWillUpdate()\n * - cacheDidUpdate()\n *\n * @param {Request|string} key The request or URL to use as the cache key.\n * @param {Response} response The response to cache.\n * @return {Promise} `false` if a cacheWillUpdate caused the response\n * not be cached, and `true` otherwise.\n */\n async cachePut(key, response) {\n const request = toRequest(key);\n // Run in the next task to avoid blocking other cache reads.\n // https://github.com/w3c/ServiceWorker/issues/1397\n await timeout(0);\n const effectiveRequest = await this.getCacheKey(request, 'write');\n if (process.env.NODE_ENV !== 'production') {\n if (effectiveRequest.method && effectiveRequest.method !== 'GET') {\n throw new WorkboxError('attempt-to-cache-non-get-request', {\n url: getFriendlyURL(effectiveRequest.url),\n method: effectiveRequest.method,\n });\n }\n // See https://github.com/GoogleChrome/workbox/issues/2818\n const vary = response.headers.get('Vary');\n if (vary) {\n logger.debug(`The response for ${getFriendlyURL(effectiveRequest.url)} ` +\n `has a 'Vary: ${vary}' header. ` +\n `Consider setting the {ignoreVary: true} option on your strategy ` +\n `to ensure cache matching and deletion works as expected.`);\n }\n }\n if (!response) {\n if (process.env.NODE_ENV !== 'production') {\n logger.error(`Cannot cache non-existent response for ` +\n `'${getFriendlyURL(effectiveRequest.url)}'.`);\n }\n throw new WorkboxError('cache-put-with-no-response', {\n url: getFriendlyURL(effectiveRequest.url),\n });\n }\n const responseToCache = await this._ensureResponseSafeToCache(response);\n if (!responseToCache) {\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`Response '${getFriendlyURL(effectiveRequest.url)}' ` +\n `will not be cached.`, responseToCache);\n }\n return false;\n }\n const { cacheName, matchOptions } = this._strategy;\n const cache = await self.caches.open(cacheName);\n const hasCacheUpdateCallback = this.hasCallback('cacheDidUpdate');\n const oldResponse = hasCacheUpdateCallback\n ? await cacheMatchIgnoreParams(\n // TODO(philipwalton): the `__WB_REVISION__` param is a precaching\n // feature. Consider into ways to only add this behavior if using\n // precaching.\n cache, effectiveRequest.clone(), ['__WB_REVISION__'], matchOptions)\n : null;\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`Updating the '${cacheName}' cache with a new Response ` +\n `for ${getFriendlyURL(effectiveRequest.url)}.`);\n }\n try {\n await cache.put(effectiveRequest, hasCacheUpdateCallback ? responseToCache.clone() : responseToCache);\n }\n catch (error) {\n if (error instanceof Error) {\n // See https://developer.mozilla.org/en-US/docs/Web/API/DOMException#exception-QuotaExceededError\n if (error.name === 'QuotaExceededError') {\n await executeQuotaErrorCallbacks();\n }\n throw error;\n }\n }\n for (const callback of this.iterateCallbacks('cacheDidUpdate')) {\n await callback({\n cacheName,\n oldResponse,\n newResponse: responseToCache.clone(),\n request: effectiveRequest,\n event: this.event,\n });\n }\n return true;\n }\n /**\n * Checks the list of plugins for the `cacheKeyWillBeUsed` callback, and\n * executes any of those callbacks found in sequence. The final `Request`\n * object returned by the last plugin is treated as the cache key for cache\n * reads and/or writes. If no `cacheKeyWillBeUsed` plugin callbacks have\n * been registered, the passed request is returned unmodified\n *\n * @param {Request} request\n * @param {string} mode\n * @return {Promise}\n */\n async getCacheKey(request, mode) {\n const key = `${request.url} | ${mode}`;\n if (!this._cacheKeys[key]) {\n let effectiveRequest = request;\n for (const callback of this.iterateCallbacks('cacheKeyWillBeUsed')) {\n effectiveRequest = toRequest(await callback({\n mode,\n request: effectiveRequest,\n event: this.event,\n // params has a type any can't change right now.\n params: this.params, // eslint-disable-line\n }));\n }\n this._cacheKeys[key] = effectiveRequest;\n }\n return this._cacheKeys[key];\n }\n /**\n * Returns true if the strategy has at least one plugin with the given\n * callback.\n *\n * @param {string} name The name of the callback to check for.\n * @return {boolean}\n */\n hasCallback(name) {\n for (const plugin of this._strategy.plugins) {\n if (name in plugin) {\n return true;\n }\n }\n return false;\n }\n /**\n * Runs all plugin callbacks matching the given name, in order, passing the\n * given param object (merged ith the current plugin state) as the only\n * argument.\n *\n * Note: since this method runs all plugins, it's not suitable for cases\n * where the return value of a callback needs to be applied prior to calling\n * the next callback. See\n * {@link workbox-strategies.StrategyHandler#iterateCallbacks}\n * below for how to handle that case.\n *\n * @param {string} name The name of the callback to run within each plugin.\n * @param {Object} param The object to pass as the first (and only) param\n * when executing each callback. This object will be merged with the\n * current plugin state prior to callback execution.\n */\n async runCallbacks(name, param) {\n for (const callback of this.iterateCallbacks(name)) {\n // TODO(philipwalton): not sure why `any` is needed. It seems like\n // this should work with `as WorkboxPluginCallbackParam[C]`.\n await callback(param);\n }\n }\n /**\n * Accepts a callback and returns an iterable of matching plugin callbacks,\n * where each callback is wrapped with the current handler state (i.e. when\n * you call each callback, whatever object parameter you pass it will\n * be merged with the plugin's current state).\n *\n * @param {string} name The name fo the callback to run\n * @return {Array}\n */\n *iterateCallbacks(name) {\n for (const plugin of this._strategy.plugins) {\n if (typeof plugin[name] === 'function') {\n const state = this._pluginStateMap.get(plugin);\n const statefulCallback = (param) => {\n const statefulParam = Object.assign(Object.assign({}, param), { state });\n // TODO(philipwalton): not sure why `any` is needed. It seems like\n // this should work with `as WorkboxPluginCallbackParam[C]`.\n return plugin[name](statefulParam);\n };\n yield statefulCallback;\n }\n }\n }\n /**\n * Adds a promise to the\n * [extend lifetime promises]{@link https://w3c.github.io/ServiceWorker/#extendableevent-extend-lifetime-promises}\n * of the event associated with the request being handled (usually a\n * `FetchEvent`).\n *\n * Note: you can await\n * {@link workbox-strategies.StrategyHandler~doneWaiting}\n * to know when all added promises have settled.\n *\n * @param {Promise} promise A promise to add to the extend lifetime promises\n * of the event that triggered the request.\n */\n waitUntil(promise) {\n this._extendLifetimePromises.push(promise);\n return promise;\n }\n /**\n * Returns a promise that resolves once all promises passed to\n * {@link workbox-strategies.StrategyHandler~waitUntil}\n * have settled.\n *\n * Note: any work done after `doneWaiting()` settles should be manually\n * passed to an event's `waitUntil()` method (not this handler's\n * `waitUntil()` method), otherwise the service worker thread may be killed\n * prior to your work completing.\n */\n async doneWaiting() {\n while (this._extendLifetimePromises.length) {\n const promises = this._extendLifetimePromises.splice(0);\n const result = await Promise.allSettled(promises);\n const firstRejection = result.find((i) => i.status === 'rejected');\n if (firstRejection) {\n throw firstRejection.reason;\n }\n }\n }\n /**\n * Stops running the strategy and immediately resolves any pending\n * `waitUntil()` promises.\n */\n destroy() {\n this._handlerDeferred.resolve(null);\n }\n /**\n * This method will call cacheWillUpdate on the available plugins (or use\n * status === 200) to determine if the Response is safe and valid to cache.\n *\n * @param {Request} options.request\n * @param {Response} options.response\n * @return {Promise}\n *\n * @private\n */\n async _ensureResponseSafeToCache(response) {\n let responseToCache = response;\n let pluginsUsed = false;\n for (const callback of this.iterateCallbacks('cacheWillUpdate')) {\n responseToCache =\n (await callback({\n request: this.request,\n response: responseToCache,\n event: this.event,\n })) || undefined;\n pluginsUsed = true;\n if (!responseToCache) {\n break;\n }\n }\n if (!pluginsUsed) {\n if (responseToCache && responseToCache.status !== 200) {\n responseToCache = undefined;\n }\n if (process.env.NODE_ENV !== 'production') {\n if (responseToCache) {\n if (responseToCache.status !== 200) {\n if (responseToCache.status === 0) {\n logger.warn(`The response for '${this.request.url}' ` +\n `is an opaque response. The caching strategy that you're ` +\n `using will not cache opaque responses by default.`);\n }\n else {\n logger.debug(`The response for '${this.request.url}' ` +\n `returned a status code of '${response.status}' and won't ` +\n `be cached as a result.`);\n }\n }\n }\n }\n }\n return responseToCache;\n }\n}\nexport { StrategyHandler };\n","/*\n Copyright 2020 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 { cacheNames } from 'workbox-core/_private/cacheNames.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { StrategyHandler } from './StrategyHandler.js';\nimport './_version.js';\n/**\n * An abstract base class that all other strategy classes must extend from:\n *\n * @memberof workbox-strategies\n */\nclass Strategy {\n /**\n * Creates a new instance of the strategy and sets all documented option\n * properties as public instance properties.\n *\n * Note: if a custom strategy class extends the base Strategy class and does\n * not need more than these properties, it does not need to define its own\n * constructor.\n *\n * @param {Object} [options]\n * @param {string} [options.cacheName] Cache name to store and retrieve\n * requests. Defaults to the cache names provided by\n * {@link workbox-core.cacheNames}.\n * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}\n * to use in conjunction with this caching strategy.\n * @param {Object} [options.fetchOptions] Values passed along to the\n * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)\n * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)\n * `fetch()` requests made by this strategy.\n * @param {Object} [options.matchOptions] The\n * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions}\n * for any `cache.match()` or `cache.put()` calls made by this strategy.\n */\n constructor(options = {}) {\n /**\n * Cache name to store and retrieve\n * requests. Defaults to the cache names provided by\n * {@link workbox-core.cacheNames}.\n *\n * @type {string}\n */\n this.cacheName = cacheNames.getRuntimeName(options.cacheName);\n /**\n * The list\n * [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}\n * used by this strategy.\n *\n * @type {Array}\n */\n this.plugins = options.plugins || [];\n /**\n * Values passed along to the\n * [`init`]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters}\n * of all fetch() requests made by this strategy.\n *\n * @type {Object}\n */\n this.fetchOptions = options.fetchOptions;\n /**\n * The\n * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions}\n * for any `cache.match()` or `cache.put()` calls made by this strategy.\n *\n * @type {Object}\n */\n this.matchOptions = options.matchOptions;\n }\n /**\n * Perform a request strategy and returns a `Promise` that will resolve with\n * a `Response`, invoking all relevant plugin callbacks.\n *\n * When a strategy instance is registered with a Workbox\n * {@link workbox-routing.Route}, this method is automatically\n * called when the route matches.\n *\n * Alternatively, this method can be used in a standalone `FetchEvent`\n * listener by passing it to `event.respondWith()`.\n *\n * @param {FetchEvent|Object} options A `FetchEvent` or an object with the\n * properties listed below.\n * @param {Request|string} options.request A request to run this strategy for.\n * @param {ExtendableEvent} options.event The event associated with the\n * request.\n * @param {URL} [options.url]\n * @param {*} [options.params]\n */\n handle(options) {\n const [responseDone] = this.handleAll(options);\n return responseDone;\n }\n /**\n * Similar to {@link workbox-strategies.Strategy~handle}, but\n * instead of just returning a `Promise` that resolves to a `Response` it\n * it will return an tuple of `[response, done]` promises, where the former\n * (`response`) is equivalent to what `handle()` returns, and the latter is a\n * Promise that will resolve once any promises that were added to\n * `event.waitUntil()` as part of performing the strategy have completed.\n *\n * You can await the `done` promise to ensure any extra work performed by\n * the strategy (usually caching responses) completes successfully.\n *\n * @param {FetchEvent|Object} options A `FetchEvent` or an object with the\n * properties listed below.\n * @param {Request|string} options.request A request to run this strategy for.\n * @param {ExtendableEvent} options.event The event associated with the\n * request.\n * @param {URL} [options.url]\n * @param {*} [options.params]\n * @return {Array} A tuple of [response, done]\n * promises that can be used to determine when the response resolves as\n * well as when the handler has completed all its work.\n */\n handleAll(options) {\n // Allow for flexible options to be passed.\n if (options instanceof FetchEvent) {\n options = {\n event: options,\n request: options.request,\n };\n }\n const event = options.event;\n const request = typeof options.request === 'string'\n ? new Request(options.request)\n : options.request;\n const params = 'params' in options ? options.params : undefined;\n const handler = new StrategyHandler(this, { event, request, params });\n const responseDone = this._getResponse(handler, request, event);\n const handlerDone = this._awaitComplete(responseDone, handler, request, event);\n // Return an array of promises, suitable for use with Promise.all().\n return [responseDone, handlerDone];\n }\n async _getResponse(handler, request, event) {\n await handler.runCallbacks('handlerWillStart', { event, request });\n let response = undefined;\n try {\n response = await this._handle(request, handler);\n // The \"official\" Strategy subclasses all throw this error automatically,\n // but in case a third-party Strategy doesn't, ensure that we have a\n // consistent failure when there's no response or an error response.\n if (!response || response.type === 'error') {\n throw new WorkboxError('no-response', { url: request.url });\n }\n }\n catch (error) {\n if (error instanceof Error) {\n for (const callback of handler.iterateCallbacks('handlerDidError')) {\n response = await callback({ error, event, request });\n if (response) {\n break;\n }\n }\n }\n if (!response) {\n throw error;\n }\n else if (process.env.NODE_ENV !== 'production') {\n logger.log(`While responding to '${getFriendlyURL(request.url)}', ` +\n `an ${error instanceof Error ? error.toString() : ''} error occurred. Using a fallback response provided by ` +\n `a handlerDidError plugin.`);\n }\n }\n for (const callback of handler.iterateCallbacks('handlerWillRespond')) {\n response = await callback({ event, request, response });\n }\n return response;\n }\n async _awaitComplete(responseDone, handler, request, event) {\n let response;\n let error;\n try {\n response = await responseDone;\n }\n catch (error) {\n // Ignore errors, as response errors should be caught via the `response`\n // promise above. The `done` promise will only throw for errors in\n // promises passed to `handler.waitUntil()`.\n }\n try {\n await handler.runCallbacks('handlerDidRespond', {\n event,\n request,\n response,\n });\n await handler.doneWaiting();\n }\n catch (waitUntilError) {\n if (waitUntilError instanceof Error) {\n error = waitUntilError;\n }\n }\n await handler.runCallbacks('handlerDidComplete', {\n event,\n request,\n response,\n error: error,\n });\n handler.destroy();\n if (error) {\n throw error;\n }\n }\n}\nexport { Strategy };\n/**\n * Classes extending the `Strategy` based class should implement this method,\n * and leverage the {@link workbox-strategies.StrategyHandler}\n * arg to perform all fetching and cache logic, which will ensure all relevant\n * cache, cache options, fetch options and plugins are used (per the current\n * strategy instance).\n *\n * @name _handle\n * @instance\n * @abstract\n * @function\n * @param {Request} request\n * @param {workbox-strategies.StrategyHandler} handler\n * @return {Promise}\n *\n * @memberof workbox-strategies.Strategy\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 '../_version.js';\nexport const cacheOkAndOpaquePlugin = {\n /**\n * Returns a valid response (to allow caching) if the status is 200 (OK) or\n * 0 (opaque).\n *\n * @param {Object} options\n * @param {Response} options.response\n * @return {Response|null}\n *\n * @private\n */\n cacheWillUpdate: async ({ response }) => {\n if (response.status === 200 || response.status === 0) {\n return response;\n }\n return null;\n },\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 { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { Strategy } from './Strategy.js';\nimport { messages } from './utils/messages.js';\nimport './_version.js';\n/**\n * An implementation of a [cache-first](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#cache-first-falling-back-to-network)\n * request strategy.\n *\n * A cache first strategy is useful for assets that have been revisioned,\n * such as URLs like `/styles/example.a8f5f1.css`, since they\n * can be cached for long periods of time.\n *\n * If the network request fails, and there is no cache match, this will throw\n * a `WorkboxError` exception.\n *\n * @extends workbox-strategies.Strategy\n * @memberof workbox-strategies\n */\nclass CacheFirst extends Strategy {\n /**\n * @private\n * @param {Request|string} request A request to run this strategy for.\n * @param {workbox-strategies.StrategyHandler} handler The event that\n * triggered the request.\n * @return {Promise}\n */\n async _handle(request, handler) {\n const logs = [];\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(request, Request, {\n moduleName: 'workbox-strategies',\n className: this.constructor.name,\n funcName: 'makeRequest',\n paramName: 'request',\n });\n }\n let response = await handler.cacheMatch(request);\n let error = undefined;\n if (!response) {\n if (process.env.NODE_ENV !== 'production') {\n logs.push(`No response found in the '${this.cacheName}' cache. ` +\n `Will respond with a network request.`);\n }\n try {\n response = await handler.fetchAndCachePut(request);\n }\n catch (err) {\n if (err instanceof Error) {\n error = err;\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n if (response) {\n logs.push(`Got response from network.`);\n }\n else {\n logs.push(`Unable to get a response from the network.`);\n }\n }\n }\n else {\n if (process.env.NODE_ENV !== 'production') {\n logs.push(`Found a cached response in the '${this.cacheName}' cache.`);\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));\n for (const log of logs) {\n logger.log(log);\n }\n messages.printFinalResponse(response);\n logger.groupEnd();\n }\n if (!response) {\n throw new WorkboxError('no-response', { url: request.url, error });\n }\n return response;\n }\n}\nexport { CacheFirst };\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 { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { Strategy } from './Strategy.js';\nimport { messages } from './utils/messages.js';\nimport './_version.js';\n/**\n * An implementation of a [cache-only](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#cache-only)\n * request strategy.\n *\n * This class is useful if you want to take advantage of any\n * [Workbox plugins](https://developer.chrome.com/docs/workbox/using-plugins/).\n *\n * If there is no cache match, this will throw a `WorkboxError` exception.\n *\n * @extends workbox-strategies.Strategy\n * @memberof workbox-strategies\n */\nclass CacheOnly extends Strategy {\n /**\n * @private\n * @param {Request|string} request A request to run this strategy for.\n * @param {workbox-strategies.StrategyHandler} handler The event that\n * triggered the request.\n * @return {Promise}\n */\n async _handle(request, handler) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(request, Request, {\n moduleName: 'workbox-strategies',\n className: this.constructor.name,\n funcName: 'makeRequest',\n paramName: 'request',\n });\n }\n const response = await handler.cacheMatch(request);\n if (process.env.NODE_ENV !== 'production') {\n logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));\n if (response) {\n logger.log(`Found a cached response in the '${this.cacheName}' ` + `cache.`);\n messages.printFinalResponse(response);\n }\n else {\n logger.log(`No response found in the '${this.cacheName}' cache.`);\n }\n logger.groupEnd();\n }\n if (!response) {\n throw new WorkboxError('no-response', { url: request.url });\n }\n return response;\n }\n}\nexport { CacheOnly };\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 { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { cacheOkAndOpaquePlugin } from './plugins/cacheOkAndOpaquePlugin.js';\nimport { Strategy } from './Strategy.js';\nimport { messages } from './utils/messages.js';\nimport './_version.js';\n/**\n * An implementation of a\n * [network first](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#network-first-falling-back-to-cache)\n * request strategy.\n *\n * By default, this strategy will cache responses with a 200 status code as\n * well as [opaque responses](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses).\n * Opaque responses are are cross-origin requests where the response doesn't\n * support [CORS](https://enable-cors.org/).\n *\n * If the network request fails, and there is no cache match, this will throw\n * a `WorkboxError` exception.\n *\n * @extends workbox-strategies.Strategy\n * @memberof workbox-strategies\n */\nclass NetworkFirst extends Strategy {\n /**\n * @param {Object} [options]\n * @param {string} [options.cacheName] Cache name to store and retrieve\n * requests. Defaults to cache names provided by\n * {@link workbox-core.cacheNames}.\n * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}\n * to use in conjunction with this caching strategy.\n * @param {Object} [options.fetchOptions] Values passed along to the\n * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)\n * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)\n * `fetch()` requests made by this strategy.\n * @param {Object} [options.matchOptions] [`CacheQueryOptions`](https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions)\n * @param {number} [options.networkTimeoutSeconds] If set, any network requests\n * that fail to respond within the timeout will fallback to the cache.\n *\n * This option can be used to combat\n * \"[lie-fi]{@link https://developers.google.com/web/fundamentals/performance/poor-connectivity/#lie-fi}\"\n * scenarios.\n */\n constructor(options = {}) {\n super(options);\n // If this instance contains no plugins with a 'cacheWillUpdate' callback,\n // prepend the `cacheOkAndOpaquePlugin` plugin to the plugins list.\n if (!this.plugins.some((p) => 'cacheWillUpdate' in p)) {\n this.plugins.unshift(cacheOkAndOpaquePlugin);\n }\n this._networkTimeoutSeconds = options.networkTimeoutSeconds || 0;\n if (process.env.NODE_ENV !== 'production') {\n if (this._networkTimeoutSeconds) {\n assert.isType(this._networkTimeoutSeconds, 'number', {\n moduleName: 'workbox-strategies',\n className: this.constructor.name,\n funcName: 'constructor',\n paramName: 'networkTimeoutSeconds',\n });\n }\n }\n }\n /**\n * @private\n * @param {Request|string} request A request to run this strategy for.\n * @param {workbox-strategies.StrategyHandler} handler The event that\n * triggered the request.\n * @return {Promise}\n */\n async _handle(request, handler) {\n const logs = [];\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(request, Request, {\n moduleName: 'workbox-strategies',\n className: this.constructor.name,\n funcName: 'handle',\n paramName: 'makeRequest',\n });\n }\n const promises = [];\n let timeoutId;\n if (this._networkTimeoutSeconds) {\n const { id, promise } = this._getTimeoutPromise({ request, logs, handler });\n timeoutId = id;\n promises.push(promise);\n }\n const networkPromise = this._getNetworkPromise({\n timeoutId,\n request,\n logs,\n handler,\n });\n promises.push(networkPromise);\n const response = await handler.waitUntil((async () => {\n // Promise.race() will resolve as soon as the first promise resolves.\n return ((await handler.waitUntil(Promise.race(promises))) ||\n // If Promise.race() resolved with null, it might be due to a network\n // timeout + a cache miss. If that were to happen, we'd rather wait until\n // the networkPromise resolves instead of returning null.\n // Note that it's fine to await an already-resolved promise, so we don't\n // have to check to see if it's still \"in flight\".\n (await networkPromise));\n })());\n if (process.env.NODE_ENV !== 'production') {\n logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));\n for (const log of logs) {\n logger.log(log);\n }\n messages.printFinalResponse(response);\n logger.groupEnd();\n }\n if (!response) {\n throw new WorkboxError('no-response', { url: request.url });\n }\n return response;\n }\n /**\n * @param {Object} options\n * @param {Request} options.request\n * @param {Array} options.logs A reference to the logs array\n * @param {Event} options.event\n * @return {Promise}\n *\n * @private\n */\n _getTimeoutPromise({ request, logs, handler, }) {\n let timeoutId;\n const timeoutPromise = new Promise((resolve) => {\n const onNetworkTimeout = async () => {\n if (process.env.NODE_ENV !== 'production') {\n logs.push(`Timing out the network response at ` +\n `${this._networkTimeoutSeconds} seconds.`);\n }\n resolve(await handler.cacheMatch(request));\n };\n timeoutId = setTimeout(onNetworkTimeout, this._networkTimeoutSeconds * 1000);\n });\n return {\n promise: timeoutPromise,\n id: timeoutId,\n };\n }\n /**\n * @param {Object} options\n * @param {number|undefined} options.timeoutId\n * @param {Request} options.request\n * @param {Array} options.logs A reference to the logs Array.\n * @param {Event} options.event\n * @return {Promise}\n *\n * @private\n */\n async _getNetworkPromise({ timeoutId, request, logs, handler, }) {\n let error;\n let response;\n try {\n response = await handler.fetchAndCachePut(request);\n }\n catch (fetchError) {\n if (fetchError instanceof Error) {\n error = fetchError;\n }\n }\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n if (process.env.NODE_ENV !== 'production') {\n if (response) {\n logs.push(`Got response from network.`);\n }\n else {\n logs.push(`Unable to get a response from the network. Will respond ` +\n `with a cached response.`);\n }\n }\n if (error || !response) {\n response = await handler.cacheMatch(request);\n if (process.env.NODE_ENV !== 'production') {\n if (response) {\n logs.push(`Found a cached response in the '${this.cacheName}'` + ` cache.`);\n }\n else {\n logs.push(`No response found in the '${this.cacheName}' cache.`);\n }\n }\n }\n return response;\n }\n}\nexport { NetworkFirst };\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 { logger } from 'workbox-core/_private/logger.js';\nimport { timeout } from 'workbox-core/_private/timeout.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { Strategy } from './Strategy.js';\nimport { messages } from './utils/messages.js';\nimport './_version.js';\n/**\n * An implementation of a\n * [network-only](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#network-only)\n * request strategy.\n *\n * This class is useful if you want to take advantage of any\n * [Workbox plugins](https://developer.chrome.com/docs/workbox/using-plugins/).\n *\n * If the network request fails, this will throw a `WorkboxError` exception.\n *\n * @extends workbox-strategies.Strategy\n * @memberof workbox-strategies\n */\nclass NetworkOnly extends Strategy {\n /**\n * @param {Object} [options]\n * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}\n * to use in conjunction with this caching strategy.\n * @param {Object} [options.fetchOptions] Values passed along to the\n * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)\n * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)\n * `fetch()` requests made by this strategy.\n * @param {number} [options.networkTimeoutSeconds] If set, any network requests\n * that fail to respond within the timeout will result in a network error.\n */\n constructor(options = {}) {\n super(options);\n this._networkTimeoutSeconds = options.networkTimeoutSeconds || 0;\n }\n /**\n * @private\n * @param {Request|string} request A request to run this strategy for.\n * @param {workbox-strategies.StrategyHandler} handler The event that\n * triggered the request.\n * @return {Promise}\n */\n async _handle(request, handler) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(request, Request, {\n moduleName: 'workbox-strategies',\n className: this.constructor.name,\n funcName: '_handle',\n paramName: 'request',\n });\n }\n let error = undefined;\n let response;\n try {\n const promises = [\n handler.fetch(request),\n ];\n if (this._networkTimeoutSeconds) {\n const timeoutPromise = timeout(this._networkTimeoutSeconds * 1000);\n promises.push(timeoutPromise);\n }\n response = await Promise.race(promises);\n if (!response) {\n throw new Error(`Timed out the network response after ` +\n `${this._networkTimeoutSeconds} seconds.`);\n }\n }\n catch (err) {\n if (err instanceof Error) {\n error = err;\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));\n if (response) {\n logger.log(`Got response from network.`);\n }\n else {\n logger.log(`Unable to get a response from the network.`);\n }\n messages.printFinalResponse(response);\n logger.groupEnd();\n }\n if (!response) {\n throw new WorkboxError('no-response', { url: request.url, error });\n }\n return response;\n }\n}\nexport { NetworkOnly };\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 { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { cacheOkAndOpaquePlugin } from './plugins/cacheOkAndOpaquePlugin.js';\nimport { Strategy } from './Strategy.js';\nimport { messages } from './utils/messages.js';\nimport './_version.js';\n/**\n * An implementation of a\n * [stale-while-revalidate](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#stale-while-revalidate)\n * request strategy.\n *\n * Resources are requested from both the cache and the network in parallel.\n * The strategy will respond with the cached version if available, otherwise\n * wait for the network response. The cache is updated with the network response\n * with each successful request.\n *\n * By default, this strategy will cache responses with a 200 status code as\n * well as [opaque responses](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses).\n * Opaque responses are cross-origin requests where the response doesn't\n * support [CORS](https://enable-cors.org/).\n *\n * If the network request fails, and there is no cache match, this will throw\n * a `WorkboxError` exception.\n *\n * @extends workbox-strategies.Strategy\n * @memberof workbox-strategies\n */\nclass StaleWhileRevalidate extends Strategy {\n /**\n * @param {Object} [options]\n * @param {string} [options.cacheName] Cache name to store and retrieve\n * requests. Defaults to cache names provided by\n * {@link workbox-core.cacheNames}.\n * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}\n * to use in conjunction with this caching strategy.\n * @param {Object} [options.fetchOptions] Values passed along to the\n * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)\n * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)\n * `fetch()` requests made by this strategy.\n * @param {Object} [options.matchOptions] [`CacheQueryOptions`](https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions)\n */\n constructor(options = {}) {\n super(options);\n // If this instance contains no plugins with a 'cacheWillUpdate' callback,\n // prepend the `cacheOkAndOpaquePlugin` plugin to the plugins list.\n if (!this.plugins.some((p) => 'cacheWillUpdate' in p)) {\n this.plugins.unshift(cacheOkAndOpaquePlugin);\n }\n }\n /**\n * @private\n * @param {Request|string} request A request to run this strategy for.\n * @param {workbox-strategies.StrategyHandler} handler The event that\n * triggered the request.\n * @return {Promise}\n */\n async _handle(request, handler) {\n const logs = [];\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(request, Request, {\n moduleName: 'workbox-strategies',\n className: this.constructor.name,\n funcName: 'handle',\n paramName: 'request',\n });\n }\n const fetchAndCachePromise = handler.fetchAndCachePut(request).catch(() => {\n // Swallow this error because a 'no-response' error will be thrown in\n // main handler return flow. This will be in the `waitUntil()` flow.\n });\n void handler.waitUntil(fetchAndCachePromise);\n let response = await handler.cacheMatch(request);\n let error;\n if (response) {\n if (process.env.NODE_ENV !== 'production') {\n logs.push(`Found a cached response in the '${this.cacheName}'` +\n ` cache. Will update with the network response in the background.`);\n }\n }\n else {\n if (process.env.NODE_ENV !== 'production') {\n logs.push(`No response found in the '${this.cacheName}' cache. ` +\n `Will wait for the network response.`);\n }\n try {\n // NOTE(philipwalton): Really annoying that we have to type cast here.\n // https://github.com/microsoft/TypeScript/issues/20006\n response = (await fetchAndCachePromise);\n }\n catch (err) {\n if (err instanceof Error) {\n error = err;\n }\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));\n for (const log of logs) {\n logger.log(log);\n }\n messages.printFinalResponse(response);\n logger.groupEnd();\n }\n if (!response) {\n throw new WorkboxError('no-response', { url: request.url, error });\n }\n return response;\n }\n}\nexport { StaleWhileRevalidate };\n"],"names":["self","_","e","toRequest","input","Request","StrategyHandler","constructor","strategy","options","this","_cacheKeys","Object","assign","event","_strategy","_handlerDeferred","Deferred","_extendLifetimePromises","_plugins","plugins","_pluginStateMap","Map","plugin","set","waitUntil","promise","async","request","mode","FetchEvent","preloadResponse","possiblePreloadResponse","originalRequest","hasCallback","clone","cb","iterateCallbacks","err","Error","WorkboxError","thrownErrorMessage","message","pluginFilteredRequest","fetchResponse","fetch","undefined","fetchOptions","callback","response","error","runCallbacks","responseClone","cachePut","key","cachedResponse","cacheName","matchOptions","effectiveRequest","getCacheKey","multiMatchOptions","caches","match","timeout","url","getFriendlyURL","responseToCache","_ensureResponseSafeToCache","cache","open","hasCacheUpdateCallback","oldResponse","cacheMatchIgnoreParams","put","name","executeQuotaErrorCallbacks","newResponse","params","param","state","get","statefulCallback","statefulParam","push","length","promises","splice","firstRejection","Promise","allSettled","find","i","status","reason","destroy","resolve","pluginsUsed","Strategy","cacheNames","getRuntimeName","handle","responseDone","handleAll","handler","_getResponse","_awaitComplete","_handle","type","doneWaiting","waitUntilError","cacheOkAndOpaquePlugin","cacheWillUpdate","cacheMatch","fetchAndCachePut","super","some","p","unshift","_networkTimeoutSeconds","networkTimeoutSeconds","logs","timeoutId","id","_getTimeoutPromise","networkPromise","_getNetworkPromise","race","setTimeout","fetchError","clearTimeout","timeoutPromise","fetchAndCachePromise","catch"],"mappings":"+FAEA,IACIA,KAAK,6BAA+BC,GACxC,CACA,MAAOC,GAAK,CCWZ,SAASC,EAAUC,GACf,MAAwB,iBAAVA,EAAqB,IAAIC,QAAQD,GAASA,CAC5D,CAUA,MAAME,EAiBFC,YAAYC,EAAUC,GAClBC,KAAKC,EAAa,CAAA,EA8ClBC,OAAOC,OAAOH,KAAMD,GACpBC,KAAKI,MAAQL,EAAQK,MACrBJ,KAAKK,EAAYP,EACjBE,KAAKM,EAAmB,IAAIC,WAC5BP,KAAKQ,EAA0B,GAG/BR,KAAKS,EAAW,IAAIX,EAASY,SAC7BV,KAAKW,EAAkB,IAAIC,IAC3B,IAAK,MAAMC,KAAUb,KAAKS,EACtBT,KAAKW,EAAgBG,IAAID,EAAQ,CAAA,GAErCb,KAAKI,MAAMW,UAAUf,KAAKM,EAAiBU,QAC/C,CAcAC,YAAYvB,GACR,MAAMU,MAAEA,GAAUJ,KAClB,IAAIkB,EAAUzB,EAAUC,GACxB,GAAqB,aAAjBwB,EAAQC,MACRf,aAAiBgB,YACjBhB,EAAMiB,gBAAiB,CACvB,MAAMC,QAAiClB,EAAMiB,gBAC7C,GAAIC,EAKA,OAAOA,CAE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B,CAYA,IAAKW,EACD,MAAM,IAAIT,EAAAA,aAAa,cAAe,CAAEwB,IAAKpC,EAAQoC,IAAKd,UAE9D,OAAOD,CACX,0BC5DJ,cAAmCgD,EAc/B1F,YAAYE,EAAU,IAClByG,MAAMzG,GAGDC,KAAKU,QAAQ+F,MAAMC,GAAM,oBAAqBA,KAC/C1G,KAAKU,QAAQiG,QAAQP,EAE7B,CAQAnF,cAAcC,EAAS2E,GAUnB,MAAM4B,EAAuB5B,EAAQU,iBAAiBrF,GAASwG,OAAM,SAIhE7B,EAAQ9E,UAAU0G,GACvB,IACIjF,EADAD,QAAiBsD,EAAQS,WAAWpF,GAExC,GAAIqB,QAWA,IAGIA,QAAkBkF,CACtB,CACA,MAAO7F,GACCA,aAAeC,QACfW,EAAQZ,EAEhB,CAUJ,IAAKW,EACD,MAAM,IAAIT,EAAAA,aAAa,cAAe,CAAEwB,IAAKpC,EAAQoC,IAAKd,UAE9D,OAAOD,CACX"} \ No newline at end of file diff --git a/node_modules/workbox-strategies/index.d.ts b/node_modules/workbox-strategies/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b51c544df121855e4efe3c984b4bb960362e5d4e --- /dev/null +++ b/node_modules/workbox-strategies/index.d.ts @@ -0,0 +1,20 @@ +import { CacheFirst } from './CacheFirst.js'; +import { CacheOnly } from './CacheOnly.js'; +import { NetworkFirst, NetworkFirstOptions } from './NetworkFirst.js'; +import { NetworkOnly, NetworkOnlyOptions } from './NetworkOnly.js'; +import { StaleWhileRevalidate } from './StaleWhileRevalidate.js'; +import { Strategy, StrategyOptions } from './Strategy.js'; +import { StrategyHandler } from './StrategyHandler.js'; +import './_version.js'; +declare global { + interface FetchEvent { + readonly preloadResponse: Promise; + } +} +/** + * There are common caching strategies that most service workers will need + * and use. This module provides simple implementations of these strategies. + * + * @module workbox-strategies + */ +export { CacheFirst, CacheOnly, NetworkFirst, NetworkFirstOptions, NetworkOnly, NetworkOnlyOptions, StaleWhileRevalidate, Strategy, StrategyHandler, StrategyOptions, }; diff --git a/node_modules/workbox-strategies/index.js b/node_modules/workbox-strategies/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a2887f36a5ad30bb196014ea6d15134a6603fd47 --- /dev/null +++ b/node_modules/workbox-strategies/index.js @@ -0,0 +1,22 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { CacheFirst } from './CacheFirst.js'; +import { CacheOnly } from './CacheOnly.js'; +import { NetworkFirst } from './NetworkFirst.js'; +import { NetworkOnly } from './NetworkOnly.js'; +import { StaleWhileRevalidate } from './StaleWhileRevalidate.js'; +import { Strategy } from './Strategy.js'; +import { StrategyHandler } from './StrategyHandler.js'; +import './_version.js'; +/** + * There are common caching strategies that most service workers will need + * and use. This module provides simple implementations of these strategies. + * + * @module workbox-strategies + */ +export { CacheFirst, CacheOnly, NetworkFirst, NetworkOnly, StaleWhileRevalidate, Strategy, StrategyHandler, }; diff --git a/node_modules/workbox-strategies/index.mjs b/node_modules/workbox-strategies/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..833b6a2f3226fec78490a3b7a622dc5146f94b53 --- /dev/null +++ b/node_modules/workbox-strategies/index.mjs @@ -0,0 +1 @@ +export * from './index.js'; \ No newline at end of file diff --git a/node_modules/workbox-strategies/package.json b/node_modules/workbox-strategies/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3234fed32d8629b29318150248d50a68958ce62e --- /dev/null +++ b/node_modules/workbox-strategies/package.json @@ -0,0 +1,32 @@ +{ + "name": "workbox-strategies", + "version": "7.4.1", + "license": "MIT", + "author": "Google's Web DevRel Team and Google's Aurora Team", + "description": "A service worker helper library implementing common caching strategies.", + "repository": { + "type": "git", + "url": "git+https://github.com/googlechrome/workbox.git" + }, + "bugs": "https://github.com/googlechrome/workbox/issues", + "homepage": "https://github.com/GoogleChrome/workbox", + "keywords": [ + "workbox", + "workboxjs", + "service worker", + "sw", + "router", + "routing" + ], + "workbox": { + "browserNamespace": "workbox.strategies", + "packageType": "sw" + }, + "main": "index.js", + "module": "index.mjs", + "types": "index.d.ts", + "dependencies": { + "workbox-core": "7.4.1" + }, + "gitHead": "62b9d8ba8eb3c1a2ab8aac9d84c90cda7865d6a3" +} diff --git a/node_modules/workbox-strategies/plugins/cacheOkAndOpaquePlugin.d.ts b/node_modules/workbox-strategies/plugins/cacheOkAndOpaquePlugin.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8e63142b255ffb695edfa44d0ce0d0984d7634e5 --- /dev/null +++ b/node_modules/workbox-strategies/plugins/cacheOkAndOpaquePlugin.d.ts @@ -0,0 +1,3 @@ +import { WorkboxPlugin } from 'workbox-core/types.js'; +import '../_version.js'; +export declare const cacheOkAndOpaquePlugin: WorkboxPlugin; diff --git a/node_modules/workbox-strategies/plugins/cacheOkAndOpaquePlugin.js b/node_modules/workbox-strategies/plugins/cacheOkAndOpaquePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..db03530bf21cac86b4a9ce30ba23b6b62437adbc --- /dev/null +++ b/node_modules/workbox-strategies/plugins/cacheOkAndOpaquePlugin.js @@ -0,0 +1,26 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import '../_version.js'; +export const cacheOkAndOpaquePlugin = { + /** + * Returns a valid response (to allow caching) if the status is 200 (OK) or + * 0 (opaque). + * + * @param {Object} options + * @param {Response} options.response + * @return {Response|null} + * + * @private + */ + cacheWillUpdate: async ({ response }) => { + if (response.status === 200 || response.status === 0) { + return response; + } + return null; + }, +}; diff --git a/node_modules/workbox-strategies/plugins/cacheOkAndOpaquePlugin.mjs b/node_modules/workbox-strategies/plugins/cacheOkAndOpaquePlugin.mjs new file mode 100644 index 0000000000000000000000000000000000000000..bd224b7d7ceff0cdead439bc81ae1e3d763518af --- /dev/null +++ b/node_modules/workbox-strategies/plugins/cacheOkAndOpaquePlugin.mjs @@ -0,0 +1 @@ +export * from './cacheOkAndOpaquePlugin.js'; \ No newline at end of file diff --git a/node_modules/workbox-strategies/src/CacheFirst.ts b/node_modules/workbox-strategies/src/CacheFirst.ts new file mode 100644 index 0000000000000000000000000000000000000000..963da690a0c1783294bc059b6ac45c24e710edd4 --- /dev/null +++ b/node_modules/workbox-strategies/src/CacheFirst.ts @@ -0,0 +1,101 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {assert} from 'workbox-core/_private/assert.js'; +import {logger} from 'workbox-core/_private/logger.js'; +import {WorkboxError} from 'workbox-core/_private/WorkboxError.js'; + +import {Strategy} from './Strategy.js'; +import {StrategyHandler} from './StrategyHandler.js'; +import {messages} from './utils/messages.js'; +import './_version.js'; + +/** + * An implementation of a [cache-first](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#cache-first-falling-back-to-network) + * request strategy. + * + * A cache first strategy is useful for assets that have been revisioned, + * such as URLs like `/styles/example.a8f5f1.css`, since they + * can be cached for long periods of time. + * + * If the network request fails, and there is no cache match, this will throw + * a `WorkboxError` exception. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-strategies + */ +class CacheFirst extends Strategy { + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + async _handle(request: Request, handler: StrategyHandler): Promise { + const logs = []; + + if (process.env.NODE_ENV !== 'production') { + assert!.isInstance(request, Request, { + moduleName: 'workbox-strategies', + className: this.constructor.name, + funcName: 'makeRequest', + paramName: 'request', + }); + } + + let response = await handler.cacheMatch(request); + + let error: Error | undefined = undefined; + if (!response) { + if (process.env.NODE_ENV !== 'production') { + logs.push( + `No response found in the '${this.cacheName}' cache. ` + + `Will respond with a network request.`, + ); + } + try { + response = await handler.fetchAndCachePut(request); + } catch (err) { + if (err instanceof Error) { + error = err; + } + } + + if (process.env.NODE_ENV !== 'production') { + if (response) { + logs.push(`Got response from network.`); + } else { + logs.push(`Unable to get a response from the network.`); + } + } + } else { + if (process.env.NODE_ENV !== 'production') { + logs.push(`Found a cached response in the '${this.cacheName}' cache.`); + } + } + + if (process.env.NODE_ENV !== 'production') { + logger.groupCollapsed( + messages.strategyStart(this.constructor.name, request), + ); + for (const log of logs) { + logger.log(log); + } + messages.printFinalResponse(response); + logger.groupEnd(); + } + + if (!response) { + throw new WorkboxError('no-response', {url: request.url, error}); + } + return response; + } +} + +export {CacheFirst}; diff --git a/node_modules/workbox-strategies/src/CacheOnly.ts b/node_modules/workbox-strategies/src/CacheOnly.ts new file mode 100644 index 0000000000000000000000000000000000000000..12714bcc6aa6ee1115991af8593e2249f23d5177 --- /dev/null +++ b/node_modules/workbox-strategies/src/CacheOnly.ts @@ -0,0 +1,72 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {assert} from 'workbox-core/_private/assert.js'; +import {logger} from 'workbox-core/_private/logger.js'; +import {WorkboxError} from 'workbox-core/_private/WorkboxError.js'; + +import {Strategy} from './Strategy.js'; +import {StrategyHandler} from './StrategyHandler.js'; +import {messages} from './utils/messages.js'; +import './_version.js'; + +/** + * An implementation of a [cache-only](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#cache-only) + * request strategy. + * + * This class is useful if you want to take advantage of any + * [Workbox plugins](https://developer.chrome.com/docs/workbox/using-plugins/). + * + * If there is no cache match, this will throw a `WorkboxError` exception. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-strategies + */ +class CacheOnly extends Strategy { + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + async _handle(request: Request, handler: StrategyHandler): Promise { + if (process.env.NODE_ENV !== 'production') { + assert!.isInstance(request, Request, { + moduleName: 'workbox-strategies', + className: this.constructor.name, + funcName: 'makeRequest', + paramName: 'request', + }); + } + + const response = await handler.cacheMatch(request); + + if (process.env.NODE_ENV !== 'production') { + logger.groupCollapsed( + messages.strategyStart(this.constructor.name, request), + ); + if (response) { + logger.log( + `Found a cached response in the '${this.cacheName}' ` + `cache.`, + ); + messages.printFinalResponse(response); + } else { + logger.log(`No response found in the '${this.cacheName}' cache.`); + } + logger.groupEnd(); + } + + if (!response) { + throw new WorkboxError('no-response', {url: request.url}); + } + return response; + } +} + +export {CacheOnly}; diff --git a/node_modules/workbox-strategies/src/NetworkFirst.ts b/node_modules/workbox-strategies/src/NetworkFirst.ts new file mode 100644 index 0000000000000000000000000000000000000000..2495dd623c47f13262f0e99f47989c1464452775 --- /dev/null +++ b/node_modules/workbox-strategies/src/NetworkFirst.ts @@ -0,0 +1,259 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {assert} from 'workbox-core/_private/assert.js'; +import {logger} from 'workbox-core/_private/logger.js'; +import {WorkboxError} from 'workbox-core/_private/WorkboxError.js'; + +import {cacheOkAndOpaquePlugin} from './plugins/cacheOkAndOpaquePlugin.js'; +import {Strategy, StrategyOptions} from './Strategy.js'; +import {StrategyHandler} from './StrategyHandler.js'; +import {messages} from './utils/messages.js'; +import './_version.js'; + +export interface NetworkFirstOptions extends StrategyOptions { + networkTimeoutSeconds?: number; +} + +/** + * An implementation of a + * [network first](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#network-first-falling-back-to-cache) + * request strategy. + * + * By default, this strategy will cache responses with a 200 status code as + * well as [opaque responses](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses). + * Opaque responses are are cross-origin requests where the response doesn't + * support [CORS](https://enable-cors.org/). + * + * If the network request fails, and there is no cache match, this will throw + * a `WorkboxError` exception. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-strategies + */ +class NetworkFirst extends Strategy { + private readonly _networkTimeoutSeconds: number; + + /** + * @param {Object} [options] + * @param {string} [options.cacheName] Cache name to store and retrieve + * requests. Defaults to cache names provided by + * {@link workbox-core.cacheNames}. + * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins} + * to use in conjunction with this caching strategy. + * @param {Object} [options.fetchOptions] Values passed along to the + * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) + * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796) + * `fetch()` requests made by this strategy. + * @param {Object} [options.matchOptions] [`CacheQueryOptions`](https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions) + * @param {number} [options.networkTimeoutSeconds] If set, any network requests + * that fail to respond within the timeout will fallback to the cache. + * + * This option can be used to combat + * "[lie-fi]{@link https://developers.google.com/web/fundamentals/performance/poor-connectivity/#lie-fi}" + * scenarios. + */ + constructor(options: NetworkFirstOptions = {}) { + super(options); + + // If this instance contains no plugins with a 'cacheWillUpdate' callback, + // prepend the `cacheOkAndOpaquePlugin` plugin to the plugins list. + if (!this.plugins.some((p) => 'cacheWillUpdate' in p)) { + this.plugins.unshift(cacheOkAndOpaquePlugin); + } + + this._networkTimeoutSeconds = options.networkTimeoutSeconds || 0; + if (process.env.NODE_ENV !== 'production') { + if (this._networkTimeoutSeconds) { + assert!.isType(this._networkTimeoutSeconds, 'number', { + moduleName: 'workbox-strategies', + className: this.constructor.name, + funcName: 'constructor', + paramName: 'networkTimeoutSeconds', + }); + } + } + } + + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + async _handle(request: Request, handler: StrategyHandler): Promise { + const logs: any[] = []; + + if (process.env.NODE_ENV !== 'production') { + assert!.isInstance(request, Request, { + moduleName: 'workbox-strategies', + className: this.constructor.name, + funcName: 'handle', + paramName: 'makeRequest', + }); + } + + const promises: Promise[] = []; + let timeoutId: number | undefined; + + if (this._networkTimeoutSeconds) { + const {id, promise} = this._getTimeoutPromise({request, logs, handler}); + timeoutId = id; + promises.push(promise); + } + + const networkPromise = this._getNetworkPromise({ + timeoutId, + request, + logs, + handler, + }); + + promises.push(networkPromise); + + const response = await handler.waitUntil( + (async () => { + // Promise.race() will resolve as soon as the first promise resolves. + return ( + (await handler.waitUntil(Promise.race(promises))) || + // If Promise.race() resolved with null, it might be due to a network + // timeout + a cache miss. If that were to happen, we'd rather wait until + // the networkPromise resolves instead of returning null. + // Note that it's fine to await an already-resolved promise, so we don't + // have to check to see if it's still "in flight". + (await networkPromise) + ); + })(), + ); + + if (process.env.NODE_ENV !== 'production') { + logger.groupCollapsed( + messages.strategyStart(this.constructor.name, request), + ); + for (const log of logs) { + logger.log(log); + } + messages.printFinalResponse(response); + logger.groupEnd(); + } + + if (!response) { + throw new WorkboxError('no-response', {url: request.url}); + } + return response; + } + + /** + * @param {Object} options + * @param {Request} options.request + * @param {Array} options.logs A reference to the logs array + * @param {Event} options.event + * @return {Promise} + * + * @private + */ + private _getTimeoutPromise({ + request, + logs, + handler, + }: { + request: Request; + logs: any[]; + handler: StrategyHandler; + }): {promise: Promise; id?: number} { + let timeoutId; + const timeoutPromise: Promise = new Promise( + (resolve) => { + const onNetworkTimeout = async () => { + if (process.env.NODE_ENV !== 'production') { + logs.push( + `Timing out the network response at ` + + `${this._networkTimeoutSeconds} seconds.`, + ); + } + resolve(await handler.cacheMatch(request)); + }; + timeoutId = setTimeout( + onNetworkTimeout, + this._networkTimeoutSeconds * 1000, + ); + }, + ); + + return { + promise: timeoutPromise, + id: timeoutId, + }; + } + + /** + * @param {Object} options + * @param {number|undefined} options.timeoutId + * @param {Request} options.request + * @param {Array} options.logs A reference to the logs Array. + * @param {Event} options.event + * @return {Promise} + * + * @private + */ + async _getNetworkPromise({ + timeoutId, + request, + logs, + handler, + }: { + request: Request; + logs: any[]; + timeoutId?: number; + handler: StrategyHandler; + }): Promise { + let error; + let response; + try { + response = await handler.fetchAndCachePut(request); + } catch (fetchError) { + if (fetchError instanceof Error) { + error = fetchError; + } + } + + if (timeoutId) { + clearTimeout(timeoutId); + } + + if (process.env.NODE_ENV !== 'production') { + if (response) { + logs.push(`Got response from network.`); + } else { + logs.push( + `Unable to get a response from the network. Will respond ` + + `with a cached response.`, + ); + } + } + + if (error || !response) { + response = await handler.cacheMatch(request); + + if (process.env.NODE_ENV !== 'production') { + if (response) { + logs.push( + `Found a cached response in the '${this.cacheName}'` + ` cache.`, + ); + } else { + logs.push(`No response found in the '${this.cacheName}' cache.`); + } + } + } + + return response; + } +} + +export {NetworkFirst}; diff --git a/node_modules/workbox-strategies/src/NetworkOnly.ts b/node_modules/workbox-strategies/src/NetworkOnly.ts new file mode 100644 index 0000000000000000000000000000000000000000..b129555eeaf87255258b8410f86ba89f33bfeed0 --- /dev/null +++ b/node_modules/workbox-strategies/src/NetworkOnly.ts @@ -0,0 +1,122 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {assert} from 'workbox-core/_private/assert.js'; +import {logger} from 'workbox-core/_private/logger.js'; +import {timeout} from 'workbox-core/_private/timeout.js'; +import {WorkboxError} from 'workbox-core/_private/WorkboxError.js'; + +import {Strategy, StrategyOptions} from './Strategy.js'; +import {StrategyHandler} from './StrategyHandler.js'; +import {messages} from './utils/messages.js'; +import './_version.js'; + +interface NetworkOnlyOptions + extends Omit { + networkTimeoutSeconds?: number; +} + +/** + * An implementation of a + * [network-only](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#network-only) + * request strategy. + * + * This class is useful if you want to take advantage of any + * [Workbox plugins](https://developer.chrome.com/docs/workbox/using-plugins/). + * + * If the network request fails, this will throw a `WorkboxError` exception. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-strategies + */ +class NetworkOnly extends Strategy { + private readonly _networkTimeoutSeconds: number; + + /** + * @param {Object} [options] + * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins} + * to use in conjunction with this caching strategy. + * @param {Object} [options.fetchOptions] Values passed along to the + * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) + * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796) + * `fetch()` requests made by this strategy. + * @param {number} [options.networkTimeoutSeconds] If set, any network requests + * that fail to respond within the timeout will result in a network error. + */ + constructor(options: NetworkOnlyOptions = {}) { + super(options); + + this._networkTimeoutSeconds = options.networkTimeoutSeconds || 0; + } + + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + async _handle(request: Request, handler: StrategyHandler): Promise { + if (process.env.NODE_ENV !== 'production') { + assert!.isInstance(request, Request, { + moduleName: 'workbox-strategies', + className: this.constructor.name, + funcName: '_handle', + paramName: 'request', + }); + } + + let error: Error | undefined = undefined; + let response: Response | undefined; + + try { + const promises: Promise[] = [ + handler.fetch(request), + ]; + + if (this._networkTimeoutSeconds) { + const timeoutPromise = timeout( + this._networkTimeoutSeconds * 1000, + ) as Promise; + promises.push(timeoutPromise); + } + + response = await Promise.race(promises); + if (!response) { + throw new Error( + `Timed out the network response after ` + + `${this._networkTimeoutSeconds} seconds.`, + ); + } + } catch (err) { + if (err instanceof Error) { + error = err; + } + } + + if (process.env.NODE_ENV !== 'production') { + logger.groupCollapsed( + messages.strategyStart(this.constructor.name, request), + ); + if (response) { + logger.log(`Got response from network.`); + } else { + logger.log(`Unable to get a response from the network.`); + } + messages.printFinalResponse(response); + logger.groupEnd(); + } + + if (!response) { + throw new WorkboxError('no-response', {url: request.url, error}); + } + return response; + } +} + +export {NetworkOnly, NetworkOnlyOptions}; diff --git a/node_modules/workbox-strategies/src/StaleWhileRevalidate.ts b/node_modules/workbox-strategies/src/StaleWhileRevalidate.ts new file mode 100644 index 0000000000000000000000000000000000000000..4594941cc24f724708b9c6d536c4f7e1ae83937d --- /dev/null +++ b/node_modules/workbox-strategies/src/StaleWhileRevalidate.ts @@ -0,0 +1,135 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {assert} from 'workbox-core/_private/assert.js'; +import {logger} from 'workbox-core/_private/logger.js'; +import {WorkboxError} from 'workbox-core/_private/WorkboxError.js'; + +import {cacheOkAndOpaquePlugin} from './plugins/cacheOkAndOpaquePlugin.js'; +import {Strategy, StrategyOptions} from './Strategy.js'; +import {StrategyHandler} from './StrategyHandler.js'; +import {messages} from './utils/messages.js'; +import './_version.js'; + +/** + * An implementation of a + * [stale-while-revalidate](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#stale-while-revalidate) + * request strategy. + * + * Resources are requested from both the cache and the network in parallel. + * The strategy will respond with the cached version if available, otherwise + * wait for the network response. The cache is updated with the network response + * with each successful request. + * + * By default, this strategy will cache responses with a 200 status code as + * well as [opaque responses](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses). + * Opaque responses are cross-origin requests where the response doesn't + * support [CORS](https://enable-cors.org/). + * + * If the network request fails, and there is no cache match, this will throw + * a `WorkboxError` exception. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-strategies + */ +class StaleWhileRevalidate extends Strategy { + /** + * @param {Object} [options] + * @param {string} [options.cacheName] Cache name to store and retrieve + * requests. Defaults to cache names provided by + * {@link workbox-core.cacheNames}. + * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins} + * to use in conjunction with this caching strategy. + * @param {Object} [options.fetchOptions] Values passed along to the + * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) + * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796) + * `fetch()` requests made by this strategy. + * @param {Object} [options.matchOptions] [`CacheQueryOptions`](https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions) + */ + constructor(options: StrategyOptions = {}) { + super(options); + + // If this instance contains no plugins with a 'cacheWillUpdate' callback, + // prepend the `cacheOkAndOpaquePlugin` plugin to the plugins list. + if (!this.plugins.some((p) => 'cacheWillUpdate' in p)) { + this.plugins.unshift(cacheOkAndOpaquePlugin); + } + } + + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + async _handle(request: Request, handler: StrategyHandler): Promise { + const logs = []; + + if (process.env.NODE_ENV !== 'production') { + assert!.isInstance(request, Request, { + moduleName: 'workbox-strategies', + className: this.constructor.name, + funcName: 'handle', + paramName: 'request', + }); + } + + const fetchAndCachePromise = handler.fetchAndCachePut(request).catch(() => { + // Swallow this error because a 'no-response' error will be thrown in + // main handler return flow. This will be in the `waitUntil()` flow. + }); + void handler.waitUntil(fetchAndCachePromise); + + let response = await handler.cacheMatch(request); + + let error; + if (response) { + if (process.env.NODE_ENV !== 'production') { + logs.push( + `Found a cached response in the '${this.cacheName}'` + + ` cache. Will update with the network response in the background.`, + ); + } + } else { + if (process.env.NODE_ENV !== 'production') { + logs.push( + `No response found in the '${this.cacheName}' cache. ` + + `Will wait for the network response.`, + ); + } + try { + // NOTE(philipwalton): Really annoying that we have to type cast here. + // https://github.com/microsoft/TypeScript/issues/20006 + response = (await fetchAndCachePromise) as Response | undefined; + } catch (err) { + if (err instanceof Error) { + error = err; + } + } + } + + if (process.env.NODE_ENV !== 'production') { + logger.groupCollapsed( + messages.strategyStart(this.constructor.name, request), + ); + for (const log of logs) { + logger.log(log); + } + messages.printFinalResponse(response); + logger.groupEnd(); + } + + if (!response) { + throw new WorkboxError('no-response', {url: request.url, error}); + } + return response; + } +} + +export {StaleWhileRevalidate}; diff --git a/node_modules/workbox-strategies/src/Strategy.ts b/node_modules/workbox-strategies/src/Strategy.ts new file mode 100644 index 0000000000000000000000000000000000000000..5ab8614551d2610b801bb02ca79b115456b20f23 --- /dev/null +++ b/node_modules/workbox-strategies/src/Strategy.ts @@ -0,0 +1,289 @@ +/* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {cacheNames} from 'workbox-core/_private/cacheNames.js'; +import {WorkboxError} from 'workbox-core/_private/WorkboxError.js'; +import {logger} from 'workbox-core/_private/logger.js'; +import {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.js'; +import { + HandlerCallbackOptions, + RouteHandlerObject, + WorkboxPlugin, +} from 'workbox-core/types.js'; + +import {StrategyHandler} from './StrategyHandler.js'; + +import './_version.js'; + +export interface StrategyOptions { + cacheName?: string; + plugins?: WorkboxPlugin[]; + fetchOptions?: RequestInit; + matchOptions?: CacheQueryOptions; +} + +/** + * An abstract base class that all other strategy classes must extend from: + * + * @memberof workbox-strategies + */ +abstract class Strategy implements RouteHandlerObject { + cacheName: string; + plugins: WorkboxPlugin[]; + fetchOptions?: RequestInit; + matchOptions?: CacheQueryOptions; + + protected abstract _handle( + request: Request, + handler: StrategyHandler, + ): Promise; + + /** + * Creates a new instance of the strategy and sets all documented option + * properties as public instance properties. + * + * Note: if a custom strategy class extends the base Strategy class and does + * not need more than these properties, it does not need to define its own + * constructor. + * + * @param {Object} [options] + * @param {string} [options.cacheName] Cache name to store and retrieve + * requests. Defaults to the cache names provided by + * {@link workbox-core.cacheNames}. + * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins} + * to use in conjunction with this caching strategy. + * @param {Object} [options.fetchOptions] Values passed along to the + * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) + * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796) + * `fetch()` requests made by this strategy. + * @param {Object} [options.matchOptions] The + * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions} + * for any `cache.match()` or `cache.put()` calls made by this strategy. + */ + constructor(options: StrategyOptions = {}) { + /** + * Cache name to store and retrieve + * requests. Defaults to the cache names provided by + * {@link workbox-core.cacheNames}. + * + * @type {string} + */ + this.cacheName = cacheNames.getRuntimeName(options.cacheName); + /** + * The list + * [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins} + * used by this strategy. + * + * @type {Array} + */ + this.plugins = options.plugins || []; + /** + * Values passed along to the + * [`init`]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters} + * of all fetch() requests made by this strategy. + * + * @type {Object} + */ + this.fetchOptions = options.fetchOptions; + /** + * The + * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions} + * for any `cache.match()` or `cache.put()` calls made by this strategy. + * + * @type {Object} + */ + this.matchOptions = options.matchOptions; + } + + /** + * Perform a request strategy and returns a `Promise` that will resolve with + * a `Response`, invoking all relevant plugin callbacks. + * + * When a strategy instance is registered with a Workbox + * {@link workbox-routing.Route}, this method is automatically + * called when the route matches. + * + * Alternatively, this method can be used in a standalone `FetchEvent` + * listener by passing it to `event.respondWith()`. + * + * @param {FetchEvent|Object} options A `FetchEvent` or an object with the + * properties listed below. + * @param {Request|string} options.request A request to run this strategy for. + * @param {ExtendableEvent} options.event The event associated with the + * request. + * @param {URL} [options.url] + * @param {*} [options.params] + */ + handle(options: FetchEvent | HandlerCallbackOptions): Promise { + const [responseDone] = this.handleAll(options); + return responseDone; + } + + /** + * Similar to {@link workbox-strategies.Strategy~handle}, but + * instead of just returning a `Promise` that resolves to a `Response` it + * it will return an tuple of `[response, done]` promises, where the former + * (`response`) is equivalent to what `handle()` returns, and the latter is a + * Promise that will resolve once any promises that were added to + * `event.waitUntil()` as part of performing the strategy have completed. + * + * You can await the `done` promise to ensure any extra work performed by + * the strategy (usually caching responses) completes successfully. + * + * @param {FetchEvent|Object} options A `FetchEvent` or an object with the + * properties listed below. + * @param {Request|string} options.request A request to run this strategy for. + * @param {ExtendableEvent} options.event The event associated with the + * request. + * @param {URL} [options.url] + * @param {*} [options.params] + * @return {Array} A tuple of [response, done] + * promises that can be used to determine when the response resolves as + * well as when the handler has completed all its work. + */ + handleAll( + options: FetchEvent | HandlerCallbackOptions, + ): [Promise, Promise] { + // Allow for flexible options to be passed. + if (options instanceof FetchEvent) { + options = { + event: options, + request: options.request, + }; + } + + const event = options.event; + const request = + typeof options.request === 'string' + ? new Request(options.request) + : options.request; + const params = 'params' in options ? options.params : undefined; + + const handler = new StrategyHandler(this, {event, request, params}); + + const responseDone = this._getResponse(handler, request, event); + const handlerDone = this._awaitComplete( + responseDone, + handler, + request, + event, + ); + + // Return an array of promises, suitable for use with Promise.all(). + return [responseDone, handlerDone]; + } + + async _getResponse( + handler: StrategyHandler, + request: Request, + event: ExtendableEvent, + ): Promise { + await handler.runCallbacks('handlerWillStart', {event, request}); + + let response: Response | undefined = undefined; + try { + response = await this._handle(request, handler); + // The "official" Strategy subclasses all throw this error automatically, + // but in case a third-party Strategy doesn't, ensure that we have a + // consistent failure when there's no response or an error response. + if (!response || response.type === 'error') { + throw new WorkboxError('no-response', {url: request.url}); + } + } catch (error) { + if (error instanceof Error) { + for (const callback of handler.iterateCallbacks('handlerDidError')) { + response = await callback({error, event, request}); + if (response) { + break; + } + } + } + + if (!response) { + throw error; + } else if (process.env.NODE_ENV !== 'production') { + logger.log( + `While responding to '${getFriendlyURL(request.url)}', ` + + `an ${ + error instanceof Error ? error.toString() : '' + } error occurred. Using a fallback response provided by ` + + `a handlerDidError plugin.`, + ); + } + } + + for (const callback of handler.iterateCallbacks('handlerWillRespond')) { + response = await callback({event, request, response}); + } + + return response; + } + + async _awaitComplete( + responseDone: Promise, + handler: StrategyHandler, + request: Request, + event: ExtendableEvent, + ): Promise { + let response; + let error; + + try { + response = await responseDone; + } catch (error) { + // Ignore errors, as response errors should be caught via the `response` + // promise above. The `done` promise will only throw for errors in + // promises passed to `handler.waitUntil()`. + } + + try { + await handler.runCallbacks('handlerDidRespond', { + event, + request, + response, + }); + await handler.doneWaiting(); + } catch (waitUntilError) { + if (waitUntilError instanceof Error) { + error = waitUntilError; + } + } + + await handler.runCallbacks('handlerDidComplete', { + event, + request, + response, + error: error as Error, + }); + handler.destroy(); + + if (error) { + throw error; + } + } +} + +export {Strategy}; + +/** + * Classes extending the `Strategy` based class should implement this method, + * and leverage the {@link workbox-strategies.StrategyHandler} + * arg to perform all fetching and cache logic, which will ensure all relevant + * cache, cache options, fetch options and plugins are used (per the current + * strategy instance). + * + * @name _handle + * @instance + * @abstract + * @function + * @param {Request} request + * @param {workbox-strategies.StrategyHandler} handler + * @return {Promise} + * + * @memberof workbox-strategies.Strategy + */ diff --git a/node_modules/workbox-strategies/src/StrategyHandler.ts b/node_modules/workbox-strategies/src/StrategyHandler.ts new file mode 100644 index 0000000000000000000000000000000000000000..56c60bcae23ede5b8532076089fd0023883086e3 --- /dev/null +++ b/node_modules/workbox-strategies/src/StrategyHandler.ts @@ -0,0 +1,640 @@ +/* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {assert} from 'workbox-core/_private/assert.js'; +import {cacheMatchIgnoreParams} from 'workbox-core/_private/cacheMatchIgnoreParams.js'; +import {Deferred} from 'workbox-core/_private/Deferred.js'; +import {executeQuotaErrorCallbacks} from 'workbox-core/_private/executeQuotaErrorCallbacks.js'; +import {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.js'; +import {logger} from 'workbox-core/_private/logger.js'; +import {timeout} from 'workbox-core/_private/timeout.js'; +import {WorkboxError} from 'workbox-core/_private/WorkboxError.js'; +import { + HandlerCallbackOptions, + MapLikeObject, + WorkboxPlugin, + WorkboxPluginCallbackParam, +} from 'workbox-core/types.js'; + +import {Strategy} from './Strategy.js'; +import './_version.js'; + +function toRequest(input: RequestInfo) { + return typeof input === 'string' ? new Request(input) : input; +} + +/** + * A class created every time a Strategy instance calls + * {@link workbox-strategies.Strategy~handle} or + * {@link workbox-strategies.Strategy~handleAll} that wraps all fetch and + * cache actions around plugin callbacks and keeps track of when the strategy + * is "done" (i.e. all added `event.waitUntil()` promises have resolved). + * + * @memberof workbox-strategies + */ +class StrategyHandler { + public request!: Request; + public url?: URL; + public event: ExtendableEvent; + public params?: any; + + private _cacheKeys: Record = {}; + + private readonly _strategy: Strategy; + private readonly _extendLifetimePromises: Promise[]; + private readonly _handlerDeferred: Deferred; + private readonly _plugins: WorkboxPlugin[]; + private readonly _pluginStateMap: Map; + + /** + * Creates a new instance associated with the passed strategy and event + * that's handling the request. + * + * The constructor also initializes the state that will be passed to each of + * the plugins handling this request. + * + * @param {workbox-strategies.Strategy} strategy + * @param {Object} options + * @param {Request|string} options.request A request to run this strategy for. + * @param {ExtendableEvent} options.event The event associated with the + * request. + * @param {URL} [options.url] + * @param {*} [options.params] The return value from the + * {@link workbox-routing~matchCallback} (if applicable). + */ + constructor(strategy: Strategy, options: HandlerCallbackOptions) { + /** + * The request the strategy is performing (passed to the strategy's + * `handle()` or `handleAll()` method). + * @name request + * @instance + * @type {Request} + * @memberof workbox-strategies.StrategyHandler + */ + /** + * The event associated with this request. + * @name event + * @instance + * @type {ExtendableEvent} + * @memberof workbox-strategies.StrategyHandler + */ + /** + * A `URL` instance of `request.url` (if passed to the strategy's + * `handle()` or `handleAll()` method). + * Note: the `url` param will be present if the strategy was invoked + * from a workbox `Route` object. + * @name url + * @instance + * @type {URL|undefined} + * @memberof workbox-strategies.StrategyHandler + */ + /** + * A `param` value (if passed to the strategy's + * `handle()` or `handleAll()` method). + * Note: the `param` param will be present if the strategy was invoked + * from a workbox `Route` object and the + * {@link workbox-routing~matchCallback} returned + * a truthy value (it will be that value). + * @name params + * @instance + * @type {*|undefined} + * @memberof workbox-strategies.StrategyHandler + */ + if (process.env.NODE_ENV !== 'production') { + assert!.isInstance(options.event, ExtendableEvent, { + moduleName: 'workbox-strategies', + className: 'StrategyHandler', + funcName: 'constructor', + paramName: 'options.event', + }); + } + + Object.assign(this, options); + + this.event = options.event; + this._strategy = strategy; + this._handlerDeferred = new Deferred(); + this._extendLifetimePromises = []; + + // Copy the plugins list (since it's mutable on the strategy), + // so any mutations don't affect this handler instance. + this._plugins = [...strategy.plugins]; + this._pluginStateMap = new Map(); + for (const plugin of this._plugins) { + this._pluginStateMap.set(plugin, {}); + } + + this.event.waitUntil(this._handlerDeferred.promise); + } + + /** + * Fetches a given request (and invokes any applicable plugin callback + * methods) using the `fetchOptions` (for non-navigation requests) and + * `plugins` defined on the `Strategy` object. + * + * The following plugin lifecycle methods are invoked when using this method: + * - `requestWillFetch()` + * - `fetchDidSucceed()` + * - `fetchDidFail()` + * + * @param {Request|string} input The URL or request to fetch. + * @return {Promise} + */ + async fetch(input: RequestInfo): Promise { + const {event} = this; + let request: Request = toRequest(input); + + if ( + request.mode === 'navigate' && + event instanceof FetchEvent && + event.preloadResponse + ) { + const possiblePreloadResponse = (await event.preloadResponse) as + | Response + | undefined; + if (possiblePreloadResponse) { + if (process.env.NODE_ENV !== 'production') { + logger.log( + `Using a preloaded navigation response for ` + + `'${getFriendlyURL(request.url)}'`, + ); + } + return possiblePreloadResponse; + } + } + + // If there is a fetchDidFail plugin, we need to save a clone of the + // original request before it's either modified by a requestWillFetch + // plugin or before the original request's body is consumed via fetch(). + const originalRequest = this.hasCallback('fetchDidFail') + ? request.clone() + : null; + + try { + for (const cb of this.iterateCallbacks('requestWillFetch')) { + request = await cb({request: request.clone(), event}); + } + } catch (err) { + if (err instanceof Error) { + throw new WorkboxError('plugin-error-request-will-fetch', { + thrownErrorMessage: err.message, + }); + } + } + + // The request can be altered by plugins with `requestWillFetch` making + // the original request (most likely from a `fetch` event) different + // from the Request we make. Pass both to `fetchDidFail` to aid debugging. + const pluginFilteredRequest: Request = request.clone(); + + try { + let fetchResponse: Response; + + // See https://github.com/GoogleChrome/workbox/issues/1796 + fetchResponse = await fetch( + request, + request.mode === 'navigate' ? undefined : this._strategy.fetchOptions, + ); + + if (process.env.NODE_ENV !== 'production') { + logger.debug( + `Network request for ` + + `'${getFriendlyURL(request.url)}' returned a response with ` + + `status '${fetchResponse.status}'.`, + ); + } + + for (const callback of this.iterateCallbacks('fetchDidSucceed')) { + fetchResponse = await callback({ + event, + request: pluginFilteredRequest, + response: fetchResponse, + }); + } + return fetchResponse; + } catch (error) { + if (process.env.NODE_ENV !== 'production') { + logger.log( + `Network request for ` + + `'${getFriendlyURL(request.url)}' threw an error.`, + error, + ); + } + + // `originalRequest` will only exist if a `fetchDidFail` callback + // is being used (see above). + if (originalRequest) { + await this.runCallbacks('fetchDidFail', { + error: error as Error, + event, + originalRequest: originalRequest.clone(), + request: pluginFilteredRequest.clone(), + }); + } + throw error; + } + } + + /** + * Calls `this.fetch()` and (in the background) runs `this.cachePut()` on + * the response generated by `this.fetch()`. + * + * The call to `this.cachePut()` automatically invokes `this.waitUntil()`, + * so you do not have to manually call `waitUntil()` on the event. + * + * @param {Request|string} input The request or URL to fetch and cache. + * @return {Promise} + */ + async fetchAndCachePut(input: RequestInfo): Promise { + const response = await this.fetch(input); + const responseClone = response.clone(); + + void this.waitUntil(this.cachePut(input, responseClone)); + + return response; + } + + /** + * Matches a request from the cache (and invokes any applicable plugin + * callback methods) using the `cacheName`, `matchOptions`, and `plugins` + * defined on the strategy object. + * + * The following plugin lifecycle methods are invoked when using this method: + * - cacheKeyWillBeUsed() + * - cachedResponseWillBeUsed() + * + * @param {Request|string} key The Request or URL to use as the cache key. + * @return {Promise} A matching response, if found. + */ + async cacheMatch(key: RequestInfo): Promise { + const request: Request = toRequest(key); + let cachedResponse: Response | undefined; + const {cacheName, matchOptions} = this._strategy; + + const effectiveRequest = await this.getCacheKey(request, 'read'); + const multiMatchOptions = {...matchOptions, ...{cacheName}}; + + cachedResponse = await caches.match(effectiveRequest, multiMatchOptions); + + if (process.env.NODE_ENV !== 'production') { + if (cachedResponse) { + logger.debug(`Found a cached response in '${cacheName}'.`); + } else { + logger.debug(`No cached response found in '${cacheName}'.`); + } + } + + for (const callback of this.iterateCallbacks('cachedResponseWillBeUsed')) { + cachedResponse = + (await callback({ + cacheName, + matchOptions, + cachedResponse, + request: effectiveRequest, + event: this.event, + })) || undefined; + } + return cachedResponse; + } + + /** + * Puts a request/response pair in the cache (and invokes any applicable + * plugin callback methods) using the `cacheName` and `plugins` defined on + * the strategy object. + * + * The following plugin lifecycle methods are invoked when using this method: + * - cacheKeyWillBeUsed() + * - cacheWillUpdate() + * - cacheDidUpdate() + * + * @param {Request|string} key The request or URL to use as the cache key. + * @param {Response} response The response to cache. + * @return {Promise} `false` if a cacheWillUpdate caused the response + * not be cached, and `true` otherwise. + */ + async cachePut(key: RequestInfo, response: Response): Promise { + const request: Request = toRequest(key); + + // Run in the next task to avoid blocking other cache reads. + // https://github.com/w3c/ServiceWorker/issues/1397 + await timeout(0); + + const effectiveRequest = await this.getCacheKey(request, 'write'); + + if (process.env.NODE_ENV !== 'production') { + if (effectiveRequest.method && effectiveRequest.method !== 'GET') { + throw new WorkboxError('attempt-to-cache-non-get-request', { + url: getFriendlyURL(effectiveRequest.url), + method: effectiveRequest.method, + }); + } + + // See https://github.com/GoogleChrome/workbox/issues/2818 + const vary = response.headers.get('Vary'); + if (vary) { + logger.debug( + `The response for ${getFriendlyURL(effectiveRequest.url)} ` + + `has a 'Vary: ${vary}' header. ` + + `Consider setting the {ignoreVary: true} option on your strategy ` + + `to ensure cache matching and deletion works as expected.`, + ); + } + } + + if (!response) { + if (process.env.NODE_ENV !== 'production') { + logger.error( + `Cannot cache non-existent response for ` + + `'${getFriendlyURL(effectiveRequest.url)}'.`, + ); + } + + throw new WorkboxError('cache-put-with-no-response', { + url: getFriendlyURL(effectiveRequest.url), + }); + } + + const responseToCache = await this._ensureResponseSafeToCache(response); + + if (!responseToCache) { + if (process.env.NODE_ENV !== 'production') { + logger.debug( + `Response '${getFriendlyURL(effectiveRequest.url)}' ` + + `will not be cached.`, + responseToCache, + ); + } + return false; + } + + const {cacheName, matchOptions} = this._strategy; + const cache = await self.caches.open(cacheName); + + const hasCacheUpdateCallback = this.hasCallback('cacheDidUpdate'); + const oldResponse = hasCacheUpdateCallback + ? await cacheMatchIgnoreParams( + // TODO(philipwalton): the `__WB_REVISION__` param is a precaching + // feature. Consider into ways to only add this behavior if using + // precaching. + cache, + effectiveRequest.clone(), + ['__WB_REVISION__'], + matchOptions, + ) + : null; + + if (process.env.NODE_ENV !== 'production') { + logger.debug( + `Updating the '${cacheName}' cache with a new Response ` + + `for ${getFriendlyURL(effectiveRequest.url)}.`, + ); + } + + try { + await cache.put( + effectiveRequest, + hasCacheUpdateCallback ? responseToCache.clone() : responseToCache, + ); + } catch (error) { + if (error instanceof Error) { + // See https://developer.mozilla.org/en-US/docs/Web/API/DOMException#exception-QuotaExceededError + if (error.name === 'QuotaExceededError') { + await executeQuotaErrorCallbacks(); + } + throw error; + } + } + + for (const callback of this.iterateCallbacks('cacheDidUpdate')) { + await callback({ + cacheName, + oldResponse, + newResponse: responseToCache.clone(), + request: effectiveRequest, + event: this.event, + }); + } + + return true; + } + + /** + * Checks the list of plugins for the `cacheKeyWillBeUsed` callback, and + * executes any of those callbacks found in sequence. The final `Request` + * object returned by the last plugin is treated as the cache key for cache + * reads and/or writes. If no `cacheKeyWillBeUsed` plugin callbacks have + * been registered, the passed request is returned unmodified + * + * @param {Request} request + * @param {string} mode + * @return {Promise} + */ + async getCacheKey( + request: Request, + mode: 'read' | 'write', + ): Promise { + const key = `${request.url} | ${mode}`; + if (!this._cacheKeys[key]) { + let effectiveRequest = request; + + for (const callback of this.iterateCallbacks('cacheKeyWillBeUsed')) { + effectiveRequest = toRequest( + await callback({ + mode, + request: effectiveRequest, + event: this.event, + // params has a type any can't change right now. + params: this.params, // eslint-disable-line + }), + ); + } + + this._cacheKeys[key] = effectiveRequest; + } + return this._cacheKeys[key]; + } + + /** + * Returns true if the strategy has at least one plugin with the given + * callback. + * + * @param {string} name The name of the callback to check for. + * @return {boolean} + */ + hasCallback(name: C): boolean { + for (const plugin of this._strategy.plugins) { + if (name in plugin) { + return true; + } + } + return false; + } + + /** + * Runs all plugin callbacks matching the given name, in order, passing the + * given param object (merged ith the current plugin state) as the only + * argument. + * + * Note: since this method runs all plugins, it's not suitable for cases + * where the return value of a callback needs to be applied prior to calling + * the next callback. See + * {@link workbox-strategies.StrategyHandler#iterateCallbacks} + * below for how to handle that case. + * + * @param {string} name The name of the callback to run within each plugin. + * @param {Object} param The object to pass as the first (and only) param + * when executing each callback. This object will be merged with the + * current plugin state prior to callback execution. + */ + async runCallbacks>( + name: C, + param: Omit, + ): Promise { + for (const callback of this.iterateCallbacks(name)) { + // TODO(philipwalton): not sure why `any` is needed. It seems like + // this should work with `as WorkboxPluginCallbackParam[C]`. + await callback(param as any); + } + } + + /** + * Accepts a callback and returns an iterable of matching plugin callbacks, + * where each callback is wrapped with the current handler state (i.e. when + * you call each callback, whatever object parameter you pass it will + * be merged with the plugin's current state). + * + * @param {string} name The name fo the callback to run + * @return {Array} + */ + *iterateCallbacks( + name: C, + ): Generator> { + for (const plugin of this._strategy.plugins) { + if (typeof plugin[name] === 'function') { + const state = this._pluginStateMap.get(plugin); + const statefulCallback = ( + param: Omit, + ) => { + const statefulParam = {...param, state}; + + // TODO(philipwalton): not sure why `any` is needed. It seems like + // this should work with `as WorkboxPluginCallbackParam[C]`. + return plugin[name]!(statefulParam as any); + }; + yield statefulCallback as NonNullable; + } + } + } + + /** + * Adds a promise to the + * [extend lifetime promises]{@link https://w3c.github.io/ServiceWorker/#extendableevent-extend-lifetime-promises} + * of the event associated with the request being handled (usually a + * `FetchEvent`). + * + * Note: you can await + * {@link workbox-strategies.StrategyHandler~doneWaiting} + * to know when all added promises have settled. + * + * @param {Promise} promise A promise to add to the extend lifetime promises + * of the event that triggered the request. + */ + waitUntil(promise: Promise): Promise { + this._extendLifetimePromises.push(promise); + return promise; + } + + /** + * Returns a promise that resolves once all promises passed to + * {@link workbox-strategies.StrategyHandler~waitUntil} + * have settled. + * + * Note: any work done after `doneWaiting()` settles should be manually + * passed to an event's `waitUntil()` method (not this handler's + * `waitUntil()` method), otherwise the service worker thread may be killed + * prior to your work completing. + */ + async doneWaiting(): Promise { + while (this._extendLifetimePromises.length) { + const promises = this._extendLifetimePromises.splice(0); + const result = await Promise.allSettled(promises); + const firstRejection = result.find((i) => i.status === 'rejected'); + if (firstRejection) { + throw (firstRejection as PromiseRejectedResult).reason; + } + } + } + + /** + * Stops running the strategy and immediately resolves any pending + * `waitUntil()` promises. + */ + destroy(): void { + this._handlerDeferred.resolve(null); + } + + /** + * This method will call cacheWillUpdate on the available plugins (or use + * status === 200) to determine if the Response is safe and valid to cache. + * + * @param {Request} options.request + * @param {Response} options.response + * @return {Promise} + * + * @private + */ + async _ensureResponseSafeToCache( + response: Response, + ): Promise { + let responseToCache: Response | undefined = response; + let pluginsUsed = false; + + for (const callback of this.iterateCallbacks('cacheWillUpdate')) { + responseToCache = + (await callback({ + request: this.request, + response: responseToCache, + event: this.event, + })) || undefined; + pluginsUsed = true; + + if (!responseToCache) { + break; + } + } + + if (!pluginsUsed) { + if (responseToCache && responseToCache.status !== 200) { + responseToCache = undefined; + } + if (process.env.NODE_ENV !== 'production') { + if (responseToCache) { + if (responseToCache.status !== 200) { + if (responseToCache.status === 0) { + logger.warn( + `The response for '${this.request.url}' ` + + `is an opaque response. The caching strategy that you're ` + + `using will not cache opaque responses by default.`, + ); + } else { + logger.debug( + `The response for '${this.request.url}' ` + + `returned a status code of '${response.status}' and won't ` + + `be cached as a result.`, + ); + } + } + } + } + } + + return responseToCache; + } +} + +export {StrategyHandler}; diff --git a/node_modules/workbox-strategies/src/_version.ts b/node_modules/workbox-strategies/src/_version.ts new file mode 100644 index 0000000000000000000000000000000000000000..e8fe137c86ce1b992cfa411d6d976098ec5e6d7c --- /dev/null +++ b/node_modules/workbox-strategies/src/_version.ts @@ -0,0 +1,2 @@ +// @ts-ignore +try{self['workbox:strategies:7.4.1']&&_()}catch(e){} \ No newline at end of file diff --git a/node_modules/workbox-strategies/src/index.ts b/node_modules/workbox-strategies/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..2ad7dbc91139c1c4ae4685638510eaa65c0c1bc1 --- /dev/null +++ b/node_modules/workbox-strategies/src/index.ts @@ -0,0 +1,44 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {CacheFirst} from './CacheFirst.js'; +import {CacheOnly} from './CacheOnly.js'; +import {NetworkFirst, NetworkFirstOptions} from './NetworkFirst.js'; +import {NetworkOnly, NetworkOnlyOptions} from './NetworkOnly.js'; +import {StaleWhileRevalidate} from './StaleWhileRevalidate.js'; +import {Strategy, StrategyOptions} from './Strategy.js'; +import {StrategyHandler} from './StrategyHandler.js'; +import './_version.js'; + +// See https://github.com/GoogleChrome/workbox/issues/2946 +declare global { + interface FetchEvent { + // See https://github.com/GoogleChrome/workbox/issues/2974 + readonly preloadResponse: Promise; + } +} + +/** + * There are common caching strategies that most service workers will need + * and use. This module provides simple implementations of these strategies. + * + * @module workbox-strategies + */ + +export { + CacheFirst, + CacheOnly, + NetworkFirst, + NetworkFirstOptions, + NetworkOnly, + NetworkOnlyOptions, + StaleWhileRevalidate, + Strategy, + StrategyHandler, + StrategyOptions, +}; diff --git a/node_modules/workbox-strategies/src/plugins/cacheOkAndOpaquePlugin.ts b/node_modules/workbox-strategies/src/plugins/cacheOkAndOpaquePlugin.ts new file mode 100644 index 0000000000000000000000000000000000000000..5f64a5fe22372e21e697ace1513f1c62bde63c74 --- /dev/null +++ b/node_modules/workbox-strategies/src/plugins/cacheOkAndOpaquePlugin.ts @@ -0,0 +1,29 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {WorkboxPlugin} from 'workbox-core/types.js'; +import '../_version.js'; + +export const cacheOkAndOpaquePlugin: WorkboxPlugin = { + /** + * Returns a valid response (to allow caching) if the status is 200 (OK) or + * 0 (opaque). + * + * @param {Object} options + * @param {Response} options.response + * @return {Response|null} + * + * @private + */ + cacheWillUpdate: async ({response}) => { + if (response.status === 200 || response.status === 0) { + return response; + } + return null; + }, +}; diff --git a/node_modules/workbox-strategies/src/utils/messages.ts b/node_modules/workbox-strategies/src/utils/messages.ts new file mode 100644 index 0000000000000000000000000000000000000000..f6d647e88de415778223f9fffd9caa0eea82ea0f --- /dev/null +++ b/node_modules/workbox-strategies/src/utils/messages.ts @@ -0,0 +1,23 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {logger} from 'workbox-core/_private/logger.js'; +import {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.js'; +import '../_version.js'; + +export const messages = { + strategyStart: (strategyName: string, request: Request): string => + `Using ${strategyName} to respond to '${getFriendlyURL(request.url)}'`, + printFinalResponse: (response?: Response): void => { + if (response) { + logger.groupCollapsed(`View the final response here.`); + logger.log(response || '[No response returned]'); + logger.groupEnd(); + } + }, +}; diff --git a/node_modules/workbox-strategies/tsconfig.json b/node_modules/workbox-strategies/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..3bb2772b586c4d0ceee3d014e64dba7aafbdd570 --- /dev/null +++ b/node_modules/workbox-strategies/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tsconfig", + "compilerOptions": { + "composite": true, + "outDir": "./", + "rootDir": "./src", + "tsBuildInfoFile": "./tsconfig.tsbuildinfo" + }, + "include": ["src/**/*.ts"], + "references": [{"path": "../workbox-core/"}] +} diff --git a/node_modules/workbox-strategies/utils/messages.d.ts b/node_modules/workbox-strategies/utils/messages.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..09e79a708df89c665985b74f58596e624a317fac --- /dev/null +++ b/node_modules/workbox-strategies/utils/messages.d.ts @@ -0,0 +1,5 @@ +import '../_version.js'; +export declare const messages: { + strategyStart: (strategyName: string, request: Request) => string; + printFinalResponse: (response?: Response) => void; +}; diff --git a/node_modules/workbox-strategies/utils/messages.js b/node_modules/workbox-strategies/utils/messages.js new file mode 100644 index 0000000000000000000000000000000000000000..b91da44f6b07b208729f26a052fb6d6870c6fa23 --- /dev/null +++ b/node_modules/workbox-strategies/utils/messages.js @@ -0,0 +1,20 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { logger } from 'workbox-core/_private/logger.js'; +import { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js'; +import '../_version.js'; +export const messages = { + strategyStart: (strategyName, request) => `Using ${strategyName} to respond to '${getFriendlyURL(request.url)}'`, + printFinalResponse: (response) => { + if (response) { + logger.groupCollapsed(`View the final response here.`); + logger.log(response || '[No response returned]'); + logger.groupEnd(); + } + }, +}; diff --git a/node_modules/workbox-strategies/utils/messages.mjs b/node_modules/workbox-strategies/utils/messages.mjs new file mode 100644 index 0000000000000000000000000000000000000000..fcad226c2238011ab36b9799e8999b5109083c3e --- /dev/null +++ b/node_modules/workbox-strategies/utils/messages.mjs @@ -0,0 +1 @@ +export * from './messages.js'; \ No newline at end of file diff --git a/node_modules/workbox-streams/LICENSE b/node_modules/workbox-streams/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..845b545fd0f5031a944cda8cf9018eb066500040 --- /dev/null +++ b/node_modules/workbox-streams/LICENSE @@ -0,0 +1,19 @@ +Copyright 2018 Google LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/workbox-streams/README.md b/node_modules/workbox-streams/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8abfa9cd30fe374ded9552126bfcc10a203c7fc3 --- /dev/null +++ b/node_modules/workbox-streams/README.md @@ -0,0 +1 @@ +This module's documentation can be found at https://developers.google.com/web/tools/workbox/reference-docs/latest/module-workbox-streams diff --git a/node_modules/workbox-streams/_types.d.ts b/node_modules/workbox-streams/_types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1ecb1ba8725ebcd476d1caa090c944d9cfe1bdde --- /dev/null +++ b/node_modules/workbox-streams/_types.d.ts @@ -0,0 +1,6 @@ +import './_version.js'; +export type StreamSource = Response | ReadableStream | BodyInit; +/** + * @typedef {Response|ReadableStream|BodyInit} StreamSource + * @memberof workbox-streams + */ diff --git a/node_modules/workbox-streams/_types.js b/node_modules/workbox-streams/_types.js new file mode 100644 index 0000000000000000000000000000000000000000..a9c28b0702cf5c1e4ae19fd67743b6050d8f1e69 --- /dev/null +++ b/node_modules/workbox-streams/_types.js @@ -0,0 +1,18 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import './_version.js'; +// * * * IMPORTANT! * * * +// ------------------------------------------------------------------------- // +// jdsoc type definitions cannot be declared above TypeScript definitions or +// they'll be stripped from the built `.js` files, and they'll only be in the +// `d.ts` files, which aren't read by the jsdoc generator. As a result we +// have to put declare them below. +/** + * @typedef {Response|ReadableStream|BodyInit} StreamSource + * @memberof workbox-streams + */ diff --git a/node_modules/workbox-streams/_types.mjs b/node_modules/workbox-streams/_types.mjs new file mode 100644 index 0000000000000000000000000000000000000000..fb0ccdd9e49605f634b19eb6c43bd521a13a66ab --- /dev/null +++ b/node_modules/workbox-streams/_types.mjs @@ -0,0 +1 @@ +export * from './_types.js'; \ No newline at end of file diff --git a/node_modules/workbox-streams/_version.d.ts b/node_modules/workbox-streams/_version.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/workbox-streams/_version.js b/node_modules/workbox-streams/_version.js new file mode 100644 index 0000000000000000000000000000000000000000..53e31d2305087b08713f8f6bb06e9cc79a383fb8 --- /dev/null +++ b/node_modules/workbox-streams/_version.js @@ -0,0 +1,6 @@ +"use strict"; +// @ts-ignore +try { + self['workbox:streams:7.4.0'] && _(); +} +catch (e) { } diff --git a/node_modules/workbox-streams/_version.mjs b/node_modules/workbox-streams/_version.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3ff1476b4e91b6216668d5d9ffacd17ef7ea47d4 --- /dev/null +++ b/node_modules/workbox-streams/_version.mjs @@ -0,0 +1 @@ +try{self['workbox:streams:7.4.1']&&_()}catch(e){}// eslint-disable-line \ No newline at end of file diff --git a/node_modules/workbox-streams/build/workbox-streams.dev.js b/node_modules/workbox-streams/build/workbox-streams.dev.js new file mode 100644 index 0000000000000000000000000000000000000000..4b0a575e8dc1ea840923021c2be587cc79600310 --- /dev/null +++ b/node_modules/workbox-streams/build/workbox-streams.dev.js @@ -0,0 +1,303 @@ +this.workbox = this.workbox || {}; +this.workbox.streams = (function (exports, assert_js, Deferred_js, logger_js, WorkboxError_js, canConstructReadableStream_js) { + 'use strict'; + + // @ts-ignore + try { + self['workbox:streams:7.4.0'] && _(); + } catch (e) {} + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Takes either a Response, a ReadableStream, or a + * [BodyInit](https://fetch.spec.whatwg.org/#bodyinit) and returns the + * ReadableStreamReader object associated with it. + * + * @param {workbox-streams.StreamSource} source + * @return {ReadableStreamReader} + * @private + */ + function _getReaderFromSource(source) { + if (source instanceof Response) { + // See https://github.com/GoogleChrome/workbox/issues/2998 + if (source.body) { + return source.body.getReader(); + } + throw new WorkboxError_js.WorkboxError('opaque-streams-source', { + type: source.type + }); + } + if (source instanceof ReadableStream) { + return source.getReader(); + } + return new Response(source).body.getReader(); + } + /** + * Takes multiple source Promises, each of which could resolve to a Response, a + * ReadableStream, or a [BodyInit](https://fetch.spec.whatwg.org/#bodyinit). + * + * Returns an object exposing a ReadableStream with each individual stream's + * data returned in sequence, along with a Promise which signals when the + * stream is finished (useful for passing to a FetchEvent's waitUntil()). + * + * @param {Array>} sourcePromises + * @return {Object<{done: Promise, stream: ReadableStream}>} + * + * @memberof workbox-streams + */ + function concatenate(sourcePromises) { + { + assert_js.assert.isArray(sourcePromises, { + moduleName: 'workbox-streams', + funcName: 'concatenate', + paramName: 'sourcePromises' + }); + } + const readerPromises = sourcePromises.map(sourcePromise => { + return Promise.resolve(sourcePromise).then(source => { + return _getReaderFromSource(source); + }); + }); + const streamDeferred = new Deferred_js.Deferred(); + let i = 0; + const logMessages = []; + const stream = new ReadableStream({ + pull(controller) { + return readerPromises[i].then(reader => { + if (reader instanceof ReadableStreamDefaultReader) { + return reader.read(); + } else { + return; + } + }).then(result => { + if (result === null || result === void 0 ? void 0 : result.done) { + { + logMessages.push(['Reached the end of source:', sourcePromises[i]]); + } + i++; + if (i >= readerPromises.length) { + // Log all the messages in the group at once in a single group. + { + logger_js.logger.groupCollapsed(`Concatenating ${readerPromises.length} sources.`); + for (const message of logMessages) { + if (Array.isArray(message)) { + logger_js.logger.log(...message); + } else { + logger_js.logger.log(message); + } + } + logger_js.logger.log('Finished reading all sources.'); + logger_js.logger.groupEnd(); + } + controller.close(); + streamDeferred.resolve(); + return; + } + // The `pull` method is defined because we're inside it. + return this.pull(controller); + } else { + controller.enqueue(result === null || result === void 0 ? void 0 : result.value); + } + }).catch(error => { + { + logger_js.logger.error('An error occurred:', error); + } + streamDeferred.reject(error); + throw error; + }); + }, + cancel() { + { + logger_js.logger.warn('The ReadableStream was cancelled.'); + } + streamDeferred.resolve(); + } + }); + return { + done: streamDeferred.promise, + stream + }; + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * This is a utility method that determines whether the current browser supports + * the features required to create streamed responses. Currently, it checks if + * [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream) + * is available. + * + * @private + * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified, + * `'text/html'` will be used by default. + * @return {boolean} `true`, if the current browser meets the requirements for + * streaming responses, and `false` otherwise. + * + * @memberof workbox-streams + */ + function createHeaders(headersInit = {}) { + // See https://github.com/GoogleChrome/workbox/issues/1461 + const headers = new Headers(headersInit); + if (!headers.has('content-type')) { + headers.set('content-type', 'text/html'); + } + return headers; + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Takes multiple source Promises, each of which could resolve to a Response, a + * ReadableStream, or a [BodyInit](https://fetch.spec.whatwg.org/#bodyinit), + * along with a + * [HeadersInit](https://fetch.spec.whatwg.org/#typedefdef-headersinit). + * + * Returns an object exposing a Response whose body consists of each individual + * stream's data returned in sequence, along with a Promise which signals when + * the stream is finished (useful for passing to a FetchEvent's waitUntil()). + * + * @param {Array>} sourcePromises + * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified, + * `'text/html'` will be used by default. + * @return {Object<{done: Promise, response: Response}>} + * + * @memberof workbox-streams + */ + function concatenateToResponse(sourcePromises, headersInit) { + const { + done, + stream + } = concatenate(sourcePromises); + const headers = createHeaders(headersInit); + const response = new Response(stream, { + headers + }); + return { + done, + response + }; + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * This is a utility method that determines whether the current browser supports + * the features required to create streamed responses. Currently, it checks if + * [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream) + * can be created. + * + * @return {boolean} `true`, if the current browser meets the requirements for + * streaming responses, and `false` otherwise. + * + * @memberof workbox-streams + */ + function isSupported() { + return canConstructReadableStream_js.canConstructReadableStream(); + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * A shortcut to create a strategy that could be dropped-in to Workbox's router. + * + * On browsers that do not support constructing new `ReadableStream`s, this + * strategy will automatically wait for all the `sourceFunctions` to complete, + * and create a final response that concatenates their values together. + * + * @param {Array} sourceFunctions + * An array of functions similar to {@link workbox-routing~handlerCallback} + * but that instead return a {@link workbox-streams.StreamSource} (or a + * Promise which resolves to one). + * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified, + * `'text/html'` will be used by default. + * @return {workbox-routing~handlerCallback} + * @memberof workbox-streams + */ + function strategy(sourceFunctions, headersInit) { + return async ({ + event, + request, + url, + params + }) => { + const sourcePromises = sourceFunctions.map(fn => { + // Ensure the return value of the function is always a promise. + return Promise.resolve(fn({ + event, + request, + url, + params + })); + }); + if (isSupported()) { + const { + done, + response + } = concatenateToResponse(sourcePromises, headersInit); + if (event) { + event.waitUntil(done); + } + return response; + } + { + logger_js.logger.log(`The current browser doesn't support creating response ` + `streams. Falling back to non-streaming response instead.`); + } + // Fallback to waiting for everything to finish, and concatenating the + // responses. + const blobPartsPromises = sourcePromises.map(async sourcePromise => { + const source = await sourcePromise; + if (source instanceof Response) { + return source.blob(); + } else { + // Technically, a `StreamSource` object can include any valid + // `BodyInit` type, including `FormData` and `URLSearchParams`, which + // cannot be passed to the Blob constructor directly, so we have to + // convert them to actual Blobs first. + return new Response(source).blob(); + } + }); + const blobParts = await Promise.all(blobPartsPromises); + const headers = createHeaders(headersInit); + // Constructing a new Response from a Blob source is well-supported. + // So is constructing a new Blob from multiple source Blobs or strings. + return new Response(new Blob(blobParts), { + headers + }); + }; + } + + exports.concatenate = concatenate; + exports.concatenateToResponse = concatenateToResponse; + exports.isSupported = isSupported; + exports.strategy = strategy; + + return exports; + +})({}, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private); +//# sourceMappingURL=workbox-streams.dev.js.map diff --git a/node_modules/workbox-streams/build/workbox-streams.dev.js.map b/node_modules/workbox-streams/build/workbox-streams.dev.js.map new file mode 100644 index 0000000000000000000000000000000000000000..3bf9b2f43b7283f3c689ab5b97e533bb129eb3c7 --- /dev/null +++ b/node_modules/workbox-streams/build/workbox-streams.dev.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-streams.dev.js","sources":["../_version.js","../concatenate.js","../utils/createHeaders.js","../concatenateToResponse.js","../isSupported.js","../strategy.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:streams:7.4.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 { Deferred } from 'workbox-core/_private/Deferred.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport './_version.js';\n/**\n * Takes either a Response, a ReadableStream, or a\n * [BodyInit](https://fetch.spec.whatwg.org/#bodyinit) and returns the\n * ReadableStreamReader object associated with it.\n *\n * @param {workbox-streams.StreamSource} source\n * @return {ReadableStreamReader}\n * @private\n */\nfunction _getReaderFromSource(source) {\n if (source instanceof Response) {\n // See https://github.com/GoogleChrome/workbox/issues/2998\n if (source.body) {\n return source.body.getReader();\n }\n throw new WorkboxError('opaque-streams-source', { type: source.type });\n }\n if (source instanceof ReadableStream) {\n return source.getReader();\n }\n return new Response(source).body.getReader();\n}\n/**\n * Takes multiple source Promises, each of which could resolve to a Response, a\n * ReadableStream, or a [BodyInit](https://fetch.spec.whatwg.org/#bodyinit).\n *\n * Returns an object exposing a ReadableStream with each individual stream's\n * data returned in sequence, along with a Promise which signals when the\n * stream is finished (useful for passing to a FetchEvent's waitUntil()).\n *\n * @param {Array>} sourcePromises\n * @return {Object<{done: Promise, stream: ReadableStream}>}\n *\n * @memberof workbox-streams\n */\nfunction concatenate(sourcePromises) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isArray(sourcePromises, {\n moduleName: 'workbox-streams',\n funcName: 'concatenate',\n paramName: 'sourcePromises',\n });\n }\n const readerPromises = sourcePromises.map((sourcePromise) => {\n return Promise.resolve(sourcePromise).then((source) => {\n return _getReaderFromSource(source);\n });\n });\n const streamDeferred = new Deferred();\n let i = 0;\n const logMessages = [];\n const stream = new ReadableStream({\n pull(controller) {\n return readerPromises[i]\n .then((reader) => {\n if (reader instanceof ReadableStreamDefaultReader) {\n return reader.read();\n }\n else {\n return;\n }\n })\n .then((result) => {\n if (result === null || result === void 0 ? void 0 : result.done) {\n if (process.env.NODE_ENV !== 'production') {\n logMessages.push([\n 'Reached the end of source:',\n sourcePromises[i],\n ]);\n }\n i++;\n if (i >= readerPromises.length) {\n // Log all the messages in the group at once in a single group.\n if (process.env.NODE_ENV !== 'production') {\n logger.groupCollapsed(`Concatenating ${readerPromises.length} sources.`);\n for (const message of logMessages) {\n if (Array.isArray(message)) {\n logger.log(...message);\n }\n else {\n logger.log(message);\n }\n }\n logger.log('Finished reading all sources.');\n logger.groupEnd();\n }\n controller.close();\n streamDeferred.resolve();\n return;\n }\n // The `pull` method is defined because we're inside it.\n return this.pull(controller);\n }\n else {\n controller.enqueue(result === null || result === void 0 ? void 0 : result.value);\n }\n })\n .catch((error) => {\n if (process.env.NODE_ENV !== 'production') {\n logger.error('An error occurred:', error);\n }\n streamDeferred.reject(error);\n throw error;\n });\n },\n cancel() {\n if (process.env.NODE_ENV !== 'production') {\n logger.warn('The ReadableStream was cancelled.');\n }\n streamDeferred.resolve();\n },\n });\n return { done: streamDeferred.promise, stream };\n}\nexport { concatenate };\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';\n/**\n * This is a utility method that determines whether the current browser supports\n * the features required to create streamed responses. Currently, it checks if\n * [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream)\n * is available.\n *\n * @private\n * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified,\n * `'text/html'` will be used by default.\n * @return {boolean} `true`, if the current browser meets the requirements for\n * streaming responses, and `false` otherwise.\n *\n * @memberof workbox-streams\n */\nfunction createHeaders(headersInit = {}) {\n // See https://github.com/GoogleChrome/workbox/issues/1461\n const headers = new Headers(headersInit);\n if (!headers.has('content-type')) {\n headers.set('content-type', 'text/html');\n }\n return headers;\n}\nexport { createHeaders };\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 { createHeaders } from './utils/createHeaders.js';\nimport { concatenate } from './concatenate.js';\nimport './_version.js';\n/**\n * Takes multiple source Promises, each of which could resolve to a Response, a\n * ReadableStream, or a [BodyInit](https://fetch.spec.whatwg.org/#bodyinit),\n * along with a\n * [HeadersInit](https://fetch.spec.whatwg.org/#typedefdef-headersinit).\n *\n * Returns an object exposing a Response whose body consists of each individual\n * stream's data returned in sequence, along with a Promise which signals when\n * the stream is finished (useful for passing to a FetchEvent's waitUntil()).\n *\n * @param {Array>} sourcePromises\n * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified,\n * `'text/html'` will be used by default.\n * @return {Object<{done: Promise, response: Response}>}\n *\n * @memberof workbox-streams\n */\nfunction concatenateToResponse(sourcePromises, headersInit) {\n const { done, stream } = concatenate(sourcePromises);\n const headers = createHeaders(headersInit);\n const response = new Response(stream, { headers });\n return { done, response };\n}\nexport { concatenateToResponse };\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 { canConstructReadableStream } from 'workbox-core/_private/canConstructReadableStream.js';\nimport './_version.js';\n/**\n * This is a utility method that determines whether the current browser supports\n * the features required to create streamed responses. Currently, it checks if\n * [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream)\n * can be created.\n *\n * @return {boolean} `true`, if the current browser meets the requirements for\n * streaming responses, and `false` otherwise.\n *\n * @memberof workbox-streams\n */\nfunction isSupported() {\n return canConstructReadableStream();\n}\nexport { isSupported };\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 { logger } from 'workbox-core/_private/logger.js';\nimport { createHeaders } from './utils/createHeaders.js';\nimport { concatenateToResponse } from './concatenateToResponse.js';\nimport { isSupported } from './isSupported.js';\nimport './_version.js';\n/**\n * A shortcut to create a strategy that could be dropped-in to Workbox's router.\n *\n * On browsers that do not support constructing new `ReadableStream`s, this\n * strategy will automatically wait for all the `sourceFunctions` to complete,\n * and create a final response that concatenates their values together.\n *\n * @param {Array} sourceFunctions\n * An array of functions similar to {@link workbox-routing~handlerCallback}\n * but that instead return a {@link workbox-streams.StreamSource} (or a\n * Promise which resolves to one).\n * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified,\n * `'text/html'` will be used by default.\n * @return {workbox-routing~handlerCallback}\n * @memberof workbox-streams\n */\nfunction strategy(sourceFunctions, headersInit) {\n return async ({ event, request, url, params }) => {\n const sourcePromises = sourceFunctions.map((fn) => {\n // Ensure the return value of the function is always a promise.\n return Promise.resolve(fn({ event, request, url, params }));\n });\n if (isSupported()) {\n const { done, response } = concatenateToResponse(sourcePromises, headersInit);\n if (event) {\n event.waitUntil(done);\n }\n return response;\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`The current browser doesn't support creating response ` +\n `streams. Falling back to non-streaming response instead.`);\n }\n // Fallback to waiting for everything to finish, and concatenating the\n // responses.\n const blobPartsPromises = sourcePromises.map(async (sourcePromise) => {\n const source = await sourcePromise;\n if (source instanceof Response) {\n return source.blob();\n }\n else {\n // Technically, a `StreamSource` object can include any valid\n // `BodyInit` type, including `FormData` and `URLSearchParams`, which\n // cannot be passed to the Blob constructor directly, so we have to\n // convert them to actual Blobs first.\n return new Response(source).blob();\n }\n });\n const blobParts = await Promise.all(blobPartsPromises);\n const headers = createHeaders(headersInit);\n // Constructing a new Response from a Blob source is well-supported.\n // So is constructing a new Blob from multiple source Blobs or strings.\n return new Response(new Blob(blobParts), { headers });\n };\n}\nexport { strategy };\n"],"names":["self","_","e","_getReaderFromSource","source","Response","body","getReader","WorkboxError","type","ReadableStream","concatenate","sourcePromises","assert","isArray","moduleName","funcName","paramName","readerPromises","map","sourcePromise","Promise","resolve","then","streamDeferred","Deferred","i","logMessages","stream","pull","controller","reader","ReadableStreamDefaultReader","read","result","done","push","length","logger","groupCollapsed","message","Array","log","groupEnd","close","enqueue","value","catch","error","reject","cancel","warn","promise","createHeaders","headersInit","headers","Headers","has","set","concatenateToResponse","response","isSupported","canConstructReadableStream","strategy","sourceFunctions","event","request","url","params","fn","waitUntil","blobPartsPromises","blob","blobParts","all","Blob"],"mappings":";;;;IACA;IACA,IAAI;IACAA,EAAAA,IAAI,CAAC,uBAAuB,CAAC,IAAIC,CAAC,EAAE;IACxC,CAAC,CACD,OAAOC,CAAC,EAAE,CAAE;;ICLZ;IACA;;IAEA;IACA;IACA;IACA;IAMA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,SAASC,oBAAoBA,CAACC,MAAM,EAAE;MAClC,IAAIA,MAAM,YAAYC,QAAQ,EAAE;IAC5B;QACA,IAAID,MAAM,CAACE,IAAI,EAAE;IACb,MAAA,OAAOF,MAAM,CAACE,IAAI,CAACC,SAAS,EAAE;IAClC,IAAA;IACA,IAAA,MAAM,IAAIC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AA,OAAOD,MAAM,CAACoE,IAAI,EAAE;IACxB,MAAA,CAAC,MACI;IACD;IACA;IACA;IACA;YACA,OAAO,IAAInE,QAAQ,CAACD,MAAM,CAAC,CAACoE,IAAI,EAAE;IACtC,MAAA;IACJ,IAAA,CAAC,CAAC;QACF,MAAMC,SAAS,GAAG,MAAMpD,OAAO,CAACqD,GAAG,CAACH,iBAAiB,CAAC;IACtD,IAAA,MAAMhB,OAAO,GAAGF,aAAa,CAACC,WAAW,CAAC;IAC1C;IACA;QACA,OAAO,IAAIjD,QAAQ,CAAC,IAAIsE,IAAI,CAACF,SAAS,CAAC,EAAE;IAAElB,MAAAA;IAAQ,KAAC,CAAC;MACzD,CAAC;IACL;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/workbox-streams/build/workbox-streams.prod.js b/node_modules/workbox-streams/build/workbox-streams.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..498ee1763fce6fcec2a17f12ccd8231a138b8035 --- /dev/null +++ b/node_modules/workbox-streams/build/workbox-streams.prod.js @@ -0,0 +1,2 @@ +this.workbox=this.workbox||{},this.workbox.streams=function(e,n,t,r){"use strict";try{self["workbox:streams:7.4.0"]&&_()}catch(e){}function s(e){const r=e.map((e=>Promise.resolve(e).then((e=>function(e){if(e instanceof Response){if(e.body)return e.body.getReader();throw new t.WorkboxError("opaque-streams-source",{type:e.type})}return e instanceof ReadableStream?e.getReader():new Response(e).body.getReader()}(e))))),s=new n.Deferred;let o=0;const a=new ReadableStream({pull(e){return r[o].then((e=>e instanceof ReadableStreamDefaultReader?e.read():void 0)).then((n=>{if(null==n?void 0:n.done)return o++,o>=r.length?(e.close(),void s.resolve()):this.pull(e);e.enqueue(null==n?void 0:n.value)})).catch((e=>{throw s.reject(e),e}))},cancel(){s.resolve()}});return{done:s.promise,stream:a}}function o(e={}){const n=new Headers(e);return n.has("content-type")||n.set("content-type","text/html"),n}function a(e,n){const{done:t,stream:r}=s(e),a=o(n);return{done:t,response:new Response(r,{headers:a})}}function u(){return r.canConstructReadableStream()}return e.concatenate=s,e.concatenateToResponse=a,e.isSupported=u,e.strategy=function(e,n){return async({event:t,request:r,url:s,params:c})=>{const i=e.map((e=>Promise.resolve(e({event:t,request:r,url:s,params:c}))));if(u()){const{done:e,response:r}=a(i,n);return t&&t.waitUntil(e),r}const f=i.map((async e=>{const n=await e;return n instanceof Response?n.blob():new Response(n).blob()})),l=await Promise.all(f),w=o(n);return new Response(new Blob(l),{headers:w})}},e}({},workbox.core._private,workbox.core._private,workbox.core._private); +//# sourceMappingURL=workbox-streams.prod.js.map diff --git a/node_modules/workbox-streams/build/workbox-streams.prod.js.map b/node_modules/workbox-streams/build/workbox-streams.prod.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8caa8722f24ce0e5819cc02aa62c9de146fcc6e2 --- /dev/null +++ b/node_modules/workbox-streams/build/workbox-streams.prod.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-streams.prod.js","sources":["../_version.js","../concatenate.js","../utils/createHeaders.js","../concatenateToResponse.js","../isSupported.js","../strategy.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:streams:7.4.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 { Deferred } from 'workbox-core/_private/Deferred.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport './_version.js';\n/**\n * Takes either a Response, a ReadableStream, or a\n * [BodyInit](https://fetch.spec.whatwg.org/#bodyinit) and returns the\n * ReadableStreamReader object associated with it.\n *\n * @param {workbox-streams.StreamSource} source\n * @return {ReadableStreamReader}\n * @private\n */\nfunction _getReaderFromSource(source) {\n if (source instanceof Response) {\n // See https://github.com/GoogleChrome/workbox/issues/2998\n if (source.body) {\n return source.body.getReader();\n }\n throw new WorkboxError('opaque-streams-source', { type: source.type });\n }\n if (source instanceof ReadableStream) {\n return source.getReader();\n }\n return new Response(source).body.getReader();\n}\n/**\n * Takes multiple source Promises, each of which could resolve to a Response, a\n * ReadableStream, or a [BodyInit](https://fetch.spec.whatwg.org/#bodyinit).\n *\n * Returns an object exposing a ReadableStream with each individual stream's\n * data returned in sequence, along with a Promise which signals when the\n * stream is finished (useful for passing to a FetchEvent's waitUntil()).\n *\n * @param {Array>} sourcePromises\n * @return {Object<{done: Promise, stream: ReadableStream}>}\n *\n * @memberof workbox-streams\n */\nfunction concatenate(sourcePromises) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isArray(sourcePromises, {\n moduleName: 'workbox-streams',\n funcName: 'concatenate',\n paramName: 'sourcePromises',\n });\n }\n const readerPromises = sourcePromises.map((sourcePromise) => {\n return Promise.resolve(sourcePromise).then((source) => {\n return _getReaderFromSource(source);\n });\n });\n const streamDeferred = new Deferred();\n let i = 0;\n const logMessages = [];\n const stream = new ReadableStream({\n pull(controller) {\n return readerPromises[i]\n .then((reader) => {\n if (reader instanceof ReadableStreamDefaultReader) {\n return reader.read();\n }\n else {\n return;\n }\n })\n .then((result) => {\n if (result === null || result === void 0 ? void 0 : result.done) {\n if (process.env.NODE_ENV !== 'production') {\n logMessages.push([\n 'Reached the end of source:',\n sourcePromises[i],\n ]);\n }\n i++;\n if (i >= readerPromises.length) {\n // Log all the messages in the group at once in a single group.\n if (process.env.NODE_ENV !== 'production') {\n logger.groupCollapsed(`Concatenating ${readerPromises.length} sources.`);\n for (const message of logMessages) {\n if (Array.isArray(message)) {\n logger.log(...message);\n }\n else {\n logger.log(message);\n }\n }\n logger.log('Finished reading all sources.');\n logger.groupEnd();\n }\n controller.close();\n streamDeferred.resolve();\n return;\n }\n // The `pull` method is defined because we're inside it.\n return this.pull(controller);\n }\n else {\n controller.enqueue(result === null || result === void 0 ? void 0 : result.value);\n }\n })\n .catch((error) => {\n if (process.env.NODE_ENV !== 'production') {\n logger.error('An error occurred:', error);\n }\n streamDeferred.reject(error);\n throw error;\n });\n },\n cancel() {\n if (process.env.NODE_ENV !== 'production') {\n logger.warn('The ReadableStream was cancelled.');\n }\n streamDeferred.resolve();\n },\n });\n return { done: streamDeferred.promise, stream };\n}\nexport { concatenate };\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';\n/**\n * This is a utility method that determines whether the current browser supports\n * the features required to create streamed responses. Currently, it checks if\n * [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream)\n * is available.\n *\n * @private\n * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified,\n * `'text/html'` will be used by default.\n * @return {boolean} `true`, if the current browser meets the requirements for\n * streaming responses, and `false` otherwise.\n *\n * @memberof workbox-streams\n */\nfunction createHeaders(headersInit = {}) {\n // See https://github.com/GoogleChrome/workbox/issues/1461\n const headers = new Headers(headersInit);\n if (!headers.has('content-type')) {\n headers.set('content-type', 'text/html');\n }\n return headers;\n}\nexport { createHeaders };\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 { createHeaders } from './utils/createHeaders.js';\nimport { concatenate } from './concatenate.js';\nimport './_version.js';\n/**\n * Takes multiple source Promises, each of which could resolve to a Response, a\n * ReadableStream, or a [BodyInit](https://fetch.spec.whatwg.org/#bodyinit),\n * along with a\n * [HeadersInit](https://fetch.spec.whatwg.org/#typedefdef-headersinit).\n *\n * Returns an object exposing a Response whose body consists of each individual\n * stream's data returned in sequence, along with a Promise which signals when\n * the stream is finished (useful for passing to a FetchEvent's waitUntil()).\n *\n * @param {Array>} sourcePromises\n * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified,\n * `'text/html'` will be used by default.\n * @return {Object<{done: Promise, response: Response}>}\n *\n * @memberof workbox-streams\n */\nfunction concatenateToResponse(sourcePromises, headersInit) {\n const { done, stream } = concatenate(sourcePromises);\n const headers = createHeaders(headersInit);\n const response = new Response(stream, { headers });\n return { done, response };\n}\nexport { concatenateToResponse };\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 { canConstructReadableStream } from 'workbox-core/_private/canConstructReadableStream.js';\nimport './_version.js';\n/**\n * This is a utility method that determines whether the current browser supports\n * the features required to create streamed responses. Currently, it checks if\n * [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream)\n * can be created.\n *\n * @return {boolean} `true`, if the current browser meets the requirements for\n * streaming responses, and `false` otherwise.\n *\n * @memberof workbox-streams\n */\nfunction isSupported() {\n return canConstructReadableStream();\n}\nexport { isSupported };\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 { logger } from 'workbox-core/_private/logger.js';\nimport { createHeaders } from './utils/createHeaders.js';\nimport { concatenateToResponse } from './concatenateToResponse.js';\nimport { isSupported } from './isSupported.js';\nimport './_version.js';\n/**\n * A shortcut to create a strategy that could be dropped-in to Workbox's router.\n *\n * On browsers that do not support constructing new `ReadableStream`s, this\n * strategy will automatically wait for all the `sourceFunctions` to complete,\n * and create a final response that concatenates their values together.\n *\n * @param {Array} sourceFunctions\n * An array of functions similar to {@link workbox-routing~handlerCallback}\n * but that instead return a {@link workbox-streams.StreamSource} (or a\n * Promise which resolves to one).\n * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified,\n * `'text/html'` will be used by default.\n * @return {workbox-routing~handlerCallback}\n * @memberof workbox-streams\n */\nfunction strategy(sourceFunctions, headersInit) {\n return async ({ event, request, url, params }) => {\n const sourcePromises = sourceFunctions.map((fn) => {\n // Ensure the return value of the function is always a promise.\n return Promise.resolve(fn({ event, request, url, params }));\n });\n if (isSupported()) {\n const { done, response } = concatenateToResponse(sourcePromises, headersInit);\n if (event) {\n event.waitUntil(done);\n }\n return response;\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`The current browser doesn't support creating response ` +\n `streams. Falling back to non-streaming response instead.`);\n }\n // Fallback to waiting for everything to finish, and concatenating the\n // responses.\n const blobPartsPromises = sourcePromises.map(async (sourcePromise) => {\n const source = await sourcePromise;\n if (source instanceof Response) {\n return source.blob();\n }\n else {\n // Technically, a `StreamSource` object can include any valid\n // `BodyInit` type, including `FormData` and `URLSearchParams`, which\n // cannot be passed to the Blob constructor directly, so we have to\n // convert them to actual Blobs first.\n return new Response(source).blob();\n }\n });\n const blobParts = await Promise.all(blobPartsPromises);\n const headers = createHeaders(headersInit);\n // Constructing a new Response from a Blob source is well-supported.\n // So is constructing a new Blob from multiple source Blobs or strings.\n return new Response(new Blob(blobParts), { headers });\n };\n}\nexport { strategy };\n"],"names":["self","_","e","concatenate","sourcePromises","readerPromises","map","sourcePromise","Promise","resolve","then","source","Response","body","getReader","WorkboxError","type","ReadableStream","_getReaderFromSource","streamDeferred","Deferred","i","stream","pull","controller","reader","ReadableStreamDefaultReader","read","result","done","length","close","this","enqueue","value","catch","error","reject","cancel","promise","createHeaders","headersInit","headers","Headers","has","set","concatenateToResponse","response","isSupported","canConstructReadableStream","sourceFunctions","async","event","request","url","params","fn","waitUntil","blobPartsPromises","blob","blobParts","all","Blob"],"mappings":"kFAEA,IACIA,KAAK,0BAA4BC,GACrC,CACA,MAAOC,GAAK,CC0CZ,SAASC,EAAYC,GAQjB,MAAMC,EAAiBD,EAAeE,KAAKC,GAChCC,QAAQC,QAAQF,GAAeG,MAAMC,GAnCpD,SAA8BA,GAC1B,GAAIA,aAAkBC,SAAU,CAE5B,GAAID,EAAOE,KACP,OAAOF,EAAOE,KAAKC,YAEvB,MAAM,IAAIC,EAAAA,aAAa,wBAAyB,CAAEC,KAAML,EAAOK,MACnE,CACA,OAAIL,aAAkBM,eACXN,EAAOG,YAEX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,QAAeJ,EACrB,OAAII,aAAkBC,SACXD,EAAOgD,OAOP,IAAI/C,SAASD,GAAQgD,MAChC,IAEEC,QAAkBpD,QAAQqD,IAAIH,GAC9BhB,EAAUF,EAAcC,GAG9B,OAAO,IAAI7B,SAAS,IAAIkD,KAAKF,GAAY,CAAElB,WAAU,CAE7D"} \ No newline at end of file diff --git a/node_modules/workbox-streams/concatenate.d.ts b/node_modules/workbox-streams/concatenate.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6135131bcec3b9c4c0b87200910ea32ba4b810d8 --- /dev/null +++ b/node_modules/workbox-streams/concatenate.d.ts @@ -0,0 +1,20 @@ +import { StreamSource } from './_types.js'; +import './_version.js'; +/** + * Takes multiple source Promises, each of which could resolve to a Response, a + * ReadableStream, or a [BodyInit](https://fetch.spec.whatwg.org/#bodyinit). + * + * Returns an object exposing a ReadableStream with each individual stream's + * data returned in sequence, along with a Promise which signals when the + * stream is finished (useful for passing to a FetchEvent's waitUntil()). + * + * @param {Array>} sourcePromises + * @return {Object<{done: Promise, stream: ReadableStream}>} + * + * @memberof workbox-streams + */ +declare function concatenate(sourcePromises: Promise[]): { + done: Promise; + stream: ReadableStream; +}; +export { concatenate }; diff --git a/node_modules/workbox-streams/concatenate.js b/node_modules/workbox-streams/concatenate.js new file mode 100644 index 0000000000000000000000000000000000000000..5d34f2301083c59f5e946a95d4e3cec2d746aaf8 --- /dev/null +++ b/node_modules/workbox-streams/concatenate.js @@ -0,0 +1,127 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { assert } from 'workbox-core/_private/assert.js'; +import { Deferred } from 'workbox-core/_private/Deferred.js'; +import { logger } from 'workbox-core/_private/logger.js'; +import { WorkboxError } from 'workbox-core/_private/WorkboxError.js'; +import './_version.js'; +/** + * Takes either a Response, a ReadableStream, or a + * [BodyInit](https://fetch.spec.whatwg.org/#bodyinit) and returns the + * ReadableStreamReader object associated with it. + * + * @param {workbox-streams.StreamSource} source + * @return {ReadableStreamReader} + * @private + */ +function _getReaderFromSource(source) { + if (source instanceof Response) { + // See https://github.com/GoogleChrome/workbox/issues/2998 + if (source.body) { + return source.body.getReader(); + } + throw new WorkboxError('opaque-streams-source', { type: source.type }); + } + if (source instanceof ReadableStream) { + return source.getReader(); + } + return new Response(source).body.getReader(); +} +/** + * Takes multiple source Promises, each of which could resolve to a Response, a + * ReadableStream, or a [BodyInit](https://fetch.spec.whatwg.org/#bodyinit). + * + * Returns an object exposing a ReadableStream with each individual stream's + * data returned in sequence, along with a Promise which signals when the + * stream is finished (useful for passing to a FetchEvent's waitUntil()). + * + * @param {Array>} sourcePromises + * @return {Object<{done: Promise, stream: ReadableStream}>} + * + * @memberof workbox-streams + */ +function concatenate(sourcePromises) { + if (process.env.NODE_ENV !== 'production') { + assert.isArray(sourcePromises, { + moduleName: 'workbox-streams', + funcName: 'concatenate', + paramName: 'sourcePromises', + }); + } + const readerPromises = sourcePromises.map((sourcePromise) => { + return Promise.resolve(sourcePromise).then((source) => { + return _getReaderFromSource(source); + }); + }); + const streamDeferred = new Deferred(); + let i = 0; + const logMessages = []; + const stream = new ReadableStream({ + pull(controller) { + return readerPromises[i] + .then((reader) => { + if (reader instanceof ReadableStreamDefaultReader) { + return reader.read(); + } + else { + return; + } + }) + .then((result) => { + if (result === null || result === void 0 ? void 0 : result.done) { + if (process.env.NODE_ENV !== 'production') { + logMessages.push([ + 'Reached the end of source:', + sourcePromises[i], + ]); + } + i++; + if (i >= readerPromises.length) { + // Log all the messages in the group at once in a single group. + if (process.env.NODE_ENV !== 'production') { + logger.groupCollapsed(`Concatenating ${readerPromises.length} sources.`); + for (const message of logMessages) { + if (Array.isArray(message)) { + logger.log(...message); + } + else { + logger.log(message); + } + } + logger.log('Finished reading all sources.'); + logger.groupEnd(); + } + controller.close(); + streamDeferred.resolve(); + return; + } + // The `pull` method is defined because we're inside it. + return this.pull(controller); + } + else { + controller.enqueue(result === null || result === void 0 ? void 0 : result.value); + } + }) + .catch((error) => { + if (process.env.NODE_ENV !== 'production') { + logger.error('An error occurred:', error); + } + streamDeferred.reject(error); + throw error; + }); + }, + cancel() { + if (process.env.NODE_ENV !== 'production') { + logger.warn('The ReadableStream was cancelled.'); + } + streamDeferred.resolve(); + }, + }); + return { done: streamDeferred.promise, stream }; +} +export { concatenate }; diff --git a/node_modules/workbox-streams/concatenate.mjs b/node_modules/workbox-streams/concatenate.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1b37f7a838f920249a0701c4a68a139d3d798f51 --- /dev/null +++ b/node_modules/workbox-streams/concatenate.mjs @@ -0,0 +1 @@ +export * from './concatenate.js'; \ No newline at end of file diff --git a/node_modules/workbox-streams/concatenateToResponse.d.ts b/node_modules/workbox-streams/concatenateToResponse.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9d732892b9261ff7e73ad268e21668cf455b5263 --- /dev/null +++ b/node_modules/workbox-streams/concatenateToResponse.d.ts @@ -0,0 +1,24 @@ +import { StreamSource } from './_types.js'; +import './_version.js'; +/** + * Takes multiple source Promises, each of which could resolve to a Response, a + * ReadableStream, or a [BodyInit](https://fetch.spec.whatwg.org/#bodyinit), + * along with a + * [HeadersInit](https://fetch.spec.whatwg.org/#typedefdef-headersinit). + * + * Returns an object exposing a Response whose body consists of each individual + * stream's data returned in sequence, along with a Promise which signals when + * the stream is finished (useful for passing to a FetchEvent's waitUntil()). + * + * @param {Array>} sourcePromises + * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified, + * `'text/html'` will be used by default. + * @return {Object<{done: Promise, response: Response}>} + * + * @memberof workbox-streams + */ +declare function concatenateToResponse(sourcePromises: Promise[], headersInit: HeadersInit): { + done: Promise; + response: Response; +}; +export { concatenateToResponse }; diff --git a/node_modules/workbox-streams/concatenateToResponse.js b/node_modules/workbox-streams/concatenateToResponse.js new file mode 100644 index 0000000000000000000000000000000000000000..8eb81a19c3288c1acab051b5c4e14479b13f2921 --- /dev/null +++ b/node_modules/workbox-streams/concatenateToResponse.js @@ -0,0 +1,34 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { createHeaders } from './utils/createHeaders.js'; +import { concatenate } from './concatenate.js'; +import './_version.js'; +/** + * Takes multiple source Promises, each of which could resolve to a Response, a + * ReadableStream, or a [BodyInit](https://fetch.spec.whatwg.org/#bodyinit), + * along with a + * [HeadersInit](https://fetch.spec.whatwg.org/#typedefdef-headersinit). + * + * Returns an object exposing a Response whose body consists of each individual + * stream's data returned in sequence, along with a Promise which signals when + * the stream is finished (useful for passing to a FetchEvent's waitUntil()). + * + * @param {Array>} sourcePromises + * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified, + * `'text/html'` will be used by default. + * @return {Object<{done: Promise, response: Response}>} + * + * @memberof workbox-streams + */ +function concatenateToResponse(sourcePromises, headersInit) { + const { done, stream } = concatenate(sourcePromises); + const headers = createHeaders(headersInit); + const response = new Response(stream, { headers }); + return { done, response }; +} +export { concatenateToResponse }; diff --git a/node_modules/workbox-streams/concatenateToResponse.mjs b/node_modules/workbox-streams/concatenateToResponse.mjs new file mode 100644 index 0000000000000000000000000000000000000000..28a2e2cb0101ccaf18f699997b6fa280400c896d --- /dev/null +++ b/node_modules/workbox-streams/concatenateToResponse.mjs @@ -0,0 +1 @@ +export * from './concatenateToResponse.js'; \ No newline at end of file diff --git a/node_modules/workbox-streams/index.d.ts b/node_modules/workbox-streams/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b8ea5123508d261fc7d50b823ab3adcb9bc2a541 --- /dev/null +++ b/node_modules/workbox-streams/index.d.ts @@ -0,0 +1,10 @@ +import { concatenate } from './concatenate.js'; +import { concatenateToResponse } from './concatenateToResponse.js'; +import { isSupported } from './isSupported.js'; +import { strategy, StreamsHandlerCallback } from './strategy.js'; +import './_version.js'; +/** + * @module workbox-streams + */ +export { concatenate, concatenateToResponse, isSupported, strategy, StreamsHandlerCallback, }; +export * from './_types.js'; diff --git a/node_modules/workbox-streams/index.js b/node_modules/workbox-streams/index.js new file mode 100644 index 0000000000000000000000000000000000000000..93d8ca7c786204d9fb4abfa5f8d23c5577e8c4ee --- /dev/null +++ b/node_modules/workbox-streams/index.js @@ -0,0 +1,17 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { concatenate } from './concatenate.js'; +import { concatenateToResponse } from './concatenateToResponse.js'; +import { isSupported } from './isSupported.js'; +import { strategy } from './strategy.js'; +import './_version.js'; +/** + * @module workbox-streams + */ +export { concatenate, concatenateToResponse, isSupported, strategy, }; +export * from './_types.js'; diff --git a/node_modules/workbox-streams/index.mjs b/node_modules/workbox-streams/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..833b6a2f3226fec78490a3b7a622dc5146f94b53 --- /dev/null +++ b/node_modules/workbox-streams/index.mjs @@ -0,0 +1 @@ +export * from './index.js'; \ No newline at end of file diff --git a/node_modules/workbox-streams/isSupported.d.ts b/node_modules/workbox-streams/isSupported.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e588b35cfcbbedf3ed4d89318a9a66118e7859f1 --- /dev/null +++ b/node_modules/workbox-streams/isSupported.d.ts @@ -0,0 +1,14 @@ +import './_version.js'; +/** + * This is a utility method that determines whether the current browser supports + * the features required to create streamed responses. Currently, it checks if + * [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream) + * can be created. + * + * @return {boolean} `true`, if the current browser meets the requirements for + * streaming responses, and `false` otherwise. + * + * @memberof workbox-streams + */ +declare function isSupported(): boolean; +export { isSupported }; diff --git a/node_modules/workbox-streams/isSupported.js b/node_modules/workbox-streams/isSupported.js new file mode 100644 index 0000000000000000000000000000000000000000..97afd40b67313997ddf8ba814c777a90f40ef75a --- /dev/null +++ b/node_modules/workbox-streams/isSupported.js @@ -0,0 +1,24 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { canConstructReadableStream } from 'workbox-core/_private/canConstructReadableStream.js'; +import './_version.js'; +/** + * This is a utility method that determines whether the current browser supports + * the features required to create streamed responses. Currently, it checks if + * [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream) + * can be created. + * + * @return {boolean} `true`, if the current browser meets the requirements for + * streaming responses, and `false` otherwise. + * + * @memberof workbox-streams + */ +function isSupported() { + return canConstructReadableStream(); +} +export { isSupported }; diff --git a/node_modules/workbox-streams/isSupported.mjs b/node_modules/workbox-streams/isSupported.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e4ec954938b7476095238ddcdab20e8f49b69f0b --- /dev/null +++ b/node_modules/workbox-streams/isSupported.mjs @@ -0,0 +1 @@ +export * from './isSupported.js'; \ No newline at end of file diff --git a/node_modules/workbox-streams/package.json b/node_modules/workbox-streams/package.json new file mode 100644 index 0000000000000000000000000000000000000000..48624dfff38947ccd0dd54d2893d8b560edcef22 --- /dev/null +++ b/node_modules/workbox-streams/package.json @@ -0,0 +1,33 @@ +{ + "name": "workbox-streams", + "version": "7.4.1", + "license": "MIT", + "author": "Google's Web DevRel Team and Google's Aurora Team", + "description": "A library that makes it easier to work with Streams in the browser.", + "repository": { + "type": "git", + "url": "git+https://github.com/googlechrome/workbox.git" + }, + "bugs": "https://github.com/googlechrome/workbox/issues", + "homepage": "https://github.com/GoogleChrome/workbox", + "keywords": [ + "workbox", + "workboxjs", + "service worker", + "sw", + "streams", + "readablestream" + ], + "workbox": { + "browserNamespace": "workbox.streams", + "packageType": "sw" + }, + "main": "index.js", + "module": "index.mjs", + "types": "index.d.ts", + "dependencies": { + "workbox-core": "7.4.1", + "workbox-routing": "7.4.1" + }, + "gitHead": "62b9d8ba8eb3c1a2ab8aac9d84c90cda7865d6a3" +} diff --git a/node_modules/workbox-streams/src/_types.ts b/node_modules/workbox-streams/src/_types.ts new file mode 100644 index 0000000000000000000000000000000000000000..2a3f3878c6579497520e1ec8a3a0aef66a4e3bea --- /dev/null +++ b/node_modules/workbox-streams/src/_types.ts @@ -0,0 +1,23 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import './_version.js'; + +export type StreamSource = Response | ReadableStream | BodyInit; + +// * * * IMPORTANT! * * * +// ------------------------------------------------------------------------- // +// jdsoc type definitions cannot be declared above TypeScript definitions or +// they'll be stripped from the built `.js` files, and they'll only be in the +// `d.ts` files, which aren't read by the jsdoc generator. As a result we +// have to put declare them below. + +/** + * @typedef {Response|ReadableStream|BodyInit} StreamSource + * @memberof workbox-streams + */ diff --git a/node_modules/workbox-streams/src/_version.ts b/node_modules/workbox-streams/src/_version.ts new file mode 100644 index 0000000000000000000000000000000000000000..46a1ed83ce0703daa5c10756c52da5b8be6b01ce --- /dev/null +++ b/node_modules/workbox-streams/src/_version.ts @@ -0,0 +1,2 @@ +// @ts-ignore +try{self['workbox:streams:7.4.1']&&_()}catch(e){} \ No newline at end of file diff --git a/node_modules/workbox-streams/src/concatenate.ts b/node_modules/workbox-streams/src/concatenate.ts new file mode 100644 index 0000000000000000000000000000000000000000..c6ba329f6d314d54c9ab6058e1e309585c49f2f1 --- /dev/null +++ b/node_modules/workbox-streams/src/concatenate.ts @@ -0,0 +1,146 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {assert} from 'workbox-core/_private/assert.js'; +import {Deferred} from 'workbox-core/_private/Deferred.js'; +import {logger} from 'workbox-core/_private/logger.js'; +import {StreamSource} from './_types.js'; +import {WorkboxError} from 'workbox-core/_private/WorkboxError.js'; + +import './_version.js'; + +/** + * Takes either a Response, a ReadableStream, or a + * [BodyInit](https://fetch.spec.whatwg.org/#bodyinit) and returns the + * ReadableStreamReader object associated with it. + * + * @param {workbox-streams.StreamSource} source + * @return {ReadableStreamReader} + * @private + */ +function _getReaderFromSource( + source: StreamSource, +): ReadableStreamReader { + if (source instanceof Response) { + // See https://github.com/GoogleChrome/workbox/issues/2998 + if (source.body) { + return source.body.getReader(); + } + throw new WorkboxError('opaque-streams-source', {type: source.type}); + } + if (source instanceof ReadableStream) { + return source.getReader(); + } + return new Response(source as BodyInit).body!.getReader(); +} + +/** + * Takes multiple source Promises, each of which could resolve to a Response, a + * ReadableStream, or a [BodyInit](https://fetch.spec.whatwg.org/#bodyinit). + * + * Returns an object exposing a ReadableStream with each individual stream's + * data returned in sequence, along with a Promise which signals when the + * stream is finished (useful for passing to a FetchEvent's waitUntil()). + * + * @param {Array>} sourcePromises + * @return {Object<{done: Promise, stream: ReadableStream}>} + * + * @memberof workbox-streams + */ +function concatenate(sourcePromises: Promise[]): { + done: Promise; + stream: ReadableStream; +} { + if (process.env.NODE_ENV !== 'production') { + assert!.isArray(sourcePromises, { + moduleName: 'workbox-streams', + funcName: 'concatenate', + paramName: 'sourcePromises', + }); + } + + const readerPromises = sourcePromises.map((sourcePromise) => { + return Promise.resolve(sourcePromise).then((source) => { + return _getReaderFromSource(source); + }); + }); + + const streamDeferred: Deferred = new Deferred(); + + let i = 0; + const logMessages: any[] = []; + const stream = new ReadableStream({ + pull(controller: ReadableStreamDefaultController) { + return readerPromises[i] + .then((reader) => { + if (reader instanceof ReadableStreamDefaultReader) { + return reader.read(); + } else { + return; + } + }) + .then((result) => { + if (result?.done) { + if (process.env.NODE_ENV !== 'production') { + logMessages.push([ + 'Reached the end of source:', + sourcePromises[i], + ]); + } + + i++; + if (i >= readerPromises.length) { + // Log all the messages in the group at once in a single group. + if (process.env.NODE_ENV !== 'production') { + logger.groupCollapsed( + `Concatenating ${readerPromises.length} sources.`, + ); + for (const message of logMessages) { + if (Array.isArray(message)) { + logger.log(...message); + } else { + logger.log(message); + } + } + logger.log('Finished reading all sources.'); + logger.groupEnd(); + } + + controller.close(); + streamDeferred.resolve(); + return; + } + + // The `pull` method is defined because we're inside it. + return this.pull!(controller); + } else { + controller.enqueue(result?.value); + } + }) + .catch((error) => { + if (process.env.NODE_ENV !== 'production') { + logger.error('An error occurred:', error); + } + streamDeferred.reject(error); + throw error; + }); + }, + + cancel() { + if (process.env.NODE_ENV !== 'production') { + logger.warn('The ReadableStream was cancelled.'); + } + + streamDeferred.resolve(); + }, + }); + + return {done: streamDeferred.promise, stream}; +} + +export {concatenate}; diff --git a/node_modules/workbox-streams/src/concatenateToResponse.ts b/node_modules/workbox-streams/src/concatenateToResponse.ts new file mode 100644 index 0000000000000000000000000000000000000000..5e45fbbc1bc477d1c250df9bf0138bc01523be2d --- /dev/null +++ b/node_modules/workbox-streams/src/concatenateToResponse.ts @@ -0,0 +1,43 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {createHeaders} from './utils/createHeaders.js'; +import {concatenate} from './concatenate.js'; +import {StreamSource} from './_types.js'; +import './_version.js'; + +/** + * Takes multiple source Promises, each of which could resolve to a Response, a + * ReadableStream, or a [BodyInit](https://fetch.spec.whatwg.org/#bodyinit), + * along with a + * [HeadersInit](https://fetch.spec.whatwg.org/#typedefdef-headersinit). + * + * Returns an object exposing a Response whose body consists of each individual + * stream's data returned in sequence, along with a Promise which signals when + * the stream is finished (useful for passing to a FetchEvent's waitUntil()). + * + * @param {Array>} sourcePromises + * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified, + * `'text/html'` will be used by default. + * @return {Object<{done: Promise, response: Response}>} + * + * @memberof workbox-streams + */ +function concatenateToResponse( + sourcePromises: Promise[], + headersInit: HeadersInit, +): {done: Promise; response: Response} { + const {done, stream} = concatenate(sourcePromises); + + const headers = createHeaders(headersInit); + const response = new Response(stream, {headers}); + + return {done, response}; +} + +export {concatenateToResponse}; diff --git a/node_modules/workbox-streams/src/index.ts b/node_modules/workbox-streams/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..e4c929465aa1ca9b288641b97c65f132c737fa6f --- /dev/null +++ b/node_modules/workbox-streams/src/index.ts @@ -0,0 +1,28 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {concatenate} from './concatenate.js'; +import {concatenateToResponse} from './concatenateToResponse.js'; +import {isSupported} from './isSupported.js'; +import {strategy, StreamsHandlerCallback} from './strategy.js'; + +import './_version.js'; + +/** + * @module workbox-streams + */ + +export { + concatenate, + concatenateToResponse, + isSupported, + strategy, + StreamsHandlerCallback, +}; + +export * from './_types.js'; diff --git a/node_modules/workbox-streams/src/isSupported.ts b/node_modules/workbox-streams/src/isSupported.ts new file mode 100644 index 0000000000000000000000000000000000000000..d6107ee7dd61e3bf40b356f9fc6f53487a63b355 --- /dev/null +++ b/node_modules/workbox-streams/src/isSupported.ts @@ -0,0 +1,27 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {canConstructReadableStream} from 'workbox-core/_private/canConstructReadableStream.js'; +import './_version.js'; + +/** + * This is a utility method that determines whether the current browser supports + * the features required to create streamed responses. Currently, it checks if + * [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream) + * can be created. + * + * @return {boolean} `true`, if the current browser meets the requirements for + * streaming responses, and `false` otherwise. + * + * @memberof workbox-streams + */ +function isSupported(): boolean { + return canConstructReadableStream(); +} + +export {isSupported}; diff --git a/node_modules/workbox-streams/src/strategy.ts b/node_modules/workbox-streams/src/strategy.ts new file mode 100644 index 0000000000000000000000000000000000000000..f90cd378561918b6b1be6c5640b18704beafbd51 --- /dev/null +++ b/node_modules/workbox-streams/src/strategy.ts @@ -0,0 +1,94 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {logger} from 'workbox-core/_private/logger.js'; +import { + RouteHandlerCallback, + RouteHandlerCallbackOptions, +} from 'workbox-core/types.js'; +import {createHeaders} from './utils/createHeaders.js'; +import {concatenateToResponse} from './concatenateToResponse.js'; +import {isSupported} from './isSupported.js'; +import {StreamSource} from './_types.js'; +import './_version.js'; + +export interface StreamsHandlerCallback { + ({url, request, event, params}: RouteHandlerCallbackOptions): + | Promise + | StreamSource; +} + +/** + * A shortcut to create a strategy that could be dropped-in to Workbox's router. + * + * On browsers that do not support constructing new `ReadableStream`s, this + * strategy will automatically wait for all the `sourceFunctions` to complete, + * and create a final response that concatenates their values together. + * + * @param {Array} sourceFunctions + * An array of functions similar to {@link workbox-routing~handlerCallback} + * but that instead return a {@link workbox-streams.StreamSource} (or a + * Promise which resolves to one). + * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified, + * `'text/html'` will be used by default. + * @return {workbox-routing~handlerCallback} + * @memberof workbox-streams + */ +function strategy( + sourceFunctions: StreamsHandlerCallback[], + headersInit: HeadersInit, +): RouteHandlerCallback { + return async ({event, request, url, params}: RouteHandlerCallbackOptions) => { + const sourcePromises = sourceFunctions.map((fn) => { + // Ensure the return value of the function is always a promise. + return Promise.resolve(fn({event, request, url, params})); + }); + + if (isSupported()) { + const {done, response} = concatenateToResponse( + sourcePromises, + headersInit, + ); + + if (event) { + event.waitUntil(done); + } + return response; + } + + if (process.env.NODE_ENV !== 'production') { + logger.log( + `The current browser doesn't support creating response ` + + `streams. Falling back to non-streaming response instead.`, + ); + } + + // Fallback to waiting for everything to finish, and concatenating the + // responses. + const blobPartsPromises = sourcePromises.map(async (sourcePromise) => { + const source = await sourcePromise; + if (source instanceof Response) { + return source.blob(); + } else { + // Technically, a `StreamSource` object can include any valid + // `BodyInit` type, including `FormData` and `URLSearchParams`, which + // cannot be passed to the Blob constructor directly, so we have to + // convert them to actual Blobs first. + return new Response(source).blob(); + } + }); + const blobParts = await Promise.all(blobPartsPromises); + const headers = createHeaders(headersInit); + + // Constructing a new Response from a Blob source is well-supported. + // So is constructing a new Blob from multiple source Blobs or strings. + return new Response(new Blob(blobParts), {headers}); + }; +} + +export {strategy}; diff --git a/node_modules/workbox-streams/src/utils/createHeaders.ts b/node_modules/workbox-streams/src/utils/createHeaders.ts new file mode 100644 index 0000000000000000000000000000000000000000..c3e51b94465af09ef6e15d065f889e8e58cccfc9 --- /dev/null +++ b/node_modules/workbox-streams/src/utils/createHeaders.ts @@ -0,0 +1,34 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import '../_version.js'; + +/** + * This is a utility method that determines whether the current browser supports + * the features required to create streamed responses. Currently, it checks if + * [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream) + * is available. + * + * @private + * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified, + * `'text/html'` will be used by default. + * @return {boolean} `true`, if the current browser meets the requirements for + * streaming responses, and `false` otherwise. + * + * @memberof workbox-streams + */ +function createHeaders(headersInit = {}): Headers { + // See https://github.com/GoogleChrome/workbox/issues/1461 + const headers = new Headers(headersInit); + if (!headers.has('content-type')) { + headers.set('content-type', 'text/html'); + } + return headers; +} + +export {createHeaders}; diff --git a/node_modules/workbox-streams/strategy.d.ts b/node_modules/workbox-streams/strategy.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5c5f53affd94368ebb54a6597ee6fb9b655c65a1 --- /dev/null +++ b/node_modules/workbox-streams/strategy.d.ts @@ -0,0 +1,24 @@ +import { RouteHandlerCallback, RouteHandlerCallbackOptions } from 'workbox-core/types.js'; +import { StreamSource } from './_types.js'; +import './_version.js'; +export interface StreamsHandlerCallback { + ({ url, request, event, params }: RouteHandlerCallbackOptions): Promise | StreamSource; +} +/** + * A shortcut to create a strategy that could be dropped-in to Workbox's router. + * + * On browsers that do not support constructing new `ReadableStream`s, this + * strategy will automatically wait for all the `sourceFunctions` to complete, + * and create a final response that concatenates their values together. + * + * @param {Array} sourceFunctions + * An array of functions similar to {@link workbox-routing~handlerCallback} + * but that instead return a {@link workbox-streams.StreamSource} (or a + * Promise which resolves to one). + * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified, + * `'text/html'` will be used by default. + * @return {workbox-routing~handlerCallback} + * @memberof workbox-streams + */ +declare function strategy(sourceFunctions: StreamsHandlerCallback[], headersInit: HeadersInit): RouteHandlerCallback; +export { strategy }; diff --git a/node_modules/workbox-streams/strategy.js b/node_modules/workbox-streams/strategy.js new file mode 100644 index 0000000000000000000000000000000000000000..227abd81ba4fcdb69b3738d30a4dbf0017ec3a1f --- /dev/null +++ b/node_modules/workbox-streams/strategy.js @@ -0,0 +1,68 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { logger } from 'workbox-core/_private/logger.js'; +import { createHeaders } from './utils/createHeaders.js'; +import { concatenateToResponse } from './concatenateToResponse.js'; +import { isSupported } from './isSupported.js'; +import './_version.js'; +/** + * A shortcut to create a strategy that could be dropped-in to Workbox's router. + * + * On browsers that do not support constructing new `ReadableStream`s, this + * strategy will automatically wait for all the `sourceFunctions` to complete, + * and create a final response that concatenates their values together. + * + * @param {Array} sourceFunctions + * An array of functions similar to {@link workbox-routing~handlerCallback} + * but that instead return a {@link workbox-streams.StreamSource} (or a + * Promise which resolves to one). + * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified, + * `'text/html'` will be used by default. + * @return {workbox-routing~handlerCallback} + * @memberof workbox-streams + */ +function strategy(sourceFunctions, headersInit) { + return async ({ event, request, url, params }) => { + const sourcePromises = sourceFunctions.map((fn) => { + // Ensure the return value of the function is always a promise. + return Promise.resolve(fn({ event, request, url, params })); + }); + if (isSupported()) { + const { done, response } = concatenateToResponse(sourcePromises, headersInit); + if (event) { + event.waitUntil(done); + } + return response; + } + if (process.env.NODE_ENV !== 'production') { + logger.log(`The current browser doesn't support creating response ` + + `streams. Falling back to non-streaming response instead.`); + } + // Fallback to waiting for everything to finish, and concatenating the + // responses. + const blobPartsPromises = sourcePromises.map(async (sourcePromise) => { + const source = await sourcePromise; + if (source instanceof Response) { + return source.blob(); + } + else { + // Technically, a `StreamSource` object can include any valid + // `BodyInit` type, including `FormData` and `URLSearchParams`, which + // cannot be passed to the Blob constructor directly, so we have to + // convert them to actual Blobs first. + return new Response(source).blob(); + } + }); + const blobParts = await Promise.all(blobPartsPromises); + const headers = createHeaders(headersInit); + // Constructing a new Response from a Blob source is well-supported. + // So is constructing a new Blob from multiple source Blobs or strings. + return new Response(new Blob(blobParts), { headers }); + }; +} +export { strategy }; diff --git a/node_modules/workbox-streams/strategy.mjs b/node_modules/workbox-streams/strategy.mjs new file mode 100644 index 0000000000000000000000000000000000000000..92a4cc2261db7044f7c5d87410a6a784efd3c811 --- /dev/null +++ b/node_modules/workbox-streams/strategy.mjs @@ -0,0 +1 @@ +export * from './strategy.js'; \ No newline at end of file diff --git a/node_modules/workbox-streams/tsconfig.json b/node_modules/workbox-streams/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..2457eadcf8e39664b6315f538007e7de076be21d --- /dev/null +++ b/node_modules/workbox-streams/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig", + "compilerOptions": { + "outDir": "./", + "rootDir": "./src", + "tsBuildInfoFile": "./tsconfig.tsbuildinfo" + }, + "include": ["src/**/*.ts"], + "references": [{"path": "../workbox-core/"}] +} diff --git a/node_modules/workbox-streams/utils/createHeaders.d.ts b/node_modules/workbox-streams/utils/createHeaders.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..368132415fd099b4051fe55d23394281b761a550 --- /dev/null +++ b/node_modules/workbox-streams/utils/createHeaders.d.ts @@ -0,0 +1,17 @@ +import '../_version.js'; +/** + * This is a utility method that determines whether the current browser supports + * the features required to create streamed responses. Currently, it checks if + * [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream) + * is available. + * + * @private + * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified, + * `'text/html'` will be used by default. + * @return {boolean} `true`, if the current browser meets the requirements for + * streaming responses, and `false` otherwise. + * + * @memberof workbox-streams + */ +declare function createHeaders(headersInit?: {}): Headers; +export { createHeaders }; diff --git a/node_modules/workbox-streams/utils/createHeaders.js b/node_modules/workbox-streams/utils/createHeaders.js new file mode 100644 index 0000000000000000000000000000000000000000..2115d9a013d44b3123ac6ce2484e7644e3675e65 --- /dev/null +++ b/node_modules/workbox-streams/utils/createHeaders.js @@ -0,0 +1,31 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import '../_version.js'; +/** + * This is a utility method that determines whether the current browser supports + * the features required to create streamed responses. Currently, it checks if + * [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream) + * is available. + * + * @private + * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified, + * `'text/html'` will be used by default. + * @return {boolean} `true`, if the current browser meets the requirements for + * streaming responses, and `false` otherwise. + * + * @memberof workbox-streams + */ +function createHeaders(headersInit = {}) { + // See https://github.com/GoogleChrome/workbox/issues/1461 + const headers = new Headers(headersInit); + if (!headers.has('content-type')) { + headers.set('content-type', 'text/html'); + } + return headers; +} +export { createHeaders }; diff --git a/node_modules/workbox-streams/utils/createHeaders.mjs b/node_modules/workbox-streams/utils/createHeaders.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c91c0c42652d820eeb8a7961929d33e86ca388e3 --- /dev/null +++ b/node_modules/workbox-streams/utils/createHeaders.mjs @@ -0,0 +1 @@ +export * from './createHeaders.js'; \ No newline at end of file diff --git a/node_modules/workbox-sw/LICENSE b/node_modules/workbox-sw/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..845b545fd0f5031a944cda8cf9018eb066500040 --- /dev/null +++ b/node_modules/workbox-sw/LICENSE @@ -0,0 +1,19 @@ +Copyright 2018 Google LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/workbox-sw/README.md b/node_modules/workbox-sw/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b4504bf72a328e1a8068689437c18993a9b061c1 --- /dev/null +++ b/node_modules/workbox-sw/README.md @@ -0,0 +1 @@ +This module's documentation can be found at https://developers.google.com/web/tools/workbox/modules/workbox-sw diff --git a/node_modules/workbox-sw/_types.mjs b/node_modules/workbox-sw/_types.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a06757b7b581d1566b4806a03e658458ddb44daf --- /dev/null +++ b/node_modules/workbox-sw/_types.mjs @@ -0,0 +1,24 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import './_version.mjs'; + +/** + * A `ModulePathCallback` function can be used to modify the modify the where + * Workbox modules are loaded. + * + * @callback ~ModulePathCallback + * @param {string} moduleName The name of the module to load (i.e. + * 'workbox-core', 'workbox-precaching' etc.). + * @param {boolean} debug When true, `dev` builds should be loaded, otherwise + * load `prod` builds. + * @return {string} This callback should return a path of module. This will + * be passed to `importScripts()`. + * + * @memberof workbox + */ diff --git a/node_modules/workbox-sw/_version.mjs b/node_modules/workbox-sw/_version.mjs new file mode 100644 index 0000000000000000000000000000000000000000..db26649438c273b1c3c5d4644f15d0c45cc429d2 --- /dev/null +++ b/node_modules/workbox-sw/_version.mjs @@ -0,0 +1 @@ +try{self['workbox:sw:7.4.1']&&_()}catch(e){}// eslint-disable-line \ No newline at end of file diff --git a/node_modules/workbox-sw/build/workbox-sw.js b/node_modules/workbox-sw/build/workbox-sw.js new file mode 100644 index 0000000000000000000000000000000000000000..13a45e262d84f8887d1d14c6e65353909a6702f8 --- /dev/null +++ b/node_modules/workbox-sw/build/workbox-sw.js @@ -0,0 +1,2 @@ +!function(){"use strict";try{self["workbox:sw:7.4.1"]&&_()}catch(t){}const t={backgroundSync:"background-sync",broadcastUpdate:"broadcast-update",cacheableResponse:"cacheable-response",core:"core",expiration:"expiration",googleAnalytics:"offline-ga",navigationPreload:"navigation-preload",precaching:"precaching",rangeRequests:"range-requests",routing:"routing",strategies:"strategies",streams:"streams",recipes:"recipes"};self.workbox=new class{constructor(){return this.v={},this.t={debug:"localhost"===self.location.hostname,modulePathPrefix:null,modulePathCb:null},this.o=this.t.debug?"dev":"prod",this.i=!1,new Proxy(this,{get(e,s){if(e[s])return e[s];const o=t[s];return o&&e.loadModule(`workbox-${o}`),e[s]}})}setConfig(t={}){if(this.i)throw new Error("Config must be set before accessing workbox.* modules");Object.assign(this.t,t),this.o=this.t.debug?"dev":"prod"}loadModule(t){const e=this.h(t);try{importScripts(e),this.i=!0}catch(s){throw console.error(`Unable to import module '${t}' from '${e}'.`),s}}h(t){if(this.t.modulePathCb)return this.t.modulePathCb(t,this.t.debug);let e=["https://storage.googleapis.com/workbox-cdn/releases/7.4.1"];const s=`${t}.${this.o}.js`,o=this.t.modulePathPrefix;return o&&(e=o.split("/"),""===e[e.length-1]&&e.splice(e.length-1,1)),e.push(s),e.join("/")}}}(); +//# sourceMappingURL=workbox-sw.js.map diff --git a/node_modules/workbox-sw/build/workbox-sw.js.map b/node_modules/workbox-sw/build/workbox-sw.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e68d31fddeb7a8b63cd270aa9dc7ea4000fee2b9 --- /dev/null +++ b/node_modules/workbox-sw/build/workbox-sw.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-sw.js","sources":["../_version.mjs","../controllers/WorkboxSW.mjs","../index.mjs"],"sourcesContent":["try{self['workbox:sw:7.4.1']&&_()}catch(e){}// eslint-disable-line","/*\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*/\n\nimport '../_version.mjs';\n\nconst CDN_PATH = `WORKBOX_CDN_ROOT_URL`;\n\nconst MODULE_KEY_TO_NAME_MAPPING = {\n /**\n * @name backgroundSync\n * @memberof workbox\n * @see module:workbox-background-sync\n */\n backgroundSync: 'background-sync',\n /**\n * @name broadcastUpdate\n * @memberof workbox\n * @see module:workbox-broadcast-update\n */\n broadcastUpdate: 'broadcast-update',\n /**\n * @name cacheableResponse\n * @memberof workbox\n * @see module:workbox-cacheable-response\n */\n cacheableResponse: 'cacheable-response',\n /**\n * @name core\n * @memberof workbox\n * @see module:workbox-core\n */\n core: 'core',\n /**\n * @name expiration\n * @memberof workbox\n * @see module:workbox-expiration\n */\n expiration: 'expiration',\n /**\n * @name googleAnalytics\n * @memberof workbox\n * @see module:workbox-google-analytics\n */\n googleAnalytics: 'offline-ga',\n /**\n * @name navigationPreload\n * @memberof workbox\n * @see module:workbox-navigation-preload\n */\n navigationPreload: 'navigation-preload',\n /**\n * @name precaching\n * @memberof workbox\n * @see module:workbox-precaching\n */\n precaching: 'precaching',\n /**\n * @name rangeRequests\n * @memberof workbox\n * @see module:workbox-range-requests\n */\n rangeRequests: 'range-requests',\n /**\n * @name routing\n * @memberof workbox\n * @see module:workbox-routing\n */\n routing: 'routing',\n /**\n * @name strategies\n * @memberof workbox\n * @see module:workbox-strategies\n */\n strategies: 'strategies',\n /**\n * @name streams\n * @memberof workbox\n * @see module:workbox-streams\n */\n streams: 'streams',\n /**\n * @name recipes\n * @memberof workbox\n * @see module:workbox-recipes\n */\n recipes: 'recipes',\n};\n\n/**\n * This class can be used to make it easy to use the various parts of\n * Workbox.\n *\n * @private\n */\nexport class WorkboxSW {\n /**\n * Creates a proxy that automatically loads workbox namespaces on demand.\n *\n * @private\n */\n constructor() {\n this.v = {};\n this._options = {\n debug: self.location.hostname === 'localhost',\n modulePathPrefix: null,\n modulePathCb: null,\n };\n\n this._env = this._options.debug ? 'dev' : 'prod';\n this._modulesLoaded = false;\n\n return new Proxy(this, {\n get(target, key) {\n if (target[key]) {\n return target[key];\n }\n\n const moduleName = MODULE_KEY_TO_NAME_MAPPING[key];\n if (moduleName) {\n target.loadModule(`workbox-${moduleName}`);\n }\n\n return target[key];\n },\n });\n }\n\n /**\n * Updates the configuration options. You can specify whether to treat as a\n * debug build and whether to use a CDN or a specific path when importing\n * other workbox-modules\n *\n * @param {Object} [options]\n * @param {boolean} [options.debug] If true, `dev` builds are using, otherwise\n * `prod` builds are used. By default, `prod` is used unless on localhost.\n * @param {Function} [options.modulePathPrefix] To avoid using the CDN with\n * `workbox-sw` set the path prefix of where modules should be loaded from.\n * For example `modulePathPrefix: '/third_party/workbox/v3.0.0/'`.\n * @param {workbox~ModulePathCallback} [options.modulePathCb] If defined,\n * this callback will be responsible for determining the path of each\n * workbox module.\n *\n * @alias workbox.setConfig\n */\n setConfig(options = {}) {\n if (!this._modulesLoaded) {\n Object.assign(this._options, options);\n this._env = this._options.debug ? 'dev' : 'prod';\n } else {\n throw new Error('Config must be set before accessing workbox.* modules');\n }\n }\n\n /**\n * Load a Workbox module by passing in the appropriate module name.\n *\n * This is not generally needed unless you know there are modules that are\n * dynamically used and you want to safe guard use of the module while the\n * user may be offline.\n *\n * @param {string} moduleName\n *\n * @alias workbox.loadModule\n */\n loadModule(moduleName) {\n const modulePath = this._getImportPath(moduleName);\n try {\n importScripts(modulePath);\n this._modulesLoaded = true;\n } catch (err) {\n // TODO Add context of this error if using the CDN vs the local file.\n\n // We can't rely on workbox-core being loaded so using console\n // eslint-disable-next-line\n console.error(\n `Unable to import module '${moduleName}' from '${modulePath}'.`);\n throw err;\n }\n }\n\n /**\n * This method will get the path / CDN URL to be used for importScript calls.\n *\n * @param {string} moduleName\n * @return {string} URL to the desired module.\n *\n * @private\n */\n _getImportPath(moduleName) {\n if (this._options.modulePathCb) {\n return this._options.modulePathCb(moduleName, this._options.debug);\n }\n\n // TODO: This needs to be dynamic some how.\n let pathParts = [CDN_PATH];\n\n const fileName = `${moduleName}.${this._env}.js`;\n\n const pathPrefix = this._options.modulePathPrefix;\n if (pathPrefix) {\n // Split to avoid issues with developers ending / not ending with slash\n pathParts = pathPrefix.split('/');\n\n // We don't need a slash at the end as we will be adding\n // a filename regardless\n if (pathParts[pathParts.length - 1] === '') {\n pathParts.splice(pathParts.length - 1, 1);\n }\n }\n\n pathParts.push(fileName);\n\n return pathParts.join('/');\n }\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*/\n\nimport {WorkboxSW} from './controllers/WorkboxSW.mjs';\nimport './_version.mjs';\n\n/**\n * @namespace workbox\n */\n\n// Don't export anything, just expose a global.\nself.workbox = new WorkboxSW();\n"],"names":["self","_","e","MODULE_KEY_TO_NAME_MAPPING","backgroundSync","broadcastUpdate","cacheableResponse","core","expiration","googleAnalytics","navigationPreload","precaching","rangeRequests","routing","strategies","streams","recipes","workbox","constructor","this","v","_options","debug","location","hostname","modulePathPrefix","modulePathCb","_env","_modulesLoaded","Proxy","get","target","key","moduleName","loadModule","setConfig","options","Error","Object","assign","modulePath","_getImportPath","importScripts","err","console","error","pathParts","fileName","pathPrefix","split","length","splice","push","join"],"mappings":"yBAAA,IAAIA,KAAK,qBAAqBC,GAAG,CA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AM,KAIW,KAApCH,EAAUA,EAAUI,OAAS,IAC/BJ,EAAUK,OAAOL,EAAUI,OAAS,EAAG,IAI3CJ,EAAUM,KAAKL,GAERD,EAAUO,KAAK,IACxB"} \ No newline at end of file diff --git a/node_modules/workbox-sw/controllers/WorkboxSW.mjs b/node_modules/workbox-sw/controllers/WorkboxSW.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e5c4f2f45e113e6912485e9b8a796d8c181694dd --- /dev/null +++ b/node_modules/workbox-sw/controllers/WorkboxSW.mjs @@ -0,0 +1,220 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import '../_version.mjs'; + +const CDN_PATH = `WORKBOX_CDN_ROOT_URL`; + +const MODULE_KEY_TO_NAME_MAPPING = { + /** + * @name backgroundSync + * @memberof workbox + * @see module:workbox-background-sync + */ + backgroundSync: 'background-sync', + /** + * @name broadcastUpdate + * @memberof workbox + * @see module:workbox-broadcast-update + */ + broadcastUpdate: 'broadcast-update', + /** + * @name cacheableResponse + * @memberof workbox + * @see module:workbox-cacheable-response + */ + cacheableResponse: 'cacheable-response', + /** + * @name core + * @memberof workbox + * @see module:workbox-core + */ + core: 'core', + /** + * @name expiration + * @memberof workbox + * @see module:workbox-expiration + */ + expiration: 'expiration', + /** + * @name googleAnalytics + * @memberof workbox + * @see module:workbox-google-analytics + */ + googleAnalytics: 'offline-ga', + /** + * @name navigationPreload + * @memberof workbox + * @see module:workbox-navigation-preload + */ + navigationPreload: 'navigation-preload', + /** + * @name precaching + * @memberof workbox + * @see module:workbox-precaching + */ + precaching: 'precaching', + /** + * @name rangeRequests + * @memberof workbox + * @see module:workbox-range-requests + */ + rangeRequests: 'range-requests', + /** + * @name routing + * @memberof workbox + * @see module:workbox-routing + */ + routing: 'routing', + /** + * @name strategies + * @memberof workbox + * @see module:workbox-strategies + */ + strategies: 'strategies', + /** + * @name streams + * @memberof workbox + * @see module:workbox-streams + */ + streams: 'streams', + /** + * @name recipes + * @memberof workbox + * @see module:workbox-recipes + */ + recipes: 'recipes', +}; + +/** + * This class can be used to make it easy to use the various parts of + * Workbox. + * + * @private + */ +export class WorkboxSW { + /** + * Creates a proxy that automatically loads workbox namespaces on demand. + * + * @private + */ + constructor() { + this.v = {}; + this._options = { + debug: self.location.hostname === 'localhost', + modulePathPrefix: null, + modulePathCb: null, + }; + + this._env = this._options.debug ? 'dev' : 'prod'; + this._modulesLoaded = false; + + return new Proxy(this, { + get(target, key) { + if (target[key]) { + return target[key]; + } + + const moduleName = MODULE_KEY_TO_NAME_MAPPING[key]; + if (moduleName) { + target.loadModule(`workbox-${moduleName}`); + } + + return target[key]; + }, + }); + } + + /** + * Updates the configuration options. You can specify whether to treat as a + * debug build and whether to use a CDN or a specific path when importing + * other workbox-modules + * + * @param {Object} [options] + * @param {boolean} [options.debug] If true, `dev` builds are using, otherwise + * `prod` builds are used. By default, `prod` is used unless on localhost. + * @param {Function} [options.modulePathPrefix] To avoid using the CDN with + * `workbox-sw` set the path prefix of where modules should be loaded from. + * For example `modulePathPrefix: '/third_party/workbox/v3.0.0/'`. + * @param {workbox~ModulePathCallback} [options.modulePathCb] If defined, + * this callback will be responsible for determining the path of each + * workbox module. + * + * @alias workbox.setConfig + */ + setConfig(options = {}) { + if (!this._modulesLoaded) { + Object.assign(this._options, options); + this._env = this._options.debug ? 'dev' : 'prod'; + } else { + throw new Error('Config must be set before accessing workbox.* modules'); + } + } + + /** + * Load a Workbox module by passing in the appropriate module name. + * + * This is not generally needed unless you know there are modules that are + * dynamically used and you want to safe guard use of the module while the + * user may be offline. + * + * @param {string} moduleName + * + * @alias workbox.loadModule + */ + loadModule(moduleName) { + const modulePath = this._getImportPath(moduleName); + try { + importScripts(modulePath); + this._modulesLoaded = true; + } catch (err) { + // TODO Add context of this error if using the CDN vs the local file. + + // We can't rely on workbox-core being loaded so using console + // eslint-disable-next-line + console.error( + `Unable to import module '${moduleName}' from '${modulePath}'.`); + throw err; + } + } + + /** + * This method will get the path / CDN URL to be used for importScript calls. + * + * @param {string} moduleName + * @return {string} URL to the desired module. + * + * @private + */ + _getImportPath(moduleName) { + if (this._options.modulePathCb) { + return this._options.modulePathCb(moduleName, this._options.debug); + } + + // TODO: This needs to be dynamic some how. + let pathParts = [CDN_PATH]; + + const fileName = `${moduleName}.${this._env}.js`; + + const pathPrefix = this._options.modulePathPrefix; + if (pathPrefix) { + // Split to avoid issues with developers ending / not ending with slash + pathParts = pathPrefix.split('/'); + + // We don't need a slash at the end as we will be adding + // a filename regardless + if (pathParts[pathParts.length - 1] === '') { + pathParts.splice(pathParts.length - 1, 1); + } + } + + pathParts.push(fileName); + + return pathParts.join('/'); + } +} diff --git a/node_modules/workbox-sw/index.mjs b/node_modules/workbox-sw/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f019fb03d504635a1f94aa955b740a5f6c692b9d --- /dev/null +++ b/node_modules/workbox-sw/index.mjs @@ -0,0 +1,17 @@ +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {WorkboxSW} from './controllers/WorkboxSW.mjs'; +import './_version.mjs'; + +/** + * @namespace workbox + */ + +// Don't export anything, just expose a global. +self.workbox = new WorkboxSW(); diff --git a/node_modules/workbox-sw/package.json b/node_modules/workbox-sw/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b542687475a18b03d507fd55493123c527ced27e --- /dev/null +++ b/node_modules/workbox-sw/package.json @@ -0,0 +1,27 @@ +{ + "name": "workbox-sw", + "version": "7.4.1", + "license": "MIT", + "author": "Google's Web DevRel Team and Google's Aurora Team", + "description": "This module makes it easy to get started with the Workbox service worker libraries.", + "repository": { + "type": "git", + "url": "git+https://github.com/googlechrome/workbox.git" + }, + "bugs": "https://github.com/googlechrome/workbox/issues", + "homepage": "https://github.com/GoogleChrome/workbox", + "keywords": [ + "workbox", + "workboxjs", + "service worker", + "sw" + ], + "workbox": { + "browserNamespace": "workbox", + "packageType": "sw", + "prodOnly": true + }, + "main": "build/workbox-sw.js", + "module": "index.mjs", + "gitHead": "62b9d8ba8eb3c1a2ab8aac9d84c90cda7865d6a3" +} diff --git a/node_modules/workbox-window/LICENSE b/node_modules/workbox-window/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..845b545fd0f5031a944cda8cf9018eb066500040 --- /dev/null +++ b/node_modules/workbox-window/LICENSE @@ -0,0 +1,19 @@ +Copyright 2018 Google LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/workbox-window/README.md b/node_modules/workbox-window/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a8c9b9b474c300493f95ee03b4515b3aaf0d71e1 --- /dev/null +++ b/node_modules/workbox-window/README.md @@ -0,0 +1 @@ +This module's documentation can be found at https://developers.google.com/web/tools/workbox/modules/workbox-window diff --git a/node_modules/workbox-window/Workbox.d.ts b/node_modules/workbox-window/Workbox.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3fafc77e9e70b9f9b286f01bca7edf53459b7340 --- /dev/null +++ b/node_modules/workbox-window/Workbox.d.ts @@ -0,0 +1,272 @@ +import { TrustedScriptURL } from 'trusted-types/lib'; +import { WorkboxEventTarget } from './utils/WorkboxEventTarget.js'; +import './_version.js'; +/** + * A class to aid in handling service worker registration, updates, and + * reacting to service worker lifecycle events. + * + * @fires {@link workbox-window.Workbox#message} + * @fires {@link workbox-window.Workbox#installed} + * @fires {@link workbox-window.Workbox#waiting} + * @fires {@link workbox-window.Workbox#controlling} + * @fires {@link workbox-window.Workbox#activated} + * @fires {@link workbox-window.Workbox#redundant} + * @memberof workbox-window + */ +declare class Workbox extends WorkboxEventTarget { + private readonly _scriptURL; + private readonly _registerOptions; + private _updateFoundCount; + private readonly _swDeferred; + private readonly _activeDeferred; + private readonly _controllingDeferred; + private _registrationTime; + private _isUpdate?; + private _compatibleControllingSW?; + private _registration?; + private _sw?; + private readonly _ownSWs; + private _externalSW?; + private _waitingTimeout?; + /** + * Creates a new Workbox instance with a script URL and service worker + * options. The script URL and options are the same as those used when + * calling [navigator.serviceWorker.register(scriptURL, options)](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register). + * + * @param {string|TrustedScriptURL} scriptURL The service worker script + * associated with this instance. Using a + * [`TrustedScriptURL`](https://web.dev/trusted-types/) is supported. + * @param {Object} [registerOptions] The service worker options associated + * with this instance. + */ + constructor(scriptURL: string | TrustedScriptURL, registerOptions?: {}); + /** + * Registers a service worker for this instances script URL and service + * worker options. By default this method delays registration until after + * the window has loaded. + * + * @param {Object} [options] + * @param {Function} [options.immediate=false] Setting this to true will + * register the service worker immediately, even if the window has + * not loaded (not recommended). + */ + register({ immediate }?: { + immediate?: boolean | undefined; + }): Promise; + /** + * Checks for updates of the registered service worker. + */ + update(): Promise; + /** + * Resolves to the service worker registered by this instance as soon as it + * is active. If a service worker was already controlling at registration + * time then it will resolve to that if the script URLs (and optionally + * script versions) match, otherwise it will wait until an update is found + * and activates. + * + * @return {Promise} + */ + get active(): Promise; + /** + * Resolves to the service worker registered by this instance as soon as it + * is controlling the page. If a service worker was already controlling at + * registration time then it will resolve to that if the script URLs (and + * optionally script versions) match, otherwise it will wait until an update + * is found and starts controlling the page. + * Note: the first time a service worker is installed it will active but + * not start controlling the page unless `clients.claim()` is called in the + * service worker. + * + * @return {Promise} + */ + get controlling(): Promise; + /** + * Resolves with a reference to a service worker that matches the script URL + * of this instance, as soon as it's available. + * + * If, at registration time, there's already an active or waiting service + * worker with a matching script URL, it will be used (with the waiting + * service worker taking precedence over the active service worker if both + * match, since the waiting service worker would have been registered more + * recently). + * If there's no matching active or waiting service worker at registration + * time then the promise will not resolve until an update is found and starts + * installing, at which point the installing service worker is used. + * + * @return {Promise} + */ + getSW(): Promise; + /** + * Sends the passed data object to the service worker registered by this + * instance (via {@link workbox-window.Workbox#getSW}) and resolves + * with a response (if any). + * + * A response can be set in a message handler in the service worker by + * calling `event.ports[0].postMessage(...)`, which will resolve the promise + * returned by `messageSW()`. If no response is set, the promise will never + * resolve. + * + * @param {Object} data An object to send to the service worker + * @return {Promise} + */ + messageSW(data: object): Promise; + /** + * Sends a `{type: 'SKIP_WAITING'}` message to the service worker that's + * currently in the `waiting` state associated with the current registration. + * + * If there is no current registration or no service worker is `waiting`, + * calling this will have no effect. + */ + messageSkipWaiting(): void; + /** + * Checks for a service worker already controlling the page and returns + * it if its script URL matches. + * + * @private + * @return {ServiceWorker|undefined} + */ + private _getControllingSWIfCompatible; + /** + * Registers a service worker for this instances script URL and register + * options and tracks the time registration was complete. + * + * @private + */ + private _registerScript; + /** + * @private + */ + private readonly _onUpdateFound; + /** + * @private + * @param {Event} originalEvent + */ + private readonly _onStateChange; + /** + * @private + * @param {Event} originalEvent + */ + private readonly _onControllerChange; + /** + * @private + * @param {Event} originalEvent + */ + private readonly _onMessage; +} +export { Workbox }; +/** + * The `message` event is dispatched any time a `postMessage` is received. + * + * @event workbox-window.Workbox#message + * @type {WorkboxEvent} + * @property {*} data The `data` property from the original `message` event. + * @property {Event} originalEvent The original [`message`]{@link https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent} + * event. + * @property {string} type `message`. + * @property {MessagePort[]} ports The `ports` value from `originalEvent`. + * @property {Workbox} target The `Workbox` instance. + */ +/** + * The `installed` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker} + * changes to `installed`. + * + * Then can happen either the very first time a service worker is installed, + * or after an update to the current service worker is found. In the case + * of an update being found, the event's `isUpdate` property will be `true`. + * + * @event workbox-window.Workbox#installed + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {string} type `installed`. + * @property {Workbox} target The `Workbox` instance. + */ +/** + * The `waiting` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw} + * changes to `installed` and then doesn't immediately change to `activating`. + * It may also be dispatched if a service worker with the same + * [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL} + * was already waiting when the {@link workbox-window.Workbox#register} + * method was called. + * + * @event workbox-window.Workbox#waiting + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event|undefined} originalEvent The original + * [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event, or `undefined` in the case where the service worker was waiting + * to before `.register()` was called. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {boolean|undefined} wasWaitingBeforeRegister True if a service worker with + * a matching `scriptURL` was already waiting when this `Workbox` + * instance called `register()`. + * @property {string} type `waiting`. + * @property {Workbox} target The `Workbox` instance. + */ +/** + * The `controlling` event is dispatched if a + * [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange} + * fires on the service worker [container]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer} + * and the [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL} + * of the new [controller]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller} + * matches the `scriptURL` of the `Workbox` instance's + * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}. + * + * @event workbox-window.Workbox#controlling + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this service worker was registered. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {string} type `controlling`. + * @property {Workbox} target The `Workbox` instance. + */ +/** + * The `activated` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker} + * changes to `activated`. + * + * @event workbox-window.Workbox#activated + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {string} type `activated`. + * @property {Workbox} target The `Workbox` instance. + */ +/** + * The `redundant` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw} + * changes to `redundant`. + * + * @event workbox-window.Workbox#redundant + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {string} type `redundant`. + * @property {Workbox} target The `Workbox` instance. + */ diff --git a/node_modules/workbox-window/Workbox.js b/node_modules/workbox-window/Workbox.js new file mode 100644 index 0000000000000000000000000000000000000000..06fb687e23a18a6152de9c7d51b19ad055375102 --- /dev/null +++ b/node_modules/workbox-window/Workbox.js @@ -0,0 +1,620 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { Deferred } from 'workbox-core/_private/Deferred.js'; +import { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js'; +import { logger } from 'workbox-core/_private/logger.js'; +import { messageSW } from './messageSW.js'; +import { WorkboxEventTarget } from './utils/WorkboxEventTarget.js'; +import { urlsMatch } from './utils/urlsMatch.js'; +import { WorkboxEvent } from './utils/WorkboxEvent.js'; +import './_version.js'; +// The time a SW must be in the waiting phase before we can conclude +// `skipWaiting()` wasn't called. This 200 amount wasn't scientifically +// chosen, but it seems to avoid false positives in my testing. +const WAITING_TIMEOUT_DURATION = 200; +// The amount of time after a registration that we can reasonably conclude +// that the registration didn't trigger an update. +const REGISTRATION_TIMEOUT_DURATION = 60000; +// The de facto standard message that a service worker should be listening for +// to trigger a call to skipWaiting(). +const SKIP_WAITING_MESSAGE = { type: 'SKIP_WAITING' }; +/** + * A class to aid in handling service worker registration, updates, and + * reacting to service worker lifecycle events. + * + * @fires {@link workbox-window.Workbox#message} + * @fires {@link workbox-window.Workbox#installed} + * @fires {@link workbox-window.Workbox#waiting} + * @fires {@link workbox-window.Workbox#controlling} + * @fires {@link workbox-window.Workbox#activated} + * @fires {@link workbox-window.Workbox#redundant} + * @memberof workbox-window + */ +class Workbox extends WorkboxEventTarget { + /** + * Creates a new Workbox instance with a script URL and service worker + * options. The script URL and options are the same as those used when + * calling [navigator.serviceWorker.register(scriptURL, options)](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register). + * + * @param {string|TrustedScriptURL} scriptURL The service worker script + * associated with this instance. Using a + * [`TrustedScriptURL`](https://web.dev/trusted-types/) is supported. + * @param {Object} [registerOptions] The service worker options associated + * with this instance. + */ + // eslint-disable-next-line @typescript-eslint/ban-types + constructor(scriptURL, registerOptions = {}) { + super(); + this._registerOptions = {}; + this._updateFoundCount = 0; + // Deferreds we can resolve later. + this._swDeferred = new Deferred(); + this._activeDeferred = new Deferred(); + this._controllingDeferred = new Deferred(); + this._registrationTime = 0; + this._ownSWs = new Set(); + /** + * @private + */ + this._onUpdateFound = () => { + // `this._registration` will never be `undefined` after an update is found. + const registration = this._registration; + const installingSW = registration.installing; + // If the script URL passed to `navigator.serviceWorker.register()` is + // different from the current controlling SW's script URL, we know any + // successful registration calls will trigger an `updatefound` event. + // But if the registered script URL is the same as the current controlling + // SW's script URL, we'll only get an `updatefound` event if the file + // changed since it was last registered. This can be a problem if the user + // opens up the same page in a different tab, and that page registers + // a SW that triggers an update. It's a problem because this page has no + // good way of knowing whether the `updatefound` event came from the SW + // script it registered or from a registration attempt made by a newer + // version of the page running in another tab. + // To minimize the possibility of a false positive, we use the logic here: + const updateLikelyTriggeredExternally = + // Since we enforce only calling `register()` once, and since we don't + // add the `updatefound` event listener until the `register()` call, if + // `_updateFoundCount` is > 0 then it means this method has already + // been called, thus this SW must be external + this._updateFoundCount > 0 || + // If the script URL of the installing SW is different from this + // instance's script URL, we know it's definitely not from our + // registration. + !urlsMatch(installingSW.scriptURL, this._scriptURL.toString()) || + // If all of the above are false, then we use a time-based heuristic: + // Any `updatefound` event that occurs long after our registration is + // assumed to be external. + performance.now() > this._registrationTime + REGISTRATION_TIMEOUT_DURATION + ? // If any of the above are not true, we assume the update was + // triggered by this instance. + true + : false; + if (updateLikelyTriggeredExternally) { + this._externalSW = installingSW; + registration.removeEventListener('updatefound', this._onUpdateFound); + } + else { + // If the update was not triggered externally we know the installing + // SW is the one we registered, so we set it. + this._sw = installingSW; + this._ownSWs.add(installingSW); + this._swDeferred.resolve(installingSW); + // The `installing` state isn't something we have a dedicated + // callback for, but we do log messages for it in development. + if (process.env.NODE_ENV !== 'production') { + if (navigator.serviceWorker.controller) { + logger.log('Updated service worker found. Installing now...'); + } + else { + logger.log('Service worker is installing...'); + } + } + } + // Increment the `updatefound` count, so future invocations of this + // method can be sure they were triggered externally. + ++this._updateFoundCount; + // Add a `statechange` listener regardless of whether this update was + // triggered externally, since we have callbacks for both. + installingSW.addEventListener('statechange', this._onStateChange); + }; + /** + * @private + * @param {Event} originalEvent + */ + this._onStateChange = (originalEvent) => { + // `this._registration` will never be `undefined` after an update is found. + const registration = this._registration; + const sw = originalEvent.target; + const { state } = sw; + const isExternal = sw === this._externalSW; + const eventProps = { + sw, + isExternal, + originalEvent, + }; + if (!isExternal && this._isUpdate) { + eventProps.isUpdate = true; + } + this.dispatchEvent(new WorkboxEvent(state, eventProps)); + if (state === 'installed') { + // This timeout is used to ignore cases where the service worker calls + // `skipWaiting()` in the install event, thus moving it directly in the + // activating state. (Since all service workers *must* go through the + // waiting phase, the only way to detect `skipWaiting()` called in the + // install event is to observe that the time spent in the waiting phase + // is very short.) + // NOTE: we don't need separate timeouts for the own and external SWs + // since they can't go through these phases at the same time. + this._waitingTimeout = self.setTimeout(() => { + // Ensure the SW is still waiting (it may now be redundant). + if (state === 'installed' && registration.waiting === sw) { + this.dispatchEvent(new WorkboxEvent('waiting', eventProps)); + if (process.env.NODE_ENV !== 'production') { + if (isExternal) { + logger.warn('An external service worker has installed but is ' + + 'waiting for this client to close before activating...'); + } + else { + logger.warn('The service worker has installed but is waiting ' + + 'for existing clients to close before activating...'); + } + } + } + }, WAITING_TIMEOUT_DURATION); + } + else if (state === 'activating') { + clearTimeout(this._waitingTimeout); + if (!isExternal) { + this._activeDeferred.resolve(sw); + } + } + if (process.env.NODE_ENV !== 'production') { + switch (state) { + case 'installed': + if (isExternal) { + logger.warn('An external service worker has installed. ' + + 'You may want to suggest users reload this page.'); + } + else { + logger.log('Registered service worker installed.'); + } + break; + case 'activated': + if (isExternal) { + logger.warn('An external service worker has activated.'); + } + else { + logger.log('Registered service worker activated.'); + if (sw !== navigator.serviceWorker.controller) { + logger.warn('The registered service worker is active but ' + + 'not yet controlling the page. Reload or run ' + + '`clients.claim()` in the service worker.'); + } + } + break; + case 'redundant': + if (sw === this._compatibleControllingSW) { + logger.log('Previously controlling service worker now redundant!'); + } + else if (!isExternal) { + logger.log('Registered service worker now redundant!'); + } + break; + } + } + }; + /** + * @private + * @param {Event} originalEvent + */ + this._onControllerChange = (originalEvent) => { + const sw = this._sw; + const isExternal = sw !== navigator.serviceWorker.controller; + // Unconditionally dispatch the controlling event, with isExternal set + // to distinguish between controller changes due to the initial registration + // vs. an update-check or other tab's registration. + // See https://github.com/GoogleChrome/workbox/issues/2786 + this.dispatchEvent(new WorkboxEvent('controlling', { + isExternal, + originalEvent, + sw, + isUpdate: this._isUpdate, + })); + if (!isExternal) { + if (process.env.NODE_ENV !== 'production') { + logger.log('Registered service worker now controlling this page.'); + } + this._controllingDeferred.resolve(sw); + } + }; + /** + * @private + * @param {Event} originalEvent + */ + this._onMessage = async (originalEvent) => { + // Can't change type 'any' of data. + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const { data, ports, source } = originalEvent; + // Wait until there's an "own" service worker. This is used to buffer + // `message` events that may be received prior to calling `register()`. + await this.getSW(); + // If the service worker that sent the message is in the list of own + // service workers for this instance, dispatch a `message` event. + // NOTE: we check for all previously owned service workers rather than + // just the current one because some messages (e.g. cache updates) use + // a timeout when sent and may be delayed long enough for a service worker + // update to be found. + if (this._ownSWs.has(source)) { + this.dispatchEvent(new WorkboxEvent('message', { + // Can't change type 'any' of data. + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + data, + originalEvent, + ports, + sw: source, + })); + } + }; + this._scriptURL = scriptURL; + this._registerOptions = registerOptions; + // Add a message listener immediately since messages received during + // page load are buffered only until the DOMContentLoaded event: + // https://github.com/GoogleChrome/workbox/issues/2202 + navigator.serviceWorker.addEventListener('message', this._onMessage); + } + /** + * Registers a service worker for this instances script URL and service + * worker options. By default this method delays registration until after + * the window has loaded. + * + * @param {Object} [options] + * @param {Function} [options.immediate=false] Setting this to true will + * register the service worker immediately, even if the window has + * not loaded (not recommended). + */ + async register({ immediate = false } = {}) { + if (process.env.NODE_ENV !== 'production') { + if (this._registrationTime) { + logger.error('Cannot re-register a Workbox instance after it has ' + + 'been registered. Create a new instance instead.'); + return; + } + } + if (!immediate && document.readyState !== 'complete') { + await new Promise((res) => window.addEventListener('load', res)); + } + // Set this flag to true if any service worker was controlling the page + // at registration time. + this._isUpdate = Boolean(navigator.serviceWorker.controller); + // Before registering, attempt to determine if a SW is already controlling + // the page, and if that SW script (and version, if specified) matches this + // instance's script. + this._compatibleControllingSW = this._getControllingSWIfCompatible(); + this._registration = await this._registerScript(); + // If we have a compatible controller, store the controller as the "own" + // SW, resolve active/controlling deferreds and add necessary listeners. + if (this._compatibleControllingSW) { + this._sw = this._compatibleControllingSW; + this._activeDeferred.resolve(this._compatibleControllingSW); + this._controllingDeferred.resolve(this._compatibleControllingSW); + this._compatibleControllingSW.addEventListener('statechange', this._onStateChange, { once: true }); + } + // If there's a waiting service worker with a matching URL before the + // `updatefound` event fires, it likely means that this site is open + // in another tab, or the user refreshed the page (and thus the previous + // page wasn't fully unloaded before this page started loading). + // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting + const waitingSW = this._registration.waiting; + if (waitingSW && + urlsMatch(waitingSW.scriptURL, this._scriptURL.toString())) { + // Store the waiting SW as the "own" Sw, even if it means overwriting + // a compatible controller. + this._sw = waitingSW; + // Run this in the next microtask, so any code that adds an event + // listener after awaiting `register()` will get this event. + dontWaitFor(Promise.resolve().then(() => { + this.dispatchEvent(new WorkboxEvent('waiting', { + sw: waitingSW, + wasWaitingBeforeRegister: true, + })); + if (process.env.NODE_ENV !== 'production') { + logger.warn('A service worker was already waiting to activate ' + + 'before this script was registered...'); + } + })); + } + // If an "own" SW is already set, resolve the deferred. + if (this._sw) { + this._swDeferred.resolve(this._sw); + this._ownSWs.add(this._sw); + } + if (process.env.NODE_ENV !== 'production') { + logger.log('Successfully registered service worker.', this._scriptURL.toString()); + if (navigator.serviceWorker.controller) { + if (this._compatibleControllingSW) { + logger.debug('A service worker with the same script URL ' + + 'is already controlling this page.'); + } + else { + logger.debug('A service worker with a different script URL is ' + + 'currently controlling the page. The browser is now fetching ' + + 'the new script now...'); + } + } + const currentPageIsOutOfScope = () => { + const scopeURL = new URL(this._registerOptions.scope || this._scriptURL.toString(), document.baseURI); + const scopeURLBasePath = new URL('./', scopeURL.href).pathname; + return !location.pathname.startsWith(scopeURLBasePath); + }; + if (currentPageIsOutOfScope()) { + logger.warn('The current page is not in scope for the registered ' + + 'service worker. Was this a mistake?'); + } + } + this._registration.addEventListener('updatefound', this._onUpdateFound); + navigator.serviceWorker.addEventListener('controllerchange', this._onControllerChange); + return this._registration; + } + /** + * Checks for updates of the registered service worker. + */ + async update() { + if (!this._registration) { + if (process.env.NODE_ENV !== 'production') { + logger.error('Cannot update a Workbox instance without ' + + 'being registered. Register the Workbox instance first.'); + } + return; + } + // Try to update registration + await this._registration.update(); + } + /** + * Resolves to the service worker registered by this instance as soon as it + * is active. If a service worker was already controlling at registration + * time then it will resolve to that if the script URLs (and optionally + * script versions) match, otherwise it will wait until an update is found + * and activates. + * + * @return {Promise} + */ + get active() { + return this._activeDeferred.promise; + } + /** + * Resolves to the service worker registered by this instance as soon as it + * is controlling the page. If a service worker was already controlling at + * registration time then it will resolve to that if the script URLs (and + * optionally script versions) match, otherwise it will wait until an update + * is found and starts controlling the page. + * Note: the first time a service worker is installed it will active but + * not start controlling the page unless `clients.claim()` is called in the + * service worker. + * + * @return {Promise} + */ + get controlling() { + return this._controllingDeferred.promise; + } + /** + * Resolves with a reference to a service worker that matches the script URL + * of this instance, as soon as it's available. + * + * If, at registration time, there's already an active or waiting service + * worker with a matching script URL, it will be used (with the waiting + * service worker taking precedence over the active service worker if both + * match, since the waiting service worker would have been registered more + * recently). + * If there's no matching active or waiting service worker at registration + * time then the promise will not resolve until an update is found and starts + * installing, at which point the installing service worker is used. + * + * @return {Promise} + */ + getSW() { + // If `this._sw` is set, resolve with that as we want `getSW()` to + // return the correct (new) service worker if an update is found. + return this._sw !== undefined + ? Promise.resolve(this._sw) + : this._swDeferred.promise; + } + /** + * Sends the passed data object to the service worker registered by this + * instance (via {@link workbox-window.Workbox#getSW}) and resolves + * with a response (if any). + * + * A response can be set in a message handler in the service worker by + * calling `event.ports[0].postMessage(...)`, which will resolve the promise + * returned by `messageSW()`. If no response is set, the promise will never + * resolve. + * + * @param {Object} data An object to send to the service worker + * @return {Promise} + */ + // We might be able to change the 'data' type to Record in the future. + // eslint-disable-next-line @typescript-eslint/ban-types + async messageSW(data) { + const sw = await this.getSW(); + return messageSW(sw, data); + } + /** + * Sends a `{type: 'SKIP_WAITING'}` message to the service worker that's + * currently in the `waiting` state associated with the current registration. + * + * If there is no current registration or no service worker is `waiting`, + * calling this will have no effect. + */ + messageSkipWaiting() { + if (this._registration && this._registration.waiting) { + void messageSW(this._registration.waiting, SKIP_WAITING_MESSAGE); + } + } + /** + * Checks for a service worker already controlling the page and returns + * it if its script URL matches. + * + * @private + * @return {ServiceWorker|undefined} + */ + _getControllingSWIfCompatible() { + const controller = navigator.serviceWorker.controller; + if (controller && + urlsMatch(controller.scriptURL, this._scriptURL.toString())) { + return controller; + } + else { + return undefined; + } + } + /** + * Registers a service worker for this instances script URL and register + * options and tracks the time registration was complete. + * + * @private + */ + async _registerScript() { + try { + // this._scriptURL may be a TrustedScriptURL, but there's no support for + // passing that to register() in lib.dom right now. + // https://github.com/GoogleChrome/workbox/issues/2855 + const reg = await navigator.serviceWorker.register(this._scriptURL, this._registerOptions); + // Keep track of when registration happened, so it can be used in the + // `this._onUpdateFound` heuristic. Also use the presence of this + // property as a way to see if `.register()` has been called. + this._registrationTime = performance.now(); + return reg; + } + catch (error) { + if (process.env.NODE_ENV !== 'production') { + logger.error(error); + } + // Re-throw the error. + throw error; + } + } +} +export { Workbox }; +// The jsdoc comments below outline the events this instance may dispatch: +// ----------------------------------------------------------------------- +/** + * The `message` event is dispatched any time a `postMessage` is received. + * + * @event workbox-window.Workbox#message + * @type {WorkboxEvent} + * @property {*} data The `data` property from the original `message` event. + * @property {Event} originalEvent The original [`message`]{@link https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent} + * event. + * @property {string} type `message`. + * @property {MessagePort[]} ports The `ports` value from `originalEvent`. + * @property {Workbox} target The `Workbox` instance. + */ +/** + * The `installed` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker} + * changes to `installed`. + * + * Then can happen either the very first time a service worker is installed, + * or after an update to the current service worker is found. In the case + * of an update being found, the event's `isUpdate` property will be `true`. + * + * @event workbox-window.Workbox#installed + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {string} type `installed`. + * @property {Workbox} target The `Workbox` instance. + */ +/** + * The `waiting` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw} + * changes to `installed` and then doesn't immediately change to `activating`. + * It may also be dispatched if a service worker with the same + * [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL} + * was already waiting when the {@link workbox-window.Workbox#register} + * method was called. + * + * @event workbox-window.Workbox#waiting + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event|undefined} originalEvent The original + * [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event, or `undefined` in the case where the service worker was waiting + * to before `.register()` was called. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {boolean|undefined} wasWaitingBeforeRegister True if a service worker with + * a matching `scriptURL` was already waiting when this `Workbox` + * instance called `register()`. + * @property {string} type `waiting`. + * @property {Workbox} target The `Workbox` instance. + */ +/** + * The `controlling` event is dispatched if a + * [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange} + * fires on the service worker [container]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer} + * and the [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL} + * of the new [controller]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller} + * matches the `scriptURL` of the `Workbox` instance's + * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}. + * + * @event workbox-window.Workbox#controlling + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this service worker was registered. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {string} type `controlling`. + * @property {Workbox} target The `Workbox` instance. + */ +/** + * The `activated` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker} + * changes to `activated`. + * + * @event workbox-window.Workbox#activated + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {string} type `activated`. + * @property {Workbox} target The `Workbox` instance. + */ +/** + * The `redundant` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw} + * changes to `redundant`. + * + * @event workbox-window.Workbox#redundant + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {string} type `redundant`. + * @property {Workbox} target The `Workbox` instance. + */ diff --git a/node_modules/workbox-window/Workbox.mjs b/node_modules/workbox-window/Workbox.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ef3b8aab206f211cec2cd99903f950b79cd2b8af --- /dev/null +++ b/node_modules/workbox-window/Workbox.mjs @@ -0,0 +1 @@ +export * from './Workbox.js'; \ No newline at end of file diff --git a/node_modules/workbox-window/_version.d.ts b/node_modules/workbox-window/_version.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/workbox-window/_version.js b/node_modules/workbox-window/_version.js new file mode 100644 index 0000000000000000000000000000000000000000..3848955433d6c27c04b6eca6d250009f4741b4be --- /dev/null +++ b/node_modules/workbox-window/_version.js @@ -0,0 +1,6 @@ +"use strict"; +// @ts-ignore +try { + self['workbox:window:7.4.0'] && _(); +} +catch (e) { } diff --git a/node_modules/workbox-window/_version.mjs b/node_modules/workbox-window/_version.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9b182773b30454171477120e237db366f1775ca8 --- /dev/null +++ b/node_modules/workbox-window/_version.mjs @@ -0,0 +1 @@ +try{self['workbox:window:7.4.1']&&_()}catch(e){}// eslint-disable-line \ No newline at end of file diff --git a/node_modules/workbox-window/build/workbox-window.dev.es5.mjs b/node_modules/workbox-window/build/workbox-window.dev.es5.mjs new file mode 100644 index 0000000000000000000000000000000000000000..eba949dfe499392e0994e5d6e6ec9fb3c9b41b0b --- /dev/null +++ b/node_modules/workbox-window/build/workbox-window.dev.es5.mjs @@ -0,0 +1,997 @@ +// @ts-ignore +try { + self['workbox:window:7.4.0'] && _(); +} catch (e) {} + +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +/** + * Sends a data object to a service worker via `postMessage` and resolves with + * a response (if any). + * + * A response can be set in a message handler in the service worker by + * calling `event.ports[0].postMessage(...)`, which will resolve the promise + * returned by `messageSW()`. If no response is set, the promise will not + * resolve. + * + * @param {ServiceWorker} sw The service worker to send the message to. + * @param {Object} data An object to send to the service worker. + * @return {Promise} + * @memberof workbox-window + */ +// Better not change type of data. +// eslint-disable-next-line @typescript-eslint/ban-types +function messageSW(sw, data) { + return new Promise(function (resolve) { + var messageChannel = new MessageChannel(); + messageChannel.port1.onmessage = function (event) { + resolve(event.data); + }; + sw.postMessage(data, [messageChannel.port2]); + }); +} + +function _arrayLikeToArray(r, a) { + (null == a || a > r.length) && (a = r.length); + for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; + return n; +} +function _defineProperties(e, r) { + for (var t = 0; t < r.length; t++) { + var o = r[t]; + o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); + } +} +function _createClass(e, r, t) { + return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { + writable: false + }), e; +} +function _createForOfIteratorHelperLoose(r, e) { + var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; + if (t) return (t = t.call(r)).next.bind(t); + if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) { + t && (r = t); + var o = 0; + return function () { + return o >= r.length ? { + done: true + } : { + done: false, + value: r[o++] + }; + }; + } + throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} +function _inheritsLoose(t, o) { + t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); +} +function _setPrototypeOf(t, e) { + return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { + return t.__proto__ = e, t; + }, _setPrototypeOf(t, e); +} +function _toPrimitive(t, r) { + if ("object" != typeof t || !t) return t; + var e = t[Symbol.toPrimitive]; + if (void 0 !== e) { + var i = e.call(t, r); + if ("object" != typeof i) return i; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (String )(t); +} +function _toPropertyKey(t) { + var i = _toPrimitive(t, "string"); + return "symbol" == typeof i ? i : i + ""; +} +function _unsupportedIterableToArray(r, a) { + if (r) { + if ("string" == typeof r) return _arrayLikeToArray(r, a); + var t = {}.toString.call(r).slice(8, -1); + return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; + } +} + +// @ts-ignore +try { + self['workbox:core:7.4.0'] && _(); +} catch (e) {} + +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +/** + * The Deferred class composes Promises in a way that allows for them to be + * resolved or rejected from outside the constructor. In most cases promises + * should be used directly, but Deferreds can be necessary when the logic to + * resolve a promise must be separate. + * + * @private + */ +var Deferred = +/** + * Creates a promise and exposes its resolve and reject functions as methods. + */ +function Deferred() { + var _this = this; + this.promise = new Promise(function (resolve, reject) { + _this.resolve = resolve; + _this.reject = reject; + }); +}; + +/* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +/** + * A helper function that prevents a promise from being flagged as unused. + * + * @private + **/ +function dontWaitFor(promise) { + // Effective no-op. + void promise.then(function () {}); +} + +/* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +var logger = function () { + // Don't overwrite this value if it's already set. + // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923 + if (!('__WB_DISABLE_DEV_LOGS' in globalThis)) { + self.__WB_DISABLE_DEV_LOGS = false; + } + var inGroup = false; + var methodToColorMap = { + debug: "#7f8c8d", + log: "#2ecc71", + warn: "#f39c12", + error: "#c0392b", + groupCollapsed: "#3498db", + groupEnd: null // No colored prefix on groupEnd + }; + var print = function print(method, args) { + var _console2; + if (self.__WB_DISABLE_DEV_LOGS) { + return; + } + if (method === 'groupCollapsed') { + // Safari doesn't print all console.groupCollapsed() arguments: + // https://bugs.webkit.org/show_bug.cgi?id=182754 + if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) { + var _console; + (_console = console)[method].apply(_console, args); + return; + } + } + var 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. + var logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')]; + (_console2 = console)[method].apply(_console2, logPrefix.concat(args)); + if (method === 'groupCollapsed') { + inGroup = true; + } + if (method === 'groupEnd') { + inGroup = false; + } + }; + // eslint-disable-next-line @typescript-eslint/ban-types + var api = {}; + var loggerMethods = Object.keys(methodToColorMap); + var _loop = function _loop() { + var key = _loggerMethods[_i]; + var method = key; + api[method] = function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + print(method, args); + }; + }; + for (var _i = 0, _loggerMethods = loggerMethods; _i < _loggerMethods.length; _i++) { + _loop(); + } + return api; +}(); + +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +/** + * A minimal `EventTarget` shim. + * This is necessary because not all browsers support constructable + * `EventTarget`, so using a real `EventTarget` will error. + * @private + */ +var WorkboxEventTarget = /*#__PURE__*/function () { + function WorkboxEventTarget() { + this._eventListenerRegistry = new Map(); + } + /** + * @param {string} type + * @param {Function} listener + * @private + */ + var _proto = WorkboxEventTarget.prototype; + _proto.addEventListener = function addEventListener(type, listener) { + var foo = this._getEventListenersByType(type); + foo.add(listener); + } + /** + * @param {string} type + * @param {Function} listener + * @private + */; + _proto.removeEventListener = function removeEventListener(type, listener) { + this._getEventListenersByType(type).delete(listener); + } + /** + * @param {Object} event + * @private + */; + _proto.dispatchEvent = function dispatchEvent(event) { + event.target = this; + var listeners = this._getEventListenersByType(event.type); + for (var _iterator = _createForOfIteratorHelperLoose(listeners), _step; !(_step = _iterator()).done;) { + var listener = _step.value; + listener(event); + } + } + /** + * Returns a Set of listeners associated with the passed event type. + * If no handlers have been registered, an empty Set is returned. + * + * @param {string} type The event type. + * @return {Set} An array of handler functions. + * @private + */; + _proto._getEventListenersByType = function _getEventListenersByType(type) { + if (!this._eventListenerRegistry.has(type)) { + this._eventListenerRegistry.set(type, new Set()); + } + return this._eventListenerRegistry.get(type); + }; + return WorkboxEventTarget; +}(); + +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +/** + * Returns true if two URLs have the same `.href` property. The URLS can be + * relative, and if they are the current location href is used to resolve URLs. + * + * @private + * @param {string} url1 + * @param {string} url2 + * @return {boolean} + */ +function urlsMatch(url1, url2) { + var _location = location, + href = _location.href; + return new URL(url1, href).href === new URL(url2, href).href; +} + +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +/** + * A minimal `Event` subclass shim. + * This doesn't *actually* subclass `Event` because not all browsers support + * constructable `EventTarget`, and using a real `Event` will error. + * @private + */ +var WorkboxEvent = function WorkboxEvent(type, props) { + this.type = type; + Object.assign(this, props); +}; + +// The time a SW must be in the waiting phase before we can conclude +// `skipWaiting()` wasn't called. This 200 amount wasn't scientifically +// chosen, but it seems to avoid false positives in my testing. + +function _await(value, then, direct) { + if (!value || !value.then) { + value = Promise.resolve(value); + } + return then ? value.then(then) : value; +} +var WAITING_TIMEOUT_DURATION = 200; +// The amount of time after a registration that we can reasonably conclude +// that the registration didn't trigger an update. + +function _async(f) { + return function () { + for (var args = [], i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; + } + try { + return Promise.resolve(f.apply(this, args)); + } catch (e) { + return Promise.reject(e); + } + }; +} +var REGISTRATION_TIMEOUT_DURATION = 60000; +// The de facto standard message that a service worker should be listening for +// to trigger a call to skipWaiting(). + +function _empty() {} +var SKIP_WAITING_MESSAGE = { + type: 'SKIP_WAITING' +}; +/** + * A class to aid in handling service worker registration, updates, and + * reacting to service worker lifecycle events. + * + * @fires {@link workbox-window.Workbox#message} + * @fires {@link workbox-window.Workbox#installed} + * @fires {@link workbox-window.Workbox#waiting} + * @fires {@link workbox-window.Workbox#controlling} + * @fires {@link workbox-window.Workbox#activated} + * @fires {@link workbox-window.Workbox#redundant} + * @memberof workbox-window + */ + +function _awaitIgnored(value, direct) { + { + return value && value.then ? value.then(_empty) : Promise.resolve(); + } +} +var Workbox = /*#__PURE__*/function (_WorkboxEventTarget) { + /** + * Creates a new Workbox instance with a script URL and service worker + * options. The script URL and options are the same as those used when + * calling [navigator.serviceWorker.register(scriptURL, options)](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register). + * + * @param {string|TrustedScriptURL} scriptURL The service worker script + * associated with this instance. Using a + * [`TrustedScriptURL`](https://web.dev/trusted-types/) is supported. + * @param {Object} [registerOptions] The service worker options associated + * with this instance. + */ + // eslint-disable-next-line @typescript-eslint/ban-types + function Workbox(scriptURL, registerOptions) { + var _this; + if (registerOptions === void 0) { + registerOptions = {}; + } + _this = _WorkboxEventTarget.call(this) || this; + _this._registerOptions = {}; + _this._updateFoundCount = 0; + // Deferreds we can resolve later. + _this._swDeferred = new Deferred(); + _this._activeDeferred = new Deferred(); + _this._controllingDeferred = new Deferred(); + _this._registrationTime = 0; + _this._ownSWs = new Set(); + /** + * @private + */ + _this._onUpdateFound = function () { + // `this._registration` will never be `undefined` after an update is found. + var registration = _this._registration; + var installingSW = registration.installing; + // If the script URL passed to `navigator.serviceWorker.register()` is + // different from the current controlling SW's script URL, we know any + // successful registration calls will trigger an `updatefound` event. + // But if the registered script URL is the same as the current controlling + // SW's script URL, we'll only get an `updatefound` event if the file + // changed since it was last registered. This can be a problem if the user + // opens up the same page in a different tab, and that page registers + // a SW that triggers an update. It's a problem because this page has no + // good way of knowing whether the `updatefound` event came from the SW + // script it registered or from a registration attempt made by a newer + // version of the page running in another tab. + // To minimize the possibility of a false positive, we use the logic here: + var updateLikelyTriggeredExternally = + // Since we enforce only calling `register()` once, and since we don't + // add the `updatefound` event listener until the `register()` call, if + // `_updateFoundCount` is > 0 then it means this method has already + // been called, thus this SW must be external + _this._updateFoundCount > 0 || + // If the script URL of the installing SW is different from this + // instance's script URL, we know it's definitely not from our + // registration. + !urlsMatch(installingSW.scriptURL, _this._scriptURL.toString()) || + // If all of the above are false, then we use a time-based heuristic: + // Any `updatefound` event that occurs long after our registration is + // assumed to be external. + performance.now() > _this._registrationTime + REGISTRATION_TIMEOUT_DURATION ? + // If any of the above are not true, we assume the update was + // triggered by this instance. + true : false; + if (updateLikelyTriggeredExternally) { + _this._externalSW = installingSW; + registration.removeEventListener('updatefound', _this._onUpdateFound); + } else { + // If the update was not triggered externally we know the installing + // SW is the one we registered, so we set it. + _this._sw = installingSW; + _this._ownSWs.add(installingSW); + _this._swDeferred.resolve(installingSW); + // The `installing` state isn't something we have a dedicated + // callback for, but we do log messages for it in development. + { + if (navigator.serviceWorker.controller) { + logger.log('Updated service worker found. Installing now...'); + } else { + logger.log('Service worker is installing...'); + } + } + } + // Increment the `updatefound` count, so future invocations of this + // method can be sure they were triggered externally. + ++_this._updateFoundCount; + // Add a `statechange` listener regardless of whether this update was + // triggered externally, since we have callbacks for both. + installingSW.addEventListener('statechange', _this._onStateChange); + }; + /** + * @private + * @param {Event} originalEvent + */ + _this._onStateChange = function (originalEvent) { + // `this._registration` will never be `undefined` after an update is found. + var registration = _this._registration; + var sw = originalEvent.target; + var state = sw.state; + var isExternal = sw === _this._externalSW; + var eventProps = { + sw: sw, + isExternal: isExternal, + originalEvent: originalEvent + }; + if (!isExternal && _this._isUpdate) { + eventProps.isUpdate = true; + } + _this.dispatchEvent(new WorkboxEvent(state, eventProps)); + if (state === 'installed') { + // This timeout is used to ignore cases where the service worker calls + // `skipWaiting()` in the install event, thus moving it directly in the + // activating state. (Since all service workers *must* go through the + // waiting phase, the only way to detect `skipWaiting()` called in the + // install event is to observe that the time spent in the waiting phase + // is very short.) + // NOTE: we don't need separate timeouts for the own and external SWs + // since they can't go through these phases at the same time. + _this._waitingTimeout = self.setTimeout(function () { + // Ensure the SW is still waiting (it may now be redundant). + if (state === 'installed' && registration.waiting === sw) { + _this.dispatchEvent(new WorkboxEvent('waiting', eventProps)); + { + if (isExternal) { + logger.warn('An external service worker has installed but is ' + 'waiting for this client to close before activating...'); + } else { + logger.warn('The service worker has installed but is waiting ' + 'for existing clients to close before activating...'); + } + } + } + }, WAITING_TIMEOUT_DURATION); + } else if (state === 'activating') { + clearTimeout(_this._waitingTimeout); + if (!isExternal) { + _this._activeDeferred.resolve(sw); + } + } + { + switch (state) { + case 'installed': + if (isExternal) { + logger.warn('An external service worker has installed. ' + 'You may want to suggest users reload this page.'); + } else { + logger.log('Registered service worker installed.'); + } + break; + case 'activated': + if (isExternal) { + logger.warn('An external service worker has activated.'); + } else { + logger.log('Registered service worker activated.'); + if (sw !== navigator.serviceWorker.controller) { + logger.warn('The registered service worker is active but ' + 'not yet controlling the page. Reload or run ' + '`clients.claim()` in the service worker.'); + } + } + break; + case 'redundant': + if (sw === _this._compatibleControllingSW) { + logger.log('Previously controlling service worker now redundant!'); + } else if (!isExternal) { + logger.log('Registered service worker now redundant!'); + } + break; + } + } + }; + /** + * @private + * @param {Event} originalEvent + */ + _this._onControllerChange = function (originalEvent) { + var sw = _this._sw; + var isExternal = sw !== navigator.serviceWorker.controller; + // Unconditionally dispatch the controlling event, with isExternal set + // to distinguish between controller changes due to the initial registration + // vs. an update-check or other tab's registration. + // See https://github.com/GoogleChrome/workbox/issues/2786 + _this.dispatchEvent(new WorkboxEvent('controlling', { + isExternal: isExternal, + originalEvent: originalEvent, + sw: sw, + isUpdate: _this._isUpdate + })); + if (!isExternal) { + { + logger.log('Registered service worker now controlling this page.'); + } + _this._controllingDeferred.resolve(sw); + } + }; + /** + * @private + * @param {Event} originalEvent + */ + _this._onMessage = _async(function (originalEvent) { + // Can't change type 'any' of data. + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + var data = originalEvent.data, + ports = originalEvent.ports, + source = originalEvent.source; + // Wait until there's an "own" service worker. This is used to buffer + // `message` events that may be received prior to calling `register()`. + return _await(_this.getSW(), function () { + if (_this._ownSWs.has(source)) { + _this.dispatchEvent(new WorkboxEvent('message', { + // Can't change type 'any' of data. + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + data: data, + originalEvent: originalEvent, + ports: ports, + sw: source + })); + } + }); // If the service worker that sent the message is in the list of own + // service workers for this instance, dispatch a `message` event. + // NOTE: we check for all previously owned service workers rather than + // just the current one because some messages (e.g. cache updates) use + // a timeout when sent and may be delayed long enough for a service worker + // update to be found. + }); + _this._scriptURL = scriptURL; + _this._registerOptions = registerOptions; + // Add a message listener immediately since messages received during + // page load are buffered only until the DOMContentLoaded event: + // https://github.com/GoogleChrome/workbox/issues/2202 + navigator.serviceWorker.addEventListener('message', _this._onMessage); + return _this; + } + /** + * Registers a service worker for this instances script URL and service + * worker options. By default this method delays registration until after + * the window has loaded. + * + * @param {Object} [options] + * @param {Function} [options.immediate=false] Setting this to true will + * register the service worker immediately, even if the window has + * not loaded (not recommended). + */ + _inheritsLoose(Workbox, _WorkboxEventTarget); + var _proto = Workbox.prototype; + _proto.register = function register(_temp) { + var _ref = _temp === void 0 ? {} : _temp, + _ref$immediate = _ref.immediate, + immediate = _ref$immediate === void 0 ? false : _ref$immediate; + try { + var _this2 = this; + if ("dev" !== 'production') { + if (_this2._registrationTime) { + logger.error('Cannot re-register a Workbox instance after it has ' + 'been registered. Create a new instance instead.'); + return _await(); + } + } + return _await(_invoke(function () { + if (!immediate && document.readyState !== 'complete') { + return _awaitIgnored(new Promise(function (res) { + return window.addEventListener('load', res); + })); + } + }, function () { + // Set this flag to true if any service worker was controlling the page + // at registration time. + _this2._isUpdate = Boolean(navigator.serviceWorker.controller); + // Before registering, attempt to determine if a SW is already controlling + // the page, and if that SW script (and version, if specified) matches this + // instance's script. + _this2._compatibleControllingSW = _this2._getControllingSWIfCompatible(); + return _await(_this2._registerScript(), function (_this2$_registerScrip) { + _this2._registration = _this2$_registerScrip; + // If we have a compatible controller, store the controller as the "own" + // SW, resolve active/controlling deferreds and add necessary listeners. + if (_this2._compatibleControllingSW) { + _this2._sw = _this2._compatibleControllingSW; + _this2._activeDeferred.resolve(_this2._compatibleControllingSW); + _this2._controllingDeferred.resolve(_this2._compatibleControllingSW); + _this2._compatibleControllingSW.addEventListener('statechange', _this2._onStateChange, { + once: true + }); + } + // If there's a waiting service worker with a matching URL before the + // `updatefound` event fires, it likely means that this site is open + // in another tab, or the user refreshed the page (and thus the previous + // page wasn't fully unloaded before this page started loading). + // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting + var waitingSW = _this2._registration.waiting; + if (waitingSW && urlsMatch(waitingSW.scriptURL, _this2._scriptURL.toString())) { + // Store the waiting SW as the "own" Sw, even if it means overwriting + // a compatible controller. + _this2._sw = waitingSW; + // Run this in the next microtask, so any code that adds an event + // listener after awaiting `register()` will get this event. + dontWaitFor(Promise.resolve().then(function () { + _this2.dispatchEvent(new WorkboxEvent('waiting', { + sw: waitingSW, + wasWaitingBeforeRegister: true + })); + if ("dev" !== 'production') { + logger.warn('A service worker was already waiting to activate ' + 'before this script was registered...'); + } + })); + } + // If an "own" SW is already set, resolve the deferred. + if (_this2._sw) { + _this2._swDeferred.resolve(_this2._sw); + _this2._ownSWs.add(_this2._sw); + } + if ("dev" !== 'production') { + logger.log('Successfully registered service worker.', _this2._scriptURL.toString()); + if (navigator.serviceWorker.controller) { + if (_this2._compatibleControllingSW) { + logger.debug('A service worker with the same script URL ' + 'is already controlling this page.'); + } else { + logger.debug('A service worker with a different script URL is ' + 'currently controlling the page. The browser is now fetching ' + 'the new script now...'); + } + } + var currentPageIsOutOfScope = function currentPageIsOutOfScope() { + var scopeURL = new URL(_this2._registerOptions.scope || _this2._scriptURL.toString(), document.baseURI); + var scopeURLBasePath = new URL('./', scopeURL.href).pathname; + return !location.pathname.startsWith(scopeURLBasePath); + }; + if (currentPageIsOutOfScope()) { + logger.warn('The current page is not in scope for the registered ' + 'service worker. Was this a mistake?'); + } + } + _this2._registration.addEventListener('updatefound', _this2._onUpdateFound); + navigator.serviceWorker.addEventListener('controllerchange', _this2._onControllerChange); + return _this2._registration; + }); + })); + } catch (e) { + return Promise.reject(e); + } + } + /** + * Checks for updates of the registered service worker. + */ + ; + _proto.update = function update() { + try { + var _this3 = this; + if (!_this3._registration) { + if ("dev" !== 'production') { + logger.error('Cannot update a Workbox instance without ' + 'being registered. Register the Workbox instance first.'); + } + return _await(); + } + // Try to update registration + return _await(_awaitIgnored(_this3._registration.update())); + } catch (e) { + return Promise.reject(e); + } + } + /** + * Resolves to the service worker registered by this instance as soon as it + * is active. If a service worker was already controlling at registration + * time then it will resolve to that if the script URLs (and optionally + * script versions) match, otherwise it will wait until an update is found + * and activates. + * + * @return {Promise} + */ + ; + /** + * Resolves with a reference to a service worker that matches the script URL + * of this instance, as soon as it's available. + * + * If, at registration time, there's already an active or waiting service + * worker with a matching script URL, it will be used (with the waiting + * service worker taking precedence over the active service worker if both + * match, since the waiting service worker would have been registered more + * recently). + * If there's no matching active or waiting service worker at registration + * time then the promise will not resolve until an update is found and starts + * installing, at which point the installing service worker is used. + * + * @return {Promise} + */ + _proto.getSW = function getSW() { + // If `this._sw` is set, resolve with that as we want `getSW()` to + // return the correct (new) service worker if an update is found. + return this._sw !== undefined ? Promise.resolve(this._sw) : this._swDeferred.promise; + } + /** + * Sends the passed data object to the service worker registered by this + * instance (via {@link workbox-window.Workbox#getSW}) and resolves + * with a response (if any). + * + * A response can be set in a message handler in the service worker by + * calling `event.ports[0].postMessage(...)`, which will resolve the promise + * returned by `messageSW()`. If no response is set, the promise will never + * resolve. + * + * @param {Object} data An object to send to the service worker + * @return {Promise} + */ + // We might be able to change the 'data' type to Record in the future. + // eslint-disable-next-line @typescript-eslint/ban-types + ; + _proto.messageSW = function messageSW$1(data) { + try { + var _this4 = this; + return _await(_this4.getSW(), function (sw) { + return messageSW(sw, data); + }); + } catch (e) { + return Promise.reject(e); + } + } + /** + * Sends a `{type: 'SKIP_WAITING'}` message to the service worker that's + * currently in the `waiting` state associated with the current registration. + * + * If there is no current registration or no service worker is `waiting`, + * calling this will have no effect. + */ + ; + _proto.messageSkipWaiting = function messageSkipWaiting() { + if (this._registration && this._registration.waiting) { + void messageSW(this._registration.waiting, SKIP_WAITING_MESSAGE); + } + } + /** + * Checks for a service worker already controlling the page and returns + * it if its script URL matches. + * + * @private + * @return {ServiceWorker|undefined} + */; + _proto._getControllingSWIfCompatible = function _getControllingSWIfCompatible() { + var controller = navigator.serviceWorker.controller; + if (controller && urlsMatch(controller.scriptURL, this._scriptURL.toString())) { + return controller; + } else { + return undefined; + } + } + /** + * Registers a service worker for this instances script URL and register + * options and tracks the time registration was complete. + * + * @private + */; + _proto._registerScript = function _registerScript() { + try { + var _this5 = this; + return _await(_catch(function () { + // this._scriptURL may be a TrustedScriptURL, but there's no support for + // passing that to register() in lib.dom right now. + // https://github.com/GoogleChrome/workbox/issues/2855 + return _await(navigator.serviceWorker.register(_this5._scriptURL, _this5._registerOptions), function (reg) { + // Keep track of when registration happened, so it can be used in the + // `this._onUpdateFound` heuristic. Also use the presence of this + // property as a way to see if `.register()` has been called. + _this5._registrationTime = performance.now(); + return reg; + }); + }, function (error) { + if ("dev" !== 'production') { + logger.error(error); + } + // Re-throw the error. + throw error; + })); + } catch (e) { + return Promise.reject(e); + } + }; + return _createClass(Workbox, [{ + key: "active", + get: function get() { + return this._activeDeferred.promise; + } + /** + * Resolves to the service worker registered by this instance as soon as it + * is controlling the page. If a service worker was already controlling at + * registration time then it will resolve to that if the script URLs (and + * optionally script versions) match, otherwise it will wait until an update + * is found and starts controlling the page. + * Note: the first time a service worker is installed it will active but + * not start controlling the page unless `clients.claim()` is called in the + * service worker. + * + * @return {Promise} + */ + }, { + key: "controlling", + get: function get() { + return this._controllingDeferred.promise; + } + }]); +}(WorkboxEventTarget); +function _invoke(body, then) { + var result = body(); + if (result && result.then) { + return result.then(then); + } + return then(result); +} // The jsdoc comments below outline the events this instance may dispatch: +// ----------------------------------------------------------------------- +/** + * The `message` event is dispatched any time a `postMessage` is received. + * + * @event workbox-window.Workbox#message + * @type {WorkboxEvent} + * @property {*} data The `data` property from the original `message` event. + * @property {Event} originalEvent The original [`message`]{@link https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent} + * event. + * @property {string} type `message`. + * @property {MessagePort[]} ports The `ports` value from `originalEvent`. + * @property {Workbox} target The `Workbox` instance. + */ +/** + * The `installed` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker} + * changes to `installed`. + * + * Then can happen either the very first time a service worker is installed, + * or after an update to the current service worker is found. In the case + * of an update being found, the event's `isUpdate` property will be `true`. + * + * @event workbox-window.Workbox#installed + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {string} type `installed`. + * @property {Workbox} target The `Workbox` instance. + */ +/** + * The `waiting` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw} + * changes to `installed` and then doesn't immediately change to `activating`. + * It may also be dispatched if a service worker with the same + * [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL} + * was already waiting when the {@link workbox-window.Workbox#register} + * method was called. + * + * @event workbox-window.Workbox#waiting + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event|undefined} originalEvent The original + * [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event, or `undefined` in the case where the service worker was waiting + * to before `.register()` was called. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {boolean|undefined} wasWaitingBeforeRegister True if a service worker with + * a matching `scriptURL` was already waiting when this `Workbox` + * instance called `register()`. + * @property {string} type `waiting`. + * @property {Workbox} target The `Workbox` instance. + */ +/** + * The `controlling` event is dispatched if a + * [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange} + * fires on the service worker [container]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer} + * and the [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL} + * of the new [controller]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller} + * matches the `scriptURL` of the `Workbox` instance's + * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}. + * + * @event workbox-window.Workbox#controlling + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this service worker was registered. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {string} type `controlling`. + * @property {Workbox} target The `Workbox` instance. + */ +/** + * The `activated` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker} + * changes to `activated`. + * + * @event workbox-window.Workbox#activated + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {string} type `activated`. + * @property {Workbox} target The `Workbox` instance. + */ +/** + * The `redundant` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw} + * changes to `redundant`. + * + * @event workbox-window.Workbox#redundant + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {string} type `redundant`. + * @property {Workbox} target The `Workbox` instance. + */ +function _catch(body, recover) { + try { + var result = body(); + } catch (e) { + return recover(e); + } + if (result && result.then) { + return result.then(void 0, recover); + } + return result; +} + +export { Workbox, WorkboxEvent, messageSW }; +//# sourceMappingURL=workbox-window.dev.es5.mjs.map diff --git a/node_modules/workbox-window/build/workbox-window.dev.es5.mjs.map b/node_modules/workbox-window/build/workbox-window.dev.es5.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..9b08ec7697b828889acf6d6e3e332bb039b47f1b --- /dev/null +++ b/node_modules/workbox-window/build/workbox-window.dev.es5.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-window.dev.es5.mjs","sources":["../_version.js","../messageSW.js","../../workbox-core/_version.js","../../workbox-core/_private/Deferred.js","../../workbox-core/_private/dontWaitFor.js","../../workbox-core/_private/logger.js","../utils/WorkboxEventTarget.js","../utils/urlsMatch.js","../utils/WorkboxEvent.js","../Workbox.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:window:7.4.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport './_version.js';\n/**\n * Sends a data object to a service worker via `postMessage` and resolves with\n * a response (if any).\n *\n * A response can be set in a message handler in the service worker by\n * calling `event.ports[0].postMessage(...)`, which will resolve the promise\n * returned by `messageSW()`. If no response is set, the promise will not\n * resolve.\n *\n * @param {ServiceWorker} sw The service worker to send the message to.\n * @param {Object} data An object to send to the service worker.\n * @return {Promise}\n * @memberof workbox-window\n */\n// Better not change type of data.\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction messageSW(sw, data) {\n return new Promise((resolve) => {\n const messageChannel = new MessageChannel();\n messageChannel.port1.onmessage = (event) => {\n resolve(event.data);\n };\n sw.postMessage(data, [messageChannel.port2]);\n });\n}\nexport { messageSW };\n","\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:core:7.4.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 '../_version.js';\n/**\n * The Deferred class composes Promises in a way that allows for them to be\n * resolved or rejected from outside the constructor. In most cases promises\n * should be used directly, but Deferreds can be necessary when the logic to\n * resolve a promise must be separate.\n *\n * @private\n */\nclass Deferred {\n /**\n * Creates a promise and exposes its resolve and reject functions as methods.\n */\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\nexport { Deferred };\n","/*\n Copyright 2019 Google LLC\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';\n/**\n * A helper function that prevents a promise from being flagged as unused.\n *\n * @private\n **/\nexport function dontWaitFor(promise) {\n // Effective no-op.\n void promise.then(() => { });\n}\n","/*\n Copyright 2019 Google LLC\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';\nconst logger = (process.env.NODE_ENV === 'production'\n ? null\n : (() => {\n // Don't overwrite this value if it's already set.\n // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923\n if (!('__WB_DISABLE_DEV_LOGS' in globalThis)) {\n self.__WB_DISABLE_DEV_LOGS = false;\n }\n let inGroup = false;\n const methodToColorMap = {\n debug: `#7f8c8d`,\n log: `#2ecc71`,\n warn: `#f39c12`,\n error: `#c0392b`,\n groupCollapsed: `#3498db`,\n groupEnd: null, // No colored prefix on groupEnd\n };\n const print = function (method, args) {\n if (self.__WB_DISABLE_DEV_LOGS) {\n return;\n }\n if (method === 'groupCollapsed') {\n // Safari doesn't print all console.groupCollapsed() arguments:\n // https://bugs.webkit.org/show_bug.cgi?id=182754\n if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {\n console[method](...args);\n return;\n }\n }\n const styles = [\n `background: ${methodToColorMap[method]}`,\n `border-radius: 0.5em`,\n `color: white`,\n `font-weight: bold`,\n `padding: 2px 0.5em`,\n ];\n // When in a group, the workbox prefix is not displayed.\n const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')];\n console[method](...logPrefix, ...args);\n if (method === 'groupCollapsed') {\n inGroup = true;\n }\n if (method === 'groupEnd') {\n inGroup = false;\n }\n };\n // eslint-disable-next-line @typescript-eslint/ban-types\n const api = {};\n const loggerMethods = Object.keys(methodToColorMap);\n for (const key of loggerMethods) {\n const method = key;\n api[method] = (...args) => {\n print(method, args);\n };\n }\n return api;\n })());\nexport { logger };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\n/**\n * A minimal `EventTarget` shim.\n * This is necessary because not all browsers support constructable\n * `EventTarget`, so using a real `EventTarget` will error.\n * @private\n */\nexport class WorkboxEventTarget {\n constructor() {\n this._eventListenerRegistry = new Map();\n }\n /**\n * @param {string} type\n * @param {Function} listener\n * @private\n */\n addEventListener(type, listener) {\n const foo = this._getEventListenersByType(type);\n foo.add(listener);\n }\n /**\n * @param {string} type\n * @param {Function} listener\n * @private\n */\n removeEventListener(type, listener) {\n this._getEventListenersByType(type).delete(listener);\n }\n /**\n * @param {Object} event\n * @private\n */\n dispatchEvent(event) {\n event.target = this;\n const listeners = this._getEventListenersByType(event.type);\n for (const listener of listeners) {\n listener(event);\n }\n }\n /**\n * Returns a Set of listeners associated with the passed event type.\n * If no handlers have been registered, an empty Set is returned.\n *\n * @param {string} type The event type.\n * @return {Set} An array of handler functions.\n * @private\n */\n _getEventListenersByType(type) {\n if (!this._eventListenerRegistry.has(type)) {\n this._eventListenerRegistry.set(type, new Set());\n }\n return this._eventListenerRegistry.get(type);\n }\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * Returns true if two URLs have the same `.href` property. The URLS can be\n * relative, and if they are the current location href is used to resolve URLs.\n *\n * @private\n * @param {string} url1\n * @param {string} url2\n * @return {boolean}\n */\nexport function urlsMatch(url1, url2) {\n const { href } = location;\n return new URL(url1, href).href === new URL(url2, href).href;\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * A minimal `Event` subclass shim.\n * This doesn't *actually* subclass `Event` because not all browsers support\n * constructable `EventTarget`, and using a real `Event` will error.\n * @private\n */\nexport class WorkboxEvent {\n constructor(type, props) {\n this.type = type;\n Object.assign(this, props);\n }\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { Deferred } from 'workbox-core/_private/Deferred.js';\nimport { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { messageSW } from './messageSW.js';\nimport { WorkboxEventTarget } from './utils/WorkboxEventTarget.js';\nimport { urlsMatch } from './utils/urlsMatch.js';\nimport { WorkboxEvent } from './utils/WorkboxEvent.js';\nimport './_version.js';\n// The time a SW must be in the waiting phase before we can conclude\n// `skipWaiting()` wasn't called. This 200 amount wasn't scientifically\n// chosen, but it seems to avoid false positives in my testing.\nconst WAITING_TIMEOUT_DURATION = 200;\n// The amount of time after a registration that we can reasonably conclude\n// that the registration didn't trigger an update.\nconst REGISTRATION_TIMEOUT_DURATION = 60000;\n// The de facto standard message that a service worker should be listening for\n// to trigger a call to skipWaiting().\nconst SKIP_WAITING_MESSAGE = { type: 'SKIP_WAITING' };\n/**\n * A class to aid in handling service worker registration, updates, and\n * reacting to service worker lifecycle events.\n *\n * @fires {@link workbox-window.Workbox#message}\n * @fires {@link workbox-window.Workbox#installed}\n * @fires {@link workbox-window.Workbox#waiting}\n * @fires {@link workbox-window.Workbox#controlling}\n * @fires {@link workbox-window.Workbox#activated}\n * @fires {@link workbox-window.Workbox#redundant}\n * @memberof workbox-window\n */\nclass Workbox extends WorkboxEventTarget {\n /**\n * Creates a new Workbox instance with a script URL and service worker\n * options. The script URL and options are the same as those used when\n * calling [navigator.serviceWorker.register(scriptURL, options)](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register).\n *\n * @param {string|TrustedScriptURL} scriptURL The service worker script\n * associated with this instance. Using a\n * [`TrustedScriptURL`](https://web.dev/trusted-types/) is supported.\n * @param {Object} [registerOptions] The service worker options associated\n * with this instance.\n */\n // eslint-disable-next-line @typescript-eslint/ban-types\n constructor(scriptURL, registerOptions = {}) {\n super();\n this._registerOptions = {};\n this._updateFoundCount = 0;\n // Deferreds we can resolve later.\n this._swDeferred = new Deferred();\n this._activeDeferred = new Deferred();\n this._controllingDeferred = new Deferred();\n this._registrationTime = 0;\n this._ownSWs = new Set();\n /**\n * @private\n */\n this._onUpdateFound = () => {\n // `this._registration` will never be `undefined` after an update is found.\n const registration = this._registration;\n const installingSW = registration.installing;\n // If the script URL passed to `navigator.serviceWorker.register()` is\n // different from the current controlling SW's script URL, we know any\n // successful registration calls will trigger an `updatefound` event.\n // But if the registered script URL is the same as the current controlling\n // SW's script URL, we'll only get an `updatefound` event if the file\n // changed since it was last registered. This can be a problem if the user\n // opens up the same page in a different tab, and that page registers\n // a SW that triggers an update. It's a problem because this page has no\n // good way of knowing whether the `updatefound` event came from the SW\n // script it registered or from a registration attempt made by a newer\n // version of the page running in another tab.\n // To minimize the possibility of a false positive, we use the logic here:\n const updateLikelyTriggeredExternally = \n // Since we enforce only calling `register()` once, and since we don't\n // add the `updatefound` event listener until the `register()` call, if\n // `_updateFoundCount` is > 0 then it means this method has already\n // been called, thus this SW must be external\n this._updateFoundCount > 0 ||\n // If the script URL of the installing SW is different from this\n // instance's script URL, we know it's definitely not from our\n // registration.\n !urlsMatch(installingSW.scriptURL, this._scriptURL.toString()) ||\n // If all of the above are false, then we use a time-based heuristic:\n // Any `updatefound` event that occurs long after our registration is\n // assumed to be external.\n performance.now() > this._registrationTime + REGISTRATION_TIMEOUT_DURATION\n ? // If any of the above are not true, we assume the update was\n // triggered by this instance.\n true\n : false;\n if (updateLikelyTriggeredExternally) {\n this._externalSW = installingSW;\n registration.removeEventListener('updatefound', this._onUpdateFound);\n }\n else {\n // If the update was not triggered externally we know the installing\n // SW is the one we registered, so we set it.\n this._sw = installingSW;\n this._ownSWs.add(installingSW);\n this._swDeferred.resolve(installingSW);\n // The `installing` state isn't something we have a dedicated\n // callback for, but we do log messages for it in development.\n if (process.env.NODE_ENV !== 'production') {\n if (navigator.serviceWorker.controller) {\n logger.log('Updated service worker found. Installing now...');\n }\n else {\n logger.log('Service worker is installing...');\n }\n }\n }\n // Increment the `updatefound` count, so future invocations of this\n // method can be sure they were triggered externally.\n ++this._updateFoundCount;\n // Add a `statechange` listener regardless of whether this update was\n // triggered externally, since we have callbacks for both.\n installingSW.addEventListener('statechange', this._onStateChange);\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onStateChange = (originalEvent) => {\n // `this._registration` will never be `undefined` after an update is found.\n const registration = this._registration;\n const sw = originalEvent.target;\n const { state } = sw;\n const isExternal = sw === this._externalSW;\n const eventProps = {\n sw,\n isExternal,\n originalEvent,\n };\n if (!isExternal && this._isUpdate) {\n eventProps.isUpdate = true;\n }\n this.dispatchEvent(new WorkboxEvent(state, eventProps));\n if (state === 'installed') {\n // This timeout is used to ignore cases where the service worker calls\n // `skipWaiting()` in the install event, thus moving it directly in the\n // activating state. (Since all service workers *must* go through the\n // waiting phase, the only way to detect `skipWaiting()` called in the\n // install event is to observe that the time spent in the waiting phase\n // is very short.)\n // NOTE: we don't need separate timeouts for the own and external SWs\n // since they can't go through these phases at the same time.\n this._waitingTimeout = self.setTimeout(() => {\n // Ensure the SW is still waiting (it may now be redundant).\n if (state === 'installed' && registration.waiting === sw) {\n this.dispatchEvent(new WorkboxEvent('waiting', eventProps));\n if (process.env.NODE_ENV !== 'production') {\n if (isExternal) {\n logger.warn('An external service worker has installed but is ' +\n 'waiting for this client to close before activating...');\n }\n else {\n logger.warn('The service worker has installed but is waiting ' +\n 'for existing clients to close before activating...');\n }\n }\n }\n }, WAITING_TIMEOUT_DURATION);\n }\n else if (state === 'activating') {\n clearTimeout(this._waitingTimeout);\n if (!isExternal) {\n this._activeDeferred.resolve(sw);\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n switch (state) {\n case 'installed':\n if (isExternal) {\n logger.warn('An external service worker has installed. ' +\n 'You may want to suggest users reload this page.');\n }\n else {\n logger.log('Registered service worker installed.');\n }\n break;\n case 'activated':\n if (isExternal) {\n logger.warn('An external service worker has activated.');\n }\n else {\n logger.log('Registered service worker activated.');\n if (sw !== navigator.serviceWorker.controller) {\n logger.warn('The registered service worker is active but ' +\n 'not yet controlling the page. Reload or run ' +\n '`clients.claim()` in the service worker.');\n }\n }\n break;\n case 'redundant':\n if (sw === this._compatibleControllingSW) {\n logger.log('Previously controlling service worker now redundant!');\n }\n else if (!isExternal) {\n logger.log('Registered service worker now redundant!');\n }\n break;\n }\n }\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onControllerChange = (originalEvent) => {\n const sw = this._sw;\n const isExternal = sw !== navigator.serviceWorker.controller;\n // Unconditionally dispatch the controlling event, with isExternal set\n // to distinguish between controller changes due to the initial registration\n // vs. an update-check or other tab's registration.\n // See https://github.com/GoogleChrome/workbox/issues/2786\n this.dispatchEvent(new WorkboxEvent('controlling', {\n isExternal,\n originalEvent,\n sw,\n isUpdate: this._isUpdate,\n }));\n if (!isExternal) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Registered service worker now controlling this page.');\n }\n this._controllingDeferred.resolve(sw);\n }\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onMessage = async (originalEvent) => {\n // Can't change type 'any' of data.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const { data, ports, source } = originalEvent;\n // Wait until there's an \"own\" service worker. This is used to buffer\n // `message` events that may be received prior to calling `register()`.\n await this.getSW();\n // If the service worker that sent the message is in the list of own\n // service workers for this instance, dispatch a `message` event.\n // NOTE: we check for all previously owned service workers rather than\n // just the current one because some messages (e.g. cache updates) use\n // a timeout when sent and may be delayed long enough for a service worker\n // update to be found.\n if (this._ownSWs.has(source)) {\n this.dispatchEvent(new WorkboxEvent('message', {\n // Can't change type 'any' of data.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n data,\n originalEvent,\n ports,\n sw: source,\n }));\n }\n };\n this._scriptURL = scriptURL;\n this._registerOptions = registerOptions;\n // Add a message listener immediately since messages received during\n // page load are buffered only until the DOMContentLoaded event:\n // https://github.com/GoogleChrome/workbox/issues/2202\n navigator.serviceWorker.addEventListener('message', this._onMessage);\n }\n /**\n * Registers a service worker for this instances script URL and service\n * worker options. By default this method delays registration until after\n * the window has loaded.\n *\n * @param {Object} [options]\n * @param {Function} [options.immediate=false] Setting this to true will\n * register the service worker immediately, even if the window has\n * not loaded (not recommended).\n */\n async register({ immediate = false } = {}) {\n if (process.env.NODE_ENV !== 'production') {\n if (this._registrationTime) {\n logger.error('Cannot re-register a Workbox instance after it has ' +\n 'been registered. Create a new instance instead.');\n return;\n }\n }\n if (!immediate && document.readyState !== 'complete') {\n await new Promise((res) => window.addEventListener('load', res));\n }\n // Set this flag to true if any service worker was controlling the page\n // at registration time.\n this._isUpdate = Boolean(navigator.serviceWorker.controller);\n // Before registering, attempt to determine if a SW is already controlling\n // the page, and if that SW script (and version, if specified) matches this\n // instance's script.\n this._compatibleControllingSW = this._getControllingSWIfCompatible();\n this._registration = await this._registerScript();\n // If we have a compatible controller, store the controller as the \"own\"\n // SW, resolve active/controlling deferreds and add necessary listeners.\n if (this._compatibleControllingSW) {\n this._sw = this._compatibleControllingSW;\n this._activeDeferred.resolve(this._compatibleControllingSW);\n this._controllingDeferred.resolve(this._compatibleControllingSW);\n this._compatibleControllingSW.addEventListener('statechange', this._onStateChange, { once: true });\n }\n // If there's a waiting service worker with a matching URL before the\n // `updatefound` event fires, it likely means that this site is open\n // in another tab, or the user refreshed the page (and thus the previous\n // page wasn't fully unloaded before this page started loading).\n // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting\n const waitingSW = this._registration.waiting;\n if (waitingSW &&\n urlsMatch(waitingSW.scriptURL, this._scriptURL.toString())) {\n // Store the waiting SW as the \"own\" Sw, even if it means overwriting\n // a compatible controller.\n this._sw = waitingSW;\n // Run this in the next microtask, so any code that adds an event\n // listener after awaiting `register()` will get this event.\n dontWaitFor(Promise.resolve().then(() => {\n this.dispatchEvent(new WorkboxEvent('waiting', {\n sw: waitingSW,\n wasWaitingBeforeRegister: true,\n }));\n if (process.env.NODE_ENV !== 'production') {\n logger.warn('A service worker was already waiting to activate ' +\n 'before this script was registered...');\n }\n }));\n }\n // If an \"own\" SW is already set, resolve the deferred.\n if (this._sw) {\n this._swDeferred.resolve(this._sw);\n this._ownSWs.add(this._sw);\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Successfully registered service worker.', this._scriptURL.toString());\n if (navigator.serviceWorker.controller) {\n if (this._compatibleControllingSW) {\n logger.debug('A service worker with the same script URL ' +\n 'is already controlling this page.');\n }\n else {\n logger.debug('A service worker with a different script URL is ' +\n 'currently controlling the page. The browser is now fetching ' +\n 'the new script now...');\n }\n }\n const currentPageIsOutOfScope = () => {\n const scopeURL = new URL(this._registerOptions.scope || this._scriptURL.toString(), document.baseURI);\n const scopeURLBasePath = new URL('./', scopeURL.href).pathname;\n return !location.pathname.startsWith(scopeURLBasePath);\n };\n if (currentPageIsOutOfScope()) {\n logger.warn('The current page is not in scope for the registered ' +\n 'service worker. Was this a mistake?');\n }\n }\n this._registration.addEventListener('updatefound', this._onUpdateFound);\n navigator.serviceWorker.addEventListener('controllerchange', this._onControllerChange);\n return this._registration;\n }\n /**\n * Checks for updates of the registered service worker.\n */\n async update() {\n if (!this._registration) {\n if (process.env.NODE_ENV !== 'production') {\n logger.error('Cannot update a Workbox instance without ' +\n 'being registered. Register the Workbox instance first.');\n }\n return;\n }\n // Try to update registration\n await this._registration.update();\n }\n /**\n * Resolves to the service worker registered by this instance as soon as it\n * is active. If a service worker was already controlling at registration\n * time then it will resolve to that if the script URLs (and optionally\n * script versions) match, otherwise it will wait until an update is found\n * and activates.\n *\n * @return {Promise}\n */\n get active() {\n return this._activeDeferred.promise;\n }\n /**\n * Resolves to the service worker registered by this instance as soon as it\n * is controlling the page. If a service worker was already controlling at\n * registration time then it will resolve to that if the script URLs (and\n * optionally script versions) match, otherwise it will wait until an update\n * is found and starts controlling the page.\n * Note: the first time a service worker is installed it will active but\n * not start controlling the page unless `clients.claim()` is called in the\n * service worker.\n *\n * @return {Promise}\n */\n get controlling() {\n return this._controllingDeferred.promise;\n }\n /**\n * Resolves with a reference to a service worker that matches the script URL\n * of this instance, as soon as it's available.\n *\n * If, at registration time, there's already an active or waiting service\n * worker with a matching script URL, it will be used (with the waiting\n * service worker taking precedence over the active service worker if both\n * match, since the waiting service worker would have been registered more\n * recently).\n * If there's no matching active or waiting service worker at registration\n * time then the promise will not resolve until an update is found and starts\n * installing, at which point the installing service worker is used.\n *\n * @return {Promise}\n */\n getSW() {\n // If `this._sw` is set, resolve with that as we want `getSW()` to\n // return the correct (new) service worker if an update is found.\n return this._sw !== undefined\n ? Promise.resolve(this._sw)\n : this._swDeferred.promise;\n }\n /**\n * Sends the passed data object to the service worker registered by this\n * instance (via {@link workbox-window.Workbox#getSW}) and resolves\n * with a response (if any).\n *\n * A response can be set in a message handler in the service worker by\n * calling `event.ports[0].postMessage(...)`, which will resolve the promise\n * returned by `messageSW()`. If no response is set, the promise will never\n * resolve.\n *\n * @param {Object} data An object to send to the service worker\n * @return {Promise}\n */\n // We might be able to change the 'data' type to Record in the future.\n // eslint-disable-next-line @typescript-eslint/ban-types\n async messageSW(data) {\n const sw = await this.getSW();\n return messageSW(sw, data);\n }\n /**\n * Sends a `{type: 'SKIP_WAITING'}` message to the service worker that's\n * currently in the `waiting` state associated with the current registration.\n *\n * If there is no current registration or no service worker is `waiting`,\n * calling this will have no effect.\n */\n messageSkipWaiting() {\n if (this._registration && this._registration.waiting) {\n void messageSW(this._registration.waiting, SKIP_WAITING_MESSAGE);\n }\n }\n /**\n * Checks for a service worker already controlling the page and returns\n * it if its script URL matches.\n *\n * @private\n * @return {ServiceWorker|undefined}\n */\n _getControllingSWIfCompatible() {\n const controller = navigator.serviceWorker.controller;\n if (controller &&\n urlsMatch(controller.scriptURL, this._scriptURL.toString())) {\n return controller;\n }\n else {\n return undefined;\n }\n }\n /**\n * Registers a service worker for this instances script URL and register\n * options and tracks the time registration was complete.\n *\n * @private\n */\n async _registerScript() {\n try {\n // this._scriptURL may be a TrustedScriptURL, but there's no support for\n // passing that to register() in lib.dom right now.\n // https://github.com/GoogleChrome/workbox/issues/2855\n const reg = await navigator.serviceWorker.register(this._scriptURL, this._registerOptions);\n // Keep track of when registration happened, so it can be used in the\n // `this._onUpdateFound` heuristic. Also use the presence of this\n // property as a way to see if `.register()` has been called.\n this._registrationTime = performance.now();\n return reg;\n }\n catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n logger.error(error);\n }\n // Re-throw the error.\n throw error;\n }\n }\n}\nexport { Workbox };\n// The jsdoc comments below outline the events this instance may dispatch:\n// -----------------------------------------------------------------------\n/**\n * The `message` event is dispatched any time a `postMessage` is received.\n *\n * @event workbox-window.Workbox#message\n * @type {WorkboxEvent}\n * @property {*} data The `data` property from the original `message` event.\n * @property {Event} originalEvent The original [`message`]{@link https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent}\n * event.\n * @property {string} type `message`.\n * @property {MessagePort[]} ports The `ports` value from `originalEvent`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `installed` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}\n * changes to `installed`.\n *\n * Then can happen either the very first time a service worker is installed,\n * or after an update to the current service worker is found. In the case\n * of an update being found, the event's `isUpdate` property will be `true`.\n *\n * @event workbox-window.Workbox#installed\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `installed`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `waiting` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}\n * changes to `installed` and then doesn't immediately change to `activating`.\n * It may also be dispatched if a service worker with the same\n * [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}\n * was already waiting when the {@link workbox-window.Workbox#register}\n * method was called.\n *\n * @event workbox-window.Workbox#waiting\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event|undefined} originalEvent The original\n * [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event, or `undefined` in the case where the service worker was waiting\n * to before `.register()` was called.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {boolean|undefined} wasWaitingBeforeRegister True if a service worker with\n * a matching `scriptURL` was already waiting when this `Workbox`\n * instance called `register()`.\n * @property {string} type `waiting`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `controlling` event is dispatched if a\n * [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}\n * fires on the service worker [container]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer}\n * and the [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}\n * of the new [controller]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller}\n * matches the `scriptURL` of the `Workbox` instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}.\n *\n * @event workbox-window.Workbox#controlling\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this service worker was registered.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `controlling`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `activated` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}\n * changes to `activated`.\n *\n * @event workbox-window.Workbox#activated\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `activated`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `redundant` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}\n * changes to `redundant`.\n *\n * @event workbox-window.Workbox#redundant\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {string} type `redundant`.\n * @property {Workbox} target The `Workbox` instance.\n */\n"],"names":["self","_","e","messageSW","sw","data","Promise","resolve","messageChannel","MessageChannel","port1","onmessage","event","postMessage","port2","Deferred","_this","promise","reject","dontWaitFor","then","logger","globalThis","__WB_DISABLE_DEV_LOGS","inGroup","methodToColorMap","debug","log","warn","error","groupCollapsed","groupEnd","print","method","args","_console2","test","navigator","userAgent","_console","console","apply","styles","logPrefix","join","concat","api","loggerMethods","Object","keys","_loop","key","_loggerMethods","_i","_len","arguments","length","Array","_key","WorkboxEventTarget","_eventListenerRegistry","Map","_proto","prototype","addEventListener","type","listener","foo","_getEventListenersByType","add","removeEventListener","delete","dispatchEvent","target","listeners","_iterator","_createForOfIteratorHelperLoose","_step","done","value","has","set","Set","get","urlsMatch","url1","url2","_location","location","href","URL","WorkboxEvent","props","assign","_await","direct","WAITING_TIMEOUT_DURATION","_async","f","i","REGISTRATION_TIMEOUT_DURATION","_empty","SKIP_WAITING_MESSAGE","_awaitIgnored","Workbox","_WorkboxEventTarget","scriptURL","registerOptions","call","_registerOptions","_updateFoundCount","_swDeferred","_activeDeferred","_controllingDeferred","_registrationTime","_ownSWs","_onUpdateFound","registration","_registration","installingSW","installing","updateLikelyTriggeredExternally","_scriptURL","toString","performance","now","_externalSW","_sw","serviceWorker","controller","_onStateChange","originalEvent","state","isExternal","eventProps","_isUpdate","isUpdate","_waitingTimeout","setTimeout","waiting","clearTimeout","_compatibleControllingSW","_onControllerChange","_onMessage","ports","source","getSW","_inheritsLoose","register","_temp","_ref","_ref$immediate","immediate","_this2","process","_invoke","document","readyState","res","window","Boolean","_getControllingSWIfCompatible","_registerScript","_this2$_registerScrip","once","waitingSW","wasWaitingBeforeRegister","currentPageIsOutOfScope","scopeURL","scope","baseURI","scopeURLBasePath","pathname","startsWith","update","_this3","undefined","_this4","messageSkipWaiting","_this5","_catch","reg","_createClass","body","result","recover"],"mappings":"AACA;AACA,IAAI;AACAA,EAAAA,IAAI,CAAC,sBAAsB,CAAC,IAAIC,CAAC,EAAE;AACvC,CAAC,CACD,OAAOC,CAAC,EAAE,CAAE;;ACLZ;AACA;;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA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ACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAzDO,SAAAJ,MAAAA,CAAgBG,IAAI,EAAEE,OAAO,EAAE;EACrC,IAAI;AACH,IAAA,IAAID,MAAM,GAAGD,IAAI,EAAE;EACpB,CAAC,CAAC,OAAMrL,CAAC,EAAE;IACV,OAAOuL,OAAO,CAACvL,CAAC,CAAC;AAClB,EAAA;AACA,EAAA,IAAIsL,MAAM,IAAIA,MAAM,CAACpK,IAAI,EAAE;IAC1B,OAAOoK,MAAM,CAACpK,IAAI,CAAC,MAAM,EAAEqK,OAAO,CAAC;AACpC,EAAA;AACA,EAAA,OAAOD,MAAM;AACd;;;;"} \ No newline at end of file diff --git a/node_modules/workbox-window/build/workbox-window.dev.mjs b/node_modules/workbox-window/build/workbox-window.dev.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3138f2ffef6bd1a137e4bfe70d0d17ca3338f996 --- /dev/null +++ b/node_modules/workbox-window/build/workbox-window.dev.mjs @@ -0,0 +1,845 @@ +// @ts-ignore +try { + self['workbox:window:7.4.0'] && _(); +} catch (e) {} + +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +/** + * Sends a data object to a service worker via `postMessage` and resolves with + * a response (if any). + * + * A response can be set in a message handler in the service worker by + * calling `event.ports[0].postMessage(...)`, which will resolve the promise + * returned by `messageSW()`. If no response is set, the promise will not + * resolve. + * + * @param {ServiceWorker} sw The service worker to send the message to. + * @param {Object} data An object to send to the service worker. + * @return {Promise} + * @memberof workbox-window + */ +// Better not change type of data. +// eslint-disable-next-line @typescript-eslint/ban-types +function messageSW(sw, data) { + return new Promise(resolve => { + const messageChannel = new MessageChannel(); + messageChannel.port1.onmessage = event => { + resolve(event.data); + }; + sw.postMessage(data, [messageChannel.port2]); + }); +} + +// @ts-ignore +try { + self['workbox:core:7.4.0'] && _(); +} catch (e) {} + +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +/** + * The Deferred class composes Promises in a way that allows for them to be + * resolved or rejected from outside the constructor. In most cases promises + * should be used directly, but Deferreds can be necessary when the logic to + * resolve a promise must be separate. + * + * @private + */ +class Deferred { + /** + * Creates a promise and exposes its resolve and reject functions as methods. + */ + constructor() { + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + } +} + +/* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +/** + * A helper function that prevents a promise from being flagged as unused. + * + * @private + **/ +function dontWaitFor(promise) { + // Effective no-op. + void promise.then(() => {}); +} + +/* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +const logger = (() => { + // Don't overwrite this value if it's already set. + // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923 + if (!('__WB_DISABLE_DEV_LOGS' in globalThis)) { + self.__WB_DISABLE_DEV_LOGS = false; + } + let inGroup = false; + const methodToColorMap = { + debug: `#7f8c8d`, + log: `#2ecc71`, + warn: `#f39c12`, + error: `#c0392b`, + groupCollapsed: `#3498db`, + groupEnd: null // No colored prefix on groupEnd + }; + const print = function (method, args) { + if (self.__WB_DISABLE_DEV_LOGS) { + return; + } + if (method === 'groupCollapsed') { + // Safari doesn't print all console.groupCollapsed() arguments: + // https://bugs.webkit.org/show_bug.cgi?id=182754 + if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) { + console[method](...args); + return; + } + } + 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. + const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')]; + console[method](...logPrefix, ...args); + if (method === 'groupCollapsed') { + inGroup = true; + } + if (method === 'groupEnd') { + inGroup = false; + } + }; + // eslint-disable-next-line @typescript-eslint/ban-types + const api = {}; + const loggerMethods = Object.keys(methodToColorMap); + for (const key of loggerMethods) { + const method = key; + api[method] = (...args) => { + print(method, args); + }; + } + return api; +})(); + +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +/** + * A minimal `EventTarget` shim. + * This is necessary because not all browsers support constructable + * `EventTarget`, so using a real `EventTarget` will error. + * @private + */ +class WorkboxEventTarget { + constructor() { + this._eventListenerRegistry = new Map(); + } + /** + * @param {string} type + * @param {Function} listener + * @private + */ + addEventListener(type, listener) { + const foo = this._getEventListenersByType(type); + foo.add(listener); + } + /** + * @param {string} type + * @param {Function} listener + * @private + */ + removeEventListener(type, listener) { + this._getEventListenersByType(type).delete(listener); + } + /** + * @param {Object} event + * @private + */ + dispatchEvent(event) { + event.target = this; + const listeners = this._getEventListenersByType(event.type); + for (const listener of listeners) { + listener(event); + } + } + /** + * Returns a Set of listeners associated with the passed event type. + * If no handlers have been registered, an empty Set is returned. + * + * @param {string} type The event type. + * @return {Set} An array of handler functions. + * @private + */ + _getEventListenersByType(type) { + if (!this._eventListenerRegistry.has(type)) { + this._eventListenerRegistry.set(type, new Set()); + } + return this._eventListenerRegistry.get(type); + } +} + +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +/** + * Returns true if two URLs have the same `.href` property. The URLS can be + * relative, and if they are the current location href is used to resolve URLs. + * + * @private + * @param {string} url1 + * @param {string} url2 + * @return {boolean} + */ +function urlsMatch(url1, url2) { + const { + href + } = location; + return new URL(url1, href).href === new URL(url2, href).href; +} + +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +/** + * A minimal `Event` subclass shim. + * This doesn't *actually* subclass `Event` because not all browsers support + * constructable `EventTarget`, and using a real `Event` will error. + * @private + */ +class WorkboxEvent { + constructor(type, props) { + this.type = type; + Object.assign(this, props); + } +} + +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +// The time a SW must be in the waiting phase before we can conclude +// `skipWaiting()` wasn't called. This 200 amount wasn't scientifically +// chosen, but it seems to avoid false positives in my testing. +const WAITING_TIMEOUT_DURATION = 200; +// The amount of time after a registration that we can reasonably conclude +// that the registration didn't trigger an update. +const REGISTRATION_TIMEOUT_DURATION = 60000; +// The de facto standard message that a service worker should be listening for +// to trigger a call to skipWaiting(). +const SKIP_WAITING_MESSAGE = { + type: 'SKIP_WAITING' +}; +/** + * A class to aid in handling service worker registration, updates, and + * reacting to service worker lifecycle events. + * + * @fires {@link workbox-window.Workbox#message} + * @fires {@link workbox-window.Workbox#installed} + * @fires {@link workbox-window.Workbox#waiting} + * @fires {@link workbox-window.Workbox#controlling} + * @fires {@link workbox-window.Workbox#activated} + * @fires {@link workbox-window.Workbox#redundant} + * @memberof workbox-window + */ +class Workbox extends WorkboxEventTarget { + /** + * Creates a new Workbox instance with a script URL and service worker + * options. The script URL and options are the same as those used when + * calling [navigator.serviceWorker.register(scriptURL, options)](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register). + * + * @param {string|TrustedScriptURL} scriptURL The service worker script + * associated with this instance. Using a + * [`TrustedScriptURL`](https://web.dev/trusted-types/) is supported. + * @param {Object} [registerOptions] The service worker options associated + * with this instance. + */ + // eslint-disable-next-line @typescript-eslint/ban-types + constructor(scriptURL, registerOptions = {}) { + super(); + this._registerOptions = {}; + this._updateFoundCount = 0; + // Deferreds we can resolve later. + this._swDeferred = new Deferred(); + this._activeDeferred = new Deferred(); + this._controllingDeferred = new Deferred(); + this._registrationTime = 0; + this._ownSWs = new Set(); + /** + * @private + */ + this._onUpdateFound = () => { + // `this._registration` will never be `undefined` after an update is found. + const registration = this._registration; + const installingSW = registration.installing; + // If the script URL passed to `navigator.serviceWorker.register()` is + // different from the current controlling SW's script URL, we know any + // successful registration calls will trigger an `updatefound` event. + // But if the registered script URL is the same as the current controlling + // SW's script URL, we'll only get an `updatefound` event if the file + // changed since it was last registered. This can be a problem if the user + // opens up the same page in a different tab, and that page registers + // a SW that triggers an update. It's a problem because this page has no + // good way of knowing whether the `updatefound` event came from the SW + // script it registered or from a registration attempt made by a newer + // version of the page running in another tab. + // To minimize the possibility of a false positive, we use the logic here: + const updateLikelyTriggeredExternally = + // Since we enforce only calling `register()` once, and since we don't + // add the `updatefound` event listener until the `register()` call, if + // `_updateFoundCount` is > 0 then it means this method has already + // been called, thus this SW must be external + this._updateFoundCount > 0 || + // If the script URL of the installing SW is different from this + // instance's script URL, we know it's definitely not from our + // registration. + !urlsMatch(installingSW.scriptURL, this._scriptURL.toString()) || + // If all of the above are false, then we use a time-based heuristic: + // Any `updatefound` event that occurs long after our registration is + // assumed to be external. + performance.now() > this._registrationTime + REGISTRATION_TIMEOUT_DURATION ? + // If any of the above are not true, we assume the update was + // triggered by this instance. + true : false; + if (updateLikelyTriggeredExternally) { + this._externalSW = installingSW; + registration.removeEventListener('updatefound', this._onUpdateFound); + } else { + // If the update was not triggered externally we know the installing + // SW is the one we registered, so we set it. + this._sw = installingSW; + this._ownSWs.add(installingSW); + this._swDeferred.resolve(installingSW); + // The `installing` state isn't something we have a dedicated + // callback for, but we do log messages for it in development. + { + if (navigator.serviceWorker.controller) { + logger.log('Updated service worker found. Installing now...'); + } else { + logger.log('Service worker is installing...'); + } + } + } + // Increment the `updatefound` count, so future invocations of this + // method can be sure they were triggered externally. + ++this._updateFoundCount; + // Add a `statechange` listener regardless of whether this update was + // triggered externally, since we have callbacks for both. + installingSW.addEventListener('statechange', this._onStateChange); + }; + /** + * @private + * @param {Event} originalEvent + */ + this._onStateChange = originalEvent => { + // `this._registration` will never be `undefined` after an update is found. + const registration = this._registration; + const sw = originalEvent.target; + const { + state + } = sw; + const isExternal = sw === this._externalSW; + const eventProps = { + sw, + isExternal, + originalEvent + }; + if (!isExternal && this._isUpdate) { + eventProps.isUpdate = true; + } + this.dispatchEvent(new WorkboxEvent(state, eventProps)); + if (state === 'installed') { + // This timeout is used to ignore cases where the service worker calls + // `skipWaiting()` in the install event, thus moving it directly in the + // activating state. (Since all service workers *must* go through the + // waiting phase, the only way to detect `skipWaiting()` called in the + // install event is to observe that the time spent in the waiting phase + // is very short.) + // NOTE: we don't need separate timeouts for the own and external SWs + // since they can't go through these phases at the same time. + this._waitingTimeout = self.setTimeout(() => { + // Ensure the SW is still waiting (it may now be redundant). + if (state === 'installed' && registration.waiting === sw) { + this.dispatchEvent(new WorkboxEvent('waiting', eventProps)); + { + if (isExternal) { + logger.warn('An external service worker has installed but is ' + 'waiting for this client to close before activating...'); + } else { + logger.warn('The service worker has installed but is waiting ' + 'for existing clients to close before activating...'); + } + } + } + }, WAITING_TIMEOUT_DURATION); + } else if (state === 'activating') { + clearTimeout(this._waitingTimeout); + if (!isExternal) { + this._activeDeferred.resolve(sw); + } + } + { + switch (state) { + case 'installed': + if (isExternal) { + logger.warn('An external service worker has installed. ' + 'You may want to suggest users reload this page.'); + } else { + logger.log('Registered service worker installed.'); + } + break; + case 'activated': + if (isExternal) { + logger.warn('An external service worker has activated.'); + } else { + logger.log('Registered service worker activated.'); + if (sw !== navigator.serviceWorker.controller) { + logger.warn('The registered service worker is active but ' + 'not yet controlling the page. Reload or run ' + '`clients.claim()` in the service worker.'); + } + } + break; + case 'redundant': + if (sw === this._compatibleControllingSW) { + logger.log('Previously controlling service worker now redundant!'); + } else if (!isExternal) { + logger.log('Registered service worker now redundant!'); + } + break; + } + } + }; + /** + * @private + * @param {Event} originalEvent + */ + this._onControllerChange = originalEvent => { + const sw = this._sw; + const isExternal = sw !== navigator.serviceWorker.controller; + // Unconditionally dispatch the controlling event, with isExternal set + // to distinguish between controller changes due to the initial registration + // vs. an update-check or other tab's registration. + // See https://github.com/GoogleChrome/workbox/issues/2786 + this.dispatchEvent(new WorkboxEvent('controlling', { + isExternal, + originalEvent, + sw, + isUpdate: this._isUpdate + })); + if (!isExternal) { + { + logger.log('Registered service worker now controlling this page.'); + } + this._controllingDeferred.resolve(sw); + } + }; + /** + * @private + * @param {Event} originalEvent + */ + this._onMessage = async originalEvent => { + // Can't change type 'any' of data. + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const { + data, + ports, + source + } = originalEvent; + // Wait until there's an "own" service worker. This is used to buffer + // `message` events that may be received prior to calling `register()`. + await this.getSW(); + // If the service worker that sent the message is in the list of own + // service workers for this instance, dispatch a `message` event. + // NOTE: we check for all previously owned service workers rather than + // just the current one because some messages (e.g. cache updates) use + // a timeout when sent and may be delayed long enough for a service worker + // update to be found. + if (this._ownSWs.has(source)) { + this.dispatchEvent(new WorkboxEvent('message', { + // Can't change type 'any' of data. + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + data, + originalEvent, + ports, + sw: source + })); + } + }; + this._scriptURL = scriptURL; + this._registerOptions = registerOptions; + // Add a message listener immediately since messages received during + // page load are buffered only until the DOMContentLoaded event: + // https://github.com/GoogleChrome/workbox/issues/2202 + navigator.serviceWorker.addEventListener('message', this._onMessage); + } + /** + * Registers a service worker for this instances script URL and service + * worker options. By default this method delays registration until after + * the window has loaded. + * + * @param {Object} [options] + * @param {Function} [options.immediate=false] Setting this to true will + * register the service worker immediately, even if the window has + * not loaded (not recommended). + */ + async register({ + immediate = false + } = {}) { + { + if (this._registrationTime) { + logger.error('Cannot re-register a Workbox instance after it has ' + 'been registered. Create a new instance instead.'); + return; + } + } + if (!immediate && document.readyState !== 'complete') { + await new Promise(res => window.addEventListener('load', res)); + } + // Set this flag to true if any service worker was controlling the page + // at registration time. + this._isUpdate = Boolean(navigator.serviceWorker.controller); + // Before registering, attempt to determine if a SW is already controlling + // the page, and if that SW script (and version, if specified) matches this + // instance's script. + this._compatibleControllingSW = this._getControllingSWIfCompatible(); + this._registration = await this._registerScript(); + // If we have a compatible controller, store the controller as the "own" + // SW, resolve active/controlling deferreds and add necessary listeners. + if (this._compatibleControllingSW) { + this._sw = this._compatibleControllingSW; + this._activeDeferred.resolve(this._compatibleControllingSW); + this._controllingDeferred.resolve(this._compatibleControllingSW); + this._compatibleControllingSW.addEventListener('statechange', this._onStateChange, { + once: true + }); + } + // If there's a waiting service worker with a matching URL before the + // `updatefound` event fires, it likely means that this site is open + // in another tab, or the user refreshed the page (and thus the previous + // page wasn't fully unloaded before this page started loading). + // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting + const waitingSW = this._registration.waiting; + if (waitingSW && urlsMatch(waitingSW.scriptURL, this._scriptURL.toString())) { + // Store the waiting SW as the "own" Sw, even if it means overwriting + // a compatible controller. + this._sw = waitingSW; + // Run this in the next microtask, so any code that adds an event + // listener after awaiting `register()` will get this event. + dontWaitFor(Promise.resolve().then(() => { + this.dispatchEvent(new WorkboxEvent('waiting', { + sw: waitingSW, + wasWaitingBeforeRegister: true + })); + { + logger.warn('A service worker was already waiting to activate ' + 'before this script was registered...'); + } + })); + } + // If an "own" SW is already set, resolve the deferred. + if (this._sw) { + this._swDeferred.resolve(this._sw); + this._ownSWs.add(this._sw); + } + { + logger.log('Successfully registered service worker.', this._scriptURL.toString()); + if (navigator.serviceWorker.controller) { + if (this._compatibleControllingSW) { + logger.debug('A service worker with the same script URL ' + 'is already controlling this page.'); + } else { + logger.debug('A service worker with a different script URL is ' + 'currently controlling the page. The browser is now fetching ' + 'the new script now...'); + } + } + const currentPageIsOutOfScope = () => { + const scopeURL = new URL(this._registerOptions.scope || this._scriptURL.toString(), document.baseURI); + const scopeURLBasePath = new URL('./', scopeURL.href).pathname; + return !location.pathname.startsWith(scopeURLBasePath); + }; + if (currentPageIsOutOfScope()) { + logger.warn('The current page is not in scope for the registered ' + 'service worker. Was this a mistake?'); + } + } + this._registration.addEventListener('updatefound', this._onUpdateFound); + navigator.serviceWorker.addEventListener('controllerchange', this._onControllerChange); + return this._registration; + } + /** + * Checks for updates of the registered service worker. + */ + async update() { + if (!this._registration) { + { + logger.error('Cannot update a Workbox instance without ' + 'being registered. Register the Workbox instance first.'); + } + return; + } + // Try to update registration + await this._registration.update(); + } + /** + * Resolves to the service worker registered by this instance as soon as it + * is active. If a service worker was already controlling at registration + * time then it will resolve to that if the script URLs (and optionally + * script versions) match, otherwise it will wait until an update is found + * and activates. + * + * @return {Promise} + */ + get active() { + return this._activeDeferred.promise; + } + /** + * Resolves to the service worker registered by this instance as soon as it + * is controlling the page. If a service worker was already controlling at + * registration time then it will resolve to that if the script URLs (and + * optionally script versions) match, otherwise it will wait until an update + * is found and starts controlling the page. + * Note: the first time a service worker is installed it will active but + * not start controlling the page unless `clients.claim()` is called in the + * service worker. + * + * @return {Promise} + */ + get controlling() { + return this._controllingDeferred.promise; + } + /** + * Resolves with a reference to a service worker that matches the script URL + * of this instance, as soon as it's available. + * + * If, at registration time, there's already an active or waiting service + * worker with a matching script URL, it will be used (with the waiting + * service worker taking precedence over the active service worker if both + * match, since the waiting service worker would have been registered more + * recently). + * If there's no matching active or waiting service worker at registration + * time then the promise will not resolve until an update is found and starts + * installing, at which point the installing service worker is used. + * + * @return {Promise} + */ + getSW() { + // If `this._sw` is set, resolve with that as we want `getSW()` to + // return the correct (new) service worker if an update is found. + return this._sw !== undefined ? Promise.resolve(this._sw) : this._swDeferred.promise; + } + /** + * Sends the passed data object to the service worker registered by this + * instance (via {@link workbox-window.Workbox#getSW}) and resolves + * with a response (if any). + * + * A response can be set in a message handler in the service worker by + * calling `event.ports[0].postMessage(...)`, which will resolve the promise + * returned by `messageSW()`. If no response is set, the promise will never + * resolve. + * + * @param {Object} data An object to send to the service worker + * @return {Promise} + */ + // We might be able to change the 'data' type to Record in the future. + // eslint-disable-next-line @typescript-eslint/ban-types + async messageSW(data) { + const sw = await this.getSW(); + return messageSW(sw, data); + } + /** + * Sends a `{type: 'SKIP_WAITING'}` message to the service worker that's + * currently in the `waiting` state associated with the current registration. + * + * If there is no current registration or no service worker is `waiting`, + * calling this will have no effect. + */ + messageSkipWaiting() { + if (this._registration && this._registration.waiting) { + void messageSW(this._registration.waiting, SKIP_WAITING_MESSAGE); + } + } + /** + * Checks for a service worker already controlling the page and returns + * it if its script URL matches. + * + * @private + * @return {ServiceWorker|undefined} + */ + _getControllingSWIfCompatible() { + const controller = navigator.serviceWorker.controller; + if (controller && urlsMatch(controller.scriptURL, this._scriptURL.toString())) { + return controller; + } else { + return undefined; + } + } + /** + * Registers a service worker for this instances script URL and register + * options and tracks the time registration was complete. + * + * @private + */ + async _registerScript() { + try { + // this._scriptURL may be a TrustedScriptURL, but there's no support for + // passing that to register() in lib.dom right now. + // https://github.com/GoogleChrome/workbox/issues/2855 + const reg = await navigator.serviceWorker.register(this._scriptURL, this._registerOptions); + // Keep track of when registration happened, so it can be used in the + // `this._onUpdateFound` heuristic. Also use the presence of this + // property as a way to see if `.register()` has been called. + this._registrationTime = performance.now(); + return reg; + } catch (error) { + { + logger.error(error); + } + // Re-throw the error. + throw error; + } + } +} +// The jsdoc comments below outline the events this instance may dispatch: +// ----------------------------------------------------------------------- +/** + * The `message` event is dispatched any time a `postMessage` is received. + * + * @event workbox-window.Workbox#message + * @type {WorkboxEvent} + * @property {*} data The `data` property from the original `message` event. + * @property {Event} originalEvent The original [`message`]{@link https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent} + * event. + * @property {string} type `message`. + * @property {MessagePort[]} ports The `ports` value from `originalEvent`. + * @property {Workbox} target The `Workbox` instance. + */ +/** + * The `installed` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker} + * changes to `installed`. + * + * Then can happen either the very first time a service worker is installed, + * or after an update to the current service worker is found. In the case + * of an update being found, the event's `isUpdate` property will be `true`. + * + * @event workbox-window.Workbox#installed + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {string} type `installed`. + * @property {Workbox} target The `Workbox` instance. + */ +/** + * The `waiting` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw} + * changes to `installed` and then doesn't immediately change to `activating`. + * It may also be dispatched if a service worker with the same + * [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL} + * was already waiting when the {@link workbox-window.Workbox#register} + * method was called. + * + * @event workbox-window.Workbox#waiting + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event|undefined} originalEvent The original + * [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event, or `undefined` in the case where the service worker was waiting + * to before `.register()` was called. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {boolean|undefined} wasWaitingBeforeRegister True if a service worker with + * a matching `scriptURL` was already waiting when this `Workbox` + * instance called `register()`. + * @property {string} type `waiting`. + * @property {Workbox} target The `Workbox` instance. + */ +/** + * The `controlling` event is dispatched if a + * [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange} + * fires on the service worker [container]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer} + * and the [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL} + * of the new [controller]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller} + * matches the `scriptURL` of the `Workbox` instance's + * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}. + * + * @event workbox-window.Workbox#controlling + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this service worker was registered. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {string} type `controlling`. + * @property {Workbox} target The `Workbox` instance. + */ +/** + * The `activated` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker} + * changes to `activated`. + * + * @event workbox-window.Workbox#activated + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {string} type `activated`. + * @property {Workbox} target The `Workbox` instance. + */ +/** + * The `redundant` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw} + * changes to `redundant`. + * + * @event workbox-window.Workbox#redundant + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {string} type `redundant`. + * @property {Workbox} target The `Workbox` instance. + */ + +export { Workbox, WorkboxEvent, messageSW }; +//# sourceMappingURL=workbox-window.dev.mjs.map diff --git a/node_modules/workbox-window/build/workbox-window.dev.mjs.map b/node_modules/workbox-window/build/workbox-window.dev.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..bfb072e9ad2fe4f78ac0d2be055389e0f392ebb8 --- /dev/null +++ b/node_modules/workbox-window/build/workbox-window.dev.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-window.dev.mjs","sources":["../_version.js","../messageSW.js","../../workbox-core/_version.js","../../workbox-core/_private/Deferred.js","../../workbox-core/_private/dontWaitFor.js","../../workbox-core/_private/logger.js","../utils/WorkboxEventTarget.js","../utils/urlsMatch.js","../utils/WorkboxEvent.js","../Workbox.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:window:7.4.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport './_version.js';\n/**\n * Sends a data object to a service worker via `postMessage` and resolves with\n * a response (if any).\n *\n * A response can be set in a message handler in the service worker by\n * calling `event.ports[0].postMessage(...)`, which will resolve the promise\n * returned by `messageSW()`. If no response is set, the promise will not\n * resolve.\n *\n * @param {ServiceWorker} sw The service worker to send the message to.\n * @param {Object} data An object to send to the service worker.\n * @return {Promise}\n * @memberof workbox-window\n */\n// Better not change type of data.\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction messageSW(sw, data) {\n return new Promise((resolve) => {\n const messageChannel = new MessageChannel();\n messageChannel.port1.onmessage = (event) => {\n resolve(event.data);\n };\n sw.postMessage(data, [messageChannel.port2]);\n });\n}\nexport { messageSW };\n","\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:core:7.4.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 '../_version.js';\n/**\n * The Deferred class composes Promises in a way that allows for them to be\n * resolved or rejected from outside the constructor. In most cases promises\n * should be used directly, but Deferreds can be necessary when the logic to\n * resolve a promise must be separate.\n *\n * @private\n */\nclass Deferred {\n /**\n * Creates a promise and exposes its resolve and reject functions as methods.\n */\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\nexport { Deferred };\n","/*\n Copyright 2019 Google LLC\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';\n/**\n * A helper function that prevents a promise from being flagged as unused.\n *\n * @private\n **/\nexport function dontWaitFor(promise) {\n // Effective no-op.\n void promise.then(() => { });\n}\n","/*\n Copyright 2019 Google LLC\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';\nconst logger = (process.env.NODE_ENV === 'production'\n ? null\n : (() => {\n // Don't overwrite this value if it's already set.\n // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923\n if (!('__WB_DISABLE_DEV_LOGS' in globalThis)) {\n self.__WB_DISABLE_DEV_LOGS = false;\n }\n let inGroup = false;\n const methodToColorMap = {\n debug: `#7f8c8d`,\n log: `#2ecc71`,\n warn: `#f39c12`,\n error: `#c0392b`,\n groupCollapsed: `#3498db`,\n groupEnd: null, // No colored prefix on groupEnd\n };\n const print = function (method, args) {\n if (self.__WB_DISABLE_DEV_LOGS) {\n return;\n }\n if (method === 'groupCollapsed') {\n // Safari doesn't print all console.groupCollapsed() arguments:\n // https://bugs.webkit.org/show_bug.cgi?id=182754\n if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {\n console[method](...args);\n return;\n }\n }\n const styles = [\n `background: ${methodToColorMap[method]}`,\n `border-radius: 0.5em`,\n `color: white`,\n `font-weight: bold`,\n `padding: 2px 0.5em`,\n ];\n // When in a group, the workbox prefix is not displayed.\n const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')];\n console[method](...logPrefix, ...args);\n if (method === 'groupCollapsed') {\n inGroup = true;\n }\n if (method === 'groupEnd') {\n inGroup = false;\n }\n };\n // eslint-disable-next-line @typescript-eslint/ban-types\n const api = {};\n const loggerMethods = Object.keys(methodToColorMap);\n for (const key of loggerMethods) {\n const method = key;\n api[method] = (...args) => {\n print(method, args);\n };\n }\n return api;\n })());\nexport { logger };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\n/**\n * A minimal `EventTarget` shim.\n * This is necessary because not all browsers support constructable\n * `EventTarget`, so using a real `EventTarget` will error.\n * @private\n */\nexport class WorkboxEventTarget {\n constructor() {\n this._eventListenerRegistry = new Map();\n }\n /**\n * @param {string} type\n * @param {Function} listener\n * @private\n */\n addEventListener(type, listener) {\n const foo = this._getEventListenersByType(type);\n foo.add(listener);\n }\n /**\n * @param {string} type\n * @param {Function} listener\n * @private\n */\n removeEventListener(type, listener) {\n this._getEventListenersByType(type).delete(listener);\n }\n /**\n * @param {Object} event\n * @private\n */\n dispatchEvent(event) {\n event.target = this;\n const listeners = this._getEventListenersByType(event.type);\n for (const listener of listeners) {\n listener(event);\n }\n }\n /**\n * Returns a Set of listeners associated with the passed event type.\n * If no handlers have been registered, an empty Set is returned.\n *\n * @param {string} type The event type.\n * @return {Set} An array of handler functions.\n * @private\n */\n _getEventListenersByType(type) {\n if (!this._eventListenerRegistry.has(type)) {\n this._eventListenerRegistry.set(type, new Set());\n }\n return this._eventListenerRegistry.get(type);\n }\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * Returns true if two URLs have the same `.href` property. The URLS can be\n * relative, and if they are the current location href is used to resolve URLs.\n *\n * @private\n * @param {string} url1\n * @param {string} url2\n * @return {boolean}\n */\nexport function urlsMatch(url1, url2) {\n const { href } = location;\n return new URL(url1, href).href === new URL(url2, href).href;\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * A minimal `Event` subclass shim.\n * This doesn't *actually* subclass `Event` because not all browsers support\n * constructable `EventTarget`, and using a real `Event` will error.\n * @private\n */\nexport class WorkboxEvent {\n constructor(type, props) {\n this.type = type;\n Object.assign(this, props);\n }\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { Deferred } from 'workbox-core/_private/Deferred.js';\nimport { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { messageSW } from './messageSW.js';\nimport { WorkboxEventTarget } from './utils/WorkboxEventTarget.js';\nimport { urlsMatch } from './utils/urlsMatch.js';\nimport { WorkboxEvent } from './utils/WorkboxEvent.js';\nimport './_version.js';\n// The time a SW must be in the waiting phase before we can conclude\n// `skipWaiting()` wasn't called. This 200 amount wasn't scientifically\n// chosen, but it seems to avoid false positives in my testing.\nconst WAITING_TIMEOUT_DURATION = 200;\n// The amount of time after a registration that we can reasonably conclude\n// that the registration didn't trigger an update.\nconst REGISTRATION_TIMEOUT_DURATION = 60000;\n// The de facto standard message that a service worker should be listening for\n// to trigger a call to skipWaiting().\nconst SKIP_WAITING_MESSAGE = { type: 'SKIP_WAITING' };\n/**\n * A class to aid in handling service worker registration, updates, and\n * reacting to service worker lifecycle events.\n *\n * @fires {@link workbox-window.Workbox#message}\n * @fires {@link workbox-window.Workbox#installed}\n * @fires {@link workbox-window.Workbox#waiting}\n * @fires {@link workbox-window.Workbox#controlling}\n * @fires {@link workbox-window.Workbox#activated}\n * @fires {@link workbox-window.Workbox#redundant}\n * @memberof workbox-window\n */\nclass Workbox extends WorkboxEventTarget {\n /**\n * Creates a new Workbox instance with a script URL and service worker\n * options. The script URL and options are the same as those used when\n * calling [navigator.serviceWorker.register(scriptURL, options)](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register).\n *\n * @param {string|TrustedScriptURL} scriptURL The service worker script\n * associated with this instance. Using a\n * [`TrustedScriptURL`](https://web.dev/trusted-types/) is supported.\n * @param {Object} [registerOptions] The service worker options associated\n * with this instance.\n */\n // eslint-disable-next-line @typescript-eslint/ban-types\n constructor(scriptURL, registerOptions = {}) {\n super();\n this._registerOptions = {};\n this._updateFoundCount = 0;\n // Deferreds we can resolve later.\n this._swDeferred = new Deferred();\n this._activeDeferred = new Deferred();\n this._controllingDeferred = new Deferred();\n this._registrationTime = 0;\n this._ownSWs = new Set();\n /**\n * @private\n */\n this._onUpdateFound = () => {\n // `this._registration` will never be `undefined` after an update is found.\n const registration = this._registration;\n const installingSW = registration.installing;\n // If the script URL passed to `navigator.serviceWorker.register()` is\n // different from the current controlling SW's script URL, we know any\n // successful registration calls will trigger an `updatefound` event.\n // But if the registered script URL is the same as the current controlling\n // SW's script URL, we'll only get an `updatefound` event if the file\n // changed since it was last registered. This can be a problem if the user\n // opens up the same page in a different tab, and that page registers\n // a SW that triggers an update. It's a problem because this page has no\n // good way of knowing whether the `updatefound` event came from the SW\n // script it registered or from a registration attempt made by a newer\n // version of the page running in another tab.\n // To minimize the possibility of a false positive, we use the logic here:\n const updateLikelyTriggeredExternally = \n // Since we enforce only calling `register()` once, and since we don't\n // add the `updatefound` event listener until the `register()` call, if\n // `_updateFoundCount` is > 0 then it means this method has already\n // been called, thus this SW must be external\n this._updateFoundCount > 0 ||\n // If the script URL of the installing SW is different from this\n // instance's script URL, we know it's definitely not from our\n // registration.\n !urlsMatch(installingSW.scriptURL, this._scriptURL.toString()) ||\n // If all of the above are false, then we use a time-based heuristic:\n // Any `updatefound` event that occurs long after our registration is\n // assumed to be external.\n performance.now() > this._registrationTime + REGISTRATION_TIMEOUT_DURATION\n ? // If any of the above are not true, we assume the update was\n // triggered by this instance.\n true\n : false;\n if (updateLikelyTriggeredExternally) {\n this._externalSW = installingSW;\n registration.removeEventListener('updatefound', this._onUpdateFound);\n }\n else {\n // If the update was not triggered externally we know the installing\n // SW is the one we registered, so we set it.\n this._sw = installingSW;\n this._ownSWs.add(installingSW);\n this._swDeferred.resolve(installingSW);\n // The `installing` state isn't something we have a dedicated\n // callback for, but we do log messages for it in development.\n if (process.env.NODE_ENV !== 'production') {\n if (navigator.serviceWorker.controller) {\n logger.log('Updated service worker found. Installing now...');\n }\n else {\n logger.log('Service worker is installing...');\n }\n }\n }\n // Increment the `updatefound` count, so future invocations of this\n // method can be sure they were triggered externally.\n ++this._updateFoundCount;\n // Add a `statechange` listener regardless of whether this update was\n // triggered externally, since we have callbacks for both.\n installingSW.addEventListener('statechange', this._onStateChange);\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onStateChange = (originalEvent) => {\n // `this._registration` will never be `undefined` after an update is found.\n const registration = this._registration;\n const sw = originalEvent.target;\n const { state } = sw;\n const isExternal = sw === this._externalSW;\n const eventProps = {\n sw,\n isExternal,\n originalEvent,\n };\n if (!isExternal && this._isUpdate) {\n eventProps.isUpdate = true;\n }\n this.dispatchEvent(new WorkboxEvent(state, eventProps));\n if (state === 'installed') {\n // This timeout is used to ignore cases where the service worker calls\n // `skipWaiting()` in the install event, thus moving it directly in the\n // activating state. (Since all service workers *must* go through the\n // waiting phase, the only way to detect `skipWaiting()` called in the\n // install event is to observe that the time spent in the waiting phase\n // is very short.)\n // NOTE: we don't need separate timeouts for the own and external SWs\n // since they can't go through these phases at the same time.\n this._waitingTimeout = self.setTimeout(() => {\n // Ensure the SW is still waiting (it may now be redundant).\n if (state === 'installed' && registration.waiting === sw) {\n this.dispatchEvent(new WorkboxEvent('waiting', eventProps));\n if (process.env.NODE_ENV !== 'production') {\n if (isExternal) {\n logger.warn('An external service worker has installed but is ' +\n 'waiting for this client to close before activating...');\n }\n else {\n logger.warn('The service worker has installed but is waiting ' +\n 'for existing clients to close before activating...');\n }\n }\n }\n }, WAITING_TIMEOUT_DURATION);\n }\n else if (state === 'activating') {\n clearTimeout(this._waitingTimeout);\n if (!isExternal) {\n this._activeDeferred.resolve(sw);\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n switch (state) {\n case 'installed':\n if (isExternal) {\n logger.warn('An external service worker has installed. ' +\n 'You may want to suggest users reload this page.');\n }\n else {\n logger.log('Registered service worker installed.');\n }\n break;\n case 'activated':\n if (isExternal) {\n logger.warn('An external service worker has activated.');\n }\n else {\n logger.log('Registered service worker activated.');\n if (sw !== navigator.serviceWorker.controller) {\n logger.warn('The registered service worker is active but ' +\n 'not yet controlling the page. Reload or run ' +\n '`clients.claim()` in the service worker.');\n }\n }\n break;\n case 'redundant':\n if (sw === this._compatibleControllingSW) {\n logger.log('Previously controlling service worker now redundant!');\n }\n else if (!isExternal) {\n logger.log('Registered service worker now redundant!');\n }\n break;\n }\n }\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onControllerChange = (originalEvent) => {\n const sw = this._sw;\n const isExternal = sw !== navigator.serviceWorker.controller;\n // Unconditionally dispatch the controlling event, with isExternal set\n // to distinguish between controller changes due to the initial registration\n // vs. an update-check or other tab's registration.\n // See https://github.com/GoogleChrome/workbox/issues/2786\n this.dispatchEvent(new WorkboxEvent('controlling', {\n isExternal,\n originalEvent,\n sw,\n isUpdate: this._isUpdate,\n }));\n if (!isExternal) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Registered service worker now controlling this page.');\n }\n this._controllingDeferred.resolve(sw);\n }\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onMessage = async (originalEvent) => {\n // Can't change type 'any' of data.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const { data, ports, source } = originalEvent;\n // Wait until there's an \"own\" service worker. This is used to buffer\n // `message` events that may be received prior to calling `register()`.\n await this.getSW();\n // If the service worker that sent the message is in the list of own\n // service workers for this instance, dispatch a `message` event.\n // NOTE: we check for all previously owned service workers rather than\n // just the current one because some messages (e.g. cache updates) use\n // a timeout when sent and may be delayed long enough for a service worker\n // update to be found.\n if (this._ownSWs.has(source)) {\n this.dispatchEvent(new WorkboxEvent('message', {\n // Can't change type 'any' of data.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n data,\n originalEvent,\n ports,\n sw: source,\n }));\n }\n };\n this._scriptURL = scriptURL;\n this._registerOptions = registerOptions;\n // Add a message listener immediately since messages received during\n // page load are buffered only until the DOMContentLoaded event:\n // https://github.com/GoogleChrome/workbox/issues/2202\n navigator.serviceWorker.addEventListener('message', this._onMessage);\n }\n /**\n * Registers a service worker for this instances script URL and service\n * worker options. By default this method delays registration until after\n * the window has loaded.\n *\n * @param {Object} [options]\n * @param {Function} [options.immediate=false] Setting this to true will\n * register the service worker immediately, even if the window has\n * not loaded (not recommended).\n */\n async register({ immediate = false } = {}) {\n if (process.env.NODE_ENV !== 'production') {\n if (this._registrationTime) {\n logger.error('Cannot re-register a Workbox instance after it has ' +\n 'been registered. Create a new instance instead.');\n return;\n }\n }\n if (!immediate && document.readyState !== 'complete') {\n await new Promise((res) => window.addEventListener('load', res));\n }\n // Set this flag to true if any service worker was controlling the page\n // at registration time.\n this._isUpdate = Boolean(navigator.serviceWorker.controller);\n // Before registering, attempt to determine if a SW is already controlling\n // the page, and if that SW script (and version, if specified) matches this\n // instance's script.\n this._compatibleControllingSW = this._getControllingSWIfCompatible();\n this._registration = await this._registerScript();\n // If we have a compatible controller, store the controller as the \"own\"\n // SW, resolve active/controlling deferreds and add necessary listeners.\n if (this._compatibleControllingSW) {\n this._sw = this._compatibleControllingSW;\n this._activeDeferred.resolve(this._compatibleControllingSW);\n this._controllingDeferred.resolve(this._compatibleControllingSW);\n this._compatibleControllingSW.addEventListener('statechange', this._onStateChange, { once: true });\n }\n // If there's a waiting service worker with a matching URL before the\n // `updatefound` event fires, it likely means that this site is open\n // in another tab, or the user refreshed the page (and thus the previous\n // page wasn't fully unloaded before this page started loading).\n // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting\n const waitingSW = this._registration.waiting;\n if (waitingSW &&\n urlsMatch(waitingSW.scriptURL, this._scriptURL.toString())) {\n // Store the waiting SW as the \"own\" Sw, even if it means overwriting\n // a compatible controller.\n this._sw = waitingSW;\n // Run this in the next microtask, so any code that adds an event\n // listener after awaiting `register()` will get this event.\n dontWaitFor(Promise.resolve().then(() => {\n this.dispatchEvent(new WorkboxEvent('waiting', {\n sw: waitingSW,\n wasWaitingBeforeRegister: true,\n }));\n if (process.env.NODE_ENV !== 'production') {\n logger.warn('A service worker was already waiting to activate ' +\n 'before this script was registered...');\n }\n }));\n }\n // If an \"own\" SW is already set, resolve the deferred.\n if (this._sw) {\n this._swDeferred.resolve(this._sw);\n this._ownSWs.add(this._sw);\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Successfully registered service worker.', this._scriptURL.toString());\n if (navigator.serviceWorker.controller) {\n if (this._compatibleControllingSW) {\n logger.debug('A service worker with the same script URL ' +\n 'is already controlling this page.');\n }\n else {\n logger.debug('A service worker with a different script URL is ' +\n 'currently controlling the page. The browser is now fetching ' +\n 'the new script now...');\n }\n }\n const currentPageIsOutOfScope = () => {\n const scopeURL = new URL(this._registerOptions.scope || this._scriptURL.toString(), document.baseURI);\n const scopeURLBasePath = new URL('./', scopeURL.href).pathname;\n return !location.pathname.startsWith(scopeURLBasePath);\n };\n if (currentPageIsOutOfScope()) {\n logger.warn('The current page is not in scope for the registered ' +\n 'service worker. Was this a mistake?');\n }\n }\n this._registration.addEventListener('updatefound', this._onUpdateFound);\n navigator.serviceWorker.addEventListener('controllerchange', this._onControllerChange);\n return this._registration;\n }\n /**\n * Checks for updates of the registered service worker.\n */\n async update() {\n if (!this._registration) {\n if (process.env.NODE_ENV !== 'production') {\n logger.error('Cannot update a Workbox instance without ' +\n 'being registered. Register the Workbox instance first.');\n }\n return;\n }\n // Try to update registration\n await this._registration.update();\n }\n /**\n * Resolves to the service worker registered by this instance as soon as it\n * is active. If a service worker was already controlling at registration\n * time then it will resolve to that if the script URLs (and optionally\n * script versions) match, otherwise it will wait until an update is found\n * and activates.\n *\n * @return {Promise}\n */\n get active() {\n return this._activeDeferred.promise;\n }\n /**\n * Resolves to the service worker registered by this instance as soon as it\n * is controlling the page. If a service worker was already controlling at\n * registration time then it will resolve to that if the script URLs (and\n * optionally script versions) match, otherwise it will wait until an update\n * is found and starts controlling the page.\n * Note: the first time a service worker is installed it will active but\n * not start controlling the page unless `clients.claim()` is called in the\n * service worker.\n *\n * @return {Promise}\n */\n get controlling() {\n return this._controllingDeferred.promise;\n }\n /**\n * Resolves with a reference to a service worker that matches the script URL\n * of this instance, as soon as it's available.\n *\n * If, at registration time, there's already an active or waiting service\n * worker with a matching script URL, it will be used (with the waiting\n * service worker taking precedence over the active service worker if both\n * match, since the waiting service worker would have been registered more\n * recently).\n * If there's no matching active or waiting service worker at registration\n * time then the promise will not resolve until an update is found and starts\n * installing, at which point the installing service worker is used.\n *\n * @return {Promise}\n */\n getSW() {\n // If `this._sw` is set, resolve with that as we want `getSW()` to\n // return the correct (new) service worker if an update is found.\n return this._sw !== undefined\n ? Promise.resolve(this._sw)\n : this._swDeferred.promise;\n }\n /**\n * Sends the passed data object to the service worker registered by this\n * instance (via {@link workbox-window.Workbox#getSW}) and resolves\n * with a response (if any).\n *\n * A response can be set in a message handler in the service worker by\n * calling `event.ports[0].postMessage(...)`, which will resolve the promise\n * returned by `messageSW()`. If no response is set, the promise will never\n * resolve.\n *\n * @param {Object} data An object to send to the service worker\n * @return {Promise}\n */\n // We might be able to change the 'data' type to Record in the future.\n // eslint-disable-next-line @typescript-eslint/ban-types\n async messageSW(data) {\n const sw = await this.getSW();\n return messageSW(sw, data);\n }\n /**\n * Sends a `{type: 'SKIP_WAITING'}` message to the service worker that's\n * currently in the `waiting` state associated with the current registration.\n *\n * If there is no current registration or no service worker is `waiting`,\n * calling this will have no effect.\n */\n messageSkipWaiting() {\n if (this._registration && this._registration.waiting) {\n void messageSW(this._registration.waiting, SKIP_WAITING_MESSAGE);\n }\n }\n /**\n * Checks for a service worker already controlling the page and returns\n * it if its script URL matches.\n *\n * @private\n * @return {ServiceWorker|undefined}\n */\n _getControllingSWIfCompatible() {\n const controller = navigator.serviceWorker.controller;\n if (controller &&\n urlsMatch(controller.scriptURL, this._scriptURL.toString())) {\n return controller;\n }\n else {\n return undefined;\n }\n }\n /**\n * Registers a service worker for this instances script URL and register\n * options and tracks the time registration was complete.\n *\n * @private\n */\n async _registerScript() {\n try {\n // this._scriptURL may be a TrustedScriptURL, but there's no support for\n // passing that to register() in lib.dom right now.\n // https://github.com/GoogleChrome/workbox/issues/2855\n const reg = await navigator.serviceWorker.register(this._scriptURL, this._registerOptions);\n // Keep track of when registration happened, so it can be used in the\n // `this._onUpdateFound` heuristic. Also use the presence of this\n // property as a way to see if `.register()` has been called.\n this._registrationTime = performance.now();\n return reg;\n }\n catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n logger.error(error);\n }\n // Re-throw the error.\n throw error;\n }\n }\n}\nexport { Workbox };\n// The jsdoc comments below outline the events this instance may dispatch:\n// -----------------------------------------------------------------------\n/**\n * The `message` event is dispatched any time a `postMessage` is received.\n *\n * @event workbox-window.Workbox#message\n * @type {WorkboxEvent}\n * @property {*} data The `data` property from the original `message` event.\n * @property {Event} originalEvent The original [`message`]{@link https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent}\n * event.\n * @property {string} type `message`.\n * @property {MessagePort[]} ports The `ports` value from `originalEvent`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `installed` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}\n * changes to `installed`.\n *\n * Then can happen either the very first time a service worker is installed,\n * or after an update to the current service worker is found. In the case\n * of an update being found, the event's `isUpdate` property will be `true`.\n *\n * @event workbox-window.Workbox#installed\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `installed`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `waiting` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}\n * changes to `installed` and then doesn't immediately change to `activating`.\n * It may also be dispatched if a service worker with the same\n * [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}\n * was already waiting when the {@link workbox-window.Workbox#register}\n * method was called.\n *\n * @event workbox-window.Workbox#waiting\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event|undefined} originalEvent The original\n * [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event, or `undefined` in the case where the service worker was waiting\n * to before `.register()` was called.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {boolean|undefined} wasWaitingBeforeRegister True if a service worker with\n * a matching `scriptURL` was already waiting when this `Workbox`\n * instance called `register()`.\n * @property {string} type `waiting`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `controlling` event is dispatched if a\n * [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}\n * fires on the service worker [container]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer}\n * and the [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}\n * of the new [controller]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller}\n * matches the `scriptURL` of the `Workbox` instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}.\n *\n * @event workbox-window.Workbox#controlling\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this service worker was registered.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `controlling`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `activated` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}\n * changes to `activated`.\n *\n * @event workbox-window.Workbox#activated\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `activated`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `redundant` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}\n * changes to `redundant`.\n *\n * @event workbox-window.Workbox#redundant\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {string} type `redundant`.\n * @property {Workbox} target The `Workbox` instance.\n */\n"],"names":["self","_","e","messageSW","sw","data","Promise","resolve","messageChannel","MessageChannel","port1","onmessage","event","postMessage","port2","Deferred","constructor","promise","reject","dontWaitFor","then","logger","globalThis","__WB_DISABLE_DEV_LOGS","inGroup","methodToColorMap","debug","log","warn","error","groupCollapsed","groupEnd","print","method","args","test","navigator","userAgent","console","styles","logPrefix","join","api","loggerMethods","Object","keys","key","WorkboxEventTarget","_eventListenerRegistry","Map","addEventListener","type","listener","foo","_getEventListenersByType","add","removeEventListener","delete","dispatchEvent","target","listeners","has","set","Set","get","urlsMatch","url1","url2","href","location","URL","WorkboxEvent","props","assign","WAITING_TIMEOUT_DURATION","REGISTRATION_TIMEOUT_DURATION","SKIP_WAITING_MESSAGE","Workbox","scriptURL","registerOptions","_registerOptions","_updateFoundCount","_swDeferred","_activeDeferred","_controllingDeferred","_registrationTime","_ownSWs","_onUpdateFound","registration","_registration","installingSW","installing","updateLikelyTriggeredExternally","_scriptURL","toString","performance","now","_externalSW","_sw","serviceWorker","controller","_onStateChange","originalEvent","state","isExternal","eventProps","_isUpdate","isUpdate","_waitingTimeout","setTimeout","waiting","clearTimeout","_compatibleControllingSW","_onControllerChange","_onMessage","ports","source","getSW","register","immediate","document","readyState","res","window","Boolean","_getControllingSWIfCompatible","_registerScript","once","waitingSW","wasWaitingBeforeRegister","currentPageIsOutOfScope","scopeURL","scope","baseURI","scopeURLBasePath","pathname","startsWith","update","active","controlling","undefined","messageSkipWaiting","reg"],"mappings":"AACA;AACA,IAAI;AACAA,EAAAA,IAAI,CAAC,sBAAsB,CAAC,IAAIC,CAAC,EAAE;AACvC,CAAC,CACD,OAAOC,CAAC,EAAE,CAAE;;ACLZ;AACA;;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,SAASA,CAACC,EAAE,EAAEC,IAAI,EAAE;AACzB,EAAA,OAAO,IAAIC,OAAO,CAAEC,OAAO,IAAK;AAC5B,IAAA,MAAMC,cAAc,GAAG,IAAIC,cAAc,EAAE;AAC3CD,IAAAA,cAAc,CAACE,KAAK,CAACC,SAAS,GAAIC,KAAK,IAAK;AACxCL,MAAAA,OAAO,CAACK,KAAK,CAACP,IAAI,CAAC;IACvB,CAAC;IACDD,EAAE,CAACS,WAAW,CAACR,IAAI,EAAE,CAACG,cAAc,CAACM,KAAK,CAAC,CAAC;AAChD,EAAA,CAAC,CAAC;AACN;;AC/BA;AACA,IAAI;AACAd,EAAAA,IAAI,CAAC,oBAAoB,CAAC,IAAIC,CAAC,EAAE;AACrC,CAAC,CACD,OAAOC,CAAC,EAAE,CAAE;;ACLZ;AACA;;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMa,QAAQ,CAAC;AACX;AACJ;AACA;AACIC,EAAAA,WAAWA,GAAG;IACV,IAAI,CAACC,OAAO,GAAG,IAAIX,OAAO,CAAC,CAAC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KAAK,CAAC;AACvB,MAAA;AACA;AACA,MAAA,MAAMA,KAAK;AACf,IAAA;AACJ,EAAA;AACJ;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;"} \ No newline at end of file diff --git a/node_modules/workbox-window/build/workbox-window.dev.umd.js b/node_modules/workbox-window/build/workbox-window.dev.umd.js new file mode 100644 index 0000000000000000000000000000000000000000..9a3e40a8dfa12f71559febb7a9523874c8dc9723 --- /dev/null +++ b/node_modules/workbox-window/build/workbox-window.dev.umd.js @@ -0,0 +1,1007 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.workbox = {})); +})(this, (function (exports) { 'use strict'; + + // @ts-ignore + try { + self['workbox:window:7.4.0'] && _(); + } catch (e) {} + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Sends a data object to a service worker via `postMessage` and resolves with + * a response (if any). + * + * A response can be set in a message handler in the service worker by + * calling `event.ports[0].postMessage(...)`, which will resolve the promise + * returned by `messageSW()`. If no response is set, the promise will not + * resolve. + * + * @param {ServiceWorker} sw The service worker to send the message to. + * @param {Object} data An object to send to the service worker. + * @return {Promise} + * @memberof workbox-window + */ + // Better not change type of data. + // eslint-disable-next-line @typescript-eslint/ban-types + function messageSW(sw, data) { + return new Promise(function (resolve) { + var messageChannel = new MessageChannel(); + messageChannel.port1.onmessage = function (event) { + resolve(event.data); + }; + sw.postMessage(data, [messageChannel.port2]); + }); + } + + function _arrayLikeToArray(r, a) { + (null == a || a > r.length) && (a = r.length); + for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; + return n; + } + function _defineProperties(e, r) { + for (var t = 0; t < r.length; t++) { + var o = r[t]; + o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); + } + } + function _createClass(e, r, t) { + return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { + writable: false + }), e; + } + function _createForOfIteratorHelperLoose(r, e) { + var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; + if (t) return (t = t.call(r)).next.bind(t); + if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) { + t && (r = t); + var o = 0; + return function () { + return o >= r.length ? { + done: true + } : { + done: false, + value: r[o++] + }; + }; + } + throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + function _inheritsLoose(t, o) { + t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); + } + function _setPrototypeOf(t, e) { + return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { + return t.__proto__ = e, t; + }, _setPrototypeOf(t, e); + } + function _toPrimitive(t, r) { + if ("object" != typeof t || !t) return t; + var e = t[Symbol.toPrimitive]; + if (void 0 !== e) { + var i = e.call(t, r); + if ("object" != typeof i) return i; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (String )(t); + } + function _toPropertyKey(t) { + var i = _toPrimitive(t, "string"); + return "symbol" == typeof i ? i : i + ""; + } + function _unsupportedIterableToArray(r, a) { + if (r) { + if ("string" == typeof r) return _arrayLikeToArray(r, a); + var t = {}.toString.call(r).slice(8, -1); + return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; + } + } + + // @ts-ignore + try { + self['workbox:core:7.4.0'] && _(); + } catch (e) {} + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * The Deferred class composes Promises in a way that allows for them to be + * resolved or rejected from outside the constructor. In most cases promises + * should be used directly, but Deferreds can be necessary when the logic to + * resolve a promise must be separate. + * + * @private + */ + var Deferred = + /** + * Creates a promise and exposes its resolve and reject functions as methods. + */ + function Deferred() { + var _this = this; + this.promise = new Promise(function (resolve, reject) { + _this.resolve = resolve; + _this.reject = reject; + }); + }; + + /* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * A helper function that prevents a promise from being flagged as unused. + * + * @private + **/ + function dontWaitFor(promise) { + // Effective no-op. + void promise.then(function () {}); + } + + /* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + var logger = function () { + // Don't overwrite this value if it's already set. + // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923 + if (!('__WB_DISABLE_DEV_LOGS' in globalThis)) { + self.__WB_DISABLE_DEV_LOGS = false; + } + var inGroup = false; + var methodToColorMap = { + debug: "#7f8c8d", + log: "#2ecc71", + warn: "#f39c12", + error: "#c0392b", + groupCollapsed: "#3498db", + groupEnd: null // No colored prefix on groupEnd + }; + var print = function print(method, args) { + var _console2; + if (self.__WB_DISABLE_DEV_LOGS) { + return; + } + if (method === 'groupCollapsed') { + // Safari doesn't print all console.groupCollapsed() arguments: + // https://bugs.webkit.org/show_bug.cgi?id=182754 + if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) { + var _console; + (_console = console)[method].apply(_console, args); + return; + } + } + var 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. + var logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')]; + (_console2 = console)[method].apply(_console2, logPrefix.concat(args)); + if (method === 'groupCollapsed') { + inGroup = true; + } + if (method === 'groupEnd') { + inGroup = false; + } + }; + // eslint-disable-next-line @typescript-eslint/ban-types + var api = {}; + var loggerMethods = Object.keys(methodToColorMap); + var _loop = function _loop() { + var key = _loggerMethods[_i]; + var method = key; + api[method] = function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + print(method, args); + }; + }; + for (var _i = 0, _loggerMethods = loggerMethods; _i < _loggerMethods.length; _i++) { + _loop(); + } + return api; + }(); + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * A minimal `EventTarget` shim. + * This is necessary because not all browsers support constructable + * `EventTarget`, so using a real `EventTarget` will error. + * @private + */ + var WorkboxEventTarget = /*#__PURE__*/function () { + function WorkboxEventTarget() { + this._eventListenerRegistry = new Map(); + } + /** + * @param {string} type + * @param {Function} listener + * @private + */ + var _proto = WorkboxEventTarget.prototype; + _proto.addEventListener = function addEventListener(type, listener) { + var foo = this._getEventListenersByType(type); + foo.add(listener); + } + /** + * @param {string} type + * @param {Function} listener + * @private + */; + _proto.removeEventListener = function removeEventListener(type, listener) { + this._getEventListenersByType(type).delete(listener); + } + /** + * @param {Object} event + * @private + */; + _proto.dispatchEvent = function dispatchEvent(event) { + event.target = this; + var listeners = this._getEventListenersByType(event.type); + for (var _iterator = _createForOfIteratorHelperLoose(listeners), _step; !(_step = _iterator()).done;) { + var listener = _step.value; + listener(event); + } + } + /** + * Returns a Set of listeners associated with the passed event type. + * If no handlers have been registered, an empty Set is returned. + * + * @param {string} type The event type. + * @return {Set} An array of handler functions. + * @private + */; + _proto._getEventListenersByType = function _getEventListenersByType(type) { + if (!this._eventListenerRegistry.has(type)) { + this._eventListenerRegistry.set(type, new Set()); + } + return this._eventListenerRegistry.get(type); + }; + return WorkboxEventTarget; + }(); + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Returns true if two URLs have the same `.href` property. The URLS can be + * relative, and if they are the current location href is used to resolve URLs. + * + * @private + * @param {string} url1 + * @param {string} url2 + * @return {boolean} + */ + function urlsMatch(url1, url2) { + var _location = location, + href = _location.href; + return new URL(url1, href).href === new URL(url2, href).href; + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * A minimal `Event` subclass shim. + * This doesn't *actually* subclass `Event` because not all browsers support + * constructable `EventTarget`, and using a real `Event` will error. + * @private + */ + var WorkboxEvent = function WorkboxEvent(type, props) { + this.type = type; + Object.assign(this, props); + }; + + // The time a SW must be in the waiting phase before we can conclude + // `skipWaiting()` wasn't called. This 200 amount wasn't scientifically + // chosen, but it seems to avoid false positives in my testing. + + function _await(value, then, direct) { + if (!value || !value.then) { + value = Promise.resolve(value); + } + return then ? value.then(then) : value; + } + var WAITING_TIMEOUT_DURATION = 200; + // The amount of time after a registration that we can reasonably conclude + // that the registration didn't trigger an update. + + function _async(f) { + return function () { + for (var args = [], i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; + } + try { + return Promise.resolve(f.apply(this, args)); + } catch (e) { + return Promise.reject(e); + } + }; + } + var REGISTRATION_TIMEOUT_DURATION = 60000; + // The de facto standard message that a service worker should be listening for + // to trigger a call to skipWaiting(). + + function _empty() {} + var SKIP_WAITING_MESSAGE = { + type: 'SKIP_WAITING' + }; + /** + * A class to aid in handling service worker registration, updates, and + * reacting to service worker lifecycle events. + * + * @fires {@link workbox-window.Workbox#message} + * @fires {@link workbox-window.Workbox#installed} + * @fires {@link workbox-window.Workbox#waiting} + * @fires {@link workbox-window.Workbox#controlling} + * @fires {@link workbox-window.Workbox#activated} + * @fires {@link workbox-window.Workbox#redundant} + * @memberof workbox-window + */ + + function _awaitIgnored(value, direct) { + { + return value && value.then ? value.then(_empty) : Promise.resolve(); + } + } + var Workbox = /*#__PURE__*/function (_WorkboxEventTarget) { + /** + * Creates a new Workbox instance with a script URL and service worker + * options. The script URL and options are the same as those used when + * calling [navigator.serviceWorker.register(scriptURL, options)](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register). + * + * @param {string|TrustedScriptURL} scriptURL The service worker script + * associated with this instance. Using a + * [`TrustedScriptURL`](https://web.dev/trusted-types/) is supported. + * @param {Object} [registerOptions] The service worker options associated + * with this instance. + */ + // eslint-disable-next-line @typescript-eslint/ban-types + function Workbox(scriptURL, registerOptions) { + var _this; + if (registerOptions === void 0) { + registerOptions = {}; + } + _this = _WorkboxEventTarget.call(this) || this; + _this._registerOptions = {}; + _this._updateFoundCount = 0; + // Deferreds we can resolve later. + _this._swDeferred = new Deferred(); + _this._activeDeferred = new Deferred(); + _this._controllingDeferred = new Deferred(); + _this._registrationTime = 0; + _this._ownSWs = new Set(); + /** + * @private + */ + _this._onUpdateFound = function () { + // `this._registration` will never be `undefined` after an update is found. + var registration = _this._registration; + var installingSW = registration.installing; + // If the script URL passed to `navigator.serviceWorker.register()` is + // different from the current controlling SW's script URL, we know any + // successful registration calls will trigger an `updatefound` event. + // But if the registered script URL is the same as the current controlling + // SW's script URL, we'll only get an `updatefound` event if the file + // changed since it was last registered. This can be a problem if the user + // opens up the same page in a different tab, and that page registers + // a SW that triggers an update. It's a problem because this page has no + // good way of knowing whether the `updatefound` event came from the SW + // script it registered or from a registration attempt made by a newer + // version of the page running in another tab. + // To minimize the possibility of a false positive, we use the logic here: + var updateLikelyTriggeredExternally = + // Since we enforce only calling `register()` once, and since we don't + // add the `updatefound` event listener until the `register()` call, if + // `_updateFoundCount` is > 0 then it means this method has already + // been called, thus this SW must be external + _this._updateFoundCount > 0 || + // If the script URL of the installing SW is different from this + // instance's script URL, we know it's definitely not from our + // registration. + !urlsMatch(installingSW.scriptURL, _this._scriptURL.toString()) || + // If all of the above are false, then we use a time-based heuristic: + // Any `updatefound` event that occurs long after our registration is + // assumed to be external. + performance.now() > _this._registrationTime + REGISTRATION_TIMEOUT_DURATION ? + // If any of the above are not true, we assume the update was + // triggered by this instance. + true : false; + if (updateLikelyTriggeredExternally) { + _this._externalSW = installingSW; + registration.removeEventListener('updatefound', _this._onUpdateFound); + } else { + // If the update was not triggered externally we know the installing + // SW is the one we registered, so we set it. + _this._sw = installingSW; + _this._ownSWs.add(installingSW); + _this._swDeferred.resolve(installingSW); + // The `installing` state isn't something we have a dedicated + // callback for, but we do log messages for it in development. + { + if (navigator.serviceWorker.controller) { + logger.log('Updated service worker found. Installing now...'); + } else { + logger.log('Service worker is installing...'); + } + } + } + // Increment the `updatefound` count, so future invocations of this + // method can be sure they were triggered externally. + ++_this._updateFoundCount; + // Add a `statechange` listener regardless of whether this update was + // triggered externally, since we have callbacks for both. + installingSW.addEventListener('statechange', _this._onStateChange); + }; + /** + * @private + * @param {Event} originalEvent + */ + _this._onStateChange = function (originalEvent) { + // `this._registration` will never be `undefined` after an update is found. + var registration = _this._registration; + var sw = originalEvent.target; + var state = sw.state; + var isExternal = sw === _this._externalSW; + var eventProps = { + sw: sw, + isExternal: isExternal, + originalEvent: originalEvent + }; + if (!isExternal && _this._isUpdate) { + eventProps.isUpdate = true; + } + _this.dispatchEvent(new WorkboxEvent(state, eventProps)); + if (state === 'installed') { + // This timeout is used to ignore cases where the service worker calls + // `skipWaiting()` in the install event, thus moving it directly in the + // activating state. (Since all service workers *must* go through the + // waiting phase, the only way to detect `skipWaiting()` called in the + // install event is to observe that the time spent in the waiting phase + // is very short.) + // NOTE: we don't need separate timeouts for the own and external SWs + // since they can't go through these phases at the same time. + _this._waitingTimeout = self.setTimeout(function () { + // Ensure the SW is still waiting (it may now be redundant). + if (state === 'installed' && registration.waiting === sw) { + _this.dispatchEvent(new WorkboxEvent('waiting', eventProps)); + { + if (isExternal) { + logger.warn('An external service worker has installed but is ' + 'waiting for this client to close before activating...'); + } else { + logger.warn('The service worker has installed but is waiting ' + 'for existing clients to close before activating...'); + } + } + } + }, WAITING_TIMEOUT_DURATION); + } else if (state === 'activating') { + clearTimeout(_this._waitingTimeout); + if (!isExternal) { + _this._activeDeferred.resolve(sw); + } + } + { + switch (state) { + case 'installed': + if (isExternal) { + logger.warn('An external service worker has installed. ' + 'You may want to suggest users reload this page.'); + } else { + logger.log('Registered service worker installed.'); + } + break; + case 'activated': + if (isExternal) { + logger.warn('An external service worker has activated.'); + } else { + logger.log('Registered service worker activated.'); + if (sw !== navigator.serviceWorker.controller) { + logger.warn('The registered service worker is active but ' + 'not yet controlling the page. Reload or run ' + '`clients.claim()` in the service worker.'); + } + } + break; + case 'redundant': + if (sw === _this._compatibleControllingSW) { + logger.log('Previously controlling service worker now redundant!'); + } else if (!isExternal) { + logger.log('Registered service worker now redundant!'); + } + break; + } + } + }; + /** + * @private + * @param {Event} originalEvent + */ + _this._onControllerChange = function (originalEvent) { + var sw = _this._sw; + var isExternal = sw !== navigator.serviceWorker.controller; + // Unconditionally dispatch the controlling event, with isExternal set + // to distinguish between controller changes due to the initial registration + // vs. an update-check or other tab's registration. + // See https://github.com/GoogleChrome/workbox/issues/2786 + _this.dispatchEvent(new WorkboxEvent('controlling', { + isExternal: isExternal, + originalEvent: originalEvent, + sw: sw, + isUpdate: _this._isUpdate + })); + if (!isExternal) { + { + logger.log('Registered service worker now controlling this page.'); + } + _this._controllingDeferred.resolve(sw); + } + }; + /** + * @private + * @param {Event} originalEvent + */ + _this._onMessage = _async(function (originalEvent) { + // Can't change type 'any' of data. + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + var data = originalEvent.data, + ports = originalEvent.ports, + source = originalEvent.source; + // Wait until there's an "own" service worker. This is used to buffer + // `message` events that may be received prior to calling `register()`. + return _await(_this.getSW(), function () { + if (_this._ownSWs.has(source)) { + _this.dispatchEvent(new WorkboxEvent('message', { + // Can't change type 'any' of data. + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + data: data, + originalEvent: originalEvent, + ports: ports, + sw: source + })); + } + }); // If the service worker that sent the message is in the list of own + // service workers for this instance, dispatch a `message` event. + // NOTE: we check for all previously owned service workers rather than + // just the current one because some messages (e.g. cache updates) use + // a timeout when sent and may be delayed long enough for a service worker + // update to be found. + }); + _this._scriptURL = scriptURL; + _this._registerOptions = registerOptions; + // Add a message listener immediately since messages received during + // page load are buffered only until the DOMContentLoaded event: + // https://github.com/GoogleChrome/workbox/issues/2202 + navigator.serviceWorker.addEventListener('message', _this._onMessage); + return _this; + } + /** + * Registers a service worker for this instances script URL and service + * worker options. By default this method delays registration until after + * the window has loaded. + * + * @param {Object} [options] + * @param {Function} [options.immediate=false] Setting this to true will + * register the service worker immediately, even if the window has + * not loaded (not recommended). + */ + _inheritsLoose(Workbox, _WorkboxEventTarget); + var _proto = Workbox.prototype; + _proto.register = function register(_temp) { + var _ref = _temp === void 0 ? {} : _temp, + _ref$immediate = _ref.immediate, + immediate = _ref$immediate === void 0 ? false : _ref$immediate; + try { + var _this2 = this; + if ("dev" !== 'production') { + if (_this2._registrationTime) { + logger.error('Cannot re-register a Workbox instance after it has ' + 'been registered. Create a new instance instead.'); + return _await(); + } + } + return _await(_invoke(function () { + if (!immediate && document.readyState !== 'complete') { + return _awaitIgnored(new Promise(function (res) { + return window.addEventListener('load', res); + })); + } + }, function () { + // Set this flag to true if any service worker was controlling the page + // at registration time. + _this2._isUpdate = Boolean(navigator.serviceWorker.controller); + // Before registering, attempt to determine if a SW is already controlling + // the page, and if that SW script (and version, if specified) matches this + // instance's script. + _this2._compatibleControllingSW = _this2._getControllingSWIfCompatible(); + return _await(_this2._registerScript(), function (_this2$_registerScrip) { + _this2._registration = _this2$_registerScrip; + // If we have a compatible controller, store the controller as the "own" + // SW, resolve active/controlling deferreds and add necessary listeners. + if (_this2._compatibleControllingSW) { + _this2._sw = _this2._compatibleControllingSW; + _this2._activeDeferred.resolve(_this2._compatibleControllingSW); + _this2._controllingDeferred.resolve(_this2._compatibleControllingSW); + _this2._compatibleControllingSW.addEventListener('statechange', _this2._onStateChange, { + once: true + }); + } + // If there's a waiting service worker with a matching URL before the + // `updatefound` event fires, it likely means that this site is open + // in another tab, or the user refreshed the page (and thus the previous + // page wasn't fully unloaded before this page started loading). + // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting + var waitingSW = _this2._registration.waiting; + if (waitingSW && urlsMatch(waitingSW.scriptURL, _this2._scriptURL.toString())) { + // Store the waiting SW as the "own" Sw, even if it means overwriting + // a compatible controller. + _this2._sw = waitingSW; + // Run this in the next microtask, so any code that adds an event + // listener after awaiting `register()` will get this event. + dontWaitFor(Promise.resolve().then(function () { + _this2.dispatchEvent(new WorkboxEvent('waiting', { + sw: waitingSW, + wasWaitingBeforeRegister: true + })); + if ("dev" !== 'production') { + logger.warn('A service worker was already waiting to activate ' + 'before this script was registered...'); + } + })); + } + // If an "own" SW is already set, resolve the deferred. + if (_this2._sw) { + _this2._swDeferred.resolve(_this2._sw); + _this2._ownSWs.add(_this2._sw); + } + if ("dev" !== 'production') { + logger.log('Successfully registered service worker.', _this2._scriptURL.toString()); + if (navigator.serviceWorker.controller) { + if (_this2._compatibleControllingSW) { + logger.debug('A service worker with the same script URL ' + 'is already controlling this page.'); + } else { + logger.debug('A service worker with a different script URL is ' + 'currently controlling the page. The browser is now fetching ' + 'the new script now...'); + } + } + var currentPageIsOutOfScope = function currentPageIsOutOfScope() { + var scopeURL = new URL(_this2._registerOptions.scope || _this2._scriptURL.toString(), document.baseURI); + var scopeURLBasePath = new URL('./', scopeURL.href).pathname; + return !location.pathname.startsWith(scopeURLBasePath); + }; + if (currentPageIsOutOfScope()) { + logger.warn('The current page is not in scope for the registered ' + 'service worker. Was this a mistake?'); + } + } + _this2._registration.addEventListener('updatefound', _this2._onUpdateFound); + navigator.serviceWorker.addEventListener('controllerchange', _this2._onControllerChange); + return _this2._registration; + }); + })); + } catch (e) { + return Promise.reject(e); + } + } + /** + * Checks for updates of the registered service worker. + */ + ; + _proto.update = function update() { + try { + var _this3 = this; + if (!_this3._registration) { + if ("dev" !== 'production') { + logger.error('Cannot update a Workbox instance without ' + 'being registered. Register the Workbox instance first.'); + } + return _await(); + } + // Try to update registration + return _await(_awaitIgnored(_this3._registration.update())); + } catch (e) { + return Promise.reject(e); + } + } + /** + * Resolves to the service worker registered by this instance as soon as it + * is active. If a service worker was already controlling at registration + * time then it will resolve to that if the script URLs (and optionally + * script versions) match, otherwise it will wait until an update is found + * and activates. + * + * @return {Promise} + */ + ; + /** + * Resolves with a reference to a service worker that matches the script URL + * of this instance, as soon as it's available. + * + * If, at registration time, there's already an active or waiting service + * worker with a matching script URL, it will be used (with the waiting + * service worker taking precedence over the active service worker if both + * match, since the waiting service worker would have been registered more + * recently). + * If there's no matching active or waiting service worker at registration + * time then the promise will not resolve until an update is found and starts + * installing, at which point the installing service worker is used. + * + * @return {Promise} + */ + _proto.getSW = function getSW() { + // If `this._sw` is set, resolve with that as we want `getSW()` to + // return the correct (new) service worker if an update is found. + return this._sw !== undefined ? Promise.resolve(this._sw) : this._swDeferred.promise; + } + /** + * Sends the passed data object to the service worker registered by this + * instance (via {@link workbox-window.Workbox#getSW}) and resolves + * with a response (if any). + * + * A response can be set in a message handler in the service worker by + * calling `event.ports[0].postMessage(...)`, which will resolve the promise + * returned by `messageSW()`. If no response is set, the promise will never + * resolve. + * + * @param {Object} data An object to send to the service worker + * @return {Promise} + */ + // We might be able to change the 'data' type to Record in the future. + // eslint-disable-next-line @typescript-eslint/ban-types + ; + _proto.messageSW = function messageSW$1(data) { + try { + var _this4 = this; + return _await(_this4.getSW(), function (sw) { + return messageSW(sw, data); + }); + } catch (e) { + return Promise.reject(e); + } + } + /** + * Sends a `{type: 'SKIP_WAITING'}` message to the service worker that's + * currently in the `waiting` state associated with the current registration. + * + * If there is no current registration or no service worker is `waiting`, + * calling this will have no effect. + */ + ; + _proto.messageSkipWaiting = function messageSkipWaiting() { + if (this._registration && this._registration.waiting) { + void messageSW(this._registration.waiting, SKIP_WAITING_MESSAGE); + } + } + /** + * Checks for a service worker already controlling the page and returns + * it if its script URL matches. + * + * @private + * @return {ServiceWorker|undefined} + */; + _proto._getControllingSWIfCompatible = function _getControllingSWIfCompatible() { + var controller = navigator.serviceWorker.controller; + if (controller && urlsMatch(controller.scriptURL, this._scriptURL.toString())) { + return controller; + } else { + return undefined; + } + } + /** + * Registers a service worker for this instances script URL and register + * options and tracks the time registration was complete. + * + * @private + */; + _proto._registerScript = function _registerScript() { + try { + var _this5 = this; + return _await(_catch(function () { + // this._scriptURL may be a TrustedScriptURL, but there's no support for + // passing that to register() in lib.dom right now. + // https://github.com/GoogleChrome/workbox/issues/2855 + return _await(navigator.serviceWorker.register(_this5._scriptURL, _this5._registerOptions), function (reg) { + // Keep track of when registration happened, so it can be used in the + // `this._onUpdateFound` heuristic. Also use the presence of this + // property as a way to see if `.register()` has been called. + _this5._registrationTime = performance.now(); + return reg; + }); + }, function (error) { + if ("dev" !== 'production') { + logger.error(error); + } + // Re-throw the error. + throw error; + })); + } catch (e) { + return Promise.reject(e); + } + }; + return _createClass(Workbox, [{ + key: "active", + get: function get() { + return this._activeDeferred.promise; + } + /** + * Resolves to the service worker registered by this instance as soon as it + * is controlling the page. If a service worker was already controlling at + * registration time then it will resolve to that if the script URLs (and + * optionally script versions) match, otherwise it will wait until an update + * is found and starts controlling the page. + * Note: the first time a service worker is installed it will active but + * not start controlling the page unless `clients.claim()` is called in the + * service worker. + * + * @return {Promise} + */ + }, { + key: "controlling", + get: function get() { + return this._controllingDeferred.promise; + } + }]); + }(WorkboxEventTarget); + function _invoke(body, then) { + var result = body(); + if (result && result.then) { + return result.then(then); + } + return then(result); + } // The jsdoc comments below outline the events this instance may dispatch: + // ----------------------------------------------------------------------- + /** + * The `message` event is dispatched any time a `postMessage` is received. + * + * @event workbox-window.Workbox#message + * @type {WorkboxEvent} + * @property {*} data The `data` property from the original `message` event. + * @property {Event} originalEvent The original [`message`]{@link https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent} + * event. + * @property {string} type `message`. + * @property {MessagePort[]} ports The `ports` value from `originalEvent`. + * @property {Workbox} target The `Workbox` instance. + */ + /** + * The `installed` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker} + * changes to `installed`. + * + * Then can happen either the very first time a service worker is installed, + * or after an update to the current service worker is found. In the case + * of an update being found, the event's `isUpdate` property will be `true`. + * + * @event workbox-window.Workbox#installed + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {string} type `installed`. + * @property {Workbox} target The `Workbox` instance. + */ + /** + * The `waiting` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw} + * changes to `installed` and then doesn't immediately change to `activating`. + * It may also be dispatched if a service worker with the same + * [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL} + * was already waiting when the {@link workbox-window.Workbox#register} + * method was called. + * + * @event workbox-window.Workbox#waiting + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event|undefined} originalEvent The original + * [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event, or `undefined` in the case where the service worker was waiting + * to before `.register()` was called. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {boolean|undefined} wasWaitingBeforeRegister True if a service worker with + * a matching `scriptURL` was already waiting when this `Workbox` + * instance called `register()`. + * @property {string} type `waiting`. + * @property {Workbox} target The `Workbox` instance. + */ + /** + * The `controlling` event is dispatched if a + * [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange} + * fires on the service worker [container]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer} + * and the [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL} + * of the new [controller]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller} + * matches the `scriptURL` of the `Workbox` instance's + * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}. + * + * @event workbox-window.Workbox#controlling + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this service worker was registered. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {string} type `controlling`. + * @property {Workbox} target The `Workbox` instance. + */ + /** + * The `activated` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker} + * changes to `activated`. + * + * @event workbox-window.Workbox#activated + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {string} type `activated`. + * @property {Workbox} target The `Workbox` instance. + */ + /** + * The `redundant` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw} + * changes to `redundant`. + * + * @event workbox-window.Workbox#redundant + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {string} type `redundant`. + * @property {Workbox} target The `Workbox` instance. + */ + function _catch(body, recover) { + try { + var result = body(); + } catch (e) { + return recover(e); + } + if (result && result.then) { + return result.then(void 0, recover); + } + return result; + } + + exports.Workbox = Workbox; + exports.WorkboxEvent = WorkboxEvent; + exports.messageSW = messageSW; + +})); +//# sourceMappingURL=workbox-window.dev.umd.js.map diff --git a/node_modules/workbox-window/build/workbox-window.dev.umd.js.map b/node_modules/workbox-window/build/workbox-window.dev.umd.js.map new file mode 100644 index 0000000000000000000000000000000000000000..255532956c38ece080b149b75b4026628d8e1034 --- /dev/null +++ b/node_modules/workbox-window/build/workbox-window.dev.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-window.dev.umd.js","sources":["../_version.js","../messageSW.js","../../workbox-core/_version.js","../../workbox-core/_private/Deferred.js","../../workbox-core/_private/dontWaitFor.js","../../workbox-core/_private/logger.js","../utils/WorkboxEventTarget.js","../utils/urlsMatch.js","../utils/WorkboxEvent.js","../Workbox.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:window:7.4.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport './_version.js';\n/**\n * Sends a data object to a service worker via `postMessage` and resolves with\n * a response (if any).\n *\n * A response can be set in a message handler in the service worker by\n * calling `event.ports[0].postMessage(...)`, which will resolve the promise\n * returned by `messageSW()`. If no response is set, the promise will not\n * resolve.\n *\n * @param {ServiceWorker} sw The service worker to send the message to.\n * @param {Object} data An object to send to the service worker.\n * @return {Promise}\n * @memberof workbox-window\n */\n// Better not change type of data.\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction messageSW(sw, data) {\n return new Promise((resolve) => {\n const messageChannel = new MessageChannel();\n messageChannel.port1.onmessage = (event) => {\n resolve(event.data);\n };\n sw.postMessage(data, [messageChannel.port2]);\n });\n}\nexport { messageSW };\n","\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:core:7.4.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 '../_version.js';\n/**\n * The Deferred class composes Promises in a way that allows for them to be\n * resolved or rejected from outside the constructor. In most cases promises\n * should be used directly, but Deferreds can be necessary when the logic to\n * resolve a promise must be separate.\n *\n * @private\n */\nclass Deferred {\n /**\n * Creates a promise and exposes its resolve and reject functions as methods.\n */\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\nexport { Deferred };\n","/*\n Copyright 2019 Google LLC\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';\n/**\n * A helper function that prevents a promise from being flagged as unused.\n *\n * @private\n **/\nexport function dontWaitFor(promise) {\n // Effective no-op.\n void promise.then(() => { });\n}\n","/*\n Copyright 2019 Google LLC\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';\nconst logger = (process.env.NODE_ENV === 'production'\n ? null\n : (() => {\n // Don't overwrite this value if it's already set.\n // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923\n if (!('__WB_DISABLE_DEV_LOGS' in globalThis)) {\n self.__WB_DISABLE_DEV_LOGS = false;\n }\n let inGroup = false;\n const methodToColorMap = {\n debug: `#7f8c8d`,\n log: `#2ecc71`,\n warn: `#f39c12`,\n error: `#c0392b`,\n groupCollapsed: `#3498db`,\n groupEnd: null, // No colored prefix on groupEnd\n };\n const print = function (method, args) {\n if (self.__WB_DISABLE_DEV_LOGS) {\n return;\n }\n if (method === 'groupCollapsed') {\n // Safari doesn't print all console.groupCollapsed() arguments:\n // https://bugs.webkit.org/show_bug.cgi?id=182754\n if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {\n console[method](...args);\n return;\n }\n }\n const styles = [\n `background: ${methodToColorMap[method]}`,\n `border-radius: 0.5em`,\n `color: white`,\n `font-weight: bold`,\n `padding: 2px 0.5em`,\n ];\n // When in a group, the workbox prefix is not displayed.\n const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')];\n console[method](...logPrefix, ...args);\n if (method === 'groupCollapsed') {\n inGroup = true;\n }\n if (method === 'groupEnd') {\n inGroup = false;\n }\n };\n // eslint-disable-next-line @typescript-eslint/ban-types\n const api = {};\n const loggerMethods = Object.keys(methodToColorMap);\n for (const key of loggerMethods) {\n const method = key;\n api[method] = (...args) => {\n print(method, args);\n };\n }\n return api;\n })());\nexport { logger };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\n/**\n * A minimal `EventTarget` shim.\n * This is necessary because not all browsers support constructable\n * `EventTarget`, so using a real `EventTarget` will error.\n * @private\n */\nexport class WorkboxEventTarget {\n constructor() {\n this._eventListenerRegistry = new Map();\n }\n /**\n * @param {string} type\n * @param {Function} listener\n * @private\n */\n addEventListener(type, listener) {\n const foo = this._getEventListenersByType(type);\n foo.add(listener);\n }\n /**\n * @param {string} type\n * @param {Function} listener\n * @private\n */\n removeEventListener(type, listener) {\n this._getEventListenersByType(type).delete(listener);\n }\n /**\n * @param {Object} event\n * @private\n */\n dispatchEvent(event) {\n event.target = this;\n const listeners = this._getEventListenersByType(event.type);\n for (const listener of listeners) {\n listener(event);\n }\n }\n /**\n * Returns a Set of listeners associated with the passed event type.\n * If no handlers have been registered, an empty Set is returned.\n *\n * @param {string} type The event type.\n * @return {Set} An array of handler functions.\n * @private\n */\n _getEventListenersByType(type) {\n if (!this._eventListenerRegistry.has(type)) {\n this._eventListenerRegistry.set(type, new Set());\n }\n return this._eventListenerRegistry.get(type);\n }\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * Returns true if two URLs have the same `.href` property. The URLS can be\n * relative, and if they are the current location href is used to resolve URLs.\n *\n * @private\n * @param {string} url1\n * @param {string} url2\n * @return {boolean}\n */\nexport function urlsMatch(url1, url2) {\n const { href } = location;\n return new URL(url1, href).href === new URL(url2, href).href;\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * A minimal `Event` subclass shim.\n * This doesn't *actually* subclass `Event` because not all browsers support\n * constructable `EventTarget`, and using a real `Event` will error.\n * @private\n */\nexport class WorkboxEvent {\n constructor(type, props) {\n this.type = type;\n Object.assign(this, props);\n }\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { Deferred } from 'workbox-core/_private/Deferred.js';\nimport { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { messageSW } from './messageSW.js';\nimport { WorkboxEventTarget } from './utils/WorkboxEventTarget.js';\nimport { urlsMatch } from './utils/urlsMatch.js';\nimport { WorkboxEvent } from './utils/WorkboxEvent.js';\nimport './_version.js';\n// The time a SW must be in the waiting phase before we can conclude\n// `skipWaiting()` wasn't called. This 200 amount wasn't scientifically\n// chosen, but it seems to avoid false positives in my testing.\nconst WAITING_TIMEOUT_DURATION = 200;\n// The amount of time after a registration that we can reasonably conclude\n// that the registration didn't trigger an update.\nconst REGISTRATION_TIMEOUT_DURATION = 60000;\n// The de facto standard message that a service worker should be listening for\n// to trigger a call to skipWaiting().\nconst SKIP_WAITING_MESSAGE = { type: 'SKIP_WAITING' };\n/**\n * A class to aid in handling service worker registration, updates, and\n * reacting to service worker lifecycle events.\n *\n * @fires {@link workbox-window.Workbox#message}\n * @fires {@link workbox-window.Workbox#installed}\n * @fires {@link workbox-window.Workbox#waiting}\n * @fires {@link workbox-window.Workbox#controlling}\n * @fires {@link workbox-window.Workbox#activated}\n * @fires {@link workbox-window.Workbox#redundant}\n * @memberof workbox-window\n */\nclass Workbox extends WorkboxEventTarget {\n /**\n * Creates a new Workbox instance with a script URL and service worker\n * options. The script URL and options are the same as those used when\n * calling [navigator.serviceWorker.register(scriptURL, options)](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register).\n *\n * @param {string|TrustedScriptURL} scriptURL The service worker script\n * associated with this instance. Using a\n * [`TrustedScriptURL`](https://web.dev/trusted-types/) is supported.\n * @param {Object} [registerOptions] The service worker options associated\n * with this instance.\n */\n // eslint-disable-next-line @typescript-eslint/ban-types\n constructor(scriptURL, registerOptions = {}) {\n super();\n this._registerOptions = {};\n this._updateFoundCount = 0;\n // Deferreds we can resolve later.\n this._swDeferred = new Deferred();\n this._activeDeferred = new Deferred();\n this._controllingDeferred = new Deferred();\n this._registrationTime = 0;\n this._ownSWs = new Set();\n /**\n * @private\n */\n this._onUpdateFound = () => {\n // `this._registration` will never be `undefined` after an update is found.\n const registration = this._registration;\n const installingSW = registration.installing;\n // If the script URL passed to `navigator.serviceWorker.register()` is\n // different from the current controlling SW's script URL, we know any\n // successful registration calls will trigger an `updatefound` event.\n // But if the registered script URL is the same as the current controlling\n // SW's script URL, we'll only get an `updatefound` event if the file\n // changed since it was last registered. This can be a problem if the user\n // opens up the same page in a different tab, and that page registers\n // a SW that triggers an update. It's a problem because this page has no\n // good way of knowing whether the `updatefound` event came from the SW\n // script it registered or from a registration attempt made by a newer\n // version of the page running in another tab.\n // To minimize the possibility of a false positive, we use the logic here:\n const updateLikelyTriggeredExternally = \n // Since we enforce only calling `register()` once, and since we don't\n // add the `updatefound` event listener until the `register()` call, if\n // `_updateFoundCount` is > 0 then it means this method has already\n // been called, thus this SW must be external\n this._updateFoundCount > 0 ||\n // If the script URL of the installing SW is different from this\n // instance's script URL, we know it's definitely not from our\n // registration.\n !urlsMatch(installingSW.scriptURL, this._scriptURL.toString()) ||\n // If all of the above are false, then we use a time-based heuristic:\n // Any `updatefound` event that occurs long after our registration is\n // assumed to be external.\n performance.now() > this._registrationTime + REGISTRATION_TIMEOUT_DURATION\n ? // If any of the above are not true, we assume the update was\n // triggered by this instance.\n true\n : false;\n if (updateLikelyTriggeredExternally) {\n this._externalSW = installingSW;\n registration.removeEventListener('updatefound', this._onUpdateFound);\n }\n else {\n // If the update was not triggered externally we know the installing\n // SW is the one we registered, so we set it.\n this._sw = installingSW;\n this._ownSWs.add(installingSW);\n this._swDeferred.resolve(installingSW);\n // The `installing` state isn't something we have a dedicated\n // callback for, but we do log messages for it in development.\n if (process.env.NODE_ENV !== 'production') {\n if (navigator.serviceWorker.controller) {\n logger.log('Updated service worker found. Installing now...');\n }\n else {\n logger.log('Service worker is installing...');\n }\n }\n }\n // Increment the `updatefound` count, so future invocations of this\n // method can be sure they were triggered externally.\n ++this._updateFoundCount;\n // Add a `statechange` listener regardless of whether this update was\n // triggered externally, since we have callbacks for both.\n installingSW.addEventListener('statechange', this._onStateChange);\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onStateChange = (originalEvent) => {\n // `this._registration` will never be `undefined` after an update is found.\n const registration = this._registration;\n const sw = originalEvent.target;\n const { state } = sw;\n const isExternal = sw === this._externalSW;\n const eventProps = {\n sw,\n isExternal,\n originalEvent,\n };\n if (!isExternal && this._isUpdate) {\n eventProps.isUpdate = true;\n }\n this.dispatchEvent(new WorkboxEvent(state, eventProps));\n if (state === 'installed') {\n // This timeout is used to ignore cases where the service worker calls\n // `skipWaiting()` in the install event, thus moving it directly in the\n // activating state. (Since all service workers *must* go through the\n // waiting phase, the only way to detect `skipWaiting()` called in the\n // install event is to observe that the time spent in the waiting phase\n // is very short.)\n // NOTE: we don't need separate timeouts for the own and external SWs\n // since they can't go through these phases at the same time.\n this._waitingTimeout = self.setTimeout(() => {\n // Ensure the SW is still waiting (it may now be redundant).\n if (state === 'installed' && registration.waiting === sw) {\n this.dispatchEvent(new WorkboxEvent('waiting', eventProps));\n if (process.env.NODE_ENV !== 'production') {\n if (isExternal) {\n logger.warn('An external service worker has installed but is ' +\n 'waiting for this client to close before activating...');\n }\n else {\n logger.warn('The service worker has installed but is waiting ' +\n 'for existing clients to close before activating...');\n }\n }\n }\n }, WAITING_TIMEOUT_DURATION);\n }\n else if (state === 'activating') {\n clearTimeout(this._waitingTimeout);\n if (!isExternal) {\n this._activeDeferred.resolve(sw);\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n switch (state) {\n case 'installed':\n if (isExternal) {\n logger.warn('An external service worker has installed. ' +\n 'You may want to suggest users reload this page.');\n }\n else {\n logger.log('Registered service worker installed.');\n }\n break;\n case 'activated':\n if (isExternal) {\n logger.warn('An external service worker has activated.');\n }\n else {\n logger.log('Registered service worker activated.');\n if (sw !== navigator.serviceWorker.controller) {\n logger.warn('The registered service worker is active but ' +\n 'not yet controlling the page. Reload or run ' +\n '`clients.claim()` in the service worker.');\n }\n }\n break;\n case 'redundant':\n if (sw === this._compatibleControllingSW) {\n logger.log('Previously controlling service worker now redundant!');\n }\n else if (!isExternal) {\n logger.log('Registered service worker now redundant!');\n }\n break;\n }\n }\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onControllerChange = (originalEvent) => {\n const sw = this._sw;\n const isExternal = sw !== navigator.serviceWorker.controller;\n // Unconditionally dispatch the controlling event, with isExternal set\n // to distinguish between controller changes due to the initial registration\n // vs. an update-check or other tab's registration.\n // See https://github.com/GoogleChrome/workbox/issues/2786\n this.dispatchEvent(new WorkboxEvent('controlling', {\n isExternal,\n originalEvent,\n sw,\n isUpdate: this._isUpdate,\n }));\n if (!isExternal) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Registered service worker now controlling this page.');\n }\n this._controllingDeferred.resolve(sw);\n }\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onMessage = async (originalEvent) => {\n // Can't change type 'any' of data.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const { data, ports, source } = originalEvent;\n // Wait until there's an \"own\" service worker. This is used to buffer\n // `message` events that may be received prior to calling `register()`.\n await this.getSW();\n // If the service worker that sent the message is in the list of own\n // service workers for this instance, dispatch a `message` event.\n // NOTE: we check for all previously owned service workers rather than\n // just the current one because some messages (e.g. cache updates) use\n // a timeout when sent and may be delayed long enough for a service worker\n // update to be found.\n if (this._ownSWs.has(source)) {\n this.dispatchEvent(new WorkboxEvent('message', {\n // Can't change type 'any' of data.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n data,\n originalEvent,\n ports,\n sw: source,\n }));\n }\n };\n this._scriptURL = scriptURL;\n this._registerOptions = registerOptions;\n // Add a message listener immediately since messages received during\n // page load are buffered only until the DOMContentLoaded event:\n // https://github.com/GoogleChrome/workbox/issues/2202\n navigator.serviceWorker.addEventListener('message', this._onMessage);\n }\n /**\n * Registers a service worker for this instances script URL and service\n * worker options. By default this method delays registration until after\n * the window has loaded.\n *\n * @param {Object} [options]\n * @param {Function} [options.immediate=false] Setting this to true will\n * register the service worker immediately, even if the window has\n * not loaded (not recommended).\n */\n async register({ immediate = false } = {}) {\n if (process.env.NODE_ENV !== 'production') {\n if (this._registrationTime) {\n logger.error('Cannot re-register a Workbox instance after it has ' +\n 'been registered. Create a new instance instead.');\n return;\n }\n }\n if (!immediate && document.readyState !== 'complete') {\n await new Promise((res) => window.addEventListener('load', res));\n }\n // Set this flag to true if any service worker was controlling the page\n // at registration time.\n this._isUpdate = Boolean(navigator.serviceWorker.controller);\n // Before registering, attempt to determine if a SW is already controlling\n // the page, and if that SW script (and version, if specified) matches this\n // instance's script.\n this._compatibleControllingSW = this._getControllingSWIfCompatible();\n this._registration = await this._registerScript();\n // If we have a compatible controller, store the controller as the \"own\"\n // SW, resolve active/controlling deferreds and add necessary listeners.\n if (this._compatibleControllingSW) {\n this._sw = this._compatibleControllingSW;\n this._activeDeferred.resolve(this._compatibleControllingSW);\n this._controllingDeferred.resolve(this._compatibleControllingSW);\n this._compatibleControllingSW.addEventListener('statechange', this._onStateChange, { once: true });\n }\n // If there's a waiting service worker with a matching URL before the\n // `updatefound` event fires, it likely means that this site is open\n // in another tab, or the user refreshed the page (and thus the previous\n // page wasn't fully unloaded before this page started loading).\n // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting\n const waitingSW = this._registration.waiting;\n if (waitingSW &&\n urlsMatch(waitingSW.scriptURL, this._scriptURL.toString())) {\n // Store the waiting SW as the \"own\" Sw, even if it means overwriting\n // a compatible controller.\n this._sw = waitingSW;\n // Run this in the next microtask, so any code that adds an event\n // listener after awaiting `register()` will get this event.\n dontWaitFor(Promise.resolve().then(() => {\n this.dispatchEvent(new WorkboxEvent('waiting', {\n sw: waitingSW,\n wasWaitingBeforeRegister: true,\n }));\n if (process.env.NODE_ENV !== 'production') {\n logger.warn('A service worker was already waiting to activate ' +\n 'before this script was registered...');\n }\n }));\n }\n // If an \"own\" SW is already set, resolve the deferred.\n if (this._sw) {\n this._swDeferred.resolve(this._sw);\n this._ownSWs.add(this._sw);\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Successfully registered service worker.', this._scriptURL.toString());\n if (navigator.serviceWorker.controller) {\n if (this._compatibleControllingSW) {\n logger.debug('A service worker with the same script URL ' +\n 'is already controlling this page.');\n }\n else {\n logger.debug('A service worker with a different script URL is ' +\n 'currently controlling the page. The browser is now fetching ' +\n 'the new script now...');\n }\n }\n const currentPageIsOutOfScope = () => {\n const scopeURL = new URL(this._registerOptions.scope || this._scriptURL.toString(), document.baseURI);\n const scopeURLBasePath = new URL('./', scopeURL.href).pathname;\n return !location.pathname.startsWith(scopeURLBasePath);\n };\n if (currentPageIsOutOfScope()) {\n logger.warn('The current page is not in scope for the registered ' +\n 'service worker. Was this a mistake?');\n }\n }\n this._registration.addEventListener('updatefound', this._onUpdateFound);\n navigator.serviceWorker.addEventListener('controllerchange', this._onControllerChange);\n return this._registration;\n }\n /**\n * Checks for updates of the registered service worker.\n */\n async update() {\n if (!this._registration) {\n if (process.env.NODE_ENV !== 'production') {\n logger.error('Cannot update a Workbox instance without ' +\n 'being registered. Register the Workbox instance first.');\n }\n return;\n }\n // Try to update registration\n await this._registration.update();\n }\n /**\n * Resolves to the service worker registered by this instance as soon as it\n * is active. If a service worker was already controlling at registration\n * time then it will resolve to that if the script URLs (and optionally\n * script versions) match, otherwise it will wait until an update is found\n * and activates.\n *\n * @return {Promise}\n */\n get active() {\n return this._activeDeferred.promise;\n }\n /**\n * Resolves to the service worker registered by this instance as soon as it\n * is controlling the page. If a service worker was already controlling at\n * registration time then it will resolve to that if the script URLs (and\n * optionally script versions) match, otherwise it will wait until an update\n * is found and starts controlling the page.\n * Note: the first time a service worker is installed it will active but\n * not start controlling the page unless `clients.claim()` is called in the\n * service worker.\n *\n * @return {Promise}\n */\n get controlling() {\n return this._controllingDeferred.promise;\n }\n /**\n * Resolves with a reference to a service worker that matches the script URL\n * of this instance, as soon as it's available.\n *\n * If, at registration time, there's already an active or waiting service\n * worker with a matching script URL, it will be used (with the waiting\n * service worker taking precedence over the active service worker if both\n * match, since the waiting service worker would have been registered more\n * recently).\n * If there's no matching active or waiting service worker at registration\n * time then the promise will not resolve until an update is found and starts\n * installing, at which point the installing service worker is used.\n *\n * @return {Promise}\n */\n getSW() {\n // If `this._sw` is set, resolve with that as we want `getSW()` to\n // return the correct (new) service worker if an update is found.\n return this._sw !== undefined\n ? Promise.resolve(this._sw)\n : this._swDeferred.promise;\n }\n /**\n * Sends the passed data object to the service worker registered by this\n * instance (via {@link workbox-window.Workbox#getSW}) and resolves\n * with a response (if any).\n *\n * A response can be set in a message handler in the service worker by\n * calling `event.ports[0].postMessage(...)`, which will resolve the promise\n * returned by `messageSW()`. If no response is set, the promise will never\n * resolve.\n *\n * @param {Object} data An object to send to the service worker\n * @return {Promise}\n */\n // We might be able to change the 'data' type to Record in the future.\n // eslint-disable-next-line @typescript-eslint/ban-types\n async messageSW(data) {\n const sw = await this.getSW();\n return messageSW(sw, data);\n }\n /**\n * Sends a `{type: 'SKIP_WAITING'}` message to the service worker that's\n * currently in the `waiting` state associated with the current registration.\n *\n * If there is no current registration or no service worker is `waiting`,\n * calling this will have no effect.\n */\n messageSkipWaiting() {\n if (this._registration && this._registration.waiting) {\n void messageSW(this._registration.waiting, SKIP_WAITING_MESSAGE);\n }\n }\n /**\n * Checks for a service worker already controlling the page and returns\n * it if its script URL matches.\n *\n * @private\n * @return {ServiceWorker|undefined}\n */\n _getControllingSWIfCompatible() {\n const controller = navigator.serviceWorker.controller;\n if (controller &&\n urlsMatch(controller.scriptURL, this._scriptURL.toString())) {\n return controller;\n }\n else {\n return undefined;\n }\n }\n /**\n * Registers a service worker for this instances script URL and register\n * options and tracks the time registration was complete.\n *\n * @private\n */\n async _registerScript() {\n try {\n // this._scriptURL may be a TrustedScriptURL, but there's no support for\n // passing that to register() in lib.dom right now.\n // https://github.com/GoogleChrome/workbox/issues/2855\n const reg = await navigator.serviceWorker.register(this._scriptURL, this._registerOptions);\n // Keep track of when registration happened, so it can be used in the\n // `this._onUpdateFound` heuristic. Also use the presence of this\n // property as a way to see if `.register()` has been called.\n this._registrationTime = performance.now();\n return reg;\n }\n catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n logger.error(error);\n }\n // Re-throw the error.\n throw error;\n }\n }\n}\nexport { Workbox };\n// The jsdoc comments below outline the events this instance may dispatch:\n// -----------------------------------------------------------------------\n/**\n * The `message` event is dispatched any time a `postMessage` is received.\n *\n * @event workbox-window.Workbox#message\n * @type {WorkboxEvent}\n * @property {*} data The `data` property from the original `message` event.\n * @property {Event} originalEvent The original [`message`]{@link https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent}\n * event.\n * @property {string} type `message`.\n * @property {MessagePort[]} ports The `ports` value from `originalEvent`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `installed` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}\n * changes to `installed`.\n *\n * Then can happen either the very first time a service worker is installed,\n * or after an update to the current service worker is found. In the case\n * of an update being found, the event's `isUpdate` property will be `true`.\n *\n * @event workbox-window.Workbox#installed\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `installed`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `waiting` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}\n * changes to `installed` and then doesn't immediately change to `activating`.\n * It may also be dispatched if a service worker with the same\n * [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}\n * was already waiting when the {@link workbox-window.Workbox#register}\n * method was called.\n *\n * @event workbox-window.Workbox#waiting\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event|undefined} originalEvent The original\n * [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event, or `undefined` in the case where the service worker was waiting\n * to before `.register()` was called.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {boolean|undefined} wasWaitingBeforeRegister True if a service worker with\n * a matching `scriptURL` was already waiting when this `Workbox`\n * instance called `register()`.\n * @property {string} type `waiting`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `controlling` event is dispatched if a\n * [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}\n * fires on the service worker [container]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer}\n * and the [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}\n * of the new [controller]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller}\n * matches the `scriptURL` of the `Workbox` instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}.\n *\n * @event workbox-window.Workbox#controlling\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this service worker was registered.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `controlling`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `activated` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}\n * changes to `activated`.\n *\n * @event workbox-window.Workbox#activated\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `activated`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `redundant` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}\n * changes to `redundant`.\n *\n * @event workbox-window.Workbox#redundant\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {string} type `redundant`.\n * @property {Workbox} target The `Workbox` instance.\n */\n"],"names":["self","_","e","messageSW","sw","data","Promise","resolve","messageChannel","MessageChannel","port1","onmessage","event","postMessage","port2","Deferred","_this","promise","reject","dontWaitFor","then","logger","globalThis","__WB_DISABLE_DEV_LOGS","inGroup","methodToColorMap","debug","log","warn","error","groupCollapsed","groupEnd","print","method","args","_console2","test","navigator","userAgent","_console","console","apply","styles","logPrefix","join","concat","api","loggerMethods","Object","keys","_loop","key","_loggerMethods","_i","_len","arguments","length","Array","_key","WorkboxEventTarget","_eventListenerRegistry","Map","_proto","prototype","addEventListener","type","listener","foo","_getEventListenersByType","add","removeEventListener","delete","dispatchEvent","target","listeners","_iterator","_createForOfIteratorHelperLoose","_step","done","value","has","set","Set","get","urlsMatch","url1","url2","_location","location","href","URL","WorkboxEvent","props","assign","_await","direct","WAITING_TIMEOUT_DURATION","_async","f","i","REGISTRATION_TIMEOUT_DURATION","_empty","SKIP_WAITING_MESSAGE","_awaitIgnored","Workbox","_WorkboxEventTarget","scriptURL","registerOptions","call","_registerOptions","_updateFoundCount","_swDeferred","_activeDeferred","_controllingDeferred","_registrationTime","_ownSWs","_onUpdateFound","registration","_registration","installingSW","installing","updateLikelyTriggeredExternally","_scriptURL","toString","performance","now","_externalSW","_sw","serviceWorker","controller","_onStateChange","originalEvent","state","isExternal","eventProps","_isUpdate","isUpdate","_waitingTimeout","setTimeout","waiting","clearTimeout","_compatibleControllingSW","_onControllerChange","_onMessage","ports","source","getSW","_inheritsLoose","register","_temp","_ref","_ref$immediate","immediate","_this2","process","_invoke","document","readyState","res","window","Boolean","_getControllingSWIfCompatible","_registerScript","_this2$_registerScrip","once","waitingSW","wasWaitingBeforeRegister","currentPageIsOutOfScope","scopeURL","scope","baseURI","scopeURLBasePath","pathname","startsWith","update","_this3","undefined","_this4","messageSkipWaiting","_this5","_catch","reg","_createClass","body","result","recover"],"mappings":";;;;;;IACA;IACA,IAAI;IACAA,EAAAA,IAAI,CAAC,sBAAsB,CAAC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;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IAzDO,SAAAJ,MAAAA,CAAgBG,IAAI,EAAEE,OAAO,EAAE;MACrC,IAAI;IACH,IAAA,IAAID,MAAM,GAAGD,IAAI,EAAE;MACpB,CAAC,CAAC,OAAMrL,CAAC,EAAE;QACV,OAAOuL,OAAO,CAACvL,CAAC,CAAC;IAClB,EAAA;IACA,EAAA,IAAIsL,MAAM,IAAIA,MAAM,CAACpK,IAAI,EAAE;QAC1B,OAAOoK,MAAM,CAACpK,IAAI,CAAC,MAAM,EAAEqK,OAAO,CAAC;IACpC,EAAA;IACA,EAAA,OAAOD,MAAM;IACd;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/workbox-window/build/workbox-window.prod.es5.mjs b/node_modules/workbox-window/build/workbox-window.prod.es5.mjs new file mode 100644 index 0000000000000000000000000000000000000000..52aae8a834033d8c3ab33fc68bf7a58ec225f5b2 --- /dev/null +++ b/node_modules/workbox-window/build/workbox-window.prod.es5.mjs @@ -0,0 +1,2 @@ +try{self["workbox:window:7.4.0"]&&_()}catch(n){}function n(n,t){return new Promise((function(r){var e=new MessageChannel;e.port1.onmessage=function(n){r(n.data)},n.postMessage(t,[e.port2])}))}function t(n,t){(null==t||t>n.length)&&(t=n.length);for(var r=0,e=Array(t);r=n.length?{done:!0}:{done:!1,value:n[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function i(n,t){return i=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,t){return n.__proto__=t,n},i(n,t)}function o(n){var t=function(n,t){if("object"!=typeof n||!n)return n;var r=n[Symbol.toPrimitive];if(void 0!==r){var e=r.call(n,t);if("object"!=typeof e)return e;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(n)}(n,"string");return"symbol"==typeof t?t:t+""}try{self["workbox:core:7.4.0"]&&_()}catch(n){}var u=function(){var n=this;this.promise=new Promise((function(t,r){n.resolve=t,n.reject=r}))};function a(n,t){var r=location.href;return new URL(n,r).href===new URL(t,r).href}var c=function(n,t){this.type=n,Object.assign(this,t)};function f(n,t,r){return n&&n.then||(n=Promise.resolve(n)),t?n.then(t):n}function s(){}var v={type:"SKIP_WAITING"};function h(n,t){return n&&n.then?n.then(s):Promise.resolve()}var l=function(t){function e(n,r){var e,i;return void 0===r&&(r={}),(e=t.call(this)||this).nn={},e.tn=0,e.rn=new u,e.en=new u,e.on=new u,e.un=0,e.an=new Set,e.cn=function(){var n=e.fn,t=n.installing;e.tn>0||!a(t.scriptURL,e.sn.toString())||performance.now()>e.un+6e4?(e.vn=t,n.removeEventListener("updatefound",e.cn)):(e.hn=t,e.an.add(t),e.rn.resolve(t)),++e.tn,t.addEventListener("statechange",e.ln)},e.ln=function(n){var t=e.fn,r=n.target,i=r.state,o=r===e.vn,u={sw:r,isExternal:o,originalEvent:n};!o&&e.mn&&(u.isUpdate=!0),e.dispatchEvent(new c(i,u)),"installed"===i?e.wn=self.setTimeout((function(){"installed"===i&&t.waiting===r&&e.dispatchEvent(new c("waiting",u))}),200):"activating"===i&&(clearTimeout(e.wn),o||e.en.resolve(r))},e.yn=function(n){var t=e.hn,r=t!==navigator.serviceWorker.controller;e.dispatchEvent(new c("controlling",{isExternal:r,originalEvent:n,sw:t,isUpdate:e.mn})),r||e.on.resolve(t)},e.gn=(i=function(n){var t=n.data,r=n.ports,i=n.source;return f(e.getSW(),(function(){e.an.has(i)&&e.dispatchEvent(new c("message",{data:t,originalEvent:n,ports:r,sw:i}))}))},function(){for(var n=[],t=0;t}\n * @memberof workbox-window\n */\n// Better not change type of data.\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction messageSW(sw, data) {\n return new Promise((resolve) => {\n const messageChannel = new MessageChannel();\n messageChannel.port1.onmessage = (event) => {\n resolve(event.data);\n };\n sw.postMessage(data, [messageChannel.port2]);\n });\n}\nexport { messageSW };\n","\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:core:7.4.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 '../_version.js';\n/**\n * The Deferred class composes Promises in a way that allows for them to be\n * resolved or rejected from outside the constructor. In most cases promises\n * should be used directly, but Deferreds can be necessary when the logic to\n * resolve a promise must be separate.\n *\n * @private\n */\nclass Deferred {\n /**\n * Creates a promise and exposes its resolve and reject functions as methods.\n */\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\nexport { Deferred };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * Returns true if two URLs have the same `.href` property. The URLS can be\n * relative, and if they are the current location href is used to resolve URLs.\n *\n * @private\n * @param {string} url1\n * @param {string} url2\n * @return {boolean}\n */\nexport function urlsMatch(url1, url2) {\n const { href } = location;\n return new URL(url1, href).href === new URL(url2, href).href;\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * A minimal `Event` subclass shim.\n * This doesn't *actually* subclass `Event` because not all browsers support\n * constructable `EventTarget`, and using a real `Event` will error.\n * @private\n */\nexport class WorkboxEvent {\n constructor(type, props) {\n this.type = type;\n Object.assign(this, props);\n }\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { Deferred } from 'workbox-core/_private/Deferred.js';\nimport { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { messageSW } from './messageSW.js';\nimport { WorkboxEventTarget } from './utils/WorkboxEventTarget.js';\nimport { urlsMatch } from './utils/urlsMatch.js';\nimport { WorkboxEvent } from './utils/WorkboxEvent.js';\nimport './_version.js';\n// The time a SW must be in the waiting phase before we can conclude\n// `skipWaiting()` wasn't called. This 200 amount wasn't scientifically\n// chosen, but it seems to avoid false positives in my testing.\nconst WAITING_TIMEOUT_DURATION = 200;\n// The amount of time after a registration that we can reasonably conclude\n// that the registration didn't trigger an update.\nconst REGISTRATION_TIMEOUT_DURATION = 60000;\n// The de facto standard message that a service worker should be listening for\n// to trigger a call to skipWaiting().\nconst SKIP_WAITING_MESSAGE = { type: 'SKIP_WAITING' };\n/**\n * A class to aid in handling service worker registration, updates, and\n * reacting to service worker lifecycle events.\n *\n * @fires {@link workbox-window.Workbox#message}\n * @fires {@link workbox-window.Workbox#installed}\n * @fires {@link workbox-window.Workbox#waiting}\n * @fires {@link workbox-window.Workbox#controlling}\n * @fires {@link workbox-window.Workbox#activated}\n * @fires {@link workbox-window.Workbox#redundant}\n * @memberof workbox-window\n */\nclass Workbox extends WorkboxEventTarget {\n /**\n * Creates a new Workbox instance with a script URL and service worker\n * options. The script URL and options are the same as those used when\n * calling [navigator.serviceWorker.register(scriptURL, options)](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register).\n *\n * @param {string|TrustedScriptURL} scriptURL The service worker script\n * associated with this instance. Using a\n * [`TrustedScriptURL`](https://web.dev/trusted-types/) is supported.\n * @param {Object} [registerOptions] The service worker options associated\n * with this instance.\n */\n // eslint-disable-next-line @typescript-eslint/ban-types\n constructor(scriptURL, registerOptions = {}) {\n super();\n this._registerOptions = {};\n this._updateFoundCount = 0;\n // Deferreds we can resolve later.\n this._swDeferred = new Deferred();\n this._activeDeferred = new Deferred();\n this._controllingDeferred = new Deferred();\n this._registrationTime = 0;\n this._ownSWs = new Set();\n /**\n * @private\n */\n this._onUpdateFound = () => {\n // `this._registration` will never be `undefined` after an update is found.\n const registration = this._registration;\n const installingSW = registration.installing;\n // If the script URL passed to `navigator.serviceWorker.register()` is\n // different from the current controlling SW's script URL, we know any\n // successful registration calls will trigger an `updatefound` event.\n // But if the registered script URL is the same as the current controlling\n // SW's script URL, we'll only get an `updatefound` event if the file\n // changed since it was last registered. This can be a problem if the user\n // opens up the same page in a different tab, and that page registers\n // a SW that triggers an update. It's a problem because this page has no\n // good way of knowing whether the `updatefound` event came from the SW\n // script it registered or from a registration attempt made by a newer\n // version of the page running in another tab.\n // To minimize the possibility of a false positive, we use the logic here:\n const updateLikelyTriggeredExternally = \n // Since we enforce only calling `register()` once, and since we don't\n // add the `updatefound` event listener until the `register()` call, if\n // `_updateFoundCount` is > 0 then it means this method has already\n // been called, thus this SW must be external\n this._updateFoundCount > 0 ||\n // If the script URL of the installing SW is different from this\n // instance's script URL, we know it's definitely not from our\n // registration.\n !urlsMatch(installingSW.scriptURL, this._scriptURL.toString()) ||\n // If all of the above are false, then we use a time-based heuristic:\n // Any `updatefound` event that occurs long after our registration is\n // assumed to be external.\n performance.now() > this._registrationTime + REGISTRATION_TIMEOUT_DURATION\n ? // If any of the above are not true, we assume the update was\n // triggered by this instance.\n true\n : false;\n if (updateLikelyTriggeredExternally) {\n this._externalSW = installingSW;\n registration.removeEventListener('updatefound', this._onUpdateFound);\n }\n else {\n // If the update was not triggered externally we know the installing\n // SW is the one we registered, so we set it.\n this._sw = installingSW;\n this._ownSWs.add(installingSW);\n this._swDeferred.resolve(installingSW);\n // The `installing` state isn't something we have a dedicated\n // callback for, but we do log messages for it in development.\n if (process.env.NODE_ENV !== 'production') {\n if (navigator.serviceWorker.controller) {\n logger.log('Updated service worker found. Installing now...');\n }\n else {\n logger.log('Service worker is installing...');\n }\n }\n }\n // Increment the `updatefound` count, so future invocations of this\n // method can be sure they were triggered externally.\n ++this._updateFoundCount;\n // Add a `statechange` listener regardless of whether this update was\n // triggered externally, since we have callbacks for both.\n installingSW.addEventListener('statechange', this._onStateChange);\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onStateChange = (originalEvent) => {\n // `this._registration` will never be `undefined` after an update is found.\n const registration = this._registration;\n const sw = originalEvent.target;\n const { state } = sw;\n const isExternal = sw === this._externalSW;\n const eventProps = {\n sw,\n isExternal,\n originalEvent,\n };\n if (!isExternal && this._isUpdate) {\n eventProps.isUpdate = true;\n }\n this.dispatchEvent(new WorkboxEvent(state, eventProps));\n if (state === 'installed') {\n // This timeout is used to ignore cases where the service worker calls\n // `skipWaiting()` in the install event, thus moving it directly in the\n // activating state. (Since all service workers *must* go through the\n // waiting phase, the only way to detect `skipWaiting()` called in the\n // install event is to observe that the time spent in the waiting phase\n // is very short.)\n // NOTE: we don't need separate timeouts for the own and external SWs\n // since they can't go through these phases at the same time.\n this._waitingTimeout = self.setTimeout(() => {\n // Ensure the SW is still waiting (it may now be redundant).\n if (state === 'installed' && registration.waiting === sw) {\n this.dispatchEvent(new WorkboxEvent('waiting', eventProps));\n if (process.env.NODE_ENV !== 'production') {\n if (isExternal) {\n logger.warn('An external service worker has installed but is ' +\n 'waiting for this client to close before activating...');\n }\n else {\n logger.warn('The service worker has installed but is waiting ' +\n 'for existing clients to close before activating...');\n }\n }\n }\n }, WAITING_TIMEOUT_DURATION);\n }\n else if (state === 'activating') {\n clearTimeout(this._waitingTimeout);\n if (!isExternal) {\n this._activeDeferred.resolve(sw);\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n switch (state) {\n case 'installed':\n if (isExternal) {\n logger.warn('An external service worker has installed. ' +\n 'You may want to suggest users reload this page.');\n }\n else {\n logger.log('Registered service worker installed.');\n }\n break;\n case 'activated':\n if (isExternal) {\n logger.warn('An external service worker has activated.');\n }\n else {\n logger.log('Registered service worker activated.');\n if (sw !== navigator.serviceWorker.controller) {\n logger.warn('The registered service worker is active but ' +\n 'not yet controlling the page. Reload or run ' +\n '`clients.claim()` in the service worker.');\n }\n }\n break;\n case 'redundant':\n if (sw === this._compatibleControllingSW) {\n logger.log('Previously controlling service worker now redundant!');\n }\n else if (!isExternal) {\n logger.log('Registered service worker now redundant!');\n }\n break;\n }\n }\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onControllerChange = (originalEvent) => {\n const sw = this._sw;\n const isExternal = sw !== navigator.serviceWorker.controller;\n // Unconditionally dispatch the controlling event, with isExternal set\n // to distinguish between controller changes due to the initial registration\n // vs. an update-check or other tab's registration.\n // See https://github.com/GoogleChrome/workbox/issues/2786\n this.dispatchEvent(new WorkboxEvent('controlling', {\n isExternal,\n originalEvent,\n sw,\n isUpdate: this._isUpdate,\n }));\n if (!isExternal) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Registered service worker now controlling this page.');\n }\n this._controllingDeferred.resolve(sw);\n }\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onMessage = async (originalEvent) => {\n // Can't change type 'any' of data.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const { data, ports, source } = originalEvent;\n // Wait until there's an \"own\" service worker. This is used to buffer\n // `message` events that may be received prior to calling `register()`.\n await this.getSW();\n // If the service worker that sent the message is in the list of own\n // service workers for this instance, dispatch a `message` event.\n // NOTE: we check for all previously owned service workers rather than\n // just the current one because some messages (e.g. cache updates) use\n // a timeout when sent and may be delayed long enough for a service worker\n // update to be found.\n if (this._ownSWs.has(source)) {\n this.dispatchEvent(new WorkboxEvent('message', {\n // Can't change type 'any' of data.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n data,\n originalEvent,\n ports,\n sw: source,\n }));\n }\n };\n this._scriptURL = scriptURL;\n this._registerOptions = registerOptions;\n // Add a message listener immediately since messages received during\n // page load are buffered only until the DOMContentLoaded event:\n // https://github.com/GoogleChrome/workbox/issues/2202\n navigator.serviceWorker.addEventListener('message', this._onMessage);\n }\n /**\n * Registers a service worker for this instances script URL and service\n * worker options. By default this method delays registration until after\n * the window has loaded.\n *\n * @param {Object} [options]\n * @param {Function} [options.immediate=false] Setting this to true will\n * register the service worker immediately, even if the window has\n * not loaded (not recommended).\n */\n async register({ immediate = false } = {}) {\n if (process.env.NODE_ENV !== 'production') {\n if (this._registrationTime) {\n logger.error('Cannot re-register a Workbox instance after it has ' +\n 'been registered. Create a new instance instead.');\n return;\n }\n }\n if (!immediate && document.readyState !== 'complete') {\n await new Promise((res) => window.addEventListener('load', res));\n }\n // Set this flag to true if any service worker was controlling the page\n // at registration time.\n this._isUpdate = Boolean(navigator.serviceWorker.controller);\n // Before registering, attempt to determine if a SW is already controlling\n // the page, and if that SW script (and version, if specified) matches this\n // instance's script.\n this._compatibleControllingSW = this._getControllingSWIfCompatible();\n this._registration = await this._registerScript();\n // If we have a compatible controller, store the controller as the \"own\"\n // SW, resolve active/controlling deferreds and add necessary listeners.\n if (this._compatibleControllingSW) {\n this._sw = this._compatibleControllingSW;\n this._activeDeferred.resolve(this._compatibleControllingSW);\n this._controllingDeferred.resolve(this._compatibleControllingSW);\n this._compatibleControllingSW.addEventListener('statechange', this._onStateChange, { once: true });\n }\n // If there's a waiting service worker with a matching URL before the\n // `updatefound` event fires, it likely means that this site is open\n // in another tab, or the user refreshed the page (and thus the previous\n // page wasn't fully unloaded before this page started loading).\n // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting\n const waitingSW = this._registration.waiting;\n if (waitingSW &&\n urlsMatch(waitingSW.scriptURL, this._scriptURL.toString())) {\n // Store the waiting SW as the \"own\" Sw, even if it means overwriting\n // a compatible controller.\n this._sw = waitingSW;\n // Run this in the next microtask, so any code that adds an event\n // listener after awaiting `register()` will get this event.\n dontWaitFor(Promise.resolve().then(() => {\n this.dispatchEvent(new WorkboxEvent('waiting', {\n sw: waitingSW,\n wasWaitingBeforeRegister: true,\n }));\n if (process.env.NODE_ENV !== 'production') {\n logger.warn('A service worker was already waiting to activate ' +\n 'before this script was registered...');\n }\n }));\n }\n // If an \"own\" SW is already set, resolve the deferred.\n if (this._sw) {\n this._swDeferred.resolve(this._sw);\n this._ownSWs.add(this._sw);\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Successfully registered service worker.', this._scriptURL.toString());\n if (navigator.serviceWorker.controller) {\n if (this._compatibleControllingSW) {\n logger.debug('A service worker with the same script URL ' +\n 'is already controlling this page.');\n }\n else {\n logger.debug('A service worker with a different script URL is ' +\n 'currently controlling the page. The browser is now fetching ' +\n 'the new script now...');\n }\n }\n const currentPageIsOutOfScope = () => {\n const scopeURL = new URL(this._registerOptions.scope || this._scriptURL.toString(), document.baseURI);\n const scopeURLBasePath = new URL('./', scopeURL.href).pathname;\n return !location.pathname.startsWith(scopeURLBasePath);\n };\n if (currentPageIsOutOfScope()) {\n logger.warn('The current page is not in scope for the registered ' +\n 'service worker. Was this a mistake?');\n }\n }\n this._registration.addEventListener('updatefound', this._onUpdateFound);\n navigator.serviceWorker.addEventListener('controllerchange', this._onControllerChange);\n return this._registration;\n }\n /**\n * Checks for updates of the registered service worker.\n */\n async update() {\n if (!this._registration) {\n if (process.env.NODE_ENV !== 'production') {\n logger.error('Cannot update a Workbox instance without ' +\n 'being registered. Register the Workbox instance first.');\n }\n return;\n }\n // Try to update registration\n await this._registration.update();\n }\n /**\n * Resolves to the service worker registered by this instance as soon as it\n * is active. If a service worker was already controlling at registration\n * time then it will resolve to that if the script URLs (and optionally\n * script versions) match, otherwise it will wait until an update is found\n * and activates.\n *\n * @return {Promise}\n */\n get active() {\n return this._activeDeferred.promise;\n }\n /**\n * Resolves to the service worker registered by this instance as soon as it\n * is controlling the page. If a service worker was already controlling at\n * registration time then it will resolve to that if the script URLs (and\n * optionally script versions) match, otherwise it will wait until an update\n * is found and starts controlling the page.\n * Note: the first time a service worker is installed it will active but\n * not start controlling the page unless `clients.claim()` is called in the\n * service worker.\n *\n * @return {Promise}\n */\n get controlling() {\n return this._controllingDeferred.promise;\n }\n /**\n * Resolves with a reference to a service worker that matches the script URL\n * of this instance, as soon as it's available.\n *\n * If, at registration time, there's already an active or waiting service\n * worker with a matching script URL, it will be used (with the waiting\n * service worker taking precedence over the active service worker if both\n * match, since the waiting service worker would have been registered more\n * recently).\n * If there's no matching active or waiting service worker at registration\n * time then the promise will not resolve until an update is found and starts\n * installing, at which point the installing service worker is used.\n *\n * @return {Promise}\n */\n getSW() {\n // If `this._sw` is set, resolve with that as we want `getSW()` to\n // return the correct (new) service worker if an update is found.\n return this._sw !== undefined\n ? Promise.resolve(this._sw)\n : this._swDeferred.promise;\n }\n /**\n * Sends the passed data object to the service worker registered by this\n * instance (via {@link workbox-window.Workbox#getSW}) and resolves\n * with a response (if any).\n *\n * A response can be set in a message handler in the service worker by\n * calling `event.ports[0].postMessage(...)`, which will resolve the promise\n * returned by `messageSW()`. If no response is set, the promise will never\n * resolve.\n *\n * @param {Object} data An object to send to the service worker\n * @return {Promise}\n */\n // We might be able to change the 'data' type to Record in the future.\n // eslint-disable-next-line @typescript-eslint/ban-types\n async messageSW(data) {\n const sw = await this.getSW();\n return messageSW(sw, data);\n }\n /**\n * Sends a `{type: 'SKIP_WAITING'}` message to the service worker that's\n * currently in the `waiting` state associated with the current registration.\n *\n * If there is no current registration or no service worker is `waiting`,\n * calling this will have no effect.\n */\n messageSkipWaiting() {\n if (this._registration && this._registration.waiting) {\n void messageSW(this._registration.waiting, SKIP_WAITING_MESSAGE);\n }\n }\n /**\n * Checks for a service worker already controlling the page and returns\n * it if its script URL matches.\n *\n * @private\n * @return {ServiceWorker|undefined}\n */\n _getControllingSWIfCompatible() {\n const controller = navigator.serviceWorker.controller;\n if (controller &&\n urlsMatch(controller.scriptURL, this._scriptURL.toString())) {\n return controller;\n }\n else {\n return undefined;\n }\n }\n /**\n * Registers a service worker for this instances script URL and register\n * options and tracks the time registration was complete.\n *\n * @private\n */\n async _registerScript() {\n try {\n // this._scriptURL may be a TrustedScriptURL, but there's no support for\n // passing that to register() in lib.dom right now.\n // https://github.com/GoogleChrome/workbox/issues/2855\n const reg = await navigator.serviceWorker.register(this._scriptURL, this._registerOptions);\n // Keep track of when registration happened, so it can be used in the\n // `this._onUpdateFound` heuristic. Also use the presence of this\n // property as a way to see if `.register()` has been called.\n this._registrationTime = performance.now();\n return reg;\n }\n catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n logger.error(error);\n }\n // Re-throw the error.\n throw error;\n }\n }\n}\nexport { Workbox };\n// The jsdoc comments below outline the events this instance may dispatch:\n// -----------------------------------------------------------------------\n/**\n * The `message` event is dispatched any time a `postMessage` is received.\n *\n * @event workbox-window.Workbox#message\n * @type {WorkboxEvent}\n * @property {*} data The `data` property from the original `message` event.\n * @property {Event} originalEvent The original [`message`]{@link https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent}\n * event.\n * @property {string} type `message`.\n * @property {MessagePort[]} ports The `ports` value from `originalEvent`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `installed` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}\n * changes to `installed`.\n *\n * Then can happen either the very first time a service worker is installed,\n * or after an update to the current service worker is found. In the case\n * of an update being found, the event's `isUpdate` property will be `true`.\n *\n * @event workbox-window.Workbox#installed\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `installed`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `waiting` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}\n * changes to `installed` and then doesn't immediately change to `activating`.\n * It may also be dispatched if a service worker with the same\n * [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}\n * was already waiting when the {@link workbox-window.Workbox#register}\n * method was called.\n *\n * @event workbox-window.Workbox#waiting\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event|undefined} originalEvent The original\n * [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event, or `undefined` in the case where the service worker was waiting\n * to before `.register()` was called.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {boolean|undefined} wasWaitingBeforeRegister True if a service worker with\n * a matching `scriptURL` was already waiting when this `Workbox`\n * instance called `register()`.\n * @property {string} type `waiting`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `controlling` event is dispatched if a\n * [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}\n * fires on the service worker [container]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer}\n * and the [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}\n * of the new [controller]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller}\n * matches the `scriptURL` of the `Workbox` instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}.\n *\n * @event workbox-window.Workbox#controlling\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this service worker was registered.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `controlling`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `activated` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}\n * changes to `activated`.\n *\n * @event workbox-window.Workbox#activated\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `activated`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `redundant` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}\n * changes to `redundant`.\n *\n * @event workbox-window.Workbox#redundant\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {string} type `redundant`.\n * @property {Workbox} target The `Workbox` instance.\n */\n","/*\n Copyright 2019 Google LLC\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';\n/**\n * A helper function that prevents a promise from being flagged as unused.\n *\n * @private\n **/\nexport function dontWaitFor(promise) {\n // Effective no-op.\n void promise.then(() => { });\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\n/**\n * A minimal `EventTarget` shim.\n * This is necessary because not all browsers support constructable\n * `EventTarget`, so using a real `EventTarget` will error.\n * @private\n */\nexport class WorkboxEventTarget {\n constructor() {\n this._eventListenerRegistry = new Map();\n }\n /**\n * @param {string} type\n * @param {Function} listener\n * @private\n */\n addEventListener(type, listener) {\n const foo = this._getEventListenersByType(type);\n foo.add(listener);\n }\n /**\n * @param {string} type\n * @param {Function} listener\n * @private\n */\n removeEventListener(type, listener) {\n this._getEventListenersByType(type).delete(listener);\n }\n /**\n * @param {Object} event\n * @private\n */\n dispatchEvent(event) {\n event.target = this;\n const listeners = this._getEventListenersByType(event.type);\n for (const listener of listeners) {\n listener(event);\n }\n }\n /**\n * Returns a Set of listeners associated with the passed event type.\n * If no handlers have been registered, an empty Set is returned.\n *\n * @param {string} type The event type.\n * @return {Set} An array of handler functions.\n * @private\n */\n _getEventListenersByType(type) {\n if (!this._eventListenerRegistry.has(type)) {\n this._eventListenerRegistry.set(type, new Set());\n }\n return this._eventListenerRegistry.get(type);\n }\n}\n"],"names":["self","_","e","messageSW","sw","data","Promise","resolve","messageChannel","MessageChannel","port1","onmessage","event","postMessage","port2","Deferred","_this","this","promise","reject","urlsMatch","url1","url2","href","location","URL","WorkboxEvent","type","props","Object","assign","_await","value","then","direct","_empty","SKIP_WAITING_MESSAGE","_awaitIgnored","Workbox","_WorkboxEventTarget","scriptURL","registerOptions","f","call","_registerOptions","_updateFoundCount","_swDeferred","_activeDeferred","_controllingDeferred","_registrationTime","_ownSWs","Set","_onUpdateFound","registration","_registration","installingSW","installing","_scriptURL","toString","performance","now","_externalSW","removeEventListener","_sw","add","addEventListener","_onStateChange","originalEvent","target","state","isExternal","eventProps","_isUpdate","isUpdate","dispatchEvent","_waitingTimeout","setTimeout","waiting","clearTimeout","_onControllerChange","navigator","serviceWorker","controller","_onMessage","ports","source","getSW","has","args","i","arguments","length","apply","_proto","prototype","register","_temp","_ref$immediate","immediate","_this2","body","result","_invoke","document","readyState","res","window","Boolean","_compatibleControllingSW","_getControllingSWIfCompatible","_registerScript","_this2$_registerScrip","once","waitingSW","wasWaitingBeforeRegister","update","undefined","messageSkipWaiting","_this5","recover","_catch","reg","error","_createClass","key","get","WorkboxEventTarget","_eventListenerRegistry","Map","listener","_getEventListenersByType","delete","_step","_iterator","_createForOfIteratorHelperLoose","done","set"],"mappings":"AAEA,IACIA,KAAK,yBAA2BC,GACpC,CACA,MAAOC,GAAK,CCmBZ,SAASC,EAAUC,EAAIC,GACnB,OAAO,IAAIC,SAAQ,SAACC,GAChB,IAAMC,EAAiB,IAAIC,eAC3BD,EAAeE,MAAMC,UAAY,SAACC,GAC9BL,EAAQK,EAAMP,KAClB,EACAD,EAAGS,YAAYR,EAAM,CAACG,EAAeM,OACzC,GACJ,26CC9BA,IACId,KAAK,uBAAyBC,GAClC,CACA,MAAOC,GAAK,CCGZ,IAQMa,EAIF,WAAc,IAAAC,EAAAC,KACVA,KAAKC,QAAU,IAAIZ,SAAQ,SAACC,EAASY,GACjCH,EAAKT,QAAUA,EACfS,EAAKG,OAASA,CAClB,GACJ,ECRG,SAASC,EAAUC,EAAMC,GAC5B,IAAQC,EAASC,SAATD,KACR,OAAO,IAAIE,IAAIJ,EAAME,GAAMA,OAAS,IAAIE,IAAIH,EAAMC,GAAMA,IAC5D,CCNA,IAAaG,EACT,SAAYC,EAAMC,GACdX,KAAKU,KAAOA,EACZE,OA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,EAAKrE,GAAoBU,YAAYC,MAC9B6D,CAAI,GACf,IAAC,SACMC,GAKH,MAAMA,CACV,IACJ,OAACxH,GAAA,OAAAI,QAAAa,OAAAjB,EAAA,CAAA,EAAAyH,EAAArF,EAAA,CAAA,CAAAsF,IAAA,SAAAC,IAjHD,WACI,OAAO5G,KAAK8B,GAAgB7B,OAChC,GACA,CAAA0G,IAAA,cAAAC,IAYA,WACI,OAAO5G,KAAK+B,GAAqB9B,OACrC,IAAC,EEtY0B,WAC3B,SAAA4G,IACI7G,KAAK8G,GAAyB,IAAIC,GACtC,CACA,IAAAnC,EAAAiC,EAAAhC,UAyCC,OAzCDD,EAKA5B,iBAAA,SAAiBtC,EAAMsG,GACPhH,KAAKiH,GAAyBvG,GACtCqC,IAAIiE,EACZ,EACApC,EAKA/B,oBAAA,SAAoBnC,EAAMsG,GACtBhH,KAAKiH,GAAyBvG,GAAMwG,OAAOF,EAC/C,EACApC,EAIAnB,cAAA,SAAc9D,GACVA,EAAMwD,OAASnD,KAEf,IADA,IACgCmH,EAAhCC,EAAAC,EADkBrH,KAAKiH,GAAyBtH,EAAMe,SACtByG,EAAAC,KAAAE,MAAE,EAC9BN,EADeG,EAAApG,OACNpB,EACb,CACJ,EACAiF,EAQAqC,GAAA,SAAyBvG,GAIrB,OAHKV,KAAK8G,GAAuBxC,IAAI5D,IACjCV,KAAK8G,GAAuBS,IAAI7G,EAAM,IAAIwB,KAEvClC,KAAK8G,GAAuBF,IAAIlG,EAC3C,EAACmG,CAAA,CA7C0B"} \ No newline at end of file diff --git a/node_modules/workbox-window/build/workbox-window.prod.mjs b/node_modules/workbox-window/build/workbox-window.prod.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9548807937a2e67200116317f2804411f6b61e79 --- /dev/null +++ b/node_modules/workbox-window/build/workbox-window.prod.mjs @@ -0,0 +1,2 @@ +try{self["workbox:window:7.4.0"]&&_()}catch(t){}function t(t,s){return new Promise((i=>{const e=new MessageChannel;e.port1.onmessage=t=>{i(t.data)},t.postMessage(s,[e.port2])}))}try{self["workbox:core:7.4.0"]&&_()}catch(t){}class s{constructor(){this.promise=new Promise(((t,s)=>{this.resolve=t,this.reject=s}))}}class i{constructor(){this.Pt=new Map}addEventListener(t,s){this.Wt(t).add(s)}removeEventListener(t,s){this.Wt(t).delete(s)}dispatchEvent(t){t.target=this;const s=this.Wt(t.type);for(const i of s)i(t)}Wt(t){return this.Pt.has(t)||this.Pt.set(t,new Set),this.Pt.get(t)}}function e(t,s){const{href:i}=location;return new URL(t,i).href===new URL(s,i).href}class h{constructor(t,s){this.type=t,Object.assign(this,s)}}const n={type:"SKIP_WAITING"};class a extends i{constructor(t,i={}){super(),this._t={},this.Lt=0,this.Ct=new s,this.Tt=new s,this.Ut=new s,this.Mt=0,this.Gt=new Set,this.Kt=()=>{const t=this.Nt,s=t.installing;this.Lt>0||!e(s.scriptURL,this.Ot.toString())||performance.now()>this.Mt+6e4?(this.zt=s,t.removeEventListener("updatefound",this.Kt)):(this.Ft=s,this.Gt.add(s),this.Ct.resolve(s)),++this.Lt,s.addEventListener("statechange",this.Ht)},this.Ht=t=>{const s=this.Nt,i=t.target,{state:e}=i,n=i===this.zt,a={sw:i,isExternal:n,originalEvent:t};!n&&this.Jt&&(a.isUpdate=!0),this.dispatchEvent(new h(e,a)),"installed"===e?this.Qt=self.setTimeout((()=>{"installed"===e&&s.waiting===i&&this.dispatchEvent(new h("waiting",a))}),200):"activating"===e&&(clearTimeout(this.Qt),n||this.Tt.resolve(i))},this.Vt=t=>{const s=this.Ft,i=s!==navigator.serviceWorker.controller;this.dispatchEvent(new h("controlling",{isExternal:i,originalEvent:t,sw:s,isUpdate:this.Jt})),i||this.Ut.resolve(s)},this.Xt=async t=>{const{data:s,ports:i,source:e}=t;await this.getSW(),this.Gt.has(e)&&this.dispatchEvent(new h("message",{data:s,originalEvent:t,ports:i,sw:e}))},this.Ot=t,this._t=i,navigator.serviceWorker.addEventListener("message",this.Xt)}async register({immediate:t=!1}={}){t||"complete"===document.readyState||await new Promise((t=>window.addEventListener("load",t))),this.Jt=Boolean(navigator.serviceWorker.controller),this.Yt=this.Zt(),this.Nt=await this.$t(),this.Yt&&(this.Ft=this.Yt,this.Tt.resolve(this.Yt),this.Ut.resolve(this.Yt),this.Yt.addEventListener("statechange",this.Ht,{once:!0}));const s=this.Nt.waiting;return s&&e(s.scriptURL,this.Ot.toString())&&(this.Ft=s,Promise.resolve().then((()=>{this.dispatchEvent(new h("waiting",{sw:s,wasWaitingBeforeRegister:!0}))})).then((()=>{}))),this.Ft&&(this.Ct.resolve(this.Ft),this.Gt.add(this.Ft)),this.Nt.addEventListener("updatefound",this.Kt),navigator.serviceWorker.addEventListener("controllerchange",this.Vt),this.Nt}async update(){this.Nt&&await this.Nt.update()}get active(){return this.Tt.promise}get controlling(){return this.Ut.promise}getSW(){return void 0!==this.Ft?Promise.resolve(this.Ft):this.Ct.promise}async messageSW(s){return t(await this.getSW(),s)}messageSkipWaiting(){this.Nt&&this.Nt.waiting&&t(this.Nt.waiting,n)}Zt(){const t=navigator.serviceWorker.controller;return t&&e(t.scriptURL,this.Ot.toString())?t:void 0}async $t(){try{const t=await navigator.serviceWorker.register(this.Ot,this._t);return this.Mt=performance.now(),t}catch(t){throw t}}}export{a as Workbox,h as WorkboxEvent,t as messageSW}; +//# sourceMappingURL=workbox-window.prod.mjs.map diff --git a/node_modules/workbox-window/build/workbox-window.prod.mjs.map b/node_modules/workbox-window/build/workbox-window.prod.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..17edd845f7e0a9faeb6ae22e2b517fb04bcec713 --- /dev/null +++ b/node_modules/workbox-window/build/workbox-window.prod.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-window.prod.mjs","sources":["../_version.js","../messageSW.js","../../workbox-core/_version.js","../../workbox-core/_private/Deferred.js","../utils/WorkboxEventTarget.js","../utils/urlsMatch.js","../utils/WorkboxEvent.js","../Workbox.js","../../workbox-core/_private/dontWaitFor.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:window:7.4.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport './_version.js';\n/**\n * Sends a data object to a service worker via `postMessage` and resolves with\n * a response (if any).\n *\n * A response can be set in a message handler in the service worker by\n * calling `event.ports[0].postMessage(...)`, which will resolve the promise\n * returned by `messageSW()`. If no response is set, the promise will not\n * resolve.\n *\n * @param {ServiceWorker} sw The service worker to send the message to.\n * @param {Object} data An object to send to the service worker.\n * @return {Promise}\n * @memberof workbox-window\n */\n// Better not change type of data.\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction messageSW(sw, data) {\n return new Promise((resolve) => {\n const messageChannel = new MessageChannel();\n messageChannel.port1.onmessage = (event) => {\n resolve(event.data);\n };\n sw.postMessage(data, [messageChannel.port2]);\n });\n}\nexport { messageSW };\n","\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:core:7.4.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 '../_version.js';\n/**\n * The Deferred class composes Promises in a way that allows for them to be\n * resolved or rejected from outside the constructor. In most cases promises\n * should be used directly, but Deferreds can be necessary when the logic to\n * resolve a promise must be separate.\n *\n * @private\n */\nclass Deferred {\n /**\n * Creates a promise and exposes its resolve and reject functions as methods.\n */\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\nexport { Deferred };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\n/**\n * A minimal `EventTarget` shim.\n * This is necessary because not all browsers support constructable\n * `EventTarget`, so using a real `EventTarget` will error.\n * @private\n */\nexport class WorkboxEventTarget {\n constructor() {\n this._eventListenerRegistry = new Map();\n }\n /**\n * @param {string} type\n * @param {Function} listener\n * @private\n */\n addEventListener(type, listener) {\n const foo = this._getEventListenersByType(type);\n foo.add(listener);\n }\n /**\n * @param {string} type\n * @param {Function} listener\n * @private\n */\n removeEventListener(type, listener) {\n this._getEventListenersByType(type).delete(listener);\n }\n /**\n * @param {Object} event\n * @private\n */\n dispatchEvent(event) {\n event.target = this;\n const listeners = this._getEventListenersByType(event.type);\n for (const listener of listeners) {\n listener(event);\n }\n }\n /**\n * Returns a Set of listeners associated with the passed event type.\n * If no handlers have been registered, an empty Set is returned.\n *\n * @param {string} type The event type.\n * @return {Set} An array of handler functions.\n * @private\n */\n _getEventListenersByType(type) {\n if (!this._eventListenerRegistry.has(type)) {\n this._eventListenerRegistry.set(type, new Set());\n }\n return this._eventListenerRegistry.get(type);\n }\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * Returns true if two URLs have the same `.href` property. The URLS can be\n * relative, and if they are the current location href is used to resolve URLs.\n *\n * @private\n * @param {string} url1\n * @param {string} url2\n * @return {boolean}\n */\nexport function urlsMatch(url1, url2) {\n const { href } = location;\n return new URL(url1, href).href === new URL(url2, href).href;\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * A minimal `Event` subclass shim.\n * This doesn't *actually* subclass `Event` because not all browsers support\n * constructable `EventTarget`, and using a real `Event` will error.\n * @private\n */\nexport class WorkboxEvent {\n constructor(type, props) {\n this.type = type;\n Object.assign(this, props);\n }\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { Deferred } from 'workbox-core/_private/Deferred.js';\nimport { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { messageSW } from './messageSW.js';\nimport { WorkboxEventTarget } from './utils/WorkboxEventTarget.js';\nimport { urlsMatch } from './utils/urlsMatch.js';\nimport { WorkboxEvent } from './utils/WorkboxEvent.js';\nimport './_version.js';\n// The time a SW must be in the waiting phase before we can conclude\n// `skipWaiting()` wasn't called. This 200 amount wasn't scientifically\n// chosen, but it seems to avoid false positives in my testing.\nconst WAITING_TIMEOUT_DURATION = 200;\n// The amount of time after a registration that we can reasonably conclude\n// that the registration didn't trigger an update.\nconst REGISTRATION_TIMEOUT_DURATION = 60000;\n// The de facto standard message that a service worker should be listening for\n// to trigger a call to skipWaiting().\nconst SKIP_WAITING_MESSAGE = { type: 'SKIP_WAITING' };\n/**\n * A class to aid in handling service worker registration, updates, and\n * reacting to service worker lifecycle events.\n *\n * @fires {@link workbox-window.Workbox#message}\n * @fires {@link workbox-window.Workbox#installed}\n * @fires {@link workbox-window.Workbox#waiting}\n * @fires {@link workbox-window.Workbox#controlling}\n * @fires {@link workbox-window.Workbox#activated}\n * @fires {@link workbox-window.Workbox#redundant}\n * @memberof workbox-window\n */\nclass Workbox extends WorkboxEventTarget {\n /**\n * Creates a new Workbox instance with a script URL and service worker\n * options. The script URL and options are the same as those used when\n * calling [navigator.serviceWorker.register(scriptURL, options)](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register).\n *\n * @param {string|TrustedScriptURL} scriptURL The service worker script\n * associated with this instance. Using a\n * [`TrustedScriptURL`](https://web.dev/trusted-types/) is supported.\n * @param {Object} [registerOptions] The service worker options associated\n * with this instance.\n */\n // eslint-disable-next-line @typescript-eslint/ban-types\n constructor(scriptURL, registerOptions = {}) {\n super();\n this._registerOptions = {};\n this._updateFoundCount = 0;\n // Deferreds we can resolve later.\n this._swDeferred = new Deferred();\n this._activeDeferred = new Deferred();\n this._controllingDeferred = new Deferred();\n this._registrationTime = 0;\n this._ownSWs = new Set();\n /**\n * @private\n */\n this._onUpdateFound = () => {\n // `this._registration` will never be `undefined` after an update is found.\n const registration = this._registration;\n const installingSW = registration.installing;\n // If the script URL passed to `navigator.serviceWorker.register()` is\n // different from the current controlling SW's script URL, we know any\n // successful registration calls will trigger an `updatefound` event.\n // But if the registered script URL is the same as the current controlling\n // SW's script URL, we'll only get an `updatefound` event if the file\n // changed since it was last registered. This can be a problem if the user\n // opens up the same page in a different tab, and that page registers\n // a SW that triggers an update. It's a problem because this page has no\n // good way of knowing whether the `updatefound` event came from the SW\n // script it registered or from a registration attempt made by a newer\n // version of the page running in another tab.\n // To minimize the possibility of a false positive, we use the logic here:\n const updateLikelyTriggeredExternally = \n // Since we enforce only calling `register()` once, and since we don't\n // add the `updatefound` event listener until the `register()` call, if\n // `_updateFoundCount` is > 0 then it means this method has already\n // been called, thus this SW must be external\n this._updateFoundCount > 0 ||\n // If the script URL of the installing SW is different from this\n // instance's script URL, we know it's definitely not from our\n // registration.\n !urlsMatch(installingSW.scriptURL, this._scriptURL.toString()) ||\n // If all of the above are false, then we use a time-based heuristic:\n // Any `updatefound` event that occurs long after our registration is\n // assumed to be external.\n performance.now() > this._registrationTime + REGISTRATION_TIMEOUT_DURATION\n ? // If any of the above are not true, we assume the update was\n // triggered by this instance.\n true\n : false;\n if (updateLikelyTriggeredExternally) {\n this._externalSW = installingSW;\n registration.removeEventListener('updatefound', this._onUpdateFound);\n }\n else {\n // If the update was not triggered externally we know the installing\n // SW is the one we registered, so we set it.\n this._sw = installingSW;\n this._ownSWs.add(installingSW);\n this._swDeferred.resolve(installingSW);\n // The `installing` state isn't something we have a dedicated\n // callback for, but we do log messages for it in development.\n if (process.env.NODE_ENV !== 'production') {\n if (navigator.serviceWorker.controller) {\n logger.log('Updated service worker found. Installing now...');\n }\n else {\n logger.log('Service worker is installing...');\n }\n }\n }\n // Increment the `updatefound` count, so future invocations of this\n // method can be sure they were triggered externally.\n ++this._updateFoundCount;\n // Add a `statechange` listener regardless of whether this update was\n // triggered externally, since we have callbacks for both.\n installingSW.addEventListener('statechange', this._onStateChange);\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onStateChange = (originalEvent) => {\n // `this._registration` will never be `undefined` after an update is found.\n const registration = this._registration;\n const sw = originalEvent.target;\n const { state } = sw;\n const isExternal = sw === this._externalSW;\n const eventProps = {\n sw,\n isExternal,\n originalEvent,\n };\n if (!isExternal && this._isUpdate) {\n eventProps.isUpdate = true;\n }\n this.dispatchEvent(new WorkboxEvent(state, eventProps));\n if (state === 'installed') {\n // This timeout is used to ignore cases where the service worker calls\n // `skipWaiting()` in the install event, thus moving it directly in the\n // activating state. (Since all service workers *must* go through the\n // waiting phase, the only way to detect `skipWaiting()` called in the\n // install event is to observe that the time spent in the waiting phase\n // is very short.)\n // NOTE: we don't need separate timeouts for the own and external SWs\n // since they can't go through these phases at the same time.\n this._waitingTimeout = self.setTimeout(() => {\n // Ensure the SW is still waiting (it may now be redundant).\n if (state === 'installed' && registration.waiting === sw) {\n this.dispatchEvent(new WorkboxEvent('waiting', eventProps));\n if (process.env.NODE_ENV !== 'production') {\n if (isExternal) {\n logger.warn('An external service worker has installed but is ' +\n 'waiting for this client to close before activating...');\n }\n else {\n logger.warn('The service worker has installed but is waiting ' +\n 'for existing clients to close before activating...');\n }\n }\n }\n }, WAITING_TIMEOUT_DURATION);\n }\n else if (state === 'activating') {\n clearTimeout(this._waitingTimeout);\n if (!isExternal) {\n this._activeDeferred.resolve(sw);\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n switch (state) {\n case 'installed':\n if (isExternal) {\n logger.warn('An external service worker has installed. ' +\n 'You may want to suggest users reload this page.');\n }\n else {\n logger.log('Registered service worker installed.');\n }\n break;\n case 'activated':\n if (isExternal) {\n logger.warn('An external service worker has activated.');\n }\n else {\n logger.log('Registered service worker activated.');\n if (sw !== navigator.serviceWorker.controller) {\n logger.warn('The registered service worker is active but ' +\n 'not yet controlling the page. Reload or run ' +\n '`clients.claim()` in the service worker.');\n }\n }\n break;\n case 'redundant':\n if (sw === this._compatibleControllingSW) {\n logger.log('Previously controlling service worker now redundant!');\n }\n else if (!isExternal) {\n logger.log('Registered service worker now redundant!');\n }\n break;\n }\n }\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onControllerChange = (originalEvent) => {\n const sw = this._sw;\n const isExternal = sw !== navigator.serviceWorker.controller;\n // Unconditionally dispatch the controlling event, with isExternal set\n // to distinguish between controller changes due to the initial registration\n // vs. an update-check or other tab's registration.\n // See https://github.com/GoogleChrome/workbox/issues/2786\n this.dispatchEvent(new WorkboxEvent('controlling', {\n isExternal,\n originalEvent,\n sw,\n isUpdate: this._isUpdate,\n }));\n if (!isExternal) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Registered service worker now controlling this page.');\n }\n this._controllingDeferred.resolve(sw);\n }\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onMessage = async (originalEvent) => {\n // Can't change type 'any' of data.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const { data, ports, source } = originalEvent;\n // Wait until there's an \"own\" service worker. This is used to buffer\n // `message` events that may be received prior to calling `register()`.\n await this.getSW();\n // If the service worker that sent the message is in the list of own\n // service workers for this instance, dispatch a `message` event.\n // NOTE: we check for all previously owned service workers rather than\n // just the current one because some messages (e.g. cache updates) use\n // a timeout when sent and may be delayed long enough for a service worker\n // update to be found.\n if (this._ownSWs.has(source)) {\n this.dispatchEvent(new WorkboxEvent('message', {\n // Can't change type 'any' of data.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n data,\n originalEvent,\n ports,\n sw: source,\n }));\n }\n };\n this._scriptURL = scriptURL;\n this._registerOptions = registerOptions;\n // Add a message listener immediately since messages received during\n // page load are buffered only until the DOMContentLoaded event:\n // https://github.com/GoogleChrome/workbox/issues/2202\n navigator.serviceWorker.addEventListener('message', this._onMessage);\n }\n /**\n * Registers a service worker for this instances script URL and service\n * worker options. By default this method delays registration until after\n * the window has loaded.\n *\n * @param {Object} [options]\n * @param {Function} [options.immediate=false] Setting this to true will\n * register the service worker immediately, even if the window has\n * not loaded (not recommended).\n */\n async register({ immediate = false } = {}) {\n if (process.env.NODE_ENV !== 'production') {\n if (this._registrationTime) {\n logger.error('Cannot re-register a Workbox instance after it has ' +\n 'been registered. Create a new instance instead.');\n return;\n }\n }\n if (!immediate && document.readyState !== 'complete') {\n await new Promise((res) => window.addEventListener('load', res));\n }\n // Set this flag to true if any service worker was controlling the page\n // at registration time.\n this._isUpdate = Boolean(navigator.serviceWorker.controller);\n // Before registering, attempt to determine if a SW is already controlling\n // the page, and if that SW script (and version, if specified) matches this\n // instance's script.\n this._compatibleControllingSW = this._getControllingSWIfCompatible();\n this._registration = await this._registerScript();\n // If we have a compatible controller, store the controller as the \"own\"\n // SW, resolve active/controlling deferreds and add necessary listeners.\n if (this._compatibleControllingSW) {\n this._sw = this._compatibleControllingSW;\n this._activeDeferred.resolve(this._compatibleControllingSW);\n this._controllingDeferred.resolve(this._compatibleControllingSW);\n this._compatibleControllingSW.addEventListener('statechange', this._onStateChange, { once: true });\n }\n // If there's a waiting service worker with a matching URL before the\n // `updatefound` event fires, it likely means that this site is open\n // in another tab, or the user refreshed the page (and thus the previous\n // page wasn't fully unloaded before this page started loading).\n // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting\n const waitingSW = this._registration.waiting;\n if (waitingSW &&\n urlsMatch(waitingSW.scriptURL, this._scriptURL.toString())) {\n // Store the waiting SW as the \"own\" Sw, even if it means overwriting\n // a compatible controller.\n this._sw = waitingSW;\n // Run this in the next microtask, so any code that adds an event\n // listener after awaiting `register()` will get this event.\n dontWaitFor(Promise.resolve().then(() => {\n this.dispatchEvent(new WorkboxEvent('waiting', {\n sw: waitingSW,\n wasWaitingBeforeRegister: true,\n }));\n if (process.env.NODE_ENV !== 'production') {\n logger.warn('A service worker was already waiting to activate ' +\n 'before this script was registered...');\n }\n }));\n }\n // If an \"own\" SW is already set, resolve the deferred.\n if (this._sw) {\n this._swDeferred.resolve(this._sw);\n this._ownSWs.add(this._sw);\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Successfully registered service worker.', this._scriptURL.toString());\n if (navigator.serviceWorker.controller) {\n if (this._compatibleControllingSW) {\n logger.debug('A service worker with the same script URL ' +\n 'is already controlling this page.');\n }\n else {\n logger.debug('A service worker with a different script URL is ' +\n 'currently controlling the page. The browser is now fetching ' +\n 'the new script now...');\n }\n }\n const currentPageIsOutOfScope = () => {\n const scopeURL = new URL(this._registerOptions.scope || this._scriptURL.toString(), document.baseURI);\n const scopeURLBasePath = new URL('./', scopeURL.href).pathname;\n return !location.pathname.startsWith(scopeURLBasePath);\n };\n if (currentPageIsOutOfScope()) {\n logger.warn('The current page is not in scope for the registered ' +\n 'service worker. Was this a mistake?');\n }\n }\n this._registration.addEventListener('updatefound', this._onUpdateFound);\n navigator.serviceWorker.addEventListener('controllerchange', this._onControllerChange);\n return this._registration;\n }\n /**\n * Checks for updates of the registered service worker.\n */\n async update() {\n if (!this._registration) {\n if (process.env.NODE_ENV !== 'production') {\n logger.error('Cannot update a Workbox instance without ' +\n 'being registered. Register the Workbox instance first.');\n }\n return;\n }\n // Try to update registration\n await this._registration.update();\n }\n /**\n * Resolves to the service worker registered by this instance as soon as it\n * is active. If a service worker was already controlling at registration\n * time then it will resolve to that if the script URLs (and optionally\n * script versions) match, otherwise it will wait until an update is found\n * and activates.\n *\n * @return {Promise}\n */\n get active() {\n return this._activeDeferred.promise;\n }\n /**\n * Resolves to the service worker registered by this instance as soon as it\n * is controlling the page. If a service worker was already controlling at\n * registration time then it will resolve to that if the script URLs (and\n * optionally script versions) match, otherwise it will wait until an update\n * is found and starts controlling the page.\n * Note: the first time a service worker is installed it will active but\n * not start controlling the page unless `clients.claim()` is called in the\n * service worker.\n *\n * @return {Promise}\n */\n get controlling() {\n return this._controllingDeferred.promise;\n }\n /**\n * Resolves with a reference to a service worker that matches the script URL\n * of this instance, as soon as it's available.\n *\n * If, at registration time, there's already an active or waiting service\n * worker with a matching script URL, it will be used (with the waiting\n * service worker taking precedence over the active service worker if both\n * match, since the waiting service worker would have been registered more\n * recently).\n * If there's no matching active or waiting service worker at registration\n * time then the promise will not resolve until an update is found and starts\n * installing, at which point the installing service worker is used.\n *\n * @return {Promise}\n */\n getSW() {\n // If `this._sw` is set, resolve with that as we want `getSW()` to\n // return the correct (new) service worker if an update is found.\n return this._sw !== undefined\n ? Promise.resolve(this._sw)\n : this._swDeferred.promise;\n }\n /**\n * Sends the passed data object to the service worker registered by this\n * instance (via {@link workbox-window.Workbox#getSW}) and resolves\n * with a response (if any).\n *\n * A response can be set in a message handler in the service worker by\n * calling `event.ports[0].postMessage(...)`, which will resolve the promise\n * returned by `messageSW()`. If no response is set, the promise will never\n * resolve.\n *\n * @param {Object} data An object to send to the service worker\n * @return {Promise}\n */\n // We might be able to change the 'data' type to Record in the future.\n // eslint-disable-next-line @typescript-eslint/ban-types\n async messageSW(data) {\n const sw = await this.getSW();\n return messageSW(sw, data);\n }\n /**\n * Sends a `{type: 'SKIP_WAITING'}` message to the service worker that's\n * currently in the `waiting` state associated with the current registration.\n *\n * If there is no current registration or no service worker is `waiting`,\n * calling this will have no effect.\n */\n messageSkipWaiting() {\n if (this._registration && this._registration.waiting) {\n void messageSW(this._registration.waiting, SKIP_WAITING_MESSAGE);\n }\n }\n /**\n * Checks for a service worker already controlling the page and returns\n * it if its script URL matches.\n *\n * @private\n * @return {ServiceWorker|undefined}\n */\n _getControllingSWIfCompatible() {\n const controller = navigator.serviceWorker.controller;\n if (controller &&\n urlsMatch(controller.scriptURL, this._scriptURL.toString())) {\n return controller;\n }\n else {\n return undefined;\n }\n }\n /**\n * Registers a service worker for this instances script URL and register\n * options and tracks the time registration was complete.\n *\n * @private\n */\n async _registerScript() {\n try {\n // this._scriptURL may be a TrustedScriptURL, but there's no support for\n // passing that to register() in lib.dom right now.\n // https://github.com/GoogleChrome/workbox/issues/2855\n const reg = await navigator.serviceWorker.register(this._scriptURL, this._registerOptions);\n // Keep track of when registration happened, so it can be used in the\n // `this._onUpdateFound` heuristic. Also use the presence of this\n // property as a way to see if `.register()` has been called.\n this._registrationTime = performance.now();\n return reg;\n }\n catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n logger.error(error);\n }\n // Re-throw the error.\n throw error;\n }\n }\n}\nexport { Workbox };\n// The jsdoc comments below outline the events this instance may dispatch:\n// -----------------------------------------------------------------------\n/**\n * The `message` event is dispatched any time a `postMessage` is received.\n *\n * @event workbox-window.Workbox#message\n * @type {WorkboxEvent}\n * @property {*} data The `data` property from the original `message` event.\n * @property {Event} originalEvent The original [`message`]{@link https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent}\n * event.\n * @property {string} type `message`.\n * @property {MessagePort[]} ports The `ports` value from `originalEvent`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `installed` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}\n * changes to `installed`.\n *\n * Then can happen either the very first time a service worker is installed,\n * or after an update to the current service worker is found. In the case\n * of an update being found, the event's `isUpdate` property will be `true`.\n *\n * @event workbox-window.Workbox#installed\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `installed`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `waiting` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}\n * changes to `installed` and then doesn't immediately change to `activating`.\n * It may also be dispatched if a service worker with the same\n * [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}\n * was already waiting when the {@link workbox-window.Workbox#register}\n * method was called.\n *\n * @event workbox-window.Workbox#waiting\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event|undefined} originalEvent The original\n * [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event, or `undefined` in the case where the service worker was waiting\n * to before `.register()` was called.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {boolean|undefined} wasWaitingBeforeRegister True if a service worker with\n * a matching `scriptURL` was already waiting when this `Workbox`\n * instance called `register()`.\n * @property {string} type `waiting`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `controlling` event is dispatched if a\n * [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}\n * fires on the service worker [container]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer}\n * and the [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}\n * of the new [controller]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller}\n * matches the `scriptURL` of the `Workbox` instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}.\n *\n * @event workbox-window.Workbox#controlling\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this service worker was registered.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `controlling`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `activated` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}\n * changes to `activated`.\n *\n * @event workbox-window.Workbox#activated\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `activated`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `redundant` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}\n * changes to `redundant`.\n *\n * @event workbox-window.Workbox#redundant\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {string} type `redundant`.\n * @property {Workbox} target The `Workbox` instance.\n */\n","/*\n Copyright 2019 Google LLC\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';\n/**\n * A helper function that prevents a promise from being flagged as unused.\n *\n * @private\n **/\nexport function dontWaitFor(promise) {\n // Effective no-op.\n void promise.then(() => { });\n}\n"],"names":["self","_","e","messageSW","sw","data","Promise","resolve","messageChannel","MessageChannel","port1","onmessage","event","postMessage","port2","Deferred","constructor","this","promise","reject","WorkboxEventTarget","_eventListenerRegistry","Map","addEventListener","type","listener","_getEventListenersByType","add","removeEventListener","delete","dispatchEvent","target","listeners","has","set","Set","get","urlsMatch","url1","url2","href","location","URL","WorkboxEvent","props","Object","assign","SKIP_WAITING_MESSAGE","Workbox","scriptURL","registerOptions","super","_registerOptions","_updateFoundCount","_swDeferred","_activeDeferred","_controllingDeferred","_registrationTime","_ownSWs","_onUpdateFound","registration","_registration","installingSW","installing","_scriptURL","toString","performance","now","_externalSW","_sw","_onStateChange","originalEvent","state","isExternal","eventProps","_isUpdate","isUpdate","_waitingTimeout","setTimeout","waiting","clearTimeout","_onControllerChange","navigator","serviceWorker","controller","_onMessage","async","ports","source","getSW","immediate","document","readyState","res","window","Boolean","_compatibleControllingSW","_getControllingSWIfCompatible","_registerScript","once","waitingSW","then","wasWaitingBeforeRegister","update","active","controlling","undefined","messageSkipWaiting","reg","register","error"],"mappings":"AAEA,IACIA,KAAK,yBAA2BC,GACpC,CACA,MAAOC,GAAK,CCmBZ,SAASC,EAAUC,EAAIC,GACnB,OAAO,IAAIC,SAASC,IAChB,MAAMC,EAAiB,IAAIC,eAC3BD,EAAeE,MAAMC,UAAaC,IAC9BL,EAAQK,EAAMP,KAAK,EAEvBD,EAAGS,YAAYR,EAAM,CAACG,EAAeM,OAAO,GAEpD,CC9BA,IACId,KAAK,uBAAyBC,GAClC,CACA,MAAOC,GAAK,CCWZ,MAAMa,EAIFC,cACIC,KAAKC,QAAU,IAAIZ,SAAQ,CAACC,EAASY,KACjCF,KAAKV,QAAUA,EACfU,KAAKE,OAASA,CAAM,GAE5B,ECZG,MAAMC,EACTJ,cACIC,KAAKI,GAAyB,IAAIC,GACtC,CAMAC,iBAAiBC,EAAMC,GACPR,KAAKS,GAAyBF,GACtCG,IAAIF,EACZ,CAMAG,oBAA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AC3C,OAAIA,GACA/C,EAAU+C,EAAWnC,UAAWhC,KAAK+C,GAAWC,YACzCmB,OAGP,CAER,CAOAE,WACI,IAII,MAAMsB,QAAY1B,UAAUC,cAAc0B,SAAS5F,KAAK+C,GAAY/C,KAAKmC,IAKzE,OADAnC,KAAKwC,GAAoBS,YAAYC,MAC9ByC,CACX,CACA,MAAOE,GAKH,MAAMA,CACV,CACJ"} \ No newline at end of file diff --git a/node_modules/workbox-window/build/workbox-window.prod.umd.js b/node_modules/workbox-window/build/workbox-window.prod.umd.js new file mode 100644 index 0000000000000000000000000000000000000000..9a83aba388c4af5b8cc40b62ca8d84f503634afd --- /dev/null +++ b/node_modules/workbox-window/build/workbox-window.prod.umd.js @@ -0,0 +1,2 @@ +!function(n,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((n="undefined"!=typeof globalThis?globalThis:n||self).workbox={})}(this,(function(n){"use strict";try{self["workbox:window:7.4.0"]&&_()}catch(n){}function t(n,t){return new Promise((function(r){var e=new MessageChannel;e.port1.onmessage=function(n){r(n.data)},n.postMessage(t,[e.port2])}))}function r(n,t){(null==t||t>n.length)&&(t=n.length);for(var r=0,e=Array(t);r=n.length?{done:!0}:{done:!1,value:n[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function o(n,t){return o=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,t){return n.__proto__=t,n},o(n,t)}function u(n){var t=function(n,t){if("object"!=typeof n||!n)return n;var r=n[Symbol.toPrimitive];if(void 0!==r){var e=r.call(n,t);if("object"!=typeof e)return e;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(n)}(n,"string");return"symbol"==typeof t?t:t+""}try{self["workbox:core:7.4.0"]&&_()}catch(n){}var a=function(){var n=this;this.promise=new Promise((function(t,r){n.resolve=t,n.reject=r}))};function c(n,t){var r=location.href;return new URL(n,r).href===new URL(t,r).href}var f=function(n,t){this.type=n,Object.assign(this,t)};function s(n,t,r){return n&&n.then||(n=Promise.resolve(n)),t?n.then(t):n}function v(){}var h={type:"SKIP_WAITING"};function l(n,t){return n&&n.then?n.then(v):Promise.resolve()}var d=function(n){function r(t,r){var e,i;return void 0===r&&(r={}),(e=n.call(this)||this).nn={},e.tn=0,e.rn=new a,e.en=new a,e.on=new a,e.un=0,e.an=new Set,e.cn=function(){var n=e.fn,t=n.installing;e.tn>0||!c(t.scriptURL,e.sn.toString())||performance.now()>e.un+6e4?(e.vn=t,n.removeEventListener("updatefound",e.cn)):(e.hn=t,e.an.add(t),e.rn.resolve(t)),++e.tn,t.addEventListener("statechange",e.ln)},e.ln=function(n){var t=e.fn,r=n.target,i=r.state,o=r===e.vn,u={sw:r,isExternal:o,originalEvent:n};!o&&e.dn&&(u.isUpdate=!0),e.dispatchEvent(new f(i,u)),"installed"===i?e.mn=self.setTimeout((function(){"installed"===i&&t.waiting===r&&e.dispatchEvent(new f("waiting",u))}),200):"activating"===i&&(clearTimeout(e.mn),o||e.en.resolve(r))},e.yn=function(n){var t=e.hn,r=t!==navigator.serviceWorker.controller;e.dispatchEvent(new f("controlling",{isExternal:r,originalEvent:n,sw:t,isUpdate:e.dn})),r||e.on.resolve(t)},e.wn=(i=function(n){var t=n.data,r=n.ports,i=n.source;return s(e.getSW(),(function(){e.an.has(i)&&e.dispatchEvent(new f("message",{data:t,originalEvent:n,ports:r,sw:i}))}))},function(){for(var n=[],t=0;t}\n * @memberof workbox-window\n */\n// Better not change type of data.\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction messageSW(sw, data) {\n return new Promise((resolve) => {\n const messageChannel = new MessageChannel();\n messageChannel.port1.onmessage = (event) => {\n resolve(event.data);\n };\n sw.postMessage(data, [messageChannel.port2]);\n });\n}\nexport { messageSW };\n","\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:core:7.4.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 '../_version.js';\n/**\n * The Deferred class composes Promises in a way that allows for them to be\n * resolved or rejected from outside the constructor. In most cases promises\n * should be used directly, but Deferreds can be necessary when the logic to\n * resolve a promise must be separate.\n *\n * @private\n */\nclass Deferred {\n /**\n * Creates a promise and exposes its resolve and reject functions as methods.\n */\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\nexport { Deferred };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * Returns true if two URLs have the same `.href` property. The URLS can be\n * relative, and if they are the current location href is used to resolve URLs.\n *\n * @private\n * @param {string} url1\n * @param {string} url2\n * @return {boolean}\n */\nexport function urlsMatch(url1, url2) {\n const { href } = location;\n return new URL(url1, href).href === new URL(url2, href).href;\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * A minimal `Event` subclass shim.\n * This doesn't *actually* subclass `Event` because not all browsers support\n * constructable `EventTarget`, and using a real `Event` will error.\n * @private\n */\nexport class WorkboxEvent {\n constructor(type, props) {\n this.type = type;\n Object.assign(this, props);\n }\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { Deferred } from 'workbox-core/_private/Deferred.js';\nimport { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { messageSW } from './messageSW.js';\nimport { WorkboxEventTarget } from './utils/WorkboxEventTarget.js';\nimport { urlsMatch } from './utils/urlsMatch.js';\nimport { WorkboxEvent } from './utils/WorkboxEvent.js';\nimport './_version.js';\n// The time a SW must be in the waiting phase before we can conclude\n// `skipWaiting()` wasn't called. This 200 amount wasn't scientifically\n// chosen, but it seems to avoid false positives in my testing.\nconst WAITING_TIMEOUT_DURATION = 200;\n// The amount of time after a registration that we can reasonably conclude\n// that the registration didn't trigger an update.\nconst REGISTRATION_TIMEOUT_DURATION = 60000;\n// The de facto standard message that a service worker should be listening for\n// to trigger a call to skipWaiting().\nconst SKIP_WAITING_MESSAGE = { type: 'SKIP_WAITING' };\n/**\n * A class to aid in handling service worker registration, updates, and\n * reacting to service worker lifecycle events.\n *\n * @fires {@link workbox-window.Workbox#message}\n * @fires {@link workbox-window.Workbox#installed}\n * @fires {@link workbox-window.Workbox#waiting}\n * @fires {@link workbox-window.Workbox#controlling}\n * @fires {@link workbox-window.Workbox#activated}\n * @fires {@link workbox-window.Workbox#redundant}\n * @memberof workbox-window\n */\nclass Workbox extends WorkboxEventTarget {\n /**\n * Creates a new Workbox instance with a script URL and service worker\n * options. The script URL and options are the same as those used when\n * calling [navigator.serviceWorker.register(scriptURL, options)](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register).\n *\n * @param {string|TrustedScriptURL} scriptURL The service worker script\n * associated with this instance. Using a\n * [`TrustedScriptURL`](https://web.dev/trusted-types/) is supported.\n * @param {Object} [registerOptions] The service worker options associated\n * with this instance.\n */\n // eslint-disable-next-line @typescript-eslint/ban-types\n constructor(scriptURL, registerOptions = {}) {\n super();\n this._registerOptions = {};\n this._updateFoundCount = 0;\n // Deferreds we can resolve later.\n this._swDeferred = new Deferred();\n this._activeDeferred = new Deferred();\n this._controllingDeferred = new Deferred();\n this._registrationTime = 0;\n this._ownSWs = new Set();\n /**\n * @private\n */\n this._onUpdateFound = () => {\n // `this._registration` will never be `undefined` after an update is found.\n const registration = this._registration;\n const installingSW = registration.installing;\n // If the script URL passed to `navigator.serviceWorker.register()` is\n // different from the current controlling SW's script URL, we know any\n // successful registration calls will trigger an `updatefound` event.\n // But if the registered script URL is the same as the current controlling\n // SW's script URL, we'll only get an `updatefound` event if the file\n // changed since it was last registered. This can be a problem if the user\n // opens up the same page in a different tab, and that page registers\n // a SW that triggers an update. It's a problem because this page has no\n // good way of knowing whether the `updatefound` event came from the SW\n // script it registered or from a registration attempt made by a newer\n // version of the page running in another tab.\n // To minimize the possibility of a false positive, we use the logic here:\n const updateLikelyTriggeredExternally = \n // Since we enforce only calling `register()` once, and since we don't\n // add the `updatefound` event listener until the `register()` call, if\n // `_updateFoundCount` is > 0 then it means this method has already\n // been called, thus this SW must be external\n this._updateFoundCount > 0 ||\n // If the script URL of the installing SW is different from this\n // instance's script URL, we know it's definitely not from our\n // registration.\n !urlsMatch(installingSW.scriptURL, this._scriptURL.toString()) ||\n // If all of the above are false, then we use a time-based heuristic:\n // Any `updatefound` event that occurs long after our registration is\n // assumed to be external.\n performance.now() > this._registrationTime + REGISTRATION_TIMEOUT_DURATION\n ? // If any of the above are not true, we assume the update was\n // triggered by this instance.\n true\n : false;\n if (updateLikelyTriggeredExternally) {\n this._externalSW = installingSW;\n registration.removeEventListener('updatefound', this._onUpdateFound);\n }\n else {\n // If the update was not triggered externally we know the installing\n // SW is the one we registered, so we set it.\n this._sw = installingSW;\n this._ownSWs.add(installingSW);\n this._swDeferred.resolve(installingSW);\n // The `installing` state isn't something we have a dedicated\n // callback for, but we do log messages for it in development.\n if (process.env.NODE_ENV !== 'production') {\n if (navigator.serviceWorker.controller) {\n logger.log('Updated service worker found. Installing now...');\n }\n else {\n logger.log('Service worker is installing...');\n }\n }\n }\n // Increment the `updatefound` count, so future invocations of this\n // method can be sure they were triggered externally.\n ++this._updateFoundCount;\n // Add a `statechange` listener regardless of whether this update was\n // triggered externally, since we have callbacks for both.\n installingSW.addEventListener('statechange', this._onStateChange);\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onStateChange = (originalEvent) => {\n // `this._registration` will never be `undefined` after an update is found.\n const registration = this._registration;\n const sw = originalEvent.target;\n const { state } = sw;\n const isExternal = sw === this._externalSW;\n const eventProps = {\n sw,\n isExternal,\n originalEvent,\n };\n if (!isExternal && this._isUpdate) {\n eventProps.isUpdate = true;\n }\n this.dispatchEvent(new WorkboxEvent(state, eventProps));\n if (state === 'installed') {\n // This timeout is used to ignore cases where the service worker calls\n // `skipWaiting()` in the install event, thus moving it directly in the\n // activating state. (Since all service workers *must* go through the\n // waiting phase, the only way to detect `skipWaiting()` called in the\n // install event is to observe that the time spent in the waiting phase\n // is very short.)\n // NOTE: we don't need separate timeouts for the own and external SWs\n // since they can't go through these phases at the same time.\n this._waitingTimeout = self.setTimeout(() => {\n // Ensure the SW is still waiting (it may now be redundant).\n if (state === 'installed' && registration.waiting === sw) {\n this.dispatchEvent(new WorkboxEvent('waiting', eventProps));\n if (process.env.NODE_ENV !== 'production') {\n if (isExternal) {\n logger.warn('An external service worker has installed but is ' +\n 'waiting for this client to close before activating...');\n }\n else {\n logger.warn('The service worker has installed but is waiting ' +\n 'for existing clients to close before activating...');\n }\n }\n }\n }, WAITING_TIMEOUT_DURATION);\n }\n else if (state === 'activating') {\n clearTimeout(this._waitingTimeout);\n if (!isExternal) {\n this._activeDeferred.resolve(sw);\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n switch (state) {\n case 'installed':\n if (isExternal) {\n logger.warn('An external service worker has installed. ' +\n 'You may want to suggest users reload this page.');\n }\n else {\n logger.log('Registered service worker installed.');\n }\n break;\n case 'activated':\n if (isExternal) {\n logger.warn('An external service worker has activated.');\n }\n else {\n logger.log('Registered service worker activated.');\n if (sw !== navigator.serviceWorker.controller) {\n logger.warn('The registered service worker is active but ' +\n 'not yet controlling the page. Reload or run ' +\n '`clients.claim()` in the service worker.');\n }\n }\n break;\n case 'redundant':\n if (sw === this._compatibleControllingSW) {\n logger.log('Previously controlling service worker now redundant!');\n }\n else if (!isExternal) {\n logger.log('Registered service worker now redundant!');\n }\n break;\n }\n }\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onControllerChange = (originalEvent) => {\n const sw = this._sw;\n const isExternal = sw !== navigator.serviceWorker.controller;\n // Unconditionally dispatch the controlling event, with isExternal set\n // to distinguish between controller changes due to the initial registration\n // vs. an update-check or other tab's registration.\n // See https://github.com/GoogleChrome/workbox/issues/2786\n this.dispatchEvent(new WorkboxEvent('controlling', {\n isExternal,\n originalEvent,\n sw,\n isUpdate: this._isUpdate,\n }));\n if (!isExternal) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Registered service worker now controlling this page.');\n }\n this._controllingDeferred.resolve(sw);\n }\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onMessage = async (originalEvent) => {\n // Can't change type 'any' of data.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const { data, ports, source } = originalEvent;\n // Wait until there's an \"own\" service worker. This is used to buffer\n // `message` events that may be received prior to calling `register()`.\n await this.getSW();\n // If the service worker that sent the message is in the list of own\n // service workers for this instance, dispatch a `message` event.\n // NOTE: we check for all previously owned service workers rather than\n // just the current one because some messages (e.g. cache updates) use\n // a timeout when sent and may be delayed long enough for a service worker\n // update to be found.\n if (this._ownSWs.has(source)) {\n this.dispatchEvent(new WorkboxEvent('message', {\n // Can't change type 'any' of data.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n data,\n originalEvent,\n ports,\n sw: source,\n }));\n }\n };\n this._scriptURL = scriptURL;\n this._registerOptions = registerOptions;\n // Add a message listener immediately since messages received during\n // page load are buffered only until the DOMContentLoaded event:\n // https://github.com/GoogleChrome/workbox/issues/2202\n navigator.serviceWorker.addEventListener('message', this._onMessage);\n }\n /**\n * Registers a service worker for this instances script URL and service\n * worker options. By default this method delays registration until after\n * the window has loaded.\n *\n * @param {Object} [options]\n * @param {Function} [options.immediate=false] Setting this to true will\n * register the service worker immediately, even if the window has\n * not loaded (not recommended).\n */\n async register({ immediate = false } = {}) {\n if (process.env.NODE_ENV !== 'production') {\n if (this._registrationTime) {\n logger.error('Cannot re-register a Workbox instance after it has ' +\n 'been registered. Create a new instance instead.');\n return;\n }\n }\n if (!immediate && document.readyState !== 'complete') {\n await new Promise((res) => window.addEventListener('load', res));\n }\n // Set this flag to true if any service worker was controlling the page\n // at registration time.\n this._isUpdate = Boolean(navigator.serviceWorker.controller);\n // Before registering, attempt to determine if a SW is already controlling\n // the page, and if that SW script (and version, if specified) matches this\n // instance's script.\n this._compatibleControllingSW = this._getControllingSWIfCompatible();\n this._registration = await this._registerScript();\n // If we have a compatible controller, store the controller as the \"own\"\n // SW, resolve active/controlling deferreds and add necessary listeners.\n if (this._compatibleControllingSW) {\n this._sw = this._compatibleControllingSW;\n this._activeDeferred.resolve(this._compatibleControllingSW);\n this._controllingDeferred.resolve(this._compatibleControllingSW);\n this._compatibleControllingSW.addEventListener('statechange', this._onStateChange, { once: true });\n }\n // If there's a waiting service worker with a matching URL before the\n // `updatefound` event fires, it likely means that this site is open\n // in another tab, or the user refreshed the page (and thus the previous\n // page wasn't fully unloaded before this page started loading).\n // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting\n const waitingSW = this._registration.waiting;\n if (waitingSW &&\n urlsMatch(waitingSW.scriptURL, this._scriptURL.toString())) {\n // Store the waiting SW as the \"own\" Sw, even if it means overwriting\n // a compatible controller.\n this._sw = waitingSW;\n // Run this in the next microtask, so any code that adds an event\n // listener after awaiting `register()` will get this event.\n dontWaitFor(Promise.resolve().then(() => {\n this.dispatchEvent(new WorkboxEvent('waiting', {\n sw: waitingSW,\n wasWaitingBeforeRegister: true,\n }));\n if (process.env.NODE_ENV !== 'production') {\n logger.warn('A service worker was already waiting to activate ' +\n 'before this script was registered...');\n }\n }));\n }\n // If an \"own\" SW is already set, resolve the deferred.\n if (this._sw) {\n this._swDeferred.resolve(this._sw);\n this._ownSWs.add(this._sw);\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Successfully registered service worker.', this._scriptURL.toString());\n if (navigator.serviceWorker.controller) {\n if (this._compatibleControllingSW) {\n logger.debug('A service worker with the same script URL ' +\n 'is already controlling this page.');\n }\n else {\n logger.debug('A service worker with a different script URL is ' +\n 'currently controlling the page. The browser is now fetching ' +\n 'the new script now...');\n }\n }\n const currentPageIsOutOfScope = () => {\n const scopeURL = new URL(this._registerOptions.scope || this._scriptURL.toString(), document.baseURI);\n const scopeURLBasePath = new URL('./', scopeURL.href).pathname;\n return !location.pathname.startsWith(scopeURLBasePath);\n };\n if (currentPageIsOutOfScope()) {\n logger.warn('The current page is not in scope for the registered ' +\n 'service worker. Was this a mistake?');\n }\n }\n this._registration.addEventListener('updatefound', this._onUpdateFound);\n navigator.serviceWorker.addEventListener('controllerchange', this._onControllerChange);\n return this._registration;\n }\n /**\n * Checks for updates of the registered service worker.\n */\n async update() {\n if (!this._registration) {\n if (process.env.NODE_ENV !== 'production') {\n logger.error('Cannot update a Workbox instance without ' +\n 'being registered. Register the Workbox instance first.');\n }\n return;\n }\n // Try to update registration\n await this._registration.update();\n }\n /**\n * Resolves to the service worker registered by this instance as soon as it\n * is active. If a service worker was already controlling at registration\n * time then it will resolve to that if the script URLs (and optionally\n * script versions) match, otherwise it will wait until an update is found\n * and activates.\n *\n * @return {Promise}\n */\n get active() {\n return this._activeDeferred.promise;\n }\n /**\n * Resolves to the service worker registered by this instance as soon as it\n * is controlling the page. If a service worker was already controlling at\n * registration time then it will resolve to that if the script URLs (and\n * optionally script versions) match, otherwise it will wait until an update\n * is found and starts controlling the page.\n * Note: the first time a service worker is installed it will active but\n * not start controlling the page unless `clients.claim()` is called in the\n * service worker.\n *\n * @return {Promise}\n */\n get controlling() {\n return this._controllingDeferred.promise;\n }\n /**\n * Resolves with a reference to a service worker that matches the script URL\n * of this instance, as soon as it's available.\n *\n * If, at registration time, there's already an active or waiting service\n * worker with a matching script URL, it will be used (with the waiting\n * service worker taking precedence over the active service worker if both\n * match, since the waiting service worker would have been registered more\n * recently).\n * If there's no matching active or waiting service worker at registration\n * time then the promise will not resolve until an update is found and starts\n * installing, at which point the installing service worker is used.\n *\n * @return {Promise}\n */\n getSW() {\n // If `this._sw` is set, resolve with that as we want `getSW()` to\n // return the correct (new) service worker if an update is found.\n return this._sw !== undefined\n ? Promise.resolve(this._sw)\n : this._swDeferred.promise;\n }\n /**\n * Sends the passed data object to the service worker registered by this\n * instance (via {@link workbox-window.Workbox#getSW}) and resolves\n * with a response (if any).\n *\n * A response can be set in a message handler in the service worker by\n * calling `event.ports[0].postMessage(...)`, which will resolve the promise\n * returned by `messageSW()`. If no response is set, the promise will never\n * resolve.\n *\n * @param {Object} data An object to send to the service worker\n * @return {Promise}\n */\n // We might be able to change the 'data' type to Record in the future.\n // eslint-disable-next-line @typescript-eslint/ban-types\n async messageSW(data) {\n const sw = await this.getSW();\n return messageSW(sw, data);\n }\n /**\n * Sends a `{type: 'SKIP_WAITING'}` message to the service worker that's\n * currently in the `waiting` state associated with the current registration.\n *\n * If there is no current registration or no service worker is `waiting`,\n * calling this will have no effect.\n */\n messageSkipWaiting() {\n if (this._registration && this._registration.waiting) {\n void messageSW(this._registration.waiting, SKIP_WAITING_MESSAGE);\n }\n }\n /**\n * Checks for a service worker already controlling the page and returns\n * it if its script URL matches.\n *\n * @private\n * @return {ServiceWorker|undefined}\n */\n _getControllingSWIfCompatible() {\n const controller = navigator.serviceWorker.controller;\n if (controller &&\n urlsMatch(controller.scriptURL, this._scriptURL.toString())) {\n return controller;\n }\n else {\n return undefined;\n }\n }\n /**\n * Registers a service worker for this instances script URL and register\n * options and tracks the time registration was complete.\n *\n * @private\n */\n async _registerScript() {\n try {\n // this._scriptURL may be a TrustedScriptURL, but there's no support for\n // passing that to register() in lib.dom right now.\n // https://github.com/GoogleChrome/workbox/issues/2855\n const reg = await navigator.serviceWorker.register(this._scriptURL, this._registerOptions);\n // Keep track of when registration happened, so it can be used in the\n // `this._onUpdateFound` heuristic. Also use the presence of this\n // property as a way to see if `.register()` has been called.\n this._registrationTime = performance.now();\n return reg;\n }\n catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n logger.error(error);\n }\n // Re-throw the error.\n throw error;\n }\n }\n}\nexport { Workbox };\n// The jsdoc comments below outline the events this instance may dispatch:\n// -----------------------------------------------------------------------\n/**\n * The `message` event is dispatched any time a `postMessage` is received.\n *\n * @event workbox-window.Workbox#message\n * @type {WorkboxEvent}\n * @property {*} data The `data` property from the original `message` event.\n * @property {Event} originalEvent The original [`message`]{@link https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent}\n * event.\n * @property {string} type `message`.\n * @property {MessagePort[]} ports The `ports` value from `originalEvent`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `installed` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}\n * changes to `installed`.\n *\n * Then can happen either the very first time a service worker is installed,\n * or after an update to the current service worker is found. In the case\n * of an update being found, the event's `isUpdate` property will be `true`.\n *\n * @event workbox-window.Workbox#installed\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `installed`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `waiting` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}\n * changes to `installed` and then doesn't immediately change to `activating`.\n * It may also be dispatched if a service worker with the same\n * [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}\n * was already waiting when the {@link workbox-window.Workbox#register}\n * method was called.\n *\n * @event workbox-window.Workbox#waiting\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event|undefined} originalEvent The original\n * [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event, or `undefined` in the case where the service worker was waiting\n * to before `.register()` was called.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {boolean|undefined} wasWaitingBeforeRegister True if a service worker with\n * a matching `scriptURL` was already waiting when this `Workbox`\n * instance called `register()`.\n * @property {string} type `waiting`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `controlling` event is dispatched if a\n * [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}\n * fires on the service worker [container]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer}\n * and the [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}\n * of the new [controller]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller}\n * matches the `scriptURL` of the `Workbox` instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}.\n *\n * @event workbox-window.Workbox#controlling\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this service worker was registered.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `controlling`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `activated` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}\n * changes to `activated`.\n *\n * @event workbox-window.Workbox#activated\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `activated`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `redundant` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}\n * changes to `redundant`.\n *\n * @event workbox-window.Workbox#redundant\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {string} type `redundant`.\n * @property {Workbox} target The `Workbox` instance.\n */\n","/*\n Copyright 2019 Google LLC\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';\n/**\n * A helper function that prevents a promise from being flagged as unused.\n *\n * @private\n **/\nexport function dontWaitFor(promise) {\n // Effective no-op.\n void promise.then(() => { });\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\n/**\n * A minimal `EventTarget` shim.\n * This is necessary because not all browsers support constructable\n * `EventTarget`, so using a real `EventTarget` will error.\n * @private\n */\nexport class WorkboxEventTarget {\n constructor() {\n this._eventListenerRegistry = new Map();\n }\n /**\n * @param {string} type\n * @param {Function} listener\n * @private\n */\n addEventListener(type, listener) {\n const foo = this._getEventListenersByType(type);\n foo.add(listener);\n }\n /**\n * @param {string} type\n * @param {Function} listener\n * @private\n */\n removeEventListener(type, listener) {\n this._getEventListenersByType(type).delete(listener);\n }\n /**\n * @param {Object} event\n * @private\n */\n dispatchEvent(event) {\n event.target = this;\n const listeners = this._getEventListenersByType(event.type);\n for (const listener of listeners) {\n listener(event);\n }\n }\n /**\n * Returns a Set of listeners associated with the passed event type.\n * If no handlers have been registered, an empty Set is returned.\n *\n * @param {string} type The event type.\n * @return {Set} An array of handler functions.\n * @private\n */\n _getEventListenersByType(type) {\n if (!this._eventListenerRegistry.has(type)) {\n this._eventListenerRegistry.set(type, new Set());\n }\n return this._eventListenerRegistry.get(type);\n }\n}\n"],"names":["self","_","e","messageSW","sw","data","Promise","resolve","messageChannel","MessageChannel","port1","onmessage","event","postMessage","port2","Deferred","_this","this","promise","reject","urlsMatch","url1","url2","href","location","URL","WorkboxEvent","type","props","Object","assign","_await","value","then","direct","_empty","SKIP_WAITING_MESSAGE","_awaitIgnored","Workbox","_WorkboxEventTarget","scriptURL","registerOptions","f","call","_registerOptions","_updateFoundCount","_swDeferred","_activeDeferred","_controllingDeferred","_registrationTime","_ownSWs","Set","_onUpdateFound","registration","_registration","installingSW","installing","_scriptURL","toString","performance","now","_externalSW","removeEventListener","_sw","add","addEventListener","_onStateChange","originalEvent","target","state","isExternal","eventProps","_isUpdate","isUpdate","dispatchEvent","_waitingTimeout","setTimeout","waiting","clearTimeout","_onControllerChange","navigator","serviceWorker","controller","_onMessage","ports","source","getSW","has","args","i","arguments","length","apply","_proto","prototype","register","_temp","_ref$immediate","immediate","_this2","body","result","_invoke","document","readyState","res","window","Boolean","_compatibleControllingSW","_getControllingSWIfCompatible","_registerScript","_this2$_registerScrip","once","waitingSW","wasWaitingBeforeRegister","update","undefined","messageSkipWaiting","_this5","recover","_catch","reg","error","_createClass","key","get","WorkboxEventTarget","_eventListenerRegistry","Map","listener","_getEventListenersByType","delete","_step","_iterator","_createForOfIteratorHelperLoose","done","set"],"mappings":"+OAEA,IACIA,KAAK,yBAA2BC,GACpC,CACA,MAAOC,GAAK,CCmBZ,SAASC,EAAUC,EAAIC,GACnB,OAAO,IAAIC,SAAQ,SAACC,GAChB,IAAMC,EAAiB,IAAIC,eAC3BD,EAAeE,MAAMC,UAAY,SAACC,GAC9BL,EAAQK,EAAMP,KAClB,EACAD,EAAGS,YAAYR,EAAM,CAACG,EAAeM,OACzC,GACJ,26CC9BA,IACId,KAAK,uBAAyBC,GAClC,CACA,MAAOC,GAAK,CCGZ,IAQMa,EAIF,WAAc,IAAAC,EAAAC,KACVA,KAAKC,QAAU,IAAIZ,SAAQ,SAACC,EAASY,GACjCH,EAAKT,QAAUA,EACfS,EAAKG,OAASA,CAClB,GACJ,ECRG,SAASC,EAAUC,EAAMC,GAC5B,IAAQC,EAASC,SAATD,KACR,OAAO,IAAIE,IAAIJ,EAAME,GAAMA,OAAS,IAAIE,IAAIH,EAAMC,GAAMA,IAC5D,CCNA,IAAaG,EACT,SAAYC,EAAMC,GACdX,KAAKU,KAAOA,EACZE,OAAOC,OAAOb,KAAMW,EACxB,ECkEG,SAASG,EAAOC,EAAOC,EAAMC,GAOnC,OAHKF,GAAUA,EAAMC,OACpBD,EAAQ1B,QAAQC,QAAQyB,IAElBC,EAAOD,EAAMC,KAAKA,GAAQD,CAClC,CAogBO,SAASG,IAChB,CAzkBA,IAAMC,EAAuB,CAAET,KAAM,gBAuE9B,SAASU,EAAcL,EAAOE,GAEnC,OAAOF,GAASA,EAAMC,KAAOD,EAAMC,KAAKE,GAAU7B,QAAQC,SAE5D,CAAC,IA9DK+B,WAAOC,GAaT,SAAAD,EAAYE,EAAWC,GAAsB,IAAAzB,EAoB1B0B,EAsMsD,YA1NnC,IAAfD,IAAAA,EAAkB,CAAA,IACrCzB,EAAAuB,EAA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G,GACtCqC,IAAIiE,EACZ,EACApC,EAKA/B,oBAAA,SAAoBnC,EAAMsG,GACtBhH,KAAKiH,GAAyBvG,GAAMwG,OAAOF,EAC/C,EACApC,EAIAnB,cAAA,SAAc9D,GACVA,EAAMwD,OAASnD,KAEf,IADA,IACgCmH,EAAhCC,EAAAC,EADkBrH,KAAKiH,GAAyBtH,EAAMe,SACtByG,EAAAC,KAAAE,MAAE,EAC9BN,EADeG,EAAApG,OACNpB,EACb,CACJ,EACAiF,EAQAqC,GAAA,SAAyBvG,GAIrB,OAHKV,KAAK8G,GAAuBxC,IAAI5D,IACjCV,KAAK8G,GAAuBS,IAAI7G,EAAM,IAAIwB,KAEvClC,KAAK8G,GAAuBF,IAAIlG,EAC3C,EAACmG,CAAA,CA7C0B"} \ No newline at end of file diff --git a/node_modules/workbox-window/index.d.ts b/node_modules/workbox-window/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..877b8d4028c66e9dc50b94ac7e57dabac8994c80 --- /dev/null +++ b/node_modules/workbox-window/index.d.ts @@ -0,0 +1,8 @@ +import { messageSW } from './messageSW.js'; +import { Workbox } from './Workbox.js'; +import './_version.js'; +/** + * @module workbox-window + */ +export { messageSW, Workbox }; +export * from './utils/WorkboxEvent.js'; diff --git a/node_modules/workbox-window/index.js b/node_modules/workbox-window/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ad4641462c437e4d6f6798dbd3bde8ea51115772 --- /dev/null +++ b/node_modules/workbox-window/index.js @@ -0,0 +1,16 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import { messageSW } from './messageSW.js'; +import { Workbox } from './Workbox.js'; +import './_version.js'; +/** + * @module workbox-window + */ +export { messageSW, Workbox }; +// See https://github.com/GoogleChrome/workbox/issues/2770 +export * from './utils/WorkboxEvent.js'; diff --git a/node_modules/workbox-window/index.mjs b/node_modules/workbox-window/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..833b6a2f3226fec78490a3b7a622dc5146f94b53 --- /dev/null +++ b/node_modules/workbox-window/index.mjs @@ -0,0 +1 @@ +export * from './index.js'; \ No newline at end of file diff --git a/node_modules/workbox-window/messageSW.d.ts b/node_modules/workbox-window/messageSW.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..11f390f4a0ccbca3d1ae68f344ec39375ad7f902 --- /dev/null +++ b/node_modules/workbox-window/messageSW.d.ts @@ -0,0 +1,17 @@ +import './_version.js'; +/** + * Sends a data object to a service worker via `postMessage` and resolves with + * a response (if any). + * + * A response can be set in a message handler in the service worker by + * calling `event.ports[0].postMessage(...)`, which will resolve the promise + * returned by `messageSW()`. If no response is set, the promise will not + * resolve. + * + * @param {ServiceWorker} sw The service worker to send the message to. + * @param {Object} data An object to send to the service worker. + * @return {Promise} + * @memberof workbox-window + */ +declare function messageSW(sw: ServiceWorker, data: {}): Promise; +export { messageSW }; diff --git a/node_modules/workbox-window/messageSW.js b/node_modules/workbox-window/messageSW.js new file mode 100644 index 0000000000000000000000000000000000000000..1d627bc5ade08357739838bee0fe475a635d7b6b --- /dev/null +++ b/node_modules/workbox-window/messageSW.js @@ -0,0 +1,34 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import './_version.js'; +/** + * Sends a data object to a service worker via `postMessage` and resolves with + * a response (if any). + * + * A response can be set in a message handler in the service worker by + * calling `event.ports[0].postMessage(...)`, which will resolve the promise + * returned by `messageSW()`. If no response is set, the promise will not + * resolve. + * + * @param {ServiceWorker} sw The service worker to send the message to. + * @param {Object} data An object to send to the service worker. + * @return {Promise} + * @memberof workbox-window + */ +// Better not change type of data. +// eslint-disable-next-line @typescript-eslint/ban-types +function messageSW(sw, data) { + return new Promise((resolve) => { + const messageChannel = new MessageChannel(); + messageChannel.port1.onmessage = (event) => { + resolve(event.data); + }; + sw.postMessage(data, [messageChannel.port2]); + }); +} +export { messageSW }; diff --git a/node_modules/workbox-window/messageSW.mjs b/node_modules/workbox-window/messageSW.mjs new file mode 100644 index 0000000000000000000000000000000000000000..12ac5dc26777503b45767c74d9632172d3ddb909 --- /dev/null +++ b/node_modules/workbox-window/messageSW.mjs @@ -0,0 +1 @@ +export * from './messageSW.js'; \ No newline at end of file diff --git a/node_modules/workbox-window/package.json b/node_modules/workbox-window/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d128031cacf8cf92ee5df26e1ff05d0daf44d4f9 --- /dev/null +++ b/node_modules/workbox-window/package.json @@ -0,0 +1,34 @@ +{ + "name": "workbox-window", + "version": "7.4.1", + "license": "MIT", + "author": "Google's Web DevRel Team and Google's Aurora Team", + "description": "Simplifies communications with Workbox packages running in the service worker", + "repository": { + "type": "git", + "url": "git+https://github.com/googlechrome/workbox.git" + }, + "bugs": "https://github.com/googlechrome/workbox/issues", + "homepage": "https://github.com/GoogleChrome/workbox", + "keywords": [ + "workbox", + "workboxjs", + "service worker", + "sw", + "window", + "message", + "postMessage" + ], + "workbox": { + "packageType": "window", + "primaryBuild": "build/workbox-window.prod.mjs" + }, + "main": "build/workbox-window.prod.umd.js", + "module": "build/workbox-window.prod.es5.mjs", + "types": "index.d.ts", + "dependencies": { + "@types/trusted-types": "^2.0.2", + "workbox-core": "7.4.1" + }, + "gitHead": "62b9d8ba8eb3c1a2ab8aac9d84c90cda7865d6a3" +} diff --git a/node_modules/workbox-window/src/Workbox.ts b/node_modules/workbox-window/src/Workbox.ts new file mode 100644 index 0000000000000000000000000000000000000000..b43baeef3221763e5aa5e304f8a9147db7d52ca4 --- /dev/null +++ b/node_modules/workbox-window/src/Workbox.ts @@ -0,0 +1,740 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {Deferred} from 'workbox-core/_private/Deferred.js'; +import {dontWaitFor} from 'workbox-core/_private/dontWaitFor.js'; +import {logger} from 'workbox-core/_private/logger.js'; +import {TrustedScriptURL} from 'trusted-types/lib'; + +import {messageSW} from './messageSW.js'; +import {WorkboxEventTarget} from './utils/WorkboxEventTarget.js'; +import {urlsMatch} from './utils/urlsMatch.js'; +import {WorkboxEvent, WorkboxLifecycleEventMap} from './utils/WorkboxEvent.js'; + +import './_version.js'; + +// The time a SW must be in the waiting phase before we can conclude +// `skipWaiting()` wasn't called. This 200 amount wasn't scientifically +// chosen, but it seems to avoid false positives in my testing. +const WAITING_TIMEOUT_DURATION = 200; + +// The amount of time after a registration that we can reasonably conclude +// that the registration didn't trigger an update. +const REGISTRATION_TIMEOUT_DURATION = 60000; + +// The de facto standard message that a service worker should be listening for +// to trigger a call to skipWaiting(). +const SKIP_WAITING_MESSAGE = {type: 'SKIP_WAITING'}; + +/** + * A class to aid in handling service worker registration, updates, and + * reacting to service worker lifecycle events. + * + * @fires {@link workbox-window.Workbox#message} + * @fires {@link workbox-window.Workbox#installed} + * @fires {@link workbox-window.Workbox#waiting} + * @fires {@link workbox-window.Workbox#controlling} + * @fires {@link workbox-window.Workbox#activated} + * @fires {@link workbox-window.Workbox#redundant} + * @memberof workbox-window + */ +class Workbox extends WorkboxEventTarget { + private readonly _scriptURL: string | TrustedScriptURL; + private readonly _registerOptions: RegistrationOptions = {}; + private _updateFoundCount = 0; + + // Deferreds we can resolve later. + private readonly _swDeferred: Deferred = new Deferred(); + private readonly _activeDeferred: Deferred = new Deferred(); + private readonly _controllingDeferred: Deferred = + new Deferred(); + + private _registrationTime: DOMHighResTimeStamp = 0; + private _isUpdate?: boolean; + private _compatibleControllingSW?: ServiceWorker; + private _registration?: ServiceWorkerRegistration; + private _sw?: ServiceWorker; + private readonly _ownSWs: Set = new Set(); + private _externalSW?: ServiceWorker; + private _waitingTimeout?: number; + + /** + * Creates a new Workbox instance with a script URL and service worker + * options. The script URL and options are the same as those used when + * calling [navigator.serviceWorker.register(scriptURL, options)](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register). + * + * @param {string|TrustedScriptURL} scriptURL The service worker script + * associated with this instance. Using a + * [`TrustedScriptURL`](https://web.dev/trusted-types/) is supported. + * @param {Object} [registerOptions] The service worker options associated + * with this instance. + */ + // eslint-disable-next-line @typescript-eslint/ban-types + constructor(scriptURL: string | TrustedScriptURL, registerOptions: {} = {}) { + super(); + + this._scriptURL = scriptURL; + this._registerOptions = registerOptions; + + // Add a message listener immediately since messages received during + // page load are buffered only until the DOMContentLoaded event: + // https://github.com/GoogleChrome/workbox/issues/2202 + navigator.serviceWorker.addEventListener('message', this._onMessage); + } + + /** + * Registers a service worker for this instances script URL and service + * worker options. By default this method delays registration until after + * the window has loaded. + * + * @param {Object} [options] + * @param {Function} [options.immediate=false] Setting this to true will + * register the service worker immediately, even if the window has + * not loaded (not recommended). + */ + async register({immediate = false} = {}): Promise< + ServiceWorkerRegistration | undefined + > { + if (process.env.NODE_ENV !== 'production') { + if (this._registrationTime) { + logger.error( + 'Cannot re-register a Workbox instance after it has ' + + 'been registered. Create a new instance instead.', + ); + return; + } + } + + if (!immediate && document.readyState !== 'complete') { + await new Promise((res) => window.addEventListener('load', res)); + } + + // Set this flag to true if any service worker was controlling the page + // at registration time. + this._isUpdate = Boolean(navigator.serviceWorker.controller); + + // Before registering, attempt to determine if a SW is already controlling + // the page, and if that SW script (and version, if specified) matches this + // instance's script. + this._compatibleControllingSW = this._getControllingSWIfCompatible(); + + this._registration = await this._registerScript(); + + // If we have a compatible controller, store the controller as the "own" + // SW, resolve active/controlling deferreds and add necessary listeners. + if (this._compatibleControllingSW) { + this._sw = this._compatibleControllingSW; + this._activeDeferred.resolve(this._compatibleControllingSW); + this._controllingDeferred.resolve(this._compatibleControllingSW); + + this._compatibleControllingSW.addEventListener( + 'statechange', + this._onStateChange, + {once: true}, + ); + } + + // If there's a waiting service worker with a matching URL before the + // `updatefound` event fires, it likely means that this site is open + // in another tab, or the user refreshed the page (and thus the previous + // page wasn't fully unloaded before this page started loading). + // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting + const waitingSW = this._registration.waiting; + if ( + waitingSW && + urlsMatch(waitingSW.scriptURL, this._scriptURL.toString()) + ) { + // Store the waiting SW as the "own" Sw, even if it means overwriting + // a compatible controller. + this._sw = waitingSW; + + // Run this in the next microtask, so any code that adds an event + // listener after awaiting `register()` will get this event. + dontWaitFor( + Promise.resolve().then(() => { + this.dispatchEvent( + new WorkboxEvent('waiting', { + sw: waitingSW, + wasWaitingBeforeRegister: true, + }), + ); + if (process.env.NODE_ENV !== 'production') { + logger.warn( + 'A service worker was already waiting to activate ' + + 'before this script was registered...', + ); + } + }), + ); + } + + // If an "own" SW is already set, resolve the deferred. + if (this._sw) { + this._swDeferred.resolve(this._sw); + this._ownSWs.add(this._sw); + } + + if (process.env.NODE_ENV !== 'production') { + logger.log( + 'Successfully registered service worker.', + this._scriptURL.toString(), + ); + + if (navigator.serviceWorker.controller) { + if (this._compatibleControllingSW) { + logger.debug( + 'A service worker with the same script URL ' + + 'is already controlling this page.', + ); + } else { + logger.debug( + 'A service worker with a different script URL is ' + + 'currently controlling the page. The browser is now fetching ' + + 'the new script now...', + ); + } + } + + const currentPageIsOutOfScope = () => { + const scopeURL = new URL( + this._registerOptions.scope || this._scriptURL.toString(), + document.baseURI, + ); + const scopeURLBasePath = new URL('./', scopeURL.href).pathname; + return !location.pathname.startsWith(scopeURLBasePath); + }; + if (currentPageIsOutOfScope()) { + logger.warn( + 'The current page is not in scope for the registered ' + + 'service worker. Was this a mistake?', + ); + } + } + + this._registration.addEventListener('updatefound', this._onUpdateFound); + navigator.serviceWorker.addEventListener( + 'controllerchange', + this._onControllerChange, + ); + + return this._registration; + } + + /** + * Checks for updates of the registered service worker. + */ + async update(): Promise { + if (!this._registration) { + if (process.env.NODE_ENV !== 'production') { + logger.error( + 'Cannot update a Workbox instance without ' + + 'being registered. Register the Workbox instance first.', + ); + } + return; + } + + // Try to update registration + await this._registration.update(); + } + + /** + * Resolves to the service worker registered by this instance as soon as it + * is active. If a service worker was already controlling at registration + * time then it will resolve to that if the script URLs (and optionally + * script versions) match, otherwise it will wait until an update is found + * and activates. + * + * @return {Promise} + */ + get active(): Promise { + return this._activeDeferred.promise; + } + + /** + * Resolves to the service worker registered by this instance as soon as it + * is controlling the page. If a service worker was already controlling at + * registration time then it will resolve to that if the script URLs (and + * optionally script versions) match, otherwise it will wait until an update + * is found and starts controlling the page. + * Note: the first time a service worker is installed it will active but + * not start controlling the page unless `clients.claim()` is called in the + * service worker. + * + * @return {Promise} + */ + get controlling(): Promise { + return this._controllingDeferred.promise; + } + + /** + * Resolves with a reference to a service worker that matches the script URL + * of this instance, as soon as it's available. + * + * If, at registration time, there's already an active or waiting service + * worker with a matching script URL, it will be used (with the waiting + * service worker taking precedence over the active service worker if both + * match, since the waiting service worker would have been registered more + * recently). + * If there's no matching active or waiting service worker at registration + * time then the promise will not resolve until an update is found and starts + * installing, at which point the installing service worker is used. + * + * @return {Promise} + */ + getSW(): Promise { + // If `this._sw` is set, resolve with that as we want `getSW()` to + // return the correct (new) service worker if an update is found. + return this._sw !== undefined + ? Promise.resolve(this._sw) + : this._swDeferred.promise; + } + + /** + * Sends the passed data object to the service worker registered by this + * instance (via {@link workbox-window.Workbox#getSW}) and resolves + * with a response (if any). + * + * A response can be set in a message handler in the service worker by + * calling `event.ports[0].postMessage(...)`, which will resolve the promise + * returned by `messageSW()`. If no response is set, the promise will never + * resolve. + * + * @param {Object} data An object to send to the service worker + * @return {Promise} + */ + // We might be able to change the 'data' type to Record in the future. + // eslint-disable-next-line @typescript-eslint/ban-types + async messageSW(data: object): Promise { + const sw = await this.getSW(); + return messageSW(sw, data); + } + + /** + * Sends a `{type: 'SKIP_WAITING'}` message to the service worker that's + * currently in the `waiting` state associated with the current registration. + * + * If there is no current registration or no service worker is `waiting`, + * calling this will have no effect. + */ + messageSkipWaiting(): void { + if (this._registration && this._registration.waiting) { + void messageSW(this._registration.waiting, SKIP_WAITING_MESSAGE); + } + } + + /** + * Checks for a service worker already controlling the page and returns + * it if its script URL matches. + * + * @private + * @return {ServiceWorker|undefined} + */ + private _getControllingSWIfCompatible() { + const controller = navigator.serviceWorker.controller; + if ( + controller && + urlsMatch(controller.scriptURL, this._scriptURL.toString()) + ) { + return controller; + } else { + return undefined; + } + } + + /** + * Registers a service worker for this instances script URL and register + * options and tracks the time registration was complete. + * + * @private + */ + private async _registerScript() { + try { + // this._scriptURL may be a TrustedScriptURL, but there's no support for + // passing that to register() in lib.dom right now. + // https://github.com/GoogleChrome/workbox/issues/2855 + const reg = await navigator.serviceWorker.register( + this._scriptURL as string, + this._registerOptions, + ); + + // Keep track of when registration happened, so it can be used in the + // `this._onUpdateFound` heuristic. Also use the presence of this + // property as a way to see if `.register()` has been called. + this._registrationTime = performance.now(); + + return reg; + } catch (error) { + if (process.env.NODE_ENV !== 'production') { + logger.error(error); + } + // Re-throw the error. + throw error; + } + } + + /** + * @private + */ + private readonly _onUpdateFound = () => { + // `this._registration` will never be `undefined` after an update is found. + const registration = this._registration!; + const installingSW = registration.installing as ServiceWorker; + + // If the script URL passed to `navigator.serviceWorker.register()` is + // different from the current controlling SW's script URL, we know any + // successful registration calls will trigger an `updatefound` event. + // But if the registered script URL is the same as the current controlling + // SW's script URL, we'll only get an `updatefound` event if the file + // changed since it was last registered. This can be a problem if the user + // opens up the same page in a different tab, and that page registers + // a SW that triggers an update. It's a problem because this page has no + // good way of knowing whether the `updatefound` event came from the SW + // script it registered or from a registration attempt made by a newer + // version of the page running in another tab. + // To minimize the possibility of a false positive, we use the logic here: + const updateLikelyTriggeredExternally = + // Since we enforce only calling `register()` once, and since we don't + // add the `updatefound` event listener until the `register()` call, if + // `_updateFoundCount` is > 0 then it means this method has already + // been called, thus this SW must be external + this._updateFoundCount > 0 || + // If the script URL of the installing SW is different from this + // instance's script URL, we know it's definitely not from our + // registration. + !urlsMatch(installingSW.scriptURL, this._scriptURL.toString()) || + // If all of the above are false, then we use a time-based heuristic: + // Any `updatefound` event that occurs long after our registration is + // assumed to be external. + performance.now() > this._registrationTime + REGISTRATION_TIMEOUT_DURATION + ? // If any of the above are not true, we assume the update was + // triggered by this instance. + true + : false; + + if (updateLikelyTriggeredExternally) { + this._externalSW = installingSW; + registration.removeEventListener('updatefound', this._onUpdateFound); + } else { + // If the update was not triggered externally we know the installing + // SW is the one we registered, so we set it. + this._sw = installingSW; + this._ownSWs.add(installingSW); + this._swDeferred.resolve(installingSW); + + // The `installing` state isn't something we have a dedicated + // callback for, but we do log messages for it in development. + if (process.env.NODE_ENV !== 'production') { + if (navigator.serviceWorker.controller) { + logger.log('Updated service worker found. Installing now...'); + } else { + logger.log('Service worker is installing...'); + } + } + } + + // Increment the `updatefound` count, so future invocations of this + // method can be sure they were triggered externally. + ++this._updateFoundCount; + + // Add a `statechange` listener regardless of whether this update was + // triggered externally, since we have callbacks for both. + installingSW.addEventListener('statechange', this._onStateChange); + }; + + /** + * @private + * @param {Event} originalEvent + */ + private readonly _onStateChange = (originalEvent: Event) => { + // `this._registration` will never be `undefined` after an update is found. + const registration = this._registration!; + const sw = originalEvent.target as ServiceWorker; + const {state} = sw; + const isExternal = sw === this._externalSW; + + const eventProps: { + sw: ServiceWorker; + originalEvent: Event; + isUpdate?: boolean; + isExternal: boolean; + } = { + sw, + isExternal, + originalEvent, + }; + if (!isExternal && this._isUpdate) { + eventProps.isUpdate = true; + } + + this.dispatchEvent( + new WorkboxEvent(state as keyof WorkboxLifecycleEventMap, eventProps), + ); + + if (state === 'installed') { + // This timeout is used to ignore cases where the service worker calls + // `skipWaiting()` in the install event, thus moving it directly in the + // activating state. (Since all service workers *must* go through the + // waiting phase, the only way to detect `skipWaiting()` called in the + // install event is to observe that the time spent in the waiting phase + // is very short.) + // NOTE: we don't need separate timeouts for the own and external SWs + // since they can't go through these phases at the same time. + this._waitingTimeout = self.setTimeout(() => { + // Ensure the SW is still waiting (it may now be redundant). + if (state === 'installed' && registration.waiting === sw) { + this.dispatchEvent(new WorkboxEvent('waiting', eventProps)); + + if (process.env.NODE_ENV !== 'production') { + if (isExternal) { + logger.warn( + 'An external service worker has installed but is ' + + 'waiting for this client to close before activating...', + ); + } else { + logger.warn( + 'The service worker has installed but is waiting ' + + 'for existing clients to close before activating...', + ); + } + } + } + }, WAITING_TIMEOUT_DURATION); + } else if (state === 'activating') { + clearTimeout(this._waitingTimeout); + if (!isExternal) { + this._activeDeferred.resolve(sw); + } + } + + if (process.env.NODE_ENV !== 'production') { + switch (state) { + case 'installed': + if (isExternal) { + logger.warn( + 'An external service worker has installed. ' + + 'You may want to suggest users reload this page.', + ); + } else { + logger.log('Registered service worker installed.'); + } + break; + case 'activated': + if (isExternal) { + logger.warn('An external service worker has activated.'); + } else { + logger.log('Registered service worker activated.'); + if (sw !== navigator.serviceWorker.controller) { + logger.warn( + 'The registered service worker is active but ' + + 'not yet controlling the page. Reload or run ' + + '`clients.claim()` in the service worker.', + ); + } + } + break; + case 'redundant': + if (sw === this._compatibleControllingSW) { + logger.log('Previously controlling service worker now redundant!'); + } else if (!isExternal) { + logger.log('Registered service worker now redundant!'); + } + break; + } + } + }; + + /** + * @private + * @param {Event} originalEvent + */ + private readonly _onControllerChange = (originalEvent: Event) => { + const sw = this._sw; + const isExternal = sw !== navigator.serviceWorker.controller; + + // Unconditionally dispatch the controlling event, with isExternal set + // to distinguish between controller changes due to the initial registration + // vs. an update-check or other tab's registration. + // See https://github.com/GoogleChrome/workbox/issues/2786 + this.dispatchEvent( + new WorkboxEvent('controlling', { + isExternal, + originalEvent, + sw, + isUpdate: this._isUpdate, + }), + ); + + if (!isExternal) { + if (process.env.NODE_ENV !== 'production') { + logger.log('Registered service worker now controlling this page.'); + } + this._controllingDeferred.resolve(sw); + } + }; + + /** + * @private + * @param {Event} originalEvent + */ + private readonly _onMessage = async (originalEvent: MessageEvent) => { + // Can't change type 'any' of data. + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const {data, ports, source} = originalEvent; + + // Wait until there's an "own" service worker. This is used to buffer + // `message` events that may be received prior to calling `register()`. + await this.getSW(); + + // If the service worker that sent the message is in the list of own + // service workers for this instance, dispatch a `message` event. + // NOTE: we check for all previously owned service workers rather than + // just the current one because some messages (e.g. cache updates) use + // a timeout when sent and may be delayed long enough for a service worker + // update to be found. + if (this._ownSWs.has(source as ServiceWorker)) { + this.dispatchEvent( + new WorkboxEvent('message', { + // Can't change type 'any' of data. + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + data, + originalEvent, + ports, + sw: source as ServiceWorker, + }), + ); + } + }; +} + +export {Workbox}; + +// The jsdoc comments below outline the events this instance may dispatch: +// ----------------------------------------------------------------------- + +/** + * The `message` event is dispatched any time a `postMessage` is received. + * + * @event workbox-window.Workbox#message + * @type {WorkboxEvent} + * @property {*} data The `data` property from the original `message` event. + * @property {Event} originalEvent The original [`message`]{@link https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent} + * event. + * @property {string} type `message`. + * @property {MessagePort[]} ports The `ports` value from `originalEvent`. + * @property {Workbox} target The `Workbox` instance. + */ + +/** + * The `installed` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker} + * changes to `installed`. + * + * Then can happen either the very first time a service worker is installed, + * or after an update to the current service worker is found. In the case + * of an update being found, the event's `isUpdate` property will be `true`. + * + * @event workbox-window.Workbox#installed + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {string} type `installed`. + * @property {Workbox} target The `Workbox` instance. + */ + +/** + * The `waiting` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw} + * changes to `installed` and then doesn't immediately change to `activating`. + * It may also be dispatched if a service worker with the same + * [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL} + * was already waiting when the {@link workbox-window.Workbox#register} + * method was called. + * + * @event workbox-window.Workbox#waiting + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event|undefined} originalEvent The original + * [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event, or `undefined` in the case where the service worker was waiting + * to before `.register()` was called. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {boolean|undefined} wasWaitingBeforeRegister True if a service worker with + * a matching `scriptURL` was already waiting when this `Workbox` + * instance called `register()`. + * @property {string} type `waiting`. + * @property {Workbox} target The `Workbox` instance. + */ + +/** + * The `controlling` event is dispatched if a + * [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange} + * fires on the service worker [container]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer} + * and the [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL} + * of the new [controller]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller} + * matches the `scriptURL` of the `Workbox` instance's + * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}. + * + * @event workbox-window.Workbox#controlling + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this service worker was registered. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {string} type `controlling`. + * @property {Workbox} target The `Workbox` instance. + */ + +/** + * The `activated` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker} + * changes to `activated`. + * + * @event workbox-window.Workbox#activated + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {string} type `activated`. + * @property {Workbox} target The `Workbox` instance. + */ + +/** + * The `redundant` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw} + * changes to `redundant`. + * + * @event workbox-window.Workbox#redundant + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {string} type `redundant`. + * @property {Workbox} target The `Workbox` instance. + */ diff --git a/node_modules/workbox-window/src/_version.ts b/node_modules/workbox-window/src/_version.ts new file mode 100644 index 0000000000000000000000000000000000000000..2fab4abe969f248bff7966aa9a77a70552ac1659 --- /dev/null +++ b/node_modules/workbox-window/src/_version.ts @@ -0,0 +1,2 @@ +// @ts-ignore +try{self['workbox:window:7.4.1']&&_()}catch(e){} \ No newline at end of file diff --git a/node_modules/workbox-window/src/index.ts b/node_modules/workbox-window/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..dfb99a1e3ba4689169caf55b3e2639b94e35325f --- /dev/null +++ b/node_modules/workbox-window/src/index.ts @@ -0,0 +1,20 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {messageSW} from './messageSW.js'; +import {Workbox} from './Workbox.js'; + +import './_version.js'; + +/** + * @module workbox-window + */ +export {messageSW, Workbox}; + +// See https://github.com/GoogleChrome/workbox/issues/2770 +export * from './utils/WorkboxEvent.js'; diff --git a/node_modules/workbox-window/src/messageSW.ts b/node_modules/workbox-window/src/messageSW.ts new file mode 100644 index 0000000000000000000000000000000000000000..c4146e21c11434a75466a31263f94bd7798c82e6 --- /dev/null +++ b/node_modules/workbox-window/src/messageSW.ts @@ -0,0 +1,37 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import './_version.js'; + +/** + * Sends a data object to a service worker via `postMessage` and resolves with + * a response (if any). + * + * A response can be set in a message handler in the service worker by + * calling `event.ports[0].postMessage(...)`, which will resolve the promise + * returned by `messageSW()`. If no response is set, the promise will not + * resolve. + * + * @param {ServiceWorker} sw The service worker to send the message to. + * @param {Object} data An object to send to the service worker. + * @return {Promise} + * @memberof workbox-window + */ +// Better not change type of data. +// eslint-disable-next-line @typescript-eslint/ban-types +function messageSW(sw: ServiceWorker, data: {}): Promise { + return new Promise((resolve) => { + const messageChannel = new MessageChannel(); + messageChannel.port1.onmessage = (event: MessageEvent) => { + resolve(event.data); + }; + sw.postMessage(data, [messageChannel.port2]); + }); +} + +export {messageSW}; diff --git a/node_modules/workbox-window/src/utils/WorkboxEvent.ts b/node_modules/workbox-window/src/utils/WorkboxEvent.ts new file mode 100644 index 0000000000000000000000000000000000000000..a038e2bbc20c55e7d66a0b45ca4b24639730e9c8 --- /dev/null +++ b/node_modules/workbox-window/src/utils/WorkboxEvent.ts @@ -0,0 +1,59 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {WorkboxEventTarget} from './WorkboxEventTarget.js'; +import '../_version.js'; + +/** + * A minimal `Event` subclass shim. + * This doesn't *actually* subclass `Event` because not all browsers support + * constructable `EventTarget`, and using a real `Event` will error. + * @private + */ +export class WorkboxEvent { + target?: WorkboxEventTarget; + sw?: ServiceWorker; + originalEvent?: Event; + isExternal?: boolean; + + constructor( + public type: K, + props: Omit, + ) { + Object.assign(this, props); + } +} + +export interface WorkboxMessageEvent extends WorkboxEvent<'message'> { + data: any; + originalEvent: Event; + ports: readonly MessagePort[]; +} + +export interface WorkboxLifecycleEvent + extends WorkboxEvent { + isUpdate?: boolean; +} + +export interface WorkboxLifecycleWaitingEvent extends WorkboxLifecycleEvent { + wasWaitingBeforeRegister?: boolean; +} + +export interface WorkboxLifecycleEventMap { + installing: WorkboxLifecycleEvent; + installed: WorkboxLifecycleEvent; + waiting: WorkboxLifecycleWaitingEvent; + activating: WorkboxLifecycleEvent; + activated: WorkboxLifecycleEvent; + controlling: WorkboxLifecycleEvent; + redundant: WorkboxLifecycleEvent; +} + +export interface WorkboxEventMap extends WorkboxLifecycleEventMap { + message: WorkboxMessageEvent; +} diff --git a/node_modules/workbox-window/src/utils/WorkboxEventTarget.ts b/node_modules/workbox-window/src/utils/WorkboxEventTarget.ts new file mode 100644 index 0000000000000000000000000000000000000000..aa5c16e8c8b231701e4145d4a2753bc879f09a9a --- /dev/null +++ b/node_modules/workbox-window/src/utils/WorkboxEventTarget.ts @@ -0,0 +1,77 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import {WorkboxEvent, WorkboxEventMap} from './WorkboxEvent.js'; + +export type ListenerCallback = (event: WorkboxEvent) => any; + +/** + * A minimal `EventTarget` shim. + * This is necessary because not all browsers support constructable + * `EventTarget`, so using a real `EventTarget` will error. + * @private + */ +export class WorkboxEventTarget { + private readonly _eventListenerRegistry: Map< + keyof WorkboxEventMap, + Set + > = new Map(); + + /** + * @param {string} type + * @param {Function} listener + * @private + */ + addEventListener( + type: K, + listener: (event: WorkboxEventMap[K]) => any, + ): void { + const foo = this._getEventListenersByType(type); + foo.add(listener as ListenerCallback); + } + + /** + * @param {string} type + * @param {Function} listener + * @private + */ + removeEventListener( + type: K, + listener: (event: WorkboxEventMap[K]) => any, + ): void { + this._getEventListenersByType(type).delete(listener as ListenerCallback); + } + + /** + * @param {Object} event + * @private + */ + dispatchEvent(event: WorkboxEvent): void { + event.target = this; + + const listeners = this._getEventListenersByType(event.type); + for (const listener of listeners) { + listener(event); + } + } + + /** + * Returns a Set of listeners associated with the passed event type. + * If no handlers have been registered, an empty Set is returned. + * + * @param {string} type The event type. + * @return {Set} An array of handler functions. + * @private + */ + private _getEventListenersByType(type: keyof WorkboxEventMap) { + if (!this._eventListenerRegistry.has(type)) { + this._eventListenerRegistry.set(type, new Set()); + } + return this._eventListenerRegistry.get(type)!; + } +} diff --git a/node_modules/workbox-window/src/utils/urlsMatch.ts b/node_modules/workbox-window/src/utils/urlsMatch.ts new file mode 100644 index 0000000000000000000000000000000000000000..882011a90caad08ad013a3851fd225a73cd72688 --- /dev/null +++ b/node_modules/workbox-window/src/utils/urlsMatch.ts @@ -0,0 +1,23 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +import '../_version.js'; + +/** + * Returns true if two URLs have the same `.href` property. The URLS can be + * relative, and if they are the current location href is used to resolve URLs. + * + * @private + * @param {string} url1 + * @param {string} url2 + * @return {boolean} + */ +export function urlsMatch(url1: string, url2: string): boolean { + const {href} = location; + return new URL(url1, href).href === new URL(url2, href).href; +} diff --git a/node_modules/workbox-window/tsconfig.json b/node_modules/workbox-window/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..79279e1641dcac93a4863387ab8198ca58da7b71 --- /dev/null +++ b/node_modules/workbox-window/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../../tsconfig", + "compilerOptions": { + "lib": ["es2017", "dom"], + "outDir": "./", + "rootDir": "./src", + "tsBuildInfoFile": "./tsconfig.tsbuildinfo" + }, + "include": ["src/**/*.ts"], + "references": [ + { + "path": "../workbox-core/" + } + ] +} diff --git a/node_modules/workbox-window/utils/WorkboxEvent.d.ts b/node_modules/workbox-window/utils/WorkboxEvent.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..caf301fb75c2b017c4a802eb5a3dea29e3ade6e4 --- /dev/null +++ b/node_modules/workbox-window/utils/WorkboxEvent.d.ts @@ -0,0 +1,39 @@ +import { WorkboxEventTarget } from './WorkboxEventTarget.js'; +import '../_version.js'; +/** + * A minimal `Event` subclass shim. + * This doesn't *actually* subclass `Event` because not all browsers support + * constructable `EventTarget`, and using a real `Event` will error. + * @private + */ +export declare class WorkboxEvent { + type: K; + target?: WorkboxEventTarget; + sw?: ServiceWorker; + originalEvent?: Event; + isExternal?: boolean; + constructor(type: K, props: Omit); +} +export interface WorkboxMessageEvent extends WorkboxEvent<'message'> { + data: any; + originalEvent: Event; + ports: readonly MessagePort[]; +} +export interface WorkboxLifecycleEvent extends WorkboxEvent { + isUpdate?: boolean; +} +export interface WorkboxLifecycleWaitingEvent extends WorkboxLifecycleEvent { + wasWaitingBeforeRegister?: boolean; +} +export interface WorkboxLifecycleEventMap { + installing: WorkboxLifecycleEvent; + installed: WorkboxLifecycleEvent; + waiting: WorkboxLifecycleWaitingEvent; + activating: WorkboxLifecycleEvent; + activated: WorkboxLifecycleEvent; + controlling: WorkboxLifecycleEvent; + redundant: WorkboxLifecycleEvent; +} +export interface WorkboxEventMap extends WorkboxLifecycleEventMap { + message: WorkboxMessageEvent; +} diff --git a/node_modules/workbox-window/utils/WorkboxEvent.js b/node_modules/workbox-window/utils/WorkboxEvent.js new file mode 100644 index 0000000000000000000000000000000000000000..e0dbe1a3dbca1567a007a22ae42f94f07f834ce6 --- /dev/null +++ b/node_modules/workbox-window/utils/WorkboxEvent.js @@ -0,0 +1,20 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import '../_version.js'; +/** + * A minimal `Event` subclass shim. + * This doesn't *actually* subclass `Event` because not all browsers support + * constructable `EventTarget`, and using a real `Event` will error. + * @private + */ +export class WorkboxEvent { + constructor(type, props) { + this.type = type; + Object.assign(this, props); + } +} diff --git a/node_modules/workbox-window/utils/WorkboxEvent.mjs b/node_modules/workbox-window/utils/WorkboxEvent.mjs new file mode 100644 index 0000000000000000000000000000000000000000..452057a51d2ee76a40619b277ac747b762f32087 --- /dev/null +++ b/node_modules/workbox-window/utils/WorkboxEvent.mjs @@ -0,0 +1 @@ +export * from './WorkboxEvent.js'; \ No newline at end of file diff --git a/node_modules/workbox-window/utils/WorkboxEventTarget.d.ts b/node_modules/workbox-window/utils/WorkboxEventTarget.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1724ea28ab3c2c8c7cdc974188cddbfc3b50bc11 --- /dev/null +++ b/node_modules/workbox-window/utils/WorkboxEventTarget.d.ts @@ -0,0 +1,37 @@ +import { WorkboxEvent, WorkboxEventMap } from './WorkboxEvent.js'; +export type ListenerCallback = (event: WorkboxEvent) => any; +/** + * A minimal `EventTarget` shim. + * This is necessary because not all browsers support constructable + * `EventTarget`, so using a real `EventTarget` will error. + * @private + */ +export declare class WorkboxEventTarget { + private readonly _eventListenerRegistry; + /** + * @param {string} type + * @param {Function} listener + * @private + */ + addEventListener(type: K, listener: (event: WorkboxEventMap[K]) => any): void; + /** + * @param {string} type + * @param {Function} listener + * @private + */ + removeEventListener(type: K, listener: (event: WorkboxEventMap[K]) => any): void; + /** + * @param {Object} event + * @private + */ + dispatchEvent(event: WorkboxEvent): void; + /** + * Returns a Set of listeners associated with the passed event type. + * If no handlers have been registered, an empty Set is returned. + * + * @param {string} type The event type. + * @return {Set} An array of handler functions. + * @private + */ + private _getEventListenersByType; +} diff --git a/node_modules/workbox-window/utils/WorkboxEventTarget.js b/node_modules/workbox-window/utils/WorkboxEventTarget.js new file mode 100644 index 0000000000000000000000000000000000000000..73e6fe233e86dd370be08e472e451b4bae2864fb --- /dev/null +++ b/node_modules/workbox-window/utils/WorkboxEventTarget.js @@ -0,0 +1,60 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +/** + * A minimal `EventTarget` shim. + * This is necessary because not all browsers support constructable + * `EventTarget`, so using a real `EventTarget` will error. + * @private + */ +export class WorkboxEventTarget { + constructor() { + this._eventListenerRegistry = new Map(); + } + /** + * @param {string} type + * @param {Function} listener + * @private + */ + addEventListener(type, listener) { + const foo = this._getEventListenersByType(type); + foo.add(listener); + } + /** + * @param {string} type + * @param {Function} listener + * @private + */ + removeEventListener(type, listener) { + this._getEventListenersByType(type).delete(listener); + } + /** + * @param {Object} event + * @private + */ + dispatchEvent(event) { + event.target = this; + const listeners = this._getEventListenersByType(event.type); + for (const listener of listeners) { + listener(event); + } + } + /** + * Returns a Set of listeners associated with the passed event type. + * If no handlers have been registered, an empty Set is returned. + * + * @param {string} type The event type. + * @return {Set} An array of handler functions. + * @private + */ + _getEventListenersByType(type) { + if (!this._eventListenerRegistry.has(type)) { + this._eventListenerRegistry.set(type, new Set()); + } + return this._eventListenerRegistry.get(type); + } +} diff --git a/node_modules/workbox-window/utils/WorkboxEventTarget.mjs b/node_modules/workbox-window/utils/WorkboxEventTarget.mjs new file mode 100644 index 0000000000000000000000000000000000000000..be5d13fdd71d202f1bfb02d232b1d12c376a8daf --- /dev/null +++ b/node_modules/workbox-window/utils/WorkboxEventTarget.mjs @@ -0,0 +1 @@ +export * from './WorkboxEventTarget.js'; \ No newline at end of file diff --git a/node_modules/workbox-window/utils/urlsMatch.d.ts b/node_modules/workbox-window/utils/urlsMatch.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..48908072895cdd752358fa2561e0080a1668450e --- /dev/null +++ b/node_modules/workbox-window/utils/urlsMatch.d.ts @@ -0,0 +1,11 @@ +import '../_version.js'; +/** + * Returns true if two URLs have the same `.href` property. The URLS can be + * relative, and if they are the current location href is used to resolve URLs. + * + * @private + * @param {string} url1 + * @param {string} url2 + * @return {boolean} + */ +export declare function urlsMatch(url1: string, url2: string): boolean; diff --git a/node_modules/workbox-window/utils/urlsMatch.js b/node_modules/workbox-window/utils/urlsMatch.js new file mode 100644 index 0000000000000000000000000000000000000000..002447165aab348c2eb8290378e44d538accafb8 --- /dev/null +++ b/node_modules/workbox-window/utils/urlsMatch.js @@ -0,0 +1,21 @@ +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +import '../_version.js'; +/** + * Returns true if two URLs have the same `.href` property. The URLS can be + * relative, and if they are the current location href is used to resolve URLs. + * + * @private + * @param {string} url1 + * @param {string} url2 + * @return {boolean} + */ +export function urlsMatch(url1, url2) { + const { href } = location; + return new URL(url1, href).href === new URL(url2, href).href; +} diff --git a/node_modules/workbox-window/utils/urlsMatch.mjs b/node_modules/workbox-window/utils/urlsMatch.mjs new file mode 100644 index 0000000000000000000000000000000000000000..cd871a5eb0579b7febd10a082ff77f8560865b71 --- /dev/null +++ b/node_modules/workbox-window/utils/urlsMatch.mjs @@ -0,0 +1 @@ +export * from './urlsMatch.js'; \ No newline at end of file diff --git a/node_modules/wrap-ansi/index.d.ts b/node_modules/wrap-ansi/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ba9833829e70c0c039a594c78c84498e6826c2ec --- /dev/null +++ b/node_modules/wrap-ansi/index.d.ts @@ -0,0 +1,41 @@ +export type Options = { + /** + By default the wrap is soft, meaning long words may extend past the column width. Setting this to `true` will make it hard wrap at the column width. + + @default false + */ + readonly hard?: boolean; + + /** + By default, an attempt is made to split words at spaces, ensuring that they don't extend past the configured columns. If wordWrap is `false`, each column will instead be completely filled splitting words as necessary. + + @default true + */ + readonly wordWrap?: boolean; + + /** + Whitespace on all lines is removed by default. Set this option to `false` if you don't want to trim. + + @default true + */ + readonly trim?: boolean; +}; + +/** +Wrap words to the specified column width. + +@param string - A string with ANSI escape codes, like one styled by [`chalk`](https://github.com/chalk/chalk). Newline characters will be normalized to `\n`. +@param columns - The number of columns to wrap the text to. + +@example +``` +import chalk from 'chalk'; +import wrapAnsi from 'wrap-ansi'; + +const input = 'The quick brown ' + chalk.red('fox jumped over ') + + 'the lazy ' + chalk.green('dog and then ran away with the unicorn.'); + +console.log(wrapAnsi(input, 20)); +``` +*/ +export default function wrapAnsi(string: string, columns: number, options?: Options): string; diff --git a/node_modules/wrap-ansi/index.js b/node_modules/wrap-ansi/index.js new file mode 100644 index 0000000000000000000000000000000000000000..10bd0bf71597e7d99074827af3e65ad68ff303c5 --- /dev/null +++ b/node_modules/wrap-ansi/index.js @@ -0,0 +1,222 @@ +import stringWidth from 'string-width'; +import stripAnsi from 'strip-ansi'; +import ansiStyles from 'ansi-styles'; + +const ESCAPES = new Set([ + '\u001B', + '\u009B', +]); + +const END_CODE = 39; +const ANSI_ESCAPE_BELL = '\u0007'; +const ANSI_CSI = '['; +const ANSI_OSC = ']'; +const ANSI_SGR_TERMINATOR = 'm'; +const ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`; + +const wrapAnsiCode = code => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`; +const wrapAnsiHyperlink = url => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`; + +// Calculate the length of words split on ' ', ignoring +// the extra characters added by ansi escape codes +const wordLengths = string => string.split(' ').map(character => stringWidth(character)); + +// Wrap a long word across multiple rows +// Ansi escape codes do not count towards length +const wrapWord = (rows, word, columns) => { + const characters = [...word]; + + let isInsideEscape = false; + let isInsideLinkEscape = false; + let visible = stringWidth(stripAnsi(rows.at(-1))); + + for (const [index, character] of characters.entries()) { + const characterLength = stringWidth(character); + + if (visible + characterLength <= columns) { + rows[rows.length - 1] += character; + } else { + rows.push(character); + visible = 0; + } + + if (ESCAPES.has(character)) { + isInsideEscape = true; + + const ansiEscapeLinkCandidate = characters.slice(index + 1, index + 1 + ANSI_ESCAPE_LINK.length).join(''); + isInsideLinkEscape = ansiEscapeLinkCandidate === ANSI_ESCAPE_LINK; + } + + if (isInsideEscape) { + if (isInsideLinkEscape) { + if (character === ANSI_ESCAPE_BELL) { + isInsideEscape = false; + isInsideLinkEscape = false; + } + } else if (character === ANSI_SGR_TERMINATOR) { + isInsideEscape = false; + } + + continue; + } + + visible += characterLength; + + if (visible === columns && index < characters.length - 1) { + rows.push(''); + visible = 0; + } + } + + // It's possible that the last row we copy over is only + // ansi escape characters, handle this edge-case + if (!visible && rows.at(-1).length > 0 && rows.length > 1) { + rows[rows.length - 2] += rows.pop(); + } +}; + +// Trims spaces from a string ignoring invisible sequences +const stringVisibleTrimSpacesRight = string => { + const words = string.split(' '); + let last = words.length; + + while (last > 0) { + if (stringWidth(words[last - 1]) > 0) { + break; + } + + last--; + } + + if (last === words.length) { + return string; + } + + return words.slice(0, last).join(' ') + words.slice(last).join(''); +}; + +// The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode. +// +// 'hard' will never allow a string to take up more than columns characters. +// +// 'soft' allows long words to expand past the column length. +const exec = (string, columns, options = {}) => { + if (options.trim !== false && string.trim() === '') { + return ''; + } + + let returnValue = ''; + let escapeCode; + let escapeUrl; + + const lengths = wordLengths(string); + let rows = ['']; + + for (const [index, word] of string.split(' ').entries()) { + if (options.trim !== false) { + rows[rows.length - 1] = rows.at(-1).trimStart(); + } + + let rowLength = stringWidth(rows.at(-1)); + + if (index !== 0) { + if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) { + // If we start with a new word but the current row length equals the length of the columns, add a new row + rows.push(''); + rowLength = 0; + } + + if (rowLength > 0 || options.trim === false) { + rows[rows.length - 1] += ' '; + rowLength++; + } + } + + // In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns' + if (options.hard && lengths[index] > columns) { + const remainingColumns = (columns - rowLength); + const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns); + const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns); + if (breaksStartingNextLine < breaksStartingThisLine) { + rows.push(''); + } + + wrapWord(rows, word, columns); + continue; + } + + if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) { + if (options.wordWrap === false && rowLength < columns) { + wrapWord(rows, word, columns); + continue; + } + + rows.push(''); + } + + if (rowLength + lengths[index] > columns && options.wordWrap === false) { + wrapWord(rows, word, columns); + continue; + } + + rows[rows.length - 1] += word; + } + + if (options.trim !== false) { + rows = rows.map(row => stringVisibleTrimSpacesRight(row)); + } + + const preString = rows.join('\n'); + const pre = [...preString]; + + // We need to keep a separate index as `String#slice()` works on Unicode code units, while `pre` is an array of codepoints. + let preStringIndex = 0; + + for (const [index, character] of pre.entries()) { + returnValue += character; + + if (ESCAPES.has(character)) { + const {groups} = new RegExp(`(?:\\${ANSI_CSI}(?\\d+)m|\\${ANSI_ESCAPE_LINK}(?.*)${ANSI_ESCAPE_BELL})`).exec(preString.slice(preStringIndex)) || {groups: {}}; + if (groups.code !== undefined) { + const code = Number.parseFloat(groups.code); + escapeCode = code === END_CODE ? undefined : code; + } else if (groups.uri !== undefined) { + escapeUrl = groups.uri.length === 0 ? undefined : groups.uri; + } + } + + const code = ansiStyles.codes.get(Number(escapeCode)); + + if (pre[index + 1] === '\n') { + if (escapeUrl) { + returnValue += wrapAnsiHyperlink(''); + } + + if (escapeCode && code) { + returnValue += wrapAnsiCode(code); + } + } else if (character === '\n') { + if (escapeCode && code) { + returnValue += wrapAnsiCode(escapeCode); + } + + if (escapeUrl) { + returnValue += wrapAnsiHyperlink(escapeUrl); + } + } + + preStringIndex += character.length; + } + + return returnValue; +}; + +// For each newline, invoke the method separately +export default function wrapAnsi(string, columns, options) { + return String(string) + .normalize() + .replaceAll('\r\n', '\n') + .split('\n') + .map(line => exec(line, columns, options)) + .join('\n'); +} diff --git a/node_modules/wrap-ansi/license b/node_modules/wrap-ansi/license new file mode 100644 index 0000000000000000000000000000000000000000..fa7ceba3eb4a9657a9db7f3ffca4e4e97a9019de --- /dev/null +++ b/node_modules/wrap-ansi/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/wrap-ansi/package.json b/node_modules/wrap-ansi/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9c9695f146024299a7dbb591e844f2f12f04b775 --- /dev/null +++ b/node_modules/wrap-ansi/package.json @@ -0,0 +1,69 @@ +{ + "name": "wrap-ansi", + "version": "9.0.2", + "description": "Wordwrap a string with ANSI escape codes", + "license": "MIT", + "repository": "chalk/wrap-ansi", + "funding": "https://github.com/chalk/wrap-ansi?sponsor=1", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "type": "module", + "exports": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "engines": { + "node": ">=18" + }, + "scripts": { + "test": "xo && nyc ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "wrap", + "break", + "wordwrap", + "wordbreak", + "linewrap", + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "devDependencies": { + "ava": "^5.3.1", + "chalk": "^5.3.0", + "coveralls": "^3.1.1", + "has-ansi": "^5.0.1", + "nyc": "^15.1.0", + "tsd": "^0.29.0", + "xo": "^0.56.0" + } +} diff --git a/node_modules/wrap-ansi/readme.md b/node_modules/wrap-ansi/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..86327dcd69bf32e6e59cd8e09ca0ac3829f20e6f --- /dev/null +++ b/node_modules/wrap-ansi/readme.md @@ -0,0 +1,75 @@ +# wrap-ansi + +> Wordwrap a string with [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) + +## Install + +```sh +npm install wrap-ansi +``` + +## Usage + +```js +import chalk from 'chalk'; +import wrapAnsi from 'wrap-ansi'; + +const input = 'The quick brown ' + chalk.red('fox jumped over ') + + 'the lazy ' + chalk.green('dog and then ran away with the unicorn.'); + +console.log(wrapAnsi(input, 20)); +``` + + + +## API + +### wrapAnsi(string, columns, options?) + +Wrap words to the specified column width. + +#### string + +Type: `string` + +A string with ANSI escape codes, like one styled by [`chalk`](https://github.com/chalk/chalk). + +Newline characters will be normalized to `\n`. + +#### columns + +Type: `number` + +The number of columns to wrap the text to. + +#### options + +Type: `object` + +##### hard + +Type: `boolean`\ +Default: `false` + +By default the wrap is soft, meaning long words may extend past the column width. Setting this to `true` will make it hard wrap at the column width. + +##### wordWrap + +Type: `boolean`\ +Default: `true` + +By default, an attempt is made to split words at spaces, ensuring that they don't extend past the configured columns. If wordWrap is `false`, each column will instead be completely filled splitting words as necessary. + +##### trim + +Type: `boolean`\ +Default: `true` + +Whitespace on all lines is removed by default. Set this option to `false` if you don't want to trim. + +## Related + +- [slice-ansi](https://github.com/chalk/slice-ansi) - Slice a string with ANSI escape codes +- [cli-truncate](https://github.com/sindresorhus/cli-truncate) - Truncate a string to a specific width in the terminal +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right +- [jsesc](https://github.com/mathiasbynens/jsesc) - Generate ASCII-only output from Unicode strings. Useful for creating test fixtures. diff --git a/node_modules/wrappy/LICENSE b/node_modules/wrappy/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..19129e315fe593965a2fdd50ec0d1253bcbd2ece --- /dev/null +++ b/node_modules/wrappy/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/wrappy/README.md b/node_modules/wrappy/README.md new file mode 100644 index 0000000000000000000000000000000000000000..98eab2522b86e5fe32c92524c4ec778b98066cbf --- /dev/null +++ b/node_modules/wrappy/README.md @@ -0,0 +1,36 @@ +# wrappy + +Callback wrapping utility + +## USAGE + +```javascript +var wrappy = require("wrappy") + +// var wrapper = wrappy(wrapperFunction) + +// make sure a cb is called only once +// See also: http://npm.im/once for this specific use case +var once = wrappy(function (cb) { + var called = false + return function () { + if (called) return + called = true + return cb.apply(this, arguments) + } +}) + +function printBoo () { + console.log('boo') +} +// has some rando property +printBoo.iAmBooPrinter = true + +var onlyPrintOnce = once(printBoo) + +onlyPrintOnce() // prints 'boo' +onlyPrintOnce() // does nothing + +// random property is retained! +assert.equal(onlyPrintOnce.iAmBooPrinter, true) +``` diff --git a/node_modules/wrappy/package.json b/node_modules/wrappy/package.json new file mode 100644 index 0000000000000000000000000000000000000000..130752046714d686d4b76ce039375d75293d74c5 --- /dev/null +++ b/node_modules/wrappy/package.json @@ -0,0 +1,29 @@ +{ + "name": "wrappy", + "version": "1.0.2", + "description": "Callback wrapping utility", + "main": "wrappy.js", + "files": [ + "wrappy.js" + ], + "directories": { + "test": "test" + }, + "dependencies": {}, + "devDependencies": { + "tap": "^2.3.1" + }, + "scripts": { + "test": "tap --coverage test/*.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/npm/wrappy" + }, + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC", + "bugs": { + "url": "https://github.com/npm/wrappy/issues" + }, + "homepage": "https://github.com/npm/wrappy" +} diff --git a/node_modules/wrappy/wrappy.js b/node_modules/wrappy/wrappy.js new file mode 100644 index 0000000000000000000000000000000000000000..bb7e7d6fcf70fdff4c5a48b7fa2ae3c9ba36fe47 --- /dev/null +++ b/node_modules/wrappy/wrappy.js @@ -0,0 +1,33 @@ +// Returns a wrapper function that returns a wrapped callback +// The wrapper function should do some stuff, and return a +// presumably different callback function. +// This makes sure that own properties are retained, so that +// decorations and such are not lost along the way. +module.exports = wrappy +function wrappy (fn, cb) { + if (fn && cb) return wrappy(fn)(cb) + + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') + + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k] + }) + + return wrapper + + function wrapper() { + var args = new Array(arguments.length) + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + var ret = fn.apply(this, args) + var cb = args[args.length-1] + if (typeof ret === 'function' && ret !== cb) { + Object.keys(cb).forEach(function (k) { + ret[k] = cb[k] + }) + } + return ret + } +} diff --git a/node_modules/ws/LICENSE b/node_modules/ws/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1da5b96a11ac2c83160e3085188f04eba7e3dd7d --- /dev/null +++ b/node_modules/ws/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2011 Einar Otto Stangvik +Copyright (c) 2013 Arnout Kazemier and contributors +Copyright (c) 2016 Luigi Pinca and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/ws/README.md b/node_modules/ws/README.md new file mode 100644 index 0000000000000000000000000000000000000000..21f10df108e11042e02b9b9cb81528d2951e18e8 --- /dev/null +++ b/node_modules/ws/README.md @@ -0,0 +1,548 @@ +# ws: a Node.js WebSocket library + +[![Version npm](https://img.shields.io/npm/v/ws.svg?logo=npm)](https://www.npmjs.com/package/ws) +[![CI](https://img.shields.io/github/actions/workflow/status/websockets/ws/ci.yml?branch=master&label=CI&logo=github)](https://github.com/websockets/ws/actions?query=workflow%3ACI+branch%3Amaster) +[![Coverage Status](https://img.shields.io/coveralls/websockets/ws/master.svg?logo=coveralls)](https://coveralls.io/github/websockets/ws) + +ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and +server implementation. + +Passes the quite extensive Autobahn test suite: [server][server-report], +[client][client-report]. + +**Note**: This module does not work in the browser. The client in the docs is a +reference to a backend with the role of a client in the WebSocket communication. +Browser clients must use the native +[`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) +object. To make the same code work seamlessly on Node.js and the browser, you +can use one of the many wrappers available on npm, like +[isomorphic-ws](https://github.com/heineiuo/isomorphic-ws). + +## Table of Contents + +- [Protocol support](#protocol-support) +- [Installing](#installing) + - [Opt-in for performance](#opt-in-for-performance) + - [Legacy opt-in for performance](#legacy-opt-in-for-performance) +- [API docs](#api-docs) +- [WebSocket compression](#websocket-compression) +- [Usage examples](#usage-examples) + - [Sending and receiving text data](#sending-and-receiving-text-data) + - [Sending binary data](#sending-binary-data) + - [Simple server](#simple-server) + - [External HTTP/S server](#external-https-server) + - [Multiple servers sharing a single HTTP/S server](#multiple-servers-sharing-a-single-https-server) + - [Client authentication](#client-authentication) + - [Server broadcast](#server-broadcast) + - [Round-trip time](#round-trip-time) + - [Use the Node.js streams API](#use-the-nodejs-streams-api) + - [Other examples](#other-examples) +- [FAQ](#faq) + - [How to get the IP address of the client?](#how-to-get-the-ip-address-of-the-client) + - [How to detect and close broken connections?](#how-to-detect-and-close-broken-connections) + - [How to connect via a proxy?](#how-to-connect-via-a-proxy) +- [Changelog](#changelog) +- [License](#license) + +## Protocol support + +- **HyBi drafts 07-12** (Use the option `protocolVersion: 8`) +- **HyBi drafts 13-17** (Current default, alternatively option + `protocolVersion: 13`) + +## Installing + +``` +npm install ws +``` + +### Opt-in for performance + +[bufferutil][] is an optional module that can be installed alongside the ws +module: + +``` +npm install --save-optional bufferutil +``` + +This is a binary addon that improves the performance of certain operations such +as masking and unmasking the data payload of the WebSocket frames. Prebuilt +binaries are available for the most popular platforms, so you don't necessarily +need to have a C++ compiler installed on your machine. + +To force ws to not use bufferutil, use the +[`WS_NO_BUFFER_UTIL`](./doc/ws.md#ws_no_buffer_util) environment variable. This +can be useful to enhance security in systems where a user can put a package in +the package search path of an application of another user, due to how the +Node.js resolver algorithm works. + +#### Legacy opt-in for performance + +If you are running on an old version of Node.js (prior to v18.14.0), ws also +supports the [utf-8-validate][] module: + +``` +npm install --save-optional utf-8-validate +``` + +This contains a binary polyfill for [`buffer.isUtf8()`][]. + +To force ws not to use utf-8-validate, use the +[`WS_NO_UTF_8_VALIDATE`](./doc/ws.md#ws_no_utf_8_validate) environment variable. + +## API docs + +See [`/doc/ws.md`](./doc/ws.md) for Node.js-like documentation of ws classes and +utility functions. + +## WebSocket compression + +ws supports the [permessage-deflate extension][permessage-deflate] which enables +the client and server to negotiate a compression algorithm and its parameters, +and then selectively apply it to the data payloads of each WebSocket message. + +The extension is disabled by default on the server and enabled by default on the +client. It adds a significant overhead in terms of performance and memory +consumption so we suggest to enable it only if it is really needed. + +Note that Node.js has a variety of issues with high-performance compression, +where increased concurrency, especially on Linux, can lead to [catastrophic +memory fragmentation][node-zlib-bug] and slow performance. If you intend to use +permessage-deflate in production, it is worthwhile to set up a test +representative of your workload and ensure Node.js/zlib will handle it with +acceptable performance and memory usage. + +Tuning of permessage-deflate can be done via the options defined below. You can +also use `zlibDeflateOptions` and `zlibInflateOptions`, which is passed directly +into the creation of [raw deflate/inflate streams][node-zlib-deflaterawdocs]. + +See [the docs][ws-server-options] for more options. + +```js +import WebSocket, { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ + port: 8080, + perMessageDeflate: { + zlibDeflateOptions: { + // See zlib defaults. + chunkSize: 1024, + memLevel: 7, + level: 3 + }, + zlibInflateOptions: { + chunkSize: 10 * 1024 + }, + // Other options settable: + clientNoContextTakeover: true, // Defaults to negotiated value. + serverNoContextTakeover: true, // Defaults to negotiated value. + serverMaxWindowBits: 10, // Defaults to negotiated value. + // Below options specified as default values. + concurrencyLimit: 10, // Limits zlib concurrency for perf. + threshold: 1024 // Size (in bytes) below which messages + // should not be compressed if context takeover is disabled. + } +}); +``` + +The client will only use the extension if it is supported and enabled on the +server. To always disable the extension on the client, set the +`perMessageDeflate` option to `false`. + +```js +import WebSocket from 'ws'; + +const ws = new WebSocket('ws://www.host.com/path', { + perMessageDeflate: false +}); +``` + +## Usage examples + +### Sending and receiving text data + +```js +import WebSocket from 'ws'; + +const ws = new WebSocket('ws://www.host.com/path'); + +ws.on('error', console.error); + +ws.on('open', function open() { + ws.send('something'); +}); + +ws.on('message', function message(data) { + console.log('received: %s', data); +}); +``` + +### Sending binary data + +```js +import WebSocket from 'ws'; + +const ws = new WebSocket('ws://www.host.com/path'); + +ws.on('error', console.error); + +ws.on('open', function open() { + const array = new Float32Array(5); + + for (var i = 0; i < array.length; ++i) { + array[i] = i / 2; + } + + ws.send(array); +}); +``` + +### Simple server + +```js +import { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.on('error', console.error); + + ws.on('message', function message(data) { + console.log('received: %s', data); + }); + + ws.send('something'); +}); +``` + +### External HTTP/S server + +```js +import { createServer } from 'https'; +import { readFileSync } from 'fs'; +import { WebSocketServer } from 'ws'; + +const server = createServer({ + cert: readFileSync('/path/to/cert.pem'), + key: readFileSync('/path/to/key.pem') +}); +const wss = new WebSocketServer({ server }); + +wss.on('connection', function connection(ws) { + ws.on('error', console.error); + + ws.on('message', function message(data) { + console.log('received: %s', data); + }); + + ws.send('something'); +}); + +server.listen(8080); +``` + +### Multiple servers sharing a single HTTP/S server + +```js +import { createServer } from 'http'; +import { WebSocketServer } from 'ws'; + +const server = createServer(); +const wss1 = new WebSocketServer({ noServer: true }); +const wss2 = new WebSocketServer({ noServer: true }); + +wss1.on('connection', function connection(ws) { + ws.on('error', console.error); + + // ... +}); + +wss2.on('connection', function connection(ws) { + ws.on('error', console.error); + + // ... +}); + +server.on('upgrade', function upgrade(request, socket, head) { + const { pathname } = new URL(request.url, 'wss://base.url'); + + if (pathname === '/foo') { + wss1.handleUpgrade(request, socket, head, function done(ws) { + wss1.emit('connection', ws, request); + }); + } else if (pathname === '/bar') { + wss2.handleUpgrade(request, socket, head, function done(ws) { + wss2.emit('connection', ws, request); + }); + } else { + socket.destroy(); + } +}); + +server.listen(8080); +``` + +### Client authentication + +```js +import { createServer } from 'http'; +import { WebSocketServer } from 'ws'; + +function onSocketError(err) { + console.error(err); +} + +const server = createServer(); +const wss = new WebSocketServer({ noServer: true }); + +wss.on('connection', function connection(ws, request, client) { + ws.on('error', console.error); + + ws.on('message', function message(data) { + console.log(`Received message ${data} from user ${client}`); + }); +}); + +server.on('upgrade', function upgrade(request, socket, head) { + socket.on('error', onSocketError); + + // This function is not defined on purpose. Implement it with your own logic. + authenticate(request, function next(err, client) { + if (err || !client) { + socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n'); + socket.destroy(); + return; + } + + socket.removeListener('error', onSocketError); + + wss.handleUpgrade(request, socket, head, function done(ws) { + wss.emit('connection', ws, request, client); + }); + }); +}); + +server.listen(8080); +``` + +Also see the provided [example][session-parse-example] using `express-session`. + +### Server broadcast + +A client WebSocket broadcasting to all connected WebSocket clients, including +itself. + +```js +import WebSocket, { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.on('error', console.error); + + ws.on('message', function message(data, isBinary) { + wss.clients.forEach(function each(client) { + if (client.readyState === WebSocket.OPEN) { + client.send(data, { binary: isBinary }); + } + }); + }); +}); +``` + +A client WebSocket broadcasting to every other connected WebSocket clients, +excluding itself. + +```js +import WebSocket, { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.on('error', console.error); + + ws.on('message', function message(data, isBinary) { + wss.clients.forEach(function each(client) { + if (client !== ws && client.readyState === WebSocket.OPEN) { + client.send(data, { binary: isBinary }); + } + }); + }); +}); +``` + +### Round-trip time + +```js +import WebSocket from 'ws'; + +const ws = new WebSocket('wss://websocket-echo.com/'); + +ws.on('error', console.error); + +ws.on('open', function open() { + console.log('connected'); + ws.send(Date.now()); +}); + +ws.on('close', function close() { + console.log('disconnected'); +}); + +ws.on('message', function message(data) { + console.log(`Round-trip time: ${Date.now() - data} ms`); + + setTimeout(function timeout() { + ws.send(Date.now()); + }, 500); +}); +``` + +### Use the Node.js streams API + +```js +import WebSocket, { createWebSocketStream } from 'ws'; + +const ws = new WebSocket('wss://websocket-echo.com/'); + +const duplex = createWebSocketStream(ws, { encoding: 'utf8' }); + +duplex.on('error', console.error); + +duplex.pipe(process.stdout); +process.stdin.pipe(duplex); +``` + +### Other examples + +For a full example with a browser client communicating with a ws server, see the +examples folder. + +Otherwise, see the test cases. + +## FAQ + +### How to get the IP address of the client? + +The remote IP address can be obtained from the raw socket. + +```js +import { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws, req) { + const ip = req.socket.remoteAddress; + + ws.on('error', console.error); +}); +``` + +When the server runs behind a proxy like NGINX, the de-facto standard is to use +the `X-Forwarded-For` header. + +```js +wss.on('connection', function connection(ws, req) { + const ip = req.headers['x-forwarded-for'].split(',')[0].trim(); + + ws.on('error', console.error); +}); +``` + +### How to detect and close broken connections? + +Sometimes, the link between the server and the client can be interrupted in a +way that keeps both the server and the client unaware of the broken state of the +connection (e.g. when pulling the cord). + +In these cases, ping messages can be used as a means to verify that the remote +endpoint is still responsive. + +```js +import { WebSocketServer } from 'ws'; + +function heartbeat() { + this.isAlive = true; +} + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.isAlive = true; + ws.on('error', console.error); + ws.on('pong', heartbeat); +}); + +const interval = setInterval(function ping() { + wss.clients.forEach(function each(ws) { + if (ws.isAlive === false) return ws.terminate(); + + ws.isAlive = false; + ws.ping(); + }); +}, 30000); + +wss.on('close', function close() { + clearInterval(interval); +}); +``` + +Pong messages are automatically sent in response to ping messages as required by +the spec. + +Just like the server example above, your clients might as well lose connection +without knowing it. You might want to add a ping listener on your clients to +prevent that. A simple implementation would be: + +```js +import WebSocket from 'ws'; + +function heartbeat() { + clearTimeout(this.pingTimeout); + + // Use `WebSocket#terminate()`, which immediately destroys the connection, + // instead of `WebSocket#close()`, which waits for the close timer. + // Delay should be equal to the interval at which your server + // sends out pings plus a conservative assumption of the latency. + this.pingTimeout = setTimeout(() => { + this.terminate(); + }, 30000 + 1000); +} + +const client = new WebSocket('wss://websocket-echo.com/'); + +client.on('error', console.error); +client.on('open', heartbeat); +client.on('ping', heartbeat); +client.on('close', function clear() { + clearTimeout(this.pingTimeout); +}); +``` + +### How to connect via a proxy? + +Use a custom `http.Agent` implementation like [https-proxy-agent][] or +[socks-proxy-agent][]. + +## Changelog + +We're using the GitHub [releases][changelog] for changelog entries. + +## License + +[MIT](LICENSE) + +[`buffer.isutf8()`]: https://nodejs.org/api/buffer.html#bufferisutf8input +[bufferutil]: https://github.com/websockets/bufferutil +[changelog]: https://github.com/websockets/ws/releases +[client-report]: http://websockets.github.io/ws/autobahn/clients/ +[https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent +[node-zlib-bug]: https://github.com/nodejs/node/issues/8871 +[node-zlib-deflaterawdocs]: + https://nodejs.org/api/zlib.html#zlib_zlib_createdeflateraw_options +[permessage-deflate]: https://tools.ietf.org/html/rfc7692 +[server-report]: http://websockets.github.io/ws/autobahn/servers/ +[session-parse-example]: ./examples/express-session-parse +[socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent +[utf-8-validate]: https://github.com/websockets/utf-8-validate +[ws-server-options]: ./doc/ws.md#new-websocketserveroptions-callback diff --git a/node_modules/ws/browser.js b/node_modules/ws/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..ca4f628ac17c80e5b1d40910d1b18c605490deda --- /dev/null +++ b/node_modules/ws/browser.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = function () { + throw new Error( + 'ws does not work in the browser. Browser clients must use the native ' + + 'WebSocket object' + ); +}; diff --git a/node_modules/ws/index.js b/node_modules/ws/index.js new file mode 100644 index 0000000000000000000000000000000000000000..3fdb7b21030c13e27777d6349ab09ed2d9910c01 --- /dev/null +++ b/node_modules/ws/index.js @@ -0,0 +1,22 @@ +'use strict'; + +const createWebSocketStream = require('./lib/stream'); +const extension = require('./lib/extension'); +const PerMessageDeflate = require('./lib/permessage-deflate'); +const Receiver = require('./lib/receiver'); +const Sender = require('./lib/sender'); +const subprotocol = require('./lib/subprotocol'); +const WebSocket = require('./lib/websocket'); +const WebSocketServer = require('./lib/websocket-server'); + +WebSocket.createWebSocketStream = createWebSocketStream; +WebSocket.extension = extension; +WebSocket.PerMessageDeflate = PerMessageDeflate; +WebSocket.Receiver = Receiver; +WebSocket.Sender = Sender; +WebSocket.Server = WebSocketServer; +WebSocket.subprotocol = subprotocol; +WebSocket.WebSocket = WebSocket; +WebSocket.WebSocketServer = WebSocketServer; + +module.exports = WebSocket; diff --git a/node_modules/ws/lib/buffer-util.js b/node_modules/ws/lib/buffer-util.js new file mode 100644 index 0000000000000000000000000000000000000000..f7536e28efa570277e30e9ea001200ee11595fee --- /dev/null +++ b/node_modules/ws/lib/buffer-util.js @@ -0,0 +1,131 @@ +'use strict'; + +const { EMPTY_BUFFER } = require('./constants'); + +const FastBuffer = Buffer[Symbol.species]; + +/** + * Merges an array of buffers into a new buffer. + * + * @param {Buffer[]} list The array of buffers to concat + * @param {Number} totalLength The total length of buffers in the list + * @return {Buffer} The resulting buffer + * @public + */ +function concat(list, totalLength) { + if (list.length === 0) return EMPTY_BUFFER; + if (list.length === 1) return list[0]; + + const target = Buffer.allocUnsafe(totalLength); + let offset = 0; + + for (let i = 0; i < list.length; i++) { + const buf = list[i]; + target.set(buf, offset); + offset += buf.length; + } + + if (offset < totalLength) { + return new FastBuffer(target.buffer, target.byteOffset, offset); + } + + return target; +} + +/** + * Masks a buffer using the given mask. + * + * @param {Buffer} source The buffer to mask + * @param {Buffer} mask The mask to use + * @param {Buffer} output The buffer where to store the result + * @param {Number} offset The offset at which to start writing + * @param {Number} length The number of bytes to mask. + * @public + */ +function _mask(source, mask, output, offset, length) { + for (let i = 0; i < length; i++) { + output[offset + i] = source[i] ^ mask[i & 3]; + } +} + +/** + * Unmasks a buffer using the given mask. + * + * @param {Buffer} buffer The buffer to unmask + * @param {Buffer} mask The mask to use + * @public + */ +function _unmask(buffer, mask) { + for (let i = 0; i < buffer.length; i++) { + buffer[i] ^= mask[i & 3]; + } +} + +/** + * Converts a buffer to an `ArrayBuffer`. + * + * @param {Buffer} buf The buffer to convert + * @return {ArrayBuffer} Converted buffer + * @public + */ +function toArrayBuffer(buf) { + if (buf.length === buf.buffer.byteLength) { + return buf.buffer; + } + + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length); +} + +/** + * Converts `data` to a `Buffer`. + * + * @param {*} data The data to convert + * @return {Buffer} The buffer + * @throws {TypeError} + * @public + */ +function toBuffer(data) { + toBuffer.readOnly = true; + + if (Buffer.isBuffer(data)) return data; + + let buf; + + if (data instanceof ArrayBuffer) { + buf = new FastBuffer(data); + } else if (ArrayBuffer.isView(data)) { + buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength); + } else { + buf = Buffer.from(data); + toBuffer.readOnly = false; + } + + return buf; +} + +module.exports = { + concat, + mask: _mask, + toArrayBuffer, + toBuffer, + unmask: _unmask +}; + +/* istanbul ignore else */ +if (!process.env.WS_NO_BUFFER_UTIL) { + try { + const bufferUtil = require('bufferutil'); + + module.exports.mask = function (source, mask, output, offset, length) { + if (length < 48) _mask(source, mask, output, offset, length); + else bufferUtil.mask(source, mask, output, offset, length); + }; + + module.exports.unmask = function (buffer, mask) { + if (buffer.length < 32) _unmask(buffer, mask); + else bufferUtil.unmask(buffer, mask); + }; + } catch (e) { + // Continue regardless of the error. + } +} diff --git a/node_modules/ws/lib/constants.js b/node_modules/ws/lib/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..69b2fe3c43f5fb4323b7540ea1a4f1d3ddfc2d5c --- /dev/null +++ b/node_modules/ws/lib/constants.js @@ -0,0 +1,19 @@ +'use strict'; + +const BINARY_TYPES = ['nodebuffer', 'arraybuffer', 'fragments']; +const hasBlob = typeof Blob !== 'undefined'; + +if (hasBlob) BINARY_TYPES.push('blob'); + +module.exports = { + BINARY_TYPES, + CLOSE_TIMEOUT: 30000, + EMPTY_BUFFER: Buffer.alloc(0), + GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', + hasBlob, + kForOnEventAttribute: Symbol('kIsForOnEventAttribute'), + kListener: Symbol('kListener'), + kStatusCode: Symbol('status-code'), + kWebSocket: Symbol('websocket'), + NOOP: () => {} +}; diff --git a/node_modules/ws/lib/event-target.js b/node_modules/ws/lib/event-target.js new file mode 100644 index 0000000000000000000000000000000000000000..fea4cbc52c3299d0bd5fea32245360594812b5a5 --- /dev/null +++ b/node_modules/ws/lib/event-target.js @@ -0,0 +1,292 @@ +'use strict'; + +const { kForOnEventAttribute, kListener } = require('./constants'); + +const kCode = Symbol('kCode'); +const kData = Symbol('kData'); +const kError = Symbol('kError'); +const kMessage = Symbol('kMessage'); +const kReason = Symbol('kReason'); +const kTarget = Symbol('kTarget'); +const kType = Symbol('kType'); +const kWasClean = Symbol('kWasClean'); + +/** + * Class representing an event. + */ +class Event { + /** + * Create a new `Event`. + * + * @param {String} type The name of the event + * @throws {TypeError} If the `type` argument is not specified + */ + constructor(type) { + this[kTarget] = null; + this[kType] = type; + } + + /** + * @type {*} + */ + get target() { + return this[kTarget]; + } + + /** + * @type {String} + */ + get type() { + return this[kType]; + } +} + +Object.defineProperty(Event.prototype, 'target', { enumerable: true }); +Object.defineProperty(Event.prototype, 'type', { enumerable: true }); + +/** + * Class representing a close event. + * + * @extends Event + */ +class CloseEvent extends Event { + /** + * Create a new `CloseEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {Number} [options.code=0] The status code explaining why the + * connection was closed + * @param {String} [options.reason=''] A human-readable string explaining why + * the connection was closed + * @param {Boolean} [options.wasClean=false] Indicates whether or not the + * connection was cleanly closed + */ + constructor(type, options = {}) { + super(type); + + this[kCode] = options.code === undefined ? 0 : options.code; + this[kReason] = options.reason === undefined ? '' : options.reason; + this[kWasClean] = options.wasClean === undefined ? false : options.wasClean; + } + + /** + * @type {Number} + */ + get code() { + return this[kCode]; + } + + /** + * @type {String} + */ + get reason() { + return this[kReason]; + } + + /** + * @type {Boolean} + */ + get wasClean() { + return this[kWasClean]; + } +} + +Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true }); +Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true }); +Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true }); + +/** + * Class representing an error event. + * + * @extends Event + */ +class ErrorEvent extends Event { + /** + * Create a new `ErrorEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {*} [options.error=null] The error that generated this event + * @param {String} [options.message=''] The error message + */ + constructor(type, options = {}) { + super(type); + + this[kError] = options.error === undefined ? null : options.error; + this[kMessage] = options.message === undefined ? '' : options.message; + } + + /** + * @type {*} + */ + get error() { + return this[kError]; + } + + /** + * @type {String} + */ + get message() { + return this[kMessage]; + } +} + +Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true }); +Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true }); + +/** + * Class representing a message event. + * + * @extends Event + */ +class MessageEvent extends Event { + /** + * Create a new `MessageEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {*} [options.data=null] The message content + */ + constructor(type, options = {}) { + super(type); + + this[kData] = options.data === undefined ? null : options.data; + } + + /** + * @type {*} + */ + get data() { + return this[kData]; + } +} + +Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true }); + +/** + * This provides methods for emulating the `EventTarget` interface. It's not + * meant to be used directly. + * + * @mixin + */ +const EventTarget = { + /** + * Register an event listener. + * + * @param {String} type A string representing the event type to listen for + * @param {(Function|Object)} handler The listener to add + * @param {Object} [options] An options object specifies characteristics about + * the event listener + * @param {Boolean} [options.once=false] A `Boolean` indicating that the + * listener should be invoked at most once after being added. If `true`, + * the listener would be automatically removed when invoked. + * @public + */ + addEventListener(type, handler, options = {}) { + for (const listener of this.listeners(type)) { + if ( + !options[kForOnEventAttribute] && + listener[kListener] === handler && + !listener[kForOnEventAttribute] + ) { + return; + } + } + + let wrapper; + + if (type === 'message') { + wrapper = function onMessage(data, isBinary) { + const event = new MessageEvent('message', { + data: isBinary ? data : data.toString() + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'close') { + wrapper = function onClose(code, message) { + const event = new CloseEvent('close', { + code, + reason: message.toString(), + wasClean: this._closeFrameReceived && this._closeFrameSent + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'error') { + wrapper = function onError(error) { + const event = new ErrorEvent('error', { + error, + message: error.message + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'open') { + wrapper = function onOpen() { + const event = new Event('open'); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else { + return; + } + + wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute]; + wrapper[kListener] = handler; + + if (options.once) { + this.once(type, wrapper); + } else { + this.on(type, wrapper); + } + }, + + /** + * Remove an event listener. + * + * @param {String} type A string representing the event type to remove + * @param {(Function|Object)} handler The listener to remove + * @public + */ + removeEventListener(type, handler) { + for (const listener of this.listeners(type)) { + if (listener[kListener] === handler && !listener[kForOnEventAttribute]) { + this.removeListener(type, listener); + break; + } + } + } +}; + +module.exports = { + CloseEvent, + ErrorEvent, + Event, + EventTarget, + MessageEvent +}; + +/** + * Call an event listener + * + * @param {(Function|Object)} listener The listener to call + * @param {*} thisArg The value to use as `this`` when calling the listener + * @param {Event} event The event to pass to the listener + * @private + */ +function callListener(listener, thisArg, event) { + if (typeof listener === 'object' && listener.handleEvent) { + listener.handleEvent.call(listener, event); + } else { + listener.call(thisArg, event); + } +} diff --git a/node_modules/ws/lib/extension.js b/node_modules/ws/lib/extension.js new file mode 100644 index 0000000000000000000000000000000000000000..3d7895c1b0608d4bef7073a6acea9be39a4f8b74 --- /dev/null +++ b/node_modules/ws/lib/extension.js @@ -0,0 +1,203 @@ +'use strict'; + +const { tokenChars } = require('./validation'); + +/** + * Adds an offer to the map of extension offers or a parameter to the map of + * parameters. + * + * @param {Object} dest The map of extension offers or parameters + * @param {String} name The extension or parameter name + * @param {(Object|Boolean|String)} elem The extension parameters or the + * parameter value + * @private + */ +function push(dest, name, elem) { + if (dest[name] === undefined) dest[name] = [elem]; + else dest[name].push(elem); +} + +/** + * Parses the `Sec-WebSocket-Extensions` header into an object. + * + * @param {String} header The field value of the header + * @return {Object} The parsed object + * @public + */ +function parse(header) { + const offers = Object.create(null); + let params = Object.create(null); + let mustUnescape = false; + let isEscaping = false; + let inQuotes = false; + let extensionName; + let paramName; + let start = -1; + let code = -1; + let end = -1; + let i = 0; + + for (; i < header.length; i++) { + code = header.charCodeAt(i); + + if (extensionName === undefined) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if ( + i !== 0 && + (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ + ) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + const name = header.slice(start, end); + if (code === 0x2c) { + push(offers, name, params); + params = Object.create(null); + } else { + extensionName = name; + } + + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (paramName === undefined) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x20 || code === 0x09) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x3b || code === 0x2c) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + push(params, header.slice(start, end), true); + if (code === 0x2c) { + push(offers, extensionName, params); + params = Object.create(null); + extensionName = undefined; + } + + start = end = -1; + } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) { + paramName = header.slice(start, i); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else { + // + // The value of a quoted-string after unescaping must conform to the + // token ABNF, so only token characters are valid. + // Ref: https://tools.ietf.org/html/rfc6455#section-9.1 + // + if (isEscaping) { + if (tokenChars[code] !== 1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (start === -1) start = i; + else if (!mustUnescape) mustUnescape = true; + isEscaping = false; + } else if (inQuotes) { + if (tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x22 /* '"' */ && start !== -1) { + inQuotes = false; + end = i; + } else if (code === 0x5c /* '\' */) { + isEscaping = true; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) { + inQuotes = true; + } else if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (start !== -1 && (code === 0x20 || code === 0x09)) { + if (end === -1) end = i; + } else if (code === 0x3b || code === 0x2c) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + let value = header.slice(start, end); + if (mustUnescape) { + value = value.replace(/\\/g, ''); + mustUnescape = false; + } + push(params, paramName, value); + if (code === 0x2c) { + push(offers, extensionName, params); + params = Object.create(null); + extensionName = undefined; + } + + paramName = undefined; + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + } + + if (start === -1 || inQuotes || code === 0x20 || code === 0x09) { + throw new SyntaxError('Unexpected end of input'); + } + + if (end === -1) end = i; + const token = header.slice(start, end); + if (extensionName === undefined) { + push(offers, token, params); + } else { + if (paramName === undefined) { + push(params, token, true); + } else if (mustUnescape) { + push(params, paramName, token.replace(/\\/g, '')); + } else { + push(params, paramName, token); + } + push(offers, extensionName, params); + } + + return offers; +} + +/** + * Builds the `Sec-WebSocket-Extensions` header field value. + * + * @param {Object} extensions The map of extensions and parameters to format + * @return {String} A string representing the given object + * @public + */ +function format(extensions) { + return Object.keys(extensions) + .map((extension) => { + let configurations = extensions[extension]; + if (!Array.isArray(configurations)) configurations = [configurations]; + return configurations + .map((params) => { + return [extension] + .concat( + Object.keys(params).map((k) => { + let values = params[k]; + if (!Array.isArray(values)) values = [values]; + return values + .map((v) => (v === true ? k : `${k}=${v}`)) + .join('; '); + }) + ) + .join('; '); + }) + .join(', '); + }) + .join(', '); +} + +module.exports = { format, parse }; diff --git a/node_modules/ws/lib/limiter.js b/node_modules/ws/lib/limiter.js new file mode 100644 index 0000000000000000000000000000000000000000..3fd35784ea9ea59cff8c112b6556a89cde7f7b6f --- /dev/null +++ b/node_modules/ws/lib/limiter.js @@ -0,0 +1,55 @@ +'use strict'; + +const kDone = Symbol('kDone'); +const kRun = Symbol('kRun'); + +/** + * A very simple job queue with adjustable concurrency. Adapted from + * https://github.com/STRML/async-limiter + */ +class Limiter { + /** + * Creates a new `Limiter`. + * + * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed + * to run concurrently + */ + constructor(concurrency) { + this[kDone] = () => { + this.pending--; + this[kRun](); + }; + this.concurrency = concurrency || Infinity; + this.jobs = []; + this.pending = 0; + } + + /** + * Adds a job to the queue. + * + * @param {Function} job The job to run + * @public + */ + add(job) { + this.jobs.push(job); + this[kRun](); + } + + /** + * Removes a job from the queue and runs it if possible. + * + * @private + */ + [kRun]() { + if (this.pending === this.concurrency) return; + + if (this.jobs.length) { + const job = this.jobs.shift(); + + this.pending++; + job(this[kDone]); + } + } +} + +module.exports = Limiter; diff --git a/node_modules/ws/lib/permessage-deflate.js b/node_modules/ws/lib/permessage-deflate.js new file mode 100644 index 0000000000000000000000000000000000000000..aa5db761dfa56144c1dc2d5d8c74b36101607f12 --- /dev/null +++ b/node_modules/ws/lib/permessage-deflate.js @@ -0,0 +1,528 @@ +'use strict'; + +const zlib = require('zlib'); + +const bufferUtil = require('./buffer-util'); +const Limiter = require('./limiter'); +const { kStatusCode } = require('./constants'); + +const FastBuffer = Buffer[Symbol.species]; +const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]); +const kPerMessageDeflate = Symbol('permessage-deflate'); +const kTotalLength = Symbol('total-length'); +const kCallback = Symbol('callback'); +const kBuffers = Symbol('buffers'); +const kError = Symbol('error'); + +// +// We limit zlib concurrency, which prevents severe memory fragmentation +// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913 +// and https://github.com/websockets/ws/issues/1202 +// +// Intentionally global; it's the global thread pool that's an issue. +// +let zlibLimiter; + +/** + * permessage-deflate implementation. + */ +class PerMessageDeflate { + /** + * Creates a PerMessageDeflate instance. + * + * @param {Object} [options] Configuration options + * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support + * for, or request, a custom client window size + * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/ + * acknowledge disabling of client context takeover + * @param {Number} [options.concurrencyLimit=10] The number of concurrent + * calls to zlib + * @param {Boolean} [options.isServer=false] Create the instance in either + * server or client mode + * @param {Number} [options.maxPayload=0] The maximum allowed message length + * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the + * use of a custom server window size + * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept + * disabling of server context takeover + * @param {Number} [options.threshold=1024] Size (in bytes) below which + * messages should not be compressed if context takeover is disabled + * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on + * deflate + * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on + * inflate + */ + constructor(options) { + this._options = options || {}; + this._threshold = + this._options.threshold !== undefined ? this._options.threshold : 1024; + this._maxPayload = this._options.maxPayload | 0; + this._isServer = !!this._options.isServer; + this._deflate = null; + this._inflate = null; + + this.params = null; + + if (!zlibLimiter) { + const concurrency = + this._options.concurrencyLimit !== undefined + ? this._options.concurrencyLimit + : 10; + zlibLimiter = new Limiter(concurrency); + } + } + + /** + * @type {String} + */ + static get extensionName() { + return 'permessage-deflate'; + } + + /** + * Create an extension negotiation offer. + * + * @return {Object} Extension parameters + * @public + */ + offer() { + const params = {}; + + if (this._options.serverNoContextTakeover) { + params.server_no_context_takeover = true; + } + if (this._options.clientNoContextTakeover) { + params.client_no_context_takeover = true; + } + if (this._options.serverMaxWindowBits) { + params.server_max_window_bits = this._options.serverMaxWindowBits; + } + if (this._options.clientMaxWindowBits) { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } else if (this._options.clientMaxWindowBits == null) { + params.client_max_window_bits = true; + } + + return params; + } + + /** + * Accept an extension negotiation offer/response. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Object} Accepted configuration + * @public + */ + accept(configurations) { + configurations = this.normalizeParams(configurations); + + this.params = this._isServer + ? this.acceptAsServer(configurations) + : this.acceptAsClient(configurations); + + return this.params; + } + + /** + * Releases all resources used by the extension. + * + * @public + */ + cleanup() { + if (this._inflate) { + this._inflate.close(); + this._inflate = null; + } + + if (this._deflate) { + const callback = this._deflate[kCallback]; + + this._deflate.close(); + this._deflate = null; + + if (callback) { + callback( + new Error( + 'The deflate stream was closed while data was being processed' + ) + ); + } + } + } + + /** + * Accept an extension negotiation offer. + * + * @param {Array} offers The extension negotiation offers + * @return {Object} Accepted configuration + * @private + */ + acceptAsServer(offers) { + const opts = this._options; + const accepted = offers.find((params) => { + if ( + (opts.serverNoContextTakeover === false && + params.server_no_context_takeover) || + (params.server_max_window_bits && + (opts.serverMaxWindowBits === false || + (typeof opts.serverMaxWindowBits === 'number' && + opts.serverMaxWindowBits > params.server_max_window_bits))) || + (typeof opts.clientMaxWindowBits === 'number' && + !params.client_max_window_bits) + ) { + return false; + } + + return true; + }); + + if (!accepted) { + throw new Error('None of the extension offers can be accepted'); + } + + if (opts.serverNoContextTakeover) { + accepted.server_no_context_takeover = true; + } + if (opts.clientNoContextTakeover) { + accepted.client_no_context_takeover = true; + } + if (typeof opts.serverMaxWindowBits === 'number') { + accepted.server_max_window_bits = opts.serverMaxWindowBits; + } + if (typeof opts.clientMaxWindowBits === 'number') { + accepted.client_max_window_bits = opts.clientMaxWindowBits; + } else if ( + accepted.client_max_window_bits === true || + opts.clientMaxWindowBits === false + ) { + delete accepted.client_max_window_bits; + } + + return accepted; + } + + /** + * Accept the extension negotiation response. + * + * @param {Array} response The extension negotiation response + * @return {Object} Accepted configuration + * @private + */ + acceptAsClient(response) { + const params = response[0]; + + if ( + this._options.clientNoContextTakeover === false && + params.client_no_context_takeover + ) { + throw new Error('Unexpected parameter "client_no_context_takeover"'); + } + + if (!params.client_max_window_bits) { + if (typeof this._options.clientMaxWindowBits === 'number') { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } + } else if ( + this._options.clientMaxWindowBits === false || + (typeof this._options.clientMaxWindowBits === 'number' && + params.client_max_window_bits > this._options.clientMaxWindowBits) + ) { + throw new Error( + 'Unexpected or invalid parameter "client_max_window_bits"' + ); + } + + return params; + } + + /** + * Normalize parameters. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Array} The offers/response with normalized parameters + * @private + */ + normalizeParams(configurations) { + configurations.forEach((params) => { + Object.keys(params).forEach((key) => { + let value = params[key]; + + if (value.length > 1) { + throw new Error(`Parameter "${key}" must have only a single value`); + } + + value = value[0]; + + if (key === 'client_max_window_bits') { + if (value !== true) { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if (!this._isServer) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else if (key === 'server_max_window_bits') { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if ( + key === 'client_no_context_takeover' || + key === 'server_no_context_takeover' + ) { + if (value !== true) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else { + throw new Error(`Unknown parameter "${key}"`); + } + + params[key] = value; + }); + }); + + return configurations; + } + + /** + * Decompress data. Concurrency limited. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + decompress(data, fin, callback) { + zlibLimiter.add((done) => { + this._decompress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + + /** + * Compress data. Concurrency limited. + * + * @param {(Buffer|String)} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + compress(data, fin, callback) { + zlibLimiter.add((done) => { + this._compress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + + /** + * Decompress data. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _decompress(data, fin, callback) { + const endpoint = this._isServer ? 'client' : 'server'; + + if (!this._inflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = + typeof this.params[key] !== 'number' + ? zlib.Z_DEFAULT_WINDOWBITS + : this.params[key]; + + this._inflate = zlib.createInflateRaw({ + ...this._options.zlibInflateOptions, + windowBits + }); + this._inflate[kPerMessageDeflate] = this; + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + this._inflate.on('error', inflateOnError); + this._inflate.on('data', inflateOnData); + } + + this._inflate[kCallback] = callback; + + this._inflate.write(data); + if (fin) this._inflate.write(TRAILER); + + this._inflate.flush(() => { + const err = this._inflate[kError]; + + if (err) { + this._inflate.close(); + this._inflate = null; + callback(err); + return; + } + + const data = bufferUtil.concat( + this._inflate[kBuffers], + this._inflate[kTotalLength] + ); + + if (this._inflate._readableState.endEmitted) { + this._inflate.close(); + this._inflate = null; + } else { + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._inflate.reset(); + } + } + + callback(null, data); + }); + } + + /** + * Compress data. + * + * @param {(Buffer|String)} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _compress(data, fin, callback) { + const endpoint = this._isServer ? 'server' : 'client'; + + if (!this._deflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = + typeof this.params[key] !== 'number' + ? zlib.Z_DEFAULT_WINDOWBITS + : this.params[key]; + + this._deflate = zlib.createDeflateRaw({ + ...this._options.zlibDeflateOptions, + windowBits + }); + + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + + this._deflate.on('data', deflateOnData); + } + + this._deflate[kCallback] = callback; + + this._deflate.write(data); + this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { + if (!this._deflate) { + // + // The deflate stream was closed while data was being processed. + // + return; + } + + let data = bufferUtil.concat( + this._deflate[kBuffers], + this._deflate[kTotalLength] + ); + + if (fin) { + data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4); + } + + // + // Ensure that the callback will not be called again in + // `PerMessageDeflate#cleanup()`. + // + this._deflate[kCallback] = null; + + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._deflate.reset(); + } + + callback(null, data); + }); + } +} + +module.exports = PerMessageDeflate; + +/** + * The listener of the `zlib.DeflateRaw` stream `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function deflateOnData(chunk) { + this[kBuffers].push(chunk); + this[kTotalLength] += chunk.length; +} + +/** + * The listener of the `zlib.InflateRaw` stream `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function inflateOnData(chunk) { + this[kTotalLength] += chunk.length; + + if ( + this[kPerMessageDeflate]._maxPayload < 1 || + this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload + ) { + this[kBuffers].push(chunk); + return; + } + + this[kError] = new RangeError('Max payload size exceeded'); + this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'; + this[kError][kStatusCode] = 1009; + this.removeListener('data', inflateOnData); + + // + // The choice to employ `zlib.reset()` over `zlib.close()` is dictated by the + // fact that in Node.js versions prior to 13.10.0, the callback for + // `zlib.flush()` is not called if `zlib.close()` is used. Utilizing + // `zlib.reset()` ensures that either the callback is invoked or an error is + // emitted. + // + this.reset(); +} + +/** + * The listener of the `zlib.InflateRaw` stream `'error'` event. + * + * @param {Error} err The emitted error + * @private + */ +function inflateOnError(err) { + // + // There is no need to call `Zlib#close()` as the handle is automatically + // closed when an error is emitted. + // + this[kPerMessageDeflate]._inflate = null; + + if (this[kError]) { + this[kCallback](this[kError]); + return; + } + + err[kStatusCode] = 1007; + this[kCallback](err); +} diff --git a/node_modules/ws/lib/receiver.js b/node_modules/ws/lib/receiver.js new file mode 100644 index 0000000000000000000000000000000000000000..1f8f0286cd460f83a49f21adbb3df8671af2e3d2 --- /dev/null +++ b/node_modules/ws/lib/receiver.js @@ -0,0 +1,760 @@ +'use strict'; + +const { Writable } = require('stream'); + +const PerMessageDeflate = require('./permessage-deflate'); +const { + BINARY_TYPES, + EMPTY_BUFFER, + kStatusCode, + kWebSocket +} = require('./constants'); +const { concat, toArrayBuffer, unmask } = require('./buffer-util'); +const { isValidStatusCode, isValidUTF8 } = require('./validation'); + +const FastBuffer = Buffer[Symbol.species]; + +const GET_INFO = 0; +const GET_PAYLOAD_LENGTH_16 = 1; +const GET_PAYLOAD_LENGTH_64 = 2; +const GET_MASK = 3; +const GET_DATA = 4; +const INFLATING = 5; +const DEFER_EVENT = 6; + +/** + * HyBi Receiver implementation. + * + * @extends Writable + */ +class Receiver extends Writable { + /** + * Creates a Receiver instance. + * + * @param {Object} [options] Options object + * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether + * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted + * multiple times in the same tick + * @param {String} [options.binaryType=nodebuffer] The type for binary data + * @param {Object} [options.extensions] An object containing the negotiated + * extensions + * @param {Boolean} [options.isServer=false] Specifies whether to operate in + * client or server mode + * @param {Number} [options.maxBufferedChunks=0] The maximum number of + * buffered data chunks + * @param {Number} [options.maxFragments=0] The maximum number of message + * fragments + * @param {Number} [options.maxPayload=0] The maximum allowed message length + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + */ + constructor(options = {}) { + super(); + + this._allowSynchronousEvents = + options.allowSynchronousEvents !== undefined + ? options.allowSynchronousEvents + : true; + this._binaryType = options.binaryType || BINARY_TYPES[0]; + this._extensions = options.extensions || {}; + this._isServer = !!options.isServer; + this._maxBufferedChunks = options.maxBufferedChunks | 0; + this._maxFragments = options.maxFragments | 0; + this._maxPayload = options.maxPayload | 0; + this._skipUTF8Validation = !!options.skipUTF8Validation; + this[kWebSocket] = undefined; + + this._bufferedBytes = 0; + this._buffers = []; + + this._compressed = false; + this._payloadLength = 0; + this._mask = undefined; + this._fragmented = 0; + this._masked = false; + this._fin = false; + this._opcode = 0; + + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragments = []; + + this._errored = false; + this._loop = false; + this._state = GET_INFO; + } + + /** + * Implements `Writable.prototype._write()`. + * + * @param {Buffer} chunk The chunk of data to write + * @param {String} encoding The character encoding of `chunk` + * @param {Function} cb Callback + * @private + */ + _write(chunk, encoding, cb) { + if (this._opcode === 0x08 && this._state == GET_INFO) return cb(); + + if ( + this._maxBufferedChunks > 0 && + this._buffers.length >= this._maxBufferedChunks + ) { + cb( + this.createError( + RangeError, + 'Too many buffered chunks', + false, + 1008, + 'WS_ERR_TOO_MANY_BUFFERED_PARTS' + ) + ); + return; + } + + this._bufferedBytes += chunk.length; + this._buffers.push(chunk); + this.startLoop(cb); + } + + /** + * Consumes `n` bytes from the buffered data. + * + * @param {Number} n The number of bytes to consume + * @return {Buffer} The consumed bytes + * @private + */ + consume(n) { + this._bufferedBytes -= n; + + if (n === this._buffers[0].length) return this._buffers.shift(); + + if (n < this._buffers[0].length) { + const buf = this._buffers[0]; + this._buffers[0] = new FastBuffer( + buf.buffer, + buf.byteOffset + n, + buf.length - n + ); + + return new FastBuffer(buf.buffer, buf.byteOffset, n); + } + + const dst = Buffer.allocUnsafe(n); + + do { + const buf = this._buffers[0]; + const offset = dst.length - n; + + if (n >= buf.length) { + dst.set(this._buffers.shift(), offset); + } else { + dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset); + this._buffers[0] = new FastBuffer( + buf.buffer, + buf.byteOffset + n, + buf.length - n + ); + } + + n -= buf.length; + } while (n > 0); + + return dst; + } + + /** + * Starts the parsing loop. + * + * @param {Function} cb Callback + * @private + */ + startLoop(cb) { + this._loop = true; + + do { + switch (this._state) { + case GET_INFO: + this.getInfo(cb); + break; + case GET_PAYLOAD_LENGTH_16: + this.getPayloadLength16(cb); + break; + case GET_PAYLOAD_LENGTH_64: + this.getPayloadLength64(cb); + break; + case GET_MASK: + this.getMask(); + break; + case GET_DATA: + this.getData(cb); + break; + case INFLATING: + case DEFER_EVENT: + this._loop = false; + return; + } + } while (this._loop); + + if (!this._errored) cb(); + } + + /** + * Reads the first two bytes of a frame. + * + * @param {Function} cb Callback + * @private + */ + getInfo(cb) { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + + const buf = this.consume(2); + + if ((buf[0] & 0x30) !== 0x00) { + const error = this.createError( + RangeError, + 'RSV2 and RSV3 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_2_3' + ); + + cb(error); + return; + } + + const compressed = (buf[0] & 0x40) === 0x40; + + if (compressed && !this._extensions[PerMessageDeflate.extensionName]) { + const error = this.createError( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + + cb(error); + return; + } + + this._fin = (buf[0] & 0x80) === 0x80; + this._opcode = buf[0] & 0x0f; + this._payloadLength = buf[1] & 0x7f; + + if (this._opcode === 0x00) { + if (compressed) { + const error = this.createError( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + + cb(error); + return; + } + + if (!this._fragmented) { + const error = this.createError( + RangeError, + 'invalid opcode 0', + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + + cb(error); + return; + } + + this._opcode = this._fragmented; + } else if (this._opcode === 0x01 || this._opcode === 0x02) { + if (this._fragmented) { + const error = this.createError( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + + cb(error); + return; + } + + this._compressed = compressed; + } else if (this._opcode > 0x07 && this._opcode < 0x0b) { + if (!this._fin) { + const error = this.createError( + RangeError, + 'FIN must be set', + true, + 1002, + 'WS_ERR_EXPECTED_FIN' + ); + + cb(error); + return; + } + + if (compressed) { + const error = this.createError( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + + cb(error); + return; + } + + if ( + this._payloadLength > 0x7d || + (this._opcode === 0x08 && this._payloadLength === 1) + ) { + const error = this.createError( + RangeError, + `invalid payload length ${this._payloadLength}`, + true, + 1002, + 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH' + ); + + cb(error); + return; + } + } else { + const error = this.createError( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + + cb(error); + return; + } + + if (!this._fin && !this._fragmented) this._fragmented = this._opcode; + this._masked = (buf[1] & 0x80) === 0x80; + + if (this._isServer) { + if (!this._masked) { + const error = this.createError( + RangeError, + 'MASK must be set', + true, + 1002, + 'WS_ERR_EXPECTED_MASK' + ); + + cb(error); + return; + } + } else if (this._masked) { + const error = this.createError( + RangeError, + 'MASK must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_MASK' + ); + + cb(error); + return; + } + + if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; + else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; + else this.haveLength(cb); + } + + /** + * Gets extended payload length (7+16). + * + * @param {Function} cb Callback + * @private + */ + getPayloadLength16(cb) { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + + this._payloadLength = this.consume(2).readUInt16BE(0); + this.haveLength(cb); + } + + /** + * Gets extended payload length (7+64). + * + * @param {Function} cb Callback + * @private + */ + getPayloadLength64(cb) { + if (this._bufferedBytes < 8) { + this._loop = false; + return; + } + + const buf = this.consume(8); + const num = buf.readUInt32BE(0); + + // + // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned + // if payload length is greater than this number. + // + if (num > Math.pow(2, 53 - 32) - 1) { + const error = this.createError( + RangeError, + 'Unsupported WebSocket frame: payload length > 2^53 - 1', + false, + 1009, + 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH' + ); + + cb(error); + return; + } + + this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); + this.haveLength(cb); + } + + /** + * Payload length has been read. + * + * @param {Function} cb Callback + * @private + */ + haveLength(cb) { + if (this._payloadLength && this._opcode < 0x08) { + this._totalPayloadLength += this._payloadLength; + if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { + const error = this.createError( + RangeError, + 'Max payload size exceeded', + false, + 1009, + 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' + ); + + cb(error); + return; + } + } + + if (this._masked) this._state = GET_MASK; + else this._state = GET_DATA; + } + + /** + * Reads mask bytes. + * + * @private + */ + getMask() { + if (this._bufferedBytes < 4) { + this._loop = false; + return; + } + + this._mask = this.consume(4); + this._state = GET_DATA; + } + + /** + * Reads data bytes. + * + * @param {Function} cb Callback + * @private + */ + getData(cb) { + let data = EMPTY_BUFFER; + + if (this._payloadLength) { + if (this._bufferedBytes < this._payloadLength) { + this._loop = false; + return; + } + + data = this.consume(this._payloadLength); + + if ( + this._masked && + (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0 + ) { + unmask(data, this._mask); + } + } + + if (this._opcode > 0x07) { + this.controlMessage(data, cb); + return; + } + + if (this._compressed) { + this._state = INFLATING; + this.decompress(data, cb); + return; + } + + if (data.length) { + if ( + this._maxFragments > 0 && + this._fragments.length >= this._maxFragments + ) { + const error = this.createError( + RangeError, + 'Too many message fragments', + false, + 1008, + 'WS_ERR_TOO_MANY_BUFFERED_PARTS' + ); + + cb(error); + return; + } + + // + // This message is not compressed so its length is the sum of the payload + // length of all fragments. + // + this._messageLength = this._totalPayloadLength; + this._fragments.push(data); + } + + this.dataMessage(cb); + } + + /** + * Decompresses data. + * + * @param {Buffer} data Compressed data + * @param {Function} cb Callback + * @private + */ + decompress(data, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + + perMessageDeflate.decompress(data, this._fin, (err, buf) => { + if (err) return cb(err); + + if (buf.length) { + this._messageLength += buf.length; + if (this._messageLength > this._maxPayload && this._maxPayload > 0) { + const error = this.createError( + RangeError, + 'Max payload size exceeded', + false, + 1009, + 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' + ); + + cb(error); + return; + } + + if ( + this._maxFragments > 0 && + this._fragments.length >= this._maxFragments + ) { + const error = this.createError( + RangeError, + 'Too many message fragments', + false, + 1008, + 'WS_ERR_TOO_MANY_BUFFERED_PARTS' + ); + + cb(error); + return; + } + + this._fragments.push(buf); + } + + this.dataMessage(cb); + if (this._state === GET_INFO) this.startLoop(cb); + }); + } + + /** + * Handles a data message. + * + * @param {Function} cb Callback + * @private + */ + dataMessage(cb) { + if (!this._fin) { + this._state = GET_INFO; + return; + } + + const messageLength = this._messageLength; + const fragments = this._fragments; + + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragmented = 0; + this._fragments = []; + + if (this._opcode === 2) { + let data; + + if (this._binaryType === 'nodebuffer') { + data = concat(fragments, messageLength); + } else if (this._binaryType === 'arraybuffer') { + data = toArrayBuffer(concat(fragments, messageLength)); + } else if (this._binaryType === 'blob') { + data = new Blob(fragments); + } else { + data = fragments; + } + + if (this._allowSynchronousEvents) { + this.emit('message', data, true); + this._state = GET_INFO; + } else { + this._state = DEFER_EVENT; + setImmediate(() => { + this.emit('message', data, true); + this._state = GET_INFO; + this.startLoop(cb); + }); + } + } else { + const buf = concat(fragments, messageLength); + + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + const error = this.createError( + Error, + 'invalid UTF-8 sequence', + true, + 1007, + 'WS_ERR_INVALID_UTF8' + ); + + cb(error); + return; + } + + if (this._state === INFLATING || this._allowSynchronousEvents) { + this.emit('message', buf, false); + this._state = GET_INFO; + } else { + this._state = DEFER_EVENT; + setImmediate(() => { + this.emit('message', buf, false); + this._state = GET_INFO; + this.startLoop(cb); + }); + } + } + } + + /** + * Handles a control message. + * + * @param {Buffer} data Data to handle + * @return {(Error|RangeError|undefined)} A possible error + * @private + */ + controlMessage(data, cb) { + if (this._opcode === 0x08) { + if (data.length === 0) { + this._loop = false; + this.emit('conclude', 1005, EMPTY_BUFFER); + this.end(); + } else { + const code = data.readUInt16BE(0); + + if (!isValidStatusCode(code)) { + const error = this.createError( + RangeError, + `invalid status code ${code}`, + true, + 1002, + 'WS_ERR_INVALID_CLOSE_CODE' + ); + + cb(error); + return; + } + + const buf = new FastBuffer( + data.buffer, + data.byteOffset + 2, + data.length - 2 + ); + + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + const error = this.createError( + Error, + 'invalid UTF-8 sequence', + true, + 1007, + 'WS_ERR_INVALID_UTF8' + ); + + cb(error); + return; + } + + this._loop = false; + this.emit('conclude', code, buf); + this.end(); + } + + this._state = GET_INFO; + return; + } + + if (this._allowSynchronousEvents) { + this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data); + this._state = GET_INFO; + } else { + this._state = DEFER_EVENT; + setImmediate(() => { + this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data); + this._state = GET_INFO; + this.startLoop(cb); + }); + } + } + + /** + * Builds an error object. + * + * @param {function(new:Error|RangeError)} ErrorCtor The error constructor + * @param {String} message The error message + * @param {Boolean} prefix Specifies whether or not to add a default prefix to + * `message` + * @param {Number} statusCode The status code + * @param {String} errorCode The exposed error code + * @return {(Error|RangeError)} The error + * @private + */ + createError(ErrorCtor, message, prefix, statusCode, errorCode) { + this._loop = false; + this._errored = true; + + const err = new ErrorCtor( + prefix ? `Invalid WebSocket frame: ${message}` : message + ); + + Error.captureStackTrace(err, this.createError); + err.code = errorCode; + err[kStatusCode] = statusCode; + return err; + } +} + +module.exports = Receiver; diff --git a/node_modules/ws/lib/sender.js b/node_modules/ws/lib/sender.js new file mode 100644 index 0000000000000000000000000000000000000000..2c767e2c62a7fb50a987454f0c148ec5b4a0a523 --- /dev/null +++ b/node_modules/ws/lib/sender.js @@ -0,0 +1,607 @@ +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex" }] */ + +'use strict'; + +const { Duplex } = require('stream'); +const { randomFillSync } = require('crypto'); +const { + types: { isUint8Array } +} = require('util'); + +const PerMessageDeflate = require('./permessage-deflate'); +const { EMPTY_BUFFER, kWebSocket, NOOP } = require('./constants'); +const { isBlob, isValidStatusCode } = require('./validation'); +const { mask: applyMask, toBuffer } = require('./buffer-util'); + +const kByteLength = Symbol('kByteLength'); +const maskBuffer = Buffer.alloc(4); +const RANDOM_POOL_SIZE = 8 * 1024; +let randomPool; +let randomPoolPointer = RANDOM_POOL_SIZE; + +const DEFAULT = 0; +const DEFLATING = 1; +const GET_BLOB_DATA = 2; + +/** + * HyBi Sender implementation. + */ +class Sender { + /** + * Creates a Sender instance. + * + * @param {Duplex} socket The connection socket + * @param {Object} [extensions] An object containing the negotiated extensions + * @param {Function} [generateMask] The function used to generate the masking + * key + */ + constructor(socket, extensions, generateMask) { + this._extensions = extensions || {}; + + if (generateMask) { + this._generateMask = generateMask; + this._maskBuffer = Buffer.alloc(4); + } + + this._socket = socket; + + this._firstFragment = true; + this._compress = false; + + this._bufferedBytes = 0; + this._queue = []; + this._state = DEFAULT; + this.onerror = NOOP; + this[kWebSocket] = undefined; + } + + /** + * Frames a piece of data according to the HyBi WebSocket protocol. + * + * @param {(Buffer|String)} data The data to frame + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @return {(Buffer|String)[]} The framed data + * @public + */ + static frame(data, options) { + let mask; + let merge = false; + let offset = 2; + let skipMasking = false; + + if (options.mask) { + mask = options.maskBuffer || maskBuffer; + + if (options.generateMask) { + options.generateMask(mask); + } else { + if (randomPoolPointer === RANDOM_POOL_SIZE) { + /* istanbul ignore else */ + if (randomPool === undefined) { + // + // This is lazily initialized because server-sent frames must not + // be masked so it may never be used. + // + randomPool = Buffer.alloc(RANDOM_POOL_SIZE); + } + + randomFillSync(randomPool, 0, RANDOM_POOL_SIZE); + randomPoolPointer = 0; + } + + mask[0] = randomPool[randomPoolPointer++]; + mask[1] = randomPool[randomPoolPointer++]; + mask[2] = randomPool[randomPoolPointer++]; + mask[3] = randomPool[randomPoolPointer++]; + } + + skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0; + offset = 6; + } + + let dataLength; + + if (typeof data === 'string') { + if ( + (!options.mask || skipMasking) && + options[kByteLength] !== undefined + ) { + dataLength = options[kByteLength]; + } else { + data = Buffer.from(data); + dataLength = data.length; + } + } else { + dataLength = data.length; + merge = options.mask && options.readOnly && !skipMasking; + } + + let payloadLength = dataLength; + + if (dataLength >= 65536) { + offset += 8; + payloadLength = 127; + } else if (dataLength > 125) { + offset += 2; + payloadLength = 126; + } + + const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset); + + target[0] = options.fin ? options.opcode | 0x80 : options.opcode; + if (options.rsv1) target[0] |= 0x40; + + target[1] = payloadLength; + + if (payloadLength === 126) { + target.writeUInt16BE(dataLength, 2); + } else if (payloadLength === 127) { + target[2] = target[3] = 0; + target.writeUIntBE(dataLength, 4, 6); + } + + if (!options.mask) return [target, data]; + + target[1] |= 0x80; + target[offset - 4] = mask[0]; + target[offset - 3] = mask[1]; + target[offset - 2] = mask[2]; + target[offset - 1] = mask[3]; + + if (skipMasking) return [target, data]; + + if (merge) { + applyMask(data, mask, target, offset, dataLength); + return [target]; + } + + applyMask(data, mask, data, 0, dataLength); + return [target, data]; + } + + /** + * Sends a close message to the other peer. + * + * @param {Number} [code] The status code component of the body + * @param {(String|Buffer)} [data] The message component of the body + * @param {Boolean} [mask=false] Specifies whether or not to mask the message + * @param {Function} [cb] Callback + * @public + */ + close(code, data, mask, cb) { + let buf; + + if (code === undefined) { + buf = EMPTY_BUFFER; + } else if (typeof code !== 'number' || !isValidStatusCode(code)) { + throw new TypeError('First argument must be a valid error code number'); + } else if (data === undefined || !data.length) { + buf = Buffer.allocUnsafe(2); + buf.writeUInt16BE(code, 0); + } else { + const length = Buffer.byteLength(data); + + if (length > 123) { + throw new RangeError('The message must not be greater than 123 bytes'); + } + + buf = Buffer.allocUnsafe(2 + length); + buf.writeUInt16BE(code, 0); + + if (typeof data === 'string') { + buf.write(data, 2); + } else if (isUint8Array(data)) { + buf.set(data, 2); + } else { + throw new TypeError('Second argument must be a string or a Uint8Array'); + } + } + + const options = { + [kByteLength]: buf.length, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x08, + readOnly: false, + rsv1: false + }; + + if (this._state !== DEFAULT) { + this.enqueue([this.dispatch, buf, false, options, cb]); + } else { + this.sendFrame(Sender.frame(buf, options), cb); + } + } + + /** + * Sends a ping message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @public + */ + ping(data, mask, cb) { + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else if (isBlob(data)) { + byteLength = data.size; + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + + if (byteLength > 125) { + throw new RangeError('The data size must not be greater than 125 bytes'); + } + + const options = { + [kByteLength]: byteLength, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x09, + readOnly, + rsv1: false + }; + + if (isBlob(data)) { + if (this._state !== DEFAULT) { + this.enqueue([this.getBlobData, data, false, options, cb]); + } else { + this.getBlobData(data, false, options, cb); + } + } else if (this._state !== DEFAULT) { + this.enqueue([this.dispatch, data, false, options, cb]); + } else { + this.sendFrame(Sender.frame(data, options), cb); + } + } + + /** + * Sends a pong message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @public + */ + pong(data, mask, cb) { + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else if (isBlob(data)) { + byteLength = data.size; + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + + if (byteLength > 125) { + throw new RangeError('The data size must not be greater than 125 bytes'); + } + + const options = { + [kByteLength]: byteLength, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x0a, + readOnly, + rsv1: false + }; + + if (isBlob(data)) { + if (this._state !== DEFAULT) { + this.enqueue([this.getBlobData, data, false, options, cb]); + } else { + this.getBlobData(data, false, options, cb); + } + } else if (this._state !== DEFAULT) { + this.enqueue([this.dispatch, data, false, options, cb]); + } else { + this.sendFrame(Sender.frame(data, options), cb); + } + } + + /** + * Sends a data message to the other peer. + * + * @param {*} data The message to send + * @param {Object} options Options object + * @param {Boolean} [options.binary=false] Specifies whether `data` is binary + * or text + * @param {Boolean} [options.compress=false] Specifies whether or not to + * compress `data` + * @param {Boolean} [options.fin=false] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Function} [cb] Callback + * @public + */ + send(data, options, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + let opcode = options.binary ? 2 : 1; + let rsv1 = options.compress; + + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else if (isBlob(data)) { + byteLength = data.size; + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + + if (this._firstFragment) { + this._firstFragment = false; + if ( + rsv1 && + perMessageDeflate && + perMessageDeflate.params[ + perMessageDeflate._isServer + ? 'server_no_context_takeover' + : 'client_no_context_takeover' + ] + ) { + rsv1 = byteLength >= perMessageDeflate._threshold; + } + this._compress = rsv1; + } else { + rsv1 = false; + opcode = 0; + } + + if (options.fin) this._firstFragment = true; + + const opts = { + [kByteLength]: byteLength, + fin: options.fin, + generateMask: this._generateMask, + mask: options.mask, + maskBuffer: this._maskBuffer, + opcode, + readOnly, + rsv1 + }; + + if (isBlob(data)) { + if (this._state !== DEFAULT) { + this.enqueue([this.getBlobData, data, this._compress, opts, cb]); + } else { + this.getBlobData(data, this._compress, opts, cb); + } + } else if (this._state !== DEFAULT) { + this.enqueue([this.dispatch, data, this._compress, opts, cb]); + } else { + this.dispatch(data, this._compress, opts, cb); + } + } + + /** + * Gets the contents of a blob as binary data. + * + * @param {Blob} blob The blob + * @param {Boolean} [compress=false] Specifies whether or not to compress + * the data + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @param {Function} [cb] Callback + * @private + */ + getBlobData(blob, compress, options, cb) { + this._bufferedBytes += options[kByteLength]; + this._state = GET_BLOB_DATA; + + blob + .arrayBuffer() + .then((arrayBuffer) => { + if (this._socket.destroyed) { + const err = new Error( + 'The socket was closed while the blob was being read' + ); + + // + // `callCallbacks` is called in the next tick to ensure that errors + // that might be thrown in the callbacks behave like errors thrown + // outside the promise chain. + // + process.nextTick(callCallbacks, this, err, cb); + return; + } + + this._bufferedBytes -= options[kByteLength]; + const data = toBuffer(arrayBuffer); + + if (!compress) { + this._state = DEFAULT; + this.sendFrame(Sender.frame(data, options), cb); + this.dequeue(); + } else { + this.dispatch(data, compress, options, cb); + } + }) + .catch((err) => { + // + // `onError` is called in the next tick for the same reason that + // `callCallbacks` above is. + // + process.nextTick(onError, this, err, cb); + }); + } + + /** + * Dispatches a message. + * + * @param {(Buffer|String)} data The message to send + * @param {Boolean} [compress=false] Specifies whether or not to compress + * `data` + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @param {Function} [cb] Callback + * @private + */ + dispatch(data, compress, options, cb) { + if (!compress) { + this.sendFrame(Sender.frame(data, options), cb); + return; + } + + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + + this._bufferedBytes += options[kByteLength]; + this._state = DEFLATING; + perMessageDeflate.compress(data, options.fin, (_, buf) => { + if (this._socket.destroyed) { + const err = new Error( + 'The socket was closed while data was being compressed' + ); + + callCallbacks(this, err, cb); + return; + } + + this._bufferedBytes -= options[kByteLength]; + this._state = DEFAULT; + options.readOnly = false; + this.sendFrame(Sender.frame(buf, options), cb); + this.dequeue(); + }); + } + + /** + * Executes queued send operations. + * + * @private + */ + dequeue() { + while (this._state === DEFAULT && this._queue.length) { + const params = this._queue.shift(); + + this._bufferedBytes -= params[3][kByteLength]; + Reflect.apply(params[0], this, params.slice(1)); + } + } + + /** + * Enqueues a send operation. + * + * @param {Array} params Send operation parameters. + * @private + */ + enqueue(params) { + this._bufferedBytes += params[3][kByteLength]; + this._queue.push(params); + } + + /** + * Sends a frame. + * + * @param {(Buffer | String)[]} list The frame to send + * @param {Function} [cb] Callback + * @private + */ + sendFrame(list, cb) { + if (list.length === 2) { + this._socket.cork(); + this._socket.write(list[0]); + this._socket.write(list[1], cb); + this._socket.uncork(); + } else { + this._socket.write(list[0], cb); + } + } +} + +module.exports = Sender; + +/** + * Calls queued callbacks with an error. + * + * @param {Sender} sender The `Sender` instance + * @param {Error} err The error to call the callbacks with + * @param {Function} [cb] The first callback + * @private + */ +function callCallbacks(sender, err, cb) { + if (typeof cb === 'function') cb(err); + + for (let i = 0; i < sender._queue.length; i++) { + const params = sender._queue[i]; + const callback = params[params.length - 1]; + + if (typeof callback === 'function') callback(err); + } +} + +/** + * Handles a `Sender` error. + * + * @param {Sender} sender The `Sender` instance + * @param {Error} err The error + * @param {Function} [cb] The first pending callback + * @private + */ +function onError(sender, err, cb) { + callCallbacks(sender, err, cb); + sender.onerror(err); +} diff --git a/node_modules/ws/lib/stream.js b/node_modules/ws/lib/stream.js new file mode 100644 index 0000000000000000000000000000000000000000..4c58c911bc3da49c9b2610da77ff61b71f111810 --- /dev/null +++ b/node_modules/ws/lib/stream.js @@ -0,0 +1,161 @@ +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^WebSocket$" }] */ +'use strict'; + +const WebSocket = require('./websocket'); +const { Duplex } = require('stream'); + +/** + * Emits the `'close'` event on a stream. + * + * @param {Duplex} stream The stream. + * @private + */ +function emitClose(stream) { + stream.emit('close'); +} + +/** + * The listener of the `'end'` event. + * + * @private + */ +function duplexOnEnd() { + if (!this.destroyed && this._writableState.finished) { + this.destroy(); + } +} + +/** + * The listener of the `'error'` event. + * + * @param {Error} err The error + * @private + */ +function duplexOnError(err) { + this.removeListener('error', duplexOnError); + this.destroy(); + if (this.listenerCount('error') === 0) { + // Do not suppress the throwing behavior. + this.emit('error', err); + } +} + +/** + * Wraps a `WebSocket` in a duplex stream. + * + * @param {WebSocket} ws The `WebSocket` to wrap + * @param {Object} [options] The options for the `Duplex` constructor + * @return {Duplex} The duplex stream + * @public + */ +function createWebSocketStream(ws, options) { + let terminateOnDestroy = true; + + const duplex = new Duplex({ + ...options, + autoDestroy: false, + emitClose: false, + objectMode: false, + writableObjectMode: false + }); + + ws.on('message', function message(msg, isBinary) { + const data = + !isBinary && duplex._readableState.objectMode ? msg.toString() : msg; + + if (!duplex.push(data)) ws.pause(); + }); + + ws.once('error', function error(err) { + if (duplex.destroyed) return; + + // Prevent `ws.terminate()` from being called by `duplex._destroy()`. + // + // - If the `'error'` event is emitted before the `'open'` event, then + // `ws.terminate()` is a noop as no socket is assigned. + // - Otherwise, the error is re-emitted by the listener of the `'error'` + // event of the `Receiver` object. The listener already closes the + // connection by calling `ws.close()`. This allows a close frame to be + // sent to the other peer. If `ws.terminate()` is called right after this, + // then the close frame might not be sent. + terminateOnDestroy = false; + duplex.destroy(err); + }); + + ws.once('close', function close() { + if (duplex.destroyed) return; + + duplex.push(null); + }); + + duplex._destroy = function (err, callback) { + if (ws.readyState === ws.CLOSED) { + callback(err); + process.nextTick(emitClose, duplex); + return; + } + + let called = false; + + ws.once('error', function error(err) { + called = true; + callback(err); + }); + + ws.once('close', function close() { + if (!called) callback(err); + process.nextTick(emitClose, duplex); + }); + + if (terminateOnDestroy) ws.terminate(); + }; + + duplex._final = function (callback) { + if (ws.readyState === ws.CONNECTING) { + ws.once('open', function open() { + duplex._final(callback); + }); + return; + } + + // If the value of the `_socket` property is `null` it means that `ws` is a + // client websocket and the handshake failed. In fact, when this happens, a + // socket is never assigned to the websocket. Wait for the `'error'` event + // that will be emitted by the websocket. + if (ws._socket === null) return; + + if (ws._socket._writableState.finished) { + callback(); + if (duplex._readableState.endEmitted) duplex.destroy(); + } else { + ws._socket.once('finish', function finish() { + // `duplex` is not destroyed here because the `'end'` event will be + // emitted on `duplex` after this `'finish'` event. The EOF signaling + // `null` chunk is, in fact, pushed when the websocket emits `'close'`. + callback(); + }); + ws.close(); + } + }; + + duplex._read = function () { + if (ws.isPaused) ws.resume(); + }; + + duplex._write = function (chunk, encoding, callback) { + if (ws.readyState === ws.CONNECTING) { + ws.once('open', function open() { + duplex._write(chunk, encoding, callback); + }); + return; + } + + ws.send(chunk, callback); + }; + + duplex.on('end', duplexOnEnd); + duplex.on('error', duplexOnError); + return duplex; +} + +module.exports = createWebSocketStream; diff --git a/node_modules/ws/lib/subprotocol.js b/node_modules/ws/lib/subprotocol.js new file mode 100644 index 0000000000000000000000000000000000000000..d4381e8864fd055e81dd75eeb4b852d9da864673 --- /dev/null +++ b/node_modules/ws/lib/subprotocol.js @@ -0,0 +1,62 @@ +'use strict'; + +const { tokenChars } = require('./validation'); + +/** + * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names. + * + * @param {String} header The field value of the header + * @return {Set} The subprotocol names + * @public + */ +function parse(header) { + const protocols = new Set(); + let start = -1; + let end = -1; + let i = 0; + + for (i; i < header.length; i++) { + const code = header.charCodeAt(i); + + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if ( + i !== 0 && + (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ + ) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x2c /* ',' */) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + + const protocol = header.slice(start, end); + + if (protocols.has(protocol)) { + throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); + } + + protocols.add(protocol); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + + if (start === -1 || end !== -1) { + throw new SyntaxError('Unexpected end of input'); + } + + const protocol = header.slice(start, i); + + if (protocols.has(protocol)) { + throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); + } + + protocols.add(protocol); + return protocols; +} + +module.exports = { parse }; diff --git a/node_modules/ws/lib/validation.js b/node_modules/ws/lib/validation.js new file mode 100644 index 0000000000000000000000000000000000000000..4a2e68d5127279431a74b6961e8d35161d3276e2 --- /dev/null +++ b/node_modules/ws/lib/validation.js @@ -0,0 +1,152 @@ +'use strict'; + +const { isUtf8 } = require('buffer'); + +const { hasBlob } = require('./constants'); + +// +// Allowed token characters: +// +// '!', '#', '$', '%', '&', ''', '*', '+', '-', +// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~' +// +// tokenChars[32] === 0 // ' ' +// tokenChars[33] === 1 // '!' +// tokenChars[34] === 0 // '"' +// ... +// +// prettier-ignore +const tokenChars = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31 + 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63 + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127 +]; + +/** + * Checks if a status code is allowed in a close frame. + * + * @param {Number} code The status code + * @return {Boolean} `true` if the status code is valid, else `false` + * @public + */ +function isValidStatusCode(code) { + return ( + (code >= 1000 && + code <= 1014 && + code !== 1004 && + code !== 1005 && + code !== 1006) || + (code >= 3000 && code <= 4999) + ); +} + +/** + * Checks if a given buffer contains only correct UTF-8. + * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by + * Markus Kuhn. + * + * @param {Buffer} buf The buffer to check + * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false` + * @public + */ +function _isValidUTF8(buf) { + const len = buf.length; + let i = 0; + + while (i < len) { + if ((buf[i] & 0x80) === 0) { + // 0xxxxxxx + i++; + } else if ((buf[i] & 0xe0) === 0xc0) { + // 110xxxxx 10xxxxxx + if ( + i + 1 === len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i] & 0xfe) === 0xc0 // Overlong + ) { + return false; + } + + i += 2; + } else if ((buf[i] & 0xf0) === 0xe0) { + // 1110xxxx 10xxxxxx 10xxxxxx + if ( + i + 2 >= len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i + 2] & 0xc0) !== 0x80 || + (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong + (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF) + ) { + return false; + } + + i += 3; + } else if ((buf[i] & 0xf8) === 0xf0) { + // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + if ( + i + 3 >= len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i + 2] & 0xc0) !== 0x80 || + (buf[i + 3] & 0xc0) !== 0x80 || + (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong + (buf[i] === 0xf4 && buf[i + 1] > 0x8f) || + buf[i] > 0xf4 // > U+10FFFF + ) { + return false; + } + + i += 4; + } else { + return false; + } + } + + return true; +} + +/** + * Determines whether a value is a `Blob`. + * + * @param {*} value The value to be tested + * @return {Boolean} `true` if `value` is a `Blob`, else `false` + * @private + */ +function isBlob(value) { + return ( + hasBlob && + typeof value === 'object' && + typeof value.arrayBuffer === 'function' && + typeof value.type === 'string' && + typeof value.stream === 'function' && + (value[Symbol.toStringTag] === 'Blob' || + value[Symbol.toStringTag] === 'File') + ); +} + +module.exports = { + isBlob, + isValidStatusCode, + isValidUTF8: _isValidUTF8, + tokenChars +}; + +if (isUtf8) { + module.exports.isValidUTF8 = function (buf) { + return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf); + }; +} /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) { + try { + const isValidUTF8 = require('utf-8-validate'); + + module.exports.isValidUTF8 = function (buf) { + return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf); + }; + } catch (e) { + // Continue regardless of the error. + } +} diff --git a/node_modules/ws/lib/websocket-server.js b/node_modules/ws/lib/websocket-server.js new file mode 100644 index 0000000000000000000000000000000000000000..8ce9798465ba6241224496d1b76b959acda4e072 --- /dev/null +++ b/node_modules/ws/lib/websocket-server.js @@ -0,0 +1,562 @@ +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex$", "caughtErrors": "none" }] */ + +'use strict'; + +const EventEmitter = require('events'); +const http = require('http'); +const { Duplex } = require('stream'); +const { createHash } = require('crypto'); + +const extension = require('./extension'); +const PerMessageDeflate = require('./permessage-deflate'); +const subprotocol = require('./subprotocol'); +const WebSocket = require('./websocket'); +const { CLOSE_TIMEOUT, GUID, kWebSocket } = require('./constants'); + +const keyRegex = /^[+/0-9A-Za-z]{22}==$/; + +const RUNNING = 0; +const CLOSING = 1; +const CLOSED = 2; + +/** + * Class representing a WebSocket server. + * + * @extends EventEmitter + */ +class WebSocketServer extends EventEmitter { + /** + * Create a `WebSocketServer` instance. + * + * @param {Object} options Configuration options + * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether + * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted + * multiple times in the same tick + * @param {Boolean} [options.autoPong=true] Specifies whether or not to + * automatically send a pong in response to a ping + * @param {Number} [options.backlog=511] The maximum length of the queue of + * pending connections + * @param {Boolean} [options.clientTracking=true] Specifies whether or not to + * track clients + * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to + * wait for the closing handshake to finish after `websocket.close()` is + * called + * @param {Function} [options.handleProtocols] A hook to handle protocols + * @param {String} [options.host] The hostname where to bind the server + * @param {Number} [options.maxBufferedChunks=1048576] The maximum number of + * buffered data chunks + * @param {Number} [options.maxFragments=131072] The maximum number of message + * fragments + * @param {Number} [options.maxPayload=104857600] The maximum allowed message + * size + * @param {Boolean} [options.noServer=false] Enable no server mode + * @param {String} [options.path] Accept only connections matching this path + * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable + * permessage-deflate + * @param {Number} [options.port] The port where to bind the server + * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S + * server to use + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @param {Function} [options.verifyClient] A hook to reject connections + * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket` + * class to use. It must be the `WebSocket` class or class that extends it + * @param {Function} [callback] A listener for the `listening` event + */ + constructor(options, callback) { + super(); + + options = { + allowSynchronousEvents: true, + autoPong: true, + maxBufferedChunks: 1024 * 1024, + maxFragments: 128 * 1024, + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: false, + handleProtocols: null, + clientTracking: true, + closeTimeout: CLOSE_TIMEOUT, + verifyClient: null, + noServer: false, + backlog: null, // use default (511 as implemented in net.js) + server: null, + host: null, + path: null, + port: null, + WebSocket, + ...options + }; + + if ( + (options.port == null && !options.server && !options.noServer) || + (options.port != null && (options.server || options.noServer)) || + (options.server && options.noServer) + ) { + throw new TypeError( + 'One and only one of the "port", "server", or "noServer" options ' + + 'must be specified' + ); + } + + if (options.port != null) { + this._server = http.createServer((req, res) => { + const body = http.STATUS_CODES[426]; + + res.writeHead(426, { + 'Content-Length': body.length, + 'Content-Type': 'text/plain' + }); + res.end(body); + }); + this._server.listen( + options.port, + options.host, + options.backlog, + callback + ); + } else if (options.server) { + this._server = options.server; + } + + if (this._server) { + const emitConnection = this.emit.bind(this, 'connection'); + + this._removeListeners = addListeners(this._server, { + listening: this.emit.bind(this, 'listening'), + error: this.emit.bind(this, 'error'), + upgrade: (req, socket, head) => { + this.handleUpgrade(req, socket, head, emitConnection); + } + }); + } + + if (options.perMessageDeflate === true) options.perMessageDeflate = {}; + if (options.clientTracking) { + this.clients = new Set(); + this._shouldEmitClose = false; + } + + this.options = options; + this._state = RUNNING; + } + + /** + * Returns the bound address, the address family name, and port of the server + * as reported by the operating system if listening on an IP socket. + * If the server is listening on a pipe or UNIX domain socket, the name is + * returned as a string. + * + * @return {(Object|String|null)} The address of the server + * @public + */ + address() { + if (this.options.noServer) { + throw new Error('The server is operating in "noServer" mode'); + } + + if (!this._server) return null; + return this._server.address(); + } + + /** + * Stop the server from accepting new connections and emit the `'close'` event + * when all existing connections are closed. + * + * @param {Function} [cb] A one-time listener for the `'close'` event + * @public + */ + close(cb) { + if (this._state === CLOSED) { + if (cb) { + this.once('close', () => { + cb(new Error('The server is not running')); + }); + } + + process.nextTick(emitClose, this); + return; + } + + if (cb) this.once('close', cb); + + if (this._state === CLOSING) return; + this._state = CLOSING; + + if (this.options.noServer || this.options.server) { + if (this._server) { + this._removeListeners(); + this._removeListeners = this._server = null; + } + + if (this.clients) { + if (!this.clients.size) { + process.nextTick(emitClose, this); + } else { + this._shouldEmitClose = true; + } + } else { + process.nextTick(emitClose, this); + } + } else { + const server = this._server; + + this._removeListeners(); + this._removeListeners = this._server = null; + + // + // The HTTP/S server was created internally. Close it, and rely on its + // `'close'` event. + // + server.close(() => { + emitClose(this); + }); + } + } + + /** + * See if a given request should be handled by this server instance. + * + * @param {http.IncomingMessage} req Request object to inspect + * @return {Boolean} `true` if the request is valid, else `false` + * @public + */ + shouldHandle(req) { + if (this.options.path) { + const index = req.url.indexOf('?'); + const pathname = index !== -1 ? req.url.slice(0, index) : req.url; + + if (pathname !== this.options.path) return false; + } + + return true; + } + + /** + * Handle a HTTP Upgrade request. + * + * @param {http.IncomingMessage} req The request object + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @public + */ + handleUpgrade(req, socket, head, cb) { + socket.on('error', socketOnError); + + const key = req.headers['sec-websocket-key']; + const upgrade = req.headers.upgrade; + const version = +req.headers['sec-websocket-version']; + + if (req.method !== 'GET') { + const message = 'Invalid HTTP method'; + abortHandshakeOrEmitwsClientError(this, req, socket, 405, message); + return; + } + + if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') { + const message = 'Invalid Upgrade header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + + if (key === undefined || !keyRegex.test(key)) { + const message = 'Missing or invalid Sec-WebSocket-Key header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + + if (version !== 13 && version !== 8) { + const message = 'Missing or invalid Sec-WebSocket-Version header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, { + 'Sec-WebSocket-Version': '13, 8' + }); + return; + } + + if (!this.shouldHandle(req)) { + abortHandshake(socket, 400); + return; + } + + const secWebSocketProtocol = req.headers['sec-websocket-protocol']; + let protocols = new Set(); + + if (secWebSocketProtocol !== undefined) { + try { + protocols = subprotocol.parse(secWebSocketProtocol); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Protocol header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + } + + const secWebSocketExtensions = req.headers['sec-websocket-extensions']; + const extensions = {}; + + if ( + this.options.perMessageDeflate && + secWebSocketExtensions !== undefined + ) { + const perMessageDeflate = new PerMessageDeflate({ + ...this.options.perMessageDeflate, + isServer: true, + maxPayload: this.options.maxPayload + }); + + try { + const offers = extension.parse(secWebSocketExtensions); + + if (offers[PerMessageDeflate.extensionName]) { + perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); + extensions[PerMessageDeflate.extensionName] = perMessageDeflate; + } + } catch (err) { + const message = + 'Invalid or unacceptable Sec-WebSocket-Extensions header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + } + + // + // Optionally call external client verification handler. + // + if (this.options.verifyClient) { + const info = { + origin: + req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`], + secure: !!(req.socket.authorized || req.socket.encrypted), + req + }; + + if (this.options.verifyClient.length === 2) { + this.options.verifyClient(info, (verified, code, message, headers) => { + if (!verified) { + return abortHandshake(socket, code || 401, message, headers); + } + + this.completeUpgrade( + extensions, + key, + protocols, + req, + socket, + head, + cb + ); + }); + return; + } + + if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); + } + + this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); + } + + /** + * Upgrade the connection to WebSocket. + * + * @param {Object} extensions The accepted extensions + * @param {String} key The value of the `Sec-WebSocket-Key` header + * @param {Set} protocols The subprotocols + * @param {http.IncomingMessage} req The request object + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @throws {Error} If called more than once with the same socket + * @private + */ + completeUpgrade(extensions, key, protocols, req, socket, head, cb) { + // + // Destroy the socket if the client has already sent a FIN packet. + // + if (!socket.readable || !socket.writable) return socket.destroy(); + + if (socket[kWebSocket]) { + throw new Error( + 'server.handleUpgrade() was called more than once with the same ' + + 'socket, possibly due to a misconfiguration' + ); + } + + if (this._state > RUNNING) return abortHandshake(socket, 503); + + const digest = createHash('sha1') + .update(key + GUID) + .digest('base64'); + + const headers = [ + 'HTTP/1.1 101 Switching Protocols', + 'Upgrade: websocket', + 'Connection: Upgrade', + `Sec-WebSocket-Accept: ${digest}` + ]; + + const ws = new this.options.WebSocket(null, undefined, this.options); + + if (protocols.size) { + // + // Optionally call external protocol selection handler. + // + const protocol = this.options.handleProtocols + ? this.options.handleProtocols(protocols, req) + : protocols.values().next().value; + + if (protocol) { + headers.push(`Sec-WebSocket-Protocol: ${protocol}`); + ws._protocol = protocol; + } + } + + if (extensions[PerMessageDeflate.extensionName]) { + const params = extensions[PerMessageDeflate.extensionName].params; + const value = extension.format({ + [PerMessageDeflate.extensionName]: [params] + }); + headers.push(`Sec-WebSocket-Extensions: ${value}`); + ws._extensions = extensions; + } + + // + // Allow external modification/inspection of handshake headers. + // + this.emit('headers', headers, req); + + socket.write(headers.concat('\r\n').join('\r\n')); + socket.removeListener('error', socketOnError); + + ws.setSocket(socket, head, { + allowSynchronousEvents: this.options.allowSynchronousEvents, + maxBufferedChunks: this.options.maxBufferedChunks, + maxFragments: this.options.maxFragments, + maxPayload: this.options.maxPayload, + skipUTF8Validation: this.options.skipUTF8Validation + }); + + if (this.clients) { + this.clients.add(ws); + ws.on('close', () => { + this.clients.delete(ws); + + if (this._shouldEmitClose && !this.clients.size) { + process.nextTick(emitClose, this); + } + }); + } + + cb(ws, req); + } +} + +module.exports = WebSocketServer; + +/** + * Add event listeners on an `EventEmitter` using a map of + * pairs. + * + * @param {EventEmitter} server The event emitter + * @param {Object.} map The listeners to add + * @return {Function} A function that will remove the added listeners when + * called + * @private + */ +function addListeners(server, map) { + for (const event of Object.keys(map)) server.on(event, map[event]); + + return function removeListeners() { + for (const event of Object.keys(map)) { + server.removeListener(event, map[event]); + } + }; +} + +/** + * Emit a `'close'` event on an `EventEmitter`. + * + * @param {EventEmitter} server The event emitter + * @private + */ +function emitClose(server) { + server._state = CLOSED; + server.emit('close'); +} + +/** + * Handle socket errors. + * + * @private + */ +function socketOnError() { + this.destroy(); +} + +/** + * Close the connection when preconditions are not fulfilled. + * + * @param {Duplex} socket The socket of the upgrade request + * @param {Number} code The HTTP response status code + * @param {String} [message] The HTTP response body + * @param {Object} [headers] Additional HTTP response headers + * @private + */ +function abortHandshake(socket, code, message, headers) { + // + // The socket is writable unless the user destroyed or ended it before calling + // `server.handleUpgrade()` or in the `verifyClient` function, which is a user + // error. Handling this does not make much sense as the worst that can happen + // is that some of the data written by the user might be discarded due to the + // call to `socket.end()` below, which triggers an `'error'` event that in + // turn causes the socket to be destroyed. + // + message = message || http.STATUS_CODES[code]; + headers = { + Connection: 'close', + 'Content-Type': 'text/html', + 'Content-Length': Buffer.byteLength(message), + ...headers + }; + + socket.once('finish', socket.destroy); + + socket.end( + `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` + + Object.keys(headers) + .map((h) => `${h}: ${headers[h]}`) + .join('\r\n') + + '\r\n\r\n' + + message + ); +} + +/** + * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least + * one listener for it, otherwise call `abortHandshake()`. + * + * @param {WebSocketServer} server The WebSocket server + * @param {http.IncomingMessage} req The request object + * @param {Duplex} socket The socket of the upgrade request + * @param {Number} code The HTTP response status code + * @param {String} message The HTTP response body + * @param {Object} [headers] The HTTP response headers + * @private + */ +function abortHandshakeOrEmitwsClientError( + server, + req, + socket, + code, + message, + headers +) { + if (server.listenerCount('wsClientError')) { + const err = new Error(message); + Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError); + + server.emit('wsClientError', err, socket, req); + } else { + abortHandshake(socket, code, message, headers); + } +} diff --git a/node_modules/ws/lib/websocket.js b/node_modules/ws/lib/websocket.js new file mode 100644 index 0000000000000000000000000000000000000000..ed3735ea48cab527a00f9245700159ceff28889c --- /dev/null +++ b/node_modules/ws/lib/websocket.js @@ -0,0 +1,1407 @@ +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex|Readable$", "caughtErrors": "none" }] */ + +'use strict'; + +const EventEmitter = require('events'); +const https = require('https'); +const http = require('http'); +const net = require('net'); +const tls = require('tls'); +const { randomBytes, createHash } = require('crypto'); +const { Duplex, Readable } = require('stream'); +const { URL } = require('url'); + +const PerMessageDeflate = require('./permessage-deflate'); +const Receiver = require('./receiver'); +const Sender = require('./sender'); +const { isBlob } = require('./validation'); + +const { + BINARY_TYPES, + CLOSE_TIMEOUT, + EMPTY_BUFFER, + GUID, + kForOnEventAttribute, + kListener, + kStatusCode, + kWebSocket, + NOOP +} = require('./constants'); +const { + EventTarget: { addEventListener, removeEventListener } +} = require('./event-target'); +const { format, parse } = require('./extension'); +const { toBuffer } = require('./buffer-util'); + +const kAborted = Symbol('kAborted'); +const protocolVersions = [8, 13]; +const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']; +const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/; + +/** + * Class representing a WebSocket. + * + * @extends EventEmitter + */ +class WebSocket extends EventEmitter { + /** + * Create a new `WebSocket`. + * + * @param {(String|URL)} address The URL to which to connect + * @param {(String|String[])} [protocols] The subprotocols + * @param {Object} [options] Connection options + */ + constructor(address, protocols, options) { + super(); + + this._binaryType = BINARY_TYPES[0]; + this._closeCode = 1006; + this._closeFrameReceived = false; + this._closeFrameSent = false; + this._closeMessage = EMPTY_BUFFER; + this._closeTimer = null; + this._errorEmitted = false; + this._extensions = {}; + this._paused = false; + this._protocol = ''; + this._readyState = WebSocket.CONNECTING; + this._receiver = null; + this._sender = null; + this._socket = null; + + if (address !== null) { + this._bufferedAmount = 0; + this._isServer = false; + this._redirects = 0; + + if (protocols === undefined) { + protocols = []; + } else if (!Array.isArray(protocols)) { + if (typeof protocols === 'object' && protocols !== null) { + options = protocols; + protocols = []; + } else { + protocols = [protocols]; + } + } + + initAsClient(this, address, protocols, options); + } else { + this._autoPong = options.autoPong; + this._closeTimeout = options.closeTimeout; + this._isServer = true; + } + } + + /** + * For historical reasons, the custom "nodebuffer" type is used by the default + * instead of "blob". + * + * @type {String} + */ + get binaryType() { + return this._binaryType; + } + + set binaryType(type) { + if (!BINARY_TYPES.includes(type)) return; + + this._binaryType = type; + + // + // Allow to change `binaryType` on the fly. + // + if (this._receiver) this._receiver._binaryType = type; + } + + /** + * @type {Number} + */ + get bufferedAmount() { + if (!this._socket) return this._bufferedAmount; + + return this._socket._writableState.length + this._sender._bufferedBytes; + } + + /** + * @type {String} + */ + get extensions() { + return Object.keys(this._extensions).join(); + } + + /** + * @type {Boolean} + */ + get isPaused() { + return this._paused; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onclose() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onerror() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onopen() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onmessage() { + return null; + } + + /** + * @type {String} + */ + get protocol() { + return this._protocol; + } + + /** + * @type {Number} + */ + get readyState() { + return this._readyState; + } + + /** + * @type {String} + */ + get url() { + return this._url; + } + + /** + * Set up the socket and the internal resources. + * + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Object} options Options object + * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether + * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted + * multiple times in the same tick + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Number} [options.maxBufferedChunks=0] The maximum number of + * buffered data chunks + * @param {Number} [options.maxFragments=0] The maximum number of message + * fragments + * @param {Number} [options.maxPayload=0] The maximum allowed message size + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @private + */ + setSocket(socket, head, options) { + const receiver = new Receiver({ + allowSynchronousEvents: options.allowSynchronousEvents, + binaryType: this.binaryType, + extensions: this._extensions, + isServer: this._isServer, + maxBufferedChunks: options.maxBufferedChunks, + maxFragments: options.maxFragments, + maxPayload: options.maxPayload, + skipUTF8Validation: options.skipUTF8Validation + }); + + const sender = new Sender(socket, this._extensions, options.generateMask); + + this._receiver = receiver; + this._sender = sender; + this._socket = socket; + + receiver[kWebSocket] = this; + sender[kWebSocket] = this; + socket[kWebSocket] = this; + + receiver.on('conclude', receiverOnConclude); + receiver.on('drain', receiverOnDrain); + receiver.on('error', receiverOnError); + receiver.on('message', receiverOnMessage); + receiver.on('ping', receiverOnPing); + receiver.on('pong', receiverOnPong); + + sender.onerror = senderOnError; + + // + // These methods may not be available if `socket` is just a `Duplex`. + // + if (socket.setTimeout) socket.setTimeout(0); + if (socket.setNoDelay) socket.setNoDelay(); + + if (head.length > 0) socket.unshift(head); + + socket.on('close', socketOnClose); + socket.on('data', socketOnData); + socket.on('end', socketOnEnd); + socket.on('error', socketOnError); + + this._readyState = WebSocket.OPEN; + this.emit('open'); + } + + /** + * Emit the `'close'` event. + * + * @private + */ + emitClose() { + if (!this._socket) { + this._readyState = WebSocket.CLOSED; + this.emit('close', this._closeCode, this._closeMessage); + return; + } + + if (this._extensions[PerMessageDeflate.extensionName]) { + this._extensions[PerMessageDeflate.extensionName].cleanup(); + } + + this._receiver.removeAllListeners(); + this._readyState = WebSocket.CLOSED; + this.emit('close', this._closeCode, this._closeMessage); + } + + /** + * Start a closing handshake. + * + * +----------+ +-----------+ +----------+ + * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - + * | +----------+ +-----------+ +----------+ | + * +----------+ +-----------+ | + * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING + * +----------+ +-----------+ | + * | | | +---+ | + * +------------------------+-->|fin| - - - - + * | +---+ | +---+ + * - - - - -|fin|<---------------------+ + * +---+ + * + * @param {Number} [code] Status code explaining why the connection is closing + * @param {(String|Buffer)} [data] The reason why the connection is + * closing + * @public + */ + close(code, data) { + if (this.readyState === WebSocket.CLOSED) return; + if (this.readyState === WebSocket.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + abortHandshake(this, this._req, msg); + return; + } + + if (this.readyState === WebSocket.CLOSING) { + if ( + this._closeFrameSent && + (this._closeFrameReceived || this._receiver._writableState.errorEmitted) + ) { + this._socket.end(); + } + + return; + } + + this._readyState = WebSocket.CLOSING; + this._sender.close(code, data, !this._isServer, (err) => { + // + // This error is handled by the `'error'` listener on the socket. We only + // want to know if the close frame has been sent here. + // + if (err) return; + + this._closeFrameSent = true; + + if ( + this._closeFrameReceived || + this._receiver._writableState.errorEmitted + ) { + this._socket.end(); + } + }); + + setCloseTimer(this); + } + + /** + * Pause the socket. + * + * @public + */ + pause() { + if ( + this.readyState === WebSocket.CONNECTING || + this.readyState === WebSocket.CLOSED + ) { + return; + } + + this._paused = true; + this._socket.pause(); + } + + /** + * Send a ping. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the ping is sent + * @public + */ + ping(data, mask, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + if (mask === undefined) mask = !this._isServer; + this._sender.ping(data || EMPTY_BUFFER, mask, cb); + } + + /** + * Send a pong. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the pong is sent + * @public + */ + pong(data, mask, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + if (mask === undefined) mask = !this._isServer; + this._sender.pong(data || EMPTY_BUFFER, mask, cb); + } + + /** + * Resume the socket. + * + * @public + */ + resume() { + if ( + this.readyState === WebSocket.CONNECTING || + this.readyState === WebSocket.CLOSED + ) { + return; + } + + this._paused = false; + if (!this._receiver._writableState.needDrain) this._socket.resume(); + } + + /** + * Send a data message. + * + * @param {*} data The message to send + * @param {Object} [options] Options object + * @param {Boolean} [options.binary] Specifies whether `data` is binary or + * text + * @param {Boolean} [options.compress] Specifies whether or not to compress + * `data` + * @param {Boolean} [options.fin=true] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when data is written out + * @public + */ + send(data, options, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof options === 'function') { + cb = options; + options = {}; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + const opts = { + binary: typeof data !== 'string', + mask: !this._isServer, + compress: true, + fin: true, + ...options + }; + + if (!this._extensions[PerMessageDeflate.extensionName]) { + opts.compress = false; + } + + this._sender.send(data || EMPTY_BUFFER, opts, cb); + } + + /** + * Forcibly close the connection. + * + * @public + */ + terminate() { + if (this.readyState === WebSocket.CLOSED) return; + if (this.readyState === WebSocket.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + abortHandshake(this, this._req, msg); + return; + } + + if (this._socket) { + this._readyState = WebSocket.CLOSING; + this._socket.destroy(); + } + } +} + +/** + * @constant {Number} CONNECTING + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CONNECTING', { + enumerable: true, + value: readyStates.indexOf('CONNECTING') +}); + +/** + * @constant {Number} CONNECTING + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CONNECTING', { + enumerable: true, + value: readyStates.indexOf('CONNECTING') +}); + +/** + * @constant {Number} OPEN + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'OPEN', { + enumerable: true, + value: readyStates.indexOf('OPEN') +}); + +/** + * @constant {Number} OPEN + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'OPEN', { + enumerable: true, + value: readyStates.indexOf('OPEN') +}); + +/** + * @constant {Number} CLOSING + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CLOSING', { + enumerable: true, + value: readyStates.indexOf('CLOSING') +}); + +/** + * @constant {Number} CLOSING + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CLOSING', { + enumerable: true, + value: readyStates.indexOf('CLOSING') +}); + +/** + * @constant {Number} CLOSED + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CLOSED', { + enumerable: true, + value: readyStates.indexOf('CLOSED') +}); + +/** + * @constant {Number} CLOSED + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CLOSED', { + enumerable: true, + value: readyStates.indexOf('CLOSED') +}); + +[ + 'binaryType', + 'bufferedAmount', + 'extensions', + 'isPaused', + 'protocol', + 'readyState', + 'url' +].forEach((property) => { + Object.defineProperty(WebSocket.prototype, property, { enumerable: true }); +}); + +// +// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes. +// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface +// +['open', 'error', 'close', 'message'].forEach((method) => { + Object.defineProperty(WebSocket.prototype, `on${method}`, { + enumerable: true, + get() { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) return listener[kListener]; + } + + return null; + }, + set(handler) { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) { + this.removeListener(method, listener); + break; + } + } + + if (typeof handler !== 'function') return; + + this.addEventListener(method, handler, { + [kForOnEventAttribute]: true + }); + } + }); +}); + +WebSocket.prototype.addEventListener = addEventListener; +WebSocket.prototype.removeEventListener = removeEventListener; + +module.exports = WebSocket; + +/** + * Initialize a WebSocket client. + * + * @param {WebSocket} websocket The client to initialize + * @param {(String|URL)} address The URL to which to connect + * @param {Array} protocols The subprotocols + * @param {Object} [options] Connection options + * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any + * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple + * times in the same tick + * @param {Boolean} [options.autoPong=true] Specifies whether or not to + * automatically send a pong in response to a ping + * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to wait + * for the closing handshake to finish after `websocket.close()` is called + * @param {Function} [options.finishRequest] A function which can be used to + * customize the headers of each http request before it is sent + * @param {Boolean} [options.followRedirects=false] Whether or not to follow + * redirects + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the + * handshake request + * @param {Number} [options.maxBufferedChunks=1048576] The maximum number of + * buffered data chunks + * @param {Number} [options.maxFragments=131072] The maximum number of message + * fragments + * @param {Number} [options.maxPayload=104857600] The maximum allowed message + * size + * @param {Number} [options.maxRedirects=10] The maximum number of redirects + * allowed + * @param {String} [options.origin] Value of the `Origin` or + * `Sec-WebSocket-Origin` header + * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable + * permessage-deflate + * @param {Number} [options.protocolVersion=13] Value of the + * `Sec-WebSocket-Version` header + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @private + */ +function initAsClient(websocket, address, protocols, options) { + const opts = { + allowSynchronousEvents: true, + autoPong: true, + closeTimeout: CLOSE_TIMEOUT, + protocolVersion: protocolVersions[1], + maxBufferedChunks: 1024 * 1024, + maxFragments: 128 * 1024, + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: true, + followRedirects: false, + maxRedirects: 10, + ...options, + socketPath: undefined, + hostname: undefined, + protocol: undefined, + timeout: undefined, + method: 'GET', + host: undefined, + path: undefined, + port: undefined + }; + + websocket._autoPong = opts.autoPong; + websocket._closeTimeout = opts.closeTimeout; + + if (!protocolVersions.includes(opts.protocolVersion)) { + throw new RangeError( + `Unsupported protocol version: ${opts.protocolVersion} ` + + `(supported versions: ${protocolVersions.join(', ')})` + ); + } + + let parsedUrl; + + if (address instanceof URL) { + parsedUrl = address; + } else { + try { + parsedUrl = new URL(address); + } catch { + throw new SyntaxError(`Invalid URL: ${address}`); + } + } + + if (parsedUrl.protocol === 'http:') { + parsedUrl.protocol = 'ws:'; + } else if (parsedUrl.protocol === 'https:') { + parsedUrl.protocol = 'wss:'; + } + + websocket._url = parsedUrl.href; + + const isSecure = parsedUrl.protocol === 'wss:'; + const isIpcUrl = parsedUrl.protocol === 'ws+unix:'; + let invalidUrlMessage; + + if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) { + invalidUrlMessage = + 'The URL\'s protocol must be one of "ws:", "wss:", ' + + '"http:", "https:", or "ws+unix:"'; + } else if (isIpcUrl && !parsedUrl.pathname) { + invalidUrlMessage = "The URL's pathname is empty"; + } else if (parsedUrl.hash) { + invalidUrlMessage = 'The URL contains a fragment identifier'; + } + + if (invalidUrlMessage) { + const err = new SyntaxError(invalidUrlMessage); + + if (websocket._redirects === 0) { + throw err; + } else { + emitErrorAndClose(websocket, err); + return; + } + } + + const defaultPort = isSecure ? 443 : 80; + const key = randomBytes(16).toString('base64'); + const request = isSecure ? https.request : http.request; + const protocolSet = new Set(); + let perMessageDeflate; + + opts.createConnection = + opts.createConnection || (isSecure ? tlsConnect : netConnect); + opts.defaultPort = opts.defaultPort || defaultPort; + opts.port = parsedUrl.port || defaultPort; + opts.host = parsedUrl.hostname.startsWith('[') + ? parsedUrl.hostname.slice(1, -1) + : parsedUrl.hostname; + opts.headers = { + ...opts.headers, + 'Sec-WebSocket-Version': opts.protocolVersion, + 'Sec-WebSocket-Key': key, + Connection: 'Upgrade', + Upgrade: 'websocket' + }; + opts.path = parsedUrl.pathname + parsedUrl.search; + opts.timeout = opts.handshakeTimeout; + + if (opts.perMessageDeflate) { + perMessageDeflate = new PerMessageDeflate({ + ...opts.perMessageDeflate, + isServer: false, + maxPayload: opts.maxPayload + }); + opts.headers['Sec-WebSocket-Extensions'] = format({ + [PerMessageDeflate.extensionName]: perMessageDeflate.offer() + }); + } + if (protocols.length) { + for (const protocol of protocols) { + if ( + typeof protocol !== 'string' || + !subprotocolRegex.test(protocol) || + protocolSet.has(protocol) + ) { + throw new SyntaxError( + 'An invalid or duplicated subprotocol was specified' + ); + } + + protocolSet.add(protocol); + } + + opts.headers['Sec-WebSocket-Protocol'] = protocols.join(','); + } + if (opts.origin) { + if (opts.protocolVersion < 13) { + opts.headers['Sec-WebSocket-Origin'] = opts.origin; + } else { + opts.headers.Origin = opts.origin; + } + } + if (parsedUrl.username || parsedUrl.password) { + opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; + } + + if (isIpcUrl) { + const parts = opts.path.split(':'); + + opts.socketPath = parts[0]; + opts.path = parts[1]; + } + + let req; + + if (opts.followRedirects) { + if (websocket._redirects === 0) { + websocket._originalIpc = isIpcUrl; + websocket._originalSecure = isSecure; + websocket._originalHostOrSocketPath = isIpcUrl + ? opts.socketPath + : parsedUrl.host; + + const headers = options && options.headers; + + // + // Shallow copy the user provided options so that headers can be changed + // without mutating the original object. + // + options = { ...options, headers: {} }; + + if (headers) { + for (const [key, value] of Object.entries(headers)) { + options.headers[key.toLowerCase()] = value; + } + } + } else if (websocket.listenerCount('redirect') === 0) { + const isSameHost = isIpcUrl + ? websocket._originalIpc + ? opts.socketPath === websocket._originalHostOrSocketPath + : false + : websocket._originalIpc + ? false + : parsedUrl.host === websocket._originalHostOrSocketPath; + + if (!isSameHost || (websocket._originalSecure && !isSecure)) { + // + // Match curl 7.77.0 behavior and drop the following headers. These + // headers are also dropped when following a redirect to a subdomain. + // + delete opts.headers.authorization; + delete opts.headers.cookie; + + if (!isSameHost) delete opts.headers.host; + + opts.auth = undefined; + } + } + + // + // Match curl 7.77.0 behavior and make the first `Authorization` header win. + // If the `Authorization` header is set, then there is nothing to do as it + // will take precedence. + // + if (opts.auth && !options.headers.authorization) { + options.headers.authorization = + 'Basic ' + Buffer.from(opts.auth).toString('base64'); + } + + req = websocket._req = request(opts); + + if (websocket._redirects) { + // + // Unlike what is done for the `'upgrade'` event, no early exit is + // triggered here if the user calls `websocket.close()` or + // `websocket.terminate()` from a listener of the `'redirect'` event. This + // is because the user can also call `request.destroy()` with an error + // before calling `websocket.close()` or `websocket.terminate()` and this + // would result in an error being emitted on the `request` object with no + // `'error'` event listeners attached. + // + websocket.emit('redirect', websocket.url, req); + } + } else { + req = websocket._req = request(opts); + } + + if (opts.timeout) { + req.on('timeout', () => { + abortHandshake(websocket, req, 'Opening handshake has timed out'); + }); + } + + req.on('error', (err) => { + if (req === null || req[kAborted]) return; + + req = websocket._req = null; + emitErrorAndClose(websocket, err); + }); + + req.on('response', (res) => { + const location = res.headers.location; + const statusCode = res.statusCode; + + if ( + location && + opts.followRedirects && + statusCode >= 300 && + statusCode < 400 + ) { + if (++websocket._redirects > opts.maxRedirects) { + abortHandshake(websocket, req, 'Maximum redirects exceeded'); + return; + } + + req.abort(); + + let addr; + + try { + addr = new URL(location, address); + } catch (e) { + const err = new SyntaxError(`Invalid URL: ${location}`); + emitErrorAndClose(websocket, err); + return; + } + + initAsClient(websocket, addr, protocols, options); + } else if (!websocket.emit('unexpected-response', req, res)) { + abortHandshake( + websocket, + req, + `Unexpected server response: ${res.statusCode}` + ); + } + }); + + req.on('upgrade', (res, socket, head) => { + websocket.emit('upgrade', res); + + // + // The user may have closed the connection from a listener of the + // `'upgrade'` event. + // + if (websocket.readyState !== WebSocket.CONNECTING) return; + + req = websocket._req = null; + + const upgrade = res.headers.upgrade; + + if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') { + abortHandshake(websocket, socket, 'Invalid Upgrade header'); + return; + } + + const digest = createHash('sha1') + .update(key + GUID) + .digest('base64'); + + if (res.headers['sec-websocket-accept'] !== digest) { + abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header'); + return; + } + + const serverProt = res.headers['sec-websocket-protocol']; + let protError; + + if (serverProt !== undefined) { + if (!protocolSet.size) { + protError = 'Server sent a subprotocol but none was requested'; + } else if (!protocolSet.has(serverProt)) { + protError = 'Server sent an invalid subprotocol'; + } + } else if (protocolSet.size) { + protError = 'Server sent no subprotocol'; + } + + if (protError) { + abortHandshake(websocket, socket, protError); + return; + } + + if (serverProt) websocket._protocol = serverProt; + + const secWebSocketExtensions = res.headers['sec-websocket-extensions']; + + if (secWebSocketExtensions !== undefined) { + if (!perMessageDeflate) { + const message = + 'Server sent a Sec-WebSocket-Extensions header but no extension ' + + 'was requested'; + abortHandshake(websocket, socket, message); + return; + } + + let extensions; + + try { + extensions = parse(secWebSocketExtensions); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Extensions header'; + abortHandshake(websocket, socket, message); + return; + } + + const extensionNames = Object.keys(extensions); + + if ( + extensionNames.length !== 1 || + extensionNames[0] !== PerMessageDeflate.extensionName + ) { + const message = 'Server indicated an extension that was not requested'; + abortHandshake(websocket, socket, message); + return; + } + + try { + perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Extensions header'; + abortHandshake(websocket, socket, message); + return; + } + + websocket._extensions[PerMessageDeflate.extensionName] = + perMessageDeflate; + } + + websocket.setSocket(socket, head, { + allowSynchronousEvents: opts.allowSynchronousEvents, + generateMask: opts.generateMask, + maxBufferedChunks: opts.maxBufferedChunks, + maxFragments: opts.maxFragments, + maxPayload: opts.maxPayload, + skipUTF8Validation: opts.skipUTF8Validation + }); + }); + + if (opts.finishRequest) { + opts.finishRequest(req, websocket); + } else { + req.end(); + } +} + +/** + * Emit the `'error'` and `'close'` events. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {Error} The error to emit + * @private + */ +function emitErrorAndClose(websocket, err) { + websocket._readyState = WebSocket.CLOSING; + // + // The following assignment is practically useless and is done only for + // consistency. + // + websocket._errorEmitted = true; + websocket.emit('error', err); + websocket.emitClose(); +} + +/** + * Create a `net.Socket` and initiate a connection. + * + * @param {Object} options Connection options + * @return {net.Socket} The newly created socket used to start the connection + * @private + */ +function netConnect(options) { + options.path = options.socketPath; + return net.connect(options); +} + +/** + * Create a `tls.TLSSocket` and initiate a connection. + * + * @param {Object} options Connection options + * @return {tls.TLSSocket} The newly created socket used to start the connection + * @private + */ +function tlsConnect(options) { + options.path = undefined; + + if (!options.servername && options.servername !== '') { + options.servername = net.isIP(options.host) ? '' : options.host; + } + + return tls.connect(options); +} + +/** + * Abort the handshake and emit an error. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to + * abort or the socket to destroy + * @param {String} message The error message + * @private + */ +function abortHandshake(websocket, stream, message) { + websocket._readyState = WebSocket.CLOSING; + + const err = new Error(message); + Error.captureStackTrace(err, abortHandshake); + + if (stream.setHeader) { + stream[kAborted] = true; + stream.abort(); + + if (stream.socket && !stream.socket.destroyed) { + // + // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if + // called after the request completed. See + // https://github.com/websockets/ws/issues/1869. + // + stream.socket.destroy(); + } + + process.nextTick(emitErrorAndClose, websocket, err); + } else { + stream.destroy(err); + stream.once('error', websocket.emit.bind(websocket, 'error')); + stream.once('close', websocket.emitClose.bind(websocket)); + } +} + +/** + * Handle cases where the `ping()`, `pong()`, or `send()` methods are called + * when the `readyState` attribute is `CLOSING` or `CLOSED`. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {*} [data] The data to send + * @param {Function} [cb] Callback + * @private + */ +function sendAfterClose(websocket, data, cb) { + if (data) { + const length = isBlob(data) ? data.size : toBuffer(data).length; + + // + // The `_bufferedAmount` property is used only when the peer is a client and + // the opening handshake fails. Under these circumstances, in fact, the + // `setSocket()` method is not called, so the `_socket` and `_sender` + // properties are set to `null`. + // + if (websocket._socket) websocket._sender._bufferedBytes += length; + else websocket._bufferedAmount += length; + } + + if (cb) { + const err = new Error( + `WebSocket is not open: readyState ${websocket.readyState} ` + + `(${readyStates[websocket.readyState]})` + ); + process.nextTick(cb, err); + } +} + +/** + * The listener of the `Receiver` `'conclude'` event. + * + * @param {Number} code The status code + * @param {Buffer} reason The reason for closing + * @private + */ +function receiverOnConclude(code, reason) { + const websocket = this[kWebSocket]; + + websocket._closeFrameReceived = true; + websocket._closeMessage = reason; + websocket._closeCode = code; + + if (websocket._socket[kWebSocket] === undefined) return; + + websocket._socket.removeListener('data', socketOnData); + process.nextTick(resume, websocket._socket); + + if (code === 1005) websocket.close(); + else websocket.close(code, reason); +} + +/** + * The listener of the `Receiver` `'drain'` event. + * + * @private + */ +function receiverOnDrain() { + const websocket = this[kWebSocket]; + + if (!websocket.isPaused) websocket._socket.resume(); +} + +/** + * The listener of the `Receiver` `'error'` event. + * + * @param {(RangeError|Error)} err The emitted error + * @private + */ +function receiverOnError(err) { + const websocket = this[kWebSocket]; + + if (websocket._socket[kWebSocket] !== undefined) { + websocket._socket.removeListener('data', socketOnData); + + // + // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See + // https://github.com/websockets/ws/issues/1940. + // + process.nextTick(resume, websocket._socket); + + websocket.close(err[kStatusCode]); + } + + if (!websocket._errorEmitted) { + websocket._errorEmitted = true; + websocket.emit('error', err); + } +} + +/** + * The listener of the `Receiver` `'finish'` event. + * + * @private + */ +function receiverOnFinish() { + this[kWebSocket].emitClose(); +} + +/** + * The listener of the `Receiver` `'message'` event. + * + * @param {Buffer|ArrayBuffer|Buffer[])} data The message + * @param {Boolean} isBinary Specifies whether the message is binary or not + * @private + */ +function receiverOnMessage(data, isBinary) { + this[kWebSocket].emit('message', data, isBinary); +} + +/** + * The listener of the `Receiver` `'ping'` event. + * + * @param {Buffer} data The data included in the ping frame + * @private + */ +function receiverOnPing(data) { + const websocket = this[kWebSocket]; + + if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP); + websocket.emit('ping', data); +} + +/** + * The listener of the `Receiver` `'pong'` event. + * + * @param {Buffer} data The data included in the pong frame + * @private + */ +function receiverOnPong(data) { + this[kWebSocket].emit('pong', data); +} + +/** + * Resume a readable stream + * + * @param {Readable} stream The readable stream + * @private + */ +function resume(stream) { + stream.resume(); +} + +/** + * The `Sender` error event handler. + * + * @param {Error} The error + * @private + */ +function senderOnError(err) { + const websocket = this[kWebSocket]; + + if (websocket.readyState === WebSocket.CLOSED) return; + if (websocket.readyState === WebSocket.OPEN) { + websocket._readyState = WebSocket.CLOSING; + setCloseTimer(websocket); + } + + // + // `socket.end()` is used instead of `socket.destroy()` to allow the other + // peer to finish sending queued data. There is no need to set a timer here + // because `CLOSING` means that it is already set or not needed. + // + this._socket.end(); + + if (!websocket._errorEmitted) { + websocket._errorEmitted = true; + websocket.emit('error', err); + } +} + +/** + * Set a timer to destroy the underlying raw socket of a WebSocket. + * + * @param {WebSocket} websocket The WebSocket instance + * @private + */ +function setCloseTimer(websocket) { + websocket._closeTimer = setTimeout( + websocket._socket.destroy.bind(websocket._socket), + websocket._closeTimeout + ); +} + +/** + * The listener of the socket `'close'` event. + * + * @private + */ +function socketOnClose() { + const websocket = this[kWebSocket]; + + this.removeListener('close', socketOnClose); + this.removeListener('data', socketOnData); + this.removeListener('end', socketOnEnd); + + websocket._readyState = WebSocket.CLOSING; + + // + // The close frame might not have been received or the `'end'` event emitted, + // for example, if the socket was destroyed due to an error. Ensure that the + // `receiver` stream is closed after writing any remaining buffered data to + // it. If the readable side of the socket is in flowing mode then there is no + // buffered data as everything has been already written. If instead, the + // socket is paused, any possible buffered data will be read as a single + // chunk. + // + if ( + !this._readableState.endEmitted && + !websocket._closeFrameReceived && + !websocket._receiver._writableState.errorEmitted && + this._readableState.length !== 0 + ) { + const chunk = this.read(this._readableState.length); + + websocket._receiver.write(chunk); + } + + websocket._receiver.end(); + + this[kWebSocket] = undefined; + + clearTimeout(websocket._closeTimer); + + if ( + websocket._receiver._writableState.finished || + websocket._receiver._writableState.errorEmitted + ) { + websocket.emitClose(); + } else { + websocket._receiver.on('error', receiverOnFinish); + websocket._receiver.on('finish', receiverOnFinish); + } +} + +/** + * The listener of the socket `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function socketOnData(chunk) { + if (!this[kWebSocket]._receiver.write(chunk)) { + this.pause(); + } +} + +/** + * The listener of the socket `'end'` event. + * + * @private + */ +function socketOnEnd() { + const websocket = this[kWebSocket]; + + websocket._readyState = WebSocket.CLOSING; + websocket._receiver.end(); + this.end(); +} + +/** + * The listener of the socket `'error'` event. + * + * @private + */ +function socketOnError() { + const websocket = this[kWebSocket]; + + this.removeListener('error', socketOnError); + this.on('error', NOOP); + + if (websocket) { + websocket._readyState = WebSocket.CLOSING; + this.destroy(); + } +} diff --git a/node_modules/ws/package.json b/node_modules/ws/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9116e663298ebdb1321f29b44463a25d76d4791b --- /dev/null +++ b/node_modules/ws/package.json @@ -0,0 +1,70 @@ +{ + "name": "ws", + "version": "8.21.0", + "description": "Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js", + "keywords": [ + "HyBi", + "Push", + "RFC-6455", + "WebSocket", + "WebSockets", + "real-time" + ], + "homepage": "https://github.com/websockets/ws", + "bugs": "https://github.com/websockets/ws/issues", + "repository": { + "type": "git", + "url": "git+https://github.com/websockets/ws.git" + }, + "author": "Einar Otto Stangvik (http://2x.io)", + "license": "MIT", + "main": "index.js", + "exports": { + ".": { + "browser": "./browser.js", + "import": "./wrapper.mjs", + "require": "./index.js" + }, + "./package.json": "./package.json" + }, + "browser": "browser.js", + "engines": { + "node": ">=10.0.0" + }, + "files": [ + "browser.js", + "index.js", + "lib/*.js", + "wrapper.mjs" + ], + "scripts": { + "test": "nyc --reporter=lcov --reporter=text mocha --throw-deprecation test/*.test.js", + "integration": "mocha --throw-deprecation test/*.integration.js", + "lint": "eslint . && prettier --check --ignore-path .gitignore \"**/*.{json,md,yaml,yml}\"" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + }, + "devDependencies": { + "@eslint/js": "^10.0.1", + "benchmark": "^2.1.4", + "bufferutil": "^4.0.1", + "eslint": "^10.0.1", + "eslint-config-prettier": "^10.0.1", + "eslint-plugin-prettier": "^5.0.0", + "globals": "^17.0.0", + "mocha": "^8.4.0", + "nyc": "^15.0.0", + "prettier": "^3.0.0", + "utf-8-validate": "^6.0.0" + } +} diff --git a/node_modules/ws/wrapper.mjs b/node_modules/ws/wrapper.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a8ffabbb0e7de8c578eeb056907b58ea31cc3b22 --- /dev/null +++ b/node_modules/ws/wrapper.mjs @@ -0,0 +1,21 @@ +import createWebSocketStream from './lib/stream.js'; +import extension from './lib/extension.js'; +import PerMessageDeflate from './lib/permessage-deflate.js'; +import Receiver from './lib/receiver.js'; +import Sender from './lib/sender.js'; +import subprotocol from './lib/subprotocol.js'; +import WebSocket from './lib/websocket.js'; +import WebSocketServer from './lib/websocket-server.js'; + +export { + createWebSocketStream, + extension, + PerMessageDeflate, + Receiver, + Sender, + subprotocol, + WebSocket, + WebSocketServer +}; + +export default WebSocket; diff --git a/node_modules/xml-name-validator/LICENSE.txt b/node_modules/xml-name-validator/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..d9a10c0d8e868ebf8da0b3dc95bb0be634c34bfe --- /dev/null +++ b/node_modules/xml-name-validator/LICENSE.txt @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/node_modules/xml-name-validator/README.md b/node_modules/xml-name-validator/README.md new file mode 100644 index 0000000000000000000000000000000000000000..175f86a60241a6a41f325c5757612cc6a78639f9 --- /dev/null +++ b/node_modules/xml-name-validator/README.md @@ -0,0 +1,35 @@ +# Validate XML Names and Qualified Names + +This package simply tells you whether or not a string matches the [`Name`](http://www.w3.org/TR/xml/#NT-Name) or [`QName`](http://www.w3.org/TR/xml-names/#NT-QName) productions in the XML Namespaces specification. We use it for implementing the [validate](https://dom.spec.whatwg.org/#validate) algorithm in jsdom, but you can use it for whatever you want. + +## Usage + +This package's main module exports two functions, `name()` and `qname()`. Both take a string and return a boolean indicating whether or not the string matches the relevant production. + +```js +"use strict": +const xnv = require("xml-name-validator"); + +// Will return true +xnv.name("x"); +xnv.name(":"); +xnv.name("a:0"); +xnv.name("a:b:c"); + +// Will return false +xnv.name("\\"); +xnv.name("'"); +xnv.name("0"); +xnv.name("a!"); + +// Will return true +xnv.qname("x"); +xnv.qname("a0"); +xnv.qname("a:b"); + +// Will return false +xnv.qname(":a"); +xnv.qname(":b"); +xnv.qname("a:b:c"); +xnv.qname("a:0"); +``` diff --git a/node_modules/xml-name-validator/lib/xml-name-validator.js b/node_modules/xml-name-validator/lib/xml-name-validator.js new file mode 100644 index 0000000000000000000000000000000000000000..d732a5ed89d2f7b34841a34c2b4eb3f6b48eeb99 --- /dev/null +++ b/node_modules/xml-name-validator/lib/xml-name-validator.js @@ -0,0 +1,9 @@ +"use strict"; + +exports.name = potentialName => { + return /^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/u.test(potentialName); +}; + +exports.qname = potentialQname => { + return /(?:^[A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}][A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*:[A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}][A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$)|(?:^[A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}][A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$)/u.test(potentialQname); +}; diff --git a/node_modules/xml-name-validator/package.json b/node_modules/xml-name-validator/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0f3a3dee256de899d12e223be7e6cd474cdc1298 --- /dev/null +++ b/node_modules/xml-name-validator/package.json @@ -0,0 +1,30 @@ +{ + "name": "xml-name-validator", + "description": "Validates whether a string matches the production for an XML name or qualified name", + "keywords": [ + "xml", + "name", + "qname" + ], + "version": "5.0.0", + "author": "Domenic Denicola (https://domenic.me/)", + "license": "Apache-2.0", + "repository": "jsdom/xml-name-validator", + "main": "lib/xml-name-validator.js", + "files": [ + "lib/" + ], + "scripts": { + "test": "node --test", + "benchmark": "node scripts/benchmark.js", + "lint": "eslint ." + }, + "devDependencies": { + "@domenic/eslint-config": "^3.0.0", + "benchmark": "^2.1.4", + "eslint": "^8.53.0" + }, + "engines": { + "node": ">=18" + } +} diff --git a/node_modules/xml-naming/README.md b/node_modules/xml-naming/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b1335516c8238043b74e2de3163e1189dc126229 --- /dev/null +++ b/node_modules/xml-naming/README.md @@ -0,0 +1,189 @@ +# xml-naming + +Validates XML name productions as defined in the [XML 1.0](https://www.w3.org/TR/xml/) and [XML 1.1](https://www.w3.org/TR/xml11/) specifications. + +Covers all five productions: + +| Production | Description | Colon | Digit/hyphen start | +|---|---|---|---| +| `Name` | General XML name | ✅ | ❌ | +| `NCName` | Non-Colonized name | ❌ | ❌ | +| `QName` | Namespace-qualified name (`prefix:local`) | ✅ (one only) | ❌ | +| `NMToken` | Name token (relaxed start) | ✅ | ✅ | +| `NMTokens` | Whitespace-separated NMToken list | ✅ | ✅ | + +Used internally by [fast-xml-parser](https://github.com/NaturalIntelligence/fast-xml-parser), [fast-xml-validator](https://github.com/NaturalIntelligence/fast-xml-validator), [@nodable\flexible-xml-parser](https://github.com/nodable/flexible-xml-parser) and [fast-svg-parser](https://github.com/amitguptagwl/fast-svg-parser). + +--- + +## Install + +```bash +npm install xml-naming +``` + +--- + +## Usage + +### Boolean validators + +```js +import { name, ncName, qName, nmToken, nmTokens } from 'xml-naming'; + +// Name — colon allowed anywhere, used for DOCTYPE entity names +name('foo') // true +name('a:b:c') // true ← multiple colons fine for Name +name('1foo') // false ← digit start invalid + +// NCName — no colon, used for SVG id attributes, namespace prefixes +ncName('my-id') // true +ncName('xlink:href') // false ← colon not allowed + +// QName — exactly one colon as prefix separator, used for element/attribute names +qName('svg:circle') // true +qName('foo') // true ← unprefixed QName is valid +qName('a:b:c') // false ← only one colon allowed +qName(':foo') // false ← cannot start with colon + +// NMToken — any NameChar at start, used for DTD NMTOKEN attributes +nmToken('123') // true ← digit start is fine +nmToken('-bar') // true +nmToken('foo bar') // false ← space not allowed + +// NMTokens — whitespace-separated NMToken list +nmTokens('tok1 tok2 -foo 123') // true +``` + +### XML version option + +All validators accept an optional `{ xmlVersion }` option: + +```js +import { name } from 'xml-naming'; + +name('\u0085', { xmlVersion: '1.0' }) // false — NEL (Next Line), not in 1.0 ranges +name('\u0085', { xmlVersion: '1.1' }) // true — explicitly allowed in 1.1 + +name('\uD800\uDC00', { xmlVersion: '1.0' }) // false +name('\uD800\uDC00', { xmlVersion: '1.1' }) // true +``` + +--- + +### Diagnostic validation + +```js +import { validate } from 'xml-naming'; + +validate('svg:circle', 'qName') +// { valid: true, production: 'qName', input: 'svg:circle' } + +validate('1foo', 'ncName') +// { +// valid: false, +// production: 'ncName', +// input: '1foo', +// reason: 'First character "1" is not a valid NameStartChar', +// position: 0 +// } + +validate('foo:bar', 'ncName') +// { +// valid: false, +// production: 'ncName', +// input: 'foo:bar', +// reason: 'Colon is not allowed in NCName', +// position: 3 +// } + +validate('a:b:c', 'qName') +// { +// valid: false, +// production: 'qName', +// input: 'a:b:c', +// reason: 'QName can have at most one colon', +// position: 3 +// } +``` + +--- + +### Batch validation + +```js +import { validateAll } from 'xml-naming'; + +validateAll(['svg', 'circle', '123bad', 'xlink:href'], 'ncName') +// [ +// { valid: true, production: 'ncName', input: 'svg' }, +// { valid: true, production: 'ncName', input: 'circle' }, +// { valid: false, production: 'ncName', input: '123bad', reason: '...', position: 0 }, +// { valid: false, production: 'ncName', input: 'xlink:href',reason: '...', position: 5 } +// ] +``` + +--- + +### Sanitize / auto-fix + +Useful when generating XML/SVG programmatically from user-supplied strings: + +```js +import { sanitize } from 'xml-naming'; + +sanitize('123abc', 'ncName') // '_123abc' ← digit start fixed +sanitize('my element','name') // 'my_element' ← space replaced +sanitize('foo:bar', 'ncName') // 'foobar' ← colon stripped +sanitize('hello!', 'name') // 'hello_' ← illegal char replaced + +// Custom replacement character +sanitize('my element', 'name', { replacement: '-' }) // 'my-element' +``` + +--- + +## Which production should I use? + +| Context | Production | +|---|---| +| XML element/attribute names (namespace-aware) | `qName` | +| SVG `id` attribute values | `ncName` | +| Namespace prefix alone | `ncName` | +| DOCTYPE `` | `name` | +| DOCTYPE `` | `name` | +| DTD `NMTOKEN` attribute values | `nmToken` | +| DTD `NMTOKENS` attribute values | `nmTokens` | + +> **Note:** DOCTYPE entity and notation names must use `Name`, not `QName`. Colons carry no namespace meaning in the DTD subset. + +--- + +## API + +### `name(str, opts?)` → `boolean` +### `ncName(str, opts?)` → `boolean` +### `qName(str, opts?)` → `boolean` +### `nmToken(str, opts?)` → `boolean` +### `nmTokens(str, opts?)` → `boolean` + +`opts`: +- `xmlVersion`: `'1.0'` (default) | `'1.1'` + +### `validate(str, production, opts?)` → `ValidationResult` + +`production`: `'name'` | `'ncName'` | `'qName'` | `'nmToken'` | `'nmTokens'` + +### `validateAll(strings[], production, opts?)` → `ValidationResult[]` + +### `sanitize(str, production?, opts?)` → `string` + +`opts`: +- `xmlVersion`: `'1.0'` | `'1.1'` +- `replacement`: string (default `'_'`) + +--- + +## License + +MIT \ No newline at end of file diff --git a/node_modules/xml-naming/package.json b/node_modules/xml-naming/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ed43eef838d97955f2c75680410d04f89dd39564 --- /dev/null +++ b/node_modules/xml-naming/package.json @@ -0,0 +1,54 @@ +{ + "name": "xml-naming", + "version": "0.1.0", + "description": "Validates XML name productions — Name, NCName, QName, NMToken, NMTokens — for XML 1.0 and 1.1", + "type": "module", + "main": "./src/index.js", + "types": "./src/index.d.ts", + "exports": { + ".": { + "import": "./src/index.js", + "types": "./src/index.d.ts" + } + }, + "files": [ + "src", + "README.md" + ], + "scripts": { + "test": "jasmine specs/*spec.js" + }, + "keywords": [ + "xml", + "xml-name", + "ncname", + "qname", + "nmtoken", + "xml-validation", + "xml-namespace", + "name-validator", + "xml-1.0", + "xml-1.1" + ], + "author": "Amit Gupta (https://solothought.com)", + "license": "MIT", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "devDependencies": { + "jasmine": "^5.0.0" + }, + "engines": { + "node": ">=16.0.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/NaturalIntelligence/xml-naming" + }, + "bugs": { + "url": "https://github.com/NaturalIntelligence/xml-naming/issues" + } +} \ No newline at end of file diff --git a/node_modules/xml-naming/src/index.d.ts b/node_modules/xml-naming/src/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..29bd913b1e8359000790127f09de31a94af5006b --- /dev/null +++ b/node_modules/xml-naming/src/index.d.ts @@ -0,0 +1,74 @@ +export interface ValidationOptions { + /** XML specification version to validate against. Defaults to '1.0'. */ + xmlVersion?: '1.0' | '1.1'; +} + +export interface SanitizeOptions extends ValidationOptions { + /** Character used to replace invalid characters. Defaults to '_'. */ + replacement?: string; +} + +export type Production = 'name' | 'ncName' | 'qName' | 'nmToken' | 'nmTokens'; + +export interface ValidationResult { + valid: boolean; + production: Production; + input: string; + /** Present only when valid is false. */ + reason?: string; + /** Index of the first offending character. Present only when valid is false. */ + position?: number; +} + +/** + * Returns true if the string is a valid XML Name. + * Colons are permitted anywhere (Name production). + * Used for: DOCTYPE entity names, notation names, DTD element declarations. + */ +export function name(str: string, opts?: ValidationOptions): boolean; + +/** + * Returns true if the string is a valid NCName (Non-Colonized Name). + * Colons are not permitted. + * Used for: namespace prefixes, local names, SVG id attributes. + */ +export function ncName(str: string, opts?: ValidationOptions): boolean; + +/** + * Returns true if the string is a valid QName (Qualified Name). + * Allows exactly one colon as a prefix separator: prefix:localName. + * Used for: element and attribute names in namespace-aware XML/SVG. + */ +export function qName(str: string, opts?: ValidationOptions): boolean; + +/** + * Returns true if the string is a valid NMToken. + * Same character set as Name but no restriction on the first character. + * Used for: DTD NMTOKEN attribute values. + */ +export function nmToken(str: string, opts?: ValidationOptions): boolean; + +/** + * Returns true if the string is a valid NMTokens value. + * A whitespace-separated list of NMToken values. + * Used for: DTD NMTOKENS attribute values. + */ +export function nmTokens(str: string, opts?: ValidationOptions): boolean; + +/** + * Validates a string against a named XML production and returns a detailed result. + */ +export function validate(str: string, production: Production, opts?: ValidationOptions): ValidationResult; + +/** + * Validates an array of strings against a named XML production. + */ +export function validateAll(strings: string[], production: Production, opts?: ValidationOptions): ValidationResult[]; + +/** + * Transforms an invalid string into the nearest valid XML name for the given production. + * - Strips or replaces illegal characters + * - Fixes invalid start characters by prepending the replacement character + * - Removes colons for NCName production + */ +export function sanitize(str: string, production?: Production, opts?: SanitizeOptions): string; \ No newline at end of file diff --git a/node_modules/xml-naming/src/index.js b/node_modules/xml-naming/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..33889c7176d3594300444c8d2c34f46f6b933369 --- /dev/null +++ b/node_modules/xml-naming/src/index.js @@ -0,0 +1,270 @@ +/** + * xml-naming + * Validates XML Name productions as defined in the XML 1.0 and 1.1 specifications. + * Covers: Name, NCName, QName, NMToken, NMTokens + * + * XML 1.0 spec: https://www.w3.org/TR/xml/#NT-Name + * XML 1.1 spec: https://www.w3.org/TR/xml11/#NT-NameStartChar + * XML NS spec: https://www.w3.org/TR/xml-names/#NT-NCName + */ + +// --------------------------------------------------------------------------- +// Character class strings — XML 1.0 +// +// NameStartChar ::= ":" | [A-Z] | "_" | [a-z] +// | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] +// | [#x370-#x37D] | [#x37F-#x1FFF] <- split to exclude #x0487 +// | [#x200C-#x200D] +// | [#x2070-#x218F] | [#x2C00-#x2FEF] +// | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] +// +// NameChar ::= NameStartChar | "-" | "." | [0-9] +// | #xB7 | [#x0300-#x036F] | [#x203F-#x2040] +// +// Note: \u0487 (Combining Cyrillic Millions Sign) was added in Unicode 4.0, +// after XML 1.0 was defined against Unicode 2.0. It falls inside the range +// \u037F-\u1FFF but must be excluded. We split that range into +// \u037F-\u0486 and \u0488-\u1FFF to exclude it explicitly. +// --------------------------------------------------------------------------- + +const nameStartChar10 = + ':A-Za-z_' + + '\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF' + + '\u0370-\u037D' + + '\u037F-\u0486\u0488-\u1FFF' + // split to exclude \u0487 + '\u200C-\u200D' + + '\u2070-\u218F' + + '\u2C00-\u2FEF' + + '\u3001-\uD7FF' + + '\uF900-\uFDCF' + + '\uFDF0-\uFFFD'; + +const nameChar10 = + nameStartChar10 + + '\\-\\.\\d' + + '\u00B7' + + '\u0300-\u036F' + + '\u203F-\u2040'; + +// --------------------------------------------------------------------------- +// Character class strings — XML 1.1 +// +// Differences from XML 1.0: +// +// NameStartChar: +// 1.0 has split ranges: \u00C0-\u00D6, \u00D8-\u00F6, \u00F8-\u02FF +// 1.1 merges them into: \u00C0-\u02FF +// (\u00D7 x and \u00F7 / are division symbols, excluded in both versions) +// +// 1.0 tops out at \uFFFD (BMP only) +// 1.1 adds \u{10000}-\u{EFFFF} (supplementary planes) +// These require the /u flag on the RegExp — see buildRegexes below. +// +// NameChar: +// 1.1 adds \u0487 (Combining Cyrillic Millions Sign, added in Unicode 4.0) +// --------------------------------------------------------------------------- + +const nameStartChar11 = + ':A-Za-z_' + + '\u00C0-\u02FF' + // merged — 1.0 had three split ranges here + '\u0370-\u037D' + + '\u037F-\u0486\u0488-\u1FFF' + // split to exclude \u0487 (combining mark, never a NameStartChar) + '\u200C-\u200D' + + '\u2070-\u218F' + + '\u2C00-\u2FEF' + + '\u3001-\uD7FF' + + '\uF900-\uFDCF' + + '\uFDF0-\uFFFD' + + '\u{10000}-\u{EFFFF}'; // supplementary planes — REQUIRES /u flag on RegExp + +const nameChar11 = + nameStartChar11 + + '\\-\\.\\d' + + '\u00B7' + + '\u0300-\u036F' + + '\u0487' + // Combining Cyrillic Millions Sign — valid in 1.1, not 1.0 + '\u203F-\u2040'; + +// --------------------------------------------------------------------------- +// Regex builders +// +// XML 1.0 regexes: no flags — BMP only, standard JS regex behaviour. +// XML 1.1 regexes: /u flag — required for \u{10000}-\u{EFFFF} to match actual +// supplementary code points rather than lone surrogates (which are illegal XML). +// --------------------------------------------------------------------------- + +const buildRegexes = (startChar, char, flags = '') => { + const ncStart = startChar.replace(':', ''); + const ncChar = char.replace(':', ''); + const ncNamePat = `[${ncStart}][${ncChar}]*`; + + return { + name: new RegExp(`^[${startChar}][${char}]*$`, flags), + ncName: new RegExp(`^${ncNamePat}$`, flags), + qName: new RegExp(`^${ncNamePat}(?::${ncNamePat})?$`, flags), + nmToken: new RegExp(`^[${char}]+$`, flags), + nmTokens: new RegExp(`^[${char}]+(?:\\s+[${char}]+)*$`, flags), + }; +}; + +const regexes10 = buildRegexes(nameStartChar10, nameChar10); // no /u — BMP only +const regexes11 = buildRegexes(nameStartChar11, nameChar11, 'u'); // /u — enables \u{10000}-\u{EFFFF} + +const getRegexes = (xmlVersion = '1.0') => + xmlVersion === '1.1' ? regexes11 : regexes10; + +// --------------------------------------------------------------------------- +// Boolean validators +// --------------------------------------------------------------------------- + +/** + * Returns true if the string is a valid XML Name. + * Colons are allowed anywhere (Name production). + * Used for: DOCTYPE entity names, notation names, DTD element declarations. + */ +export const name = (str, { xmlVersion = '1.0' } = {}) => + getRegexes(xmlVersion).name.test(str); + +/** + * Returns true if the string is a valid NCName (Non-Colonized Name). + * Colons are not permitted. + * Used for: namespace prefixes, local names, SVG id attributes. + */ +export const ncName = (str, { xmlVersion = '1.0' } = {}) => + getRegexes(xmlVersion).ncName.test(str); + +/** + * Returns true if the string is a valid QName (Qualified Name). + * Allows exactly one colon as a prefix separator: prefix:localName. + * Used for: element and attribute names in namespace-aware XML/SVG. + */ +export const qName = (str, { xmlVersion = '1.0' } = {}) => + getRegexes(xmlVersion).qName.test(str); + +/** + * Returns true if the string is a valid NMToken. + * Like Name but no restriction on the first character. + * Used for: DTD NMTOKEN attribute values. + */ +export const nmToken = (str, { xmlVersion = '1.0' } = {}) => + getRegexes(xmlVersion).nmToken.test(str); + +/** + * Returns true if the string is a valid NMTokens value. + * A whitespace-separated list of NMToken values. + * Used for: DTD NMTOKENS attribute values. + */ +export const nmTokens = (str, { xmlVersion = '1.0' } = {}) => + getRegexes(xmlVersion).nmTokens.test(str); + +// --------------------------------------------------------------------------- +// Diagnostic validator +// --------------------------------------------------------------------------- + +const PRODUCTIONS = ['name', 'ncName', 'qName', 'nmToken', 'nmTokens']; + +/** + * Validates a string against a named production and returns a detailed result. + * + * @param {string} str + * @param {'name'|'ncName'|'qName'|'nmToken'|'nmTokens'} production + * @param {{ xmlVersion?: '1.0'|'1.1' }} [opts] + * @returns {{ valid: boolean, production: string, input: string, reason?: string, position?: number }} + */ +export const validate = (str, production, { xmlVersion = '1.0' } = {}) => { + if (!PRODUCTIONS.includes(production)) { + throw new TypeError( + `Unknown production "${production}". Must be one of: ${PRODUCTIONS.join(', ')}` + ); + } + + const validators = { name, ncName, qName, nmToken, nmTokens }; + const isValid = validators[production](str, { xmlVersion }); + + if (isValid) return { valid: true, production, input: str }; + + let reason = 'Does not match the production rules'; + let position; + + if (str.length === 0) { + reason = 'Input is empty'; + } else if (production === 'ncName' && str.includes(':')) { + position = str.indexOf(':'); + reason = 'Colon is not allowed in NCName'; + } else if (production === 'qName' && str.startsWith(':')) { + reason = 'QName cannot start with a colon'; + position = 0; + } else if (production === 'qName' && str.endsWith(':')) { + reason = 'QName cannot end with a colon'; + position = str.length - 1; + } else if (production === 'qName' && (str.match(/:/g) || []).length > 1) { + reason = 'QName can have at most one colon'; + position = str.lastIndexOf(':'); + } else if ( + ['name', 'ncName', 'qName'].includes(production) && + !/^[:A-Za-z_\u00C0-\uFFFD]/.test(str[0]) + ) { + reason = `First character "${str[0]}" is not a valid NameStartChar`; + position = 0; + } else { + for (let i = 0; i < str.length; i++) { + if (!/[\w\-\\.:\u00B7\u00C0-\uFFFD]/.test(str[i])) { + reason = `Character "${str[i]}" at position ${i} is not a valid NameChar`; + position = i; + break; + } + } + } + + return { valid: false, production, input: str, reason, position }; +}; + +// --------------------------------------------------------------------------- +// Batch validator +// --------------------------------------------------------------------------- + +/** + * Validates an array of strings against a named production. + * + * @param {string[]} strings + * @param {'name'|'ncName'|'qName'|'nmToken'|'nmTokens'} production + * @param {{ xmlVersion?: '1.0'|'1.1' }} [opts] + * @returns {Array<{ valid: boolean, production: string, input: string, reason?: string, position?: number }>} + */ +export const validateAll = (strings, production, opts = {}) => + strings.map(str => validate(str, production, opts)); + +// --------------------------------------------------------------------------- +// Sanitizer +// --------------------------------------------------------------------------- + +/** + * Transforms an invalid string into the nearest valid XML name for the given production. + * + * @param {string} str + * @param {'name'|'ncName'|'qName'|'nmToken'|'nmTokens'} production + * @param {{ replacement?: string }} [opts] + * @returns {string} + */ +export const sanitize = (str, production = 'name', { replacement = '_' } = {}) => { + if (!str) return replacement; + + let result = str; + + // Strip colons for NCName + if (production === 'ncName') { + result = result.replace(/:/g, ''); + } + + // Replace illegal characters + result = result.replace(/[^\w\-\.:\u00B7\u00C0-\uFFFD]/g, replacement); + + // Fix invalid start character for Name / NCName / QName + if (production !== 'nmToken' && production !== 'nmTokens') { + if (/^[\-\.\d]/.test(result)) { + result = replacement + result; + } + } + + return result || replacement; +}; \ No newline at end of file diff --git a/node_modules/xml-parse-from-string/LICENSE.md b/node_modules/xml-parse-from-string/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..9b10ce2a896836b7200887e64906c09daf80801f --- /dev/null +++ b/node_modules/xml-parse-from-string/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) +Copyright (c) 2015 Jam3 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE +OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/node_modules/xml-parse-from-string/README.md b/node_modules/xml-parse-from-string/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3fc7f962cae19f4d8664456ccbfda259ce4f2b49 --- /dev/null +++ b/node_modules/xml-parse-from-string/README.md @@ -0,0 +1,35 @@ +# xml-parse-from-string + +[![stable](http://badges.github.io/stability-badges/dist/stable.svg)](http://github.com/badges/stability-badges) + +A light browser wrapper around `DOMParser.parseFromString` for XML, with fallback for IE8 and other browsers. + +- attempts to use DOMParser with `"application/xml"` +- falls back to `ActiveXObject('Microsoft.XMLDOM')` +- then falls back to `createElement` / `innerHTML` + +```js +var parseXML = require('xml-parse-from-string') + +var str = '' +var doc = parseXML(str) +var tag = doc.getElementsByTagName('foobar')[0] + +console.log(tag.getAttribute('id')) // -> "blah" +``` + +Be wary of subtle differences between implementations, such as case-sensitivity in `attribute.nodeName`. + +PRs for Node version welcome. + +## Usage + +[![NPM](https://nodei.co/npm/xml-parse-from-string.png)](https://www.npmjs.com/package/xml-parse-from-string) + +#### `root = parse(str)` + +Parses the string as XML and returns the `root` element as a DOM element, so you can do operations similar to `document.getElementById`, `document.getElementsByTagName`, and so forth. + +## License + +MIT, see [LICENSE.md](http://github.com/Jam3/xml-parse-from-string/blob/master/LICENSE.md) for details. diff --git a/node_modules/xml-parse-from-string/index.js b/node_modules/xml-parse-from-string/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c045afab7c0f1dc3c6b1437d63d172c9f18d8fc5 --- /dev/null +++ b/node_modules/xml-parse-from-string/index.js @@ -0,0 +1,27 @@ +module.exports = (function xmlparser() { + //common browsers + if (typeof self.DOMParser !== 'undefined') { + return function(str) { + var parser = new self.DOMParser() + return parser.parseFromString(str, 'application/xml') + } + } + + //IE8 fallback + if (typeof self.ActiveXObject !== 'undefined' + && new self.ActiveXObject('Microsoft.XMLDOM')) { + return function(str) { + var xmlDoc = new self.ActiveXObject("Microsoft.XMLDOM") + xmlDoc.async = "false" + xmlDoc.loadXML(str) + return xmlDoc + } + } + + //last resort fallback + return function(str) { + var div = document.createElement('div') + div.innerHTML = str + return div + } +})() diff --git a/node_modules/xml-parse-from-string/package.json b/node_modules/xml-parse-from-string/package.json new file mode 100644 index 0000000000000000000000000000000000000000..2f8b61d46fb3e85a70e482684a21d6603959c90d --- /dev/null +++ b/node_modules/xml-parse-from-string/package.json @@ -0,0 +1,45 @@ +{ + "name": "xml-parse-from-string", + "version": "1.0.1", + "description": "DOMParser.parseFromString for XML with IE8 fallback", + "main": "index.js", + "license": "MIT", + "author": { + "name": "Matt DesLauriers", + "email": "dave.des@gmail.com", + "url": "https://github.com/mattdesl" + }, + "dependencies": {}, + "devDependencies": { + "brfs": "^1.4.0", + "browserify": "^9.0.3", + "faucet": "0.0.1", + "tape": "^3.5.0", + "testling": "^1.7.1" + }, + "scripts": { + "test": "browserify test.js -t brfs | testling | faucet" + }, + "keywords": [ + "ie8", + "fallback", + "dom", + "parser", + "DOMParser", + "xml", + "string", + "parse", + "browser", + "browserify", + "webpack", + "activeXObject" + ], + "repository": { + "type": "git", + "url": "git://github.com/Jam3/xml-parse-from-string.git" + }, + "homepage": "https://github.com/Jam3/xml-parse-from-string", + "bugs": { + "url": "https://github.com/Jam3/xml-parse-from-string/issues" + } +} diff --git a/node_modules/xml2js/LICENSE b/node_modules/xml2js/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..e3b4222a66a62c70677b034d409dae137e19032e --- /dev/null +++ b/node_modules/xml2js/LICENSE @@ -0,0 +1,19 @@ +Copyright 2010, 2011, 2012, 2013. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. diff --git a/node_modules/xml2js/README.md b/node_modules/xml2js/README.md new file mode 100644 index 0000000000000000000000000000000000000000..67f2104a51353ec192c1d9a27b5ec51d9aab1cfb --- /dev/null +++ b/node_modules/xml2js/README.md @@ -0,0 +1,507 @@ +node-xml2js +=========== + +Ever had the urge to parse XML? And wanted to access the data in some sane, +easy way? Don't want to compile a C parser, for whatever reason? Then xml2js is +what you're looking for! + +Description +=========== + +Simple XML to JavaScript object converter. It supports bi-directional conversion. +Uses [sax-js](https://github.com/isaacs/sax-js/) and +[xmlbuilder-js](https://github.com/oozcitak/xmlbuilder-js/). + +Note: If you're looking for a full DOM parser, you probably want +[JSDom](https://github.com/tmpvar/jsdom). + +Installation +============ + +Simplest way to install `xml2js` is to use [npm](http://npmjs.org), just `npm +install xml2js` which will download xml2js and all dependencies. + +xml2js is also available via [Bower](http://bower.io/), just `bower install +xml2js` which will download xml2js and all dependencies. + +Usage +===== + +No extensive tutorials required because you are a smart developer! The task of +parsing XML should be an easy one, so let's make it so! Here's some examples. + +Shoot-and-forget usage +---------------------- + +You want to parse XML as simple and easy as possible? It's dangerous to go +alone, take this: + +```javascript +var parseString = require('xml2js').parseString; +var xml = "Hello xml2js!" +parseString(xml, function (err, result) { + console.dir(result); +}); +``` + +Can't get easier than this, right? This works starting with `xml2js` 0.2.3. +With CoffeeScript it looks like this: + +```coffeescript +{parseString} = require 'xml2js' +xml = "Hello xml2js!" +parseString xml, (err, result) -> + console.dir result +``` + +If you need some special options, fear not, `xml2js` supports a number of +options (see below), you can specify these as second argument: + +```javascript +parseString(xml, {trim: true}, function (err, result) { +}); +``` + +Simple as pie usage +------------------- + +That's right, if you have been using xml-simple or a home-grown +wrapper, this was added in 0.1.11 just for you: + +```javascript +var fs = require('fs'), + xml2js = require('xml2js'); + +var parser = new xml2js.Parser(); +fs.readFile(__dirname + '/foo.xml', function(err, data) { + parser.parseString(data, function (err, result) { + console.dir(result); + console.log('Done'); + }); +}); +``` + +Look ma, no event listeners! + +You can also use `xml2js` from +[CoffeeScript](https://github.com/jashkenas/coffeescript), further reducing +the clutter: + +```coffeescript +fs = require 'fs', +xml2js = require 'xml2js' + +parser = new xml2js.Parser() +fs.readFile __dirname + '/foo.xml', (err, data) -> + parser.parseString data, (err, result) -> + console.dir result + console.log 'Done.' +``` + +But what happens if you forget the `new` keyword to create a new `Parser`? In +the middle of a nightly coding session, it might get lost, after all. Worry +not, we got you covered! Starting with 0.2.8 you can also leave it out, in +which case `xml2js` will helpfully add it for you, no bad surprises and +inexplicable bugs! + +Promise usage +------------- + +```javascript +var xml2js = require('xml2js'); +var xml = ''; + +// With parser +var parser = new xml2js.Parser(/* options */); +parser.parseStringPromise(xml).then(function (result) { + console.dir(result); + console.log('Done'); +}) +.catch(function (err) { + // Failed +}); + +// Without parser +xml2js.parseStringPromise(xml /*, options */).then(function (result) { + console.dir(result); + console.log('Done'); +}) +.catch(function (err) { + // Failed +}); +``` + +Parsing multiple files +---------------------- + +If you want to parse multiple files, you have multiple possibilities: + + * You can create one `xml2js.Parser` per file. That's the recommended one + and is promised to always *just work*. + * You can call `reset()` on your parser object. + * You can hope everything goes well anyway. This behaviour is not + guaranteed work always, if ever. Use option #1 if possible. Thanks! + +So you wanna some JSON? +----------------------- + +Just wrap the `result` object in a call to `JSON.stringify` like this +`JSON.stringify(result)`. You get a string containing the JSON representation +of the parsed object that you can feed to JSON-hungry consumers. + +Displaying results +------------------ + +You might wonder why, using `console.dir` or `console.log` the output at some +level is only `[Object]`. Don't worry, this is not because `xml2js` got lazy. +That's because Node uses `util.inspect` to convert the object into strings and +that function stops after `depth=2` which is a bit low for most XML. + +To display the whole deal, you can use `console.log(util.inspect(result, false, +null))`, which displays the whole result. + +So much for that, but what if you use +[eyes](https://github.com/cloudhead/eyes.js) for nice colored output and it +truncates the output with `…`? Don't fear, there's also a solution for that, +you just need to increase the `maxLength` limit by creating a custom inspector +`var inspect = require('eyes').inspector({maxLength: false})` and then you can +easily `inspect(result)`. + +XML builder usage +----------------- + +Since 0.4.0, objects can be also be used to build XML: + +```javascript +var xml2js = require('xml2js'); + +var obj = {name: "Super", Surname: "Man", age: 23}; + +var builder = new xml2js.Builder(); +var xml = builder.buildObject(obj); +``` +will result in: + +```xml + + + Super + Man + 23 + +``` + +At the moment, a one to one bi-directional conversion is guaranteed only for +default configuration, except for `attrkey`, `charkey` and `explicitArray` options +you can redefine to your taste. Writing CDATA is supported via setting the `cdata` +option to `true`. + +To specify attributes: +```javascript +var xml2js = require('xml2js'); + +var obj = {root: {$: {id: "my id"}, _: "my inner text"}}; + +var builder = new xml2js.Builder(); +var xml = builder.buildObject(obj); +``` +will result in: +```xml + +my inner text +``` + +### Adding xmlns attributes + +You can generate XML that declares XML namespace prefix / URI pairs with xmlns attributes. + +Example declaring a default namespace on the root element: + +```javascript +let obj = { + Foo: { + $: { + "xmlns": "http://foo.com" + } + } +}; +``` +Result of `buildObject(obj)`: +```xml + +``` +Example declaring non-default namespaces on non-root elements: +```javascript +let obj = { + 'foo:Foo': { + $: { + 'xmlns:foo': 'http://foo.com' + }, + 'bar:Bar': { + $: { + 'xmlns:bar': 'http://bar.com' + } + } + } +} +``` +Result of `buildObject(obj)`: +```xml + + + +``` + + +Processing attribute, tag names and values +------------------------------------------ + +Since 0.4.1 you can optionally provide the parser with attribute name and tag name processors as well as element value processors (Since 0.4.14, you can also optionally provide the parser with attribute value processors): + +```javascript + +function nameToUpperCase(name){ + return name.toUpperCase(); +} + +//transform all attribute and tag names and values to uppercase +parseString(xml, { + tagNameProcessors: [nameToUpperCase], + attrNameProcessors: [nameToUpperCase], + valueProcessors: [nameToUpperCase], + attrValueProcessors: [nameToUpperCase]}, + function (err, result) { + // processed data +}); +``` + +The `tagNameProcessors` and `attrNameProcessors` options +accept an `Array` of functions with the following signature: + +```javascript +function (name){ + //do something with `name` + return name +} +``` + +The `attrValueProcessors` and `valueProcessors` options +accept an `Array` of functions with the following signature: + +```javascript +function (value, name) { + //`name` will be the node name or attribute name + //do something with `value`, (optionally) dependent on the node/attr name + return value +} +``` + +Some processors are provided out-of-the-box and can be found in `lib/processors.js`: + +- `normalize`: transforms the name to lowercase. +(Automatically used when `options.normalize` is set to `true`) + +- `firstCharLowerCase`: transforms the first character to lower case. +E.g. 'MyTagName' becomes 'myTagName' + +- `stripPrefix`: strips the xml namespace prefix. E.g `` will become 'Bar'. +(N.B.: the `xmlns` prefix is NOT stripped.) + +- `parseNumbers`: parses integer-like strings as integers and float-like strings as floats +E.g. "0" becomes 0 and "15.56" becomes 15.56 + +- `parseBooleans`: parses boolean-like strings to booleans +E.g. "true" becomes true and "False" becomes false + +Options +======= + +Apart from the default settings, there are a number of options that can be +specified for the parser. Options are specified by ``new Parser({optionName: +value})``. Possible options are: + + * `attrkey` (default: `$`): Prefix that is used to access the attributes. + Version 0.1 default was `@`. + * `charkey` (default: `_`): Prefix that is used to access the character + content. Version 0.1 default was `#`. + * `explicitCharkey` (default: `false`) Determines whether or not to use + a `charkey` prefix for elements with no attributes. + * `trim` (default: `false`): Trim the whitespace at the beginning and end of + text nodes. + * `normalizeTags` (default: `false`): Normalize all tag names to lowercase. + * `normalize` (default: `false`): Trim whitespaces inside text nodes. + * `explicitRoot` (default: `true`): Set this if you want to get the root + node in the resulting object. + * `emptyTag` (default: `''`): what will the value of empty nodes be. In case + you want to use an empty object as a default value, it is better to provide a factory + function `() => ({})` instead. Without this function a plain object would + become a shared reference across all occurrences with unwanted behavior. + * `explicitArray` (default: `true`): Always put child nodes in an array if + true; otherwise an array is created only if there is more than one. + * `ignoreAttrs` (default: `false`): Ignore all XML attributes and only create + text nodes. + * `mergeAttrs` (default: `false`): Merge attributes and child elements as + properties of the parent, instead of keying attributes off a child + attribute object. This option is ignored if `ignoreAttrs` is `true`. + * `validator` (default `null`): You can specify a callable that validates + the resulting structure somehow, however you want. See unit tests + for an example. + * `xmlns` (default `false`): Give each element a field usually called '$ns' + (the first character is the same as attrkey) that contains its local name + and namespace URI. + * `explicitChildren` (default `false`): Put child elements to separate + property. Doesn't work with `mergeAttrs = true`. If element has no children + then "children" won't be created. Added in 0.2.5. + * `childkey` (default `$$`): Prefix that is used to access child elements if + `explicitChildren` is set to `true`. Added in 0.2.5. + * `preserveChildrenOrder` (default `false`): Modifies the behavior of + `explicitChildren` so that the value of the "children" property becomes an + ordered array. When this is `true`, every node will also get a `#name` field + whose value will correspond to the XML nodeName, so that you may iterate + the "children" array and still be able to determine node names. The named + (and potentially unordered) properties are also retained in this + configuration at the same level as the ordered "children" array. Added in + 0.4.9. + * `charsAsChildren` (default `false`): Determines whether chars should be + considered children if `explicitChildren` is on. Added in 0.2.5. + * `includeWhiteChars` (default `false`): Determines whether whitespace-only + text nodes should be included. Added in 0.4.17. + * `async` (default `false`): Should the callbacks be async? This *might* be + an incompatible change if your code depends on sync execution of callbacks. + Future versions of `xml2js` might change this default, so the recommendation + is to not depend on sync execution anyway. Added in 0.2.6. + * `strict` (default `true`): Set sax-js to strict or non-strict parsing mode. + Defaults to `true` which is *highly* recommended, since parsing HTML which + is not well-formed XML might yield just about anything. Added in 0.2.7. + * `attrNameProcessors` (default: `null`): Allows the addition of attribute + name processing functions. Accepts an `Array` of functions with following + signature: + ```javascript + function (name){ + //do something with `name` + return name + } + ``` + Added in 0.4.14 + * `attrValueProcessors` (default: `null`): Allows the addition of attribute + value processing functions. Accepts an `Array` of functions with following + signature: + ```javascript + function (value, name){ + //do something with `name` + return name + } + ``` + Added in 0.4.1 + * `tagNameProcessors` (default: `null`): Allows the addition of tag name + processing functions. Accepts an `Array` of functions with following + signature: + ```javascript + function (name){ + //do something with `name` + return name + } + ``` + Added in 0.4.1 + * `valueProcessors` (default: `null`): Allows the addition of element value + processing functions. Accepts an `Array` of functions with following + signature: + ```javascript + function (value, name){ + //do something with `name` + return name + } + ``` + Added in 0.4.6 + +Options for the `Builder` class +------------------------------- +These options are specified by ``new Builder({optionName: value})``. +Possible options are: + + * `attrkey` (default: `$`): Prefix that is used to access the attributes. + Version 0.1 default was `@`. + * `charkey` (default: `_`): Prefix that is used to access the character + content. Version 0.1 default was `#`. + * `rootName` (default `root` or the root key name): root element name to be used in case + `explicitRoot` is `false` or to override the root element name. + * `renderOpts` (default `{ 'pretty': true, 'indent': ' ', 'newline': '\n' }`): + Rendering options for xmlbuilder-js. + * pretty: prettify generated XML + * indent: whitespace for indentation (only when pretty) + * newline: newline char (only when pretty) + * `xmldec` (default `{ 'version': '1.0', 'encoding': 'UTF-8', 'standalone': true }`: + XML declaration attributes. + * `xmldec.version` A version number string, e.g. 1.0 + * `xmldec.encoding` Encoding declaration, e.g. UTF-8 + * `xmldec.standalone` standalone document declaration: true or false + * `doctype` (default `null`): optional DTD. Eg. `{'ext': 'hello.dtd'}` + * `headless` (default: `false`): omit the XML header. Added in 0.4.3. + * `allowSurrogateChars` (default: `false`): allows using characters from the Unicode + surrogate blocks. + * `cdata` (default: `false`): wrap text nodes in `` instead of + escaping when necessary. Does not add `` if it is not required. + Added in 0.4.5. + +`renderOpts`, `xmldec`,`doctype` and `headless` pass through to +[xmlbuilder-js](https://github.com/oozcitak/xmlbuilder-js). + +Updating to new version +======================= + +Version 0.2 changed the default parsing settings, but version 0.1.14 introduced +the default settings for version 0.2, so these settings can be tried before the +migration. + +```javascript +var xml2js = require('xml2js'); +var parser = new xml2js.Parser(xml2js.defaults["0.2"]); +``` + +To get the 0.1 defaults in version 0.2 you can just use +`xml2js.defaults["0.1"]` in the same place. This provides you with enough time +to migrate to the saner way of parsing in `xml2js` 0.2. We try to make the +migration as simple and gentle as possible, but some breakage cannot be +avoided. + +So, what exactly did change and why? In 0.2 we changed some defaults to parse +the XML in a more universal and sane way. So we disabled `normalize` and `trim` +so `xml2js` does not cut out any text content. You can reenable this at will of +course. A more important change is that we return the root tag in the resulting +JavaScript structure via the `explicitRoot` setting, so you need to access the +first element. This is useful for anybody who wants to know what the root node +is and preserves more information. The last major change was to enable +`explicitArray`, so everytime it is possible that one might embed more than one +sub-tag into a tag, xml2js >= 0.2 returns an array even if the array just +includes one element. This is useful when dealing with APIs that return +variable amounts of subtags. + +Running tests, development +========================== + +[![Build Status](https://travis-ci.org/Leonidas-from-XIV/node-xml2js.svg?branch=master)](https://travis-ci.org/Leonidas-from-XIV/node-xml2js) +[![Coverage Status](https://coveralls.io/repos/Leonidas-from-XIV/node-xml2js/badge.svg?branch=)](https://coveralls.io/r/Leonidas-from-XIV/node-xml2js?branch=master) +[![Dependency Status](https://david-dm.org/Leonidas-from-XIV/node-xml2js.svg)](https://david-dm.org/Leonidas-from-XIV/node-xml2js) + +The development requirements are handled by npm, you just need to install them. +We also have a number of unit tests, they can be run using `npm test` directly +from the project root. This runs zap to discover all the tests and execute +them. + +If you like to contribute, keep in mind that `xml2js` is written in +CoffeeScript, so don't develop on the JavaScript files that are checked into +the repository for convenience reasons. Also, please write some unit test to +check your behaviour and if it is some user-facing thing, add some +documentation to this README, so people will know it exists. Thanks in advance! + +Getting support +=============== + +Please, if you have a problem with the library, first make sure you read this +README. If you read this far, thanks, you're good. Then, please make sure your +problem really is with `xml2js`. It is? Okay, then I'll look at it. Send me a +mail and we can talk. Please don't open issues, as I don't think that is the +proper forum for support problems. Some problems might as well really be bugs +in `xml2js`, if so I'll let you know to open an issue instead :) + +But if you know you really found a bug, feel free to open an issue instead. diff --git a/node_modules/xml2js/lib/bom.js b/node_modules/xml2js/lib/bom.js new file mode 100644 index 0000000000000000000000000000000000000000..7b8fb27b11817be1ee104b6f73faf7131d9037e0 --- /dev/null +++ b/node_modules/xml2js/lib/bom.js @@ -0,0 +1,12 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + "use strict"; + exports.stripBOM = function(str) { + if (str[0] === '\uFEFF') { + return str.substring(1); + } else { + return str; + } + }; + +}).call(this); diff --git a/node_modules/xml2js/lib/builder.js b/node_modules/xml2js/lib/builder.js new file mode 100644 index 0000000000000000000000000000000000000000..58f36384891ff1b4362e404863b31dc6c4a4923d --- /dev/null +++ b/node_modules/xml2js/lib/builder.js @@ -0,0 +1,127 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + "use strict"; + var builder, defaults, escapeCDATA, requiresCDATA, wrapCDATA, + hasProp = {}.hasOwnProperty; + + builder = require('xmlbuilder'); + + defaults = require('./defaults').defaults; + + requiresCDATA = function(entry) { + return typeof entry === "string" && (entry.indexOf('&') >= 0 || entry.indexOf('>') >= 0 || entry.indexOf('<') >= 0); + }; + + wrapCDATA = function(entry) { + return ""; + }; + + escapeCDATA = function(entry) { + return entry.replace(']]>', ']]]]>'); + }; + + exports.Builder = (function() { + function Builder(opts) { + var key, ref, value; + this.options = {}; + ref = defaults["0.2"]; + for (key in ref) { + if (!hasProp.call(ref, key)) continue; + value = ref[key]; + this.options[key] = value; + } + for (key in opts) { + if (!hasProp.call(opts, key)) continue; + value = opts[key]; + this.options[key] = value; + } + } + + Builder.prototype.buildObject = function(rootObj) { + var attrkey, charkey, render, rootElement, rootName; + attrkey = this.options.attrkey; + charkey = this.options.charkey; + if ((Object.keys(rootObj).length === 1) && (this.options.rootName === defaults['0.2'].rootName)) { + rootName = Object.keys(rootObj)[0]; + rootObj = rootObj[rootName]; + } else { + rootName = this.options.rootName; + } + render = (function(_this) { + return function(element, obj) { + var attr, child, entry, index, key, value; + if (typeof obj !== 'object') { + if (_this.options.cdata && requiresCDATA(obj)) { + element.raw(wrapCDATA(obj)); + } else { + element.txt(obj); + } + } else if (Array.isArray(obj)) { + for (index in obj) { + if (!hasProp.call(obj, index)) continue; + child = obj[index]; + for (key in child) { + entry = child[key]; + element = render(element.ele(key), entry).up(); + } + } + } else { + for (key in obj) { + if (!hasProp.call(obj, key)) continue; + child = obj[key]; + if (key === attrkey) { + if (typeof child === "object") { + for (attr in child) { + value = child[attr]; + element = element.att(attr, value); + } + } + } else if (key === charkey) { + if (_this.options.cdata && requiresCDATA(child)) { + element = element.raw(wrapCDATA(child)); + } else { + element = element.txt(child); + } + } else if (Array.isArray(child)) { + for (index in child) { + if (!hasProp.call(child, index)) continue; + entry = child[index]; + if (typeof entry === 'string') { + if (_this.options.cdata && requiresCDATA(entry)) { + element = element.ele(key).raw(wrapCDATA(entry)).up(); + } else { + element = element.ele(key, entry).up(); + } + } else { + element = render(element.ele(key), entry).up(); + } + } + } else if (typeof child === "object") { + element = render(element.ele(key), child).up(); + } else { + if (typeof child === 'string' && _this.options.cdata && requiresCDATA(child)) { + element = element.ele(key).raw(wrapCDATA(child)).up(); + } else { + if (child == null) { + child = ''; + } + element = element.ele(key, child.toString()).up(); + } + } + } + } + return element; + }; + })(this); + rootElement = builder.create(rootName, this.options.xmldec, this.options.doctype, { + headless: this.options.headless, + allowSurrogateChars: this.options.allowSurrogateChars + }); + return render(rootElement, rootObj).end(this.options.renderOpts); + }; + + return Builder; + + })(); + +}).call(this); diff --git a/node_modules/xml2js/lib/defaults.js b/node_modules/xml2js/lib/defaults.js new file mode 100644 index 0000000000000000000000000000000000000000..0a21da0a2fc3572c7768b897c63dbcfb3f799b6c --- /dev/null +++ b/node_modules/xml2js/lib/defaults.js @@ -0,0 +1,72 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + exports.defaults = { + "0.1": { + explicitCharkey: false, + trim: true, + normalize: true, + normalizeTags: false, + attrkey: "@", + charkey: "#", + explicitArray: false, + ignoreAttrs: false, + mergeAttrs: false, + explicitRoot: false, + validator: null, + xmlns: false, + explicitChildren: false, + childkey: '@@', + charsAsChildren: false, + includeWhiteChars: false, + async: false, + strict: true, + attrNameProcessors: null, + attrValueProcessors: null, + tagNameProcessors: null, + valueProcessors: null, + emptyTag: '' + }, + "0.2": { + explicitCharkey: false, + trim: false, + normalize: false, + normalizeTags: false, + attrkey: "$", + charkey: "_", + explicitArray: true, + ignoreAttrs: false, + mergeAttrs: false, + explicitRoot: true, + validator: null, + xmlns: false, + explicitChildren: false, + preserveChildrenOrder: false, + childkey: '$$', + charsAsChildren: false, + includeWhiteChars: false, + async: false, + strict: true, + attrNameProcessors: null, + attrValueProcessors: null, + tagNameProcessors: null, + valueProcessors: null, + rootName: 'root', + xmldec: { + 'version': '1.0', + 'encoding': 'UTF-8', + 'standalone': true + }, + doctype: null, + renderOpts: { + 'pretty': true, + 'indent': ' ', + 'newline': '\n' + }, + headless: false, + chunkSize: 10000, + emptyTag: '', + cdata: false + } + }; + +}).call(this); diff --git a/node_modules/xml2js/lib/parser.js b/node_modules/xml2js/lib/parser.js new file mode 100644 index 0000000000000000000000000000000000000000..192382d3c461c8b61e56e1e0363fb893fe937449 --- /dev/null +++ b/node_modules/xml2js/lib/parser.js @@ -0,0 +1,385 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + "use strict"; + var bom, defaults, events, isEmpty, processItem, processors, sax, setImmediate, + bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + sax = require('sax'); + + events = require('events'); + + bom = require('./bom'); + + processors = require('./processors'); + + setImmediate = require('timers').setImmediate; + + defaults = require('./defaults').defaults; + + isEmpty = function(thing) { + return typeof thing === "object" && (thing != null) && Object.keys(thing).length === 0; + }; + + processItem = function(processors, item, key) { + var i, len, process; + for (i = 0, len = processors.length; i < len; i++) { + process = processors[i]; + item = process(item, key); + } + return item; + }; + + exports.Parser = (function(superClass) { + extend(Parser, superClass); + + function Parser(opts) { + this.parseStringPromise = bind(this.parseStringPromise, this); + this.parseString = bind(this.parseString, this); + this.reset = bind(this.reset, this); + this.assignOrPush = bind(this.assignOrPush, this); + this.processAsync = bind(this.processAsync, this); + var key, ref, value; + if (!(this instanceof exports.Parser)) { + return new exports.Parser(opts); + } + this.options = {}; + ref = defaults["0.2"]; + for (key in ref) { + if (!hasProp.call(ref, key)) continue; + value = ref[key]; + this.options[key] = value; + } + for (key in opts) { + if (!hasProp.call(opts, key)) continue; + value = opts[key]; + this.options[key] = value; + } + if (this.options.xmlns) { + this.options.xmlnskey = this.options.attrkey + "ns"; + } + if (this.options.normalizeTags) { + if (!this.options.tagNameProcessors) { + this.options.tagNameProcessors = []; + } + this.options.tagNameProcessors.unshift(processors.normalize); + } + this.reset(); + } + + Parser.prototype.processAsync = function() { + var chunk, err; + try { + if (this.remaining.length <= this.options.chunkSize) { + chunk = this.remaining; + this.remaining = ''; + this.saxParser = this.saxParser.write(chunk); + return this.saxParser.close(); + } else { + chunk = this.remaining.substr(0, this.options.chunkSize); + this.remaining = this.remaining.substr(this.options.chunkSize, this.remaining.length); + this.saxParser = this.saxParser.write(chunk); + return setImmediate(this.processAsync); + } + } catch (error1) { + err = error1; + if (!this.saxParser.errThrown) { + this.saxParser.errThrown = true; + return this.emit(err); + } + } + }; + + Parser.prototype.assignOrPush = function(obj, key, newValue) { + if (!(key in obj)) { + if (!this.options.explicitArray) { + return obj[key] = newValue; + } else { + return obj[key] = [newValue]; + } + } else { + if (!(obj[key] instanceof Array)) { + obj[key] = [obj[key]]; + } + return obj[key].push(newValue); + } + }; + + Parser.prototype.reset = function() { + var attrkey, charkey, ontext, stack; + this.removeAllListeners(); + this.saxParser = sax.parser(this.options.strict, { + trim: false, + normalize: false, + xmlns: this.options.xmlns + }); + this.saxParser.errThrown = false; + this.saxParser.onerror = (function(_this) { + return function(error) { + _this.saxParser.resume(); + if (!_this.saxParser.errThrown) { + _this.saxParser.errThrown = true; + return _this.emit("error", error); + } + }; + })(this); + this.saxParser.onend = (function(_this) { + return function() { + if (!_this.saxParser.ended) { + _this.saxParser.ended = true; + return _this.emit("end", _this.resultObject); + } + }; + })(this); + this.saxParser.ended = false; + this.EXPLICIT_CHARKEY = this.options.explicitCharkey; + this.resultObject = null; + stack = []; + attrkey = this.options.attrkey; + charkey = this.options.charkey; + this.saxParser.onopentag = (function(_this) { + return function(node) { + var key, newValue, obj, processedKey, ref; + obj = Object.create(null); + obj[charkey] = ""; + if (!_this.options.ignoreAttrs) { + ref = node.attributes; + for (key in ref) { + if (!hasProp.call(ref, key)) continue; + if (!(attrkey in obj) && !_this.options.mergeAttrs) { + obj[attrkey] = Object.create(null); + } + newValue = _this.options.attrValueProcessors ? processItem(_this.options.attrValueProcessors, node.attributes[key], key) : node.attributes[key]; + processedKey = _this.options.attrNameProcessors ? processItem(_this.options.attrNameProcessors, key) : key; + if (_this.options.mergeAttrs) { + _this.assignOrPush(obj, processedKey, newValue); + } else { + obj[attrkey][processedKey] = newValue; + } + } + } + obj["#name"] = _this.options.tagNameProcessors ? processItem(_this.options.tagNameProcessors, node.name) : node.name; + if (_this.options.xmlns) { + obj[_this.options.xmlnskey] = { + uri: node.uri, + local: node.local + }; + } + return stack.push(obj); + }; + })(this); + this.saxParser.onclosetag = (function(_this) { + return function() { + var cdata, emptyStr, key, node, nodeName, obj, objClone, old, s, xpath; + obj = stack.pop(); + nodeName = obj["#name"]; + if (!_this.options.explicitChildren || !_this.options.preserveChildrenOrder) { + delete obj["#name"]; + } + if (obj.cdata === true) { + cdata = obj.cdata; + delete obj.cdata; + } + s = stack[stack.length - 1]; + if (obj[charkey].match(/^\s*$/) && !cdata) { + emptyStr = obj[charkey]; + delete obj[charkey]; + } else { + if (_this.options.trim) { + obj[charkey] = obj[charkey].trim(); + } + if (_this.options.normalize) { + obj[charkey] = obj[charkey].replace(/\s{2,}/g, " ").trim(); + } + obj[charkey] = _this.options.valueProcessors ? processItem(_this.options.valueProcessors, obj[charkey], nodeName) : obj[charkey]; + if (Object.keys(obj).length === 1 && charkey in obj && !_this.EXPLICIT_CHARKEY) { + obj = obj[charkey]; + } + } + if (isEmpty(obj)) { + if (typeof _this.options.emptyTag === 'function') { + obj = _this.options.emptyTag(); + } else { + obj = _this.options.emptyTag !== '' ? _this.options.emptyTag : emptyStr; + } + } + if (_this.options.validator != null) { + xpath = "/" + ((function() { + var i, len, results; + results = []; + for (i = 0, len = stack.length; i < len; i++) { + node = stack[i]; + results.push(node["#name"]); + } + return results; + })()).concat(nodeName).join("/"); + (function() { + var err; + try { + return obj = _this.options.validator(xpath, s && s[nodeName], obj); + } catch (error1) { + err = error1; + return _this.emit("error", err); + } + })(); + } + if (_this.options.explicitChildren && !_this.options.mergeAttrs && typeof obj === 'object') { + if (!_this.options.preserveChildrenOrder) { + node = Object.create(null); + if (_this.options.attrkey in obj) { + node[_this.options.attrkey] = obj[_this.options.attrkey]; + delete obj[_this.options.attrkey]; + } + if (!_this.options.charsAsChildren && _this.options.charkey in obj) { + node[_this.options.charkey] = obj[_this.options.charkey]; + delete obj[_this.options.charkey]; + } + if (Object.getOwnPropertyNames(obj).length > 0) { + node[_this.options.childkey] = obj; + } + obj = node; + } else if (s) { + s[_this.options.childkey] = s[_this.options.childkey] || []; + objClone = Object.create(null); + for (key in obj) { + if (!hasProp.call(obj, key)) continue; + objClone[key] = obj[key]; + } + s[_this.options.childkey].push(objClone); + delete obj["#name"]; + if (Object.keys(obj).length === 1 && charkey in obj && !_this.EXPLICIT_CHARKEY) { + obj = obj[charkey]; + } + } + } + if (stack.length > 0) { + return _this.assignOrPush(s, nodeName, obj); + } else { + if (_this.options.explicitRoot) { + old = obj; + obj = Object.create(null); + obj[nodeName] = old; + } + _this.resultObject = obj; + _this.saxParser.ended = true; + return _this.emit("end", _this.resultObject); + } + }; + })(this); + ontext = (function(_this) { + return function(text) { + var charChild, s; + s = stack[stack.length - 1]; + if (s) { + s[charkey] += text; + if (_this.options.explicitChildren && _this.options.preserveChildrenOrder && _this.options.charsAsChildren && (_this.options.includeWhiteChars || text.replace(/\\n/g, '').trim() !== '')) { + s[_this.options.childkey] = s[_this.options.childkey] || []; + charChild = { + '#name': '__text__' + }; + charChild[charkey] = text; + if (_this.options.normalize) { + charChild[charkey] = charChild[charkey].replace(/\s{2,}/g, " ").trim(); + } + s[_this.options.childkey].push(charChild); + } + return s; + } + }; + })(this); + this.saxParser.ontext = ontext; + return this.saxParser.oncdata = (function(_this) { + return function(text) { + var s; + s = ontext(text); + if (s) { + return s.cdata = true; + } + }; + })(this); + }; + + Parser.prototype.parseString = function(str, cb) { + var err; + if ((cb != null) && typeof cb === "function") { + this.on("end", function(result) { + this.reset(); + return cb(null, result); + }); + this.on("error", function(err) { + this.reset(); + return cb(err); + }); + } + try { + str = str.toString(); + if (str.trim() === '') { + this.emit("end", null); + return true; + } + str = bom.stripBOM(str); + if (this.options.async) { + this.remaining = str; + setImmediate(this.processAsync); + return this.saxParser; + } + return this.saxParser.write(str).close(); + } catch (error1) { + err = error1; + if (!(this.saxParser.errThrown || this.saxParser.ended)) { + this.emit('error', err); + return this.saxParser.errThrown = true; + } else if (this.saxParser.ended) { + throw err; + } + } + }; + + Parser.prototype.parseStringPromise = function(str) { + return new Promise((function(_this) { + return function(resolve, reject) { + return _this.parseString(str, function(err, value) { + if (err) { + return reject(err); + } else { + return resolve(value); + } + }); + }; + })(this)); + }; + + return Parser; + + })(events); + + exports.parseString = function(str, a, b) { + var cb, options, parser; + if (b != null) { + if (typeof b === 'function') { + cb = b; + } + if (typeof a === 'object') { + options = a; + } + } else { + if (typeof a === 'function') { + cb = a; + } + options = {}; + } + parser = new exports.Parser(options); + return parser.parseString(str, cb); + }; + + exports.parseStringPromise = function(str, a) { + var options, parser; + if (typeof a === 'object') { + options = a; + } + parser = new exports.Parser(options); + return parser.parseStringPromise(str); + }; + +}).call(this); diff --git a/node_modules/xml2js/lib/processors.js b/node_modules/xml2js/lib/processors.js new file mode 100644 index 0000000000000000000000000000000000000000..89aa85f22cfecd621fd7ac737235bddc9a765ca8 --- /dev/null +++ b/node_modules/xml2js/lib/processors.js @@ -0,0 +1,34 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + "use strict"; + var prefixMatch; + + prefixMatch = new RegExp(/(?!xmlns)^.*:/); + + exports.normalize = function(str) { + return str.toLowerCase(); + }; + + exports.firstCharLowerCase = function(str) { + return str.charAt(0).toLowerCase() + str.slice(1); + }; + + exports.stripPrefix = function(str) { + return str.replace(prefixMatch, ''); + }; + + exports.parseNumbers = function(str) { + if (!isNaN(str)) { + str = str % 1 === 0 ? parseInt(str, 10) : parseFloat(str); + } + return str; + }; + + exports.parseBooleans = function(str) { + if (/^(?:true|false)$/i.test(str)) { + str = str.toLowerCase() === 'true'; + } + return str; + }; + +}).call(this); diff --git a/node_modules/xml2js/lib/xml2js.js b/node_modules/xml2js/lib/xml2js.js new file mode 100644 index 0000000000000000000000000000000000000000..24b6e699ddcab4c7e8fdd91bfff43f51d1c559b0 --- /dev/null +++ b/node_modules/xml2js/lib/xml2js.js @@ -0,0 +1,39 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + "use strict"; + var builder, defaults, parser, processors, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + defaults = require('./defaults'); + + builder = require('./builder'); + + parser = require('./parser'); + + processors = require('./processors'); + + exports.defaults = defaults.defaults; + + exports.processors = processors; + + exports.ValidationError = (function(superClass) { + extend(ValidationError, superClass); + + function ValidationError(message) { + this.message = message; + } + + return ValidationError; + + })(Error); + + exports.Builder = builder.Builder; + + exports.Parser = parser.Parser; + + exports.parseString = parser.parseString; + + exports.parseStringPromise = parser.parseStringPromise; + +}).call(this); diff --git a/node_modules/xml2js/package.json b/node_modules/xml2js/package.json new file mode 100644 index 0000000000000000000000000000000000000000..bc8eb6639fe2c021f8c2d458b44afb3fac3ff1d6 --- /dev/null +++ b/node_modules/xml2js/package.json @@ -0,0 +1,93 @@ +{ + "name": "xml2js", + "description": "Simple XML to JavaScript object converter.", + "keywords": [ + "xml", + "json" + ], + "homepage": "https://github.com/Leonidas-from-XIV/node-xml2js", + "version": "0.5.0", + "author": "Marek Kubica (https://xivilization.net)", + "contributors": [ + "maqr (https://github.com/maqr)", + "Ben Weaver (http://benweaver.com/)", + "Jae Kwon (https://github.com/jaekwon)", + "Jim Robert", + "Ștefan Rusu (http://www.saltwaterc.eu/)", + "Carter Cole (http://cartercole.com/)", + "Kurt Raschke (http://www.kurtraschke.com/)", + "Contra (https://github.com/Contra)", + "Marcelo Diniz (https://github.com/mdiniz)", + "Michael Hart (https://github.com/mhart)", + "Zachary Scott (http://zacharyscott.net/)", + "Raoul Millais (https://github.com/raoulmillais)", + "Salsita Software (http://www.salsitasoft.com/)", + "Mike Schilling (http://www.emotive.com/)", + "Jackson Tian (http://weibo.com/shyvo)", + "Mikhail Zyatin (https://github.com/Sitin)", + "Chris Tavares (https://github.com/christav)", + "Frank Xu (http://f2e.us/)", + "Guido D'Albore (http://www.bitstorm.it/)", + "Jack Senechal (http://jacksenechal.com/)", + "Matthias Hölzl (https://github.com/hoelzl)", + "Camille Reynders (http://www.creynders.be/)", + "Taylor Gautier (https://github.com/tsgautier)", + "Todd Bryan (https://github.com/toddrbryan)", + "Leore Avidar (http://leoreavidar.com/)", + "Dave Aitken (http://www.actionshrimp.com/)", + "Shaney Orrowe ", + "Candle ", + "Jess Telford (http://jes.st)", + "Tom Hughes < (http://compton.nu/)", + "Piotr Rochala (http://rocha.la/)", + "Michael Avila (https://github.com/michaelavila)", + "Ryan Gahl (https://github.com/ryedin)", + "Eric Laberge (https://github.com/elaberge)", + "Benjamin E. Coe (https://twitter.com/benjamincoe)", + "Stephen Cresswell (https://github.com/cressie176)", + "Pascal Ehlert (http://www.hacksrus.net/)", + "Tom Spencer (http://fiznool.com/)", + "Tristian Flanagan (https://github.com/tflanagan)", + "Tim Johns (https://github.com/TimJohns)", + "Bogdan Chadkin (https://github.com/TrySound)", + "David Wood (http://codesleuth.co.uk/)", + "Nicolas Maquet (https://github.com/nmaquet)", + "Lovell Fuller (http://lovell.info/)", + "d3adc0d3 (https://github.com/d3adc0d3)", + "James Crosby (https://github.com/autopulated)" + ], + "main": "./lib/xml2js", + "files": [ + "lib" + ], + "directories": { + "lib": "./lib" + }, + "scripts": { + "build": "cake build", + "test": "zap", + "coverage": "nyc npm test && nyc report", + "coveralls": "nyc npm test && nyc report --reporter=text-lcov | coveralls", + "doc": "cake doc" + }, + "repository": { + "type": "git", + "url": "https://github.com/Leonidas-from-XIV/node-xml2js.git" + }, + "dependencies": { + "sax": ">=0.6.0", + "xmlbuilder": "~11.0.0" + }, + "devDependencies": { + "coffee-script": ">=1.10.0", + "coveralls": "^3.0.1", + "diff": ">=1.0.8", + "docco": ">=0.6.2", + "nyc": ">=2.2.1", + "zap": ">=0.2.9" + }, + "engines": { + "node": ">=4.0.0" + }, + "license": "MIT" +} diff --git a/node_modules/xmlbuilder/CHANGELOG.md b/node_modules/xmlbuilder/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..610f412e225e1d0b011051fc5a0b3b96bfd50fe2 --- /dev/null +++ b/node_modules/xmlbuilder/CHANGELOG.md @@ -0,0 +1,470 @@ +# Change Log + +All notable changes to this project are documented in this file. This project adheres to [Semantic Versioning](http://semver.org/#semantic-versioning-200). + +## [11.0.0] - 2019-02-18 +- Calling `end()` with arguments no longer overwrites writer options. See [#120](https://github.com/oozcitak/xmlbuilder-js/issues/120). +- Added writer state and customizable space and endline functions to help customize writer behavior. Also added `openNode` and `closeNode` functions to writer. See [#193](https://github.com/oozcitak/xmlbuilder-js/issues/193). +- Fixed a bug where writer functions would not be called for nodes with a single child node in pretty print mode. See [#195](https://github.com/oozcitak/xmlbuilder-js/issues/195). +- Renamed `elEscape` to `textEscape` in `XMLStringifier`. +- Fixed a bug where empty arrays would produce child nodes. See [#190](https://github.com/oozcitak/xmlbuilder-js/issues/190). +- Removed the `skipNullAttributes` option. `null` attributes are now skipped by default. Added the `keepNullAttributes` option in case someone needs the old behavior. +- Removed the `skipNullNodes` option. `null` nodes are now skipped by default. Added the `keepNullNodes` option in case someone needs the old behavior. +- `undefined` values are now skipped when converting JS objects. +- Renamed stringify functions. See [#194](https://github.com/oozcitak/xmlbuilder-js/issues/194): + * `eleName` -> `name` + * `attName` -> `name` + * `eleText` -> `text` +- Fixed argument order for `attribute` function in the writer. See [#196](https://github.com/oozcitak/xmlbuilder-js/issues/196). +- Added `openAttribute` and `closeAttribute` functions to writer. See [#196](https://github.com/oozcitak/xmlbuilder-js/issues/196). +- Added node types to node objects. Node types and writer states are exported by the module with the `nodeType` and `writerState` properties. +- Fixed a bug where array items would not be correctly converted. See [#159](https://github.com/oozcitak/xmlbuilder-js/issues/159). +- Fixed a bug where mixed-content inside JS objects with `#text` decorator would not be correctly converted. See [#171](https://github.com/oozcitak/xmlbuilder-js/issues/171). +- Fixed a bug where JS objects would not be expanded in callback mode. See [#173](https://github.com/oozcitak/xmlbuilder-js/issues/173). +- Fixed a bug where character validation would not obey document's XML version. Added separate validation for XML 1.0 and XML 1.1 documents. See [#169](https://github.com/oozcitak/xmlbuilder-js/issues/169). +- Fixed a bug where names would not be validated according to the spec. See [#49](https://github.com/oozcitak/xmlbuilder-js/issues/49). +- Renamed `text` property to `value` in comment and cdata nodes to unify the API. +- Removed `doctype` function to prevent name clash with DOM implementation. Use the `dtd` function instead. +- Removed dummy nodes from the XML tree (Those were created while chain-building the tree). +- Renamed `attributes`property to `attribs` to prevent name clash with DOM property with the same name. +- Implemented the DOM standard (read-only) to support XPath lookups. XML namespaces are not currently supported. See [#122](https://github.com/oozcitak/xmlbuilder-js/issues/122). + +## [10.1.1] - 2018-10-24 +- Fixed an edge case where a null node at root level would be printed although `skipNullNodes` was set. See [#187](https://github.com/oozcitak/xmlbuilder-js/issues/187). + +## [10.1.0] - 2018-10-10 +- Added the `skipNullNodes` option to skip nodes with null values. See [#158](https://github.com/oozcitak/xmlbuilder-js/issues/158). + +## [10.0.0] - 2018-04-26 +- Added current indentation level as a parameter to the onData function when in callback mode. See [#125](https://github.com/oozcitak/xmlbuilder-js/issues/125). +- Added name of the current node and parent node to error messages where possible. See [#152](https://github.com/oozcitak/xmlbuilder-js/issues/152). This has the potential to break code depending on the content of error messages. +- Fixed an issue where objects created with Object.create(null) created an error. See [#176](https://github.com/oozcitak/xmlbuilder-js/issues/176). +- Added test builds for node.js v8 and v10. + +## [9.0.7] - 2018-02-09 +- Simplified regex used for validating encoding. + +## [9.0.4] - 2017-08-16 +- `spacebeforeslash` writer option accepts `true` as well as space char(s). + +## [9.0.3] - 2017-08-15 +- `spacebeforeslash` writer option can now be used with XML fragments. + +## [9.0.2] - 2017-08-15 +- Added the `spacebeforeslash` writer option to add a space character before closing tags of empty elements. See +[#157](https://github.com/oozcitak/xmlbuilder-js/issues/157). + +## [9.0.1] - 2017-06-19 +- Fixed character validity checks to work with node.js 4.0 and 5.0. See +[#161](https://github.com/oozcitak/xmlbuilder-js/issues/161). + +## [9.0.0] - 2017-05-05 +- Removed case conversion options. +- Removed support for node.js 4.0 and 5.0. Minimum required version is now 6.0. +- Fixed valid char filter to use XML 1.1 instead of 1.0. See +[#147](https://github.com/oozcitak/xmlbuilder-js/issues/147). +- Added options for negative indentation and suppressing pretty printing of text +nodes. See +[#145](https://github.com/oozcitak/xmlbuilder-js/issues/145). + +## [8.2.2] - 2016-04-08 +- Falsy values can now be used as a text node in callback mode. + +## [8.2.1] - 2016-04-07 +- Falsy values can now be used as a text node. See +[#117](https://github.com/oozcitak/xmlbuilder-js/issues/117). + +## [8.2.0] - 2016-04-01 +- Removed lodash dependency to keep the library small and simple. See +[#114](https://github.com/oozcitak/xmlbuilder-js/issues/114), +[#53](https://github.com/oozcitak/xmlbuilder-js/issues/53), +and [#43](https://github.com/oozcitak/xmlbuilder-js/issues/43). +- Added title case to name conversion options. + +## [8.1.0] - 2016-03-29 +- Added the callback option to the `begin` export function. When used with a +callback function, the XML document will be generated in chunks and each chunk +will be passed to the supplied function. In this mode, `begin` uses a different +code path and the builder should use much less memory since the entire XML tree +is not kept. There are a few drawbacks though. For example, traversing the document +tree or adding attributes to a node after it is written is not possible. It is +also not possible to remove nodes or attributes. + +``` js +var result = ''; + +builder.begin(function(chunk) { result += chunk; }) + .dec() + .ele('root') + .ele('xmlbuilder').up() + .end(); +``` + +- Replaced native `Object.assign` with `lodash.assign` to support old JS engines. See [#111](https://github.com/oozcitak/xmlbuilder-js/issues/111). + +## [8.0.0] - 2016-03-25 +- Added the `begin` export function. See the wiki for details. +- Added the ability to add comments and processing instructions before and after the root element. Added `commentBefore`, `commentAfter`, `instructionBefore` and `instructionAfter` functions for this purpose. +- Dropped support for old node.js releases. Minimum required node.js version is now 4.0. + +## [7.0.0] - 2016-03-21 +- Processing instructions are now created as regular nodes. This is a major breaking change if you are using processing instructions. Previously processing instructions were inserted before their parent node. After this change processing instructions are appended to the children of the parent node. Note that it is not currently possible to insert processing instructions before or after the root element. +```js +root.ele('node').ins('pi'); +// pre-v7 + +// v7 + +``` + +## [6.0.0] - 2016-03-20 +- Added custom XML writers. The default string conversion functions are now collected under the `XMLStringWriter` class which can be accessed by the `stringWriter(options)` function exported by the module. An `XMLStreamWriter` is also added which outputs the XML document to a writable stream. A stream writer can be created by calling the `streamWriter(stream, options)` function exported by the module. Both classes are heavily customizable and the details are added to the wiki. It is also possible to write an XML writer from scratch and use it when calling `end()` on the XML document. + +## [5.0.1] - 2016-03-08 +- Moved require statements for text case conversion to the top of files to reduce lazy requires. + +## [5.0.0] - 2016-03-05 +- Added text case option for element names and attribute names. Valid cases are `lower`, `upper`, `camel`, `kebab` and `snake`. +- Attribute and element values are escaped according to the [Canonical XML 1.0 specification](http://www.w3.org/TR/2000/WD-xml-c14n-20000119.html#charescaping). See [#54](https://github.com/oozcitak/xmlbuilder-js/issues/54) and [#86](https://github.com/oozcitak/xmlbuilder-js/issues/86). +- Added the `allowEmpty` option to `end()`. When this option is set, empty elements are not self-closed. +- Added support for [nested CDATA](https://en.wikipedia.org/wiki/CDATA#Nesting). The triad `]]>` in CDATA is now automatically replaced with `]]]]>`. + +## [4.2.1] - 2016-01-15 +- Updated lodash dependency to 4.0.0. + +## [4.2.0] - 2015-12-16 +- Added the `noDoubleEncoding` option to `create()` to control whether existing html entities are encoded. + +## [4.1.0] - 2015-11-11 +- Added the `separateArrayItems` option to `create()` to control how arrays are handled when converting from objects. e.g. + +```js +root.ele({ number: [ "one", "two" ]}); +// with separateArrayItems: true + + + + +// with separateArrayItems: false +one +two +``` + +## [4.0.0] - 2015-11-01 +- Removed the `#list` decorator. Array items are now created as child nodes by default. +- Fixed a bug where the XML encoding string was checked partially. + +## [3.1.0] - 2015-09-19 +- `#list` decorator ignores empty arrays. + +## [3.0.0] - 2015-09-10 +- Allow `\r`, `\n` and `\t` in attribute values without escaping. See [#86](https://github.com/oozcitak/xmlbuilder-js/issues/86). + +## [2.6.5] - 2015-09-09 +- Use native `isArray` instead of lodash. +- Indentation of processing instructions are set to the parent element's. + +## [2.6.4] - 2015-05-27 +- Updated lodash dependency to 3.5.0. + +## [2.6.3] - 2015-05-27 +- Bumped version because previous release was not published on npm. + +## [2.6.2] - 2015-03-10 +- Updated lodash dependency to 3.5.0. + +## [2.6.1] - 2015-02-20 +- Updated lodash dependency to 3.3.0. + +## [2.6.0] - 2015-02-20 +- Fixed a bug where the `XMLNode` constructor overwrote the super class parent. +- Removed document property from cloned nodes. +- Switched to mocha.js for testing. + +## [2.5.2] - 2015-02-16 +- Updated lodash dependency to 3.2.0. + +## [2.5.1] - 2015-02-09 +- Updated lodash dependency to 3.1.0. +- Support all node >= 0.8. + +## [2.5.0] - 2015-00-03 +- Updated lodash dependency to 3.0.0. + +## [2.4.6] - 2015-01-26 +- Show more information from attribute creation with null values. +- Added iojs as an engine. +- Self close elements with empty text. + +## [2.4.5] - 2014-11-15 +- Fixed prepublish script to run on windows. +- Fixed bug in XMLStringifier where an undefined value was used while reporting an invalid encoding value. +- Moved require statements to the top of files to reduce lazy requires. See [#62](https://github.com/oozcitak/xmlbuilder-js/issues/62). + +## [2.4.4] - 2014-09-08 +- Added the `offset` option to `toString()` for use in XML fragments. + +## [2.4.3] - 2014-08-13 +- Corrected license in package description. + +## [2.4.2] - 2014-08-13 +- Dropped performance test and memwatch dependency. + +## [2.4.1] - 2014-08-12 +- Fixed a bug where empty indent string was omitted when pretty printing. See [#59](https://github.com/oozcitak/xmlbuilder-js/issues/59). + +## [2.4.0] - 2014-08-04 +- Correct cases of pubID and sysID. +- Use single lodash instead of separate npm modules. See [#53](https://github.com/oozcitak/xmlbuilder-js/issues/53). +- Escape according to Canonical XML 1.0. See [#54](https://github.com/oozcitak/xmlbuilder-js/issues/54). + +## [2.3.0] - 2014-07-17 +- Convert objects to JS primitives while sanitizing user input. +- Object builder preserves items with null values. See [#44](https://github.com/oozcitak/xmlbuilder-js/issues/44). +- Use modularized lodash functions to cut down dependencies. +- Process empty objects when converting from objects so that we don't throw on empty child objects. + +## [2.2.1] - 2014-04-04 +- Bumped version because previous release was not published on npm. + +## [2.2.0] - 2014-04-04 +- Switch to lodash from underscore. +- Removed legacy `ext` option from `create()`. +- Drop old node versions: 0.4, 0.5, 0.6. 0.8 is the minimum requirement from now on. + +## [2.1.0] - 2013-12-30 +- Removed duplicate null checks from constructors. +- Fixed node count in performance test. +- Added option for skipping null attribute values. See [#26](https://github.com/oozcitak/xmlbuilder-js/issues/26). +- Allow multiple values in `att()` and `ins()`. +- Added ability to run individual performance tests. +- Added flag for ignoring decorator strings. + +## [2.0.1] - 2013-12-24 +- Removed performance tests from npm package. + +## [2.0.0] - 2013-12-24 +- Combined loops for speed up. +- Added support for the DTD and XML declaration. +- `clone` includes attributes. +- Added performance tests. +- Evaluate attribute value if function. +- Evaluate instruction value if function. + +## [1.1.2] - 2013-12-11 +- Changed processing instruction decorator to `?`. + +## [1.1.1] - 2013-12-11 +- Added processing instructions to JS object conversion. + +## [1.1.0] - 2013-12-10 +- Added license to package. +- `create()` and `element()` accept JS object to fully build the document. +- Added `nod()` and `n()` aliases for `node()`. +- Renamed `convertAttChar` decorator to `convertAttKey`. +- Ignore empty decorator strings when converting JS objects. + +## [1.0.2] - 2013-11-27 +- Removed temp file which was accidentally included in the package. + +## [1.0.1] - 2013-11-27 +- Custom stringify functions affect current instance only. + +## [1.0.0] - 2013-11-27 +- Added processing instructions. +- Added stringify functions to sanitize and convert input values. +- Added option for headless XML documents. +- Added vows tests. +- Removed Makefile. Using npm publish scripts instead. +- Removed the `begin()` function. `create()` begins the document by creating the root node. + +## [0.4.3] - 2013-11-08 +- Added option to include surrogate pairs in XML content. See [#29](https://github.com/oozcitak/xmlbuilder-js/issues/29). +- Fixed empty value string representation in pretty mode. +- Added pre and postpublish scripts to package.json. +- Filtered out prototype properties when appending attributes. See [#31](https://github.com/oozcitak/xmlbuilder-js/issues/31). + +## [0.4.2] - 2012-09-14 +- Removed README.md from `.npmignore`. + +## [0.4.1] - 2012-08-31 +- Removed `begin()` calls in favor of `XMLBuilder` constructor. +- Added the `end()` function. `end()` is a convenience over `doc().toString()`. + +## [0.4.0] - 2012-08-31 +- Added arguments to `XMLBuilder` constructor to allow the name of the root element and XML prolog to be defined in one line. +- Soft deprecated `begin()`. + +## [0.3.11] - 2012-08-13 +- Package keywords are fixed to be an array of values. + +## [0.3.10] - 2012-08-13 +- Brought back npm package contents which were lost due to incorrect configuration of `package.json` in previous releases. + +## [0.3.3] - 2012-07-27 +- Implemented `importXMLBuilder()`. + +## [0.3.2] - 2012-07-20 +- Fixed a duplicated escaping problem on `element()`. +- Fixed a problem with text node creation from empty string. +- Calling `root()` on the document element returns the root element. +- `XMLBuilder` no longer extends `XMLFragment`. + +## [0.3.1] - 2011-11-28 +- Added guards for document element so that nodes cannot be inserted at document level. + +## [0.3.0] - 2011-11-28 +- Added `doc()` to return the document element. + +## [0.2.2] - 2011-11-28 +- Prevent code relying on `up()`'s older behavior to break. + +## [0.2.1] - 2011-11-28 +- Added the `root()` function. + +## [0.2.0] - 2011-11-21 +- Added Travis-CI integration. +- Added coffee-script dependency. +- Added insert, traversal and delete functions. + +## [0.1.7] - 2011-10-25 +- No changes. Accidental release. + +## [0.1.6] - 2011-10-25 +- Corrected `package.json` bugs link to `url` from `web`. + +## [0.1.5] - 2011-08-08 +- Added missing npm package contents. + +## [0.1.4] - 2011-07-29 +- Text-only nodes are no longer indented. +- Added documentation for multiple instances. + +## [0.1.3] - 2011-07-27 +- Exported the `create()` function to return a new instance. This allows multiple builder instances to be constructed. +- Fixed `u()` function so that it now correctly calls `up()`. +- Fixed typo in `element()` so that `attributes` and `text` can be passed interchangeably. + +## [0.1.2] - 2011-06-03 +- `ele()` accepts element text. +- `attributes()` now overrides existing attributes if passed the same attribute name. + +## [0.1.1] - 2011-05-19 +- Added the raw output option. +- Removed most validity checks. + +## [0.1.0] - 2011-04-27 +- `text()` and `cdata()` now return parent element. +- Attribute values are escaped. + +## [0.0.7] - 2011-04-23 +- Coerced text values to string. + +## [0.0.6] - 2011-02-23 +- Added support for XML comments. +- Text nodes are checked against CharData. + +## [0.0.5] - 2010-12-31 +- Corrected the name of the main npm module in `package.json`. + +## [0.0.4] - 2010-12-28 +- Added `.npmignore`. + +## [0.0.3] - 2010-12-27 +- root element is now constructed in `begin()`. +- moved prolog to `begin()`. +- Added the ability to have CDATA in element text. +- Removed unused prolog aliases. +- Removed `builder()` function from main module. +- Added the name of the main npm module in `package.json`. + +## [0.0.2] - 2010-11-03 +- `element()` expands nested arrays. +- Added pretty printing. +- Added the `up()`, `build()` and `prolog()` functions. +- Added readme. + +## 0.0.1 - 2010-11-02 +- Initial release + +[11.0.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v10.1.1...v11.0.0 +[10.1.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v10.1.0...v10.1.1 +[10.1.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v10.0.0...v10.1.0 +[10.0.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v9.0.7...v10.0.0 +[9.0.7]: https://github.com/oozcitak/xmlbuilder-js/compare/v9.0.4...v9.0.7 +[9.0.4]: https://github.com/oozcitak/xmlbuilder-js/compare/v9.0.3...v9.0.4 +[9.0.3]: https://github.com/oozcitak/xmlbuilder-js/compare/v9.0.2...v9.0.3 +[9.0.2]: https://github.com/oozcitak/xmlbuilder-js/compare/v9.0.1...v9.0.2 +[9.0.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v9.0.0...v9.0.1 +[9.0.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v8.2.2...v9.0.0 +[8.2.2]: https://github.com/oozcitak/xmlbuilder-js/compare/v8.2.1...v8.2.2 +[8.2.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v8.2.0...v8.2.1 +[8.2.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v8.1.0...v8.2.0 +[8.1.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v8.0.0...v8.1.0 +[8.0.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v7.0.0...v8.0.0 +[7.0.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v6.0.0...v7.0.0 +[6.0.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v5.0.1...v6.0.0 +[5.0.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v5.0.0...v5.0.1 +[5.0.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v4.2.1...v5.0.0 +[4.2.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v4.2.0...v4.2.1 +[4.2.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v4.1.0...v4.2.0 +[4.1.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v4.0.0...v4.1.0 +[4.0.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v3.1.0...v4.0.0 +[3.1.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v3.0.0...v3.1.0 +[3.0.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.6.5...v3.0.0 +[2.6.5]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.6.4...v2.6.5 +[2.6.4]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.6.3...v2.6.4 +[2.6.3]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.6.2...v2.6.3 +[2.6.2]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.6.1...v2.6.2 +[2.6.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.6.0...v2.6.1 +[2.6.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.5.2...v2.6.0 +[2.5.2]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.5.1...v2.5.2 +[2.5.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.5.0...v2.5.1 +[2.5.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.4.6...v2.5.0 +[2.4.6]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.4.5...v2.4.6 +[2.4.5]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.4.4...v2.4.5 +[2.4.4]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.4.3...v2.4.4 +[2.4.3]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.4.2...v2.4.3 +[2.4.2]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.4.1...v2.4.2 +[2.4.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.4.0...v2.4.1 +[2.4.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.3.0...v2.4.0 +[2.3.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.2.1...v2.3.0 +[2.2.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.2.0...v2.2.1 +[2.2.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.1.0...v2.2.0 +[2.1.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.0.1...v2.1.0 +[2.0.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.0.0...v2.0.1 +[2.0.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v1.1.2...v2.0.0 +[1.1.2]: https://github.com/oozcitak/xmlbuilder-js/compare/v1.1.1...v1.1.2 +[1.1.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v1.1.0...v1.1.1 +[1.1.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v1.0.2...v1.1.0 +[1.0.2]: https://github.com/oozcitak/xmlbuilder-js/compare/v1.0.1...v1.0.2 +[1.0.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v1.0.0...v1.0.1 +[1.0.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.4.3...v1.0.0 +[0.4.3]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.4.2...v0.4.3 +[0.4.2]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.4.1...v0.4.2 +[0.4.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.4.0...v0.4.1 +[0.4.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.3.11...v0.4.0 +[0.3.11]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.3.10...v0.3.11 +[0.3.10]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.3.3...v0.3.10 +[0.3.3]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.3.2...v0.3.3 +[0.3.2]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.3.1...v0.3.2 +[0.3.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.3.0...v0.3.1 +[0.3.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.2.2...v0.3.0 +[0.2.2]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.2.1...v0.2.2 +[0.2.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.2.0...v0.2.1 +[0.2.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.1.7...v0.2.0 +[0.1.7]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.1.6...v0.1.7 +[0.1.6]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.1.5...v0.1.6 +[0.1.5]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.1.4...v0.1.5 +[0.1.4]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.1.3...v0.1.4 +[0.1.3]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.1.2...v0.1.3 +[0.1.2]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.1.1...v0.1.2 +[0.1.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.1.0...v0.1.1 +[0.1.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.0.7...v0.1.0 +[0.0.7]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.0.6...v0.0.7 +[0.0.6]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.0.5...v0.0.6 +[0.0.5]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.0.4...v0.0.5 +[0.0.4]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.0.3...v0.0.4 +[0.0.3]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.0.2...v0.0.3 +[0.0.2]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.0.1...v0.0.2 + diff --git a/node_modules/xmlbuilder/LICENSE b/node_modules/xmlbuilder/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9fb97002a2928586a33381cf889caca4fa69c50a --- /dev/null +++ b/node_modules/xmlbuilder/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013 Ozgur Ozcitak + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/xmlbuilder/README.md b/node_modules/xmlbuilder/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1a96edb586778c8682109df5ebb6d0ce0f4b3cbf --- /dev/null +++ b/node_modules/xmlbuilder/README.md @@ -0,0 +1,86 @@ +# xmlbuilder-js + +An XML builder for [node.js](https://nodejs.org/) similar to +[java-xmlbuilder](https://github.com/jmurty/java-xmlbuilder). + +[![License](http://img.shields.io/npm/l/xmlbuilder.svg?style=flat-square)](http://opensource.org/licenses/MIT) +[![NPM Version](http://img.shields.io/npm/v/xmlbuilder.svg?style=flat-square)](https://npmjs.com/package/xmlbuilder) +[![NPM Downloads](https://img.shields.io/npm/dm/xmlbuilder.svg?style=flat-square)](https://npmjs.com/package/xmlbuilder) + +[![Travis Build Status](http://img.shields.io/travis/oozcitak/xmlbuilder-js.svg?style=flat-square)](http://travis-ci.org/oozcitak/xmlbuilder-js) +[![AppVeyor Build status](https://ci.appveyor.com/api/projects/status/bf7odb20hj77isry?svg=true)](https://ci.appveyor.com/project/oozcitak/xmlbuilder-js) +[![Dev Dependency Status](http://img.shields.io/david/dev/oozcitak/xmlbuilder-js.svg?style=flat-square)](https://david-dm.org/oozcitak/xmlbuilder-js) +[![Code Coverage](https://img.shields.io/coveralls/oozcitak/xmlbuilder-js.svg?style=flat-square)](https://coveralls.io/github/oozcitak/xmlbuilder-js) + +### Installation: + +``` sh +npm install xmlbuilder +``` + +### Usage: + +``` js +var builder = require('xmlbuilder'); +var xml = builder.create('root') + .ele('xmlbuilder') + .ele('repo', {'type': 'git'}, 'git://github.com/oozcitak/xmlbuilder-js.git') + .end({ pretty: true}); + +console.log(xml); +``` + +will result in: + +``` xml + + + + git://github.com/oozcitak/xmlbuilder-js.git + + +``` + +It is also possible to convert objects into nodes: + +``` js +builder.create({ + root: { + xmlbuilder: { + repo: { + '@type': 'git', // attributes start with @ + '#text': 'git://github.com/oozcitak/xmlbuilder-js.git' // text node + } + } + } +}); +``` + +If you need to do some processing: + +``` js +var root = builder.create('squares'); +root.com('f(x) = x^2'); +for(var i = 1; i <= 5; i++) +{ + var item = root.ele('data'); + item.att('x', i); + item.att('y', i * i); +} +``` + +This will result in: + +``` xml + + + + + + + + + +``` + +See the [wiki](https://github.com/oozcitak/xmlbuilder-js/wiki) for details and [examples](https://github.com/oozcitak/xmlbuilder-js/wiki/Examples) for more complex examples. diff --git a/node_modules/xmlbuilder/appveyor.yml b/node_modules/xmlbuilder/appveyor.yml new file mode 100644 index 0000000000000000000000000000000000000000..9604b785333cc11e657944f92a2e22963840ba35 --- /dev/null +++ b/node_modules/xmlbuilder/appveyor.yml @@ -0,0 +1,20 @@ +environment: + matrix: + - nodejs_version: "4" + - nodejs_version: "5" + - nodejs_version: "6" + - nodejs_version: "8" + - nodejs_version: "10" + - nodejs_version: "" # latest + +install: + - ps: "Install-Product node $env:nodejs_version" + - "npm install" + +test_script: + - "node --version" + - "npm --version" + - "npm test" + +build: off + diff --git a/node_modules/xmlbuilder/lib/Derivation.js b/node_modules/xmlbuilder/lib/Derivation.js new file mode 100644 index 0000000000000000000000000000000000000000..2abfd08ddd6e0ee9337aeaaa199e20f416304d9a --- /dev/null +++ b/node_modules/xmlbuilder/lib/Derivation.js @@ -0,0 +1,10 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + module.exports = { + Restriction: 1, + Extension: 2, + Union: 4, + List: 8 + }; + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/DocumentPosition.js b/node_modules/xmlbuilder/lib/DocumentPosition.js new file mode 100644 index 0000000000000000000000000000000000000000..1cbd21c14a407235e39e72fbe6a91b13b7c09dbf --- /dev/null +++ b/node_modules/xmlbuilder/lib/DocumentPosition.js @@ -0,0 +1,12 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + module.exports = { + Disconnected: 1, + Preceding: 2, + Following: 4, + Contains: 8, + ContainedBy: 16, + ImplementationSpecific: 32 + }; + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/NodeType.js b/node_modules/xmlbuilder/lib/NodeType.js new file mode 100644 index 0000000000000000000000000000000000000000..4c200e3cff4f611bf106a0ee7eaee31e33de8347 --- /dev/null +++ b/node_modules/xmlbuilder/lib/NodeType.js @@ -0,0 +1,23 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + module.exports = { + Element: 1, + Attribute: 2, + Text: 3, + CData: 4, + EntityReference: 5, + EntityDeclaration: 6, + ProcessingInstruction: 7, + Comment: 8, + Document: 9, + DocType: 10, + DocumentFragment: 11, + NotationDeclaration: 12, + Declaration: 201, + Raw: 202, + AttributeDeclaration: 203, + ElementDeclaration: 204, + Dummy: 205 + }; + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/OperationType.js b/node_modules/xmlbuilder/lib/OperationType.js new file mode 100644 index 0000000000000000000000000000000000000000..29428f6111b3a0bbab0303cb7db6105b7c6d045e --- /dev/null +++ b/node_modules/xmlbuilder/lib/OperationType.js @@ -0,0 +1,11 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + module.exports = { + Clones: 1, + Imported: 2, + Deleted: 3, + Renamed: 4, + Adopted: 5 + }; + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/Utility.js b/node_modules/xmlbuilder/lib/Utility.js new file mode 100644 index 0000000000000000000000000000000000000000..1d42cfd312388742a4f062bf6d9ac62a460f82c1 --- /dev/null +++ b/node_modules/xmlbuilder/lib/Utility.js @@ -0,0 +1,83 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var assign, getValue, isArray, isEmpty, isFunction, isObject, isPlainObject, + slice = [].slice, + hasProp = {}.hasOwnProperty; + + assign = function() { + var i, key, len, source, sources, target; + target = arguments[0], sources = 2 <= arguments.length ? slice.call(arguments, 1) : []; + if (isFunction(Object.assign)) { + Object.assign.apply(null, arguments); + } else { + for (i = 0, len = sources.length; i < len; i++) { + source = sources[i]; + if (source != null) { + for (key in source) { + if (!hasProp.call(source, key)) continue; + target[key] = source[key]; + } + } + } + } + return target; + }; + + isFunction = function(val) { + return !!val && Object.prototype.toString.call(val) === '[object Function]'; + }; + + isObject = function(val) { + var ref; + return !!val && ((ref = typeof val) === 'function' || ref === 'object'); + }; + + isArray = function(val) { + if (isFunction(Array.isArray)) { + return Array.isArray(val); + } else { + return Object.prototype.toString.call(val) === '[object Array]'; + } + }; + + isEmpty = function(val) { + var key; + if (isArray(val)) { + return !val.length; + } else { + for (key in val) { + if (!hasProp.call(val, key)) continue; + return false; + } + return true; + } + }; + + isPlainObject = function(val) { + var ctor, proto; + return isObject(val) && (proto = Object.getPrototypeOf(val)) && (ctor = proto.constructor) && (typeof ctor === 'function') && (ctor instanceof ctor) && (Function.prototype.toString.call(ctor) === Function.prototype.toString.call(Object)); + }; + + getValue = function(obj) { + if (isFunction(obj.valueOf)) { + return obj.valueOf(); + } else { + return obj; + } + }; + + module.exports.assign = assign; + + module.exports.isFunction = isFunction; + + module.exports.isObject = isObject; + + module.exports.isArray = isArray; + + module.exports.isEmpty = isEmpty; + + module.exports.isPlainObject = isPlainObject; + + module.exports.getValue = getValue; + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/WriterState.js b/node_modules/xmlbuilder/lib/WriterState.js new file mode 100644 index 0000000000000000000000000000000000000000..0923eec9feb66b3f0f04bff6a980bd4cdad3362f --- /dev/null +++ b/node_modules/xmlbuilder/lib/WriterState.js @@ -0,0 +1,10 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + module.exports = { + None: 0, + OpenTag: 1, + InsideTag: 2, + CloseTag: 3 + }; + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/XMLAttribute.js b/node_modules/xmlbuilder/lib/XMLAttribute.js new file mode 100644 index 0000000000000000000000000000000000000000..c208566dde9efdade97192243e27ae92e75df250 --- /dev/null +++ b/node_modules/xmlbuilder/lib/XMLAttribute.js @@ -0,0 +1,108 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLAttribute, XMLNode; + + NodeType = require('./NodeType'); + + XMLNode = require('./XMLNode'); + + module.exports = XMLAttribute = (function() { + function XMLAttribute(parent, name, value) { + this.parent = parent; + if (this.parent) { + this.options = this.parent.options; + this.stringify = this.parent.stringify; + } + if (name == null) { + throw new Error("Missing attribute name. " + this.debugInfo(name)); + } + this.name = this.stringify.name(name); + this.value = this.stringify.attValue(value); + this.type = NodeType.Attribute; + this.isId = false; + this.schemaTypeInfo = null; + } + + Object.defineProperty(XMLAttribute.prototype, 'nodeType', { + get: function() { + return this.type; + } + }); + + Object.defineProperty(XMLAttribute.prototype, 'ownerElement', { + get: function() { + return this.parent; + } + }); + + Object.defineProperty(XMLAttribute.prototype, 'textContent', { + get: function() { + return this.value; + }, + set: function(value) { + return this.value = value || ''; + } + }); + + Object.defineProperty(XMLAttribute.prototype, 'namespaceURI', { + get: function() { + return ''; + } + }); + + Object.defineProperty(XMLAttribute.prototype, 'prefix', { + get: function() { + return ''; + } + }); + + Object.defineProperty(XMLAttribute.prototype, 'localName', { + get: function() { + return this.name; + } + }); + + Object.defineProperty(XMLAttribute.prototype, 'specified', { + get: function() { + return true; + } + }); + + XMLAttribute.prototype.clone = function() { + return Object.create(this); + }; + + XMLAttribute.prototype.toString = function(options) { + return this.options.writer.attribute(this, this.options.writer.filterOptions(options)); + }; + + XMLAttribute.prototype.debugInfo = function(name) { + name = name || this.name; + if (name == null) { + return "parent: <" + this.parent.name + ">"; + } else { + return "attribute: {" + name + "}, parent: <" + this.parent.name + ">"; + } + }; + + XMLAttribute.prototype.isEqualNode = function(node) { + if (node.namespaceURI !== this.namespaceURI) { + return false; + } + if (node.prefix !== this.prefix) { + return false; + } + if (node.localName !== this.localName) { + return false; + } + if (node.value !== this.value) { + return false; + } + return true; + }; + + return XMLAttribute; + + })(); + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/XMLCData.js b/node_modules/xmlbuilder/lib/XMLCData.js new file mode 100644 index 0000000000000000000000000000000000000000..c732ec5b0388c90322c39a6aff06b984a7c330cf --- /dev/null +++ b/node_modules/xmlbuilder/lib/XMLCData.js @@ -0,0 +1,36 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLCData, XMLCharacterData, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + NodeType = require('./NodeType'); + + XMLCharacterData = require('./XMLCharacterData'); + + module.exports = XMLCData = (function(superClass) { + extend(XMLCData, superClass); + + function XMLCData(parent, text) { + XMLCData.__super__.constructor.call(this, parent); + if (text == null) { + throw new Error("Missing CDATA text. " + this.debugInfo()); + } + this.name = "#cdata-section"; + this.type = NodeType.CData; + this.value = this.stringify.cdata(text); + } + + XMLCData.prototype.clone = function() { + return Object.create(this); + }; + + XMLCData.prototype.toString = function(options) { + return this.options.writer.cdata(this, this.options.writer.filterOptions(options)); + }; + + return XMLCData; + + })(XMLCharacterData); + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/XMLCharacterData.js b/node_modules/xmlbuilder/lib/XMLCharacterData.js new file mode 100644 index 0000000000000000000000000000000000000000..c007a1810925ef962a48799cba26f04005d20d2a --- /dev/null +++ b/node_modules/xmlbuilder/lib/XMLCharacterData.js @@ -0,0 +1,79 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var XMLCharacterData, XMLNode, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + XMLNode = require('./XMLNode'); + + module.exports = XMLCharacterData = (function(superClass) { + extend(XMLCharacterData, superClass); + + function XMLCharacterData(parent) { + XMLCharacterData.__super__.constructor.call(this, parent); + this.value = ''; + } + + Object.defineProperty(XMLCharacterData.prototype, 'data', { + get: function() { + return this.value; + }, + set: function(value) { + return this.value = value || ''; + } + }); + + Object.defineProperty(XMLCharacterData.prototype, 'length', { + get: function() { + return this.value.length; + } + }); + + Object.defineProperty(XMLCharacterData.prototype, 'textContent', { + get: function() { + return this.value; + }, + set: function(value) { + return this.value = value || ''; + } + }); + + XMLCharacterData.prototype.clone = function() { + return Object.create(this); + }; + + XMLCharacterData.prototype.substringData = function(offset, count) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLCharacterData.prototype.appendData = function(arg) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLCharacterData.prototype.insertData = function(offset, arg) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLCharacterData.prototype.deleteData = function(offset, count) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLCharacterData.prototype.replaceData = function(offset, count, arg) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLCharacterData.prototype.isEqualNode = function(node) { + if (!XMLCharacterData.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) { + return false; + } + if (node.data !== this.data) { + return false; + } + return true; + }; + + return XMLCharacterData; + + })(XMLNode); + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/XMLComment.js b/node_modules/xmlbuilder/lib/XMLComment.js new file mode 100644 index 0000000000000000000000000000000000000000..828721685b9e5770c96514c38696f6ff2aa4cbeb --- /dev/null +++ b/node_modules/xmlbuilder/lib/XMLComment.js @@ -0,0 +1,36 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLCharacterData, XMLComment, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + NodeType = require('./NodeType'); + + XMLCharacterData = require('./XMLCharacterData'); + + module.exports = XMLComment = (function(superClass) { + extend(XMLComment, superClass); + + function XMLComment(parent, text) { + XMLComment.__super__.constructor.call(this, parent); + if (text == null) { + throw new Error("Missing comment text. " + this.debugInfo()); + } + this.name = "#comment"; + this.type = NodeType.Comment; + this.value = this.stringify.comment(text); + } + + XMLComment.prototype.clone = function() { + return Object.create(this); + }; + + XMLComment.prototype.toString = function(options) { + return this.options.writer.comment(this, this.options.writer.filterOptions(options)); + }; + + return XMLComment; + + })(XMLCharacterData); + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/XMLDOMConfiguration.js b/node_modules/xmlbuilder/lib/XMLDOMConfiguration.js new file mode 100644 index 0000000000000000000000000000000000000000..b331b86f358ca28601d2d05dab3a9518683b6704 --- /dev/null +++ b/node_modules/xmlbuilder/lib/XMLDOMConfiguration.js @@ -0,0 +1,64 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var XMLDOMConfiguration, XMLDOMErrorHandler, XMLDOMStringList; + + XMLDOMErrorHandler = require('./XMLDOMErrorHandler'); + + XMLDOMStringList = require('./XMLDOMStringList'); + + module.exports = XMLDOMConfiguration = (function() { + function XMLDOMConfiguration() { + var clonedSelf; + this.defaultParams = { + "canonical-form": false, + "cdata-sections": false, + "comments": false, + "datatype-normalization": false, + "element-content-whitespace": true, + "entities": true, + "error-handler": new XMLDOMErrorHandler(), + "infoset": true, + "validate-if-schema": false, + "namespaces": true, + "namespace-declarations": true, + "normalize-characters": false, + "schema-location": '', + "schema-type": '', + "split-cdata-sections": true, + "validate": false, + "well-formed": true + }; + this.params = clonedSelf = Object.create(this.defaultParams); + } + + Object.defineProperty(XMLDOMConfiguration.prototype, 'parameterNames', { + get: function() { + return new XMLDOMStringList(Object.keys(this.defaultParams)); + } + }); + + XMLDOMConfiguration.prototype.getParameter = function(name) { + if (this.params.hasOwnProperty(name)) { + return this.params[name]; + } else { + return null; + } + }; + + XMLDOMConfiguration.prototype.canSetParameter = function(name, value) { + return true; + }; + + XMLDOMConfiguration.prototype.setParameter = function(name, value) { + if (value != null) { + return this.params[name] = value; + } else { + return delete this.params[name]; + } + }; + + return XMLDOMConfiguration; + + })(); + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/XMLDOMErrorHandler.js b/node_modules/xmlbuilder/lib/XMLDOMErrorHandler.js new file mode 100644 index 0000000000000000000000000000000000000000..4a0446c0976f6f71e2f51f78ac9035aa6483e4f7 --- /dev/null +++ b/node_modules/xmlbuilder/lib/XMLDOMErrorHandler.js @@ -0,0 +1,16 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var XMLDOMErrorHandler; + + module.exports = XMLDOMErrorHandler = (function() { + function XMLDOMErrorHandler() {} + + XMLDOMErrorHandler.prototype.handleError = function(error) { + throw new Error(error); + }; + + return XMLDOMErrorHandler; + + })(); + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/XMLDOMImplementation.js b/node_modules/xmlbuilder/lib/XMLDOMImplementation.js new file mode 100644 index 0000000000000000000000000000000000000000..4f9f9db15027a3b243c0dc137136c7d842c29159 --- /dev/null +++ b/node_modules/xmlbuilder/lib/XMLDOMImplementation.js @@ -0,0 +1,32 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var XMLDOMImplementation; + + module.exports = XMLDOMImplementation = (function() { + function XMLDOMImplementation() {} + + XMLDOMImplementation.prototype.hasFeature = function(feature, version) { + return true; + }; + + XMLDOMImplementation.prototype.createDocumentType = function(qualifiedName, publicId, systemId) { + throw new Error("This DOM method is not implemented."); + }; + + XMLDOMImplementation.prototype.createDocument = function(namespaceURI, qualifiedName, doctype) { + throw new Error("This DOM method is not implemented."); + }; + + XMLDOMImplementation.prototype.createHTMLDocument = function(title) { + throw new Error("This DOM method is not implemented."); + }; + + XMLDOMImplementation.prototype.getFeature = function(feature, version) { + throw new Error("This DOM method is not implemented."); + }; + + return XMLDOMImplementation; + + })(); + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/XMLDOMStringList.js b/node_modules/xmlbuilder/lib/XMLDOMStringList.js new file mode 100644 index 0000000000000000000000000000000000000000..ba558c5bc97252d352c4342cc7f11dbd441a1095 --- /dev/null +++ b/node_modules/xmlbuilder/lib/XMLDOMStringList.js @@ -0,0 +1,28 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var XMLDOMStringList; + + module.exports = XMLDOMStringList = (function() { + function XMLDOMStringList(arr) { + this.arr = arr || []; + } + + Object.defineProperty(XMLDOMStringList.prototype, 'length', { + get: function() { + return this.arr.length; + } + }); + + XMLDOMStringList.prototype.item = function(index) { + return this.arr[index] || null; + }; + + XMLDOMStringList.prototype.contains = function(str) { + return this.arr.indexOf(str) !== -1; + }; + + return XMLDOMStringList; + + })(); + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/XMLDTDAttList.js b/node_modules/xmlbuilder/lib/XMLDTDAttList.js new file mode 100644 index 0000000000000000000000000000000000000000..aca9dbd4f746382a214f57abb7abda43d4b8066a --- /dev/null +++ b/node_modules/xmlbuilder/lib/XMLDTDAttList.js @@ -0,0 +1,55 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLDTDAttList, XMLNode, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + XMLNode = require('./XMLNode'); + + NodeType = require('./NodeType'); + + module.exports = XMLDTDAttList = (function(superClass) { + extend(XMLDTDAttList, superClass); + + function XMLDTDAttList(parent, elementName, attributeName, attributeType, defaultValueType, defaultValue) { + XMLDTDAttList.__super__.constructor.call(this, parent); + if (elementName == null) { + throw new Error("Missing DTD element name. " + this.debugInfo()); + } + if (attributeName == null) { + throw new Error("Missing DTD attribute name. " + this.debugInfo(elementName)); + } + if (!attributeType) { + throw new Error("Missing DTD attribute type. " + this.debugInfo(elementName)); + } + if (!defaultValueType) { + throw new Error("Missing DTD attribute default. " + this.debugInfo(elementName)); + } + if (defaultValueType.indexOf('#') !== 0) { + defaultValueType = '#' + defaultValueType; + } + if (!defaultValueType.match(/^(#REQUIRED|#IMPLIED|#FIXED|#DEFAULT)$/)) { + throw new Error("Invalid default value type; expected: #REQUIRED, #IMPLIED, #FIXED or #DEFAULT. " + this.debugInfo(elementName)); + } + if (defaultValue && !defaultValueType.match(/^(#FIXED|#DEFAULT)$/)) { + throw new Error("Default value only applies to #FIXED or #DEFAULT. " + this.debugInfo(elementName)); + } + this.elementName = this.stringify.name(elementName); + this.type = NodeType.AttributeDeclaration; + this.attributeName = this.stringify.name(attributeName); + this.attributeType = this.stringify.dtdAttType(attributeType); + if (defaultValue) { + this.defaultValue = this.stringify.dtdAttDefault(defaultValue); + } + this.defaultValueType = defaultValueType; + } + + XMLDTDAttList.prototype.toString = function(options) { + return this.options.writer.dtdAttList(this, this.options.writer.filterOptions(options)); + }; + + return XMLDTDAttList; + + })(XMLNode); + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/XMLDTDElement.js b/node_modules/xmlbuilder/lib/XMLDTDElement.js new file mode 100644 index 0000000000000000000000000000000000000000..f8f1ae76d08953c2a1b8fac6cfcaf8ce8545265c --- /dev/null +++ b/node_modules/xmlbuilder/lib/XMLDTDElement.js @@ -0,0 +1,38 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLDTDElement, XMLNode, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + XMLNode = require('./XMLNode'); + + NodeType = require('./NodeType'); + + module.exports = XMLDTDElement = (function(superClass) { + extend(XMLDTDElement, superClass); + + function XMLDTDElement(parent, name, value) { + XMLDTDElement.__super__.constructor.call(this, parent); + if (name == null) { + throw new Error("Missing DTD element name. " + this.debugInfo()); + } + if (!value) { + value = '(#PCDATA)'; + } + if (Array.isArray(value)) { + value = '(' + value.join(',') + ')'; + } + this.name = this.stringify.name(name); + this.type = NodeType.ElementDeclaration; + this.value = this.stringify.dtdElementValue(value); + } + + XMLDTDElement.prototype.toString = function(options) { + return this.options.writer.dtdElement(this, this.options.writer.filterOptions(options)); + }; + + return XMLDTDElement; + + })(XMLNode); + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/XMLDTDEntity.js b/node_modules/xmlbuilder/lib/XMLDTDEntity.js new file mode 100644 index 0000000000000000000000000000000000000000..0a940d6e67a99b9c20b8580a8f7af9e9d36a042e --- /dev/null +++ b/node_modules/xmlbuilder/lib/XMLDTDEntity.js @@ -0,0 +1,97 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLDTDEntity, XMLNode, isObject, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + isObject = require('./Utility').isObject; + + XMLNode = require('./XMLNode'); + + NodeType = require('./NodeType'); + + module.exports = XMLDTDEntity = (function(superClass) { + extend(XMLDTDEntity, superClass); + + function XMLDTDEntity(parent, pe, name, value) { + XMLDTDEntity.__super__.constructor.call(this, parent); + if (name == null) { + throw new Error("Missing DTD entity name. " + this.debugInfo(name)); + } + if (value == null) { + throw new Error("Missing DTD entity value. " + this.debugInfo(name)); + } + this.pe = !!pe; + this.name = this.stringify.name(name); + this.type = NodeType.EntityDeclaration; + if (!isObject(value)) { + this.value = this.stringify.dtdEntityValue(value); + this.internal = true; + } else { + if (!value.pubID && !value.sysID) { + throw new Error("Public and/or system identifiers are required for an external entity. " + this.debugInfo(name)); + } + if (value.pubID && !value.sysID) { + throw new Error("System identifier is required for a public external entity. " + this.debugInfo(name)); + } + this.internal = false; + if (value.pubID != null) { + this.pubID = this.stringify.dtdPubID(value.pubID); + } + if (value.sysID != null) { + this.sysID = this.stringify.dtdSysID(value.sysID); + } + if (value.nData != null) { + this.nData = this.stringify.dtdNData(value.nData); + } + if (this.pe && this.nData) { + throw new Error("Notation declaration is not allowed in a parameter entity. " + this.debugInfo(name)); + } + } + } + + Object.defineProperty(XMLDTDEntity.prototype, 'publicId', { + get: function() { + return this.pubID; + } + }); + + Object.defineProperty(XMLDTDEntity.prototype, 'systemId', { + get: function() { + return this.sysID; + } + }); + + Object.defineProperty(XMLDTDEntity.prototype, 'notationName', { + get: function() { + return this.nData || null; + } + }); + + Object.defineProperty(XMLDTDEntity.prototype, 'inputEncoding', { + get: function() { + return null; + } + }); + + Object.defineProperty(XMLDTDEntity.prototype, 'xmlEncoding', { + get: function() { + return null; + } + }); + + Object.defineProperty(XMLDTDEntity.prototype, 'xmlVersion', { + get: function() { + return null; + } + }); + + XMLDTDEntity.prototype.toString = function(options) { + return this.options.writer.dtdEntity(this, this.options.writer.filterOptions(options)); + }; + + return XMLDTDEntity; + + })(XMLNode); + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/XMLDTDNotation.js b/node_modules/xmlbuilder/lib/XMLDTDNotation.js new file mode 100644 index 0000000000000000000000000000000000000000..57a119d2db38d7da25badbe485310cf9505ab8c8 --- /dev/null +++ b/node_modules/xmlbuilder/lib/XMLDTDNotation.js @@ -0,0 +1,52 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLDTDNotation, XMLNode, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + XMLNode = require('./XMLNode'); + + NodeType = require('./NodeType'); + + module.exports = XMLDTDNotation = (function(superClass) { + extend(XMLDTDNotation, superClass); + + function XMLDTDNotation(parent, name, value) { + XMLDTDNotation.__super__.constructor.call(this, parent); + if (name == null) { + throw new Error("Missing DTD notation name. " + this.debugInfo(name)); + } + if (!value.pubID && !value.sysID) { + throw new Error("Public or system identifiers are required for an external entity. " + this.debugInfo(name)); + } + this.name = this.stringify.name(name); + this.type = NodeType.NotationDeclaration; + if (value.pubID != null) { + this.pubID = this.stringify.dtdPubID(value.pubID); + } + if (value.sysID != null) { + this.sysID = this.stringify.dtdSysID(value.sysID); + } + } + + Object.defineProperty(XMLDTDNotation.prototype, 'publicId', { + get: function() { + return this.pubID; + } + }); + + Object.defineProperty(XMLDTDNotation.prototype, 'systemId', { + get: function() { + return this.sysID; + } + }); + + XMLDTDNotation.prototype.toString = function(options) { + return this.options.writer.dtdNotation(this, this.options.writer.filterOptions(options)); + }; + + return XMLDTDNotation; + + })(XMLNode); + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/XMLDeclaration.js b/node_modules/xmlbuilder/lib/XMLDeclaration.js new file mode 100644 index 0000000000000000000000000000000000000000..d4f7f44729784b2fee19dfc27cd7d55fcf17f8c4 --- /dev/null +++ b/node_modules/xmlbuilder/lib/XMLDeclaration.js @@ -0,0 +1,43 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLDeclaration, XMLNode, isObject, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + isObject = require('./Utility').isObject; + + XMLNode = require('./XMLNode'); + + NodeType = require('./NodeType'); + + module.exports = XMLDeclaration = (function(superClass) { + extend(XMLDeclaration, superClass); + + function XMLDeclaration(parent, version, encoding, standalone) { + var ref; + XMLDeclaration.__super__.constructor.call(this, parent); + if (isObject(version)) { + ref = version, version = ref.version, encoding = ref.encoding, standalone = ref.standalone; + } + if (!version) { + version = '1.0'; + } + this.type = NodeType.Declaration; + this.version = this.stringify.xmlVersion(version); + if (encoding != null) { + this.encoding = this.stringify.xmlEncoding(encoding); + } + if (standalone != null) { + this.standalone = this.stringify.xmlStandalone(standalone); + } + } + + XMLDeclaration.prototype.toString = function(options) { + return this.options.writer.declaration(this, this.options.writer.filterOptions(options)); + }; + + return XMLDeclaration; + + })(XMLNode); + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/XMLDocType.js b/node_modules/xmlbuilder/lib/XMLDocType.js new file mode 100644 index 0000000000000000000000000000000000000000..ef043f4c248a035e7a4b87b76cb91b8504371e2a --- /dev/null +++ b/node_modules/xmlbuilder/lib/XMLDocType.js @@ -0,0 +1,186 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDocType, XMLNamedNodeMap, XMLNode, isObject, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + isObject = require('./Utility').isObject; + + XMLNode = require('./XMLNode'); + + NodeType = require('./NodeType'); + + XMLDTDAttList = require('./XMLDTDAttList'); + + XMLDTDEntity = require('./XMLDTDEntity'); + + XMLDTDElement = require('./XMLDTDElement'); + + XMLDTDNotation = require('./XMLDTDNotation'); + + XMLNamedNodeMap = require('./XMLNamedNodeMap'); + + module.exports = XMLDocType = (function(superClass) { + extend(XMLDocType, superClass); + + function XMLDocType(parent, pubID, sysID) { + var child, i, len, ref, ref1, ref2; + XMLDocType.__super__.constructor.call(this, parent); + this.type = NodeType.DocType; + if (parent.children) { + ref = parent.children; + for (i = 0, len = ref.length; i < len; i++) { + child = ref[i]; + if (child.type === NodeType.Element) { + this.name = child.name; + break; + } + } + } + this.documentObject = parent; + if (isObject(pubID)) { + ref1 = pubID, pubID = ref1.pubID, sysID = ref1.sysID; + } + if (sysID == null) { + ref2 = [pubID, sysID], sysID = ref2[0], pubID = ref2[1]; + } + if (pubID != null) { + this.pubID = this.stringify.dtdPubID(pubID); + } + if (sysID != null) { + this.sysID = this.stringify.dtdSysID(sysID); + } + } + + Object.defineProperty(XMLDocType.prototype, 'entities', { + get: function() { + var child, i, len, nodes, ref; + nodes = {}; + ref = this.children; + for (i = 0, len = ref.length; i < len; i++) { + child = ref[i]; + if ((child.type === NodeType.EntityDeclaration) && !child.pe) { + nodes[child.name] = child; + } + } + return new XMLNamedNodeMap(nodes); + } + }); + + Object.defineProperty(XMLDocType.prototype, 'notations', { + get: function() { + var child, i, len, nodes, ref; + nodes = {}; + ref = this.children; + for (i = 0, len = ref.length; i < len; i++) { + child = ref[i]; + if (child.type === NodeType.NotationDeclaration) { + nodes[child.name] = child; + } + } + return new XMLNamedNodeMap(nodes); + } + }); + + Object.defineProperty(XMLDocType.prototype, 'publicId', { + get: function() { + return this.pubID; + } + }); + + Object.defineProperty(XMLDocType.prototype, 'systemId', { + get: function() { + return this.sysID; + } + }); + + Object.defineProperty(XMLDocType.prototype, 'internalSubset', { + get: function() { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + } + }); + + XMLDocType.prototype.element = function(name, value) { + var child; + child = new XMLDTDElement(this, name, value); + this.children.push(child); + return this; + }; + + XMLDocType.prototype.attList = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) { + var child; + child = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue); + this.children.push(child); + return this; + }; + + XMLDocType.prototype.entity = function(name, value) { + var child; + child = new XMLDTDEntity(this, false, name, value); + this.children.push(child); + return this; + }; + + XMLDocType.prototype.pEntity = function(name, value) { + var child; + child = new XMLDTDEntity(this, true, name, value); + this.children.push(child); + return this; + }; + + XMLDocType.prototype.notation = function(name, value) { + var child; + child = new XMLDTDNotation(this, name, value); + this.children.push(child); + return this; + }; + + XMLDocType.prototype.toString = function(options) { + return this.options.writer.docType(this, this.options.writer.filterOptions(options)); + }; + + XMLDocType.prototype.ele = function(name, value) { + return this.element(name, value); + }; + + XMLDocType.prototype.att = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) { + return this.attList(elementName, attributeName, attributeType, defaultValueType, defaultValue); + }; + + XMLDocType.prototype.ent = function(name, value) { + return this.entity(name, value); + }; + + XMLDocType.prototype.pent = function(name, value) { + return this.pEntity(name, value); + }; + + XMLDocType.prototype.not = function(name, value) { + return this.notation(name, value); + }; + + XMLDocType.prototype.up = function() { + return this.root() || this.documentObject; + }; + + XMLDocType.prototype.isEqualNode = function(node) { + if (!XMLDocType.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) { + return false; + } + if (node.name !== this.name) { + return false; + } + if (node.publicId !== this.publicId) { + return false; + } + if (node.systemId !== this.systemId) { + return false; + } + return true; + }; + + return XMLDocType; + + })(XMLNode); + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/XMLDocument.js b/node_modules/xmlbuilder/lib/XMLDocument.js new file mode 100644 index 0000000000000000000000000000000000000000..88df56c43445b9ec4e169300f6f9ac17a6e07f56 --- /dev/null +++ b/node_modules/xmlbuilder/lib/XMLDocument.js @@ -0,0 +1,242 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLDOMConfiguration, XMLDOMImplementation, XMLDocument, XMLNode, XMLStringWriter, XMLStringifier, isPlainObject, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + isPlainObject = require('./Utility').isPlainObject; + + XMLDOMImplementation = require('./XMLDOMImplementation'); + + XMLDOMConfiguration = require('./XMLDOMConfiguration'); + + XMLNode = require('./XMLNode'); + + NodeType = require('./NodeType'); + + XMLStringifier = require('./XMLStringifier'); + + XMLStringWriter = require('./XMLStringWriter'); + + module.exports = XMLDocument = (function(superClass) { + extend(XMLDocument, superClass); + + function XMLDocument(options) { + XMLDocument.__super__.constructor.call(this, null); + this.name = "#document"; + this.type = NodeType.Document; + this.documentURI = null; + this.domConfig = new XMLDOMConfiguration(); + options || (options = {}); + if (!options.writer) { + options.writer = new XMLStringWriter(); + } + this.options = options; + this.stringify = new XMLStringifier(options); + } + + Object.defineProperty(XMLDocument.prototype, 'implementation', { + value: new XMLDOMImplementation() + }); + + Object.defineProperty(XMLDocument.prototype, 'doctype', { + get: function() { + var child, i, len, ref; + ref = this.children; + for (i = 0, len = ref.length; i < len; i++) { + child = ref[i]; + if (child.type === NodeType.DocType) { + return child; + } + } + return null; + } + }); + + Object.defineProperty(XMLDocument.prototype, 'documentElement', { + get: function() { + return this.rootObject || null; + } + }); + + Object.defineProperty(XMLDocument.prototype, 'inputEncoding', { + get: function() { + return null; + } + }); + + Object.defineProperty(XMLDocument.prototype, 'strictErrorChecking', { + get: function() { + return false; + } + }); + + Object.defineProperty(XMLDocument.prototype, 'xmlEncoding', { + get: function() { + if (this.children.length !== 0 && this.children[0].type === NodeType.Declaration) { + return this.children[0].encoding; + } else { + return null; + } + } + }); + + Object.defineProperty(XMLDocument.prototype, 'xmlStandalone', { + get: function() { + if (this.children.length !== 0 && this.children[0].type === NodeType.Declaration) { + return this.children[0].standalone === 'yes'; + } else { + return false; + } + } + }); + + Object.defineProperty(XMLDocument.prototype, 'xmlVersion', { + get: function() { + if (this.children.length !== 0 && this.children[0].type === NodeType.Declaration) { + return this.children[0].version; + } else { + return "1.0"; + } + } + }); + + Object.defineProperty(XMLDocument.prototype, 'URL', { + get: function() { + return this.documentURI; + } + }); + + Object.defineProperty(XMLDocument.prototype, 'origin', { + get: function() { + return null; + } + }); + + Object.defineProperty(XMLDocument.prototype, 'compatMode', { + get: function() { + return null; + } + }); + + Object.defineProperty(XMLDocument.prototype, 'characterSet', { + get: function() { + return null; + } + }); + + Object.defineProperty(XMLDocument.prototype, 'contentType', { + get: function() { + return null; + } + }); + + XMLDocument.prototype.end = function(writer) { + var writerOptions; + writerOptions = {}; + if (!writer) { + writer = this.options.writer; + } else if (isPlainObject(writer)) { + writerOptions = writer; + writer = this.options.writer; + } + return writer.document(this, writer.filterOptions(writerOptions)); + }; + + XMLDocument.prototype.toString = function(options) { + return this.options.writer.document(this, this.options.writer.filterOptions(options)); + }; + + XMLDocument.prototype.createElement = function(tagName) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.createDocumentFragment = function() { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.createTextNode = function(data) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.createComment = function(data) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.createCDATASection = function(data) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.createProcessingInstruction = function(target, data) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.createAttribute = function(name) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.createEntityReference = function(name) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.getElementsByTagName = function(tagname) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.importNode = function(importedNode, deep) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.createElementNS = function(namespaceURI, qualifiedName) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.createAttributeNS = function(namespaceURI, qualifiedName) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.getElementsByTagNameNS = function(namespaceURI, localName) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.getElementById = function(elementId) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.adoptNode = function(source) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.normalizeDocument = function() { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.renameNode = function(node, namespaceURI, qualifiedName) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.getElementsByClassName = function(classNames) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.createEvent = function(eventInterface) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.createRange = function() { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.createNodeIterator = function(root, whatToShow, filter) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.createTreeWalker = function(root, whatToShow, filter) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + return XMLDocument; + + })(XMLNode); + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/XMLDocumentCB.js b/node_modules/xmlbuilder/lib/XMLDocumentCB.js new file mode 100644 index 0000000000000000000000000000000000000000..ca1aa1cf0389aeacbe1aa3eeb1a732623cc1c42c --- /dev/null +++ b/node_modules/xmlbuilder/lib/XMLDocumentCB.js @@ -0,0 +1,528 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, WriterState, XMLAttribute, XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDeclaration, XMLDocType, XMLDocument, XMLDocumentCB, XMLElement, XMLProcessingInstruction, XMLRaw, XMLStringWriter, XMLStringifier, XMLText, getValue, isFunction, isObject, isPlainObject, ref, + hasProp = {}.hasOwnProperty; + + ref = require('./Utility'), isObject = ref.isObject, isFunction = ref.isFunction, isPlainObject = ref.isPlainObject, getValue = ref.getValue; + + NodeType = require('./NodeType'); + + XMLDocument = require('./XMLDocument'); + + XMLElement = require('./XMLElement'); + + XMLCData = require('./XMLCData'); + + XMLComment = require('./XMLComment'); + + XMLRaw = require('./XMLRaw'); + + XMLText = require('./XMLText'); + + XMLProcessingInstruction = require('./XMLProcessingInstruction'); + + XMLDeclaration = require('./XMLDeclaration'); + + XMLDocType = require('./XMLDocType'); + + XMLDTDAttList = require('./XMLDTDAttList'); + + XMLDTDEntity = require('./XMLDTDEntity'); + + XMLDTDElement = require('./XMLDTDElement'); + + XMLDTDNotation = require('./XMLDTDNotation'); + + XMLAttribute = require('./XMLAttribute'); + + XMLStringifier = require('./XMLStringifier'); + + XMLStringWriter = require('./XMLStringWriter'); + + WriterState = require('./WriterState'); + + module.exports = XMLDocumentCB = (function() { + function XMLDocumentCB(options, onData, onEnd) { + var writerOptions; + this.name = "?xml"; + this.type = NodeType.Document; + options || (options = {}); + writerOptions = {}; + if (!options.writer) { + options.writer = new XMLStringWriter(); + } else if (isPlainObject(options.writer)) { + writerOptions = options.writer; + options.writer = new XMLStringWriter(); + } + this.options = options; + this.writer = options.writer; + this.writerOptions = this.writer.filterOptions(writerOptions); + this.stringify = new XMLStringifier(options); + this.onDataCallback = onData || function() {}; + this.onEndCallback = onEnd || function() {}; + this.currentNode = null; + this.currentLevel = -1; + this.openTags = {}; + this.documentStarted = false; + this.documentCompleted = false; + this.root = null; + } + + XMLDocumentCB.prototype.createChildNode = function(node) { + var att, attName, attributes, child, i, len, ref1, ref2; + switch (node.type) { + case NodeType.CData: + this.cdata(node.value); + break; + case NodeType.Comment: + this.comment(node.value); + break; + case NodeType.Element: + attributes = {}; + ref1 = node.attribs; + for (attName in ref1) { + if (!hasProp.call(ref1, attName)) continue; + att = ref1[attName]; + attributes[attName] = att.value; + } + this.node(node.name, attributes); + break; + case NodeType.Dummy: + this.dummy(); + break; + case NodeType.Raw: + this.raw(node.value); + break; + case NodeType.Text: + this.text(node.value); + break; + case NodeType.ProcessingInstruction: + this.instruction(node.target, node.value); + break; + default: + throw new Error("This XML node type is not supported in a JS object: " + node.constructor.name); + } + ref2 = node.children; + for (i = 0, len = ref2.length; i < len; i++) { + child = ref2[i]; + this.createChildNode(child); + if (child.type === NodeType.Element) { + this.up(); + } + } + return this; + }; + + XMLDocumentCB.prototype.dummy = function() { + return this; + }; + + XMLDocumentCB.prototype.node = function(name, attributes, text) { + var ref1; + if (name == null) { + throw new Error("Missing node name."); + } + if (this.root && this.currentLevel === -1) { + throw new Error("Document can only have one root node. " + this.debugInfo(name)); + } + this.openCurrent(); + name = getValue(name); + if (attributes == null) { + attributes = {}; + } + attributes = getValue(attributes); + if (!isObject(attributes)) { + ref1 = [attributes, text], text = ref1[0], attributes = ref1[1]; + } + this.currentNode = new XMLElement(this, name, attributes); + this.currentNode.children = false; + this.currentLevel++; + this.openTags[this.currentLevel] = this.currentNode; + if (text != null) { + this.text(text); + } + return this; + }; + + XMLDocumentCB.prototype.element = function(name, attributes, text) { + var child, i, len, oldValidationFlag, ref1, root; + if (this.currentNode && this.currentNode.type === NodeType.DocType) { + this.dtdElement.apply(this, arguments); + } else { + if (Array.isArray(name) || isObject(name) || isFunction(name)) { + oldValidationFlag = this.options.noValidation; + this.options.noValidation = true; + root = new XMLDocument(this.options).element('TEMP_ROOT'); + root.element(name); + this.options.noValidation = oldValidationFlag; + ref1 = root.children; + for (i = 0, len = ref1.length; i < len; i++) { + child = ref1[i]; + this.createChildNode(child); + if (child.type === NodeType.Element) { + this.up(); + } + } + } else { + this.node(name, attributes, text); + } + } + return this; + }; + + XMLDocumentCB.prototype.attribute = function(name, value) { + var attName, attValue; + if (!this.currentNode || this.currentNode.children) { + throw new Error("att() can only be used immediately after an ele() call in callback mode. " + this.debugInfo(name)); + } + if (name != null) { + name = getValue(name); + } + if (isObject(name)) { + for (attName in name) { + if (!hasProp.call(name, attName)) continue; + attValue = name[attName]; + this.attribute(attName, attValue); + } + } else { + if (isFunction(value)) { + value = value.apply(); + } + if (this.options.keepNullAttributes && (value == null)) { + this.currentNode.attribs[name] = new XMLAttribute(this, name, ""); + } else if (value != null) { + this.currentNode.attribs[name] = new XMLAttribute(this, name, value); + } + } + return this; + }; + + XMLDocumentCB.prototype.text = function(value) { + var node; + this.openCurrent(); + node = new XMLText(this, value); + this.onData(this.writer.text(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); + return this; + }; + + XMLDocumentCB.prototype.cdata = function(value) { + var node; + this.openCurrent(); + node = new XMLCData(this, value); + this.onData(this.writer.cdata(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); + return this; + }; + + XMLDocumentCB.prototype.comment = function(value) { + var node; + this.openCurrent(); + node = new XMLComment(this, value); + this.onData(this.writer.comment(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); + return this; + }; + + XMLDocumentCB.prototype.raw = function(value) { + var node; + this.openCurrent(); + node = new XMLRaw(this, value); + this.onData(this.writer.raw(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); + return this; + }; + + XMLDocumentCB.prototype.instruction = function(target, value) { + var i, insTarget, insValue, len, node; + this.openCurrent(); + if (target != null) { + target = getValue(target); + } + if (value != null) { + value = getValue(value); + } + if (Array.isArray(target)) { + for (i = 0, len = target.length; i < len; i++) { + insTarget = target[i]; + this.instruction(insTarget); + } + } else if (isObject(target)) { + for (insTarget in target) { + if (!hasProp.call(target, insTarget)) continue; + insValue = target[insTarget]; + this.instruction(insTarget, insValue); + } + } else { + if (isFunction(value)) { + value = value.apply(); + } + node = new XMLProcessingInstruction(this, target, value); + this.onData(this.writer.processingInstruction(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); + } + return this; + }; + + XMLDocumentCB.prototype.declaration = function(version, encoding, standalone) { + var node; + this.openCurrent(); + if (this.documentStarted) { + throw new Error("declaration() must be the first node."); + } + node = new XMLDeclaration(this, version, encoding, standalone); + this.onData(this.writer.declaration(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); + return this; + }; + + XMLDocumentCB.prototype.doctype = function(root, pubID, sysID) { + this.openCurrent(); + if (root == null) { + throw new Error("Missing root node name."); + } + if (this.root) { + throw new Error("dtd() must come before the root node."); + } + this.currentNode = new XMLDocType(this, pubID, sysID); + this.currentNode.rootNodeName = root; + this.currentNode.children = false; + this.currentLevel++; + this.openTags[this.currentLevel] = this.currentNode; + return this; + }; + + XMLDocumentCB.prototype.dtdElement = function(name, value) { + var node; + this.openCurrent(); + node = new XMLDTDElement(this, name, value); + this.onData(this.writer.dtdElement(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); + return this; + }; + + XMLDocumentCB.prototype.attList = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) { + var node; + this.openCurrent(); + node = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue); + this.onData(this.writer.dtdAttList(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); + return this; + }; + + XMLDocumentCB.prototype.entity = function(name, value) { + var node; + this.openCurrent(); + node = new XMLDTDEntity(this, false, name, value); + this.onData(this.writer.dtdEntity(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); + return this; + }; + + XMLDocumentCB.prototype.pEntity = function(name, value) { + var node; + this.openCurrent(); + node = new XMLDTDEntity(this, true, name, value); + this.onData(this.writer.dtdEntity(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); + return this; + }; + + XMLDocumentCB.prototype.notation = function(name, value) { + var node; + this.openCurrent(); + node = new XMLDTDNotation(this, name, value); + this.onData(this.writer.dtdNotation(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); + return this; + }; + + XMLDocumentCB.prototype.up = function() { + if (this.currentLevel < 0) { + throw new Error("The document node has no parent."); + } + if (this.currentNode) { + if (this.currentNode.children) { + this.closeNode(this.currentNode); + } else { + this.openNode(this.currentNode); + } + this.currentNode = null; + } else { + this.closeNode(this.openTags[this.currentLevel]); + } + delete this.openTags[this.currentLevel]; + this.currentLevel--; + return this; + }; + + XMLDocumentCB.prototype.end = function() { + while (this.currentLevel >= 0) { + this.up(); + } + return this.onEnd(); + }; + + XMLDocumentCB.prototype.openCurrent = function() { + if (this.currentNode) { + this.currentNode.children = true; + return this.openNode(this.currentNode); + } + }; + + XMLDocumentCB.prototype.openNode = function(node) { + var att, chunk, name, ref1; + if (!node.isOpen) { + if (!this.root && this.currentLevel === 0 && node.type === NodeType.Element) { + this.root = node; + } + chunk = ''; + if (node.type === NodeType.Element) { + this.writerOptions.state = WriterState.OpenTag; + chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + '<' + node.name; + ref1 = node.attribs; + for (name in ref1) { + if (!hasProp.call(ref1, name)) continue; + att = ref1[name]; + chunk += this.writer.attribute(att, this.writerOptions, this.currentLevel); + } + chunk += (node.children ? '>' : '/>') + this.writer.endline(node, this.writerOptions, this.currentLevel); + this.writerOptions.state = WriterState.InsideTag; + } else { + this.writerOptions.state = WriterState.OpenTag; + chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + ''; + } + chunk += this.writer.endline(node, this.writerOptions, this.currentLevel); + } + this.onData(chunk, this.currentLevel); + return node.isOpen = true; + } + }; + + XMLDocumentCB.prototype.closeNode = function(node) { + var chunk; + if (!node.isClosed) { + chunk = ''; + this.writerOptions.state = WriterState.CloseTag; + if (node.type === NodeType.Element) { + chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + '' + this.writer.endline(node, this.writerOptions, this.currentLevel); + } else { + chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + ']>' + this.writer.endline(node, this.writerOptions, this.currentLevel); + } + this.writerOptions.state = WriterState.None; + this.onData(chunk, this.currentLevel); + return node.isClosed = true; + } + }; + + XMLDocumentCB.prototype.onData = function(chunk, level) { + this.documentStarted = true; + return this.onDataCallback(chunk, level + 1); + }; + + XMLDocumentCB.prototype.onEnd = function() { + this.documentCompleted = true; + return this.onEndCallback(); + }; + + XMLDocumentCB.prototype.debugInfo = function(name) { + if (name == null) { + return ""; + } else { + return "node: <" + name + ">"; + } + }; + + XMLDocumentCB.prototype.ele = function() { + return this.element.apply(this, arguments); + }; + + XMLDocumentCB.prototype.nod = function(name, attributes, text) { + return this.node(name, attributes, text); + }; + + XMLDocumentCB.prototype.txt = function(value) { + return this.text(value); + }; + + XMLDocumentCB.prototype.dat = function(value) { + return this.cdata(value); + }; + + XMLDocumentCB.prototype.com = function(value) { + return this.comment(value); + }; + + XMLDocumentCB.prototype.ins = function(target, value) { + return this.instruction(target, value); + }; + + XMLDocumentCB.prototype.dec = function(version, encoding, standalone) { + return this.declaration(version, encoding, standalone); + }; + + XMLDocumentCB.prototype.dtd = function(root, pubID, sysID) { + return this.doctype(root, pubID, sysID); + }; + + XMLDocumentCB.prototype.e = function(name, attributes, text) { + return this.element(name, attributes, text); + }; + + XMLDocumentCB.prototype.n = function(name, attributes, text) { + return this.node(name, attributes, text); + }; + + XMLDocumentCB.prototype.t = function(value) { + return this.text(value); + }; + + XMLDocumentCB.prototype.d = function(value) { + return this.cdata(value); + }; + + XMLDocumentCB.prototype.c = function(value) { + return this.comment(value); + }; + + XMLDocumentCB.prototype.r = function(value) { + return this.raw(value); + }; + + XMLDocumentCB.prototype.i = function(target, value) { + return this.instruction(target, value); + }; + + XMLDocumentCB.prototype.att = function() { + if (this.currentNode && this.currentNode.type === NodeType.DocType) { + return this.attList.apply(this, arguments); + } else { + return this.attribute.apply(this, arguments); + } + }; + + XMLDocumentCB.prototype.a = function() { + if (this.currentNode && this.currentNode.type === NodeType.DocType) { + return this.attList.apply(this, arguments); + } else { + return this.attribute.apply(this, arguments); + } + }; + + XMLDocumentCB.prototype.ent = function(name, value) { + return this.entity(name, value); + }; + + XMLDocumentCB.prototype.pent = function(name, value) { + return this.pEntity(name, value); + }; + + XMLDocumentCB.prototype.not = function(name, value) { + return this.notation(name, value); + }; + + return XMLDocumentCB; + + })(); + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/XMLDocumentFragment.js b/node_modules/xmlbuilder/lib/XMLDocumentFragment.js new file mode 100644 index 0000000000000000000000000000000000000000..5d6039c410709e1a2814eb9a43491d9bddd5bae6 --- /dev/null +++ b/node_modules/xmlbuilder/lib/XMLDocumentFragment.js @@ -0,0 +1,24 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLDocumentFragment, XMLNode, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + XMLNode = require('./XMLNode'); + + NodeType = require('./NodeType'); + + module.exports = XMLDocumentFragment = (function(superClass) { + extend(XMLDocumentFragment, superClass); + + function XMLDocumentFragment() { + XMLDocumentFragment.__super__.constructor.call(this, null); + this.name = "#document-fragment"; + this.type = NodeType.DocumentFragment; + } + + return XMLDocumentFragment; + + })(XMLNode); + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/XMLDummy.js b/node_modules/xmlbuilder/lib/XMLDummy.js new file mode 100644 index 0000000000000000000000000000000000000000..b26083a3c88c5e95f11be277e041142618c71714 --- /dev/null +++ b/node_modules/xmlbuilder/lib/XMLDummy.js @@ -0,0 +1,31 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLDummy, XMLNode, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + XMLNode = require('./XMLNode'); + + NodeType = require('./NodeType'); + + module.exports = XMLDummy = (function(superClass) { + extend(XMLDummy, superClass); + + function XMLDummy(parent) { + XMLDummy.__super__.constructor.call(this, parent); + this.type = NodeType.Dummy; + } + + XMLDummy.prototype.clone = function() { + return Object.create(this); + }; + + XMLDummy.prototype.toString = function(options) { + return ''; + }; + + return XMLDummy; + + })(XMLNode); + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/XMLElement.js b/node_modules/xmlbuilder/lib/XMLElement.js new file mode 100644 index 0000000000000000000000000000000000000000..c165729950d20b29b798fb02638c03c3d4dfe529 --- /dev/null +++ b/node_modules/xmlbuilder/lib/XMLElement.js @@ -0,0 +1,298 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLAttribute, XMLElement, XMLNamedNodeMap, XMLNode, getValue, isFunction, isObject, ref, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + ref = require('./Utility'), isObject = ref.isObject, isFunction = ref.isFunction, getValue = ref.getValue; + + XMLNode = require('./XMLNode'); + + NodeType = require('./NodeType'); + + XMLAttribute = require('./XMLAttribute'); + + XMLNamedNodeMap = require('./XMLNamedNodeMap'); + + module.exports = XMLElement = (function(superClass) { + extend(XMLElement, superClass); + + function XMLElement(parent, name, attributes) { + var child, j, len, ref1; + XMLElement.__super__.constructor.call(this, parent); + if (name == null) { + throw new Error("Missing element name. " + this.debugInfo()); + } + this.name = this.stringify.name(name); + this.type = NodeType.Element; + this.attribs = {}; + this.schemaTypeInfo = null; + if (attributes != null) { + this.attribute(attributes); + } + if (parent.type === NodeType.Document) { + this.isRoot = true; + this.documentObject = parent; + parent.rootObject = this; + if (parent.children) { + ref1 = parent.children; + for (j = 0, len = ref1.length; j < len; j++) { + child = ref1[j]; + if (child.type === NodeType.DocType) { + child.name = this.name; + break; + } + } + } + } + } + + Object.defineProperty(XMLElement.prototype, 'tagName', { + get: function() { + return this.name; + } + }); + + Object.defineProperty(XMLElement.prototype, 'namespaceURI', { + get: function() { + return ''; + } + }); + + Object.defineProperty(XMLElement.prototype, 'prefix', { + get: function() { + return ''; + } + }); + + Object.defineProperty(XMLElement.prototype, 'localName', { + get: function() { + return this.name; + } + }); + + Object.defineProperty(XMLElement.prototype, 'id', { + get: function() { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + } + }); + + Object.defineProperty(XMLElement.prototype, 'className', { + get: function() { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + } + }); + + Object.defineProperty(XMLElement.prototype, 'classList', { + get: function() { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + } + }); + + Object.defineProperty(XMLElement.prototype, 'attributes', { + get: function() { + if (!this.attributeMap || !this.attributeMap.nodes) { + this.attributeMap = new XMLNamedNodeMap(this.attribs); + } + return this.attributeMap; + } + }); + + XMLElement.prototype.clone = function() { + var att, attName, clonedSelf, ref1; + clonedSelf = Object.create(this); + if (clonedSelf.isRoot) { + clonedSelf.documentObject = null; + } + clonedSelf.attribs = {}; + ref1 = this.attribs; + for (attName in ref1) { + if (!hasProp.call(ref1, attName)) continue; + att = ref1[attName]; + clonedSelf.attribs[attName] = att.clone(); + } + clonedSelf.children = []; + this.children.forEach(function(child) { + var clonedChild; + clonedChild = child.clone(); + clonedChild.parent = clonedSelf; + return clonedSelf.children.push(clonedChild); + }); + return clonedSelf; + }; + + XMLElement.prototype.attribute = function(name, value) { + var attName, attValue; + if (name != null) { + name = getValue(name); + } + if (isObject(name)) { + for (attName in name) { + if (!hasProp.call(name, attName)) continue; + attValue = name[attName]; + this.attribute(attName, attValue); + } + } else { + if (isFunction(value)) { + value = value.apply(); + } + if (this.options.keepNullAttributes && (value == null)) { + this.attribs[name] = new XMLAttribute(this, name, ""); + } else if (value != null) { + this.attribs[name] = new XMLAttribute(this, name, value); + } + } + return this; + }; + + XMLElement.prototype.removeAttribute = function(name) { + var attName, j, len; + if (name == null) { + throw new Error("Missing attribute name. " + this.debugInfo()); + } + name = getValue(name); + if (Array.isArray(name)) { + for (j = 0, len = name.length; j < len; j++) { + attName = name[j]; + delete this.attribs[attName]; + } + } else { + delete this.attribs[name]; + } + return this; + }; + + XMLElement.prototype.toString = function(options) { + return this.options.writer.element(this, this.options.writer.filterOptions(options)); + }; + + XMLElement.prototype.att = function(name, value) { + return this.attribute(name, value); + }; + + XMLElement.prototype.a = function(name, value) { + return this.attribute(name, value); + }; + + XMLElement.prototype.getAttribute = function(name) { + if (this.attribs.hasOwnProperty(name)) { + return this.attribs[name].value; + } else { + return null; + } + }; + + XMLElement.prototype.setAttribute = function(name, value) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.getAttributeNode = function(name) { + if (this.attribs.hasOwnProperty(name)) { + return this.attribs[name]; + } else { + return null; + } + }; + + XMLElement.prototype.setAttributeNode = function(newAttr) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.removeAttributeNode = function(oldAttr) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.getElementsByTagName = function(name) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.getAttributeNS = function(namespaceURI, localName) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.setAttributeNS = function(namespaceURI, qualifiedName, value) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.removeAttributeNS = function(namespaceURI, localName) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.getAttributeNodeNS = function(namespaceURI, localName) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.setAttributeNodeNS = function(newAttr) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.getElementsByTagNameNS = function(namespaceURI, localName) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.hasAttribute = function(name) { + return this.attribs.hasOwnProperty(name); + }; + + XMLElement.prototype.hasAttributeNS = function(namespaceURI, localName) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.setIdAttribute = function(name, isId) { + if (this.attribs.hasOwnProperty(name)) { + return this.attribs[name].isId; + } else { + return isId; + } + }; + + XMLElement.prototype.setIdAttributeNS = function(namespaceURI, localName, isId) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.setIdAttributeNode = function(idAttr, isId) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.getElementsByTagName = function(tagname) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.getElementsByTagNameNS = function(namespaceURI, localName) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.getElementsByClassName = function(classNames) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.isEqualNode = function(node) { + var i, j, ref1; + if (!XMLElement.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) { + return false; + } + if (node.namespaceURI !== this.namespaceURI) { + return false; + } + if (node.prefix !== this.prefix) { + return false; + } + if (node.localName !== this.localName) { + return false; + } + if (node.attribs.length !== this.attribs.length) { + return false; + } + for (i = j = 0, ref1 = this.attribs.length - 1; 0 <= ref1 ? j <= ref1 : j >= ref1; i = 0 <= ref1 ? ++j : --j) { + if (!this.attribs[i].isEqualNode(node.attribs[i])) { + return false; + } + } + return true; + }; + + return XMLElement; + + })(XMLNode); + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/XMLNamedNodeMap.js b/node_modules/xmlbuilder/lib/XMLNamedNodeMap.js new file mode 100644 index 0000000000000000000000000000000000000000..885402d098ea329c43594508aad9543ad80ec9e1 --- /dev/null +++ b/node_modules/xmlbuilder/lib/XMLNamedNodeMap.js @@ -0,0 +1,58 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var XMLNamedNodeMap; + + module.exports = XMLNamedNodeMap = (function() { + function XMLNamedNodeMap(nodes) { + this.nodes = nodes; + } + + Object.defineProperty(XMLNamedNodeMap.prototype, 'length', { + get: function() { + return Object.keys(this.nodes).length || 0; + } + }); + + XMLNamedNodeMap.prototype.clone = function() { + return this.nodes = null; + }; + + XMLNamedNodeMap.prototype.getNamedItem = function(name) { + return this.nodes[name]; + }; + + XMLNamedNodeMap.prototype.setNamedItem = function(node) { + var oldNode; + oldNode = this.nodes[node.nodeName]; + this.nodes[node.nodeName] = node; + return oldNode || null; + }; + + XMLNamedNodeMap.prototype.removeNamedItem = function(name) { + var oldNode; + oldNode = this.nodes[name]; + delete this.nodes[name]; + return oldNode || null; + }; + + XMLNamedNodeMap.prototype.item = function(index) { + return this.nodes[Object.keys(this.nodes)[index]] || null; + }; + + XMLNamedNodeMap.prototype.getNamedItemNS = function(namespaceURI, localName) { + throw new Error("This DOM method is not implemented."); + }; + + XMLNamedNodeMap.prototype.setNamedItemNS = function(node) { + throw new Error("This DOM method is not implemented."); + }; + + XMLNamedNodeMap.prototype.removeNamedItemNS = function(namespaceURI, localName) { + throw new Error("This DOM method is not implemented."); + }; + + return XMLNamedNodeMap; + + })(); + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/XMLNode.js b/node_modules/xmlbuilder/lib/XMLNode.js new file mode 100644 index 0000000000000000000000000000000000000000..e2c7bb76dec9a85c5a1713c2cafeb6c307406310 --- /dev/null +++ b/node_modules/xmlbuilder/lib/XMLNode.js @@ -0,0 +1,785 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var DocumentPosition, NodeType, XMLCData, XMLComment, XMLDeclaration, XMLDocType, XMLDummy, XMLElement, XMLNamedNodeMap, XMLNode, XMLNodeList, XMLProcessingInstruction, XMLRaw, XMLText, getValue, isEmpty, isFunction, isObject, ref1, + hasProp = {}.hasOwnProperty; + + ref1 = require('./Utility'), isObject = ref1.isObject, isFunction = ref1.isFunction, isEmpty = ref1.isEmpty, getValue = ref1.getValue; + + XMLElement = null; + + XMLCData = null; + + XMLComment = null; + + XMLDeclaration = null; + + XMLDocType = null; + + XMLRaw = null; + + XMLText = null; + + XMLProcessingInstruction = null; + + XMLDummy = null; + + NodeType = null; + + XMLNodeList = null; + + XMLNamedNodeMap = null; + + DocumentPosition = null; + + module.exports = XMLNode = (function() { + function XMLNode(parent1) { + this.parent = parent1; + if (this.parent) { + this.options = this.parent.options; + this.stringify = this.parent.stringify; + } + this.value = null; + this.children = []; + this.baseURI = null; + if (!XMLElement) { + XMLElement = require('./XMLElement'); + XMLCData = require('./XMLCData'); + XMLComment = require('./XMLComment'); + XMLDeclaration = require('./XMLDeclaration'); + XMLDocType = require('./XMLDocType'); + XMLRaw = require('./XMLRaw'); + XMLText = require('./XMLText'); + XMLProcessingInstruction = require('./XMLProcessingInstruction'); + XMLDummy = require('./XMLDummy'); + NodeType = require('./NodeType'); + XMLNodeList = require('./XMLNodeList'); + XMLNamedNodeMap = require('./XMLNamedNodeMap'); + DocumentPosition = require('./DocumentPosition'); + } + } + + Object.defineProperty(XMLNode.prototype, 'nodeName', { + get: function() { + return this.name; + } + }); + + Object.defineProperty(XMLNode.prototype, 'nodeType', { + get: function() { + return this.type; + } + }); + + Object.defineProperty(XMLNode.prototype, 'nodeValue', { + get: function() { + return this.value; + } + }); + + Object.defineProperty(XMLNode.prototype, 'parentNode', { + get: function() { + return this.parent; + } + }); + + Object.defineProperty(XMLNode.prototype, 'childNodes', { + get: function() { + if (!this.childNodeList || !this.childNodeList.nodes) { + this.childNodeList = new XMLNodeList(this.children); + } + return this.childNodeList; + } + }); + + Object.defineProperty(XMLNode.prototype, 'firstChild', { + get: function() { + return this.children[0] || null; + } + }); + + Object.defineProperty(XMLNode.prototype, 'lastChild', { + get: function() { + return this.children[this.children.length - 1] || null; + } + }); + + Object.defineProperty(XMLNode.prototype, 'previousSibling', { + get: function() { + var i; + i = this.parent.children.indexOf(this); + return this.parent.children[i - 1] || null; + } + }); + + Object.defineProperty(XMLNode.prototype, 'nextSibling', { + get: function() { + var i; + i = this.parent.children.indexOf(this); + return this.parent.children[i + 1] || null; + } + }); + + Object.defineProperty(XMLNode.prototype, 'ownerDocument', { + get: function() { + return this.document() || null; + } + }); + + Object.defineProperty(XMLNode.prototype, 'textContent', { + get: function() { + var child, j, len, ref2, str; + if (this.nodeType === NodeType.Element || this.nodeType === NodeType.DocumentFragment) { + str = ''; + ref2 = this.children; + for (j = 0, len = ref2.length; j < len; j++) { + child = ref2[j]; + if (child.textContent) { + str += child.textContent; + } + } + return str; + } else { + return null; + } + }, + set: function(value) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + } + }); + + XMLNode.prototype.setParent = function(parent) { + var child, j, len, ref2, results; + this.parent = parent; + if (parent) { + this.options = parent.options; + this.stringify = parent.stringify; + } + ref2 = this.children; + results = []; + for (j = 0, len = ref2.length; j < len; j++) { + child = ref2[j]; + results.push(child.setParent(this)); + } + return results; + }; + + XMLNode.prototype.element = function(name, attributes, text) { + var childNode, item, j, k, key, lastChild, len, len1, ref2, ref3, val; + lastChild = null; + if (attributes === null && (text == null)) { + ref2 = [{}, null], attributes = ref2[0], text = ref2[1]; + } + if (attributes == null) { + attributes = {}; + } + attributes = getValue(attributes); + if (!isObject(attributes)) { + ref3 = [attributes, text], text = ref3[0], attributes = ref3[1]; + } + if (name != null) { + name = getValue(name); + } + if (Array.isArray(name)) { + for (j = 0, len = name.length; j < len; j++) { + item = name[j]; + lastChild = this.element(item); + } + } else if (isFunction(name)) { + lastChild = this.element(name.apply()); + } else if (isObject(name)) { + for (key in name) { + if (!hasProp.call(name, key)) continue; + val = name[key]; + if (isFunction(val)) { + val = val.apply(); + } + if (!this.options.ignoreDecorators && this.stringify.convertAttKey && key.indexOf(this.stringify.convertAttKey) === 0) { + lastChild = this.attribute(key.substr(this.stringify.convertAttKey.length), val); + } else if (!this.options.separateArrayItems && Array.isArray(val) && isEmpty(val)) { + lastChild = this.dummy(); + } else if (isObject(val) && isEmpty(val)) { + lastChild = this.element(key); + } else if (!this.options.keepNullNodes && (val == null)) { + lastChild = this.dummy(); + } else if (!this.options.separateArrayItems && Array.isArray(val)) { + for (k = 0, len1 = val.length; k < len1; k++) { + item = val[k]; + childNode = {}; + childNode[key] = item; + lastChild = this.element(childNode); + } + } else if (isObject(val)) { + if (!this.options.ignoreDecorators && this.stringify.convertTextKey && key.indexOf(this.stringify.convertTextKey) === 0) { + lastChild = this.element(val); + } else { + lastChild = this.element(key); + lastChild.element(val); + } + } else { + lastChild = this.element(key, val); + } + } + } else if (!this.options.keepNullNodes && text === null) { + lastChild = this.dummy(); + } else { + if (!this.options.ignoreDecorators && this.stringify.convertTextKey && name.indexOf(this.stringify.convertTextKey) === 0) { + lastChild = this.text(text); + } else if (!this.options.ignoreDecorators && this.stringify.convertCDataKey && name.indexOf(this.stringify.convertCDataKey) === 0) { + lastChild = this.cdata(text); + } else if (!this.options.ignoreDecorators && this.stringify.convertCommentKey && name.indexOf(this.stringify.convertCommentKey) === 0) { + lastChild = this.comment(text); + } else if (!this.options.ignoreDecorators && this.stringify.convertRawKey && name.indexOf(this.stringify.convertRawKey) === 0) { + lastChild = this.raw(text); + } else if (!this.options.ignoreDecorators && this.stringify.convertPIKey && name.indexOf(this.stringify.convertPIKey) === 0) { + lastChild = this.instruction(name.substr(this.stringify.convertPIKey.length), text); + } else { + lastChild = this.node(name, attributes, text); + } + } + if (lastChild == null) { + throw new Error("Could not create any elements with: " + name + ". " + this.debugInfo()); + } + return lastChild; + }; + + XMLNode.prototype.insertBefore = function(name, attributes, text) { + var child, i, newChild, refChild, removed; + if (name != null ? name.type : void 0) { + newChild = name; + refChild = attributes; + newChild.setParent(this); + if (refChild) { + i = children.indexOf(refChild); + removed = children.splice(i); + children.push(newChild); + Array.prototype.push.apply(children, removed); + } else { + children.push(newChild); + } + return newChild; + } else { + if (this.isRoot) { + throw new Error("Cannot insert elements at root level. " + this.debugInfo(name)); + } + i = this.parent.children.indexOf(this); + removed = this.parent.children.splice(i); + child = this.parent.element(name, attributes, text); + Array.prototype.push.apply(this.parent.children, removed); + return child; + } + }; + + XMLNode.prototype.insertAfter = function(name, attributes, text) { + var child, i, removed; + if (this.isRoot) { + throw new Error("Cannot insert elements at root level. " + this.debugInfo(name)); + } + i = this.parent.children.indexOf(this); + removed = this.parent.children.splice(i + 1); + child = this.parent.element(name, attributes, text); + Array.prototype.push.apply(this.parent.children, removed); + return child; + }; + + XMLNode.prototype.remove = function() { + var i, ref2; + if (this.isRoot) { + throw new Error("Cannot remove the root element. " + this.debugInfo()); + } + i = this.parent.children.indexOf(this); + [].splice.apply(this.parent.children, [i, i - i + 1].concat(ref2 = [])), ref2; + return this.parent; + }; + + XMLNode.prototype.node = function(name, attributes, text) { + var child, ref2; + if (name != null) { + name = getValue(name); + } + attributes || (attributes = {}); + attributes = getValue(attributes); + if (!isObject(attributes)) { + ref2 = [attributes, text], text = ref2[0], attributes = ref2[1]; + } + child = new XMLElement(this, name, attributes); + if (text != null) { + child.text(text); + } + this.children.push(child); + return child; + }; + + XMLNode.prototype.text = function(value) { + var child; + if (isObject(value)) { + this.element(value); + } + child = new XMLText(this, value); + this.children.push(child); + return this; + }; + + XMLNode.prototype.cdata = function(value) { + var child; + child = new XMLCData(this, value); + this.children.push(child); + return this; + }; + + XMLNode.prototype.comment = function(value) { + var child; + child = new XMLComment(this, value); + this.children.push(child); + return this; + }; + + XMLNode.prototype.commentBefore = function(value) { + var child, i, removed; + i = this.parent.children.indexOf(this); + removed = this.parent.children.splice(i); + child = this.parent.comment(value); + Array.prototype.push.apply(this.parent.children, removed); + return this; + }; + + XMLNode.prototype.commentAfter = function(value) { + var child, i, removed; + i = this.parent.children.indexOf(this); + removed = this.parent.children.splice(i + 1); + child = this.parent.comment(value); + Array.prototype.push.apply(this.parent.children, removed); + return this; + }; + + XMLNode.prototype.raw = function(value) { + var child; + child = new XMLRaw(this, value); + this.children.push(child); + return this; + }; + + XMLNode.prototype.dummy = function() { + var child; + child = new XMLDummy(this); + return child; + }; + + XMLNode.prototype.instruction = function(target, value) { + var insTarget, insValue, instruction, j, len; + if (target != null) { + target = getValue(target); + } + if (value != null) { + value = getValue(value); + } + if (Array.isArray(target)) { + for (j = 0, len = target.length; j < len; j++) { + insTarget = target[j]; + this.instruction(insTarget); + } + } else if (isObject(target)) { + for (insTarget in target) { + if (!hasProp.call(target, insTarget)) continue; + insValue = target[insTarget]; + this.instruction(insTarget, insValue); + } + } else { + if (isFunction(value)) { + value = value.apply(); + } + instruction = new XMLProcessingInstruction(this, target, value); + this.children.push(instruction); + } + return this; + }; + + XMLNode.prototype.instructionBefore = function(target, value) { + var child, i, removed; + i = this.parent.children.indexOf(this); + removed = this.parent.children.splice(i); + child = this.parent.instruction(target, value); + Array.prototype.push.apply(this.parent.children, removed); + return this; + }; + + XMLNode.prototype.instructionAfter = function(target, value) { + var child, i, removed; + i = this.parent.children.indexOf(this); + removed = this.parent.children.splice(i + 1); + child = this.parent.instruction(target, value); + Array.prototype.push.apply(this.parent.children, removed); + return this; + }; + + XMLNode.prototype.declaration = function(version, encoding, standalone) { + var doc, xmldec; + doc = this.document(); + xmldec = new XMLDeclaration(doc, version, encoding, standalone); + if (doc.children.length === 0) { + doc.children.unshift(xmldec); + } else if (doc.children[0].type === NodeType.Declaration) { + doc.children[0] = xmldec; + } else { + doc.children.unshift(xmldec); + } + return doc.root() || doc; + }; + + XMLNode.prototype.dtd = function(pubID, sysID) { + var child, doc, doctype, i, j, k, len, len1, ref2, ref3; + doc = this.document(); + doctype = new XMLDocType(doc, pubID, sysID); + ref2 = doc.children; + for (i = j = 0, len = ref2.length; j < len; i = ++j) { + child = ref2[i]; + if (child.type === NodeType.DocType) { + doc.children[i] = doctype; + return doctype; + } + } + ref3 = doc.children; + for (i = k = 0, len1 = ref3.length; k < len1; i = ++k) { + child = ref3[i]; + if (child.isRoot) { + doc.children.splice(i, 0, doctype); + return doctype; + } + } + doc.children.push(doctype); + return doctype; + }; + + XMLNode.prototype.up = function() { + if (this.isRoot) { + throw new Error("The root node has no parent. Use doc() if you need to get the document object."); + } + return this.parent; + }; + + XMLNode.prototype.root = function() { + var node; + node = this; + while (node) { + if (node.type === NodeType.Document) { + return node.rootObject; + } else if (node.isRoot) { + return node; + } else { + node = node.parent; + } + } + }; + + XMLNode.prototype.document = function() { + var node; + node = this; + while (node) { + if (node.type === NodeType.Document) { + return node; + } else { + node = node.parent; + } + } + }; + + XMLNode.prototype.end = function(options) { + return this.document().end(options); + }; + + XMLNode.prototype.prev = function() { + var i; + i = this.parent.children.indexOf(this); + if (i < 1) { + throw new Error("Already at the first node. " + this.debugInfo()); + } + return this.parent.children[i - 1]; + }; + + XMLNode.prototype.next = function() { + var i; + i = this.parent.children.indexOf(this); + if (i === -1 || i === this.parent.children.length - 1) { + throw new Error("Already at the last node. " + this.debugInfo()); + } + return this.parent.children[i + 1]; + }; + + XMLNode.prototype.importDocument = function(doc) { + var clonedRoot; + clonedRoot = doc.root().clone(); + clonedRoot.parent = this; + clonedRoot.isRoot = false; + this.children.push(clonedRoot); + return this; + }; + + XMLNode.prototype.debugInfo = function(name) { + var ref2, ref3; + name = name || this.name; + if ((name == null) && !((ref2 = this.parent) != null ? ref2.name : void 0)) { + return ""; + } else if (name == null) { + return "parent: <" + this.parent.name + ">"; + } else if (!((ref3 = this.parent) != null ? ref3.name : void 0)) { + return "node: <" + name + ">"; + } else { + return "node: <" + name + ">, parent: <" + this.parent.name + ">"; + } + }; + + XMLNode.prototype.ele = function(name, attributes, text) { + return this.element(name, attributes, text); + }; + + XMLNode.prototype.nod = function(name, attributes, text) { + return this.node(name, attributes, text); + }; + + XMLNode.prototype.txt = function(value) { + return this.text(value); + }; + + XMLNode.prototype.dat = function(value) { + return this.cdata(value); + }; + + XMLNode.prototype.com = function(value) { + return this.comment(value); + }; + + XMLNode.prototype.ins = function(target, value) { + return this.instruction(target, value); + }; + + XMLNode.prototype.doc = function() { + return this.document(); + }; + + XMLNode.prototype.dec = function(version, encoding, standalone) { + return this.declaration(version, encoding, standalone); + }; + + XMLNode.prototype.e = function(name, attributes, text) { + return this.element(name, attributes, text); + }; + + XMLNode.prototype.n = function(name, attributes, text) { + return this.node(name, attributes, text); + }; + + XMLNode.prototype.t = function(value) { + return this.text(value); + }; + + XMLNode.prototype.d = function(value) { + return this.cdata(value); + }; + + XMLNode.prototype.c = function(value) { + return this.comment(value); + }; + + XMLNode.prototype.r = function(value) { + return this.raw(value); + }; + + XMLNode.prototype.i = function(target, value) { + return this.instruction(target, value); + }; + + XMLNode.prototype.u = function() { + return this.up(); + }; + + XMLNode.prototype.importXMLBuilder = function(doc) { + return this.importDocument(doc); + }; + + XMLNode.prototype.replaceChild = function(newChild, oldChild) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLNode.prototype.removeChild = function(oldChild) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLNode.prototype.appendChild = function(newChild) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLNode.prototype.hasChildNodes = function() { + return this.children.length !== 0; + }; + + XMLNode.prototype.cloneNode = function(deep) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLNode.prototype.normalize = function() { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLNode.prototype.isSupported = function(feature, version) { + return true; + }; + + XMLNode.prototype.hasAttributes = function() { + return this.attribs.length !== 0; + }; + + XMLNode.prototype.compareDocumentPosition = function(other) { + var ref, res; + ref = this; + if (ref === other) { + return 0; + } else if (this.document() !== other.document()) { + res = DocumentPosition.Disconnected | DocumentPosition.ImplementationSpecific; + if (Math.random() < 0.5) { + res |= DocumentPosition.Preceding; + } else { + res |= DocumentPosition.Following; + } + return res; + } else if (ref.isAncestor(other)) { + return DocumentPosition.Contains | DocumentPosition.Preceding; + } else if (ref.isDescendant(other)) { + return DocumentPosition.Contains | DocumentPosition.Following; + } else if (ref.isPreceding(other)) { + return DocumentPosition.Preceding; + } else { + return DocumentPosition.Following; + } + }; + + XMLNode.prototype.isSameNode = function(other) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLNode.prototype.lookupPrefix = function(namespaceURI) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLNode.prototype.isDefaultNamespace = function(namespaceURI) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLNode.prototype.lookupNamespaceURI = function(prefix) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLNode.prototype.isEqualNode = function(node) { + var i, j, ref2; + if (node.nodeType !== this.nodeType) { + return false; + } + if (node.children.length !== this.children.length) { + return false; + } + for (i = j = 0, ref2 = this.children.length - 1; 0 <= ref2 ? j <= ref2 : j >= ref2; i = 0 <= ref2 ? ++j : --j) { + if (!this.children[i].isEqualNode(node.children[i])) { + return false; + } + } + return true; + }; + + XMLNode.prototype.getFeature = function(feature, version) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLNode.prototype.setUserData = function(key, data, handler) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLNode.prototype.getUserData = function(key) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLNode.prototype.contains = function(other) { + if (!other) { + return false; + } + return other === this || this.isDescendant(other); + }; + + XMLNode.prototype.isDescendant = function(node) { + var child, isDescendantChild, j, len, ref2; + ref2 = this.children; + for (j = 0, len = ref2.length; j < len; j++) { + child = ref2[j]; + if (node === child) { + return true; + } + isDescendantChild = child.isDescendant(node); + if (isDescendantChild) { + return true; + } + } + return false; + }; + + XMLNode.prototype.isAncestor = function(node) { + return node.isDescendant(this); + }; + + XMLNode.prototype.isPreceding = function(node) { + var nodePos, thisPos; + nodePos = this.treePosition(node); + thisPos = this.treePosition(this); + if (nodePos === -1 || thisPos === -1) { + return false; + } else { + return nodePos < thisPos; + } + }; + + XMLNode.prototype.isFollowing = function(node) { + var nodePos, thisPos; + nodePos = this.treePosition(node); + thisPos = this.treePosition(this); + if (nodePos === -1 || thisPos === -1) { + return false; + } else { + return nodePos > thisPos; + } + }; + + XMLNode.prototype.treePosition = function(node) { + var found, pos; + pos = 0; + found = false; + this.foreachTreeNode(this.document(), function(childNode) { + pos++; + if (!found && childNode === node) { + return found = true; + } + }); + if (found) { + return pos; + } else { + return -1; + } + }; + + XMLNode.prototype.foreachTreeNode = function(node, func) { + var child, j, len, ref2, res; + node || (node = this.document()); + ref2 = node.children; + for (j = 0, len = ref2.length; j < len; j++) { + child = ref2[j]; + if (res = func(child)) { + return res; + } else { + res = this.foreachTreeNode(child, func); + if (res) { + return res; + } + } + } + }; + + return XMLNode; + + })(); + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/XMLNodeFilter.js b/node_modules/xmlbuilder/lib/XMLNodeFilter.js new file mode 100644 index 0000000000000000000000000000000000000000..ce32fd590bbe01331cbc938c76ab1c8837c7cf52 --- /dev/null +++ b/node_modules/xmlbuilder/lib/XMLNodeFilter.js @@ -0,0 +1,48 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var XMLNodeFilter; + + module.exports = XMLNodeFilter = (function() { + function XMLNodeFilter() {} + + XMLNodeFilter.prototype.FilterAccept = 1; + + XMLNodeFilter.prototype.FilterReject = 2; + + XMLNodeFilter.prototype.FilterSkip = 3; + + XMLNodeFilter.prototype.ShowAll = 0xffffffff; + + XMLNodeFilter.prototype.ShowElement = 0x1; + + XMLNodeFilter.prototype.ShowAttribute = 0x2; + + XMLNodeFilter.prototype.ShowText = 0x4; + + XMLNodeFilter.prototype.ShowCDataSection = 0x8; + + XMLNodeFilter.prototype.ShowEntityReference = 0x10; + + XMLNodeFilter.prototype.ShowEntity = 0x20; + + XMLNodeFilter.prototype.ShowProcessingInstruction = 0x40; + + XMLNodeFilter.prototype.ShowComment = 0x80; + + XMLNodeFilter.prototype.ShowDocument = 0x100; + + XMLNodeFilter.prototype.ShowDocumentType = 0x200; + + XMLNodeFilter.prototype.ShowDocumentFragment = 0x400; + + XMLNodeFilter.prototype.ShowNotation = 0x800; + + XMLNodeFilter.prototype.acceptNode = function(node) { + throw new Error("This DOM method is not implemented."); + }; + + return XMLNodeFilter; + + })(); + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/XMLNodeList.js b/node_modules/xmlbuilder/lib/XMLNodeList.js new file mode 100644 index 0000000000000000000000000000000000000000..3414a3e41fc491714fc22afc32b08143ae566e23 --- /dev/null +++ b/node_modules/xmlbuilder/lib/XMLNodeList.js @@ -0,0 +1,28 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var XMLNodeList; + + module.exports = XMLNodeList = (function() { + function XMLNodeList(nodes) { + this.nodes = nodes; + } + + Object.defineProperty(XMLNodeList.prototype, 'length', { + get: function() { + return this.nodes.length || 0; + } + }); + + XMLNodeList.prototype.clone = function() { + return this.nodes = null; + }; + + XMLNodeList.prototype.item = function(index) { + return this.nodes[index] || null; + }; + + return XMLNodeList; + + })(); + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/XMLProcessingInstruction.js b/node_modules/xmlbuilder/lib/XMLProcessingInstruction.js new file mode 100644 index 0000000000000000000000000000000000000000..d4333d46ff4cd95037b4e3b38c87df6d4229a97f --- /dev/null +++ b/node_modules/xmlbuilder/lib/XMLProcessingInstruction.js @@ -0,0 +1,49 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLCharacterData, XMLProcessingInstruction, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + NodeType = require('./NodeType'); + + XMLCharacterData = require('./XMLCharacterData'); + + module.exports = XMLProcessingInstruction = (function(superClass) { + extend(XMLProcessingInstruction, superClass); + + function XMLProcessingInstruction(parent, target, value) { + XMLProcessingInstruction.__super__.constructor.call(this, parent); + if (target == null) { + throw new Error("Missing instruction target. " + this.debugInfo()); + } + this.type = NodeType.ProcessingInstruction; + this.target = this.stringify.insTarget(target); + this.name = this.target; + if (value) { + this.value = this.stringify.insValue(value); + } + } + + XMLProcessingInstruction.prototype.clone = function() { + return Object.create(this); + }; + + XMLProcessingInstruction.prototype.toString = function(options) { + return this.options.writer.processingInstruction(this, this.options.writer.filterOptions(options)); + }; + + XMLProcessingInstruction.prototype.isEqualNode = function(node) { + if (!XMLProcessingInstruction.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) { + return false; + } + if (node.target !== this.target) { + return false; + } + return true; + }; + + return XMLProcessingInstruction; + + })(XMLCharacterData); + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/XMLRaw.js b/node_modules/xmlbuilder/lib/XMLRaw.js new file mode 100644 index 0000000000000000000000000000000000000000..b5928502d4fe74d6c4ac8a8e7ea11ac264ec37f9 --- /dev/null +++ b/node_modules/xmlbuilder/lib/XMLRaw.js @@ -0,0 +1,35 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLNode, XMLRaw, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + NodeType = require('./NodeType'); + + XMLNode = require('./XMLNode'); + + module.exports = XMLRaw = (function(superClass) { + extend(XMLRaw, superClass); + + function XMLRaw(parent, text) { + XMLRaw.__super__.constructor.call(this, parent); + if (text == null) { + throw new Error("Missing raw text. " + this.debugInfo()); + } + this.type = NodeType.Raw; + this.value = this.stringify.raw(text); + } + + XMLRaw.prototype.clone = function() { + return Object.create(this); + }; + + XMLRaw.prototype.toString = function(options) { + return this.options.writer.raw(this, this.options.writer.filterOptions(options)); + }; + + return XMLRaw; + + })(XMLNode); + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/XMLStreamWriter.js b/node_modules/xmlbuilder/lib/XMLStreamWriter.js new file mode 100644 index 0000000000000000000000000000000000000000..159dc6b6e11c3fc1dad9990c718e8055a28a1f30 --- /dev/null +++ b/node_modules/xmlbuilder/lib/XMLStreamWriter.js @@ -0,0 +1,176 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, WriterState, XMLStreamWriter, XMLWriterBase, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + NodeType = require('./NodeType'); + + XMLWriterBase = require('./XMLWriterBase'); + + WriterState = require('./WriterState'); + + module.exports = XMLStreamWriter = (function(superClass) { + extend(XMLStreamWriter, superClass); + + function XMLStreamWriter(stream, options) { + this.stream = stream; + XMLStreamWriter.__super__.constructor.call(this, options); + } + + XMLStreamWriter.prototype.endline = function(node, options, level) { + if (node.isLastRootNode && options.state === WriterState.CloseTag) { + return ''; + } else { + return XMLStreamWriter.__super__.endline.call(this, node, options, level); + } + }; + + XMLStreamWriter.prototype.document = function(doc, options) { + var child, i, j, k, len, len1, ref, ref1, results; + ref = doc.children; + for (i = j = 0, len = ref.length; j < len; i = ++j) { + child = ref[i]; + child.isLastRootNode = i === doc.children.length - 1; + } + options = this.filterOptions(options); + ref1 = doc.children; + results = []; + for (k = 0, len1 = ref1.length; k < len1; k++) { + child = ref1[k]; + results.push(this.writeChildNode(child, options, 0)); + } + return results; + }; + + XMLStreamWriter.prototype.attribute = function(att, options, level) { + return this.stream.write(XMLStreamWriter.__super__.attribute.call(this, att, options, level)); + }; + + XMLStreamWriter.prototype.cdata = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.cdata.call(this, node, options, level)); + }; + + XMLStreamWriter.prototype.comment = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.comment.call(this, node, options, level)); + }; + + XMLStreamWriter.prototype.declaration = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.declaration.call(this, node, options, level)); + }; + + XMLStreamWriter.prototype.docType = function(node, options, level) { + var child, j, len, ref; + level || (level = 0); + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + this.stream.write(this.indent(node, options, level)); + this.stream.write(' 0) { + this.stream.write(' ['); + this.stream.write(this.endline(node, options, level)); + options.state = WriterState.InsideTag; + ref = node.children; + for (j = 0, len = ref.length; j < len; j++) { + child = ref[j]; + this.writeChildNode(child, options, level + 1); + } + options.state = WriterState.CloseTag; + this.stream.write(']'); + } + options.state = WriterState.CloseTag; + this.stream.write(options.spaceBeforeSlash + '>'); + this.stream.write(this.endline(node, options, level)); + options.state = WriterState.None; + return this.closeNode(node, options, level); + }; + + XMLStreamWriter.prototype.element = function(node, options, level) { + var att, child, childNodeCount, firstChildNode, j, len, name, prettySuppressed, ref, ref1; + level || (level = 0); + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + this.stream.write(this.indent(node, options, level) + '<' + node.name); + ref = node.attribs; + for (name in ref) { + if (!hasProp.call(ref, name)) continue; + att = ref[name]; + this.attribute(att, options, level); + } + childNodeCount = node.children.length; + firstChildNode = childNodeCount === 0 ? null : node.children[0]; + if (childNodeCount === 0 || node.children.every(function(e) { + return (e.type === NodeType.Text || e.type === NodeType.Raw) && e.value === ''; + })) { + if (options.allowEmpty) { + this.stream.write('>'); + options.state = WriterState.CloseTag; + this.stream.write(''); + } else { + options.state = WriterState.CloseTag; + this.stream.write(options.spaceBeforeSlash + '/>'); + } + } else if (options.pretty && childNodeCount === 1 && (firstChildNode.type === NodeType.Text || firstChildNode.type === NodeType.Raw) && (firstChildNode.value != null)) { + this.stream.write('>'); + options.state = WriterState.InsideTag; + options.suppressPrettyCount++; + prettySuppressed = true; + this.writeChildNode(firstChildNode, options, level + 1); + options.suppressPrettyCount--; + prettySuppressed = false; + options.state = WriterState.CloseTag; + this.stream.write(''); + } else { + this.stream.write('>' + this.endline(node, options, level)); + options.state = WriterState.InsideTag; + ref1 = node.children; + for (j = 0, len = ref1.length; j < len; j++) { + child = ref1[j]; + this.writeChildNode(child, options, level + 1); + } + options.state = WriterState.CloseTag; + this.stream.write(this.indent(node, options, level) + ''); + } + this.stream.write(this.endline(node, options, level)); + options.state = WriterState.None; + return this.closeNode(node, options, level); + }; + + XMLStreamWriter.prototype.processingInstruction = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.processingInstruction.call(this, node, options, level)); + }; + + XMLStreamWriter.prototype.raw = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.raw.call(this, node, options, level)); + }; + + XMLStreamWriter.prototype.text = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.text.call(this, node, options, level)); + }; + + XMLStreamWriter.prototype.dtdAttList = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.dtdAttList.call(this, node, options, level)); + }; + + XMLStreamWriter.prototype.dtdElement = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.dtdElement.call(this, node, options, level)); + }; + + XMLStreamWriter.prototype.dtdEntity = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.dtdEntity.call(this, node, options, level)); + }; + + XMLStreamWriter.prototype.dtdNotation = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.dtdNotation.call(this, node, options, level)); + }; + + return XMLStreamWriter; + + })(XMLWriterBase); + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/XMLStringWriter.js b/node_modules/xmlbuilder/lib/XMLStringWriter.js new file mode 100644 index 0000000000000000000000000000000000000000..7187017052b832fe0466450e5c5e65d46c4bc237 --- /dev/null +++ b/node_modules/xmlbuilder/lib/XMLStringWriter.js @@ -0,0 +1,35 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var XMLStringWriter, XMLWriterBase, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + XMLWriterBase = require('./XMLWriterBase'); + + module.exports = XMLStringWriter = (function(superClass) { + extend(XMLStringWriter, superClass); + + function XMLStringWriter(options) { + XMLStringWriter.__super__.constructor.call(this, options); + } + + XMLStringWriter.prototype.document = function(doc, options) { + var child, i, len, r, ref; + options = this.filterOptions(options); + r = ''; + ref = doc.children; + for (i = 0, len = ref.length; i < len; i++) { + child = ref[i]; + r += this.writeChildNode(child, options, 0); + } + if (options.pretty && r.slice(-options.newline.length) === options.newline) { + r = r.slice(0, -options.newline.length); + } + return r; + }; + + return XMLStringWriter; + + })(XMLWriterBase); + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/XMLStringifier.js b/node_modules/xmlbuilder/lib/XMLStringifier.js new file mode 100644 index 0000000000000000000000000000000000000000..a39475c1b25191c86c0d3ba76165a044a5314c97 --- /dev/null +++ b/node_modules/xmlbuilder/lib/XMLStringifier.js @@ -0,0 +1,240 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var XMLStringifier, + bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, + hasProp = {}.hasOwnProperty; + + module.exports = XMLStringifier = (function() { + function XMLStringifier(options) { + this.assertLegalName = bind(this.assertLegalName, this); + this.assertLegalChar = bind(this.assertLegalChar, this); + var key, ref, value; + options || (options = {}); + this.options = options; + if (!this.options.version) { + this.options.version = '1.0'; + } + ref = options.stringify || {}; + for (key in ref) { + if (!hasProp.call(ref, key)) continue; + value = ref[key]; + this[key] = value; + } + } + + XMLStringifier.prototype.name = function(val) { + if (this.options.noValidation) { + return val; + } + return this.assertLegalName('' + val || ''); + }; + + XMLStringifier.prototype.text = function(val) { + if (this.options.noValidation) { + return val; + } + return this.assertLegalChar(this.textEscape('' + val || '')); + }; + + XMLStringifier.prototype.cdata = function(val) { + if (this.options.noValidation) { + return val; + } + val = '' + val || ''; + val = val.replace(']]>', ']]]]>'); + return this.assertLegalChar(val); + }; + + XMLStringifier.prototype.comment = function(val) { + if (this.options.noValidation) { + return val; + } + val = '' + val || ''; + if (val.match(/--/)) { + throw new Error("Comment text cannot contain double-hypen: " + val); + } + return this.assertLegalChar(val); + }; + + XMLStringifier.prototype.raw = function(val) { + if (this.options.noValidation) { + return val; + } + return '' + val || ''; + }; + + XMLStringifier.prototype.attValue = function(val) { + if (this.options.noValidation) { + return val; + } + return this.assertLegalChar(this.attEscape(val = '' + val || '')); + }; + + XMLStringifier.prototype.insTarget = function(val) { + if (this.options.noValidation) { + return val; + } + return this.assertLegalChar('' + val || ''); + }; + + XMLStringifier.prototype.insValue = function(val) { + if (this.options.noValidation) { + return val; + } + val = '' + val || ''; + if (val.match(/\?>/)) { + throw new Error("Invalid processing instruction value: " + val); + } + return this.assertLegalChar(val); + }; + + XMLStringifier.prototype.xmlVersion = function(val) { + if (this.options.noValidation) { + return val; + } + val = '' + val || ''; + if (!val.match(/1\.[0-9]+/)) { + throw new Error("Invalid version number: " + val); + } + return val; + }; + + XMLStringifier.prototype.xmlEncoding = function(val) { + if (this.options.noValidation) { + return val; + } + val = '' + val || ''; + if (!val.match(/^[A-Za-z](?:[A-Za-z0-9._-])*$/)) { + throw new Error("Invalid encoding: " + val); + } + return this.assertLegalChar(val); + }; + + XMLStringifier.prototype.xmlStandalone = function(val) { + if (this.options.noValidation) { + return val; + } + if (val) { + return "yes"; + } else { + return "no"; + } + }; + + XMLStringifier.prototype.dtdPubID = function(val) { + if (this.options.noValidation) { + return val; + } + return this.assertLegalChar('' + val || ''); + }; + + XMLStringifier.prototype.dtdSysID = function(val) { + if (this.options.noValidation) { + return val; + } + return this.assertLegalChar('' + val || ''); + }; + + XMLStringifier.prototype.dtdElementValue = function(val) { + if (this.options.noValidation) { + return val; + } + return this.assertLegalChar('' + val || ''); + }; + + XMLStringifier.prototype.dtdAttType = function(val) { + if (this.options.noValidation) { + return val; + } + return this.assertLegalChar('' + val || ''); + }; + + XMLStringifier.prototype.dtdAttDefault = function(val) { + if (this.options.noValidation) { + return val; + } + return this.assertLegalChar('' + val || ''); + }; + + XMLStringifier.prototype.dtdEntityValue = function(val) { + if (this.options.noValidation) { + return val; + } + return this.assertLegalChar('' + val || ''); + }; + + XMLStringifier.prototype.dtdNData = function(val) { + if (this.options.noValidation) { + return val; + } + return this.assertLegalChar('' + val || ''); + }; + + XMLStringifier.prototype.convertAttKey = '@'; + + XMLStringifier.prototype.convertPIKey = '?'; + + XMLStringifier.prototype.convertTextKey = '#text'; + + XMLStringifier.prototype.convertCDataKey = '#cdata'; + + XMLStringifier.prototype.convertCommentKey = '#comment'; + + XMLStringifier.prototype.convertRawKey = '#raw'; + + XMLStringifier.prototype.assertLegalChar = function(str) { + var regex, res; + if (this.options.noValidation) { + return str; + } + regex = ''; + if (this.options.version === '1.0') { + regex = /[\0-\x08\x0B\f\x0E-\x1F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; + if (res = str.match(regex)) { + throw new Error("Invalid character in string: " + str + " at index " + res.index); + } + } else if (this.options.version === '1.1') { + regex = /[\0\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; + if (res = str.match(regex)) { + throw new Error("Invalid character in string: " + str + " at index " + res.index); + } + } + return str; + }; + + XMLStringifier.prototype.assertLegalName = function(str) { + var regex; + if (this.options.noValidation) { + return str; + } + this.assertLegalChar(str); + regex = /^([:A-Z_a-z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])([\x2D\.0-:A-Z_a-z\xB7\xC0-\xD6\xD8-\xF6\xF8-\u037D\u037F-\u1FFF\u200C\u200D\u203F\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])*$/; + if (!str.match(regex)) { + throw new Error("Invalid character in name"); + } + return str; + }; + + XMLStringifier.prototype.textEscape = function(str) { + var ampregex; + if (this.options.noValidation) { + return str; + } + ampregex = this.options.noDoubleEncoding ? /(?!&\S+;)&/g : /&/g; + return str.replace(ampregex, '&').replace(//g, '>').replace(/\r/g, ' '); + }; + + XMLStringifier.prototype.attEscape = function(str) { + var ampregex; + if (this.options.noValidation) { + return str; + } + ampregex = this.options.noDoubleEncoding ? /(?!&\S+;)&/g : /&/g; + return str.replace(ampregex, '&').replace(/ 0) { + return new Array(indentLevel).join(options.indent); + } + } + return ''; + }; + + XMLWriterBase.prototype.endline = function(node, options, level) { + if (!options.pretty || options.suppressPrettyCount) { + return ''; + } else { + return options.newline; + } + }; + + XMLWriterBase.prototype.attribute = function(att, options, level) { + var r; + this.openAttribute(att, options, level); + r = ' ' + att.name + '="' + att.value + '"'; + this.closeAttribute(att, options, level); + return r; + }; + + XMLWriterBase.prototype.cdata = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level) + '' + this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.comment = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level) + '' + this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.declaration = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level) + ''; + r += this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.docType = function(node, options, level) { + var child, i, len, r, ref; + level || (level = 0); + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level); + r += ' 0) { + r += ' ['; + r += this.endline(node, options, level); + options.state = WriterState.InsideTag; + ref = node.children; + for (i = 0, len = ref.length; i < len; i++) { + child = ref[i]; + r += this.writeChildNode(child, options, level + 1); + } + options.state = WriterState.CloseTag; + r += ']'; + } + options.state = WriterState.CloseTag; + r += options.spaceBeforeSlash + '>'; + r += this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.element = function(node, options, level) { + var att, child, childNodeCount, firstChildNode, i, j, len, len1, name, prettySuppressed, r, ref, ref1, ref2; + level || (level = 0); + prettySuppressed = false; + r = ''; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r += this.indent(node, options, level) + '<' + node.name; + ref = node.attribs; + for (name in ref) { + if (!hasProp.call(ref, name)) continue; + att = ref[name]; + r += this.attribute(att, options, level); + } + childNodeCount = node.children.length; + firstChildNode = childNodeCount === 0 ? null : node.children[0]; + if (childNodeCount === 0 || node.children.every(function(e) { + return (e.type === NodeType.Text || e.type === NodeType.Raw) && e.value === ''; + })) { + if (options.allowEmpty) { + r += '>'; + options.state = WriterState.CloseTag; + r += '' + this.endline(node, options, level); + } else { + options.state = WriterState.CloseTag; + r += options.spaceBeforeSlash + '/>' + this.endline(node, options, level); + } + } else if (options.pretty && childNodeCount === 1 && (firstChildNode.type === NodeType.Text || firstChildNode.type === NodeType.Raw) && (firstChildNode.value != null)) { + r += '>'; + options.state = WriterState.InsideTag; + options.suppressPrettyCount++; + prettySuppressed = true; + r += this.writeChildNode(firstChildNode, options, level + 1); + options.suppressPrettyCount--; + prettySuppressed = false; + options.state = WriterState.CloseTag; + r += '' + this.endline(node, options, level); + } else { + if (options.dontPrettyTextNodes) { + ref1 = node.children; + for (i = 0, len = ref1.length; i < len; i++) { + child = ref1[i]; + if ((child.type === NodeType.Text || child.type === NodeType.Raw) && (child.value != null)) { + options.suppressPrettyCount++; + prettySuppressed = true; + break; + } + } + } + r += '>' + this.endline(node, options, level); + options.state = WriterState.InsideTag; + ref2 = node.children; + for (j = 0, len1 = ref2.length; j < len1; j++) { + child = ref2[j]; + r += this.writeChildNode(child, options, level + 1); + } + options.state = WriterState.CloseTag; + r += this.indent(node, options, level) + ''; + if (prettySuppressed) { + options.suppressPrettyCount--; + } + r += this.endline(node, options, level); + options.state = WriterState.None; + } + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.writeChildNode = function(node, options, level) { + switch (node.type) { + case NodeType.CData: + return this.cdata(node, options, level); + case NodeType.Comment: + return this.comment(node, options, level); + case NodeType.Element: + return this.element(node, options, level); + case NodeType.Raw: + return this.raw(node, options, level); + case NodeType.Text: + return this.text(node, options, level); + case NodeType.ProcessingInstruction: + return this.processingInstruction(node, options, level); + case NodeType.Dummy: + return ''; + case NodeType.Declaration: + return this.declaration(node, options, level); + case NodeType.DocType: + return this.docType(node, options, level); + case NodeType.AttributeDeclaration: + return this.dtdAttList(node, options, level); + case NodeType.ElementDeclaration: + return this.dtdElement(node, options, level); + case NodeType.EntityDeclaration: + return this.dtdEntity(node, options, level); + case NodeType.NotationDeclaration: + return this.dtdNotation(node, options, level); + default: + throw new Error("Unknown XML node type: " + node.constructor.name); + } + }; + + XMLWriterBase.prototype.processingInstruction = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level) + ''; + r += this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.raw = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level); + options.state = WriterState.InsideTag; + r += node.value; + options.state = WriterState.CloseTag; + r += this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.text = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level); + options.state = WriterState.InsideTag; + r += node.value; + options.state = WriterState.CloseTag; + r += this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.dtdAttList = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level) + '' + this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.dtdElement = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level) + '' + this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.dtdEntity = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level) + '' + this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.dtdNotation = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level) + '' + this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.openNode = function(node, options, level) {}; + + XMLWriterBase.prototype.closeNode = function(node, options, level) {}; + + XMLWriterBase.prototype.openAttribute = function(att, options, level) {}; + + XMLWriterBase.prototype.closeAttribute = function(att, options, level) {}; + + return XMLWriterBase; + + })(); + +}).call(this); diff --git a/node_modules/xmlbuilder/lib/index.js b/node_modules/xmlbuilder/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b1ed2636ac2b2d13c6a054ede4722ba124211232 --- /dev/null +++ b/node_modules/xmlbuilder/lib/index.js @@ -0,0 +1,65 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, WriterState, XMLDOMImplementation, XMLDocument, XMLDocumentCB, XMLStreamWriter, XMLStringWriter, assign, isFunction, ref; + + ref = require('./Utility'), assign = ref.assign, isFunction = ref.isFunction; + + XMLDOMImplementation = require('./XMLDOMImplementation'); + + XMLDocument = require('./XMLDocument'); + + XMLDocumentCB = require('./XMLDocumentCB'); + + XMLStringWriter = require('./XMLStringWriter'); + + XMLStreamWriter = require('./XMLStreamWriter'); + + NodeType = require('./NodeType'); + + WriterState = require('./WriterState'); + + module.exports.create = function(name, xmldec, doctype, options) { + var doc, root; + if (name == null) { + throw new Error("Root element needs a name."); + } + options = assign({}, xmldec, doctype, options); + doc = new XMLDocument(options); + root = doc.element(name); + if (!options.headless) { + doc.declaration(options); + if ((options.pubID != null) || (options.sysID != null)) { + doc.dtd(options); + } + } + return root; + }; + + module.exports.begin = function(options, onData, onEnd) { + var ref1; + if (isFunction(options)) { + ref1 = [options, onData], onData = ref1[0], onEnd = ref1[1]; + options = {}; + } + if (onData) { + return new XMLDocumentCB(options, onData, onEnd); + } else { + return new XMLDocument(options); + } + }; + + module.exports.stringWriter = function(options) { + return new XMLStringWriter(options); + }; + + module.exports.streamWriter = function(stream, options) { + return new XMLStreamWriter(stream, options); + }; + + module.exports.implementation = new XMLDOMImplementation(); + + module.exports.nodeType = NodeType; + + module.exports.writerState = WriterState; + +}).call(this); diff --git a/node_modules/xmlbuilder/package.json b/node_modules/xmlbuilder/package.json new file mode 100644 index 0000000000000000000000000000000000000000..512cd97716458d8a41403fa1f5525b41ebcca1ec --- /dev/null +++ b/node_modules/xmlbuilder/package.json @@ -0,0 +1,39 @@ +{ + "name": "xmlbuilder", + "version": "11.0.1", + "keywords": [ + "xml", + "xmlbuilder" + ], + "homepage": "http://github.com/oozcitak/xmlbuilder-js", + "description": "An XML builder for node.js", + "author": "Ozgur Ozcitak ", + "contributors": [], + "license": "MIT", + "repository": { + "type": "git", + "url": "git://github.com/oozcitak/xmlbuilder-js.git" + }, + "bugs": { + "url": "http://github.com/oozcitak/xmlbuilder-js/issues" + }, + "main": "./lib/index", + "typings": "./typings/index.d.ts", + "engines": { + "node": ">=4.0" + }, + "dependencies": {}, + "devDependencies": { + "coffeescript": "1.*", + "mocha": "*", + "coffee-coverage": "2.*", + "istanbul": "*", + "coveralls": "*", + "xpath": "*" + }, + "scripts": { + "prepublishOnly": "coffee -co lib src", + "postpublish": "rm -rf lib", + "test": "mocha \"test/**/*.coffee\" && istanbul report text lcov" + } +} diff --git a/node_modules/xmlbuilder/typings/index.d.ts b/node_modules/xmlbuilder/typings/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3e0e5b0a7ccbc956cbb5bffb27939e9ec96d9403 --- /dev/null +++ b/node_modules/xmlbuilder/typings/index.d.ts @@ -0,0 +1,153 @@ +// Type definitions for xmlbuilder +// Project: https://github.com/oozcitak/xmlbuilder-js +// Definitions by: Wallymathieu +// : GaikwadPratik +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = xmlbuilder; + +declare namespace xmlbuilder { + + class XMLDocType { + clone(): XMLDocType; + element(name: string, value?: Object): XMLDocType; + attList(elementName: string, attributeName: string, attributeType: string, defaultValueType?: string, defaultValue?: any): XMLDocType; + entity(name: string, value: any): XMLDocType; + pEntity(name: string, value: any): XMLDocType; + notation(name: string, value: any): XMLDocType; + cdata(value: string): XMLDocType; + comment(value: string): XMLDocType; + instruction(target: string, value: any): XMLDocType; + root(): XMLDocType; + document(): any; + toString(options?: XMLToStringOptions, level?: Number): string; + + ele(name: string, value?: Object): XMLDocType; + att(elementName: string, attributeName: string, attributeType: string, defaultValueType?: string, defaultValue?: any): XMLDocType; + ent(name: string, value: any): XMLDocType; + pent(name: string, value: any): XMLDocType; + not(name: string, value: any): XMLDocType; + dat(value: string): XMLDocType; + com(value: string): XMLDocType; + ins(target: string, value: any): XMLDocType; + up(): XMLDocType; + doc(): any; + } + + class XMLElementOrXMLNode { + // XMLElement: + clone(): XMLElementOrXMLNode; + attribute(name: any, value?: any): XMLElementOrXMLNode; + att(name: any, value?: any): XMLElementOrXMLNode; + removeAttribute(name: string): XMLElementOrXMLNode; + instruction(target: string, value: any): XMLElementOrXMLNode; + instruction(array: Array): XMLElementOrXMLNode; + instruction(obj: Object): XMLElementOrXMLNode; + ins(target: string, value: any): XMLElementOrXMLNode; + ins(array: Array): XMLElementOrXMLNode; + ins(obj: Object): XMLElementOrXMLNode; + a(name: any, value?: any): XMLElementOrXMLNode; + i(target: string, value: any): XMLElementOrXMLNode; + i(array: Array): XMLElementOrXMLNode; + i(obj: Object): XMLElementOrXMLNode; + toString(options?: XMLToStringOptions, level?: Number): string; + // XMLNode: + element(name: any, attributes?: Object, text?: any): XMLElementOrXMLNode; + ele(name: any, attributes?: Object, text?: any): XMLElementOrXMLNode; + insertBefore(name: any, attributes?: Object, text?: any): XMLElementOrXMLNode; + insertAfter(name: any, attributes?: Object, text?: any): XMLElementOrXMLNode; + remove(): XMLElementOrXMLNode; + node(name: any, attributes?: Object, text?: any): XMLElementOrXMLNode; + text(value: string): XMLElementOrXMLNode; + cdata(value: string): XMLElementOrXMLNode; + comment(value: string): XMLElementOrXMLNode; + raw(value: string): XMLElementOrXMLNode; + declaration(version: string, encoding: string, standalone: boolean): XMLElementOrXMLNode; + doctype(pubID: string, sysID: string): XMLDocType; + up(): XMLElementOrXMLNode; + importDocument(input: XMLElementOrXMLNode): XMLElementOrXMLNode; + root(): XMLElementOrXMLNode; + document(): any; + end(options?: XMLEndOptions): string; + prev(): XMLElementOrXMLNode; + next(): XMLElementOrXMLNode; + nod(name: any, attributes?: Object, text?: any): XMLElementOrXMLNode; + txt(value: string): XMLElementOrXMLNode; + dat(value: string): XMLElementOrXMLNode; + com(value: string): XMLElementOrXMLNode; + doc(): XMLElementOrXMLNode; + dec(version: string, encoding: string, standalone: boolean): XMLElementOrXMLNode; + dtd(pubID: string, sysID: string): XMLDocType; + e(name: any, attributes?: Object, text?: any): XMLElementOrXMLNode; + n(name: any, attributes?: Object, text?: any): XMLElementOrXMLNode; + t(value: string): XMLElementOrXMLNode; + d(value: string): XMLElementOrXMLNode; + c(value: string): XMLElementOrXMLNode; + r(value: string): XMLElementOrXMLNode; + u(): XMLElementOrXMLNode; + } + + interface XMLDec { + version?: string; + encoding?: string; + standalone?: boolean; + } + + interface XMLDtd { + pubID?: string; + sysID?: string; + } + + interface XMLStringifier { + [x: string]: ((v: any) => string) | string; + } + + interface XMLWriter { + [x: string]: ((e: XMLElementOrXMLNode, options: WriterOptions, level?: number) => void); + } + + interface XMLCreateOptions { + headless?: boolean; + keepNullNodes?: boolean; + keepNullAttributes?: boolean; + ignoreDecorators?: boolean; + separateArrayItems?: boolean; + noDoubleEncoding?: boolean; + stringify?: XMLStringifier; + } + + interface XMLToStringOptions { + pretty?: boolean; + indent?: string; + offset?: number; + newline?: string; + allowEmpty?: boolean; + spacebeforeslash?: string; + } + + interface XMLEndOptions extends XMLToStringOptions { + writer?: XMLWriter; + } + + interface WriterOptions { + pretty?: boolean; + indent?: string; + newline?: string; + offset?: number; + allowEmpty?: boolean; + dontPrettyTextNodes?: boolean; + spaceBeforeSlash?: string | boolean; + user? :any; + state?: WriterState; + } + + enum WriterState { + None = 0, + OpenTag = 1, + InsideTag = 2, + CloseTag = 3 + } + + function create(nameOrObjSpec: string | { [name: string]: Object }, xmldecOrOptions?: XMLDec | XMLCreateOptions, doctypeOrOptions?: XMLDtd | XMLCreateOptions, options?: XMLCreateOptions): XMLElementOrXMLNode; + function begin(): XMLElementOrXMLNode; +} \ No newline at end of file diff --git a/node_modules/xmlchars/LICENSE b/node_modules/xmlchars/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ec8c59ca75ac44886aae008936916616b8738368 --- /dev/null +++ b/node_modules/xmlchars/LICENSE @@ -0,0 +1,18 @@ +Copyright Louis-Dominique Dubeau and contributors to xmlchars + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/xmlchars/README.md b/node_modules/xmlchars/README.md new file mode 100644 index 0000000000000000000000000000000000000000..609ff04588e81a63b0985ee9b94aa93cde569c28 --- /dev/null +++ b/node_modules/xmlchars/README.md @@ -0,0 +1,33 @@ +Utilities for determining whether characters belong to character classes defined +by the XML specs. + +## Organization + +It used to be that the library was contained in a single file and you could just +import/require/what-have-you the `xmlchars` module. However, that setup did not +work well for people who cared about code optimization. Importing `xmlchars` +meant importing *all* of the library and because of the way the code was +generated there was no way to shake the resulting code tree. + +Different modules cover different standards. At the time this documentation was +last updated, we had: + +* `xmlchars/xml/1.0/ed5` which covers XML 1.0 edition 5. +* `xmlchars/xml/1.0/ed4` which covers XML 1.0 edition 4. +* `xmlchars/xml/1.1/ed2` which covers XML 1.0 edition 2. +* `xmlchars/xmlns/1.0/ed3` which covers XML Namespaces 1.0 edition 3. + +## Features + +The "things" each module contains can be categorized as follows: + +1. "Fragments": these are parts and pieces of regular expressions that +correspond to the productions defined in the standard that the module +covers. You'd use these to *build regular expressions*. + +2. Regular expressions that correspond to the productions defined in the +standard that the module covers. + +3. Lists: these are arrays of characters that correspond to the productions. + +4. Functions that test code points to verify whether they fit a production. diff --git a/node_modules/xmlchars/package.json b/node_modules/xmlchars/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ff709a193e740262d5721860b0884790778d13d4 --- /dev/null +++ b/node_modules/xmlchars/package.json @@ -0,0 +1,51 @@ +{ + "name": "xmlchars", + "version": "2.2.0", + "description": "Utilities for determining if characters belong to character classes defined by the XML specs.", + "keywords": [ + "XML", + "validation" + ], + "main": "xmlchars.js", + "types": "xmlchars.d.ts", + "repository": "https://github.com/lddubeau/xmlchars.git", + "author": "Louis-Dominique Dubeau ", + "license": "MIT", + "devDependencies": { + "@commitlint/cli": "^8.1.0", + "@commitlint/config-angular": "^8.1.0", + "@types/chai": "^4.2.1", + "@types/mocha": "^5.2.7", + "chai": "^4.2.0", + "conventional-changelog-cli": "^2.0.23", + "husky": "^3.0.5", + "mocha": "^6.2.0", + "ts-node": "^8.3.0", + "tslint": "^5.19.0", + "tslint-config-lddubeau": "^4.1.0", + "typescript": "^3.6.2" + }, + "scripts": { + "copy": "cp README.md LICENSE build/dist && sed -e'/\"private\": true/d' package.json > build/dist/package.json", + "build": "tsc && npm run copy", + "pretest": "npm run build", + "test": "mocha", + "posttest": "tslint -p tsconfig.json && tslint -p test/tsconfig.json", + "prepack": "node -e 'require(\"assert\")(!require(\"./package.json\").private)'", + "test-install": "npm run test && (test_dir=build/install_dir; rm -rf $test_dir; mkdir -p $test_dir/node_modules; packname=`npm run xmlchars:pack --silent`; (cd $test_dir; npm install ../$packname); rm -rf $test_dir)", + "xmlchars:pack": "cd build/dist/ && (packname=`npm pack --silent`; mv $packname ..; echo $packname)", + "prepublishOnly": "node -e 'require(\"assert\")(!require(\"./package.json\").private)'", + "xmlchars:publish": "npm run test-install && (cd build/dist && npm publish)", + "preversion": "npm run test-install", + "version": "conventional-changelog -p angular -i CHANGELOG.md -s && git add CHANGELOG.md", + "postversion": "npm run xmlchars:publish", + "postpublish": "git push origin --follow-tags", + "clean": "rm -rf build" + }, + "dependencies": {}, + "husky": { + "hooks": { + "commit-msg": "commitlint -e $HUSKY_GIT_PARAMS" + } + } +} diff --git a/node_modules/xmlchars/xml/1.0/ed4.d.ts b/node_modules/xmlchars/xml/1.0/ed4.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8d21792f351e344e25f8ba471bec75a9b2e95e6d --- /dev/null +++ b/node_modules/xmlchars/xml/1.0/ed4.d.ts @@ -0,0 +1,31 @@ +/** + * Character classes and associated utilities for the 4th edition of XML 1.0. + * + * These are deprecated in the 5th edition but some of the standards related to + * XML 1.0 (e.g. XML Schema 1.0) refer to these. So they are still generally + * useful. + * + * @author Louis-Dominique Dubeau + * @license MIT + * @copyright Louis-Dominique Dubeau + */ +export declare const CHAR = "\t\n\r -\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF"; +export declare const S = " \t\r\n"; +export declare const BASE_CHAR = "A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0100-\u0131\u0134-\u013E\u0141-\u0148\u014A-\u017E\u0180-\u01C3\u01CD-\u01F0\u01F4-\u01F5\u01FA-\u0217\u0250-\u02A8\u02BB-\u02C1\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03CE\u03D0-\u03D6\u03DA\u03DC\u03DE\u03E0\u03E2-\u03F3\u0401-\u040C\u040E-\u044F\u0451-\u045C\u045E-\u0481\u0490-\u04C4\u04C7-\u04C8\u04CB-\u04CC\u04D0-\u04EB\u04EE-\u04F5\u04F8-\u04F9\u0531-\u0556\u0559\u0561-\u0586\u05D0-\u05EA\u05F0-\u05F2\u0621-\u063A\u0641-\u064A\u0671-\u06B7\u06BA-\u06BE\u06C0-\u06CE\u06D0-\u06D3\u06D5\u06E5-\u06E6\u0905-\u0939\u093D\u0958-\u0961\u0985-\u098C\u098F-\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09DC-\u09DD\u09DF-\u09E1\u09F0-\u09F1\u0A05-\u0A0A\u0A0F-\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32-\u0A33\u0A35-\u0A36\u0A38-\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8B\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2-\u0AB3\u0AB5-\u0AB9\u0ABD\u0AE0\u0B05-\u0B0C\u0B0F-\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32-\u0B33\u0B36-\u0B39\u0B3D\u0B5C-\u0B5D\u0B5F-\u0B61\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99-\u0B9A\u0B9C\u0B9E-\u0B9F\u0BA3-\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB5\u0BB7-\u0BB9\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C60-\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CDE\u0CE0-\u0CE1\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D28\u0D2A-\u0D39\u0D60-\u0D61\u0E01-\u0E2E\u0E30\u0E32-\u0E33\u0E40-\u0E45\u0E81-\u0E82\u0E84\u0E87-\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA-\u0EAB\u0EAD-\u0EAE\u0EB0\u0EB2-\u0EB3\u0EBD\u0EC0-\u0EC4\u0F40-\u0F47\u0F49-\u0F69\u10A0-\u10C5\u10D0-\u10F6\u1100\u1102-\u1103\u1105-\u1107\u1109\u110B-\u110C\u110E-\u1112\u113C\u113E\u1140\u114C\u114E\u1150\u1154-\u1155\u1159\u115F-\u1161\u1163\u1165\u1167\u1169\u116D-\u116E\u1172-\u1173\u1175\u119E\u11A8\u11AB\u11AE-\u11AF\u11B7-\u11B8\u11BA\u11BC-\u11C2\u11EB\u11F0\u11F9\u1E00-\u1E9B\u1EA0-\u1EF9\u1F00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2126\u212A-\u212B\u212E\u2180-\u2182\u3041-\u3094\u30A1-\u30FA\u3105-\u312C\uAC00-\uD7A3"; +export declare const IDEOGRAPHIC = "\u4E00-\u9FA5\u3007\u3021-\u3029"; +export declare const COMBINING_CHAR = "\u0300-\u0345\u0360-\u0361\u0483-\u0486\u0591-\u05A1\u05A3-\u05B9\u05BB-\u05BD\u05BF\u05C1-\u05C2\u05C4\u064B-\u0652\u0670\u06D6-\u06DC\u06DD-\u06DF\u06E0-\u06E4\u06E7-\u06E8\u06EA-\u06ED\u0901-\u0903\u093C\u093E-\u094C\u094D\u0951-\u0954\u0962-\u0963\u0981-\u0983\u09BC\u09BE\u09BF\u09C0-\u09C4\u09C7-\u09C8\u09CB-\u09CD\u09D7\u09E2-\u09E3\u0A02\u0A3C\u0A3E\u0A3F\u0A40-\u0A42\u0A47-\u0A48\u0A4B-\u0A4D\u0A70-\u0A71\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0B01-\u0B03\u0B3C\u0B3E-\u0B43\u0B47-\u0B48\u0B4B-\u0B4D\u0B56-\u0B57\u0B82-\u0B83\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C01-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55-\u0C56\u0C82-\u0C83\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5-\u0CD6\u0D02-\u0D03\u0D3E-\u0D43\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB-\u0EBC\u0EC8-\u0ECD\u0F18-\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86-\u0F8B\u0F90-\u0F95\u0F97\u0F99-\u0FAD\u0FB1-\u0FB7\u0FB9\u20D0-\u20DC\u20E1\u302A-\u302F\u3099\u309A"; +export declare const DIGIT = "0-9\u0660-\u0669\u06F0-\u06F9\u0966-\u096F\u09E6-\u09EF\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0BE7-\u0BEF\u0C66-\u0C6F\u0CE6-\u0CEF\u0D66-\u0D6F\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F29"; +export declare const EXTENDER = "\u00B7\u02D0\u02D1\u0387\u0640\u0E46\u0EC6\u3005\u3031-\u3035\u309D-\u309E\u30FC-\u30FE"; +export declare const LETTER: string; +export declare const NAME_CHAR: string; +export declare const CHAR_RE: RegExp; +export declare const S_RE: RegExp; +export declare const BASE_CHAR_RE: RegExp; +export declare const IDEOGRAPHIC_RE: RegExp; +export declare const COMBINING_CHAR_RE: RegExp; +export declare const DIGIT_RE: RegExp; +export declare const EXTENDER_RE: RegExp; +export declare const LETTER_RE: RegExp; +export declare const NAME_CHAR_RE: RegExp; +export declare const NAME_RE: RegExp; +export declare const NMTOKEN_RE: RegExp; diff --git a/node_modules/xmlchars/xml/1.0/ed4.js b/node_modules/xmlchars/xml/1.0/ed4.js new file mode 100644 index 0000000000000000000000000000000000000000..ba11516af632aaf2f0249bd43bce15681901400d --- /dev/null +++ b/node_modules/xmlchars/xml/1.0/ed4.js @@ -0,0 +1,44 @@ +"use strict"; +/** + * Character classes and associated utilities for the 4th edition of XML 1.0. + * + * These are deprecated in the 5th edition but some of the standards related to + * XML 1.0 (e.g. XML Schema 1.0) refer to these. So they are still generally + * useful. + * + * @author Louis-Dominique Dubeau + * @license MIT + * @copyright Louis-Dominique Dubeau + */ +Object.defineProperty(exports, "__esModule", { value: true }); +// +// Fragments. +// +exports.CHAR = "\t\n\r -\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF"; +exports.S = " \t\r\n"; +// tslint:disable-next-line:missing-jsdoc max-line-length +exports.BASE_CHAR = "A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0100-\u0131\u0134-\u013E\u0141-\u0148\u014A-\u017E\u0180-\u01C3\u01CD-\u01F0\u01F4-\u01F5\u01FA-\u0217\u0250-\u02A8\u02BB-\u02C1\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03CE\u03D0-\u03D6\u03DA\u03DC\u03DE\u03E0\u03E2-\u03F3\u0401-\u040C\u040E-\u044F\u0451-\u045C\u045E-\u0481\u0490-\u04C4\u04C7-\u04C8\u04CB-\u04CC\u04D0-\u04EB\u04EE-\u04F5\u04F8-\u04F9\u0531-\u0556\u0559\u0561-\u0586\u05D0-\u05EA\u05F0-\u05F2\u0621-\u063A\u0641-\u064A\u0671-\u06B7\u06BA-\u06BE\u06C0-\u06CE\u06D0-\u06D3\u06D5\u06E5-\u06E6\u0905-\u0939\u093D\u0958-\u0961\u0985-\u098C\u098F-\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09DC-\u09DD\u09DF-\u09E1\u09F0-\u09F1\u0A05-\u0A0A\u0A0F-\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32-\u0A33\u0A35-\u0A36\u0A38-\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8B\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2-\u0AB3\u0AB5-\u0AB9\u0ABD\u0AE0\u0B05-\u0B0C\u0B0F-\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32-\u0B33\u0B36-\u0B39\u0B3D\u0B5C-\u0B5D\u0B5F-\u0B61\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99-\u0B9A\u0B9C\u0B9E-\u0B9F\u0BA3-\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB5\u0BB7-\u0BB9\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C60-\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CDE\u0CE0-\u0CE1\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D28\u0D2A-\u0D39\u0D60-\u0D61\u0E01-\u0E2E\u0E30\u0E32-\u0E33\u0E40-\u0E45\u0E81-\u0E82\u0E84\u0E87-\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA-\u0EAB\u0EAD-\u0EAE\u0EB0\u0EB2-\u0EB3\u0EBD\u0EC0-\u0EC4\u0F40-\u0F47\u0F49-\u0F69\u10A0-\u10C5\u10D0-\u10F6\u1100\u1102-\u1103\u1105-\u1107\u1109\u110B-\u110C\u110E-\u1112\u113C\u113E\u1140\u114C\u114E\u1150\u1154-\u1155\u1159\u115F-\u1161\u1163\u1165\u1167\u1169\u116D-\u116E\u1172-\u1173\u1175\u119E\u11A8\u11AB\u11AE-\u11AF\u11B7-\u11B8\u11BA\u11BC-\u11C2\u11EB\u11F0\u11F9\u1E00-\u1E9B\u1EA0-\u1EF9\u1F00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2126\u212A-\u212B\u212E\u2180-\u2182\u3041-\u3094\u30A1-\u30FA\u3105-\u312C\uAC00-\uD7A3"; +exports.IDEOGRAPHIC = "\u4E00-\u9FA5\u3007\u3021-\u3029"; +// tslint:disable-next-line:missing-jsdoc max-line-length +exports.COMBINING_CHAR = "\u0300-\u0345\u0360-\u0361\u0483-\u0486\u0591-\u05A1\u05A3-\u05B9\u05BB-\u05BD\u05BF\u05C1-\u05C2\u05C4\u064B-\u0652\u0670\u06D6-\u06DC\u06DD-\u06DF\u06E0-\u06E4\u06E7-\u06E8\u06EA-\u06ED\u0901-\u0903\u093C\u093E-\u094C\u094D\u0951-\u0954\u0962-\u0963\u0981-\u0983\u09BC\u09BE\u09BF\u09C0-\u09C4\u09C7-\u09C8\u09CB-\u09CD\u09D7\u09E2-\u09E3\u0A02\u0A3C\u0A3E\u0A3F\u0A40-\u0A42\u0A47-\u0A48\u0A4B-\u0A4D\u0A70-\u0A71\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0B01-\u0B03\u0B3C\u0B3E-\u0B43\u0B47-\u0B48\u0B4B-\u0B4D\u0B56-\u0B57\u0B82-\u0B83\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C01-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55-\u0C56\u0C82-\u0C83\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5-\u0CD6\u0D02-\u0D03\u0D3E-\u0D43\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB-\u0EBC\u0EC8-\u0ECD\u0F18-\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86-\u0F8B\u0F90-\u0F95\u0F97\u0F99-\u0FAD\u0FB1-\u0FB7\u0FB9\u20D0-\u20DC\u20E1\u302A-\u302F\u3099\u309A"; +// tslint:disable-next-line:missing-jsdoc max-line-length +exports.DIGIT = "0-9\u0660-\u0669\u06F0-\u06F9\u0966-\u096F\u09E6-\u09EF\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0BE7-\u0BEF\u0C66-\u0C6F\u0CE6-\u0CEF\u0D66-\u0D6F\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F29"; +// tslint:disable-next-line:missing-jsdoc max-line-length +exports.EXTENDER = "\u00B7\u02D0\u02D1\u0387\u0640\u0E46\u0EC6\u3005\u3031-\u3035\u309D-\u309E\u30FC-\u30FE"; +exports.LETTER = exports.BASE_CHAR + exports.IDEOGRAPHIC; +exports.NAME_CHAR = "-" + exports.LETTER + exports.DIGIT + "._:" + exports.COMBINING_CHAR + exports.EXTENDER; +// +// Regular expressions. +// +exports.CHAR_RE = new RegExp("^[" + exports.CHAR + "]$", "u"); +exports.S_RE = new RegExp("^[" + exports.S + "]+$", "u"); +exports.BASE_CHAR_RE = new RegExp("^[" + exports.BASE_CHAR + "]$", "u"); +exports.IDEOGRAPHIC_RE = new RegExp("^[" + exports.IDEOGRAPHIC + "]$", "u"); +exports.COMBINING_CHAR_RE = new RegExp("^[" + exports.COMBINING_CHAR + "]$", "u"); +exports.DIGIT_RE = new RegExp("^[" + exports.DIGIT + "]$", "u"); +exports.EXTENDER_RE = new RegExp("^[" + exports.EXTENDER + "]$", "u"); +exports.LETTER_RE = new RegExp("^[" + exports.LETTER + "]$", "u"); +exports.NAME_CHAR_RE = new RegExp("^[" + exports.NAME_CHAR + "]$", "u"); +exports.NAME_RE = new RegExp("^[" + exports.LETTER + "_:][" + exports.NAME_CHAR + "]*$", "u"); +exports.NMTOKEN_RE = new RegExp("^[" + exports.NAME_CHAR + "]+$", "u"); +//# sourceMappingURL=ed4.js.map \ No newline at end of file diff --git a/node_modules/xmlchars/xml/1.0/ed4.js.map b/node_modules/xmlchars/xml/1.0/ed4.js.map new file mode 100644 index 0000000000000000000000000000000000000000..fe1973c200c41466ef592dfbce8f5834a5e4a4d7 --- /dev/null +++ b/node_modules/xmlchars/xml/1.0/ed4.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ed4.js","sourceRoot":"","sources":["../../../../src/xml/1.0/ed4.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;GAUG;;AAEH,EAAE;AACF,aAAa;AACb,EAAE;AAEW,QAAA,IAAI,GAAG,sDAAsD,CAAC;AAE9D,QAAA,CAAC,GAAG,SAAS,CAAC;AAE3B,yDAAyD;AAC5C,QAAA,SAAS,GAAG,osEAAosE,CAAC;AAEjtE,QAAA,WAAW,GAAG,kCAAkC,CAAC;AAE9D,yDAAyD;AAC5C,QAAA,cAAc,GAAG,0gCAA0gC,CAAC;AAEziC,yDAAyD;AAC5C,QAAA,KAAK,GAAG,2LAA2L,CAAC;AAEjN,yDAAyD;AAC5C,QAAA,QAAQ,GAAG,yFAAyF,CAAC;AAErG,QAAA,MAAM,GAAI,iBAAS,GAAG,mBAAW,CAAC;AAElC,QAAA,SAAS,GAAG,MAAI,cAAM,GAAG,aAAK,WAAM,sBAAc,GAAG,gBAAU,CAAC;AAE7E,EAAE;AACF,uBAAuB;AACvB,EAAE;AAEW,QAAA,OAAO,GAAG,IAAI,MAAM,CAAC,OAAK,YAAI,OAAI,EAAE,GAAG,CAAC,CAAC;AAEzC,QAAA,IAAI,GAAG,IAAI,MAAM,CAAC,OAAK,SAAC,QAAK,EAAE,GAAG,CAAC,CAAC;AAEpC,QAAA,YAAY,GAAG,IAAI,MAAM,CAAC,OAAK,iBAAS,OAAI,EAAE,GAAG,CAAC,CAAC;AAEnD,QAAA,cAAc,GAAG,IAAI,MAAM,CAAC,OAAK,mBAAW,OAAI,EAAE,GAAG,CAAC,CAAC;AAEvD,QAAA,iBAAiB,GAAG,IAAI,MAAM,CAAC,OAAK,sBAAc,OAAI,EAAE,GAAG,CAAC,CAAC;AAE7D,QAAA,QAAQ,GAAG,IAAI,MAAM,CAAC,OAAK,aAAK,OAAI,EAAE,GAAG,CAAC,CAAC;AAE3C,QAAA,WAAW,GAAG,IAAI,MAAM,CAAC,OAAK,gBAAQ,OAAI,EAAE,GAAG,CAAC,CAAC;AAEjD,QAAA,SAAS,GAAG,IAAI,MAAM,CAAC,OAAK,cAAM,OAAI,EAAE,GAAG,CAAC,CAAC;AAE7C,QAAA,YAAY,GAAG,IAAI,MAAM,CAAC,OAAK,iBAAS,OAAI,EAAE,GAAG,CAAC,CAAC;AAEnD,QAAA,OAAO,GAAG,IAAI,MAAM,CAAC,OAAK,cAAM,YAAO,iBAAS,QAAK,EAAE,GAAG,CAAC,CAAC;AAE5D,QAAA,UAAU,GAAG,IAAI,MAAM,CAAC,OAAK,iBAAS,QAAK,EAAE,GAAG,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/xmlchars/xml/1.0/ed5.d.ts b/node_modules/xmlchars/xml/1.0/ed5.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..859934684d0252e8d04b34e6dcd5ebd75a1dbb4d --- /dev/null +++ b/node_modules/xmlchars/xml/1.0/ed5.d.ts @@ -0,0 +1,51 @@ +/** + * Character classes and associated utilities for the 5th edition of XML 1.0. + * + * @author Louis-Dominique Dubeau + * @license MIT + * @copyright Louis-Dominique Dubeau + */ +export declare const CHAR = "\t\n\r -\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF"; +export declare const S = " \t\r\n"; +export declare const NAME_START_CHAR = ":A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\uD800\uDC00-\uDB7F\uDFFF"; +export declare const NAME_CHAR: string; +export declare const CHAR_RE: RegExp; +export declare const S_RE: RegExp; +export declare const NAME_START_CHAR_RE: RegExp; +export declare const NAME_CHAR_RE: RegExp; +export declare const NAME_RE: RegExp; +export declare const NMTOKEN_RE: RegExp; +/** All characters in the ``S`` production. */ +export declare const S_LIST: number[]; +/** + * Determines whether a codepoint matches the ``CHAR`` production. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches ``CHAR``. + */ +export declare function isChar(c: number): boolean; +/** + * Determines whether a codepoint matches the ``S`` (space) production. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches ``S``. + */ +export declare function isS(c: number): boolean; +/** + * Determines whether a codepoint matches the ``NAME_START_CHAR`` production. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches ``NAME_START_CHAR``. + */ +export declare function isNameStartChar(c: number): boolean; +/** + * Determines whether a codepoint matches the ``NAME_CHAR`` production. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches ``NAME_CHAR``. + */ +export declare function isNameChar(c: number): boolean; diff --git a/node_modules/xmlchars/xml/1.0/ed5.js b/node_modules/xmlchars/xml/1.0/ed5.js new file mode 100644 index 0000000000000000000000000000000000000000..e515a28012ee78e0f4ebf3f9240e074170319e1d --- /dev/null +++ b/node_modules/xmlchars/xml/1.0/ed5.js @@ -0,0 +1,105 @@ +"use strict"; +/** + * Character classes and associated utilities for the 5th edition of XML 1.0. + * + * @author Louis-Dominique Dubeau + * @license MIT + * @copyright Louis-Dominique Dubeau + */ +Object.defineProperty(exports, "__esModule", { value: true }); +// +// Fragments. +// +exports.CHAR = "\t\n\r -\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF"; +exports.S = " \t\r\n"; +// tslint:disable-next-line:max-line-length +exports.NAME_START_CHAR = ":A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\uD800\uDC00-\uDB7F\uDFFF"; +exports.NAME_CHAR = "-" + exports.NAME_START_CHAR + ".0-9\u00B7\u0300-\u036F\u203F-\u2040"; +// +// Regular expressions. +// +exports.CHAR_RE = new RegExp("^[" + exports.CHAR + "]$", "u"); +exports.S_RE = new RegExp("^[" + exports.S + "]+$", "u"); +exports.NAME_START_CHAR_RE = new RegExp("^[" + exports.NAME_START_CHAR + "]$", "u"); +exports.NAME_CHAR_RE = new RegExp("^[" + exports.NAME_CHAR + "]$", "u"); +exports.NAME_RE = new RegExp("^[" + exports.NAME_START_CHAR + "][" + exports.NAME_CHAR + "]*$", "u"); +exports.NMTOKEN_RE = new RegExp("^[" + exports.NAME_CHAR + "]+$", "u"); +var TAB = 9; +var NL = 0xA; +var CR = 0xD; +var SPACE = 0x20; +// +// Lists. +// +/** All characters in the ``S`` production. */ +exports.S_LIST = [SPACE, NL, CR, TAB]; +/** + * Determines whether a codepoint matches the ``CHAR`` production. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches ``CHAR``. + */ +function isChar(c) { + return (c >= SPACE && c <= 0xD7FF) || + c === NL || c === CR || c === TAB || + (c >= 0xE000 && c <= 0xFFFD) || + (c >= 0x10000 && c <= 0x10FFFF); +} +exports.isChar = isChar; +/** + * Determines whether a codepoint matches the ``S`` (space) production. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches ``S``. + */ +function isS(c) { + return c === SPACE || c === NL || c === CR || c === TAB; +} +exports.isS = isS; +/** + * Determines whether a codepoint matches the ``NAME_START_CHAR`` production. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches ``NAME_START_CHAR``. + */ +function isNameStartChar(c) { + return ((c >= 0x41 && c <= 0x5A) || + (c >= 0x61 && c <= 0x7A) || + c === 0x3A || + c === 0x5F || + c === 0x200C || + c === 0x200D || + (c >= 0xC0 && c <= 0xD6) || + (c >= 0xD8 && c <= 0xF6) || + (c >= 0x00F8 && c <= 0x02FF) || + (c >= 0x0370 && c <= 0x037D) || + (c >= 0x037F && c <= 0x1FFF) || + (c >= 0x2070 && c <= 0x218F) || + (c >= 0x2C00 && c <= 0x2FEF) || + (c >= 0x3001 && c <= 0xD7FF) || + (c >= 0xF900 && c <= 0xFDCF) || + (c >= 0xFDF0 && c <= 0xFFFD) || + (c >= 0x10000 && c <= 0xEFFFF)); +} +exports.isNameStartChar = isNameStartChar; +/** + * Determines whether a codepoint matches the ``NAME_CHAR`` production. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches ``NAME_CHAR``. + */ +function isNameChar(c) { + return isNameStartChar(c) || + (c >= 0x30 && c <= 0x39) || + c === 0x2D || + c === 0x2E || + c === 0xB7 || + (c >= 0x0300 && c <= 0x036F) || + (c >= 0x203F && c <= 0x2040); +} +exports.isNameChar = isNameChar; +//# sourceMappingURL=ed5.js.map \ No newline at end of file diff --git a/node_modules/xmlchars/xml/1.0/ed5.js.map b/node_modules/xmlchars/xml/1.0/ed5.js.map new file mode 100644 index 0000000000000000000000000000000000000000..cc8dbe98adfc96c3b8f0bb02a43226bc6f49f1e2 --- /dev/null +++ b/node_modules/xmlchars/xml/1.0/ed5.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ed5.js","sourceRoot":"","sources":["../../../../src/xml/1.0/ed5.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;AAEH,EAAE;AACF,aAAa;AACb,EAAE;AACW,QAAA,IAAI,GAAG,sDAAsD,CAAC;AAE9D,QAAA,CAAC,GAAG,SAAS,CAAC;AAE3B,2CAA2C;AAC9B,QAAA,eAAe,GAAG,iLAA2K,CAAC;AAE9L,QAAA,SAAS,GACpB,MAAI,uBAAe,yCAAsC,CAAC;AAE5D,EAAE;AACF,uBAAuB;AACvB,EAAE;AAEW,QAAA,OAAO,GAAG,IAAI,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,KAAK,IAAI;QACV,CAAC,KAAK,IAAI;QACV,CAAC,CAAC,IAAI,MAAM,IAAI,CAAC,IAAI,MAAM,CAAC;QAC5B,CAAC,CAAC,IAAI,MAAM,IAAI,CAAC,IAAI,MAAM,CAAC,CAAC;AACjC,CAAC;AARD,gCAQC"} \ No newline at end of file diff --git a/node_modules/xmlchars/xml/1.1/ed2.d.ts b/node_modules/xmlchars/xml/1.1/ed2.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5e96aeeeeba5638568156449dd1a258445bb8262 --- /dev/null +++ b/node_modules/xmlchars/xml/1.1/ed2.d.ts @@ -0,0 +1,73 @@ +/** + * Character classes and associated utilities for the 2nd edition of XML 1.1. + * + * @author Louis-Dominique Dubeau + * @license MIT + * @copyright Louis-Dominique Dubeau + */ +export declare const CHAR = "\u0001-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF"; +export declare const RESTRICTED_CHAR = "\u0001-\b\v\f\u000E-\u001F-\u0084\u0086-\u009F"; +export declare const S = " \t\r\n"; +export declare const NAME_START_CHAR = ":A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\uD800\uDC00-\uDB7F\uDFFF"; +export declare const NAME_CHAR: string; +export declare const CHAR_RE: RegExp; +export declare const RESTRICTED_CHAR_RE: RegExp; +export declare const S_RE: RegExp; +export declare const NAME_START_CHAR_RE: RegExp; +export declare const NAME_CHAR_RE: RegExp; +export declare const NAME_RE: RegExp; +export declare const NMTOKEN_RE: RegExp; +/** All characters in the ``S`` production. */ +export declare const S_LIST: number[]; +/** + * Determines whether a codepoint matches the ``CHAR`` production. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches ``CHAR``. + */ +export declare function isChar(c: number): boolean; +/** + * Determines whether a codepoint matches the ``RESTRICTED_CHAR`` production. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches ``RESTRICTED_CHAR``. + */ +export declare function isRestrictedChar(c: number): boolean; +/** + * Determines whether a codepoint matches the ``CHAR`` production and does not + * match the ``RESTRICTED_CHAR`` production. ``isCharAndNotRestricted(x)`` is + * equivalent to ``isChar(x) && !isRestrictedChar(x)``. This function is faster + * than running the two-call equivalent. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches ``CHAR`` and does not match + * ``RESTRICTED_CHAR``. + */ +export declare function isCharAndNotRestricted(c: number): boolean; +/** + * Determines whether a codepoint matches the ``S`` (space) production. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches ``S``. + */ +export declare function isS(c: number): boolean; +/** + * Determines whether a codepoint matches the ``NAME_START_CHAR`` production. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches ``NAME_START_CHAR``. + */ +export declare function isNameStartChar(c: number): boolean; +/** + * Determines whether a codepoint matches the ``NAME_CHAR`` production. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches ``NAME_CHAR``. + */ +export declare function isNameChar(c: number): boolean; diff --git a/node_modules/xmlchars/xml/1.1/ed2.js b/node_modules/xmlchars/xml/1.1/ed2.js new file mode 100644 index 0000000000000000000000000000000000000000..7906e76a23b2a8dc7b687e15656e10794561000d --- /dev/null +++ b/node_modules/xmlchars/xml/1.1/ed2.js @@ -0,0 +1,145 @@ +"use strict"; +/** + * Character classes and associated utilities for the 2nd edition of XML 1.1. + * + * @author Louis-Dominique Dubeau + * @license MIT + * @copyright Louis-Dominique Dubeau + */ +Object.defineProperty(exports, "__esModule", { value: true }); +// +// Fragments. +// +exports.CHAR = "\u0001-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF"; +exports.RESTRICTED_CHAR = "\u0001-\u0008\u000B\u000C\u000E-\u001F\u007F-\u0084\u0086-\u009F"; +exports.S = " \t\r\n"; +// tslint:disable-next-line:max-line-length +exports.NAME_START_CHAR = ":A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\uD800\uDC00-\uDB7F\uDFFF"; +exports.NAME_CHAR = "-" + exports.NAME_START_CHAR + ".0-9\u00B7\u0300-\u036F\u203F-\u2040"; +// +// Regular expressions. +// +exports.CHAR_RE = new RegExp("^[" + exports.CHAR + "]$", "u"); +exports.RESTRICTED_CHAR_RE = new RegExp("^[" + exports.RESTRICTED_CHAR + "]$", "u"); +exports.S_RE = new RegExp("^[" + exports.S + "]+$", "u"); +exports.NAME_START_CHAR_RE = new RegExp("^[" + exports.NAME_START_CHAR + "]$", "u"); +exports.NAME_CHAR_RE = new RegExp("^[" + exports.NAME_CHAR + "]$", "u"); +exports.NAME_RE = new RegExp("^[" + exports.NAME_START_CHAR + "][" + exports.NAME_CHAR + "]*$", "u"); +exports.NMTOKEN_RE = new RegExp("^[" + exports.NAME_CHAR + "]+$", "u"); +var TAB = 9; +var NL = 0xA; +var CR = 0xD; +var SPACE = 0x20; +// +// Lists. +// +/** All characters in the ``S`` production. */ +exports.S_LIST = [SPACE, NL, CR, TAB]; +/** + * Determines whether a codepoint matches the ``CHAR`` production. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches ``CHAR``. + */ +function isChar(c) { + return (c >= 0x0001 && c <= 0xD7FF) || + (c >= 0xE000 && c <= 0xFFFD) || + (c >= 0x10000 && c <= 0x10FFFF); +} +exports.isChar = isChar; +/** + * Determines whether a codepoint matches the ``RESTRICTED_CHAR`` production. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches ``RESTRICTED_CHAR``. + */ +function isRestrictedChar(c) { + return (c >= 0x1 && c <= 0x8) || + c === 0xB || + c === 0xC || + (c >= 0xE && c <= 0x1F) || + (c >= 0x7F && c <= 0x84) || + (c >= 0x86 && c <= 0x9F); +} +exports.isRestrictedChar = isRestrictedChar; +/** + * Determines whether a codepoint matches the ``CHAR`` production and does not + * match the ``RESTRICTED_CHAR`` production. ``isCharAndNotRestricted(x)`` is + * equivalent to ``isChar(x) && !isRestrictedChar(x)``. This function is faster + * than running the two-call equivalent. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches ``CHAR`` and does not match + * ``RESTRICTED_CHAR``. + */ +function isCharAndNotRestricted(c) { + return (c === 0x9) || + (c === 0xA) || + (c === 0xD) || + (c > 0x1F && c < 0x7F) || + (c === 0x85) || + (c > 0x9F && c <= 0xD7FF) || + (c >= 0xE000 && c <= 0xFFFD) || + (c >= 0x10000 && c <= 0x10FFFF); +} +exports.isCharAndNotRestricted = isCharAndNotRestricted; +/** + * Determines whether a codepoint matches the ``S`` (space) production. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches ``S``. + */ +function isS(c) { + return c === SPACE || c === NL || c === CR || c === TAB; +} +exports.isS = isS; +/** + * Determines whether a codepoint matches the ``NAME_START_CHAR`` production. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches ``NAME_START_CHAR``. + */ +// tslint:disable-next-line:cyclomatic-complexity +function isNameStartChar(c) { + return ((c >= 0x41 && c <= 0x5A) || + (c >= 0x61 && c <= 0x7A) || + c === 0x3A || + c === 0x5F || + c === 0x200C || + c === 0x200D || + (c >= 0xC0 && c <= 0xD6) || + (c >= 0xD8 && c <= 0xF6) || + (c >= 0x00F8 && c <= 0x02FF) || + (c >= 0x0370 && c <= 0x037D) || + (c >= 0x037F && c <= 0x1FFF) || + (c >= 0x2070 && c <= 0x218F) || + (c >= 0x2C00 && c <= 0x2FEF) || + (c >= 0x3001 && c <= 0xD7FF) || + (c >= 0xF900 && c <= 0xFDCF) || + (c >= 0xFDF0 && c <= 0xFFFD) || + (c >= 0x10000 && c <= 0xEFFFF)); +} +exports.isNameStartChar = isNameStartChar; +/** + * Determines whether a codepoint matches the ``NAME_CHAR`` production. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches ``NAME_CHAR``. + */ +function isNameChar(c) { + return isNameStartChar(c) || + (c >= 0x30 && c <= 0x39) || + c === 0x2D || + c === 0x2E || + c === 0xB7 || + (c >= 0x0300 && c <= 0x036F) || + (c >= 0x203F && c <= 0x2040); +} +exports.isNameChar = isNameChar; +//# sourceMappingURL=ed2.js.map \ No newline at end of file diff --git a/node_modules/xmlchars/xml/1.1/ed2.js.map b/node_modules/xmlchars/xml/1.1/ed2.js.map new file mode 100644 index 0000000000000000000000000000000000000000..96fb7e24fb500a91b376b51518587985041e78ab --- /dev/null +++ b/node_modules/xmlchars/xml/1.1/ed2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ed2.js","sourceRoot":"","sources":["../../../../src/xml/1.1/ed2.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;AAEH,EAAE;AACF,aAAa;AACb,EAAE;AACW,QAAA,IAAI,GAAG,qDAAgD,CAAC;AAExD,QAAA,eAAe,GAC1B,kEAAkE,CAAC;AAExD,QAAA,CAAC,GAAG,SAAS,CAAC;AAE3B,2CAA2C;AAC9B,QAAA,eAAe,GAAG,iLAA2K,CAAC;AAE9L,QAAA,SAAS,GACpB,MAAI,uBAAe,yCAAsC,CAAC;AAE5D,EAAE;AACF,uBAAuB;AACvB,EAAE;AAEW,QAAA,OAAO,GAAG,IAAI,MAAM,CAAC,OAAK,YAAI,OAAI,EAAE,GAAG,CAAC,CAAC;AAEzC,QAAA,kBAAkB,GAAG,IAAI,MAAM,CAAC,OAAK,uBAAe,OAAI,EAAE,GAAG,CAAC,CAAC;AAE/D,QAAA,IAAI,GAAG,IAAI,MAAM,CAAC,OAAK,SAAC,QAAK,EAAE,GAAG,CAAC,CAAC;AAEpC,QAAA,kBAAkB,GAAG,IAAI,MAAM,CAAC,OAAK,uBAAe,OAAI,EAAE,GAAG,CAAC,CAAC;AAE/D,QAAA,YAAY,GAAG,IAAI,MAAM,CAAC,OAAK,iBAAS,OAAI,EAAE,GAAG,CAAC,CAAC;AAEnD,QAAA,OAAO,GAAG,IAAI,MAAM,CA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,MAAM,IAAI,CAAC,IAAI,MAAM,CAAC;QAC5B,CAAC,CAAC,IAAI,MAAM,IAAI,CAAC,IAAI,MAAM,CAAC;QAC5B,CAAC,CAAC,IAAI,MAAM,IAAI,CAAC,IAAI,MAAM,CAAC;QAC5B,CAAC,CAAC,IAAI,OAAO,IAAI,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC;AAC1C,CAAC;AAlBD,0CAkBC;AAED;;;;;;GAMG;AACH,SAAgB,UAAU,CAAC,CAAS;IAClC,OAAO,eAAe,CAAC,CAAC,CAAC;QACvB,CAAC,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,IAAI,CAAC;QACxB,CAAC,KAAK,IAAI;QACV,CAAC,KAAK,IAAI;QACV,CAAC,KAAK,IAAI;QACV,CAAC,CAAC,IAAI,MAAM,IAAI,CAAC,IAAI,MAAM,CAAC;QAC5B,CAAC,CAAC,IAAI,MAAM,IAAI,CAAC,IAAI,MAAM,CAAC,CAAC;AACjC,CAAC;AARD,gCAQC"} \ No newline at end of file diff --git a/node_modules/xmlchars/xmlchars.d.ts b/node_modules/xmlchars/xmlchars.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bdb3d400a06553b50735fd8934800eba951e76db --- /dev/null +++ b/node_modules/xmlchars/xmlchars.d.ts @@ -0,0 +1,170 @@ +/** + * Character classes for XML. + * + * @deprecated since 1.3.0. Import from the ``xml`` and ``xmlns`` hierarchies + * instead. + * + * @author Louis-Dominique Dubeau + * @license MIT + * @copyright Louis-Dominique Dubeau + */ +import * as ed5 from "./xml/1.0/ed5"; +import * as nsed3 from "./xmlns/1.0/ed3"; +/** + * Character class utilities for XML 1.0. + */ +export declare namespace XML_1_0 { + /** + * Fifth edition. + */ + namespace ED5 { + /** + * Regular expression fragments. These fragments are designed to be included + * inside square brackets in a regular expression. + */ + namespace fragments { + const CHAR = "\t\n\r -\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF"; + const S = " \t\r\n"; + const NAME_START_CHAR = ":A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\uD800\uDC00-\uDB7F\uDFFF"; + const NAME_CHAR: string; + } + /** + * Regular expression. These correspond to the productions of the same name + * in the specification. + */ + namespace regexes { + const CHAR: RegExp; + const S: RegExp; + const NAME_START_CHAR: RegExp; + const NAME_CHAR: RegExp; + const NAME: RegExp; + const NMTOKEN: RegExp; + } + /** + * Lists of characters. + * + * The names defined in this namespace are arrays of codepoints which + * contain the set of codepoints that an XML production encompasses. Note + * that many productions are too large to be reasonably represented as sets. + */ + namespace lists { + const S: number[]; + } + /** + * Determines whether a codepoint matches the ``CHAR`` production. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches ``CHAR``. + */ + const isChar: typeof ed5.isChar; + /** + * Determines whether a codepoint matches the ``S`` (space) production. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches ``S``. + */ + const isS: typeof ed5.isS; + /** + * Determines whether a codepoint matches the ``NAME_START_CHAR`` + * production. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches ``NAME_START_CHAR``. + */ + const isNameStartChar: typeof ed5.isNameStartChar; + /** + * Determines whether a codepoint matches the ``NAME_CHAR`` production. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches ``NAME_CHAR``. + */ + const isNameChar: typeof ed5.isNameChar; + } + /** + * Fourth edition. These are deprecated in the 5th edition but some of the + * standards related to XML 1.0 (e.g. XML Schema 1.0) refer to these. So they + * are still generally useful. + */ + namespace ED4 { + /** + * Regular expression fragments. These fragments are designed to be included + * inside square brackets in a regular expression. + */ + namespace fragments { + const CHAR = "\t\n\r -\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF"; + const S = " \t\r\n"; + const BASE_CHAR = "A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0100-\u0131\u0134-\u013E\u0141-\u0148\u014A-\u017E\u0180-\u01C3\u01CD-\u01F0\u01F4-\u01F5\u01FA-\u0217\u0250-\u02A8\u02BB-\u02C1\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03CE\u03D0-\u03D6\u03DA\u03DC\u03DE\u03E0\u03E2-\u03F3\u0401-\u040C\u040E-\u044F\u0451-\u045C\u045E-\u0481\u0490-\u04C4\u04C7-\u04C8\u04CB-\u04CC\u04D0-\u04EB\u04EE-\u04F5\u04F8-\u04F9\u0531-\u0556\u0559\u0561-\u0586\u05D0-\u05EA\u05F0-\u05F2\u0621-\u063A\u0641-\u064A\u0671-\u06B7\u06BA-\u06BE\u06C0-\u06CE\u06D0-\u06D3\u06D5\u06E5-\u06E6\u0905-\u0939\u093D\u0958-\u0961\u0985-\u098C\u098F-\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09DC-\u09DD\u09DF-\u09E1\u09F0-\u09F1\u0A05-\u0A0A\u0A0F-\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32-\u0A33\u0A35-\u0A36\u0A38-\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8B\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2-\u0AB3\u0AB5-\u0AB9\u0ABD\u0AE0\u0B05-\u0B0C\u0B0F-\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32-\u0B33\u0B36-\u0B39\u0B3D\u0B5C-\u0B5D\u0B5F-\u0B61\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99-\u0B9A\u0B9C\u0B9E-\u0B9F\u0BA3-\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB5\u0BB7-\u0BB9\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C60-\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CDE\u0CE0-\u0CE1\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D28\u0D2A-\u0D39\u0D60-\u0D61\u0E01-\u0E2E\u0E30\u0E32-\u0E33\u0E40-\u0E45\u0E81-\u0E82\u0E84\u0E87-\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA-\u0EAB\u0EAD-\u0EAE\u0EB0\u0EB2-\u0EB3\u0EBD\u0EC0-\u0EC4\u0F40-\u0F47\u0F49-\u0F69\u10A0-\u10C5\u10D0-\u10F6\u1100\u1102-\u1103\u1105-\u1107\u1109\u110B-\u110C\u110E-\u1112\u113C\u113E\u1140\u114C\u114E\u1150\u1154-\u1155\u1159\u115F-\u1161\u1163\u1165\u1167\u1169\u116D-\u116E\u1172-\u1173\u1175\u119E\u11A8\u11AB\u11AE-\u11AF\u11B7-\u11B8\u11BA\u11BC-\u11C2\u11EB\u11F0\u11F9\u1E00-\u1E9B\u1EA0-\u1EF9\u1F00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2126\u212A-\u212B\u212E\u2180-\u2182\u3041-\u3094\u30A1-\u30FA\u3105-\u312C\uAC00-\uD7A3"; + const IDEOGRAPHIC = "\u4E00-\u9FA5\u3007\u3021-\u3029"; + const COMBINING_CHAR = "\u0300-\u0345\u0360-\u0361\u0483-\u0486\u0591-\u05A1\u05A3-\u05B9\u05BB-\u05BD\u05BF\u05C1-\u05C2\u05C4\u064B-\u0652\u0670\u06D6-\u06DC\u06DD-\u06DF\u06E0-\u06E4\u06E7-\u06E8\u06EA-\u06ED\u0901-\u0903\u093C\u093E-\u094C\u094D\u0951-\u0954\u0962-\u0963\u0981-\u0983\u09BC\u09BE\u09BF\u09C0-\u09C4\u09C7-\u09C8\u09CB-\u09CD\u09D7\u09E2-\u09E3\u0A02\u0A3C\u0A3E\u0A3F\u0A40-\u0A42\u0A47-\u0A48\u0A4B-\u0A4D\u0A70-\u0A71\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0B01-\u0B03\u0B3C\u0B3E-\u0B43\u0B47-\u0B48\u0B4B-\u0B4D\u0B56-\u0B57\u0B82-\u0B83\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C01-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55-\u0C56\u0C82-\u0C83\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5-\u0CD6\u0D02-\u0D03\u0D3E-\u0D43\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB-\u0EBC\u0EC8-\u0ECD\u0F18-\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86-\u0F8B\u0F90-\u0F95\u0F97\u0F99-\u0FAD\u0FB1-\u0FB7\u0FB9\u20D0-\u20DC\u20E1\u302A-\u302F\u3099\u309A"; + const DIGIT = "0-9\u0660-\u0669\u06F0-\u06F9\u0966-\u096F\u09E6-\u09EF\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0BE7-\u0BEF\u0C66-\u0C6F\u0CE6-\u0CEF\u0D66-\u0D6F\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F29"; + const EXTENDER = "\u00B7\u02D0\u02D1\u0387\u0640\u0E46\u0EC6\u3005\u3031-\u3035\u309D-\u309E\u30FC-\u30FE"; + const LETTER: string; + const NAME_CHAR: string; + } + /** + * Regular expression. These correspond to the productions of the same + * name in the specification. + */ + namespace regexes { + const CHAR: RegExp; + const S: RegExp; + const BASE_CHAR: RegExp; + const IDEOGRAPHIC: RegExp; + const COMBINING_CHAR: RegExp; + const DIGIT: RegExp; + const EXTENDER: RegExp; + const LETTER: RegExp; + const NAME_CHAR: RegExp; + const NAME: RegExp; + const NMTOKEN: RegExp; + } + } +} +/** + * Character class utilities for XML NS 1.0. + */ +export declare namespace XMLNS_1_0 { + /** + * Third edition. + */ + namespace ED3 { + /** + * Regular expression fragments. These fragments are designed to be included + * inside square brackets in a regular expression. + */ + namespace fragments { + const NC_NAME_START_CHAR = "A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\uD800\uDC00-\uDB7F\uDFFF"; + const NC_NAME_CHAR: string; + } + /** + * Regular expression. These correspond to the productions of the same name + * in the specification. + */ + namespace regexes { + const NC_NAME_START_CHAR: RegExp; + const NC_NAME_CHAR: RegExp; + const NC_NAME: RegExp; + } + /** + * Determines whether a codepoint matches + * [[regexes.NC_NAME_START_CHAR]]. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches. + */ + const isNCNameStartChar: typeof nsed3.isNCNameStartChar; + /** + * Determines whether a codepoint matches [[regexes.NC_NAME_CHAR]]. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches. + */ + const isNCNameChar: typeof nsed3.isNCNameChar; + } +} diff --git a/node_modules/xmlchars/xmlchars.js b/node_modules/xmlchars/xmlchars.js new file mode 100644 index 0000000000000000000000000000000000000000..acf682b4e12bf74682f7298e691b096b94299bef --- /dev/null +++ b/node_modules/xmlchars/xmlchars.js @@ -0,0 +1,191 @@ +"use strict"; +/** + * Character classes for XML. + * + * @deprecated since 1.3.0. Import from the ``xml`` and ``xmlns`` hierarchies + * instead. + * + * @author Louis-Dominique Dubeau + * @license MIT + * @copyright Louis-Dominique Dubeau + */ +Object.defineProperty(exports, "__esModule", { value: true }); +var ed4 = require("./xml/1.0/ed4"); +var ed5 = require("./xml/1.0/ed5"); +var nsed3 = require("./xmlns/1.0/ed3"); +// tslint:disable-next-line:no-console +console.warn("DEPRECATION WARNING: the xmlchar *module* is deprecated: please \ +replace e.g. require('xmlchars') with require('xmlchars/xml/...')"); +/** + * Character class utilities for XML 1.0. + */ +// tslint:disable-next-line:no-namespace +var XML_1_0; +(function (XML_1_0) { + /** + * Fifth edition. + */ + var ED5; + (function (ED5) { + /** + * Regular expression fragments. These fragments are designed to be included + * inside square brackets in a regular expression. + */ + var fragments; + (function (fragments) { + fragments.CHAR = ed5.CHAR; + fragments.S = ed5.S; + fragments.NAME_START_CHAR = ed5.NAME_START_CHAR; + fragments.NAME_CHAR = ed5.NAME_CHAR; + })(fragments = ED5.fragments || (ED5.fragments = {})); + /** + * Regular expression. These correspond to the productions of the same name + * in the specification. + */ + var regexes; + (function (regexes) { + regexes.CHAR = ed5.CHAR_RE; + regexes.S = ed5.S_RE; + regexes.NAME_START_CHAR = ed5.NAME_START_CHAR_RE; + regexes.NAME_CHAR = ed5.NAME_CHAR_RE; + regexes.NAME = ed5.NAME_RE; + regexes.NMTOKEN = ed5.NMTOKEN_RE; + })(regexes = ED5.regexes || (ED5.regexes = {})); + /** + * Lists of characters. + * + * The names defined in this namespace are arrays of codepoints which + * contain the set of codepoints that an XML production encompasses. Note + * that many productions are too large to be reasonably represented as sets. + */ + var lists; + (function (lists) { + lists.S = ed5.S_LIST; + })(lists = ED5.lists || (ED5.lists = {})); + /** + * Determines whether a codepoint matches the ``CHAR`` production. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches ``CHAR``. + */ + ED5.isChar = ed5.isChar; + /** + * Determines whether a codepoint matches the ``S`` (space) production. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches ``S``. + */ + ED5.isS = ed5.isS; + /** + * Determines whether a codepoint matches the ``NAME_START_CHAR`` + * production. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches ``NAME_START_CHAR``. + */ + ED5.isNameStartChar = ed5.isNameStartChar; + /** + * Determines whether a codepoint matches the ``NAME_CHAR`` production. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches ``NAME_CHAR``. + */ + ED5.isNameChar = ed5.isNameChar; + })(ED5 = XML_1_0.ED5 || (XML_1_0.ED5 = {})); + /** + * Fourth edition. These are deprecated in the 5th edition but some of the + * standards related to XML 1.0 (e.g. XML Schema 1.0) refer to these. So they + * are still generally useful. + */ + var ED4; + (function (ED4) { + /** + * Regular expression fragments. These fragments are designed to be included + * inside square brackets in a regular expression. + */ + var fragments; + (function (fragments) { + fragments.CHAR = ed4.CHAR; + fragments.S = ed4.S; + fragments.BASE_CHAR = ed4.BASE_CHAR; + fragments.IDEOGRAPHIC = ed4.IDEOGRAPHIC; + fragments.COMBINING_CHAR = ed4.COMBINING_CHAR; + fragments.DIGIT = ed4.DIGIT; + fragments.EXTENDER = ed4.EXTENDER; + fragments.LETTER = ed4.LETTER; + fragments.NAME_CHAR = ed4.NAME_CHAR; + })(fragments = ED4.fragments || (ED4.fragments = {})); + /** + * Regular expression. These correspond to the productions of the same + * name in the specification. + */ + var regexes; + (function (regexes) { + regexes.CHAR = ed4.CHAR_RE; + regexes.S = ed4.S_RE; + regexes.BASE_CHAR = ed4.BASE_CHAR_RE; + regexes.IDEOGRAPHIC = ed4.IDEOGRAPHIC_RE; + regexes.COMBINING_CHAR = ed4.COMBINING_CHAR_RE; + regexes.DIGIT = ed4.DIGIT_RE; + regexes.EXTENDER = ed4.EXTENDER_RE; + regexes.LETTER = ed4.LETTER_RE; + regexes.NAME_CHAR = ed4.NAME_CHAR_RE; + regexes.NAME = ed4.NAME_RE; + regexes.NMTOKEN = ed4.NMTOKEN_RE; + })(regexes = ED4.regexes || (ED4.regexes = {})); + })(ED4 = XML_1_0.ED4 || (XML_1_0.ED4 = {})); +})(XML_1_0 = exports.XML_1_0 || (exports.XML_1_0 = {})); +/** + * Character class utilities for XML NS 1.0. + */ +// tslint:disable-next-line:no-namespace +var XMLNS_1_0; +(function (XMLNS_1_0) { + /** + * Third edition. + */ + var ED3; + (function (ED3) { + /** + * Regular expression fragments. These fragments are designed to be included + * inside square brackets in a regular expression. + */ + var fragments; + (function (fragments) { + fragments.NC_NAME_START_CHAR = nsed3.NC_NAME_START_CHAR; + fragments.NC_NAME_CHAR = nsed3.NC_NAME_CHAR; + })(fragments = ED3.fragments || (ED3.fragments = {})); + /** + * Regular expression. These correspond to the productions of the same name + * in the specification. + */ + var regexes; + (function (regexes) { + regexes.NC_NAME_START_CHAR = nsed3.NC_NAME_START_CHAR_RE; + regexes.NC_NAME_CHAR = nsed3.NC_NAME_CHAR_RE; + regexes.NC_NAME = nsed3.NC_NAME_RE; + })(regexes = ED3.regexes || (ED3.regexes = {})); + /** + * Determines whether a codepoint matches + * [[regexes.NC_NAME_START_CHAR]]. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches. + */ + ED3.isNCNameStartChar = nsed3.isNCNameStartChar; + /** + * Determines whether a codepoint matches [[regexes.NC_NAME_CHAR]]. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches. + */ + ED3.isNCNameChar = nsed3.isNCNameChar; + })(ED3 = XMLNS_1_0.ED3 || (XMLNS_1_0.ED3 = {})); +})(XMLNS_1_0 = exports.XMLNS_1_0 || (exports.XMLNS_1_0 = {})); +//# sourceMappingURL=xmlchars.js.map \ No newline at end of file diff --git a/node_modules/xmlchars/xmlchars.js.map b/node_modules/xmlchars/xmlchars.js.map new file mode 100644 index 0000000000000000000000000000000000000000..47b8c34c9848d8637bf83b5db66fcbfba3aab75f --- /dev/null +++ b/node_modules/xmlchars/xmlchars.js.map @@ -0,0 +1 @@ +{"version":3,"file":"xmlchars.js","sourceRoot":"","sources":["../../src/xmlchars.ts"],"names":[],"mappings":";AAAA;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AC;QACxC,CAAC,EAZgB,OAAO,GAAP,WAAO,KAAP,WAAO,QAYvB;IACH,CAAC,EAlCgB,GAAG,GAAH,WAAG,KAAH,WAAG,QAkCnB;AACH,CAAC,EAtHgB,OAAO,GAAP,eAAO,KAAP,eAAO,QAsHvB;AAED;;GAEG;AACH,wCAAwC;AACxC,IAAiB,SAAS,CA4CzB;AA5CD,WAAiB,SAAS;IAExB;;OAEG;IACH,IAAiB,GAAG,CAsCnB;IAtCD,WAAiB,GAAG;QAClB;;;WAGG;QACH,IAAiB,SAAS,CAGzB;QAHD,WAAiB,SAAS;YACX,4BAAkB,GAAG,KAAK,CAAC,kBAAkB,CAAC;YAC9C,sBAAY,GAAG,KAAK,CAAC,YAAY,CAAC;QACjD,CAAC,EAHgB,SAAS,GAAT,aAAS,KAAT,aAAS,QAGzB;QAED;;;WAGG;QACH,IAAiB,OAAO,CAIvB;QAJD,WAAiB,OAAO;YACT,0BAAkB,GAAG,KAAK,CAAC,qBAAqB,CAAC;YACjD,oBAAY,GAAG,KAAK,CAAC,eAAe,CAAC;YACrC,eAAO,GAAG,KAAK,CAAC,UAAU,CAAC;QAC1C,CAAC,EAJgB,OAAO,GAAP,WAAO,KAAP,WAAO,QAIvB;QAED;;;;;;;WAOG;QACU,qBAAiB,GAAG,KAAK,CAAC,iBAAiB,CAAC;QAEzD;;;;;;WAMG;QACU,gBAAY,GAAG,KAAK,CAAC,YAAY,CAAC;IACjD,CAAC,EAtCgB,GAAG,GAAH,aAAG,KAAH,aAAG,QAsCnB;AACH,CAAC,EA5CgB,SAAS,GAAT,iBAAS,KAAT,iBAAS,QA4CzB"} \ No newline at end of file diff --git a/node_modules/xmlchars/xmlns/1.0/ed3.d.ts b/node_modules/xmlchars/xmlns/1.0/ed3.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5cdf37ac8a26c8378b728fbe626508e5fc574fc1 --- /dev/null +++ b/node_modules/xmlchars/xmlns/1.0/ed3.d.ts @@ -0,0 +1,28 @@ +/** + * Character class utilities for XML NS 1.0 edition 3. + * + * @author Louis-Dominique Dubeau + * @license MIT + * @copyright Louis-Dominique Dubeau + */ +export declare const NC_NAME_START_CHAR = "A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\uD800\uDC00-\uDB7F\uDFFF"; +export declare const NC_NAME_CHAR: string; +export declare const NC_NAME_START_CHAR_RE: RegExp; +export declare const NC_NAME_CHAR_RE: RegExp; +export declare const NC_NAME_RE: RegExp; +/** + * Determines whether a codepoint matches [[NC_NAME_START_CHAR]]. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches. + */ +export declare function isNCNameStartChar(c: number): boolean; +/** + * Determines whether a codepoint matches [[NC_NAME_CHAR]]. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches. + */ +export declare function isNCNameChar(c: number): boolean; diff --git a/node_modules/xmlchars/xmlns/1.0/ed3.js b/node_modules/xmlchars/xmlns/1.0/ed3.js new file mode 100644 index 0000000000000000000000000000000000000000..50d8d9d6edd626737005a5a71f021f509ff12480 --- /dev/null +++ b/node_modules/xmlchars/xmlns/1.0/ed3.js @@ -0,0 +1,65 @@ +"use strict"; +/** + * Character class utilities for XML NS 1.0 edition 3. + * + * @author Louis-Dominique Dubeau + * @license MIT + * @copyright Louis-Dominique Dubeau + */ +Object.defineProperty(exports, "__esModule", { value: true }); +// +// Fragments. +// +// tslint:disable-next-line:max-line-length +exports.NC_NAME_START_CHAR = "A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\uD800\uDC00-\uDB7F\uDFFF"; +exports.NC_NAME_CHAR = "-" + exports.NC_NAME_START_CHAR + ".0-9\u00B7\u0300-\u036F\u203F-\u2040"; +// +// Regular expressions. +// +exports.NC_NAME_START_CHAR_RE = new RegExp("^[" + exports.NC_NAME_START_CHAR + "]$", "u"); +exports.NC_NAME_CHAR_RE = new RegExp("^[" + exports.NC_NAME_CHAR + "]$", "u"); +exports.NC_NAME_RE = new RegExp("^[" + exports.NC_NAME_START_CHAR + "][" + exports.NC_NAME_CHAR + "]*$", "u"); +/** + * Determines whether a codepoint matches [[NC_NAME_START_CHAR]]. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches. + */ +// tslint:disable-next-line:cyclomatic-complexity +function isNCNameStartChar(c) { + return ((c >= 0x41 && c <= 0x5A) || + c === 0x5F || + (c >= 0x61 && c <= 0x7A) || + (c >= 0xC0 && c <= 0xD6) || + (c >= 0xD8 && c <= 0xF6) || + (c >= 0x00F8 && c <= 0x02FF) || + (c >= 0x0370 && c <= 0x037D) || + (c >= 0x037F && c <= 0x1FFF) || + (c >= 0x200C && c <= 0x200D) || + (c >= 0x2070 && c <= 0x218F) || + (c >= 0x2C00 && c <= 0x2FEF) || + (c >= 0x3001 && c <= 0xD7FF) || + (c >= 0xF900 && c <= 0xFDCF) || + (c >= 0xFDF0 && c <= 0xFFFD) || + (c >= 0x10000 && c <= 0xEFFFF)); +} +exports.isNCNameStartChar = isNCNameStartChar; +/** + * Determines whether a codepoint matches [[NC_NAME_CHAR]]. + * + * @param c The code point. + * + * @returns ``true`` if the codepoint matches. + */ +function isNCNameChar(c) { + return isNCNameStartChar(c) || + (c === 0x2D || + c === 0x2E || + (c >= 0x30 && c <= 0x39) || + c === 0x00B7 || + (c >= 0x0300 && c <= 0x036F) || + (c >= 0x203F && c <= 0x2040)); +} +exports.isNCNameChar = isNCNameChar; +//# sourceMappingURL=ed3.js.map \ No newline at end of file diff --git a/node_modules/xmlchars/xmlns/1.0/ed3.js.map b/node_modules/xmlchars/xmlns/1.0/ed3.js.map new file mode 100644 index 0000000000000000000000000000000000000000..9195a690d88d5b79f45d380952987d26a3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AI,MAAM,IAAI,CAAC,IAAI,MAAM,CAAC;QAC5B,CAAC,CAAC,IAAI,MAAM,IAAI,CAAC,IAAI,MAAM,CAAC;QAC5B,CAAC,CAAC,IAAI,MAAM,IAAI,CAAC,IAAI,MAAM,CAAC;QAC5B,CAAC,CAAC,IAAI,MAAM,IAAI,CAAC,IAAI,MAAM,CAAC;QAC5B,CAAC,CAAC,IAAI,MAAM,IAAI,CAAC,IAAI,MAAM,CAAC;QAC5B,CAAC,CAAC,IAAI,OAAO,IAAI,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC;AAC1C,CAAC;AAhBD,8CAgBC;AAED;;;;;;GAMG;AACH,SAAgB,YAAY,CAAC,CAAS;IACpC,OAAO,iBAAiB,CAAC,CAAC,CAAC;QACzB,CAAC,CAAC,KAAK,IAAI;YACV,CAAC,KAAK,IAAI;YACV,CAAC,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,IAAI,CAAC;YACxB,CAAC,KAAK,MAAM;YACZ,CAAC,CAAC,IAAI,MAAM,IAAI,CAAC,IAAI,MAAM,CAAC;YAC5B,CAAC,CAAC,IAAI,MAAM,IAAI,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC;AACnC,CAAC;AARD,oCAQC"} \ No newline at end of file diff --git a/node_modules/y18n/CHANGELOG.md b/node_modules/y18n/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..244d83850d30a2e3ca559b2abeff529a04e971df --- /dev/null +++ b/node_modules/y18n/CHANGELOG.md @@ -0,0 +1,100 @@ +# Change Log + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +### [5.0.8](https://www.github.com/yargs/y18n/compare/v5.0.7...v5.0.8) (2021-04-07) + + +### Bug Fixes + +* **deno:** force modern release for Deno ([b1c215a](https://www.github.com/yargs/y18n/commit/b1c215aed714bee5830e76de3e335504dc2c4dab)) + +### [5.0.7](https://www.github.com/yargs/y18n/compare/v5.0.6...v5.0.7) (2021-04-07) + + +### Bug Fixes + +* **deno:** force release for deno ([#121](https://www.github.com/yargs/y18n/issues/121)) ([d3f2560](https://www.github.com/yargs/y18n/commit/d3f2560e6cedf2bfa2352e9eec044da53f9a06b2)) + +### [5.0.6](https://www.github.com/yargs/y18n/compare/v5.0.5...v5.0.6) (2021-04-05) + + +### Bug Fixes + +* **webpack:** skip readFileSync if not defined ([#117](https://www.github.com/yargs/y18n/issues/117)) ([6966fa9](https://www.github.com/yargs/y18n/commit/6966fa91d2881cc6a6c531e836099e01f4da1616)) + +### [5.0.5](https://www.github.com/yargs/y18n/compare/v5.0.4...v5.0.5) (2020-10-25) + + +### Bug Fixes + +* address prototype pollution issue ([#108](https://www.github.com/yargs/y18n/issues/108)) ([a9ac604](https://www.github.com/yargs/y18n/commit/a9ac604abf756dec9687be3843e2c93bfe581f25)) + +### [5.0.4](https://www.github.com/yargs/y18n/compare/v5.0.3...v5.0.4) (2020-10-16) + + +### Bug Fixes + +* **exports:** node 13.0 and 13.1 require the dotted object form _with_ a string fallback ([#105](https://www.github.com/yargs/y18n/issues/105)) ([4f85d80](https://www.github.com/yargs/y18n/commit/4f85d80dbaae6d2c7899ae394f7ad97805df4886)) + +### [5.0.3](https://www.github.com/yargs/y18n/compare/v5.0.2...v5.0.3) (2020-10-16) + + +### Bug Fixes + +* **exports:** node 13.0-13.6 require a string fallback ([#103](https://www.github.com/yargs/y18n/issues/103)) ([e39921e](https://www.github.com/yargs/y18n/commit/e39921e1017f88f5d8ea97ddea854ffe92d68e74)) + +### [5.0.2](https://www.github.com/yargs/y18n/compare/v5.0.1...v5.0.2) (2020-10-01) + + +### Bug Fixes + +* **deno:** update types for deno ^1.4.0 ([#100](https://www.github.com/yargs/y18n/issues/100)) ([3834d9a](https://www.github.com/yargs/y18n/commit/3834d9ab1332f2937c935ada5e76623290efae81)) + +### [5.0.1](https://www.github.com/yargs/y18n/compare/v5.0.0...v5.0.1) (2020-09-05) + + +### Bug Fixes + +* main had old index path ([#98](https://www.github.com/yargs/y18n/issues/98)) ([124f7b0](https://www.github.com/yargs/y18n/commit/124f7b047ba9596bdbdf64459988304e77f3de1b)) + +## [5.0.0](https://www.github.com/yargs/y18n/compare/v4.0.0...v5.0.0) (2020-09-05) + + +### ⚠ BREAKING CHANGES + +* exports maps are now used, which modifies import behavior. +* drops Node 6 and 4. begin following Node.js LTS schedule (#89) + +### Features + +* add support for ESM and Deno [#95](https://www.github.com/yargs/y18n/issues/95)) ([4d7ae94](https://www.github.com/yargs/y18n/commit/4d7ae94bcb42e84164e2180366474b1cd321ed94)) + + +### Build System + +* drops Node 6 and 4. begin following Node.js LTS schedule ([#89](https://www.github.com/yargs/y18n/issues/89)) ([3cc0c28](https://www.github.com/yargs/y18n/commit/3cc0c287240727b84eaf1927f903612ec80f5e43)) + +### 4.0.1 (2020-10-25) + + +### Bug Fixes + +* address prototype pollution issue ([#108](https://www.github.com/yargs/y18n/issues/108)) ([a9ac604](https://www.github.com/yargs/y18n/commit/7de58ca0d315990cdb38234e97fc66254cdbcd71)) + +## [4.0.0](https://github.com/yargs/y18n/compare/v3.2.1...v4.0.0) (2017-10-10) + + +### Bug Fixes + +* allow support for falsy values like 0 in tagged literal ([#45](https://github.com/yargs/y18n/issues/45)) ([c926123](https://github.com/yargs/y18n/commit/c926123)) + + +### Features + +* **__:** added tagged template literal support ([#44](https://github.com/yargs/y18n/issues/44)) ([0598daf](https://github.com/yargs/y18n/commit/0598daf)) + + +### BREAKING CHANGES + +* **__:** dropping Node 0.10/Node 0.12 support diff --git a/node_modules/y18n/LICENSE b/node_modules/y18n/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..3c157f0b9d9bed83163710392914df506bcb15b1 --- /dev/null +++ b/node_modules/y18n/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2015, Contributors + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. diff --git a/node_modules/y18n/README.md b/node_modules/y18n/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5102bb17dbd41847e8a3c07e0e3e9273fb9ea8c7 --- /dev/null +++ b/node_modules/y18n/README.md @@ -0,0 +1,127 @@ +# y18n + +[![NPM version][npm-image]][npm-url] +[![js-standard-style][standard-image]][standard-url] +[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) + +The bare-bones internationalization library used by yargs. + +Inspired by [i18n](https://www.npmjs.com/package/i18n). + +## Examples + +_simple string translation:_ + +```js +const __ = require('y18n')().__; + +console.log(__('my awesome string %s', 'foo')); +``` + +output: + +`my awesome string foo` + +_using tagged template literals_ + +```js +const __ = require('y18n')().__; + +const str = 'foo'; + +console.log(__`my awesome string ${str}`); +``` + +output: + +`my awesome string foo` + +_pluralization support:_ + +```js +const __n = require('y18n')().__n; + +console.log(__n('one fish %s', '%d fishes %s', 2, 'foo')); +``` + +output: + +`2 fishes foo` + +## Deno Example + +As of `v5` `y18n` supports [Deno](https://github.com/denoland/deno): + +```typescript +import y18n from "https://deno.land/x/y18n/deno.ts"; + +const __ = y18n({ + locale: 'pirate', + directory: './test/locales' +}).__ + +console.info(__`Hi, ${'Ben'} ${'Coe'}!`) +``` + +You will need to run with `--allow-read` to load alternative locales. + +## JSON Language Files + +The JSON language files should be stored in a `./locales` folder. +File names correspond to locales, e.g., `en.json`, `pirate.json`. + +When strings are observed for the first time they will be +added to the JSON file corresponding to the current locale. + +## Methods + +### require('y18n')(config) + +Create an instance of y18n with the config provided, options include: + +* `directory`: the locale directory, default `./locales`. +* `updateFiles`: should newly observed strings be updated in file, default `true`. +* `locale`: what locale should be used. +* `fallbackToLanguage`: should fallback to a language-only file (e.g. `en.json`) + be allowed if a file matching the locale does not exist (e.g. `en_US.json`), + default `true`. + +### y18n.\_\_(str, arg, arg, arg) + +Print a localized string, `%s` will be replaced with `arg`s. + +This function can also be used as a tag for a template literal. You can use it +like this: __`hello ${'world'}`. This will be equivalent to +`__('hello %s', 'world')`. + +### y18n.\_\_n(singularString, pluralString, count, arg, arg, arg) + +Print a localized string with appropriate pluralization. If `%d` is provided +in the string, the `count` will replace this placeholder. + +### y18n.setLocale(str) + +Set the current locale being used. + +### y18n.getLocale() + +What locale is currently being used? + +### y18n.updateLocale(obj) + +Update the current locale with the key value pairs in `obj`. + +## Supported Node.js Versions + +Libraries in this ecosystem make a best effort to track +[Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a +post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). + +## License + +ISC + +[npm-url]: https://npmjs.org/package/y18n +[npm-image]: https://img.shields.io/npm/v/y18n.svg +[standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg +[standard-url]: https://github.com/feross/standard diff --git a/node_modules/y18n/build/index.cjs b/node_modules/y18n/build/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..b2731e1a53de43288b7c0705ee9c2b5d96a9f44e --- /dev/null +++ b/node_modules/y18n/build/index.cjs @@ -0,0 +1,203 @@ +'use strict'; + +var fs = require('fs'); +var util = require('util'); +var path = require('path'); + +let shim; +class Y18N { + constructor(opts) { + // configurable options. + opts = opts || {}; + this.directory = opts.directory || './locales'; + this.updateFiles = typeof opts.updateFiles === 'boolean' ? opts.updateFiles : true; + this.locale = opts.locale || 'en'; + this.fallbackToLanguage = typeof opts.fallbackToLanguage === 'boolean' ? opts.fallbackToLanguage : true; + // internal stuff. + this.cache = Object.create(null); + this.writeQueue = []; + } + __(...args) { + if (typeof arguments[0] !== 'string') { + return this._taggedLiteral(arguments[0], ...arguments); + } + const str = args.shift(); + let cb = function () { }; // start with noop. + if (typeof args[args.length - 1] === 'function') + cb = args.pop(); + cb = cb || function () { }; // noop. + if (!this.cache[this.locale]) + this._readLocaleFile(); + // we've observed a new string, update the language file. + if (!this.cache[this.locale][str] && this.updateFiles) { + this.cache[this.locale][str] = str; + // include the current directory and locale, + // since these values could change before the + // write is performed. + this._enqueueWrite({ + directory: this.directory, + locale: this.locale, + cb + }); + } + else { + cb(); + } + return shim.format.apply(shim.format, [this.cache[this.locale][str] || str].concat(args)); + } + __n() { + const args = Array.prototype.slice.call(arguments); + const singular = args.shift(); + const plural = args.shift(); + const quantity = args.shift(); + let cb = function () { }; // start with noop. + if (typeof args[args.length - 1] === 'function') + cb = args.pop(); + if (!this.cache[this.locale]) + this._readLocaleFile(); + let str = quantity === 1 ? singular : plural; + if (this.cache[this.locale][singular]) { + const entry = this.cache[this.locale][singular]; + str = entry[quantity === 1 ? 'one' : 'other']; + } + // we've observed a new string, update the language file. + if (!this.cache[this.locale][singular] && this.updateFiles) { + this.cache[this.locale][singular] = { + one: singular, + other: plural + }; + // include the current directory and locale, + // since these values could change before the + // write is performed. + this._enqueueWrite({ + directory: this.directory, + locale: this.locale, + cb + }); + } + else { + cb(); + } + // if a %d placeholder is provided, add quantity + // to the arguments expanded by util.format. + const values = [str]; + if (~str.indexOf('%d')) + values.push(quantity); + return shim.format.apply(shim.format, values.concat(args)); + } + setLocale(locale) { + this.locale = locale; + } + getLocale() { + return this.locale; + } + updateLocale(obj) { + if (!this.cache[this.locale]) + this._readLocaleFile(); + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + this.cache[this.locale][key] = obj[key]; + } + } + } + _taggedLiteral(parts, ...args) { + let str = ''; + parts.forEach(function (part, i) { + const arg = args[i + 1]; + str += part; + if (typeof arg !== 'undefined') { + str += '%s'; + } + }); + return this.__.apply(this, [str].concat([].slice.call(args, 1))); + } + _enqueueWrite(work) { + this.writeQueue.push(work); + if (this.writeQueue.length === 1) + this._processWriteQueue(); + } + _processWriteQueue() { + const _this = this; + const work = this.writeQueue[0]; + // destructure the enqueued work. + const directory = work.directory; + const locale = work.locale; + const cb = work.cb; + const languageFile = this._resolveLocaleFile(directory, locale); + const serializedLocale = JSON.stringify(this.cache[locale], null, 2); + shim.fs.writeFile(languageFile, serializedLocale, 'utf-8', function (err) { + _this.writeQueue.shift(); + if (_this.writeQueue.length > 0) + _this._processWriteQueue(); + cb(err); + }); + } + _readLocaleFile() { + let localeLookup = {}; + const languageFile = this._resolveLocaleFile(this.directory, this.locale); + try { + // When using a bundler such as webpack, readFileSync may not be defined: + if (shim.fs.readFileSync) { + localeLookup = JSON.parse(shim.fs.readFileSync(languageFile, 'utf-8')); + } + } + catch (err) { + if (err instanceof SyntaxError) { + err.message = 'syntax error in ' + languageFile; + } + if (err.code === 'ENOENT') + localeLookup = {}; + else + throw err; + } + this.cache[this.locale] = localeLookup; + } + _resolveLocaleFile(directory, locale) { + let file = shim.resolve(directory, './', locale + '.json'); + if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf('_')) { + // attempt fallback to language only + const languageFile = shim.resolve(directory, './', locale.split('_')[0] + '.json'); + if (this._fileExistsSync(languageFile)) + file = languageFile; + } + return file; + } + _fileExistsSync(file) { + return shim.exists(file); + } +} +function y18n$1(opts, _shim) { + shim = _shim; + const y18n = new Y18N(opts); + return { + __: y18n.__.bind(y18n), + __n: y18n.__n.bind(y18n), + setLocale: y18n.setLocale.bind(y18n), + getLocale: y18n.getLocale.bind(y18n), + updateLocale: y18n.updateLocale.bind(y18n), + locale: y18n.locale + }; +} + +var nodePlatformShim = { + fs: { + readFileSync: fs.readFileSync, + writeFile: fs.writeFile + }, + format: util.format, + resolve: path.resolve, + exists: (file) => { + try { + return fs.statSync(file).isFile(); + } + catch (err) { + return false; + } + } +}; + +const y18n = (opts) => { + return y18n$1(opts, nodePlatformShim); +}; + +module.exports = y18n; diff --git a/node_modules/y18n/build/lib/cjs.js b/node_modules/y18n/build/lib/cjs.js new file mode 100644 index 0000000000000000000000000000000000000000..ff5847093ebdcdf8290758559893d704ba28e98b --- /dev/null +++ b/node_modules/y18n/build/lib/cjs.js @@ -0,0 +1,6 @@ +import { y18n as _y18n } from './index.js'; +import nodePlatformShim from './platform-shims/node.js'; +const y18n = (opts) => { + return _y18n(opts, nodePlatformShim); +}; +export default y18n; diff --git a/node_modules/y18n/build/lib/index.js b/node_modules/y18n/build/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e38f33594c158b6335ef049f35a0ed18abf7d2d0 --- /dev/null +++ b/node_modules/y18n/build/lib/index.js @@ -0,0 +1,174 @@ +let shim; +class Y18N { + constructor(opts) { + // configurable options. + opts = opts || {}; + this.directory = opts.directory || './locales'; + this.updateFiles = typeof opts.updateFiles === 'boolean' ? opts.updateFiles : true; + this.locale = opts.locale || 'en'; + this.fallbackToLanguage = typeof opts.fallbackToLanguage === 'boolean' ? opts.fallbackToLanguage : true; + // internal stuff. + this.cache = Object.create(null); + this.writeQueue = []; + } + __(...args) { + if (typeof arguments[0] !== 'string') { + return this._taggedLiteral(arguments[0], ...arguments); + } + const str = args.shift(); + let cb = function () { }; // start with noop. + if (typeof args[args.length - 1] === 'function') + cb = args.pop(); + cb = cb || function () { }; // noop. + if (!this.cache[this.locale]) + this._readLocaleFile(); + // we've observed a new string, update the language file. + if (!this.cache[this.locale][str] && this.updateFiles) { + this.cache[this.locale][str] = str; + // include the current directory and locale, + // since these values could change before the + // write is performed. + this._enqueueWrite({ + directory: this.directory, + locale: this.locale, + cb + }); + } + else { + cb(); + } + return shim.format.apply(shim.format, [this.cache[this.locale][str] || str].concat(args)); + } + __n() { + const args = Array.prototype.slice.call(arguments); + const singular = args.shift(); + const plural = args.shift(); + const quantity = args.shift(); + let cb = function () { }; // start with noop. + if (typeof args[args.length - 1] === 'function') + cb = args.pop(); + if (!this.cache[this.locale]) + this._readLocaleFile(); + let str = quantity === 1 ? singular : plural; + if (this.cache[this.locale][singular]) { + const entry = this.cache[this.locale][singular]; + str = entry[quantity === 1 ? 'one' : 'other']; + } + // we've observed a new string, update the language file. + if (!this.cache[this.locale][singular] && this.updateFiles) { + this.cache[this.locale][singular] = { + one: singular, + other: plural + }; + // include the current directory and locale, + // since these values could change before the + // write is performed. + this._enqueueWrite({ + directory: this.directory, + locale: this.locale, + cb + }); + } + else { + cb(); + } + // if a %d placeholder is provided, add quantity + // to the arguments expanded by util.format. + const values = [str]; + if (~str.indexOf('%d')) + values.push(quantity); + return shim.format.apply(shim.format, values.concat(args)); + } + setLocale(locale) { + this.locale = locale; + } + getLocale() { + return this.locale; + } + updateLocale(obj) { + if (!this.cache[this.locale]) + this._readLocaleFile(); + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + this.cache[this.locale][key] = obj[key]; + } + } + } + _taggedLiteral(parts, ...args) { + let str = ''; + parts.forEach(function (part, i) { + const arg = args[i + 1]; + str += part; + if (typeof arg !== 'undefined') { + str += '%s'; + } + }); + return this.__.apply(this, [str].concat([].slice.call(args, 1))); + } + _enqueueWrite(work) { + this.writeQueue.push(work); + if (this.writeQueue.length === 1) + this._processWriteQueue(); + } + _processWriteQueue() { + const _this = this; + const work = this.writeQueue[0]; + // destructure the enqueued work. + const directory = work.directory; + const locale = work.locale; + const cb = work.cb; + const languageFile = this._resolveLocaleFile(directory, locale); + const serializedLocale = JSON.stringify(this.cache[locale], null, 2); + shim.fs.writeFile(languageFile, serializedLocale, 'utf-8', function (err) { + _this.writeQueue.shift(); + if (_this.writeQueue.length > 0) + _this._processWriteQueue(); + cb(err); + }); + } + _readLocaleFile() { + let localeLookup = {}; + const languageFile = this._resolveLocaleFile(this.directory, this.locale); + try { + // When using a bundler such as webpack, readFileSync may not be defined: + if (shim.fs.readFileSync) { + localeLookup = JSON.parse(shim.fs.readFileSync(languageFile, 'utf-8')); + } + } + catch (err) { + if (err instanceof SyntaxError) { + err.message = 'syntax error in ' + languageFile; + } + if (err.code === 'ENOENT') + localeLookup = {}; + else + throw err; + } + this.cache[this.locale] = localeLookup; + } + _resolveLocaleFile(directory, locale) { + let file = shim.resolve(directory, './', locale + '.json'); + if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf('_')) { + // attempt fallback to language only + const languageFile = shim.resolve(directory, './', locale.split('_')[0] + '.json'); + if (this._fileExistsSync(languageFile)) + file = languageFile; + } + return file; + } + _fileExistsSync(file) { + return shim.exists(file); + } +} +export function y18n(opts, _shim) { + shim = _shim; + const y18n = new Y18N(opts); + return { + __: y18n.__.bind(y18n), + __n: y18n.__n.bind(y18n), + setLocale: y18n.setLocale.bind(y18n), + getLocale: y18n.getLocale.bind(y18n), + updateLocale: y18n.updateLocale.bind(y18n), + locale: y18n.locale + }; +} diff --git a/node_modules/y18n/build/lib/platform-shims/node.js b/node_modules/y18n/build/lib/platform-shims/node.js new file mode 100644 index 0000000000000000000000000000000000000000..181208b81fcaa9d6916aed072abc7ff580781d6c --- /dev/null +++ b/node_modules/y18n/build/lib/platform-shims/node.js @@ -0,0 +1,19 @@ +import { readFileSync, statSync, writeFile } from 'fs'; +import { format } from 'util'; +import { resolve } from 'path'; +export default { + fs: { + readFileSync, + writeFile + }, + format, + resolve, + exists: (file) => { + try { + return statSync(file).isFile(); + } + catch (err) { + return false; + } + } +}; diff --git a/node_modules/y18n/index.mjs b/node_modules/y18n/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..46c82133c91d2fd6582c5cbf280232eb83bc4a2f --- /dev/null +++ b/node_modules/y18n/index.mjs @@ -0,0 +1,8 @@ +import shim from './build/lib/platform-shims/node.js' +import { y18n as _y18n } from './build/lib/index.js' + +const y18n = (opts) => { + return _y18n(opts, shim) +} + +export default y18n diff --git a/node_modules/y18n/package.json b/node_modules/y18n/package.json new file mode 100644 index 0000000000000000000000000000000000000000..4e5c1ca6029714c76f51a0f19ac92d0c4cff19be --- /dev/null +++ b/node_modules/y18n/package.json @@ -0,0 +1,70 @@ +{ + "name": "y18n", + "version": "5.0.8", + "description": "the bare-bones internationalization library used by yargs", + "exports": { + ".": [ + { + "import": "./index.mjs", + "require": "./build/index.cjs" + }, + "./build/index.cjs" + ] + }, + "type": "module", + "module": "./build/lib/index.js", + "keywords": [ + "i18n", + "internationalization", + "yargs" + ], + "homepage": "https://github.com/yargs/y18n", + "bugs": { + "url": "https://github.com/yargs/y18n/issues" + }, + "repository": "yargs/y18n", + "license": "ISC", + "author": "Ben Coe ", + "main": "./build/index.cjs", + "scripts": { + "check": "standardx **/*.ts **/*.cjs **/*.mjs", + "fix": "standardx --fix **/*.ts **/*.cjs **/*.mjs", + "pretest": "rimraf build && tsc -p tsconfig.test.json && cross-env NODE_ENV=test npm run build:cjs", + "test": "c8 --reporter=text --reporter=html mocha test/*.cjs", + "test:esm": "c8 --reporter=text --reporter=html mocha test/esm/*.mjs", + "posttest": "npm run check", + "coverage": "c8 report --check-coverage", + "precompile": "rimraf build", + "compile": "tsc", + "postcompile": "npm run build:cjs", + "build:cjs": "rollup -c", + "prepare": "npm run compile" + }, + "devDependencies": { + "@types/node": "^14.6.4", + "@wessberg/rollup-plugin-ts": "^1.3.1", + "c8": "^7.3.0", + "chai": "^4.0.1", + "cross-env": "^7.0.2", + "gts": "^3.0.0", + "mocha": "^8.0.0", + "rimraf": "^3.0.2", + "rollup": "^2.26.10", + "standardx": "^7.0.0", + "ts-transform-default-export": "^1.0.2", + "typescript": "^4.0.0" + }, + "files": [ + "build", + "index.mjs", + "!*.d.ts" + ], + "engines": { + "node": ">=10" + }, + "standardx": { + "ignore": [ + "build" + ] + } +} diff --git a/node_modules/yallist/LICENSE b/node_modules/yallist/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..19129e315fe593965a2fdd50ec0d1253bcbd2ece --- /dev/null +++ b/node_modules/yallist/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/yallist/README.md b/node_modules/yallist/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f5861018696688887f69d055dd7d3ef54b38ebdc --- /dev/null +++ b/node_modules/yallist/README.md @@ -0,0 +1,204 @@ +# yallist + +Yet Another Linked List + +There are many doubly-linked list implementations like it, but this +one is mine. + +For when an array would be too big, and a Map can't be iterated in +reverse order. + + +[![Build Status](https://travis-ci.org/isaacs/yallist.svg?branch=master)](https://travis-ci.org/isaacs/yallist) [![Coverage Status](https://coveralls.io/repos/isaacs/yallist/badge.svg?service=github)](https://coveralls.io/github/isaacs/yallist) + +## basic usage + +```javascript +var yallist = require('yallist') +var myList = yallist.create([1, 2, 3]) +myList.push('foo') +myList.unshift('bar') +// of course pop() and shift() are there, too +console.log(myList.toArray()) // ['bar', 1, 2, 3, 'foo'] +myList.forEach(function (k) { + // walk the list head to tail +}) +myList.forEachReverse(function (k, index, list) { + // walk the list tail to head +}) +var myDoubledList = myList.map(function (k) { + return k + k +}) +// now myDoubledList contains ['barbar', 2, 4, 6, 'foofoo'] +// mapReverse is also a thing +var myDoubledListReverse = myList.mapReverse(function (k) { + return k + k +}) // ['foofoo', 6, 4, 2, 'barbar'] + +var reduced = myList.reduce(function (set, entry) { + set += entry + return set +}, 'start') +console.log(reduced) // 'startfoo123bar' +``` + +## api + +The whole API is considered "public". + +Functions with the same name as an Array method work more or less the +same way. + +There's reverse versions of most things because that's the point. + +### Yallist + +Default export, the class that holds and manages a list. + +Call it with either a forEach-able (like an array) or a set of +arguments, to initialize the list. + +The Array-ish methods all act like you'd expect. No magic length, +though, so if you change that it won't automatically prune or add +empty spots. + +### Yallist.create(..) + +Alias for Yallist function. Some people like factories. + +#### yallist.head + +The first node in the list + +#### yallist.tail + +The last node in the list + +#### yallist.length + +The number of nodes in the list. (Change this at your peril. It is +not magic like Array length.) + +#### yallist.toArray() + +Convert the list to an array. + +#### yallist.forEach(fn, [thisp]) + +Call a function on each item in the list. + +#### yallist.forEachReverse(fn, [thisp]) + +Call a function on each item in the list, in reverse order. + +#### yallist.get(n) + +Get the data at position `n` in the list. If you use this a lot, +probably better off just using an Array. + +#### yallist.getReverse(n) + +Get the data at position `n`, counting from the tail. + +#### yallist.map(fn, thisp) + +Create a new Yallist with the result of calling the function on each +item. + +#### yallist.mapReverse(fn, thisp) + +Same as `map`, but in reverse. + +#### yallist.pop() + +Get the data from the list tail, and remove the tail from the list. + +#### yallist.push(item, ...) + +Insert one or more items to the tail of the list. + +#### yallist.reduce(fn, initialValue) + +Like Array.reduce. + +#### yallist.reduceReverse + +Like Array.reduce, but in reverse. + +#### yallist.reverse + +Reverse the list in place. + +#### yallist.shift() + +Get the data from the list head, and remove the head from the list. + +#### yallist.slice([from], [to]) + +Just like Array.slice, but returns a new Yallist. + +#### yallist.sliceReverse([from], [to]) + +Just like yallist.slice, but the result is returned in reverse. + +#### yallist.toArray() + +Create an array representation of the list. + +#### yallist.toArrayReverse() + +Create a reversed array representation of the list. + +#### yallist.unshift(item, ...) + +Insert one or more items to the head of the list. + +#### yallist.unshiftNode(node) + +Move a Node object to the front of the list. (That is, pull it out of +wherever it lives, and make it the new head.) + +If the node belongs to a different list, then that list will remove it +first. + +#### yallist.pushNode(node) + +Move a Node object to the end of the list. (That is, pull it out of +wherever it lives, and make it the new tail.) + +If the node belongs to a list already, then that list will remove it +first. + +#### yallist.removeNode(node) + +Remove a node from the list, preserving referential integrity of head +and tail and other nodes. + +Will throw an error if you try to have a list remove a node that +doesn't belong to it. + +### Yallist.Node + +The class that holds the data and is actually the list. + +Call with `var n = new Node(value, previousNode, nextNode)` + +Note that if you do direct operations on Nodes themselves, it's very +easy to get into weird states where the list is broken. Be careful :) + +#### node.next + +The next node in the list. + +#### node.prev + +The previous node in the list. + +#### node.value + +The data the node contains. + +#### node.list + +The list to which this node belongs. (Null if it does not belong to +any list.) diff --git a/node_modules/yallist/iterator.js b/node_modules/yallist/iterator.js new file mode 100644 index 0000000000000000000000000000000000000000..d41c97a19f98495928bd657b330d3b687699e78c --- /dev/null +++ b/node_modules/yallist/iterator.js @@ -0,0 +1,8 @@ +'use strict' +module.exports = function (Yallist) { + Yallist.prototype[Symbol.iterator] = function* () { + for (let walker = this.head; walker; walker = walker.next) { + yield walker.value + } + } +} diff --git a/node_modules/yallist/package.json b/node_modules/yallist/package.json new file mode 100644 index 0000000000000000000000000000000000000000..271280992323aed8e192323c2907db530a48acb1 --- /dev/null +++ b/node_modules/yallist/package.json @@ -0,0 +1,29 @@ +{ + "name": "yallist", + "version": "3.1.1", + "description": "Yet Another Linked List", + "main": "yallist.js", + "directories": { + "test": "test" + }, + "files": [ + "yallist.js", + "iterator.js" + ], + "dependencies": {}, + "devDependencies": { + "tap": "^12.1.0" + }, + "scripts": { + "test": "tap test/*.js --100", + "preversion": "npm test", + "postversion": "npm publish", + "postpublish": "git push origin --all; git push origin --tags" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/isaacs/yallist.git" + }, + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC" +} diff --git a/node_modules/yallist/yallist.js b/node_modules/yallist/yallist.js new file mode 100644 index 0000000000000000000000000000000000000000..ed4e7303aa47d3e11cd8993666a101bde88834d6 --- /dev/null +++ b/node_modules/yallist/yallist.js @@ -0,0 +1,426 @@ +'use strict' +module.exports = Yallist + +Yallist.Node = Node +Yallist.create = Yallist + +function Yallist (list) { + var self = this + if (!(self instanceof Yallist)) { + self = new Yallist() + } + + self.tail = null + self.head = null + self.length = 0 + + if (list && typeof list.forEach === 'function') { + list.forEach(function (item) { + self.push(item) + }) + } else if (arguments.length > 0) { + for (var i = 0, l = arguments.length; i < l; i++) { + self.push(arguments[i]) + } + } + + return self +} + +Yallist.prototype.removeNode = function (node) { + if (node.list !== this) { + throw new Error('removing node which does not belong to this list') + } + + var next = node.next + var prev = node.prev + + if (next) { + next.prev = prev + } + + if (prev) { + prev.next = next + } + + if (node === this.head) { + this.head = next + } + if (node === this.tail) { + this.tail = prev + } + + node.list.length-- + node.next = null + node.prev = null + node.list = null + + return next +} + +Yallist.prototype.unshiftNode = function (node) { + if (node === this.head) { + return + } + + if (node.list) { + node.list.removeNode(node) + } + + var head = this.head + node.list = this + node.next = head + if (head) { + head.prev = node + } + + this.head = node + if (!this.tail) { + this.tail = node + } + this.length++ +} + +Yallist.prototype.pushNode = function (node) { + if (node === this.tail) { + return + } + + if (node.list) { + node.list.removeNode(node) + } + + var tail = this.tail + node.list = this + node.prev = tail + if (tail) { + tail.next = node + } + + this.tail = node + if (!this.head) { + this.head = node + } + this.length++ +} + +Yallist.prototype.push = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + push(this, arguments[i]) + } + return this.length +} + +Yallist.prototype.unshift = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + unshift(this, arguments[i]) + } + return this.length +} + +Yallist.prototype.pop = function () { + if (!this.tail) { + return undefined + } + + var res = this.tail.value + this.tail = this.tail.prev + if (this.tail) { + this.tail.next = null + } else { + this.head = null + } + this.length-- + return res +} + +Yallist.prototype.shift = function () { + if (!this.head) { + return undefined + } + + var res = this.head.value + this.head = this.head.next + if (this.head) { + this.head.prev = null + } else { + this.tail = null + } + this.length-- + return res +} + +Yallist.prototype.forEach = function (fn, thisp) { + thisp = thisp || this + for (var walker = this.head, i = 0; walker !== null; i++) { + fn.call(thisp, walker.value, i, this) + walker = walker.next + } +} + +Yallist.prototype.forEachReverse = function (fn, thisp) { + thisp = thisp || this + for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { + fn.call(thisp, walker.value, i, this) + walker = walker.prev + } +} + +Yallist.prototype.get = function (n) { + for (var i = 0, walker = this.head; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.next + } + if (i === n && walker !== null) { + return walker.value + } +} + +Yallist.prototype.getReverse = function (n) { + for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.prev + } + if (i === n && walker !== null) { + return walker.value + } +} + +Yallist.prototype.map = function (fn, thisp) { + thisp = thisp || this + var res = new Yallist() + for (var walker = this.head; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)) + walker = walker.next + } + return res +} + +Yallist.prototype.mapReverse = function (fn, thisp) { + thisp = thisp || this + var res = new Yallist() + for (var walker = this.tail; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)) + walker = walker.prev + } + return res +} + +Yallist.prototype.reduce = function (fn, initial) { + var acc + var walker = this.head + if (arguments.length > 1) { + acc = initial + } else if (this.head) { + walker = this.head.next + acc = this.head.value + } else { + throw new TypeError('Reduce of empty list with no initial value') + } + + for (var i = 0; walker !== null; i++) { + acc = fn(acc, walker.value, i) + walker = walker.next + } + + return acc +} + +Yallist.prototype.reduceReverse = function (fn, initial) { + var acc + var walker = this.tail + if (arguments.length > 1) { + acc = initial + } else if (this.tail) { + walker = this.tail.prev + acc = this.tail.value + } else { + throw new TypeError('Reduce of empty list with no initial value') + } + + for (var i = this.length - 1; walker !== null; i--) { + acc = fn(acc, walker.value, i) + walker = walker.prev + } + + return acc +} + +Yallist.prototype.toArray = function () { + var arr = new Array(this.length) + for (var i = 0, walker = this.head; walker !== null; i++) { + arr[i] = walker.value + walker = walker.next + } + return arr +} + +Yallist.prototype.toArrayReverse = function () { + var arr = new Array(this.length) + for (var i = 0, walker = this.tail; walker !== null; i++) { + arr[i] = walker.value + walker = walker.prev + } + return arr +} + +Yallist.prototype.slice = function (from, to) { + to = to || this.length + if (to < 0) { + to += this.length + } + from = from || 0 + if (from < 0) { + from += this.length + } + var ret = new Yallist() + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0 + } + if (to > this.length) { + to = this.length + } + for (var i = 0, walker = this.head; walker !== null && i < from; i++) { + walker = walker.next + } + for (; walker !== null && i < to; i++, walker = walker.next) { + ret.push(walker.value) + } + return ret +} + +Yallist.prototype.sliceReverse = function (from, to) { + to = to || this.length + if (to < 0) { + to += this.length + } + from = from || 0 + if (from < 0) { + from += this.length + } + var ret = new Yallist() + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0 + } + if (to > this.length) { + to = this.length + } + for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { + walker = walker.prev + } + for (; walker !== null && i > from; i--, walker = walker.prev) { + ret.push(walker.value) + } + return ret +} + +Yallist.prototype.splice = function (start, deleteCount /*, ...nodes */) { + if (start > this.length) { + start = this.length - 1 + } + if (start < 0) { + start = this.length + start; + } + + for (var i = 0, walker = this.head; walker !== null && i < start; i++) { + walker = walker.next + } + + var ret = [] + for (var i = 0; walker && i < deleteCount; i++) { + ret.push(walker.value) + walker = this.removeNode(walker) + } + if (walker === null) { + walker = this.tail + } + + if (walker !== this.head && walker !== this.tail) { + walker = walker.prev + } + + for (var i = 2; i < arguments.length; i++) { + walker = insert(this, walker, arguments[i]) + } + return ret; +} + +Yallist.prototype.reverse = function () { + var head = this.head + var tail = this.tail + for (var walker = head; walker !== null; walker = walker.prev) { + var p = walker.prev + walker.prev = walker.next + walker.next = p + } + this.head = tail + this.tail = head + return this +} + +function insert (self, node, value) { + var inserted = node === self.head ? + new Node(value, null, node, self) : + new Node(value, node, node.next, self) + + if (inserted.next === null) { + self.tail = inserted + } + if (inserted.prev === null) { + self.head = inserted + } + + self.length++ + + return inserted +} + +function push (self, item) { + self.tail = new Node(item, self.tail, null, self) + if (!self.head) { + self.head = self.tail + } + self.length++ +} + +function unshift (self, item) { + self.head = new Node(item, null, self.head, self) + if (!self.tail) { + self.tail = self.head + } + self.length++ +} + +function Node (value, prev, next, list) { + if (!(this instanceof Node)) { + return new Node(value, prev, next, list) + } + + this.list = list + this.value = value + + if (prev) { + prev.next = this + this.prev = prev + } else { + this.prev = null + } + + if (next) { + next.prev = this + this.next = next + } else { + this.next = null + } +} + +try { + // add if support for Symbol.iterator is present + require('./iterator.js')(Yallist) +} catch (er) {} diff --git a/node_modules/yargs-parser/CHANGELOG.md b/node_modules/yargs-parser/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..f58acb863c933d05a2814fd985728e068065e84e --- /dev/null +++ b/node_modules/yargs-parser/CHANGELOG.md @@ -0,0 +1,319 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +## [22.0.0](https://github.com/yargs/yargs-parser/compare/yargs-parser-v21.1.1...yargs-parser-v22.0.0) (2025-05-26) + + +### ⚠ BREAKING CHANGES + +* yargs is now ESM first ([#503](https://github.com/yargs/yargs-parser/issues/503)) + +### Features + +* yargs is now ESM first ([#503](https://github.com/yargs/yargs-parser/issues/503)) ([6d69295](https://github.com/yargs/yargs-parser/commit/6d692953ade099375c6c5e131367968b07ae8470)) + +## [21.1.1](https://github.com/yargs/yargs-parser/compare/yargs-parser-v21.1.0...yargs-parser-v21.1.1) (2022-08-04) + + +### Bug Fixes + +* **typescript:** ignore .cts files during publish ([#454](https://github.com/yargs/yargs-parser/issues/454)) ([d69f9c3](https://github.com/yargs/yargs-parser/commit/d69f9c3a91c3ad2f9494d0a94e29a8b76c41b81b)), closes [#452](https://github.com/yargs/yargs-parser/issues/452) + +## [21.1.0](https://github.com/yargs/yargs-parser/compare/yargs-parser-v21.0.1...yargs-parser-v21.1.0) (2022-08-03) + + +### Features + +* allow the browser build to be imported ([#443](https://github.com/yargs/yargs-parser/issues/443)) ([a89259f](https://github.com/yargs/yargs-parser/commit/a89259ff41d6f5312b3ce8a30bef343a993f395a)) + + +### Bug Fixes + +* **halt-at-non-option:** prevent known args from being parsed when "unknown-options-as-args" is enabled ([#438](https://github.com/yargs/yargs-parser/issues/438)) ([c474bc1](https://github.com/yargs/yargs-parser/commit/c474bc10c3aa0ae864b95e5722730114ef15f573)) +* node version check now uses process.versions.node ([#450](https://github.com/yargs/yargs-parser/issues/450)) ([d07bcdb](https://github.com/yargs/yargs-parser/commit/d07bcdbe43075f7201fbe8a08e491217247fe1f1)) +* parse options ending with 3+ hyphens ([#434](https://github.com/yargs/yargs-parser/issues/434)) ([4f1060b](https://github.com/yargs/yargs-parser/commit/4f1060b50759fadbac3315c5117b0c3d65b0a7d8)) + +### [21.0.1](https://github.com/yargs/yargs-parser/compare/yargs-parser-v21.0.0...yargs-parser-v21.0.1) (2022-02-27) + + +### Bug Fixes + +* return deno env object ([#432](https://github.com/yargs/yargs-parser/issues/432)) ([b00eb87](https://github.com/yargs/yargs-parser/commit/b00eb87b4860a890dd2dab0d6058241bbfd2b3ec)) + +## [21.0.0](https://www.github.com/yargs/yargs-parser/compare/yargs-parser-v20.2.9...yargs-parser-v21.0.0) (2021-11-15) + + +### ⚠ BREAKING CHANGES + +* drops support for 10 (#421) + +### Bug Fixes + +* esm json import ([#416](https://www.github.com/yargs/yargs-parser/issues/416)) ([90f970a](https://www.github.com/yargs/yargs-parser/commit/90f970a6482dd4f5b5eb18d38596dd6f02d73edf)) +* parser should preserve inner quotes ([#407](https://www.github.com/yargs/yargs-parser/issues/407)) ([ae11f49](https://www.github.com/yargs/yargs-parser/commit/ae11f496a8318ea8885aa25015d429b33713c314)) + + +### Code Refactoring + +* drops support for 10 ([#421](https://www.github.com/yargs/yargs-parser/issues/421)) ([3aaf878](https://www.github.com/yargs/yargs-parser/commit/3aaf8784f5c7f2aec6108c1c6a55537fa7e3b5c1)) + +### [20.2.9](https://www.github.com/yargs/yargs-parser/compare/yargs-parser-v20.2.8...yargs-parser-v20.2.9) (2021-06-20) + + +### Bug Fixes + +* **build:** fixed automated release pipeline ([1fe9135](https://www.github.com/yargs/yargs-parser/commit/1fe9135884790a083615419b2861683e2597dac3)) + +### [20.2.8](https://www.github.com/yargs/yargs-parser/compare/yargs-parser-v20.2.7...yargs-parser-v20.2.8) (2021-06-20) + + +### Bug Fixes + +* **locale:** Turkish camelize and decamelize issues with toLocaleLowerCase/toLocaleUpperCase ([2617303](https://www.github.com/yargs/yargs-parser/commit/261730383e02448562f737b94bbd1f164aed5143)) +* **perf:** address slow parse when using unknown-options-as-args ([#394](https://www.github.com/yargs/yargs-parser/issues/394)) ([441f059](https://www.github.com/yargs/yargs-parser/commit/441f059d585d446551068ad213db79ac91daf83a)) +* **string-utils:** detect [0,1] ranged values as numbers ([#388](https://www.github.com/yargs/yargs-parser/issues/388)) ([efcc32c](https://www.github.com/yargs/yargs-parser/commit/efcc32c2d6b09aba31abfa2db9bd947befe5586b)) + +### [20.2.7](https://www.github.com/yargs/yargs-parser/compare/v20.2.6...v20.2.7) (2021-03-10) + + +### Bug Fixes + +* **deno:** force release for Deno ([6687c97](https://www.github.com/yargs/yargs-parser/commit/6687c972d0f3ca7865a97908dde3080b05f8b026)) + +### [20.2.6](https://www.github.com/yargs/yargs-parser/compare/v20.2.5...v20.2.6) (2021-02-22) + + +### Bug Fixes + +* **populate--:** -- should always be array ([#354](https://www.github.com/yargs/yargs-parser/issues/354)) ([585ae8f](https://www.github.com/yargs/yargs-parser/commit/585ae8ffad74cc02974f92d788e750137fd65146)) + +### [20.2.5](https://www.github.com/yargs/yargs-parser/compare/v20.2.4...v20.2.5) (2021-02-13) + + +### Bug Fixes + +* do not lowercase camel cased string ([#348](https://www.github.com/yargs/yargs-parser/issues/348)) ([5f4da1f](https://www.github.com/yargs/yargs-parser/commit/5f4da1f17d9d50542d2aaa206c9806ce3e320335)) + +### [20.2.4](https://www.github.com/yargs/yargs-parser/compare/v20.2.3...v20.2.4) (2020-11-09) + + +### Bug Fixes + +* **deno:** address import issues in Deno ([#339](https://www.github.com/yargs/yargs-parser/issues/339)) ([3b54e5e](https://www.github.com/yargs/yargs-parser/commit/3b54e5eef6e9a7b7c6eec7c12bab3ba3b8ba8306)) + +### [20.2.3](https://www.github.com/yargs/yargs-parser/compare/v20.2.2...v20.2.3) (2020-10-16) + + +### Bug Fixes + +* **exports:** node 13.0 and 13.1 require the dotted object form _with_ a string fallback ([#336](https://www.github.com/yargs/yargs-parser/issues/336)) ([3ae7242](https://www.github.com/yargs/yargs-parser/commit/3ae7242040ff876d28dabded60ac226e00150c88)) + +### [20.2.2](https://www.github.com/yargs/yargs-parser/compare/v20.2.1...v20.2.2) (2020-10-14) + + +### Bug Fixes + +* **exports:** node 13.0-13.6 require a string fallback ([#333](https://www.github.com/yargs/yargs-parser/issues/333)) ([291aeda](https://www.github.com/yargs/yargs-parser/commit/291aeda06b685b7a015d83bdf2558e180b37388d)) + +### [20.2.1](https://www.github.com/yargs/yargs-parser/compare/v20.2.0...v20.2.1) (2020-10-01) + + +### Bug Fixes + +* **deno:** update types for deno ^1.4.0 ([#330](https://www.github.com/yargs/yargs-parser/issues/330)) ([0ab92e5](https://www.github.com/yargs/yargs-parser/commit/0ab92e50b090f11196334c048c9c92cecaddaf56)) + +## [20.2.0](https://www.github.com/yargs/yargs-parser/compare/v20.1.0...v20.2.0) (2020-09-21) + + +### Features + +* **string-utils:** export looksLikeNumber helper ([#324](https://www.github.com/yargs/yargs-parser/issues/324)) ([c8580a2](https://www.github.com/yargs/yargs-parser/commit/c8580a2327b55f6342acecb6e72b62963d506750)) + + +### Bug Fixes + +* **unknown-options-as-args:** convert positionals that look like numbers ([#326](https://www.github.com/yargs/yargs-parser/issues/326)) ([f85ebb4](https://www.github.com/yargs/yargs-parser/commit/f85ebb4face9d4b0f56147659404cbe0002f3dad)) + +## [20.1.0](https://www.github.com/yargs/yargs-parser/compare/v20.0.0...v20.1.0) (2020-09-20) + + +### Features + +* adds parse-positional-numbers configuration ([#321](https://www.github.com/yargs/yargs-parser/issues/321)) ([9cec00a](https://www.github.com/yargs/yargs-parser/commit/9cec00a622251292ffb7dce6f78f5353afaa0d4c)) + + +### Bug Fixes + +* **build:** update release-please; make labels kick off builds ([#323](https://www.github.com/yargs/yargs-parser/issues/323)) ([09f448b](https://www.github.com/yargs/yargs-parser/commit/09f448b4cd66e25d2872544718df46dab8af062a)) + +## [20.0.0](https://www.github.com/yargs/yargs-parser/compare/v19.0.4...v20.0.0) (2020-09-09) + + +### ⚠ BREAKING CHANGES + +* do not ship type definitions (#318) + +### Bug Fixes + +* only strip camel case if hyphenated ([#316](https://www.github.com/yargs/yargs-parser/issues/316)) ([95a9e78](https://www.github.com/yargs/yargs-parser/commit/95a9e785127b9bbf2d1db1f1f808ca1fb100e82a)), closes [#315](https://www.github.com/yargs/yargs-parser/issues/315) + + +### Code Refactoring + +* do not ship type definitions ([#318](https://www.github.com/yargs/yargs-parser/issues/318)) ([8fbd56f](https://www.github.com/yargs/yargs-parser/commit/8fbd56f1d0b6c44c30fca62708812151ca0ce330)) + +### [19.0.4](https://www.github.com/yargs/yargs-parser/compare/v19.0.3...v19.0.4) (2020-08-27) + + +### Bug Fixes + +* **build:** fixing publication ([#310](https://www.github.com/yargs/yargs-parser/issues/310)) ([5d3c6c2](https://www.github.com/yargs/yargs-parser/commit/5d3c6c29a9126248ba601920d9cf87c78e161ff5)) + +### [19.0.3](https://www.github.com/yargs/yargs-parser/compare/v19.0.2...v19.0.3) (2020-08-27) + + +### Bug Fixes + +* **build:** switch to action for publish ([#308](https://www.github.com/yargs/yargs-parser/issues/308)) ([5c2f305](https://www.github.com/yargs/yargs-parser/commit/5c2f30585342bcd8aaf926407c863099d256d174)) + +### [19.0.2](https://www.github.com/yargs/yargs-parser/compare/v19.0.1...v19.0.2) (2020-08-27) + + +### Bug Fixes + +* **types:** envPrefix should be optional ([#305](https://www.github.com/yargs/yargs-parser/issues/305)) ([ae3f180](https://www.github.com/yargs/yargs-parser/commit/ae3f180e14df2de2fd962145f4518f9aa0e76523)) + +### [19.0.1](https://www.github.com/yargs/yargs-parser/compare/v19.0.0...v19.0.1) (2020-08-09) + + +### Bug Fixes + +* **build:** push tag created for deno ([2186a14](https://www.github.com/yargs/yargs-parser/commit/2186a14989749887d56189867602e39e6679f8b0)) + +## [19.0.0](https://www.github.com/yargs/yargs-parser/compare/v18.1.3...v19.0.0) (2020-08-09) + + +### ⚠ BREAKING CHANGES + +* adds support for ESM and Deno (#295) +* **ts:** projects using `@types/yargs-parser` may see variations in type definitions. +* drops Node 6. begin following Node.js LTS schedule (#278) + +### Features + +* adds support for ESM and Deno ([#295](https://www.github.com/yargs/yargs-parser/issues/295)) ([195bc4a](https://www.github.com/yargs/yargs-parser/commit/195bc4a7f20c2a8f8e33fbb6ba96ef6e9a0120a1)) +* expose camelCase and decamelize helpers ([#296](https://www.github.com/yargs/yargs-parser/issues/296)) ([39154ce](https://www.github.com/yargs/yargs-parser/commit/39154ceb5bdcf76b5f59a9219b34cedb79b67f26)) +* **deps:** update to latest camelcase/decamelize ([#281](https://www.github.com/yargs/yargs-parser/issues/281)) ([8931ab0](https://www.github.com/yargs/yargs-parser/commit/8931ab08f686cc55286f33a95a83537da2be5516)) + + +### Bug Fixes + +* boolean numeric short option ([#294](https://www.github.com/yargs/yargs-parser/issues/294)) ([f600082](https://www.github.com/yargs/yargs-parser/commit/f600082c959e092076caf420bbbc9d7a231e2418)) +* raise permission error for Deno if config load fails ([#298](https://www.github.com/yargs/yargs-parser/issues/298)) ([1174e2b](https://www.github.com/yargs/yargs-parser/commit/1174e2b3f0c845a1cd64e14ffc3703e730567a84)) +* **deps:** update dependency decamelize to v3 ([#274](https://www.github.com/yargs/yargs-parser/issues/274)) ([4d98698](https://www.github.com/yargs/yargs-parser/commit/4d98698bc6767e84ec54a0842908191739be73b7)) +* **types:** switch back to using Partial types ([#293](https://www.github.com/yargs/yargs-parser/issues/293)) ([bdc80ba](https://www.github.com/yargs/yargs-parser/commit/bdc80ba59fa13bc3025ce0a85e8bad9f9da24ea7)) + + +### Build System + +* drops Node 6. begin following Node.js LTS schedule ([#278](https://www.github.com/yargs/yargs-parser/issues/278)) ([9014ed7](https://www.github.com/yargs/yargs-parser/commit/9014ed722a32768b96b829e65a31705db5c1458a)) + + +### Code Refactoring + +* **ts:** move index.js to TypeScript ([#292](https://www.github.com/yargs/yargs-parser/issues/292)) ([f78d2b9](https://www.github.com/yargs/yargs-parser/commit/f78d2b97567ac4828624406e420b4047c710b789)) + +### [18.1.3](https://www.github.com/yargs/yargs-parser/compare/v18.1.2...v18.1.3) (2020-04-16) + + +### Bug Fixes + +* **setArg:** options using camel-case and dot-notation populated twice ([#268](https://www.github.com/yargs/yargs-parser/issues/268)) ([f7e15b9](https://www.github.com/yargs/yargs-parser/commit/f7e15b9800900b9856acac1a830a5f35847be73e)) + +### [18.1.2](https://www.github.com/yargs/yargs-parser/compare/v18.1.1...v18.1.2) (2020-03-26) + + +### Bug Fixes + +* **array, nargs:** support -o=--value and --option=--value format ([#262](https://www.github.com/yargs/yargs-parser/issues/262)) ([41d3f81](https://www.github.com/yargs/yargs-parser/commit/41d3f8139e116706b28de9b0de3433feb08d2f13)) + +### [18.1.1](https://www.github.com/yargs/yargs-parser/compare/v18.1.0...v18.1.1) (2020-03-16) + + +### Bug Fixes + +* \_\_proto\_\_ will now be replaced with \_\_\_proto\_\_\_ in parse ([#258](https://www.github.com/yargs/yargs-parser/issues/258)), patching a potential +prototype pollution vulnerability. This was reported by the Snyk Security Research Team.([63810ca](https://www.github.com/yargs/yargs-parser/commit/63810ca1ae1a24b08293a4d971e70e058c7a41e2)) + +## [18.1.0](https://www.github.com/yargs/yargs-parser/compare/v18.0.0...v18.1.0) (2020-03-07) + + +### Features + +* introduce single-digit boolean aliases ([#255](https://www.github.com/yargs/yargs-parser/issues/255)) ([9c60265](https://www.github.com/yargs/yargs-parser/commit/9c60265fd7a03cb98e6df3e32c8c5e7508d9f56f)) + +## [18.0.0](https://www.github.com/yargs/yargs-parser/compare/v17.1.0...v18.0.0) (2020-03-02) + + +### ⚠ BREAKING CHANGES + +* the narg count is now enforced when parsing arrays. + +### Features + +* NaN can now be provided as a value for nargs, indicating "at least" one value is expected for array ([#251](https://www.github.com/yargs/yargs-parser/issues/251)) ([9db4be8](https://www.github.com/yargs/yargs-parser/commit/9db4be81417a2c7097128db34d86fe70ef4af70c)) + +## [17.1.0](https://www.github.com/yargs/yargs-parser/compare/v17.0.1...v17.1.0) (2020-03-01) + + +### Features + +* introduce greedy-arrays config, for specifying whether arrays consume multiple positionals ([#249](https://www.github.com/yargs/yargs-parser/issues/249)) ([60e880a](https://www.github.com/yargs/yargs-parser/commit/60e880a837046314d89fa4725f923837fd33a9eb)) + +### [17.0.1](https://www.github.com/yargs/yargs-parser/compare/v17.0.0...v17.0.1) (2020-02-29) + + +### Bug Fixes + +* normalized keys were not enumerable ([#247](https://www.github.com/yargs/yargs-parser/issues/247)) ([57119f9](https://www.github.com/yargs/yargs-parser/commit/57119f9f17cf27499bd95e61c2f72d18314f11ba)) + +## [17.0.0](https://www.github.com/yargs/yargs-parser/compare/v16.1.0...v17.0.0) (2020-02-10) + + +### ⚠ BREAKING CHANGES + +* this reverts parsing behavior of booleans to that of yargs@14 +* objects used during parsing are now created with a null +prototype. There may be some scenarios where this change in behavior +leaks externally. + +### Features + +* boolean arguments will not be collected into an implicit array ([#236](https://www.github.com/yargs/yargs-parser/issues/236)) ([34c4e19](https://www.github.com/yargs/yargs-parser/commit/34c4e19bae4e7af63e3cb6fa654a97ed476e5eb5)) +* introduce nargs-eats-options config option ([#246](https://www.github.com/yargs/yargs-parser/issues/246)) ([d50822a](https://www.github.com/yargs/yargs-parser/commit/d50822ac10e1b05f2e9643671ca131ac251b6732)) + + +### Bug Fixes + +* address bugs with "uknown-options-as-args" ([bc023e3](https://www.github.com/yargs/yargs-parser/commit/bc023e3b13e20a118353f9507d1c999bf388a346)) +* array should take precedence over nargs, but enforce nargs ([#243](https://www.github.com/yargs/yargs-parser/issues/243)) ([4cbc188](https://www.github.com/yargs/yargs-parser/commit/4cbc188b7abb2249529a19c090338debdad2fe6c)) +* support keys that collide with object prototypes ([#234](https://www.github.com/yargs/yargs-parser/issues/234)) ([1587b6d](https://www.github.com/yargs/yargs-parser/commit/1587b6d91db853a9109f1be6b209077993fee4de)) +* unknown options terminated with digits now handled by unknown-options-as-args ([#238](https://www.github.com/yargs/yargs-parser/issues/238)) ([d36cdfa](https://www.github.com/yargs/yargs-parser/commit/d36cdfa854254d7c7e0fe1d583818332ac46c2a5)) + +## [16.1.0](https://www.github.com/yargs/yargs-parser/compare/v16.0.0...v16.1.0) (2019-11-01) + + +### ⚠ BREAKING CHANGES + +* populate error if incompatible narg/count or array/count options are used (#191) + +### Features + +* options that have had their default value used are now tracked ([#211](https://www.github.com/yargs/yargs-parser/issues/211)) ([a525234](https://www.github.com/yargs/yargs-parser/commit/a525234558c847deedd73f8792e0a3b77b26e2c0)) +* populate error if incompatible narg/count or array/count options are used ([#191](https://www.github.com/yargs/yargs-parser/issues/191)) ([84a401f](https://www.github.com/yargs/yargs-parser/commit/84a401f0fa3095e0a19661670d1570d0c3b9d3c9)) + + +### Reverts + +* revert 16.0.0 CHANGELOG entry ([920320a](https://www.github.com/yargs/yargs-parser/commit/920320ad9861bbfd58eda39221ae211540fc1daf)) diff --git a/node_modules/yargs-parser/LICENSE.txt b/node_modules/yargs-parser/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..836440bef7cf14841c05b0f8635e580c91327fc4 --- /dev/null +++ b/node_modules/yargs-parser/LICENSE.txt @@ -0,0 +1,14 @@ +Copyright (c) 2016, Contributors + +Permission to use, copy, modify, and/or distribute this software +for any purpose with or without fee is hereby granted, provided +that the above copyright notice and this permission notice +appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE +LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/yargs-parser/README.md b/node_modules/yargs-parser/README.md new file mode 100644 index 0000000000000000000000000000000000000000..261484076844a39cf85f72d88acf39217692c933 --- /dev/null +++ b/node_modules/yargs-parser/README.md @@ -0,0 +1,518 @@ +# yargs-parser + +![ci](https://github.com/yargs/yargs-parser/workflows/ci/badge.svg) +[![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser) +[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) +![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/yargs-parser) + +The mighty option parser used by [yargs](https://github.com/yargs/yargs). + +visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions. + + + +## Example + +```sh +npm i yargs-parser --save +``` + +```js +const argv = require('yargs-parser')(process.argv.slice(2)) +console.log(argv) +``` + +```console +$ node example.js --foo=33 --bar hello +{ _: [], foo: 33, bar: 'hello' } +``` + +_or parse a string!_ + +```js +const argv = require('yargs-parser')('--foo=99 --bar=33') +console.log(argv) +``` + +```console +{ _: [], foo: 99, bar: 33 } +``` + +Convert an array of mixed types before passing to `yargs-parser`: + +```js +const parse = require('yargs-parser') +parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string +parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings +``` + +## Deno Example + +As of `v19` `yargs-parser` supports [Deno](https://github.com/denoland/deno): + +```typescript +import parser from "https://deno.land/x/yargs_parser/deno.ts"; + +const argv = parser('--foo=99 --bar=9987930', { + string: ['bar'] +}) +console.log(argv) +``` + +## ESM Example + +As of `v19` `yargs-parser` supports ESM (_both in Node.js and in the browser_): + +**Node.js:** + +```js +import parser from 'yargs-parser' + +const argv = parser('--foo=99 --bar=9987930', { + string: ['bar'] +}) +console.log(argv) +``` + +**Browsers:** + +```html + + + + +``` + +## API + +### parser(args, opts={}) + +Parses command line arguments returning a simple mapping of keys and values. + +**expects:** + +* `args`: a string or array of strings representing the options to parse. +* `opts`: provide a set of hints indicating how `args` should be parsed: + * `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`. + * `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`.
+ Indicate that keys should be parsed as an array and coerced to booleans / numbers:
+ `{array: [{ key: 'foo', boolean: true }, {key: 'bar', number: true}]}`. + * `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`. + * `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided + (or throws an error). For arrays the function is called only once for the entire array:
+ `{coerce: {foo: function (arg) {return modifiedArg}}}`. + * `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed). + * `opts.configObjects`: configuration objects to parse, their properties will be set as arguments:
+ `{configObjects: [{'x': 5, 'y': 33}, {'z': 44}]}`. + * `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)). + * `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`. + * `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`. + * `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed. + * `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`. + * `opts.normalize`: `path.normalize()` will be applied to values set to this key. + * `opts.number`: keys should be treated as numbers. + * `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`). + +**returns:** + +* `obj`: an object representing the parsed value of `args` + * `key/value`: key value pairs for each argument and their aliases. + * `_`: an array representing the positional arguments. + * [optional] `--`: an array with arguments after the end-of-options flag `--`. + +### require('yargs-parser').detailed(args, opts={}) + +Parses a command line string, returning detailed information required by the +yargs engine. + +**expects:** + +* `args`: a string or array of strings representing options to parse. +* `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`. + +**returns:** + +* `argv`: an object representing the parsed value of `args` + * `key/value`: key value pairs for each argument and their aliases. + * `_`: an array representing the positional arguments. + * [optional] `--`: an array with arguments after the end-of-options flag `--`. +* `error`: populated with an error object if an exception occurred during parsing. +* `aliases`: the inferred list of aliases built by combining lists in `opts.alias`. +* `newAliases`: any new aliases added via camel-case expansion: + * `boolean`: `{ fooBar: true }` +* `defaulted`: any new argument created by `opts.default`, no aliases included. + * `boolean`: `{ foo: true }` +* `configuration`: given by default settings and `opts.configuration`. + + + +### Configuration + +The yargs-parser applies several automated transformations on the keys provided +in `args`. These features can be turned on and off using the `configuration` field +of `opts`. + +```js +var parsed = parser(['--no-dice'], { + configuration: { + 'boolean-negation': false + } +}) +``` + +### short option groups + +* default: `true`. +* key: `short-option-groups`. + +Should a group of short-options be treated as boolean flags? + +```console +$ node example.js -abc +{ _: [], a: true, b: true, c: true } +``` + +_if disabled:_ + +```console +$ node example.js -abc +{ _: [], abc: true } +``` + +### camel-case expansion + +* default: `true`. +* key: `camel-case-expansion`. + +Should hyphenated arguments be expanded into camel-case aliases? + +```console +$ node example.js --foo-bar +{ _: [], 'foo-bar': true, fooBar: true } +``` + +_if disabled:_ + +```console +$ node example.js --foo-bar +{ _: [], 'foo-bar': true } +``` + +### dot-notation + +* default: `true` +* key: `dot-notation` + +Should keys that contain `.` be treated as objects? + +```console +$ node example.js --foo.bar +{ _: [], foo: { bar: true } } +``` + +_if disabled:_ + +```console +$ node example.js --foo.bar +{ _: [], "foo.bar": true } +``` + +### parse numbers + +* default: `true` +* key: `parse-numbers` + +Should keys that look like numbers be treated as such? + +```console +$ node example.js --foo=99.3 +{ _: [], foo: 99.3 } +``` + +_if disabled:_ + +```console +$ node example.js --foo=99.3 +{ _: [], foo: "99.3" } +``` + +### parse positional numbers + +* default: `true` +* key: `parse-positional-numbers` + +Should positional keys that look like numbers be treated as such. + +```console +$ node example.js 99.3 +{ _: [99.3] } +``` + +_if disabled:_ + +```console +$ node example.js 99.3 +{ _: ['99.3'] } +``` + +### boolean negation + +* default: `true` +* key: `boolean-negation` + +Should variables prefixed with `--no` be treated as negations? + +```console +$ node example.js --no-foo +{ _: [], foo: false } +``` + +_if disabled:_ + +```console +$ node example.js --no-foo +{ _: [], "no-foo": true } +``` + +### combine arrays + +* default: `false` +* key: `combine-arrays` + +Should arrays be combined when provided by both command line arguments and +a configuration file. + +### duplicate arguments array + +* default: `true` +* key: `duplicate-arguments-array` + +Should arguments be coerced into an array when duplicated: + +```console +$ node example.js -x 1 -x 2 +{ _: [], x: [1, 2] } +``` + +_if disabled:_ + +```console +$ node example.js -x 1 -x 2 +{ _: [], x: 2 } +``` + +### flatten duplicate arrays + +* default: `true` +* key: `flatten-duplicate-arrays` + +Should array arguments be coerced into a single array when duplicated: + +```console +$ node example.js -x 1 2 -x 3 4 +{ _: [], x: [1, 2, 3, 4] } +``` + +_if disabled:_ + +```console +$ node example.js -x 1 2 -x 3 4 +{ _: [], x: [[1, 2], [3, 4]] } +``` + +### greedy arrays + +* default: `true` +* key: `greedy-arrays` + +Should arrays consume more than one positional argument following their flag. + +```console +$ node example --arr 1 2 +{ _: [], arr: [1, 2] } +``` + +_if disabled:_ + +```console +$ node example --arr 1 2 +{ _: [2], arr: [1] } +``` + +**Note: in `v18.0.0` we are considering defaulting greedy arrays to `false`.** + +### nargs eats options + +* default: `false` +* key: `nargs-eats-options` + +Should nargs consume dash options as well as positional arguments. + +### negation prefix + +* default: `no-` +* key: `negation-prefix` + +The prefix to use for negated boolean variables. + +```console +$ node example.js --no-foo +{ _: [], foo: false } +``` + +_if set to `quux`:_ + +```console +$ node example.js --quuxfoo +{ _: [], foo: false } +``` + +### populate -- + +* default: `false`. +* key: `populate--` + +Should unparsed flags be stored in `--` or `_`. + +_If disabled:_ + +```console +$ node example.js a -b -- x y +{ _: [ 'a', 'x', 'y' ], b: true } +``` + +_If enabled:_ + +```console +$ node example.js a -b -- x y +{ _: [ 'a' ], '--': [ 'x', 'y' ], b: true } +``` + +### set placeholder key + +* default: `false`. +* key: `set-placeholder-key`. + +Should a placeholder be added for keys not set via the corresponding CLI argument? + +_If disabled:_ + +```console +$ node example.js -a 1 -c 2 +{ _: [], a: 1, c: 2 } +``` + +_If enabled:_ + +```console +$ node example.js -a 1 -c 2 +{ _: [], a: 1, b: undefined, c: 2 } +``` + +### halt at non-option + +* default: `false`. +* key: `halt-at-non-option`. + +Should parsing stop at the first positional argument? This is similar to how e.g. `ssh` parses its command line. + +_If disabled:_ + +```console +$ node example.js -a run b -x y +{ _: [ 'b' ], a: 'run', x: 'y' } +``` + +_If enabled:_ + +```console +$ node example.js -a run b -x y +{ _: [ 'b', '-x', 'y' ], a: 'run' } +``` + +### strip aliased + +* default: `false` +* key: `strip-aliased` + +Should aliases be removed before returning results? + +_If disabled:_ + +```console +$ node example.js --test-field 1 +{ _: [], 'test-field': 1, testField: 1, 'test-alias': 1, testAlias: 1 } +``` + +_If enabled:_ + +```console +$ node example.js --test-field 1 +{ _: [], 'test-field': 1, testField: 1 } +``` + +### strip dashed + +* default: `false` +* key: `strip-dashed` + +Should dashed keys be removed before returning results? This option has no effect if +`camel-case-expansion` is disabled. + +_If disabled:_ + +```console +$ node example.js --test-field 1 +{ _: [], 'test-field': 1, testField: 1 } +``` + +_If enabled:_ + +```console +$ node example.js --test-field 1 +{ _: [], testField: 1 } +``` + +### unknown options as args + +* default: `false` +* key: `unknown-options-as-args` + +Should unknown options be treated like regular arguments? An unknown option is one that is not +configured in `opts`. + +_If disabled_ + +```console +$ node example.js --unknown-option --known-option 2 --string-option --unknown-option2 +{ _: [], unknownOption: true, knownOption: 2, stringOption: '', unknownOption2: true } +``` + +_If enabled_ + +```console +$ node example.js --unknown-option --known-option 2 --string-option --unknown-option2 +{ _: ['--unknown-option'], knownOption: 2, stringOption: '--unknown-option2' } +``` + +## Supported Node.js Versions + +Libraries in this ecosystem make a best effort to track +[Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a +post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). + +## Special Thanks + +The yargs project evolves from optimist and minimist. It owes its +existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/ + +## License + +ISC diff --git a/node_modules/yargs-parser/browser.js b/node_modules/yargs-parser/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..241202c7e2bb27983e2648a8524a8f3a52d21667 --- /dev/null +++ b/node_modules/yargs-parser/browser.js @@ -0,0 +1,29 @@ +// Main entrypoint for ESM web browser environments. Avoids using Node.js +// specific libraries, such as "path". +// +// TODO: figure out reasonable web equivalents for "resolve", "normalize", etc. +import { camelCase, decamelize, looksLikeNumber } from './build/lib/string-utils.js' +import { YargsParser } from './build/lib/yargs-parser.js' +const parser = new YargsParser({ + cwd: () => { return '' }, + format: (str, arg) => { return str.replace('%s', arg) }, + normalize: (str) => { return str }, + resolve: (str) => { return str }, + require: () => { + throw Error('loading config from files not currently supported in browser') + }, + env: () => {} +}) + +const yargsParser = function Parser (args, opts) { + const result = parser.parse(args.slice(), opts) + return result.argv +} +yargsParser.detailed = function (args, opts) { + return parser.parse(args.slice(), opts) +} +yargsParser.camelCase = camelCase +yargsParser.decamelize = decamelize +yargsParser.looksLikeNumber = looksLikeNumber + +export default yargsParser diff --git a/node_modules/yargs-parser/build/lib/index.js b/node_modules/yargs-parser/build/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..91093919317134e74f5cc5bd3ccf509ba4a72cd7 --- /dev/null +++ b/node_modules/yargs-parser/build/lib/index.js @@ -0,0 +1,64 @@ +/** + * @fileoverview Main entrypoint for libraries using yargs-parser in Node.js + * + * @license + * Copyright (c) 2016, Contributors + * SPDX-License-Identifier: ISC + */ +var _a, _b, _c; +/* eslint-disable n/no-unpublished-import */ +import { format } from 'util'; +import { normalize, resolve } from 'path'; +import { camelCase, decamelize, looksLikeNumber } from './string-utils.js'; +import { YargsParser } from './yargs-parser.js'; +import { readFileSync } from 'fs'; +import { createRequire } from 'node:module'; +// See https://github.com/yargs/yargs-parser#supported-nodejs-versions for our +// version support policy. The YARGS_MIN_NODE_VERSION is used for testing only. +const minNodeVersion = (process && process.env && process.env.YARGS_MIN_NODE_VERSION) + ? Number(process.env.YARGS_MIN_NODE_VERSION) + : 20; +const nodeVersion = (_b = (_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node) !== null && _b !== void 0 ? _b : (_c = process === null || process === void 0 ? void 0 : process.version) === null || _c === void 0 ? void 0 : _c.slice(1); +if (nodeVersion) { + const major = Number(nodeVersion.match(/^([^.]+)/)[1]); + if (major < minNodeVersion) { + throw Error(`yargs parser supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`); + } +} +// Creates a yargs-parser instance using Node.js standard libraries: +const env = process ? process.env : {}; +const require = createRequire ? createRequire(import.meta.url) : undefined; +const parser = new YargsParser({ + cwd: process.cwd, + env: () => { + return env; + }, + format, + normalize, + resolve, + require: (path) => { + if (typeof require !== 'undefined') { + return require(path); + } + else if (path.match(/\.json$/)) { + // Addresses: https://github.com/yargs/yargs/issues/2040 + return JSON.parse(readFileSync(path, 'utf8')); + } + else { + throw Error('only .json config files are supported in ESM'); + } + } +}); +const yargsParser = function Parser(args, opts) { + const result = parser.parse(args.slice(), opts); + return result.argv; +}; +yargsParser.detailed = function (args, opts) { + return parser.parse(args.slice(), opts); +}; +yargsParser.camelCase = camelCase; +yargsParser.decamelize = decamelize; +yargsParser.looksLikeNumber = looksLikeNumber; +export default yargsParser; +// special syntax to allow unqualified default export from CommonJS +export { yargsParser as 'module.exports' }; diff --git a/node_modules/yargs-parser/build/lib/string-utils.js b/node_modules/yargs-parser/build/lib/string-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..4e8bd996e7a97a2c1e9c9fc4919044a171b73918 --- /dev/null +++ b/node_modules/yargs-parser/build/lib/string-utils.js @@ -0,0 +1,65 @@ +/** + * @license + * Copyright (c) 2016, Contributors + * SPDX-License-Identifier: ISC + */ +export function camelCase(str) { + // Handle the case where an argument is provided as camel case, e.g., fooBar. + // by ensuring that the string isn't already mixed case: + const isCamelCase = str !== str.toLowerCase() && str !== str.toUpperCase(); + if (!isCamelCase) { + str = str.toLowerCase(); + } + if (str.indexOf('-') === -1 && str.indexOf('_') === -1) { + return str; + } + else { + let camelcase = ''; + let nextChrUpper = false; + const leadingHyphens = str.match(/^-+/); + for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str.length; i++) { + let chr = str.charAt(i); + if (nextChrUpper) { + nextChrUpper = false; + chr = chr.toUpperCase(); + } + if (i !== 0 && (chr === '-' || chr === '_')) { + nextChrUpper = true; + } + else if (chr !== '-' && chr !== '_') { + camelcase += chr; + } + } + return camelcase; + } +} +export function decamelize(str, joinString) { + const lowercase = str.toLowerCase(); + joinString = joinString || '-'; + let notCamelcase = ''; + for (let i = 0; i < str.length; i++) { + const chrLower = lowercase.charAt(i); + const chrString = str.charAt(i); + if (chrLower !== chrString && i > 0) { + notCamelcase += `${joinString}${lowercase.charAt(i)}`; + } + else { + notCamelcase += chrString; + } + } + return notCamelcase; +} +export function looksLikeNumber(x) { + if (x === null || x === undefined) + return false; + // if loaded from config, may already be a number. + if (typeof x === 'number') + return true; + // hexadecimal. + if (/^0x[0-9a-f]+$/i.test(x)) + return true; + // don't treat 0123 as a number; as it drops the leading '0'. + if (/^0[^.]/.test(x)) + return false; + return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); +} diff --git a/node_modules/yargs-parser/build/lib/tokenize-arg-string.js b/node_modules/yargs-parser/build/lib/tokenize-arg-string.js new file mode 100644 index 0000000000000000000000000000000000000000..5e732efe019ab064effaa667bfe7bf904a5f1cb0 --- /dev/null +++ b/node_modules/yargs-parser/build/lib/tokenize-arg-string.js @@ -0,0 +1,40 @@ +/** + * @license + * Copyright (c) 2016, Contributors + * SPDX-License-Identifier: ISC + */ +// take an un-split argv string and tokenize it. +export function tokenizeArgString(argString) { + if (Array.isArray(argString)) { + return argString.map(e => typeof e !== 'string' ? e + '' : e); + } + argString = argString.trim(); + let i = 0; + let prevC = null; + let c = null; + let opening = null; + const args = []; + for (let ii = 0; ii < argString.length; ii++) { + prevC = c; + c = argString.charAt(ii); + // split on spaces unless we're in quotes. + if (c === ' ' && !opening) { + if (!(prevC === ' ')) { + i++; + } + continue; + } + // don't split the string if we're in matching + // opening or closing single and double quotes. + if (c === opening) { + opening = null; + } + else if ((c === "'" || c === '"') && !opening) { + opening = c; + } + if (!args[i]) + args[i] = ''; + args[i] += c; + } + return args; +} diff --git a/node_modules/yargs-parser/build/lib/yargs-parser-types.js b/node_modules/yargs-parser/build/lib/yargs-parser-types.js new file mode 100644 index 0000000000000000000000000000000000000000..63b7c313aa9b5fe645373222c88c5bccb19b806c --- /dev/null +++ b/node_modules/yargs-parser/build/lib/yargs-parser-types.js @@ -0,0 +1,12 @@ +/** + * @license + * Copyright (c) 2016, Contributors + * SPDX-License-Identifier: ISC + */ +export var DefaultValuesForTypeKey; +(function (DefaultValuesForTypeKey) { + DefaultValuesForTypeKey["BOOLEAN"] = "boolean"; + DefaultValuesForTypeKey["STRING"] = "string"; + DefaultValuesForTypeKey["NUMBER"] = "number"; + DefaultValuesForTypeKey["ARRAY"] = "array"; +})(DefaultValuesForTypeKey || (DefaultValuesForTypeKey = {})); diff --git a/node_modules/yargs-parser/build/lib/yargs-parser.js b/node_modules/yargs-parser/build/lib/yargs-parser.js new file mode 100644 index 0000000000000000000000000000000000000000..e3624fb7bf96f4b7b7cdb26c3bdd11e099d48a1a --- /dev/null +++ b/node_modules/yargs-parser/build/lib/yargs-parser.js @@ -0,0 +1,1046 @@ +/** + * @license + * Copyright (c) 2016, Contributors + * SPDX-License-Identifier: ISC + */ +/* eslint-disable prefer-arrow-callback */ +import { tokenizeArgString } from './tokenize-arg-string.js'; +import { DefaultValuesForTypeKey } from './yargs-parser-types.js'; +import { camelCase, decamelize, looksLikeNumber } from './string-utils.js'; +let mixin; +export class YargsParser { + constructor(_mixin) { + mixin = _mixin; + } + parse(argsInput, options) { + const opts = Object.assign({ + alias: undefined, + array: undefined, + boolean: undefined, + config: undefined, + configObjects: undefined, + configuration: undefined, + coerce: undefined, + count: undefined, + default: undefined, + envPrefix: undefined, + narg: undefined, + normalize: undefined, + string: undefined, + number: undefined, + __: undefined, + key: undefined + }, options); + // allow a string argument to be passed in rather + // than an argv array. + const args = tokenizeArgString(argsInput); + // tokenizeArgString adds extra quotes to args if argsInput is a string + // only strip those extra quotes in processValue if argsInput is a string + const inputIsString = typeof argsInput === 'string'; + // aliases might have transitive relationships, normalize this. + const aliases = combineAliases(Object.assign(Object.create(null), opts.alias)); + const configuration = Object.assign({ + 'boolean-negation': true, + 'camel-case-expansion': true, + 'combine-arrays': false, + 'dot-notation': true, + 'duplicate-arguments-array': true, + 'flatten-duplicate-arrays': true, + 'greedy-arrays': true, + 'halt-at-non-option': false, + 'nargs-eats-options': false, + 'negation-prefix': 'no-', + 'parse-numbers': true, + 'parse-positional-numbers': true, + 'populate--': false, + 'set-placeholder-key': false, + 'short-option-groups': true, + 'strip-aliased': false, + 'strip-dashed': false, + 'unknown-options-as-args': false + }, opts.configuration); + const defaults = Object.assign(Object.create(null), opts.default); + const configObjects = opts.configObjects || []; + const envPrefix = opts.envPrefix; + const notFlagsOption = configuration['populate--']; + const notFlagsArgv = notFlagsOption ? '--' : '_'; + const newAliases = Object.create(null); + const defaulted = Object.create(null); + // allow a i18n handler to be passed in, default to a fake one (util.format). + const __ = opts.__ || mixin.format; + const flags = { + aliases: Object.create(null), + arrays: Object.create(null), + bools: Object.create(null), + strings: Object.create(null), + numbers: Object.create(null), + counts: Object.create(null), + normalize: Object.create(null), + configs: Object.create(null), + nargs: Object.create(null), + coercions: Object.create(null), + keys: [] + }; + const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/; + const negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)'); + [].concat(opts.array || []).filter(Boolean).forEach(function (opt) { + const key = typeof opt === 'object' ? opt.key : opt; + // assign to flags[bools|strings|numbers] + const assignment = Object.keys(opt).map(function (key) { + const arrayFlagKeys = { + boolean: 'bools', + string: 'strings', + number: 'numbers' + }; + return arrayFlagKeys[key]; + }).filter(Boolean).pop(); + // assign key to be coerced + if (assignment) { + flags[assignment][key] = true; + } + flags.arrays[key] = true; + flags.keys.push(key); + }); + [].concat(opts.boolean || []).filter(Boolean).forEach(function (key) { + flags.bools[key] = true; + flags.keys.push(key); + }); + [].concat(opts.string || []).filter(Boolean).forEach(function (key) { + flags.strings[key] = true; + flags.keys.push(key); + }); + [].concat(opts.number || []).filter(Boolean).forEach(function (key) { + flags.numbers[key] = true; + flags.keys.push(key); + }); + [].concat(opts.count || []).filter(Boolean).forEach(function (key) { + flags.counts[key] = true; + flags.keys.push(key); + }); + [].concat(opts.normalize || []).filter(Boolean).forEach(function (key) { + flags.normalize[key] = true; + flags.keys.push(key); + }); + if (typeof opts.narg === 'object') { + Object.entries(opts.narg).forEach(([key, value]) => { + if (typeof value === 'number') { + flags.nargs[key] = value; + flags.keys.push(key); + } + }); + } + if (typeof opts.coerce === 'object') { + Object.entries(opts.coerce).forEach(([key, value]) => { + if (typeof value === 'function') { + flags.coercions[key] = value; + flags.keys.push(key); + } + }); + } + if (typeof opts.config !== 'undefined') { + if (Array.isArray(opts.config) || typeof opts.config === 'string') { + ; + [].concat(opts.config).filter(Boolean).forEach(function (key) { + flags.configs[key] = true; + }); + } + else if (typeof opts.config === 'object') { + Object.entries(opts.config).forEach(([key, value]) => { + if (typeof value === 'boolean' || typeof value === 'function') { + flags.configs[key] = value; + } + }); + } + } + // create a lookup table that takes into account all + // combinations of aliases: {f: ['foo'], foo: ['f']} + extendAliases(opts.key, aliases, opts.default, flags.arrays); + // apply default values to all aliases. + Object.keys(defaults).forEach(function (key) { + (flags.aliases[key] || []).forEach(function (alias) { + defaults[alias] = defaults[key]; + }); + }); + let error = null; + checkConfiguration(); + let notFlags = []; + const argv = Object.assign(Object.create(null), { _: [] }); + // TODO(bcoe): for the first pass at removing object prototype we didn't + // remove all prototypes from objects returned by this API, we might want + // to gradually move towards doing so. + const argvReturn = {}; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + const truncatedArg = arg.replace(/^-{3,}/, '---'); + let broken; + let key; + let letters; + let m; + let next; + let value; + // any unknown option (except for end-of-options, "--") + if (arg !== '--' && /^-/.test(arg) && isUnknownOptionAsArg(arg)) { + pushPositional(arg); + // ---, ---=, ----, etc, + } + else if (truncatedArg.match(/^---+(=|$)/)) { + // options without key name are invalid. + pushPositional(arg); + continue; + // -- separated by = + } + else if (arg.match(/^--.+=/) || (!configuration['short-option-groups'] && arg.match(/^-.+=/))) { + // Using [\s\S] instead of . because js doesn't support the + // 'dotall' regex modifier. See: + // http://stackoverflow.com/a/1068308/13216 + m = arg.match(/^--?([^=]+)=([\s\S]*)$/); + // arrays format = '--f=a b c' + if (m !== null && Array.isArray(m) && m.length >= 3) { + if (checkAllAliases(m[1], flags.arrays)) { + i = eatArray(i, m[1], args, m[2]); + } + else if (checkAllAliases(m[1], flags.nargs) !== false) { + // nargs format = '--f=monkey washing cat' + i = eatNargs(i, m[1], args, m[2]); + } + else { + setArg(m[1], m[2], true); + } + } + } + else if (arg.match(negatedBoolean) && configuration['boolean-negation']) { + m = arg.match(negatedBoolean); + if (m !== null && Array.isArray(m) && m.length >= 2) { + key = m[1]; + setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false); + } + // -- separated by space. + } + else if (arg.match(/^--.+/) || (!configuration['short-option-groups'] && arg.match(/^-[^-]+/))) { + m = arg.match(/^--?(.+)/); + if (m !== null && Array.isArray(m) && m.length >= 2) { + key = m[1]; + if (checkAllAliases(key, flags.arrays)) { + // array format = '--foo a b c' + i = eatArray(i, key, args); + } + else if (checkAllAliases(key, flags.nargs) !== false) { + // nargs format = '--foo a b c' + // should be truthy even if: flags.nargs[key] === 0 + i = eatNargs(i, key, args); + } + else { + next = args[i + 1]; + if (next !== undefined && (!next.match(/^-/) || + next.match(negative)) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next); + i++; + } + else if (/^(true|false)$/.test(next)) { + setArg(key, next); + i++; + } + else { + setArg(key, defaultValue(key)); + } + } + } + // dot-notation flag separated by '='. + } + else if (arg.match(/^-.\..+=/)) { + m = arg.match(/^-([^=]+)=([\s\S]*)$/); + if (m !== null && Array.isArray(m) && m.length >= 3) { + setArg(m[1], m[2]); + } + // dot-notation flag separated by space. + } + else if (arg.match(/^-.\..+/) && !arg.match(negative)) { + next = args[i + 1]; + m = arg.match(/^-(.\..+)/); + if (m !== null && Array.isArray(m) && m.length >= 2) { + key = m[1]; + if (next !== undefined && !next.match(/^-/) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next); + i++; + } + else { + setArg(key, defaultValue(key)); + } + } + } + else if (arg.match(/^-[^-]+/) && !arg.match(negative)) { + letters = arg.slice(1, -1).split(''); + broken = false; + for (let j = 0; j < letters.length; j++) { + next = arg.slice(j + 2); + if (letters[j + 1] && letters[j + 1] === '=') { + value = arg.slice(j + 3); + key = letters[j]; + if (checkAllAliases(key, flags.arrays)) { + // array format = '-f=a b c' + i = eatArray(i, key, args, value); + } + else if (checkAllAliases(key, flags.nargs) !== false) { + // nargs format = '-f=monkey washing cat' + i = eatNargs(i, key, args, value); + } + else { + setArg(key, value); + } + broken = true; + break; + } + if (next === '-') { + setArg(letters[j], next); + continue; + } + // current letter is an alphabetic character and next value is a number + if (/[A-Za-z]/.test(letters[j]) && + /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) && + checkAllAliases(next, flags.bools) === false) { + setArg(letters[j], next); + broken = true; + break; + } + if (letters[j + 1] && letters[j + 1].match(/\W/)) { + setArg(letters[j], next); + broken = true; + break; + } + else { + setArg(letters[j], defaultValue(letters[j])); + } + } + key = arg.slice(-1)[0]; + if (!broken && key !== '-') { + if (checkAllAliases(key, flags.arrays)) { + // array format = '-f a b c' + i = eatArray(i, key, args); + } + else if (checkAllAliases(key, flags.nargs) !== false) { + // nargs format = '-f a b c' + // should be truthy even if: flags.nargs[key] === 0 + i = eatNargs(i, key, args); + } + else { + next = args[i + 1]; + if (next !== undefined && (!/^(-|--)[^-]/.test(next) || + next.match(negative)) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next); + i++; + } + else if (/^(true|false)$/.test(next)) { + setArg(key, next); + i++; + } + else { + setArg(key, defaultValue(key)); + } + } + } + } + else if (arg.match(/^-[0-9]$/) && + arg.match(negative) && + checkAllAliases(arg.slice(1), flags.bools)) { + // single-digit boolean alias, e.g: xargs -0 + key = arg.slice(1); + setArg(key, defaultValue(key)); + } + else if (arg === '--') { + notFlags = args.slice(i + 1); + break; + } + else if (configuration['halt-at-non-option']) { + notFlags = args.slice(i); + break; + } + else { + pushPositional(arg); + } + } + // order of precedence: + // 1. command line arg + // 2. value from env var + // 3. value from config file + // 4. value from config objects + // 5. configured default value + applyEnvVars(argv, true); // special case: check env vars that point to config file + applyEnvVars(argv, false); + setConfig(argv); + setConfigObjects(); + applyDefaultsAndAliases(argv, flags.aliases, defaults, true); + applyCoercions(argv); + if (configuration['set-placeholder-key']) + setPlaceholderKeys(argv); + // for any counts either not in args or without an explicit default, set to 0 + Object.keys(flags.counts).forEach(function (key) { + if (!hasKey(argv, key.split('.'))) + setArg(key, 0); + }); + // '--' defaults to undefined. + if (notFlagsOption && notFlags.length) + argv[notFlagsArgv] = []; + notFlags.forEach(function (key) { + argv[notFlagsArgv].push(key); + }); + if (configuration['camel-case-expansion'] && configuration['strip-dashed']) { + Object.keys(argv).filter(key => key !== '--' && key.includes('-')).forEach(key => { + delete argv[key]; + }); + } + if (configuration['strip-aliased']) { + ; + [].concat(...Object.keys(aliases).map(k => aliases[k])).forEach(alias => { + if (configuration['camel-case-expansion'] && alias.includes('-')) { + delete argv[alias.split('.').map(prop => camelCase(prop)).join('.')]; + } + delete argv[alias]; + }); + } + // Push argument into positional array, applying numeric coercion: + function pushPositional(arg) { + const maybeCoercedNumber = maybeCoerceNumber('_', arg); + if (typeof maybeCoercedNumber === 'string' || typeof maybeCoercedNumber === 'number') { + argv._.push(maybeCoercedNumber); + } + } + // how many arguments should we consume, based + // on the nargs option? + function eatNargs(i, key, args, argAfterEqualSign) { + let ii; + let toEat = checkAllAliases(key, flags.nargs); + // NaN has a special meaning for the array type, indicating that one or + // more values are expected. + toEat = typeof toEat !== 'number' || isNaN(toEat) ? 1 : toEat; + if (toEat === 0) { + if (!isUndefined(argAfterEqualSign)) { + error = Error(__('Argument unexpected for: %s', key)); + } + setArg(key, defaultValue(key)); + return i; + } + let available = isUndefined(argAfterEqualSign) ? 0 : 1; + if (configuration['nargs-eats-options']) { + // classic behavior, yargs eats positional and dash arguments. + if (args.length - (i + 1) + available < toEat) { + error = Error(__('Not enough arguments following: %s', key)); + } + available = toEat; + } + else { + // nargs will not consume flag arguments, e.g., -abc, --foo, + // and terminates when one is observed. + for (ii = i + 1; ii < args.length; ii++) { + if (!args[ii].match(/^-[^0-9]/) || args[ii].match(negative) || isUnknownOptionAsArg(args[ii])) + available++; + else + break; + } + if (available < toEat) + error = Error(__('Not enough arguments following: %s', key)); + } + let consumed = Math.min(available, toEat); + if (!isUndefined(argAfterEqualSign) && consumed > 0) { + setArg(key, argAfterEqualSign); + consumed--; + } + for (ii = i + 1; ii < (consumed + i + 1); ii++) { + setArg(key, args[ii]); + } + return (i + consumed); + } + // if an option is an array, eat all non-hyphenated arguments + // following it... YUM! + // e.g., --foo apple banana cat becomes ["apple", "banana", "cat"] + function eatArray(i, key, args, argAfterEqualSign) { + let argsToSet = []; + let next = argAfterEqualSign || args[i + 1]; + // If both array and nargs are configured, enforce the nargs count: + const nargsCount = checkAllAliases(key, flags.nargs); + if (checkAllAliases(key, flags.bools) && !(/^(true|false)$/.test(next))) { + argsToSet.push(true); + } + else if (isUndefined(next) || + (isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))) { + // for keys without value ==> argsToSet remains an empty [] + // set user default value, if available + if (defaults[key] !== undefined) { + const defVal = defaults[key]; + argsToSet = Array.isArray(defVal) ? defVal : [defVal]; + } + } + else { + // value in --option=value is eaten as is + if (!isUndefined(argAfterEqualSign)) { + argsToSet.push(processValue(key, argAfterEqualSign, true)); + } + for (let ii = i + 1; ii < args.length; ii++) { + if ((!configuration['greedy-arrays'] && argsToSet.length > 0) || + (nargsCount && typeof nargsCount === 'number' && argsToSet.length >= nargsCount)) + break; + next = args[ii]; + if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next)) + break; + i = ii; + argsToSet.push(processValue(key, next, inputIsString)); + } + } + // If both array and nargs are configured, create an error if less than + // nargs positionals were found. NaN has special meaning, indicating + // that at least one value is required (more are okay). + if (typeof nargsCount === 'number' && ((nargsCount && argsToSet.length < nargsCount) || + (isNaN(nargsCount) && argsToSet.length === 0))) { + error = Error(__('Not enough arguments following: %s', key)); + } + setArg(key, argsToSet); + return i; + } + function setArg(key, val, shouldStripQuotes = inputIsString) { + if (/-/.test(key) && configuration['camel-case-expansion']) { + const alias = key.split('.').map(function (prop) { + return camelCase(prop); + }).join('.'); + addNewAlias(key, alias); + } + const value = processValue(key, val, shouldStripQuotes); + const splitKey = key.split('.'); + setKey(argv, splitKey, value); + // handle populating aliases of the full key + if (flags.aliases[key]) { + flags.aliases[key].forEach(function (x) { + const keyProperties = x.split('.'); + setKey(argv, keyProperties, value); + }); + } + // handle populating aliases of the first element of the dot-notation key + if (splitKey.length > 1 && configuration['dot-notation']) { + ; + (flags.aliases[splitKey[0]] || []).forEach(function (x) { + let keyProperties = x.split('.'); + // expand alias with nested objects in key + const a = [].concat(splitKey); + a.shift(); // nuke the old key. + keyProperties = keyProperties.concat(a); + // populate alias only if is not already an alias of the full key + // (already populated above) + if (!(flags.aliases[key] || []).includes(keyProperties.join('.'))) { + setKey(argv, keyProperties, value); + } + }); + } + // Set normalize getter and setter when key is in 'normalize' but isn't an array + if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) { + const keys = [key].concat(flags.aliases[key] || []); + keys.forEach(function (key) { + Object.defineProperty(argvReturn, key, { + enumerable: true, + get() { + return val; + }, + set(value) { + val = typeof value === 'string' ? mixin.normalize(value) : value; + } + }); + }); + } + } + function addNewAlias(key, alias) { + if (!(flags.aliases[key] && flags.aliases[key].length)) { + flags.aliases[key] = [alias]; + newAliases[alias] = true; + } + if (!(flags.aliases[alias] && flags.aliases[alias].length)) { + addNewAlias(alias, key); + } + } + function processValue(key, val, shouldStripQuotes) { + // strings may be quoted, clean this up as we assign values. + if (shouldStripQuotes) { + val = stripQuotes(val); + } + // handle parsing boolean arguments --foo=true --bar false. + if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) { + if (typeof val === 'string') + val = val === 'true'; + } + let value = Array.isArray(val) + ? val.map(function (v) { return maybeCoerceNumber(key, v); }) + : maybeCoerceNumber(key, val); + // increment a count given as arg (either no value or value parsed as boolean) + if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) { + value = increment(); + } + // Set normalized value when key is in 'normalize' and in 'arrays' + if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) { + if (Array.isArray(val)) + value = val.map((val) => { return mixin.normalize(val); }); + else + value = mixin.normalize(val); + } + return value; + } + function maybeCoerceNumber(key, value) { + if (!configuration['parse-positional-numbers'] && key === '_') + return value; + if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) { + const shouldCoerceNumber = looksLikeNumber(value) && configuration['parse-numbers'] && (Number.isSafeInteger(Math.floor(parseFloat(`${value}`)))); + if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) { + value = Number(value); + } + } + return value; + } + // set args from config.json file, this should be + // applied last so that defaults can be applied. + function setConfig(argv) { + const configLookup = Object.create(null); + // expand defaults/aliases, in-case any happen to reference + // the config.json file. + applyDefaultsAndAliases(configLookup, flags.aliases, defaults); + Object.keys(flags.configs).forEach(function (configKey) { + const configPath = argv[configKey] || configLookup[configKey]; + if (configPath) { + try { + let config = null; + const resolvedConfigPath = mixin.resolve(mixin.cwd(), configPath); + const resolveConfig = flags.configs[configKey]; + if (typeof resolveConfig === 'function') { + try { + config = resolveConfig(resolvedConfigPath); + } + catch (e) { + config = e; + } + if (config instanceof Error) { + error = config; + return; + } + } + else { + config = mixin.require(resolvedConfigPath); + } + setConfigObject(config); + } + catch (ex) { + // Deno will receive a PermissionDenied error if an attempt is + // made to load config without the --allow-read flag: + if (ex.name === 'PermissionDenied') + error = ex; + else if (argv[configKey]) + error = Error(__('Invalid JSON config file: %s', configPath)); + } + } + }); + } + // set args from config object. + // it recursively checks nested objects. + function setConfigObject(config, prev) { + Object.keys(config).forEach(function (key) { + const value = config[key]; + const fullKey = prev ? prev + '.' + key : key; + // if the value is an inner object and we have dot-notation + // enabled, treat inner objects in config the same as + // heavily nested dot notations (foo.bar.apple). + if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) { + // if the value is an object but not an array, check nested object + setConfigObject(value, fullKey); + } + else { + // setting arguments via CLI takes precedence over + // values within the config file. + if (!hasKey(argv, fullKey.split('.')) || (checkAllAliases(fullKey, flags.arrays) && configuration['combine-arrays'])) { + setArg(fullKey, value); + } + } + }); + } + // set all config objects passed in opts + function setConfigObjects() { + if (typeof configObjects !== 'undefined') { + configObjects.forEach(function (configObject) { + setConfigObject(configObject); + }); + } + } + function applyEnvVars(argv, configOnly) { + if (typeof envPrefix === 'undefined') + return; + const prefix = typeof envPrefix === 'string' ? envPrefix : ''; + const env = mixin.env(); + Object.keys(env).forEach(function (envVar) { + if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) { + // get array of nested keys and convert them to camel case + const keys = envVar.split('__').map(function (key, i) { + if (i === 0) { + key = key.substring(prefix.length); + } + return camelCase(key); + }); + if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && !hasKey(argv, keys)) { + setArg(keys.join('.'), env[envVar]); + } + } + }); + } + function applyCoercions(argv) { + let coerce; + const applied = new Set(); + Object.keys(argv).forEach(function (key) { + if (!applied.has(key)) { // If we haven't already coerced this option via one of its aliases + coerce = checkAllAliases(key, flags.coercions); + if (typeof coerce === 'function') { + try { + const value = maybeCoerceNumber(key, coerce(argv[key])); + ([].concat(flags.aliases[key] || [], key)).forEach(ali => { + applied.add(ali); + argv[ali] = value; + }); + } + catch (err) { + error = err; + } + } + } + }); + } + function setPlaceholderKeys(argv) { + flags.keys.forEach((key) => { + // don't set placeholder keys for dot notation options 'foo.bar'. + if (~key.indexOf('.')) + return; + if (typeof argv[key] === 'undefined') + argv[key] = undefined; + }); + return argv; + } + function applyDefaultsAndAliases(obj, aliases, defaults, canLog = false) { + Object.keys(defaults).forEach(function (key) { + if (!hasKey(obj, key.split('.'))) { + setKey(obj, key.split('.'), defaults[key]); + if (canLog) + defaulted[key] = true; + (aliases[key] || []).forEach(function (x) { + if (hasKey(obj, x.split('.'))) + return; + setKey(obj, x.split('.'), defaults[key]); + }); + } + }); + } + function hasKey(obj, keys) { + let o = obj; + if (!configuration['dot-notation']) + keys = [keys.join('.')]; + keys.slice(0, -1).forEach(function (key) { + o = (o[key] || {}); + }); + const key = keys[keys.length - 1]; + if (typeof o !== 'object') + return false; + else + return key in o; + } + function setKey(obj, keys, value) { + let o = obj; + if (!configuration['dot-notation']) + keys = [keys.join('.')]; + keys.slice(0, -1).forEach(function (key) { + // TODO(bcoe): in the next major version of yargs, switch to + // Object.create(null) for dot notation: + key = sanitizeKey(key); + if (typeof o === 'object' && o[key] === undefined) { + o[key] = {}; + } + if (typeof o[key] !== 'object' || Array.isArray(o[key])) { + // ensure that o[key] is an array, and that the last item is an empty object. + if (Array.isArray(o[key])) { + o[key].push({}); + } + else { + o[key] = [o[key], {}]; + } + // we want to update the empty object at the end of the o[key] array, so set o to that object + o = o[key][o[key].length - 1]; + } + else { + o = o[key]; + } + }); + // TODO(bcoe): in the next major version of yargs, switch to + // Object.create(null) for dot notation: + const key = sanitizeKey(keys[keys.length - 1]); + const isTypeArray = checkAllAliases(keys.join('.'), flags.arrays); + const isValueArray = Array.isArray(value); + let duplicate = configuration['duplicate-arguments-array']; + // nargs has higher priority than duplicate + if (!duplicate && checkAllAliases(key, flags.nargs)) { + duplicate = true; + if ((!isUndefined(o[key]) && flags.nargs[key] === 1) || (Array.isArray(o[key]) && o[key].length === flags.nargs[key])) { + o[key] = undefined; + } + } + if (value === increment()) { + o[key] = increment(o[key]); + } + else if (Array.isArray(o[key])) { + if (duplicate && isTypeArray && isValueArray) { + o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]); + } + else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) { + o[key] = value; + } + else { + o[key] = o[key].concat([value]); + } + } + else if (o[key] === undefined && isTypeArray) { + o[key] = isValueArray ? value : [value]; + } + else if (duplicate && !(o[key] === undefined || + checkAllAliases(key, flags.counts) || + checkAllAliases(key, flags.bools))) { + o[key] = [o[key], value]; + } + else { + o[key] = value; + } + } + // extend the aliases list with inferred aliases. + function extendAliases(...args) { + args.forEach(function (obj) { + Object.keys(obj || {}).forEach(function (key) { + // short-circuit if we've already added a key + // to the aliases array, for example it might + // exist in both 'opts.default' and 'opts.key'. + if (flags.aliases[key]) + return; + flags.aliases[key] = [].concat(aliases[key] || []); + // For "--option-name", also set argv.optionName + flags.aliases[key].concat(key).forEach(function (x) { + if (/-/.test(x) && configuration['camel-case-expansion']) { + const c = camelCase(x); + if (c !== key && flags.aliases[key].indexOf(c) === -1) { + flags.aliases[key].push(c); + newAliases[c] = true; + } + } + }); + // For "--optionName", also set argv['option-name'] + flags.aliases[key].concat(key).forEach(function (x) { + if (x.length > 1 && /[A-Z]/.test(x) && configuration['camel-case-expansion']) { + const c = decamelize(x, '-'); + if (c !== key && flags.aliases[key].indexOf(c) === -1) { + flags.aliases[key].push(c); + newAliases[c] = true; + } + } + }); + flags.aliases[key].forEach(function (x) { + flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) { + return x !== y; + })); + }); + }); + }); + } + function checkAllAliases(key, flag) { + const toCheck = [].concat(flags.aliases[key] || [], key); + const keys = Object.keys(flag); + const setAlias = toCheck.find(key => keys.includes(key)); + return setAlias ? flag[setAlias] : false; + } + function hasAnyFlag(key) { + const flagsKeys = Object.keys(flags); + const toCheck = [].concat(flagsKeys.map(k => flags[k])); + return toCheck.some(function (flag) { + return Array.isArray(flag) ? flag.includes(key) : flag[key]; + }); + } + function hasFlagsMatching(arg, ...patterns) { + const toCheck = [].concat(...patterns); + return toCheck.some(function (pattern) { + const match = arg.match(pattern); + return match && hasAnyFlag(match[1]); + }); + } + // based on a simplified version of the short flag group parsing logic + function hasAllShortFlags(arg) { + // if this is a negative number, or doesn't start with a single hyphen, it's not a short flag group + if (arg.match(negative) || !arg.match(/^-[^-]+/)) { + return false; + } + let hasAllFlags = true; + let next; + const letters = arg.slice(1).split(''); + for (let j = 0; j < letters.length; j++) { + next = arg.slice(j + 2); + if (!hasAnyFlag(letters[j])) { + hasAllFlags = false; + break; + } + if ((letters[j + 1] && letters[j + 1] === '=') || + next === '-' || + (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) || + (letters[j + 1] && letters[j + 1].match(/\W/))) { + break; + } + } + return hasAllFlags; + } + function isUnknownOptionAsArg(arg) { + return configuration['unknown-options-as-args'] && isUnknownOption(arg); + } + function isUnknownOption(arg) { + arg = arg.replace(/^-{3,}/, '--'); + // ignore negative numbers + if (arg.match(negative)) { + return false; + } + // if this is a short option group and all of them are configured, it isn't unknown + if (hasAllShortFlags(arg)) { + return false; + } + // e.g. '--count=2' + const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/; + // e.g. '-a' or '--arg' + const normalFlag = /^-+([^=]+?)$/; + // e.g. '-a-' + const flagEndingInHyphen = /^-+([^=]+?)-$/; + // e.g. '-abc123' + const flagEndingInDigits = /^-+([^=]+?\d+)$/; + // e.g. '-a/usr/local' + const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/; + // check the different types of flag styles, including negatedBoolean, a pattern defined near the start of the parse method + return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters); + } + // make a best effort to pick a default value + // for an option based on name and type. + function defaultValue(key) { + if (!checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts) && + `${key}` in defaults) { + return defaults[key]; + } + else { + return defaultForType(guessType(key)); + } + } + // return a default value, given the type of a flag., + function defaultForType(type) { + const def = { + [DefaultValuesForTypeKey.BOOLEAN]: true, + [DefaultValuesForTypeKey.STRING]: '', + [DefaultValuesForTypeKey.NUMBER]: undefined, + [DefaultValuesForTypeKey.ARRAY]: [] + }; + return def[type]; + } + // given a flag, enforce a default type. + function guessType(key) { + let type = DefaultValuesForTypeKey.BOOLEAN; + if (checkAllAliases(key, flags.strings)) + type = DefaultValuesForTypeKey.STRING; + else if (checkAllAliases(key, flags.numbers)) + type = DefaultValuesForTypeKey.NUMBER; + else if (checkAllAliases(key, flags.bools)) + type = DefaultValuesForTypeKey.BOOLEAN; + else if (checkAllAliases(key, flags.arrays)) + type = DefaultValuesForTypeKey.ARRAY; + return type; + } + function isUndefined(num) { + return num === undefined; + } + // check user configuration settings for inconsistencies + function checkConfiguration() { + // count keys should not be set as array/narg + Object.keys(flags.counts).find(key => { + if (checkAllAliases(key, flags.arrays)) { + error = Error(__('Invalid configuration: %s, opts.count excludes opts.array.', key)); + return true; + } + else if (checkAllAliases(key, flags.nargs)) { + error = Error(__('Invalid configuration: %s, opts.count excludes opts.narg.', key)); + return true; + } + return false; + }); + } + return { + aliases: Object.assign({}, flags.aliases), + argv: Object.assign(argvReturn, argv), + configuration: configuration, + defaulted: Object.assign({}, defaulted), + error: error, + newAliases: Object.assign({}, newAliases) + }; + } +} +// if any aliases reference each other, we should +// merge them together. +function combineAliases(aliases) { + const aliasArrays = []; + const combined = Object.create(null); + let change = true; + // turn alias lookup hash {key: ['alias1', 'alias2']} into + // a simple array ['key', 'alias1', 'alias2'] + Object.keys(aliases).forEach(function (key) { + aliasArrays.push([].concat(aliases[key], key)); + }); + // combine arrays until zero changes are + // made in an iteration. + while (change) { + change = false; + for (let i = 0; i < aliasArrays.length; i++) { + for (let ii = i + 1; ii < aliasArrays.length; ii++) { + const intersect = aliasArrays[i].filter(function (v) { + return aliasArrays[ii].indexOf(v) !== -1; + }); + if (intersect.length) { + aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]); + aliasArrays.splice(ii, 1); + change = true; + break; + } + } + } + } + // map arrays back to the hash-lookup (de-dupe while + // we're at it). + aliasArrays.forEach(function (aliasArray) { + aliasArray = aliasArray.filter(function (v, i, self) { + return self.indexOf(v) === i; + }); + const lastAlias = aliasArray.pop(); + if (lastAlias !== undefined && typeof lastAlias === 'string') { + combined[lastAlias] = aliasArray; + } + }); + return combined; +} +// this function should only be called when a count is given as an arg +// it is NOT called to set a default value +// thus we can start the count at 1 instead of 0 +function increment(orig) { + return orig !== undefined ? orig + 1 : 1; +} +// TODO(bcoe): in the next major version of yargs, switch to +// Object.create(null) for dot notation: +function sanitizeKey(key) { + if (key === '__proto__') + return '___proto___'; + return key; +} +function stripQuotes(val) { + return (typeof val === 'string' && + (val[0] === "'" || val[0] === '"') && + val[val.length - 1] === val[0]) + ? val.substring(1, val.length - 1) + : val; +} diff --git a/node_modules/yargs-parser/package.json b/node_modules/yargs-parser/package.json new file mode 100644 index 0000000000000000000000000000000000000000..82c021783d1f9329c0dc82f6659271579c015288 --- /dev/null +++ b/node_modules/yargs-parser/package.json @@ -0,0 +1,78 @@ +{ + "name": "yargs-parser", + "version": "22.0.0", + "description": "the mighty option parser used by yargs", + "main": "build/lib/index.js", + "exports": { + ".": [ + { + "import": "./build/lib/index.js" + }, + "./build/lib/index.js" + ], + "./browser": [ + "./browser.js" + ] + }, + "type": "module", + "module": "./build/lib/index.js", + "scripts": { + "check": "gts lint", + "fix": "gts fix", + "pretest": "rimraf build && tsc -p tsconfig.test.json", + "test": "c8 --reporter=text --reporter=html mocha test/*.mjs", + "test:browser": "start-server-and-test 'serve ./ -p 8080' http://127.0.0.1:8080/package.json 'node ./test/browser/yargs-test.cjs'", + "pretest:typescript": "npm run pretest", + "test:typescript": "c8 mocha ./build/test/typescript/*.js", + "coverage": "c8 report --check-coverage", + "precompile": "rimraf build", + "compile": "tsc", + "prepare": "npm run compile" + }, + "repository": { + "type": "git", + "url": "https://github.com/yargs/yargs-parser.git" + }, + "keywords": [ + "argument", + "parser", + "yargs", + "command", + "cli", + "parsing", + "option", + "args", + "argument" + ], + "author": "Ben Coe ", + "license": "ISC", + "devDependencies": { + "@babel/eslint-parser": "^7.27.1", + "@babel/preset-typescript": "^7.27.1", + "@types/chai": "^5.2.1", + "@types/mocha": "^10.0.10", + "@types/node": "^22.15.3", + "@typescript-eslint/eslint-plugin": "^8.29.1", + "@typescript-eslint/parser": "^8.31.1", + "c8": "^10.1.3", + "chai": "^5.2.0", + "cross-env": "^7.0.2", + "eslint": "^8.57.1", + "gts": "^5.3.1", + "mocha": "^11.1.0", + "puppeteer": "^24.6.1", + "rimraf": "^6.0.1", + "serve": "^14.0.0", + "start-server-and-test": "^2.0.11", + "typescript": "^5.8.3" + }, + "files": [ + "browser.js", + "build", + "!*.d.ts", + "!*.d.cts" + ], + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=23" + } +} diff --git a/node_modules/yargs/LICENSE b/node_modules/yargs/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b0145ca0b03bdc922de70dbaf5ae87c3a244c413 --- /dev/null +++ b/node_modules/yargs/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright 2010 James Halliday (mail@substack.net); Modified work Copyright 2014 Contributors (ben@npmjs.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/yargs/README.md b/node_modules/yargs/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5a3c6698ad34cec9ca9ca5bd63fbbe742edaaa4b --- /dev/null +++ b/node_modules/yargs/README.md @@ -0,0 +1,182 @@ +

+ +

+

Yargs

+

+ Yargs be a node.js library fer hearties tryin' ter parse optstrings +

+ +
+ +![ci](https://github.com/yargs/yargs/workflows/ci/badge.svg) +[![NPM version][npm-image]][npm-url] +[![js-standard-style][standard-image]][standard-url] +[![Coverage][coverage-image]][coverage-url] +[![Conventional Commits][conventional-commits-image]][conventional-commits-url] + +## Description +Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface. + +It gives you: + +* commands and (grouped) options (`my-program.js serve --port=5000`). +* a dynamically generated help menu based on your arguments: + +``` +mocha [spec..] + +Run tests with Mocha + +Commands + mocha inspect [spec..] Run tests with Mocha [default] + mocha init create a client-side Mocha setup at + +Rules & Behavior + --allow-uncaught Allow uncaught errors to propagate [boolean] + --async-only, -A Require all tests to use a callback (async) or + return a Promise [boolean] +``` + +* generate completion scripts for Bash and Zsh for your command +* and [tons more](/docs/api.md). + +## Installation + +Stable version: +```bash +npm i yargs +``` + +Bleeding edge version with the most recent features: +```bash +npm i yargs@next +``` + +## Usage + +### Simple Example + +```javascript +#!/usr/bin/env node +import yargs from 'yargs'; +import { hideBin } from 'yargs/helpers'; +const argv = yargs(hideBin(process.argv)).parse() + +if (argv.ships > 3 && argv.distance < 53.5) { + console.log('Plunder more riffiwobbles!') +} else { + console.log('Retreat from the xupptumblers!') +} +``` + +```bash +$ ./plunder.js --ships=4 --distance=22 +Plunder more riffiwobbles! + +$ ./plunder.js --ships 12 --distance 98.7 +Retreat from the xupptumblers! +``` + +> Note: `hideBin` is a shorthand for `process.argv.slice(2)`. It has the benefit that it takes into account variations in some environments, e.g., [Electron](https://github.com/electron/electron/issues/4690). + +### Complex Example + +```javascript +#!/usr/bin/env node +import yargs from 'yargs'; +import { hideBin } from 'yargs/helpers'; + +yargs(hideBin(process.argv)) + .command('serve [port]', 'start the server', (yargs) => { + return yargs + .positional('port', { + describe: 'port to bind on', + default: 5000 + }) + }, (argv) => { + if (argv.verbose) console.info(`start server on :${argv.port}`) + serve(argv.port) + }) + .option('verbose', { + alias: 'v', + type: 'boolean', + description: 'Run with verbose logging' + }) + .parse() +``` + +Run the example above with `--help` to see the help for the application. + +## Supported Platforms + +### TypeScript + +yargs has type definitions at [@types/yargs][type-definitions]. + +``` +npm i @types/yargs --save-dev +``` + +See usage examples in [docs](/docs/typescript.md). + +### Deno + +As of `v16`, `yargs` supports [Deno](https://github.com/denoland/deno): + +```typescript +import yargs from 'https://deno.land/x/yargs@v17.7.2-deno/deno.ts' +import { Arguments } from 'https://deno.land/x/yargs@v17.7.2-deno/deno-types.ts' + +yargs(Deno.args) + .command('download ', 'download a list of files', (yargs: any) => { + return yargs.positional('files', { + describe: 'a list of files to do something with' + }) + }, (argv: Arguments) => { + console.info(argv) + }) + .strictCommands() + .demandCommand(1) + .parse() +``` + +> Note: If you use version tags in url then you also have to add `-deno` flag on the end, like `@17.7.2-deno` + +### Usage in Browser + +See examples of using yargs in the browser in [docs](/docs/browser.md). + +## Documentation + +### Table of Contents + +* [Yargs' API](/docs/api.md) +* [Examples](/docs/examples.md) +* [Parsing Tricks](/docs/tricks.md) + * [Stop the Parser](/docs/tricks.md#stop) + * [Negating Boolean Arguments](/docs/tricks.md#negate) + * [Numbers](/docs/tricks.md#numbers) + * [Arrays](/docs/tricks.md#arrays) + * [Objects](/docs/tricks.md#objects) + * [Quotes](/docs/tricks.md#quotes) +* [Advanced Topics](/docs/advanced.md) + * [Composing Your App Using Commands](/docs/advanced.md#commands) + * [Building Configurable CLI Apps](/docs/advanced.md#configuration) + * [Customizing Yargs' Parser](/docs/advanced.md#customizing) +* [Contributing](/contributing.md) + +## Supported Node.js Versions + +Libraries in this ecosystem make a best effort to track +[Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a +post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). + +[npm-url]: https://www.npmjs.com/package/yargs +[npm-image]: https://img.shields.io/npm/v/yargs.svg +[standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg +[standard-url]: http://standardjs.com/ +[conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg +[conventional-commits-url]: https://conventionalcommits.org/ +[type-definitions]: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs +[coverage-image]: https://img.shields.io/nycrc/yargs/yargs +[coverage-url]: https://github.com/yargs/yargs/blob/main/.nycrc diff --git a/node_modules/yargs/browser.d.ts b/node_modules/yargs/browser.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..21f3fc69190b574ab8456514d3da1972afa53973 --- /dev/null +++ b/node_modules/yargs/browser.d.ts @@ -0,0 +1,5 @@ +import {YargsFactory} from './build/lib/yargs-factory'; + +declare const Yargs: ReturnType; + +export default Yargs; diff --git a/node_modules/yargs/browser.mjs b/node_modules/yargs/browser.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2d0d6e9e5b7c3e264462f10f0152efafae75005c --- /dev/null +++ b/node_modules/yargs/browser.mjs @@ -0,0 +1,7 @@ +// Bootstrap yargs for browser: +import browserPlatformShim from './lib/platform-shims/browser.mjs'; +import {YargsFactory} from './build/lib/yargs-factory.js'; + +const Yargs = YargsFactory(browserPlatformShim); + +export default Yargs; diff --git a/node_modules/yargs/build/lib/argsert.js b/node_modules/yargs/build/lib/argsert.js new file mode 100644 index 0000000000000000000000000000000000000000..be5b3aa69f30d65946196e1c79621ca9987e5f36 --- /dev/null +++ b/node_modules/yargs/build/lib/argsert.js @@ -0,0 +1,62 @@ +import { YError } from './yerror.js'; +import { parseCommand } from './parse-command.js'; +const positionName = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']; +export function argsert(arg1, arg2, arg3) { + function parseArgs() { + return typeof arg1 === 'object' + ? [{ demanded: [], optional: [] }, arg1, arg2] + : [ + parseCommand(`cmd ${arg1}`), + arg2, + arg3, + ]; + } + try { + let position = 0; + const [parsed, callerArguments, _length] = parseArgs(); + const args = [].slice.call(callerArguments); + while (args.length && args[args.length - 1] === undefined) + args.pop(); + const length = _length || args.length; + if (length < parsed.demanded.length) { + throw new YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`); + } + const totalCommands = parsed.demanded.length + parsed.optional.length; + if (length > totalCommands) { + throw new YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`); + } + parsed.demanded.forEach(demanded => { + const arg = args.shift(); + const observedType = guessType(arg); + const matchingTypes = demanded.cmd.filter(type => type === observedType || type === '*'); + if (matchingTypes.length === 0) + argumentTypeError(observedType, demanded.cmd, position); + position += 1; + }); + parsed.optional.forEach(optional => { + if (args.length === 0) + return; + const arg = args.shift(); + const observedType = guessType(arg); + const matchingTypes = optional.cmd.filter(type => type === observedType || type === '*'); + if (matchingTypes.length === 0) + argumentTypeError(observedType, optional.cmd, position); + position += 1; + }); + } + catch (err) { + console.warn(err.stack); + } +} +function guessType(arg) { + if (Array.isArray(arg)) { + return 'array'; + } + else if (arg === null) { + return 'null'; + } + return typeof arg; +} +function argumentTypeError(observedType, allowedTypes, position) { + throw new YError(`Invalid ${positionName[position] || 'manyith'} argument. Expected ${allowedTypes.join(' or ')} but received ${observedType}.`); +} diff --git a/node_modules/yargs/build/lib/command.js b/node_modules/yargs/build/lib/command.js new file mode 100644 index 0000000000000000000000000000000000000000..984d18ccdece95758498ba7b1b12fda371b4cf12 --- /dev/null +++ b/node_modules/yargs/build/lib/command.js @@ -0,0 +1,479 @@ +import { assertNotStrictEqual, } from './typings/common-types.js'; +import { isPromise } from './utils/is-promise.js'; +import { applyMiddleware, commandMiddlewareFactory, } from './middleware.js'; +import { parseCommand } from './parse-command.js'; +import { isYargsInstance, } from './yargs-factory.js'; +import { maybeAsyncResult } from './utils/maybe-async-result.js'; +const DEFAULT_MARKER = /(^\*)|(^\$0)/; +export class CommandInstance { + constructor(usage, validation, globalMiddleware, shim) { + this.requireCache = new Set(); + this.handlers = {}; + this.aliasMap = {}; + this.frozens = []; + this.shim = shim; + this.usage = usage; + this.globalMiddleware = globalMiddleware; + this.validation = validation; + } + addDirectory(dir, req, callerFile, opts) { + opts = opts || {}; + this.requireCache.add(callerFile); + const fullDirPath = this.shim.path.resolve(this.shim.path.dirname(callerFile), dir); + const files = this.shim.readdirSync(fullDirPath, { + recursive: opts.recurse ? true : false, + }); + if (!Array.isArray(opts.extensions)) + opts.extensions = ['js']; + const visit = typeof opts.visit === 'function' ? opts.visit : (o) => o; + for (const fileb of files) { + const file = fileb.toString(); + if (opts.exclude) { + let exclude = false; + if (typeof opts.exclude === 'function') { + exclude = opts.exclude(file); + } + else { + exclude = opts.exclude.test(file); + } + if (exclude) + continue; + } + if (opts.include) { + let include = false; + if (typeof opts.include === 'function') { + include = opts.include(file); + } + else { + include = opts.include.test(file); + } + if (!include) + continue; + } + let supportedExtension = false; + for (const ext of opts.extensions) { + if (file.endsWith(ext)) + supportedExtension = true; + } + if (supportedExtension) { + const joined = this.shim.path.join(fullDirPath, file); + const module = req(joined); + const extendableModule = Object.create(null, Object.getOwnPropertyDescriptors({ ...module })); + const visited = visit(extendableModule, joined, file); + if (visited) { + if (this.requireCache.has(joined)) + continue; + else + this.requireCache.add(joined); + if (!extendableModule.command) { + extendableModule.command = this.shim.path.basename(joined, this.shim.path.extname(joined)); + } + this.addHandler(extendableModule); + } + } + } + } + addHandler(cmd, description, builder, handler, commandMiddleware, deprecated) { + let aliases = []; + const middlewares = commandMiddlewareFactory(commandMiddleware); + handler = handler || (() => { }); + if (Array.isArray(cmd)) { + if (isCommandAndAliases(cmd)) { + [cmd, ...aliases] = cmd; + } + else { + for (const command of cmd) { + this.addHandler(command); + } + } + } + else if (isCommandHandlerDefinition(cmd)) { + let command = Array.isArray(cmd.command) || typeof cmd.command === 'string' + ? cmd.command + : null; + if (command === null) { + throw new Error(`No command name given for module: ${this.shim.inspect(cmd)}`); + } + if (cmd.aliases) + command = [].concat(command).concat(cmd.aliases); + this.addHandler(command, this.extractDesc(cmd), cmd.builder, cmd.handler, cmd.middlewares, cmd.deprecated); + return; + } + else if (isCommandBuilderDefinition(builder)) { + this.addHandler([cmd].concat(aliases), description, builder.builder, builder.handler, builder.middlewares, builder.deprecated); + return; + } + if (typeof cmd === 'string') { + const parsedCommand = parseCommand(cmd); + aliases = aliases.map(alias => parseCommand(alias).cmd); + let isDefault = false; + const parsedAliases = [parsedCommand.cmd].concat(aliases).filter(c => { + if (DEFAULT_MARKER.test(c)) { + isDefault = true; + return false; + } + return true; + }); + if (parsedAliases.length === 0 && isDefault) + parsedAliases.push('$0'); + if (isDefault) { + parsedCommand.cmd = parsedAliases[0]; + aliases = parsedAliases.slice(1); + cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd); + } + aliases.forEach(alias => { + this.aliasMap[alias] = parsedCommand.cmd; + }); + if (description !== false) { + this.usage.command(cmd, description, isDefault, aliases, deprecated); + } + this.handlers[parsedCommand.cmd] = { + original: cmd, + description, + handler, + builder: builder || {}, + middlewares, + deprecated, + demanded: parsedCommand.demanded, + optional: parsedCommand.optional, + }; + if (isDefault) + this.defaultCommand = this.handlers[parsedCommand.cmd]; + } + } + getCommandHandlers() { + return this.handlers; + } + getCommands() { + return Object.keys(this.handlers).concat(Object.keys(this.aliasMap)); + } + hasDefaultCommand() { + return !!this.defaultCommand; + } + runCommand(command, yargs, parsed, commandIndex, helpOnly, helpOrVersionSet) { + const commandHandler = this.handlers[command] || + this.handlers[this.aliasMap[command]] || + this.defaultCommand; + const currentContext = yargs.getInternalMethods().getContext(); + const parentCommands = currentContext.commands.slice(); + const isDefaultCommand = !command; + if (command) { + currentContext.commands.push(command); + currentContext.fullCommands.push(commandHandler.original); + } + const builderResult = this.applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, parsed.aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet); + return isPromise(builderResult) + ? builderResult.then(result => this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, result.innerArgv, currentContext, helpOnly, result.aliases, yargs)) + : this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, builderResult.innerArgv, currentContext, helpOnly, builderResult.aliases, yargs); + } + applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet) { + const builder = commandHandler.builder; + let innerYargs = yargs; + if (isCommandBuilderCallback(builder)) { + yargs.getInternalMethods().getUsageInstance().freeze(); + const builderOutput = builder(yargs.getInternalMethods().reset(aliases), helpOrVersionSet); + if (isPromise(builderOutput)) { + return builderOutput.then(output => { + innerYargs = isYargsInstance(output) ? output : yargs; + return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly); + }); + } + } + else if (isCommandBuilderOptionDefinitions(builder)) { + yargs.getInternalMethods().getUsageInstance().freeze(); + innerYargs = yargs.getInternalMethods().reset(aliases); + Object.keys(commandHandler.builder).forEach(key => { + innerYargs.option(key, builder[key]); + }); + } + return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly); + } + parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly) { + if (isDefaultCommand) + innerYargs.getInternalMethods().getUsageInstance().unfreeze(true); + if (this.shouldUpdateUsage(innerYargs)) { + innerYargs + .getInternalMethods() + .getUsageInstance() + .usage(this.usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description); + } + const innerArgv = innerYargs + .getInternalMethods() + .runYargsParserAndExecuteCommands(null, undefined, true, commandIndex, helpOnly); + return isPromise(innerArgv) + ? innerArgv.then(argv => ({ + aliases: innerYargs.parsed.aliases, + innerArgv: argv, + })) + : { + aliases: innerYargs.parsed.aliases, + innerArgv: innerArgv, + }; + } + shouldUpdateUsage(yargs) { + return (!yargs.getInternalMethods().getUsageInstance().getUsageDisabled() && + yargs.getInternalMethods().getUsageInstance().getUsage().length === 0); + } + usageFromParentCommandsCommandHandler(parentCommands, commandHandler) { + const c = DEFAULT_MARKER.test(commandHandler.original) + ? commandHandler.original.replace(DEFAULT_MARKER, '').trim() + : commandHandler.original; + const pc = parentCommands.filter(c => { + return !DEFAULT_MARKER.test(c); + }); + pc.push(c); + return `$0 ${pc.join(' ')}`; + } + handleValidationAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, aliases, yargs, middlewares, positionalMap) { + if (!yargs.getInternalMethods().getHasOutput()) { + const validation = yargs + .getInternalMethods() + .runValidation(aliases, positionalMap, yargs.parsed.error, isDefaultCommand); + innerArgv = maybeAsyncResult(innerArgv, result => { + validation(result); + return result; + }); + } + if (commandHandler.handler && !yargs.getInternalMethods().getHasOutput()) { + yargs.getInternalMethods().setHasOutput(); + const populateDoubleDash = !!yargs.getOptions().configuration['populate--']; + yargs + .getInternalMethods() + .postProcess(innerArgv, populateDoubleDash, false, false); + innerArgv = applyMiddleware(innerArgv, yargs, middlewares, false); + innerArgv = maybeAsyncResult(innerArgv, result => { + const handlerResult = commandHandler.handler(result); + return isPromise(handlerResult) + ? handlerResult.then(() => result) + : result; + }); + if (!isDefaultCommand) { + yargs.getInternalMethods().getUsageInstance().cacheHelpMessage(); + } + if (isPromise(innerArgv) && + !yargs.getInternalMethods().hasParseCallback()) { + innerArgv.catch(error => { + try { + yargs.getInternalMethods().getUsageInstance().fail(null, error); + } + catch (_err) { + } + }); + } + } + if (!isDefaultCommand) { + currentContext.commands.pop(); + currentContext.fullCommands.pop(); + } + return innerArgv; + } + applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, helpOnly, aliases, yargs) { + let positionalMap = {}; + if (helpOnly) + return innerArgv; + if (!yargs.getInternalMethods().getHasOutput()) { + positionalMap = this.populatePositionals(commandHandler, innerArgv, currentContext, yargs); + } + const middlewares = this.globalMiddleware + .getMiddleware() + .slice(0) + .concat(commandHandler.middlewares); + const maybePromiseArgv = applyMiddleware(innerArgv, yargs, middlewares, true); + return isPromise(maybePromiseArgv) + ? maybePromiseArgv.then(resolvedInnerArgv => this.handleValidationAndGetResult(isDefaultCommand, commandHandler, resolvedInnerArgv, currentContext, aliases, yargs, middlewares, positionalMap)) + : this.handleValidationAndGetResult(isDefaultCommand, commandHandler, maybePromiseArgv, currentContext, aliases, yargs, middlewares, positionalMap); + } + populatePositionals(commandHandler, argv, context, yargs) { + argv._ = argv._.slice(context.commands.length); + const demanded = commandHandler.demanded.slice(0); + const optional = commandHandler.optional.slice(0); + const positionalMap = {}; + this.validation.positionalCount(demanded.length, argv._.length); + while (demanded.length) { + const demand = demanded.shift(); + this.populatePositional(demand, argv, positionalMap); + } + while (optional.length) { + const maybe = optional.shift(); + this.populatePositional(maybe, argv, positionalMap); + } + argv._ = context.commands.concat(argv._.map(a => '' + a)); + this.postProcessPositionals(argv, positionalMap, this.cmdToParseOptions(commandHandler.original), yargs); + return positionalMap; + } + populatePositional(positional, argv, positionalMap) { + const cmd = positional.cmd[0]; + if (positional.variadic) { + positionalMap[cmd] = argv._.splice(0).map(String); + } + else { + if (argv._.length) + positionalMap[cmd] = [String(argv._.shift())]; + } + } + cmdToParseOptions(cmdString) { + const parseOptions = { + array: [], + default: {}, + alias: {}, + demand: {}, + }; + const parsed = parseCommand(cmdString); + parsed.demanded.forEach(d => { + const [cmd, ...aliases] = d.cmd; + if (d.variadic) { + parseOptions.array.push(cmd); + parseOptions.default[cmd] = []; + } + parseOptions.alias[cmd] = aliases; + parseOptions.demand[cmd] = true; + }); + parsed.optional.forEach(o => { + const [cmd, ...aliases] = o.cmd; + if (o.variadic) { + parseOptions.array.push(cmd); + parseOptions.default[cmd] = []; + } + parseOptions.alias[cmd] = aliases; + }); + return parseOptions; + } + postProcessPositionals(argv, positionalMap, parseOptions, yargs) { + const options = Object.assign({}, yargs.getOptions()); + options.default = Object.assign(parseOptions.default, options.default); + for (const key of Object.keys(parseOptions.alias)) { + options.alias[key] = (options.alias[key] || []).concat(parseOptions.alias[key]); + } + options.array = options.array.concat(parseOptions.array); + options.config = {}; + const unparsed = []; + Object.keys(positionalMap).forEach(key => { + positionalMap[key].map(value => { + if (options.configuration['unknown-options-as-args']) + options.key[key] = true; + unparsed.push(`--${key}`); + unparsed.push(value); + }); + }); + if (!unparsed.length) + return; + const config = Object.assign({}, options.configuration, { + 'populate--': false, + }); + const parsed = this.shim.Parser.detailed(unparsed, Object.assign({}, options, { + configuration: config, + })); + if (parsed.error) { + yargs + .getInternalMethods() + .getUsageInstance() + .fail(parsed.error.message, parsed.error); + } + else { + const positionalKeys = Object.keys(positionalMap); + Object.keys(positionalMap).forEach(key => { + positionalKeys.push(...parsed.aliases[key]); + }); + Object.keys(parsed.argv).forEach(key => { + if (positionalKeys.includes(key)) { + if (!positionalMap[key]) + positionalMap[key] = parsed.argv[key]; + if (!this.isInConfigs(yargs, key) && + !this.isDefaulted(yargs, key) && + Object.prototype.hasOwnProperty.call(argv, key) && + Object.prototype.hasOwnProperty.call(parsed.argv, key) && + (Array.isArray(argv[key]) || Array.isArray(parsed.argv[key]))) { + argv[key] = [].concat(argv[key], parsed.argv[key]); + } + else { + argv[key] = parsed.argv[key]; + } + } + }); + } + } + isDefaulted(yargs, key) { + const { default: defaults } = yargs.getOptions(); + return (Object.prototype.hasOwnProperty.call(defaults, key) || + Object.prototype.hasOwnProperty.call(defaults, this.shim.Parser.camelCase(key))); + } + isInConfigs(yargs, key) { + const { configObjects } = yargs.getOptions(); + return (configObjects.some(c => Object.prototype.hasOwnProperty.call(c, key)) || + configObjects.some(c => Object.prototype.hasOwnProperty.call(c, this.shim.Parser.camelCase(key)))); + } + runDefaultBuilderOn(yargs) { + if (!this.defaultCommand) + return; + if (this.shouldUpdateUsage(yargs)) { + const commandString = DEFAULT_MARKER.test(this.defaultCommand.original) + ? this.defaultCommand.original + : this.defaultCommand.original.replace(/^[^[\]<>]*/, '$0 '); + yargs + .getInternalMethods() + .getUsageInstance() + .usage(commandString, this.defaultCommand.description); + } + const builder = this.defaultCommand.builder; + if (isCommandBuilderCallback(builder)) { + return builder(yargs, true); + } + else if (!isCommandBuilderDefinition(builder)) { + Object.keys(builder).forEach(key => { + yargs.option(key, builder[key]); + }); + } + return undefined; + } + extractDesc({ describe, description, desc }) { + for (const test of [describe, description, desc]) { + if (typeof test === 'string' || test === false) + return test; + assertNotStrictEqual(test, true, this.shim); + } + return false; + } + freeze() { + this.frozens.push({ + handlers: this.handlers, + aliasMap: this.aliasMap, + defaultCommand: this.defaultCommand, + }); + } + unfreeze() { + const frozen = this.frozens.pop(); + assertNotStrictEqual(frozen, undefined, this.shim); + ({ + handlers: this.handlers, + aliasMap: this.aliasMap, + defaultCommand: this.defaultCommand, + } = frozen); + } + reset() { + this.handlers = {}; + this.aliasMap = {}; + this.defaultCommand = undefined; + this.requireCache = new Set(); + return this; + } +} +export function command(usage, validation, globalMiddleware, shim) { + return new CommandInstance(usage, validation, globalMiddleware, shim); +} +export function isCommandBuilderDefinition(builder) { + return (typeof builder === 'object' && + !!builder.builder && + typeof builder.handler === 'function'); +} +function isCommandAndAliases(cmd) { + return cmd.every(c => typeof c === 'string'); +} +export function isCommandBuilderCallback(builder) { + return typeof builder === 'function'; +} +function isCommandBuilderOptionDefinitions(builder) { + return typeof builder === 'object'; +} +export function isCommandHandlerDefinition(cmd) { + return typeof cmd === 'object' && !Array.isArray(cmd); +} diff --git a/node_modules/yargs/build/lib/completion-templates.js b/node_modules/yargs/build/lib/completion-templates.js new file mode 100644 index 0000000000000000000000000000000000000000..28cb5e6b00067f870c12771e2e763c6eaf0223a0 --- /dev/null +++ b/node_modules/yargs/build/lib/completion-templates.js @@ -0,0 +1,57 @@ +export const completionShTemplate = `###-begin-{{app_name}}-completions-### +# +# yargs command completion script +# +# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc +# or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX. +# +_{{app_name}}_yargs_completions() +{ + local cur_word args type_list + + cur_word="\${COMP_WORDS[COMP_CWORD]}" + args=("\${COMP_WORDS[@]}") + + # ask yargs to generate completions. + # see https://stackoverflow.com/a/40944195/7080036 for the spaces-handling awk + mapfile -t type_list < <({{app_path}} --get-yargs-completions "\${args[@]}") + mapfile -t COMPREPLY < <(compgen -W "$( printf '%q ' "\${type_list[@]}" )" -- "\${cur_word}" | + awk '/ / { print "\\""$0"\\"" } /^[^ ]+$/ { print $0 }') + + # if no match was found, fall back to filename completion + if [ \${#COMPREPLY[@]} -eq 0 ]; then + COMPREPLY=() + fi + + return 0 +} +complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}} +###-end-{{app_name}}-completions-### +`; +export const completionZshTemplate = `#compdef {{app_name}} +###-begin-{{app_name}}-completions-### +# +# yargs command completion script +# +# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc +# or {{app_path}} {{completion_command}} >> ~/.zprofile on OSX. +# +_{{app_name}}_yargs_completions() +{ + local reply + local si=$IFS + IFS=$'\n' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "\${words[@]}")) + IFS=$si + if [[ \${#reply} -gt 0 ]]; then + _describe 'values' reply + else + _default + fi +} +if [[ "'\${zsh_eval_context[-1]}" == "loadautofunc" ]]; then + _{{app_name}}_yargs_completions "$@" +else + compdef _{{app_name}}_yargs_completions {{app_name}} +fi +###-end-{{app_name}}-completions-### +`; diff --git a/node_modules/yargs/build/lib/completion.js b/node_modules/yargs/build/lib/completion.js new file mode 100644 index 0000000000000000000000000000000000000000..cef2bbe0890aa083348a2e9a55d7e4bb6b7ee672 --- /dev/null +++ b/node_modules/yargs/build/lib/completion.js @@ -0,0 +1,243 @@ +import { isCommandBuilderCallback } from './command.js'; +import { assertNotStrictEqual } from './typings/common-types.js'; +import * as templates from './completion-templates.js'; +import { isPromise } from './utils/is-promise.js'; +import { parseCommand } from './parse-command.js'; +export class Completion { + constructor(yargs, usage, command, shim) { + var _a, _b, _c; + this.yargs = yargs; + this.usage = usage; + this.command = command; + this.shim = shim; + this.completionKey = 'get-yargs-completions'; + this.aliases = null; + this.customCompletionFunction = null; + this.indexAfterLastReset = 0; + this.zshShell = + (_c = (((_a = this.shim.getEnv('SHELL')) === null || _a === void 0 ? void 0 : _a.includes('zsh')) || + ((_b = this.shim.getEnv('ZSH_NAME')) === null || _b === void 0 ? void 0 : _b.includes('zsh')))) !== null && _c !== void 0 ? _c : false; + } + defaultCompletion(args, argv, current, done) { + const handlers = this.command.getCommandHandlers(); + for (let i = 0, ii = args.length; i < ii; ++i) { + if (handlers[args[i]] && handlers[args[i]].builder) { + const builder = handlers[args[i]].builder; + if (isCommandBuilderCallback(builder)) { + this.indexAfterLastReset = i + 1; + const y = this.yargs.getInternalMethods().reset(); + builder(y, true); + return y.argv; + } + } + } + const completions = []; + this.commandCompletions(completions, args, current); + this.optionCompletions(completions, args, argv, current); + this.choicesFromOptionsCompletions(completions, args, argv, current); + this.choicesFromPositionalsCompletions(completions, args, argv, current); + done(null, completions); + } + commandCompletions(completions, args, current) { + const parentCommands = this.yargs + .getInternalMethods() + .getContext().commands; + if (!current.match(/^-/) && + parentCommands[parentCommands.length - 1] !== current && + !this.previousArgHasChoices(args)) { + this.usage.getCommands().forEach(usageCommand => { + const commandName = parseCommand(usageCommand[0]).cmd; + if (args.indexOf(commandName) === -1) { + if (!this.zshShell) { + completions.push(commandName); + } + else { + const desc = usageCommand[1] || ''; + completions.push(commandName.replace(/:/g, '\\:') + ':' + desc); + } + } + }); + } + } + optionCompletions(completions, args, argv, current) { + if ((current.match(/^-/) || (current === '' && completions.length === 0)) && + !this.previousArgHasChoices(args)) { + const options = this.yargs.getOptions(); + const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || []; + Object.keys(options.key).forEach(key => { + const negable = !!options.configuration['boolean-negation'] && + options.boolean.includes(key); + const isPositionalKey = positionalKeys.includes(key); + if (!isPositionalKey && + !options.hiddenOptions.includes(key) && + !this.argsContainKey(args, key, negable)) { + this.completeOptionKey(key, completions, current, negable && !!options.default[key]); + } + }); + } + } + choicesFromOptionsCompletions(completions, args, argv, current) { + if (this.previousArgHasChoices(args)) { + const choices = this.getPreviousArgChoices(args); + if (choices && choices.length > 0) { + completions.push(...choices.map(c => c.replace(/:/g, '\\:'))); + } + } + } + choicesFromPositionalsCompletions(completions, args, argv, current) { + if (current === '' && + completions.length > 0 && + this.previousArgHasChoices(args)) { + return; + } + const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || []; + const offset = Math.max(this.indexAfterLastReset, this.yargs.getInternalMethods().getContext().commands.length + + 1); + const positionalKey = positionalKeys[argv._.length - offset - 1]; + if (!positionalKey) { + return; + } + const choices = this.yargs.getOptions().choices[positionalKey] || []; + for (const choice of choices) { + if (choice.startsWith(current)) { + completions.push(choice.replace(/:/g, '\\:')); + } + } + } + getPreviousArgChoices(args) { + if (args.length < 1) + return; + let previousArg = args[args.length - 1]; + let filter = ''; + if (!previousArg.startsWith('-') && args.length > 1) { + filter = previousArg; + previousArg = args[args.length - 2]; + } + if (!previousArg.startsWith('-')) + return; + const previousArgKey = previousArg.replace(/^-+/, ''); + const options = this.yargs.getOptions(); + const possibleAliases = [ + previousArgKey, + ...(this.yargs.getAliases()[previousArgKey] || []), + ]; + let choices; + for (const possibleAlias of possibleAliases) { + if (Object.prototype.hasOwnProperty.call(options.key, possibleAlias) && + Array.isArray(options.choices[possibleAlias])) { + choices = options.choices[possibleAlias]; + break; + } + } + if (choices) { + return choices.filter(choice => !filter || choice.startsWith(filter)); + } + } + previousArgHasChoices(args) { + const choices = this.getPreviousArgChoices(args); + return choices !== undefined && choices.length > 0; + } + argsContainKey(args, key, negable) { + const argsContains = (s) => args.indexOf((/^[^0-9]$/.test(s) ? '-' : '--') + s) !== -1; + if (argsContains(key)) + return true; + if (negable && argsContains(`no-${key}`)) + return true; + if (this.aliases) { + for (const alias of this.aliases[key]) { + if (argsContains(alias)) + return true; + } + } + return false; + } + completeOptionKey(key, completions, current, negable) { + var _a, _b, _c, _d; + let keyWithDesc = key; + if (this.zshShell) { + const descs = this.usage.getDescriptions(); + const aliasKey = (_b = (_a = this === null || this === void 0 ? void 0 : this.aliases) === null || _a === void 0 ? void 0 : _a[key]) === null || _b === void 0 ? void 0 : _b.find(alias => { + const desc = descs[alias]; + return typeof desc === 'string' && desc.length > 0; + }); + const descFromAlias = aliasKey ? descs[aliasKey] : undefined; + const desc = (_d = (_c = descs[key]) !== null && _c !== void 0 ? _c : descFromAlias) !== null && _d !== void 0 ? _d : ''; + keyWithDesc = `${key.replace(/:/g, '\\:')}:${desc + .replace('__yargsString__:', '') + .replace(/(\r\n|\n|\r)/gm, ' ')}`; + } + const startsByTwoDashes = (s) => /^--/.test(s); + const isShortOption = (s) => /^[^0-9]$/.test(s); + const dashes = !startsByTwoDashes(current) && isShortOption(key) ? '-' : '--'; + completions.push(dashes + keyWithDesc); + if (negable) { + completions.push(dashes + 'no-' + keyWithDesc); + } + } + customCompletion(args, argv, current, done) { + assertNotStrictEqual(this.customCompletionFunction, null, this.shim); + if (isSyncCompletionFunction(this.customCompletionFunction)) { + const result = this.customCompletionFunction(current, argv); + if (isPromise(result)) { + return result + .then(list => { + this.shim.process.nextTick(() => { + done(null, list); + }); + }) + .catch(err => { + this.shim.process.nextTick(() => { + done(err, undefined); + }); + }); + } + return done(null, result); + } + else if (isFallbackCompletionFunction(this.customCompletionFunction)) { + return this.customCompletionFunction(current, argv, (onCompleted = done) => this.defaultCompletion(args, argv, current, onCompleted), completions => { + done(null, completions); + }); + } + else { + return this.customCompletionFunction(current, argv, completions => { + done(null, completions); + }); + } + } + getCompletion(args, done) { + const current = args.length ? args[args.length - 1] : ''; + const argv = this.yargs.parse(args, true); + const completionFunction = this.customCompletionFunction + ? (argv) => this.customCompletion(args, argv, current, done) + : (argv) => this.defaultCompletion(args, argv, current, done); + return isPromise(argv) + ? argv.then(completionFunction) + : completionFunction(argv); + } + generateCompletionScript($0, cmd) { + let script = this.zshShell + ? templates.completionZshTemplate + : templates.completionShTemplate; + const name = this.shim.path.basename($0); + if ($0.match(/\.js$/)) + $0 = `./${$0}`; + script = script.replace(/{{app_name}}/g, name); + script = script.replace(/{{completion_command}}/g, cmd); + return script.replace(/{{app_path}}/g, $0); + } + registerFunction(fn) { + this.customCompletionFunction = fn; + } + setParsed(parsed) { + this.aliases = parsed.aliases; + } +} +export function completion(yargs, usage, command, shim) { + return new Completion(yargs, usage, command, shim); +} +function isSyncCompletionFunction(completionFunction) { + return completionFunction.length < 3; +} +function isFallbackCompletionFunction(completionFunction) { + return completionFunction.length > 3; +} diff --git a/node_modules/yargs/build/lib/middleware.js b/node_modules/yargs/build/lib/middleware.js new file mode 100644 index 0000000000000000000000000000000000000000..4e561a79f8614dc18dc8df156ddaba7e996cfedc --- /dev/null +++ b/node_modules/yargs/build/lib/middleware.js @@ -0,0 +1,88 @@ +import { argsert } from './argsert.js'; +import { isPromise } from './utils/is-promise.js'; +export class GlobalMiddleware { + constructor(yargs) { + this.globalMiddleware = []; + this.frozens = []; + this.yargs = yargs; + } + addMiddleware(callback, applyBeforeValidation, global = true, mutates = false) { + argsert(' [boolean] [boolean] [boolean]', [callback, applyBeforeValidation, global], arguments.length); + if (Array.isArray(callback)) { + for (let i = 0; i < callback.length; i++) { + if (typeof callback[i] !== 'function') { + throw Error('middleware must be a function'); + } + const m = callback[i]; + m.applyBeforeValidation = applyBeforeValidation; + m.global = global; + } + Array.prototype.push.apply(this.globalMiddleware, callback); + } + else if (typeof callback === 'function') { + const m = callback; + m.applyBeforeValidation = applyBeforeValidation; + m.global = global; + m.mutates = mutates; + this.globalMiddleware.push(callback); + } + return this.yargs; + } + addCoerceMiddleware(callback, option) { + const aliases = this.yargs.getAliases(); + this.globalMiddleware = this.globalMiddleware.filter(m => { + const toCheck = [...(aliases[option] || []), option]; + if (!m.option) + return true; + else + return !toCheck.includes(m.option); + }); + callback.option = option; + return this.addMiddleware(callback, true, true, true); + } + getMiddleware() { + return this.globalMiddleware; + } + freeze() { + this.frozens.push([...this.globalMiddleware]); + } + unfreeze() { + const frozen = this.frozens.pop(); + if (frozen !== undefined) + this.globalMiddleware = frozen; + } + reset() { + this.globalMiddleware = this.globalMiddleware.filter(m => m.global); + } +} +export function commandMiddlewareFactory(commandMiddleware) { + if (!commandMiddleware) + return []; + return commandMiddleware.map(middleware => { + middleware.applyBeforeValidation = false; + return middleware; + }); +} +export function applyMiddleware(argv, yargs, middlewares, beforeValidation) { + return middlewares.reduce((acc, middleware) => { + if (middleware.applyBeforeValidation !== beforeValidation) { + return acc; + } + if (middleware.mutates) { + if (middleware.applied) + return acc; + middleware.applied = true; + } + if (isPromise(acc)) { + return acc + .then(initialObj => Promise.all([initialObj, middleware(initialObj, yargs)])) + .then(([initialObj, middlewareObj]) => Object.assign(initialObj, middlewareObj)); + } + else { + const result = middleware(acc, yargs); + return isPromise(result) + ? result.then(middlewareObj => Object.assign(acc, middlewareObj)) + : Object.assign(acc, result); + } + }, argv); +} diff --git a/node_modules/yargs/build/lib/parse-command.js b/node_modules/yargs/build/lib/parse-command.js new file mode 100644 index 0000000000000000000000000000000000000000..4989f53102bff7466b12475db98047852d02eabc --- /dev/null +++ b/node_modules/yargs/build/lib/parse-command.js @@ -0,0 +1,32 @@ +export function parseCommand(cmd) { + const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, ' '); + const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/); + const bregex = /\.*[\][<>]/g; + const firstCommand = splitCommand.shift(); + if (!firstCommand) + throw new Error(`No command found in: ${cmd}`); + const parsedCommand = { + cmd: firstCommand.replace(bregex, ''), + demanded: [], + optional: [], + }; + splitCommand.forEach((cmd, i) => { + let variadic = false; + cmd = cmd.replace(/\s/g, ''); + if (/\.+[\]>]/.test(cmd) && i === splitCommand.length - 1) + variadic = true; + if (/^\[/.test(cmd)) { + parsedCommand.optional.push({ + cmd: cmd.replace(bregex, '').split('|'), + variadic, + }); + } + else { + parsedCommand.demanded.push({ + cmd: cmd.replace(bregex, '').split('|'), + variadic, + }); + } + }); + return parsedCommand; +} diff --git a/node_modules/yargs/build/lib/typings/common-types.js b/node_modules/yargs/build/lib/typings/common-types.js new file mode 100644 index 0000000000000000000000000000000000000000..73e1773a26a670272d0c3a9fabff2717b553fdbe --- /dev/null +++ b/node_modules/yargs/build/lib/typings/common-types.js @@ -0,0 +1,9 @@ +export function assertNotStrictEqual(actual, expected, shim, message) { + shim.assert.notStrictEqual(actual, expected, message); +} +export function assertSingleKey(actual, shim) { + shim.assert.strictEqual(typeof actual, 'string'); +} +export function objectKeys(object) { + return Object.keys(object); +} diff --git a/node_modules/yargs/build/lib/typings/yargs-parser-types.js b/node_modules/yargs/build/lib/typings/yargs-parser-types.js new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/node_modules/yargs/build/lib/typings/yargs-parser-types.js @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/yargs/build/lib/usage.js b/node_modules/yargs/build/lib/usage.js new file mode 100644 index 0000000000000000000000000000000000000000..0127c130d504fc0ac43adf40369f452c6c4782c7 --- /dev/null +++ b/node_modules/yargs/build/lib/usage.js @@ -0,0 +1,584 @@ +import { objFilter } from './utils/obj-filter.js'; +import { YError } from './yerror.js'; +import setBlocking from './utils/set-blocking.js'; +function isBoolean(fail) { + return typeof fail === 'boolean'; +} +export function usage(yargs, shim) { + const __ = shim.y18n.__; + const self = {}; + const fails = []; + self.failFn = function failFn(f) { + fails.push(f); + }; + let failMessage = null; + let globalFailMessage = null; + let showHelpOnFail = true; + self.showHelpOnFail = function showHelpOnFailFn(arg1 = true, arg2) { + const [enabled, message] = typeof arg1 === 'string' ? [true, arg1] : [arg1, arg2]; + if (yargs.getInternalMethods().isGlobalContext()) { + globalFailMessage = message; + } + failMessage = message; + showHelpOnFail = enabled; + return self; + }; + let failureOutput = false; + self.fail = function fail(msg, err) { + const logger = yargs.getInternalMethods().getLoggerInstance(); + if (fails.length) { + for (let i = fails.length - 1; i >= 0; --i) { + const fail = fails[i]; + if (isBoolean(fail)) { + if (err) + throw err; + else if (msg) + throw Error(msg); + } + else { + fail(msg, err, self); + } + } + } + else { + if (yargs.getExitProcess()) + setBlocking(true); + if (!failureOutput) { + failureOutput = true; + if (showHelpOnFail) { + yargs.showHelp('error'); + logger.error(); + } + if (msg || err) + logger.error(msg || err); + const globalOrCommandFailMessage = failMessage || globalFailMessage; + if (globalOrCommandFailMessage) { + if (msg || err) + logger.error(''); + logger.error(globalOrCommandFailMessage); + } + } + err = err || new YError(msg); + if (yargs.getExitProcess()) { + return yargs.exit(1); + } + else if (yargs.getInternalMethods().hasParseCallback()) { + return yargs.exit(1, err); + } + else { + throw err; + } + } + }; + let usages = []; + let usageDisabled = false; + self.usage = (msg, description) => { + if (msg === null) { + usageDisabled = true; + usages = []; + return self; + } + usageDisabled = false; + usages.push([msg, description || '']); + return self; + }; + self.getUsage = () => { + return usages; + }; + self.getUsageDisabled = () => { + return usageDisabled; + }; + self.getPositionalGroupName = () => { + return __('Positionals:'); + }; + let examples = []; + self.example = (cmd, description) => { + examples.push([cmd, description || '']); + }; + let commands = []; + self.command = function command(cmd, description, isDefault, aliases, deprecated = false) { + if (isDefault) { + commands = commands.map(cmdArray => { + cmdArray[2] = false; + return cmdArray; + }); + } + commands.push([cmd, description || '', isDefault, aliases, deprecated]); + }; + self.getCommands = () => commands; + let descriptions = {}; + self.describe = function describe(keyOrKeys, desc) { + if (Array.isArray(keyOrKeys)) { + keyOrKeys.forEach(k => { + self.describe(k, desc); + }); + } + else if (typeof keyOrKeys === 'object') { + Object.keys(keyOrKeys).forEach(k => { + self.describe(k, keyOrKeys[k]); + }); + } + else { + descriptions[keyOrKeys] = desc; + } + }; + self.getDescriptions = () => descriptions; + let epilogs = []; + self.epilog = msg => { + epilogs.push(msg); + }; + let wrapSet = false; + let wrap; + self.wrap = cols => { + wrapSet = true; + wrap = cols; + }; + self.getWrap = () => { + if (shim.getEnv('YARGS_DISABLE_WRAP')) { + return null; + } + if (!wrapSet) { + wrap = windowWidth(); + wrapSet = true; + } + return wrap; + }; + const deferY18nLookupPrefix = '__yargsString__:'; + self.deferY18nLookup = str => deferY18nLookupPrefix + str; + self.help = function help() { + if (cachedHelpMessage) + return cachedHelpMessage; + normalizeAliases(); + const base$0 = yargs.customScriptName + ? yargs.$0 + : shim.path.basename(yargs.$0); + const demandedOptions = yargs.getDemandedOptions(); + const demandedCommands = yargs.getDemandedCommands(); + const deprecatedOptions = yargs.getDeprecatedOptions(); + const groups = yargs.getGroups(); + const options = yargs.getOptions(); + let keys = []; + keys = keys.concat(Object.keys(descriptions)); + keys = keys.concat(Object.keys(demandedOptions)); + keys = keys.concat(Object.keys(demandedCommands)); + keys = keys.concat(Object.keys(options.default)); + keys = keys.filter(filterHiddenOptions); + keys = Object.keys(keys.reduce((acc, key) => { + if (key !== '_') + acc[key] = true; + return acc; + }, {})); + const theWrap = self.getWrap(); + const ui = shim.cliui({ + width: theWrap, + wrap: !!theWrap, + }); + if (!usageDisabled) { + if (usages.length) { + usages.forEach(usage => { + ui.div({ text: `${usage[0].replace(/\$0/g, base$0)}` }); + if (usage[1]) { + ui.div({ text: `${usage[1]}`, padding: [1, 0, 0, 0] }); + } + }); + ui.div(); + } + else if (commands.length) { + let u = null; + if (demandedCommands._) { + u = `${base$0} <${__('command')}>\n`; + } + else { + u = `${base$0} [${__('command')}]\n`; + } + ui.div(`${u}`); + } + } + if (commands.length > 1 || (commands.length === 1 && !commands[0][2])) { + ui.div(__('Commands:')); + const context = yargs.getInternalMethods().getContext(); + const parentCommands = context.commands.length + ? `${context.commands.join(' ')} ` + : ''; + if (yargs.getInternalMethods().getParserConfiguration()['sort-commands'] === + true) { + commands = commands.sort((a, b) => a[0].localeCompare(b[0])); + } + const prefix = base$0 ? `${base$0} ` : ''; + commands.forEach(command => { + const commandString = `${prefix}${parentCommands}${command[0].replace(/^\$0 ?/, '')}`; + ui.span({ + text: commandString, + padding: [0, 2, 0, 2], + width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4, + }, { text: command[1] }); + const hints = []; + if (command[2]) + hints.push(`[${__('default')}]`); + if (command[3] && command[3].length) { + hints.push(`[${__('aliases:')} ${command[3].join(', ')}]`); + } + if (command[4]) { + if (typeof command[4] === 'string') { + hints.push(`[${__('deprecated: %s', command[4])}]`); + } + else { + hints.push(`[${__('deprecated')}]`); + } + } + if (hints.length) { + ui.div({ + text: hints.join(' '), + padding: [0, 0, 0, 2], + align: 'right', + }); + } + else { + ui.div(); + } + }); + ui.div(); + } + const aliasKeys = (Object.keys(options.alias) || []).concat(Object.keys(yargs.parsed.newAliases) || []); + keys = keys.filter(key => !yargs.parsed.newAliases[key] && + aliasKeys.every(alias => (options.alias[alias] || []).indexOf(key) === -1)); + const defaultGroup = __('Options:'); + if (!groups[defaultGroup]) + groups[defaultGroup] = []; + addUngroupedKeys(keys, options.alias, groups, defaultGroup); + const isLongSwitch = (sw) => /^--/.test(getText(sw)); + const displayedGroups = Object.keys(groups) + .filter(groupName => groups[groupName].length > 0) + .map(groupName => { + const normalizedKeys = groups[groupName] + .filter(filterHiddenOptions) + .map(key => { + if (aliasKeys.includes(key)) + return key; + for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== undefined; i++) { + if ((options.alias[aliasKey] || []).includes(key)) + return aliasKey; + } + return key; + }); + return { groupName, normalizedKeys }; + }) + .filter(({ normalizedKeys }) => normalizedKeys.length > 0) + .map(({ groupName, normalizedKeys }) => { + const switches = normalizedKeys.reduce((acc, key) => { + acc[key] = [key] + .concat(options.alias[key] || []) + .map(sw => { + if (groupName === self.getPositionalGroupName()) + return sw; + else { + return ((/^[0-9]$/.test(sw) + ? options.boolean.includes(key) + ? '-' + : '--' + : sw.length > 1 + ? '--' + : '-') + sw); + } + }) + .sort((sw1, sw2) => isLongSwitch(sw1) === isLongSwitch(sw2) + ? 0 + : isLongSwitch(sw1) + ? 1 + : -1) + .join(', '); + return acc; + }, {}); + return { groupName, normalizedKeys, switches }; + }); + const shortSwitchesUsed = displayedGroups + .filter(({ groupName }) => groupName !== self.getPositionalGroupName()) + .some(({ normalizedKeys, switches }) => !normalizedKeys.every(key => isLongSwitch(switches[key]))); + if (shortSwitchesUsed) { + displayedGroups + .filter(({ groupName }) => groupName !== self.getPositionalGroupName()) + .forEach(({ normalizedKeys, switches }) => { + normalizedKeys.forEach(key => { + if (isLongSwitch(switches[key])) { + switches[key] = addIndentation(switches[key], '-x, '.length); + } + }); + }); + } + displayedGroups.forEach(({ groupName, normalizedKeys, switches }) => { + ui.div(groupName); + normalizedKeys.forEach(key => { + const kswitch = switches[key]; + let desc = descriptions[key] || ''; + let type = null; + if (desc.includes(deferY18nLookupPrefix)) + desc = __(desc.substring(deferY18nLookupPrefix.length)); + if (options.boolean.includes(key)) + type = `[${__('boolean')}]`; + if (options.count.includes(key)) + type = `[${__('count')}]`; + if (options.string.includes(key)) + type = `[${__('string')}]`; + if (options.normalize.includes(key)) + type = `[${__('string')}]`; + if (options.array.includes(key)) + type = `[${__('array')}]`; + if (options.number.includes(key)) + type = `[${__('number')}]`; + const deprecatedExtra = (deprecated) => typeof deprecated === 'string' + ? `[${__('deprecated: %s', deprecated)}]` + : `[${__('deprecated')}]`; + const extra = [ + key in deprecatedOptions + ? deprecatedExtra(deprecatedOptions[key]) + : null, + type, + key in demandedOptions ? `[${__('required')}]` : null, + options.choices && options.choices[key] + ? `[${__('choices:')} ${self.stringifiedValues(options.choices[key])}]` + : null, + defaultString(options.default[key], options.defaultDescription[key]), + ] + .filter(Boolean) + .join(' '); + ui.span({ + text: getText(kswitch), + padding: [0, 2, 0, 2 + getIndentation(kswitch)], + width: maxWidth(switches, theWrap) + 4, + }, desc); + const shouldHideOptionExtras = yargs.getInternalMethods().getUsageConfiguration()['hide-types'] === + true; + if (extra && !shouldHideOptionExtras) + ui.div({ text: extra, padding: [0, 0, 0, 2], align: 'right' }); + else + ui.div(); + }); + ui.div(); + }); + if (examples.length) { + ui.div(__('Examples:')); + examples.forEach(example => { + example[0] = example[0].replace(/\$0/g, base$0); + }); + examples.forEach(example => { + if (example[1] === '') { + ui.div({ + text: example[0], + padding: [0, 2, 0, 2], + }); + } + else { + ui.div({ + text: example[0], + padding: [0, 2, 0, 2], + width: maxWidth(examples, theWrap) + 4, + }, { + text: example[1], + }); + } + }); + ui.div(); + } + if (epilogs.length > 0) { + const e = epilogs + .map(epilog => epilog.replace(/\$0/g, base$0)) + .join('\n'); + ui.div(`${e}\n`); + } + return ui.toString().replace(/\s*$/, ''); + }; + function maxWidth(table, theWrap, modifier) { + let width = 0; + if (!Array.isArray(table)) { + table = Object.values(table).map(v => [v]); + } + table.forEach(v => { + width = Math.max(shim.stringWidth(modifier ? `${modifier} ${getText(v[0])}` : getText(v[0])) + getIndentation(v[0]), width); + }); + if (theWrap) + width = Math.min(width, parseInt((theWrap * 0.5).toString(), 10)); + return width; + } + function normalizeAliases() { + const demandedOptions = yargs.getDemandedOptions(); + const options = yargs.getOptions(); + (Object.keys(options.alias) || []).forEach(key => { + options.alias[key].forEach(alias => { + if (descriptions[alias]) + self.describe(key, descriptions[alias]); + if (alias in demandedOptions) + yargs.demandOption(key, demandedOptions[alias]); + if (options.boolean.includes(alias)) + yargs.boolean(key); + if (options.count.includes(alias)) + yargs.count(key); + if (options.string.includes(alias)) + yargs.string(key); + if (options.normalize.includes(alias)) + yargs.normalize(key); + if (options.array.includes(alias)) + yargs.array(key); + if (options.number.includes(alias)) + yargs.number(key); + }); + }); + } + let cachedHelpMessage; + self.cacheHelpMessage = function () { + cachedHelpMessage = this.help(); + }; + self.clearCachedHelpMessage = function () { + cachedHelpMessage = undefined; + }; + self.hasCachedHelpMessage = function () { + return !!cachedHelpMessage; + }; + function addUngroupedKeys(keys, aliases, groups, defaultGroup) { + let groupedKeys = []; + let toCheck = null; + Object.keys(groups).forEach(group => { + groupedKeys = groupedKeys.concat(groups[group]); + }); + keys.forEach(key => { + toCheck = [key].concat(aliases[key]); + if (!toCheck.some(k => groupedKeys.indexOf(k) !== -1)) { + groups[defaultGroup].push(key); + } + }); + return groupedKeys; + } + function filterHiddenOptions(key) { + return (yargs.getOptions().hiddenOptions.indexOf(key) < 0 || + yargs.parsed.argv[yargs.getOptions().showHiddenOpt]); + } + self.showHelp = (level) => { + const logger = yargs.getInternalMethods().getLoggerInstance(); + if (!level) + level = 'error'; + const emit = typeof level === 'function' ? level : logger[level]; + emit(self.help()); + }; + self.functionDescription = fn => { + const description = fn.name + ? shim.Parser.decamelize(fn.name, '-') + : __('generated-value'); + return ['(', description, ')'].join(''); + }; + self.stringifiedValues = function stringifiedValues(values, separator) { + let string = ''; + const sep = separator || ', '; + const array = [].concat(values); + if (!values || !array.length) + return string; + array.forEach(value => { + if (string.length) + string += sep; + string += JSON.stringify(value); + }); + return string; + }; + function defaultString(value, defaultDescription) { + let string = `[${__('default:')} `; + if (value === undefined && !defaultDescription) + return null; + if (defaultDescription) { + string += defaultDescription; + } + else { + switch (typeof value) { + case 'string': + string += `"${value}"`; + break; + case 'object': + string += JSON.stringify(value); + break; + default: + string += value; + } + } + return `${string}]`; + } + function windowWidth() { + const maxWidth = 80; + if (shim.process.stdColumns) { + return Math.min(maxWidth, shim.process.stdColumns); + } + else { + return maxWidth; + } + } + let version = null; + self.version = ver => { + version = ver; + }; + self.showVersion = level => { + const logger = yargs.getInternalMethods().getLoggerInstance(); + if (!level) + level = 'error'; + const emit = typeof level === 'function' ? level : logger[level]; + emit(version); + }; + self.reset = function reset(localLookup) { + failMessage = null; + failureOutput = false; + usages = []; + usageDisabled = false; + epilogs = []; + examples = []; + commands = []; + descriptions = objFilter(descriptions, k => !localLookup[k]); + return self; + }; + const frozens = []; + self.freeze = function freeze() { + frozens.push({ + failMessage, + failureOutput, + usages, + usageDisabled, + epilogs, + examples, + commands, + descriptions, + }); + }; + self.unfreeze = function unfreeze(defaultCommand = false) { + const frozen = frozens.pop(); + if (!frozen) + return; + if (defaultCommand) { + descriptions = { ...frozen.descriptions, ...descriptions }; + commands = [...frozen.commands, ...commands]; + usages = [...frozen.usages, ...usages]; + examples = [...frozen.examples, ...examples]; + epilogs = [...frozen.epilogs, ...epilogs]; + } + else { + ({ + failMessage, + failureOutput, + usages, + usageDisabled, + epilogs, + examples, + commands, + descriptions, + } = frozen); + } + }; + return self; +} +function isIndentedText(text) { + return typeof text === 'object'; +} +function addIndentation(text, indent) { + return isIndentedText(text) + ? { text: text.text, indentation: text.indentation + indent } + : { text, indentation: indent }; +} +function getIndentation(text) { + return isIndentedText(text) ? text.indentation : 0; +} +function getText(text) { + return isIndentedText(text) ? text.text : text; +} diff --git a/node_modules/yargs/build/lib/utils/apply-extends.js b/node_modules/yargs/build/lib/utils/apply-extends.js new file mode 100644 index 0000000000000000000000000000000000000000..91294c20191693ff8ac245c567b66957cfb63f3f --- /dev/null +++ b/node_modules/yargs/build/lib/utils/apply-extends.js @@ -0,0 +1,59 @@ +import { YError } from '../yerror.js'; +let previouslyVisitedConfigs = []; +let shim; +export function applyExtends(config, cwd, mergeExtends, _shim) { + shim = _shim; + let defaultConfig = {}; + if (Object.prototype.hasOwnProperty.call(config, 'extends')) { + if (typeof config.extends !== 'string') + return defaultConfig; + const isPath = /\.json|\..*rc$/.test(config.extends); + let pathToDefault = null; + if (!isPath) { + try { + pathToDefault = import.meta.resolve(config.extends); + } + catch (_err) { + return config; + } + } + else { + pathToDefault = getPathToDefaultConfig(cwd, config.extends); + } + checkForCircularExtends(pathToDefault); + previouslyVisitedConfigs.push(pathToDefault); + defaultConfig = isPath + ? JSON.parse(shim.readFileSync(pathToDefault, 'utf8')) + : _shim.require(config.extends); + delete config.extends; + defaultConfig = applyExtends(defaultConfig, shim.path.dirname(pathToDefault), mergeExtends, shim); + } + previouslyVisitedConfigs = []; + return mergeExtends + ? mergeDeep(defaultConfig, config) + : Object.assign({}, defaultConfig, config); +} +function checkForCircularExtends(cfgPath) { + if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) { + throw new YError(`Circular extended configurations: '${cfgPath}'.`); + } +} +function getPathToDefaultConfig(cwd, pathToExtend) { + return shim.path.resolve(cwd, pathToExtend); +} +function mergeDeep(config1, config2) { + const target = {}; + function isObject(obj) { + return obj && typeof obj === 'object' && !Array.isArray(obj); + } + Object.assign(target, config1); + for (const key of Object.keys(config2)) { + if (isObject(config2[key]) && isObject(target[key])) { + target[key] = mergeDeep(config1[key], config2[key]); + } + else { + target[key] = config2[key]; + } + } + return target; +} diff --git a/node_modules/yargs/build/lib/utils/is-promise.js b/node_modules/yargs/build/lib/utils/is-promise.js new file mode 100644 index 0000000000000000000000000000000000000000..d250c08aaf47c1e104a4ec720a5833242a0c9e26 --- /dev/null +++ b/node_modules/yargs/build/lib/utils/is-promise.js @@ -0,0 +1,5 @@ +export function isPromise(maybePromise) { + return (!!maybePromise && + !!maybePromise.then && + typeof maybePromise.then === 'function'); +} diff --git a/node_modules/yargs/build/lib/utils/levenshtein.js b/node_modules/yargs/build/lib/utils/levenshtein.js new file mode 100644 index 0000000000000000000000000000000000000000..60575ef34f08f8a711639dcd1e57f47030cc6af6 --- /dev/null +++ b/node_modules/yargs/build/lib/utils/levenshtein.js @@ -0,0 +1,34 @@ +export function levenshtein(a, b) { + if (a.length === 0) + return b.length; + if (b.length === 0) + return a.length; + const matrix = []; + let i; + for (i = 0; i <= b.length; i++) { + matrix[i] = [i]; + } + let j; + for (j = 0; j <= a.length; j++) { + matrix[0][j] = j; + } + for (i = 1; i <= b.length; i++) { + for (j = 1; j <= a.length; j++) { + if (b.charAt(i - 1) === a.charAt(j - 1)) { + matrix[i][j] = matrix[i - 1][j - 1]; + } + else { + if (i > 1 && + j > 1 && + b.charAt(i - 2) === a.charAt(j - 1) && + b.charAt(i - 1) === a.charAt(j - 2)) { + matrix[i][j] = matrix[i - 2][j - 2] + 1; + } + else { + matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1)); + } + } + } + } + return matrix[b.length][a.length]; +} diff --git a/node_modules/yargs/build/lib/utils/maybe-async-result.js b/node_modules/yargs/build/lib/utils/maybe-async-result.js new file mode 100644 index 0000000000000000000000000000000000000000..8c6a40c658a7704dc0756573d18c097ec20481ef --- /dev/null +++ b/node_modules/yargs/build/lib/utils/maybe-async-result.js @@ -0,0 +1,17 @@ +import { isPromise } from './is-promise.js'; +export function maybeAsyncResult(getResult, resultHandler, errorHandler = (err) => { + throw err; +}) { + try { + const result = isFunction(getResult) ? getResult() : getResult; + return isPromise(result) + ? result.then((result) => resultHandler(result)) + : resultHandler(result); + } + catch (err) { + return errorHandler(err); + } +} +function isFunction(arg) { + return typeof arg === 'function'; +} diff --git a/node_modules/yargs/build/lib/utils/obj-filter.js b/node_modules/yargs/build/lib/utils/obj-filter.js new file mode 100644 index 0000000000000000000000000000000000000000..cd68ad2983c063049da26ce1ac731bcbec9017f0 --- /dev/null +++ b/node_modules/yargs/build/lib/utils/obj-filter.js @@ -0,0 +1,10 @@ +import { objectKeys } from '../typings/common-types.js'; +export function objFilter(original = {}, filter = () => true) { + const obj = {}; + objectKeys(original).forEach(key => { + if (filter(key, original[key])) { + obj[key] = original[key]; + } + }); + return obj; +} diff --git a/node_modules/yargs/build/lib/utils/process-argv.js b/node_modules/yargs/build/lib/utils/process-argv.js new file mode 100644 index 0000000000000000000000000000000000000000..74dc9e4c451d0503ec91fd578429887f96f5a449 --- /dev/null +++ b/node_modules/yargs/build/lib/utils/process-argv.js @@ -0,0 +1,17 @@ +function getProcessArgvBinIndex() { + if (isBundledElectronApp()) + return 0; + return 1; +} +function isBundledElectronApp() { + return isElectronApp() && !process.defaultApp; +} +function isElectronApp() { + return !!process.versions.electron; +} +export function hideBin(argv) { + return argv.slice(getProcessArgvBinIndex() + 1); +} +export function getProcessArgvBin() { + return process.argv[getProcessArgvBinIndex()]; +} diff --git a/node_modules/yargs/build/lib/utils/set-blocking.js b/node_modules/yargs/build/lib/utils/set-blocking.js new file mode 100644 index 0000000000000000000000000000000000000000..88fb806df36b9f035b55b958776a4e429a8baeaa --- /dev/null +++ b/node_modules/yargs/build/lib/utils/set-blocking.js @@ -0,0 +1,12 @@ +export default function setBlocking(blocking) { + if (typeof process === 'undefined') + return; + [process.stdout, process.stderr].forEach(_stream => { + const stream = _stream; + if (stream._handle && + stream.isTTY && + typeof stream._handle.setBlocking === 'function') { + stream._handle.setBlocking(blocking); + } + }); +} diff --git a/node_modules/yargs/build/lib/utils/which-module.js b/node_modules/yargs/build/lib/utils/which-module.js new file mode 100644 index 0000000000000000000000000000000000000000..5974e22689d43f748460b4e103493fe70f7f3841 --- /dev/null +++ b/node_modules/yargs/build/lib/utils/which-module.js @@ -0,0 +1,10 @@ +export default function whichModule(exported) { + if (typeof require === 'undefined') + return null; + for (let i = 0, files = Object.keys(require.cache), mod; i < files.length; i++) { + mod = require.cache[files[i]]; + if (mod.exports === exported) + return mod; + } + return null; +} diff --git a/node_modules/yargs/build/lib/validation.js b/node_modules/yargs/build/lib/validation.js new file mode 100644 index 0000000000000000000000000000000000000000..bd2e1b8b1a70ebbac8088ae30c36d0a283a6ad81 --- /dev/null +++ b/node_modules/yargs/build/lib/validation.js @@ -0,0 +1,305 @@ +import { argsert } from './argsert.js'; +import { assertNotStrictEqual, } from './typings/common-types.js'; +import { levenshtein as distance } from './utils/levenshtein.js'; +import { objFilter } from './utils/obj-filter.js'; +const specialKeys = ['$0', '--', '_']; +export function validation(yargs, usage, shim) { + const __ = shim.y18n.__; + const __n = shim.y18n.__n; + const self = {}; + self.nonOptionCount = function nonOptionCount(argv) { + const demandedCommands = yargs.getDemandedCommands(); + const positionalCount = argv._.length + (argv['--'] ? argv['--'].length : 0); + const _s = positionalCount - yargs.getInternalMethods().getContext().commands.length; + if (demandedCommands._ && + (_s < demandedCommands._.min || _s > demandedCommands._.max)) { + if (_s < demandedCommands._.min) { + if (demandedCommands._.minMsg !== undefined) { + usage.fail(demandedCommands._.minMsg + ? demandedCommands._.minMsg + .replace(/\$0/g, _s.toString()) + .replace(/\$1/, demandedCommands._.min.toString()) + : null); + } + else { + usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', _s, _s.toString(), demandedCommands._.min.toString())); + } + } + else if (_s > demandedCommands._.max) { + if (demandedCommands._.maxMsg !== undefined) { + usage.fail(demandedCommands._.maxMsg + ? demandedCommands._.maxMsg + .replace(/\$0/g, _s.toString()) + .replace(/\$1/, demandedCommands._.max.toString()) + : null); + } + else { + usage.fail(__n('Too many non-option arguments: got %s, maximum of %s', 'Too many non-option arguments: got %s, maximum of %s', _s, _s.toString(), demandedCommands._.max.toString())); + } + } + } + }; + self.positionalCount = function positionalCount(required, observed) { + if (observed < required) { + usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', observed, observed + '', required + '')); + } + }; + self.requiredArguments = function requiredArguments(argv, demandedOptions) { + let missing = null; + for (const key of Object.keys(demandedOptions)) { + if (!Object.prototype.hasOwnProperty.call(argv, key) || + typeof argv[key] === 'undefined') { + missing = missing || {}; + missing[key] = demandedOptions[key]; + } + } + if (missing) { + const customMsgs = []; + for (const key of Object.keys(missing)) { + const msg = missing[key]; + if (msg && customMsgs.indexOf(msg) < 0) { + customMsgs.push(msg); + } + } + const customMsg = customMsgs.length ? `\n${customMsgs.join('\n')}` : ''; + usage.fail(__n('Missing required argument: %s', 'Missing required arguments: %s', Object.keys(missing).length, Object.keys(missing).join(', ') + customMsg)); + } + }; + self.unknownArguments = function unknownArguments(argv, aliases, positionalMap, isDefaultCommand, checkPositionals = true) { + var _a; + const commandKeys = yargs + .getInternalMethods() + .getCommandInstance() + .getCommands(); + const unknown = []; + const currentContext = yargs.getInternalMethods().getContext(); + Object.keys(argv).forEach(key => { + if (!specialKeys.includes(key) && + !Object.prototype.hasOwnProperty.call(positionalMap, key) && + !Object.prototype.hasOwnProperty.call(yargs.getInternalMethods().getParseContext(), key) && + !self.isValidAndSomeAliasIsNotNew(key, aliases)) { + unknown.push(key); + } + }); + if (checkPositionals && + (currentContext.commands.length > 0 || + commandKeys.length > 0 || + isDefaultCommand)) { + argv._.slice(currentContext.commands.length).forEach(key => { + if (!commandKeys.includes('' + key)) { + unknown.push('' + key); + } + }); + } + if (checkPositionals) { + const demandedCommands = yargs.getDemandedCommands(); + const maxNonOptDemanded = ((_a = demandedCommands._) === null || _a === void 0 ? void 0 : _a.max) || 0; + const expected = currentContext.commands.length + maxNonOptDemanded; + if (expected < argv._.length) { + argv._.slice(expected).forEach(key => { + key = String(key); + if (!currentContext.commands.includes(key) && + !unknown.includes(key)) { + unknown.push(key); + } + }); + } + } + if (unknown.length) { + usage.fail(__n('Unknown argument: %s', 'Unknown arguments: %s', unknown.length, unknown.map(s => (s.trim() ? s : `"${s}"`)).join(', '))); + } + }; + self.unknownCommands = function unknownCommands(argv) { + const commandKeys = yargs + .getInternalMethods() + .getCommandInstance() + .getCommands(); + const unknown = []; + const currentContext = yargs.getInternalMethods().getContext(); + if (currentContext.commands.length > 0 || commandKeys.length > 0) { + argv._.slice(currentContext.commands.length).forEach(key => { + if (!commandKeys.includes('' + key)) { + unknown.push('' + key); + } + }); + } + if (unknown.length > 0) { + usage.fail(__n('Unknown command: %s', 'Unknown commands: %s', unknown.length, unknown.join(', '))); + return true; + } + else { + return false; + } + }; + self.isValidAndSomeAliasIsNotNew = function isValidAndSomeAliasIsNotNew(key, aliases) { + if (!Object.prototype.hasOwnProperty.call(aliases, key)) { + return false; + } + const newAliases = yargs.parsed.newAliases; + return [key, ...aliases[key]].some(a => !Object.prototype.hasOwnProperty.call(newAliases, a) || !newAliases[key]); + }; + self.limitedChoices = function limitedChoices(argv) { + const options = yargs.getOptions(); + const invalid = {}; + if (!Object.keys(options.choices).length) + return; + Object.keys(argv).forEach(key => { + if (specialKeys.indexOf(key) === -1 && + Object.prototype.hasOwnProperty.call(options.choices, key)) { + [].concat(argv[key]).forEach(value => { + if (options.choices[key].indexOf(value) === -1 && + value !== undefined) { + invalid[key] = (invalid[key] || []).concat(value); + } + }); + } + }); + const invalidKeys = Object.keys(invalid); + if (!invalidKeys.length) + return; + let msg = __('Invalid values:'); + invalidKeys.forEach(key => { + msg += `\n ${__('Argument: %s, Given: %s, Choices: %s', key, usage.stringifiedValues(invalid[key]), usage.stringifiedValues(options.choices[key]))}`; + }); + usage.fail(msg); + }; + let implied = {}; + self.implies = function implies(key, value) { + argsert(' [array|number|string]', [key, value], arguments.length); + if (typeof key === 'object') { + Object.keys(key).forEach(k => { + self.implies(k, key[k]); + }); + } + else { + yargs.global(key); + if (!implied[key]) { + implied[key] = []; + } + if (Array.isArray(value)) { + value.forEach(i => self.implies(key, i)); + } + else { + assertNotStrictEqual(value, undefined, shim); + implied[key].push(value); + } + } + }; + self.getImplied = function getImplied() { + return implied; + }; + function keyExists(argv, val) { + const num = Number(val); + val = isNaN(num) ? val : num; + if (typeof val === 'number') { + val = argv._.length >= val; + } + else if (val.match(/^--no-.+/)) { + val = val.match(/^--no-(.+)/)[1]; + val = !Object.prototype.hasOwnProperty.call(argv, val); + } + else { + val = Object.prototype.hasOwnProperty.call(argv, val); + } + return val; + } + self.implications = function implications(argv) { + const implyFail = []; + Object.keys(implied).forEach(key => { + const origKey = key; + (implied[key] || []).forEach(value => { + let key = origKey; + const origValue = value; + key = keyExists(argv, key); + value = keyExists(argv, value); + if (key && !value) { + implyFail.push(` ${origKey} -> ${origValue}`); + } + }); + }); + if (implyFail.length) { + let msg = `${__('Implications failed:')}\n`; + implyFail.forEach(value => { + msg += value; + }); + usage.fail(msg); + } + }; + let conflicting = {}; + self.conflicts = function conflicts(key, value) { + argsert(' [array|string]', [key, value], arguments.length); + if (typeof key === 'object') { + Object.keys(key).forEach(k => { + self.conflicts(k, key[k]); + }); + } + else { + yargs.global(key); + if (!conflicting[key]) { + conflicting[key] = []; + } + if (Array.isArray(value)) { + value.forEach(i => self.conflicts(key, i)); + } + else { + conflicting[key].push(value); + } + } + }; + self.getConflicting = () => conflicting; + self.conflicting = function conflictingFn(argv) { + Object.keys(argv).forEach(key => { + if (conflicting[key]) { + conflicting[key].forEach(value => { + if (value && argv[key] !== undefined && argv[value] !== undefined) { + usage.fail(__('Arguments %s and %s are mutually exclusive', key, value)); + } + }); + } + }); + if (yargs.getInternalMethods().getParserConfiguration()['strip-dashed']) { + Object.keys(conflicting).forEach(key => { + conflicting[key].forEach(value => { + if (value && + argv[shim.Parser.camelCase(key)] !== undefined && + argv[shim.Parser.camelCase(value)] !== undefined) { + usage.fail(__('Arguments %s and %s are mutually exclusive', key, value)); + } + }); + }); + } + }; + self.recommendCommands = function recommendCommands(cmd, potentialCommands) { + const threshold = 3; + potentialCommands = potentialCommands.sort((a, b) => b.length - a.length); + let recommended = null; + let bestDistance = Infinity; + for (let i = 0, candidate; (candidate = potentialCommands[i]) !== undefined; i++) { + const d = distance(cmd, candidate); + if (d <= threshold && d < bestDistance) { + bestDistance = d; + recommended = candidate; + } + } + if (recommended) + usage.fail(__('Did you mean %s?', recommended)); + }; + self.reset = function reset(localLookup) { + implied = objFilter(implied, k => !localLookup[k]); + conflicting = objFilter(conflicting, k => !localLookup[k]); + return self; + }; + const frozens = []; + self.freeze = function freeze() { + frozens.push({ + implied, + conflicting, + }); + }; + self.unfreeze = function unfreeze() { + const frozen = frozens.pop(); + assertNotStrictEqual(frozen, undefined, shim); + ({ implied, conflicting } = frozen); + }; + return self; +} diff --git a/node_modules/yargs/build/lib/yargs-factory.js b/node_modules/yargs/build/lib/yargs-factory.js new file mode 100644 index 0000000000000000000000000000000000000000..642a357970b48d08c81794fc5aa5d1de6aeab19f --- /dev/null +++ b/node_modules/yargs/build/lib/yargs-factory.js @@ -0,0 +1,1517 @@ +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _YargsInstance_command, _YargsInstance_cwd, _YargsInstance_context, _YargsInstance_completion, _YargsInstance_completionCommand, _YargsInstance_defaultShowHiddenOpt, _YargsInstance_exitError, _YargsInstance_detectLocale, _YargsInstance_emittedWarnings, _YargsInstance_exitProcess, _YargsInstance_frozens, _YargsInstance_globalMiddleware, _YargsInstance_groups, _YargsInstance_hasOutput, _YargsInstance_helpOpt, _YargsInstance_isGlobalContext, _YargsInstance_logger, _YargsInstance_output, _YargsInstance_options, _YargsInstance_parentRequire, _YargsInstance_parserConfig, _YargsInstance_parseFn, _YargsInstance_parseContext, _YargsInstance_pkgs, _YargsInstance_preservedGroups, _YargsInstance_processArgs, _YargsInstance_recommendCommands, _YargsInstance_shim, _YargsInstance_strict, _YargsInstance_strictCommands, _YargsInstance_strictOptions, _YargsInstance_usage, _YargsInstance_usageConfig, _YargsInstance_versionOpt, _YargsInstance_validation; +import { command as Command, } from './command.js'; +import { assertNotStrictEqual, assertSingleKey, objectKeys, } from './typings/common-types.js'; +import { YError } from './yerror.js'; +import { usage as Usage } from './usage.js'; +import { argsert } from './argsert.js'; +import { completion as Completion, } from './completion.js'; +import { validation as Validation, } from './validation.js'; +import { objFilter } from './utils/obj-filter.js'; +import { applyExtends } from './utils/apply-extends.js'; +import { applyMiddleware, GlobalMiddleware, } from './middleware.js'; +import { isPromise } from './utils/is-promise.js'; +import { maybeAsyncResult } from './utils/maybe-async-result.js'; +import setBlocking from './utils/set-blocking.js'; +export function YargsFactory(_shim) { + return (processArgs = [], cwd = _shim.process.cwd(), parentRequire) => { + const yargs = new YargsInstance(processArgs, cwd, parentRequire, _shim); + Object.defineProperty(yargs, 'argv', { + get: () => { + return yargs.parse(); + }, + enumerable: true, + }); + yargs.help(); + yargs.version(); + return yargs; + }; +} +const kCopyDoubleDash = Symbol('copyDoubleDash'); +const kCreateLogger = Symbol('copyDoubleDash'); +const kDeleteFromParserHintObject = Symbol('deleteFromParserHintObject'); +const kEmitWarning = Symbol('emitWarning'); +const kFreeze = Symbol('freeze'); +const kGetDollarZero = Symbol('getDollarZero'); +const kGetParserConfiguration = Symbol('getParserConfiguration'); +const kGetUsageConfiguration = Symbol('getUsageConfiguration'); +const kGuessLocale = Symbol('guessLocale'); +const kGuessVersion = Symbol('guessVersion'); +const kParsePositionalNumbers = Symbol('parsePositionalNumbers'); +const kPkgUp = Symbol('pkgUp'); +const kPopulateParserHintArray = Symbol('populateParserHintArray'); +const kPopulateParserHintSingleValueDictionary = Symbol('populateParserHintSingleValueDictionary'); +const kPopulateParserHintArrayDictionary = Symbol('populateParserHintArrayDictionary'); +const kPopulateParserHintDictionary = Symbol('populateParserHintDictionary'); +const kSanitizeKey = Symbol('sanitizeKey'); +const kSetKey = Symbol('setKey'); +const kUnfreeze = Symbol('unfreeze'); +const kValidateAsync = Symbol('validateAsync'); +const kGetCommandInstance = Symbol('getCommandInstance'); +const kGetContext = Symbol('getContext'); +const kGetHasOutput = Symbol('getHasOutput'); +const kGetLoggerInstance = Symbol('getLoggerInstance'); +const kGetParseContext = Symbol('getParseContext'); +const kGetUsageInstance = Symbol('getUsageInstance'); +const kGetValidationInstance = Symbol('getValidationInstance'); +const kHasParseCallback = Symbol('hasParseCallback'); +const kIsGlobalContext = Symbol('isGlobalContext'); +const kPostProcess = Symbol('postProcess'); +const kRebase = Symbol('rebase'); +const kReset = Symbol('reset'); +const kRunYargsParserAndExecuteCommands = Symbol('runYargsParserAndExecuteCommands'); +const kRunValidation = Symbol('runValidation'); +const kSetHasOutput = Symbol('setHasOutput'); +const kTrackManuallySetKeys = Symbol('kTrackManuallySetKeys'); +const DEFAULT_LOCALE = 'en_US'; +export class YargsInstance { + constructor(processArgs = [], cwd, parentRequire, shim) { + this.customScriptName = false; + this.parsed = false; + _YargsInstance_command.set(this, void 0); + _YargsInstance_cwd.set(this, void 0); + _YargsInstance_context.set(this, { commands: [], fullCommands: [] }); + _YargsInstance_completion.set(this, null); + _YargsInstance_completionCommand.set(this, null); + _YargsInstance_defaultShowHiddenOpt.set(this, 'show-hidden'); + _YargsInstance_exitError.set(this, null); + _YargsInstance_detectLocale.set(this, true); + _YargsInstance_emittedWarnings.set(this, {}); + _YargsInstance_exitProcess.set(this, true); + _YargsInstance_frozens.set(this, []); + _YargsInstance_globalMiddleware.set(this, void 0); + _YargsInstance_groups.set(this, {}); + _YargsInstance_hasOutput.set(this, false); + _YargsInstance_helpOpt.set(this, null); + _YargsInstance_isGlobalContext.set(this, true); + _YargsInstance_logger.set(this, void 0); + _YargsInstance_output.set(this, ''); + _YargsInstance_options.set(this, void 0); + _YargsInstance_parentRequire.set(this, void 0); + _YargsInstance_parserConfig.set(this, {}); + _YargsInstance_parseFn.set(this, null); + _YargsInstance_parseContext.set(this, null); + _YargsInstance_pkgs.set(this, {}); + _YargsInstance_preservedGroups.set(this, {}); + _YargsInstance_processArgs.set(this, void 0); + _YargsInstance_recommendCommands.set(this, false); + _YargsInstance_shim.set(this, void 0); + _YargsInstance_strict.set(this, false); + _YargsInstance_strictCommands.set(this, false); + _YargsInstance_strictOptions.set(this, false); + _YargsInstance_usage.set(this, void 0); + _YargsInstance_usageConfig.set(this, {}); + _YargsInstance_versionOpt.set(this, null); + _YargsInstance_validation.set(this, void 0); + __classPrivateFieldSet(this, _YargsInstance_shim, shim, "f"); + __classPrivateFieldSet(this, _YargsInstance_processArgs, processArgs, "f"); + __classPrivateFieldSet(this, _YargsInstance_cwd, cwd, "f"); + __classPrivateFieldSet(this, _YargsInstance_parentRequire, parentRequire, "f"); + __classPrivateFieldSet(this, _YargsInstance_globalMiddleware, new GlobalMiddleware(this), "f"); + this.$0 = this[kGetDollarZero](); + this[kReset](); + __classPrivateFieldSet(this, _YargsInstance_command, __classPrivateFieldGet(this, _YargsInstance_command, "f"), "f"); + __classPrivateFieldSet(this, _YargsInstance_usage, __classPrivateFieldGet(this, _YargsInstance_usage, "f"), "f"); + __classPrivateFieldSet(this, _YargsInstance_validation, __classPrivateFieldGet(this, _YargsInstance_validation, "f"), "f"); + __classPrivateFieldSet(this, _YargsInstance_options, __classPrivateFieldGet(this, _YargsInstance_options, "f"), "f"); + __classPrivateFieldGet(this, _YargsInstance_options, "f").showHiddenOpt = __classPrivateFieldGet(this, _YargsInstance_defaultShowHiddenOpt, "f"); + __classPrivateFieldSet(this, _YargsInstance_logger, this[kCreateLogger](), "f"); + __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.setLocale(DEFAULT_LOCALE); + } + addHelpOpt(opt, msg) { + const defaultHelpOpt = 'help'; + argsert('[string|boolean] [string]', [opt, msg], arguments.length); + if (__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")) { + this[kDeleteFromParserHintObject](__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")); + __classPrivateFieldSet(this, _YargsInstance_helpOpt, null, "f"); + } + if (opt === false && msg === undefined) + return this; + __classPrivateFieldSet(this, _YargsInstance_helpOpt, typeof opt === 'string' ? opt : defaultHelpOpt, "f"); + this.boolean(__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")); + this.describe(__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f"), msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Show help')); + return this; + } + help(opt, msg) { + return this.addHelpOpt(opt, msg); + } + addShowHiddenOpt(opt, msg) { + argsert('[string|boolean] [string]', [opt, msg], arguments.length); + if (opt === false && msg === undefined) + return this; + const showHiddenOpt = typeof opt === 'string' ? opt : __classPrivateFieldGet(this, _YargsInstance_defaultShowHiddenOpt, "f"); + this.boolean(showHiddenOpt); + this.describe(showHiddenOpt, msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Show hidden options')); + __classPrivateFieldGet(this, _YargsInstance_options, "f").showHiddenOpt = showHiddenOpt; + return this; + } + showHidden(opt, msg) { + return this.addShowHiddenOpt(opt, msg); + } + alias(key, value) { + argsert(' [string|array]', [key, value], arguments.length); + this[kPopulateParserHintArrayDictionary](this.alias.bind(this), 'alias', key, value); + return this; + } + array(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('array', keys); + this[kTrackManuallySetKeys](keys); + return this; + } + boolean(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('boolean', keys); + this[kTrackManuallySetKeys](keys); + return this; + } + check(f, global) { + argsert(' [boolean]', [f, global], arguments.length); + this.middleware((argv, _yargs) => { + return maybeAsyncResult(() => { + return f(argv, _yargs.getOptions()); + }, (result) => { + if (!result) { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(__classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.__('Argument check failed: %s', f.toString())); + } + else if (typeof result === 'string' || result instanceof Error) { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(result.toString(), result); + } + return argv; + }, (err) => { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(err.message ? err.message : err.toString(), err); + return argv; + }); + }, false, global); + return this; + } + choices(key, value) { + argsert(' [string|array]', [key, value], arguments.length); + this[kPopulateParserHintArrayDictionary](this.choices.bind(this), 'choices', key, value); + return this; + } + coerce(keys, value) { + argsert(' [function]', [keys, value], arguments.length); + if (Array.isArray(keys)) { + if (!value) { + throw new YError('coerce callback must be provided'); + } + for (const key of keys) { + this.coerce(key, value); + } + return this; + } + else if (typeof keys === 'object') { + for (const key of Object.keys(keys)) { + this.coerce(key, keys[key]); + } + return this; + } + if (!value) { + throw new YError('coerce callback must be provided'); + } + const coerceKey = keys; + __classPrivateFieldGet(this, _YargsInstance_options, "f").key[coerceKey] = true; + __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").addCoerceMiddleware((argv, yargs) => { + var _a; + const coerceKeyAliases = (_a = yargs.getAliases()[coerceKey]) !== null && _a !== void 0 ? _a : []; + const argvKeys = [coerceKey, ...coerceKeyAliases].filter(key => Object.prototype.hasOwnProperty.call(argv, key)); + if (argvKeys.length === 0) { + return argv; + } + return maybeAsyncResult(() => { + return value(argv[argvKeys[0]]); + }, (result) => { + argvKeys.forEach(key => { + argv[key] = result; + }); + return argv; + }, (err) => { + throw new YError(err.message); + }); + }, coerceKey); + return this; + } + conflicts(key1, key2) { + argsert(' [string|array]', [key1, key2], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").conflicts(key1, key2); + return this; + } + config(key = 'config', msg, parseFn) { + argsert('[object|string] [string|function] [function]', [key, msg, parseFn], arguments.length); + if (typeof key === 'object' && !Array.isArray(key)) { + key = applyExtends(key, __classPrivateFieldGet(this, _YargsInstance_cwd, "f"), this[kGetParserConfiguration]()['deep-merge-config'] || false, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects = (__classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects || []).concat(key); + return this; + } + if (typeof msg === 'function') { + parseFn = msg; + msg = undefined; + } + this.describe(key, msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Path to JSON config file')); + (Array.isArray(key) ? key : [key]).forEach(k => { + __classPrivateFieldGet(this, _YargsInstance_options, "f").config[k] = parseFn || true; + }); + return this; + } + completion(cmd, desc, fn) { + argsert('[string] [string|boolean|function] [function]', [cmd, desc, fn], arguments.length); + if (typeof desc === 'function') { + fn = desc; + desc = undefined; + } + __classPrivateFieldSet(this, _YargsInstance_completionCommand, cmd || __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f") || 'completion', "f"); + if (!desc && desc !== false) { + desc = 'generate completion script'; + } + this.command(__classPrivateFieldGet(this, _YargsInstance_completionCommand, "f"), desc); + if (fn) + __classPrivateFieldGet(this, _YargsInstance_completion, "f").registerFunction(fn); + return this; + } + command(cmd, description, builder, handler, middlewares, deprecated) { + argsert(' [string|boolean] [function|object] [function] [array] [boolean|string]', [cmd, description, builder, handler, middlewares, deprecated], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_command, "f").addHandler(cmd, description, builder, handler, middlewares, deprecated); + return this; + } + commands(cmd, description, builder, handler, middlewares, deprecated) { + return this.command(cmd, description, builder, handler, middlewares, deprecated); + } + commandDir(dir, opts) { + argsert(' [object]', [dir, opts], arguments.length); + const req = __classPrivateFieldGet(this, _YargsInstance_parentRequire, "f") || __classPrivateFieldGet(this, _YargsInstance_shim, "f").require; + __classPrivateFieldGet(this, _YargsInstance_command, "f").addDirectory(dir, req, __classPrivateFieldGet(this, _YargsInstance_shim, "f").getCallerFile(), opts); + return this; + } + count(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('count', keys); + this[kTrackManuallySetKeys](keys); + return this; + } + default(key, value, defaultDescription) { + argsert(' [*] [string]', [key, value, defaultDescription], arguments.length); + if (defaultDescription) { + assertSingleKey(key, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + __classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key] = defaultDescription; + } + if (typeof value === 'function') { + assertSingleKey(key, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + if (!__classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key]) + __classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key] = + __classPrivateFieldGet(this, _YargsInstance_usage, "f").functionDescription(value); + value = value.call(); + } + this[kPopulateParserHintSingleValueDictionary](this.default.bind(this), 'default', key, value); + return this; + } + defaults(key, value, defaultDescription) { + return this.default(key, value, defaultDescription); + } + demandCommand(min = 1, max, minMsg, maxMsg) { + argsert('[number] [number|string] [string|null|undefined] [string|null|undefined]', [min, max, minMsg, maxMsg], arguments.length); + if (typeof max !== 'number') { + minMsg = max; + max = Infinity; + } + this.global('_', false); + __classPrivateFieldGet(this, _YargsInstance_options, "f").demandedCommands._ = { + min, + max, + minMsg, + maxMsg, + }; + return this; + } + demand(keys, max, msg) { + if (Array.isArray(max)) { + max.forEach(key => { + assertNotStrictEqual(msg, true, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + this.demandOption(key, msg); + }); + max = Infinity; + } + else if (typeof max !== 'number') { + msg = max; + max = Infinity; + } + if (typeof keys === 'number') { + assertNotStrictEqual(msg, true, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + this.demandCommand(keys, max, msg, msg); + } + else if (Array.isArray(keys)) { + keys.forEach(key => { + assertNotStrictEqual(msg, true, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + this.demandOption(key, msg); + }); + } + else { + if (typeof msg === 'string') { + this.demandOption(keys, msg); + } + else if (msg === true || typeof msg === 'undefined') { + this.demandOption(keys); + } + } + return this; + } + demandOption(keys, msg) { + argsert(' [string]', [keys, msg], arguments.length); + this[kPopulateParserHintSingleValueDictionary](this.demandOption.bind(this), 'demandedOptions', keys, msg); + return this; + } + deprecateOption(option, message) { + argsert(' [string|boolean]', [option, message], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_options, "f").deprecatedOptions[option] = message; + return this; + } + describe(keys, description) { + argsert(' [string]', [keys, description], arguments.length); + this[kSetKey](keys, true); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").describe(keys, description); + return this; + } + detectLocale(detect) { + argsert('', [detect], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_detectLocale, detect, "f"); + return this; + } + env(prefix) { + argsert('[string|boolean]', [prefix], arguments.length); + if (prefix === false) + delete __classPrivateFieldGet(this, _YargsInstance_options, "f").envPrefix; + else + __classPrivateFieldGet(this, _YargsInstance_options, "f").envPrefix = prefix || ''; + return this; + } + epilogue(msg) { + argsert('', [msg], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").epilog(msg); + return this; + } + epilog(msg) { + return this.epilogue(msg); + } + example(cmd, description) { + argsert(' [string]', [cmd, description], arguments.length); + if (Array.isArray(cmd)) { + cmd.forEach(exampleParams => this.example(...exampleParams)); + } + else { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").example(cmd, description); + } + return this; + } + exit(code, err) { + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + __classPrivateFieldSet(this, _YargsInstance_exitError, err, "f"); + if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) + __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.exit(code); + } + exitProcess(enabled = true) { + argsert('[boolean]', [enabled], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_exitProcess, enabled, "f"); + return this; + } + fail(f) { + argsert('', [f], arguments.length); + if (typeof f === 'boolean' && f !== false) { + throw new YError("Invalid first argument. Expected function or boolean 'false'"); + } + __classPrivateFieldGet(this, _YargsInstance_usage, "f").failFn(f); + return this; + } + getAliases() { + return this.parsed ? this.parsed.aliases : {}; + } + async getCompletion(args, done) { + argsert(' [function]', [args, done], arguments.length); + if (!done) { + return new Promise((resolve, reject) => { + __classPrivateFieldGet(this, _YargsInstance_completion, "f").getCompletion(args, (err, completions) => { + if (err) + reject(err); + else + resolve(completions); + }); + }); + } + else { + return __classPrivateFieldGet(this, _YargsInstance_completion, "f").getCompletion(args, done); + } + } + getDemandedOptions() { + argsert([], 0); + return __classPrivateFieldGet(this, _YargsInstance_options, "f").demandedOptions; + } + getDemandedCommands() { + argsert([], 0); + return __classPrivateFieldGet(this, _YargsInstance_options, "f").demandedCommands; + } + getDeprecatedOptions() { + argsert([], 0); + return __classPrivateFieldGet(this, _YargsInstance_options, "f").deprecatedOptions; + } + getDetectLocale() { + return __classPrivateFieldGet(this, _YargsInstance_detectLocale, "f"); + } + getExitProcess() { + return __classPrivateFieldGet(this, _YargsInstance_exitProcess, "f"); + } + getGroups() { + return Object.assign({}, __classPrivateFieldGet(this, _YargsInstance_groups, "f"), __classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")); + } + getHelp() { + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + if (!__classPrivateFieldGet(this, _YargsInstance_usage, "f").hasCachedHelpMessage()) { + if (!this.parsed) { + const parse = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet(this, _YargsInstance_processArgs, "f"), undefined, undefined, 0, true); + if (isPromise(parse)) { + return parse.then(() => { + return __classPrivateFieldGet(this, _YargsInstance_usage, "f").help(); + }); + } + } + const builderResponse = __classPrivateFieldGet(this, _YargsInstance_command, "f").runDefaultBuilderOn(this); + if (isPromise(builderResponse)) { + return builderResponse.then(() => { + return __classPrivateFieldGet(this, _YargsInstance_usage, "f").help(); + }); + } + } + return Promise.resolve(__classPrivateFieldGet(this, _YargsInstance_usage, "f").help()); + } + getOptions() { + return __classPrivateFieldGet(this, _YargsInstance_options, "f"); + } + getStrict() { + return __classPrivateFieldGet(this, _YargsInstance_strict, "f"); + } + getStrictCommands() { + return __classPrivateFieldGet(this, _YargsInstance_strictCommands, "f"); + } + getStrictOptions() { + return __classPrivateFieldGet(this, _YargsInstance_strictOptions, "f"); + } + global(globals, global) { + argsert(' [boolean]', [globals, global], arguments.length); + globals = [].concat(globals); + if (global !== false) { + __classPrivateFieldGet(this, _YargsInstance_options, "f").local = __classPrivateFieldGet(this, _YargsInstance_options, "f").local.filter(l => globals.indexOf(l) === -1); + } + else { + globals.forEach(g => { + if (!__classPrivateFieldGet(this, _YargsInstance_options, "f").local.includes(g)) + __classPrivateFieldGet(this, _YargsInstance_options, "f").local.push(g); + }); + } + return this; + } + group(opts, groupName) { + argsert(' ', [opts, groupName], arguments.length); + const existing = __classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")[groupName] || __classPrivateFieldGet(this, _YargsInstance_groups, "f")[groupName]; + if (__classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")[groupName]) { + delete __classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")[groupName]; + } + const seen = {}; + __classPrivateFieldGet(this, _YargsInstance_groups, "f")[groupName] = (existing || []).concat(opts).filter(key => { + if (seen[key]) + return false; + return (seen[key] = true); + }); + return this; + } + hide(key) { + argsert('', [key], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_options, "f").hiddenOptions.push(key); + return this; + } + implies(key, value) { + argsert(' [number|string|array]', [key, value], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").implies(key, value); + return this; + } + locale(locale) { + argsert('[string]', [locale], arguments.length); + if (locale === undefined) { + this[kGuessLocale](); + return __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.getLocale(); + } + __classPrivateFieldSet(this, _YargsInstance_detectLocale, false, "f"); + __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.setLocale(locale); + return this; + } + middleware(callback, applyBeforeValidation, global) { + return __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").addMiddleware(callback, !!applyBeforeValidation, global); + } + nargs(key, value) { + argsert(' [number]', [key, value], arguments.length); + this[kPopulateParserHintSingleValueDictionary](this.nargs.bind(this), 'narg', key, value); + return this; + } + normalize(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('normalize', keys); + return this; + } + number(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('number', keys); + this[kTrackManuallySetKeys](keys); + return this; + } + option(key, opt) { + argsert(' [object]', [key, opt], arguments.length); + if (typeof key === 'object') { + Object.keys(key).forEach(k => { + this.options(k, key[k]); + }); + } + else { + if (typeof opt !== 'object') { + opt = {}; + } + this[kTrackManuallySetKeys](key); + if (__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f") && (key === 'version' || (opt === null || opt === void 0 ? void 0 : opt.alias) === 'version')) { + this[kEmitWarning]([ + '"version" is a reserved word.', + 'Please do one of the following:', + '- Disable version with `yargs.version(false)` if using "version" as an option', + '- Use the built-in `yargs.version` method instead (if applicable)', + '- Use a different option key', + 'https://yargs.js.org/docs/#api-reference-version', + ].join('\n'), undefined, 'versionWarning'); + } + __classPrivateFieldGet(this, _YargsInstance_options, "f").key[key] = true; + if (opt.alias) + this.alias(key, opt.alias); + const deprecate = opt.deprecate || opt.deprecated; + if (deprecate) { + this.deprecateOption(key, deprecate); + } + const demand = opt.demand || opt.required || opt.require; + if (demand) { + this.demand(key, demand); + } + if (opt.demandOption) { + this.demandOption(key, typeof opt.demandOption === 'string' ? opt.demandOption : undefined); + } + if (opt.conflicts) { + this.conflicts(key, opt.conflicts); + } + if ('default' in opt) { + this.default(key, opt.default); + } + if (opt.implies !== undefined) { + this.implies(key, opt.implies); + } + if (opt.nargs !== undefined) { + this.nargs(key, opt.nargs); + } + if (opt.config) { + this.config(key, opt.configParser); + } + if (opt.normalize) { + this.normalize(key); + } + if (opt.choices) { + this.choices(key, opt.choices); + } + if (opt.coerce) { + this.coerce(key, opt.coerce); + } + if (opt.group) { + this.group(key, opt.group); + } + if (opt.boolean || opt.type === 'boolean') { + this.boolean(key); + if (opt.alias) + this.boolean(opt.alias); + } + if (opt.array || opt.type === 'array') { + this.array(key); + if (opt.alias) + this.array(opt.alias); + } + if (opt.number || opt.type === 'number') { + this.number(key); + if (opt.alias) + this.number(opt.alias); + } + if (opt.string || opt.type === 'string') { + this.string(key); + if (opt.alias) + this.string(opt.alias); + } + if (opt.count || opt.type === 'count') { + this.count(key); + } + if (typeof opt.global === 'boolean') { + this.global(key, opt.global); + } + if (opt.defaultDescription) { + __classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key] = opt.defaultDescription; + } + if (opt.skipValidation) { + this.skipValidation(key); + } + const desc = opt.describe || opt.description || opt.desc; + const descriptions = __classPrivateFieldGet(this, _YargsInstance_usage, "f").getDescriptions(); + if (!Object.prototype.hasOwnProperty.call(descriptions, key) || + typeof desc === 'string') { + this.describe(key, desc); + } + if (opt.hidden) { + this.hide(key); + } + if (opt.requiresArg) { + this.requiresArg(key); + } + } + return this; + } + options(key, opt) { + return this.option(key, opt); + } + parse(args, shortCircuit, _parseFn) { + argsert('[string|array] [function|boolean|object] [function]', [args, shortCircuit, _parseFn], arguments.length); + this[kFreeze](); + if (typeof args === 'undefined') { + args = __classPrivateFieldGet(this, _YargsInstance_processArgs, "f"); + } + if (typeof shortCircuit === 'object') { + __classPrivateFieldSet(this, _YargsInstance_parseContext, shortCircuit, "f"); + shortCircuit = _parseFn; + } + if (typeof shortCircuit === 'function') { + __classPrivateFieldSet(this, _YargsInstance_parseFn, shortCircuit, "f"); + shortCircuit = false; + } + if (!shortCircuit) + __classPrivateFieldSet(this, _YargsInstance_processArgs, args, "f"); + if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) + __classPrivateFieldSet(this, _YargsInstance_exitProcess, false, "f"); + const parsed = this[kRunYargsParserAndExecuteCommands](args, !!shortCircuit); + const tmpParsed = this.parsed; + __classPrivateFieldGet(this, _YargsInstance_completion, "f").setParsed(this.parsed); + if (isPromise(parsed)) { + return parsed + .then(argv => { + if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) + __classPrivateFieldGet(this, _YargsInstance_parseFn, "f").call(this, __classPrivateFieldGet(this, _YargsInstance_exitError, "f"), argv, __classPrivateFieldGet(this, _YargsInstance_output, "f")); + return argv; + }) + .catch(err => { + if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) { + __classPrivateFieldGet(this, _YargsInstance_parseFn, "f")(err, this.parsed.argv, __classPrivateFieldGet(this, _YargsInstance_output, "f")); + } + throw err; + }) + .finally(() => { + this[kUnfreeze](); + this.parsed = tmpParsed; + }); + } + else { + if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) + __classPrivateFieldGet(this, _YargsInstance_parseFn, "f").call(this, __classPrivateFieldGet(this, _YargsInstance_exitError, "f"), parsed, __classPrivateFieldGet(this, _YargsInstance_output, "f")); + this[kUnfreeze](); + this.parsed = tmpParsed; + } + return parsed; + } + parseAsync(args, shortCircuit, _parseFn) { + const maybePromise = this.parse(args, shortCircuit, _parseFn); + return !isPromise(maybePromise) + ? Promise.resolve(maybePromise) + : maybePromise; + } + parseSync(args, shortCircuit, _parseFn) { + const maybePromise = this.parse(args, shortCircuit, _parseFn); + if (isPromise(maybePromise)) { + throw new YError('.parseSync() must not be used with asynchronous builders, handlers, or middleware'); + } + return maybePromise; + } + parserConfiguration(config) { + argsert('', [config], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_parserConfig, config, "f"); + return this; + } + pkgConf(key, rootPath) { + argsert(' [string]', [key, rootPath], arguments.length); + let conf = null; + const obj = this[kPkgUp](rootPath || __classPrivateFieldGet(this, _YargsInstance_cwd, "f")); + if (obj[key] && typeof obj[key] === 'object') { + conf = applyExtends(obj[key], rootPath || __classPrivateFieldGet(this, _YargsInstance_cwd, "f"), this[kGetParserConfiguration]()['deep-merge-config'] || false, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects = (__classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects || []).concat(conf); + } + return this; + } + positional(key, opts) { + argsert(' ', [key, opts], arguments.length); + const supportedOpts = [ + 'default', + 'defaultDescription', + 'implies', + 'normalize', + 'choices', + 'conflicts', + 'coerce', + 'type', + 'describe', + 'desc', + 'description', + 'alias', + ]; + opts = objFilter(opts, (k, v) => { + if (k === 'type' && !['string', 'number', 'boolean'].includes(v)) + return false; + return supportedOpts.includes(k); + }); + const fullCommand = __classPrivateFieldGet(this, _YargsInstance_context, "f").fullCommands[__classPrivateFieldGet(this, _YargsInstance_context, "f").fullCommands.length - 1]; + const parseOptions = fullCommand + ? __classPrivateFieldGet(this, _YargsInstance_command, "f").cmdToParseOptions(fullCommand) + : { + array: [], + alias: {}, + default: {}, + demand: {}, + }; + objectKeys(parseOptions).forEach(pk => { + const parseOption = parseOptions[pk]; + if (Array.isArray(parseOption)) { + if (parseOption.indexOf(key) !== -1) + opts[pk] = true; + } + else { + if (parseOption[key] && !(pk in opts)) + opts[pk] = parseOption[key]; + } + }); + this.group(key, __classPrivateFieldGet(this, _YargsInstance_usage, "f").getPositionalGroupName()); + return this.option(key, opts); + } + recommendCommands(recommend = true) { + argsert('[boolean]', [recommend], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_recommendCommands, recommend, "f"); + return this; + } + required(keys, max, msg) { + return this.demand(keys, max, msg); + } + require(keys, max, msg) { + return this.demand(keys, max, msg); + } + requiresArg(keys) { + argsert(' [number]', [keys], arguments.length); + if (typeof keys === 'string' && __classPrivateFieldGet(this, _YargsInstance_options, "f").narg[keys]) { + return this; + } + else { + this[kPopulateParserHintSingleValueDictionary](this.requiresArg.bind(this), 'narg', keys, NaN); + } + return this; + } + showCompletionScript($0, cmd) { + argsert('[string] [string]', [$0, cmd], arguments.length); + $0 = $0 || this.$0; + __classPrivateFieldGet(this, _YargsInstance_logger, "f").log(__classPrivateFieldGet(this, _YargsInstance_completion, "f").generateCompletionScript($0, cmd || __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f") || 'completion')); + return this; + } + showHelp(level) { + argsert('[string|function]', [level], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + if (!__classPrivateFieldGet(this, _YargsInstance_usage, "f").hasCachedHelpMessage()) { + if (!this.parsed) { + const parse = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet(this, _YargsInstance_processArgs, "f"), undefined, undefined, 0, true); + if (isPromise(parse)) { + parse.then(() => { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelp(level); + }); + return this; + } + } + const builderResponse = __classPrivateFieldGet(this, _YargsInstance_command, "f").runDefaultBuilderOn(this); + if (isPromise(builderResponse)) { + builderResponse.then(() => { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelp(level); + }); + return this; + } + } + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelp(level); + return this; + } + scriptName(scriptName) { + this.customScriptName = true; + this.$0 = scriptName; + return this; + } + showHelpOnFail(enabled, message) { + argsert('[boolean|string] [string]', [enabled, message], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelpOnFail(enabled, message); + return this; + } + showVersion(level) { + argsert('[string|function]', [level], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showVersion(level); + return this; + } + skipValidation(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('skipValidation', keys); + return this; + } + strict(enabled) { + argsert('[boolean]', [enabled], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_strict, enabled !== false, "f"); + return this; + } + strictCommands(enabled) { + argsert('[boolean]', [enabled], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_strictCommands, enabled !== false, "f"); + return this; + } + strictOptions(enabled) { + argsert('[boolean]', [enabled], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_strictOptions, enabled !== false, "f"); + return this; + } + string(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('string', keys); + this[kTrackManuallySetKeys](keys); + return this; + } + terminalWidth() { + argsert([], 0); + return __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.stdColumns; + } + updateLocale(obj) { + return this.updateStrings(obj); + } + updateStrings(obj) { + argsert('', [obj], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_detectLocale, false, "f"); + __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.updateLocale(obj); + return this; + } + usage(msg, description, builder, handler) { + argsert(' [string|boolean] [function|object] [function]', [msg, description, builder, handler], arguments.length); + if (description !== undefined) { + assertNotStrictEqual(msg, null, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + if ((msg || '').match(/^\$0( |$)/)) { + return this.command(msg, description, builder, handler); + } + else { + throw new YError('.usage() description must start with $0 if being used as alias for .command()'); + } + } + else { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").usage(msg); + return this; + } + } + usageConfiguration(config) { + argsert('', [config], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_usageConfig, config, "f"); + return this; + } + version(opt, msg, ver) { + const defaultVersionOpt = 'version'; + argsert('[boolean|string] [string] [string]', [opt, msg, ver], arguments.length); + if (__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f")) { + this[kDeleteFromParserHintObject](__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f")); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").version(undefined); + __classPrivateFieldSet(this, _YargsInstance_versionOpt, null, "f"); + } + if (arguments.length === 0) { + ver = this[kGuessVersion](); + opt = defaultVersionOpt; + } + else if (arguments.length === 1) { + if (opt === false) { + return this; + } + ver = opt; + opt = defaultVersionOpt; + } + else if (arguments.length === 2) { + ver = msg; + msg = undefined; + } + __classPrivateFieldSet(this, _YargsInstance_versionOpt, typeof opt === 'string' ? opt : defaultVersionOpt, "f"); + msg = msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Show version number'); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").version(ver || undefined); + this.boolean(__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f")); + this.describe(__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f"), msg); + return this; + } + wrap(cols) { + argsert('', [cols], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").wrap(cols); + return this; + } + [(_YargsInstance_command = new WeakMap(), _YargsInstance_cwd = new WeakMap(), _YargsInstance_context = new WeakMap(), _YargsInstance_completion = new WeakMap(), _YargsInstance_completionCommand = new WeakMap(), _YargsInstance_defaultShowHiddenOpt = new WeakMap(), _YargsInstance_exitError = new WeakMap(), _YargsInstance_detectLocale = new WeakMap(), _YargsInstance_emittedWarnings = new WeakMap(), _YargsInstance_exitProcess = new WeakMap(), _YargsInstance_frozens = new WeakMap(), _YargsInstance_globalMiddleware = new WeakMap(), _YargsInstance_groups = new WeakMap(), _YargsInstance_hasOutput = new WeakMap(), _YargsInstance_helpOpt = new WeakMap(), _YargsInstance_isGlobalContext = new WeakMap(), _YargsInstance_logger = new WeakMap(), _YargsInstance_output = new WeakMap(), _YargsInstance_options = new WeakMap(), _YargsInstance_parentRequire = new WeakMap(), _YargsInstance_parserConfig = new WeakMap(), _YargsInstance_parseFn = new WeakMap(), _YargsInstance_parseContext = new WeakMap(), _YargsInstance_pkgs = new WeakMap(), _YargsInstance_preservedGroups = new WeakMap(), _YargsInstance_processArgs = new WeakMap(), _YargsInstance_recommendCommands = new WeakMap(), _YargsInstance_shim = new WeakMap(), _YargsInstance_strict = new WeakMap(), _YargsInstance_strictCommands = new WeakMap(), _YargsInstance_strictOptions = new WeakMap(), _YargsInstance_usage = new WeakMap(), _YargsInstance_usageConfig = new WeakMap(), _YargsInstance_versionOpt = new WeakMap(), _YargsInstance_validation = new WeakMap(), kCopyDoubleDash)](argv) { + if (!argv._ || !argv['--']) + return argv; + argv._.push.apply(argv._, argv['--']); + try { + delete argv['--']; + } + catch (_err) { } + return argv; + } + [kCreateLogger]() { + return { + log: (...args) => { + if (!this[kHasParseCallback]()) + console.log(...args); + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + if (__classPrivateFieldGet(this, _YargsInstance_output, "f").length) + __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + '\n', "f"); + __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + args.join(' '), "f"); + }, + error: (...args) => { + if (!this[kHasParseCallback]()) + console.error(...args); + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + if (__classPrivateFieldGet(this, _YargsInstance_output, "f").length) + __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + '\n', "f"); + __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + args.join(' '), "f"); + }, + }; + } + [kDeleteFromParserHintObject](optionKey) { + objectKeys(__classPrivateFieldGet(this, _YargsInstance_options, "f")).forEach((hintKey) => { + if (((key) => key === 'configObjects')(hintKey)) + return; + const hint = __classPrivateFieldGet(this, _YargsInstance_options, "f")[hintKey]; + if (Array.isArray(hint)) { + if (hint.includes(optionKey)) + hint.splice(hint.indexOf(optionKey), 1); + } + else if (typeof hint === 'object') { + delete hint[optionKey]; + } + }); + delete __classPrivateFieldGet(this, _YargsInstance_usage, "f").getDescriptions()[optionKey]; + } + [kEmitWarning](warning, type, deduplicationId) { + if (!__classPrivateFieldGet(this, _YargsInstance_emittedWarnings, "f")[deduplicationId]) { + __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.emitWarning(warning, type); + __classPrivateFieldGet(this, _YargsInstance_emittedWarnings, "f")[deduplicationId] = true; + } + } + [kFreeze]() { + __classPrivateFieldGet(this, _YargsInstance_frozens, "f").push({ + options: __classPrivateFieldGet(this, _YargsInstance_options, "f"), + configObjects: __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects.slice(0), + exitProcess: __classPrivateFieldGet(this, _YargsInstance_exitProcess, "f"), + groups: __classPrivateFieldGet(this, _YargsInstance_groups, "f"), + strict: __classPrivateFieldGet(this, _YargsInstance_strict, "f"), + strictCommands: __classPrivateFieldGet(this, _YargsInstance_strictCommands, "f"), + strictOptions: __classPrivateFieldGet(this, _YargsInstance_strictOptions, "f"), + completionCommand: __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f"), + output: __classPrivateFieldGet(this, _YargsInstance_output, "f"), + exitError: __classPrivateFieldGet(this, _YargsInstance_exitError, "f"), + hasOutput: __classPrivateFieldGet(this, _YargsInstance_hasOutput, "f"), + parsed: this.parsed, + parseFn: __classPrivateFieldGet(this, _YargsInstance_parseFn, "f"), + parseContext: __classPrivateFieldGet(this, _YargsInstance_parseContext, "f"), + }); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").freeze(); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").freeze(); + __classPrivateFieldGet(this, _YargsInstance_command, "f").freeze(); + __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").freeze(); + } + [kGetDollarZero]() { + let $0 = ''; + let default$0; + if (/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet(this, _YargsInstance_shim, "f").process.argv()[0])) { + default$0 = __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.argv().slice(1, 2); + } + else { + default$0 = __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.argv().slice(0, 1); + } + $0 = default$0 + .map(x => { + const b = this[kRebase](__classPrivateFieldGet(this, _YargsInstance_cwd, "f"), x); + return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x; + }) + .join(' ') + .trim(); + if (__classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('_') && + __classPrivateFieldGet(this, _YargsInstance_shim, "f").getProcessArgvBin() === __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('_')) { + $0 = __classPrivateFieldGet(this, _YargsInstance_shim, "f") + .getEnv('_') + .replace(`${__classPrivateFieldGet(this, _YargsInstance_shim, "f").path.dirname(__classPrivateFieldGet(this, _YargsInstance_shim, "f").process.execPath())}/`, ''); + } + return $0; + } + [kGetParserConfiguration]() { + return __classPrivateFieldGet(this, _YargsInstance_parserConfig, "f"); + } + [kGetUsageConfiguration]() { + return __classPrivateFieldGet(this, _YargsInstance_usageConfig, "f"); + } + [kGuessLocale]() { + if (!__classPrivateFieldGet(this, _YargsInstance_detectLocale, "f")) + return; + const locale = __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LC_ALL') || + __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LC_MESSAGES') || + __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LANG') || + __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LANGUAGE') || + 'en_US'; + this.locale(locale.replace(/[.:].*/, '')); + } + [kGuessVersion]() { + const obj = this[kPkgUp](); + return obj.version || 'unknown'; + } + [kParsePositionalNumbers](argv) { + const args = argv['--'] ? argv['--'] : argv._; + for (let i = 0, arg; (arg = args[i]) !== undefined; i++) { + if (__classPrivateFieldGet(this, _YargsInstance_shim, "f").Parser.looksLikeNumber(arg) && + Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))) { + args[i] = Number(arg); + } + } + return argv; + } + [kPkgUp](rootPath) { + const npath = rootPath || '*'; + if (__classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath]) + return __classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath]; + let obj = {}; + try { + let startDir = rootPath || __classPrivateFieldGet(this, _YargsInstance_shim, "f").mainFilename; + if (__classPrivateFieldGet(this, _YargsInstance_shim, "f").path.extname(startDir)) { + startDir = __classPrivateFieldGet(this, _YargsInstance_shim, "f").path.dirname(startDir); + } + const pkgJsonPath = __classPrivateFieldGet(this, _YargsInstance_shim, "f").findUp(startDir, (dir, names) => { + if (names.includes('package.json')) { + return 'package.json'; + } + else { + return undefined; + } + }); + assertNotStrictEqual(pkgJsonPath, undefined, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + obj = JSON.parse(__classPrivateFieldGet(this, _YargsInstance_shim, "f").readFileSync(pkgJsonPath, 'utf8')); + } + catch (_noop) { } + __classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath] = obj || {}; + return __classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath]; + } + [kPopulateParserHintArray](type, keys) { + keys = [].concat(keys); + keys.forEach(key => { + key = this[kSanitizeKey](key); + __classPrivateFieldGet(this, _YargsInstance_options, "f")[type].push(key); + }); + } + [kPopulateParserHintSingleValueDictionary](builder, type, key, value) { + this[kPopulateParserHintDictionary](builder, type, key, value, (type, key, value) => { + __classPrivateFieldGet(this, _YargsInstance_options, "f")[type][key] = value; + }); + } + [kPopulateParserHintArrayDictionary](builder, type, key, value) { + this[kPopulateParserHintDictionary](builder, type, key, value, (type, key, value) => { + __classPrivateFieldGet(this, _YargsInstance_options, "f")[type][key] = (__classPrivateFieldGet(this, _YargsInstance_options, "f")[type][key] || []).concat(value); + }); + } + [kPopulateParserHintDictionary](builder, type, key, value, singleKeyHandler) { + if (Array.isArray(key)) { + key.forEach(k => { + builder(k, value); + }); + } + else if (((key) => typeof key === 'object')(key)) { + for (const k of objectKeys(key)) { + builder(k, key[k]); + } + } + else { + singleKeyHandler(type, this[kSanitizeKey](key), value); + } + } + [kSanitizeKey](key) { + if (key === '__proto__') + return '___proto___'; + return key; + } + [kSetKey](key, set) { + this[kPopulateParserHintSingleValueDictionary](this[kSetKey].bind(this), 'key', key, set); + return this; + } + [kUnfreeze]() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; + const frozen = __classPrivateFieldGet(this, _YargsInstance_frozens, "f").pop(); + assertNotStrictEqual(frozen, undefined, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + let configObjects; + (_a = this, _b = this, _c = this, _d = this, _e = this, _f = this, _g = this, _h = this, _j = this, _k = this, _l = this, _m = this, { + options: ({ set value(_o) { __classPrivateFieldSet(_a, _YargsInstance_options, _o, "f"); } }).value, + configObjects, + exitProcess: ({ set value(_o) { __classPrivateFieldSet(_b, _YargsInstance_exitProcess, _o, "f"); } }).value, + groups: ({ set value(_o) { __classPrivateFieldSet(_c, _YargsInstance_groups, _o, "f"); } }).value, + output: ({ set value(_o) { __classPrivateFieldSet(_d, _YargsInstance_output, _o, "f"); } }).value, + exitError: ({ set value(_o) { __classPrivateFieldSet(_e, _YargsInstance_exitError, _o, "f"); } }).value, + hasOutput: ({ set value(_o) { __classPrivateFieldSet(_f, _YargsInstance_hasOutput, _o, "f"); } }).value, + parsed: this.parsed, + strict: ({ set value(_o) { __classPrivateFieldSet(_g, _YargsInstance_strict, _o, "f"); } }).value, + strictCommands: ({ set value(_o) { __classPrivateFieldSet(_h, _YargsInstance_strictCommands, _o, "f"); } }).value, + strictOptions: ({ set value(_o) { __classPrivateFieldSet(_j, _YargsInstance_strictOptions, _o, "f"); } }).value, + completionCommand: ({ set value(_o) { __classPrivateFieldSet(_k, _YargsInstance_completionCommand, _o, "f"); } }).value, + parseFn: ({ set value(_o) { __classPrivateFieldSet(_l, _YargsInstance_parseFn, _o, "f"); } }).value, + parseContext: ({ set value(_o) { __classPrivateFieldSet(_m, _YargsInstance_parseContext, _o, "f"); } }).value, + } = frozen); + __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects = configObjects; + __classPrivateFieldGet(this, _YargsInstance_usage, "f").unfreeze(); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").unfreeze(); + __classPrivateFieldGet(this, _YargsInstance_command, "f").unfreeze(); + __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").unfreeze(); + } + [kValidateAsync](validation, argv) { + return maybeAsyncResult(argv, result => { + validation(result); + return result; + }); + } + getInternalMethods() { + return { + getCommandInstance: this[kGetCommandInstance].bind(this), + getContext: this[kGetContext].bind(this), + getHasOutput: this[kGetHasOutput].bind(this), + getLoggerInstance: this[kGetLoggerInstance].bind(this), + getParseContext: this[kGetParseContext].bind(this), + getParserConfiguration: this[kGetParserConfiguration].bind(this), + getUsageConfiguration: this[kGetUsageConfiguration].bind(this), + getUsageInstance: this[kGetUsageInstance].bind(this), + getValidationInstance: this[kGetValidationInstance].bind(this), + hasParseCallback: this[kHasParseCallback].bind(this), + isGlobalContext: this[kIsGlobalContext].bind(this), + postProcess: this[kPostProcess].bind(this), + reset: this[kReset].bind(this), + runValidation: this[kRunValidation].bind(this), + runYargsParserAndExecuteCommands: this[kRunYargsParserAndExecuteCommands].bind(this), + setHasOutput: this[kSetHasOutput].bind(this), + }; + } + [kGetCommandInstance]() { + return __classPrivateFieldGet(this, _YargsInstance_command, "f"); + } + [kGetContext]() { + return __classPrivateFieldGet(this, _YargsInstance_context, "f"); + } + [kGetHasOutput]() { + return __classPrivateFieldGet(this, _YargsInstance_hasOutput, "f"); + } + [kGetLoggerInstance]() { + return __classPrivateFieldGet(this, _YargsInstance_logger, "f"); + } + [kGetParseContext]() { + return __classPrivateFieldGet(this, _YargsInstance_parseContext, "f") || {}; + } + [kGetUsageInstance]() { + return __classPrivateFieldGet(this, _YargsInstance_usage, "f"); + } + [kGetValidationInstance]() { + return __classPrivateFieldGet(this, _YargsInstance_validation, "f"); + } + [kHasParseCallback]() { + return !!__classPrivateFieldGet(this, _YargsInstance_parseFn, "f"); + } + [kIsGlobalContext]() { + return __classPrivateFieldGet(this, _YargsInstance_isGlobalContext, "f"); + } + [kPostProcess](argv, populateDoubleDash, calledFromCommand, runGlobalMiddleware) { + if (calledFromCommand) + return argv; + if (isPromise(argv)) + return argv; + if (!populateDoubleDash) { + argv = this[kCopyDoubleDash](argv); + } + const parsePositionalNumbers = this[kGetParserConfiguration]()['parse-positional-numbers'] || + this[kGetParserConfiguration]()['parse-positional-numbers'] === undefined; + if (parsePositionalNumbers) { + argv = this[kParsePositionalNumbers](argv); + } + if (runGlobalMiddleware) { + argv = applyMiddleware(argv, this, __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), false); + } + return argv; + } + [kReset](aliases = {}) { + __classPrivateFieldSet(this, _YargsInstance_options, __classPrivateFieldGet(this, _YargsInstance_options, "f") || {}, "f"); + const tmpOptions = {}; + tmpOptions.local = __classPrivateFieldGet(this, _YargsInstance_options, "f").local || []; + tmpOptions.configObjects = __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects || []; + const localLookup = {}; + tmpOptions.local.forEach(l => { + localLookup[l] = true; + (aliases[l] || []).forEach(a => { + localLookup[a] = true; + }); + }); + Object.assign(__classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f"), Object.keys(__classPrivateFieldGet(this, _YargsInstance_groups, "f")).reduce((acc, groupName) => { + const keys = __classPrivateFieldGet(this, _YargsInstance_groups, "f")[groupName].filter(key => !(key in localLookup)); + if (keys.length > 0) { + acc[groupName] = keys; + } + return acc; + }, {})); + __classPrivateFieldSet(this, _YargsInstance_groups, {}, "f"); + const arrayOptions = [ + 'array', + 'boolean', + 'string', + 'skipValidation', + 'count', + 'normalize', + 'number', + 'hiddenOptions', + ]; + const objectOptions = [ + 'narg', + 'key', + 'alias', + 'default', + 'defaultDescription', + 'config', + 'choices', + 'demandedOptions', + 'demandedCommands', + 'deprecatedOptions', + ]; + arrayOptions.forEach(k => { + tmpOptions[k] = (__classPrivateFieldGet(this, _YargsInstance_options, "f")[k] || []).filter((k) => !localLookup[k]); + }); + objectOptions.forEach((k) => { + tmpOptions[k] = objFilter(__classPrivateFieldGet(this, _YargsInstance_options, "f")[k], k => !localLookup[k]); + }); + tmpOptions.envPrefix = __classPrivateFieldGet(this, _YargsInstance_options, "f").envPrefix; + __classPrivateFieldSet(this, _YargsInstance_options, tmpOptions, "f"); + __classPrivateFieldSet(this, _YargsInstance_usage, __classPrivateFieldGet(this, _YargsInstance_usage, "f") + ? __classPrivateFieldGet(this, _YargsInstance_usage, "f").reset(localLookup) + : Usage(this, __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f"); + __classPrivateFieldSet(this, _YargsInstance_validation, __classPrivateFieldGet(this, _YargsInstance_validation, "f") + ? __classPrivateFieldGet(this, _YargsInstance_validation, "f").reset(localLookup) + : Validation(this, __classPrivateFieldGet(this, _YargsInstance_usage, "f"), __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f"); + __classPrivateFieldSet(this, _YargsInstance_command, __classPrivateFieldGet(this, _YargsInstance_command, "f") + ? __classPrivateFieldGet(this, _YargsInstance_command, "f").reset() + : Command(__classPrivateFieldGet(this, _YargsInstance_usage, "f"), __classPrivateFieldGet(this, _YargsInstance_validation, "f"), __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f"), __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f"); + if (!__classPrivateFieldGet(this, _YargsInstance_completion, "f")) + __classPrivateFieldSet(this, _YargsInstance_completion, Completion(this, __classPrivateFieldGet(this, _YargsInstance_usage, "f"), __classPrivateFieldGet(this, _YargsInstance_command, "f"), __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f"); + __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").reset(); + __classPrivateFieldSet(this, _YargsInstance_completionCommand, null, "f"); + __classPrivateFieldSet(this, _YargsInstance_output, '', "f"); + __classPrivateFieldSet(this, _YargsInstance_exitError, null, "f"); + __classPrivateFieldSet(this, _YargsInstance_hasOutput, false, "f"); + this.parsed = false; + return this; + } + [kRebase](base, dir) { + return __classPrivateFieldGet(this, _YargsInstance_shim, "f").path.relative(base, dir); + } + [kRunYargsParserAndExecuteCommands](args, shortCircuit, calledFromCommand, commandIndex = 0, helpOnly = false) { + var _a, _b, _c, _d; + let skipValidation = !!calledFromCommand || helpOnly; + args = args || __classPrivateFieldGet(this, _YargsInstance_processArgs, "f"); + __classPrivateFieldGet(this, _YargsInstance_options, "f").__ = __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.__; + __classPrivateFieldGet(this, _YargsInstance_options, "f").configuration = this[kGetParserConfiguration](); + const populateDoubleDash = !!__classPrivateFieldGet(this, _YargsInstance_options, "f").configuration['populate--']; + const config = Object.assign({}, __classPrivateFieldGet(this, _YargsInstance_options, "f").configuration, { + 'populate--': true, + }); + const parsed = __classPrivateFieldGet(this, _YargsInstance_shim, "f").Parser.detailed(args, Object.assign({}, __classPrivateFieldGet(this, _YargsInstance_options, "f"), { + configuration: { 'parse-positional-numbers': false, ...config }, + })); + const argv = Object.assign(parsed.argv, __classPrivateFieldGet(this, _YargsInstance_parseContext, "f")); + let argvPromise = undefined; + const aliases = parsed.aliases; + let helpOptSet = false; + let versionOptSet = false; + Object.keys(argv).forEach(key => { + if (key === __classPrivateFieldGet(this, _YargsInstance_helpOpt, "f") && argv[key]) { + helpOptSet = true; + } + else if (key === __classPrivateFieldGet(this, _YargsInstance_versionOpt, "f") && argv[key]) { + versionOptSet = true; + } + }); + argv.$0 = this.$0; + this.parsed = parsed; + if (commandIndex === 0) { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").clearCachedHelpMessage(); + } + try { + this[kGuessLocale](); + if (shortCircuit) { + return this[kPostProcess](argv, populateDoubleDash, !!calledFromCommand, false); + } + if (__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")) { + const helpCmds = [__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")] + .concat(aliases[__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")] || []) + .filter(k => k.length > 1); + if (helpCmds.includes('' + argv._[argv._.length - 1])) { + argv._.pop(); + helpOptSet = true; + } + } + __classPrivateFieldSet(this, _YargsInstance_isGlobalContext, false, "f"); + const handlerKeys = __classPrivateFieldGet(this, _YargsInstance_command, "f").getCommands(); + const requestCompletions = ((_a = __classPrivateFieldGet(this, _YargsInstance_completion, "f")) === null || _a === void 0 ? void 0 : _a.completionKey) + ? [ + (_b = __classPrivateFieldGet(this, _YargsInstance_completion, "f")) === null || _b === void 0 ? void 0 : _b.completionKey, + ...((_d = this.getAliases()[(_c = __classPrivateFieldGet(this, _YargsInstance_completion, "f")) === null || _c === void 0 ? void 0 : _c.completionKey]) !== null && _d !== void 0 ? _d : []), + ].some((key) => Object.prototype.hasOwnProperty.call(argv, key)) + : false; + const skipRecommendation = helpOptSet || requestCompletions || helpOnly; + if (argv._.length) { + if (handlerKeys.length) { + let firstUnknownCommand; + for (let i = commandIndex || 0, cmd; argv._[i] !== undefined; i++) { + cmd = String(argv._[i]); + if (handlerKeys.includes(cmd) && cmd !== __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f")) { + const innerArgv = __classPrivateFieldGet(this, _YargsInstance_command, "f").runCommand(cmd, this, parsed, i + 1, helpOnly, helpOptSet || versionOptSet || helpOnly); + return this[kPostProcess](innerArgv, populateDoubleDash, !!calledFromCommand, false); + } + else if (!firstUnknownCommand && + cmd !== __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f")) { + firstUnknownCommand = cmd; + break; + } + } + if (!__classPrivateFieldGet(this, _YargsInstance_command, "f").hasDefaultCommand() && + __classPrivateFieldGet(this, _YargsInstance_recommendCommands, "f") && + firstUnknownCommand && + !skipRecommendation) { + __classPrivateFieldGet(this, _YargsInstance_validation, "f").recommendCommands(firstUnknownCommand, handlerKeys); + } + } + if (__classPrivateFieldGet(this, _YargsInstance_completionCommand, "f") && + argv._.includes(__classPrivateFieldGet(this, _YargsInstance_completionCommand, "f")) && + !requestCompletions) { + if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) + setBlocking(true); + this.showCompletionScript(); + this.exit(0); + } + } + if (__classPrivateFieldGet(this, _YargsInstance_command, "f").hasDefaultCommand() && !skipRecommendation) { + const innerArgv = __classPrivateFieldGet(this, _YargsInstance_command, "f").runCommand(null, this, parsed, 0, helpOnly, helpOptSet || versionOptSet || helpOnly); + return this[kPostProcess](innerArgv, populateDoubleDash, !!calledFromCommand, false); + } + if (requestCompletions) { + if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) + setBlocking(true); + args = [].concat(args); + const completionArgs = args.slice(args.indexOf(`--${__classPrivateFieldGet(this, _YargsInstance_completion, "f").completionKey}`) + 1); + __classPrivateFieldGet(this, _YargsInstance_completion, "f").getCompletion(completionArgs, (err, completions) => { + if (err) + throw new YError(err.message); + (completions || []).forEach(completion => { + __classPrivateFieldGet(this, _YargsInstance_logger, "f").log(completion); + }); + this.exit(0); + }); + return this[kPostProcess](argv, !populateDoubleDash, !!calledFromCommand, false); + } + if (!__classPrivateFieldGet(this, _YargsInstance_hasOutput, "f")) { + if (helpOptSet) { + if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) + setBlocking(true); + skipValidation = true; + this.showHelp(message => { + __classPrivateFieldGet(this, _YargsInstance_logger, "f").log(message); + this.exit(0); + }); + } + else if (versionOptSet) { + if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) + setBlocking(true); + skipValidation = true; + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showVersion('log'); + this.exit(0); + } + } + if (!skipValidation && __classPrivateFieldGet(this, _YargsInstance_options, "f").skipValidation.length > 0) { + skipValidation = Object.keys(argv).some(key => __classPrivateFieldGet(this, _YargsInstance_options, "f").skipValidation.indexOf(key) >= 0 && argv[key] === true); + } + if (!skipValidation) { + if (parsed.error) + throw new YError(parsed.error.message); + if (!requestCompletions) { + const validation = this[kRunValidation](aliases, {}, parsed.error); + if (!calledFromCommand) { + argvPromise = applyMiddleware(argv, this, __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), true); + } + argvPromise = this[kValidateAsync](validation, argvPromise !== null && argvPromise !== void 0 ? argvPromise : argv); + if (isPromise(argvPromise) && !calledFromCommand) { + argvPromise = argvPromise.then(() => { + return applyMiddleware(argv, this, __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), false); + }); + } + } + } + } + catch (err) { + if (err instanceof YError) + __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(err.message, err); + else + throw err; + } + return this[kPostProcess](argvPromise !== null && argvPromise !== void 0 ? argvPromise : argv, populateDoubleDash, !!calledFromCommand, true); + } + [kRunValidation](aliases, positionalMap, parseErrors, isDefaultCommand) { + const demandedOptions = { ...this.getDemandedOptions() }; + return (argv) => { + if (parseErrors) + throw new YError(parseErrors.message); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").nonOptionCount(argv); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").requiredArguments(argv, demandedOptions); + let failedStrictCommands = false; + if (__classPrivateFieldGet(this, _YargsInstance_strictCommands, "f")) { + failedStrictCommands = __classPrivateFieldGet(this, _YargsInstance_validation, "f").unknownCommands(argv); + } + if (__classPrivateFieldGet(this, _YargsInstance_strict, "f") && !failedStrictCommands) { + __classPrivateFieldGet(this, _YargsInstance_validation, "f").unknownArguments(argv, aliases, positionalMap, !!isDefaultCommand); + } + else if (__classPrivateFieldGet(this, _YargsInstance_strictOptions, "f")) { + __classPrivateFieldGet(this, _YargsInstance_validation, "f").unknownArguments(argv, aliases, {}, false, false); + } + __classPrivateFieldGet(this, _YargsInstance_validation, "f").limitedChoices(argv); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").implications(argv); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").conflicting(argv); + }; + } + [kSetHasOutput]() { + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + } + [kTrackManuallySetKeys](keys) { + if (typeof keys === 'string') { + __classPrivateFieldGet(this, _YargsInstance_options, "f").key[keys] = true; + } + else { + for (const k of keys) { + __classPrivateFieldGet(this, _YargsInstance_options, "f").key[k] = true; + } + } + } +} +export function isYargsInstance(y) { + return !!y && typeof y.getInternalMethods === 'function'; +} diff --git a/node_modules/yargs/build/lib/yerror.js b/node_modules/yargs/build/lib/yerror.js new file mode 100644 index 0000000000000000000000000000000000000000..7a36684da8dbfb687f8d8dacfd69fbd8e1dab931 --- /dev/null +++ b/node_modules/yargs/build/lib/yerror.js @@ -0,0 +1,9 @@ +export class YError extends Error { + constructor(msg) { + super(msg || 'yargs error'); + this.name = 'YError'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, YError); + } + } +} diff --git a/node_modules/yargs/helpers/helpers.mjs b/node_modules/yargs/helpers/helpers.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3f96b3db80ff7a486abaca3683947a54b659a2e2 --- /dev/null +++ b/node_modules/yargs/helpers/helpers.mjs @@ -0,0 +1,10 @@ +import {applyExtends as _applyExtends} from '../build/lib/utils/apply-extends.js'; +import {hideBin} from '../build/lib/utils/process-argv.js'; +import Parser from 'yargs-parser'; +import shim from '../lib/platform-shims/esm.mjs'; + +const applyExtends = (config, cwd, mergeExtends) => { + return _applyExtends(config, cwd, mergeExtends, shim); +}; + +export {applyExtends, hideBin, Parser}; diff --git a/node_modules/yargs/helpers/package.json b/node_modules/yargs/helpers/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5bbefffbabee392d1855491b84dc0a716b6a3bf2 --- /dev/null +++ b/node_modules/yargs/helpers/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/node_modules/yargs/index.mjs b/node_modules/yargs/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d65a6f446f48bcce71674425d25f31a867fee6e5 --- /dev/null +++ b/node_modules/yargs/index.mjs @@ -0,0 +1,10 @@ +'use strict'; + +// Bootstraps yargs for ESM: +import esmPlatformShim from './lib/platform-shims/esm.mjs'; +import {YargsFactory} from './build/lib/yargs-factory.js'; + +const Yargs = YargsFactory(esmPlatformShim); +export default Yargs; + +export {Yargs as 'module.exports'}; diff --git a/node_modules/yargs/lib/platform-shims/browser.mjs b/node_modules/yargs/lib/platform-shims/browser.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7e6ba57a1f9779ed63834a8269cae10e481a2918 --- /dev/null +++ b/node_modules/yargs/lib/platform-shims/browser.mjs @@ -0,0 +1,99 @@ +/* eslint-disable no-unused-vars */ +'use strict'; + +import cliui from 'https://unpkg.com/cliui@8.0.1/index.mjs'; // eslint-disable-line +import Parser from 'https://unpkg.com/yargs-parser@21.1.1/browser.js'; // eslint-disable-line +import {getProcessArgvBin} from '../../build/lib/utils/process-argv.js'; +import {YError} from '../../build/lib/yerror.js'; + +const REQUIRE_ERROR = 'require is not supported in browser'; +const REQUIRE_DIRECTORY_ERROR = + 'loading a directory of commands is not supported in browser'; + +export default { + assert: { + notStrictEqual: (a, b) => { + // noop. + }, + strictEqual: (a, b) => { + // noop. + }, + }, + cliui, + findUp: () => undefined, + getEnv: key => { + // There is no environment in browser: + return undefined; + }, + inspect: console.log, + getCallerFile: () => { + throw new YError(REQUIRE_DIRECTORY_ERROR); + }, + getProcessArgvBin, + mainFilename: 'yargs', + Parser, + path: { + basename: str => str, + dirname: str => str, + extname: str => str, + relative: str => str, + join: (str, _str2) => str, + }, + process: { + argv: () => [], + cwd: () => '', + emitWarning: (warning, name) => {}, + execPath: () => '', + // exit is noop browser: + exit: () => {}, + nextTick: cb => { + // eslint-disable-next-line no-undef + window.setTimeout(cb, 1); + }, + stdColumns: 80, + }, + readFileSync: () => { + return ''; + }, + readdirSync: () => { + return []; + }, + require: () => { + throw new YError(REQUIRE_ERROR); + }, + requireDirectory: () => { + throw new YError(REQUIRE_DIRECTORY_ERROR); + }, + stringWidth: str => { + return [...str].length; + }, + // TODO: replace this with y18n once it's ported to ESM: + y18n: { + __: (...str) => { + if (str.length === 0) return ''; + const args = str.slice(1); + return sprintf(str[0], ...args); + }, + __n: (str1, str2, count, ...args) => { + if (count === 1) { + return sprintf(str1, ...args); + } else { + return sprintf(str2, ...args); + } + }, + getLocale: () => { + return 'en_US'; + }, + setLocale: () => {}, + updateLocale: () => {}, + }, +}; + +function sprintf(_str, ...args) { + let str = ''; + const split = _str.split('%s'); + split.forEach((token, i) => { + str += `${token}${split[i + 1] !== undefined && args[i] ? args[i] : ''}`; + }); + return str; +} diff --git a/node_modules/yargs/lib/platform-shims/esm.mjs b/node_modules/yargs/lib/platform-shims/esm.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1b8efe80e26109b4688b76ea662a23ee39b2af4e --- /dev/null +++ b/node_modules/yargs/lib/platform-shims/esm.mjs @@ -0,0 +1,67 @@ +'use strict' + +import { notStrictEqual, strictEqual } from 'assert' +import cliui from 'cliui' +import escalade from 'escalade/sync' +import { inspect } from 'util' +import { fileURLToPath } from 'url'; +import Parser from 'yargs-parser' +import { basename, dirname, extname, relative, resolve, join } from 'path' +import { getProcessArgvBin } from '../../build/lib/utils/process-argv.js' +import stringWidth from 'string-width'; +import y18n from 'y18n' +import { createRequire } from 'node:module'; +import getCallerFile from 'get-caller-file'; +import { readFileSync, readdirSync } from 'node:fs' + +const __dirname = fileURLToPath(import.meta.url); +const mainFilename = __dirname.substring(0, __dirname.lastIndexOf('node_modules')); +const require = createRequire(import.meta.url); + +export default { + assert: { + notStrictEqual, + strictEqual + }, + cliui, + findUp: escalade, + getEnv: (key) => { + return process.env[key] + }, + inspect, + getProcessArgvBin, + mainFilename: mainFilename || process.cwd(), + Parser, + path: { + basename, + dirname, + extname, + relative, + resolve, + join + }, + process: { + argv: () => process.argv, + cwd: process.cwd, + emitWarning: (warning, type) => process.emitWarning(warning, type), + execPath: () => process.execPath, + exit: (code) => { + // eslint-disable-next-line n/no-process-exit + process.exit(code); + }, + nextTick: process.nextTick, + stdColumns: typeof process.stdout.columns !== 'undefined' ? process.stdout.columns : null + }, + readFileSync, + readdirSync, + require, + getCallerFile: () => { + const callerFile = getCallerFile(3); + return callerFile.match(/^file:\/\//) ? fileURLToPath(callerFile) : callerFile; + }, + stringWidth, + y18n: y18n({ + directory: resolve(__dirname, '../../../locales'), + updateFiles: false + }) +} diff --git a/node_modules/yargs/locales/be.json b/node_modules/yargs/locales/be.json new file mode 100644 index 0000000000000000000000000000000000000000..e28fa30139366dfd6e5f1a603149aae590912775 --- /dev/null +++ b/node_modules/yargs/locales/be.json @@ -0,0 +1,46 @@ +{ + "Commands:": "Каманды:", + "Options:": "Опцыі:", + "Examples:": "Прыклады:", + "boolean": "булевы тып", + "count": "падлік", + "string": "радковы тып", + "number": "лік", + "array": "масіў", + "required": "неабходна", + "default": "па змаўчанні", + "default:": "па змаўчанні:", + "choices:": "магчымасці:", + "aliases:": "аліасы:", + "generated-value": "згенераванае значэнне", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Недастаткова неапцыйных аргументаў: ёсць %s, трэба як мінімум %s", + "other": "Недастаткова неапцыйных аргументаў: ёсць %s, трэба як мінімум %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Занадта шмат неапцыйных аргументаў: ёсць %s, максімум дапушчальна %s", + "other": "Занадта шмат неапцыйных аргументаў: ёсць %s, максімум дапушчальна %s" + }, + "Missing argument value: %s": { + "one": "Не хапае значэння аргументу: %s", + "other": "Не хапае значэнняў аргументаў: %s" + }, + "Missing required argument: %s": { + "one": "Не хапае неабходнага аргументу: %s", + "other": "Не хапае неабходных аргументаў: %s" + }, + "Unknown argument: %s": { + "one": "Невядомы аргумент: %s", + "other": "Невядомыя аргументы: %s" + }, + "Invalid values:": "Несапраўдныя значэння:", + "Argument: %s, Given: %s, Choices: %s": "Аргумент: %s, Дадзенае значэнне: %s, Магчымасці: %s", + "Argument check failed: %s": "Праверка аргументаў не ўдалася: %s", + "Implications failed:": "Дадзены аргумент патрабуе наступны дадатковы аргумент:", + "Not enough arguments following: %s": "Недастаткова наступных аргументаў: %s", + "Invalid JSON config file: %s": "Несапраўдны файл канфігурацыі JSON: %s", + "Path to JSON config file": "Шлях да файла канфігурацыі JSON", + "Show help": "Паказаць дапамогу", + "Show version number": "Паказаць нумар версіі", + "Did you mean %s?": "Вы мелі на ўвазе %s?" +} diff --git a/node_modules/yargs/locales/cs.json b/node_modules/yargs/locales/cs.json new file mode 100644 index 0000000000000000000000000000000000000000..6394875647e85093fdf5f677a7dafe73db04983e --- /dev/null +++ b/node_modules/yargs/locales/cs.json @@ -0,0 +1,51 @@ +{ + "Commands:": "Příkazy:", + "Options:": "Možnosti:", + "Examples:": "Příklady:", + "boolean": "logická hodnota", + "count": "počet", + "string": "řetězec", + "number": "číslo", + "array": "pole", + "required": "povinné", + "default": "výchozí", + "default:": "výchozí:", + "choices:": "volby:", + "aliases:": "aliasy:", + "generated-value": "generovaná-hodnota", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Nedostatek argumentů: zadáno %s, je potřeba alespoň %s", + "other": "Nedostatek argumentů: zadáno %s, je potřeba alespoň %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Příliš mnoho argumentů: zadáno %s, maximálně %s", + "other": "Příliš mnoho argumentů: zadáno %s, maximálně %s" + }, + "Missing argument value: %s": { + "one": "Chybí hodnota argumentu: %s", + "other": "Chybí hodnoty argumentů: %s" + }, + "Missing required argument: %s": { + "one": "Chybí požadovaný argument: %s", + "other": "Chybí požadované argumenty: %s" + }, + "Unknown argument: %s": { + "one": "Neznámý argument: %s", + "other": "Neznámé argumenty: %s" + }, + "Invalid values:": "Neplatné hodnoty:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Zadáno: %s, Možnosti: %s", + "Argument check failed: %s": "Kontrola argumentů se nezdařila: %s", + "Implications failed:": "Chybí závislé argumenty:", + "Not enough arguments following: %s": "Následuje nedostatek argumentů: %s", + "Invalid JSON config file: %s": "Neplatný konfigurační soubor JSON: %s", + "Path to JSON config file": "Cesta ke konfiguračnímu souboru JSON", + "Show help": "Zobrazit nápovědu", + "Show version number": "Zobrazit číslo verze", + "Did you mean %s?": "Měl jste na mysli %s?", + "Arguments %s and %s are mutually exclusive" : "Argumenty %s a %s se vzájemně vylučují", + "Positionals:": "Poziční:", + "command": "příkaz", + "deprecated": "zastaralé", + "deprecated: %s": "zastaralé: %s" +} diff --git a/node_modules/yargs/locales/de.json b/node_modules/yargs/locales/de.json new file mode 100644 index 0000000000000000000000000000000000000000..dc73ec3f020738a423cd079ed80cbbc43c353830 --- /dev/null +++ b/node_modules/yargs/locales/de.json @@ -0,0 +1,46 @@ +{ + "Commands:": "Kommandos:", + "Options:": "Optionen:", + "Examples:": "Beispiele:", + "boolean": "boolean", + "count": "Zähler", + "string": "string", + "number": "Zahl", + "array": "array", + "required": "erforderlich", + "default": "Standard", + "default:": "Standard:", + "choices:": "Möglichkeiten:", + "aliases:": "Aliase:", + "generated-value": "Generierter-Wert", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Nicht genügend Argumente ohne Optionen: %s vorhanden, mindestens %s benötigt", + "other": "Nicht genügend Argumente ohne Optionen: %s vorhanden, mindestens %s benötigt" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Zu viele Argumente ohne Optionen: %s vorhanden, maximal %s erlaubt", + "other": "Zu viele Argumente ohne Optionen: %s vorhanden, maximal %s erlaubt" + }, + "Missing argument value: %s": { + "one": "Fehlender Argumentwert: %s", + "other": "Fehlende Argumentwerte: %s" + }, + "Missing required argument: %s": { + "one": "Fehlendes Argument: %s", + "other": "Fehlende Argumente: %s" + }, + "Unknown argument: %s": { + "one": "Unbekanntes Argument: %s", + "other": "Unbekannte Argumente: %s" + }, + "Invalid values:": "Unzulässige Werte:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gegeben: %s, Möglichkeiten: %s", + "Argument check failed: %s": "Argumente-Check fehlgeschlagen: %s", + "Implications failed:": "Fehlende abhängige Argumente:", + "Not enough arguments following: %s": "Nicht genügend Argumente nach: %s", + "Invalid JSON config file: %s": "Fehlerhafte JSON-Config Datei: %s", + "Path to JSON config file": "Pfad zur JSON-Config Datei", + "Show help": "Hilfe anzeigen", + "Show version number": "Version anzeigen", + "Did you mean %s?": "Meintest du %s?" +} diff --git a/node_modules/yargs/locales/en.json b/node_modules/yargs/locales/en.json new file mode 100644 index 0000000000000000000000000000000000000000..af096a110a2df76bee8e605b3b380c8490aa4959 --- /dev/null +++ b/node_modules/yargs/locales/en.json @@ -0,0 +1,55 @@ +{ + "Commands:": "Commands:", + "Options:": "Options:", + "Examples:": "Examples:", + "boolean": "boolean", + "count": "count", + "string": "string", + "number": "number", + "array": "array", + "required": "required", + "default": "default", + "default:": "default:", + "choices:": "choices:", + "aliases:": "aliases:", + "generated-value": "generated-value", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Not enough non-option arguments: got %s, need at least %s", + "other": "Not enough non-option arguments: got %s, need at least %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Too many non-option arguments: got %s, maximum of %s", + "other": "Too many non-option arguments: got %s, maximum of %s" + }, + "Missing argument value: %s": { + "one": "Missing argument value: %s", + "other": "Missing argument values: %s" + }, + "Missing required argument: %s": { + "one": "Missing required argument: %s", + "other": "Missing required arguments: %s" + }, + "Unknown argument: %s": { + "one": "Unknown argument: %s", + "other": "Unknown arguments: %s" + }, + "Unknown command: %s": { + "one": "Unknown command: %s", + "other": "Unknown commands: %s" + }, + "Invalid values:": "Invalid values:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Given: %s, Choices: %s", + "Argument check failed: %s": "Argument check failed: %s", + "Implications failed:": "Missing dependent arguments:", + "Not enough arguments following: %s": "Not enough arguments following: %s", + "Invalid JSON config file: %s": "Invalid JSON config file: %s", + "Path to JSON config file": "Path to JSON config file", + "Show help": "Show help", + "Show version number": "Show version number", + "Did you mean %s?": "Did you mean %s?", + "Arguments %s and %s are mutually exclusive" : "Arguments %s and %s are mutually exclusive", + "Positionals:": "Positionals:", + "command": "command", + "deprecated": "deprecated", + "deprecated: %s": "deprecated: %s" +} diff --git a/node_modules/yargs/locales/es.json b/node_modules/yargs/locales/es.json new file mode 100644 index 0000000000000000000000000000000000000000..d77b4616a211fea5f553a8c8aa5c89153e87f6d7 --- /dev/null +++ b/node_modules/yargs/locales/es.json @@ -0,0 +1,46 @@ +{ + "Commands:": "Comandos:", + "Options:": "Opciones:", + "Examples:": "Ejemplos:", + "boolean": "booleano", + "count": "cuenta", + "string": "cadena de caracteres", + "number": "número", + "array": "tabla", + "required": "requerido", + "default": "defecto", + "default:": "defecto:", + "choices:": "selección:", + "aliases:": "alias:", + "generated-value": "valor-generado", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Hacen falta argumentos no-opcionales: Número recibido %s, necesita por lo menos %s", + "other": "Hacen falta argumentos no-opcionales: Número recibido %s, necesita por lo menos %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Demasiados argumentos no-opcionales: Número recibido %s, máximo es %s", + "other": "Demasiados argumentos no-opcionales: Número recibido %s, máximo es %s" + }, + "Missing argument value: %s": { + "one": "Falta argumento: %s", + "other": "Faltan argumentos: %s" + }, + "Missing required argument: %s": { + "one": "Falta argumento requerido: %s", + "other": "Faltan argumentos requeridos: %s" + }, + "Unknown argument: %s": { + "one": "Argumento desconocido: %s", + "other": "Argumentos desconocidos: %s" + }, + "Invalid values:": "Valores inválidos:", + "Argument: %s, Given: %s, Choices: %s": "Argumento: %s, Recibido: %s, Seleccionados: %s", + "Argument check failed: %s": "Verificación de argumento ha fallado: %s", + "Implications failed:": "Implicaciones fallidas:", + "Not enough arguments following: %s": "No hay suficientes argumentos después de: %s", + "Invalid JSON config file: %s": "Archivo de configuración JSON inválido: %s", + "Path to JSON config file": "Ruta al archivo de configuración JSON", + "Show help": "Muestra ayuda", + "Show version number": "Muestra número de versión", + "Did you mean %s?": "Quisiste decir %s?" +} diff --git a/node_modules/yargs/locales/fi.json b/node_modules/yargs/locales/fi.json new file mode 100644 index 0000000000000000000000000000000000000000..481feb710a199af1660685a2cf93cac5306da3d1 --- /dev/null +++ b/node_modules/yargs/locales/fi.json @@ -0,0 +1,49 @@ +{ + "Commands:": "Komennot:", + "Options:": "Valinnat:", + "Examples:": "Esimerkkejä:", + "boolean": "totuusarvo", + "count": "lukumäärä", + "string": "merkkijono", + "number": "numero", + "array": "taulukko", + "required": "pakollinen", + "default": "oletusarvo", + "default:": "oletusarvo:", + "choices:": "vaihtoehdot:", + "aliases:": "aliakset:", + "generated-value": "generoitu-arvo", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Liian vähän argumentteja, jotka eivät ole valintoja: annettu %s, vaaditaan vähintään %s", + "other": "Liian vähän argumentteja, jotka eivät ole valintoja: annettu %s, vaaditaan vähintään %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Liikaa argumentteja, jotka eivät ole valintoja: annettu %s, sallitaan enintään %s", + "other": "Liikaa argumentteja, jotka eivät ole valintoja: annettu %s, sallitaan enintään %s" + }, + "Missing argument value: %s": { + "one": "Argumentin arvo puuttuu: %s", + "other": "Argumentin arvot puuttuvat: %s" + }, + "Missing required argument: %s": { + "one": "Pakollinen argumentti puuttuu: %s", + "other": "Pakollisia argumentteja puuttuu: %s" + }, + "Unknown argument: %s": { + "one": "Tuntematon argumentti: %s", + "other": "Tuntemattomia argumentteja: %s" + }, + "Invalid values:": "Virheelliset arvot:", + "Argument: %s, Given: %s, Choices: %s": "Argumentti: %s, Annettu: %s, Vaihtoehdot: %s", + "Argument check failed: %s": "Argumentin tarkistus epäonnistui: %s", + "Implications failed:": "Riippuvia argumentteja puuttuu:", + "Not enough arguments following: %s": "Argumentin perässä ei ole tarpeeksi argumentteja: %s", + "Invalid JSON config file: %s": "Epävalidi JSON-asetustiedosto: %s", + "Path to JSON config file": "JSON-asetustiedoston polku", + "Show help": "Näytä ohje", + "Show version number": "Näytä versionumero", + "Did you mean %s?": "Tarkoititko %s?", + "Arguments %s and %s are mutually exclusive" : "Argumentit %s ja %s eivät ole yhteensopivat", + "Positionals:": "Sijaintiparametrit:", + "command": "komento" +} diff --git a/node_modules/yargs/locales/fr.json b/node_modules/yargs/locales/fr.json new file mode 100644 index 0000000000000000000000000000000000000000..edd743f0c9420a67f020bece655987c7e9b66781 --- /dev/null +++ b/node_modules/yargs/locales/fr.json @@ -0,0 +1,53 @@ +{ + "Commands:": "Commandes :", + "Options:": "Options :", + "Examples:": "Exemples :", + "boolean": "booléen", + "count": "compteur", + "string": "chaîne de caractères", + "number": "nombre", + "array": "tableau", + "required": "requis", + "default": "défaut", + "default:": "défaut :", + "choices:": "choix :", + "aliases:": "alias :", + "generated-value": "valeur générée", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Pas assez d'arguments (hors options) : reçu %s, besoin d'au moins %s", + "other": "Pas assez d'arguments (hors options) : reçus %s, besoin d'au moins %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Trop d'arguments (hors options) : reçu %s, maximum de %s", + "other": "Trop d'arguments (hors options) : reçus %s, maximum de %s" + }, + "Missing argument value: %s": { + "one": "Argument manquant : %s", + "other": "Arguments manquants : %s" + }, + "Missing required argument: %s": { + "one": "Argument requis manquant : %s", + "other": "Arguments requis manquants : %s" + }, + "Unknown argument: %s": { + "one": "Argument inconnu : %s", + "other": "Arguments inconnus : %s" + }, + "Unknown command: %s": { + "one": "Commande inconnue : %s", + "other": "Commandes inconnues : %s" + }, + "Invalid values:": "Valeurs invalides :", + "Argument: %s, Given: %s, Choices: %s": "Argument : %s, donné : %s, choix : %s", + "Argument check failed: %s": "Echec de la vérification de l'argument : %s", + "Implications failed:": "Arguments dépendants manquants :", + "Not enough arguments following: %s": "Pas assez d'arguments après : %s", + "Invalid JSON config file: %s": "Fichier de configuration JSON invalide : %s", + "Path to JSON config file": "Chemin du fichier de configuration JSON", + "Show help": "Affiche l'aide", + "Show version number": "Affiche le numéro de version", + "Did you mean %s?": "Vouliez-vous dire %s ?", + "Arguments %s and %s are mutually exclusive" : "Les arguments %s et %s sont mutuellement exclusifs", + "Positionals:": "Arguments positionnels :", + "command": "commande" +} diff --git a/node_modules/yargs/locales/he.json b/node_modules/yargs/locales/he.json new file mode 100644 index 0000000000000000000000000000000000000000..947cc8870175088919a51a24c667a23540af5606 --- /dev/null +++ b/node_modules/yargs/locales/he.json @@ -0,0 +1,55 @@ +{ + "Commands:": "פקודות:", + "Options:": "אופציות:", + "Examples:": "דוגמות:", + "boolean": "בוליאני", + "count": "ספירה", + "string": "מחרוזת", + "number": "מספר", + "array": "מערך", + "required": "דרוש", + "default": "ברירת מחדל", + "default:": "ברירת מחדל:", + "choices:": "בחירות:", + "aliases:": "כינויים:", + "generated-value": "ערך-שנוצר", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "אין מספיק טיעונים שאינם אופציונלים: קיבל %s, צריך לפחות %s", + "other": "אין מספיק טיעונים שאינם אופציונלים: קיבל %s, צריך לפחות %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "יותר מדי טיעונים שאינם אופציונלים: קיבל %s, מקסימום של %s", + "other": "יותר מדי טיעונים שאינם אופציונלים: קיבל %s, מקסימום של %s" + }, + "Missing argument value: %s": { + "one": "חסר ערך הטענה: %s", + "other": "חסרים ערכי הטענה: %s" + }, + "Missing required argument: %s": { + "one": "חסר טענה דרושה: %s", + "other": "חסרות טענות דרושות: %s" + }, + "Unknown argument: %s": { + "one": "טענה לא ידוע: %s", + "other": "טענות לא ידועות: %s" + }, + "Unknown command: %s": { + "one": "פקודת לא ידועה: %s", + "other": "פקודות לא ידועות: %s" + }, + "Invalid values:": "ערכים לא חוקיים:", + "Argument: %s, Given: %s, Choices: %s": "טענות: %s, ניתנו: %s, בחירות: %s", + "Argument check failed: %s": "בדיקת הטענה נכשלה: %s", + "Implications failed:": "חסרים טיעונים תלויים:", + "Not enough arguments following: %s": "אין מספיק טיעונים לאחר: %s", + "Invalid JSON config file: %s": "קובץ תצורה לא תקין של JSON: %s", + "Path to JSON config file": "נתיב לקובץ התצורה של JSON", + "Show help": "הצג עזרה", + "Show version number": "הצג מספר גרסה", + "Did you mean %s?": "האם התכוונת ל- %s?", + "Arguments %s and %s are mutually exclusive" : "טענות %s ו- %s סותרים זה את זה", + "Positionals:": "עמדות:", + "command": "פקודה", + "deprecated": "הוצא משימוש", + "deprecated: %s": "הוצא משימוש: %s" +} diff --git a/node_modules/yargs/locales/hi.json b/node_modules/yargs/locales/hi.json new file mode 100644 index 0000000000000000000000000000000000000000..a9de77cce1546c088ea42925cdd5cd642f42f3de --- /dev/null +++ b/node_modules/yargs/locales/hi.json @@ -0,0 +1,49 @@ +{ + "Commands:": "आदेश:", + "Options:": "विकल्प:", + "Examples:": "उदाहरण:", + "boolean": "सत्यता", + "count": "संख्या", + "string": "वर्णों का तार ", + "number": "अंक", + "array": "सरणी", + "required": "आवश्यक", + "default": "डिफॉल्ट", + "default:": "डिफॉल्ट:", + "choices:": "विकल्प:", + "aliases:": "उपनाम:", + "generated-value": "उत्पन्न-मूल्य", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "पर्याप्त गैर-विकल्प तर्क प्राप्त नहीं: %s प्राप्त, कम से कम %s की आवश्यकता है", + "other": "पर्याप्त गैर-विकल्प तर्क प्राप्त नहीं: %s प्राप्त, कम से कम %s की आवश्यकता है" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "बहुत सारे गैर-विकल्प तर्क: %s प्राप्त, अधिकतम %s मान्य", + "other": "बहुत सारे गैर-विकल्प तर्क: %s प्राप्त, अधिकतम %s मान्य" + }, + "Missing argument value: %s": { + "one": "कुछ तर्को के मूल्य गुम हैं: %s", + "other": "कुछ तर्को के मूल्य गुम हैं: %s" + }, + "Missing required argument: %s": { + "one": "आवश्यक तर्क गुम हैं: %s", + "other": "आवश्यक तर्क गुम हैं: %s" + }, + "Unknown argument: %s": { + "one": "अज्ञात तर्क प्राप्त: %s", + "other": "अज्ञात तर्क प्राप्त: %s" + }, + "Invalid values:": "अमान्य मूल्य:", + "Argument: %s, Given: %s, Choices: %s": "तर्क: %s, प्राप्त: %s, विकल्प: %s", + "Argument check failed: %s": "तर्क जांच विफल: %s", + "Implications failed:": "दिए गए तर्क के लिए अतिरिक्त तर्क की अपेक्षा है:", + "Not enough arguments following: %s": "निम्नलिखित के बाद पर्याप्त तर्क नहीं प्राप्त: %s", + "Invalid JSON config file: %s": "अमान्य JSON config फाइल: %s", + "Path to JSON config file": "JSON config फाइल का पथ", + "Show help": "सहायता दिखाएँ", + "Show version number": "Version संख्या दिखाएँ", + "Did you mean %s?": "क्या आपका मतलब है %s?", + "Arguments %s and %s are mutually exclusive" : "तर्क %s और %s परस्पर अनन्य हैं", + "Positionals:": "स्थानीय:", + "command": "आदेश" +} diff --git a/node_modules/yargs/locales/hu.json b/node_modules/yargs/locales/hu.json new file mode 100644 index 0000000000000000000000000000000000000000..21492d05a7c84e9e08b05459d51d6ad37088d012 --- /dev/null +++ b/node_modules/yargs/locales/hu.json @@ -0,0 +1,46 @@ +{ + "Commands:": "Parancsok:", + "Options:": "Opciók:", + "Examples:": "Példák:", + "boolean": "boolean", + "count": "számláló", + "string": "szöveg", + "number": "szám", + "array": "tömb", + "required": "kötelező", + "default": "alapértelmezett", + "default:": "alapértelmezett:", + "choices:": "lehetőségek:", + "aliases:": "aliaszok:", + "generated-value": "generált-érték", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Nincs elég nem opcionális argumentum: %s van, legalább %s kell", + "other": "Nincs elég nem opcionális argumentum: %s van, legalább %s kell" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Túl sok nem opciánlis argumentum van: %s van, maximum %s lehet", + "other": "Túl sok nem opciánlis argumentum van: %s van, maximum %s lehet" + }, + "Missing argument value: %s": { + "one": "Hiányzó argumentum érték: %s", + "other": "Hiányzó argumentum értékek: %s" + }, + "Missing required argument: %s": { + "one": "Hiányzó kötelező argumentum: %s", + "other": "Hiányzó kötelező argumentumok: %s" + }, + "Unknown argument: %s": { + "one": "Ismeretlen argumentum: %s", + "other": "Ismeretlen argumentumok: %s" + }, + "Invalid values:": "Érvénytelen érték:", + "Argument: %s, Given: %s, Choices: %s": "Argumentum: %s, Megadott: %s, Lehetőségek: %s", + "Argument check failed: %s": "Argumentum ellenőrzés sikertelen: %s", + "Implications failed:": "Implikációk sikertelenek:", + "Not enough arguments following: %s": "Nem elég argumentum követi: %s", + "Invalid JSON config file: %s": "Érvénytelen JSON konfigurációs file: %s", + "Path to JSON config file": "JSON konfigurációs file helye", + "Show help": "Súgo megjelenítése", + "Show version number": "Verziószám megjelenítése", + "Did you mean %s?": "Erre gondoltál %s?" +} diff --git a/node_modules/yargs/locales/id.json b/node_modules/yargs/locales/id.json new file mode 100644 index 0000000000000000000000000000000000000000..125867cbb0eedc13d9a5a85ce6df7c3b348ae45f --- /dev/null +++ b/node_modules/yargs/locales/id.json @@ -0,0 +1,50 @@ + +{ + "Commands:": "Perintah:", + "Options:": "Pilihan:", + "Examples:": "Contoh:", + "boolean": "boolean", + "count": "jumlah", + "number": "nomor", + "string": "string", + "array": "larik", + "required": "diperlukan", + "default": "bawaan", + "default:": "bawaan:", + "aliases:": "istilah lain:", + "choices:": "pilihan:", + "generated-value": "nilai-yang-dihasilkan", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Argumen wajib kurang: hanya %s, minimal %s", + "other": "Argumen wajib kurang: hanya %s, minimal %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Terlalu banyak argumen wajib: ada %s, maksimal %s", + "other": "Terlalu banyak argumen wajib: ada %s, maksimal %s" + }, + "Missing argument value: %s": { + "one": "Kurang argumen: %s", + "other": "Kurang argumen: %s" + }, + "Missing required argument: %s": { + "one": "Kurang argumen wajib: %s", + "other": "Kurang argumen wajib: %s" + }, + "Unknown argument: %s": { + "one": "Argumen tak diketahui: %s", + "other": "Argumen tak diketahui: %s" + }, + "Invalid values:": "Nilai-nilai tidak valid:", + "Argument: %s, Given: %s, Choices: %s": "Argumen: %s, Diberikan: %s, Pilihan: %s", + "Argument check failed: %s": "Pemeriksaan argument gagal: %s", + "Implications failed:": "Implikasi gagal:", + "Not enough arguments following: %s": "Kurang argumen untuk: %s", + "Invalid JSON config file: %s": "Berkas konfigurasi JSON tidak valid: %s", + "Path to JSON config file": "Alamat berkas konfigurasi JSON", + "Show help": "Lihat bantuan", + "Show version number": "Lihat nomor versi", + "Did you mean %s?": "Maksud Anda: %s?", + "Arguments %s and %s are mutually exclusive" : "Argumen %s dan %s saling eksklusif", + "Positionals:": "Posisional-posisional:", + "command": "perintah" +} diff --git a/node_modules/yargs/locales/it.json b/node_modules/yargs/locales/it.json new file mode 100644 index 0000000000000000000000000000000000000000..fde575618817ac6c60846ce12ac8d041c65739af --- /dev/null +++ b/node_modules/yargs/locales/it.json @@ -0,0 +1,46 @@ +{ + "Commands:": "Comandi:", + "Options:": "Opzioni:", + "Examples:": "Esempi:", + "boolean": "booleano", + "count": "contatore", + "string": "stringa", + "number": "numero", + "array": "vettore", + "required": "richiesto", + "default": "predefinito", + "default:": "predefinito:", + "choices:": "scelte:", + "aliases:": "alias:", + "generated-value": "valore generato", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Numero insufficiente di argomenti non opzione: inseriti %s, richiesti almeno %s", + "other": "Numero insufficiente di argomenti non opzione: inseriti %s, richiesti almeno %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Troppi argomenti non opzione: inseriti %s, massimo possibile %s", + "other": "Troppi argomenti non opzione: inseriti %s, massimo possibile %s" + }, + "Missing argument value: %s": { + "one": "Argomento mancante: %s", + "other": "Argomenti mancanti: %s" + }, + "Missing required argument: %s": { + "one": "Argomento richiesto mancante: %s", + "other": "Argomenti richiesti mancanti: %s" + }, + "Unknown argument: %s": { + "one": "Argomento sconosciuto: %s", + "other": "Argomenti sconosciuti: %s" + }, + "Invalid values:": "Valori non validi:", + "Argument: %s, Given: %s, Choices: %s": "Argomento: %s, Richiesto: %s, Scelte: %s", + "Argument check failed: %s": "Controllo dell'argomento fallito: %s", + "Implications failed:": "Argomenti dipendenti mancanti:", + "Not enough arguments following: %s": "Argomenti insufficienti dopo: %s", + "Invalid JSON config file: %s": "File di configurazione JSON non valido: %s", + "Path to JSON config file": "Percorso del file di configurazione JSON", + "Show help": "Mostra la schermata di aiuto", + "Show version number": "Mostra il numero di versione", + "Did you mean %s?": "Intendi forse %s?" +} diff --git a/node_modules/yargs/locales/ja.json b/node_modules/yargs/locales/ja.json new file mode 100644 index 0000000000000000000000000000000000000000..3954ae68f895ca5fdd80d55257b2f655dcf92718 --- /dev/null +++ b/node_modules/yargs/locales/ja.json @@ -0,0 +1,51 @@ +{ + "Commands:": "コマンド:", + "Options:": "オプション:", + "Examples:": "例:", + "boolean": "真偽", + "count": "カウント", + "string": "文字列", + "number": "数値", + "array": "配列", + "required": "必須", + "default": "デフォルト", + "default:": "デフォルト:", + "choices:": "選択してください:", + "aliases:": "エイリアス:", + "generated-value": "生成された値", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "オプションではない引数が %s 個では不足しています。少なくとも %s 個の引数が必要です:", + "other": "オプションではない引数が %s 個では不足しています。少なくとも %s 個の引数が必要です:" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "オプションではない引数が %s 個では多すぎます。最大で %s 個までです:", + "other": "オプションではない引数が %s 個では多すぎます。最大で %s 個までです:" + }, + "Missing argument value: %s": { + "one": "引数の値が見つかりません: %s", + "other": "引数の値が見つかりません: %s" + }, + "Missing required argument: %s": { + "one": "必須の引数が見つかりません: %s", + "other": "必須の引数が見つかりません: %s" + }, + "Unknown argument: %s": { + "one": "未知の引数です: %s", + "other": "未知の引数です: %s" + }, + "Invalid values:": "不正な値です:", + "Argument: %s, Given: %s, Choices: %s": "引数は %s です。与えられた値: %s, 選択してください: %s", + "Argument check failed: %s": "引数のチェックに失敗しました: %s", + "Implications failed:": "オプションの組み合わせで不正が生じました:", + "Not enough arguments following: %s": "次の引数が不足しています。: %s", + "Invalid JSON config file: %s": "JSONの設定ファイルが不正です: %s", + "Path to JSON config file": "JSONの設定ファイルまでのpath", + "Show help": "ヘルプを表示", + "Show version number": "バージョンを表示", + "Did you mean %s?": "もしかして %s?", + "Arguments %s and %s are mutually exclusive" : "引数 %s と %s は同時に指定できません", + "Positionals:": "位置:", + "command": "コマンド", + "deprecated": "非推奨", + "deprecated: %s": "非推奨: %s" +} diff --git a/node_modules/yargs/locales/ko.json b/node_modules/yargs/locales/ko.json new file mode 100644 index 0000000000000000000000000000000000000000..746bc89fe91299a14e567fd3866564985586e262 --- /dev/null +++ b/node_modules/yargs/locales/ko.json @@ -0,0 +1,49 @@ +{ + "Commands:": "명령:", + "Options:": "옵션:", + "Examples:": "예시:", + "boolean": "불리언", + "count": "개수", + "string": "문자열", + "number": "숫자", + "array": "배열", + "required": "필수", + "default": "기본값", + "default:": "기본값:", + "choices:": "선택지:", + "aliases:": "별칭:", + "generated-value": "생성된 값", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "옵션이 아닌 인수가 충분하지 않습니다: %s개 입력받음, 최소 %s개 입력 필요", + "other": "옵션이 아닌 인수가 충분하지 않습니다: %s개 입력받음, 최소 %s개 입력 필요" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "옵션이 아닌 인수가 너무 많습니다: %s개 입력받음, 최대 %s개 입력 가능", + "other": "옵션이 아닌 인수가 너무 많습니다: %s개 입력받음, 최대 %s개 입력 가능" + }, + "Missing argument value: %s": { + "one": "인수가 주어지지 않았습니다: %s", + "other": "인수가 주어지지 않았습니다: %s" + }, + "Missing required argument: %s": { + "one": "필수 인수가 주어지지 않았습니다: %s", + "other": "필수 인수가 주어지지 않았습니다: %s" + }, + "Unknown argument: %s": { + "one": "알 수 없는 인수입니다: %s", + "other": "알 수 없는 인수입니다: %s" + }, + "Invalid values:": "유효하지 않은 값:", + "Argument: %s, Given: %s, Choices: %s": "인수: %s, 주어진 값: %s, 선택지: %s", + "Argument check failed: %s": "인수 체크에 실패했습니다: %s", + "Implications failed:": "주어진 인수에 필요한 추가 인수가 주어지지 않았습니다:", + "Not enough arguments following: %s": "다음 인수가 주어지지 않았습니다: %s", + "Invalid JSON config file: %s": "유효하지 않은 JSON 설정 파일: %s", + "Path to JSON config file": "JSON 설정 파일 경로", + "Show help": "도움말 표시", + "Show version number": "버전 표시", + "Did you mean %s?": "%s을(를) 찾으시나요?", + "Arguments %s and %s are mutually exclusive" : "인수 %s과(와) %s은(는) 동시에 지정할 수 없습니다", + "Positionals:": "위치:", + "command": "명령" +} diff --git a/node_modules/yargs/locales/nb.json b/node_modules/yargs/locales/nb.json new file mode 100644 index 0000000000000000000000000000000000000000..6f410ed09d052d89d421d5aa07aa8b216500fbb0 --- /dev/null +++ b/node_modules/yargs/locales/nb.json @@ -0,0 +1,44 @@ +{ + "Commands:": "Kommandoer:", + "Options:": "Alternativer:", + "Examples:": "Eksempler:", + "boolean": "boolsk", + "count": "antall", + "string": "streng", + "number": "nummer", + "array": "matrise", + "required": "obligatorisk", + "default": "standard", + "default:": "standard:", + "choices:": "valg:", + "generated-value": "generert-verdi", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Ikke nok ikke-alternativ argumenter: fikk %s, trenger minst %s", + "other": "Ikke nok ikke-alternativ argumenter: fikk %s, trenger minst %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "For mange ikke-alternativ argumenter: fikk %s, maksimum %s", + "other": "For mange ikke-alternativ argumenter: fikk %s, maksimum %s" + }, + "Missing argument value: %s": { + "one": "Mangler argument verdi: %s", + "other": "Mangler argument verdier: %s" + }, + "Missing required argument: %s": { + "one": "Mangler obligatorisk argument: %s", + "other": "Mangler obligatoriske argumenter: %s" + }, + "Unknown argument: %s": { + "one": "Ukjent argument: %s", + "other": "Ukjente argumenter: %s" + }, + "Invalid values:": "Ugyldige verdier:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gitt: %s, Valg: %s", + "Argument check failed: %s": "Argumentsjekk mislyktes: %s", + "Implications failed:": "Konsekvensene mislyktes:", + "Not enough arguments following: %s": "Ikke nok følgende argumenter: %s", + "Invalid JSON config file: %s": "Ugyldig JSON konfigurasjonsfil: %s", + "Path to JSON config file": "Bane til JSON konfigurasjonsfil", + "Show help": "Vis hjelp", + "Show version number": "Vis versjonsnummer" +} diff --git a/node_modules/yargs/locales/nl.json b/node_modules/yargs/locales/nl.json new file mode 100644 index 0000000000000000000000000000000000000000..9ff95c5594cb5a3e7ea849273913d8b88a50f53c --- /dev/null +++ b/node_modules/yargs/locales/nl.json @@ -0,0 +1,49 @@ +{ + "Commands:": "Commando's:", + "Options:": "Opties:", + "Examples:": "Voorbeelden:", + "boolean": "booleaans", + "count": "aantal", + "string": "string", + "number": "getal", + "array": "lijst", + "required": "verplicht", + "default": "standaard", + "default:": "standaard:", + "choices:": "keuzes:", + "aliases:": "aliassen:", + "generated-value": "gegenereerde waarde", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Niet genoeg niet-optie-argumenten: %s gekregen, minstens %s nodig", + "other": "Niet genoeg niet-optie-argumenten: %s gekregen, minstens %s nodig" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Te veel niet-optie-argumenten: %s gekregen, maximum is %s", + "other": "Te veel niet-optie-argumenten: %s gekregen, maximum is %s" + }, + "Missing argument value: %s": { + "one": "Missende argumentwaarde: %s", + "other": "Missende argumentwaarden: %s" + }, + "Missing required argument: %s": { + "one": "Missend verplicht argument: %s", + "other": "Missende verplichte argumenten: %s" + }, + "Unknown argument: %s": { + "one": "Onbekend argument: %s", + "other": "Onbekende argumenten: %s" + }, + "Invalid values:": "Ongeldige waarden:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gegeven: %s, Keuzes: %s", + "Argument check failed: %s": "Argumentcontrole mislukt: %s", + "Implications failed:": "Ontbrekende afhankelijke argumenten:", + "Not enough arguments following: %s": "Niet genoeg argumenten na: %s", + "Invalid JSON config file: %s": "Ongeldig JSON-config-bestand: %s", + "Path to JSON config file": "Pad naar JSON-config-bestand", + "Show help": "Toon help", + "Show version number": "Toon versienummer", + "Did you mean %s?": "Bedoelde u misschien %s?", + "Arguments %s and %s are mutually exclusive": "Argumenten %s en %s kunnen niet tegelijk gebruikt worden", + "Positionals:": "Positie-afhankelijke argumenten", + "command": "commando" +} diff --git a/node_modules/yargs/locales/nn.json b/node_modules/yargs/locales/nn.json new file mode 100644 index 0000000000000000000000000000000000000000..24479ac946ceab9e5fe788b60862b6f7b9633b54 --- /dev/null +++ b/node_modules/yargs/locales/nn.json @@ -0,0 +1,44 @@ +{ + "Commands:": "Kommandoar:", + "Options:": "Alternativ:", + "Examples:": "Døme:", + "boolean": "boolsk", + "count": "mengd", + "string": "streng", + "number": "nummer", + "array": "matrise", + "required": "obligatorisk", + "default": "standard", + "default:": "standard:", + "choices:": "val:", + "generated-value": "generert-verdi", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Ikkje nok ikkje-alternativ argument: fekk %s, treng minst %s", + "other": "Ikkje nok ikkje-alternativ argument: fekk %s, treng minst %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "For mange ikkje-alternativ argument: fekk %s, maksimum %s", + "other": "For mange ikkje-alternativ argument: fekk %s, maksimum %s" + }, + "Missing argument value: %s": { + "one": "Manglar argumentverdi: %s", + "other": "Manglar argumentverdiar: %s" + }, + "Missing required argument: %s": { + "one": "Manglar obligatorisk argument: %s", + "other": "Manglar obligatoriske argument: %s" + }, + "Unknown argument: %s": { + "one": "Ukjent argument: %s", + "other": "Ukjende argument: %s" + }, + "Invalid values:": "Ugyldige verdiar:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gjeve: %s, Val: %s", + "Argument check failed: %s": "Argumentsjekk mislukkast: %s", + "Implications failed:": "Konsekvensane mislukkast:", + "Not enough arguments following: %s": "Ikkje nok fylgjande argument: %s", + "Invalid JSON config file: %s": "Ugyldig JSON konfigurasjonsfil: %s", + "Path to JSON config file": "Bane til JSON konfigurasjonsfil", + "Show help": "Vis hjelp", + "Show version number": "Vis versjonsnummer" +} diff --git a/node_modules/yargs/locales/pirate.json b/node_modules/yargs/locales/pirate.json new file mode 100644 index 0000000000000000000000000000000000000000..dcb5cb75377d70d5e4783199e54bda11eae259cd --- /dev/null +++ b/node_modules/yargs/locales/pirate.json @@ -0,0 +1,13 @@ +{ + "Commands:": "Choose yer command:", + "Options:": "Options for me hearties!", + "Examples:": "Ex. marks the spot:", + "required": "requi-yar-ed", + "Missing required argument: %s": { + "one": "Ye be havin' to set the followin' argument land lubber: %s", + "other": "Ye be havin' to set the followin' arguments land lubber: %s" + }, + "Show help": "Parlay this here code of conduct", + "Show version number": "'Tis the version ye be askin' fer", + "Arguments %s and %s are mutually exclusive" : "Yon scurvy dogs %s and %s be as bad as rum and a prudish wench" +} diff --git a/node_modules/yargs/locales/pl.json b/node_modules/yargs/locales/pl.json new file mode 100644 index 0000000000000000000000000000000000000000..a41d4bd50f5b1b385f2677cfadb246c4b76b3e23 --- /dev/null +++ b/node_modules/yargs/locales/pl.json @@ -0,0 +1,49 @@ +{ + "Commands:": "Polecenia:", + "Options:": "Opcje:", + "Examples:": "Przykłady:", + "boolean": "boolean", + "count": "ilość", + "string": "ciąg znaków", + "number": "liczba", + "array": "tablica", + "required": "wymagany", + "default": "domyślny", + "default:": "domyślny:", + "choices:": "dostępne:", + "aliases:": "aliasy:", + "generated-value": "wygenerowana-wartość", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Niewystarczająca ilość argumentów: otrzymano %s, wymagane co najmniej %s", + "other": "Niewystarczająca ilość argumentów: otrzymano %s, wymagane co najmniej %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Zbyt duża ilość argumentów: otrzymano %s, wymagane co najwyżej %s", + "other": "Zbyt duża ilość argumentów: otrzymano %s, wymagane co najwyżej %s" + }, + "Missing argument value: %s": { + "one": "Brak wartości dla argumentu: %s", + "other": "Brak wartości dla argumentów: %s" + }, + "Missing required argument: %s": { + "one": "Brak wymaganego argumentu: %s", + "other": "Brak wymaganych argumentów: %s" + }, + "Unknown argument: %s": { + "one": "Nieznany argument: %s", + "other": "Nieznane argumenty: %s" + }, + "Invalid values:": "Nieprawidłowe wartości:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Otrzymano: %s, Dostępne: %s", + "Argument check failed: %s": "Weryfikacja argumentów nie powiodła się: %s", + "Implications failed:": "Założenia nie zostały spełnione:", + "Not enough arguments following: %s": "Niewystarczająca ilość argumentów następujących po: %s", + "Invalid JSON config file: %s": "Nieprawidłowy plik konfiguracyjny JSON: %s", + "Path to JSON config file": "Ścieżka do pliku konfiguracyjnego JSON", + "Show help": "Pokaż pomoc", + "Show version number": "Pokaż numer wersji", + "Did you mean %s?": "Czy chodziło Ci o %s?", + "Arguments %s and %s are mutually exclusive": "Argumenty %s i %s wzajemnie się wykluczają", + "Positionals:": "Pozycyjne:", + "command": "polecenie" +} diff --git a/node_modules/yargs/locales/pt.json b/node_modules/yargs/locales/pt.json new file mode 100644 index 0000000000000000000000000000000000000000..0c8ac99c82f4ab25025b42274bfdfbf386f46a02 --- /dev/null +++ b/node_modules/yargs/locales/pt.json @@ -0,0 +1,45 @@ +{ + "Commands:": "Comandos:", + "Options:": "Opções:", + "Examples:": "Exemplos:", + "boolean": "boolean", + "count": "contagem", + "string": "cadeia de caracteres", + "number": "número", + "array": "arranjo", + "required": "requerido", + "default": "padrão", + "default:": "padrão:", + "choices:": "escolhas:", + "generated-value": "valor-gerado", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Argumentos insuficientes não opcionais: Argumento %s, necessário pelo menos %s", + "other": "Argumentos insuficientes não opcionais: Argumento %s, necessário pelo menos %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Excesso de argumentos não opcionais: recebido %s, máximo de %s", + "other": "Excesso de argumentos não opcionais: recebido %s, máximo de %s" + }, + "Missing argument value: %s": { + "one": "Falta valor de argumento: %s", + "other": "Falta valores de argumento: %s" + }, + "Missing required argument: %s": { + "one": "Falta argumento obrigatório: %s", + "other": "Faltando argumentos obrigatórios: %s" + }, + "Unknown argument: %s": { + "one": "Argumento desconhecido: %s", + "other": "Argumentos desconhecidos: %s" + }, + "Invalid values:": "Valores inválidos:", + "Argument: %s, Given: %s, Choices: %s": "Argumento: %s, Dado: %s, Escolhas: %s", + "Argument check failed: %s": "Verificação de argumento falhou: %s", + "Implications failed:": "Implicações falharam:", + "Not enough arguments following: %s": "Insuficientes argumentos a seguir: %s", + "Invalid JSON config file: %s": "Arquivo de configuração em JSON esta inválido: %s", + "Path to JSON config file": "Caminho para o arquivo de configuração em JSON", + "Show help": "Mostra ajuda", + "Show version number": "Mostra número de versão", + "Arguments %s and %s are mutually exclusive" : "Argumentos %s e %s são mutualmente exclusivos" +} diff --git a/node_modules/yargs/locales/pt_BR.json b/node_modules/yargs/locales/pt_BR.json new file mode 100644 index 0000000000000000000000000000000000000000..eae1ec60d2bde9a5283a3dbc2720f4caa08341f4 --- /dev/null +++ b/node_modules/yargs/locales/pt_BR.json @@ -0,0 +1,48 @@ +{ + "Commands:": "Comandos:", + "Options:": "Opções:", + "Examples:": "Exemplos:", + "boolean": "booleano", + "count": "contagem", + "string": "string", + "number": "número", + "array": "array", + "required": "obrigatório", + "default:": "padrão:", + "choices:": "opções:", + "aliases:": "sinônimos:", + "generated-value": "valor-gerado", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Argumentos insuficientes: Argumento %s, necessário pelo menos %s", + "other": "Argumentos insuficientes: Argumento %s, necessário pelo menos %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Excesso de argumentos: recebido %s, máximo de %s", + "other": "Excesso de argumentos: recebido %s, máximo de %s" + }, + "Missing argument value: %s": { + "one": "Falta valor de argumento: %s", + "other": "Falta valores de argumento: %s" + }, + "Missing required argument: %s": { + "one": "Falta argumento obrigatório: %s", + "other": "Faltando argumentos obrigatórios: %s" + }, + "Unknown argument: %s": { + "one": "Argumento desconhecido: %s", + "other": "Argumentos desconhecidos: %s" + }, + "Invalid values:": "Valores inválidos:", + "Argument: %s, Given: %s, Choices: %s": "Argumento: %s, Dado: %s, Opções: %s", + "Argument check failed: %s": "Verificação de argumento falhou: %s", + "Implications failed:": "Implicações falharam:", + "Not enough arguments following: %s": "Argumentos insuficientes a seguir: %s", + "Invalid JSON config file: %s": "Arquivo JSON de configuração inválido: %s", + "Path to JSON config file": "Caminho para o arquivo JSON de configuração", + "Show help": "Exibe ajuda", + "Show version number": "Exibe a versão", + "Did you mean %s?": "Você quis dizer %s?", + "Arguments %s and %s are mutually exclusive" : "Argumentos %s e %s são mutualmente exclusivos", + "Positionals:": "Posicionais:", + "command": "comando" +} diff --git a/node_modules/yargs/locales/ru.json b/node_modules/yargs/locales/ru.json new file mode 100644 index 0000000000000000000000000000000000000000..d5c9e323b83c578b4182b0a489bd2bfe4b284f78 --- /dev/null +++ b/node_modules/yargs/locales/ru.json @@ -0,0 +1,51 @@ +{ + "Commands:": "Команды:", + "Options:": "Опции:", + "Examples:": "Примеры:", + "boolean": "булевый тип", + "count": "подсчет", + "string": "строковой тип", + "number": "число", + "array": "массив", + "required": "необходимо", + "default": "по умолчанию", + "default:": "по умолчанию:", + "choices:": "возможности:", + "aliases:": "алиасы:", + "generated-value": "генерированное значение", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Недостаточно неопционных аргументов: есть %s, нужно как минимум %s", + "other": "Недостаточно неопционных аргументов: есть %s, нужно как минимум %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Слишком много неопционных аргументов: есть %s, максимум допустимо %s", + "other": "Слишком много неопционных аргументов: есть %s, максимум допустимо %s" + }, + "Missing argument value: %s": { + "one": "Не хватает значения аргумента: %s", + "other": "Не хватает значений аргументов: %s" + }, + "Missing required argument: %s": { + "one": "Не хватает необходимого аргумента: %s", + "other": "Не хватает необходимых аргументов: %s" + }, + "Unknown argument: %s": { + "one": "Неизвестный аргумент: %s", + "other": "Неизвестные аргументы: %s" + }, + "Invalid values:": "Недействительные значения:", + "Argument: %s, Given: %s, Choices: %s": "Аргумент: %s, Данное значение: %s, Возможности: %s", + "Argument check failed: %s": "Проверка аргументов не удалась: %s", + "Implications failed:": "Данный аргумент требует следующий дополнительный аргумент:", + "Not enough arguments following: %s": "Недостаточно следующих аргументов: %s", + "Invalid JSON config file: %s": "Недействительный файл конфигурации JSON: %s", + "Path to JSON config file": "Путь к файлу конфигурации JSON", + "Show help": "Показать помощь", + "Show version number": "Показать номер версии", + "Did you mean %s?": "Вы имели в виду %s?", + "Arguments %s and %s are mutually exclusive": "Аргументы %s и %s являются взаимоисключающими", + "Positionals:": "Позиционные аргументы:", + "command": "команда", + "deprecated": "устар.", + "deprecated: %s": "устар.: %s" +} diff --git a/node_modules/yargs/locales/th.json b/node_modules/yargs/locales/th.json new file mode 100644 index 0000000000000000000000000000000000000000..33b048e2a9275dd540d62aa1e38b07c113b6d9e5 --- /dev/null +++ b/node_modules/yargs/locales/th.json @@ -0,0 +1,46 @@ +{ + "Commands:": "คอมมาน", + "Options:": "ออฟชั่น", + "Examples:": "ตัวอย่าง", + "boolean": "บูลีน", + "count": "นับ", + "string": "สตริง", + "number": "ตัวเลข", + "array": "อาเรย์", + "required": "จำเป็น", + "default": "ค่าเริ่มต้", + "default:": "ค่าเริ่มต้น", + "choices:": "ตัวเลือก", + "aliases:": "เอเลียส", + "generated-value": "ค่าที่ถูกสร้างขึ้น", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "ใส่อาร์กิวเมนต์ไม่ครบตามจำนวนที่กำหนด: ใส่ค่ามาจำนวน %s ค่า, แต่ต้องการอย่างน้อย %s ค่า", + "other": "ใส่อาร์กิวเมนต์ไม่ครบตามจำนวนที่กำหนด: ใส่ค่ามาจำนวน %s ค่า, แต่ต้องการอย่างน้อย %s ค่า" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "ใส่อาร์กิวเมนต์เกินจำนวนที่กำหนด: ใส่ค่ามาจำนวน %s ค่า, แต่ต้องการมากที่สุด %s ค่า", + "other": "ใส่อาร์กิวเมนต์เกินจำนวนที่กำหนด: ใส่ค่ามาจำนวน %s ค่า, แต่ต้องการมากที่สุด %s ค่า" + }, + "Missing argument value: %s": { + "one": "ค่าอาร์กิวเมนต์ที่ขาดไป: %s", + "other": "ค่าอาร์กิวเมนต์ที่ขาดไป: %s" + }, + "Missing required argument: %s": { + "one": "อาร์กิวเมนต์จำเป็นที่ขาดไป: %s", + "other": "อาร์กิวเมนต์จำเป็นที่ขาดไป: %s" + }, + "Unknown argument: %s": { + "one": "อาร์กิวเมนต์ที่ไม่รู้จัก: %s", + "other": "อาร์กิวเมนต์ที่ไม่รู้จัก: %s" + }, + "Invalid values:": "ค่าไม่ถูกต้อง:", + "Argument: %s, Given: %s, Choices: %s": "อาร์กิวเมนต์: %s, ได้รับ: %s, ตัวเลือก: %s", + "Argument check failed: %s": "ตรวจสอบพบอาร์กิวเมนต์ที่ไม่ถูกต้อง: %s", + "Implications failed:": "Implications ไม่สำเร็จ:", + "Not enough arguments following: %s": "ใส่อาร์กิวเมนต์ไม่ครบ: %s", + "Invalid JSON config file: %s": "ไฟล์คอนฟิค JSON ไม่ถูกต้อง: %s", + "Path to JSON config file": "พาทไฟล์คอนฟิค JSON", + "Show help": "ขอความช่วยเหลือ", + "Show version number": "แสดงตัวเลขเวอร์ชั่น", + "Did you mean %s?": "คุณหมายถึง %s?" +} diff --git a/node_modules/yargs/locales/tr.json b/node_modules/yargs/locales/tr.json new file mode 100644 index 0000000000000000000000000000000000000000..0d0d2ccd8fa5867fb2e929a30c5ae5ca1cb45616 --- /dev/null +++ b/node_modules/yargs/locales/tr.json @@ -0,0 +1,48 @@ +{ + "Commands:": "Komutlar:", + "Options:": "Seçenekler:", + "Examples:": "Örnekler:", + "boolean": "boolean", + "count": "sayı", + "string": "string", + "number": "numara", + "array": "array", + "required": "zorunlu", + "default": "varsayılan", + "default:": "varsayılan:", + "choices:": "seçimler:", + "aliases:": "takma adlar:", + "generated-value": "oluşturulan-değer", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Seçenek dışı argümanlar yetersiz: %s bulundu, %s gerekli", + "other": "Seçenek dışı argümanlar yetersiz: %s bulundu, %s gerekli" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Seçenek dışı argümanlar gereğinden fazla: %s bulundu, azami %s", + "other": "Seçenek dışı argümanlar gereğinden fazla: %s bulundu, azami %s" + }, + "Missing argument value: %s": { + "one": "Eksik argüman değeri: %s", + "other": "Eksik argüman değerleri: %s" + }, + "Missing required argument: %s": { + "one": "Eksik zorunlu argüman: %s", + "other": "Eksik zorunlu argümanlar: %s" + }, + "Unknown argument: %s": { + "one": "Bilinmeyen argüman: %s", + "other": "Bilinmeyen argümanlar: %s" + }, + "Invalid values:": "Geçersiz değerler:", + "Argument: %s, Given: %s, Choices: %s": "Argüman: %s, Verilen: %s, Seçimler: %s", + "Argument check failed: %s": "Argüman kontrolü başarısız oldu: %s", + "Implications failed:": "Sonuçlar başarısız oldu:", + "Not enough arguments following: %s": "%s için yeterli argüman bulunamadı", + "Invalid JSON config file: %s": "Geçersiz JSON yapılandırma dosyası: %s", + "Path to JSON config file": "JSON yapılandırma dosya konumu", + "Show help": "Yardım detaylarını göster", + "Show version number": "Versiyon detaylarını göster", + "Did you mean %s?": "Bunu mu demek istediniz: %s?", + "Positionals:": "Sıralılar:", + "command": "komut" +} diff --git a/node_modules/yargs/locales/uk_UA.json b/node_modules/yargs/locales/uk_UA.json new file mode 100644 index 0000000000000000000000000000000000000000..0af0e99cb11ce6c121cae3576a02665751b8e6a2 --- /dev/null +++ b/node_modules/yargs/locales/uk_UA.json @@ -0,0 +1,51 @@ +{ + "Commands:": "Команди:", + "Options:": "Опції:", + "Examples:": "Приклади:", + "boolean": "boolean", + "count": "кількість", + "string": "строка", + "number": "число", + "array": "масива", + "required": "обов'язково", + "default": "за замовчуванням", + "default:": "за замовчуванням:", + "choices:": "доступні варіанти:", + "aliases:": "псевдоніми:", + "generated-value": "згенероване значення", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Недостатньо аргументів: наразі %s, потрібно %s або більше", + "other": "Недостатньо аргументів: наразі %s, потрібно %s або більше" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Забагато аргументів: наразі %s, максимум %s", + "other": "Too many non-option arguments: наразі %s, максимум of %s" + }, + "Missing argument value: %s": { + "one": "Відсутнє значення для аргументу: %s", + "other": "Відсутні значення для аргументу: %s" + }, + "Missing required argument: %s": { + "one": "Відсутній обов'язковий аргумент: %s", + "other": "Відсутні обов'язкові аргументи: %s" + }, + "Unknown argument: %s": { + "one": "Аргумент %s не підтримується", + "other": "Аргументи %s не підтримуються" + }, + "Invalid values:": "Некоректні значення:", + "Argument: %s, Given: %s, Choices: %s": "Аргумент: %s, Введено: %s, Доступні варіанти: %s", + "Argument check failed: %s": "Аргумент не пройшов перевірку: %s", + "Implications failed:": "Відсутні залежні аргументи:", + "Not enough arguments following: %s": "Не достатньо аргументів після: %s", + "Invalid JSON config file: %s": "Некоректний JSON-файл конфігурації: %s", + "Path to JSON config file": "Шлях до JSON-файлу конфігурації", + "Show help": "Показати довідку", + "Show version number": "Показати версію", + "Did you mean %s?": "Можливо, ви мали на увазі %s?", + "Arguments %s and %s are mutually exclusive" : "Аргументи %s та %s взаємовиключні", + "Positionals:": "Позиційні:", + "command": "команда", + "deprecated": "застарілий", + "deprecated: %s": "застарілий: %s" +} diff --git a/node_modules/yargs/locales/uz.json b/node_modules/yargs/locales/uz.json new file mode 100644 index 0000000000000000000000000000000000000000..0d0716819b5e8de0fe7a43d377e1ec6084cd0da7 --- /dev/null +++ b/node_modules/yargs/locales/uz.json @@ -0,0 +1,52 @@ +{ + "Commands:": "Buyruqlar:", + "Options:": "Imkoniyatlar:", + "Examples:": "Misollar:", + "boolean": "boolean", + "count": "sanoq", + "string": "satr", + "number": "raqam", + "array": "massiv", + "required": "majburiy", + "default": "boshlang'ich", + "default:": "boshlang'ich:", + "choices:": "tanlovlar:", + "aliases:": "taxalluslar:", + "generated-value": "yaratilgan-qiymat", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "No-imkoniyat argumentlar yetarli emas: berilgan %s, minimum %s", + "other": "No-imkoniyat argumentlar yetarli emas: berilgan %s, minimum %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "No-imkoniyat argumentlar juda ko'p: berilgan %s, maksimum %s", + "other": "No-imkoniyat argumentlar juda ko'p: got %s, maksimum %s" + }, + "Missing argument value: %s": { + "one": "Argument qiymati berilmagan: %s", + "other": "Argument qiymatlari berilmagan: %s" + }, + "Missing required argument: %s": { + "one": "Majburiy argument berilmagan: %s", + "other": "Majburiy argumentlar berilmagan: %s" + }, + "Unknown argument: %s": { + "one": "Noma'lum argument berilmagan: %s", + "other": "Noma'lum argumentlar berilmagan: %s" + }, + "Invalid values:": "Nosoz qiymatlar:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Berilgan: %s, Tanlovlar: %s", + "Argument check failed: %s": "Muvaffaqiyatsiz argument tekshiruvi: %s", + "Implications failed:": "Bog'liq argumentlar berilmagan:", + "Not enough arguments following: %s": "Quyidagi argumentlar yetarli emas: %s", + "Invalid JSON config file: %s": "Nosoz JSON konfiguratsiya fayli: %s", + "Path to JSON config file": "JSON konfiguratsiya fayli joylashuvi", + "Show help": "Yordam ko'rsatish", + "Show version number": "Versiyani ko'rsatish", + "Did you mean %s?": "%s ni nazarda tutyapsizmi?", + "Arguments %s and %s are mutually exclusive" : "%s va %s argumentlari alohida", + "Positionals:": "Positsionallar:", + "command": "buyruq", + "deprecated": "eskirgan", + "deprecated: %s": "eskirgan: %s" + } + \ No newline at end of file diff --git a/node_modules/yargs/locales/zh_CN.json b/node_modules/yargs/locales/zh_CN.json new file mode 100644 index 0000000000000000000000000000000000000000..257d26babccd72cc3042db74b65a6339b7fa6172 --- /dev/null +++ b/node_modules/yargs/locales/zh_CN.json @@ -0,0 +1,48 @@ +{ + "Commands:": "命令:", + "Options:": "选项:", + "Examples:": "示例:", + "boolean": "布尔", + "count": "计数", + "string": "字符串", + "number": "数字", + "array": "数组", + "required": "必需", + "default": "默认值", + "default:": "默认值:", + "choices:": "可选值:", + "generated-value": "生成的值", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "缺少 non-option 参数:传入了 %s 个, 至少需要 %s 个", + "other": "缺少 non-option 参数:传入了 %s 个, 至少需要 %s 个" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "non-option 参数过多:传入了 %s 个, 最大允许 %s 个", + "other": "non-option 参数过多:传入了 %s 个, 最大允许 %s 个" + }, + "Missing argument value: %s": { + "one": "没有给此选项指定值:%s", + "other": "没有给这些选项指定值:%s" + }, + "Missing required argument: %s": { + "one": "缺少必须的选项:%s", + "other": "缺少这些必须的选项:%s" + }, + "Unknown argument: %s": { + "one": "无法识别的选项:%s", + "other": "无法识别这些选项:%s" + }, + "Invalid values:": "无效的选项值:", + "Argument: %s, Given: %s, Choices: %s": "选项名称: %s, 传入的值: %s, 可选的值:%s", + "Argument check failed: %s": "选项值验证失败:%s", + "Implications failed:": "缺少依赖的选项:", + "Not enough arguments following: %s": "没有提供足够的值给此选项:%s", + "Invalid JSON config file: %s": "无效的 JSON 配置文件:%s", + "Path to JSON config file": "JSON 配置文件的路径", + "Show help": "显示帮助信息", + "Show version number": "显示版本号", + "Did you mean %s?": "是指 %s?", + "Arguments %s and %s are mutually exclusive" : "选项 %s 和 %s 是互斥的", + "Positionals:": "位置:", + "command": "命令" +} diff --git a/node_modules/yargs/locales/zh_TW.json b/node_modules/yargs/locales/zh_TW.json new file mode 100644 index 0000000000000000000000000000000000000000..e38495d3a238525c8eb1372eac9d14bbd28a4eb8 --- /dev/null +++ b/node_modules/yargs/locales/zh_TW.json @@ -0,0 +1,51 @@ +{ + "Commands:": "命令:", + "Options:": "選項:", + "Examples:": "範例:", + "boolean": "布林", + "count": "次數", + "string": "字串", + "number": "數字", + "array": "陣列", + "required": "必填", + "default": "預設值", + "default:": "預設值:", + "choices:": "可選值:", + "aliases:": "別名:", + "generated-value": "生成的值", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "non-option 引數不足:只傳入了 %s 個, 至少要 %s 個", + "other": "non-option 引數不足:只傳入了 %s 個, 至少要 %s 個" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "non-option 引數過多:傳入了 %s 個, 但最多 %s 個", + "other": "non-option 引數過多:傳入了 %s 個, 但最多 %s 個" + }, + "Missing argument value: %s": { + "one": "此引數無指定值:%s", + "other": "這些引數無指定值:%s" + }, + "Missing required argument: %s": { + "one": "缺少必須的引數:%s", + "other": "缺少這些必須的引數:%s" + }, + "Unknown argument: %s": { + "one": "未知的引數:%s", + "other": "未知的引數:%s" + }, + "Invalid values:": "無效的選項值:", + "Argument: %s, Given: %s, Choices: %s": "引數名稱: %s, 傳入的值: %s, 可選的值:%s", + "Argument check failed: %s": "引數驗證失敗:%s", + "Implications failed:": "缺少依賴引數:", + "Not enough arguments following: %s": "沒有提供足夠的值給此引數:%s", + "Invalid JSON config file: %s": "無效的 JSON 設置文件:%s", + "Path to JSON config file": "JSON 設置文件的路徑", + "Show help": "顯示說明", + "Show version number": "顯示版本", + "Did you mean %s?": "您是指 %s 嗎?", + "Arguments %s and %s are mutually exclusive" : "引數 %s 和 %s 互斥", + "Positionals:": "位置:", + "command": "命令", + "deprecated": "已淘汰", + "deprecated: %s": "已淘汰:%s" + } diff --git a/node_modules/yargs/package.json b/node_modules/yargs/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d55f2bd27de53c322590e2ff6c8607a2de2e75f3 --- /dev/null +++ b/node_modules/yargs/package.json @@ -0,0 +1,103 @@ +{ + "name": "yargs", + "version": "18.0.0", + "description": "yargs the modern, pirate-themed, successor to optimist.", + "main": "./index.mjs", + "exports": { + "./package.json": "./package.json", + "./helpers": "./helpers/helpers.mjs", + "./browser": { + "types": "./browser.d.ts", + "import": "./browser.mjs" + }, + ".": "./index.mjs", + "./yargs": "./index.mjs" + }, + "type": "module", + "module": "./index.mjs", + "contributors": [ + { + "name": "Yargs Contributors", + "url": "https://github.com/yargs/yargs/graphs/contributors" + } + ], + "files": [ + "browser.mjs", + "browser.d.ts", + "helpers/*.js", + "helpers/*", + "index.mjs", + "build", + "locales", + "LICENSE", + "lib/platform-shims/*.mjs", + "!*.d.ts", + "!**/*.d.ts" + ], + "dependencies": { + "cliui": "^9.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "string-width": "^7.2.0", + "y18n": "^5.0.5", + "yargs-parser": "^22.0.0" + }, + "devDependencies": { + "@babel/eslint-parser": "^7.26.10", + "@babel/preset-typescript": "^7.26.0", + "@types/chai": "^4.2.11", + "@types/mocha": "^9.0.0", + "@types/node": "^20.0.0", + "@typescript-eslint/eslint-plugin": "^8.26.1", + "browserslist-generator": "^2.0.1", + "c8": "^9.1.0", + "chai": "^4.2.0", + "chalk": "^4.0.0", + "cpr": "^3.0.1", + "cross-env": "^7.0.2", + "cross-spawn": "^7.0.6", + "eslint": "^8.57.1", + "eslint-plugin-prettier": "^5.1.2", + "gts": "^5.2.0", + "hashish": "0.0.4", + "mocha": "^10.8.2", + "rimraf": "^3.0.2", + "typescript": "^5.8.3", + "which": "^2.0.0", + "yargs-test-extends": "^1.0.1" + }, + "scripts": { + "fix": "gts fix && npm run fix:js", + "fix:js": "eslint . --ext mjs --ext js --fix", + "posttest": "npm run check", + "test": "c8 mocha --enable-source-maps ./test/*.mjs --require ./test/before.mjs --timeout=24000 --check-leaks", + "test:esm": "c8 mocha --enable-source-maps ./test/esm/*.mjs --check-leaks", + "coverage": "c8 report --check-coverage", + "prepare": "npm run compile", + "pretest": "npm run compile -- -p tsconfig.test.json", + "compile": "rimraf build && tsc", + "check": "gts lint && npm run check:js", + "check:js": "eslint . --ext mjs --ext js", + "clean": "gts clean", + "watch": "rimraf build && npm:watch:tsc", + "watch:tsc": "tsc --watch" + }, + "repository": { + "type": "git", + "url": "https://github.com/yargs/yargs.git" + }, + "homepage": "https://yargs.js.org/", + "keywords": [ + "argument", + "args", + "option", + "parser", + "parsing", + "cli", + "command" + ], + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=23" + } +} diff --git a/node_modules/yocto-queue/index.d.ts b/node_modules/yocto-queue/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9541986b44c7169dfbc1764f06c4035881e870ac --- /dev/null +++ b/node_modules/yocto-queue/index.d.ts @@ -0,0 +1,56 @@ +declare class Queue implements Iterable { + /** + The size of the queue. + */ + readonly size: number; + + /** + Tiny queue data structure. + + The instance is an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols), which means you can iterate over the queue front to back with a “for…of” loop, or use spreading to convert the queue to an array. Don't do this unless you really need to though, since it's slow. + + @example + ``` + import Queue = require('yocto-queue'); + + const queue = new Queue(); + + queue.enqueue('🦄'); + queue.enqueue('🌈'); + + console.log(queue.size); + //=> 2 + + console.log(...queue); + //=> '🦄 🌈' + + console.log(queue.dequeue()); + //=> '🦄' + + console.log(queue.dequeue()); + //=> '🌈' + ``` + */ + constructor(); + + [Symbol.iterator](): IterableIterator; + + /** + Add a value to the queue. + */ + enqueue(value: ValueType): void; + + /** + Remove the next value in the queue. + + @returns The removed value or `undefined` if the queue is empty. + */ + dequeue(): ValueType | undefined; + + /** + Clear the queue. + */ + clear(): void; +} + +export = Queue; diff --git a/node_modules/yocto-queue/index.js b/node_modules/yocto-queue/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2f3e6dcd7299584287a2e2961e6affd2e36f9141 --- /dev/null +++ b/node_modules/yocto-queue/index.js @@ -0,0 +1,68 @@ +class Node { + /// value; + /// next; + + constructor(value) { + this.value = value; + + // TODO: Remove this when targeting Node.js 12. + this.next = undefined; + } +} + +class Queue { + // TODO: Use private class fields when targeting Node.js 12. + // #_head; + // #_tail; + // #_size; + + constructor() { + this.clear(); + } + + enqueue(value) { + const node = new Node(value); + + if (this._head) { + this._tail.next = node; + this._tail = node; + } else { + this._head = node; + this._tail = node; + } + + this._size++; + } + + dequeue() { + const current = this._head; + if (!current) { + return; + } + + this._head = this._head.next; + this._size--; + return current.value; + } + + clear() { + this._head = undefined; + this._tail = undefined; + this._size = 0; + } + + get size() { + return this._size; + } + + * [Symbol.iterator]() { + let current = this._head; + + while (current) { + yield current.value; + current = current.next; + } + } +} + +module.exports = Queue; diff --git a/node_modules/yocto-queue/license b/node_modules/yocto-queue/license new file mode 100644 index 0000000000000000000000000000000000000000..fa7ceba3eb4a9657a9db7f3ffca4e4e97a9019de --- /dev/null +++ b/node_modules/yocto-queue/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/yocto-queue/package.json b/node_modules/yocto-queue/package.json new file mode 100644 index 0000000000000000000000000000000000000000..71a91017b6ee77b63075fee64993d931e33cd7ea --- /dev/null +++ b/node_modules/yocto-queue/package.json @@ -0,0 +1,43 @@ +{ + "name": "yocto-queue", + "version": "0.1.0", + "description": "Tiny queue data structure", + "license": "MIT", + "repository": "sindresorhus/yocto-queue", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "queue", + "data", + "structure", + "algorithm", + "queues", + "queuing", + "list", + "array", + "linkedlist", + "fifo", + "enqueue", + "dequeue", + "data-structure" + ], + "devDependencies": { + "ava": "^2.4.0", + "tsd": "^0.13.1", + "xo": "^0.35.0" + } +} diff --git a/node_modules/yocto-queue/readme.md b/node_modules/yocto-queue/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..c72fefc486d495eb9a51c2a38a1245fc7dae18fc --- /dev/null +++ b/node_modules/yocto-queue/readme.md @@ -0,0 +1,64 @@ +# yocto-queue [![](https://badgen.net/bundlephobia/minzip/yocto-queue)](https://bundlephobia.com/result?p=yocto-queue) + +> Tiny queue data structure + +You should use this package instead of an array if you do a lot of `Array#push()` and `Array#shift()` on large arrays, since `Array#shift()` has [linear time complexity](https://medium.com/@ariel.salem1989/an-easy-to-use-guide-to-big-o-time-complexity-5dcf4be8a444#:~:text=O(N)%E2%80%94Linear%20Time) *O(n)* while `Queue#dequeue()` has [constant time complexity](https://medium.com/@ariel.salem1989/an-easy-to-use-guide-to-big-o-time-complexity-5dcf4be8a444#:~:text=O(1)%20%E2%80%94%20Constant%20Time) *O(1)*. That makes a huge difference for large arrays. + +> A [queue](https://en.wikipedia.org/wiki/Queue_(abstract_data_type)) is an ordered list of elements where an element is inserted at the end of the queue and is removed from the front of the queue. A queue works based on the first-in, first-out ([FIFO](https://en.wikipedia.org/wiki/FIFO_(computing_and_electronics))) principle. + +## Install + +``` +$ npm install yocto-queue +``` + +## Usage + +```js +const Queue = require('yocto-queue'); + +const queue = new Queue(); + +queue.enqueue('🦄'); +queue.enqueue('🌈'); + +console.log(queue.size); +//=> 2 + +console.log(...queue); +//=> '🦄 🌈' + +console.log(queue.dequeue()); +//=> '🦄' + +console.log(queue.dequeue()); +//=> '🌈' +``` + +## API + +### `queue = new Queue()` + +The instance is an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols), which means you can iterate over the queue front to back with a “for…of” loop, or use spreading to convert the queue to an array. Don't do this unless you really need to though, since it's slow. + +#### `.enqueue(value)` + +Add a value to the queue. + +#### `.dequeue()` + +Remove the next value in the queue. + +Returns the removed value or `undefined` if the queue is empty. + +#### `.clear()` + +Clear the queue. + +#### `.size` + +The size of the queue. + +## Related + +- [quick-lru](https://github.com/sindresorhus/quick-lru) - Simple “Least Recently Used” (LRU) cache diff --git a/node_modules/yoga-layout/README.md b/node_modules/yoga-layout/README.md new file mode 100644 index 0000000000000000000000000000000000000000..da4fe27f58fec33151ba724ef06a18540bbc9c71 --- /dev/null +++ b/node_modules/yoga-layout/README.md @@ -0,0 +1,40 @@ +# yoga-layout + +This package provides prebuilt WebAssembly bindings for the Yoga layout engine. + +See more at https://yogalayout.dev + +## Usage + +```ts +import {Yoga, Align} from 'yoga-layout'; + +const node = Yoga.Node.create(); +node.setAlignContent(Align.Center); +``` + +Objects created by `Yoga.<>.create()` are not automatically garbage collected and should be freed once they are no longer in use. + +```ts +// Free a config +config.free(); + +// Free a tree of Nodes +node.freeRecursive(); + +// Free a single Node +node.free(); +``` + +## Requirements + +`yoga-layout` requires a toolchain that supports ES Modules and top-level await. + +If top-level-await is not supported, use the `yoga-layout/load` entry point instead. This requires to load yoga manually: + +```ts +import {loadYoga, Align} from 'yoga-layout/load'; + +const node = (await loadYoga).Node.create(); +node.setAlignContent(Align.Center); +``` diff --git a/node_modules/yoga-layout/package.json b/node_modules/yoga-layout/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1fb0482c9451d745ca010f9c1ad58f5d0f74a559 --- /dev/null +++ b/node_modules/yoga-layout/package.json @@ -0,0 +1,53 @@ +{ + "name": "yoga-layout", + "version": "3.2.1", + "description": "An embeddable and performant flexbox layout engine with bindings for multiple languages", + "license": "MIT", + "author": "Meta Open Source", + "homepage": "https://yogalayout.dev/", + "repository": { + "type": "git", + "url": "git@github.com:facebook/yoga.git" + }, + "type": "module", + "main": "./dist/src/index.js", + "types": "./dist/src/index.d.ts", + "exports": { + ".": "./dist/src/index.js", + "./load": "./dist/src/load.js" + }, + "files": [ + "dist/binaries/**", + "dist/src/**", + "src/**" + ], + "scripts": { + "benchmark": "just benchmark --config just.config.cjs", + "build": "just build --config just.config.cjs", + "clang-format": "just clang-format --config just.config.cjs", + "clang-format:fix": "just clang-format --fix --config just.config.cjs", + "clean": "just clean --config just.config.cjs", + "lint": "eslint .", + "lint:fix": "eslint . --fix", + "prepack": "just prepack --config just.config.cjs", + "test": "just test --config just.config.cjs", + "tsc": "tsc --noEmit" + }, + "devDependencies": { + "@babel/cli": "^7.23.0", + "@babel/core": "^7.23.0", + "@babel/preset-env": "^7.23.0", + "@babel/preset-typescript": "^7.23.0", + "@types/jest": "^29.5.1", + "@types/node": "^16.18.25", + "@types/which": "^3.0.0", + "@yogalayout/cmake-bin": "3.28.0-1", + "babel-register-esm": "^1.2.5", + "clang-format": "^1.8.0", + "glob": "^10.4.2", + "jest": "^29.3.1", + "just-scripts": "^2.1.0", + "ninja-binaries": "^1.11.1", + "which": "^3.0.0" + } +} \ No newline at end of file diff --git a/node_modules/yoga-layout/src/Config.cpp b/node_modules/yoga-layout/src/Config.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d9313d8e38aa15186d8a8b47c53be674a4baa9be --- /dev/null +++ b/node_modules/yoga-layout/src/Config.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include "./Config.h" + +/* static */ Config* Config::create(void) { + return new Config(); +} + +/* static */ void Config::destroy(Config* node) { + delete node; +} + +Config::Config(void) : m_config(YGConfigNew()) {} + +Config::~Config(void) { + YGConfigFree(m_config); +} + +void Config::setExperimentalFeatureEnabled(int feature, bool enabled) { + YGConfigSetExperimentalFeatureEnabled( + m_config, static_cast(feature), enabled); +} + +void Config::setPointScaleFactor(float pixelsInPoint) { + YGConfigSetPointScaleFactor(m_config, pixelsInPoint); +} + +void Config::setErrata(int errata) { + YGConfigSetErrata(m_config, static_cast(errata)); +} + +void Config::setUseWebDefaults(bool useWebDefaults) { + YGConfigSetUseWebDefaults(m_config, useWebDefaults); +} + +bool Config::isExperimentalFeatureEnabled(int feature) const { + return YGConfigIsExperimentalFeatureEnabled( + m_config, static_cast(feature)); +} + +int Config::getErrata() const { + return static_cast(YGConfigGetErrata(m_config)); +} + +bool Config::useWebDefaults() const { + return YGConfigGetUseWebDefaults(m_config); +} diff --git a/node_modules/yoga-layout/src/Config.h b/node_modules/yoga-layout/src/Config.h new file mode 100644 index 0000000000000000000000000000000000000000..cc1441fee14cefedcccf9e980b00ecb3e00dd72e --- /dev/null +++ b/node_modules/yoga-layout/src/Config.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +class Config { + friend class Node; + + public: + static Config* create(void); + + static void destroy(Config* config); + + private: + Config(void); + + public: + ~Config(void); + + public: // Prevent accidental copy + Config(Config const&) = delete; + + Config const& operator=(Config const&) = delete; + + public: // Setters + void setExperimentalFeatureEnabled(int feature, bool enabled); + void setPointScaleFactor(float pixelsInPoint); + void setErrata(int errata); + void setUseWebDefaults(bool useWebDefaults); + + public: // Getters + bool isExperimentalFeatureEnabled(int feature) const; + int getErrata() const; + bool useWebDefaults() const; + + private: + YGConfigRef m_config; +}; diff --git a/node_modules/yoga-layout/src/Layout.h b/node_modules/yoga-layout/src/Layout.h new file mode 100644 index 0000000000000000000000000000000000000000..72380afe83e9172e340cac5da509732c0aeb9495 --- /dev/null +++ b/node_modules/yoga-layout/src/Layout.h @@ -0,0 +1,19 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +struct Layout { + double left; + double right; + + double top; + double bottom; + + double width; + double height; +}; diff --git a/node_modules/yoga-layout/src/Node.cpp b/node_modules/yoga-layout/src/Node.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f5c6a866519929054063abc12c81532a3ea6322f --- /dev/null +++ b/node_modules/yoga-layout/src/Node.cpp @@ -0,0 +1,507 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include + +#include "./Config.h" +#include "./Layout.h" +#include "./Node.h" +#include "./Size.h" + +static YGSize globalMeasureFunc( + YGNodeConstRef nodeRef, + float width, + YGMeasureMode widthMode, + float height, + YGMeasureMode heightMode) { + Node const& node = *reinterpret_cast(YGNodeGetContext(nodeRef)); + + Size size = node.callMeasureFunc(width, widthMode, height, heightMode); + YGSize ygSize = { + static_cast(size.width), static_cast(size.height)}; + + return ygSize; +} + +static void globalDirtiedFunc(YGNodeConstRef nodeRef) { + Node const& node = *reinterpret_cast(YGNodeGetContext(nodeRef)); + + node.callDirtiedFunc(); +} + +/* static */ Node* Node::createDefault(void) { + return new Node(nullptr); +} + +/* static */ Node* Node::createWithConfig(Config* config) { + return new Node(config); +} + +/* static */ void Node::destroy(Node* node) { + delete node; +} + +/* static */ Node* Node::fromYGNode(YGNodeRef nodeRef) { + return reinterpret_cast(YGNodeGetContext(nodeRef)); +} + +Node::Node(Config* config) + : m_node( + config != nullptr ? YGNodeNewWithConfig(config->m_config) + : YGNodeNew()), + m_measureFunc(nullptr), + m_dirtiedFunc(nullptr) { + YGNodeSetContext(m_node, reinterpret_cast(this)); +} + +Node::~Node(void) { + YGNodeFree(m_node); +} + +void Node::reset(void) { + m_measureFunc.reset(nullptr); + m_dirtiedFunc.reset(nullptr); + + YGNodeReset(m_node); +} + +void Node::copyStyle(Node const& other) { + YGNodeCopyStyle(m_node, other.m_node); +} + +void Node::setBoxSizing(int boxSizing) { + YGNodeStyleSetBoxSizing(m_node, static_cast(boxSizing)); +} + +void Node::setPositionType(int positionType) { + YGNodeStyleSetPositionType(m_node, static_cast(positionType)); +} + +void Node::setPosition(int edge, double position) { + YGNodeStyleSetPosition(m_node, static_cast(edge), position); +} + +void Node::setPositionPercent(int edge, double position) { + YGNodeStyleSetPositionPercent(m_node, static_cast(edge), position); +} + +void Node::setPositionAuto(int edge) { + YGNodeStyleSetPositionAuto(m_node, static_cast(edge)); +} + +void Node::setAlignContent(int alignContent) { + YGNodeStyleSetAlignContent(m_node, static_cast(alignContent)); +} + +void Node::setAlignItems(int alignItems) { + YGNodeStyleSetAlignItems(m_node, static_cast(alignItems)); +} + +void Node::setAlignSelf(int alignSelf) { + YGNodeStyleSetAlignSelf(m_node, static_cast(alignSelf)); +} + +void Node::setFlexDirection(int flexDirection) { + YGNodeStyleSetFlexDirection( + m_node, static_cast(flexDirection)); +} + +void Node::setDirection(int direction) { + YGNodeStyleSetDirection(m_node, static_cast(direction)); +} + +void Node::setFlexWrap(int flexWrap) { + YGNodeStyleSetFlexWrap(m_node, static_cast(flexWrap)); +} + +void Node::setJustifyContent(int justifyContent) { + YGNodeStyleSetJustifyContent(m_node, static_cast(justifyContent)); +} + +void Node::setMargin(int edge, double margin) { + YGNodeStyleSetMargin(m_node, static_cast(edge), margin); +} + +void Node::setMarginPercent(int edge, double margin) { + YGNodeStyleSetMarginPercent(m_node, static_cast(edge), margin); +} + +void Node::setMarginAuto(int edge) { + YGNodeStyleSetMarginAuto(m_node, static_cast(edge)); +} + +void Node::setOverflow(int overflow) { + YGNodeStyleSetOverflow(m_node, static_cast(overflow)); +} + +void Node::setDisplay(int display) { + YGNodeStyleSetDisplay(m_node, static_cast(display)); +} + +void Node::setFlex(double flex) { + YGNodeStyleSetFlex(m_node, flex); +} + +void Node::setFlexBasis(double flexBasis) { + YGNodeStyleSetFlexBasis(m_node, flexBasis); +} + +void Node::setFlexBasisPercent(double flexBasis) { + YGNodeStyleSetFlexBasisPercent(m_node, flexBasis); +} + +void Node::setFlexBasisAuto() { + YGNodeStyleSetFlexBasisAuto(m_node); +} + +void Node::setFlexGrow(double flexGrow) { + YGNodeStyleSetFlexGrow(m_node, flexGrow); +} + +void Node::setFlexShrink(double flexShrink) { + YGNodeStyleSetFlexShrink(m_node, flexShrink); +} + +void Node::setWidth(double width) { + YGNodeStyleSetWidth(m_node, width); +} + +void Node::setWidthPercent(double width) { + YGNodeStyleSetWidthPercent(m_node, width); +} + +void Node::setWidthAuto() { + YGNodeStyleSetWidthAuto(m_node); +} + +void Node::setHeight(double height) { + YGNodeStyleSetHeight(m_node, height); +} + +void Node::setHeightPercent(double height) { + YGNodeStyleSetHeightPercent(m_node, height); +} + +void Node::setHeightAuto() { + YGNodeStyleSetHeightAuto(m_node); +} + +void Node::setMinWidth(double minWidth) { + YGNodeStyleSetMinWidth(m_node, minWidth); +} + +void Node::setMinWidthPercent(double minWidth) { + YGNodeStyleSetMinWidthPercent(m_node, minWidth); +} + +void Node::setMinHeight(double minHeight) { + YGNodeStyleSetMinHeight(m_node, minHeight); +} + +void Node::setMinHeightPercent(double minHeight) { + YGNodeStyleSetMinHeightPercent(m_node, minHeight); +} + +void Node::setMaxWidth(double maxWidth) { + YGNodeStyleSetMaxWidth(m_node, maxWidth); +} + +void Node::setMaxWidthPercent(double maxWidth) { + YGNodeStyleSetMaxWidthPercent(m_node, maxWidth); +} + +void Node::setMaxHeight(double maxHeight) { + YGNodeStyleSetMaxHeight(m_node, maxHeight); +} + +void Node::setMaxHeightPercent(double maxHeight) { + YGNodeStyleSetMaxHeightPercent(m_node, maxHeight); +} + +void Node::setAspectRatio(double aspectRatio) { + YGNodeStyleSetAspectRatio(m_node, aspectRatio); +} + +void Node::setBorder(int edge, double border) { + YGNodeStyleSetBorder(m_node, static_cast(edge), border); +} + +void Node::setPadding(int edge, double padding) { + YGNodeStyleSetPadding(m_node, static_cast(edge), padding); +} + +void Node::setPaddingPercent(int edge, double padding) { + YGNodeStyleSetPaddingPercent(m_node, static_cast(edge), padding); +} + +void Node::setIsReferenceBaseline(bool isReferenceBaseline) { + YGNodeSetIsReferenceBaseline(m_node, isReferenceBaseline); +} + +void Node::setGap(int gutter, double gapLength) { + YGNodeStyleSetGap(m_node, static_cast(gutter), gapLength); +} + +void Node::setGapPercent(int gutter, double gapLength) { + YGNodeStyleSetGapPercent(m_node, static_cast(gutter), gapLength); +} + +int Node::getBoxSizing(void) const { + return YGNodeStyleGetBoxSizing(m_node); +} + +int Node::getPositionType(void) const { + return YGNodeStyleGetPositionType(m_node); +} + +Value Node::getPosition(int edge) const { + return Value::fromYGValue( + YGNodeStyleGetPosition(m_node, static_cast(edge))); +} + +int Node::getAlignContent(void) const { + return YGNodeStyleGetAlignContent(m_node); +} + +int Node::getAlignItems(void) const { + return YGNodeStyleGetAlignItems(m_node); +} + +int Node::getAlignSelf(void) const { + return YGNodeStyleGetAlignSelf(m_node); +} + +int Node::getFlexDirection(void) const { + return YGNodeStyleGetFlexDirection(m_node); +} + +int Node::getDirection(void) const { + return YGNodeStyleGetDirection(m_node); +} + +int Node::getFlexWrap(void) const { + return YGNodeStyleGetFlexWrap(m_node); +} + +int Node::getJustifyContent(void) const { + return YGNodeStyleGetJustifyContent(m_node); +} + +Value Node::getMargin(int edge) const { + return Value::fromYGValue( + YGNodeStyleGetMargin(m_node, static_cast(edge))); +} + +int Node::getOverflow(void) const { + return YGNodeStyleGetOverflow(m_node); +} + +int Node::getDisplay(void) const { + return YGNodeStyleGetDisplay(m_node); +} + +Value Node::getFlexBasis(void) const { + return Value::fromYGValue(YGNodeStyleGetFlexBasis(m_node)); +} + +double Node::getFlexGrow(void) const { + return YGNodeStyleGetFlexGrow(m_node); +} + +double Node::getFlexShrink(void) const { + return YGNodeStyleGetFlexShrink(m_node); +} + +Value Node::getWidth(void) const { + return Value::fromYGValue(YGNodeStyleGetWidth(m_node)); +} + +Value Node::getHeight(void) const { + return Value::fromYGValue(YGNodeStyleGetHeight(m_node)); +} + +Value Node::getMinWidth(void) const { + return Value::fromYGValue(YGNodeStyleGetMinWidth(m_node)); +} + +Value Node::getMinHeight(void) const { + return Value::fromYGValue(YGNodeStyleGetMinHeight(m_node)); +} + +Value Node::getMaxWidth(void) const { + return Value::fromYGValue(YGNodeStyleGetMaxWidth(m_node)); +} + +Value Node::getMaxHeight(void) const { + return Value::fromYGValue(YGNodeStyleGetMaxHeight(m_node)); +} + +double Node::getAspectRatio(void) const { + return YGNodeStyleGetAspectRatio(m_node); +} + +double Node::getBorder(int edge) const { + return YGNodeStyleGetBorder(m_node, static_cast(edge)); +} + +Value Node::getPadding(int edge) const { + return Value::fromYGValue( + YGNodeStyleGetPadding(m_node, static_cast(edge))); +} + +float Node::getGap(int gutter) { + return YGNodeStyleGetGap(m_node, static_cast(gutter)); +} + +bool Node::isReferenceBaseline() { + return YGNodeIsReferenceBaseline(m_node); +} + +void Node::insertChild(Node* child, unsigned index) { + YGNodeInsertChild(m_node, child->m_node, index); +} + +void Node::removeChild(Node* child) { + YGNodeRemoveChild(m_node, child->m_node); +} + +unsigned Node::getChildCount(void) const { + return YGNodeGetChildCount(m_node); +} + +Node* Node::getParent(void) { + auto nodePtr = YGNodeGetParent(m_node); + + if (nodePtr == nullptr) + return nullptr; + + return Node::fromYGNode(nodePtr); +} + +Node* Node::getChild(unsigned index) { + auto nodePtr = YGNodeGetChild(m_node, index); + + if (nodePtr == nullptr) + return nullptr; + + return Node::fromYGNode(nodePtr); +} + +void Node::setMeasureFunc(MeasureCallback* measureFunc) { + m_measureFunc.reset(measureFunc); + + YGNodeSetMeasureFunc(m_node, &globalMeasureFunc); +} + +void Node::unsetMeasureFunc(void) { + m_measureFunc.reset(nullptr); + + YGNodeSetMeasureFunc(m_node, nullptr); +} + +Size Node::callMeasureFunc( + double width, + int widthMode, + double height, + int heightMode) const { + return m_measureFunc->measure(width, widthMode, height, heightMode); +} + +void Node::setDirtiedFunc(DirtiedCallback* dirtiedFunc) { + m_dirtiedFunc.reset(dirtiedFunc); + + YGNodeSetDirtiedFunc(m_node, &globalDirtiedFunc); +} + +void Node::unsetDirtiedFunc(void) { + m_dirtiedFunc.reset(nullptr); + + YGNodeSetDirtiedFunc(m_node, nullptr); +} + +void Node::callDirtiedFunc(void) const { + m_dirtiedFunc->dirtied(); +} + +void Node::markDirty(void) { + YGNodeMarkDirty(m_node); +} + +bool Node::isDirty(void) const { + return YGNodeIsDirty(m_node); +} + +void Node::markLayoutSeen() { + YGNodeSetHasNewLayout(m_node, false); +} + +bool Node::hasNewLayout(void) const { + return YGNodeGetHasNewLayout(m_node); +} + +void Node::calculateLayout(double width, double height, int direction) { + YGNodeCalculateLayout( + m_node, width, height, static_cast(direction)); +} + +double Node::getComputedLeft(void) const { + return YGNodeLayoutGetLeft(m_node); +} + +double Node::getComputedRight(void) const { + return YGNodeLayoutGetRight(m_node); +} + +double Node::getComputedTop(void) const { + return YGNodeLayoutGetTop(m_node); +} + +double Node::getComputedBottom(void) const { + return YGNodeLayoutGetBottom(m_node); +} + +double Node::getComputedWidth(void) const { + return YGNodeLayoutGetWidth(m_node); +} + +double Node::getComputedHeight(void) const { + return YGNodeLayoutGetHeight(m_node); +} + +Layout Node::getComputedLayout(void) const { + Layout layout; + + layout.left = YGNodeLayoutGetLeft(m_node); + layout.right = YGNodeLayoutGetRight(m_node); + + layout.top = YGNodeLayoutGetTop(m_node); + layout.bottom = YGNodeLayoutGetBottom(m_node); + + layout.width = YGNodeLayoutGetWidth(m_node); + layout.height = YGNodeLayoutGetHeight(m_node); + + return layout; +} + +double Node::getComputedMargin(int edge) const { + return YGNodeLayoutGetMargin(m_node, static_cast(edge)); +} + +double Node::getComputedBorder(int edge) const { + return YGNodeLayoutGetBorder(m_node, static_cast(edge)); +} + +double Node::getComputedPadding(int edge) const { + return YGNodeLayoutGetPadding(m_node, static_cast(edge)); +} + +void Node::setAlwaysFormsContainingBlock(bool alwaysFormsContainingBlock) { + return YGNodeSetAlwaysFormsContainingBlock( + m_node, alwaysFormsContainingBlock); +} diff --git a/node_modules/yoga-layout/src/Node.h b/node_modules/yoga-layout/src/Node.h new file mode 100644 index 0000000000000000000000000000000000000000..c30f1d2dedda86716f9323df5e66e978905f4d2c --- /dev/null +++ b/node_modules/yoga-layout/src/Node.h @@ -0,0 +1,239 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +#include +#include + +#include "./Config.h" +#include "./Layout.h" +#include "./Size.h" +#include "./Value.h" + +class MeasureCallback { + public: + virtual ~MeasureCallback() {} + virtual Size + measure(float width, int widthMode, float height, int heightMode) = 0; +}; + +class MeasureCallbackWrapper : public emscripten::wrapper { + public: + EMSCRIPTEN_WRAPPER(MeasureCallbackWrapper); + Size measure(float width, int widthMode, float height, int heightMode) { + return call("measure", width, widthMode, height, heightMode); + } +}; + +class DirtiedCallback { + public: + virtual ~DirtiedCallback() {} + virtual void dirtied() = 0; +}; + +class DirtiedCallbackWrapper : public emscripten::wrapper { + public: + EMSCRIPTEN_WRAPPER(DirtiedCallbackWrapper); + void dirtied() { + return call("dirtied"); + } +}; + +class Node { + public: + static Node* createDefault(void); + static Node* createWithConfig(Config* config); + + static void destroy(Node* node); + + public: + static Node* fromYGNode(YGNodeRef nodeRef); + + private: + Node(Config* config); + + public: + ~Node(void); + + public: // Prevent accidental copy + Node(Node const&) = delete; + + Node const& operator=(Node const&) = delete; + + public: + void reset(void); + + public: // Style setters + void copyStyle(Node const& other); + + void setPositionType(int positionType); + void setPosition(int edge, double position); + void setPositionPercent(int edge, double position); + void setPositionAuto(int edge); + + void setAlignContent(int alignContent); + void setAlignItems(int alignItems); + void setAlignSelf(int alignSelf); + void setFlexDirection(int flexDirection); + void setFlexWrap(int flexWrap); + void setJustifyContent(int justifyContent); + void setDirection(int direction); + + void setMargin(int edge, double margin); + void setMarginPercent(int edge, double margin); + void setMarginAuto(int edge); + + void setOverflow(int overflow); + void setDisplay(int display); + + void setFlex(double flex); + void setFlexBasis(double flexBasis); + void setFlexBasisPercent(double flexBasis); + void setFlexBasisAuto(); + void setFlexGrow(double flexGrow); + void setFlexShrink(double flexShrink); + + void setWidth(double width); + void setWidthPercent(double width); + void setWidthAuto(); + void setHeight(double height); + void setHeightPercent(double height); + void setHeightAuto(); + + void setMinWidth(double minWidth); + void setMinWidthPercent(double minWidth); + void setMinHeight(double minHeight); + void setMinHeightPercent(double minHeight); + + void setMaxWidth(double maxWidth); + void setMaxWidthPercent(double maxWidth); + void setMaxHeight(double maxHeight); + void setMaxHeightPercent(double maxHeight); + + void setAspectRatio(double aspectRatio); + + void setBorder(int edge, double border); + + void setPadding(int edge, double padding); + void setPaddingPercent(int edge, double padding); + + void setGap(int gutter, double gapLength); + void setGapPercent(int gutter, double gapLength); + + void setBoxSizing(int boxSizing); + + public: // Style getters + int getPositionType(void) const; + Value getPosition(int edge) const; + + int getAlignContent(void) const; + int getAlignItems(void) const; + int getAlignSelf(void) const; + int getFlexDirection(void) const; + int getFlexWrap(void) const; + int getJustifyContent(void) const; + int getDirection(void) const; + + Value getMargin(int edge) const; + + int getOverflow(void) const; + int getDisplay(void) const; + + Value getFlexBasis(void) const; + double getFlexGrow(void) const; + double getFlexShrink(void) const; + + Value getWidth(void) const; + Value getHeight(void) const; + + Value getMinWidth(void) const; + Value getMinHeight(void) const; + + Value getMaxWidth(void) const; + Value getMaxHeight(void) const; + + double getAspectRatio(void) const; + + double getBorder(int edge) const; + + Value getPadding(int edge) const; + + float getGap(int gutter); + + int getBoxSizing(void) const; + + public: // Tree hierarchy mutators + void insertChild(Node* child, unsigned index); + void removeChild(Node* child); + + public: // Tree hierarchy inspectors + unsigned getChildCount(void) const; + + // The following functions cannot be const because they could discard const + // qualifiers (ex: constNode->getChild(0)->getParent() wouldn't be const) + + Node* getParent(void); + Node* getChild(unsigned index); + + public: // Measure func mutators + void setMeasureFunc(MeasureCallback* measureFunc); + void unsetMeasureFunc(void); + + public: // Measure func inspectors + Size callMeasureFunc( + double width, + int widthMode, + double height, + int heightMode) const; + + public: // Dirtied func mutators + void setDirtiedFunc(DirtiedCallback* dirtiedFunc); + void unsetDirtiedFunc(void); + + public: // Dirtied func inspectors + void callDirtiedFunc(void) const; + + public: // Dirtiness accessors + void markDirty(void); + bool isDirty(void) const; + void markLayoutSeen(); + bool hasNewLayout(void) const; + + public: // Layout mutators + void calculateLayout(double width, double height, int direction); + + public: // Layout inspectors + double getComputedLeft(void) const; + double getComputedRight(void) const; + + double getComputedTop(void) const; + double getComputedBottom(void) const; + + double getComputedWidth(void) const; + double getComputedHeight(void) const; + + Layout getComputedLayout(void) const; + + double getComputedMargin(int edge) const; + double getComputedBorder(int edge) const; + double getComputedPadding(int edge) const; + + public: + void setIsReferenceBaseline(bool isReferenceBaseline); + bool isReferenceBaseline(); + + YGNodeRef m_node; + + std::unique_ptr m_measureFunc; + std::unique_ptr m_dirtiedFunc; + + public: + void setAlwaysFormsContainingBlock(bool alwaysFormContainingBlock); +}; diff --git a/node_modules/yoga-layout/src/Size.h b/node_modules/yoga-layout/src/Size.h new file mode 100644 index 0000000000000000000000000000000000000000..c42bb90ac7d771a195842f66b11b4b39779652a2 --- /dev/null +++ b/node_modules/yoga-layout/src/Size.h @@ -0,0 +1,17 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +struct Size { + double width; + double height; + + Size(void) : width(0.0), height(0.0) {} + + Size(double width, double height) : width(width), height(height) {} +}; diff --git a/node_modules/yoga-layout/src/Value.h b/node_modules/yoga-layout/src/Value.h new file mode 100644 index 0000000000000000000000000000000000000000..2a37d0e90a6343a1c5b261139522f9dd8f7b2225 --- /dev/null +++ b/node_modules/yoga-layout/src/Value.h @@ -0,0 +1,23 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +struct Value { + static Value fromYGValue(YGValue const& ygValue) { + return Value(static_cast(ygValue.unit), ygValue.value); + } + + int unit; + double value; + + Value(void) : unit(YGUnitUndefined), value(0.0) {} + + Value(int unit, double value) : unit(unit), value(value) {} +}; diff --git a/node_modules/yoga-layout/src/embind.cpp b/node_modules/yoga-layout/src/embind.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d1789788cfebbd1a4d956fb82e47f8d5244f9814 --- /dev/null +++ b/node_modules/yoga-layout/src/embind.cpp @@ -0,0 +1,207 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include "./Config.h" +#include "./Layout.h" +#include "./Node.h" +#include "./Size.h" +#include "./Value.h" + +#include +#include + +using namespace emscripten; + +EMSCRIPTEN_BINDINGS(YOGA_LAYOUT) { + class_("MeasureCallback") + .function("measure", &MeasureCallback::measure, pure_virtual()) + .allow_subclass("MeasureCallbackWrapper"); + class_("DirtiedCallback") + .function("dirtied", &DirtiedCallback::dirtied, pure_virtual()) + .allow_subclass("DirtiedCallbackWrapper"); + + class_("Config") + .constructor<>(&Config::create, allow_raw_pointers()) + .class_function<>("create", &Config::create, allow_raw_pointers()) + .class_function<>("destroy", &Config::destroy, allow_raw_pointers()) + .function( + "setExperimentalFeatureEnabled", + &Config::setExperimentalFeatureEnabled) + .function("setPointScaleFactor", &Config::setPointScaleFactor) + .function("setErrata", &Config::setErrata) + .function("setUseWebDefaults", &Config::setUseWebDefaults) + .function( + "isExperimentalFeatureEnabled", &Config::isExperimentalFeatureEnabled) + .function("getErrata", &Config::getErrata) + .function("useWebDefaults", &Config::useWebDefaults); + + value_object("Layout") + .field("left", &Layout::left) + .field("right", &Layout::right) + .field("top", &Layout::top) + .field("bottom", &Layout::bottom) + .field("width", &Layout::width) + .field("height", &Layout::height); + + value_object("Size") + .field("width", &Size::width) + .field("height", &Size::height); + + value_object("Value") + .field("value", &Value::value) + .field("unit", &Value::unit); + + class_("Node") + .constructor<>(&Node::createDefault, allow_raw_pointers()) + + .class_function<>( + "createDefault", &Node::createDefault, allow_raw_pointers()) + .class_function<>( + "createWithConfig", &Node::createWithConfig, allow_raw_pointers()) + .class_function<>("destroy", &Node::destroy, allow_raw_pointers()) + .function("reset", &Node::reset) + + .function("copyStyle", &Node::copyStyle) + + .function("setPositionType", &Node::setPositionType) + .function("setPosition", &Node::setPosition) + .function("setPositionPercent", &Node::setPositionPercent) + .function("setPositionAuto", &Node::setPositionAuto) + + .function("setAlignContent", &Node::setAlignContent) + .function("setAlignItems", &Node::setAlignItems) + .function("setAlignSelf", &Node::setAlignSelf) + .function("setFlexDirection", &Node::setFlexDirection) + .function("setFlexWrap", &Node::setFlexWrap) + .function("setJustifyContent", &Node::setJustifyContent) + + .function("setMargin", &Node::setMargin) + .function("setMarginPercent", &Node::setMarginPercent) + .function("setMarginAuto", &Node::setMarginAuto) + + .function("setOverflow", &Node::setOverflow) + .function("setDisplay", &Node::setDisplay) + + .function("setFlex", &Node::setFlex) + .function("setFlexBasis", &Node::setFlexBasis) + .function("setFlexBasisPercent", &Node::setFlexBasisPercent) + .function("setFlexBasisAuto", &Node::setFlexBasisAuto) + .function("setFlexGrow", &Node::setFlexGrow) + .function("setFlexShrink", &Node::setFlexShrink) + + .function("setWidth", &Node::setWidth) + .function("setWidthPercent", &Node::setWidthPercent) + .function("setWidthAuto", &Node::setWidthAuto) + .function("setHeight", &Node::setHeight) + .function("setHeightPercent", &Node::setHeightPercent) + .function("setHeightAuto", &Node::setHeightAuto) + + .function("setMinWidth", &Node::setMinWidth) + .function("setMinWidthPercent", &Node::setMinWidthPercent) + .function("setMinHeight", &Node::setMinHeight) + .function("setMinHeightPercent", &Node::setMinHeightPercent) + + .function("setMaxWidth", &Node::setMaxWidth) + .function("setMaxWidthPercent", &Node::setMaxWidthPercent) + .function("setMaxHeight", &Node::setMaxHeight) + .function("setMaxHeightPercent", &Node::setMaxHeightPercent) + + .function("setBoxSizing", &Node::setBoxSizing) + + .function("setAspectRatio", &Node::setAspectRatio) + + .function("setBorder", &Node::setBorder) + + .function("setPadding", &Node::setPadding) + .function("setPaddingPercent", &Node::setPaddingPercent) + .function("setGap", &Node::setGap) + .function("setGapPercent", &Node::setGapPercent) + + .function("setDirection", &Node::setDirection) + + .function("getPositionType", &Node::getPositionType) + .function("getPosition", &Node::getPosition) + + .function("getAlignContent", &Node::getAlignContent) + .function("getAlignItems", &Node::getAlignItems) + .function("getAlignSelf", &Node::getAlignSelf) + .function("getFlexDirection", &Node::getFlexDirection) + .function("getFlexWrap", &Node::getFlexWrap) + .function("getJustifyContent", &Node::getJustifyContent) + + .function("getMargin", &Node::getMargin) + + .function("getFlexBasis", &Node::getFlexBasis) + .function("getFlexGrow", &Node::getFlexGrow) + .function("getFlexShrink", &Node::getFlexShrink) + + .function("getWidth", &Node::getWidth) + .function("getHeight", &Node::getHeight) + + .function("getMinWidth", &Node::getMinWidth) + .function("getMinHeight", &Node::getMinHeight) + + .function("getMaxWidth", &Node::getMaxWidth) + .function("getMaxHeight", &Node::getMaxHeight) + + .function("getBoxSizing", &Node::getBoxSizing) + + .function("getAspectRatio", &Node::getAspectRatio) + + .function("getBorder", &Node::getBorder) + + .function("getOverflow", &Node::getOverflow) + .function("getDisplay", &Node::getDisplay) + + .function("getPadding", &Node::getPadding) + .function("getGap", &Node::getGap) + + .function("insertChild", &Node::insertChild, allow_raw_pointers()) + .function("removeChild", &Node::removeChild, allow_raw_pointers()) + + .function("getChildCount", &Node::getChildCount) + + .function("getParent", &Node::getParent, allow_raw_pointers()) + .function("getChild", &Node::getChild, allow_raw_pointers()) + + .function( + "setAlwaysFormsContainingBlock", &Node::setAlwaysFormsContainingBlock) + + .function("isReferenceBaseline", &Node::isReferenceBaseline) + .function("setIsReferenceBaseline", &Node::setIsReferenceBaseline) + + .function("setMeasureFunc", &Node::setMeasureFunc, allow_raw_pointers()) + .function("unsetMeasureFunc", &Node::unsetMeasureFunc) + + .function("setDirtiedFunc", &Node::setDirtiedFunc, allow_raw_pointers()) + .function("unsetDirtiedFunc", &Node::unsetDirtiedFunc) + + .function("markDirty", &Node::markDirty) + .function("isDirty", &Node::isDirty) + + .function("markLayoutSeen", &Node::markLayoutSeen) + .function("hasNewLayout", &Node::hasNewLayout) + + .function("calculateLayout", &Node::calculateLayout) + + .function("getComputedLeft", &Node::getComputedLeft) + .function("getComputedRight", &Node::getComputedRight) + + .function("getComputedTop", &Node::getComputedTop) + .function("getComputedBottom", &Node::getComputedBottom) + + .function("getComputedWidth", &Node::getComputedWidth) + .function("getComputedHeight", &Node::getComputedHeight) + + .function("getComputedLayout", &Node::getComputedLayout) + + .function("getComputedMargin", &Node::getComputedMargin) + .function("getComputedBorder", &Node::getComputedBorder) + .function("getComputedPadding", &Node::getComputedPadding) + + .function("getDirection", &Node::getDirection); +} diff --git a/node_modules/yoga-layout/src/generated/YGEnums.ts b/node_modules/yoga-layout/src/generated/YGEnums.ts new file mode 100644 index 0000000000000000000000000000000000000000..2aafc682ffb0343d639a8770d21cd16328749055 --- /dev/null +++ b/node_modules/yoga-layout/src/generated/YGEnums.ts @@ -0,0 +1,210 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// @generated by enums.py + +export enum Align { + Auto = 0, + FlexStart = 1, + Center = 2, + FlexEnd = 3, + Stretch = 4, + Baseline = 5, + SpaceBetween = 6, + SpaceAround = 7, + SpaceEvenly = 8, +} + +export enum BoxSizing { + BorderBox = 0, + ContentBox = 1, +} + +export enum Dimension { + Width = 0, + Height = 1, +} + +export enum Direction { + Inherit = 0, + LTR = 1, + RTL = 2, +} + +export enum Display { + Flex = 0, + None = 1, + Contents = 2, +} + +export enum Edge { + Left = 0, + Top = 1, + Right = 2, + Bottom = 3, + Start = 4, + End = 5, + Horizontal = 6, + Vertical = 7, + All = 8, +} + +export enum Errata { + None = 0, + StretchFlexBasis = 1, + AbsolutePositionWithoutInsetsExcludesPadding = 2, + AbsolutePercentAgainstInnerSize = 4, + All = 2147483647, + Classic = 2147483646, +} + +export enum ExperimentalFeature { + WebFlexBasis = 0, +} + +export enum FlexDirection { + Column = 0, + ColumnReverse = 1, + Row = 2, + RowReverse = 3, +} + +export enum Gutter { + Column = 0, + Row = 1, + All = 2, +} + +export enum Justify { + FlexStart = 0, + Center = 1, + FlexEnd = 2, + SpaceBetween = 3, + SpaceAround = 4, + SpaceEvenly = 5, +} + +export enum LogLevel { + Error = 0, + Warn = 1, + Info = 2, + Debug = 3, + Verbose = 4, + Fatal = 5, +} + +export enum MeasureMode { + Undefined = 0, + Exactly = 1, + AtMost = 2, +} + +export enum NodeType { + Default = 0, + Text = 1, +} + +export enum Overflow { + Visible = 0, + Hidden = 1, + Scroll = 2, +} + +export enum PositionType { + Static = 0, + Relative = 1, + Absolute = 2, +} + +export enum Unit { + Undefined = 0, + Point = 1, + Percent = 2, + Auto = 3, +} + +export enum Wrap { + NoWrap = 0, + Wrap = 1, + WrapReverse = 2, +} + +const constants = { + ALIGN_AUTO: Align.Auto, + ALIGN_FLEX_START: Align.FlexStart, + ALIGN_CENTER: Align.Center, + ALIGN_FLEX_END: Align.FlexEnd, + ALIGN_STRETCH: Align.Stretch, + ALIGN_BASELINE: Align.Baseline, + ALIGN_SPACE_BETWEEN: Align.SpaceBetween, + ALIGN_SPACE_AROUND: Align.SpaceAround, + ALIGN_SPACE_EVENLY: Align.SpaceEvenly, + BOX_SIZING_BORDER_BOX: BoxSizing.BorderBox, + BOX_SIZING_CONTENT_BOX: BoxSizing.ContentBox, + DIMENSION_WIDTH: Dimension.Width, + DIMENSION_HEIGHT: Dimension.Height, + DIRECTION_INHERIT: Direction.Inherit, + DIRECTION_LTR: Direction.LTR, + DIRECTION_RTL: Direction.RTL, + DISPLAY_FLEX: Display.Flex, + DISPLAY_NONE: Display.None, + DISPLAY_CONTENTS: Display.Contents, + EDGE_LEFT: Edge.Left, + EDGE_TOP: Edge.Top, + EDGE_RIGHT: Edge.Right, + EDGE_BOTTOM: Edge.Bottom, + EDGE_START: Edge.Start, + EDGE_END: Edge.End, + EDGE_HORIZONTAL: Edge.Horizontal, + EDGE_VERTICAL: Edge.Vertical, + EDGE_ALL: Edge.All, + ERRATA_NONE: Errata.None, + ERRATA_STRETCH_FLEX_BASIS: Errata.StretchFlexBasis, + ERRATA_ABSOLUTE_POSITION_WITHOUT_INSETS_EXCLUDES_PADDING: Errata.AbsolutePositionWithoutInsetsExcludesPadding, + ERRATA_ABSOLUTE_PERCENT_AGAINST_INNER_SIZE: Errata.AbsolutePercentAgainstInnerSize, + ERRATA_ALL: Errata.All, + ERRATA_CLASSIC: Errata.Classic, + EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS: ExperimentalFeature.WebFlexBasis, + FLEX_DIRECTION_COLUMN: FlexDirection.Column, + FLEX_DIRECTION_COLUMN_REVERSE: FlexDirection.ColumnReverse, + FLEX_DIRECTION_ROW: FlexDirection.Row, + FLEX_DIRECTION_ROW_REVERSE: FlexDirection.RowReverse, + GUTTER_COLUMN: Gutter.Column, + GUTTER_ROW: Gutter.Row, + GUTTER_ALL: Gutter.All, + JUSTIFY_FLEX_START: Justify.FlexStart, + JUSTIFY_CENTER: Justify.Center, + JUSTIFY_FLEX_END: Justify.FlexEnd, + JUSTIFY_SPACE_BETWEEN: Justify.SpaceBetween, + JUSTIFY_SPACE_AROUND: Justify.SpaceAround, + JUSTIFY_SPACE_EVENLY: Justify.SpaceEvenly, + LOG_LEVEL_ERROR: LogLevel.Error, + LOG_LEVEL_WARN: LogLevel.Warn, + LOG_LEVEL_INFO: LogLevel.Info, + LOG_LEVEL_DEBUG: LogLevel.Debug, + LOG_LEVEL_VERBOSE: LogLevel.Verbose, + LOG_LEVEL_FATAL: LogLevel.Fatal, + MEASURE_MODE_UNDEFINED: MeasureMode.Undefined, + MEASURE_MODE_EXACTLY: MeasureMode.Exactly, + MEASURE_MODE_AT_MOST: MeasureMode.AtMost, + NODE_TYPE_DEFAULT: NodeType.Default, + NODE_TYPE_TEXT: NodeType.Text, + OVERFLOW_VISIBLE: Overflow.Visible, + OVERFLOW_HIDDEN: Overflow.Hidden, + OVERFLOW_SCROLL: Overflow.Scroll, + POSITION_TYPE_STATIC: PositionType.Static, + POSITION_TYPE_RELATIVE: PositionType.Relative, + POSITION_TYPE_ABSOLUTE: PositionType.Absolute, + UNIT_UNDEFINED: Unit.Undefined, + UNIT_POINT: Unit.Point, + UNIT_PERCENT: Unit.Percent, + UNIT_AUTO: Unit.Auto, + WRAP_NO_WRAP: Wrap.NoWrap, + WRAP_WRAP: Wrap.Wrap, + WRAP_WRAP_REVERSE: Wrap.WrapReverse, +} +export default constants \ No newline at end of file diff --git a/node_modules/yoga-layout/src/index.ts b/node_modules/yoga-layout/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..3028b225a021d67523e51e12790b3deb450001a4 --- /dev/null +++ b/node_modules/yoga-layout/src/index.ts @@ -0,0 +1,23 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + */ + +// @ts-ignore untyped from Emscripten +import loadYoga from '../binaries/yoga-wasm-base64-esm.js'; +import wrapAssembly from './wrapAssembly.ts'; + +export type { + Config, + DirtiedFunction, + MeasureFunction, + Node, +} from './wrapAssembly.ts'; + +const Yoga = wrapAssembly(await loadYoga()); +export default Yoga; +export * from './generated/YGEnums.ts'; diff --git a/node_modules/yoga-layout/src/load.ts b/node_modules/yoga-layout/src/load.ts new file mode 100644 index 0000000000000000000000000000000000000000..a415a0dd715412b8e5d11844c03f3eb194c5884f --- /dev/null +++ b/node_modules/yoga-layout/src/load.ts @@ -0,0 +1,25 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + */ + +// @ts-ignore untyped from Emscripten +import loadYogaImpl from '../binaries/yoga-wasm-base64-esm.js'; +import wrapAssembly from './wrapAssembly.ts'; + +export type { + Config, + DirtiedFunction, + MeasureFunction, + Node, + Yoga, +} from './wrapAssembly.ts'; + +export async function loadYoga() { + return wrapAssembly(await loadYogaImpl()); +} +export * from './generated/YGEnums.ts'; diff --git a/node_modules/yoga-layout/src/wrapAssembly.ts b/node_modules/yoga-layout/src/wrapAssembly.ts new file mode 100644 index 0000000000000000000000000000000000000000..3f91c160bf2bf4cadaf76b4d1654290f029a833a --- /dev/null +++ b/node_modules/yoga-layout/src/wrapAssembly.ts @@ -0,0 +1,336 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + */ + +// @ts-nocheck + +import {Unit, Direction} from './generated/YGEnums.ts'; +import YGEnums from './generated/YGEnums.ts'; + +import type { + Align, + BoxSizing, + Display, + Edge, + Errata, + ExperimentalFeature, + FlexDirection, + Gutter, + Justify, + MeasureMode, + Overflow, + PositionType, + Wrap, +} from './generated/YGEnums.ts'; + +type Layout = { + left: number; + right: number; + top: number; + bottom: number; + width: number; + height: number; +}; + +type Size = { + width: number; + height: number; +}; + +type Value = { + unit: Unit; + value: number; +}; + +export type Config = { + free(): void; + isExperimentalFeatureEnabled(feature: ExperimentalFeature): boolean; + setExperimentalFeatureEnabled( + feature: ExperimentalFeature, + enabled: boolean, + ): void; + setPointScaleFactor(factor: number): void; + getErrata(): Errata; + setErrata(errata: Errata): void; + useWebDefaults(): boolean; + setUseWebDefaults(useWebDefaults: boolean): void; +}; + +export type DirtiedFunction = (node: Node) => void; + +export type MeasureFunction = ( + width: number, + widthMode: MeasureMode, + height: number, + heightMode: MeasureMode, +) => Size; + +export type Node = { + calculateLayout( + width: number | 'auto' | undefined, + height: number | 'auto' | undefined, + direction?: Direction, + ): void; + copyStyle(node: Node): void; + free(): void; + freeRecursive(): void; + getAlignContent(): Align; + getAlignItems(): Align; + getAlignSelf(): Align; + getAspectRatio(): number; + getBorder(edge: Edge): number; + getChild(index: number): Node; + getChildCount(): number; + getComputedBorder(edge: Edge): number; + getComputedBottom(): number; + getComputedHeight(): number; + getComputedLayout(): Layout; + getComputedLeft(): number; + getComputedMargin(edge: Edge): number; + getComputedPadding(edge: Edge): number; + getComputedRight(): number; + getComputedTop(): number; + getComputedWidth(): number; + getDirection(): Direction; + getDisplay(): Display; + getFlexBasis(): Value; + getFlexDirection(): FlexDirection; + getFlexGrow(): number; + getFlexShrink(): number; + getFlexWrap(): Wrap; + getHeight(): Value; + getJustifyContent(): Justify; + getGap(gutter: Gutter): Value; + getMargin(edge: Edge): Value; + getMaxHeight(): Value; + getMaxWidth(): Value; + getMinHeight(): Value; + getMinWidth(): Value; + getOverflow(): Overflow; + getPadding(edge: Edge): Value; + getParent(): Node | null; + getPosition(edge: Edge): Value; + getPositionType(): PositionType; + getBoxSizing(): BoxSizing; + getWidth(): Value; + insertChild(child: Node, index: number): void; + isDirty(): boolean; + isReferenceBaseline(): boolean; + markDirty(): void; + hasNewLayout(): boolean; + markLayoutSeen(): void; + removeChild(child: Node): void; + reset(): void; + setAlignContent(alignContent: Align): void; + setAlignItems(alignItems: Align): void; + setAlignSelf(alignSelf: Align): void; + setAspectRatio(aspectRatio: number | undefined): void; + setBorder(edge: Edge, borderWidth: number | undefined): void; + setDirection(direction: Direction): void; + setDisplay(display: Display): void; + setFlex(flex: number | undefined): void; + setFlexBasis(flexBasis: number | 'auto' | `${number}%` | undefined): void; + setFlexBasisPercent(flexBasis: number | undefined): void; + setFlexBasisAuto(): void; + setFlexDirection(flexDirection: FlexDirection): void; + setFlexGrow(flexGrow: number | undefined): void; + setFlexShrink(flexShrink: number | undefined): void; + setFlexWrap(flexWrap: Wrap): void; + setHeight(height: number | 'auto' | `${number}%` | undefined): void; + setIsReferenceBaseline(isReferenceBaseline: boolean): void; + setHeightAuto(): void; + setHeightPercent(height: number | undefined): void; + setJustifyContent(justifyContent: Justify): void; + setGap(gutter: Gutter, gapLength: number | `${number}%` | undefined): Value; + setGapPercent(gutter: Gutter, gapLength: number | undefined): Value; + setMargin( + edge: Edge, + margin: number | 'auto' | `${number}%` | undefined, + ): void; + setMarginAuto(edge: Edge): void; + setMarginPercent(edge: Edge, margin: number | undefined): void; + setMaxHeight(maxHeight: number | `${number}%` | undefined): void; + setMaxHeightPercent(maxHeight: number | undefined): void; + setMaxWidth(maxWidth: number | `${number}%` | undefined): void; + setMaxWidthPercent(maxWidth: number | undefined): void; + setDirtiedFunc(dirtiedFunc: DirtiedFunction | null): void; + setMeasureFunc(measureFunc: MeasureFunction | null): void; + setMinHeight(minHeight: number | `${number}%` | undefined): void; + setMinHeightPercent(minHeight: number | undefined): void; + setMinWidth(minWidth: number | `${number}%` | undefined): void; + setMinWidthPercent(minWidth: number | undefined): void; + setOverflow(overflow: Overflow): void; + setPadding(edge: Edge, padding: number | `${number}%` | undefined): void; + setPaddingPercent(edge: Edge, padding: number | undefined): void; + setPosition(edge: Edge, position: number | `${number}%` | undefined): void; + setPositionPercent(edge: Edge, position: number | undefined): void; + setPositionType(positionType: PositionType): void; + setPositionAuto(edge: Edge): void; + setBoxSizing(boxSizing: BoxSizing): void; + setWidth(width: number | 'auto' | `${number}%` | undefined): void; + setWidthAuto(): void; + setWidthPercent(width: number | undefined): void; + unsetDirtiedFunc(): void; + unsetMeasureFunc(): void; + setAlwaysFormsContainingBlock(alwaysFormsContainingBlock: boolean): void; +}; + +export type Yoga = { + Config: { + create(): Config; + destroy(config: Config): void; + }; + Node: { + create(config?: Config): Node; + createDefault(): Node; + createWithConfig(config: Config): Node; + destroy(node: Node): void; + }; +} & typeof YGEnums; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export default function wrapAssembly(lib: any): Yoga { + function patch(prototype, name, fn) { + const original = prototype[name]; + + prototype[name] = function (...args) { + return fn.call(this, original, ...args); + }; + } + + for (const fnName of [ + 'setPosition', + 'setMargin', + 'setFlexBasis', + 'setWidth', + 'setHeight', + 'setMinWidth', + 'setMinHeight', + 'setMaxWidth', + 'setMaxHeight', + 'setPadding', + 'setGap', + ]) { + const methods = { + [Unit.Point]: lib.Node.prototype[fnName], + [Unit.Percent]: lib.Node.prototype[`${fnName}Percent`], + [Unit.Auto]: lib.Node.prototype[`${fnName}Auto`], + }; + + patch(lib.Node.prototype, fnName, function (original, ...args) { + // We patch all these functions to add support for the following calls: + // .setWidth(100) / .setWidth("100%") / .setWidth(.getWidth()) / .setWidth("auto") + + const value = args.pop(); + let unit, asNumber; + + if (value === 'auto') { + unit = Unit.Auto; + asNumber = undefined; + } else if (typeof value === 'object') { + unit = value.unit; + asNumber = value.valueOf(); + } else { + unit = + typeof value === 'string' && value.endsWith('%') + ? Unit.Percent + : Unit.Point; + asNumber = parseFloat(value); + if ( + value !== undefined && + !Number.isNaN(value) && + Number.isNaN(asNumber) + ) { + throw new Error(`Invalid value ${value} for ${fnName}`); + } + } + + if (!methods[unit]) + throw new Error( + `Failed to execute "${fnName}": Unsupported unit '${value}'`, + ); + + if (asNumber !== undefined) { + return methods[unit].call(this, ...args, asNumber); + } else { + return methods[unit].call(this, ...args); + } + }); + } + + function wrapMeasureFunction(measureFunction) { + return lib.MeasureCallback.implement({ + measure: (...args) => { + const {width, height} = measureFunction(...args); + return { + width: width ?? NaN, + height: height ?? NaN, + }; + }, + }); + } + + patch(lib.Node.prototype, 'setMeasureFunc', function (original, measureFunc) { + // This patch is just a convenience patch, since it helps write more + // idiomatic source code (such as .setMeasureFunc(null)) + if (measureFunc) { + return original.call(this, wrapMeasureFunction(measureFunc)); + } else { + return this.unsetMeasureFunc(); + } + }); + + function wrapDirtiedFunc(dirtiedFunction) { + return lib.DirtiedCallback.implement({dirtied: dirtiedFunction}); + } + + patch(lib.Node.prototype, 'setDirtiedFunc', function (original, dirtiedFunc) { + original.call(this, wrapDirtiedFunc(dirtiedFunc)); + }); + + patch(lib.Config.prototype, 'free', function () { + // Since we handle the memory allocation ourselves (via lib.Config.create), + // we also need to handle the deallocation + lib.Config.destroy(this); + }); + + patch(lib.Node, 'create', (_, config) => { + // We decide the constructor we want to call depending on the parameters + return config + ? lib.Node.createWithConfig(config) + : lib.Node.createDefault(); + }); + + patch(lib.Node.prototype, 'free', function () { + // Since we handle the memory allocation ourselves (via lib.Node.create), + // we also need to handle the deallocation + lib.Node.destroy(this); + }); + + patch(lib.Node.prototype, 'freeRecursive', function () { + for (let t = 0, T = this.getChildCount(); t < T; ++t) { + this.getChild(0).freeRecursive(); + } + this.free(); + }); + + patch( + lib.Node.prototype, + 'calculateLayout', + function (original, width = NaN, height = NaN, direction = Direction.LTR) { + // Just a small patch to add support for the function default parameters + return original.call(this, width, height, direction); + }, + ); + + return { + Config: lib.Config, + Node: lib.Node, + ...YGEnums, + }; +} diff --git a/node_modules/zip-stream/CHANGELOG.md b/node_modules/zip-stream/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..b26512830c1299fa14903961d8fa7f4de02d9486 --- /dev/null +++ b/node_modules/zip-stream/CHANGELOG.md @@ -0,0 +1,118 @@ +## Changelog + +**5.0.2** - February 27, 2024 — [Diff](https://github.com/archiverjs/node-zip-stream/compare/5.0.1...5.0.2) + +**5.0.1** - September 3, 2023 — [Diff](https://github.com/archiverjs/node-zip-stream/compare/5.0.0...5.0.1) + +**5.0.0** - September 2, 2023 — [Diff](https://github.com/archiverjs/node-zip-stream/compare/4.1.1...5.0.0) + +**4.1.1** - September 2, 2023 — [Diff](https://github.com/archiverjs/node-zip-stream/compare/4.1.0...4.1.1) + +**4.1.0** - March 2, 2021 — [Diff](https://github.com/archiverjs/node-zip-stream/compare/4.0.5...4.1.0) + +## Features + +- Allow prepending forward slash in entry name (#79) + +## Maintenance + +- Bump mocha from 8.2.1 to 8.3.0 (#76) +- Bump actions/setup-node from v2.1.4 to v2.1.5 (#77) +- Bump actions/setup-node from v2.1.2 to v2.1.4 (#74) + +**4.0.5** - November 18, 2020 — [Diff](https://github.com/archiverjs/node-zip-stream/compare/4.0.4...4.0.5) + +- No Changes + +**4.0.4** - November 18, 2020 — [Diff](https://github.com/archiverjs/node-zip-stream/compare/4.0.3...4.0.4) + +### Maintenance + +- Bump compress-commons from 4.0.1 to 4.0.2 (#72) + +**4.0.3** - November 18, 2020 — [Diff](https://github.com/archiverjs/node-zip-stream/compare/4.0.2...4.0.3) + +### Maintenance + +- Update docs example with latest ES6 syntax (#60) +- Update archiver-jsdoc-theme to ^1.1.3 (#71) +- Update archiver-jsdoc-theme to ^1.1.2 (#70) +- Bump jsdoc from 3.6.5 to 3.6.6 (#62) +- Bump actions/setup-node from v2.1.1 to v2.1.2 (#64) +- Bump mocha from 8.1.1 to 8.2.1 (#66) +- Bump actions/checkout from v2.3.2 to v2.3.4 (#67) +- Bump mocha from 8.1.0 to 8.1.1 (#55) +- Bump actions/checkout from v2.3.1 to v2.3.2 (#56) +- Bump mocha from 8.0.1 to 8.1.0 (#54) +- Bump actions/setup-node from v2.1.0 to v2.1.1 (#52) +- Bump jsdoc from 3.6.4 to 3.6.5 (#53) + + +**4.0.2** - July 20, 2020 — [Diff](https://github.com/archiverjs/node-zip-stream/compare/4.0.1...4.0.2) + +* Bump compress-commons from 4.0.0 to 4.0.1 (#51) @dependabot + +**4.0.1** - July 20, 2020 — [Diff](https://github.com/archiverjs/node-zip-stream/compare/4.0.0...4.0.1) + +* Bump compress-commons from 3.0.0 to 4.0.0 (#50) @dependabot + +**4.0.0** - July 18, 2020 — [Diff](https://github.com/archiverjs/node-zip-stream/compare/3.0.1...4.0.0) + +* Bump mocha from 6.2.3 to 8.0.1 (#47) @dependabot +* Bump rimraf from 2.7.1 to 3.0.2 (#46) @dependabot +* Bump actions/setup-node from v1 to v2.1.0 (#45) @dependabot +* Bump mkdirp from 0.5.5 to 1.0.4 (#48) @dependabot +* remove support for node < 10 (#49) @ctalkington +* Bump actions/checkout from v1 to v2.3.1 (#44) @dependabot + +**3.0.1** - April 14, 2020 — [Diff](https://github.com/archiverjs/node-zip-stream/compare/3.0.0...3.0.1) + +- update to compress-commons@^3.0.0 + +**3.0.0** - April 14, 2020 — [Diff](https://github.com/archiverjs/node-zip-stream/compare/2.1.3...3.0.0) + +- breaking: slowly catch up with node LTS, remove support for versions under 8. +- update multiple deps. + +**2.1.3** — January 8, 2020 — [Diff](https://github.com/archiverjs/node-zip-stream/compare/2.1.0...2.1.3) + +- allow zip64 for no compression (#40) + +**2.1.2** — August 2, 2019 — [Diff](https://github.com/archiverjs/node-zip-stream/compare/2.1.0...2.1.2) + +- update compress-commons to v2.1.1 + +**2.1.1** — August 2, 2019 — [Diff](https://github.com/archiverjs/node-zip-stream/compare/2.1.0...2.1.1) + +- update compress-commons to v2.1.0 + +**2.1.0** — July 19, 2019 — [Diff](https://github.com/archiverjs/node-zip-stream/compare/2.0.1...2.1.0) + +- test: now targeting node v12 +- other: update dependencies. + +**2.0.1** — August 22, 2018 — [Diff](https://github.com/archiverjs/node-zip-stream/compare/2.0.0...2.0.1) + +- update to archiver-utils@2 + +**2.0.0** — August 22, 2018 — [Diff](https://github.com/archiverjs/node-zip-stream/compare/1.2.0...2.0.0) + +- breaking: follow node LTS, remove support for versions under 6. +- other: remove unused lodash dependence (#35) + +**1.2.0** — June 16, 2017 — [Diff](https://github.com/archiverjs/node-zip-stream/compare/1.1.1...1.2.0) + +- groundwork for symlinks support. + +*NOTE: this will be the last release for node v0.10 and v0.12. node v4 will become the minimum and a version bump to 2.0.0 will take place.* + +**1.1.1** — _January 17, 2017_ — [Diff](https://github.com/archiverjs/node-zip-stream/compare/1.1.0...1.1.1) + +- actually use STORE method if level is 0 (GH #21) +- bump deps to ensure latest versions are used. + +**1.1.0** — _August 27, 2016_ — [Diff](https://github.com/archiverjs/node-zip-stream/compare/1.0.0...1.1.0) + +- bump deps to ensure latest versions are used. + +[Release Archive](https://github.com/archiverjs/node-zip-stream/releases) diff --git a/node_modules/zip-stream/LICENSE b/node_modules/zip-stream/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..56420a6a06bd156003ce69970b50c67176f2afe5 --- /dev/null +++ b/node_modules/zip-stream/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2014 Chris Talkington, contributors. + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/zip-stream/README.md b/node_modules/zip-stream/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ff85b9ba33e3c3d95775ccb40cdb2cfcd2f31bd3 --- /dev/null +++ b/node_modules/zip-stream/README.md @@ -0,0 +1,45 @@ +# ZipStream + +zip-stream is a streaming zip archive generator based on the `ZipArchiveOutputStream` prototype found in the [compress-commons](https://www.npmjs.org/package/compress-commons) project. + +It was originally created to be a successor to [zipstream](https://npmjs.org/package/zipstream). + +Visit the [API documentation](http://archiverjs.com/zip-stream) for a list of all methods available. + +### Install + +```bash +npm install zip-stream --save +``` + +You can also use `npm install https://github.com/archiverjs/node-zip-stream/archive/master.tar.gz` to test upcoming versions. + +### Usage + +This module is meant to be wrapped internally by other modules and therefore lacks any queue management. This means you have to wait until the previous entry has been fully consumed to add another. Nested callbacks should be used to add multiple entries. There are modules like [async](https://npmjs.org/package/async) that ease the so called "callback hell". + +If you want a module that handles entry queueing and much more, you should check out [archiver](https://npmjs.org/package/archiver) which uses this module internally. + +```js +const Packer = require('zip-stream'); +const archive = new Packer(); // OR new Packer(options) + +archive.on('error', function(err) { + throw err; +}); + +// pipe archive where you want it (ie fs, http, etc) +// listen to the destination's end, close, or finish event + +archive.entry('string contents', { name: 'string.txt' }, function(err, entry) { + if (err) throw err; + archive.entry(null, { name: 'directory/' }, function(err, entry) { + if (err) throw err; + archive.finish(); + }); +}); +``` + +## Credits + +Concept inspired by Antoine van Wel's [zipstream](https://npmjs.org/package/zipstream) module, which is no longer being updated. diff --git a/node_modules/zip-stream/index.js b/node_modules/zip-stream/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2c692376d200e6aa706397a8e9e4d2ce75566dd9 --- /dev/null +++ b/node_modules/zip-stream/index.js @@ -0,0 +1,187 @@ +/** + * ZipStream + * + * @ignore + * @license [MIT]{@link https://github.com/archiverjs/node-zip-stream/blob/master/LICENSE} + * @copyright (c) 2014 Chris Talkington, contributors. + */ +var inherits = require('util').inherits; + +var ZipArchiveOutputStream = require('compress-commons').ZipArchiveOutputStream; +var ZipArchiveEntry = require('compress-commons').ZipArchiveEntry; + +var util = require('archiver-utils'); + +/** + * @constructor + * @extends external:ZipArchiveOutputStream + * @param {Object} [options] + * @param {String} [options.comment] Sets the zip archive comment. + * @param {Boolean} [options.forceLocalTime=false] Forces the archive to contain local file times instead of UTC. + * @param {Boolean} [options.forceZip64=false] Forces the archive to contain ZIP64 headers. + * @param {Boolean} [options.store=false] Sets the compression method to STORE. + * @param {Object} [options.zlib] Passed to [zlib]{@link https://nodejs.org/api/zlib.html#zlib_class_options} + * to control compression. + */ +var ZipStream = module.exports = function(options) { + if (!(this instanceof ZipStream)) { + return new ZipStream(options); + } + + options = this.options = options || {}; + options.zlib = options.zlib || {}; + + ZipArchiveOutputStream.call(this, options); + + if (typeof options.level === 'number' && options.level >= 0) { + options.zlib.level = options.level; + delete options.level; + } + + if (!options.forceZip64 && typeof options.zlib.level === 'number' && options.zlib.level === 0) { + options.store = true; + } + + options.namePrependSlash = options.namePrependSlash || false; + + if (options.comment && options.comment.length > 0) { + this.setComment(options.comment); + } +}; + +inherits(ZipStream, ZipArchiveOutputStream); + +/** + * Normalizes entry data with fallbacks for key properties. + * + * @private + * @param {Object} data + * @return {Object} + */ +ZipStream.prototype._normalizeFileData = function(data) { + data = util.defaults(data, { + type: 'file', + name: null, + namePrependSlash: this.options.namePrependSlash, + linkname: null, + date: null, + mode: null, + store: this.options.store, + comment: '' + }); + + var isDir = data.type === 'directory'; + var isSymlink = data.type === 'symlink'; + + if (data.name) { + data.name = util.sanitizePath(data.name); + + if (!isSymlink && data.name.slice(-1) === '/') { + isDir = true; + data.type = 'directory'; + } else if (isDir) { + data.name += '/'; + } + } + + if (isDir || isSymlink) { + data.store = true; + } + + data.date = util.dateify(data.date); + + return data; +}; + +/** + * Appends an entry given an input source (text string, buffer, or stream). + * + * @param {(Buffer|Stream|String)} source The input source. + * @param {Object} data + * @param {String} data.name Sets the entry name including internal path. + * @param {String} [data.comment] Sets the entry comment. + * @param {(String|Date)} [data.date=NOW()] Sets the entry date. + * @param {Number} [data.mode=D:0755/F:0644] Sets the entry permissions. + * @param {Boolean} [data.store=options.store] Sets the compression method to STORE. + * @param {String} [data.type=file] Sets the entry type. Defaults to `directory` + * if name ends with trailing slash. + * @param {Function} callback + * @return this + */ +ZipStream.prototype.entry = function(source, data, callback) { + if (typeof callback !== 'function') { + callback = this._emitErrorCallback.bind(this); + } + + data = this._normalizeFileData(data); + + if (data.type !== 'file' && data.type !== 'directory' && data.type !== 'symlink') { + callback(new Error(data.type + ' entries not currently supported')); + return; + } + + if (typeof data.name !== 'string' || data.name.length === 0) { + callback(new Error('entry name must be a non-empty string value')); + return; + } + + if (data.type === 'symlink' && typeof data.linkname !== 'string') { + callback(new Error('entry linkname must be a non-empty string value when type equals symlink')); + return; + } + + var entry = new ZipArchiveEntry(data.name); + entry.setTime(data.date, this.options.forceLocalTime); + + if (data.namePrependSlash) { + entry.setName(data.name, true); + } + + if (data.store) { + entry.setMethod(0); + } + + if (data.comment.length > 0) { + entry.setComment(data.comment); + } + + if (data.type === 'symlink' && typeof data.mode !== 'number') { + data.mode = 40960; // 0120000 + } + + if (typeof data.mode === 'number') { + if (data.type === 'symlink') { + data.mode |= 40960; + } + + entry.setUnixMode(data.mode); + } + + if (data.type === 'symlink' && typeof data.linkname === 'string') { + source = Buffer.from(data.linkname); + } + + return ZipArchiveOutputStream.prototype.entry.call(this, entry, source, callback); +}; + +/** + * Finalizes the instance and prevents further appending to the archive + * structure (queue will continue til drained). + * + * @return void + */ +ZipStream.prototype.finalize = function() { + this.finish(); +}; + +/** + * Returns the current number of bytes written to this stream. + * @function ZipStream#getBytesWritten + * @returns {Number} + */ + +/** + * Compress Commons ZipArchiveOutputStream + * @external ZipArchiveOutputStream + * @see {@link https://github.com/archiverjs/node-compress-commons} + */ diff --git a/node_modules/zip-stream/package.json b/node_modules/zip-stream/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9b9e8860f30b7c9ccabf2fa9cffd159a0022cf4a --- /dev/null +++ b/node_modules/zip-stream/package.json @@ -0,0 +1,49 @@ +{ + "name": "zip-stream", + "version": "5.0.2", + "description": "a streaming zip archive generator.", + "homepage": "https://github.com/archiverjs/node-zip-stream", + "author": { + "name": "Chris Talkington", + "url": "http://christalkington.com/" + }, + "repository": { + "type": "git", + "url": "https://github.com/archiverjs/node-zip-stream.git" + }, + "bugs": { + "url": "https://github.com/archiverjs/node-zip-stream/issues" + }, + "license": "MIT", + "main": "index.js", + "files": [ + "index.js" + ], + "engines": { + "node": ">= 12.0.0" + }, + "scripts": { + "test": "mocha --reporter dot", + "jsdoc": "jsdoc -c jsdoc.json README.md" + }, + "dependencies": { + "archiver-utils": "^4.0.1", + "compress-commons": "^5.0.1", + "readable-stream": "^3.6.0" + }, + "devDependencies": { + "archiver-jsdoc-theme": "1.1.3", + "chai": "4.4.1", + "jsdoc": "3.6.11", + "minami": "1.2.3", + "mkdirp": "3.0.1", + "mocha": "9.2.2", + "rimraf": "5.0.5" + }, + "keywords": [ + "archive", + "stream", + "zip-stream", + "zip" + ] +} diff --git a/node_modules/zod/LICENSE b/node_modules/zod/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..c06579627b432d09779094cd0166b7f37fe51db8 --- /dev/null +++ b/node_modules/zod/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Colin McDonnell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/zod/README.md b/node_modules/zod/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cefb2a3bbc574608ddce064ba21676484cdf83bb --- /dev/null +++ b/node_modules/zod/README.md @@ -0,0 +1,191 @@ +

+ Zod logo +

Zod

+

+ TypeScript-first schema validation with static type inference +
+ by @colinhacks +

+

+
+ +

+Zod CI status +License +npm +discord server +stars +

+ +
+ Docs +   •   + Discord +   •   + 𝕏 +   •   + Bluesky +
+
+ +
+
+ +### [Read the docs →](https://zod.dev/api) + +
+
+ +## What is Zod? + +Zod is a TypeScript-first validation library. Define a schema and parse some data with it. You'll get back a strongly typed, validated result. + +```ts +import * as z from "zod"; + +const User = z.object({ + name: z.string(), +}); + +// some untrusted data... +const input = { + /* stuff */ +}; + +// the parsed result is validated and type safe! +const data = User.parse(input); + +// so you can use it with confidence :) +console.log(data.name); +``` + +
+ +## Features + +- Zero external dependencies +- Works in Node.js and all modern browsers +- Tiny: `2kb` core bundle (gzipped) +- Immutable API: methods return a new instance +- Concise interface +- Works with TypeScript and plain JS +- Built-in JSON Schema conversion +- Extensive ecosystem + +
+ +## Installation + +```sh +npm install zod +``` + +
+ +## Basic usage + +Before you can do anything else, you need to define a schema. For the purposes of this guide, we'll use a simple object schema. + +```ts +import * as z from "zod"; + +const Player = z.object({ + username: z.string(), + xp: z.number(), +}); +``` + +### Parsing data + +Given any Zod schema, use `.parse` to validate an input. If it's valid, Zod returns a strongly-typed _deep clone_ of the input. + +```ts +Player.parse({ username: "billie", xp: 100 }); +// => returns { username: "billie", xp: 100 } +``` + +**Note** — If your schema uses certain asynchronous APIs like `async` [refinements](https://zod.dev/api#refinements) or [transforms](https://zod.dev/api#transforms), you'll need to use the `.parseAsync()` method instead. + +```ts +const schema = z.string().refine(async (val) => val.length <= 8); + +await schema.parseAsync("hello"); +// => "hello" +``` + +### Handling errors + +When validation fails, the `.parse()` method will throw a `ZodError` instance with granular information about the validation issues. + +```ts +try { + Player.parse({ username: 42, xp: "100" }); +} catch (err) { + if (err instanceof z.ZodError) { + err.issues; + /* [ + { + expected: 'string', + code: 'invalid_type', + path: [ 'username' ], + message: 'Invalid input: expected string' + }, + { + expected: 'number', + code: 'invalid_type', + path: [ 'xp' ], + message: 'Invalid input: expected number' + } + ] */ + } +} +``` + +To avoid a `try/catch` block, you can use the `.safeParse()` method to get back a plain result object containing either the successfully parsed data or a `ZodError`. The result type is a [discriminated union](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions), so you can handle both cases conveniently. + +```ts +const result = Player.safeParse({ username: 42, xp: "100" }); +if (!result.success) { + result.error; // ZodError instance +} else { + result.data; // { username: string; xp: number } +} +``` + +**Note** — If your schema uses certain asynchronous APIs like `async` [refinements](https://zod.dev/api#refinements) or [transforms](https://zod.dev/api#transforms), you'll need to use the `.safeParseAsync()` method instead. + +```ts +const schema = z.string().refine(async (val) => val.length <= 8); + +await schema.safeParseAsync("hello"); +// => { success: true; data: "hello" } +``` + +### Inferring types + +Zod infers a static type from your schema definitions. You can extract this type with the `z.infer<>` utility and use it however you like. + +```ts +const Player = z.object({ + username: z.string(), + xp: z.number(), +}); + +// extract the inferred type +type Player = z.infer; + +// use it in your code +const player: Player = { username: "billie", xp: 100 }; +``` + +In some cases, the input & output types of a schema can diverge. For instance, the `.transform()` API can convert the input from one type to another. In these cases, you can extract the input and output types independently: + +```ts +const mySchema = z.string().transform((val) => val.length); + +type MySchemaIn = z.input; +// => string + +type MySchemaOut = z.output; // equivalent to z.infer +// number +``` diff --git a/node_modules/zod/index.cjs b/node_modules/zod/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..3e30380fbb5d71076cd01b3f28cad42d3d53136a --- /dev/null +++ b/node_modules/zod/index.cjs @@ -0,0 +1,33 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.z = void 0; +const z = __importStar(require("./v4/classic/external.cjs")); +exports.z = z; +__exportStar(require("./v4/classic/external.cjs"), exports); +exports.default = z; diff --git a/node_modules/zod/index.d.cts b/node_modules/zod/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..ed2f3c30c3db5598d4fc16ccdc532ec64e202d16 --- /dev/null +++ b/node_modules/zod/index.d.cts @@ -0,0 +1,4 @@ +import * as z from "./v4/classic/external.cjs"; +export * from "./v4/classic/external.cjs"; +export { z }; +export default z; diff --git a/node_modules/zod/index.d.ts b/node_modules/zod/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b0bbaefb767b76b3b59cf6598f08fa189e426f16 --- /dev/null +++ b/node_modules/zod/index.d.ts @@ -0,0 +1,4 @@ +import * as z from "./v4/classic/external.js"; +export * from "./v4/classic/external.js"; +export { z }; +export default z; diff --git a/node_modules/zod/index.js b/node_modules/zod/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b0bbaefb767b76b3b59cf6598f08fa189e426f16 --- /dev/null +++ b/node_modules/zod/index.js @@ -0,0 +1,4 @@ +import * as z from "./v4/classic/external.js"; +export * from "./v4/classic/external.js"; +export { z }; +export default z; diff --git a/node_modules/zod/locales/index.cjs b/node_modules/zod/locales/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..65f2079f7148d5e82c5429326d5dc0bc81b1ccef --- /dev/null +++ b/node_modules/zod/locales/index.cjs @@ -0,0 +1,17 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("../v4/locales/index.cjs"), exports); diff --git a/node_modules/zod/locales/index.d.cts b/node_modules/zod/locales/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..cd70ce63df73c2e1c1ee1c194ab73b35639c6556 --- /dev/null +++ b/node_modules/zod/locales/index.d.cts @@ -0,0 +1 @@ +export * from "../v4/locales/index.cjs"; diff --git a/node_modules/zod/locales/index.d.ts b/node_modules/zod/locales/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e6e7dd67c13286f3d529ee32ff37d25dcc848612 --- /dev/null +++ b/node_modules/zod/locales/index.d.ts @@ -0,0 +1 @@ +export * from "../v4/locales/index.js"; diff --git a/node_modules/zod/locales/index.js b/node_modules/zod/locales/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e6e7dd67c13286f3d529ee32ff37d25dcc848612 --- /dev/null +++ b/node_modules/zod/locales/index.js @@ -0,0 +1 @@ +export * from "../v4/locales/index.js"; diff --git a/node_modules/zod/locales/package.json b/node_modules/zod/locales/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f5d2e90cdae223ed38764ab1d69169a1c54b6661 --- /dev/null +++ b/node_modules/zod/locales/package.json @@ -0,0 +1,7 @@ +{ + "type": "module", + "main": "./index.cjs", + "module": "./index.js", + "types": "./index.d.cts", + "sideEffects": false +}