Add type definitions and refactor common types

This commit is contained in:
Philip Walton
2019-07-11 17:04:22 -07:00
parent bd5c7a0ba8
commit 027d2055d3
51 changed files with 358 additions and 197 deletions
+1 -1
View File
@@ -18,7 +18,6 @@ local-builds/
firebase-debug.log
.firebase
# Generated TypeScript files and build data
tsconfig.tsbuildinfo
packages/workbox-*/**/*.d.ts
@@ -30,6 +29,7 @@ packages/workbox-broadcast-update/**/*.mjs
packages/workbox-cacheable-response/**/*.mjs
packages/workbox-core/**/*.mjs
packages/workbox-expiration/**/*.mjs
packages/workbox-google-analytics/**/*.mjs
packages/workbox-navigation-preload/**/*.mjs
packages/workbox-precaching/**/*.mjs
packages/workbox-range-requests/**/*.mjs
+1 -1
View File
@@ -19,7 +19,7 @@ const cleanPackage = async (packagePath) => {
if (await fs.pathExists(path.join(packagePath, 'src', 'index.ts'))) {
// Store the list of deleted files, so we can delete directories after.
const deletedPaths = await del([
path.posix.join(packagePath, '**/*.+(js|mjs|d.ts)'),
path.posix.join(packagePath, '**/*.+(js|mjs|d.ts|tsbuildinfo)'),
// Don't delete files in node_modules
'!**/node_modules', '!**/node_modules/**/*',
]);
@@ -6,7 +6,7 @@
https://opensource.org/licenses/MIT.
*/
import {WorkboxPlugin} from 'workbox-core/utils/pluginUtils.js';
import {WorkboxPlugin} from 'workbox-core/types.js';
import {Queue, QueueOptions} from './Queue.js';
import './_version.js';
@@ -2,9 +2,13 @@
"extends": "../../tsconfig",
"compilerOptions": {
"outDir": "./",
"rootDir": "./src"
"rootDir": "./src",
"tsBuildInfoFile": "./tsconfig.tsbuildinfo"
},
"include": [
"src/**/*.ts"
],
"references": [
{ "path": "../workbox-core/" }
]
}
@@ -7,7 +7,7 @@
*/
import {assert} from 'workbox-core/_private/assert.js';
import {WorkboxPlugin} from 'workbox-core/utils/pluginUtils.js';
import {WorkboxPlugin} from 'workbox-core/types.js';
import {BroadcastCacheUpdate, BroadcastCacheUpdateOptions} from './BroadcastCacheUpdate.js';
import './_version.js';
@@ -2,9 +2,13 @@
"extends": "../../tsconfig",
"compilerOptions": {
"outDir": "./",
"rootDir": "./src"
"rootDir": "./src",
"tsBuildInfoFile": "./tsconfig.tsbuildinfo"
},
"include": [
"src/**/*.ts"
],
"references": [
{ "path": "../workbox-core/" }
]
}
@@ -6,7 +6,7 @@
https://opensource.org/licenses/MIT.
*/
import {WorkboxPlugin} from 'workbox-core/utils/pluginUtils.js';
import {WorkboxPlugin} from 'workbox-core/types.js';
import {CacheableResponse, CacheableResponseOptions} from './CacheableResponse.js';
import './_version.js';
@@ -2,9 +2,13 @@
"extends": "../../tsconfig",
"compilerOptions": {
"outDir": "./",
"rootDir": "./src"
"rootDir": "./src",
"tsBuildInfoFile": "./tsconfig.tsbuildinfo"
},
"include": [
"src/**/*.ts"
],
"references": [
{ "path": "../workbox-core/" }
]
}
@@ -12,7 +12,8 @@ import {getFriendlyURL} from './getFriendlyURL.js';
import {logger} from './logger.js';
import {executeQuotaErrorCallbacks} from './executeQuotaErrorCallbacks.js';
import {pluginEvents} from '../models/pluginEvents.js';
import {pluginUtils, WorkboxPlugin} from '../utils/pluginUtils.js';
import {WorkboxPlugin} from '../types.js';
import {pluginUtils} from '../utils/pluginUtils.js';
import '../_version.js';
@@ -11,7 +11,8 @@ import {logger} from './logger.js';
import {assert} from './assert.js';
import {getFriendlyURL} from '../_private/getFriendlyURL.js';
import {pluginEvents} from '../models/pluginEvents.js';
import {pluginUtils, WorkboxPlugin} from '../utils/pluginUtils.js';
import {WorkboxPlugin} from '../types.js';
import {pluginUtils} from '../utils/pluginUtils.js';
import '../_version.js';
+135
View File
@@ -0,0 +1,135 @@
/*
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';
/**
* Options passed to a `RouteMatchCallback` function.
*/
export interface RouteMatchCallbackOptions {
url: URL;
request: Request;
event?: ExtendableEvent;
}
/**
* 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 {
({url, request, event}: RouteMatchCallbackOptions): any;
}
/**
* Options passed to a `RouteHandlerCallback` function.
*/
export interface RouteHandlerCallbackOptions extends RouteMatchCallbackOptions {
params?: string[] | {[paramName: string]: string};
}
/**
* 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 {
({url, request, event, params}: RouteHandlerCallbackOptions): Promise<Response>;
}
/**
* 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 RouteHandler {
handle(opts: RouteHandlerCallbackOptions): Promise<Response>;
}
interface CacheDidUpdateCallback {
({cacheName, oldResponse, newResponse, request, event}: {
cacheName: string,
oldResponse?: Response,
newResponse: Response,
request: Request,
event?: FetchEvent
}): Promise<void | null | undefined>;
}
interface CacheKeyWillBeUsedCallback {
({request, mode}: {
request: Request,
mode: string,
}): Promise<Request | string>;
}
interface CacheWillUpdateCallback {
({response, request, event}: {
response: Response,
request?: Request,
event?: ExtendableEvent,
}): Promise<Response | void | null | undefined>;
}
interface CachedResponseWillBeUsedCallback {
({cacheName, request, matchOptions, cachedResponse, event}: {
cacheName: string,
request: Request,
matchOptions?: CacheQueryOptions,
cachedResponse?: Response,
event?: ExtendableEvent,
}): Promise<Response | void | null | undefined>;
}
interface FetchDidFailCallback {
({originalRequest, request, error, event}: {
originalRequest: Request,
error: Error,
request: Request,
event?: ExtendableEvent,
}): Promise<void | null | undefined>;
}
interface FetchDidSucceedCallback {
({request, response}: {
request: Request,
response: Response,
}): Promise<Response>
}
interface RequestWillFetchCallback {
({request}: {
request: Request
}): Promise<void | null | undefined>
}
/**
* An object with optional lifecycle callback properties for the fetch and
* cache operations.
*/
export interface WorkboxPlugin {
cacheDidUpdate?: CacheDidUpdateCallback;
cacheKeyWillBeUsed?: CacheKeyWillBeUsedCallback;
cacheWillUpdate?: CacheWillUpdateCallback;
cachedResponseWillBeUsed?: CachedResponseWillBeUsedCallback;
fetchDidFail?: FetchDidFailCallback;
fetchDidSucceed?: FetchDidSucceedCallback;
requestWillFetch?: RequestWillFetchCallback;
}
+1 -46
View File
@@ -6,55 +6,10 @@
https://opensource.org/licenses/MIT.
*/
import {WorkboxPlugin} from '../types.js';
import '../_version.js';
export interface WorkboxPlugin {
cacheDidUpdate?: ({
cacheName,
oldResponse,
newResponse,
request,
event
}: {
cacheName: string,
oldResponse?: Response,
newResponse: Response,
request: Request,
event?: FetchEvent
}) => Promise<void>;
cacheKeyWillBeUsed?: Function;
cacheWillUpdate?: ({
response,
request,
event,
}: {
response: Response,
request?: Request,
event?: ExtendableEvent,
}) => Promise<Response | null | undefined>;
cachedResponseWillBeUsed?: ({
cacheName,
request,
matchOptions,
cachedResponse,
event
}: {
cacheName: string,
request: Request,
matchOptions?: CacheQueryOptions,
cachedResponse?: Response,
event?: ExtendableEvent,
}) => Promise<Response | null | undefined>;
fetchDidFail?: ({
request
}: {
request: Request
}) => Promise<void>;
fetchDidSucceed?: Function;
requestWillFetch?: Function;
}
export const pluginUtils = {
filter: (plugins: WorkboxPlugin[], callbackName: string) => {
return plugins.filter((plugin) => callbackName in plugin);
+2 -1
View File
@@ -2,7 +2,8 @@
"extends": "../../tsconfig",
"compilerOptions": {
"outDir": "./",
"rootDir": "./src"
"rootDir": "./src",
"tsBuildInfoFile": "./tsconfig.tsbuildinfo"
},
"include": [
"src/**/*.ts"
+1 -1
View File
@@ -12,7 +12,7 @@ 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 {registerQuotaErrorCallback} from 'workbox-core/registerQuotaErrorCallback.js';
import {WorkboxPlugin} from 'workbox-core/utils/pluginUtils.js';
import {WorkboxPlugin} from 'workbox-core/types.js';
import {CacheExpiration} from './CacheExpiration.js';
import './_version.js';
+5 -1
View File
@@ -2,9 +2,13 @@
"extends": "../../tsconfig",
"compilerOptions": {
"outDir": "./",
"rootDir": "./src"
"rootDir": "./src",
"tsBuildInfoFile": "./tsconfig.tsbuildinfo"
},
"include": [
"src/**/*.ts"
],
"references": [
{ "path": "../workbox-core/" }
]
}
@@ -26,8 +26,9 @@
"outputFilename": "workbox-offline-ga",
"packageType": "browser"
},
"main": "build/workbox-offline-ga.prod.js",
"main": "index.js",
"module": "index.mjs",
"types": "index.d.ts",
"dependencies": {
"workbox-background-sync": "^4.3.1",
"workbox-core": "^4.3.1",
@@ -1 +1,2 @@
try{self['workbox:google-analytics:4.3.1']&&_()}catch(e){}// eslint-disable-line
// @ts-ignore
try{self['workbox:google-analytics:4.3.1']&&_()}catch(e){}
@@ -7,9 +7,11 @@
*/
import {Plugin} from 'workbox-background-sync/Plugin.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';
@@ -26,6 +28,13 @@ import {
} from './utils/constants.js';
import './_version.js';
interface GoogleAnalyticsInitializeOptions {
cacheName?: string;
parameterOverrides?: {[paramName: string]: string},
hitFilter?: (params: URLSearchParams) => void;
}
/**
* Creates the requestWillDequeue callback to be used with the background
* sync queue plugin. The callback takes the failed request and adds the
@@ -37,8 +46,8 @@ import './_version.js';
*
* @private
*/
const createOnSyncCallback = (config) => {
return async ({queue}) => {
const createOnSyncCallback = (config: GoogleAnalyticsInitializeOptions) => {
return async ({queue}: {queue: Queue}) => {
let entry;
while (entry = await queue.shiftRequest()) {
const {request, timestamp} = entry;
@@ -53,11 +62,11 @@ const createOnSyncCallback = (config) => {
// 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 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', queueTime);
params.set('qt', String(queueTime));
// Apply `paramterOverrideds`, if set.
if (config.parameterOverrides) {
@@ -112,8 +121,9 @@ const createOnSyncCallback = (config) => {
*
* @private
*/
const createCollectRoutes = (queuePlugin) => {
const match = ({url}) => url.hostname === GOOGLE_ANALYTICS_HOST &&
const createCollectRoutes = (queuePlugin: Plugin) => {
const match = ({url}: RouteMatchCallbackOptions) =>
url.hostname === GOOGLE_ANALYTICS_HOST &&
COLLECT_PATHS_REGEX.test(url.pathname);
const handler = new NetworkOnly({
@@ -134,9 +144,11 @@ const createCollectRoutes = (queuePlugin) => {
*
* @private
*/
const createAnalyticsJsRoute = (cacheName) => {
const match = ({url}) => url.hostname === GOOGLE_ANALYTICS_HOST &&
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');
@@ -150,9 +162,11 @@ const createAnalyticsJsRoute = (cacheName) => {
*
* @private
*/
const createGtagJsRoute = (cacheName) => {
const match = ({url}) => url.hostname === GTM_HOST &&
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');
@@ -166,9 +180,11 @@ const createGtagJsRoute = (cacheName) => {
*
* @private
*/
const createGtmJsRoute = (cacheName) => {
const match = ({url}) => url.hostname === GTM_HOST &&
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');
@@ -190,7 +206,7 @@ const createGtmJsRoute = (cacheName) => {
*
* @memberof workbox.googleAnalytics
*/
const initialize = (options = {}) => {
const initialize = (options: GoogleAnalyticsInitializeOptions = {}) => {
const cacheName = cacheNames.getGoogleAnalyticsName(options.cacheName);
const queuePlugin = new Plugin(QUEUE_NAME, {
@@ -0,0 +1,17 @@
{
"extends": "../../tsconfig",
"compilerOptions": {
"outDir": "./",
"rootDir": "./src",
"tsBuildInfoFile": "./tsconfig.tsbuildinfo"
},
"include": [
"src/**/*.ts"
],
"references": [
{ "path": "../workbox-background-sync/" },
{ "path": "../workbox-core/" },
{ "path": "../workbox-routing/" },
{ "path": "../workbox-strategies/" }
]
}
@@ -2,9 +2,13 @@
"extends": "../../tsconfig",
"compilerOptions": {
"outDir": "./",
"rootDir": "./src"
"rootDir": "./src",
"tsBuildInfoFile": "./tsconfig.tsbuildinfo"
},
"include": [
"src/**/*.ts"
],
"references": [
{ "path": "../workbox-core/" }
]
}
@@ -11,7 +11,7 @@ import {cacheNames} from 'workbox-core/_private/cacheNames.js';
import {cacheWrapper} from 'workbox-core/_private/cacheWrapper.js';
import {fetchWrapper} from 'workbox-core/_private/fetchWrapper.js';
import {WorkboxError} from 'workbox-core/_private/WorkboxError.js';
import {WorkboxPlugin} from 'workbox-core/utils/pluginUtils.js';
import {WorkboxPlugin} from 'workbox-core/types.js';
import {cleanRedirect} from './utils/cleanRedirect.js';
import {createCacheKey} from './utils/createCacheKey.js';
@@ -6,7 +6,7 @@
https://opensource.org/licenses/MIT.
*/
import {WorkboxPlugin} from 'workbox-core/utils/pluginUtils.js';
import {WorkboxPlugin} from 'workbox-core/types.js';
import {precachePlugins} from './utils/precachePlugins.js';
import './_version.js';
@@ -6,7 +6,7 @@
https://opensource.org/licenses/MIT.
*/
import {WorkboxPlugin} from 'workbox-core/utils/pluginUtils.js';
import {WorkboxPlugin} from 'workbox-core/types.js';
import '../_version.js';
+5 -1
View File
@@ -2,9 +2,13 @@
"extends": "../../tsconfig",
"compilerOptions": {
"outDir": "./",
"rootDir": "./src"
"rootDir": "./src",
"tsBuildInfoFile": "./tsconfig.tsbuildinfo"
},
"include": [
"src/**/*.ts"
],
"references": [
{ "path": "../workbox-core/" }
]
}
@@ -6,7 +6,7 @@
https://opensource.org/licenses/MIT.
*/
import {WorkboxPlugin} from 'workbox-core/utils/pluginUtils.js';
import {WorkboxPlugin} from 'workbox-core/types.js';
import {createPartialResponse} from './createPartialResponse.js';
import './_version.js';
@@ -2,9 +2,13 @@
"extends": "../../tsconfig",
"compilerOptions": {
"outDir": "./",
"rootDir": "./src"
"rootDir": "./src",
"tsBuildInfoFile": "./tsconfig.tsbuildinfo"
},
"include": [
"src/**/*.ts"
],
"references": [
{ "path": "../workbox-core/" }
]
}
@@ -9,7 +9,7 @@
import {assert} from 'workbox-core/_private/assert.js';
import {logger} from 'workbox-core/_private/logger.js';
import {Route} from './Route.js';
import {handlerCallback, MatchCallbackOptions} from './_types.js';
import {HandlerCallback, MatchCallbackOptions} from './_types.js';
import './_version.js';
export interface NavigationRouteMatchOptions {
@@ -55,7 +55,7 @@ class NavigationRoute extends Route {
* match the URL's pathname and search parameter, the route will handle the
* request (assuming the blacklist doesn't match).
*/
constructor(handler: handlerCallback,
constructor(handler: HandlerCallback,
{whitelist = [/./], blacklist = []}: NavigationRouteMatchOptions = {}) {
if (process.env.NODE_ENV !== 'production') {
assert!.isArrayOfClass(whitelist, RegExp, {
+3 -3
View File
@@ -10,7 +10,7 @@ import {assert} from 'workbox-core/_private/assert.js';
import {logger} from 'workbox-core/_private/logger.js';
import {HTTPMethod} from './utils/constants.js';
import {Route} from './Route.js';
import {MatchCallbackOptions, handlerCallback, matchCallback} from './_types.js';
import {MatchCallbackOptions, HandlerCallback, MatchCallback} from './_types.js';
import './_version.js';
@@ -41,7 +41,7 @@ class RegExpRoute extends Route {
* @param {string} [method='GET'] The HTTP method to match the Route
* against.
*/
constructor(regExp: RegExp, handler: handlerCallback, method?: HTTPMethod) {
constructor(regExp: RegExp, handler: HandlerCallback, method?: HTTPMethod) {
if (process.env.NODE_ENV !== 'production') {
assert!.isInstance(regExp, RegExp, {
moduleName: 'workbox-routing',
@@ -51,7 +51,7 @@ class RegExpRoute extends Route {
});
}
const match: matchCallback = ({url}: MatchCallbackOptions) => {
const match: MatchCallback = ({url}: MatchCallbackOptions) => {
const result = regExp.exec(url.href);
// Return immediately if there's no match.
+6 -5
View File
@@ -9,9 +9,10 @@
import {assert} from 'workbox-core/_private/assert.js';
import {HTTPMethod, defaultMethod, validMethods} from './utils/constants.js';
import {normalizeHandler} from './utils/normalizeHandler.js';
import {handlerCallback, matchCallback} from './_types.js';
import {Handler, HandlerCallback, MatchCallback} from './_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
@@ -22,8 +23,8 @@ import './_version.js';
* @memberof workbox.routing
*/
class Route {
handler: {handle: handlerCallback};
match: matchCallback;
handler: Handler;
match: MatchCallback;
method: HTTPMethod;
/**
@@ -38,8 +39,8 @@ class Route {
* against.
*/
constructor(
match: matchCallback,
handler: handlerCallback,
match: MatchCallback,
handler: HandlerCallback | Handler,
method: HTTPMethod = defaultMethod) {
if (process.env.NODE_ENV !== 'production') {
assert!.isType(match, 'function', {
+7 -7
View File
@@ -12,8 +12,8 @@ import {WorkboxError} from 'workbox-core/_private/WorkboxError.js';
import {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.js';
import {Route} from './Route.js';
import {HTTPMethod} from './utils/constants.js';
import {normalizeHandler, NormalizedHandlerCallback} from './utils/normalizeHandler.js';
import {HandlerCallbackOptions, handlerCallback} from './_types.js';
import {normalizeHandler} from './utils/normalizeHandler.js';
import {Handler, HandlerCallback, HandlerCallbackOptions} from './_types.js';
import './_version.js';
@@ -46,8 +46,8 @@ interface CacheURLsMessageData {
*/
class Router {
private _routes: Map<HTTPMethod, Route[]>;
private _defaultHandler: NormalizedHandlerCallback;
private _catchHandler: NormalizedHandlerCallback;
private _defaultHandler: Handler;
private _catchHandler: Handler;
/**
* Initializes a new Router.
@@ -248,7 +248,7 @@ class Router {
logger.error(err);
logger.groupEnd();
}
return this._catchHandler.handle({url, event});
return this._catchHandler.handle({url, request, event});
});
}
@@ -320,7 +320,7 @@ class Router {
* @param {workbox.routing.Route~handlerCallback} handler A callback
* function that returns a Promise resulting in a Response.
*/
setDefaultHandler(handler: handlerCallback) {
setDefaultHandler(handler: HandlerCallback) {
this._defaultHandler = normalizeHandler(handler);
}
@@ -331,7 +331,7 @@ class Router {
* @param {workbox.routing.Route~handlerCallback} handler A callback
* function that returns a Promise resulting in a Response.
*/
setCatchHandler(handler: handlerCallback) {
setCatchHandler(handler: HandlerCallback) {
this._catchHandler = normalizeHandler(handler);
}
+15 -14
View File
@@ -6,18 +6,15 @@
https://opensource.org/licenses/MIT.
*/
import {
RouteHandler,
RouteHandlerCallback,
RouteHandlerCallbackOptions,
RouteMatchCallback,
RouteMatchCallbackOptions
} from 'workbox-core/types.js';
import './_version.js';
export interface MatchCallbackOptions {
url: URL;
request?: Request;
event?: ExtendableEvent;
}
export interface HandlerCallbackOptions extends MatchCallbackOptions {
params?: string[] | {[paramName: string]: string};
}
/**
* 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
@@ -41,7 +38,6 @@ export interface HandlerCallbackOptions extends MatchCallbackOptions {
*
* @memberof workbox.routing
*/
export type matchCallback = ({url, request, event}: MatchCallbackOptions) => any;
/**
* The "handler" callback is invoked whenever a `Router` matches a URL to a
@@ -67,6 +63,11 @@ export type matchCallback = ({url, request, event}: MatchCallbackOptions) => any
*
* @memberof workbox.routing
*/
export type handlerCallback =
({url, request, event, params}: HandlerCallbackOptions) =>
Promise<Response>;
export {
RouteHandler as Handler,
RouteHandlerCallback as HandlerCallback,
RouteHandlerCallbackOptions as HandlerCallbackOptions,
RouteMatchCallback as MatchCallback,
RouteMatchCallbackOptions as MatchCallbackOptions,
}
@@ -12,7 +12,7 @@ import {Route} from './Route.js';
import {RegExpRoute} from './RegExpRoute.js';
import {HTTPMethod} from './utils/constants.js';
import {getOrCreateDefaultRouter} from './utils/getOrCreateDefaultRouter.js';
import {matchCallback, handlerCallback} from './_types.js';
import {MatchCallback, HandlerCallback} from './_types.js';
import './_version.js';
@@ -42,8 +42,8 @@ import './_version.js';
* @alias workbox.routing.registerRoute
*/
export const registerRoute = (
capture: RegExp | string | matchCallback | Route,
handler?: handlerCallback,
capture: RegExp | string | MatchCallback | Route,
handler?: HandlerCallback,
method?: HTTPMethod): Route => {
let route;
@@ -75,7 +75,7 @@ export const registerRoute = (
}
}
const matchCallback: matchCallback = ({url}) => {
const matchCallback: MatchCallback = ({url}) => {
if (process.env.NODE_ENV !== 'production') {
if ((url.pathname === captureUrl.pathname) &&
(url.origin !== captureUrl.origin)) {
@@ -7,7 +7,7 @@
*/
import {getOrCreateDefaultRouter} from './utils/getOrCreateDefaultRouter.js';
import {handlerCallback} from './_types.js';
import {HandlerCallback} from './_types.js';
import './_version.js';
@@ -20,7 +20,7 @@ import './_version.js';
*
* @alias workbox.routing.setCatchHandler
*/
export const setCatchHandler = (handler: handlerCallback) => {
export const setCatchHandler = (handler: HandlerCallback) => {
const defaultRouter = getOrCreateDefaultRouter();
defaultRouter.setCatchHandler(handler);
};
@@ -7,7 +7,7 @@
*/
import {getOrCreateDefaultRouter} from './utils/getOrCreateDefaultRouter.js';
import {handlerCallback} from './_types.js';
import {HandlerCallback} from './_types.js';
import './_version.js';
@@ -23,7 +23,7 @@ import './_version.js';
*
* @alias workbox.routing.setDefaultHandler
*/
export const setDefaultHandler = (handler: handlerCallback) => {
export const setDefaultHandler = (handler: HandlerCallback) => {
const defaultRouter = getOrCreateDefaultRouter();
defaultRouter.setDefaultHandler(handler);
};
@@ -7,14 +7,10 @@
*/
import {assert} from 'workbox-core/_private/assert.js';
import {handlerCallback} from '../_types.js';
import {Handler, HandlerCallback} from '../_types.js';
import '../_version.js';
export interface NormalizedHandlerCallback {
handle: handlerCallback;
}
/**
* @param {function()|Object} handler Either a function, or an object with a
* 'handle' method.
@@ -22,8 +18,9 @@ export interface NormalizedHandlerCallback {
*
* @private
*/
export const normalizeHandler = (handler: handlerCallback |
{handle: handlerCallback}): {handle: handlerCallback} => {
export const normalizeHandler = (
handler: Handler | HandlerCallback
): Handler => {
if (handler && typeof handler === 'object') {
if (process.env.NODE_ENV !== 'production') {
assert!.hasMethod(handler, 'handle', {
+5 -1
View File
@@ -2,9 +2,13 @@
"extends": "../../tsconfig",
"compilerOptions": {
"outDir": "./",
"rootDir": "./src"
"rootDir": "./src",
"tsBuildInfoFile": "./tsconfig.tsbuildinfo"
},
"include": [
"src/**/*.ts"
],
"references": [
{ "path": "../workbox-core/" }
]
}
+2 -1
View File
@@ -28,6 +28,7 @@
"module": "index.mjs",
"types": "index.d.ts",
"dependencies": {
"workbox-core": "^4.3.1"
"workbox-core": "^4.3.1",
"workbox-routing": "^4.3.1"
}
}
@@ -13,9 +13,8 @@ import {fetchWrapper} from 'workbox-core/_private/fetchWrapper.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/utils/pluginUtils.js';
import {RouteHandler, RouteHandlerCallbackOptions, WorkboxPlugin} from 'workbox-core/types.js';
import {messages} from './utils/messages.js';
import {WorkboxStrategy, WorkboxStrategyHandleOptions} from './_types.js';
import './_version.js';
@@ -39,7 +38,7 @@ interface CacheFirstOptions {
*
* @memberof workbox.strategies
*/
class CacheFirst implements WorkboxStrategy {
class CacheFirst implements RouteHandler {
private _cacheName: string;
private _plugins: WorkboxPlugin[];
private _fetchOptions?: RequestInit;
@@ -74,7 +73,7 @@ class CacheFirst implements WorkboxStrategy {
* @param {Event} [options.event] The event that triggered the request.
* @return {Promise<Response>}
*/
async handle({event, request}: WorkboxStrategyHandleOptions) {
async handle({event, request}: RouteHandlerCallbackOptions): Promise<Response> {
return this.makeRequest({
event,
request: request || (event as FetchEvent).request,
@@ -96,7 +95,10 @@ class CacheFirst implements WorkboxStrategy {
be called automatically to extend the service worker's lifetime.
* @return {Promise<Response>}
*/
async makeRequest({event, request}: WorkboxStrategyHandleOptions) {
async makeRequest({event, request}: {
request: Request,
event?: ExtendableEvent
}): Promise<Response> {
const logs = [];
if (typeof request === 'string') {
+7 -5
View File
@@ -11,9 +11,8 @@ import {cacheNames} from 'workbox-core/_private/cacheNames.js';
import {cacheWrapper} from 'workbox-core/_private/cacheWrapper.js';
import {logger} from 'workbox-core/_private/logger.js';
import {WorkboxError} from 'workbox-core/_private/WorkboxError.js';
import {WorkboxPlugin} from 'workbox-core/utils/pluginUtils.js';
import {RouteHandler, RouteHandlerCallbackOptions, WorkboxPlugin} from 'workbox-core/types.js';
import {messages} from './utils/messages.js';
import {WorkboxStrategy, WorkboxStrategyHandleOptions} from './_types.js';
import './_version.js';
@@ -35,7 +34,7 @@ interface CacheOnlyOptions {
*
* @memberof workbox.strategies
*/
class CacheOnly implements WorkboxStrategy {
class CacheOnly implements RouteHandler {
private _cacheName: string;
private _plugins: WorkboxPlugin[];
private _matchOptions?: CacheQueryOptions;
@@ -65,7 +64,7 @@ class CacheOnly implements WorkboxStrategy {
* @param {Event} [options.event] The event that triggered the request.
* @return {Promise<Response>}
*/
async handle({event, request}: WorkboxStrategyHandleOptions) {
async handle({event, request}: RouteHandlerCallbackOptions): Promise<Response> {
return this.makeRequest({
event,
request: request || (event as FetchEvent).request,
@@ -87,7 +86,10 @@ class CacheOnly implements WorkboxStrategy {
* be called automatically to extend the service worker's lifetime.
* @return {Promise<Response>}
*/
async makeRequest({event, request}: WorkboxStrategyHandleOptions) {
async makeRequest({event, request}: {
request: Request,
event?: ExtendableEvent
}): Promise<Response> {
if (typeof request === 'string') {
request = new Request(request);
}
@@ -13,10 +13,9 @@ import {fetchWrapper} from 'workbox-core/_private/fetchWrapper.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/utils/pluginUtils.js';
import {RouteHandler, RouteHandlerCallbackOptions, WorkboxPlugin} from 'workbox-core/types.js';
import {messages} from './utils/messages.js';
import {cacheOkAndOpaquePlugin} from './plugins/cacheOkAndOpaquePlugin.js';
import {WorkboxStrategy, WorkboxStrategyHandleOptions} from './_types.js';
import './_version.js';
@@ -43,7 +42,7 @@ interface NetworkFirstOptions {
*
* @memberof workbox.strategies
*/
class NetworkFirst implements WorkboxStrategy {
class NetworkFirst implements RouteHandler {
private _cacheName: string;
private _plugins: WorkboxPlugin[];
private _fetchOptions?: RequestInit;
@@ -107,7 +106,7 @@ class NetworkFirst implements WorkboxStrategy {
* @param {Event} [options.event] The event that triggered the request.
* @return {Promise<Response>}
*/
async handle({event, request}: WorkboxStrategyHandleOptions) {
async handle({event, request}: RouteHandlerCallbackOptions): Promise<Response> {
return this.makeRequest({
event,
request: request || (event as FetchEvent).request,
@@ -129,8 +128,11 @@ class NetworkFirst implements WorkboxStrategy {
* be called automatically to extend the service worker's lifetime.
* @return {Promise<Response>}
*/
async makeRequest({event, request}: WorkboxStrategyHandleOptions) {
const logs: any[] = [];
async makeRequest({event, request}: {
request: Request,
event?: ExtendableEvent
}): Promise<Response> {
const logs: any[] = [];
if (typeof request === 'string') {
request = new Request(request);
@@ -10,9 +10,8 @@ import {assert} from 'workbox-core/_private/assert.js';
import {fetchWrapper} from 'workbox-core/_private/fetchWrapper.js';
import {logger} from 'workbox-core/_private/logger.js';
import {WorkboxError} from 'workbox-core/_private/WorkboxError.js';
import {WorkboxPlugin} from 'workbox-core/utils/pluginUtils.js';
import {RouteHandler, RouteHandlerCallbackOptions, WorkboxPlugin} from 'workbox-core/types.js';
import {messages} from './utils/messages.js';
import {WorkboxStrategy, WorkboxStrategyHandleOptions} from './_types.js';
import './_version.js';
@@ -33,7 +32,7 @@ interface NetworkFirstOptions {
*
* @memberof workbox.strategies
*/
class NetworkOnly implements WorkboxStrategy {
class NetworkOnly implements RouteHandler {
private _plugins: WorkboxPlugin[];
private _fetchOptions?: RequestInit;
@@ -63,7 +62,7 @@ class NetworkOnly implements WorkboxStrategy {
* @param {Event} [options.event] The event that triggered the request.
* @return {Promise<Response>}
*/
async handle({event, request}: WorkboxStrategyHandleOptions) {
async handle({event, request}: RouteHandlerCallbackOptions): Promise<Response> {
return this.makeRequest({
event,
request: request || (event as FetchEvent).request,
@@ -85,8 +84,11 @@ class NetworkOnly implements WorkboxStrategy {
* be called automatically to extend the service worker's lifetime.
* @return {Promise<Response>}
*/
async makeRequest({event, request}: WorkboxStrategyHandleOptions) {
if (typeof request === 'string') {
async makeRequest({event, request}: {
request: Request,
event?: ExtendableEvent
}): Promise<Response> {
if (typeof request === 'string') {
request = new Request(request);
}
@@ -13,14 +13,12 @@ import {fetchWrapper} from 'workbox-core/_private/fetchWrapper.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/utils/pluginUtils.js';
import {RouteHandler, RouteHandlerCallbackOptions, WorkboxPlugin} from 'workbox-core/types.js';
import {messages} from './utils/messages.js';
import {cacheOkAndOpaquePlugin} from './plugins/cacheOkAndOpaquePlugin.js';
import {WorkboxStrategy, WorkboxStrategyHandleOptions} from './_types.js';
import './_version.js';
interface StaleWhileRevalidateOptions {
cacheName?: string;
plugins?: WorkboxPlugin[];
@@ -28,7 +26,6 @@ interface StaleWhileRevalidateOptions {
matchOptions?: CacheQueryOptions;
}
/**
* An implementation of a
* [stale-while-revalidate]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#stale-while-revalidate}
@@ -49,7 +46,7 @@ interface StaleWhileRevalidateOptions {
*
* @memberof workbox.strategies
*/
class StaleWhileRevalidate implements WorkboxStrategy {
class StaleWhileRevalidate implements RouteHandler {
private _cacheName: string;
private _plugins: WorkboxPlugin[];
private _fetchOptions?: RequestInit;
@@ -95,7 +92,7 @@ class StaleWhileRevalidate implements WorkboxStrategy {
* @param {Event} [options.event] The event that triggered the request.
* @return {Promise<Response>}
*/
async handle({event, request}: WorkboxStrategyHandleOptions) {
async handle({event, request}: RouteHandlerCallbackOptions): Promise<Response> {
return this.makeRequest({
event,
request: request || (event as FetchEvent).request,
@@ -116,8 +113,11 @@ class StaleWhileRevalidate implements WorkboxStrategy {
* be called automatically to extend the service worker's lifetime.
* @return {Promise<Response>}
*/
async makeRequest({event, request}: WorkboxStrategyHandleOptions) {
const logs = [];
async makeRequest({event, request}: {
request: Request,
event?: ExtendableEvent
}): Promise<Response> {
const logs = [];
if (typeof request === 'string') {
request = new Request(request);
-20
View File
@@ -1,20 +0,0 @@
/*
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 WorkboxStrategyHandleOptions {
request: Request;
event?: ExtendableEvent;
}
export interface WorkboxStrategy {
handle({event, request}: WorkboxStrategyHandleOptions): Promise<Response>;
makeRequest({event, request}: WorkboxStrategyHandleOptions): Promise<Response>;
}
+4 -4
View File
@@ -7,21 +7,21 @@
*/
import {logger} from 'workbox-core/_private/logger.js';
import {RouteHandler} from 'workbox-core/types.js';
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 './_version.js';
import { WorkboxStrategy } from './_types.js';
interface Strategy {
new({}: object): WorkboxStrategy
interface StrategyClass {
new({}: object): RouteHandler
}
interface StrategyDeprecationMap {
[strategyName: string]: Strategy;
[strategyName: string]: StrategyClass;
}
const mapping: StrategyDeprecationMap = {
@@ -6,7 +6,7 @@
https://opensource.org/licenses/MIT.
*/
import {WorkboxPlugin} from 'workbox-core/utils/pluginUtils.js';
import {WorkboxPlugin} from 'workbox-core/types.js';
import '../_version.js';
+5 -1
View File
@@ -2,9 +2,13 @@
"extends": "../../tsconfig",
"compilerOptions": {
"outDir": "./",
"rootDir": "./src"
"rootDir": "./src",
"tsBuildInfoFile": "./tsconfig.tsbuildinfo"
},
"include": [
"src/**/*.ts"
],
"references": [
{ "path": "../workbox-core/" }
]
}
+7 -7
View File
@@ -7,17 +7,17 @@
*/
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 {handlerCallback, HandlerCallbackOptions} from 'workbox-routing/_types.js';
import {StreamSource} from './_types.js';
import './_version.js';
type streamsHandlerCallback =
({url, request, event, params}: HandlerCallbackOptions) =>
Promise<StreamSource> | StreamSource;
interface StreamsHandlerCallback {
({url, request, event, params}: RouteHandlerCallbackOptions): Promise<StreamSource> | StreamSource;
}
/**
* A shortcut to create a strategy that could be dropped-in to Workbox's router.
@@ -37,10 +37,10 @@ type streamsHandlerCallback =
* @memberof workbox.streams
*/
function strategy(
sourceFunctions: streamsHandlerCallback[],
sourceFunctions: StreamsHandlerCallback[],
headersInit: HeadersInit,
): handlerCallback {
return async ({event, request, url, params}: HandlerCallbackOptions) => {
): 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}));
+5 -1
View File
@@ -2,9 +2,13 @@
"extends": "../../tsconfig",
"compilerOptions": {
"outDir": "./",
"rootDir": "./src"
"rootDir": "./src",
"tsBuildInfoFile": "./tsconfig.tsbuildinfo"
},
"include": [
"src/**/*.ts"
],
"references": [
{ "path": "../workbox-core/" }
]
}
+5 -1
View File
@@ -3,9 +3,13 @@
"compilerOptions": {
"lib": ["es2017", "dom"],
"outDir": "./",
"rootDir": "./src"
"rootDir": "./src",
"tsBuildInfoFile": "./tsconfig.tsbuildinfo"
},
"include": [
"src/**/*.ts"
],
"references": [
{ "path": "../workbox-core/" }
]
}
+1 -1
View File
@@ -64,7 +64,7 @@ describe(`[all] Window and SW packages`, function() {
// Inspect the package directory to get a list of top-level, public
// module basenames.
const topLevelFiles = glob.sync(`*.${ext}`, {
ignore: ['index', '_types', '_version'].map((file) => `${file}.${ext}`),
ignore: ['index', 'types', '_types', '_version'].map((file) => `${file}.${ext}`),
cwd: packagePath,
}).map((file) => path.basename(file, `.${ext}`));
+3 -2
View File
@@ -13,7 +13,8 @@
"noUnusedLocals": true,
"noUnusedParameters": true,
"preserveConstEnums": true,
"strictNullChecks": true
"strictNullChecks": true,
"tsBuildInfoFile": "./tsconfig.tsbuildinfo"
},
"files": [
"./infra/type-overrides.d.ts",
@@ -32,5 +33,5 @@
{ "path": "./packages/workbox-strategies/" },
{ "path": "./packages/workbox-streams/" },
{ "path": "./packages/workbox-window/" }
]
],
}