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
@@ -6,11 +6,11 @@
6
6
  https://opensource.org/licenses/MIT.
7
7
  */
8
8
 
9
+ import { assert } from "#utils/assert.js";
10
+ import { logger } from "#utils/logger.js";
9
11
  import { Route } from "./Route.js";
10
12
  import type { HTTPMethod } from "./constants.js";
11
13
  import type { RouteHandler, RouteMatchCallback, RouteMatchCallbackOptions } from "./types.js";
12
- import { assert } from "./utils/assert.js";
13
- import { logger } from "./utils/logger.js";
14
14
 
15
15
  /**
16
16
  * A class that makes it easy to create a {@linkcode Route} object with a regular expression.
package/src/Route.ts CHANGED
@@ -6,11 +6,11 @@
6
6
  https://opensource.org/licenses/MIT.
7
7
  */
8
8
 
9
+ import { assert } from "#utils/assert.js";
10
+ import { normalizeHandler } from "#utils/normalizeHandler.js";
9
11
  import type { HTTPMethod } from "./constants.js";
10
12
  import { defaultMethod, validMethods } from "./constants.js";
11
13
  import type { RouteHandler, RouteHandlerObject, RouteMatchCallback } from "./types.js";
12
- import { assert } from "./utils/assert.js";
13
- import { normalizeHandler } from "./utils/normalizeHandler.js";
14
14
 
15
15
  /**
16
16
  * A `Route` consists of a pair of callback functions, `match` and `handler`.
package/src/Serwist.ts CHANGED
@@ -1,40 +1,33 @@
1
- import { parallel } from "@serwist/utils";
2
- import { NavigationRoute } from "./NavigationRoute.js";
3
- import { PrecacheRoute } from "./PrecacheRoute.js";
1
+ import { PrecacheController, type PrecacheOptions } from "#lib/controllers/PrecacheController/PrecacheController.js";
2
+ import { RuntimeCacheController } from "#lib/controllers/RuntimeCacheController.js";
3
+ import { type GoogleAnalyticsInitializeOptions, initializeGoogleAnalytics } from "#lib/googleAnalytics/initializeGoogleAnalytics.js";
4
+ import type { PrecacheFallbackEntry } from "#lib/precaching/PrecacheFallbackPlugin.js";
5
+ import type { Strategy } from "#lib/strategies/Strategy.js";
6
+ import { SerwistError } from "#utils/SerwistError.js";
7
+ import { assert } from "#utils/assert.js";
8
+ import { clientsClaim as clientsClaimImpl } from "#utils/clientsClaim.js";
9
+ import { getFriendlyURL } from "#utils/getFriendlyURL.js";
10
+ import { logger } from "#utils/logger.js";
11
+ import { normalizeHandler } from "#utils/normalizeHandler.js";
12
+ import { parseRoute } from "#utils/parseRoute.js";
13
+ import { waitUntil } from "#utils/waitUntil.js";
4
14
  import type { Route } from "./Route.js";
5
15
  import { type HTTPMethod, defaultMethod } from "./constants.js";
6
16
  import { disableDevLogs as disableDevLogsImpl } from "./disableDevLogs.js";
7
- 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";
11
17
  import { enableNavigationPreload } from "./navigationPreload.js";
12
18
  import { setCacheNameDetails } from "./setCacheNameDetails.js";
13
19
  import type {
14
- PrecacheOptions,
20
+ Controller,
21
+ ControllerParam,
22
+ PrecacheEntry,
15
23
  RouteHandler,
16
24
  RouteHandlerCallback,
17
25
  RouteHandlerCallbackOptions,
18
26
  RouteHandlerObject,
19
27
  RouteMatchCallback,
20
28
  RouteMatchCallbackOptions,
29
+ RuntimeCaching,
21
30
  } 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
- import { SerwistError } from "./utils/SerwistError.js";
26
- import { assert } from "./utils/assert.js";
27
- import { cleanupOutdatedCaches as cleanupOutdatedCachesImpl } from "./utils/cleanupOutdatedCaches.js";
28
- import { clientsClaim as clientsClaimImpl } from "./utils/clientsClaim.js";
29
- import { createCacheKey } from "./utils/createCacheKey.js";
30
- import { getFriendlyURL } from "./utils/getFriendlyURL.js";
31
- import { logger } from "./utils/logger.js";
32
- import { normalizeHandler } from "./utils/normalizeHandler.js";
33
- import { parseRoute } from "./utils/parseRoute.js";
34
- import { printCleanupDetails } from "./utils/printCleanupDetails.js";
35
- import { printInstallDetails } from "./utils/printInstallDetails.js";
36
- import { waitUntil } from "./utils/waitUntil.js";
37
- import { parsePrecacheOptions } from "./utils/parsePrecacheOptions.js";
38
31
 
39
32
  declare const self: ServiceWorkerGlobalScope;
40
33
 
@@ -56,6 +49,10 @@ export interface SerwistOptions {
56
49
  * Options to customize how Serwist precaches the URLs in the precache list.
57
50
  */
58
51
  precacheOptions?: PrecacheOptions;
52
+ /**
53
+ * A list of controllers that run throughout Serwist's lifecycle.
54
+ */
55
+ controllers?: Controller[];
59
56
  /**
60
57
  * Forces the waiting service worker to become the active one.
61
58
  *
@@ -88,6 +85,8 @@ export interface SerwistOptions {
88
85
  clientsClaim?: boolean;
89
86
  /**
90
87
  * A list of caching strategies.
88
+ *
89
+ * @deprecated Use {@linkcode RuntimeCacheController} instead.
91
90
  */
92
91
  runtimeCaching?: RuntimeCaching[];
93
92
  /**
@@ -107,6 +106,8 @@ export interface SerwistOptions {
107
106
  *
108
107
  * Note: This option mutates `runtimeCaching`. It also expects the URLs
109
108
  * defined in `entries` to have been precached beforehand.
109
+ *
110
+ * @deprecated Use {@linkcode RuntimeCacheController} instead.
110
111
  */
111
112
  fallbacks?: FallbacksOptions;
112
113
  }
@@ -126,18 +127,16 @@ interface CacheURLsMessageData {
126
127
  * @see https://serwist.pages.dev/docs/serwist/core/serwist
127
128
  */
128
129
  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
130
  private readonly _routes: Map<HTTPMethod, Route[]>;
135
131
  private readonly _defaultHandlerMap: Map<HTTPMethod, RouteHandlerObject>;
132
+ private readonly _precacheController: PrecacheController;
133
+ private readonly _controllers: Controller[];
136
134
  private _catchHandler?: RouteHandlerObject;
137
135
 
138
136
  constructor({
139
137
  precacheEntries,
140
138
  precacheOptions,
139
+ controllers = [],
141
140
  skipWaiting = false,
142
141
  importScripts,
143
142
  navigationPreload = false,
@@ -148,12 +147,9 @@ export class Serwist {
148
147
  disableDevLogs = false,
149
148
  fallbacks,
150
149
  }: SerwistOptions = {}) {
151
- const { precacheStrategyOptions, precacheRouteOptions, precacheMiscOptions } = parsePrecacheOptions(this, precacheOptions);
152
-
153
- this._concurrentPrecaching = precacheMiscOptions.concurrency;
154
- this._precacheStrategy = new PrecacheStrategy(precacheStrategyOptions);
155
150
  this._routes = new Map();
156
151
  this._defaultHandlerMap = new Map();
152
+ this._controllers = controllers;
157
153
 
158
154
  this.handleInstall = this.handleInstall.bind(this);
159
155
  this.handleActivate = this.handleActivate.bind(this);
@@ -182,24 +178,19 @@ export class Serwist {
182
178
 
183
179
  if (clientsClaim) clientsClaimImpl();
184
180
 
185
- if (!!precacheEntries && precacheEntries.length > 0) {
186
- this.addToPrecacheList(precacheEntries);
187
- }
181
+ this._precacheController = new PrecacheController(precacheEntries ?? [], precacheOptions);
188
182
 
189
- if (precacheMiscOptions.cleanupOutdatedCaches) {
190
- cleanupOutdatedCachesImpl(precacheStrategyOptions.cacheName);
183
+ // TODO(ducanhgh): remove in v11.
184
+ // Fallback for legacy users who have not migrated from `runtimeCaching` to the Controller pattern.
185
+ if (runtimeCaching) {
186
+ if (!this._controllers?.some((controller) => controller instanceof RuntimeCacheController)) {
187
+ this._controllers.unshift(new RuntimeCacheController(runtimeCaching, { fallbacks }));
188
+ } else if (process.env.NODE_ENV !== "production") {
189
+ logger.warn("You have migrated to the Controller pattern, so setting `runtimeCaching` is a no-op.");
190
+ }
191
191
  }
192
192
 
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
- }
193
+ this._controllers.unshift(this._precacheController);
203
194
 
204
195
  if (offlineAnalyticsConfig !== undefined) {
205
196
  if (typeof offlineAnalyticsConfig === "boolean") {
@@ -212,37 +203,46 @@ export class Serwist {
212
203
  }
213
204
  }
214
205
 
215
- if (runtimeCaching !== undefined) {
216
- if (fallbacks !== undefined) {
217
- const fallbackPlugin = new PrecacheFallbackPlugin({
218
- fallbackUrls: fallbacks.entries,
219
- serwist: this,
220
- });
206
+ for (const callback of this.iterateControllers("init")) {
207
+ callback({ serwist: this });
208
+ }
221
209
 
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);
210
+ if (disableDevLogs) disableDevLogsImpl();
211
+ }
212
+
213
+ /**
214
+ * Accepts a callback name and returns an iterable of matching plugin callbacks.
215
+ *
216
+ * @param name The name fo the callback to run
217
+ * @returns
218
+ */
219
+ *iterateControllers<C extends keyof Controller>(name: C): Generator<NonNullable<Controller[C]>> {
220
+ if (!this._controllers) return;
221
+
222
+ for (const controller of this._controllers) {
223
+ if (typeof controller[name] === "function") {
224
+ const callback = (param: ControllerParam[C]) => {
225
+ controller[name]!(param as any);
226
+ };
227
+ yield callback as NonNullable<Controller[C]>;
234
228
  }
235
229
  }
230
+ }
236
231
 
237
- if (disableDevLogs) disableDevLogsImpl();
232
+ /**
233
+ * The `PrecacheController` used to handle precaching.
234
+ */
235
+ get precache(): PrecacheController {
236
+ return this._precacheController;
238
237
  }
239
238
 
240
239
  /**
241
240
  * The strategy used to precache assets and respond to `fetch` events.
242
241
  */
243
242
  get precacheStrategy(): Strategy {
244
- return this._precacheStrategy;
243
+ return this._precacheController.strategy;
245
244
  }
245
+
246
246
  /**
247
247
  * A `Map` of HTTP method name (`'GET'`, etc.) to an array of all corresponding registered {@linkcode Route}
248
248
  * instances.
@@ -252,7 +252,7 @@ export class Serwist {
252
252
  }
253
253
 
254
254
  /**
255
- * Adds Serwist's event listeners for you. Before calling it, add your own listeners should you need to.
255
+ * Adds Serwist's event listeners. Before calling it, add your own listeners should you need to.
256
256
  */
257
257
  addEventListeners() {
258
258
  self.addEventListener("install", this.handleInstall);
@@ -261,67 +261,6 @@ export class Serwist {
261
261
  self.addEventListener("message", this.handleCache);
262
262
  }
263
263
 
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
264
  /**
326
265
  * Precaches new and updated assets. Call this method from the service worker's
327
266
  * `install` event.
@@ -332,38 +271,11 @@ export class Serwist {
332
271
  * @param event
333
272
  * @returns
334
273
  */
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);
274
+ handleInstall(event: ExtendableEvent): Promise<void> {
275
+ return waitUntil(event, async () => {
276
+ for (const callback of this.iterateControllers("install")) {
277
+ await callback({ event, serwist: this });
364
278
  }
365
-
366
- return { updatedURLs, notUpdatedURLs };
367
279
  });
368
280
  }
369
281
 
@@ -377,26 +289,11 @@ export class Serwist {
377
289
  * @param event
378
290
  * @returns
379
291
  */
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);
292
+ handleActivate(event: ExtendableEvent): Promise<void> {
293
+ return waitUntil(event, async () => {
294
+ for (const callback of this.iterateControllers("activate")) {
295
+ await callback({ event, serwist: this });
397
296
  }
398
-
399
- return { deletedCacheRequests };
400
297
  });
401
298
  }
402
299
 
@@ -568,97 +465,6 @@ export class Serwist {
568
465
  }
569
466
  }
570
467
 
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
468
  /**
663
469
  * Applies the routing rules to a `FetchEvent` object to get a response from an
664
470
  * appropriate route.
@@ -864,4 +670,97 @@ export class Serwist {
864
670
  // If no match was found above, return and empty object.
865
671
  return {};
866
672
  }
673
+
674
+ // The following are deprecated methods:
675
+
676
+ /**
677
+ * Adds items to the precache list, removing duplicates and ensuring the information is valid.
678
+ *
679
+ * @deprecated Use `serwist.precache.addToCacheList` instead.
680
+ * @param entries Array of entries to precache.
681
+ */
682
+ addToPrecacheList(entries: (PrecacheEntry | string)[]): void {
683
+ this._precacheController.addToCacheList(entries);
684
+ }
685
+
686
+ /**
687
+ * Returns a mapping of a precached URL to the corresponding cache key, taking
688
+ * into account the revision information for the URL.
689
+ *
690
+ * @deprecated Use `serwist.precache.getUrlsToPrecacheKeys` instead.
691
+ * @returns A URL to cache key mapping.
692
+ */
693
+ getUrlsToPrecacheKeys(): Map<string, string> {
694
+ return this.precache.getUrlsToPrecacheKeys();
695
+ }
696
+
697
+ /**
698
+ * Returns a list of all the URLs that have been precached by the current
699
+ * service worker.
700
+ *
701
+ * @deprecated Use `serwist.precache.getPrecachedUrls` instead.
702
+ * @returns The precached URLs.
703
+ */
704
+ getPrecachedUrls(): string[] {
705
+ return this.precache.getPrecachedUrls();
706
+ }
707
+
708
+ /**
709
+ * Returns the cache key used for storing a given URL. If that URL is
710
+ * unversioned, like "/index.html", then the cache key will be the original
711
+ * URL with a search parameter appended to it.
712
+ *
713
+ * @deprecated Use `serwist.precache.getPrecacheKeyForUrl` instead.
714
+ * @param url A URL whose cache key you want to look up.
715
+ * @returns The versioned URL that corresponds to a cache key
716
+ * for the original URL, or undefined if that URL isn't precached.
717
+ */
718
+ getPrecacheKeyForUrl(url: string): string | undefined {
719
+ return this.precache.getPrecacheKeyForUrl(url);
720
+ }
721
+
722
+ /**
723
+ * @deprecated Use `serwist.precache.getIntegrityForPrecacheKey` instead.
724
+ * @param url A cache key whose SRI you want to look up.
725
+ * @returns The subresource integrity associated with the cache key,
726
+ * or undefined if it's not set.
727
+ */
728
+ getIntegrityForPrecacheKey(cacheKey: string): string | undefined {
729
+ return this.precache.getIntegrityForPrecacheKey(cacheKey);
730
+ }
731
+
732
+ /**
733
+ * This acts as a drop-in replacement for
734
+ * [`cache.match()`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/match)
735
+ * with the following differences:
736
+ *
737
+ * - It knows what the name of the precache is, and only checks in that cache.
738
+ * - It allows you to pass in an "original" URL without versioning parameters,
739
+ * and it will automatically look up the correct cache key for the currently
740
+ * active revision of that URL.
741
+ *
742
+ * E.g., `matchPrecache('index.html')` will find the correct precached
743
+ * response for the currently active service worker, even if the actual cache
744
+ * key is `'/index.html?__WB_REVISION__=1234abcd'`.
745
+ *
746
+ * @deprecated Use `serwist.precache.matchPrecache` instead.
747
+ * @param request The key (without revisioning parameters)
748
+ * to look up in the precache.
749
+ * @returns
750
+ */
751
+ matchPrecache(request: string | Request): Promise<Response | undefined> {
752
+ return this.precache.matchPrecache(request);
753
+ }
754
+
755
+ /**
756
+ * Returns a function that looks up `url` in the precache (taking into
757
+ * account revision information), and returns the corresponding `Response`.
758
+ *
759
+ * @deprecated Use `serwist.precache.createHandlerBoundToUrl` instead.
760
+ * @param url The precached URL which will be used to lookup the response.
761
+ * @return
762
+ */
763
+ createHandlerBoundToUrl(url: string): RouteHandlerCallback {
764
+ return this.precache.createHandlerBoundToUrl(url);
765
+ }
867
766
  }
package/src/cacheNames.ts CHANGED
@@ -6,7 +6,7 @@
6
6
  https://opensource.org/licenses/MIT.
7
7
  */
8
8
 
9
- import { cacheNames as privateCacheNames } from "./utils/cacheNames.js";
9
+ import { cacheNames as privateCacheNames } from "#utils/cacheNames.js";
10
10
 
11
11
  /**
12
12
  * Get the current cache names and prefix/suffix used by Serwist.
@@ -6,8 +6,8 @@
6
6
  https://opensource.org/licenses/MIT.
7
7
  */
8
8
 
9
- import { SerwistError } from "./utils/SerwistError.js";
10
- import { canConstructResponseFromBodyStream } from "./utils/canConstructResponseFromBodyStream.js";
9
+ import { SerwistError } from "#utils/SerwistError.js";
10
+ import { canConstructResponseFromBodyStream } from "#utils/canConstructResponseFromBodyStream.js";
11
11
 
12
12
  /**
13
13
  * Allows developers to copy a response and modify its `headers`, `status`,
@@ -1,19 +1,19 @@
1
- import { Deferred } from "./utils/Deferred.js";
2
- import { SerwistError } from "./utils/SerwistError.js";
3
- import { assert } from "./utils/assert.js";
4
- import { cacheMatchIgnoreParams } from "./utils/cacheMatchIgnoreParams.js";
5
- import { cacheNames as privateCacheNames } from "./utils/cacheNames.js";
6
- import { canConstructReadableStream } from "./utils/canConstructReadableStream.js";
7
- import { canConstructResponseFromBodyStream } from "./utils/canConstructResponseFromBodyStream.js";
8
- import { cleanupOutdatedCaches } from "./utils/cleanupOutdatedCaches.js";
9
- import { clientsClaim } from "./utils/clientsClaim.js";
10
- import { dontWaitFor } from "./utils/dontWaitFor.js";
11
- import { executeQuotaErrorCallbacks } from "./utils/executeQuotaErrorCallbacks.js";
12
- import { getFriendlyURL } from "./utils/getFriendlyURL.js";
13
- import { logger } from "./utils/logger.js";
14
- import { resultingClientExists } from "./utils/resultingClientExists.js";
15
- import { timeout } from "./utils/timeout.js";
16
- import { waitUntil } from "./utils/waitUntil.js";
1
+ import { Deferred } from "#utils/Deferred.js";
2
+ import { SerwistError } from "#utils/SerwistError.js";
3
+ import { assert } from "#utils/assert.js";
4
+ import { cacheMatchIgnoreParams } from "#utils/cacheMatchIgnoreParams.js";
5
+ import { cacheNames as privateCacheNames } from "#utils/cacheNames.js";
6
+ import { canConstructReadableStream } from "#utils/canConstructReadableStream.js";
7
+ import { canConstructResponseFromBodyStream } from "#utils/canConstructResponseFromBodyStream.js";
8
+ import { cleanupOutdatedCaches } from "#utils/cleanupOutdatedCaches.js";
9
+ import { clientsClaim } from "#utils/clientsClaim.js";
10
+ import { dontWaitFor } from "#utils/dontWaitFor.js";
11
+ import { executeQuotaErrorCallbacks } from "#utils/executeQuotaErrorCallbacks.js";
12
+ import { getFriendlyURL } from "#utils/getFriendlyURL.js";
13
+ import { logger } from "#utils/logger.js";
14
+ import { resultingClientExists } from "#utils/resultingClientExists.js";
15
+ import { timeout } from "#utils/timeout.js";
16
+ import { waitUntil } from "#utils/waitUntil.js";
17
17
 
18
18
  // Serwist's internal functions, classes, variables, and more. Feel free to use them,
19
19
  // but they are not documented. Note: they do follow semver.