mirror of
https://github.com/hanzoai/workbox.git
synced 2026-09-24 17:04:35 +00:00
Initial TS linting (#2359)
* Updates various devDependencies * Swithcing back to Object * Switch node back to 8 * Revert a test changee * Adding in tslint * Linting * async OnSyncCallback * Disable unbound-method * Brought in some rules from gts
This commit is contained in:
Generated
+3096
-1881
File diff suppressed because it is too large
Load Diff
+5
-1
@@ -9,7 +9,9 @@
|
||||
"coveralls": "cat ./coverage/lcov.info | coveralls",
|
||||
"demos-deploy": "firebase deploy --project workbox-demos",
|
||||
"demos-serve": "firebase serve --only hosting,functions --project workbox-demos",
|
||||
"lint": "eslint \"**/*.{js,mjs}\" --ignore-path .gitignore",
|
||||
"lint": "npm run lint-js && npm run lint-ts",
|
||||
"lint-js": "eslint '**/*.{js,mjs}' --config javascript.eslintrc.js --ignore-path .gitignore",
|
||||
"lint-ts": "eslint '**/*.ts' --config typescript.eslintrc.js --ignore-path .gitignore",
|
||||
"local-jsdoc": "jsdoc",
|
||||
"local-lerna": "lerna",
|
||||
"local-tsc": "tsc",
|
||||
@@ -50,6 +52,8 @@
|
||||
"@babel/preset-env": "^7.8.4",
|
||||
"@google-cloud/storage": "^4.3.0",
|
||||
"@octokit/rest": "^16.43.1",
|
||||
"@typescript-eslint/eslint-plugin": "^2.19.0",
|
||||
"@typescript-eslint/parser": "^2.19.0",
|
||||
"acorn": "^7.1.0",
|
||||
"archiver": "^3.1.1",
|
||||
"babel-plugin-transform-async-to-promises": "^0.8.15",
|
||||
|
||||
@@ -17,7 +17,7 @@ import './_version.js';
|
||||
* @memberof module:workbox-background-sync
|
||||
*/
|
||||
class BackgroundSyncPlugin implements WorkboxPlugin {
|
||||
private _queue: Queue;
|
||||
private readonly _queue: Queue;
|
||||
|
||||
/**
|
||||
* @param {string} name See the [Queue]{@link module:workbox-background-sync.Queue}
|
||||
|
||||
@@ -16,14 +16,14 @@ import './_version.js';
|
||||
|
||||
|
||||
// Give TypeScript the correct global.
|
||||
declare var self: ServiceWorkerGlobalScope;
|
||||
declare let self: ServiceWorkerGlobalScope;
|
||||
|
||||
interface OnSyncCallbackOptions {
|
||||
queue: Queue;
|
||||
}
|
||||
|
||||
interface OnSyncCallback {
|
||||
(options: OnSyncCallbackOptions): void;
|
||||
(options: OnSyncCallbackOptions): void|Promise<void>;
|
||||
}
|
||||
|
||||
export interface QueueOptions {
|
||||
@@ -42,6 +42,26 @@ const MAX_RETENTION_TIME = 60 * 24 * 7; // 7 days in minutes
|
||||
|
||||
const queueNames = new Set();
|
||||
|
||||
/**
|
||||
* Converts a QueueStore entry into the format exposed by Queue. This entails
|
||||
* converting the request data into a real request and omitting the `id` and
|
||||
* `queueName` properties.
|
||||
*
|
||||
* @param {Object} queueStoreEntry
|
||||
* @return {Object}
|
||||
* @private
|
||||
*/
|
||||
const convertEntry = (queueStoreEntry: UnidentifiedQueueStoreEntry): QueueEntry => {
|
||||
const queueEntry: QueueEntry = {
|
||||
request: new StorableRequest(queueStoreEntry.requestData).toRequest(),
|
||||
timestamp: queueStoreEntry.timestamp,
|
||||
};
|
||||
if (queueStoreEntry.metadata) {
|
||||
queueEntry.metadata = queueStoreEntry.metadata;
|
||||
}
|
||||
return queueEntry;
|
||||
};
|
||||
|
||||
/**
|
||||
* A class to manage storing failed requests in IndexedDB and retrying them
|
||||
* later. All parts of the storing and replaying process are observable via
|
||||
@@ -50,12 +70,12 @@ const queueNames = new Set();
|
||||
* @memberof module:workbox-background-sync
|
||||
*/
|
||||
class Queue {
|
||||
private _name: string;
|
||||
private _onSync: OnSyncCallback;
|
||||
private _maxRetentionTime: number;
|
||||
private _queueStore: QueueStore;
|
||||
private _syncInProgress: boolean = false;
|
||||
private _requestsAddedDuringSync: boolean = false;
|
||||
private readonly _name: string;
|
||||
private readonly _onSync: OnSyncCallback;
|
||||
private readonly _maxRetentionTime: number;
|
||||
private readonly _queueStore: QueueStore;
|
||||
private _syncInProgress = false;
|
||||
private _requestsAddedDuringSync = false;
|
||||
|
||||
/**
|
||||
* Creates an instance of Queue with the given options
|
||||
@@ -409,25 +429,4 @@ class Queue {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Converts a QueueStore entry into the format exposed by Queue. This entails
|
||||
* converting the request data into a real request and omitting the `id` and
|
||||
* `queueName` properties.
|
||||
*
|
||||
* @param {Object} queueStoreEntry
|
||||
* @return {Object}
|
||||
* @private
|
||||
*/
|
||||
const convertEntry = (queueStoreEntry: UnidentifiedQueueStoreEntry): QueueEntry => {
|
||||
const queueEntry: QueueEntry = {
|
||||
request: new StorableRequest(queueStoreEntry.requestData).toRequest(),
|
||||
timestamp: queueStoreEntry.timestamp,
|
||||
};
|
||||
if (queueStoreEntry.metadata) {
|
||||
queueEntry.metadata = queueStoreEntry.metadata;
|
||||
}
|
||||
return queueEntry;
|
||||
};
|
||||
|
||||
export {Queue};
|
||||
|
||||
@@ -36,8 +36,8 @@ export interface QueueStoreEntry extends UnidentifiedQueueStoreEntry {
|
||||
* @private
|
||||
*/
|
||||
export class QueueStore {
|
||||
private _queueName: string;
|
||||
private _db: DBWrapper;
|
||||
private readonly _queueName: string;
|
||||
private readonly _db: DBWrapper;
|
||||
|
||||
/**
|
||||
* Associates this instance with a Queue instance, so entries added can be
|
||||
@@ -203,7 +203,7 @@ export class QueueStore {
|
||||
* @private
|
||||
*/
|
||||
private _upgradeDb(event: IDBVersionChangeEvent) {
|
||||
const db = (<IDBOpenDBRequest> event.target).result;
|
||||
const db = (event.target as IDBOpenDBRequest).result;
|
||||
|
||||
if (event.oldVersion > 0 && event.oldVersion < DB_VERSION) {
|
||||
if (db.objectStoreNames.contains(OBJECT_STORE_NAME)) {
|
||||
|
||||
@@ -40,7 +40,7 @@ export interface RequestData {
|
||||
* @private
|
||||
*/
|
||||
class StorableRequest {
|
||||
private _requestData: RequestData;
|
||||
private readonly _requestData: RequestData;
|
||||
|
||||
/**
|
||||
* Converts a Request object to a plain object that can be structured
|
||||
|
||||
@@ -24,11 +24,11 @@ const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
|
||||
|
||||
|
||||
// Give TypeScript the correct global.
|
||||
declare var self: ServiceWorkerGlobalScope;
|
||||
declare let self: ServiceWorkerGlobalScope;
|
||||
|
||||
export interface BroadcastCacheUpdateOptions {
|
||||
headersToCheck?: string[];
|
||||
generatePayload?: (options: CacheDidUpdateCallbackParam) => Object;
|
||||
generatePayload?: (options: CacheDidUpdateCallbackParam) => Record<string, any>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -38,7 +38,7 @@ export interface BroadcastCacheUpdateOptions {
|
||||
* @return Object
|
||||
* @private
|
||||
*/
|
||||
function defaultPayloadGenerator(data: CacheDidUpdateCallbackParam): Object {
|
||||
function defaultPayloadGenerator(data: CacheDidUpdateCallbackParam): Record<string, any> {
|
||||
return {
|
||||
cacheName: data.cacheName,
|
||||
updatedURL: data.request.url,
|
||||
@@ -55,8 +55,8 @@ function defaultPayloadGenerator(data: CacheDidUpdateCallbackParam): Object {
|
||||
* @memberof module:workbox-broadcast-update
|
||||
*/
|
||||
class BroadcastCacheUpdate {
|
||||
private _headersToCheck: string[];
|
||||
private _generatePayload: (options: CacheDidUpdateCallbackParam) => Object;
|
||||
private readonly _headersToCheck: string[];
|
||||
private readonly _generatePayload: (options: CacheDidUpdateCallbackParam) => Record<string, any>;
|
||||
|
||||
/**
|
||||
* Construct a BroadcastCacheUpdate instance with a specific `channelName` to
|
||||
@@ -136,7 +136,7 @@ class BroadcastCacheUpdate {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!responsesAreSame(options.oldResponse!, options.newResponse, this._headersToCheck)) {
|
||||
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);
|
||||
|
||||
@@ -20,7 +20,7 @@ import './_version.js';
|
||||
* @memberof module:workbox-broadcast-update
|
||||
*/
|
||||
class BroadcastUpdatePlugin implements WorkboxPlugin {
|
||||
private _broadcastUpdate: BroadcastCacheUpdate;
|
||||
private readonly _broadcastUpdate: BroadcastCacheUpdate;
|
||||
|
||||
/**
|
||||
* Construct a BroadcastCacheUpdate instance with the passed options and
|
||||
|
||||
@@ -27,8 +27,8 @@ export interface CacheableResponseOptions {
|
||||
* @memberof module:workbox-cacheable-response
|
||||
*/
|
||||
class CacheableResponse {
|
||||
private _statuses?: CacheableResponseOptions['statuses'];
|
||||
private _headers?: CacheableResponseOptions['headers'];
|
||||
private readonly _statuses?: CacheableResponseOptions['statuses'];
|
||||
private readonly _headers?: CacheableResponseOptions['headers'];
|
||||
|
||||
/**
|
||||
* To construct a new CacheableResponse instance you must provide at least
|
||||
|
||||
@@ -18,7 +18,7 @@ import './_version.js';
|
||||
* @memberof module:workbox-cacheable-response
|
||||
*/
|
||||
class CacheableResponsePlugin implements WorkboxPlugin {
|
||||
private _cacheableResponse: CacheableResponse;
|
||||
private readonly _cacheableResponse: CacheableResponse;
|
||||
|
||||
/**
|
||||
* To construct a new CacheableResponsePlugin instance you must provide at
|
||||
|
||||
@@ -20,11 +20,11 @@ interface DBWrapperOptions {
|
||||
}
|
||||
|
||||
interface GetAllMatchingOptions {
|
||||
index?: string,
|
||||
query?: Query,
|
||||
direction?: IDBCursorDirection,
|
||||
count?: number,
|
||||
includeKeys?: boolean,
|
||||
index?: string;
|
||||
query?: Query;
|
||||
direction?: IDBCursorDirection;
|
||||
count?: number;
|
||||
includeKeys?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -35,10 +35,10 @@ interface GetAllMatchingOptions {
|
||||
* @private
|
||||
*/
|
||||
export class DBWrapper {
|
||||
private _name: string;
|
||||
private _version: number;
|
||||
private _onupgradeneeded?: DBWrapperOptions['onupgradeneeded'];
|
||||
private _onversionchange: DBWrapperOptions['onversionchange'];
|
||||
private readonly _name: string;
|
||||
private readonly _version: number;
|
||||
private readonly _onupgradeneeded?: DBWrapperOptions['onupgradeneeded'];
|
||||
private readonly _onversionchange: DBWrapperOptions['onversionchange'];
|
||||
private _db: IDBDatabase | null = null;
|
||||
|
||||
// The following IDBObjectStore methods are shadowed on this class.
|
||||
@@ -63,7 +63,7 @@ export class DBWrapper {
|
||||
constructor(name: string, version: number, {
|
||||
onupgradeneeded,
|
||||
onversionchange,
|
||||
} : DBWrapperOptions = {}) {
|
||||
}: DBWrapperOptions = {}) {
|
||||
this._name = name;
|
||||
this._version = version;
|
||||
this._onupgradeneeded = onupgradeneeded;
|
||||
@@ -76,7 +76,7 @@ export class DBWrapper {
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
get db() : IDBDatabase | null {
|
||||
get db(): IDBDatabase | null {
|
||||
return this._db;
|
||||
}
|
||||
|
||||
@@ -194,7 +194,7 @@ export class DBWrapper {
|
||||
direction = 'next',
|
||||
count,
|
||||
includeKeys = false,
|
||||
} : GetAllMatchingOptions = {}) : Promise<Array<IDBCursor | any>> {
|
||||
}: GetAllMatchingOptions = {}): Promise<Array<IDBCursor | any>> {
|
||||
return await this.transaction([storeName], 'readonly', (txn, done) => {
|
||||
const store = txn.objectStore(storeName);
|
||||
const target = index ? store.index(index) : store;
|
||||
@@ -238,7 +238,7 @@ export class DBWrapper {
|
||||
storeNames: string | string[],
|
||||
type: IDBTransactionMode,
|
||||
callback: (txn: IDBTransaction, done: Function) => void,
|
||||
) : Promise<any> {
|
||||
): Promise<any> {
|
||||
await this.open();
|
||||
return await new Promise((resolve, reject) => {
|
||||
const txn = this._db!.transaction(storeNames, type);
|
||||
@@ -269,7 +269,7 @@ export class DBWrapper {
|
||||
const objStore = txn.objectStore(storeName);
|
||||
// TODO(philipwalton): Fix this underlying TS2684 error.
|
||||
// @ts-ignore
|
||||
const request = <IDBRequest> objStore[method].apply(objStore, args);
|
||||
const request = objStore[method].apply(objStore, args);
|
||||
|
||||
request.onsuccess = () => done(request.result);
|
||||
};
|
||||
@@ -312,12 +312,12 @@ for (const [mode, methods] of Object.entries(methodsToWrap)) {
|
||||
for (const method of methods) {
|
||||
if (method in IDBObjectStore.prototype) {
|
||||
// Don't use arrow functions here since we're outside of the class.
|
||||
DBWrapper.prototype[<IDBObjectStoreMethods> method] =
|
||||
DBWrapper.prototype[method as IDBObjectStoreMethods] =
|
||||
async function(storeName: string, ...args: any[]) {
|
||||
return await this._call(
|
||||
<IDBObjectStoreMethods> method,
|
||||
method as IDBObjectStoreMethods,
|
||||
storeName,
|
||||
<IDBTransactionMode> mode,
|
||||
mode as IDBTransactionMode,
|
||||
...args);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -37,7 +37,7 @@ class WorkboxError extends Error {
|
||||
* be added as a key on the context object.
|
||||
*/
|
||||
constructor(errorCode: string, details?: WorkboxErrorDetails) {
|
||||
let message = messageGenerator(errorCode, details);
|
||||
const message = messageGenerator(errorCode, details);
|
||||
|
||||
super(message);
|
||||
|
||||
|
||||
@@ -89,7 +89,7 @@ const isArrayOfClass = (
|
||||
throw error;
|
||||
}
|
||||
|
||||
for (let item of value) {
|
||||
for (const item of value) {
|
||||
if (!(item instanceof expectedClass)) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
import '../_version.js';
|
||||
|
||||
|
||||
declare var registration : ServiceWorkerRegistration|undefined;
|
||||
declare let registration: ServiceWorkerRegistration|undefined;
|
||||
|
||||
export interface CacheNameDetails {
|
||||
googleAnalytics: string;
|
||||
@@ -32,7 +32,7 @@ const _cacheNameDetails: CacheNameDetails = {
|
||||
precache: 'precache-v2',
|
||||
prefix: 'workbox',
|
||||
runtime: 'runtime',
|
||||
suffix: typeof registration !== 'undefined' ? registration!.scope : '',
|
||||
suffix: typeof registration !== 'undefined' ? registration.scope : '',
|
||||
};
|
||||
|
||||
const _createCacheName = (cacheName: string): string => {
|
||||
@@ -43,7 +43,7 @@ const _createCacheName = (cacheName: string): string => {
|
||||
|
||||
const eachCacheNameDetail = (fn: Function): void => {
|
||||
for (const key of Object.keys(_cacheNameDetails)) {
|
||||
fn(<CacheNameDetailsProp> key);
|
||||
fn(key as CacheNameDetailsProp);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ export const cacheNames = {
|
||||
updateDetails: (details: PartialCacheNameDetails) => {
|
||||
eachCacheNameDetail((key: CacheNameDetailsProp) => {
|
||||
if (typeof details[key] === 'string') {
|
||||
_cacheNameDetails[key] = <string> details[key];
|
||||
_cacheNameDetails[key] = details[key];
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
@@ -26,175 +26,57 @@ interface MatchWrapperOptions {
|
||||
}
|
||||
|
||||
interface PutWrapperOptions extends MatchWrapperOptions {
|
||||
response: Response,
|
||||
response: Response;
|
||||
}
|
||||
|
||||
interface GetEffectiveRequestOptions {
|
||||
request: Request,
|
||||
mode: string,
|
||||
plugins?: WorkboxPlugin[],
|
||||
request: Request;
|
||||
mode: string;
|
||||
plugins?: WorkboxPlugin[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrapper around cache.put().
|
||||
*
|
||||
* Will call `cacheDidUpdate` on plugins if the cache was updated, using
|
||||
* `matchOptions` when determining what the old entry is.
|
||||
* 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.
|
||||
*
|
||||
* @param {Object} options
|
||||
* @param {string} options.cacheName
|
||||
* @param {Request} options.request
|
||||
* @param {Response} options.response
|
||||
* @param {Event} [options.event]
|
||||
* @param {string} options.mode
|
||||
* @param {Array<Object>} [options.plugins=[]]
|
||||
* @param {Object} [options.matchOptions]
|
||||
* @return {Promise<Request>}
|
||||
*
|
||||
* @private
|
||||
* @memberof module:workbox-core
|
||||
*/
|
||||
const putWrapper = async ({
|
||||
cacheName,
|
||||
const _getEffectiveRequest = async ({
|
||||
request,
|
||||
response,
|
||||
event,
|
||||
mode,
|
||||
plugins = [],
|
||||
matchOptions,
|
||||
} : PutWrapperOptions) : Promise<void> => {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
if (request.method && request.method !== 'GET') {
|
||||
throw new WorkboxError('attempt-to-cache-non-get-request', {
|
||||
url: getFriendlyURL(request.url),
|
||||
method: request.method,
|
||||
}: GetEffectiveRequestOptions) => {
|
||||
const cacheKeyWillBeUsedPlugins = pluginUtils.filter(
|
||||
plugins, pluginEvents.CACHE_KEY_WILL_BE_USED);
|
||||
|
||||
let effectiveRequest: Request | string = request;
|
||||
for (const plugin of cacheKeyWillBeUsedPlugins) {
|
||||
effectiveRequest = await plugin[pluginEvents.CACHE_KEY_WILL_BE_USED]!.call(
|
||||
plugin, {mode, request: effectiveRequest});
|
||||
|
||||
if (typeof effectiveRequest === 'string') {
|
||||
effectiveRequest = new Request(effectiveRequest);
|
||||
}
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
assert!.isInstance(effectiveRequest, Request, {
|
||||
moduleName: 'Plugin',
|
||||
funcName: pluginEvents.CACHE_KEY_WILL_BE_USED,
|
||||
isReturnValueProblem: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const effectiveRequest = await _getEffectiveRequest({
|
||||
plugins, request, mode: 'write'});
|
||||
|
||||
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),
|
||||
});
|
||||
}
|
||||
|
||||
let responseToCache = await _isResponseSafeToCache({
|
||||
event,
|
||||
plugins,
|
||||
response,
|
||||
request: effectiveRequest,
|
||||
});
|
||||
|
||||
if (!responseToCache) {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
logger.debug(`Response '${getFriendlyURL(effectiveRequest.url)}' will ` +
|
||||
`not be cached.`, responseToCache);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const cache = await self.caches.open(cacheName);
|
||||
|
||||
const updatePlugins = pluginUtils.filter(
|
||||
plugins, pluginEvents.CACHE_DID_UPDATE);
|
||||
|
||||
let oldResponse = updatePlugins.length > 0 ?
|
||||
await matchWrapper({cacheName, matchOptions, request: effectiveRequest}) :
|
||||
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, responseToCache);
|
||||
} catch (error) {
|
||||
// See https://developer.mozilla.org/en-US/docs/Web/API/DOMException#exception-QuotaExceededError
|
||||
if (error.name === 'QuotaExceededError') {
|
||||
await executeQuotaErrorCallbacks();
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
for (let plugin of updatePlugins) {
|
||||
await plugin[pluginEvents.CACHE_DID_UPDATE]!.call(plugin, {
|
||||
cacheName,
|
||||
event,
|
||||
oldResponse,
|
||||
newResponse: responseToCache,
|
||||
request: effectiveRequest,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* This is a wrapper around cache.match().
|
||||
*
|
||||
* @param {Object} options
|
||||
* @param {string} options.cacheName Name of the cache to match against.
|
||||
* @param {Request} options.request The Request that will be used to look up
|
||||
* cache entries.
|
||||
* @param {Event} [options.event] The event that prompted the action.
|
||||
* @param {Object} [options.matchOptions] Options passed to cache.match().
|
||||
* @param {Array<Object>} [options.plugins=[]] Array of plugins.
|
||||
* @return {Response} A cached response if available.
|
||||
*
|
||||
* @private
|
||||
* @memberof module:workbox-core
|
||||
*/
|
||||
const matchWrapper = async ({
|
||||
cacheName,
|
||||
request,
|
||||
event,
|
||||
matchOptions,
|
||||
plugins = [],
|
||||
} : MatchWrapperOptions) : Promise<Response|undefined> => {
|
||||
const cache = await self.caches.open(cacheName);
|
||||
|
||||
const effectiveRequest = await _getEffectiveRequest({
|
||||
plugins, request, mode: 'read'});
|
||||
|
||||
let cachedResponse = await cache.match(effectiveRequest, matchOptions);
|
||||
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 plugin of plugins) {
|
||||
if (pluginEvents.CACHED_RESPONSE_WILL_BE_USED in plugin) {
|
||||
const pluginMethod =
|
||||
<Function> plugin[pluginEvents.CACHED_RESPONSE_WILL_BE_USED];
|
||||
|
||||
cachedResponse = await pluginMethod.call(plugin, {
|
||||
cacheName,
|
||||
event,
|
||||
matchOptions,
|
||||
cachedResponse,
|
||||
request: effectiveRequest,
|
||||
});
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
if (cachedResponse) {
|
||||
assert!.isInstance(cachedResponse, Response, {
|
||||
moduleName: 'Plugin',
|
||||
funcName: pluginEvents.CACHED_RESPONSE_WILL_BE_USED,
|
||||
isReturnValueProblem: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return cachedResponse;
|
||||
return effectiveRequest;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -216,19 +98,19 @@ const _isResponseSafeToCache = async ({
|
||||
response,
|
||||
event,
|
||||
plugins = [],
|
||||
} : {
|
||||
request: Request,
|
||||
response: Response,
|
||||
event?: Event,
|
||||
plugins?: WorkboxPlugin[],
|
||||
}: {
|
||||
request: Request;
|
||||
response: Response;
|
||||
event?: Event;
|
||||
plugins?: WorkboxPlugin[];
|
||||
}) => {
|
||||
let responseToCache: Response|undefined = response;
|
||||
let pluginsUsed = false;
|
||||
for (let plugin of plugins) {
|
||||
for (const plugin of plugins) {
|
||||
if (pluginEvents.CACHE_WILL_UPDATE in plugin) {
|
||||
pluginsUsed = true;
|
||||
|
||||
const pluginMethod = <Function> plugin[pluginEvents.CACHE_WILL_UPDATE];
|
||||
const pluginMethod = plugin[pluginEvents.CACHE_WILL_UPDATE] as Function;
|
||||
responseToCache = await pluginMethod.call(plugin, {
|
||||
request,
|
||||
response: responseToCache,
|
||||
@@ -276,47 +158,165 @@ const _isResponseSafeToCache = async ({
|
||||
};
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* This is a wrapper around cache.match().
|
||||
*
|
||||
* @param {Object} options
|
||||
* @param {Request} options.request
|
||||
* @param {string} options.mode
|
||||
* @param {Array<Object>} [options.plugins=[]]
|
||||
* @return {Promise<Request>}
|
||||
* @param {string} options.cacheName Name of the cache to match against.
|
||||
* @param {Request} options.request The Request that will be used to look up
|
||||
* cache entries.
|
||||
* @param {Event} [options.event] The event that prompted the action.
|
||||
* @param {Object} [options.matchOptions] Options passed to cache.match().
|
||||
* @param {Array<Object>} [options.plugins=[]] Array of plugins.
|
||||
* @return {Response} A cached response if available.
|
||||
*
|
||||
* @private
|
||||
* @memberof module:workbox-core
|
||||
*/
|
||||
const _getEffectiveRequest = async ({
|
||||
const matchWrapper = async ({
|
||||
cacheName,
|
||||
request,
|
||||
mode,
|
||||
event,
|
||||
matchOptions,
|
||||
plugins = [],
|
||||
} : GetEffectiveRequestOptions) => {
|
||||
const cacheKeyWillBeUsedPlugins = pluginUtils.filter(
|
||||
plugins, pluginEvents.CACHE_KEY_WILL_BE_USED);
|
||||
}: MatchWrapperOptions): Promise<Response|undefined> => {
|
||||
const cache = await self.caches.open(cacheName);
|
||||
|
||||
let effectiveRequest: Request | string = request;
|
||||
for (const plugin of cacheKeyWillBeUsedPlugins) {
|
||||
effectiveRequest = await plugin[pluginEvents.CACHE_KEY_WILL_BE_USED]!.call(
|
||||
plugin, {mode, request: effectiveRequest});
|
||||
const effectiveRequest = await _getEffectiveRequest({
|
||||
plugins, request, mode: 'read'});
|
||||
|
||||
if (typeof effectiveRequest === 'string') {
|
||||
effectiveRequest = new Request(effectiveRequest);
|
||||
let cachedResponse = await cache.match(effectiveRequest, matchOptions);
|
||||
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}'.`);
|
||||
}
|
||||
}
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
assert!.isInstance(effectiveRequest, Request, {
|
||||
moduleName: 'Plugin',
|
||||
funcName: pluginEvents.CACHE_KEY_WILL_BE_USED,
|
||||
isReturnValueProblem: true,
|
||||
for (const plugin of plugins) {
|
||||
if (pluginEvents.CACHED_RESPONSE_WILL_BE_USED in plugin) {
|
||||
const pluginMethod =
|
||||
plugin[pluginEvents.CACHED_RESPONSE_WILL_BE_USED] as Function;
|
||||
|
||||
cachedResponse = await pluginMethod.call(plugin, {
|
||||
cacheName,
|
||||
event,
|
||||
matchOptions,
|
||||
cachedResponse,
|
||||
request: effectiveRequest,
|
||||
});
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
if (cachedResponse) {
|
||||
assert!.isInstance(cachedResponse, Response, {
|
||||
moduleName: 'Plugin',
|
||||
funcName: pluginEvents.CACHED_RESPONSE_WILL_BE_USED,
|
||||
isReturnValueProblem: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return cachedResponse;
|
||||
};
|
||||
|
||||
/**
|
||||
* Wrapper around cache.put().
|
||||
*
|
||||
* Will call `cacheDidUpdate` on plugins if the cache was updated, using
|
||||
* `matchOptions` when determining what the old entry is.
|
||||
*
|
||||
* @param {Object} options
|
||||
* @param {string} options.cacheName
|
||||
* @param {Request} options.request
|
||||
* @param {Response} options.response
|
||||
* @param {Event} [options.event]
|
||||
* @param {Array<Object>} [options.plugins=[]]
|
||||
* @param {Object} [options.matchOptions]
|
||||
*
|
||||
* @private
|
||||
* @memberof module:workbox-core
|
||||
*/
|
||||
const putWrapper = async ({
|
||||
cacheName,
|
||||
request,
|
||||
response,
|
||||
event,
|
||||
plugins = [],
|
||||
matchOptions,
|
||||
}: PutWrapperOptions): Promise<void> => {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
if (request.method && request.method !== 'GET') {
|
||||
throw new WorkboxError('attempt-to-cache-non-get-request', {
|
||||
url: getFriendlyURL(request.url),
|
||||
method: request.method,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return effectiveRequest;
|
||||
const effectiveRequest = await _getEffectiveRequest({
|
||||
plugins, request, mode: 'write'});
|
||||
|
||||
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 _isResponseSafeToCache({
|
||||
event,
|
||||
plugins,
|
||||
response,
|
||||
request: effectiveRequest,
|
||||
});
|
||||
|
||||
if (!responseToCache) {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
logger.debug(`Response '${getFriendlyURL(effectiveRequest.url)}' will ` +
|
||||
`not be cached.`, responseToCache);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const cache = await self.caches.open(cacheName);
|
||||
|
||||
const updatePlugins = pluginUtils.filter(
|
||||
plugins, pluginEvents.CACHE_DID_UPDATE);
|
||||
|
||||
const oldResponse = updatePlugins.length > 0 ?
|
||||
await matchWrapper({cacheName, matchOptions, request: effectiveRequest}) :
|
||||
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, responseToCache);
|
||||
} catch (error) {
|
||||
// See https://developer.mozilla.org/en-US/docs/Web/API/DOMException#exception-QuotaExceededError
|
||||
if (error.name === 'QuotaExceededError') {
|
||||
await executeQuotaErrorCallbacks();
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
for (const plugin of updatePlugins) {
|
||||
await plugin[pluginEvents.CACHE_DID_UPDATE]!.call(plugin, {
|
||||
cacheName,
|
||||
event,
|
||||
oldResponse,
|
||||
newResponse: responseToCache,
|
||||
request: effectiveRequest,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const cacheWrapper = {
|
||||
|
||||
@@ -43,7 +43,7 @@ const wrappedFetch = async ({
|
||||
fetchOptions,
|
||||
event,
|
||||
plugins = [],
|
||||
} : WrappedFetchOptions) => {
|
||||
}: WrappedFetchOptions) => {
|
||||
|
||||
if (typeof request === 'string') {
|
||||
request = new Request(request);
|
||||
@@ -83,15 +83,15 @@ const wrappedFetch = async ({
|
||||
request.clone() : null;
|
||||
|
||||
try {
|
||||
for (let plugin of plugins) {
|
||||
for (const plugin of plugins) {
|
||||
if (pluginEvents.REQUEST_WILL_FETCH in plugin) {
|
||||
const pluginMethod = plugin[pluginEvents.REQUEST_WILL_FETCH]!;
|
||||
const requestClone = (<Request> request).clone();
|
||||
const requestClone = request.clone();
|
||||
|
||||
request = <Request> (await pluginMethod.call(plugin, {
|
||||
request = await pluginMethod.call(plugin, {
|
||||
request: requestClone,
|
||||
event,
|
||||
}));
|
||||
}) as Request;
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
if (request) {
|
||||
@@ -113,7 +113,7 @@ const wrappedFetch = async ({
|
||||
// The request can be altered by plugins with `requestWillFetch` making
|
||||
// the original request (Most likely from a `fetch` event) to be different
|
||||
// to the Request we make. Pass both to `fetchDidFail` to aid debugging.
|
||||
let pluginFilteredRequest = request.clone();
|
||||
const pluginFilteredRequest = request.clone();
|
||||
|
||||
try {
|
||||
let fetchResponse;
|
||||
|
||||
@@ -20,10 +20,10 @@ declare global {
|
||||
|
||||
type LoggerMethods = 'debug'|'log'|'warn'|'error'|'groupCollapsed'|'groupEnd';
|
||||
|
||||
const logger = <Console> (process.env.NODE_ENV === 'production' ? null : (() => {
|
||||
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 self!)) {
|
||||
if (!('__WB_DISABLE_DEV_LOGS' in self)) {
|
||||
self.__WB_DISABLE_DEV_LOGS = false;
|
||||
}
|
||||
|
||||
@@ -77,14 +77,14 @@ const logger = <Console> (process.env.NODE_ENV === 'production' ? null : (() =>
|
||||
const loggerMethods = Object.keys(methodToColorMap);
|
||||
|
||||
for (const key of loggerMethods) {
|
||||
const method = <LoggerMethods> key;
|
||||
const method = key as LoggerMethods;
|
||||
|
||||
api[method] = (...args: any[]) => {
|
||||
print(method, args);
|
||||
};
|
||||
}
|
||||
|
||||
return <unknown> api;
|
||||
})());
|
||||
return api as unknown;
|
||||
})()) as Console;
|
||||
|
||||
export {logger};
|
||||
|
||||
@@ -10,7 +10,7 @@ import '../_version.js';
|
||||
|
||||
|
||||
// Give TypeScript the correct global.
|
||||
declare var self: ServiceWorkerGlobalScope;
|
||||
declare let self: ServiceWorkerGlobalScope;
|
||||
|
||||
const MAX_RETRY_TIME = 2000;
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ import './_version.js';
|
||||
|
||||
|
||||
// Give TypeScript the correct global.
|
||||
declare var self: ServiceWorkerGlobalScope;
|
||||
declare let self: ServiceWorkerGlobalScope;
|
||||
|
||||
/**
|
||||
* Claim any currently available clients once the service worker
|
||||
@@ -20,6 +20,6 @@ declare var self: ServiceWorkerGlobalScope;
|
||||
*/
|
||||
function clientsClaim() {
|
||||
self.addEventListener('activate', () => self.clients.claim());
|
||||
};
|
||||
}
|
||||
|
||||
export {clientsClaim}
|
||||
|
||||
@@ -49,6 +49,6 @@ async function copyResponse(
|
||||
clonedResponse.body : await clonedResponse.blob();
|
||||
|
||||
return new Response(body, modifiedResponseInit);
|
||||
};
|
||||
}
|
||||
|
||||
export {copyResponse}
|
||||
|
||||
@@ -17,7 +17,7 @@ interface MessageMap {
|
||||
[messageID: string]: (param: MessageParam) => string;
|
||||
}
|
||||
|
||||
export const messages : MessageMap = {
|
||||
export const messages: MessageMap = {
|
||||
'invalid-value': ({paramName, validValueDescription, value}) => {
|
||||
if (!paramName || !validValueDescription) {
|
||||
throw new Error(`Unexpected input to 'invalid-value' error.`);
|
||||
|
||||
@@ -17,4 +17,4 @@ export const enum pluginEvents {
|
||||
FETCH_DID_FAIL = 'fetchDidFail',
|
||||
FETCH_DID_SUCCEED = 'fetchDidSucceed',
|
||||
REQUEST_WILL_FETCH = 'requestWillFetch',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -62,6 +62,6 @@ function setCacheNameDetails(details: PartialCacheNameDetails) {
|
||||
}
|
||||
|
||||
cacheNames.updateDetails(details);
|
||||
};
|
||||
}
|
||||
|
||||
export {setCacheNameDetails}
|
||||
|
||||
@@ -10,7 +10,7 @@ import './_version.js';
|
||||
|
||||
|
||||
// Give TypeScript the correct global.
|
||||
declare var self: ServiceWorkerGlobalScope;
|
||||
declare let self: ServiceWorkerGlobalScope;
|
||||
|
||||
/**
|
||||
* Force a service worker to activate immediately, instead of
|
||||
@@ -23,6 +23,6 @@ function skipWaiting() {
|
||||
// We need to explicitly call `self.skipWaiting()` here because we're
|
||||
// shadowing `skipWaiting` with this local function.
|
||||
self.addEventListener('install', () => self.skipWaiting());
|
||||
};
|
||||
}
|
||||
|
||||
export {skipWaiting}
|
||||
|
||||
@@ -132,7 +132,7 @@ export interface FetchDidSucceedCallbackParam {
|
||||
}
|
||||
|
||||
export interface FetchDidSucceedCallback {
|
||||
(param: FetchDidSucceedCallbackParam): Promise<Response>
|
||||
(param: FetchDidSucceedCallbackParam): Promise<Response>;
|
||||
}
|
||||
|
||||
export interface RequestWillFetchCallbackParam {
|
||||
@@ -140,7 +140,7 @@ export interface RequestWillFetchCallbackParam {
|
||||
}
|
||||
|
||||
export interface RequestWillFetchCallback {
|
||||
(param: RequestWillFetchCallbackParam): Promise<Request | void | null | undefined>
|
||||
(param: RequestWillFetchCallbackParam): Promise<Request | void | null | undefined>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -29,12 +29,12 @@ interface CacheExpirationConfig {
|
||||
* @memberof module:workbox-expiration
|
||||
*/
|
||||
class CacheExpiration {
|
||||
private _isRunning: boolean = false;
|
||||
private _rerunRequested: boolean = false;
|
||||
private _maxEntries?: number;
|
||||
private _maxAgeSeconds?: number;
|
||||
private _cacheName: string;
|
||||
private _timestampModel: CacheTimestampsModel;
|
||||
private _isRunning = false;
|
||||
private _rerunRequested = false;
|
||||
private readonly _maxEntries?: number;
|
||||
private readonly _maxAgeSeconds?: number;
|
||||
private readonly _cacheName: string;
|
||||
private readonly _timestampModel: CacheTimestampsModel;
|
||||
|
||||
/**
|
||||
* To construct a new CacheExpiration instance you must provide at least
|
||||
@@ -180,7 +180,7 @@ class CacheExpiration {
|
||||
return false;
|
||||
} else {
|
||||
const timestamp = await this._timestampModel.getTimestamp(url);
|
||||
const expireOlderThan = Date.now() - (this._maxAgeSeconds! * 1000);
|
||||
const expireOlderThan = Date.now() - (this._maxAgeSeconds * 1000);
|
||||
return (timestamp < expireOlderThan);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,8 +38,8 @@ import './_version.js';
|
||||
* @memberof module:workbox-expiration
|
||||
*/
|
||||
class ExpirationPlugin implements WorkboxPlugin {
|
||||
private _config: object;
|
||||
private _maxAgeSeconds?: number;
|
||||
private readonly _config: object;
|
||||
private readonly _maxAgeSeconds?: number;
|
||||
private _cacheExpirations: Map<string, CacheExpiration>;
|
||||
|
||||
/**
|
||||
@@ -142,7 +142,7 @@ class ExpirationPlugin implements WorkboxPlugin {
|
||||
return null;
|
||||
}
|
||||
|
||||
let isFresh = this._isResponseDateFresh(cachedResponse);
|
||||
const isFresh = this._isResponseDateFresh(cachedResponse);
|
||||
|
||||
// Expire entries to ensure that even if the expiration date has
|
||||
// expired, it'll only be used once.
|
||||
@@ -161,7 +161,7 @@ class ExpirationPlugin implements WorkboxPlugin {
|
||||
if ('request' in event) {
|
||||
logger.warn(`Unable to ensure service worker stays alive when ` +
|
||||
`updating cache entry for ` +
|
||||
`'${getFriendlyURL((<FetchEvent> event).request.url)}'.`);
|
||||
`'${getFriendlyURL((event as FetchEvent).request.url)}'.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,8 +35,8 @@ interface CacheTimestampsModelEntry {
|
||||
* @private
|
||||
*/
|
||||
class CacheTimestampsModel {
|
||||
private _cacheName: string;
|
||||
private _db: DBWrapper;
|
||||
private readonly _cacheName: string;
|
||||
private readonly _db: DBWrapper;
|
||||
|
||||
/**
|
||||
*
|
||||
@@ -60,7 +60,7 @@ class CacheTimestampsModel {
|
||||
* @private
|
||||
*/
|
||||
private _handleUpgrade(event: IDBVersionChangeEvent) {
|
||||
const db = (<IDBOpenDBRequest> event.target).result;
|
||||
const db = (event.target as IDBOpenDBRequest).result;
|
||||
|
||||
// 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
|
||||
|
||||
@@ -31,7 +31,7 @@ import './_version.js';
|
||||
|
||||
interface GoogleAnalyticsInitializeOptions {
|
||||
cacheName?: string;
|
||||
parameterOverrides?: {[paramName: string]: string},
|
||||
parameterOverrides?: {[paramName: string]: string};
|
||||
hitFilter?: (params: URLSearchParams) => void;
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ import './_version.js';
|
||||
|
||||
|
||||
// Give TypeScript the correct global.
|
||||
declare var self: ServiceWorkerGlobalScope;
|
||||
declare let self: ServiceWorkerGlobalScope;
|
||||
|
||||
/**
|
||||
* If the browser supports Navigation Preload, then this will disable it.
|
||||
|
||||
@@ -12,7 +12,7 @@ import './_version.js';
|
||||
|
||||
|
||||
// Give TypeScript the correct global.
|
||||
declare var self: ServiceWorkerGlobalScope;
|
||||
declare let self: ServiceWorkerGlobalScope;
|
||||
|
||||
/**
|
||||
* If the browser supports Navigation Preload, then this will enable it.
|
||||
|
||||
@@ -10,7 +10,7 @@ import './_version.js';
|
||||
|
||||
|
||||
// Give TypeScript the correct global.
|
||||
declare var self: ServiceWorkerGlobalScope;
|
||||
declare let self: ServiceWorkerGlobalScope;
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether or not the current browser supports enabling
|
||||
|
||||
@@ -30,10 +30,10 @@ import './_version.js';
|
||||
* @memberof module:workbox-precaching
|
||||
*/
|
||||
class PrecacheController {
|
||||
private _cacheName: string;
|
||||
private _urlsToCacheKeys: Map<string, string>;
|
||||
private _urlsToCacheModes: Map<string, "reload" | "default" | "no-store" | "no-cache" | "force-cache" | "only-if-cached">;
|
||||
private _cacheKeysToIntegrities: Map<string, string>;
|
||||
private readonly _cacheName: string;
|
||||
private readonly _urlsToCacheKeys: Map<string, string>;
|
||||
private readonly _urlsToCacheModes: Map<string, "reload" | "default" | "no-store" | "no-cache" | "force-cache" | "only-if-cached">;
|
||||
private readonly _cacheKeysToIntegrities: Map<string, string>;
|
||||
|
||||
/**
|
||||
* Create a new PrecacheController.
|
||||
@@ -126,8 +126,8 @@ class PrecacheController {
|
||||
* @return {Promise<module:workbox-precaching.InstallResult>}
|
||||
*/
|
||||
async install({event, plugins}: {
|
||||
event?: ExtendableEvent,
|
||||
plugins?: WorkboxPlugin[],
|
||||
event?: ExtendableEvent;
|
||||
plugins?: WorkboxPlugin[];
|
||||
} = {}) {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
if (plugins) {
|
||||
@@ -140,7 +140,7 @@ class PrecacheController {
|
||||
}
|
||||
}
|
||||
|
||||
const toBePrecached: {cacheKey: string, url: string}[] = [];
|
||||
const toBePrecached: {cacheKey: string; url: string}[] = [];
|
||||
const alreadyPrecached: string[] = [];
|
||||
|
||||
const cache = await self.caches.open(this._cacheName);
|
||||
@@ -229,12 +229,12 @@ class PrecacheController {
|
||||
* field when making the request.
|
||||
*/
|
||||
async _addURLToCache({cacheKey, url, cacheMode, event, plugins, integrity}: {
|
||||
cacheKey: string,
|
||||
url: string,
|
||||
cacheMode: "reload" | "default" | "no-store" | "no-cache" | "force-cache" | "only-if-cached" | undefined,
|
||||
event?: ExtendableEvent,
|
||||
plugins?: WorkboxPlugin[],
|
||||
integrity?: string,
|
||||
cacheKey: string;
|
||||
url: string;
|
||||
cacheMode: "reload" | "default" | "no-store" | "no-cache" | "force-cache" | "only-if-cached" | undefined;
|
||||
event?: ExtendableEvent;
|
||||
plugins?: WorkboxPlugin[];
|
||||
integrity?: string;
|
||||
}) {
|
||||
const request = new Request(url, {
|
||||
integrity,
|
||||
|
||||
@@ -14,7 +14,7 @@ export interface InstallResult {
|
||||
}
|
||||
|
||||
export interface CleanupResult {
|
||||
deletedCacheRequests: string[],
|
||||
deletedCacheRequests: string[];
|
||||
}
|
||||
|
||||
export interface PrecacheEntry {
|
||||
|
||||
@@ -20,6 +20,6 @@ import './_version.js';
|
||||
*/
|
||||
function addPlugins(newPlugins: WorkboxPlugin[]) {
|
||||
precachePlugins.add(newPlugins);
|
||||
};
|
||||
}
|
||||
|
||||
export {addPlugins};
|
||||
|
||||
@@ -41,6 +41,6 @@ function addRoute(options?: FetchListenerOptions) {
|
||||
addFetchListener(options);
|
||||
listenerAdded = true;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export {addRoute}
|
||||
export {addRoute}
|
||||
|
||||
@@ -32,6 +32,6 @@ function cleanupOutdatedCaches() {
|
||||
}
|
||||
}));
|
||||
}) as EventListener);
|
||||
};
|
||||
}
|
||||
|
||||
export {cleanupOutdatedCaches}
|
||||
|
||||
@@ -28,6 +28,6 @@ import './_version.js';
|
||||
function createHandler(fallbackToNetwork = true) {
|
||||
const precacheController = getOrCreatePrecacheController();
|
||||
return precacheController.createHandler(fallbackToNetwork);
|
||||
};
|
||||
}
|
||||
|
||||
export {createHandler}
|
||||
|
||||
@@ -30,6 +30,6 @@ import './_version.js';
|
||||
function createHandlerBoundToURL(url: string) {
|
||||
const precacheController = getOrCreatePrecacheController();
|
||||
return precacheController.createHandlerBoundToURL(url);
|
||||
};
|
||||
}
|
||||
|
||||
export {createHandlerBoundToURL}
|
||||
|
||||
@@ -32,6 +32,6 @@ import './_version.js';
|
||||
function getCacheKeyForURL(url: string) {
|
||||
const precacheController = getOrCreatePrecacheController();
|
||||
return precacheController.getCacheKeyForURL(url);
|
||||
};
|
||||
}
|
||||
|
||||
export {getCacheKeyForURL}
|
||||
|
||||
@@ -28,6 +28,6 @@ import './_version.js';
|
||||
function matchPrecache(request: string|Request) {
|
||||
const precacheController = getOrCreatePrecacheController();
|
||||
return precacheController.matchPrecache(request);
|
||||
};
|
||||
}
|
||||
|
||||
export {matchPrecache}
|
||||
|
||||
@@ -72,6 +72,6 @@ function precache(entries: Array<PrecacheEntry|string>) {
|
||||
self.addEventListener('install', installListener as EventListener);
|
||||
self.addEventListener('activate', activateListener as EventListener);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export {precache}
|
||||
|
||||
@@ -35,6 +35,6 @@ declare global {
|
||||
function precacheAndRoute(entries: Array<PrecacheEntry|string>, options?: FetchListenerOptions) {
|
||||
precache(entries);
|
||||
addRoute(options);
|
||||
};
|
||||
}
|
||||
|
||||
export {precacheAndRoute}
|
||||
|
||||
@@ -10,7 +10,7 @@ import '../_version.js';
|
||||
|
||||
|
||||
// Give TypeScript the correct global.
|
||||
declare var self: ServiceWorkerGlobalScope;
|
||||
declare let self: ServiceWorkerGlobalScope;
|
||||
|
||||
const SUBSTRING_TO_FIND = '-precache-';
|
||||
|
||||
@@ -34,7 +34,7 @@ const SUBSTRING_TO_FIND = '-precache-';
|
||||
*/
|
||||
const deleteOutdatedCaches = async (
|
||||
currentPrecacheName: string,
|
||||
substringToFind:string = SUBSTRING_TO_FIND) => {
|
||||
substringToFind: string = SUBSTRING_TO_FIND) => {
|
||||
const cacheNames = await self.caches.keys();
|
||||
|
||||
const cacheNamesToDelete = cacheNames.filter((cacheName) => {
|
||||
|
||||
@@ -22,7 +22,7 @@ import '../_version.js';
|
||||
* @private
|
||||
*/
|
||||
function calculateEffectiveBoundaries(
|
||||
blob: Blob, start?: number, end?: number): {start: number, end: number} {
|
||||
blob: Blob, start?: number, end?: number): {start: number; end: number} {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
assert!.isInstance(blob, Blob, {
|
||||
moduleName: 'workbox-range-requests',
|
||||
|
||||
@@ -19,7 +19,7 @@ import '../_version.js';
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
function parseRangeHeader(rangeHeader: string): {start?: number, end?: number} {
|
||||
function parseRangeHeader(rangeHeader: string): {start?: number; end?: number} {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
assert!.isType(rangeHeader, 'string', {
|
||||
moduleName: 'workbox-range-requests',
|
||||
|
||||
@@ -13,8 +13,8 @@ import {Handler, MatchCallbackOptions} from './_types.js';
|
||||
import './_version.js';
|
||||
|
||||
export interface NavigationRouteMatchOptions {
|
||||
allowlist?: RegExp[],
|
||||
denylist?: RegExp[],
|
||||
allowlist?: RegExp[];
|
||||
denylist?: RegExp[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -33,8 +33,8 @@ export interface NavigationRouteMatchOptions {
|
||||
* @extends module:workbox-routing.Route
|
||||
*/
|
||||
class NavigationRoute extends Route {
|
||||
private _allowlist: RegExp[];
|
||||
private _denylist: RegExp[];
|
||||
private readonly _allowlist: RegExp[];
|
||||
private readonly _denylist: RegExp[];
|
||||
|
||||
/**
|
||||
* If both `denylist` and `allowlist` are provided, the `denylist` will
|
||||
|
||||
@@ -23,7 +23,7 @@ type RequestArgs = string | [string, RequestInit?];
|
||||
interface CacheURLsMessageData {
|
||||
type: string;
|
||||
payload: {
|
||||
urlsToCache: RequestArgs[],
|
||||
urlsToCache: RequestArgs[];
|
||||
};
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ interface CacheURLsMessageData {
|
||||
* @memberof module:workbox-routing
|
||||
*/
|
||||
class Router {
|
||||
private _routes: Map<HTTPMethod, Route[]>;
|
||||
private readonly _routes: Map<HTTPMethod, Route[]>;
|
||||
private _defaultHandler?: HandlerObject;
|
||||
private _catchHandler?: HandlerObject;
|
||||
|
||||
@@ -150,8 +150,8 @@ class Router {
|
||||
* route and there's no `defaultHandler`, `undefined` is returned.
|
||||
*/
|
||||
handleRequest({request, event}: {
|
||||
request: Request,
|
||||
event?: ExtendableEvent,
|
||||
request: Request;
|
||||
event?: ExtendableEvent;
|
||||
}): Promise<Response> | undefined {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
assert!.isInstance(request, Request, {
|
||||
@@ -171,10 +171,10 @@ class Router {
|
||||
return;
|
||||
}
|
||||
|
||||
let {params, route} = this.findMatchingRoute({url, request, event});
|
||||
const {params, route} = this.findMatchingRoute({url, request, event});
|
||||
let handler = route && route.handler;
|
||||
|
||||
let debugMessages = [];
|
||||
const debugMessages = [];
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
if (handler) {
|
||||
debugMessages.push([
|
||||
@@ -265,10 +265,10 @@ class Router {
|
||||
* otherwise.
|
||||
*/
|
||||
findMatchingRoute({url, request, event}: {
|
||||
url: URL,
|
||||
request: Request,
|
||||
event?: ExtendableEvent
|
||||
}): {route?: Route, params?: HandlerCallbackOptions['params']} {
|
||||
url: URL;
|
||||
request: Request;
|
||||
event?: ExtendableEvent;
|
||||
}): {route?: Route; params?: HandlerCallbackOptions['params']} {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
assert!.isInstance(url, URL, {
|
||||
moduleName: 'workbox-routing',
|
||||
@@ -287,7 +287,7 @@ class Router {
|
||||
const routes = this._routes.get(request.method as HTTPMethod) || [];
|
||||
for (const route of routes) {
|
||||
let params;
|
||||
let matchResult = route.match({url, request, event});
|
||||
const matchResult = route.match({url, request, event});
|
||||
if (matchResult) {
|
||||
// See https://github.com/GoogleChrome/workbox/issues/2079
|
||||
params = matchResult;
|
||||
|
||||
@@ -60,7 +60,7 @@ function registerRoute(
|
||||
|
||||
// See https://github.com/pillarjs/path-to-regexp#parameters
|
||||
const wildcards = '[*:?+]';
|
||||
if (valueToCheck.match(new RegExp(`${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 ` +
|
||||
@@ -105,6 +105,6 @@ function registerRoute(
|
||||
defaultRouter.registerRoute(route);
|
||||
|
||||
return route;
|
||||
};
|
||||
}
|
||||
|
||||
export {registerRoute}
|
||||
|
||||
@@ -22,6 +22,6 @@ import './_version.js';
|
||||
function setCatchHandler(handler: Handler) {
|
||||
const defaultRouter = getOrCreateDefaultRouter();
|
||||
defaultRouter.setCatchHandler(handler);
|
||||
};
|
||||
}
|
||||
|
||||
export {setCatchHandler}
|
||||
|
||||
@@ -26,6 +26,6 @@ import './_version.js';
|
||||
function setDefaultHandler(handler: Handler) {
|
||||
const defaultRouter = getOrCreateDefaultRouter();
|
||||
defaultRouter.setDefaultHandler(handler);
|
||||
};
|
||||
}
|
||||
|
||||
export {setDefaultHandler}
|
||||
|
||||
@@ -39,10 +39,10 @@ interface CacheFirstOptions {
|
||||
* @memberof module:workbox-strategies
|
||||
*/
|
||||
class CacheFirst implements RouteHandlerObject {
|
||||
private _cacheName: string;
|
||||
private _plugins: WorkboxPlugin[];
|
||||
private _fetchOptions?: RequestInit;
|
||||
private _matchOptions?: CacheQueryOptions;
|
||||
private readonly _cacheName: string;
|
||||
private readonly _plugins: WorkboxPlugin[];
|
||||
private readonly _fetchOptions?: RequestInit;
|
||||
private readonly _matchOptions?: CacheQueryOptions;
|
||||
|
||||
/**
|
||||
* @param {Object} options
|
||||
@@ -127,7 +127,7 @@ class CacheFirst implements RouteHandlerObject {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
logger.groupCollapsed(
|
||||
messages.strategyStart('CacheFirst', request));
|
||||
for (let log of logs) {
|
||||
for (const log of logs) {
|
||||
logger.log(log);
|
||||
}
|
||||
messages.printFinalResponse(response);
|
||||
|
||||
@@ -35,9 +35,9 @@ interface CacheOnlyOptions {
|
||||
* @memberof module:workbox-strategies
|
||||
*/
|
||||
class CacheOnly implements RouteHandlerObject {
|
||||
private _cacheName: string;
|
||||
private _plugins: WorkboxPlugin[];
|
||||
private _matchOptions?: CacheQueryOptions;
|
||||
private readonly _cacheName: string;
|
||||
private readonly _plugins: WorkboxPlugin[];
|
||||
private readonly _matchOptions?: CacheQueryOptions;
|
||||
|
||||
/**
|
||||
* @param {Object} options
|
||||
|
||||
@@ -43,11 +43,11 @@ interface NetworkFirstOptions {
|
||||
* @memberof module:workbox-strategies
|
||||
*/
|
||||
class NetworkFirst implements RouteHandlerObject {
|
||||
private _cacheName: string;
|
||||
private _plugins: WorkboxPlugin[];
|
||||
private _fetchOptions?: RequestInit;
|
||||
private _matchOptions?: CacheQueryOptions;
|
||||
private _networkTimeoutSeconds: number;
|
||||
private readonly _cacheName: string;
|
||||
private readonly _plugins: WorkboxPlugin[];
|
||||
private readonly _fetchOptions?: RequestInit;
|
||||
private readonly _matchOptions?: CacheQueryOptions;
|
||||
private readonly _networkTimeoutSeconds: number;
|
||||
|
||||
/**
|
||||
* @param {Object} options
|
||||
@@ -71,7 +71,7 @@ class NetworkFirst implements RouteHandlerObject {
|
||||
this._cacheName = cacheNames.getRuntimeName(options.cacheName);
|
||||
|
||||
if (options.plugins) {
|
||||
let isUsingCacheWillUpdate =
|
||||
const isUsingCacheWillUpdate =
|
||||
options.plugins.some((plugin) => !!plugin.cacheWillUpdate);
|
||||
this._plugins = isUsingCacheWillUpdate ?
|
||||
options.plugins : [cacheOkAndOpaquePlugin, ...options.plugins];
|
||||
@@ -149,7 +149,7 @@ class NetworkFirst implements RouteHandlerObject {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
logger.groupCollapsed(
|
||||
messages.strategyStart('NetworkFirst', request));
|
||||
for (let log of logs) {
|
||||
for (const log of logs) {
|
||||
logger.log(log);
|
||||
}
|
||||
messages.printFinalResponse(response);
|
||||
@@ -172,10 +172,10 @@ class NetworkFirst implements RouteHandlerObject {
|
||||
* @private
|
||||
*/
|
||||
private _getTimeoutPromise({request, logs, event}: {
|
||||
request: Request,
|
||||
logs: any[],
|
||||
event?: ExtendableEvent,
|
||||
}): {promise: Promise<Response | undefined>, id?: number} {
|
||||
request: Request;
|
||||
logs: any[];
|
||||
event?: ExtendableEvent;
|
||||
}): {promise: Promise<Response | undefined>; id?: number} {
|
||||
let timeoutId;
|
||||
const timeoutPromise: Promise<Response | undefined> = new Promise((resolve) => {
|
||||
const onNetworkTimeout = async () => {
|
||||
@@ -210,10 +210,10 @@ class NetworkFirst implements RouteHandlerObject {
|
||||
* @private
|
||||
*/
|
||||
async _getNetworkPromise({timeoutId, request, logs, event}: {
|
||||
request: Request,
|
||||
logs: any[],
|
||||
timeoutId?: number,
|
||||
event?: ExtendableEvent,
|
||||
request: Request;
|
||||
logs: any[];
|
||||
timeoutId?: number;
|
||||
event?: ExtendableEvent;
|
||||
}): Promise<Response> {
|
||||
let error;
|
||||
let response;
|
||||
@@ -290,8 +290,8 @@ class NetworkFirst implements RouteHandlerObject {
|
||||
* @private
|
||||
*/
|
||||
private _respondFromCache({event, request}: {
|
||||
request: Request,
|
||||
event?: ExtendableEvent,
|
||||
request: Request;
|
||||
event?: ExtendableEvent;
|
||||
}): Promise<Response | undefined> {
|
||||
return cacheWrapper.match({
|
||||
cacheName: this._cacheName,
|
||||
|
||||
@@ -33,8 +33,8 @@ interface NetworkFirstOptions {
|
||||
* @memberof module:workbox-strategies
|
||||
*/
|
||||
class NetworkOnly implements RouteHandlerObject {
|
||||
private _plugins: WorkboxPlugin[];
|
||||
private _fetchOptions?: RequestInit;
|
||||
private readonly _plugins: WorkboxPlugin[];
|
||||
private readonly _fetchOptions?: RequestInit;
|
||||
|
||||
/**
|
||||
* @param {Object} options
|
||||
|
||||
@@ -47,10 +47,10 @@ interface StaleWhileRevalidateOptions {
|
||||
* @memberof module:workbox-strategies
|
||||
*/
|
||||
class StaleWhileRevalidate implements RouteHandlerObject {
|
||||
private _cacheName: string;
|
||||
private _plugins: WorkboxPlugin[];
|
||||
private _fetchOptions?: RequestInit;
|
||||
private _matchOptions?: CacheQueryOptions;
|
||||
private readonly _cacheName: string;
|
||||
private readonly _plugins: WorkboxPlugin[];
|
||||
private readonly _fetchOptions?: RequestInit;
|
||||
private readonly _matchOptions?: CacheQueryOptions;
|
||||
|
||||
/**
|
||||
* @param {Object} options
|
||||
@@ -69,7 +69,7 @@ class StaleWhileRevalidate implements RouteHandlerObject {
|
||||
this._plugins = options.plugins || [];
|
||||
|
||||
if (options.plugins) {
|
||||
let isUsingCacheWillUpdate =
|
||||
const isUsingCacheWillUpdate =
|
||||
options.plugins.some((plugin) => !!plugin.cacheWillUpdate);
|
||||
this._plugins = isUsingCacheWillUpdate ?
|
||||
options.plugins : [cacheOkAndOpaquePlugin, ...options.plugins];
|
||||
@@ -149,7 +149,7 @@ class StaleWhileRevalidate implements RouteHandlerObject {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
logger.groupCollapsed(
|
||||
messages.strategyStart('StaleWhileRevalidate', request));
|
||||
for (let log of logs) {
|
||||
for (const log of logs) {
|
||||
logger.log(log);
|
||||
}
|
||||
messages.printFinalResponse(response);
|
||||
@@ -171,8 +171,8 @@ class StaleWhileRevalidate implements RouteHandlerObject {
|
||||
* @private
|
||||
*/
|
||||
async _getFromNetwork({request, event}: {
|
||||
request: Request,
|
||||
event?: ExtendableEvent,
|
||||
request: Request;
|
||||
event?: ExtendableEvent;
|
||||
}): Promise<Response> {
|
||||
const response = await fetchWrapper.fetch({
|
||||
request,
|
||||
|
||||
@@ -45,8 +45,8 @@ function _getReaderFromSource(source: StreamSource): ReadableStreamReader {
|
||||
* @memberof module:workbox-streams
|
||||
*/
|
||||
function concatenate(sourcePromises: Promise<StreamSource>[]): {
|
||||
done: Promise<void>,
|
||||
stream: ReadableStream,
|
||||
done: Promise<void>;
|
||||
stream: ReadableStream;
|
||||
} {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
assert!.isArray(sourcePromises, {
|
||||
@@ -62,7 +62,7 @@ function concatenate(sourcePromises: Promise<StreamSource>[]): {
|
||||
});
|
||||
});
|
||||
|
||||
const streamDeferred:Deferred<void> = new Deferred();
|
||||
const streamDeferred: Deferred<void> = new Deferred();
|
||||
|
||||
let i = 0;
|
||||
const logMessages: any[] = [];
|
||||
|
||||
@@ -31,7 +31,7 @@ import './_version.js';
|
||||
*/
|
||||
function concatenateToResponse(
|
||||
sourcePromises: Promise<StreamSource>[],
|
||||
headersInit: HeadersInit): {done: Promise<void>, response: Response} {
|
||||
headersInit: HeadersInit): {done: Promise<void>; response: Response} {
|
||||
const {done, stream} = concatenate(sourcePromises);
|
||||
|
||||
const headers = createHeaders(headersInit);
|
||||
|
||||
@@ -43,21 +43,21 @@ const REGISTRATION_TIMEOUT_DURATION = 60000;
|
||||
* @memberof module:workbox-window
|
||||
*/
|
||||
class Workbox extends WorkboxEventTarget {
|
||||
private _scriptURL: string;
|
||||
private _registerOptions: RegistrationOptions = {};
|
||||
private _updateFoundCount: number = 0;
|
||||
private readonly _scriptURL: string;
|
||||
private readonly _registerOptions: RegistrationOptions = {};
|
||||
private _updateFoundCount = 0;
|
||||
|
||||
// Deferreds we can resolve later.
|
||||
private _swDeferred: Deferred<ServiceWorker> = new Deferred();
|
||||
private _activeDeferred: Deferred<ServiceWorker> = new Deferred();
|
||||
private _controllingDeferred: Deferred<ServiceWorker> = new Deferred();
|
||||
private readonly _swDeferred: Deferred<ServiceWorker> = new Deferred();
|
||||
private readonly _activeDeferred: Deferred<ServiceWorker> = new Deferred();
|
||||
private readonly _controllingDeferred: Deferred<ServiceWorker> = new Deferred();
|
||||
|
||||
private _registrationTime: DOMHighResTimeStamp = 0;
|
||||
private _isUpdate?: boolean;
|
||||
private _compatibleControllingSW?: ServiceWorker;
|
||||
private _registration?: ServiceWorkerRegistration;
|
||||
private _sw?: ServiceWorker;
|
||||
private _ownSWs: Set<ServiceWorker> = new Set();
|
||||
private readonly _ownSWs: Set<ServiceWorker> = new Set();
|
||||
private _externalSW?: ServiceWorker;
|
||||
private _waitingTimeout?: number;
|
||||
|
||||
@@ -322,10 +322,10 @@ class Workbox extends WorkboxEventTarget {
|
||||
/**
|
||||
* @private
|
||||
*/
|
||||
private _onUpdateFound = () => {
|
||||
private readonly _onUpdateFound = () => {
|
||||
// `this._registration` will never be `undefined` after an update is found.
|
||||
const registration = this._registration!;
|
||||
const installingSW = <ServiceWorker> registration.installing;
|
||||
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
|
||||
@@ -339,7 +339,7 @@ class Workbox extends WorkboxEventTarget {
|
||||
// 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:
|
||||
let updateLikelyTriggeredExternally =
|
||||
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
|
||||
@@ -392,7 +392,7 @@ class Workbox extends WorkboxEventTarget {
|
||||
* @private
|
||||
* @param {Event} originalEvent
|
||||
*/
|
||||
private _onStateChange = (originalEvent: Event) => {
|
||||
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;
|
||||
@@ -400,7 +400,7 @@ class Workbox extends WorkboxEventTarget {
|
||||
const isExternal = sw === this._externalSW;
|
||||
const eventPrefix = isExternal ? 'external' : '';
|
||||
|
||||
const eventProps: {sw: ServiceWorker, originalEvent: Event, isUpdate?: boolean} = {
|
||||
const eventProps: {sw: ServiceWorker; originalEvent: Event; isUpdate?: boolean} = {
|
||||
sw,
|
||||
originalEvent
|
||||
};
|
||||
@@ -481,7 +481,7 @@ class Workbox extends WorkboxEventTarget {
|
||||
* @private
|
||||
* @param {Event} originalEvent
|
||||
*/
|
||||
private _onControllerChange = (originalEvent: Event) => {
|
||||
private readonly _onControllerChange = (originalEvent: Event) => {
|
||||
const sw = this._sw;
|
||||
if (sw === navigator.serviceWorker.controller) {
|
||||
this.dispatchEvent(new WorkboxEvent('controlling', {
|
||||
@@ -501,7 +501,7 @@ class Workbox extends WorkboxEventTarget {
|
||||
* @private
|
||||
* @param {Event} originalEvent
|
||||
*/
|
||||
private _onMessage = async (originalEvent: MessageEvent) => {
|
||||
private readonly _onMessage = async (originalEvent: MessageEvent) => {
|
||||
const {data, source} = originalEvent;
|
||||
|
||||
// Wait until there's an "own" service worker. This is used to buffer
|
||||
|
||||
@@ -25,12 +25,12 @@ import './_version.js';
|
||||
*/
|
||||
function messageSW(sw: ServiceWorker, data: {}): Promise<any> {
|
||||
return new Promise((resolve) => {
|
||||
let messageChannel = new MessageChannel();
|
||||
const messageChannel = new MessageChannel();
|
||||
messageChannel.port1.onmessage = (event: MessageEvent) => {
|
||||
resolve(event.data);
|
||||
};
|
||||
sw.postMessage(data, [messageChannel.port2]);
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
export {messageSW}
|
||||
|
||||
@@ -18,7 +18,7 @@ export type ListenerCallback = (event: WorkboxEvent<any>) => any;
|
||||
* @private
|
||||
*/
|
||||
export class WorkboxEventTarget {
|
||||
private _eventListenerRegistry: Map<keyof WorkboxEventMap, Set<ListenerCallback>> = new Map();
|
||||
private readonly _eventListenerRegistry: Map<keyof WorkboxEventMap, Set<ListenerCallback>> = new Map();
|
||||
|
||||
/**
|
||||
* @param {string} type
|
||||
|
||||
@@ -21,4 +21,4 @@ import '../_version.js';
|
||||
export function urlsMatch(url1: string, url2: string): boolean {
|
||||
const {href} = location;
|
||||
return new URL(url1, href).href === new URL(url2, href).href;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
module.exports = {
|
||||
root: true,
|
||||
parser: '@typescript-eslint/parser',
|
||||
parserOptions: {
|
||||
project: ['./packages/*/tsconfig.json'],
|
||||
tsconfigRootDir: __dirname,
|
||||
},
|
||||
plugins: [
|
||||
'@typescript-eslint',
|
||||
],
|
||||
extends: [
|
||||
'eslint:recommended',
|
||||
'plugin:@typescript-eslint/eslint-recommended',
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
'plugin:@typescript-eslint/recommended-requiring-type-checking',
|
||||
],
|
||||
// Partially borrowed from https://github.com/google/gts/blob/8bd78c4c78526a72400f618a95a987d2a7c1a8db/.eslintrc.json
|
||||
rules: {
|
||||
'@typescript-eslint/ban-ts-ignore': 'off',
|
||||
'@typescript-eslint/camelcase': 'off',
|
||||
'@typescript-eslint/explicit-function-return-type': 'off',
|
||||
'@typescript-eslint/interface-name-prefix': 'off',
|
||||
'@typescript-eslint/no-empty-function': 'off',
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
'@typescript-eslint/no-misused-promises': 'off',
|
||||
'@typescript-eslint/no-non-null-assertion': 'off',
|
||||
'@typescript-eslint/no-use-before-define': 'off',
|
||||
'@typescript-eslint/prefer-readonly': 'error',
|
||||
'@typescript-eslint/require-await': 'off',
|
||||
'@typescript-eslint/unbound-method': 'off',
|
||||
'block-scoped-var': 'error',
|
||||
'eol-last': 'error',
|
||||
'eqeqeq': 'error',
|
||||
'no-cond-assign': 'off',
|
||||
'no-dupe-class-members': 'off',
|
||||
'no-var': 'error',
|
||||
'no-warning-comments': 'off',
|
||||
'prefer-const': 'error',
|
||||
'prefer-spread': 'off',
|
||||
},
|
||||
ignorePatterns: [
|
||||
'**/_version.ts',
|
||||
'test/**',
|
||||
],
|
||||
};
|
||||
Reference in New Issue
Block a user