@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,433 +0,0 @@
1
- import { privateCacheNames, logger, getFriendlyURL, SerwistError, assert, waitUntil } from '@serwist/core/internal';
2
- import { copyResponse } from '@serwist/core';
3
- import { S as Strategy } from './Strategy.js';
4
-
5
- const parallel = async (limit, array, func)=>{
6
- const work = array.map((item, index)=>({
7
- index,
8
- item
9
- }));
10
- const processor = async (res)=>{
11
- const results = [];
12
- while(true){
13
- const next = work.pop();
14
- if (!next) {
15
- return res(results);
16
- }
17
- const result = await func(next.item);
18
- results.push({
19
- result: result,
20
- index: next.index
21
- });
22
- }
23
- };
24
- const queues = Array.from({
25
- length: limit
26
- }, ()=>new Promise(processor));
27
- const results = (await Promise.all(queues)).flat().sort((a, b)=>a.index < b.index ? -1 : 1).map((res)=>res.result);
28
- return results;
29
- };
30
-
31
- class PrecacheStrategy extends Strategy {
32
- _fallbackToNetwork;
33
- static defaultPrecacheCacheabilityPlugin = {
34
- async cacheWillUpdate ({ response }) {
35
- if (!response || response.status >= 400) {
36
- return null;
37
- }
38
- return response;
39
- }
40
- };
41
- static copyRedirectedCacheableResponsesPlugin = {
42
- async cacheWillUpdate ({ response }) {
43
- return response.redirected ? await copyResponse(response) : response;
44
- }
45
- };
46
- constructor(options = {}){
47
- options.cacheName = privateCacheNames.getPrecacheName(options.cacheName);
48
- super(options);
49
- this._fallbackToNetwork = options.fallbackToNetwork === false ? false : true;
50
- this.plugins.push(PrecacheStrategy.copyRedirectedCacheableResponsesPlugin);
51
- }
52
- async _handle(request, handler) {
53
- const response = await handler.cacheMatch(request);
54
- if (response) {
55
- return response;
56
- }
57
- if (handler.event && handler.event.type === "install") {
58
- return await this._handleInstall(request, handler);
59
- }
60
- return await this._handleFetch(request, handler);
61
- }
62
- async _handleFetch(request, handler) {
63
- let response = undefined;
64
- const params = handler.params || {};
65
- if (this._fallbackToNetwork) {
66
- if (process.env.NODE_ENV !== "production") {
67
- logger.warn(`The precached response for ${getFriendlyURL(request.url)} in ${this.cacheName} was not found. Falling back to the network.`);
68
- }
69
- const integrityInManifest = params.integrity;
70
- const integrityInRequest = request.integrity;
71
- const noIntegrityConflict = !integrityInRequest || integrityInRequest === integrityInManifest;
72
- response = await handler.fetch(new Request(request, {
73
- integrity: request.mode !== "no-cors" ? integrityInRequest || integrityInManifest : undefined
74
- }));
75
- if (integrityInManifest && noIntegrityConflict && request.mode !== "no-cors") {
76
- this._useDefaultCacheabilityPluginIfNeeded();
77
- const wasCached = await handler.cachePut(request, response.clone());
78
- if (process.env.NODE_ENV !== "production") {
79
- if (wasCached) {
80
- logger.log(`A response for ${getFriendlyURL(request.url)} was used to "repair" the precache.`);
81
- }
82
- }
83
- }
84
- } else {
85
- throw new SerwistError("missing-precache-entry", {
86
- cacheName: this.cacheName,
87
- url: request.url
88
- });
89
- }
90
- if (process.env.NODE_ENV !== "production") {
91
- const cacheKey = params.cacheKey || await handler.getCacheKey(request, "read");
92
- logger.groupCollapsed(`Precaching is responding to: ${getFriendlyURL(request.url)}`);
93
- logger.log(`Serving the precached url: ${getFriendlyURL(cacheKey instanceof Request ? cacheKey.url : cacheKey)}`);
94
- logger.groupCollapsed("View request details here.");
95
- logger.log(request);
96
- logger.groupEnd();
97
- logger.groupCollapsed("View response details here.");
98
- logger.log(response);
99
- logger.groupEnd();
100
- logger.groupEnd();
101
- }
102
- return response;
103
- }
104
- async _handleInstall(request, handler) {
105
- this._useDefaultCacheabilityPluginIfNeeded();
106
- const response = await handler.fetch(request);
107
- const wasCached = await handler.cachePut(request, response.clone());
108
- if (!wasCached) {
109
- throw new SerwistError("bad-precaching-response", {
110
- url: request.url,
111
- status: response.status
112
- });
113
- }
114
- return response;
115
- }
116
- _useDefaultCacheabilityPluginIfNeeded() {
117
- let defaultPluginIndex = null;
118
- let cacheWillUpdatePluginCount = 0;
119
- for (const [index, plugin] of this.plugins.entries()){
120
- if (plugin === PrecacheStrategy.copyRedirectedCacheableResponsesPlugin) {
121
- continue;
122
- }
123
- if (plugin === PrecacheStrategy.defaultPrecacheCacheabilityPlugin) {
124
- defaultPluginIndex = index;
125
- }
126
- if (plugin.cacheWillUpdate) {
127
- cacheWillUpdatePluginCount++;
128
- }
129
- }
130
- if (cacheWillUpdatePluginCount === 0) {
131
- this.plugins.push(PrecacheStrategy.defaultPrecacheCacheabilityPlugin);
132
- } else if (cacheWillUpdatePluginCount > 1 && defaultPluginIndex !== null) {
133
- this.plugins.splice(defaultPluginIndex, 1);
134
- }
135
- }
136
- }
137
-
138
- class PrecacheCacheKeyPlugin {
139
- _precacheController;
140
- constructor({ precacheController }){
141
- this._precacheController = precacheController;
142
- }
143
- cacheKeyWillBeUsed = async ({ request, params })=>{
144
- const cacheKey = params?.cacheKey || this._precacheController.getCacheKeyForURL(request.url);
145
- return cacheKey ? new Request(cacheKey, {
146
- headers: request.headers
147
- }) : request;
148
- };
149
- }
150
-
151
- class PrecacheInstallReportPlugin {
152
- updatedURLs = [];
153
- notUpdatedURLs = [];
154
- handlerWillStart = async ({ request, state })=>{
155
- if (state) {
156
- state.originalRequest = request;
157
- }
158
- };
159
- cachedResponseWillBeUsed = async ({ event, state, cachedResponse })=>{
160
- if (event.type === "install") {
161
- if (state?.originalRequest && state.originalRequest instanceof Request) {
162
- const url = state.originalRequest.url;
163
- if (cachedResponse) {
164
- this.notUpdatedURLs.push(url);
165
- } else {
166
- this.updatedURLs.push(url);
167
- }
168
- }
169
- }
170
- return cachedResponse;
171
- };
172
- }
173
-
174
- const REVISION_SEARCH_PARAM = "__WB_REVISION__";
175
- function createCacheKey(entry) {
176
- if (!entry) {
177
- throw new SerwistError("add-to-cache-list-unexpected-type", {
178
- entry
179
- });
180
- }
181
- if (typeof entry === "string") {
182
- const urlObject = new URL(entry, location.href);
183
- return {
184
- cacheKey: urlObject.href,
185
- url: urlObject.href
186
- };
187
- }
188
- const { revision, url } = entry;
189
- if (!url) {
190
- throw new SerwistError("add-to-cache-list-unexpected-type", {
191
- entry
192
- });
193
- }
194
- if (!revision) {
195
- const urlObject = new URL(url, location.href);
196
- return {
197
- cacheKey: urlObject.href,
198
- url: urlObject.href
199
- };
200
- }
201
- const cacheKeyURL = new URL(url, location.href);
202
- const originalURL = new URL(url, location.href);
203
- cacheKeyURL.searchParams.set(REVISION_SEARCH_PARAM, revision);
204
- return {
205
- cacheKey: cacheKeyURL.href,
206
- url: originalURL.href
207
- };
208
- }
209
-
210
- const logGroup = (groupTitle, deletedURLs)=>{
211
- logger.groupCollapsed(groupTitle);
212
- for (const url of deletedURLs){
213
- logger.log(url);
214
- }
215
- logger.groupEnd();
216
- };
217
- function printCleanupDetails(deletedURLs) {
218
- const deletionCount = deletedURLs.length;
219
- if (deletionCount > 0) {
220
- logger.groupCollapsed(`During precaching cleanup, ${deletionCount} cached request${deletionCount === 1 ? " was" : "s were"} deleted.`);
221
- logGroup("Deleted Cache Requests", deletedURLs);
222
- logger.groupEnd();
223
- }
224
- }
225
-
226
- function _nestedGroup(groupTitle, urls) {
227
- if (urls.length === 0) {
228
- return;
229
- }
230
- logger.groupCollapsed(groupTitle);
231
- for (const url of urls){
232
- logger.log(url);
233
- }
234
- logger.groupEnd();
235
- }
236
- function printInstallDetails(urlsToPrecache, urlsAlreadyPrecached) {
237
- const precachedCount = urlsToPrecache.length;
238
- const alreadyPrecachedCount = urlsAlreadyPrecached.length;
239
- if (precachedCount || alreadyPrecachedCount) {
240
- let message = `Precaching ${precachedCount} file${precachedCount === 1 ? "" : "s"}.`;
241
- if (alreadyPrecachedCount > 0) {
242
- message += ` ${alreadyPrecachedCount} ` + `file${alreadyPrecachedCount === 1 ? " is" : "s are"} already cached.`;
243
- }
244
- logger.groupCollapsed(message);
245
- _nestedGroup("View newly precached URLs.", urlsToPrecache);
246
- _nestedGroup("View previously precached URLs.", urlsAlreadyPrecached);
247
- logger.groupEnd();
248
- }
249
- }
250
-
251
- class PrecacheController {
252
- _installAndActiveListenersAdded;
253
- _concurrentPrecaching;
254
- _strategy;
255
- _urlsToCacheKeys = new Map();
256
- _urlsToCacheModes = new Map();
257
- _cacheKeysToIntegrities = new Map();
258
- constructor({ cacheName, plugins = [], fallbackToNetwork = true, concurrentPrecaching = 1 } = {}){
259
- this._concurrentPrecaching = concurrentPrecaching;
260
- this._strategy = new PrecacheStrategy({
261
- cacheName: privateCacheNames.getPrecacheName(cacheName),
262
- plugins: [
263
- ...plugins,
264
- new PrecacheCacheKeyPlugin({
265
- precacheController: this
266
- })
267
- ],
268
- fallbackToNetwork
269
- });
270
- this.install = this.install.bind(this);
271
- this.activate = this.activate.bind(this);
272
- }
273
- get strategy() {
274
- return this._strategy;
275
- }
276
- precache(entries) {
277
- this.addToCacheList(entries);
278
- if (!this._installAndActiveListenersAdded) {
279
- self.addEventListener("install", this.install);
280
- self.addEventListener("activate", this.activate);
281
- this._installAndActiveListenersAdded = true;
282
- }
283
- }
284
- addToCacheList(entries) {
285
- if (process.env.NODE_ENV !== "production") {
286
- assert.isArray(entries, {
287
- moduleName: "@serwist/precaching",
288
- className: "PrecacheController",
289
- funcName: "addToCacheList",
290
- paramName: "entries"
291
- });
292
- }
293
- const urlsToWarnAbout = [];
294
- for (const entry of entries){
295
- if (typeof entry === "string") {
296
- urlsToWarnAbout.push(entry);
297
- } else if (entry && !entry.integrity && entry.revision === undefined) {
298
- urlsToWarnAbout.push(entry.url);
299
- }
300
- const { cacheKey, url } = createCacheKey(entry);
301
- const cacheMode = typeof entry !== "string" && entry.revision ? "reload" : "default";
302
- if (this._urlsToCacheKeys.has(url) && this._urlsToCacheKeys.get(url) !== cacheKey) {
303
- throw new SerwistError("add-to-cache-list-conflicting-entries", {
304
- firstEntry: this._urlsToCacheKeys.get(url),
305
- secondEntry: cacheKey
306
- });
307
- }
308
- if (typeof entry !== "string" && entry.integrity) {
309
- if (this._cacheKeysToIntegrities.has(cacheKey) && this._cacheKeysToIntegrities.get(cacheKey) !== entry.integrity) {
310
- throw new SerwistError("add-to-cache-list-conflicting-integrities", {
311
- url
312
- });
313
- }
314
- this._cacheKeysToIntegrities.set(cacheKey, entry.integrity);
315
- }
316
- this._urlsToCacheKeys.set(url, cacheKey);
317
- this._urlsToCacheModes.set(url, cacheMode);
318
- if (urlsToWarnAbout.length > 0) {
319
- const warningMessage = `Serwist is precaching URLs without revision info: ${urlsToWarnAbout.join(", ")}\nThis is generally NOT safe. Learn more at https://bit.ly/wb-precache`;
320
- if (process.env.NODE_ENV === "production") {
321
- console.warn(warningMessage);
322
- } else {
323
- logger.warn(warningMessage);
324
- }
325
- }
326
- }
327
- }
328
- install(event) {
329
- return waitUntil(event, async ()=>{
330
- const installReportPlugin = new PrecacheInstallReportPlugin();
331
- this.strategy.plugins.push(installReportPlugin);
332
- await parallel(this._concurrentPrecaching, Array.from(this._urlsToCacheKeys.entries()), async ([url, cacheKey])=>{
333
- const integrity = this._cacheKeysToIntegrities.get(cacheKey);
334
- const cacheMode = this._urlsToCacheModes.get(url);
335
- const request = new Request(url, {
336
- integrity,
337
- cache: cacheMode,
338
- credentials: "same-origin"
339
- });
340
- await Promise.all(this.strategy.handleAll({
341
- event,
342
- request,
343
- url: new URL(request.url),
344
- params: {
345
- cacheKey
346
- }
347
- }));
348
- });
349
- const { updatedURLs, notUpdatedURLs } = installReportPlugin;
350
- if (process.env.NODE_ENV !== "production") {
351
- printInstallDetails(updatedURLs, notUpdatedURLs);
352
- }
353
- return {
354
- updatedURLs,
355
- notUpdatedURLs
356
- };
357
- });
358
- }
359
- activate(event) {
360
- return waitUntil(event, async ()=>{
361
- const cache = await self.caches.open(this.strategy.cacheName);
362
- const currentlyCachedRequests = await cache.keys();
363
- const expectedCacheKeys = new Set(this._urlsToCacheKeys.values());
364
- const deletedCacheRequests = [];
365
- for (const request of currentlyCachedRequests){
366
- if (!expectedCacheKeys.has(request.url)) {
367
- await cache.delete(request);
368
- deletedCacheRequests.push(request.url);
369
- }
370
- }
371
- if (process.env.NODE_ENV !== "production") {
372
- printCleanupDetails(deletedCacheRequests);
373
- }
374
- return {
375
- deletedCacheRequests
376
- };
377
- });
378
- }
379
- getURLsToCacheKeys() {
380
- return this._urlsToCacheKeys;
381
- }
382
- getCachedURLs() {
383
- return [
384
- ...this._urlsToCacheKeys.keys()
385
- ];
386
- }
387
- getCacheKeyForURL(url) {
388
- const urlObject = new URL(url, location.href);
389
- return this._urlsToCacheKeys.get(urlObject.href);
390
- }
391
- getIntegrityForCacheKey(cacheKey) {
392
- return this._cacheKeysToIntegrities.get(cacheKey);
393
- }
394
- async matchPrecache(request) {
395
- const url = request instanceof Request ? request.url : request;
396
- const cacheKey = this.getCacheKeyForURL(url);
397
- if (cacheKey) {
398
- const cache = await self.caches.open(this.strategy.cacheName);
399
- return cache.match(cacheKey);
400
- }
401
- return undefined;
402
- }
403
- createHandlerBoundToURL(url) {
404
- const cacheKey = this.getCacheKeyForURL(url);
405
- if (!cacheKey) {
406
- throw new SerwistError("non-precached-url", {
407
- url
408
- });
409
- }
410
- return (options)=>{
411
- options.request = new Request(url);
412
- options.params = {
413
- cacheKey,
414
- ...options.params
415
- };
416
- return this.strategy.handle(options);
417
- };
418
- }
419
- }
420
-
421
- let defaultPrecacheController = undefined;
422
- const getSingletonPrecacheController = ()=>{
423
- if (!defaultPrecacheController) {
424
- defaultPrecacheController = new PrecacheController();
425
- }
426
- return defaultPrecacheController;
427
- };
428
- const setSingletonPrecacheController = (precacheController)=>{
429
- defaultPrecacheController = precacheController;
430
- return defaultPrecacheController;
431
- };
432
-
433
- export { PrecacheController as P, PrecacheStrategy as a, getSingletonPrecacheController as g, setSingletonPrecacheController as s };