@serwist/routing 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,729 @@
1
+ 'use strict';
2
+
3
+ var internal = require('@serwist/core/internal');
4
+
5
+ /*
6
+ Copyright 2018 Google LLC
7
+
8
+ Use of this source code is governed by an MIT-style
9
+ license that can be found in the LICENSE file or at
10
+ https://opensource.org/licenses/MIT.
11
+ */ /**
12
+ * The default HTTP method, 'GET', used when there's no specific method
13
+ * configured for a route.
14
+ *
15
+ * @type {string}
16
+ *
17
+ * @private
18
+ */ const defaultMethod = "GET";
19
+ /**
20
+ * The list of valid HTTP methods associated with requests that could be routed.
21
+ *
22
+ * @type {Array<string>}
23
+ *
24
+ * @private
25
+ */ const validMethods = [
26
+ "DELETE",
27
+ "GET",
28
+ "HEAD",
29
+ "PATCH",
30
+ "POST",
31
+ "PUT"
32
+ ];
33
+
34
+ /**
35
+ * @param handler Either a function, or an object with a
36
+ * 'handle' method.
37
+ * @returns An object with a handle method.
38
+ *
39
+ * @private
40
+ */ const normalizeHandler = (handler)=>{
41
+ if (handler && typeof handler === "object") {
42
+ if (process.env.NODE_ENV !== "production") {
43
+ internal.assert.hasMethod(handler, "handle", {
44
+ moduleName: "@serwist/routing",
45
+ className: "Route",
46
+ funcName: "constructor",
47
+ paramName: "handler"
48
+ });
49
+ }
50
+ return handler;
51
+ } else {
52
+ if (process.env.NODE_ENV !== "production") {
53
+ internal.assert.isType(handler, "function", {
54
+ moduleName: "@serwist/routing",
55
+ className: "Route",
56
+ funcName: "constructor",
57
+ paramName: "handler"
58
+ });
59
+ }
60
+ return {
61
+ handle: handler
62
+ };
63
+ }
64
+ };
65
+
66
+ /**
67
+ * A `Route` consists of a pair of callback functions, "match" and "handler".
68
+ * The "match" callback determine if a route should be used to "handle" a
69
+ * request by returning a non-falsy value if it can. The "handler" callback
70
+ * is called when there is a match and should return a Promise that resolves
71
+ * to a `Response`.
72
+ */ class Route {
73
+ handler;
74
+ match;
75
+ method;
76
+ catchHandler;
77
+ /**
78
+ * Constructor for Route class.
79
+ *
80
+ * @param match A callback function that determines whether the
81
+ * route matches a given `fetch` event by returning a non-falsy value.
82
+ * @param handler A callback function that returns a Promise resolving
83
+ * to a Response.
84
+ * @param method The HTTP method to match the Route against. Defaults
85
+ * to GET.
86
+ */ constructor(match, handler, method = defaultMethod){
87
+ if (process.env.NODE_ENV !== "production") {
88
+ internal.assert.isType(match, "function", {
89
+ moduleName: "@serwist/routing",
90
+ className: "Route",
91
+ funcName: "constructor",
92
+ paramName: "match"
93
+ });
94
+ if (method) {
95
+ internal.assert.isOneOf(method, validMethods, {
96
+ paramName: "method"
97
+ });
98
+ }
99
+ }
100
+ // These values are referenced directly by Router so cannot be
101
+ // altered by minificaton.
102
+ this.handler = normalizeHandler(handler);
103
+ this.match = match;
104
+ this.method = method;
105
+ }
106
+ /**
107
+ *
108
+ * @param handler A callback function that returns a Promise resolving
109
+ * to a Response.
110
+ */ setCatchHandler(handler) {
111
+ this.catchHandler = normalizeHandler(handler);
112
+ }
113
+ }
114
+
115
+ /**
116
+ * NavigationRoute makes it easy to create a `@serwist/routing` Route that matches for browser
117
+ * [navigation requests](https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests).
118
+ *
119
+ * It will only match incoming Requests whose [mode](https://fetch.spec.whatwg.org/#concept-request-mode) is set to `navigate`.
120
+ *
121
+ * You can optionally only apply this route to a subset of navigation requests
122
+ * by using one or both of the `denylist` and `allowlist` parameters.
123
+ */ class NavigationRoute extends Route {
124
+ _allowlist;
125
+ _denylist;
126
+ /**
127
+ * If both `denylist` and `allowlist` are provided, the `denylist` will
128
+ * take precedence and the request will not match this route.
129
+ *
130
+ * The regular expressions in `allowlist` and `denylist`
131
+ * are matched against the concatenated
132
+ * [`pathname`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/pathname)
133
+ * and [`search`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search)
134
+ * portions of the requested URL.
135
+ *
136
+ * *Note*: These RegExps may be evaluated against every destination URL during
137
+ * a navigation. Avoid using
138
+ * [complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077),
139
+ * or else your users may see delays when navigating your site.
140
+ *
141
+ * @param handler A callback function that returns a Promise resulting in a Response.
142
+ * @param options
143
+ */ constructor(handler, { allowlist = [
144
+ /./
145
+ ], denylist = [] } = {}){
146
+ if (process.env.NODE_ENV !== "production") {
147
+ internal.assert.isArrayOfClass(allowlist, RegExp, {
148
+ moduleName: "@serwist/routing",
149
+ className: "NavigationRoute",
150
+ funcName: "constructor",
151
+ paramName: "options.allowlist"
152
+ });
153
+ internal.assert.isArrayOfClass(denylist, RegExp, {
154
+ moduleName: "@serwist/routing",
155
+ className: "NavigationRoute",
156
+ funcName: "constructor",
157
+ paramName: "options.denylist"
158
+ });
159
+ }
160
+ super((options)=>this._match(options), handler);
161
+ this._allowlist = allowlist;
162
+ this._denylist = denylist;
163
+ }
164
+ /**
165
+ * Routes match handler.
166
+ *
167
+ * @param options
168
+ * @returns
169
+ * @private
170
+ */ _match({ url, request }) {
171
+ if (request && request.mode !== "navigate") {
172
+ return false;
173
+ }
174
+ const pathnameAndSearch = url.pathname + url.search;
175
+ for (const regExp of this._denylist){
176
+ if (regExp.test(pathnameAndSearch)) {
177
+ if (process.env.NODE_ENV !== "production") {
178
+ internal.logger.log(`The navigation route ${pathnameAndSearch} is not ` + `being used, since the URL matches this denylist pattern: ` + `${regExp.toString()}`);
179
+ }
180
+ return false;
181
+ }
182
+ }
183
+ if (this._allowlist.some((regExp)=>regExp.test(pathnameAndSearch))) {
184
+ if (process.env.NODE_ENV !== "production") {
185
+ internal.logger.debug(`The navigation route ${pathnameAndSearch} ` + `is being used.`);
186
+ }
187
+ return true;
188
+ }
189
+ if (process.env.NODE_ENV !== "production") {
190
+ internal.logger.log(`The navigation route ${pathnameAndSearch} is not ` + `being used, since the URL being navigated to doesn't ` + `match the allowlist.`);
191
+ }
192
+ return false;
193
+ }
194
+ }
195
+
196
+ /**
197
+ * RegExpRoute makes it easy to create a regular expression based on a `@serwist/routing` Route.
198
+ *
199
+ * For same-origin requests the RegExp only needs to match part of the URL. For
200
+ * requests against third-party servers, you must define a RegExp that matches
201
+ * the start of the URL.
202
+ */ class RegExpRoute extends Route {
203
+ /**
204
+ * If the regular expression contains
205
+ * [capture groups](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references),
206
+ * the captured values will be passed to the `params` argument.
207
+ *
208
+ * @param regExp The regular expression to match against URLs.
209
+ * @param handler A callback function that returns a Promise resulting in a Response.
210
+ * @param method The HTTP method to match the Route, defaults to GET.
211
+ * against.
212
+ */ constructor(regExp, handler, method){
213
+ if (process.env.NODE_ENV !== "production") {
214
+ internal.assert.isInstance(regExp, RegExp, {
215
+ moduleName: "@serwist/routing",
216
+ className: "RegExpRoute",
217
+ funcName: "constructor",
218
+ paramName: "pattern"
219
+ });
220
+ }
221
+ const match = ({ url })=>{
222
+ const result = regExp.exec(url.href);
223
+ // Return immediately if there's no match.
224
+ if (!result) {
225
+ return;
226
+ }
227
+ // Require that the match start at the first character in the URL string
228
+ // if it's a cross-origin request.
229
+ // See https://github.com/GoogleChrome/workbox/issues/281 for the context
230
+ // behind this behavior.
231
+ if (url.origin !== location.origin && result.index !== 0) {
232
+ if (process.env.NODE_ENV !== "production") {
233
+ internal.logger.debug(`The regular expression '${regExp.toString()}' only partially matched ` + `against the cross-origin URL '${url.toString()}'. RegExpRoute's will only ` + `handle cross-origin requests if they match the entire URL.`);
234
+ }
235
+ return;
236
+ }
237
+ // If the route matches, but there aren't any capture groups defined, then
238
+ // this will return [], which is truthy and therefore sufficient to
239
+ // indicate a match.
240
+ // If there are capture groups, then it will return their values.
241
+ return result.slice(1);
242
+ };
243
+ super(match, handler, method);
244
+ }
245
+ }
246
+
247
+ /**
248
+ * The Router can be used to process a `FetchEvent` using one or more `@serwist/routing` Route(s),
249
+ * responding with a `Response` if a matching route exists.
250
+ *
251
+ * If no route matches a given a request, the Router will use a "default" handler if one is defined.
252
+ *
253
+ * Should the matching Route throw an error, the Router will use a "catch" handler if one is defined to
254
+ * gracefully deal with issues and respond with a Request.
255
+ *
256
+ * If a request matches multiple routes, the **earliest** registered route will
257
+ * be used to respond to the request.
258
+ */ class Router {
259
+ _routes;
260
+ _defaultHandlerMap;
261
+ _catchHandler;
262
+ /**
263
+ * Initializes a new Router.
264
+ */ constructor(){
265
+ this._routes = new Map();
266
+ this._defaultHandlerMap = new Map();
267
+ }
268
+ /**
269
+ * @returns routes A `Map` of HTTP method name ('GET', etc.) to an array of all the corresponding `Route`
270
+ * instances that are registered.
271
+ */ get routes() {
272
+ return this._routes;
273
+ }
274
+ /**
275
+ * Adds a fetch event listener to respond to events when a route matches
276
+ * the event's request.
277
+ */ addFetchListener() {
278
+ // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
279
+ self.addEventListener("fetch", (event)=>{
280
+ const { request } = event;
281
+ const responsePromise = this.handleRequest({
282
+ request,
283
+ event
284
+ });
285
+ if (responsePromise) {
286
+ event.respondWith(responsePromise);
287
+ }
288
+ });
289
+ }
290
+ /**
291
+ * Adds a message event listener for URLs to cache from the window.
292
+ * This is useful to cache resources loaded on the page prior to when the
293
+ * service worker started controlling it.
294
+ *
295
+ * The format of the message data sent from the window should be as follows.
296
+ * Where the `urlsToCache` array may consist of URL strings or an array of
297
+ * URL string + `requestInit` object (the same as you'd pass to `fetch()`).
298
+ *
299
+ * ```
300
+ * {
301
+ * type: 'CACHE_URLS',
302
+ * payload: {
303
+ * urlsToCache: [
304
+ * './script1.js',
305
+ * './script2.js',
306
+ * ['./script3.js', {mode: 'no-cors'}],
307
+ * ],
308
+ * },
309
+ * }
310
+ * ```
311
+ */ addCacheListener() {
312
+ // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
313
+ self.addEventListener("message", (event)=>{
314
+ // event.data is type 'any'
315
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
316
+ if (event.data && event.data.type === "CACHE_URLS") {
317
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
318
+ const { payload } = event.data;
319
+ if (process.env.NODE_ENV !== "production") {
320
+ internal.logger.debug(`Caching URLs from the window`, payload.urlsToCache);
321
+ }
322
+ const requestPromises = Promise.all(payload.urlsToCache.map((entry)=>{
323
+ if (typeof entry === "string") {
324
+ entry = [
325
+ entry
326
+ ];
327
+ }
328
+ const request = new Request(...entry);
329
+ return this.handleRequest({
330
+ request,
331
+ event
332
+ });
333
+ // TODO(philipwalton): TypeScript errors without this typecast for
334
+ // some reason (probably a bug). The real type here should work but
335
+ // doesn't: `Array<Promise<Response> | undefined>`.
336
+ })); // TypeScript
337
+ event.waitUntil(requestPromises);
338
+ // If a MessageChannel was used, reply to the message on success.
339
+ if (event.ports && event.ports[0]) {
340
+ void requestPromises.then(()=>event.ports[0].postMessage(true));
341
+ }
342
+ }
343
+ });
344
+ }
345
+ /**
346
+ * Apply the routing rules to a FetchEvent object to get a Response from an
347
+ * appropriate Route's handler.
348
+ *
349
+ * @param options
350
+ * @returns A promise is returned if a registered route can handle the request.
351
+ * If there is no matching route and there's no `defaultHandler`, `undefined`
352
+ * is returned.
353
+ */ handleRequest({ request, event }) {
354
+ if (process.env.NODE_ENV !== "production") {
355
+ internal.assert.isInstance(request, Request, {
356
+ moduleName: "@serwist/routing",
357
+ className: "Router",
358
+ funcName: "handleRequest",
359
+ paramName: "options.request"
360
+ });
361
+ }
362
+ const url = new URL(request.url, location.href);
363
+ if (!url.protocol.startsWith("http")) {
364
+ if (process.env.NODE_ENV !== "production") {
365
+ internal.logger.debug(`Serwist Router only supports URLs that start with 'http'.`);
366
+ }
367
+ return;
368
+ }
369
+ const sameOrigin = url.origin === location.origin;
370
+ const { params, route } = this.findMatchingRoute({
371
+ event,
372
+ request,
373
+ sameOrigin,
374
+ url
375
+ });
376
+ let handler = route && route.handler;
377
+ const debugMessages = [];
378
+ if (process.env.NODE_ENV !== "production") {
379
+ if (handler) {
380
+ debugMessages.push([
381
+ `Found a route to handle this request:`,
382
+ route
383
+ ]);
384
+ if (params) {
385
+ debugMessages.push([
386
+ `Passing the following params to the route's handler:`,
387
+ params
388
+ ]);
389
+ }
390
+ }
391
+ }
392
+ // If we don't have a handler because there was no matching route, then
393
+ // fall back to defaultHandler if that's defined.
394
+ const method = request.method;
395
+ if (!handler && this._defaultHandlerMap.has(method)) {
396
+ if (process.env.NODE_ENV !== "production") {
397
+ debugMessages.push(`Failed to find a matching route. Falling ` + `back to the default handler for ${method}.`);
398
+ }
399
+ handler = this._defaultHandlerMap.get(method);
400
+ }
401
+ if (!handler) {
402
+ if (process.env.NODE_ENV !== "production") {
403
+ // No handler so Serwist will do nothing. If logs is set of debug
404
+ // i.e. verbose, we should print out this information.
405
+ internal.logger.debug(`No route found for: ${internal.getFriendlyURL(url)}`);
406
+ }
407
+ return;
408
+ }
409
+ if (process.env.NODE_ENV !== "production") {
410
+ // We have a handler, meaning Serwist is going to handle the route.
411
+ // print the routing details to the console.
412
+ internal.logger.groupCollapsed(`Router is responding to: ${internal.getFriendlyURL(url)}`);
413
+ debugMessages.forEach((msg)=>{
414
+ if (Array.isArray(msg)) {
415
+ internal.logger.log(...msg);
416
+ } else {
417
+ internal.logger.log(msg);
418
+ }
419
+ });
420
+ internal.logger.groupEnd();
421
+ }
422
+ // Wrap in try and catch in case the handle method throws a synchronous
423
+ // error. It should still callback to the catch handler.
424
+ let responsePromise;
425
+ try {
426
+ responsePromise = handler.handle({
427
+ url,
428
+ request,
429
+ event,
430
+ params
431
+ });
432
+ } catch (err) {
433
+ responsePromise = Promise.reject(err);
434
+ }
435
+ // Get route's catch handler, if it exists
436
+ const catchHandler = route && route.catchHandler;
437
+ if (responsePromise instanceof Promise && (this._catchHandler || catchHandler)) {
438
+ responsePromise = responsePromise.catch(async (err)=>{
439
+ // If there's a route catch handler, process that first
440
+ if (catchHandler) {
441
+ if (process.env.NODE_ENV !== "production") {
442
+ // Still include URL here as it will be async from the console group
443
+ // and may not make sense without the URL
444
+ internal.logger.groupCollapsed(`Error thrown when responding to: ` + ` ${internal.getFriendlyURL(url)}. Falling back to route's Catch Handler.`);
445
+ internal.logger.error(`Error thrown by:`, route);
446
+ internal.logger.error(err);
447
+ internal.logger.groupEnd();
448
+ }
449
+ try {
450
+ return await catchHandler.handle({
451
+ url,
452
+ request,
453
+ event,
454
+ params
455
+ });
456
+ } catch (catchErr) {
457
+ if (catchErr instanceof Error) {
458
+ err = catchErr;
459
+ }
460
+ }
461
+ }
462
+ if (this._catchHandler) {
463
+ if (process.env.NODE_ENV !== "production") {
464
+ // Still include URL here as it will be async from the console group
465
+ // and may not make sense without the URL
466
+ internal.logger.groupCollapsed(`Error thrown when responding to: ` + ` ${internal.getFriendlyURL(url)}. Falling back to global Catch Handler.`);
467
+ internal.logger.error(`Error thrown by:`, route);
468
+ internal.logger.error(err);
469
+ internal.logger.groupEnd();
470
+ }
471
+ return this._catchHandler.handle({
472
+ url,
473
+ request,
474
+ event
475
+ });
476
+ }
477
+ throw err;
478
+ });
479
+ }
480
+ return responsePromise;
481
+ }
482
+ /**
483
+ * Checks a request and URL (and optionally an event) against the list of
484
+ * registered routes, and if there's a match, returns the corresponding
485
+ * route along with any params generated by the match.
486
+ *
487
+ * @param options
488
+ * @returns An object with `route` and `params` properties. They are populated
489
+ * if a matching route was found or `undefined` otherwise.
490
+ */ findMatchingRoute({ url, sameOrigin, request, event }) {
491
+ const routes = this._routes.get(request.method) || [];
492
+ for (const route of routes){
493
+ let params;
494
+ // route.match returns type any, not possible to change right now.
495
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
496
+ const matchResult = route.match({
497
+ url,
498
+ sameOrigin,
499
+ request,
500
+ event
501
+ });
502
+ if (matchResult) {
503
+ if (process.env.NODE_ENV !== "production") {
504
+ // Warn developers that using an async matchCallback is almost always
505
+ // not the right thing to do.
506
+ if (matchResult instanceof Promise) {
507
+ internal.logger.warn(`While routing ${internal.getFriendlyURL(url)}, an async ` + `matchCallback function was used. Please convert the ` + `following route to use a synchronous matchCallback function:`, route);
508
+ }
509
+ }
510
+ // See https://github.com/GoogleChrome/workbox/issues/2079
511
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
512
+ params = matchResult;
513
+ if (Array.isArray(params) && params.length === 0) {
514
+ // Instead of passing an empty array in as params, use undefined.
515
+ params = undefined;
516
+ } else if (matchResult.constructor === Object && // eslint-disable-line
517
+ Object.keys(matchResult).length === 0) {
518
+ // Instead of passing an empty object in as params, use undefined.
519
+ params = undefined;
520
+ } else if (typeof matchResult === "boolean") {
521
+ // For the boolean value true (rather than just something truth-y),
522
+ // don't set params.
523
+ // See https://github.com/GoogleChrome/workbox/pull/2134#issuecomment-513924353
524
+ params = undefined;
525
+ }
526
+ // Return early if have a match.
527
+ return {
528
+ route,
529
+ params
530
+ };
531
+ }
532
+ }
533
+ // If no match was found above, return and empty object.
534
+ return {};
535
+ }
536
+ /**
537
+ * Define a default `handler` that's called when no routes explicitly
538
+ * match the incoming request.
539
+ *
540
+ * Each HTTP method ('GET', 'POST', etc.) gets its own default handler.
541
+ *
542
+ * Without a default handler, unmatched requests will go against the
543
+ * network as if there were no service worker present.
544
+ *
545
+ * @param handler A callback function that returns a Promise resulting in a Response.
546
+ * @param method The HTTP method to associate with this default handler. Each method
547
+ * has its own default. Defaults to GET.
548
+ */ setDefaultHandler(handler, method = defaultMethod) {
549
+ this._defaultHandlerMap.set(method, normalizeHandler(handler));
550
+ }
551
+ /**
552
+ * If a Route throws an error while handling a request, this `handler`
553
+ * will be called and given a chance to provide a response.
554
+ *
555
+ * @param handler A callback function that returns a Promise resulting
556
+ * in a Response.
557
+ */ setCatchHandler(handler) {
558
+ this._catchHandler = normalizeHandler(handler);
559
+ }
560
+ /**
561
+ * Registers a route with the router.
562
+ *
563
+ * @param route The route to register.
564
+ */ registerRoute(route) {
565
+ if (process.env.NODE_ENV !== "production") {
566
+ internal.assert.isType(route, "object", {
567
+ moduleName: "@serwist/routing",
568
+ className: "Router",
569
+ funcName: "registerRoute",
570
+ paramName: "route"
571
+ });
572
+ internal.assert.hasMethod(route, "match", {
573
+ moduleName: "@serwist/routing",
574
+ className: "Router",
575
+ funcName: "registerRoute",
576
+ paramName: "route"
577
+ });
578
+ internal.assert.isType(route.handler, "object", {
579
+ moduleName: "@serwist/routing",
580
+ className: "Router",
581
+ funcName: "registerRoute",
582
+ paramName: "route"
583
+ });
584
+ internal.assert.hasMethod(route.handler, "handle", {
585
+ moduleName: "@serwist/routing",
586
+ className: "Router",
587
+ funcName: "registerRoute",
588
+ paramName: "route.handler"
589
+ });
590
+ internal.assert.isType(route.method, "string", {
591
+ moduleName: "@serwist/routing",
592
+ className: "Router",
593
+ funcName: "registerRoute",
594
+ paramName: "route.method"
595
+ });
596
+ }
597
+ if (!this._routes.has(route.method)) {
598
+ this._routes.set(route.method, []);
599
+ }
600
+ // Give precedence to all of the earlier routes by adding this additional
601
+ // route to the end of the array.
602
+ this._routes.get(route.method).push(route);
603
+ }
604
+ /**
605
+ * Unregisters a route with the router.
606
+ *
607
+ * @param route The route to unregister.
608
+ */ unregisterRoute(route) {
609
+ if (!this._routes.has(route.method)) {
610
+ throw new internal.SerwistError("unregister-route-but-not-found-with-method", {
611
+ method: route.method
612
+ });
613
+ }
614
+ const routeIndex = this._routes.get(route.method).indexOf(route);
615
+ if (routeIndex > -1) {
616
+ this._routes.get(route.method).splice(routeIndex, 1);
617
+ } else {
618
+ throw new internal.SerwistError("unregister-route-route-not-registered");
619
+ }
620
+ }
621
+ }
622
+
623
+ let defaultRouter;
624
+ /**
625
+ * Creates a new, singleton Router instance if one does not exist. If one
626
+ * does already exist, that instance is returned.
627
+ *
628
+ * @private
629
+ * @returns
630
+ */ const getOrCreateDefaultRouter = ()=>{
631
+ if (!defaultRouter) {
632
+ defaultRouter = new Router();
633
+ // The helpers that use the default Router assume these listeners exist.
634
+ defaultRouter.addFetchListener();
635
+ defaultRouter.addCacheListener();
636
+ }
637
+ return defaultRouter;
638
+ };
639
+
640
+ /**
641
+ * Easily register a RegExp, string, or function with a caching
642
+ * strategy to a singleton Router instance.
643
+ *
644
+ * @param capture If the capture param is a `Route`, all other arguments will be ignored.
645
+ * @param handler A callback function that returns a Promise resulting in a Response.
646
+ * This parameter is required if `capture` is not a `Route` object.
647
+ * @param method The HTTP method to match the Route against. Defaults to GET.
648
+ * @returns The generated `Route`.
649
+ */ function registerRoute(capture, handler, method) {
650
+ let route;
651
+ if (typeof capture === "string") {
652
+ const captureUrl = new URL(capture, location.href);
653
+ if (process.env.NODE_ENV !== "production") {
654
+ if (!(capture.startsWith("/") || capture.startsWith("http"))) {
655
+ throw new internal.SerwistError("invalid-string", {
656
+ moduleName: "@serwist/routing",
657
+ funcName: "registerRoute",
658
+ paramName: "capture"
659
+ });
660
+ }
661
+ // We want to check if Express-style wildcards are in the pathname only.
662
+ // TODO: Remove this log message in v4.
663
+ const valueToCheck = capture.startsWith("http") ? captureUrl.pathname : capture;
664
+ // See https://github.com/pillarjs/path-to-regexp#parameters
665
+ const wildcards = "[*:?+]";
666
+ if (new RegExp(`${wildcards}`).exec(valueToCheck)) {
667
+ internal.logger.debug(`The '$capture' parameter contains an Express-style wildcard ` + `character (${wildcards}). Strings are now always interpreted as ` + `exact matches; use a RegExp for partial or wildcard matches.`);
668
+ }
669
+ }
670
+ const matchCallback = ({ url })=>{
671
+ if (process.env.NODE_ENV !== "production") {
672
+ if (url.pathname === captureUrl.pathname && url.origin !== captureUrl.origin) {
673
+ internal.logger.debug(`${capture} only partially matches the cross-origin URL ` + `${url.toString()}. This route will only handle cross-origin requests ` + `if they match the entire URL.`);
674
+ }
675
+ }
676
+ return url.href === captureUrl.href;
677
+ };
678
+ // If `capture` is a string then `handler` and `method` must be present.
679
+ route = new Route(matchCallback, handler, method);
680
+ } else if (capture instanceof RegExp) {
681
+ // If `capture` is a `RegExp` then `handler` and `method` must be present.
682
+ route = new RegExpRoute(capture, handler, method);
683
+ } else if (typeof capture === "function") {
684
+ // If `capture` is a function then `handler` and `method` must be present.
685
+ route = new Route(capture, handler, method);
686
+ } else if (capture instanceof Route) {
687
+ route = capture;
688
+ } else {
689
+ throw new internal.SerwistError("unsupported-route-type", {
690
+ moduleName: "@serwist/routing",
691
+ funcName: "registerRoute",
692
+ paramName: "capture"
693
+ });
694
+ }
695
+ const defaultRouter = getOrCreateDefaultRouter();
696
+ defaultRouter.registerRoute(route);
697
+ return route;
698
+ }
699
+
700
+ /**
701
+ * If a Route throws an error while handling a request, this `handler`
702
+ * will be called and given a chance to provide a response.
703
+ *
704
+ * @param handler A callback function that returns a Promise resulting in a Response.
705
+ */ function setCatchHandler(handler) {
706
+ const defaultRouter = getOrCreateDefaultRouter();
707
+ defaultRouter.setCatchHandler(handler);
708
+ }
709
+
710
+ /**
711
+ * Define a default `handler` that's called when no routes explicitly
712
+ * match the incoming request.
713
+ *
714
+ * Without a default handler, unmatched requests will go against the
715
+ * network as if there were no service worker present.
716
+ *
717
+ * @param handler A callback function that returns a Promise resulting in a Response.
718
+ */ function setDefaultHandler(handler) {
719
+ const defaultRouter = getOrCreateDefaultRouter();
720
+ defaultRouter.setDefaultHandler(handler);
721
+ }
722
+
723
+ exports.NavigationRoute = NavigationRoute;
724
+ exports.RegExpRoute = RegExpRoute;
725
+ exports.Route = Route;
726
+ exports.Router = Router;
727
+ exports.registerRoute = registerRoute;
728
+ exports.setCatchHandler = setCatchHandler;
729
+ exports.setDefaultHandler = setDefaultHandler;