serwist 9.0.12 → 10.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 (151) hide show
  1. package/dist/Serwist.d.ts +74 -52
  2. package/dist/Serwist.d.ts.map +1 -1
  3. package/dist/chunks/resultingClientExists.js +426 -2
  4. package/dist/{legacy/utils → controllers/PrecacheController}/PrecacheCacheKeyPlugin.d.ts +4 -4
  5. package/dist/controllers/PrecacheController/PrecacheCacheKeyPlugin.d.ts.map +1 -0
  6. package/dist/{legacy → controllers/PrecacheController}/PrecacheController.d.ts +73 -64
  7. package/dist/controllers/PrecacheController/PrecacheController.d.ts.map +1 -0
  8. package/dist/controllers/PrecacheController/PrecacheInstallReportPlugin.d.ts +14 -0
  9. package/dist/controllers/PrecacheController/PrecacheInstallReportPlugin.d.ts.map +1 -0
  10. package/dist/{PrecacheRoute.d.ts → controllers/PrecacheController/PrecacheRoute.d.ts} +4 -5
  11. package/dist/controllers/PrecacheController/PrecacheRoute.d.ts.map +1 -0
  12. package/dist/{lib/strategies → controllers/PrecacheController}/PrecacheStrategy.d.ts +6 -6
  13. package/dist/controllers/PrecacheController/PrecacheStrategy.d.ts.map +1 -0
  14. package/dist/controllers/PrecacheController/parsePrecacheOptions.d.ts +25 -0
  15. package/dist/controllers/PrecacheController/parsePrecacheOptions.d.ts.map +1 -0
  16. package/dist/controllers/RuntimeCacheController.d.ts +65 -0
  17. package/dist/controllers/RuntimeCacheController.d.ts.map +1 -0
  18. package/dist/index.d.ts +4 -3
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.internal.js +25 -3
  21. package/dist/index.js +1868 -211
  22. package/dist/lib/backgroundSync/BackgroundSyncPlugin.d.ts +2 -2
  23. package/dist/lib/backgroundSync/BackgroundSyncPlugin.d.ts.map +1 -1
  24. package/dist/lib/broadcastUpdate/BroadcastUpdatePlugin.d.ts +2 -2
  25. package/dist/lib/broadcastUpdate/BroadcastUpdatePlugin.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/expiration/ExpirationPlugin.d.ts +2 -2
  29. package/dist/lib/expiration/ExpirationPlugin.d.ts.map +1 -1
  30. package/dist/lib/precaching/PrecacheFallbackPlugin.d.ts +7 -7
  31. package/dist/lib/precaching/PrecacheFallbackPlugin.d.ts.map +1 -1
  32. package/dist/lib/rangeRequests/RangeRequestsPlugin.d.ts +3 -3
  33. package/dist/lib/rangeRequests/RangeRequestsPlugin.d.ts.map +1 -1
  34. package/dist/lib/strategies/Strategy.d.ts +3 -3
  35. package/dist/lib/strategies/Strategy.d.ts.map +1 -1
  36. package/dist/lib/strategies/StrategyHandler.d.ts +4 -4
  37. package/dist/lib/strategies/StrategyHandler.d.ts.map +1 -1
  38. package/dist/lib/strategies/plugins/cacheOkAndOpaquePlugin.d.ts +2 -2
  39. package/dist/lib/strategies/plugins/cacheOkAndOpaquePlugin.d.ts.map +1 -1
  40. package/dist/types.d.ts +16 -64
  41. package/dist/types.d.ts.map +1 -1
  42. package/dist/utils/pluginUtils.d.ts +2 -2
  43. package/dist/utils/pluginUtils.d.ts.map +1 -1
  44. package/package.json +5 -12
  45. package/src/Serwist.ts +157 -262
  46. package/src/{legacy/utils → controllers/PrecacheController}/PrecacheCacheKeyPlugin.ts +5 -6
  47. package/src/{legacy → controllers/PrecacheController}/PrecacheController.ts +143 -155
  48. package/src/{utils → controllers/PrecacheController}/PrecacheInstallReportPlugin.ts +5 -5
  49. package/src/{PrecacheRoute.ts → controllers/PrecacheController/PrecacheRoute.ts} +11 -12
  50. package/src/{lib/strategies → controllers/PrecacheController}/PrecacheStrategy.ts +7 -7
  51. package/src/controllers/PrecacheController/parsePrecacheOptions.ts +46 -0
  52. package/src/controllers/RuntimeCacheController.ts +119 -0
  53. package/src/index.ts +5 -2
  54. package/src/lib/backgroundSync/BackgroundSyncPlugin.ts +2 -2
  55. package/src/lib/broadcastUpdate/BroadcastUpdatePlugin.ts +2 -2
  56. package/src/lib/cacheableResponse/CacheableResponsePlugin.ts +3 -3
  57. package/src/lib/expiration/ExpirationPlugin.ts +2 -2
  58. package/src/lib/precaching/PrecacheFallbackPlugin.ts +10 -10
  59. package/src/lib/rangeRequests/RangeRequestsPlugin.ts +3 -3
  60. package/src/lib/strategies/Strategy.ts +3 -3
  61. package/src/lib/strategies/StrategyHandler.ts +9 -9
  62. package/src/lib/strategies/plugins/cacheOkAndOpaquePlugin.ts +2 -2
  63. package/src/types.ts +24 -67
  64. package/src/utils/pluginUtils.ts +2 -2
  65. package/dist/PrecacheRoute.d.ts.map +0 -1
  66. package/dist/chunks/printInstallDetails.js +0 -1601
  67. package/dist/chunks/waitUntil.js +0 -449
  68. package/dist/index.legacy.d.ts +0 -28
  69. package/dist/index.legacy.d.ts.map +0 -1
  70. package/dist/index.legacy.js +0 -790
  71. package/dist/legacy/PrecacheController.d.ts.map +0 -1
  72. package/dist/legacy/PrecacheFallbackPlugin.d.ts +0 -61
  73. package/dist/legacy/PrecacheFallbackPlugin.d.ts.map +0 -1
  74. package/dist/legacy/PrecacheRoute.d.ts +0 -19
  75. package/dist/legacy/PrecacheRoute.d.ts.map +0 -1
  76. package/dist/legacy/Router.d.ts +0 -151
  77. package/dist/legacy/Router.d.ts.map +0 -1
  78. package/dist/legacy/addPlugins.d.ts +0 -9
  79. package/dist/legacy/addPlugins.d.ts.map +0 -1
  80. package/dist/legacy/addRoute.d.ts +0 -14
  81. package/dist/legacy/addRoute.d.ts.map +0 -1
  82. package/dist/legacy/constants.d.ts +0 -10
  83. package/dist/legacy/constants.d.ts.map +0 -1
  84. package/dist/legacy/createHandlerBoundToURL.d.ts +0 -17
  85. package/dist/legacy/createHandlerBoundToURL.d.ts.map +0 -1
  86. package/dist/legacy/fallbacks.d.ts +0 -59
  87. package/dist/legacy/fallbacks.d.ts.map +0 -1
  88. package/dist/legacy/getCacheKeyForURL.d.ts +0 -20
  89. package/dist/legacy/getCacheKeyForURL.d.ts.map +0 -1
  90. package/dist/legacy/handlePrecaching.d.ts +0 -54
  91. package/dist/legacy/handlePrecaching.d.ts.map +0 -1
  92. package/dist/legacy/initializeGoogleAnalytics.d.ts +0 -38
  93. package/dist/legacy/initializeGoogleAnalytics.d.ts.map +0 -1
  94. package/dist/legacy/installSerwist.d.ts +0 -81
  95. package/dist/legacy/installSerwist.d.ts.map +0 -1
  96. package/dist/legacy/matchPrecache.d.ts +0 -15
  97. package/dist/legacy/matchPrecache.d.ts.map +0 -1
  98. package/dist/legacy/precache.d.ts +0 -20
  99. package/dist/legacy/precache.d.ts.map +0 -1
  100. package/dist/legacy/precacheAndRoute.d.ts +0 -14
  101. package/dist/legacy/precacheAndRoute.d.ts.map +0 -1
  102. package/dist/legacy/registerRoute.d.ts +0 -16
  103. package/dist/legacy/registerRoute.d.ts.map +0 -1
  104. package/dist/legacy/registerRuntimeCaching.d.ts +0 -11
  105. package/dist/legacy/registerRuntimeCaching.d.ts.map +0 -1
  106. package/dist/legacy/setCatchHandler.d.ts +0 -10
  107. package/dist/legacy/setCatchHandler.d.ts.map +0 -1
  108. package/dist/legacy/setDefaultHandler.d.ts +0 -13
  109. package/dist/legacy/setDefaultHandler.d.ts.map +0 -1
  110. package/dist/legacy/singletonPrecacheController.d.ts +0 -34
  111. package/dist/legacy/singletonPrecacheController.d.ts.map +0 -1
  112. package/dist/legacy/singletonRouter.d.ts +0 -41
  113. package/dist/legacy/singletonRouter.d.ts.map +0 -1
  114. package/dist/legacy/unregisterRoute.d.ts +0 -9
  115. package/dist/legacy/unregisterRoute.d.ts.map +0 -1
  116. package/dist/legacy/utils/PrecacheCacheKeyPlugin.d.ts.map +0 -1
  117. package/dist/legacy/utils/getCacheKeyForURL.d.ts +0 -14
  118. package/dist/legacy/utils/getCacheKeyForURL.d.ts.map +0 -1
  119. package/dist/lib/strategies/PrecacheStrategy.d.ts.map +0 -1
  120. package/dist/utils/PrecacheCacheKeyPlugin.d.ts +0 -16
  121. package/dist/utils/PrecacheCacheKeyPlugin.d.ts.map +0 -1
  122. package/dist/utils/PrecacheInstallReportPlugin.d.ts +0 -14
  123. package/dist/utils/PrecacheInstallReportPlugin.d.ts.map +0 -1
  124. package/dist/utils/parsePrecacheOptions.d.ts +0 -26
  125. package/dist/utils/parsePrecacheOptions.d.ts.map +0 -1
  126. package/src/index.legacy.ts +0 -62
  127. package/src/legacy/PrecacheFallbackPlugin.ts +0 -92
  128. package/src/legacy/PrecacheRoute.ts +0 -48
  129. package/src/legacy/Router.ts +0 -484
  130. package/src/legacy/addPlugins.ts +0 -21
  131. package/src/legacy/addRoute.ts +0 -27
  132. package/src/legacy/constants.ts +0 -22
  133. package/src/legacy/createHandlerBoundToURL.ts +0 -30
  134. package/src/legacy/fallbacks.ts +0 -94
  135. package/src/legacy/getCacheKeyForURL.ts +0 -32
  136. package/src/legacy/handlePrecaching.ts +0 -86
  137. package/src/legacy/initializeGoogleAnalytics.ts +0 -218
  138. package/src/legacy/installSerwist.ts +0 -170
  139. package/src/legacy/matchPrecache.ts +0 -27
  140. package/src/legacy/precache.ts +0 -33
  141. package/src/legacy/precacheAndRoute.ts +0 -27
  142. package/src/legacy/registerRoute.ts +0 -28
  143. package/src/legacy/registerRuntimeCaching.ts +0 -17
  144. package/src/legacy/setCatchHandler.ts +0 -21
  145. package/src/legacy/setDefaultHandler.ts +0 -24
  146. package/src/legacy/singletonPrecacheController.ts +0 -53
  147. package/src/legacy/singletonRouter.ts +0 -70
  148. package/src/legacy/unregisterRoute.ts +0 -13
  149. package/src/legacy/utils/getCacheKeyForURL.ts +0 -36
  150. package/src/utils/PrecacheCacheKeyPlugin.ts +0 -33
  151. package/src/utils/parsePrecacheOptions.ts +0 -47
package/src/Serwist.ts CHANGED
@@ -1,40 +1,32 @@
1
- import { parallel } from "@serwist/utils";
2
- import { NavigationRoute } from "./NavigationRoute.js";
3
- import { PrecacheRoute } from "./PrecacheRoute.js";
4
1
  import type { Route } from "./Route.js";
5
2
  import { type HTTPMethod, defaultMethod } from "./constants.js";
6
3
  import { disableDevLogs as disableDevLogsImpl } from "./disableDevLogs.js";
7
4
  import { type GoogleAnalyticsInitializeOptions, initializeGoogleAnalytics } from "./lib/googleAnalytics/initializeGoogleAnalytics.js";
8
- import { type PrecacheFallbackEntry, PrecacheFallbackPlugin } from "./lib/precaching/PrecacheFallbackPlugin.js";
9
- import { PrecacheStrategy } from "./lib/strategies/PrecacheStrategy.js";
10
- import { Strategy } from "./lib/strategies/Strategy.js";
5
+ import type { PrecacheFallbackEntry } from "./lib/precaching/PrecacheFallbackPlugin.js";
6
+ import type { Strategy } from "./lib/strategies/Strategy.js";
11
7
  import { enableNavigationPreload } from "./navigationPreload.js";
12
8
  import { setCacheNameDetails } from "./setCacheNameDetails.js";
13
9
  import type {
14
- PrecacheOptions,
10
+ Controller,
11
+ PrecacheEntry,
15
12
  RouteHandler,
16
13
  RouteHandlerCallback,
17
14
  RouteHandlerCallbackOptions,
18
15
  RouteHandlerObject,
19
16
  RouteMatchCallback,
20
17
  RouteMatchCallbackOptions,
18
+ RuntimeCaching,
21
19
  } from "./types.js";
22
- import type { RuntimeCaching } from "./types.js";
23
- import type { CleanupResult, InstallResult, PrecacheEntry } from "./types.js";
24
- import { PrecacheInstallReportPlugin } from "./utils/PrecacheInstallReportPlugin.js";
25
20
  import { SerwistError } from "./utils/SerwistError.js";
26
21
  import { assert } from "./utils/assert.js";
27
- import { cleanupOutdatedCaches as cleanupOutdatedCachesImpl } from "./utils/cleanupOutdatedCaches.js";
28
22
  import { clientsClaim as clientsClaimImpl } from "./utils/clientsClaim.js";
29
- import { createCacheKey } from "./utils/createCacheKey.js";
30
23
  import { getFriendlyURL } from "./utils/getFriendlyURL.js";
31
24
  import { logger } from "./utils/logger.js";
32
25
  import { normalizeHandler } from "./utils/normalizeHandler.js";
33
26
  import { parseRoute } from "./utils/parseRoute.js";
34
- import { printCleanupDetails } from "./utils/printCleanupDetails.js";
35
- import { printInstallDetails } from "./utils/printInstallDetails.js";
36
27
  import { waitUntil } from "./utils/waitUntil.js";
37
- import { parsePrecacheOptions } from "./utils/parsePrecacheOptions.js";
28
+ import { PrecacheController, type PrecacheOptions } from "./controllers/PrecacheController/PrecacheController.js";
29
+ import { RuntimeCacheController } from "./controllers/RuntimeCacheController.js";
38
30
 
39
31
  declare const self: ServiceWorkerGlobalScope;
40
32
 
@@ -56,6 +48,10 @@ export interface SerwistOptions {
56
48
  * Options to customize how Serwist precaches the URLs in the precache list.
57
49
  */
58
50
  precacheOptions?: PrecacheOptions;
51
+ /**
52
+ * A list of controllers that run throughout Serwist's lifecycle.
53
+ */
54
+ controllers?: Controller[];
59
55
  /**
60
56
  * Forces the waiting service worker to become the active one.
61
57
  *
@@ -88,6 +84,8 @@ export interface SerwistOptions {
88
84
  clientsClaim?: boolean;
89
85
  /**
90
86
  * A list of caching strategies.
87
+ *
88
+ * @deprecated Use {@linkcode RuntimeCacheController} instead.
91
89
  */
92
90
  runtimeCaching?: RuntimeCaching[];
93
91
  /**
@@ -107,6 +105,8 @@ export interface SerwistOptions {
107
105
  *
108
106
  * Note: This option mutates `runtimeCaching`. It also expects the URLs
109
107
  * defined in `entries` to have been precached beforehand.
108
+ *
109
+ * @deprecated Use {@linkcode RuntimeCacheController} instead.
110
110
  */
111
111
  fallbacks?: FallbacksOptions;
112
112
  }
@@ -126,18 +126,16 @@ interface CacheURLsMessageData {
126
126
  * @see https://serwist.pages.dev/docs/serwist/core/serwist
127
127
  */
128
128
  export class Serwist {
129
- private readonly _urlsToCacheKeys: Map<string, string> = new Map();
130
- private readonly _urlsToCacheModes: Map<string, "reload" | "default" | "no-store" | "no-cache" | "force-cache" | "only-if-cached"> = new Map();
131
- private readonly _cacheKeysToIntegrities: Map<string, string> = new Map();
132
- private _concurrentPrecaching: number;
133
- private readonly _precacheStrategy: Strategy;
134
129
  private readonly _routes: Map<HTTPMethod, Route[]>;
135
130
  private readonly _defaultHandlerMap: Map<HTTPMethod, RouteHandlerObject>;
131
+ private readonly _precacheController: PrecacheController;
132
+ private readonly _controllers: Controller[];
136
133
  private _catchHandler?: RouteHandlerObject;
137
134
 
138
135
  constructor({
139
136
  precacheEntries,
140
137
  precacheOptions,
138
+ controllers = [],
141
139
  skipWaiting = false,
142
140
  importScripts,
143
141
  navigationPreload = false,
@@ -148,12 +146,9 @@ export class Serwist {
148
146
  disableDevLogs = false,
149
147
  fallbacks,
150
148
  }: SerwistOptions = {}) {
151
- const { precacheStrategyOptions, precacheRouteOptions, precacheMiscOptions } = parsePrecacheOptions(this, precacheOptions);
152
-
153
- this._concurrentPrecaching = precacheMiscOptions.concurrency;
154
- this._precacheStrategy = new PrecacheStrategy(precacheStrategyOptions);
155
149
  this._routes = new Map();
156
150
  this._defaultHandlerMap = new Map();
151
+ this._controllers = controllers;
157
152
 
158
153
  this.handleInstall = this.handleInstall.bind(this);
159
154
  this.handleActivate = this.handleActivate.bind(this);
@@ -182,24 +177,19 @@ export class Serwist {
182
177
 
183
178
  if (clientsClaim) clientsClaimImpl();
184
179
 
185
- if (!!precacheEntries && precacheEntries.length > 0) {
186
- this.addToPrecacheList(precacheEntries);
187
- }
180
+ this._precacheController = new PrecacheController(precacheEntries ?? [], precacheOptions);
188
181
 
189
- if (precacheMiscOptions.cleanupOutdatedCaches) {
190
- cleanupOutdatedCachesImpl(precacheStrategyOptions.cacheName);
182
+ // TODO(ducanhgh): remove in v10.
183
+ // Fallback for legacy users who have not migrated from `runtimeCaching` to the Controller pattern.
184
+ if (runtimeCaching) {
185
+ if (!this._controllers?.some((controller) => controller instanceof RuntimeCacheController)) {
186
+ this._controllers.unshift(new RuntimeCacheController(runtimeCaching, { fallbacks }));
187
+ } else if (process.env.NODE_ENV !== "production") {
188
+ logger.warn("You have migrated to the Controller pattern, so setting `runtimeCaching` is a no-op.");
189
+ }
191
190
  }
192
191
 
193
- this.registerRoute(new PrecacheRoute(this, precacheRouteOptions));
194
-
195
- if (precacheMiscOptions.navigateFallback) {
196
- this.registerRoute(
197
- new NavigationRoute(this.createHandlerBoundToUrl(precacheMiscOptions.navigateFallback), {
198
- allowlist: precacheMiscOptions.navigateFallbackAllowlist,
199
- denylist: precacheMiscOptions.navigateFallbackDenylist,
200
- }),
201
- );
202
- }
192
+ this._controllers.unshift(this._precacheController);
203
193
 
204
194
  if (offlineAnalyticsConfig !== undefined) {
205
195
  if (typeof offlineAnalyticsConfig === "boolean") {
@@ -212,37 +202,43 @@ export class Serwist {
212
202
  }
213
203
  }
214
204
 
215
- if (runtimeCaching !== undefined) {
216
- if (fallbacks !== undefined) {
217
- const fallbackPlugin = new PrecacheFallbackPlugin({
218
- fallbackUrls: fallbacks.entries,
219
- serwist: this,
220
- });
205
+ for (const callback of this.iterateControllers("init")) {
206
+ callback(this);
207
+ }
221
208
 
222
- runtimeCaching.forEach((cacheEntry) => {
223
- if (
224
- cacheEntry.handler instanceof Strategy &&
225
- // This also filters entries with `PrecacheFallbackPlugin` as it also has `handlerDidError`.
226
- !cacheEntry.handler.plugins.some((plugin) => "handlerDidError" in plugin)
227
- ) {
228
- cacheEntry.handler.plugins.push(fallbackPlugin);
229
- }
230
- });
231
- }
232
- for (const entry of runtimeCaching) {
233
- this.registerCapture(entry.matcher, entry.handler, entry.method);
209
+ if (disableDevLogs) disableDevLogsImpl();
210
+ }
211
+
212
+ /**
213
+ * Accepts a callback name and returns an iterable of matching plugin callbacks.
214
+ *
215
+ * @param name The name fo the callback to run
216
+ * @returns
217
+ */
218
+ *iterateControllers<C extends keyof Controller>(name: C): Generator<NonNullable<Controller[C]>> {
219
+ if (!this._controllers) return;
220
+
221
+ for (const controller of this._controllers) {
222
+ if (typeof controller[name] === "function") {
223
+ yield controller[name];
234
224
  }
235
225
  }
226
+ }
236
227
 
237
- if (disableDevLogs) disableDevLogsImpl();
228
+ /**
229
+ * The `PrecacheController` used to handle precaching.
230
+ */
231
+ get precache(): PrecacheController {
232
+ return this._precacheController;
238
233
  }
239
234
 
240
235
  /**
241
236
  * The strategy used to precache assets and respond to `fetch` events.
242
237
  */
243
238
  get precacheStrategy(): Strategy {
244
- return this._precacheStrategy;
239
+ return this._precacheController.strategy;
245
240
  }
241
+
246
242
  /**
247
243
  * A `Map` of HTTP method name (`'GET'`, etc.) to an array of all corresponding registered {@linkcode Route}
248
244
  * instances.
@@ -252,7 +248,7 @@ export class Serwist {
252
248
  }
253
249
 
254
250
  /**
255
- * Adds Serwist's event listeners for you. Before calling it, add your own listeners should you need to.
251
+ * Adds Serwist's event listeners. Before calling it, add your own listeners should you need to.
256
252
  */
257
253
  addEventListeners() {
258
254
  self.addEventListener("install", this.handleInstall);
@@ -261,67 +257,6 @@ export class Serwist {
261
257
  self.addEventListener("message", this.handleCache);
262
258
  }
263
259
 
264
- /**
265
- * Adds items to the precache list, removing duplicates and ensuring the information is valid.
266
- *
267
- * @param entries Array of entries to precache.
268
- */
269
- addToPrecacheList(entries: (PrecacheEntry | string)[]): void {
270
- if (process.env.NODE_ENV !== "production") {
271
- assert!.isArray(entries, {
272
- moduleName: "serwist",
273
- className: "Serwist",
274
- funcName: "addToCacheList",
275
- paramName: "entries",
276
- });
277
- }
278
-
279
- const urlsToWarnAbout: string[] = [];
280
- for (const entry of entries) {
281
- // See https://github.com/GoogleChrome/workbox/issues/2259
282
- if (typeof entry === "string") {
283
- urlsToWarnAbout.push(entry);
284
- } else if (entry && !entry.integrity && entry.revision === undefined) {
285
- urlsToWarnAbout.push(entry.url);
286
- }
287
-
288
- const { cacheKey, url } = createCacheKey(entry);
289
- const cacheMode = typeof entry !== "string" && entry.revision ? "reload" : "default";
290
-
291
- if (this._urlsToCacheKeys.has(url) && this._urlsToCacheKeys.get(url) !== cacheKey) {
292
- throw new SerwistError("add-to-cache-list-conflicting-entries", {
293
- firstEntry: this._urlsToCacheKeys.get(url),
294
- secondEntry: cacheKey,
295
- });
296
- }
297
-
298
- if (typeof entry !== "string" && entry.integrity) {
299
- if (this._cacheKeysToIntegrities.has(cacheKey) && this._cacheKeysToIntegrities.get(cacheKey) !== entry.integrity) {
300
- throw new SerwistError("add-to-cache-list-conflicting-integrities", {
301
- url,
302
- });
303
- }
304
- this._cacheKeysToIntegrities.set(cacheKey, entry.integrity);
305
- }
306
-
307
- this._urlsToCacheKeys.set(url, cacheKey);
308
- this._urlsToCacheModes.set(url, cacheMode);
309
-
310
- if (urlsToWarnAbout.length > 0) {
311
- const warningMessage = `Serwist is precaching URLs without revision info: ${urlsToWarnAbout.join(
312
- ", ",
313
- )}\nThis is generally NOT safe. Learn more at https://bit.ly/wb-precache`;
314
- if (process.env.NODE_ENV === "production") {
315
- // Use console directly to display this warning without bloating
316
- // bundle sizes by pulling in all of the logger codebase in prod.
317
- console.warn(warningMessage);
318
- } else {
319
- logger.warn(warningMessage);
320
- }
321
- }
322
- }
323
- }
324
-
325
260
  /**
326
261
  * Precaches new and updated assets. Call this method from the service worker's
327
262
  * `install` event.
@@ -332,38 +267,11 @@ export class Serwist {
332
267
  * @param event
333
268
  * @returns
334
269
  */
335
- handleInstall(event: ExtendableEvent): Promise<InstallResult> {
336
- return waitUntil<InstallResult>(event, async () => {
337
- const installReportPlugin = new PrecacheInstallReportPlugin();
338
- this.precacheStrategy.plugins.push(installReportPlugin);
339
-
340
- await parallel(this._concurrentPrecaching, Array.from(this._urlsToCacheKeys.entries()), async ([url, cacheKey]): Promise<void> => {
341
- const integrity = this._cacheKeysToIntegrities.get(cacheKey);
342
- const cacheMode = this._urlsToCacheModes.get(url);
343
-
344
- const request = new Request(url, {
345
- integrity,
346
- cache: cacheMode,
347
- credentials: "same-origin",
348
- });
349
-
350
- await Promise.all(
351
- this.precacheStrategy.handleAll({
352
- event,
353
- request,
354
- url: new URL(request.url),
355
- params: { cacheKey },
356
- }),
357
- );
358
- });
359
-
360
- const { updatedURLs, notUpdatedURLs } = installReportPlugin;
361
-
362
- if (process.env.NODE_ENV !== "production") {
363
- printInstallDetails(updatedURLs, notUpdatedURLs);
270
+ handleInstall(event: ExtendableEvent): Promise<void> {
271
+ return waitUntil(event, async () => {
272
+ for (const callback of this.iterateControllers("install")) {
273
+ await callback(event, this);
364
274
  }
365
-
366
- return { updatedURLs, notUpdatedURLs };
367
275
  });
368
276
  }
369
277
 
@@ -377,26 +285,11 @@ export class Serwist {
377
285
  * @param event
378
286
  * @returns
379
287
  */
380
- handleActivate(event: ExtendableEvent): Promise<CleanupResult> {
381
- return waitUntil<CleanupResult>(event, async () => {
382
- const cache = await self.caches.open(this.precacheStrategy.cacheName);
383
- const currentlyCachedRequests = await cache.keys();
384
- const expectedCacheKeys = new Set(this._urlsToCacheKeys.values());
385
-
386
- const deletedCacheRequests: string[] = [];
387
-
388
- for (const request of currentlyCachedRequests) {
389
- if (!expectedCacheKeys.has(request.url)) {
390
- await cache.delete(request);
391
- deletedCacheRequests.push(request.url);
392
- }
393
- }
394
-
395
- if (process.env.NODE_ENV !== "production") {
396
- printCleanupDetails(deletedCacheRequests);
288
+ handleActivate(event: ExtendableEvent): Promise<void> {
289
+ return waitUntil(event, async () => {
290
+ for (const callback of this.iterateControllers("activate")) {
291
+ await callback(event, this);
397
292
  }
398
-
399
- return { deletedCacheRequests };
400
293
  });
401
294
  }
402
295
 
@@ -568,97 +461,6 @@ export class Serwist {
568
461
  }
569
462
  }
570
463
 
571
- /**
572
- * Returns a mapping of a precached URL to the corresponding cache key, taking
573
- * into account the revision information for the URL.
574
- *
575
- * @returns A URL to cache key mapping.
576
- */
577
- getUrlsToPrecacheKeys(): Map<string, string> {
578
- return this._urlsToCacheKeys;
579
- }
580
-
581
- /**
582
- * Returns a list of all the URLs that have been precached by the current
583
- * service worker.
584
- *
585
- * @returns The precached URLs.
586
- */
587
- getPrecachedUrls(): string[] {
588
- return [...this._urlsToCacheKeys.keys()];
589
- }
590
-
591
- /**
592
- * Returns the cache key used for storing a given URL. If that URL is
593
- * unversioned, like "/index.html", then the cache key will be the original
594
- * URL with a search parameter appended to it.
595
- *
596
- * @param url A URL whose cache key you want to look up.
597
- * @returns The versioned URL that corresponds to a cache key
598
- * for the original URL, or undefined if that URL isn't precached.
599
- */
600
- getPrecacheKeyForUrl(url: string): string | undefined {
601
- const urlObject = new URL(url, location.href);
602
- return this._urlsToCacheKeys.get(urlObject.href);
603
- }
604
-
605
- /**
606
- * @param url A cache key whose SRI you want to look up.
607
- * @returns The subresource integrity associated with the cache key,
608
- * or undefined if it's not set.
609
- */
610
- getIntegrityForPrecacheKey(cacheKey: string): string | undefined {
611
- return this._cacheKeysToIntegrities.get(cacheKey);
612
- }
613
-
614
- /**
615
- * This acts as a drop-in replacement for
616
- * [`cache.match()`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/match)
617
- * with the following differences:
618
- *
619
- * - It knows what the name of the precache is, and only checks in that cache.
620
- * - It allows you to pass in an "original" URL without versioning parameters,
621
- * and it will automatically look up the correct cache key for the currently
622
- * active revision of that URL.
623
- *
624
- * E.g., `matchPrecache('index.html')` will find the correct precached
625
- * response for the currently active service worker, even if the actual cache
626
- * key is `'/index.html?__WB_REVISION__=1234abcd'`.
627
- *
628
- * @param request The key (without revisioning parameters)
629
- * to look up in the precache.
630
- * @returns
631
- */
632
- async matchPrecache(request: string | Request): Promise<Response | undefined> {
633
- const url = request instanceof Request ? request.url : request;
634
- const cacheKey = this.getPrecacheKeyForUrl(url);
635
- if (cacheKey) {
636
- const cache = await self.caches.open(this.precacheStrategy.cacheName);
637
- return cache.match(cacheKey);
638
- }
639
- return undefined;
640
- }
641
-
642
- /**
643
- * Returns a function that looks up `url` in the precache (taking into
644
- * account revision information), and returns the corresponding `Response`.
645
- *
646
- * @param url The precached URL which will be used to lookup the response.
647
- * @return
648
- */
649
- createHandlerBoundToUrl(url: string): RouteHandlerCallback {
650
- const cacheKey = this.getPrecacheKeyForUrl(url);
651
- if (!cacheKey) {
652
- throw new SerwistError("non-precached-url", { url });
653
- }
654
- return (options) => {
655
- options.request = new Request(url);
656
- options.params = { cacheKey, ...options.params };
657
-
658
- return this.precacheStrategy.handle(options);
659
- };
660
- }
661
-
662
464
  /**
663
465
  * Applies the routing rules to a `FetchEvent` object to get a response from an
664
466
  * appropriate route.
@@ -864,4 +666,97 @@ export class Serwist {
864
666
  // If no match was found above, return and empty object.
865
667
  return {};
866
668
  }
669
+
670
+ // The following are deprecated methods:
671
+
672
+ /**
673
+ * Adds items to the precache list, removing duplicates and ensuring the information is valid.
674
+ *
675
+ * @deprecated Use `serwist.precache.addToPrecacheList` instead.
676
+ * @param entries Array of entries to precache.
677
+ */
678
+ addToPrecacheList(entries: (PrecacheEntry | string)[]): void {
679
+ this._precacheController.addToCacheList(entries);
680
+ }
681
+
682
+ /**
683
+ * Returns a mapping of a precached URL to the corresponding cache key, taking
684
+ * into account the revision information for the URL.
685
+ *
686
+ * @deprecated Use `serwist.precache.getUrlsToPrecacheKeys` instead.
687
+ * @returns A URL to cache key mapping.
688
+ */
689
+ getUrlsToPrecacheKeys(): Map<string, string> {
690
+ return this.precache.getUrlsToPrecacheKeys();
691
+ }
692
+
693
+ /**
694
+ * Returns a list of all the URLs that have been precached by the current
695
+ * service worker.
696
+ *
697
+ * @deprecated Use `serwist.precache.getPrecachedUrls` instead.
698
+ * @returns The precached URLs.
699
+ */
700
+ getPrecachedUrls(): string[] {
701
+ return this.precache.getPrecachedUrls();
702
+ }
703
+
704
+ /**
705
+ * Returns the cache key used for storing a given URL. If that URL is
706
+ * unversioned, like "/index.html", then the cache key will be the original
707
+ * URL with a search parameter appended to it.
708
+ *
709
+ * @deprecated Use `serwist.precache.getPrecacheKeyForUrl` instead.
710
+ * @param url A URL whose cache key you want to look up.
711
+ * @returns The versioned URL that corresponds to a cache key
712
+ * for the original URL, or undefined if that URL isn't precached.
713
+ */
714
+ getPrecacheKeyForUrl(url: string): string | undefined {
715
+ return this.precache.getPrecacheKeyForUrl(url);
716
+ }
717
+
718
+ /**
719
+ * @deprecated Use `serwist.precache.getIntegrityForPrecacheKey` instead.
720
+ * @param url A cache key whose SRI you want to look up.
721
+ * @returns The subresource integrity associated with the cache key,
722
+ * or undefined if it's not set.
723
+ */
724
+ getIntegrityForPrecacheKey(cacheKey: string): string | undefined {
725
+ return this.precache.getIntegrityForPrecacheKey(cacheKey);
726
+ }
727
+
728
+ /**
729
+ * This acts as a drop-in replacement for
730
+ * [`cache.match()`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/match)
731
+ * with the following differences:
732
+ *
733
+ * - It knows what the name of the precache is, and only checks in that cache.
734
+ * - It allows you to pass in an "original" URL without versioning parameters,
735
+ * and it will automatically look up the correct cache key for the currently
736
+ * active revision of that URL.
737
+ *
738
+ * E.g., `matchPrecache('index.html')` will find the correct precached
739
+ * response for the currently active service worker, even if the actual cache
740
+ * key is `'/index.html?__WB_REVISION__=1234abcd'`.
741
+ *
742
+ * @deprecated Use `serwist.precache.matchPrecache` instead.
743
+ * @param request The key (without revisioning parameters)
744
+ * to look up in the precache.
745
+ * @returns
746
+ */
747
+ matchPrecache(request: string | Request): Promise<Response | undefined> {
748
+ return this.precache.matchPrecache(request);
749
+ }
750
+
751
+ /**
752
+ * Returns a function that looks up `url` in the precache (taking into
753
+ * account revision information), and returns the corresponding `Response`.
754
+ *
755
+ * @deprecated Use `serwist.precache.createHandlerBoundToUrl` instead.
756
+ * @param url The precached URL which will be used to lookup the response.
757
+ * @return
758
+ */
759
+ createHandlerBoundToUrl(url: string): RouteHandlerCallback {
760
+ return this.precache.createHandlerBoundToUrl(url);
761
+ }
867
762
  }
@@ -5,9 +5,8 @@
5
5
  license that can be found in the LICENSE file or at
6
6
  https://opensource.org/licenses/MIT.
7
7
  */
8
-
9
- import type { SerwistPlugin, SerwistPluginCallbackParam } from "../../types.js";
10
- import type { PrecacheController } from "../PrecacheController.js";
8
+ import type { PrecacheController } from "./PrecacheController.js";
9
+ import type { StrategyPlugin, StrategyPluginCallbackParam } from "../../types.js";
11
10
 
12
11
  /**
13
12
  * A plugin, designed to be used with PrecacheController, to translate URLs into
@@ -15,17 +14,17 @@ import type { PrecacheController } from "../PrecacheController.js";
15
14
  *
16
15
  * @private
17
16
  */
18
- export class PrecacheCacheKeyPlugin implements SerwistPlugin {
17
+ export class PrecacheCacheKeyPlugin implements StrategyPlugin {
19
18
  private readonly _precacheController: PrecacheController;
20
19
 
21
20
  constructor({ precacheController }: { precacheController: PrecacheController }) {
22
21
  this._precacheController = precacheController;
23
22
  }
24
23
 
25
- cacheKeyWillBeUsed: SerwistPlugin["cacheKeyWillBeUsed"] = async ({ request, params }: SerwistPluginCallbackParam["cacheKeyWillBeUsed"]) => {
24
+ cacheKeyWillBeUsed: StrategyPlugin["cacheKeyWillBeUsed"] = async ({ request, params }: StrategyPluginCallbackParam["cacheKeyWillBeUsed"]) => {
26
25
  // Params is type any, can't change right now.
27
26
  /* eslint-disable */
28
- const cacheKey = params?.cacheKey || this._precacheController.getCacheKeyForURL(request.url);
27
+ const cacheKey = params?.cacheKey || this._precacheController.getPrecacheKeyForUrl(request.url);
29
28
  /* eslint-enable */
30
29
 
31
30
  return cacheKey ? new Request(cacheKey, { headers: request.headers }) : request;