@serwist/sw 9.0.0-preview.19 → 9.0.0-preview.20

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 (70) hide show
  1. package/dist/abstractions/Serwist.d.ts +5 -7
  2. package/dist/abstractions/Serwist.d.ts.map +1 -1
  3. package/dist/chunks/NavigationRoute.js +1 -1
  4. package/dist/chunks/PrecacheFallbackPlugin.js +9 -9
  5. package/dist/chunks/precacheAndRoute.js +6 -5
  6. package/dist/chunks/registerRoute.js +3 -404
  7. package/dist/chunks/{getOrCreatePrecacheController.js → singletonPrecacheController.js} +10 -6
  8. package/dist/chunks/singletonRouter.js +435 -0
  9. package/dist/index.js +8 -7
  10. package/dist/index.plugins.js +2 -2
  11. package/dist/index.precaching.d.ts +2 -1
  12. package/dist/index.precaching.d.ts.map +1 -1
  13. package/dist/index.precaching.js +7 -7
  14. package/dist/index.routing.d.ts +3 -1
  15. package/dist/index.routing.d.ts.map +1 -1
  16. package/dist/index.routing.js +7 -9
  17. package/dist/plugins/googleAnalytics/initialize.d.ts +9 -1
  18. package/dist/plugins/googleAnalytics/initialize.d.ts.map +1 -1
  19. package/dist/precaching/addRoute.d.ts.map +1 -1
  20. package/dist/precaching/matchPrecache.d.ts.map +1 -1
  21. package/dist/precaching/precache.d.ts.map +1 -1
  22. package/dist/precaching/singletonPrecacheController.d.ts +38 -0
  23. package/dist/precaching/singletonPrecacheController.d.ts.map +1 -0
  24. package/dist/precaching/utils/getCacheKeyForURL.d.ts.map +1 -1
  25. package/dist/routing/RegExpRoute.d.ts +3 -3
  26. package/dist/routing/Router.d.ts +49 -23
  27. package/dist/routing/Router.d.ts.map +1 -1
  28. package/dist/routing/parseRoute.d.ts +16 -0
  29. package/dist/routing/parseRoute.d.ts.map +1 -0
  30. package/dist/routing/registerRoute.d.ts +5 -5
  31. package/dist/routing/registerRoute.d.ts.map +1 -1
  32. package/dist/routing/setCatchHandler.d.ts +1 -1
  33. package/dist/routing/setCatchHandler.d.ts.map +1 -1
  34. package/dist/routing/setDefaultHandler.d.ts +1 -1
  35. package/dist/routing/setDefaultHandler.d.ts.map +1 -1
  36. package/dist/routing/singletonRouter.d.ts +47 -0
  37. package/dist/routing/singletonRouter.d.ts.map +1 -0
  38. package/dist/routing/unregisterRoute.d.ts +1 -1
  39. package/dist/routing/unregisterRoute.d.ts.map +1 -1
  40. package/package.json +4 -4
  41. package/src/abstractions/Serwist.ts +10 -12
  42. package/src/abstractions/installSerwist.ts +4 -4
  43. package/src/index.precaching.ts +3 -0
  44. package/src/index.routing.ts +15 -1
  45. package/src/plugins/googleAnalytics/initialize.ts +19 -6
  46. package/src/plugins/precaching/PrecacheFallbackPlugin.ts +2 -2
  47. package/src/precaching/addPlugins.ts +2 -2
  48. package/src/precaching/addRoute.ts +2 -2
  49. package/src/precaching/createHandlerBoundToURL.ts +2 -2
  50. package/src/precaching/getCacheKeyForURL.ts +2 -2
  51. package/src/precaching/matchPrecache.ts +2 -3
  52. package/src/precaching/precache.ts +2 -2
  53. package/src/precaching/singletonPrecacheController.ts +57 -0
  54. package/src/precaching/utils/getCacheKeyForURL.ts +2 -2
  55. package/src/routing/RegExpRoute.ts +3 -3
  56. package/src/routing/Router.ts +101 -52
  57. package/src/routing/{utils/parseRoute.ts → parseRoute.ts} +14 -3
  58. package/src/routing/registerRoute.ts +7 -13
  59. package/src/routing/setCatchHandler.ts +3 -4
  60. package/src/routing/setDefaultHandler.ts +3 -4
  61. package/src/routing/singletonRouter.ts +76 -0
  62. package/src/routing/unregisterRoute.ts +3 -4
  63. package/dist/precaching/utils/getOrCreatePrecacheController.d.ts +0 -7
  64. package/dist/precaching/utils/getOrCreatePrecacheController.d.ts.map +0 -1
  65. package/dist/routing/utils/getOrCreateDefaultRouter.d.ts +0 -10
  66. package/dist/routing/utils/getOrCreateDefaultRouter.d.ts.map +0 -1
  67. package/dist/routing/utils/parseRoute.d.ts +0 -5
  68. package/dist/routing/utils/parseRoute.d.ts.map +0 -1
  69. package/src/precaching/utils/getOrCreatePrecacheController.ts +0 -22
  70. package/src/routing/utils/getOrCreateDefaultRouter.ts +0 -29
@@ -0,0 +1,38 @@
1
+ import { PrecacheController } from "./PrecacheController.js";
2
+ /**
3
+ * Creates a new, singleton `PrecacheController` if one does not exist. If one does
4
+ * already exist, that instance is returned. This instance is used by Serwist's
5
+ * `PrecacheController`-dependent functions and classes unless you provide a different
6
+ * `Router` to them.
7
+ *
8
+ * @returns The singleton `PrecacheController`.
9
+ */
10
+ export declare const getSingletonPrecacheController: () => PrecacheController;
11
+ /**
12
+ * Changes the singleton `PrecacheController` to a different instance. This is meant for when you do not
13
+ * want to pass your own `PrecacheController` to every one of Serwist's `PrecacheController`-dependent
14
+ * functions and classes.
15
+ *
16
+ * It is highly recommended that you call this before anything else, if you plan on doing so.
17
+ *
18
+ * @example
19
+ * ```js
20
+ * import { PrecacheController, setSingletonPrecacheController } from "@serwist/sw/precaching";
21
+ *
22
+ * const controller = new PrecacheController();
23
+ *
24
+ * setSingletonPrecacheController(controller);
25
+ *
26
+ * // Do something with your controller...
27
+ *
28
+ * // This class now automatically picks up your `PrecacheController`! Without `setSingletonPrecacheController`,
29
+ * // you'd need to write this instead: `new Serwist({ controller })`
30
+ * const serwist = new Serwist();
31
+ *
32
+ * serwist.install();
33
+ * ```
34
+ * @param router
35
+ * @returns The new singleton `PrecacheController`.
36
+ */
37
+ export declare const setSingletonPrecacheController: (precacheController: PrecacheController) => PrecacheController;
38
+ //# sourceMappingURL=singletonPrecacheController.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"singletonPrecacheController.d.ts","sourceRoot":"","sources":["../../src/precaching/singletonPrecacheController.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAI7D;;;;;;;GAOG;AACH,eAAO,MAAM,8BAA8B,QAAO,kBAKjD,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,eAAO,MAAM,8BAA8B,uBAAwB,kBAAkB,KAAG,kBAGvF,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"getCacheKeyForURL.d.ts","sourceRoot":"","sources":["../../../src/precaching/utils/getCacheKeyForURL.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAIxD;;;;;;;;;;GAUG;AACH,eAAO,MAAM,iBAAiB,QAAS,MAAM,WAAW,oBAAoB,KAAG,MAAM,GAAG,SAYvF,CAAC"}
1
+ {"version":3,"file":"getCacheKeyForURL.d.ts","sourceRoot":"","sources":["../../../src/precaching/utils/getCacheKeyForURL.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAGxD;;;;;;;;;;GAUG;AACH,eAAO,MAAM,iBAAiB,QAAS,MAAM,WAAW,oBAAoB,KAAG,MAAM,GAAG,SAYvF,CAAC"}
@@ -2,10 +2,10 @@ import type { RouteHandler } from "@serwist/core";
2
2
  import { Route } from "./Route.js";
3
3
  import type { HTTPMethod } from "./utils/constants.js";
4
4
  /**
5
- * RegExpRoute makes it easy to create a regular expression based on a `@serwist/routing` Route.
5
+ * `RegExpRoute` makes it easy to create a regular expression based on a `@serwist/routing` Route.
6
6
  *
7
- * For same-origin requests the RegExp only needs to match part of the URL. For
8
- * requests against third-party servers, you must define a RegExp that matches
7
+ * For same-origin requests the `RegExp` only needs to match part of the URL. For
8
+ * requests against third-party servers, you must define a `RegExp` that matches
9
9
  * the start of the URL.
10
10
  */
11
11
  export declare class RegExpRoute extends Route {
@@ -1,40 +1,49 @@
1
- import type { RouteHandler, RouteHandlerCallbackOptions, RouteMatchCallbackOptions } from "@serwist/core";
1
+ import type { RouteHandler, RouteHandlerCallbackOptions, RouteMatchCallback, RouteMatchCallbackOptions } from "@serwist/core";
2
2
  import type { Route } from "./Route.js";
3
3
  import type { HTTPMethod } from "./utils/constants.js";
4
4
  /**
5
- * The Router can be used to process a `FetchEvent` using one or more `@serwist/routing` Route(s),
6
- * responding with a `Response` if a matching route exists.
5
+ * `Router` can be used to process a `FetchEvent` using one or more `Route`(s), responding with a `Response`
6
+ * if a matching route exists.
7
7
  *
8
- * If no route matches a given a request, the Router will use a "default" handler if one is defined.
8
+ * If no `Route` matches given a `Request`, the `Router` will use the default handler if one is defined.
9
9
  *
10
- * Should the matching Route throw an error, the Router will use a "catch" handler if one is defined to
11
- * gracefully deal with issues and respond with a Request.
10
+ * Should the matching Route throw an error, the Router will use the catch handler if one is defined to
11
+ * gracefully deal with issues and respond with a `Request`.
12
12
  *
13
- * If a request matches multiple routes, the **earliest** registered route will
14
- * be used to respond to the request.
13
+ * If a `Request` matches multiple routes, the earliest registered route will be used to respond to the `Request`.
15
14
  */
16
15
  export declare class Router {
17
16
  private readonly _routes;
18
17
  private readonly _defaultHandlerMap;
18
+ private _fetchListenerHandler;
19
+ private _cacheListenerHandler;
19
20
  private _catchHandler?;
20
21
  /**
21
22
  * Initializes a new Router.
22
23
  */
23
24
  constructor();
24
25
  /**
25
- * @returns routes A `Map` of HTTP method name ('GET', etc.) to an array of all the corresponding `Route`
26
+ * @returns routes A `Map` of HTTP method name (`'GET'`, etc.) to an array of all the corresponding `Route`
26
27
  * instances that are registered.
27
28
  */
28
29
  get routes(): Map<HTTPMethod, Route[]>;
29
30
  /**
30
- * Adds a fetch event listener to respond to events when a route matches
31
- * the event's request.
31
+ * Adds a `fetch` event listener to respond to events when a `Route` matches
32
+ * the event's request. Effectively no-op if `addFEtchListener` has been
33
+ * called, but `removeFetchListener` has not.
32
34
  */
33
35
  addFetchListener(): void;
34
36
  /**
35
- * Adds a message event listener for URLs to cache from the window.
37
+ * Removes `fetch` event listener added by `addFetchListener`.
38
+ * Effectively no-op if either `addFetchListener` has not been called or,
39
+ * if it has, so has `removeFetchListener`.
40
+ */
41
+ removeFetchListener(): void;
42
+ /**
43
+ * Adds a `message` event listener for URLs to cache from the window.
36
44
  * This is useful to cache resources loaded on the page prior to when the
37
- * service worker started controlling it.
45
+ * service worker started controlling it. Effectively no-op if `addCacheListener`
46
+ * has been called, but `removeCacheListener` hasn't.
38
47
  *
39
48
  * The format of the message data sent from the window should be as follows.
40
49
  * Where the `urlsToCache` array may consist of URL strings or an array of
@@ -55,8 +64,14 @@ export declare class Router {
55
64
  */
56
65
  addCacheListener(): void;
57
66
  /**
58
- * Apply the routing rules to a FetchEvent object to get a Response from an
59
- * appropriate Route's handler.
67
+ * Removes the `message` event listener added by `addCacheListener`.
68
+ * Effectively no-op if either `addCacheListener` has not been called or,
69
+ * if it has, so has `removeCacheListener`.
70
+ */
71
+ removeCacheListener(): void;
72
+ /**
73
+ * Apply the routing rules to a `FetchEvent` object to get a `Response` from an
74
+ * appropriate `Route`'s handler.
60
75
  *
61
76
  * @param options
62
77
  * @returns A promise is returned if a registered route can handle the request.
@@ -90,18 +105,18 @@ export declare class Router {
90
105
  * Define a default `handler` that's called when no routes explicitly
91
106
  * match the incoming request.
92
107
  *
93
- * Each HTTP method ('GET', 'POST', etc.) gets its own default handler.
108
+ * Each HTTP method (`'GET'`, `'POST'`, etc.) gets its own default handler.
94
109
  *
95
110
  * Without a default handler, unmatched requests will go against the
96
111
  * network as if there were no service worker present.
97
112
  *
98
- * @param handler A callback function that returns a Promise resulting in a Response.
113
+ * @param handler A callback function that returns a `Promise` resulting in a `Response`.
99
114
  * @param method The HTTP method to associate with this default handler. Each method
100
- * has its own default. Defaults to GET.
115
+ * has its own default. Defaults to `'GET'`.
101
116
  */
102
117
  setDefaultHandler(handler: RouteHandler, method?: HTTPMethod): void;
103
118
  /**
104
- * If a Route throws an error while handling a request, this `handler`
119
+ * If a `Route` throws an error while handling a request, this `handler`
105
120
  * will be called and given a chance to provide a response.
106
121
  *
107
122
  * @param handler A callback function that returns a Promise resulting
@@ -109,15 +124,26 @@ export declare class Router {
109
124
  */
110
125
  setCatchHandler(handler: RouteHandler): void;
111
126
  /**
112
- * Registers a route with the router.
127
+ * Registers a `RegExp`, string, or function with a caching
128
+ * strategy to the `Router`.
129
+ *
130
+ * @param capture If the capture param is a `Route`, all other arguments will be ignored.
131
+ * @param handler A callback function that returns a `Promise` resulting in a `Response`.
132
+ * This parameter is required if `capture` is not a `Route` object.
133
+ * @param method The HTTP method to match the Route against. Defaults to `'GET'`.
134
+ * @returns The generated `Route`.
135
+ */
136
+ registerCapture(capture: RegExp | string | RouteMatchCallback | Route, handler?: RouteHandler, method?: HTTPMethod): Route;
137
+ /**
138
+ * Registers a `Route` with the router.
113
139
  *
114
- * @param route The route to register.
140
+ * @param route The `Route` to register.
115
141
  */
116
142
  registerRoute(route: Route): void;
117
143
  /**
118
- * Unregisters a route with the router.
144
+ * Unregisters a `Route` with the `Router`.
119
145
  *
120
- * @param route The route to unregister.
146
+ * @param route The `Route` to unregister.
121
147
  */
122
148
  unregisterRoute(route: Route): void;
123
149
  }
@@ -1 +1 @@
1
- {"version":3,"file":"Router.d.ts","sourceRoot":"","sources":["../../src/routing/Router.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,YAAY,EAAE,2BAA2B,EAAsB,yBAAyB,EAAE,MAAM,eAAe,CAAC;AAG9H,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAevD;;;;;;;;;;;GAWG;AACH,qBAAa,MAAM;IACjB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA2B;IACnD,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAAsC;IACzE,OAAO,CAAC,aAAa,CAAC,CAAqB;IAE3C;;OAEG;;IAMH;;;OAGG;IACH,IAAI,MAAM,IAAI,GAAG,CAAC,UAAU,EAAE,KAAK,EAAE,CAAC,CAErC;IAED;;;OAGG;IACH,gBAAgB,IAAI,IAAI;IAUxB;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,gBAAgB,IAAI,IAAI;IA8BxB;;;;;;;;OAQG;IACH,aAAa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import { Route } from "./Route.js";
3
+ import type { HTTPMethod } from "./utils/constants.js";
4
+ /**
5
+ * Parses a `RegExp`, string, or function with a caching strategy into a `Route`. This is for
6
+ * when you want to create a `Route`, but you don't want to register it just yet: sometimes
7
+ * you want to call `setCatchHandler` first, for example.
8
+ *
9
+ * @param capture If the capture param is a `Route`, all other arguments will be ignored.
10
+ * @param handler A callback function that returns a `Promise` resulting in a `Response`.
11
+ * This parameter is required if `capture` is not a `Route` object.
12
+ * @param method The HTTP method to match the `Route` against. Defaults to `'GET'`.
13
+ * @returns The generated `Route`.
14
+ */
15
+ export declare const parseRoute: (capture: RegExp | string | RouteMatchCallback | Route, handler?: RouteHandler, method?: HTTPMethod) => Route;
16
+ //# sourceMappingURL=parseRoute.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parseRoute.d.ts","sourceRoot":"","sources":["../../src/routing/parseRoute.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAItE,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAEvD;;;;;;;;;;GAUG;AACH,eAAO,MAAM,UAAU,YAAa,MAAM,GAAG,MAAM,GAAG,kBAAkB,GAAG,KAAK,YAAY,YAAY,WAAW,UAAU,KAAG,KA2D/H,CAAC"}
@@ -2,14 +2,14 @@ import type { RouteHandler, RouteMatchCallback } from "@serwist/core";
2
2
  import { Route } from "./Route.js";
3
3
  import type { HTTPMethod } from "./utils/constants.js";
4
4
  /**
5
- * Registers a RegExp, string, or function with a caching
6
- * strategy to a singleton Router instance.
5
+ * Registers a `RegExp`, string, or function with a caching
6
+ * strategy to a singleton `Router` instance.
7
7
  *
8
8
  * @param capture If the capture param is a `Route`, all other arguments will be ignored.
9
- * @param handler A callback function that returns a Promise resulting in a Response.
9
+ * @param handler A callback function that returns a `Promise` resulting in a `Response`.
10
10
  * This parameter is required if `capture` is not a `Route` object.
11
- * @param method The HTTP method to match the Route against. Defaults to GET.
12
- * @returns The generated `Route`.
11
+ * @param method The HTTP method to match the `Route` against. Defaults to `'GET'`.
12
+ * @returns The generated `Route`, which can then be provided to `unregisterRoute` if needed.
13
13
  */
14
14
  export declare const registerRoute: (capture: RegExp | string | RouteMatchCallback | Route, handler?: RouteHandler, method?: HTTPMethod) => Route;
15
15
  //# sourceMappingURL=registerRoute.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"registerRoute.d.ts","sourceRoot":"","sources":["../../src/routing/registerRoute.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAEtE,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAIvD;;;;;;;;;GASG;AACH,eAAO,MAAM,aAAa,YAAa,MAAM,GAAG,MAAM,GAAG,kBAAkB,GAAG,KAAK,YAAY,YAAY,WAAW,UAAU,KAAG,KAOlI,CAAC"}
1
+ {"version":3,"file":"registerRoute.d.ts","sourceRoot":"","sources":["../../src/routing/registerRoute.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAEtE,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAEnC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAEvD;;;;;;;;;GASG;AACH,eAAO,MAAM,aAAa,YAAa,MAAM,GAAG,MAAM,GAAG,kBAAkB,GAAG,KAAK,YAAY,YAAY,WAAW,UAAU,KAAG,KAElI,CAAC"}
@@ -1,6 +1,6 @@
1
1
  import type { RouteHandler } from "@serwist/core";
2
2
  /**
3
- * If a Route throws an error while handling a request, this `handler`
3
+ * If a `Route` throws an error while handling a request, this `handler`
4
4
  * will be called and given a chance to provide a response.
5
5
  *
6
6
  * @param handler A callback function that returns a Promise resulting in a Response.
@@ -1 +1 @@
1
- {"version":3,"file":"setCatchHandler.d.ts","sourceRoot":"","sources":["../../src/routing/setCatchHandler.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAIlD;;;;;GAKG;AACH,eAAO,MAAM,eAAe,YAAa,YAAY,KAAG,IAGvD,CAAC"}
1
+ {"version":3,"file":"setCatchHandler.d.ts","sourceRoot":"","sources":["../../src/routing/setCatchHandler.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAIlD;;;;;GAKG;AACH,eAAO,MAAM,eAAe,YAAa,YAAY,KAAG,IAEvD,CAAC"}
@@ -3,7 +3,7 @@ import type { RouteHandler } from "@serwist/core";
3
3
  * Defines a default `handler` that's called when no routes explicitly
4
4
  * match the incoming request.
5
5
  *
6
- * Without a default handler, unmatched requests will go against the
6
+ * Without a default `handler`, unmatched requests will go against the
7
7
  * network as if there were no service worker present.
8
8
  *
9
9
  * @param handler A callback function that returns a Promise resulting in a Response.
@@ -1 +1 @@
1
- {"version":3,"file":"setDefaultHandler.d.ts","sourceRoot":"","sources":["../../src/routing/setDefaultHandler.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAIlD;;;;;;;;GAQG;AACH,eAAO,MAAM,iBAAiB,YAAa,YAAY,KAAG,IAGzD,CAAC"}
1
+ {"version":3,"file":"setDefaultHandler.d.ts","sourceRoot":"","sources":["../../src/routing/setDefaultHandler.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAIlD;;;;;;;;GAQG;AACH,eAAO,MAAM,iBAAiB,YAAa,YAAY,KAAG,IAEzD,CAAC"}
@@ -0,0 +1,47 @@
1
+ import { Router } from "./Router.js";
2
+ /**
3
+ * Creates a new, singleton `Router` if one does not exist. If one does
4
+ * already exist, that instance is returned. This instance is used by
5
+ * Serwist's `Router`-dependent functions and classes unless you provide
6
+ * a different `Router` to them.
7
+ *
8
+ * @returns The singleton `Router`.
9
+ */
10
+ export declare const getSingletonRouter: () => Router;
11
+ /**
12
+ * Changes the singleton `Router` to a different instance. This is meant for when you do not
13
+ * want to pass your own `Router` to every one of Serwist's `Router`-dependent functions and classes.
14
+ * If this or `getSingletonRouter` has been called before, it removes the listeners of the
15
+ * previous singleton `Router`. It also adds those of the new one, so you need not do that yourself.
16
+ *
17
+ * It is highly recommended that you call this before anything else, if you plan on doing so.
18
+ *
19
+ * @example
20
+ * ```js
21
+ * import { Router, setSingletonRouter } from "@serwist/sw/routing";
22
+ *
23
+ * const router = new Router();
24
+ *
25
+ * setSingletonRouter(router);
26
+ *
27
+ * router.registerRoute(
28
+ * new Route(
29
+ * /\/api\/.*\/*.json/,
30
+ * new NetworkOnly({
31
+ * plugins: [backgroundSync],
32
+ * }),
33
+ * "POST",
34
+ * ),
35
+ * );
36
+ *
37
+ * // This class now automatically picks up your `Router`! Without `setSingletonRouter`, you'd need to
38
+ * // write this instead: `new Serwist({ router })`
39
+ * const serwist = new Serwist();
40
+ *
41
+ * serwist.install();
42
+ * ```
43
+ * @param router
44
+ * @returns The new singleton `Router`.
45
+ */
46
+ export declare const setSingletonRouter: (router: Router) => Router;
47
+ //# sourceMappingURL=singletonRouter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"singletonRouter.d.ts","sourceRoot":"","sources":["../../src/routing/singletonRouter.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAIrC;;;;;;;GAOG;AACH,eAAO,MAAM,kBAAkB,QAAO,MASrC,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,eAAO,MAAM,kBAAkB,WAAY,MAAM,KAAG,MASnD,CAAC"}
@@ -1,6 +1,6 @@
1
1
  import type { Route } from "./Route.js";
2
2
  /**
3
- * Unregisters a route from the singleton Router instance.
3
+ * Unregisters a route from the singleton `Router` instance.
4
4
  *
5
5
  * @param route The route to unregister.
6
6
  */
@@ -1 +1 @@
1
- {"version":3,"file":"unregisterRoute.d.ts","sourceRoot":"","sources":["../../src/routing/unregisterRoute.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAGxC;;;;GAIG;AACH,eAAO,MAAM,eAAe,UAAW,KAAK,KAAG,IAG9C,CAAC"}
1
+ {"version":3,"file":"unregisterRoute.d.ts","sourceRoot":"","sources":["../../src/routing/unregisterRoute.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAGxC;;;;GAIG;AACH,eAAO,MAAM,eAAe,UAAW,KAAK,KAAG,IAE9C,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@serwist/sw",
3
- "version": "9.0.0-preview.19",
3
+ "version": "9.0.0-preview.20",
4
4
  "type": "module",
5
5
  "description": "A service worker helper module.",
6
6
  "files": [
@@ -61,13 +61,13 @@
61
61
  },
62
62
  "dependencies": {
63
63
  "idb": "8.0.0",
64
- "@serwist/core": "9.0.0-preview.19"
64
+ "@serwist/core": "9.0.0-preview.20"
65
65
  },
66
66
  "devDependencies": {
67
67
  "rollup": "4.13.0",
68
68
  "typescript": "5.5.0-dev.20240323",
69
- "@serwist/constants": "9.0.0-preview.19",
70
- "@serwist/utils": "9.0.0-preview.19"
69
+ "@serwist/constants": "9.0.0-preview.20",
70
+ "@serwist/utils": "9.0.0-preview.20"
71
71
  },
72
72
  "peerDependencies": {
73
73
  "typescript": ">=5.0.0"
@@ -4,11 +4,11 @@ import { PrecacheController } from "../precaching/PrecacheController.js";
4
4
  import { PrecacheRoute } from "../precaching/PrecacheRoute.js";
5
5
  import { cleanupOutdatedCaches as cleanupOutdatedCachesImpl } from "../precaching/cleanupOutdatedCaches.js";
6
6
  import { createHandlerBoundToURL } from "../precaching/createHandlerBoundToURL.js";
7
- import { getOrCreatePrecacheController } from "../precaching/utils/getOrCreatePrecacheController.js";
7
+ import { getSingletonPrecacheController } from "../precaching/singletonPrecacheController.js";
8
8
  import { NavigationRoute } from "../routing/NavigationRoute.js";
9
9
  import { Router } from "../routing/Router.js";
10
- import { getOrCreateDefaultRouter } from "../routing/utils/getOrCreateDefaultRouter.js";
11
- import { parseRoute } from "../routing/utils/parseRoute.js";
10
+ import { parseRoute } from "../routing/parseRoute.js";
11
+ import { getSingletonRouter } from "../routing/singletonRouter.js";
12
12
  import { disableDevLogs as disableDevLogsImpl } from "./disableDevLogs.js";
13
13
  import { fallbacks as fallbacksImpl } from "./fallbacks.js";
14
14
  import type { FallbacksOptions } from "./fallbacks.js";
@@ -20,15 +20,13 @@ declare const self: ServiceWorkerGlobalScope;
20
20
 
21
21
  export interface SerwistOptions {
22
22
  /**
23
- * The precache controller that will be used to perform efficient
24
- * precaching of assets.
25
- * @see https://serwist.pages.dev/docs/sw/precaching
23
+ * An optional `PrecacheController` instance. If not provided, the singleton
24
+ * `PrecacheController` will be used.
26
25
  */
27
26
  precacheController?: PrecacheController;
28
27
  /**
29
- * The router that will be used to process a `FetchEvent`, responding
30
- * with a `Response` if a matching route exists.
31
- * @see https://serwist.pages.dev/docs/sw/routing
28
+ * An optional `Router` instance. If not provided, the singleton `Router`
29
+ * will be used.
32
30
  */
33
31
  router?: Router;
34
32
  }
@@ -95,8 +93,8 @@ export class Serwist {
95
93
  private _precacheController: PrecacheController;
96
94
  private _router: Router;
97
95
  constructor({ precacheController, router }: SerwistOptions = {}) {
98
- this._precacheController = precacheController || getOrCreatePrecacheController();
99
- this._router = router || getOrCreateDefaultRouter();
96
+ this._precacheController = precacheController || getSingletonPrecacheController();
97
+ this._router = router || getSingletonRouter();
100
98
  }
101
99
  install({
102
100
  precacheEntries,
@@ -114,7 +112,7 @@ export class Serwist {
114
112
  offlineAnalyticsConfig,
115
113
  disableDevLogs = false,
116
114
  fallbacks,
117
- }: SerwistInstallOptions) {
115
+ }: SerwistInstallOptions = {}) {
118
116
  if (!!importScripts && importScripts.length > 0) self.importScripts(...importScripts);
119
117
 
120
118
  if (navigationPreload) enableNavigationPreload();
@@ -1,6 +1,6 @@
1
1
  import { logger } from "@serwist/core/internal";
2
- import { getOrCreatePrecacheController } from "../precaching/utils/getOrCreatePrecacheController.js";
3
- import { getOrCreateDefaultRouter } from "../routing/utils/getOrCreateDefaultRouter.js";
2
+ import { getSingletonPrecacheController } from "../precaching/singletonPrecacheController.js";
3
+ import { getSingletonRouter } from "../routing/singletonRouter.js";
4
4
  import { Serwist, type SerwistInstallOptions } from "./Serwist.js";
5
5
 
6
6
  /**
@@ -21,8 +21,8 @@ export const installSerwist = (options: InstallSerwistOptions): void => {
21
21
  logger.warn("'installSerwist' has been deprecated. Please migrate to 'new Serwist().install()'.");
22
22
  }
23
23
  const serwist = new Serwist({
24
- precacheController: getOrCreatePrecacheController(),
25
- router: getOrCreateDefaultRouter(),
24
+ precacheController: getSingletonPrecacheController(),
25
+ router: getSingletonRouter(),
26
26
  });
27
27
  serwist.install(options);
28
28
  };
@@ -9,6 +9,7 @@ import { getCacheKeyForURL } from "./precaching/getCacheKeyForURL.js";
9
9
  import { matchPrecache } from "./precaching/matchPrecache.js";
10
10
  import { precache } from "./precaching/precache.js";
11
11
  import { precacheAndRoute } from "./precaching/precacheAndRoute.js";
12
+ import { getSingletonPrecacheController, setSingletonPrecacheController } from "./precaching/singletonPrecacheController.js";
12
13
 
13
14
  /**
14
15
  * Most consumers of this module will want to use the
@@ -33,6 +34,8 @@ export {
33
34
  PrecacheController,
34
35
  PrecacheRoute,
35
36
  PrecacheStrategy,
37
+ getSingletonPrecacheController,
38
+ setSingletonPrecacheController,
36
39
  };
37
40
 
38
41
  export type * from "./precaching/types.js";
@@ -3,12 +3,26 @@ import { NavigationRoute } from "./routing/NavigationRoute.js";
3
3
  import { RegExpRoute } from "./routing/RegExpRoute.js";
4
4
  import { Route } from "./routing/Route.js";
5
5
  import { Router } from "./routing/Router.js";
6
+ import { parseRoute } from "./routing/parseRoute.js";
6
7
  import { registerRoute } from "./routing/registerRoute.js";
7
8
  import { setCatchHandler } from "./routing/setCatchHandler.js";
8
9
  import { setDefaultHandler } from "./routing/setDefaultHandler.js";
10
+ import { getSingletonRouter, setSingletonRouter } from "./routing/singletonRouter.js";
9
11
  import { unregisterRoute } from "./routing/unregisterRoute.js";
10
12
  import type { HTTPMethod } from "./routing/utils/constants.js";
11
13
 
12
- export { NavigationRoute, RegExpRoute, registerRoute, Route, Router, setCatchHandler, setDefaultHandler, unregisterRoute };
14
+ export {
15
+ NavigationRoute,
16
+ RegExpRoute,
17
+ parseRoute,
18
+ registerRoute,
19
+ Route,
20
+ Router,
21
+ setCatchHandler,
22
+ setDefaultHandler,
23
+ getSingletonRouter,
24
+ setSingletonRouter,
25
+ unregisterRoute,
26
+ };
13
27
 
14
28
  export type { HTTPMethod, NavigationRouteMatchOptions };
@@ -9,12 +9,13 @@
9
9
  import type { RouteMatchCallbackOptions } from "@serwist/core";
10
10
  import { getFriendlyURL, logger, privateCacheNames } from "@serwist/core/internal";
11
11
  import { Route } from "../../routing/Route.js";
12
- import { registerRoute } from "../../routing/registerRoute.js";
13
12
  import { NetworkFirst } from "../../strategies/NetworkFirst.js";
14
13
  import { NetworkOnly } from "../../strategies/NetworkOnly.js";
15
14
  import { BackgroundSyncPlugin } from "../backgroundSync/BackgroundSyncPlugin.js";
16
15
  import type { Queue, QueueEntry } from "../backgroundSync/Queue.js";
17
16
 
17
+ import type { Router } from "../../routing/Router.js";
18
+ import { getSingletonRouter } from "../../routing/singletonRouter.js";
18
19
  import {
19
20
  ANALYTICS_JS_PATH,
20
21
  COLLECT_PATHS_REGEX,
@@ -27,6 +28,11 @@ import {
27
28
  } from "./constants.js";
28
29
 
29
30
  export interface GoogleAnalyticsInitializeOptions {
31
+ /**
32
+ * An optional `Router` instance. If not provided, the singleton `Router`
33
+ * will be used.
34
+ */
35
+ router?: Router;
30
36
  /**
31
37
  * The cache name to store and retrieve analytics.js. Defaults to the cache names provided by `@serwist/core`.
32
38
  */
@@ -56,7 +62,7 @@ export interface GoogleAnalyticsInitializeOptions {
56
62
  * @returns The requestWillDequeue callback function.
57
63
  * @private
58
64
  */
59
- const createOnSyncCallback = (config: GoogleAnalyticsInitializeOptions) => {
65
+ const createOnSyncCallback = (config: Pick<GoogleAnalyticsInitializeOptions, "parameterOverrides" | "hitFilter">) => {
60
66
  return async ({ queue }: { queue: Queue }) => {
61
67
  let entry: QueueEntry | undefined = undefined;
62
68
  while ((entry = await queue.shiftRequest())) {
@@ -182,19 +188,26 @@ const createGtmJsRoute = (cacheName: string) => {
182
188
  };
183
189
 
184
190
  /**
191
+ * Initialize Serwist's offline Google Analytics v3 support.
192
+ *
185
193
  * @param options
186
194
  */
187
- export const initialize = (options: GoogleAnalyticsInitializeOptions = {}): void => {
188
- const cacheName = privateCacheNames.getGoogleAnalyticsName(options.cacheName);
195
+ export const initialize = ({ cacheName, router = getSingletonRouter(), ...options }: GoogleAnalyticsInitializeOptions = {}): void => {
196
+ const resolvedCacheName = privateCacheNames.getGoogleAnalyticsName(cacheName);
189
197
 
190
198
  const bgSyncPlugin = new BackgroundSyncPlugin(QUEUE_NAME, {
191
199
  maxRetentionTime: MAX_RETENTION_TIME,
192
200
  onSync: createOnSyncCallback(options),
193
201
  });
194
202
 
195
- const routes = [createGtmJsRoute(cacheName), createAnalyticsJsRoute(cacheName), createGtagJsRoute(cacheName), ...createCollectRoutes(bgSyncPlugin)];
203
+ const routes = [
204
+ createGtmJsRoute(resolvedCacheName),
205
+ createAnalyticsJsRoute(resolvedCacheName),
206
+ createGtagJsRoute(resolvedCacheName),
207
+ ...createCollectRoutes(bgSyncPlugin),
208
+ ];
196
209
 
197
210
  for (const route of routes) {
198
- registerRoute(route);
211
+ router.registerRoute(route);
199
212
  }
200
213
  };
@@ -9,7 +9,7 @@
9
9
  import type { HandlerDidErrorCallbackParam, SerwistPlugin } from "@serwist/core";
10
10
 
11
11
  import type { PrecacheController } from "../../precaching/PrecacheController.js";
12
- import { getOrCreatePrecacheController } from "../../precaching/utils/getOrCreatePrecacheController.js";
12
+ import { getSingletonPrecacheController } from "../../precaching/singletonPrecacheController.js";
13
13
 
14
14
  export interface PrecacheFallbackEntry {
15
15
  /**
@@ -59,7 +59,7 @@ export class PrecacheFallbackPlugin implements SerwistPlugin {
59
59
  */
60
60
  constructor({ fallbackUrls, precacheController }: PrecacheFallbackPluginOptions) {
61
61
  this._fallbackUrls = fallbackUrls;
62
- this._precacheController = precacheController || getOrCreatePrecacheController();
62
+ this._precacheController = precacheController || getSingletonPrecacheController();
63
63
  }
64
64
 
65
65
  /**
@@ -8,7 +8,7 @@
8
8
 
9
9
  import type { SerwistPlugin } from "@serwist/core";
10
10
 
11
- import { getOrCreatePrecacheController } from "./utils/getOrCreatePrecacheController.js";
11
+ import { getSingletonPrecacheController } from "./singletonPrecacheController.js";
12
12
 
13
13
  /**
14
14
  * Adds plugins to the precaching strategy.
@@ -16,6 +16,6 @@ import { getOrCreatePrecacheController } from "./utils/getOrCreatePrecacheContro
16
16
  * @param plugins
17
17
  */
18
18
  export const addPlugins = (plugins: SerwistPlugin[]): void => {
19
- const precacheController = getOrCreatePrecacheController();
19
+ const precacheController = getSingletonPrecacheController();
20
20
  precacheController.strategy.plugins.push(...plugins);
21
21
  };
@@ -7,8 +7,8 @@
7
7
 
8
8
  import { registerRoute } from "../routing/registerRoute.js";
9
9
  import { PrecacheRoute } from "./PrecacheRoute.js";
10
+ import { getSingletonPrecacheController } from "./singletonPrecacheController.js";
10
11
  import type { PrecacheRouteOptions } from "./types.js";
11
- import { getOrCreatePrecacheController } from "./utils/getOrCreatePrecacheController.js";
12
12
 
13
13
  /**
14
14
  * Add a `fetch` listener to the service worker that will
@@ -23,7 +23,7 @@ import { getOrCreatePrecacheController } from "./utils/getOrCreatePrecacheContro
23
23
  * @param options See the `@serwist/precaching.PrecacheRoute` options.
24
24
  */
25
25
  export const addRoute = (options?: PrecacheRouteOptions): void => {
26
- const precacheController = getOrCreatePrecacheController();
26
+ const precacheController = getSingletonPrecacheController();
27
27
 
28
28
  const precacheRoute = new PrecacheRoute(precacheController, options);
29
29
  registerRoute(precacheRoute);