@serwist/routing 8.4.4 → 9.0.0-preview.1

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