@serwist/sw 9.0.0-preview.21 → 9.0.0-preview.24

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 (249) hide show
  1. package/dist/index.d.ts +4 -11
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +2 -156
  4. package/package.json +5 -40
  5. package/src/index.ts +5 -22
  6. package/README.md +0 -1
  7. package/dist/abstractions/Serwist.d.ts +0 -82
  8. package/dist/abstractions/Serwist.d.ts.map +0 -1
  9. package/dist/abstractions/disableDevLogs.d.ts +0 -7
  10. package/dist/abstractions/disableDevLogs.d.ts.map +0 -1
  11. package/dist/abstractions/fallbacks.d.ts +0 -39
  12. package/dist/abstractions/fallbacks.d.ts.map +0 -1
  13. package/dist/abstractions/handlePrecaching.d.ts +0 -39
  14. package/dist/abstractions/handlePrecaching.d.ts.map +0 -1
  15. package/dist/abstractions/installSerwist.d.ts +0 -15
  16. package/dist/abstractions/installSerwist.d.ts.map +0 -1
  17. package/dist/abstractions/navigationPreload.d.ts +0 -20
  18. package/dist/abstractions/navigationPreload.d.ts.map +0 -1
  19. package/dist/abstractions/registerRuntimeCaching.d.ts +0 -11
  20. package/dist/abstractions/registerRuntimeCaching.d.ts.map +0 -1
  21. package/dist/abstractions/types.d.ts +0 -29
  22. package/dist/abstractions/types.d.ts.map +0 -1
  23. package/dist/chunks/NavigationRoute.js +0 -54
  24. package/dist/chunks/NetworkOnly.js +0 -193
  25. package/dist/chunks/PrecacheFallbackPlugin.js +0 -573
  26. package/dist/chunks/Strategy.js +0 -410
  27. package/dist/chunks/precacheAndRoute.js +0 -113
  28. package/dist/chunks/registerRoute.js +0 -7
  29. package/dist/chunks/singletonPrecacheController.js +0 -433
  30. package/dist/chunks/singletonRouter.js +0 -435
  31. package/dist/index.plugins.d.ts +0 -41
  32. package/dist/index.plugins.d.ts.map +0 -1
  33. package/dist/index.plugins.js +0 -671
  34. package/dist/index.precaching.d.ts +0 -25
  35. package/dist/index.precaching.d.ts.map +0 -1
  36. package/dist/index.precaching.js +0 -24
  37. package/dist/index.routing.d.ts +0 -15
  38. package/dist/index.routing.d.ts.map +0 -1
  39. package/dist/index.routing.js +0 -19
  40. package/dist/index.strategies.d.ts +0 -22
  41. package/dist/index.strategies.d.ts.map +0 -1
  42. package/dist/index.strategies.js +0 -146
  43. package/dist/plugins/backgroundSync/BackgroundSyncPlugin.d.ts +0 -23
  44. package/dist/plugins/backgroundSync/BackgroundSyncPlugin.d.ts.map +0 -1
  45. package/dist/plugins/backgroundSync/Queue.d.ts +0 -166
  46. package/dist/plugins/backgroundSync/Queue.d.ts.map +0 -1
  47. package/dist/plugins/backgroundSync/QueueDb.d.ts +0 -90
  48. package/dist/plugins/backgroundSync/QueueDb.d.ts.map +0 -1
  49. package/dist/plugins/backgroundSync/QueueStore.d.ts +0 -75
  50. package/dist/plugins/backgroundSync/QueueStore.d.ts.map +0 -1
  51. package/dist/plugins/backgroundSync/StorableRequest.d.ts +0 -51
  52. package/dist/plugins/backgroundSync/StorableRequest.d.ts.map +0 -1
  53. package/dist/plugins/broadcastUpdate/BroadcastCacheUpdate.d.ts +0 -45
  54. package/dist/plugins/broadcastUpdate/BroadcastCacheUpdate.d.ts.map +0 -1
  55. package/dist/plugins/broadcastUpdate/BroadcastUpdatePlugin.d.ts +0 -27
  56. package/dist/plugins/broadcastUpdate/BroadcastUpdatePlugin.d.ts.map +0 -1
  57. package/dist/plugins/broadcastUpdate/constants.d.ts +0 -5
  58. package/dist/plugins/broadcastUpdate/constants.d.ts.map +0 -1
  59. package/dist/plugins/broadcastUpdate/responsesAreSame.d.ts +0 -11
  60. package/dist/plugins/broadcastUpdate/responsesAreSame.d.ts.map +0 -1
  61. package/dist/plugins/broadcastUpdate/types.d.ts +0 -34
  62. package/dist/plugins/broadcastUpdate/types.d.ts.map +0 -1
  63. package/dist/plugins/cacheableResponse/CacheableResponse.d.ts +0 -40
  64. package/dist/plugins/cacheableResponse/CacheableResponse.d.ts.map +0 -1
  65. package/dist/plugins/cacheableResponse/CacheableResponsePlugin.d.ts +0 -27
  66. package/dist/plugins/cacheableResponse/CacheableResponsePlugin.d.ts.map +0 -1
  67. package/dist/plugins/expiration/CacheExpiration.d.ts +0 -66
  68. package/dist/plugins/expiration/CacheExpiration.d.ts.map +0 -1
  69. package/dist/plugins/expiration/ExpirationPlugin.d.ts +0 -116
  70. package/dist/plugins/expiration/ExpirationPlugin.d.ts.map +0 -1
  71. package/dist/plugins/expiration/models/CacheTimestampsModel.d.ts +0 -73
  72. package/dist/plugins/expiration/models/CacheTimestampsModel.d.ts.map +0 -1
  73. package/dist/plugins/googleAnalytics/constants.d.ts +0 -10
  74. package/dist/plugins/googleAnalytics/constants.d.ts.map +0 -1
  75. package/dist/plugins/googleAnalytics/initialize.d.ts +0 -34
  76. package/dist/plugins/googleAnalytics/initialize.d.ts.map +0 -1
  77. package/dist/plugins/precaching/PrecacheFallbackPlugin.d.ts +0 -54
  78. package/dist/plugins/precaching/PrecacheFallbackPlugin.d.ts.map +0 -1
  79. package/dist/plugins/rangeRequests/RangeRequestsPlugin.d.ts +0 -19
  80. package/dist/plugins/rangeRequests/RangeRequestsPlugin.d.ts.map +0 -1
  81. package/dist/plugins/rangeRequests/createPartialResponse.d.ts +0 -18
  82. package/dist/plugins/rangeRequests/createPartialResponse.d.ts.map +0 -1
  83. package/dist/plugins/rangeRequests/utils/calculateEffectiveBoundaries.d.ts +0 -14
  84. package/dist/plugins/rangeRequests/utils/calculateEffectiveBoundaries.d.ts.map +0 -1
  85. package/dist/plugins/rangeRequests/utils/parseRangeHeader.d.ts +0 -12
  86. package/dist/plugins/rangeRequests/utils/parseRangeHeader.d.ts.map +0 -1
  87. package/dist/precaching/PrecacheController.d.ts +0 -145
  88. package/dist/precaching/PrecacheController.d.ts.map +0 -1
  89. package/dist/precaching/PrecacheRoute.d.ts +0 -20
  90. package/dist/precaching/PrecacheRoute.d.ts.map +0 -1
  91. package/dist/precaching/PrecacheStrategy.d.ts +0 -68
  92. package/dist/precaching/PrecacheStrategy.d.ts.map +0 -1
  93. package/dist/precaching/addPlugins.d.ts +0 -8
  94. package/dist/precaching/addPlugins.d.ts.map +0 -1
  95. package/dist/precaching/addRoute.d.ts +0 -15
  96. package/dist/precaching/addRoute.d.ts.map +0 -1
  97. package/dist/precaching/cleanupOutdatedCaches.d.ts +0 -6
  98. package/dist/precaching/cleanupOutdatedCaches.d.ts.map +0 -1
  99. package/dist/precaching/createHandlerBoundToURL.d.ts +0 -17
  100. package/dist/precaching/createHandlerBoundToURL.d.ts.map +0 -1
  101. package/dist/precaching/getCacheKeyForURL.d.ts +0 -20
  102. package/dist/precaching/getCacheKeyForURL.d.ts.map +0 -1
  103. package/dist/precaching/matchPrecache.d.ts +0 -14
  104. package/dist/precaching/matchPrecache.d.ts.map +0 -1
  105. package/dist/precaching/precache.d.ts +0 -19
  106. package/dist/precaching/precache.d.ts.map +0 -1
  107. package/dist/precaching/precacheAndRoute.d.ts +0 -14
  108. package/dist/precaching/precacheAndRoute.d.ts.map +0 -1
  109. package/dist/precaching/singletonPrecacheController.d.ts +0 -38
  110. package/dist/precaching/singletonPrecacheController.d.ts.map +0 -1
  111. package/dist/precaching/types.d.ts +0 -37
  112. package/dist/precaching/types.d.ts.map +0 -1
  113. package/dist/precaching/utils/PrecacheCacheKeyPlugin.d.ts +0 -17
  114. package/dist/precaching/utils/PrecacheCacheKeyPlugin.d.ts.map +0 -1
  115. package/dist/precaching/utils/PrecacheInstallReportPlugin.d.ts +0 -15
  116. package/dist/precaching/utils/PrecacheInstallReportPlugin.d.ts.map +0 -1
  117. package/dist/precaching/utils/createCacheKey.d.ts +0 -16
  118. package/dist/precaching/utils/createCacheKey.d.ts.map +0 -1
  119. package/dist/precaching/utils/deleteOutdatedCaches.d.ts +0 -18
  120. package/dist/precaching/utils/deleteOutdatedCaches.d.ts.map +0 -1
  121. package/dist/precaching/utils/generateURLVariations.d.ts +0 -12
  122. package/dist/precaching/utils/generateURLVariations.d.ts.map +0 -1
  123. package/dist/precaching/utils/getCacheKeyForURL.d.ts +0 -14
  124. package/dist/precaching/utils/getCacheKeyForURL.d.ts.map +0 -1
  125. package/dist/precaching/utils/printCleanupDetails.d.ts +0 -6
  126. package/dist/precaching/utils/printCleanupDetails.d.ts.map +0 -1
  127. package/dist/precaching/utils/printInstallDetails.d.ts +0 -7
  128. package/dist/precaching/utils/printInstallDetails.d.ts.map +0 -1
  129. package/dist/precaching/utils/removeIgnoredSearchParams.d.ts +0 -12
  130. package/dist/precaching/utils/removeIgnoredSearchParams.d.ts.map +0 -1
  131. package/dist/routing/NavigationRoute.d.ts +0 -57
  132. package/dist/routing/NavigationRoute.d.ts.map +0 -1
  133. package/dist/routing/RegExpRoute.d.ts +0 -24
  134. package/dist/routing/RegExpRoute.d.ts.map +0 -1
  135. package/dist/routing/Route.d.ts +0 -33
  136. package/dist/routing/Route.d.ts.map +0 -1
  137. package/dist/routing/Router.d.ts +0 -150
  138. package/dist/routing/Router.d.ts.map +0 -1
  139. package/dist/routing/parseRoute.d.ts +0 -16
  140. package/dist/routing/parseRoute.d.ts.map +0 -1
  141. package/dist/routing/registerRoute.d.ts +0 -15
  142. package/dist/routing/registerRoute.d.ts.map +0 -1
  143. package/dist/routing/setCatchHandler.d.ts +0 -9
  144. package/dist/routing/setCatchHandler.d.ts.map +0 -1
  145. package/dist/routing/setDefaultHandler.d.ts +0 -12
  146. package/dist/routing/setDefaultHandler.d.ts.map +0 -1
  147. package/dist/routing/singletonRouter.d.ts +0 -47
  148. package/dist/routing/singletonRouter.d.ts.map +0 -1
  149. package/dist/routing/unregisterRoute.d.ts +0 -8
  150. package/dist/routing/unregisterRoute.d.ts.map +0 -1
  151. package/dist/routing/utils/constants.d.ts +0 -15
  152. package/dist/routing/utils/constants.d.ts.map +0 -1
  153. package/dist/routing/utils/normalizeHandler.d.ts +0 -10
  154. package/dist/routing/utils/normalizeHandler.d.ts.map +0 -1
  155. package/dist/strategies/CacheFirst.d.ts +0 -23
  156. package/dist/strategies/CacheFirst.d.ts.map +0 -1
  157. package/dist/strategies/CacheOnly.d.ts +0 -20
  158. package/dist/strategies/CacheOnly.d.ts.map +0 -1
  159. package/dist/strategies/NetworkFirst.d.ts +0 -61
  160. package/dist/strategies/NetworkFirst.d.ts.map +0 -1
  161. package/dist/strategies/NetworkOnly.d.ts +0 -32
  162. package/dist/strategies/NetworkOnly.d.ts.map +0 -1
  163. package/dist/strategies/StaleWhileRevalidate.d.ts +0 -35
  164. package/dist/strategies/StaleWhileRevalidate.d.ts.map +0 -1
  165. package/dist/strategies/Strategy.d.ts +0 -83
  166. package/dist/strategies/Strategy.d.ts.map +0 -1
  167. package/dist/strategies/StrategyHandler.d.ts +0 -189
  168. package/dist/strategies/StrategyHandler.d.ts.map +0 -1
  169. package/dist/strategies/plugins/cacheOkAndOpaquePlugin.d.ts +0 -3
  170. package/dist/strategies/plugins/cacheOkAndOpaquePlugin.d.ts.map +0 -1
  171. package/dist/strategies/utils/messages.d.ts +0 -5
  172. package/dist/strategies/utils/messages.d.ts.map +0 -1
  173. package/src/abstractions/Serwist.ts +0 -177
  174. package/src/abstractions/disableDevLogs.ts +0 -10
  175. package/src/abstractions/fallbacks.ts +0 -65
  176. package/src/abstractions/handlePrecaching.ts +0 -65
  177. package/src/abstractions/installSerwist.ts +0 -28
  178. package/src/abstractions/navigationPreload.ts +0 -64
  179. package/src/abstractions/registerRuntimeCaching.ts +0 -17
  180. package/src/abstractions/types.ts +0 -29
  181. package/src/index.plugins.ts +0 -95
  182. package/src/index.precaching.ts +0 -41
  183. package/src/index.routing.ts +0 -28
  184. package/src/index.strategies.ts +0 -26
  185. package/src/plugins/backgroundSync/BackgroundSyncPlugin.ts +0 -39
  186. package/src/plugins/backgroundSync/Queue.ts +0 -438
  187. package/src/plugins/backgroundSync/QueueDb.ts +0 -176
  188. package/src/plugins/backgroundSync/QueueStore.ts +0 -161
  189. package/src/plugins/backgroundSync/StorableRequest.ts +0 -142
  190. package/src/plugins/broadcastUpdate/BroadcastCacheUpdate.ts +0 -159
  191. package/src/plugins/broadcastUpdate/BroadcastUpdatePlugin.ts +0 -43
  192. package/src/plugins/broadcastUpdate/constants.ts +0 -12
  193. package/src/plugins/broadcastUpdate/responsesAreSame.ts +0 -48
  194. package/src/plugins/broadcastUpdate/types.ts +0 -37
  195. package/src/plugins/cacheableResponse/CacheableResponse.ts +0 -141
  196. package/src/plugins/cacheableResponse/CacheableResponsePlugin.ts +0 -46
  197. package/src/plugins/expiration/CacheExpiration.ts +0 -192
  198. package/src/plugins/expiration/ExpirationPlugin.ts +0 -297
  199. package/src/plugins/expiration/models/CacheTimestampsModel.ts +0 -184
  200. package/src/plugins/googleAnalytics/constants.ts +0 -22
  201. package/src/plugins/googleAnalytics/initialize.ts +0 -213
  202. package/src/plugins/precaching/PrecacheFallbackPlugin.ts +0 -86
  203. package/src/plugins/rangeRequests/RangeRequestsPlugin.ts +0 -39
  204. package/src/plugins/rangeRequests/createPartialResponse.ts +0 -92
  205. package/src/plugins/rangeRequests/utils/calculateEffectiveBoundaries.ts +0 -58
  206. package/src/plugins/rangeRequests/utils/parseRangeHeader.ts +0 -54
  207. package/src/precaching/PrecacheController.ts +0 -332
  208. package/src/precaching/PrecacheRoute.ts +0 -50
  209. package/src/precaching/PrecacheStrategy.ts +0 -238
  210. package/src/precaching/addPlugins.ts +0 -21
  211. package/src/precaching/addRoute.ts +0 -30
  212. package/src/precaching/cleanupOutdatedCaches.ts +0 -33
  213. package/src/precaching/createHandlerBoundToURL.ts +0 -30
  214. package/src/precaching/getCacheKeyForURL.ts +0 -33
  215. package/src/precaching/matchPrecache.ts +0 -25
  216. package/src/precaching/precache.ts +0 -31
  217. package/src/precaching/precacheAndRoute.ts +0 -27
  218. package/src/precaching/singletonPrecacheController.ts +0 -57
  219. package/src/precaching/types.ts +0 -46
  220. package/src/precaching/utils/PrecacheCacheKeyPlugin.ts +0 -36
  221. package/src/precaching/utils/PrecacheInstallReportPlugin.ts +0 -49
  222. package/src/precaching/utils/createCacheKey.ts +0 -68
  223. package/src/precaching/utils/deleteOutdatedCaches.ts +0 -40
  224. package/src/precaching/utils/generateURLVariations.ts +0 -55
  225. package/src/precaching/utils/getCacheKeyForURL.ts +0 -36
  226. package/src/precaching/utils/printCleanupDetails.ts +0 -38
  227. package/src/precaching/utils/printInstallDetails.ts +0 -53
  228. package/src/precaching/utils/removeIgnoredSearchParams.ts +0 -29
  229. package/src/routing/NavigationRoute.ts +0 -119
  230. package/src/routing/RegExpRoute.ts +0 -74
  231. package/src/routing/Route.ts +0 -68
  232. package/src/routing/Router.ts +0 -481
  233. package/src/routing/parseRoute.ts +0 -78
  234. package/src/routing/registerRoute.ts +0 -27
  235. package/src/routing/setCatchHandler.ts +0 -21
  236. package/src/routing/setDefaultHandler.ts +0 -24
  237. package/src/routing/singletonRouter.ts +0 -76
  238. package/src/routing/unregisterRoute.ts +0 -11
  239. package/src/routing/utils/constants.ts +0 -24
  240. package/src/routing/utils/normalizeHandler.ts +0 -40
  241. package/src/strategies/CacheFirst.ts +0 -87
  242. package/src/strategies/CacheOnly.ts +0 -58
  243. package/src/strategies/NetworkFirst.ts +0 -228
  244. package/src/strategies/NetworkOnly.ts +0 -96
  245. package/src/strategies/StaleWhileRevalidate.ts +0 -109
  246. package/src/strategies/Strategy.ts +0 -202
  247. package/src/strategies/StrategyHandler.ts +0 -557
  248. package/src/strategies/plugins/cacheOkAndOpaquePlugin.ts +0 -26
  249. package/src/strategies/utils/messages.ts +0 -20
@@ -1,141 +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 { assert, SerwistError, getFriendlyURL, logger } from "@serwist/core/internal";
10
-
11
- export interface CacheableResponseOptions {
12
- /**
13
- * One or more status codes that a `Response` can have to be considered cacheable.
14
- */
15
- statuses?: number[];
16
- /**
17
- * A mapping of header names and expected values that a `Response` can have and be
18
- * considered cacheable. If multiple headers are provided, only one needs to be present.
19
- */
20
- headers?: HeadersInit;
21
- }
22
-
23
- /**
24
- * Allows you to set up rules determining what status codes and/or headers need
25
- * to be present in order for a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
26
- * to be considered cacheable.
27
- */
28
- export class CacheableResponse {
29
- private readonly _statuses?: CacheableResponseOptions["statuses"];
30
- private readonly _headers?: Headers;
31
-
32
- /**
33
- * To construct a new CacheableResponse instance you must provide at least
34
- * one of the `config` properties.
35
- *
36
- * If both `statuses` and `headers` are specified, then both conditions must
37
- * be met for the `Response` to be considered cacheable.
38
- *
39
- * @param config
40
- */
41
- constructor(config: CacheableResponseOptions = {}) {
42
- if (process.env.NODE_ENV !== "production") {
43
- if (!(config.statuses || config.headers)) {
44
- throw new SerwistError("statuses-or-headers-required", {
45
- moduleName: "@serwist/cacheable-response",
46
- className: "CacheableResponse",
47
- funcName: "constructor",
48
- });
49
- }
50
-
51
- if (config.statuses) {
52
- assert!.isArray(config.statuses, {
53
- moduleName: "@serwist/cacheable-response",
54
- className: "CacheableResponse",
55
- funcName: "constructor",
56
- paramName: "config.statuses",
57
- });
58
- }
59
-
60
- if (config.headers) {
61
- assert!.isType(config.headers, "object", {
62
- moduleName: "@serwist/cacheable-response",
63
- className: "CacheableResponse",
64
- funcName: "constructor",
65
- paramName: "config.headers",
66
- });
67
- }
68
- }
69
-
70
- this._statuses = config.statuses;
71
- if (config.headers) {
72
- this._headers = new Headers(config.headers);
73
- }
74
- }
75
-
76
- /**
77
- * Checks a response to see whether it's cacheable or not.
78
- *
79
- * @param response The response whose cacheability is being
80
- * checked.
81
- * @returns `true` if the `Response` is cacheable, and `false`
82
- * otherwise.
83
- */
84
- isResponseCacheable(response: Response): boolean {
85
- if (process.env.NODE_ENV !== "production") {
86
- assert!.isInstance(response, Response, {
87
- moduleName: "@serwist/cacheable-response",
88
- className: "CacheableResponse",
89
- funcName: "isResponseCacheable",
90
- paramName: "response",
91
- });
92
- }
93
-
94
- let cacheable = true;
95
-
96
- if (this._statuses) {
97
- cacheable = this._statuses.includes(response.status);
98
- }
99
-
100
- if (this._headers && cacheable) {
101
- for (const [headerName, headerValue] of this._headers.entries()) {
102
- if (response.headers.get(headerName) !== headerValue) {
103
- cacheable = false;
104
- break;
105
- }
106
- }
107
- }
108
-
109
- if (process.env.NODE_ENV !== "production") {
110
- if (!cacheable) {
111
- logger.groupCollapsed(
112
- `The request for '${getFriendlyURL(response.url)}' returned a response that does not meet the criteria for being cached.`,
113
- );
114
-
115
- logger.groupCollapsed("View cacheability criteria here.");
116
- logger.log(`Cacheable statuses: ${JSON.stringify(this._statuses)}`);
117
- logger.log(`Cacheable headers: ${JSON.stringify(this._headers, null, 2)}`);
118
- logger.groupEnd();
119
-
120
- const logFriendlyHeaders: { [key: string]: string } = {};
121
- response.headers.forEach((value, key) => {
122
- logFriendlyHeaders[key] = value;
123
- });
124
-
125
- logger.groupCollapsed("View response status and headers here.");
126
- logger.log(`Response status: ${response.status}`);
127
- logger.log(`Response headers: ${JSON.stringify(logFriendlyHeaders, null, 2)}`);
128
- logger.groupEnd();
129
-
130
- logger.groupCollapsed("View full response details here.");
131
- logger.log(response.headers);
132
- logger.log(response);
133
- logger.groupEnd();
134
-
135
- logger.groupEnd();
136
- }
137
- }
138
-
139
- return cacheable;
140
- }
141
- }
@@ -1,46 +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 { SerwistPlugin } from "@serwist/core";
10
-
11
- import type { CacheableResponseOptions } from "./CacheableResponse.js";
12
- import { CacheableResponse } from "./CacheableResponse.js";
13
-
14
- /**
15
- * A class implementing the `cacheWillUpdate` lifecycle callback. This makes it
16
- * easier to add in cacheability checks to requests made via Serwist's built-in
17
- * strategies.
18
- */
19
- export class CacheableResponsePlugin implements SerwistPlugin {
20
- private readonly _cacheableResponse: CacheableResponse;
21
-
22
- /**
23
- * To construct a new CacheableResponsePlugin instance you must provide at
24
- * least one of the `config` properties.
25
- *
26
- * If both `statuses` and `headers` are specified, then both conditions must
27
- * be met for the `Response` to be considered cacheable.
28
- *
29
- * @param config
30
- */
31
- constructor(config: CacheableResponseOptions) {
32
- this._cacheableResponse = new CacheableResponse(config);
33
- }
34
-
35
- /**
36
- * @param options
37
- * @returns
38
- * @private
39
- */
40
- cacheWillUpdate: SerwistPlugin["cacheWillUpdate"] = async ({ response }) => {
41
- if (this._cacheableResponse.isResponseCacheable(response)) {
42
- return response;
43
- }
44
- return null;
45
- };
46
- }
@@ -1,192 +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 { assert, SerwistError, logger } from "@serwist/core/internal";
10
-
11
- import { CacheTimestampsModel } from "./models/CacheTimestampsModel.js";
12
-
13
- interface CacheExpirationConfig {
14
- /**
15
- * The maximum number of entries to cache. Entries used the least will
16
- * be removed as the maximum is reached.
17
- */
18
- maxEntries?: number;
19
- /**
20
- * The maximum age of an entry before it's treated as stale and removed.
21
- */
22
- maxAgeSeconds?: number;
23
- /**
24
- * The [`CacheQueryOptions`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete#Parameters)
25
- * that will be used when calling `delete()` on the cache.
26
- */
27
- matchOptions?: CacheQueryOptions;
28
- }
29
-
30
- /**
31
- * Allows you to expires cached responses based on age or maximum number of entries.
32
- * @see https://serwist.pages.dev/docs/expiration/cache-expiration
33
- */
34
- export class CacheExpiration {
35
- private _isRunning = false;
36
- private _rerunRequested = false;
37
- private readonly _maxEntries?: number;
38
- private readonly _maxAgeSeconds?: number;
39
- private readonly _matchOptions?: CacheQueryOptions;
40
- private readonly _cacheName: string;
41
- private readonly _timestampModel: CacheTimestampsModel;
42
-
43
- /**
44
- * To construct a new CacheExpiration instance you must provide at least
45
- * one of the `config` properties.
46
- *
47
- * @param cacheName Name of the cache to apply restrictions to.
48
- * @param config
49
- */
50
- constructor(cacheName: string, config: CacheExpirationConfig = {}) {
51
- if (process.env.NODE_ENV !== "production") {
52
- assert!.isType(cacheName, "string", {
53
- moduleName: "@serwist/expiration",
54
- className: "CacheExpiration",
55
- funcName: "constructor",
56
- paramName: "cacheName",
57
- });
58
-
59
- if (!(config.maxEntries || config.maxAgeSeconds)) {
60
- throw new SerwistError("max-entries-or-age-required", {
61
- moduleName: "@serwist/expiration",
62
- className: "CacheExpiration",
63
- funcName: "constructor",
64
- });
65
- }
66
-
67
- if (config.maxEntries) {
68
- assert!.isType(config.maxEntries, "number", {
69
- moduleName: "@serwist/expiration",
70
- className: "CacheExpiration",
71
- funcName: "constructor",
72
- paramName: "config.maxEntries",
73
- });
74
- }
75
-
76
- if (config.maxAgeSeconds) {
77
- assert!.isType(config.maxAgeSeconds, "number", {
78
- moduleName: "@serwist/expiration",
79
- className: "CacheExpiration",
80
- funcName: "constructor",
81
- paramName: "config.maxAgeSeconds",
82
- });
83
- }
84
- }
85
-
86
- this._maxEntries = config.maxEntries;
87
- this._maxAgeSeconds = config.maxAgeSeconds;
88
- this._matchOptions = config.matchOptions;
89
- this._cacheName = cacheName;
90
- this._timestampModel = new CacheTimestampsModel(cacheName);
91
- }
92
-
93
- /**
94
- * Expires entries for the given cache and given criteria.
95
- */
96
- async expireEntries(): Promise<void> {
97
- if (this._isRunning) {
98
- this._rerunRequested = true;
99
- return;
100
- }
101
- this._isRunning = true;
102
-
103
- const minTimestamp = this._maxAgeSeconds ? Date.now() - this._maxAgeSeconds * 1000 : 0;
104
-
105
- const urlsExpired = await this._timestampModel.expireEntries(minTimestamp, this._maxEntries);
106
-
107
- // Delete URLs from the cache
108
- const cache = await self.caches.open(this._cacheName);
109
- for (const url of urlsExpired) {
110
- await cache.delete(url, this._matchOptions);
111
- }
112
-
113
- if (process.env.NODE_ENV !== "production") {
114
- if (urlsExpired.length > 0) {
115
- logger.groupCollapsed(
116
- `Expired ${urlsExpired.length} ` +
117
- `${urlsExpired.length === 1 ? "entry" : "entries"} and removed ` +
118
- `${urlsExpired.length === 1 ? "it" : "them"} from the ` +
119
- `'${this._cacheName}' cache.`,
120
- );
121
- logger.log(`Expired the following ${urlsExpired.length === 1 ? "URL" : "URLs"}:`);
122
- for (const url of urlsExpired) {
123
- logger.log(` ${url}`);
124
- }
125
- logger.groupEnd();
126
- } else {
127
- logger.debug("Cache expiration ran and found no entries to remove.");
128
- }
129
- }
130
-
131
- this._isRunning = false;
132
- if (this._rerunRequested) {
133
- this._rerunRequested = false;
134
- void this.expireEntries();
135
- }
136
- }
137
-
138
- /**
139
- * Updates the timestamp for the given URL, allowing it to be correctly
140
- * tracked by the class.
141
- *
142
- * @param url
143
- */
144
- async updateTimestamp(url: string): Promise<void> {
145
- if (process.env.NODE_ENV !== "production") {
146
- assert!.isType(url, "string", {
147
- moduleName: "@serwist/expiration",
148
- className: "CacheExpiration",
149
- funcName: "updateTimestamp",
150
- paramName: "url",
151
- });
152
- }
153
-
154
- await this._timestampModel.setTimestamp(url, Date.now());
155
- }
156
-
157
- /**
158
- * Checks if a URL has expired or not before it's used.
159
- *
160
- * This looks the timestamp up in IndexedDB and can be slow.
161
- *
162
- * Note: This method does not remove an expired entry, call
163
- * `expireEntries()` to remove such entries instead.
164
- *
165
- * @param url
166
- * @returns
167
- */
168
- async isURLExpired(url: string): Promise<boolean> {
169
- if (!this._maxAgeSeconds) {
170
- if (process.env.NODE_ENV !== "production") {
171
- throw new SerwistError("expired-test-without-max-age", {
172
- methodName: "isURLExpired",
173
- paramName: "maxAgeSeconds",
174
- });
175
- }
176
- return false;
177
- }
178
- const timestamp = await this._timestampModel.getTimestamp(url);
179
- const expireOlderThan = Date.now() - this._maxAgeSeconds * 1000;
180
- return timestamp !== undefined ? timestamp < expireOlderThan : true;
181
- }
182
-
183
- /**
184
- * Removes the IndexedDB used to keep track of cache expiration metadata.
185
- */
186
- async delete(): Promise<void> {
187
- // Make sure we don't attempt another rerun if we're called in the middle of
188
- // a cache expiration.
189
- this._rerunRequested = false;
190
- await this._timestampModel.expireEntries(Number.POSITIVE_INFINITY); // Expires all.
191
- }
192
- }
@@ -1,297 +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 { CacheDidUpdateCallbackParam, CachedResponseWillBeUsedCallbackParam, SerwistPlugin } from "@serwist/core";
10
- import { registerQuotaErrorCallback } from "@serwist/core";
11
- import { assert, SerwistError, getFriendlyURL, logger, privateCacheNames } from "@serwist/core/internal";
12
-
13
- import { CacheExpiration } from "./CacheExpiration.js";
14
-
15
- export interface ExpirationPluginOptions {
16
- /**
17
- * The maximum number of entries to cache. Entries used the least will be removed
18
- * as the maximum is reached.
19
- */
20
- maxEntries?: number;
21
- /**
22
- * The maximum number of seconds before an entry is treated as stale and removed.
23
- */
24
- maxAgeSeconds?: number;
25
- /**
26
- * Determines whether `maxAgeSeconds` should be calculated from when an
27
- * entry was last fetched or when it was last used.
28
- *
29
- * @default "last-fetched"
30
- */
31
- maxAgeFrom?: "last-fetched" | "last-used";
32
- /**
33
- * The [`CacheQueryOptions`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete#Parameters)
34
- * that will be used when calling `delete()` on the cache.
35
- */
36
- matchOptions?: CacheQueryOptions;
37
- /**
38
- * Whether to opt this cache into automatic deletion if the available storage quota has been exceeded.
39
- */
40
- purgeOnQuotaError?: boolean;
41
- }
42
-
43
- /**
44
- * This plugin can be used in a `@serwist/strategies` Strategy to regularly enforce a
45
- * limit on the age and/or the number of cached requests.
46
- *
47
- * It can only be used with Strategy instances that have a custom `cacheName` property set.
48
- * In other words, it can't be used to expire entries in strategies that use the default runtime
49
- * cache name.
50
- *
51
- * Whenever a cached response is used or updated, this plugin will look
52
- * at the associated cache and remove any old or extra responses.
53
- *
54
- * When using `maxAgeSeconds`, responses may be used *once* after expiring
55
- * because the expiration clean up will not have occurred until *after* the
56
- * cached response has been used. If the response has a "Date" header, then a lightweight expiration
57
- * check is performed, and the response will not be used immediately.
58
- *
59
- * When using `maxEntries`, the least recently requested entry will be removed
60
- * from the cache.
61
- *
62
- * @see https://serwist.pages.dev/docs/expiration/expiration-plugin
63
- */
64
- export class ExpirationPlugin implements SerwistPlugin {
65
- private readonly _config: ExpirationPluginOptions;
66
- private _cacheExpirations: Map<string, CacheExpiration>;
67
-
68
- /**
69
- * @param config
70
- */
71
- constructor(config: ExpirationPluginOptions = {}) {
72
- if (process.env.NODE_ENV !== "production") {
73
- if (!(config.maxEntries || config.maxAgeSeconds)) {
74
- throw new SerwistError("max-entries-or-age-required", {
75
- moduleName: "@serwist/expiration",
76
- className: "ExpirationPlugin",
77
- funcName: "constructor",
78
- });
79
- }
80
-
81
- if (config.maxEntries) {
82
- assert!.isType(config.maxEntries, "number", {
83
- moduleName: "@serwist/expiration",
84
- className: "ExpirationPlugin",
85
- funcName: "constructor",
86
- paramName: "config.maxEntries",
87
- });
88
- }
89
-
90
- if (config.maxAgeSeconds) {
91
- assert!.isType(config.maxAgeSeconds, "number", {
92
- moduleName: "@serwist/expiration",
93
- className: "ExpirationPlugin",
94
- funcName: "constructor",
95
- paramName: "config.maxAgeSeconds",
96
- });
97
- }
98
-
99
- if (config.maxAgeFrom) {
100
- assert!.isType(config.maxAgeFrom, "string", {
101
- moduleName: "@serwist/expiration",
102
- className: "ExpirationPlugin",
103
- funcName: "constructor",
104
- paramName: "config.maxAgeFrom",
105
- });
106
- }
107
- }
108
-
109
- this._config = config;
110
- this._cacheExpirations = new Map();
111
-
112
- if (!this._config.maxAgeFrom) {
113
- this._config.maxAgeFrom = "last-fetched";
114
- }
115
-
116
- if (this._config.purgeOnQuotaError) {
117
- registerQuotaErrorCallback(() => this.deleteCacheAndMetadata());
118
- }
119
- }
120
-
121
- /**
122
- * A simple helper method to return a CacheExpiration instance for a given
123
- * cache name.
124
- *
125
- * @param cacheName
126
- * @returns
127
- * @private
128
- */
129
- private _getCacheExpiration(cacheName: string): CacheExpiration {
130
- if (cacheName === privateCacheNames.getRuntimeName()) {
131
- throw new SerwistError("expire-custom-caches-only");
132
- }
133
-
134
- let cacheExpiration = this._cacheExpirations.get(cacheName);
135
- if (!cacheExpiration) {
136
- cacheExpiration = new CacheExpiration(cacheName, this._config);
137
- this._cacheExpirations.set(cacheName, cacheExpiration);
138
- }
139
- return cacheExpiration;
140
- }
141
-
142
- /**
143
- * A "lifecycle" callback that will be triggered automatically by the
144
- * `@serwist/strategies` handlers when a `Response` is about to be returned
145
- * from a [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache) to
146
- * the handler. It allows the `Response` to be inspected for freshness and
147
- * prevents it from being used if the `Response`'s `Date` header value is
148
- * older than the configured `maxAgeSeconds`.
149
- *
150
- * @param options
151
- * @returns `cachedResponse` if it is fresh and `null` if it is stale or
152
- * not available.
153
- * @private
154
- */
155
- cachedResponseWillBeUsed({ event, cacheName, request, cachedResponse }: CachedResponseWillBeUsedCallbackParam) {
156
- if (!cachedResponse) {
157
- return null;
158
- }
159
-
160
- const isFresh = this._isResponseDateFresh(cachedResponse);
161
-
162
- // Expire entries to ensure that even if the expiration date has
163
- // expired, it'll only be used once.
164
- const cacheExpiration = this._getCacheExpiration(cacheName);
165
-
166
- const isMaxAgeFromLastUsed = this._config.maxAgeFrom === "last-used";
167
-
168
- const done = (async () => {
169
- // Update the metadata for the request URL to the current timestamp.
170
- // Only applies if `maxAgeFrom` is `"last-used"`, since the current
171
- // lifecycle callback is `cachedResponseWillBeUsed`.
172
- // This needs to be called before `expireEntries()` so as to avoid
173
- // this URL being marked as expired.
174
- if (isMaxAgeFromLastUsed) {
175
- await cacheExpiration.updateTimestamp(request.url);
176
- }
177
- await cacheExpiration.expireEntries();
178
- })();
179
- try {
180
- event.waitUntil(done);
181
- } catch (error) {
182
- if (process.env.NODE_ENV !== "production") {
183
- if (event instanceof FetchEvent) {
184
- logger.warn(`Unable to ensure service worker stays alive when updating cache entry for '${getFriendlyURL(event.request.url)}'.`);
185
- }
186
- }
187
- }
188
-
189
- return isFresh ? cachedResponse : null;
190
- }
191
-
192
- /**
193
- * @param cachedResponse
194
- * @returns
195
- * @private
196
- */
197
- private _isResponseDateFresh(cachedResponse: Response): boolean {
198
- const isMaxAgeFromLastUsed = this._config.maxAgeFrom === "last-used";
199
- // If `maxAgeFrom` is `"last-used"`, the `Date` header doesn't really
200
- // matter since it is about when the response was created.
201
- if (isMaxAgeFromLastUsed) {
202
- return true;
203
- }
204
- const now = Date.now();
205
- if (!this._config.maxAgeSeconds) {
206
- return true;
207
- }
208
- // Check if the `Date` header will suffice a quick expiration check.
209
- // See https://github.com/GoogleChromeLabs/sw-toolbox/issues/164 for
210
- // discussion.
211
- const dateHeaderTimestamp = this._getDateHeaderTimestamp(cachedResponse);
212
- if (dateHeaderTimestamp === null) {
213
- // Unable to parse date, so assume it's fresh.
214
- return true;
215
- }
216
- // If we have a valid headerTime, then our response is fresh if the
217
- // headerTime plus maxAgeSeconds is greater than the current time.
218
- return dateHeaderTimestamp >= now - this._config.maxAgeSeconds * 1000;
219
- }
220
-
221
- /**
222
- * Extracts the `Date` header and parse it into an useful value.
223
- *
224
- * @param cachedResponse
225
- * @returns
226
- * @private
227
- */
228
- private _getDateHeaderTimestamp(cachedResponse: Response): number | null {
229
- if (!cachedResponse.headers.has("date")) {
230
- return null;
231
- }
232
-
233
- const dateHeader = cachedResponse.headers.get("date")!;
234
- const parsedDate = new Date(dateHeader);
235
- const headerTime = parsedDate.getTime();
236
-
237
- // If the `Date` header is invalid for some reason, `parsedDate.getTime()`
238
- // will return NaN.
239
- if (Number.isNaN(headerTime)) {
240
- return null;
241
- }
242
-
243
- return headerTime;
244
- }
245
-
246
- /**
247
- * A "lifecycle" callback that will be triggered automatically by the
248
- * `@serwist/strategies` handlers when an entry is added to a cache.
249
- *
250
- * @param options
251
- * @private
252
- */
253
- async cacheDidUpdate({ cacheName, request }: CacheDidUpdateCallbackParam) {
254
- if (process.env.NODE_ENV !== "production") {
255
- assert!.isType(cacheName, "string", {
256
- moduleName: "@serwist/expiration",
257
- className: "Plugin",
258
- funcName: "cacheDidUpdate",
259
- paramName: "cacheName",
260
- });
261
- assert!.isInstance(request, Request, {
262
- moduleName: "@serwist/expiration",
263
- className: "Plugin",
264
- funcName: "cacheDidUpdate",
265
- paramName: "request",
266
- });
267
- }
268
-
269
- const cacheExpiration = this._getCacheExpiration(cacheName);
270
- await cacheExpiration.updateTimestamp(request.url);
271
- await cacheExpiration.expireEntries();
272
- }
273
-
274
- /**
275
- * Deletes the underlying `Cache` instance associated with this instance and the metadata
276
- * from IndexedDB used to keep track of expiration details for each `Cache` instance.
277
- *
278
- * When using cache expiration, calling this method is preferable to calling
279
- * `caches.delete()` directly, since this will ensure that the IndexedDB
280
- * metadata is also cleanly removed and that open IndexedDB instances are deleted.
281
- *
282
- * Note that if you're *not* using cache expiration for a given cache, calling
283
- * `caches.delete()` and passing in the cache's name should be sufficient.
284
- * There is no Serwist-specific method needed for cleanup in that case.
285
- */
286
- async deleteCacheAndMetadata(): Promise<void> {
287
- // Do this one at a time instead of all at once via `Promise.all()` to
288
- // reduce the chance of inconsistency if a promise rejects.
289
- for (const [cacheName, cacheExpiration] of this._cacheExpirations) {
290
- await self.caches.delete(cacheName);
291
- await cacheExpiration.delete();
292
- }
293
-
294
- // Reset this._cacheExpirations to its initial state.
295
- this._cacheExpirations = new Map();
296
- }
297
- }