serwist 9.1.0-preview.0 → 10.0.0-preview.2

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 (239) hide show
  1. package/dist/NavigationRoute.d.ts.map +1 -1
  2. package/dist/RegExpRoute.d.ts.map +1 -1
  3. package/dist/Route.d.ts.map +1 -1
  4. package/dist/Serwist.d.ts +75 -53
  5. package/dist/Serwist.d.ts.map +1 -1
  6. package/dist/cacheNames.d.ts.map +1 -1
  7. package/dist/chunks/waitUntil.js +49 -42
  8. package/dist/copyResponse.d.ts.map +1 -1
  9. package/dist/index.d.ts +11 -36
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.internal.d.ts +16 -16
  12. package/dist/index.internal.d.ts.map +1 -1
  13. package/dist/index.internal.js +25 -3
  14. package/dist/index.js +1918 -248
  15. package/dist/lib/backgroundSync/BackgroundSyncPlugin.d.ts +2 -2
  16. package/dist/lib/backgroundSync/BackgroundSyncPlugin.d.ts.map +1 -1
  17. package/dist/lib/backgroundSync/StorableRequest.d.ts.map +1 -1
  18. package/dist/lib/backgroundSync/index.d.ts +6 -0
  19. package/dist/lib/backgroundSync/index.d.ts.map +1 -0
  20. package/dist/lib/broadcastUpdate/BroadcastCacheUpdate.d.ts.map +1 -1
  21. package/dist/lib/broadcastUpdate/BroadcastUpdatePlugin.d.ts +2 -2
  22. package/dist/lib/broadcastUpdate/BroadcastUpdatePlugin.d.ts.map +1 -1
  23. package/dist/lib/broadcastUpdate/index.d.ts +6 -0
  24. package/dist/lib/broadcastUpdate/index.d.ts.map +1 -0
  25. package/dist/lib/broadcastUpdate/responsesAreSame.d.ts.map +1 -1
  26. package/dist/lib/cacheableResponse/CacheableResponsePlugin.d.ts +3 -3
  27. package/dist/lib/cacheableResponse/CacheableResponsePlugin.d.ts.map +1 -1
  28. package/dist/lib/cacheableResponse/index.d.ts +4 -0
  29. package/dist/lib/cacheableResponse/index.d.ts.map +1 -0
  30. package/dist/{legacy/utils → lib/controllers/PrecacheController}/PrecacheCacheKeyPlugin.d.ts +4 -4
  31. package/dist/lib/controllers/PrecacheController/PrecacheCacheKeyPlugin.d.ts.map +1 -0
  32. package/dist/{legacy → lib/controllers/PrecacheController}/PrecacheController.d.ts +77 -64
  33. package/dist/lib/controllers/PrecacheController/PrecacheController.d.ts.map +1 -0
  34. package/dist/lib/controllers/PrecacheController/PrecacheInstallReportPlugin.d.ts +14 -0
  35. package/dist/lib/controllers/PrecacheController/PrecacheInstallReportPlugin.d.ts.map +1 -0
  36. package/dist/{PrecacheRoute.d.ts → lib/controllers/PrecacheController/PrecacheRoute.d.ts} +4 -5
  37. package/dist/lib/controllers/PrecacheController/PrecacheRoute.d.ts.map +1 -0
  38. package/dist/lib/{strategies → controllers/PrecacheController}/PrecacheStrategy.d.ts +6 -6
  39. package/dist/lib/controllers/PrecacheController/PrecacheStrategy.d.ts.map +1 -0
  40. package/dist/lib/controllers/PrecacheController/parsePrecacheOptions.d.ts +25 -0
  41. package/dist/lib/controllers/PrecacheController/parsePrecacheOptions.d.ts.map +1 -0
  42. package/dist/lib/controllers/RuntimeCacheController.d.ts +70 -0
  43. package/dist/lib/controllers/RuntimeCacheController.d.ts.map +1 -0
  44. package/dist/lib/controllers/index.d.ts +4 -0
  45. package/dist/lib/controllers/index.d.ts.map +1 -0
  46. package/dist/lib/expiration/ExpirationPlugin.d.ts +2 -2
  47. package/dist/lib/expiration/ExpirationPlugin.d.ts.map +1 -1
  48. package/dist/lib/expiration/index.d.ts +4 -0
  49. package/dist/lib/expiration/index.d.ts.map +1 -0
  50. package/dist/lib/googleAnalytics/index.d.ts +3 -0
  51. package/dist/lib/googleAnalytics/index.d.ts.map +1 -0
  52. package/dist/lib/googleAnalytics/initializeGoogleAnalytics.d.ts.map +1 -1
  53. package/dist/lib/precaching/PrecacheFallbackPlugin.d.ts +15 -9
  54. package/dist/lib/precaching/PrecacheFallbackPlugin.d.ts.map +1 -1
  55. package/dist/lib/precaching/index.d.ts +3 -0
  56. package/dist/lib/precaching/index.d.ts.map +1 -0
  57. package/dist/lib/rangeRequests/RangeRequestsPlugin.d.ts +3 -3
  58. package/dist/lib/rangeRequests/RangeRequestsPlugin.d.ts.map +1 -1
  59. package/dist/lib/rangeRequests/createPartialResponse.d.ts.map +1 -1
  60. package/dist/lib/rangeRequests/index.d.ts +3 -0
  61. package/dist/lib/rangeRequests/index.d.ts.map +1 -0
  62. package/dist/lib/rangeRequests/utils/calculateEffectiveBoundaries.d.ts.map +1 -1
  63. package/dist/lib/rangeRequests/utils/parseRangeHeader.d.ts.map +1 -1
  64. package/dist/lib/strategies/Strategy.d.ts +3 -3
  65. package/dist/lib/strategies/Strategy.d.ts.map +1 -1
  66. package/dist/lib/strategies/StrategyHandler.d.ts +4 -4
  67. package/dist/lib/strategies/StrategyHandler.d.ts.map +1 -1
  68. package/dist/lib/strategies/index.d.ts +11 -0
  69. package/dist/lib/strategies/index.d.ts.map +1 -0
  70. package/dist/lib/strategies/plugins/cacheOkAndOpaquePlugin.d.ts +2 -2
  71. package/dist/lib/strategies/plugins/cacheOkAndOpaquePlugin.d.ts.map +1 -1
  72. package/dist/navigationPreload.d.ts.map +1 -1
  73. package/dist/registerQuotaErrorCallback.d.ts.map +1 -1
  74. package/dist/setCacheNameDetails.d.ts +1 -1
  75. package/dist/setCacheNameDetails.d.ts.map +1 -1
  76. package/dist/types.d.ts +35 -64
  77. package/dist/types.d.ts.map +1 -1
  78. package/dist/utils/SerwistError.d.ts +1 -1
  79. package/dist/utils/SerwistError.d.ts.map +1 -1
  80. package/dist/utils/cleanupOutdatedCaches.d.ts.map +1 -1
  81. package/dist/utils/createCacheKey.d.ts.map +1 -1
  82. package/dist/utils/deleteOutdatedCaches.d.ts.map +1 -1
  83. package/dist/utils/getFriendlyURL.d.ts.map +1 -1
  84. package/dist/utils/normalizeHandler.d.ts.map +1 -1
  85. package/dist/utils/parseRoute.d.ts.map +1 -1
  86. package/dist/utils/pluginUtils.d.ts +2 -2
  87. package/dist/utils/pluginUtils.d.ts.map +1 -1
  88. package/dist/utils/printCleanupDetails.d.ts.map +1 -1
  89. package/dist/utils/printInstallDetails.d.ts.map +1 -1
  90. package/dist/utils/removeIgnoredSearchParams.d.ts.map +1 -1
  91. package/dist/utils/waitUntil.d.ts.map +1 -1
  92. package/package.json +29 -13
  93. package/src/NavigationRoute.ts +2 -2
  94. package/src/RegExpRoute.ts +2 -2
  95. package/src/Route.ts +2 -2
  96. package/src/Serwist.ts +170 -271
  97. package/src/cacheNames.ts +1 -1
  98. package/src/copyResponse.ts +2 -2
  99. package/src/index.internal.ts +16 -16
  100. package/src/index.ts +68 -93
  101. package/src/lib/backgroundSync/BackgroundSyncPlugin.ts +2 -2
  102. package/src/lib/backgroundSync/BackgroundSyncQueue.ts +4 -4
  103. package/src/lib/backgroundSync/BackgroundSyncQueueStore.ts +1 -1
  104. package/src/lib/backgroundSync/StorableRequest.ts +1 -1
  105. package/src/lib/backgroundSync/index.ts +5 -0
  106. package/src/lib/broadcastUpdate/BroadcastCacheUpdate.ts +4 -4
  107. package/src/lib/broadcastUpdate/BroadcastUpdatePlugin.ts +2 -2
  108. package/src/lib/broadcastUpdate/index.ts +5 -0
  109. package/src/lib/broadcastUpdate/responsesAreSame.ts +2 -2
  110. package/src/lib/cacheableResponse/CacheableResponse.ts +4 -4
  111. package/src/lib/cacheableResponse/CacheableResponsePlugin.ts +3 -3
  112. package/src/lib/cacheableResponse/index.ts +3 -0
  113. package/src/{legacy/utils → lib/controllers/PrecacheController}/PrecacheCacheKeyPlugin.ts +5 -6
  114. package/src/lib/controllers/PrecacheController/PrecacheController.ts +328 -0
  115. package/src/{utils → lib/controllers/PrecacheController}/PrecacheInstallReportPlugin.ts +5 -5
  116. package/src/{PrecacheRoute.ts → lib/controllers/PrecacheController/PrecacheRoute.ts} +11 -12
  117. package/src/lib/{strategies → controllers/PrecacheController}/PrecacheStrategy.ts +13 -13
  118. package/src/lib/controllers/PrecacheController/parsePrecacheOptions.ts +46 -0
  119. package/src/lib/controllers/RuntimeCacheController.ts +119 -0
  120. package/src/lib/controllers/index.ts +3 -0
  121. package/src/lib/expiration/CacheExpiration.ts +3 -3
  122. package/src/lib/expiration/ExpirationPlugin.ts +8 -8
  123. package/src/lib/expiration/index.ts +3 -0
  124. package/src/lib/googleAnalytics/index.ts +2 -0
  125. package/src/lib/googleAnalytics/initializeGoogleAnalytics.ts +5 -5
  126. package/src/lib/precaching/PrecacheFallbackPlugin.ts +23 -12
  127. package/src/lib/precaching/index.ts +2 -0
  128. package/src/lib/rangeRequests/RangeRequestsPlugin.ts +3 -3
  129. package/src/lib/rangeRequests/createPartialResponse.ts +3 -3
  130. package/src/lib/rangeRequests/index.ts +2 -0
  131. package/src/lib/rangeRequests/utils/calculateEffectiveBoundaries.ts +2 -2
  132. package/src/lib/rangeRequests/utils/parseRangeHeader.ts +2 -2
  133. package/src/lib/strategies/CacheFirst.ts +3 -3
  134. package/src/lib/strategies/CacheOnly.ts +3 -3
  135. package/src/lib/strategies/NetworkFirst.ts +3 -3
  136. package/src/lib/strategies/NetworkOnly.ts +4 -4
  137. package/src/lib/strategies/StaleWhileRevalidate.ts +3 -3
  138. package/src/lib/strategies/Strategy.ts +7 -7
  139. package/src/lib/strategies/StrategyHandler.ts +18 -18
  140. package/src/lib/strategies/index.ts +10 -0
  141. package/src/lib/strategies/plugins/cacheOkAndOpaquePlugin.ts +2 -2
  142. package/src/lib/strategies/utils/messages.ts +2 -2
  143. package/src/models/messages/messages.ts +3 -3
  144. package/src/navigationPreload.ts +1 -1
  145. package/src/registerQuotaErrorCallback.ts +2 -2
  146. package/src/setCacheNameDetails.ts +4 -4
  147. package/src/types.ts +56 -68
  148. package/src/utils/SerwistError.ts +2 -2
  149. package/src/utils/cacheNames.ts +1 -1
  150. package/src/utils/executeQuotaErrorCallbacks.ts +1 -1
  151. package/src/utils/pluginUtils.ts +2 -2
  152. package/dist/PrecacheRoute.d.ts.map +0 -1
  153. package/dist/chunks/printInstallDetails.js +0 -1601
  154. package/dist/chunks/resultingClientExists.js +0 -32
  155. package/dist/index.legacy.d.ts +0 -28
  156. package/dist/index.legacy.d.ts.map +0 -1
  157. package/dist/index.legacy.js +0 -790
  158. package/dist/legacy/PrecacheController.d.ts.map +0 -1
  159. package/dist/legacy/PrecacheFallbackPlugin.d.ts +0 -61
  160. package/dist/legacy/PrecacheFallbackPlugin.d.ts.map +0 -1
  161. package/dist/legacy/PrecacheRoute.d.ts +0 -19
  162. package/dist/legacy/PrecacheRoute.d.ts.map +0 -1
  163. package/dist/legacy/Router.d.ts +0 -151
  164. package/dist/legacy/Router.d.ts.map +0 -1
  165. package/dist/legacy/addPlugins.d.ts +0 -9
  166. package/dist/legacy/addPlugins.d.ts.map +0 -1
  167. package/dist/legacy/addRoute.d.ts +0 -14
  168. package/dist/legacy/addRoute.d.ts.map +0 -1
  169. package/dist/legacy/constants.d.ts +0 -10
  170. package/dist/legacy/constants.d.ts.map +0 -1
  171. package/dist/legacy/createHandlerBoundToURL.d.ts +0 -17
  172. package/dist/legacy/createHandlerBoundToURL.d.ts.map +0 -1
  173. package/dist/legacy/fallbacks.d.ts +0 -59
  174. package/dist/legacy/fallbacks.d.ts.map +0 -1
  175. package/dist/legacy/getCacheKeyForURL.d.ts +0 -20
  176. package/dist/legacy/getCacheKeyForURL.d.ts.map +0 -1
  177. package/dist/legacy/handlePrecaching.d.ts +0 -54
  178. package/dist/legacy/handlePrecaching.d.ts.map +0 -1
  179. package/dist/legacy/initializeGoogleAnalytics.d.ts +0 -38
  180. package/dist/legacy/initializeGoogleAnalytics.d.ts.map +0 -1
  181. package/dist/legacy/installSerwist.d.ts +0 -81
  182. package/dist/legacy/installSerwist.d.ts.map +0 -1
  183. package/dist/legacy/matchPrecache.d.ts +0 -15
  184. package/dist/legacy/matchPrecache.d.ts.map +0 -1
  185. package/dist/legacy/precache.d.ts +0 -20
  186. package/dist/legacy/precache.d.ts.map +0 -1
  187. package/dist/legacy/precacheAndRoute.d.ts +0 -14
  188. package/dist/legacy/precacheAndRoute.d.ts.map +0 -1
  189. package/dist/legacy/registerRoute.d.ts +0 -16
  190. package/dist/legacy/registerRoute.d.ts.map +0 -1
  191. package/dist/legacy/registerRuntimeCaching.d.ts +0 -11
  192. package/dist/legacy/registerRuntimeCaching.d.ts.map +0 -1
  193. package/dist/legacy/setCatchHandler.d.ts +0 -10
  194. package/dist/legacy/setCatchHandler.d.ts.map +0 -1
  195. package/dist/legacy/setDefaultHandler.d.ts +0 -13
  196. package/dist/legacy/setDefaultHandler.d.ts.map +0 -1
  197. package/dist/legacy/singletonPrecacheController.d.ts +0 -34
  198. package/dist/legacy/singletonPrecacheController.d.ts.map +0 -1
  199. package/dist/legacy/singletonRouter.d.ts +0 -41
  200. package/dist/legacy/singletonRouter.d.ts.map +0 -1
  201. package/dist/legacy/unregisterRoute.d.ts +0 -9
  202. package/dist/legacy/unregisterRoute.d.ts.map +0 -1
  203. package/dist/legacy/utils/PrecacheCacheKeyPlugin.d.ts.map +0 -1
  204. package/dist/legacy/utils/getCacheKeyForURL.d.ts +0 -14
  205. package/dist/legacy/utils/getCacheKeyForURL.d.ts.map +0 -1
  206. package/dist/lib/strategies/PrecacheStrategy.d.ts.map +0 -1
  207. package/dist/utils/PrecacheCacheKeyPlugin.d.ts +0 -16
  208. package/dist/utils/PrecacheCacheKeyPlugin.d.ts.map +0 -1
  209. package/dist/utils/PrecacheInstallReportPlugin.d.ts +0 -14
  210. package/dist/utils/PrecacheInstallReportPlugin.d.ts.map +0 -1
  211. package/dist/utils/parsePrecacheOptions.d.ts +0 -26
  212. package/dist/utils/parsePrecacheOptions.d.ts.map +0 -1
  213. package/src/index.legacy.ts +0 -62
  214. package/src/legacy/PrecacheController.ts +0 -337
  215. package/src/legacy/PrecacheFallbackPlugin.ts +0 -92
  216. package/src/legacy/PrecacheRoute.ts +0 -48
  217. package/src/legacy/Router.ts +0 -484
  218. package/src/legacy/addPlugins.ts +0 -21
  219. package/src/legacy/addRoute.ts +0 -27
  220. package/src/legacy/constants.ts +0 -22
  221. package/src/legacy/createHandlerBoundToURL.ts +0 -30
  222. package/src/legacy/fallbacks.ts +0 -94
  223. package/src/legacy/getCacheKeyForURL.ts +0 -32
  224. package/src/legacy/handlePrecaching.ts +0 -86
  225. package/src/legacy/initializeGoogleAnalytics.ts +0 -218
  226. package/src/legacy/installSerwist.ts +0 -170
  227. package/src/legacy/matchPrecache.ts +0 -27
  228. package/src/legacy/precache.ts +0 -33
  229. package/src/legacy/precacheAndRoute.ts +0 -27
  230. package/src/legacy/registerRoute.ts +0 -28
  231. package/src/legacy/registerRuntimeCaching.ts +0 -17
  232. package/src/legacy/setCatchHandler.ts +0 -21
  233. package/src/legacy/setDefaultHandler.ts +0 -24
  234. package/src/legacy/singletonPrecacheController.ts +0 -53
  235. package/src/legacy/singletonRouter.ts +0 -70
  236. package/src/legacy/unregisterRoute.ts +0 -13
  237. package/src/legacy/utils/getCacheKeyForURL.ts +0 -36
  238. package/src/utils/PrecacheCacheKeyPlugin.ts +0 -33
  239. package/src/utils/parsePrecacheOptions.ts +0 -47
@@ -1,484 +0,0 @@
1
- /*
2
- Copyright 2018 Google LLC
3
-
4
- Use of this source code is governed by an MIT-style
5
- license that can be found in the LICENSE file or at
6
- https://opensource.org/licenses/MIT.
7
- */
8
-
9
- import type { Route } from "../Route.js";
10
- import type { HTTPMethod } from "../constants.js";
11
- import { defaultMethod } from "../constants.js";
12
- import type { RouteHandler, RouteHandlerCallbackOptions, RouteHandlerObject, RouteMatchCallback, RouteMatchCallbackOptions } from "../types.js";
13
- import { SerwistError } from "../utils/SerwistError.js";
14
- import { assert } from "../utils/assert.js";
15
- import { getFriendlyURL } from "../utils/getFriendlyURL.js";
16
- import { logger } from "../utils/logger.js";
17
- import { normalizeHandler } from "../utils/normalizeHandler.js";
18
- import { parseRoute } from "../utils/parseRoute.js";
19
-
20
- declare const self: ServiceWorkerGlobalScope;
21
-
22
- type RequestArgs = string | [string, RequestInit?];
23
-
24
- interface CacheURLsMessageData {
25
- type: string;
26
- payload: {
27
- urlsToCache: RequestArgs[];
28
- };
29
- }
30
-
31
- /**
32
- * A class that can be used to process a `fetch` event using one or more route(s), responding with a response
33
- * if a matching route exists.
34
- *
35
- * If no route matches given a request, the router will use the default handler if one is defined.
36
- *
37
- * Should the matching route throw an error, the router will use the catch handler if one is defined to
38
- * gracefully deal with issues and respond with a response.
39
- *
40
- * If a request matches multiple routes, the earliest registered route will be used to respond to the it.
41
- * @deprecated
42
- */
43
- export class Router {
44
- private readonly _routes: Map<HTTPMethod, Route[]>;
45
- private readonly _defaultHandlerMap: Map<HTTPMethod, RouteHandlerObject>;
46
- private _fetchListenerHandler: ((ev: FetchEvent) => void) | null = null;
47
- private _cacheListenerHandler: ((ev: ExtendableMessageEvent) => void) | null = null;
48
- private _catchHandler?: RouteHandlerObject;
49
-
50
- /**
51
- * Initializes a new Router.
52
- */
53
- constructor() {
54
- this._routes = new Map();
55
- this._defaultHandlerMap = new Map();
56
- }
57
-
58
- /**
59
- * @returns routes A `Map` of HTTP method name (`'GET'`, etc.) to an array of all
60
- * the corresponding {@linkcode Route} instances that are registered.
61
- */
62
- get routes(): Map<HTTPMethod, Route[]> {
63
- return this._routes;
64
- }
65
-
66
- /**
67
- * Adds a `fetch` event listener to respond to events when a route matches
68
- * the event's request. Effectively no-op if `addFetchListener` has been
69
- * called, but `removeFetchListener` has not.
70
- */
71
- addFetchListener(): void {
72
- if (!this._fetchListenerHandler) {
73
- this._fetchListenerHandler = (event) => {
74
- const { request } = event;
75
- const responsePromise = this.handleRequest({ request, event });
76
- if (responsePromise) {
77
- event.respondWith(responsePromise);
78
- }
79
- };
80
- self.addEventListener("fetch", this._fetchListenerHandler);
81
- }
82
- }
83
-
84
- /**
85
- * Removes `fetch` event listener added by `addFetchListener`.
86
- * Effectively no-op if either `addFetchListener` has not been called or,
87
- * if it has, so has `removeFetchListener`.
88
- */
89
- removeFetchListener(): void {
90
- if (this._fetchListenerHandler) {
91
- self.removeEventListener("fetch", this._fetchListenerHandler);
92
- this._fetchListenerHandler = null;
93
- }
94
- }
95
-
96
- /**
97
- * Adds a `message` event listener for URLs to cache from the window.
98
- * This is useful to cache resources loaded on the page prior to when the
99
- * service worker started controlling it. Effectively no-op if `addCacheListener`
100
- * has been called, but `removeCacheListener` hasn't.
101
- *
102
- * The format of the message data sent from the window should be as follows.
103
- * Where the `urlsToCache` array may consist of URL strings or an array of
104
- * URL string + `requestInit` object (the same as you'd pass to `fetch()`).
105
- *
106
- * ```
107
- * {
108
- * type: 'CACHE_URLS',
109
- * payload: {
110
- * urlsToCache: [
111
- * './script1.js',
112
- * './script2.js',
113
- * ['./script3.js', {mode: 'no-cors'}],
114
- * ],
115
- * },
116
- * }
117
- * ```
118
- */
119
- addCacheListener(): void {
120
- if (!this._cacheListenerHandler) {
121
- this._cacheListenerHandler = (event) => {
122
- if (event.data && event.data.type === "CACHE_URLS") {
123
- const { payload }: CacheURLsMessageData = event.data;
124
-
125
- if (process.env.NODE_ENV !== "production") {
126
- logger.debug("Caching URLs from the window", payload.urlsToCache);
127
- }
128
-
129
- const requestPromises = Promise.all(
130
- payload.urlsToCache.map((entry: string | [string, RequestInit?]) => {
131
- if (typeof entry === "string") {
132
- entry = [entry];
133
- }
134
-
135
- const request = new Request(...entry);
136
- return this.handleRequest({ request, event });
137
- }),
138
- );
139
-
140
- event.waitUntil(requestPromises);
141
-
142
- // If a MessageChannel was used, reply to the message on success.
143
- if (event.ports?.[0]) {
144
- void requestPromises.then(() => event.ports[0].postMessage(true));
145
- }
146
- }
147
- };
148
- self.addEventListener("message", this._cacheListenerHandler);
149
- }
150
- }
151
-
152
- /**
153
- * Removes the `message` event listener added by `addCacheListener`.
154
- * Effectively no-op if either `addCacheListener` has not been called or,
155
- * if it has, so has `removeCacheListener`.
156
- */
157
- removeCacheListener(): void {
158
- if (this._cacheListenerHandler) {
159
- self.removeEventListener("message", this._cacheListenerHandler);
160
- }
161
- }
162
-
163
- /**
164
- * Apply the routing rules to a `fetch` event to get a response from an
165
- * appropriate route.
166
- *
167
- * @param options
168
- * @returns A promise is returned if a registered route can handle the request.
169
- * If there is no matching route and there's no `defaultHandler`, `undefined`
170
- * is returned.
171
- */
172
- handleRequest({
173
- request,
174
- event,
175
- }: {
176
- /**
177
- * The request to handle.
178
- */
179
- request: Request;
180
- /**
181
- * The event that triggered the request.
182
- */
183
- event: ExtendableEvent;
184
- }): Promise<Response> | undefined {
185
- if (process.env.NODE_ENV !== "production") {
186
- assert!.isInstance(request, Request, {
187
- moduleName: "serwist/legacy",
188
- className: "Router",
189
- funcName: "handleRequest",
190
- paramName: "options.request",
191
- });
192
- }
193
-
194
- const url = new URL(request.url, location.href);
195
- if (!url.protocol.startsWith("http")) {
196
- if (process.env.NODE_ENV !== "production") {
197
- logger.debug("Router only supports URLs that start with 'http'.");
198
- }
199
- return;
200
- }
201
-
202
- const sameOrigin = url.origin === location.origin;
203
- const { params, route } = this.findMatchingRoute({
204
- event,
205
- request,
206
- sameOrigin,
207
- url,
208
- });
209
- let handler = route?.handler;
210
-
211
- const debugMessages = [];
212
- if (process.env.NODE_ENV !== "production") {
213
- if (handler) {
214
- debugMessages.push(["Found a route to handle this request:", route]);
215
-
216
- if (params) {
217
- debugMessages.push([`Passing the following params to the route's handler:`, params]);
218
- }
219
- }
220
- }
221
-
222
- // If we don't have a handler because there was no matching route, then
223
- // fall back to defaultHandler if that's defined.
224
- const method = request.method as HTTPMethod;
225
- if (!handler && this._defaultHandlerMap.has(method)) {
226
- if (process.env.NODE_ENV !== "production") {
227
- debugMessages.push(`Failed to find a matching route. Falling back to the default handler for ${method}.`);
228
- }
229
- handler = this._defaultHandlerMap.get(method);
230
- }
231
-
232
- if (!handler) {
233
- if (process.env.NODE_ENV !== "production") {
234
- // No handler so Serwist will do nothing. If logs is set of debug
235
- // i.e. verbose, we should print out this information.
236
- logger.debug(`No route found for: ${getFriendlyURL(url)}`);
237
- }
238
- return;
239
- }
240
-
241
- if (process.env.NODE_ENV !== "production") {
242
- // We have a handler, meaning Serwist is going to handle the route.
243
- // print the routing details to the console.
244
- logger.groupCollapsed(`Router is responding to: ${getFriendlyURL(url)}`);
245
-
246
- for (const msg of debugMessages) {
247
- if (Array.isArray(msg)) {
248
- logger.log(...msg);
249
- } else {
250
- logger.log(msg);
251
- }
252
- }
253
-
254
- logger.groupEnd();
255
- }
256
-
257
- // Wrap in try and catch in case the handle method throws a synchronous
258
- // error. It should still callback to the catch handler.
259
- let responsePromise: Promise<Response>;
260
- try {
261
- responsePromise = handler.handle({ url, request, event, params });
262
- } catch (err) {
263
- responsePromise = Promise.reject(err);
264
- }
265
-
266
- // Get route's catch handler, if it exists
267
- const catchHandler = route?.catchHandler;
268
-
269
- if (responsePromise instanceof Promise && (this._catchHandler || catchHandler)) {
270
- responsePromise = responsePromise.catch(async (err) => {
271
- // If there's a route catch handler, process that first
272
- if (catchHandler) {
273
- if (process.env.NODE_ENV !== "production") {
274
- // Still include URL here as it will be async from the console group
275
- // and may not make sense without the URL
276
- logger.groupCollapsed(`Error thrown when responding to: ${getFriendlyURL(url)}. Falling back to route's Catch Handler.`);
277
- logger.error("Error thrown by:", route);
278
- logger.error(err);
279
- logger.groupEnd();
280
- }
281
-
282
- try {
283
- return await catchHandler.handle({ url, request, event, params });
284
- } catch (catchErr) {
285
- if (catchErr instanceof Error) {
286
- err = catchErr;
287
- }
288
- }
289
- }
290
-
291
- if (this._catchHandler) {
292
- if (process.env.NODE_ENV !== "production") {
293
- // Still include URL here as it will be async from the console group
294
- // and may not make sense without the URL
295
- logger.groupCollapsed(`Error thrown when responding to: ${getFriendlyURL(url)}. Falling back to global Catch Handler.`);
296
- logger.error("Error thrown by:", route);
297
- logger.error(err);
298
- logger.groupEnd();
299
- }
300
- return this._catchHandler.handle({ url, request, event });
301
- }
302
-
303
- throw err;
304
- });
305
- }
306
-
307
- return responsePromise;
308
- }
309
-
310
- /**
311
- * Checks a request and URL (and optionally an event) against the list of
312
- * registered routes, and if there's a match, returns the corresponding
313
- * route along with any params generated by the match.
314
- *
315
- * @param options
316
- * @returns An object with `route` and `params` properties. They are populated
317
- * if a matching route was found or `undefined` otherwise.
318
- */
319
- findMatchingRoute({ url, sameOrigin, request, event }: RouteMatchCallbackOptions): {
320
- route?: Route;
321
- params?: RouteHandlerCallbackOptions["params"];
322
- } {
323
- const routes = this._routes.get(request.method as HTTPMethod) || [];
324
- for (const route of routes) {
325
- let params: Promise<any> | undefined;
326
- // route.match returns type any, not possible to change right now.
327
- const matchResult = route.match({ url, sameOrigin, request, event });
328
- if (matchResult) {
329
- if (process.env.NODE_ENV !== "production") {
330
- // Warn developers that using an async matchCallback is almost always
331
- // not the right thing to do.
332
- if (matchResult instanceof Promise) {
333
- logger.warn(
334
- `While routing ${getFriendlyURL(
335
- url,
336
- )}, an async matchCallback function was used. Please convert the following route to use a synchronous matchCallback function:`,
337
- route,
338
- );
339
- }
340
- }
341
-
342
- // See https://github.com/GoogleChrome/workbox/issues/2079
343
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
344
- params = matchResult;
345
- if (Array.isArray(params) && params.length === 0) {
346
- // Instead of passing an empty array in as params, use undefined.
347
- params = undefined;
348
- } else if (
349
- matchResult.constructor === Object && // eslint-disable-line
350
- Object.keys(matchResult).length === 0
351
- ) {
352
- // Instead of passing an empty object in as params, use undefined.
353
- params = undefined;
354
- } else if (typeof matchResult === "boolean") {
355
- // For the boolean value true (rather than just something truth-y),
356
- // don't set params.
357
- // See https://github.com/GoogleChrome/workbox/pull/2134#issuecomment-513924353
358
- params = undefined;
359
- }
360
-
361
- // Return early if have a match.
362
- return { route, params };
363
- }
364
- }
365
- // If no match was found above, return and empty object.
366
- return {};
367
- }
368
-
369
- /**
370
- * Define a default handler that's called when no routes explicitly
371
- * match the incoming request.
372
- *
373
- * Each HTTP method (`'GET'`, `'POST'`, etc.) gets its own default handler.
374
- *
375
- * Without a default handler, unmatched requests will go against the
376
- * network as if there were no service worker present.
377
- *
378
- * @param handler A callback function that returns a promise resulting in a response.
379
- * @param method The HTTP method to associate with this default handler. Each method
380
- * has its own default. Defaults to `'GET'`.
381
- */
382
- setDefaultHandler(handler: RouteHandler, method: HTTPMethod = defaultMethod): void {
383
- this._defaultHandlerMap.set(method, normalizeHandler(handler));
384
- }
385
-
386
- /**
387
- * If a `Route` throws an error while handling a request, this `handler`
388
- * will be called and given a chance to provide a response.
389
- *
390
- * @param handler A callback function that returns a Promise resulting
391
- * in a Response.
392
- */
393
- setCatchHandler(handler: RouteHandler): void {
394
- this._catchHandler = normalizeHandler(handler);
395
- }
396
-
397
- /**
398
- * Registers a `RegExp`, string, or function with a caching
399
- * strategy to the router.
400
- *
401
- * @param capture If the capture param is a {@linkcode Route} object, all other arguments will be ignored.
402
- * @param handler A callback function that returns a promise resulting in a response.
403
- * This parameter is required if `capture` is not a {@linkcode Route} object.
404
- * @param method The HTTP method to match the route against. Defaults to `'GET'`.
405
- * @returns The generated {@linkcode Route} object.
406
- */
407
- registerCapture(capture: RegExp | string | RouteMatchCallback | Route, handler?: RouteHandler, method?: HTTPMethod): Route {
408
- const route = parseRoute(capture, handler, method);
409
- this.registerRoute(route);
410
- return route;
411
- }
412
-
413
- /**
414
- * Registers a route with the router.
415
- *
416
- * @param route The route to register.
417
- */
418
- registerRoute(route: Route): void {
419
- if (process.env.NODE_ENV !== "production") {
420
- assert!.isType(route, "object", {
421
- moduleName: "serwist/legacy",
422
- className: "Router",
423
- funcName: "registerRoute",
424
- paramName: "route",
425
- });
426
-
427
- assert!.hasMethod(route, "match", {
428
- moduleName: "serwist/legacy",
429
- className: "Router",
430
- funcName: "registerRoute",
431
- paramName: "route",
432
- });
433
-
434
- assert!.isType(route.handler, "object", {
435
- moduleName: "serwist/legacy",
436
- className: "Router",
437
- funcName: "registerRoute",
438
- paramName: "route",
439
- });
440
-
441
- assert!.hasMethod(route.handler, "handle", {
442
- moduleName: "serwist/legacy",
443
- className: "Router",
444
- funcName: "registerRoute",
445
- paramName: "route.handler",
446
- });
447
-
448
- assert!.isType(route.method, "string", {
449
- moduleName: "serwist/legacy",
450
- className: "Router",
451
- funcName: "registerRoute",
452
- paramName: "route.method",
453
- });
454
- }
455
-
456
- if (!this._routes.has(route.method)) {
457
- this._routes.set(route.method, []);
458
- }
459
-
460
- // Give precedence to all of the earlier routes by adding this additional
461
- // route to the end of the array.
462
- this._routes.get(route.method)!.push(route);
463
- }
464
-
465
- /**
466
- * Unregisters a route from the router.
467
- *
468
- * @param route The route to unregister.
469
- */
470
- unregisterRoute(route: Route): void {
471
- if (!this._routes.has(route.method)) {
472
- throw new SerwistError("unregister-route-but-not-found-with-method", {
473
- method: route.method,
474
- });
475
- }
476
-
477
- const routeIndex = this._routes.get(route.method)!.indexOf(route);
478
- if (routeIndex > -1) {
479
- this._routes.get(route.method)!.splice(routeIndex, 1);
480
- } else {
481
- throw new SerwistError("unregister-route-route-not-registered");
482
- }
483
- }
484
- }
@@ -1,21 +0,0 @@
1
- /*
2
- Copyright 2019 Google LLC
3
-
4
- Use of this source code is governed by an MIT-style
5
- license that can be found in the LICENSE file or at
6
- https://opensource.org/licenses/MIT.
7
- */
8
-
9
- import type { SerwistPlugin } from "../types.js";
10
- import { getSingletonPrecacheController } from "./singletonPrecacheController.js";
11
-
12
- /**
13
- * Adds plugins to the precaching strategy.
14
- *
15
- * @param plugins
16
- * @deprecated
17
- */
18
- export const addPlugins = (plugins: SerwistPlugin[]): void => {
19
- const precacheController = getSingletonPrecacheController();
20
- precacheController.strategy.plugins.push(...plugins);
21
- };
@@ -1,27 +0,0 @@
1
- /*
2
- Copyright 2019 Google LLC
3
- Use of this source code is governed by an MIT-style
4
- license that can be found in the LICENSE file or at
5
- https://opensource.org/licenses/MIT.
6
- */
7
-
8
- import type { PrecacheRouteOptions } from "../types.js";
9
- import { PrecacheRoute } from "./PrecacheRoute.js";
10
- import { registerRoute } from "./registerRoute.js";
11
- import { getSingletonPrecacheController } from "./singletonPrecacheController.js";
12
-
13
- /**
14
- * Add a `fetch` listener that will
15
- * respond to [network requests](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#Custom_responses_to_requests)
16
- * with precached assets to the service worker.
17
- *
18
- * As for requests for assets that aren't precached, the `fetch` event will not be
19
- * responded to, allowing the event to fall through to other `fetch` event listeners.
20
- *
21
- * @param options See {@linkcode PrecacheRouteOptions}.
22
- * @deprecated
23
- */
24
- export const addRoute = (options?: PrecacheRouteOptions): void => {
25
- const precacheRoute = new PrecacheRoute(getSingletonPrecacheController(), options);
26
- registerRoute(precacheRoute);
27
- };
@@ -1,22 +0,0 @@
1
- /*
2
- Copyright 2018 Google LLC
3
-
4
- Use of this source code is governed by an MIT-style
5
- license that can be found in the LICENSE file or at
6
- https://opensource.org/licenses/MIT.
7
- */
8
-
9
- export const QUEUE_NAME = "serwist-google-analytics";
10
- export const MAX_RETENTION_TIME = 60 * 48; // Two days in minutes
11
- export const GOOGLE_ANALYTICS_HOST = "www.google-analytics.com";
12
- export const GTM_HOST = "www.googletagmanager.com";
13
- export const ANALYTICS_JS_PATH = "/analytics.js";
14
- export const GTAG_JS_PATH = "/gtag/js";
15
- export const GTM_JS_PATH = "/gtm.js";
16
- export const COLLECT_DEFAULT_PATH = "/collect";
17
-
18
- // This RegExp matches all known Measurement Protocol single-hit collect
19
- // endpoints. Most of the time the default path (/collect) is used, but
20
- // occasionally an experimental endpoint is used when testing new features,
21
- // (e.g. /r/collect or /j/collect)
22
- export const COLLECT_PATHS_REGEX = /^\/(\w+\/)?collect/;
@@ -1,30 +0,0 @@
1
- /*
2
- Copyright 2019 Google LLC
3
-
4
- Use of this source code is governed by an MIT-style
5
- license that can be found in the LICENSE file or at
6
- https://opensource.org/licenses/MIT.
7
- */
8
-
9
- import type { RouteHandlerCallback } from "../types.js";
10
- import type { PrecacheController } from "./PrecacheController.js";
11
- import { getSingletonPrecacheController } from "./singletonPrecacheController.js";
12
-
13
- /**
14
- * Helper function that calls {@linkcode PrecacheController.createHandlerBoundToURL}
15
- * on the default {@linkcode PrecacheController} instance.
16
- *
17
- * If you are creating your own {@linkcode PrecacheController}, then call the
18
- * {@linkcode PrecacheController.createHandlerBoundToURL} function on that instance
19
- * instead of using this function.
20
- *
21
- * @param url The precached URL which will be used to look up the response.
22
- * @param fallbackToNetwork Whether to attempt to get the
23
- * response from the network if there's a precache miss.
24
- * @return
25
- * @deprecated
26
- */
27
- export const createHandlerBoundToURL = (url: string): RouteHandlerCallback => {
28
- const precacheController = getSingletonPrecacheController();
29
- return precacheController.createHandlerBoundToURL(url);
30
- };
@@ -1,94 +0,0 @@
1
- import { Strategy } from "../lib/strategies/Strategy.js";
2
- import type { PrecacheRouteOptions, RuntimeCaching } from "../types.js";
3
- import type { PrecacheController } from "./PrecacheController.js";
4
- import { PrecacheFallbackPlugin } from "./PrecacheFallbackPlugin.js";
5
- import type { PrecacheFallbackEntry } from "./PrecacheFallbackPlugin.js";
6
- import { PrecacheRoute } from "./PrecacheRoute.js";
7
- import type { Router } from "./Router.js";
8
- import { getSingletonPrecacheController } from "./singletonPrecacheController.js";
9
- import { getSingletonRouter } from "./singletonRouter.js";
10
-
11
- export interface FallbackEntry extends PrecacheFallbackEntry {
12
- /**
13
- * The revision used for precaching.
14
- */
15
- revision: string;
16
- }
17
-
18
- export interface FallbacksOptions {
19
- /**
20
- * A list of fallback entries.
21
- */
22
- entries: FallbackEntry[];
23
- /**
24
- * Precache options that will be used for your
25
- * fallback entries.
26
- */
27
- precacheOptions?: PrecacheRouteOptions;
28
- }
29
-
30
- export interface FallbacksOptions {
31
- /**
32
- * An optional {@linkcode PrecacheController} instance. If not provided, the singleton
33
- * {@linkcode PrecacheController} will be used.
34
- */
35
- precacheController?: PrecacheController;
36
- /**
37
- * An optional {@linkcode Router} instance. If not provided, the singleton {@linkcode Router}
38
- * will be used.
39
- */
40
- router?: Router;
41
- /**
42
- * Your previous list of caching strategies.
43
- */
44
- runtimeCaching: RuntimeCaching[];
45
- /**
46
- * A list of fallback entries.
47
- */
48
- entries: FallbackEntry[];
49
- /**
50
- * Precache options that will be used for your
51
- * fallback entries.
52
- */
53
- precacheOptions?: PrecacheRouteOptions;
54
- }
55
-
56
- /**
57
- * Precaches routes so that they can be used as a fallback when
58
- * a Strategy fails to generate a response.
59
- *
60
- * Note: This function mutates `runtimeCaching`. It also precaches the URLs
61
- * defined in `entries`, so you must NOT precache any of them beforehand.
62
- *
63
- * @param options
64
- * @returns The modified `runtimeCaching` array.
65
- * @deprecated
66
- */
67
- export const fallbacks = ({
68
- precacheController = getSingletonPrecacheController(),
69
- router = getSingletonRouter(),
70
- runtimeCaching,
71
- entries,
72
- precacheOptions,
73
- }: FallbacksOptions): RuntimeCaching[] => {
74
- precacheController.precache(entries);
75
- router.registerRoute(new PrecacheRoute(precacheController, precacheOptions));
76
-
77
- const fallbackPlugin = new PrecacheFallbackPlugin({
78
- fallbackUrls: entries,
79
- });
80
-
81
- runtimeCaching.forEach((cacheEntry) => {
82
- if (
83
- cacheEntry.handler instanceof Strategy &&
84
- // PrecacheFallbackPlugin also has `handlerDidError`, so we don't need to check for its instances.
85
- !cacheEntry.handler.plugins.some((plugin) => "handlerDidError" in plugin)
86
- ) {
87
- cacheEntry.handler.plugins.push(fallbackPlugin);
88
- }
89
-
90
- return cacheEntry;
91
- });
92
-
93
- return runtimeCaching;
94
- };