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