| 1 | /*
|
|---|
| 2 | Copyright 2018 Google LLC
|
|---|
| 3 |
|
|---|
| 4 | Use of this source code is governed by an MIT-style
|
|---|
| 5 | license that can be found in the LICENSE file or at
|
|---|
| 6 | https://opensource.org/licenses/MIT.
|
|---|
| 7 | */
|
|---|
| 8 | import { assert } from 'workbox-core/_private/assert.js';
|
|---|
| 9 | import { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';
|
|---|
| 10 | import { defaultMethod } from './utils/constants.js';
|
|---|
| 11 | import { logger } from 'workbox-core/_private/logger.js';
|
|---|
| 12 | import { normalizeHandler } from './utils/normalizeHandler.js';
|
|---|
| 13 | import { WorkboxError } from 'workbox-core/_private/WorkboxError.js';
|
|---|
| 14 | import './_version.js';
|
|---|
| 15 | /**
|
|---|
| 16 | * The Router can be used to process a `FetchEvent` using one or more
|
|---|
| 17 | * {@link workbox-routing.Route}, responding with a `Response` if
|
|---|
| 18 | * a matching route exists.
|
|---|
| 19 | *
|
|---|
| 20 | * If no route matches a given a request, the Router will use a "default"
|
|---|
| 21 | * handler if one is defined.
|
|---|
| 22 | *
|
|---|
| 23 | * Should the matching Route throw an error, the Router will use a "catch"
|
|---|
| 24 | * handler if one is defined to gracefully deal with issues and respond with a
|
|---|
| 25 | * Request.
|
|---|
| 26 | *
|
|---|
| 27 | * If a request matches multiple routes, the **earliest** registered route will
|
|---|
| 28 | * be used to respond to the request.
|
|---|
| 29 | *
|
|---|
| 30 | * @memberof workbox-routing
|
|---|
| 31 | */
|
|---|
| 32 | class Router {
|
|---|
| 33 | /**
|
|---|
| 34 | * Initializes a new Router.
|
|---|
| 35 | */
|
|---|
| 36 | constructor() {
|
|---|
| 37 | this._routes = new Map();
|
|---|
| 38 | this._defaultHandlerMap = new Map();
|
|---|
| 39 | }
|
|---|
| 40 | /**
|
|---|
| 41 | * @return {Map<string, Array<workbox-routing.Route>>} routes A `Map` of HTTP
|
|---|
| 42 | * method name ('GET', etc.) to an array of all the corresponding `Route`
|
|---|
| 43 | * instances that are registered.
|
|---|
| 44 | */
|
|---|
| 45 | get routes() {
|
|---|
| 46 | return this._routes;
|
|---|
| 47 | }
|
|---|
| 48 | /**
|
|---|
| 49 | * Adds a fetch event listener to respond to events when a route matches
|
|---|
| 50 | * the event's request.
|
|---|
| 51 | */
|
|---|
| 52 | addFetchListener() {
|
|---|
| 53 | // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
|
|---|
| 54 | self.addEventListener('fetch', ((event) => {
|
|---|
| 55 | const { request } = event;
|
|---|
| 56 | const responsePromise = this.handleRequest({ request, event });
|
|---|
| 57 | if (responsePromise) {
|
|---|
| 58 | event.respondWith(responsePromise);
|
|---|
| 59 | }
|
|---|
| 60 | }));
|
|---|
| 61 | }
|
|---|
| 62 | /**
|
|---|
| 63 | * Adds a message event listener for URLs to cache from the window.
|
|---|
| 64 | * This is useful to cache resources loaded on the page prior to when the
|
|---|
| 65 | * service worker started controlling it.
|
|---|
| 66 | *
|
|---|
| 67 | * The format of the message data sent from the window should be as follows.
|
|---|
| 68 | * Where the `urlsToCache` array may consist of URL strings or an array of
|
|---|
| 69 | * URL string + `requestInit` object (the same as you'd pass to `fetch()`).
|
|---|
| 70 | *
|
|---|
| 71 | * ```
|
|---|
| 72 | * {
|
|---|
| 73 | * type: 'CACHE_URLS',
|
|---|
| 74 | * payload: {
|
|---|
| 75 | * urlsToCache: [
|
|---|
| 76 | * './script1.js',
|
|---|
| 77 | * './script2.js',
|
|---|
| 78 | * ['./script3.js', {mode: 'no-cors'}],
|
|---|
| 79 | * ],
|
|---|
| 80 | * },
|
|---|
| 81 | * }
|
|---|
| 82 | * ```
|
|---|
| 83 | */
|
|---|
| 84 | addCacheListener() {
|
|---|
| 85 | // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
|
|---|
| 86 | self.addEventListener('message', ((event) => {
|
|---|
| 87 | // event.data is type 'any'
|
|---|
| 88 | // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
|---|
| 89 | if (event.data && event.data.type === 'CACHE_URLS') {
|
|---|
| 90 | // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
|---|
| 91 | const { payload } = event.data;
|
|---|
| 92 | if (process.env.NODE_ENV !== 'production') {
|
|---|
| 93 | logger.debug(`Caching URLs from the window`, payload.urlsToCache);
|
|---|
| 94 | }
|
|---|
| 95 | const requestPromises = Promise.all(payload.urlsToCache.map((entry) => {
|
|---|
| 96 | if (typeof entry === 'string') {
|
|---|
| 97 | entry = [entry];
|
|---|
| 98 | }
|
|---|
| 99 | const request = new Request(...entry);
|
|---|
| 100 | return this.handleRequest({ request, event });
|
|---|
| 101 | // TODO(philipwalton): TypeScript errors without this typecast for
|
|---|
| 102 | // some reason (probably a bug). The real type here should work but
|
|---|
| 103 | // doesn't: `Array<Promise<Response> | undefined>`.
|
|---|
| 104 | })); // TypeScript
|
|---|
| 105 | event.waitUntil(requestPromises);
|
|---|
| 106 | // If a MessageChannel was used, reply to the message on success.
|
|---|
| 107 | if (event.ports && event.ports[0]) {
|
|---|
| 108 | void requestPromises.then(() => event.ports[0].postMessage(true));
|
|---|
| 109 | }
|
|---|
| 110 | }
|
|---|
| 111 | }));
|
|---|
| 112 | }
|
|---|
| 113 | /**
|
|---|
| 114 | * Apply the routing rules to a FetchEvent object to get a Response from an
|
|---|
| 115 | * appropriate Route's handler.
|
|---|
| 116 | *
|
|---|
| 117 | * @param {Object} options
|
|---|
| 118 | * @param {Request} options.request The request to handle.
|
|---|
| 119 | * @param {ExtendableEvent} options.event The event that triggered the
|
|---|
| 120 | * request.
|
|---|
| 121 | * @return {Promise<Response>|undefined} A promise is returned if a
|
|---|
| 122 | * registered route can handle the request. If there is no matching
|
|---|
| 123 | * route and there's no `defaultHandler`, `undefined` is returned.
|
|---|
| 124 | */
|
|---|
| 125 | handleRequest({ request, event, }) {
|
|---|
| 126 | if (process.env.NODE_ENV !== 'production') {
|
|---|
| 127 | assert.isInstance(request, Request, {
|
|---|
| 128 | moduleName: 'workbox-routing',
|
|---|
| 129 | className: 'Router',
|
|---|
| 130 | funcName: 'handleRequest',
|
|---|
| 131 | paramName: 'options.request',
|
|---|
| 132 | });
|
|---|
| 133 | }
|
|---|
| 134 | const url = new URL(request.url, location.href);
|
|---|
| 135 | if (!url.protocol.startsWith('http')) {
|
|---|
| 136 | if (process.env.NODE_ENV !== 'production') {
|
|---|
| 137 | logger.debug(`Workbox Router only supports URLs that start with 'http'.`);
|
|---|
| 138 | }
|
|---|
| 139 | return;
|
|---|
| 140 | }
|
|---|
| 141 | const sameOrigin = url.origin === location.origin;
|
|---|
| 142 | const { params, route } = this.findMatchingRoute({
|
|---|
| 143 | event,
|
|---|
| 144 | request,
|
|---|
| 145 | sameOrigin,
|
|---|
| 146 | url,
|
|---|
| 147 | });
|
|---|
| 148 | let handler = route && route.handler;
|
|---|
| 149 | const debugMessages = [];
|
|---|
| 150 | if (process.env.NODE_ENV !== 'production') {
|
|---|
| 151 | if (handler) {
|
|---|
| 152 | debugMessages.push([`Found a route to handle this request:`, route]);
|
|---|
| 153 | if (params) {
|
|---|
| 154 | debugMessages.push([
|
|---|
| 155 | `Passing the following params to the route's handler:`,
|
|---|
| 156 | params,
|
|---|
| 157 | ]);
|
|---|
| 158 | }
|
|---|
| 159 | }
|
|---|
| 160 | }
|
|---|
| 161 | // If we don't have a handler because there was no matching route, then
|
|---|
| 162 | // fall back to defaultHandler if that's defined.
|
|---|
| 163 | const method = request.method;
|
|---|
| 164 | if (!handler && this._defaultHandlerMap.has(method)) {
|
|---|
| 165 | if (process.env.NODE_ENV !== 'production') {
|
|---|
| 166 | debugMessages.push(`Failed to find a matching route. Falling ` +
|
|---|
| 167 | `back to the default handler for ${method}.`);
|
|---|
| 168 | }
|
|---|
| 169 | handler = this._defaultHandlerMap.get(method);
|
|---|
| 170 | }
|
|---|
| 171 | if (!handler) {
|
|---|
| 172 | if (process.env.NODE_ENV !== 'production') {
|
|---|
| 173 | // No handler so Workbox will do nothing. If logs is set of debug
|
|---|
| 174 | // i.e. verbose, we should print out this information.
|
|---|
| 175 | logger.debug(`No route found for: ${getFriendlyURL(url)}`);
|
|---|
| 176 | }
|
|---|
| 177 | return;
|
|---|
| 178 | }
|
|---|
| 179 | if (process.env.NODE_ENV !== 'production') {
|
|---|
| 180 | // We have a handler, meaning Workbox is going to handle the route.
|
|---|
| 181 | // print the routing details to the console.
|
|---|
| 182 | logger.groupCollapsed(`Router is responding to: ${getFriendlyURL(url)}`);
|
|---|
| 183 | debugMessages.forEach((msg) => {
|
|---|
| 184 | if (Array.isArray(msg)) {
|
|---|
| 185 | logger.log(...msg);
|
|---|
| 186 | }
|
|---|
| 187 | else {
|
|---|
| 188 | logger.log(msg);
|
|---|
| 189 | }
|
|---|
| 190 | });
|
|---|
| 191 | logger.groupEnd();
|
|---|
| 192 | }
|
|---|
| 193 | // Wrap in try and catch in case the handle method throws a synchronous
|
|---|
| 194 | // error. It should still callback to the catch handler.
|
|---|
| 195 | let responsePromise;
|
|---|
| 196 | try {
|
|---|
| 197 | responsePromise = handler.handle({ url, request, event, params });
|
|---|
| 198 | }
|
|---|
| 199 | catch (err) {
|
|---|
| 200 | responsePromise = Promise.reject(err);
|
|---|
| 201 | }
|
|---|
| 202 | // Get route's catch handler, if it exists
|
|---|
| 203 | const catchHandler = route && route.catchHandler;
|
|---|
| 204 | if (responsePromise instanceof Promise &&
|
|---|
| 205 | (this._catchHandler || catchHandler)) {
|
|---|
| 206 | responsePromise = responsePromise.catch(async (err) => {
|
|---|
| 207 | // If there's a route catch handler, process that first
|
|---|
| 208 | if (catchHandler) {
|
|---|
| 209 | if (process.env.NODE_ENV !== 'production') {
|
|---|
| 210 | // Still include URL here as it will be async from the console group
|
|---|
| 211 | // and may not make sense without the URL
|
|---|
| 212 | logger.groupCollapsed(`Error thrown when responding to: ` +
|
|---|
| 213 | ` ${getFriendlyURL(url)}. Falling back to route's Catch Handler.`);
|
|---|
| 214 | logger.error(`Error thrown by:`, route);
|
|---|
| 215 | logger.error(err);
|
|---|
| 216 | logger.groupEnd();
|
|---|
| 217 | }
|
|---|
| 218 | try {
|
|---|
| 219 | return await catchHandler.handle({ url, request, event, params });
|
|---|
| 220 | }
|
|---|
| 221 | catch (catchErr) {
|
|---|
| 222 | if (catchErr instanceof Error) {
|
|---|
| 223 | err = catchErr;
|
|---|
| 224 | }
|
|---|
| 225 | }
|
|---|
| 226 | }
|
|---|
| 227 | if (this._catchHandler) {
|
|---|
| 228 | if (process.env.NODE_ENV !== 'production') {
|
|---|
| 229 | // Still include URL here as it will be async from the console group
|
|---|
| 230 | // and may not make sense without the URL
|
|---|
| 231 | logger.groupCollapsed(`Error thrown when responding to: ` +
|
|---|
| 232 | ` ${getFriendlyURL(url)}. Falling back to global Catch Handler.`);
|
|---|
| 233 | logger.error(`Error thrown by:`, route);
|
|---|
| 234 | logger.error(err);
|
|---|
| 235 | logger.groupEnd();
|
|---|
| 236 | }
|
|---|
| 237 | return this._catchHandler.handle({ url, request, event });
|
|---|
| 238 | }
|
|---|
| 239 | throw err;
|
|---|
| 240 | });
|
|---|
| 241 | }
|
|---|
| 242 | return responsePromise;
|
|---|
| 243 | }
|
|---|
| 244 | /**
|
|---|
| 245 | * Checks a request and URL (and optionally an event) against the list of
|
|---|
| 246 | * registered routes, and if there's a match, returns the corresponding
|
|---|
| 247 | * route along with any params generated by the match.
|
|---|
| 248 | *
|
|---|
| 249 | * @param {Object} options
|
|---|
| 250 | * @param {URL} options.url
|
|---|
| 251 | * @param {boolean} options.sameOrigin The result of comparing `url.origin`
|
|---|
| 252 | * against the current origin.
|
|---|
| 253 | * @param {Request} options.request The request to match.
|
|---|
| 254 | * @param {Event} options.event The corresponding event.
|
|---|
| 255 | * @return {Object} An object with `route` and `params` properties.
|
|---|
| 256 | * They are populated if a matching route was found or `undefined`
|
|---|
| 257 | * otherwise.
|
|---|
| 258 | */
|
|---|
| 259 | findMatchingRoute({ url, sameOrigin, request, event, }) {
|
|---|
| 260 | const routes = this._routes.get(request.method) || [];
|
|---|
| 261 | for (const route of routes) {
|
|---|
| 262 | let params;
|
|---|
| 263 | // route.match returns type any, not possible to change right now.
|
|---|
| 264 | // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
|---|
| 265 | const matchResult = route.match({ url, sameOrigin, request, event });
|
|---|
| 266 | if (matchResult) {
|
|---|
| 267 | if (process.env.NODE_ENV !== 'production') {
|
|---|
| 268 | // Warn developers that using an async matchCallback is almost always
|
|---|
| 269 | // not the right thing to do.
|
|---|
| 270 | if (matchResult instanceof Promise) {
|
|---|
| 271 | logger.warn(`While routing ${getFriendlyURL(url)}, an async ` +
|
|---|
| 272 | `matchCallback function was used. Please convert the ` +
|
|---|
| 273 | `following route to use a synchronous matchCallback function:`, route);
|
|---|
| 274 | }
|
|---|
| 275 | }
|
|---|
| 276 | // See https://github.com/GoogleChrome/workbox/issues/2079
|
|---|
| 277 | // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
|---|
| 278 | params = matchResult;
|
|---|
| 279 | if (Array.isArray(params) && params.length === 0) {
|
|---|
| 280 | // Instead of passing an empty array in as params, use undefined.
|
|---|
| 281 | params = undefined;
|
|---|
| 282 | }
|
|---|
| 283 | else if (matchResult.constructor === Object && // eslint-disable-line
|
|---|
| 284 | Object.keys(matchResult).length === 0) {
|
|---|
| 285 | // Instead of passing an empty object in as params, use undefined.
|
|---|
| 286 | params = undefined;
|
|---|
| 287 | }
|
|---|
| 288 | else if (typeof matchResult === 'boolean') {
|
|---|
| 289 | // For the boolean value true (rather than just something truth-y),
|
|---|
| 290 | // don't set params.
|
|---|
| 291 | // See https://github.com/GoogleChrome/workbox/pull/2134#issuecomment-513924353
|
|---|
| 292 | params = undefined;
|
|---|
| 293 | }
|
|---|
| 294 | // Return early if have a match.
|
|---|
| 295 | return { route, params };
|
|---|
| 296 | }
|
|---|
| 297 | }
|
|---|
| 298 | // If no match was found above, return and empty object.
|
|---|
| 299 | return {};
|
|---|
| 300 | }
|
|---|
| 301 | /**
|
|---|
| 302 | * Define a default `handler` that's called when no routes explicitly
|
|---|
| 303 | * match the incoming request.
|
|---|
| 304 | *
|
|---|
| 305 | * Each HTTP method ('GET', 'POST', etc.) gets its own default handler.
|
|---|
| 306 | *
|
|---|
| 307 | * Without a default handler, unmatched requests will go against the
|
|---|
| 308 | * network as if there were no service worker present.
|
|---|
| 309 | *
|
|---|
| 310 | * @param {workbox-routing~handlerCallback} handler A callback
|
|---|
| 311 | * function that returns a Promise resulting in a Response.
|
|---|
| 312 | * @param {string} [method='GET'] The HTTP method to associate with this
|
|---|
| 313 | * default handler. Each method has its own default.
|
|---|
| 314 | */
|
|---|
| 315 | setDefaultHandler(handler, method = defaultMethod) {
|
|---|
| 316 | this._defaultHandlerMap.set(method, normalizeHandler(handler));
|
|---|
| 317 | }
|
|---|
| 318 | /**
|
|---|
| 319 | * If a Route throws an error while handling a request, this `handler`
|
|---|
| 320 | * will be called and given a chance to provide a response.
|
|---|
| 321 | *
|
|---|
| 322 | * @param {workbox-routing~handlerCallback} handler A callback
|
|---|
| 323 | * function that returns a Promise resulting in a Response.
|
|---|
| 324 | */
|
|---|
| 325 | setCatchHandler(handler) {
|
|---|
| 326 | this._catchHandler = normalizeHandler(handler);
|
|---|
| 327 | }
|
|---|
| 328 | /**
|
|---|
| 329 | * Registers a route with the router.
|
|---|
| 330 | *
|
|---|
| 331 | * @param {workbox-routing.Route} route The route to register.
|
|---|
| 332 | */
|
|---|
| 333 | registerRoute(route) {
|
|---|
| 334 | if (process.env.NODE_ENV !== 'production') {
|
|---|
| 335 | assert.isType(route, 'object', {
|
|---|
| 336 | moduleName: 'workbox-routing',
|
|---|
| 337 | className: 'Router',
|
|---|
| 338 | funcName: 'registerRoute',
|
|---|
| 339 | paramName: 'route',
|
|---|
| 340 | });
|
|---|
| 341 | assert.hasMethod(route, 'match', {
|
|---|
| 342 | moduleName: 'workbox-routing',
|
|---|
| 343 | className: 'Router',
|
|---|
| 344 | funcName: 'registerRoute',
|
|---|
| 345 | paramName: 'route',
|
|---|
| 346 | });
|
|---|
| 347 | assert.isType(route.handler, 'object', {
|
|---|
| 348 | moduleName: 'workbox-routing',
|
|---|
| 349 | className: 'Router',
|
|---|
| 350 | funcName: 'registerRoute',
|
|---|
| 351 | paramName: 'route',
|
|---|
| 352 | });
|
|---|
| 353 | assert.hasMethod(route.handler, 'handle', {
|
|---|
| 354 | moduleName: 'workbox-routing',
|
|---|
| 355 | className: 'Router',
|
|---|
| 356 | funcName: 'registerRoute',
|
|---|
| 357 | paramName: 'route.handler',
|
|---|
| 358 | });
|
|---|
| 359 | assert.isType(route.method, 'string', {
|
|---|
| 360 | moduleName: 'workbox-routing',
|
|---|
| 361 | className: 'Router',
|
|---|
| 362 | funcName: 'registerRoute',
|
|---|
| 363 | paramName: 'route.method',
|
|---|
| 364 | });
|
|---|
| 365 | }
|
|---|
| 366 | if (!this._routes.has(route.method)) {
|
|---|
| 367 | this._routes.set(route.method, []);
|
|---|
| 368 | }
|
|---|
| 369 | // Give precedence to all of the earlier routes by adding this additional
|
|---|
| 370 | // route to the end of the array.
|
|---|
| 371 | this._routes.get(route.method).push(route);
|
|---|
| 372 | }
|
|---|
| 373 | /**
|
|---|
| 374 | * Unregisters a route with the router.
|
|---|
| 375 | *
|
|---|
| 376 | * @param {workbox-routing.Route} route The route to unregister.
|
|---|
| 377 | */
|
|---|
| 378 | unregisterRoute(route) {
|
|---|
| 379 | if (!this._routes.has(route.method)) {
|
|---|
| 380 | throw new WorkboxError('unregister-route-but-not-found-with-method', {
|
|---|
| 381 | method: route.method,
|
|---|
| 382 | });
|
|---|
| 383 | }
|
|---|
| 384 | const routeIndex = this._routes.get(route.method).indexOf(route);
|
|---|
| 385 | if (routeIndex > -1) {
|
|---|
| 386 | this._routes.get(route.method).splice(routeIndex, 1);
|
|---|
| 387 | }
|
|---|
| 388 | else {
|
|---|
| 389 | throw new WorkboxError('unregister-route-route-not-registered');
|
|---|
| 390 | }
|
|---|
| 391 | }
|
|---|
| 392 | }
|
|---|
| 393 | export { Router };
|
|---|