serwist 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 (330) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -0
  3. package/dist/NavigationRoute.d.ts +57 -0
  4. package/dist/NavigationRoute.d.ts.map +1 -0
  5. package/dist/PrecacheRoute.d.ts +17 -0
  6. package/dist/PrecacheRoute.d.ts.map +1 -0
  7. package/dist/PrecacheStrategy.d.ts +66 -0
  8. package/dist/PrecacheStrategy.d.ts.map +1 -0
  9. package/dist/RegExpRoute.d.ts +24 -0
  10. package/dist/RegExpRoute.d.ts.map +1 -0
  11. package/dist/Route.d.ts +33 -0
  12. package/dist/Route.d.ts.map +1 -0
  13. package/dist/Serwist.d.ts +331 -0
  14. package/dist/Serwist.d.ts.map +1 -0
  15. package/dist/cacheNames.d.ts +20 -0
  16. package/dist/cacheNames.d.ts.map +1 -0
  17. package/dist/chunks/NetworkOnly.js +599 -0
  18. package/dist/chunks/PrecacheFallbackPlugin.js +634 -0
  19. package/dist/chunks/Serwist.js +1034 -0
  20. package/dist/chunks/registerQuotaErrorCallback.js +17 -0
  21. package/dist/chunks/resultingClientExists.js +32 -0
  22. package/dist/chunks/timeout.js +400 -0
  23. package/dist/chunks/waitUntil.js +24 -0
  24. package/dist/cleanupOutdatedCaches.d.ts +6 -0
  25. package/dist/cleanupOutdatedCaches.d.ts.map +1 -0
  26. package/dist/clientsClaim.d.ts +6 -0
  27. package/dist/clientsClaim.d.ts.map +1 -0
  28. package/dist/constants.d.ts +15 -0
  29. package/dist/constants.d.ts.map +1 -0
  30. package/dist/copyResponse.d.ts +20 -0
  31. package/dist/copyResponse.d.ts.map +1 -0
  32. package/dist/disableDevLogs.d.ts +7 -0
  33. package/dist/disableDevLogs.d.ts.map +1 -0
  34. package/dist/index.d.ts +21 -0
  35. package/dist/index.d.ts.map +1 -0
  36. package/dist/index.internal.d.ts +16 -0
  37. package/dist/index.internal.d.ts.map +1 -0
  38. package/dist/index.internal.js +24 -0
  39. package/dist/index.js +27 -0
  40. package/dist/index.legacy.d.ts +32 -0
  41. package/dist/index.legacy.d.ts.map +1 -0
  42. package/dist/index.legacy.js +640 -0
  43. package/dist/index.plugins.d.ts +41 -0
  44. package/dist/index.plugins.d.ts.map +1 -0
  45. package/dist/index.plugins.js +669 -0
  46. package/dist/index.strategies.d.ts +22 -0
  47. package/dist/index.strategies.d.ts.map +1 -0
  48. package/dist/index.strategies.js +144 -0
  49. package/dist/legacy/PrecacheController.d.ts +146 -0
  50. package/dist/legacy/PrecacheController.d.ts.map +1 -0
  51. package/dist/legacy/PrecacheFallbackPlugin.d.ts +62 -0
  52. package/dist/legacy/PrecacheFallbackPlugin.d.ts.map +1 -0
  53. package/dist/legacy/PrecacheRoute.d.ts +19 -0
  54. package/dist/legacy/PrecacheRoute.d.ts.map +1 -0
  55. package/dist/legacy/Router.d.ts +151 -0
  56. package/dist/legacy/Router.d.ts.map +1 -0
  57. package/dist/legacy/addPlugins.d.ts +9 -0
  58. package/dist/legacy/addPlugins.d.ts.map +1 -0
  59. package/dist/legacy/addRoute.d.ts +16 -0
  60. package/dist/legacy/addRoute.d.ts.map +1 -0
  61. package/dist/legacy/createHandlerBoundToURL.d.ts +18 -0
  62. package/dist/legacy/createHandlerBoundToURL.d.ts.map +1 -0
  63. package/dist/legacy/fallbacks.d.ts +59 -0
  64. package/dist/legacy/fallbacks.d.ts.map +1 -0
  65. package/dist/legacy/getCacheKeyForURL.d.ts +20 -0
  66. package/dist/legacy/getCacheKeyForURL.d.ts.map +1 -0
  67. package/dist/legacy/handlePrecaching.d.ts +54 -0
  68. package/dist/legacy/handlePrecaching.d.ts.map +1 -0
  69. package/dist/legacy/installSerwist.d.ts +15 -0
  70. package/dist/legacy/installSerwist.d.ts.map +1 -0
  71. package/dist/legacy/matchPrecache.d.ts +15 -0
  72. package/dist/legacy/matchPrecache.d.ts.map +1 -0
  73. package/dist/legacy/precache.d.ts +20 -0
  74. package/dist/legacy/precache.d.ts.map +1 -0
  75. package/dist/legacy/precacheAndRoute.d.ts +15 -0
  76. package/dist/legacy/precacheAndRoute.d.ts.map +1 -0
  77. package/dist/legacy/registerRoute.d.ts +16 -0
  78. package/dist/legacy/registerRoute.d.ts.map +1 -0
  79. package/dist/legacy/registerRuntimeCaching.d.ts +11 -0
  80. package/dist/legacy/registerRuntimeCaching.d.ts.map +1 -0
  81. package/dist/legacy/setCatchHandler.d.ts +10 -0
  82. package/dist/legacy/setCatchHandler.d.ts.map +1 -0
  83. package/dist/legacy/setDefaultHandler.d.ts +13 -0
  84. package/dist/legacy/setDefaultHandler.d.ts.map +1 -0
  85. package/dist/legacy/singletonPrecacheController.d.ts +34 -0
  86. package/dist/legacy/singletonPrecacheController.d.ts.map +1 -0
  87. package/dist/legacy/singletonRouter.d.ts +41 -0
  88. package/dist/legacy/singletonRouter.d.ts.map +1 -0
  89. package/dist/legacy/unregisterRoute.d.ts +9 -0
  90. package/dist/legacy/unregisterRoute.d.ts.map +1 -0
  91. package/dist/legacy/utils/PrecacheCacheKeyPlugin.d.ts +16 -0
  92. package/dist/legacy/utils/PrecacheCacheKeyPlugin.d.ts.map +1 -0
  93. package/dist/legacy/utils/getCacheKeyForURL.d.ts +14 -0
  94. package/dist/legacy/utils/getCacheKeyForURL.d.ts.map +1 -0
  95. package/dist/models/messages/messageGenerator.d.ts +4 -0
  96. package/dist/models/messages/messageGenerator.d.ts.map +1 -0
  97. package/dist/models/messages/messages.d.ts +44 -0
  98. package/dist/models/messages/messages.d.ts.map +1 -0
  99. package/dist/models/pluginEvents.d.ts +10 -0
  100. package/dist/models/pluginEvents.d.ts.map +1 -0
  101. package/dist/models/quotaErrorCallbacks.d.ts +3 -0
  102. package/dist/models/quotaErrorCallbacks.d.ts.map +1 -0
  103. package/dist/navigationPreload.d.ts +24 -0
  104. package/dist/navigationPreload.d.ts.map +1 -0
  105. package/dist/parseRoute.d.ts +16 -0
  106. package/dist/parseRoute.d.ts.map +1 -0
  107. package/dist/plugins/backgroundSync/BackgroundSyncPlugin.d.ts +23 -0
  108. package/dist/plugins/backgroundSync/BackgroundSyncPlugin.d.ts.map +1 -0
  109. package/dist/plugins/backgroundSync/Queue.d.ts +166 -0
  110. package/dist/plugins/backgroundSync/Queue.d.ts.map +1 -0
  111. package/dist/plugins/backgroundSync/QueueDb.d.ts +90 -0
  112. package/dist/plugins/backgroundSync/QueueDb.d.ts.map +1 -0
  113. package/dist/plugins/backgroundSync/QueueStore.d.ts +75 -0
  114. package/dist/plugins/backgroundSync/QueueStore.d.ts.map +1 -0
  115. package/dist/plugins/backgroundSync/StorableRequest.d.ts +51 -0
  116. package/dist/plugins/backgroundSync/StorableRequest.d.ts.map +1 -0
  117. package/dist/plugins/broadcastUpdate/BroadcastCacheUpdate.d.ts +45 -0
  118. package/dist/plugins/broadcastUpdate/BroadcastCacheUpdate.d.ts.map +1 -0
  119. package/dist/plugins/broadcastUpdate/BroadcastUpdatePlugin.d.ts +27 -0
  120. package/dist/plugins/broadcastUpdate/BroadcastUpdatePlugin.d.ts.map +1 -0
  121. package/dist/plugins/broadcastUpdate/constants.d.ts +5 -0
  122. package/dist/plugins/broadcastUpdate/constants.d.ts.map +1 -0
  123. package/dist/plugins/broadcastUpdate/responsesAreSame.d.ts +11 -0
  124. package/dist/plugins/broadcastUpdate/responsesAreSame.d.ts.map +1 -0
  125. package/dist/plugins/broadcastUpdate/types.d.ts +34 -0
  126. package/dist/plugins/broadcastUpdate/types.d.ts.map +1 -0
  127. package/dist/plugins/cacheableResponse/CacheableResponse.d.ts +40 -0
  128. package/dist/plugins/cacheableResponse/CacheableResponse.d.ts.map +1 -0
  129. package/dist/plugins/cacheableResponse/CacheableResponsePlugin.d.ts +27 -0
  130. package/dist/plugins/cacheableResponse/CacheableResponsePlugin.d.ts.map +1 -0
  131. package/dist/plugins/expiration/CacheExpiration.d.ts +66 -0
  132. package/dist/plugins/expiration/CacheExpiration.d.ts.map +1 -0
  133. package/dist/plugins/expiration/ExpirationPlugin.d.ts +116 -0
  134. package/dist/plugins/expiration/ExpirationPlugin.d.ts.map +1 -0
  135. package/dist/plugins/expiration/models/CacheTimestampsModel.d.ts +73 -0
  136. package/dist/plugins/expiration/models/CacheTimestampsModel.d.ts.map +1 -0
  137. package/dist/plugins/googleAnalytics/constants.d.ts +10 -0
  138. package/dist/plugins/googleAnalytics/constants.d.ts.map +1 -0
  139. package/dist/plugins/googleAnalytics/initialize.d.ts +30 -0
  140. package/dist/plugins/googleAnalytics/initialize.d.ts.map +1 -0
  141. package/dist/plugins/precaching/PrecacheFallbackPlugin.d.ts +53 -0
  142. package/dist/plugins/precaching/PrecacheFallbackPlugin.d.ts.map +1 -0
  143. package/dist/plugins/rangeRequests/RangeRequestsPlugin.d.ts +19 -0
  144. package/dist/plugins/rangeRequests/RangeRequestsPlugin.d.ts.map +1 -0
  145. package/dist/plugins/rangeRequests/createPartialResponse.d.ts +18 -0
  146. package/dist/plugins/rangeRequests/createPartialResponse.d.ts.map +1 -0
  147. package/dist/plugins/rangeRequests/utils/calculateEffectiveBoundaries.d.ts +14 -0
  148. package/dist/plugins/rangeRequests/utils/calculateEffectiveBoundaries.d.ts.map +1 -0
  149. package/dist/plugins/rangeRequests/utils/parseRangeHeader.d.ts +12 -0
  150. package/dist/plugins/rangeRequests/utils/parseRangeHeader.d.ts.map +1 -0
  151. package/dist/registerQuotaErrorCallback.d.ts +8 -0
  152. package/dist/registerQuotaErrorCallback.d.ts.map +1 -0
  153. package/dist/setCacheNameDetails.d.ts +9 -0
  154. package/dist/setCacheNameDetails.d.ts.map +1 -0
  155. package/dist/strategies/CacheFirst.d.ts +23 -0
  156. package/dist/strategies/CacheFirst.d.ts.map +1 -0
  157. package/dist/strategies/CacheOnly.d.ts +20 -0
  158. package/dist/strategies/CacheOnly.d.ts.map +1 -0
  159. package/dist/strategies/NetworkFirst.d.ts +61 -0
  160. package/dist/strategies/NetworkFirst.d.ts.map +1 -0
  161. package/dist/strategies/NetworkOnly.d.ts +32 -0
  162. package/dist/strategies/NetworkOnly.d.ts.map +1 -0
  163. package/dist/strategies/StaleWhileRevalidate.d.ts +35 -0
  164. package/dist/strategies/StaleWhileRevalidate.d.ts.map +1 -0
  165. package/dist/strategies/Strategy.d.ts +83 -0
  166. package/dist/strategies/Strategy.d.ts.map +1 -0
  167. package/dist/strategies/StrategyHandler.d.ts +189 -0
  168. package/dist/strategies/StrategyHandler.d.ts.map +1 -0
  169. package/dist/strategies/plugins/cacheOkAndOpaquePlugin.d.ts +3 -0
  170. package/dist/strategies/plugins/cacheOkAndOpaquePlugin.d.ts.map +1 -0
  171. package/dist/strategies/utils/messages.d.ts +5 -0
  172. package/dist/strategies/utils/messages.d.ts.map +1 -0
  173. package/dist/types.d.ts +317 -0
  174. package/dist/types.d.ts.map +1 -0
  175. package/dist/utils/Deferred.d.ts +19 -0
  176. package/dist/utils/Deferred.d.ts.map +1 -0
  177. package/dist/utils/PrecacheCacheKeyPlugin.d.ts +16 -0
  178. package/dist/utils/PrecacheCacheKeyPlugin.d.ts.map +1 -0
  179. package/dist/utils/PrecacheInstallReportPlugin.d.ts +14 -0
  180. package/dist/utils/PrecacheInstallReportPlugin.d.ts.map +1 -0
  181. package/dist/utils/SerwistError.d.ts +24 -0
  182. package/dist/utils/SerwistError.d.ts.map +1 -0
  183. package/dist/utils/assert.d.ts +11 -0
  184. package/dist/utils/assert.d.ts.map +1 -0
  185. package/dist/utils/cacheMatchIgnoreParams.d.ts +15 -0
  186. package/dist/utils/cacheMatchIgnoreParams.d.ts.map +1 -0
  187. package/dist/utils/cacheNames.d.ts +40 -0
  188. package/dist/utils/cacheNames.d.ts.map +1 -0
  189. package/dist/utils/canConstructReadableStream.d.ts +12 -0
  190. package/dist/utils/canConstructReadableStream.d.ts.map +1 -0
  191. package/dist/utils/canConstructResponseFromBodyStream.d.ts +11 -0
  192. package/dist/utils/canConstructResponseFromBodyStream.d.ts.map +1 -0
  193. package/dist/utils/createCacheKey.d.ts +16 -0
  194. package/dist/utils/createCacheKey.d.ts.map +1 -0
  195. package/dist/utils/deleteOutdatedCaches.d.ts +18 -0
  196. package/dist/utils/deleteOutdatedCaches.d.ts.map +1 -0
  197. package/dist/utils/dontWaitFor.d.ts +7 -0
  198. package/dist/utils/dontWaitFor.d.ts.map +1 -0
  199. package/dist/utils/executeQuotaErrorCallbacks.d.ts +8 -0
  200. package/dist/utils/executeQuotaErrorCallbacks.d.ts.map +1 -0
  201. package/dist/utils/generateURLVariations.d.ts +12 -0
  202. package/dist/utils/generateURLVariations.d.ts.map +1 -0
  203. package/dist/utils/getFriendlyURL.d.ts +3 -0
  204. package/dist/utils/getFriendlyURL.d.ts.map +1 -0
  205. package/dist/utils/logger.d.ts +24 -0
  206. package/dist/utils/logger.d.ts.map +1 -0
  207. package/dist/utils/normalizeHandler.d.ts +10 -0
  208. package/dist/utils/normalizeHandler.d.ts.map +1 -0
  209. package/dist/utils/pluginUtils.d.ts +5 -0
  210. package/dist/utils/pluginUtils.d.ts.map +1 -0
  211. package/dist/utils/printCleanupDetails.d.ts +6 -0
  212. package/dist/utils/printCleanupDetails.d.ts.map +1 -0
  213. package/dist/utils/printInstallDetails.d.ts +7 -0
  214. package/dist/utils/printInstallDetails.d.ts.map +1 -0
  215. package/dist/utils/removeIgnoredSearchParams.d.ts +12 -0
  216. package/dist/utils/removeIgnoredSearchParams.d.ts.map +1 -0
  217. package/dist/utils/resultingClientExists.d.ts +12 -0
  218. package/dist/utils/resultingClientExists.d.ts.map +1 -0
  219. package/dist/utils/timeout.d.ts +10 -0
  220. package/dist/utils/timeout.d.ts.map +1 -0
  221. package/dist/utils/waitUntil.d.ts +11 -0
  222. package/dist/utils/waitUntil.d.ts.map +1 -0
  223. package/dist/utils/welcome.d.ts +2 -0
  224. package/dist/utils/welcome.d.ts.map +1 -0
  225. package/package.json +85 -0
  226. package/src/NavigationRoute.ts +119 -0
  227. package/src/PrecacheRoute.ts +46 -0
  228. package/src/PrecacheStrategy.ts +239 -0
  229. package/src/RegExpRoute.ts +74 -0
  230. package/src/Route.ts +67 -0
  231. package/src/Serwist.ts +920 -0
  232. package/src/cacheNames.ts +39 -0
  233. package/src/cleanupOutdatedCaches.ts +32 -0
  234. package/src/clientsClaim.ts +18 -0
  235. package/src/constants.ts +24 -0
  236. package/src/copyResponse.ts +60 -0
  237. package/src/disableDevLogs.ts +10 -0
  238. package/src/index.internal.ts +33 -0
  239. package/src/index.legacy.ts +66 -0
  240. package/src/index.plugins.ts +95 -0
  241. package/src/index.strategies.ts +26 -0
  242. package/src/index.ts +39 -0
  243. package/src/legacy/PrecacheController.ts +337 -0
  244. package/src/legacy/PrecacheFallbackPlugin.ts +93 -0
  245. package/src/legacy/PrecacheRoute.ts +48 -0
  246. package/src/legacy/Router.ts +484 -0
  247. package/src/legacy/addPlugins.ts +21 -0
  248. package/src/legacy/addRoute.ts +29 -0
  249. package/src/legacy/createHandlerBoundToURL.ts +30 -0
  250. package/src/legacy/fallbacks.ts +94 -0
  251. package/src/legacy/getCacheKeyForURL.ts +32 -0
  252. package/src/legacy/handlePrecaching.ts +86 -0
  253. package/src/legacy/installSerwist.ts +19 -0
  254. package/src/legacy/matchPrecache.ts +26 -0
  255. package/src/legacy/precache.ts +31 -0
  256. package/src/legacy/precacheAndRoute.ts +28 -0
  257. package/src/legacy/registerRoute.ts +27 -0
  258. package/src/legacy/registerRuntimeCaching.ts +17 -0
  259. package/src/legacy/setCatchHandler.ts +21 -0
  260. package/src/legacy/setDefaultHandler.ts +24 -0
  261. package/src/legacy/singletonPrecacheController.ts +53 -0
  262. package/src/legacy/singletonRouter.ts +70 -0
  263. package/src/legacy/unregisterRoute.ts +12 -0
  264. package/src/legacy/utils/PrecacheCacheKeyPlugin.ts +33 -0
  265. package/src/legacy/utils/getCacheKeyForURL.ts +36 -0
  266. package/src/models/messages/messageGenerator.ts +29 -0
  267. package/src/models/messages/messages.ts +233 -0
  268. package/src/models/pluginEvents.ts +17 -0
  269. package/src/models/quotaErrorCallbacks.ts +13 -0
  270. package/src/navigationPreload.ts +68 -0
  271. package/src/parseRoute.ts +78 -0
  272. package/src/plugins/backgroundSync/BackgroundSyncPlugin.ts +38 -0
  273. package/src/plugins/backgroundSync/Queue.ts +440 -0
  274. package/src/plugins/backgroundSync/QueueDb.ts +176 -0
  275. package/src/plugins/backgroundSync/QueueStore.ts +160 -0
  276. package/src/plugins/backgroundSync/StorableRequest.ts +142 -0
  277. package/src/plugins/broadcastUpdate/BroadcastCacheUpdate.ts +161 -0
  278. package/src/plugins/broadcastUpdate/BroadcastUpdatePlugin.ts +42 -0
  279. package/src/plugins/broadcastUpdate/constants.ts +12 -0
  280. package/src/plugins/broadcastUpdate/responsesAreSame.ts +49 -0
  281. package/src/plugins/broadcastUpdate/types.ts +37 -0
  282. package/src/plugins/cacheableResponse/CacheableResponse.ts +144 -0
  283. package/src/plugins/cacheableResponse/CacheableResponsePlugin.ts +45 -0
  284. package/src/plugins/expiration/CacheExpiration.ts +193 -0
  285. package/src/plugins/expiration/ExpirationPlugin.ts +300 -0
  286. package/src/plugins/expiration/models/CacheTimestampsModel.ts +184 -0
  287. package/src/plugins/googleAnalytics/constants.ts +22 -0
  288. package/src/plugins/googleAnalytics/initialize.ts +209 -0
  289. package/src/plugins/precaching/PrecacheFallbackPlugin.ts +83 -0
  290. package/src/plugins/rangeRequests/RangeRequestsPlugin.ts +38 -0
  291. package/src/plugins/rangeRequests/createPartialResponse.ts +93 -0
  292. package/src/plugins/rangeRequests/utils/calculateEffectiveBoundaries.ts +59 -0
  293. package/src/plugins/rangeRequests/utils/parseRangeHeader.ts +55 -0
  294. package/src/registerQuotaErrorCallback.ts +34 -0
  295. package/src/setCacheNameDetails.ts +53 -0
  296. package/src/strategies/CacheFirst.ts +88 -0
  297. package/src/strategies/CacheOnly.ts +59 -0
  298. package/src/strategies/NetworkFirst.ts +229 -0
  299. package/src/strategies/NetworkOnly.ts +98 -0
  300. package/src/strategies/StaleWhileRevalidate.ts +110 -0
  301. package/src/strategies/Strategy.ts +204 -0
  302. package/src/strategies/StrategyHandler.ts +554 -0
  303. package/src/strategies/plugins/cacheOkAndOpaquePlugin.ts +26 -0
  304. package/src/strategies/utils/messages.ts +21 -0
  305. package/src/types.ts +358 -0
  306. package/src/utils/Deferred.ts +33 -0
  307. package/src/utils/PrecacheCacheKeyPlugin.ts +33 -0
  308. package/src/utils/PrecacheInstallReportPlugin.ts +47 -0
  309. package/src/utils/SerwistError.ts +41 -0
  310. package/src/utils/assert.ts +89 -0
  311. package/src/utils/cacheMatchIgnoreParams.ts +54 -0
  312. package/src/utils/cacheNames.ts +87 -0
  313. package/src/utils/canConstructReadableStream.ts +34 -0
  314. package/src/utils/canConstructResponseFromBodyStream.ts +37 -0
  315. package/src/utils/createCacheKey.ts +68 -0
  316. package/src/utils/deleteOutdatedCaches.ts +40 -0
  317. package/src/utils/dontWaitFor.ts +16 -0
  318. package/src/utils/executeQuotaErrorCallbacks.ts +33 -0
  319. package/src/utils/generateURLVariations.ts +55 -0
  320. package/src/utils/getFriendlyURL.ts +16 -0
  321. package/src/utils/logger.ts +95 -0
  322. package/src/utils/normalizeHandler.ts +40 -0
  323. package/src/utils/pluginUtils.ts +15 -0
  324. package/src/utils/printCleanupDetails.ts +38 -0
  325. package/src/utils/printInstallDetails.ts +53 -0
  326. package/src/utils/removeIgnoredSearchParams.ts +29 -0
  327. package/src/utils/resultingClientExists.ts +58 -0
  328. package/src/utils/timeout.ts +19 -0
  329. package/src/utils/waitUntil.ts +21 -0
  330. package/src/utils/welcome.ts +19 -0
@@ -0,0 +1,1034 @@
1
+ import { c as cacheNames, l as logger, S as SerwistError, f as finalAssertExports, g as getFriendlyURL } from './timeout.js';
2
+ import { c as canConstructResponseFromBodyStream, w as waitUntil } from './waitUntil.js';
3
+ import { R as Route, i as initialize, P as PrecacheFallbackPlugin, n as normalizeHandler, d as defaultMethod } from './PrecacheFallbackPlugin.js';
4
+ import { S as Strategy } from './NetworkOnly.js';
5
+
6
+ const SUBSTRING_TO_FIND = "-precache-";
7
+ const deleteOutdatedCaches = async (currentPrecacheName, substringToFind = SUBSTRING_TO_FIND)=>{
8
+ const cacheNames = await self.caches.keys();
9
+ const cacheNamesToDelete = cacheNames.filter((cacheName)=>{
10
+ return cacheName.includes(substringToFind) && cacheName.includes(self.registration.scope) && cacheName !== currentPrecacheName;
11
+ });
12
+ await Promise.all(cacheNamesToDelete.map((cacheName)=>self.caches.delete(cacheName)));
13
+ return cacheNamesToDelete;
14
+ };
15
+
16
+ const cleanupOutdatedCaches = (cacheName)=>{
17
+ self.addEventListener("activate", (event)=>{
18
+ event.waitUntil(deleteOutdatedCaches(cacheNames.getPrecacheName(cacheName)).then((cachesDeleted)=>{
19
+ if (process.env.NODE_ENV !== "production") {
20
+ if (cachesDeleted.length > 0) {
21
+ logger.log("The following out-of-date precaches were cleaned up automatically:", cachesDeleted);
22
+ }
23
+ }
24
+ }));
25
+ });
26
+ };
27
+
28
+ const clientsClaim = ()=>{
29
+ self.addEventListener("activate", ()=>self.clients.claim());
30
+ };
31
+
32
+ const copyResponse = async (response, modifier)=>{
33
+ let origin = null;
34
+ if (response.url) {
35
+ const responseURL = new URL(response.url);
36
+ origin = responseURL.origin;
37
+ }
38
+ if (origin !== self.location.origin) {
39
+ throw new SerwistError("cross-origin-copy-response", {
40
+ origin
41
+ });
42
+ }
43
+ const clonedResponse = response.clone();
44
+ const responseInit = {
45
+ headers: new Headers(clonedResponse.headers),
46
+ status: clonedResponse.status,
47
+ statusText: clonedResponse.statusText
48
+ };
49
+ const modifiedResponseInit = modifier ? modifier(responseInit) : responseInit;
50
+ const body = canConstructResponseFromBodyStream() ? clonedResponse.body : await clonedResponse.blob();
51
+ return new Response(body, modifiedResponseInit);
52
+ };
53
+
54
+ const disableDevLogs = ()=>{
55
+ self.__WB_DISABLE_DEV_LOGS = true;
56
+ };
57
+
58
+ const isNavigationPreloadSupported = ()=>{
59
+ return Boolean(self.registration?.navigationPreload);
60
+ };
61
+ const enableNavigationPreload = (headerValue)=>{
62
+ if (isNavigationPreloadSupported()) {
63
+ self.addEventListener("activate", (event)=>{
64
+ event.waitUntil(self.registration.navigationPreload.enable().then(()=>{
65
+ if (headerValue) {
66
+ void self.registration.navigationPreload.setHeaderValue(headerValue);
67
+ }
68
+ if (process.env.NODE_ENV !== "production") {
69
+ logger.log("Navigation preloading is enabled.");
70
+ }
71
+ }));
72
+ });
73
+ } else {
74
+ if (process.env.NODE_ENV !== "production") {
75
+ logger.log("Navigation preloading is not supported in this browser.");
76
+ }
77
+ }
78
+ };
79
+ const disableNavigationPreload = ()=>{
80
+ if (isNavigationPreloadSupported()) {
81
+ self.addEventListener("activate", (event)=>{
82
+ event.waitUntil(self.registration.navigationPreload.disable().then(()=>{
83
+ if (process.env.NODE_ENV !== "production") {
84
+ logger.log("Navigation preloading is disabled.");
85
+ }
86
+ }));
87
+ });
88
+ } else {
89
+ if (process.env.NODE_ENV !== "production") {
90
+ logger.log("Navigation preloading is not supported in this browser.");
91
+ }
92
+ }
93
+ };
94
+
95
+ class NavigationRoute extends Route {
96
+ _allowlist;
97
+ _denylist;
98
+ constructor(handler, { allowlist = [
99
+ /./
100
+ ], denylist = [] } = {}){
101
+ if (process.env.NODE_ENV !== "production") {
102
+ finalAssertExports.isArrayOfClass(allowlist, RegExp, {
103
+ moduleName: "serwist",
104
+ className: "NavigationRoute",
105
+ funcName: "constructor",
106
+ paramName: "options.allowlist"
107
+ });
108
+ finalAssertExports.isArrayOfClass(denylist, RegExp, {
109
+ moduleName: "serwist",
110
+ className: "NavigationRoute",
111
+ funcName: "constructor",
112
+ paramName: "options.denylist"
113
+ });
114
+ }
115
+ super((options)=>this._match(options), handler);
116
+ this._allowlist = allowlist;
117
+ this._denylist = denylist;
118
+ }
119
+ _match({ url, request }) {
120
+ if (request && request.mode !== "navigate") {
121
+ return false;
122
+ }
123
+ const pathnameAndSearch = url.pathname + url.search;
124
+ for (const regExp of this._denylist){
125
+ if (regExp.test(pathnameAndSearch)) {
126
+ if (process.env.NODE_ENV !== "production") {
127
+ logger.log(`The navigation route ${pathnameAndSearch} is not being used, since the URL matches this denylist pattern: ${regExp.toString()}`);
128
+ }
129
+ return false;
130
+ }
131
+ }
132
+ if (this._allowlist.some((regExp)=>regExp.test(pathnameAndSearch))) {
133
+ if (process.env.NODE_ENV !== "production") {
134
+ logger.debug(`The navigation route ${pathnameAndSearch} is being used.`);
135
+ }
136
+ return true;
137
+ }
138
+ if (process.env.NODE_ENV !== "production") {
139
+ logger.log(`The navigation route ${pathnameAndSearch} is not being used, since the URL being navigated to doesn't match the allowlist.`);
140
+ }
141
+ return false;
142
+ }
143
+ }
144
+
145
+ class RegExpRoute extends Route {
146
+ constructor(regExp, handler, method){
147
+ if (process.env.NODE_ENV !== "production") {
148
+ finalAssertExports.isInstance(regExp, RegExp, {
149
+ moduleName: "serwist",
150
+ className: "RegExpRoute",
151
+ funcName: "constructor",
152
+ paramName: "pattern"
153
+ });
154
+ }
155
+ const match = ({ url })=>{
156
+ const result = regExp.exec(url.href);
157
+ if (!result) {
158
+ return;
159
+ }
160
+ if (url.origin !== location.origin && result.index !== 0) {
161
+ if (process.env.NODE_ENV !== "production") {
162
+ logger.debug(`The regular expression '${regExp.toString()}' only partially matched against the cross-origin URL '${url.toString()}'. RegExpRoute's will only handle cross-origin requests if they match the entire URL.`);
163
+ }
164
+ return;
165
+ }
166
+ return result.slice(1);
167
+ };
168
+ super(match, handler, method);
169
+ }
170
+ }
171
+
172
+ const parseRoute = (capture, handler, method)=>{
173
+ let route;
174
+ if (typeof capture === "string") {
175
+ const captureUrl = new URL(capture, location.href);
176
+ if (process.env.NODE_ENV !== "production") {
177
+ if (!(capture.startsWith("/") || capture.startsWith("http"))) {
178
+ throw new SerwistError("invalid-string", {
179
+ moduleName: "serwist",
180
+ funcName: "parseRoute",
181
+ paramName: "capture"
182
+ });
183
+ }
184
+ const valueToCheck = capture.startsWith("http") ? captureUrl.pathname : capture;
185
+ const wildcards = "[*:?+]";
186
+ if (new RegExp(`${wildcards}`).exec(valueToCheck)) {
187
+ logger.debug(`The '$capture' parameter contains an Express-style wildcard character (${wildcards}). Strings are now always interpreted as exact matches; use a RegExp for partial or wildcard matches.`);
188
+ }
189
+ }
190
+ const matchCallback = ({ url })=>{
191
+ if (process.env.NODE_ENV !== "production") {
192
+ if (url.pathname === captureUrl.pathname && url.origin !== captureUrl.origin) {
193
+ logger.debug(`${capture} only partially matches the cross-origin URL ${url.toString()}. This route will only handle cross-origin requests if they match the entire URL.`);
194
+ }
195
+ }
196
+ return url.href === captureUrl.href;
197
+ };
198
+ route = new Route(matchCallback, handler, method);
199
+ } else if (capture instanceof RegExp) {
200
+ route = new RegExpRoute(capture, handler, method);
201
+ } else if (typeof capture === "function") {
202
+ route = new Route(capture, handler, method);
203
+ } else if (capture instanceof Route) {
204
+ route = capture;
205
+ } else {
206
+ throw new SerwistError("unsupported-route-type", {
207
+ moduleName: "serwist",
208
+ funcName: "parseRoute",
209
+ paramName: "capture"
210
+ });
211
+ }
212
+ return route;
213
+ };
214
+
215
+ const removeIgnoredSearchParams = (urlObject, ignoreURLParametersMatching = [])=>{
216
+ for (const paramName of [
217
+ ...urlObject.searchParams.keys()
218
+ ]){
219
+ if (ignoreURLParametersMatching.some((regExp)=>regExp.test(paramName))) {
220
+ urlObject.searchParams.delete(paramName);
221
+ }
222
+ }
223
+ return urlObject;
224
+ };
225
+
226
+ function* generateURLVariations(url, { directoryIndex = "index.html", ignoreURLParametersMatching = [
227
+ /^utm_/,
228
+ /^fbclid$/
229
+ ], cleanURLs = true, urlManipulation } = {}) {
230
+ const urlObject = new URL(url, location.href);
231
+ urlObject.hash = "";
232
+ yield urlObject.href;
233
+ const urlWithoutIgnoredParams = removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching);
234
+ yield urlWithoutIgnoredParams.href;
235
+ if (directoryIndex && urlWithoutIgnoredParams.pathname.endsWith("/")) {
236
+ const directoryURL = new URL(urlWithoutIgnoredParams.href);
237
+ directoryURL.pathname += directoryIndex;
238
+ yield directoryURL.href;
239
+ }
240
+ if (cleanURLs) {
241
+ const cleanURL = new URL(urlWithoutIgnoredParams.href);
242
+ cleanURL.pathname += ".html";
243
+ yield cleanURL.href;
244
+ }
245
+ if (urlManipulation) {
246
+ const additionalURLs = urlManipulation({
247
+ url: urlObject
248
+ });
249
+ for (const urlToAttempt of additionalURLs){
250
+ yield urlToAttempt.href;
251
+ }
252
+ }
253
+ }
254
+
255
+ class PrecacheRoute extends Route {
256
+ constructor(serwist, options){
257
+ const match = ({ request })=>{
258
+ const urlsToCacheKeys = serwist.getUrlsToPrecacheKeys();
259
+ for (const possibleURL of generateURLVariations(request.url, options)){
260
+ const cacheKey = urlsToCacheKeys.get(possibleURL);
261
+ if (cacheKey) {
262
+ const integrity = serwist.getIntegrityForPrecacheKey(cacheKey);
263
+ return {
264
+ cacheKey,
265
+ integrity
266
+ };
267
+ }
268
+ }
269
+ if (process.env.NODE_ENV !== "production") {
270
+ logger.debug(`Precaching did not find a match for ${getFriendlyURL(request.url)}.`);
271
+ }
272
+ return;
273
+ };
274
+ super(match, serwist.precacheStrategy);
275
+ }
276
+ }
277
+
278
+ class PrecacheStrategy extends Strategy {
279
+ _fallbackToNetwork;
280
+ static defaultPrecacheCacheabilityPlugin = {
281
+ async cacheWillUpdate ({ response }) {
282
+ if (!response || response.status >= 400) {
283
+ return null;
284
+ }
285
+ return response;
286
+ }
287
+ };
288
+ static copyRedirectedCacheableResponsesPlugin = {
289
+ async cacheWillUpdate ({ response }) {
290
+ return response.redirected ? await copyResponse(response) : response;
291
+ }
292
+ };
293
+ constructor(options = {}){
294
+ options.cacheName = cacheNames.getPrecacheName(options.cacheName);
295
+ super(options);
296
+ this._fallbackToNetwork = options.fallbackToNetwork === false ? false : true;
297
+ this.plugins.push(PrecacheStrategy.copyRedirectedCacheableResponsesPlugin);
298
+ }
299
+ async _handle(request, handler) {
300
+ const response = await handler.cacheMatch(request);
301
+ if (response) {
302
+ return response;
303
+ }
304
+ if (handler.event && handler.event.type === "install") {
305
+ return await this._handleInstall(request, handler);
306
+ }
307
+ return await this._handleFetch(request, handler);
308
+ }
309
+ async _handleFetch(request, handler) {
310
+ let response = undefined;
311
+ const params = handler.params || {};
312
+ if (this._fallbackToNetwork) {
313
+ if (process.env.NODE_ENV !== "production") {
314
+ logger.warn(`The precached response for ${getFriendlyURL(request.url)} in ${this.cacheName} was not found. Falling back to the network.`);
315
+ }
316
+ const integrityInManifest = params.integrity;
317
+ const integrityInRequest = request.integrity;
318
+ const noIntegrityConflict = !integrityInRequest || integrityInRequest === integrityInManifest;
319
+ response = await handler.fetch(new Request(request, {
320
+ integrity: request.mode !== "no-cors" ? integrityInRequest || integrityInManifest : undefined
321
+ }));
322
+ if (integrityInManifest && noIntegrityConflict && request.mode !== "no-cors") {
323
+ this._useDefaultCacheabilityPluginIfNeeded();
324
+ const wasCached = await handler.cachePut(request, response.clone());
325
+ if (process.env.NODE_ENV !== "production") {
326
+ if (wasCached) {
327
+ logger.log(`A response for ${getFriendlyURL(request.url)} was used to "repair" the precache.`);
328
+ }
329
+ }
330
+ }
331
+ } else {
332
+ throw new SerwistError("missing-precache-entry", {
333
+ cacheName: this.cacheName,
334
+ url: request.url
335
+ });
336
+ }
337
+ if (process.env.NODE_ENV !== "production") {
338
+ const cacheKey = params.cacheKey || await handler.getCacheKey(request, "read");
339
+ logger.groupCollapsed(`Precaching is responding to: ${getFriendlyURL(request.url)}`);
340
+ logger.log(`Serving the precached url: ${getFriendlyURL(cacheKey instanceof Request ? cacheKey.url : cacheKey)}`);
341
+ logger.groupCollapsed("View request details here.");
342
+ logger.log(request);
343
+ logger.groupEnd();
344
+ logger.groupCollapsed("View response details here.");
345
+ logger.log(response);
346
+ logger.groupEnd();
347
+ logger.groupEnd();
348
+ }
349
+ return response;
350
+ }
351
+ async _handleInstall(request, handler) {
352
+ this._useDefaultCacheabilityPluginIfNeeded();
353
+ const response = await handler.fetch(request);
354
+ const wasCached = await handler.cachePut(request, response.clone());
355
+ if (!wasCached) {
356
+ throw new SerwistError("bad-precaching-response", {
357
+ url: request.url,
358
+ status: response.status
359
+ });
360
+ }
361
+ return response;
362
+ }
363
+ _useDefaultCacheabilityPluginIfNeeded() {
364
+ let defaultPluginIndex = null;
365
+ let cacheWillUpdatePluginCount = 0;
366
+ for (const [index, plugin] of this.plugins.entries()){
367
+ if (plugin === PrecacheStrategy.copyRedirectedCacheableResponsesPlugin) {
368
+ continue;
369
+ }
370
+ if (plugin === PrecacheStrategy.defaultPrecacheCacheabilityPlugin) {
371
+ defaultPluginIndex = index;
372
+ }
373
+ if (plugin.cacheWillUpdate) {
374
+ cacheWillUpdatePluginCount++;
375
+ }
376
+ }
377
+ if (cacheWillUpdatePluginCount === 0) {
378
+ this.plugins.push(PrecacheStrategy.defaultPrecacheCacheabilityPlugin);
379
+ } else if (cacheWillUpdatePluginCount > 1 && defaultPluginIndex !== null) {
380
+ this.plugins.splice(defaultPluginIndex, 1);
381
+ }
382
+ }
383
+ }
384
+
385
+ const setCacheNameDetails = (details)=>{
386
+ if (process.env.NODE_ENV !== "production") {
387
+ for (const key of Object.keys(details)){
388
+ finalAssertExports.isType(details[key], "string", {
389
+ moduleName: "@serwist/core",
390
+ funcName: "setCacheNameDetails",
391
+ paramName: `details.${key}`
392
+ });
393
+ }
394
+ if (details.precache?.length === 0) {
395
+ throw new SerwistError("invalid-cache-name", {
396
+ cacheNameId: "precache",
397
+ value: details.precache
398
+ });
399
+ }
400
+ if (details.runtime?.length === 0) {
401
+ throw new SerwistError("invalid-cache-name", {
402
+ cacheNameId: "runtime",
403
+ value: details.runtime
404
+ });
405
+ }
406
+ if (details.googleAnalytics?.length === 0) {
407
+ throw new SerwistError("invalid-cache-name", {
408
+ cacheNameId: "googleAnalytics",
409
+ value: details.googleAnalytics
410
+ });
411
+ }
412
+ }
413
+ cacheNames.updateDetails(details);
414
+ };
415
+
416
+ const parallel = async (limit, array, func)=>{
417
+ const work = array.map((item, index)=>({
418
+ index,
419
+ item
420
+ }));
421
+ const processor = async (res)=>{
422
+ const results = [];
423
+ while(true){
424
+ const next = work.pop();
425
+ if (!next) {
426
+ return res(results);
427
+ }
428
+ const result = await func(next.item);
429
+ results.push({
430
+ result: result,
431
+ index: next.index
432
+ });
433
+ }
434
+ };
435
+ const queues = Array.from({
436
+ length: limit
437
+ }, ()=>new Promise(processor));
438
+ const results = (await Promise.all(queues)).flat().sort((a, b)=>a.index < b.index ? -1 : 1).map((res)=>res.result);
439
+ return results;
440
+ };
441
+
442
+ class PrecacheCacheKeyPlugin {
443
+ _precacheController;
444
+ constructor({ precacheController }){
445
+ this._precacheController = precacheController;
446
+ }
447
+ cacheKeyWillBeUsed = async ({ request, params })=>{
448
+ const cacheKey = params?.cacheKey || this._precacheController.getPrecacheKeyForUrl(request.url);
449
+ return cacheKey ? new Request(cacheKey, {
450
+ headers: request.headers
451
+ }) : request;
452
+ };
453
+ }
454
+
455
+ class PrecacheInstallReportPlugin {
456
+ updatedURLs = [];
457
+ notUpdatedURLs = [];
458
+ handlerWillStart = async ({ request, state })=>{
459
+ if (state) {
460
+ state.originalRequest = request;
461
+ }
462
+ };
463
+ cachedResponseWillBeUsed = async ({ event, state, cachedResponse })=>{
464
+ if (event.type === "install") {
465
+ if (state?.originalRequest && state.originalRequest instanceof Request) {
466
+ const url = state.originalRequest.url;
467
+ if (cachedResponse) {
468
+ this.notUpdatedURLs.push(url);
469
+ } else {
470
+ this.updatedURLs.push(url);
471
+ }
472
+ }
473
+ }
474
+ return cachedResponse;
475
+ };
476
+ }
477
+
478
+ const REVISION_SEARCH_PARAM = "__WB_REVISION__";
479
+ const createCacheKey = (entry)=>{
480
+ if (!entry) {
481
+ throw new SerwistError("add-to-cache-list-unexpected-type", {
482
+ entry
483
+ });
484
+ }
485
+ if (typeof entry === "string") {
486
+ const urlObject = new URL(entry, location.href);
487
+ return {
488
+ cacheKey: urlObject.href,
489
+ url: urlObject.href
490
+ };
491
+ }
492
+ const { revision, url } = entry;
493
+ if (!url) {
494
+ throw new SerwistError("add-to-cache-list-unexpected-type", {
495
+ entry
496
+ });
497
+ }
498
+ if (!revision) {
499
+ const urlObject = new URL(url, location.href);
500
+ return {
501
+ cacheKey: urlObject.href,
502
+ url: urlObject.href
503
+ };
504
+ }
505
+ const cacheKeyURL = new URL(url, location.href);
506
+ const originalURL = new URL(url, location.href);
507
+ cacheKeyURL.searchParams.set(REVISION_SEARCH_PARAM, revision);
508
+ return {
509
+ cacheKey: cacheKeyURL.href,
510
+ url: originalURL.href
511
+ };
512
+ };
513
+
514
+ const logGroup = (groupTitle, deletedURLs)=>{
515
+ logger.groupCollapsed(groupTitle);
516
+ for (const url of deletedURLs){
517
+ logger.log(url);
518
+ }
519
+ logger.groupEnd();
520
+ };
521
+ const printCleanupDetails = (deletedURLs)=>{
522
+ const deletionCount = deletedURLs.length;
523
+ if (deletionCount > 0) {
524
+ logger.groupCollapsed(`During precaching cleanup, ${deletionCount} cached request${deletionCount === 1 ? " was" : "s were"} deleted.`);
525
+ logGroup("Deleted Cache Requests", deletedURLs);
526
+ logger.groupEnd();
527
+ }
528
+ };
529
+
530
+ function _nestedGroup(groupTitle, urls) {
531
+ if (urls.length === 0) {
532
+ return;
533
+ }
534
+ logger.groupCollapsed(groupTitle);
535
+ for (const url of urls){
536
+ logger.log(url);
537
+ }
538
+ logger.groupEnd();
539
+ }
540
+ const printInstallDetails = (urlsToPrecache, urlsAlreadyPrecached)=>{
541
+ const precachedCount = urlsToPrecache.length;
542
+ const alreadyPrecachedCount = urlsAlreadyPrecached.length;
543
+ if (precachedCount || alreadyPrecachedCount) {
544
+ let message = `Precaching ${precachedCount} file${precachedCount === 1 ? "" : "s"}.`;
545
+ if (alreadyPrecachedCount > 0) {
546
+ message += ` ${alreadyPrecachedCount} ` + `file${alreadyPrecachedCount === 1 ? " is" : "s are"} already cached.`;
547
+ }
548
+ logger.groupCollapsed(message);
549
+ _nestedGroup("View newly precached URLs.", urlsToPrecache);
550
+ _nestedGroup("View previously precached URLs.", urlsAlreadyPrecached);
551
+ logger.groupEnd();
552
+ }
553
+ };
554
+
555
+ class Serwist {
556
+ _urlsToCacheKeys = new Map();
557
+ _urlsToCacheModes = new Map();
558
+ _cacheKeysToIntegrities = new Map();
559
+ _concurrentPrecaching;
560
+ _precacheStrategy;
561
+ _routes;
562
+ _defaultHandlerMap;
563
+ _catchHandler;
564
+ constructor({ precacheEntries, precacheOptions, cleanupOutdatedCaches: cleanupOutdatedCaches$1, navigateFallback, navigateFallbackAllowlist, navigateFallbackDenylist, plugins = [], fallbackToNetwork = true, concurrentPrecaching = 1, skipWaiting = false, importScripts, navigationPreload = false, cacheId, clientsClaim: clientsClaim$1 = false, runtimeCaching, offlineAnalyticsConfig, disableDevLogs: disableDevLogs$1 = false, fallbacks } = {}){
565
+ this._concurrentPrecaching = concurrentPrecaching;
566
+ this._precacheStrategy = new PrecacheStrategy({
567
+ cacheName: cacheNames.getPrecacheName(precacheOptions?.cacheName),
568
+ plugins: [
569
+ ...plugins,
570
+ new PrecacheCacheKeyPlugin({
571
+ precacheController: this
572
+ })
573
+ ],
574
+ fallbackToNetwork
575
+ });
576
+ this._routes = new Map();
577
+ this._defaultHandlerMap = new Map();
578
+ this.handleInstall = this.handleInstall.bind(this);
579
+ this.handleActivate = this.handleActivate.bind(this);
580
+ this.handleFetch = this.handleFetch.bind(this);
581
+ this.handleCache = this.handleCache.bind(this);
582
+ if (!!importScripts && importScripts.length > 0) self.importScripts(...importScripts);
583
+ if (navigationPreload) enableNavigationPreload();
584
+ if (cacheId !== undefined) {
585
+ setCacheNameDetails({
586
+ prefix: cacheId
587
+ });
588
+ }
589
+ if (skipWaiting) {
590
+ self.skipWaiting();
591
+ } else {
592
+ self.addEventListener("message", (event)=>{
593
+ if (event.data && event.data.type === "SKIP_WAITING") {
594
+ self.skipWaiting();
595
+ }
596
+ });
597
+ }
598
+ if (clientsClaim$1) clientsClaim();
599
+ this.registerRoute(new PrecacheRoute(this, precacheOptions));
600
+ if (!!precacheEntries && precacheEntries.length > 0) {
601
+ this.addToPrecacheList(precacheEntries);
602
+ }
603
+ if (cleanupOutdatedCaches$1) {
604
+ cleanupOutdatedCaches(precacheOptions?.cacheName);
605
+ }
606
+ if (navigateFallback) {
607
+ this.registerRoute(new NavigationRoute(this.createHandlerBoundToUrl(navigateFallback), {
608
+ allowlist: navigateFallbackAllowlist,
609
+ denylist: navigateFallbackDenylist
610
+ }));
611
+ }
612
+ if (offlineAnalyticsConfig !== undefined) {
613
+ if (typeof offlineAnalyticsConfig === "boolean") {
614
+ offlineAnalyticsConfig && initialize({
615
+ serwist: this
616
+ });
617
+ } else {
618
+ initialize({
619
+ ...offlineAnalyticsConfig,
620
+ serwist: this
621
+ });
622
+ }
623
+ }
624
+ if (runtimeCaching !== undefined) {
625
+ if (fallbacks !== undefined) {
626
+ const fallbackPlugin = new PrecacheFallbackPlugin({
627
+ fallbackUrls: fallbacks.entries,
628
+ serwist: this
629
+ });
630
+ runtimeCaching.forEach((cacheEntry)=>{
631
+ if (cacheEntry.handler instanceof Strategy && !cacheEntry.handler.plugins.some((plugin)=>"handlerDidError" in plugin)) {
632
+ cacheEntry.handler.plugins.push(fallbackPlugin);
633
+ }
634
+ });
635
+ }
636
+ for (const entry of runtimeCaching){
637
+ this.registerCapture(entry.matcher, entry.handler, entry.method);
638
+ }
639
+ }
640
+ if (disableDevLogs$1) disableDevLogs();
641
+ }
642
+ get precacheStrategy() {
643
+ return this._precacheStrategy;
644
+ }
645
+ get routes() {
646
+ return this._routes;
647
+ }
648
+ addEventListeners() {
649
+ self.addEventListener("install", this.handleInstall);
650
+ self.addEventListener("activate", this.handleActivate);
651
+ self.addEventListener("fetch", this.handleFetch);
652
+ self.addEventListener("message", this.handleCache);
653
+ }
654
+ addToPrecacheList(entries) {
655
+ if (process.env.NODE_ENV !== "production") {
656
+ finalAssertExports.isArray(entries, {
657
+ moduleName: "serwist",
658
+ className: "Serwist",
659
+ funcName: "addToCacheList",
660
+ paramName: "entries"
661
+ });
662
+ }
663
+ const urlsToWarnAbout = [];
664
+ for (const entry of entries){
665
+ if (typeof entry === "string") {
666
+ urlsToWarnAbout.push(entry);
667
+ } else if (entry && !entry.integrity && entry.revision === undefined) {
668
+ urlsToWarnAbout.push(entry.url);
669
+ }
670
+ const { cacheKey, url } = createCacheKey(entry);
671
+ const cacheMode = typeof entry !== "string" && entry.revision ? "reload" : "default";
672
+ if (this._urlsToCacheKeys.has(url) && this._urlsToCacheKeys.get(url) !== cacheKey) {
673
+ throw new SerwistError("add-to-cache-list-conflicting-entries", {
674
+ firstEntry: this._urlsToCacheKeys.get(url),
675
+ secondEntry: cacheKey
676
+ });
677
+ }
678
+ if (typeof entry !== "string" && entry.integrity) {
679
+ if (this._cacheKeysToIntegrities.has(cacheKey) && this._cacheKeysToIntegrities.get(cacheKey) !== entry.integrity) {
680
+ throw new SerwistError("add-to-cache-list-conflicting-integrities", {
681
+ url
682
+ });
683
+ }
684
+ this._cacheKeysToIntegrities.set(cacheKey, entry.integrity);
685
+ }
686
+ this._urlsToCacheKeys.set(url, cacheKey);
687
+ this._urlsToCacheModes.set(url, cacheMode);
688
+ if (urlsToWarnAbout.length > 0) {
689
+ const warningMessage = `Serwist is precaching URLs without revision info: ${urlsToWarnAbout.join(", ")}\nThis is generally NOT safe. Learn more at https://bit.ly/wb-precache`;
690
+ if (process.env.NODE_ENV === "production") {
691
+ console.warn(warningMessage);
692
+ } else {
693
+ logger.warn(warningMessage);
694
+ }
695
+ }
696
+ }
697
+ }
698
+ handleInstall(event) {
699
+ return waitUntil(event, async ()=>{
700
+ const installReportPlugin = new PrecacheInstallReportPlugin();
701
+ this.precacheStrategy.plugins.push(installReportPlugin);
702
+ await parallel(this._concurrentPrecaching, Array.from(this._urlsToCacheKeys.entries()), async ([url, cacheKey])=>{
703
+ const integrity = this._cacheKeysToIntegrities.get(cacheKey);
704
+ const cacheMode = this._urlsToCacheModes.get(url);
705
+ const request = new Request(url, {
706
+ integrity,
707
+ cache: cacheMode,
708
+ credentials: "same-origin"
709
+ });
710
+ await Promise.all(this.precacheStrategy.handleAll({
711
+ event,
712
+ request,
713
+ url: new URL(request.url),
714
+ params: {
715
+ cacheKey
716
+ }
717
+ }));
718
+ });
719
+ const { updatedURLs, notUpdatedURLs } = installReportPlugin;
720
+ if (process.env.NODE_ENV !== "production") {
721
+ printInstallDetails(updatedURLs, notUpdatedURLs);
722
+ }
723
+ return {
724
+ updatedURLs,
725
+ notUpdatedURLs
726
+ };
727
+ });
728
+ }
729
+ handleActivate(event) {
730
+ return waitUntil(event, async ()=>{
731
+ const cache = await self.caches.open(this.precacheStrategy.cacheName);
732
+ const currentlyCachedRequests = await cache.keys();
733
+ const expectedCacheKeys = new Set(this._urlsToCacheKeys.values());
734
+ const deletedCacheRequests = [];
735
+ for (const request of currentlyCachedRequests){
736
+ if (!expectedCacheKeys.has(request.url)) {
737
+ await cache.delete(request);
738
+ deletedCacheRequests.push(request.url);
739
+ }
740
+ }
741
+ if (process.env.NODE_ENV !== "production") {
742
+ printCleanupDetails(deletedCacheRequests);
743
+ }
744
+ return {
745
+ deletedCacheRequests
746
+ };
747
+ });
748
+ }
749
+ handleFetch(event) {
750
+ const { request } = event;
751
+ const responsePromise = this.handleRequest({
752
+ request,
753
+ event
754
+ });
755
+ if (responsePromise) {
756
+ event.respondWith(responsePromise);
757
+ }
758
+ }
759
+ handleCache(event) {
760
+ if (event.data && event.data.type === "CACHE_URLS") {
761
+ const { payload } = event.data;
762
+ if (process.env.NODE_ENV !== "production") {
763
+ logger.debug("Caching URLs from the window", payload.urlsToCache);
764
+ }
765
+ const requestPromises = Promise.all(payload.urlsToCache.map((entry)=>{
766
+ let request;
767
+ if (typeof entry === "string") {
768
+ request = new Request(entry);
769
+ } else {
770
+ request = new Request(...entry);
771
+ }
772
+ return this.handleRequest({
773
+ request,
774
+ event
775
+ });
776
+ }));
777
+ event.waitUntil(requestPromises);
778
+ if (event.ports?.[0]) {
779
+ void requestPromises.then(()=>event.ports[0].postMessage(true));
780
+ }
781
+ }
782
+ }
783
+ setDefaultHandler(handler, method = defaultMethod) {
784
+ this._defaultHandlerMap.set(method, normalizeHandler(handler));
785
+ }
786
+ setCatchHandler(handler) {
787
+ this._catchHandler = normalizeHandler(handler);
788
+ }
789
+ registerCapture(capture, handler, method) {
790
+ const route = parseRoute(capture, handler, method);
791
+ this.registerRoute(route);
792
+ return route;
793
+ }
794
+ registerRoute(route) {
795
+ if (process.env.NODE_ENV !== "production") {
796
+ finalAssertExports.isType(route, "object", {
797
+ moduleName: "serwist",
798
+ className: "Serwist",
799
+ funcName: "registerRoute",
800
+ paramName: "route"
801
+ });
802
+ finalAssertExports.hasMethod(route, "match", {
803
+ moduleName: "serwist",
804
+ className: "Serwist",
805
+ funcName: "registerRoute",
806
+ paramName: "route"
807
+ });
808
+ finalAssertExports.isType(route.handler, "object", {
809
+ moduleName: "serwist",
810
+ className: "Serwist",
811
+ funcName: "registerRoute",
812
+ paramName: "route"
813
+ });
814
+ finalAssertExports.hasMethod(route.handler, "handle", {
815
+ moduleName: "serwist",
816
+ className: "Serwist",
817
+ funcName: "registerRoute",
818
+ paramName: "route.handler"
819
+ });
820
+ finalAssertExports.isType(route.method, "string", {
821
+ moduleName: "serwist",
822
+ className: "Serwist",
823
+ funcName: "registerRoute",
824
+ paramName: "route.method"
825
+ });
826
+ }
827
+ if (!this._routes.has(route.method)) {
828
+ this._routes.set(route.method, []);
829
+ }
830
+ this._routes.get(route.method).push(route);
831
+ }
832
+ unregisterRoute(route) {
833
+ if (!this._routes.has(route.method)) {
834
+ throw new SerwistError("unregister-route-but-not-found-with-method", {
835
+ method: route.method
836
+ });
837
+ }
838
+ const routeIndex = this._routes.get(route.method).indexOf(route);
839
+ if (routeIndex > -1) {
840
+ this._routes.get(route.method).splice(routeIndex, 1);
841
+ } else {
842
+ throw new SerwistError("unregister-route-route-not-registered");
843
+ }
844
+ }
845
+ getUrlsToPrecacheKeys() {
846
+ return this._urlsToCacheKeys;
847
+ }
848
+ getPrecachedUrls() {
849
+ return [
850
+ ...this._urlsToCacheKeys.keys()
851
+ ];
852
+ }
853
+ getPrecacheKeyForUrl(url) {
854
+ const urlObject = new URL(url, location.href);
855
+ return this._urlsToCacheKeys.get(urlObject.href);
856
+ }
857
+ getIntegrityForPrecacheKey(cacheKey) {
858
+ return this._cacheKeysToIntegrities.get(cacheKey);
859
+ }
860
+ async matchPrecache(request) {
861
+ const url = request instanceof Request ? request.url : request;
862
+ const cacheKey = this.getPrecacheKeyForUrl(url);
863
+ if (cacheKey) {
864
+ const cache = await self.caches.open(this.precacheStrategy.cacheName);
865
+ return cache.match(cacheKey);
866
+ }
867
+ return undefined;
868
+ }
869
+ createHandlerBoundToUrl(url) {
870
+ const cacheKey = this.getPrecacheKeyForUrl(url);
871
+ if (!cacheKey) {
872
+ throw new SerwistError("non-precached-url", {
873
+ url
874
+ });
875
+ }
876
+ return (options)=>{
877
+ options.request = new Request(url);
878
+ options.params = {
879
+ cacheKey,
880
+ ...options.params
881
+ };
882
+ return this.precacheStrategy.handle(options);
883
+ };
884
+ }
885
+ handleRequest({ request, event }) {
886
+ if (process.env.NODE_ENV !== "production") {
887
+ finalAssertExports.isInstance(request, Request, {
888
+ moduleName: "serwist",
889
+ className: "Serwist",
890
+ funcName: "handleRequest",
891
+ paramName: "options.request"
892
+ });
893
+ }
894
+ const url = new URL(request.url, location.href);
895
+ if (!url.protocol.startsWith("http")) {
896
+ if (process.env.NODE_ENV !== "production") {
897
+ logger.debug("Router only supports URLs that start with 'http'.");
898
+ }
899
+ return;
900
+ }
901
+ const sameOrigin = url.origin === location.origin;
902
+ const { params, route } = this.findMatchingRoute({
903
+ event,
904
+ request,
905
+ sameOrigin,
906
+ url
907
+ });
908
+ let handler = route?.handler;
909
+ const debugMessages = [];
910
+ if (process.env.NODE_ENV !== "production") {
911
+ if (handler) {
912
+ debugMessages.push([
913
+ "Found a route to handle this request:",
914
+ route
915
+ ]);
916
+ if (params) {
917
+ debugMessages.push([
918
+ `Passing the following params to the route's handler:`,
919
+ params
920
+ ]);
921
+ }
922
+ }
923
+ }
924
+ const method = request.method;
925
+ if (!handler && this._defaultHandlerMap.has(method)) {
926
+ if (process.env.NODE_ENV !== "production") {
927
+ debugMessages.push(`Failed to find a matching route. Falling back to the default handler for ${method}.`);
928
+ }
929
+ handler = this._defaultHandlerMap.get(method);
930
+ }
931
+ if (!handler) {
932
+ if (process.env.NODE_ENV !== "production") {
933
+ logger.debug(`No route found for: ${getFriendlyURL(url)}`);
934
+ }
935
+ return;
936
+ }
937
+ if (process.env.NODE_ENV !== "production") {
938
+ logger.groupCollapsed(`Router is responding to: ${getFriendlyURL(url)}`);
939
+ for (const msg of debugMessages){
940
+ if (Array.isArray(msg)) {
941
+ logger.log(...msg);
942
+ } else {
943
+ logger.log(msg);
944
+ }
945
+ }
946
+ logger.groupEnd();
947
+ }
948
+ let responsePromise;
949
+ try {
950
+ responsePromise = handler.handle({
951
+ url,
952
+ request,
953
+ event,
954
+ params
955
+ });
956
+ } catch (err) {
957
+ responsePromise = Promise.reject(err);
958
+ }
959
+ const catchHandler = route?.catchHandler;
960
+ if (responsePromise instanceof Promise && (this._catchHandler || catchHandler)) {
961
+ responsePromise = responsePromise.catch(async (err)=>{
962
+ if (catchHandler) {
963
+ if (process.env.NODE_ENV !== "production") {
964
+ logger.groupCollapsed(`Error thrown when responding to: ${getFriendlyURL(url)}. Falling back to route's Catch Handler.`);
965
+ logger.error("Error thrown by:", route);
966
+ logger.error(err);
967
+ logger.groupEnd();
968
+ }
969
+ try {
970
+ return await catchHandler.handle({
971
+ url,
972
+ request,
973
+ event,
974
+ params
975
+ });
976
+ } catch (catchErr) {
977
+ if (catchErr instanceof Error) {
978
+ err = catchErr;
979
+ }
980
+ }
981
+ }
982
+ if (this._catchHandler) {
983
+ if (process.env.NODE_ENV !== "production") {
984
+ logger.groupCollapsed(`Error thrown when responding to: ${getFriendlyURL(url)}. Falling back to global Catch Handler.`);
985
+ logger.error("Error thrown by:", route);
986
+ logger.error(err);
987
+ logger.groupEnd();
988
+ }
989
+ return this._catchHandler.handle({
990
+ url,
991
+ request,
992
+ event
993
+ });
994
+ }
995
+ throw err;
996
+ });
997
+ }
998
+ return responsePromise;
999
+ }
1000
+ findMatchingRoute({ url, sameOrigin, request, event }) {
1001
+ const routes = this._routes.get(request.method) || [];
1002
+ for (const route of routes){
1003
+ let params;
1004
+ const matchResult = route.match({
1005
+ url,
1006
+ sameOrigin,
1007
+ request,
1008
+ event
1009
+ });
1010
+ if (matchResult) {
1011
+ if (process.env.NODE_ENV !== "production") {
1012
+ if (matchResult instanceof Promise) {
1013
+ logger.warn(`While routing ${getFriendlyURL(url)}, an async matchCallback function was used. Please convert the following route to use a synchronous matchCallback function:`, route);
1014
+ }
1015
+ }
1016
+ params = matchResult;
1017
+ if (Array.isArray(params) && params.length === 0) {
1018
+ params = undefined;
1019
+ } else if (matchResult.constructor === Object && Object.keys(matchResult).length === 0) {
1020
+ params = undefined;
1021
+ } else if (typeof matchResult === "boolean") {
1022
+ params = undefined;
1023
+ }
1024
+ return {
1025
+ route,
1026
+ params
1027
+ };
1028
+ }
1029
+ }
1030
+ return {};
1031
+ }
1032
+ }
1033
+
1034
+ export { NavigationRoute as N, PrecacheRoute as P, RegExpRoute as R, Serwist as S, clientsClaim as a, copyResponse as b, cleanupOutdatedCaches as c, disableDevLogs as d, disableNavigationPreload as e, enableNavigationPreload as f, PrecacheStrategy as g, createCacheKey as h, isNavigationPreloadSupported as i, parallel as j, printInstallDetails as k, printCleanupDetails as l, PrecacheInstallReportPlugin as m, generateURLVariations as n, parseRoute as p, setCacheNameDetails as s };