serwist 9.0.0-preview.24 → 9.0.0-preview.26

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 (232) hide show
  1. package/dist/NavigationRoute.d.ts +6 -7
  2. package/dist/NavigationRoute.d.ts.map +1 -1
  3. package/dist/PrecacheRoute.d.ts +2 -2
  4. package/dist/PrecacheRoute.d.ts.map +1 -1
  5. package/dist/RegExpRoute.d.ts +4 -4
  6. package/dist/RegExpRoute.d.ts.map +1 -1
  7. package/dist/Route.d.ts +10 -10
  8. package/dist/Route.d.ts.map +1 -1
  9. package/dist/Serwist.d.ts +39 -44
  10. package/dist/Serwist.d.ts.map +1 -1
  11. package/dist/chunks/printInstallDetails.js +1587 -0
  12. package/dist/chunks/resultingClientExists.js +1 -1
  13. package/dist/chunks/waitUntil.js +426 -1
  14. package/dist/copyResponse.d.ts +8 -10
  15. package/dist/copyResponse.d.ts.map +1 -1
  16. package/dist/disableDevLogs.d.ts +1 -1
  17. package/dist/index.d.ts +41 -12
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.internal.d.ts +3 -1
  20. package/dist/index.internal.d.ts.map +1 -1
  21. package/dist/index.internal.js +1 -2
  22. package/dist/index.js +1464 -8
  23. package/dist/index.legacy.d.ts +4 -8
  24. package/dist/index.legacy.d.ts.map +1 -1
  25. package/dist/index.legacy.js +166 -16
  26. package/dist/legacy/PrecacheController.d.ts +1 -1
  27. package/dist/legacy/PrecacheController.d.ts.map +1 -1
  28. package/dist/legacy/PrecacheRoute.d.ts.map +1 -1
  29. package/dist/legacy/Router.d.ts +1 -1
  30. package/dist/legacy/Router.d.ts.map +1 -1
  31. package/dist/legacy/constants.d.ts.map +1 -0
  32. package/dist/legacy/fallbacks.d.ts +1 -1
  33. package/dist/legacy/fallbacks.d.ts.map +1 -1
  34. package/dist/legacy/handlePrecaching.d.ts.map +1 -1
  35. package/dist/legacy/initializeGoogleAnalytics.d.ts +38 -0
  36. package/dist/legacy/initializeGoogleAnalytics.d.ts.map +1 -0
  37. package/dist/legacy/installSerwist.d.ts +69 -3
  38. package/dist/legacy/installSerwist.d.ts.map +1 -1
  39. package/dist/legacy/registerRoute.d.ts +1 -1
  40. package/dist/legacy/registerRoute.d.ts.map +1 -1
  41. package/dist/{plugins → lib}/backgroundSync/BackgroundSyncPlugin.d.ts +3 -3
  42. package/dist/lib/backgroundSync/BackgroundSyncPlugin.d.ts.map +1 -0
  43. package/dist/{plugins/backgroundSync/Queue.d.ts → lib/backgroundSync/BackgroundSyncQueue.d.ts} +29 -13
  44. package/dist/lib/backgroundSync/BackgroundSyncQueue.d.ts.map +1 -0
  45. package/dist/{plugins/backgroundSync/QueueDb.d.ts → lib/backgroundSync/BackgroundSyncQueueDb.d.ts} +7 -7
  46. package/dist/lib/backgroundSync/BackgroundSyncQueueDb.d.ts.map +1 -0
  47. package/dist/{plugins/backgroundSync/QueueStore.d.ts → lib/backgroundSync/BackgroundSyncQueueStore.d.ts} +7 -7
  48. package/dist/lib/backgroundSync/BackgroundSyncQueueStore.d.ts.map +1 -0
  49. package/dist/lib/backgroundSync/StorableRequest.d.ts.map +1 -0
  50. package/dist/lib/broadcastUpdate/BroadcastCacheUpdate.d.ts.map +1 -0
  51. package/dist/{plugins → lib}/broadcastUpdate/BroadcastUpdatePlugin.d.ts +1 -1
  52. package/dist/lib/broadcastUpdate/BroadcastUpdatePlugin.d.ts.map +1 -0
  53. package/dist/lib/broadcastUpdate/constants.d.ts +5 -0
  54. package/dist/lib/broadcastUpdate/constants.d.ts.map +1 -0
  55. package/dist/lib/broadcastUpdate/responsesAreSame.d.ts.map +1 -0
  56. package/dist/{plugins → lib}/broadcastUpdate/types.d.ts +3 -3
  57. package/dist/lib/broadcastUpdate/types.d.ts.map +1 -0
  58. package/dist/lib/cacheableResponse/CacheableResponse.d.ts.map +1 -0
  59. package/dist/lib/cacheableResponse/CacheableResponsePlugin.d.ts.map +1 -0
  60. package/dist/{plugins → lib}/expiration/CacheExpiration.d.ts +1 -1
  61. package/dist/lib/expiration/CacheExpiration.d.ts.map +1 -0
  62. package/dist/{plugins → lib}/expiration/ExpirationPlugin.d.ts +1 -1
  63. package/dist/lib/expiration/ExpirationPlugin.d.ts.map +1 -0
  64. package/dist/lib/expiration/models/CacheTimestampsModel.d.ts.map +1 -0
  65. package/dist/lib/googleAnalytics/constants.d.ts +10 -0
  66. package/dist/lib/googleAnalytics/constants.d.ts.map +1 -0
  67. package/dist/{plugins/googleAnalytics/initialize.d.ts → lib/googleAnalytics/initializeGoogleAnalytics.d.ts} +2 -2
  68. package/dist/lib/googleAnalytics/initializeGoogleAnalytics.d.ts.map +1 -0
  69. package/dist/{plugins → lib}/precaching/PrecacheFallbackPlugin.d.ts +1 -1
  70. package/dist/lib/precaching/PrecacheFallbackPlugin.d.ts.map +1 -0
  71. package/dist/lib/rangeRequests/RangeRequestsPlugin.d.ts.map +1 -0
  72. package/dist/lib/rangeRequests/createPartialResponse.d.ts.map +1 -0
  73. package/dist/lib/rangeRequests/utils/calculateEffectiveBoundaries.d.ts.map +1 -0
  74. package/dist/lib/rangeRequests/utils/parseRangeHeader.d.ts.map +1 -0
  75. package/dist/{strategies → lib/strategies}/CacheFirst.d.ts +1 -1
  76. package/dist/lib/strategies/CacheFirst.d.ts.map +1 -0
  77. package/dist/{strategies → lib/strategies}/CacheOnly.d.ts +2 -2
  78. package/dist/lib/strategies/CacheOnly.d.ts.map +1 -0
  79. package/dist/{strategies → lib/strategies}/NetworkFirst.d.ts +2 -2
  80. package/dist/lib/strategies/NetworkFirst.d.ts.map +1 -0
  81. package/dist/{strategies → lib/strategies}/NetworkOnly.d.ts +2 -2
  82. package/dist/lib/strategies/NetworkOnly.d.ts.map +1 -0
  83. package/dist/{PrecacheStrategy.d.ts → lib/strategies/PrecacheStrategy.d.ts} +5 -5
  84. package/dist/lib/strategies/PrecacheStrategy.d.ts.map +1 -0
  85. package/dist/{strategies → lib/strategies}/StaleWhileRevalidate.d.ts +1 -1
  86. package/dist/lib/strategies/StaleWhileRevalidate.d.ts.map +1 -0
  87. package/dist/{strategies → lib/strategies}/Strategy.d.ts +15 -17
  88. package/dist/lib/strategies/Strategy.d.ts.map +1 -0
  89. package/dist/{strategies → lib/strategies}/StrategyHandler.d.ts +35 -41
  90. package/dist/lib/strategies/StrategyHandler.d.ts.map +1 -0
  91. package/dist/lib/strategies/plugins/cacheOkAndOpaquePlugin.d.ts +3 -0
  92. package/dist/lib/strategies/plugins/cacheOkAndOpaquePlugin.d.ts.map +1 -0
  93. package/dist/lib/strategies/utils/messages.d.ts.map +1 -0
  94. package/dist/navigationPreload.d.ts +3 -3
  95. package/dist/types.d.ts +12 -7
  96. package/dist/types.d.ts.map +1 -1
  97. package/dist/utils/PrecacheCacheKeyPlugin.d.ts +1 -1
  98. package/dist/utils/PrecacheCacheKeyPlugin.d.ts.map +1 -1
  99. package/dist/utils/assert.d.ts.map +1 -1
  100. package/dist/utils/cleanupOutdatedCaches.d.ts.map +1 -0
  101. package/dist/utils/clientsClaim.d.ts.map +1 -0
  102. package/dist/{parseRoute.d.ts → utils/parseRoute.d.ts} +3 -3
  103. package/dist/utils/parseRoute.d.ts.map +1 -0
  104. package/package.json +7 -21
  105. package/src/NavigationRoute.ts +6 -7
  106. package/src/PrecacheRoute.ts +5 -5
  107. package/src/RegExpRoute.ts +5 -5
  108. package/src/Route.ts +11 -11
  109. package/src/Serwist.ts +73 -80
  110. package/src/copyResponse.ts +7 -9
  111. package/src/disableDevLogs.ts +1 -1
  112. package/src/index.internal.ts +4 -0
  113. package/src/index.legacy.ts +14 -18
  114. package/src/index.ts +105 -19
  115. package/src/legacy/PrecacheController.ts +8 -8
  116. package/src/legacy/PrecacheFallbackPlugin.ts +1 -1
  117. package/src/legacy/PrecacheRoute.ts +3 -3
  118. package/src/legacy/Router.ts +5 -5
  119. package/src/legacy/fallbacks.ts +3 -3
  120. package/src/legacy/handlePrecaching.ts +1 -1
  121. package/src/legacy/initializeGoogleAnalytics.ts +218 -0
  122. package/src/legacy/installSerwist.ts +156 -5
  123. package/src/legacy/registerRoute.ts +1 -1
  124. package/src/{plugins → lib}/backgroundSync/BackgroundSyncPlugin.ts +6 -6
  125. package/src/{plugins/backgroundSync/Queue.ts → lib/backgroundSync/BackgroundSyncQueue.ts} +47 -26
  126. package/src/{plugins/backgroundSync/QueueDb.ts → lib/backgroundSync/BackgroundSyncQueueDb.ts} +16 -16
  127. package/src/{plugins/backgroundSync/QueueStore.ts → lib/backgroundSync/BackgroundSyncQueueStore.ts} +13 -13
  128. package/src/{plugins → lib}/backgroundSync/StorableRequest.ts +2 -2
  129. package/src/{plugins → lib}/broadcastUpdate/BroadcastCacheUpdate.ts +14 -9
  130. package/src/{plugins → lib}/broadcastUpdate/BroadcastUpdatePlugin.ts +1 -1
  131. package/src/lib/broadcastUpdate/constants.ts +12 -0
  132. package/src/{plugins → lib}/broadcastUpdate/types.ts +3 -3
  133. package/src/{plugins → lib}/cacheableResponse/CacheableResponse.ts +5 -5
  134. package/src/{plugins → lib}/expiration/CacheExpiration.ts +7 -7
  135. package/src/{plugins → lib}/expiration/ExpirationPlugin.ts +10 -10
  136. package/src/lib/googleAnalytics/constants.ts +22 -0
  137. package/src/{plugins/googleAnalytics/initialize.ts → lib/googleAnalytics/initializeGoogleAnalytics.ts} +9 -9
  138. package/src/{strategies → lib/strategies}/CacheFirst.ts +5 -5
  139. package/src/{strategies → lib/strategies}/CacheOnly.ts +6 -6
  140. package/src/{strategies → lib/strategies}/NetworkFirst.ts +7 -7
  141. package/src/{strategies → lib/strategies}/NetworkOnly.ts +7 -7
  142. package/src/{PrecacheStrategy.ts → lib/strategies/PrecacheStrategy.ts} +14 -10
  143. package/src/{strategies → lib/strategies}/StaleWhileRevalidate.ts +5 -5
  144. package/src/{strategies → lib/strategies}/Strategy.ts +19 -21
  145. package/src/{strategies → lib/strategies}/StrategyHandler.ts +45 -51
  146. package/src/{strategies → lib/strategies}/plugins/cacheOkAndOpaquePlugin.ts +1 -1
  147. package/src/{strategies → lib/strategies}/utils/messages.ts +2 -2
  148. package/src/models/messages/messages.ts +1 -1
  149. package/src/navigationPreload.ts +3 -3
  150. package/src/registerQuotaErrorCallback.ts +1 -1
  151. package/src/types.ts +12 -7
  152. package/src/utils/PrecacheCacheKeyPlugin.ts +1 -1
  153. package/src/utils/assert.ts +1 -1
  154. package/src/{cleanupOutdatedCaches.ts → utils/cleanupOutdatedCaches.ts} +3 -4
  155. package/src/utils/executeQuotaErrorCallbacks.ts +1 -1
  156. package/src/{parseRoute.ts → utils/parseRoute.ts} +21 -23
  157. package/src/utils/welcome.ts +1 -1
  158. package/dist/PrecacheStrategy.d.ts.map +0 -1
  159. package/dist/chunks/NetworkOnly.js +0 -599
  160. package/dist/chunks/PrecacheFallbackPlugin.js +0 -634
  161. package/dist/chunks/Serwist.js +0 -1034
  162. package/dist/chunks/registerQuotaErrorCallback.js +0 -17
  163. package/dist/chunks/timeout.js +0 -400
  164. package/dist/cleanupOutdatedCaches.d.ts.map +0 -1
  165. package/dist/clientsClaim.d.ts.map +0 -1
  166. package/dist/index.plugins.d.ts +0 -41
  167. package/dist/index.plugins.d.ts.map +0 -1
  168. package/dist/index.plugins.js +0 -669
  169. package/dist/index.strategies.d.ts +0 -22
  170. package/dist/index.strategies.d.ts.map +0 -1
  171. package/dist/index.strategies.js +0 -144
  172. package/dist/parseRoute.d.ts.map +0 -1
  173. package/dist/plugins/backgroundSync/BackgroundSyncPlugin.d.ts.map +0 -1
  174. package/dist/plugins/backgroundSync/Queue.d.ts.map +0 -1
  175. package/dist/plugins/backgroundSync/QueueDb.d.ts.map +0 -1
  176. package/dist/plugins/backgroundSync/QueueStore.d.ts.map +0 -1
  177. package/dist/plugins/backgroundSync/StorableRequest.d.ts.map +0 -1
  178. package/dist/plugins/broadcastUpdate/BroadcastCacheUpdate.d.ts.map +0 -1
  179. package/dist/plugins/broadcastUpdate/BroadcastUpdatePlugin.d.ts.map +0 -1
  180. package/dist/plugins/broadcastUpdate/constants.d.ts +0 -5
  181. package/dist/plugins/broadcastUpdate/constants.d.ts.map +0 -1
  182. package/dist/plugins/broadcastUpdate/responsesAreSame.d.ts.map +0 -1
  183. package/dist/plugins/broadcastUpdate/types.d.ts.map +0 -1
  184. package/dist/plugins/cacheableResponse/CacheableResponse.d.ts.map +0 -1
  185. package/dist/plugins/cacheableResponse/CacheableResponsePlugin.d.ts.map +0 -1
  186. package/dist/plugins/expiration/CacheExpiration.d.ts.map +0 -1
  187. package/dist/plugins/expiration/ExpirationPlugin.d.ts.map +0 -1
  188. package/dist/plugins/expiration/models/CacheTimestampsModel.d.ts.map +0 -1
  189. package/dist/plugins/googleAnalytics/constants.d.ts.map +0 -1
  190. package/dist/plugins/googleAnalytics/initialize.d.ts.map +0 -1
  191. package/dist/plugins/precaching/PrecacheFallbackPlugin.d.ts.map +0 -1
  192. package/dist/plugins/rangeRequests/RangeRequestsPlugin.d.ts.map +0 -1
  193. package/dist/plugins/rangeRequests/createPartialResponse.d.ts.map +0 -1
  194. package/dist/plugins/rangeRequests/utils/calculateEffectiveBoundaries.d.ts.map +0 -1
  195. package/dist/plugins/rangeRequests/utils/parseRangeHeader.d.ts.map +0 -1
  196. package/dist/strategies/CacheFirst.d.ts.map +0 -1
  197. package/dist/strategies/CacheOnly.d.ts.map +0 -1
  198. package/dist/strategies/NetworkFirst.d.ts.map +0 -1
  199. package/dist/strategies/NetworkOnly.d.ts.map +0 -1
  200. package/dist/strategies/StaleWhileRevalidate.d.ts.map +0 -1
  201. package/dist/strategies/Strategy.d.ts.map +0 -1
  202. package/dist/strategies/StrategyHandler.d.ts.map +0 -1
  203. package/dist/strategies/plugins/cacheOkAndOpaquePlugin.d.ts +0 -3
  204. package/dist/strategies/plugins/cacheOkAndOpaquePlugin.d.ts.map +0 -1
  205. package/dist/strategies/utils/messages.d.ts.map +0 -1
  206. package/src/index.plugins.ts +0 -95
  207. package/src/index.strategies.ts +0 -26
  208. package/src/plugins/broadcastUpdate/constants.ts +0 -12
  209. package/dist/{plugins/googleAnalytics → legacy}/constants.d.ts +0 -0
  210. package/dist/{plugins → lib}/backgroundSync/StorableRequest.d.ts +0 -0
  211. package/dist/{plugins → lib}/broadcastUpdate/BroadcastCacheUpdate.d.ts +0 -0
  212. package/dist/{plugins → lib}/broadcastUpdate/responsesAreSame.d.ts +0 -0
  213. package/dist/{plugins → lib}/cacheableResponse/CacheableResponse.d.ts +0 -0
  214. package/dist/{plugins → lib}/cacheableResponse/CacheableResponsePlugin.d.ts +0 -0
  215. package/dist/{plugins → lib}/expiration/models/CacheTimestampsModel.d.ts +0 -0
  216. package/dist/{plugins → lib}/rangeRequests/RangeRequestsPlugin.d.ts +0 -0
  217. package/dist/{plugins → lib}/rangeRequests/createPartialResponse.d.ts +0 -0
  218. package/dist/{plugins → lib}/rangeRequests/utils/calculateEffectiveBoundaries.d.ts +0 -0
  219. package/dist/{plugins → lib}/rangeRequests/utils/parseRangeHeader.d.ts +0 -0
  220. package/dist/{strategies → lib/strategies}/utils/messages.d.ts +0 -0
  221. package/dist/{cleanupOutdatedCaches.d.ts → utils/cleanupOutdatedCaches.d.ts} +0 -0
  222. package/dist/{clientsClaim.d.ts → utils/clientsClaim.d.ts} +0 -0
  223. package/src/{plugins/googleAnalytics → legacy}/constants.ts +0 -0
  224. package/src/{plugins → lib}/broadcastUpdate/responsesAreSame.ts +0 -0
  225. package/src/{plugins → lib}/cacheableResponse/CacheableResponsePlugin.ts +0 -0
  226. package/src/{plugins → lib}/expiration/models/CacheTimestampsModel.ts +0 -0
  227. package/src/{plugins → lib}/precaching/PrecacheFallbackPlugin.ts +1 -1
  228. package/src/{plugins → lib}/rangeRequests/RangeRequestsPlugin.ts +0 -0
  229. package/src/{plugins → lib}/rangeRequests/createPartialResponse.ts +1 -1
  230. package/src/{plugins → lib}/rangeRequests/utils/calculateEffectiveBoundaries.ts +1 -1
  231. package/src/{plugins → lib}/rangeRequests/utils/parseRangeHeader.ts +1 -1
  232. /package/src/{clientsClaim.ts → utils/clientsClaim.ts} +0 -0
@@ -0,0 +1,1587 @@
1
+ import { f as finalAssertExports, l as logger, D as Deferred, g as getFriendlyURL, S as SerwistError, t as timeout, d as cacheMatchIgnoreParams, e as executeQuotaErrorCallbacks, c as cacheNames, h as canConstructResponseFromBodyStream } from './waitUntil.js';
2
+ import { openDB } from 'idb';
3
+
4
+ const defaultMethod = "GET";
5
+ const validMethods = [
6
+ "DELETE",
7
+ "GET",
8
+ "HEAD",
9
+ "PATCH",
10
+ "POST",
11
+ "PUT"
12
+ ];
13
+
14
+ const normalizeHandler = (handler)=>{
15
+ if (handler && typeof handler === "object") {
16
+ if (process.env.NODE_ENV !== "production") {
17
+ finalAssertExports.hasMethod(handler, "handle", {
18
+ moduleName: "serwist",
19
+ className: "Route",
20
+ funcName: "constructor",
21
+ paramName: "handler"
22
+ });
23
+ }
24
+ return handler;
25
+ }
26
+ if (process.env.NODE_ENV !== "production") {
27
+ finalAssertExports.isType(handler, "function", {
28
+ moduleName: "serwist",
29
+ className: "Route",
30
+ funcName: "constructor",
31
+ paramName: "handler"
32
+ });
33
+ }
34
+ return {
35
+ handle: handler
36
+ };
37
+ };
38
+
39
+ class Route {
40
+ handler;
41
+ match;
42
+ method;
43
+ catchHandler;
44
+ constructor(match, handler, method = defaultMethod){
45
+ if (process.env.NODE_ENV !== "production") {
46
+ finalAssertExports.isType(match, "function", {
47
+ moduleName: "serwist",
48
+ className: "Route",
49
+ funcName: "constructor",
50
+ paramName: "match"
51
+ });
52
+ if (method) {
53
+ finalAssertExports.isOneOf(method, validMethods, {
54
+ paramName: "method"
55
+ });
56
+ }
57
+ }
58
+ this.handler = normalizeHandler(handler);
59
+ this.match = match;
60
+ this.method = method;
61
+ }
62
+ setCatchHandler(handler) {
63
+ this.catchHandler = normalizeHandler(handler);
64
+ }
65
+ }
66
+
67
+ class NavigationRoute extends Route {
68
+ _allowlist;
69
+ _denylist;
70
+ constructor(handler, { allowlist = [
71
+ /./
72
+ ], denylist = [] } = {}){
73
+ if (process.env.NODE_ENV !== "production") {
74
+ finalAssertExports.isArrayOfClass(allowlist, RegExp, {
75
+ moduleName: "serwist",
76
+ className: "NavigationRoute",
77
+ funcName: "constructor",
78
+ paramName: "options.allowlist"
79
+ });
80
+ finalAssertExports.isArrayOfClass(denylist, RegExp, {
81
+ moduleName: "serwist",
82
+ className: "NavigationRoute",
83
+ funcName: "constructor",
84
+ paramName: "options.denylist"
85
+ });
86
+ }
87
+ super((options)=>this._match(options), handler);
88
+ this._allowlist = allowlist;
89
+ this._denylist = denylist;
90
+ }
91
+ _match({ url, request }) {
92
+ if (request && request.mode !== "navigate") {
93
+ return false;
94
+ }
95
+ const pathnameAndSearch = url.pathname + url.search;
96
+ for (const regExp of this._denylist){
97
+ if (regExp.test(pathnameAndSearch)) {
98
+ if (process.env.NODE_ENV !== "production") {
99
+ logger.log(`The navigation route ${pathnameAndSearch} is not being used, since the URL matches this denylist pattern: ${regExp.toString()}`);
100
+ }
101
+ return false;
102
+ }
103
+ }
104
+ if (this._allowlist.some((regExp)=>regExp.test(pathnameAndSearch))) {
105
+ if (process.env.NODE_ENV !== "production") {
106
+ logger.debug(`The navigation route ${pathnameAndSearch} is being used.`);
107
+ }
108
+ return true;
109
+ }
110
+ if (process.env.NODE_ENV !== "production") {
111
+ logger.log(`The navigation route ${pathnameAndSearch} is not being used, since the URL being navigated to doesn't match the allowlist.`);
112
+ }
113
+ return false;
114
+ }
115
+ }
116
+
117
+ const removeIgnoredSearchParams = (urlObject, ignoreURLParametersMatching = [])=>{
118
+ for (const paramName of [
119
+ ...urlObject.searchParams.keys()
120
+ ]){
121
+ if (ignoreURLParametersMatching.some((regExp)=>regExp.test(paramName))) {
122
+ urlObject.searchParams.delete(paramName);
123
+ }
124
+ }
125
+ return urlObject;
126
+ };
127
+
128
+ function* generateURLVariations(url, { directoryIndex = "index.html", ignoreURLParametersMatching = [
129
+ /^utm_/,
130
+ /^fbclid$/
131
+ ], cleanURLs = true, urlManipulation } = {}) {
132
+ const urlObject = new URL(url, location.href);
133
+ urlObject.hash = "";
134
+ yield urlObject.href;
135
+ const urlWithoutIgnoredParams = removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching);
136
+ yield urlWithoutIgnoredParams.href;
137
+ if (directoryIndex && urlWithoutIgnoredParams.pathname.endsWith("/")) {
138
+ const directoryURL = new URL(urlWithoutIgnoredParams.href);
139
+ directoryURL.pathname += directoryIndex;
140
+ yield directoryURL.href;
141
+ }
142
+ if (cleanURLs) {
143
+ const cleanURL = new URL(urlWithoutIgnoredParams.href);
144
+ cleanURL.pathname += ".html";
145
+ yield cleanURL.href;
146
+ }
147
+ if (urlManipulation) {
148
+ const additionalURLs = urlManipulation({
149
+ url: urlObject
150
+ });
151
+ for (const urlToAttempt of additionalURLs){
152
+ yield urlToAttempt.href;
153
+ }
154
+ }
155
+ }
156
+
157
+ class RegExpRoute extends Route {
158
+ constructor(regExp, handler, method){
159
+ if (process.env.NODE_ENV !== "production") {
160
+ finalAssertExports.isInstance(regExp, RegExp, {
161
+ moduleName: "serwist",
162
+ className: "RegExpRoute",
163
+ funcName: "constructor",
164
+ paramName: "pattern"
165
+ });
166
+ }
167
+ const match = ({ url })=>{
168
+ const result = regExp.exec(url.href);
169
+ if (!result) {
170
+ return;
171
+ }
172
+ if (url.origin !== location.origin && result.index !== 0) {
173
+ if (process.env.NODE_ENV !== "production") {
174
+ 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.`);
175
+ }
176
+ return;
177
+ }
178
+ return result.slice(1);
179
+ };
180
+ super(match, handler, method);
181
+ }
182
+ }
183
+
184
+ const parallel = async (limit, array, func)=>{
185
+ const work = array.map((item, index)=>({
186
+ index,
187
+ item
188
+ }));
189
+ const processor = async (res)=>{
190
+ const results = [];
191
+ while(true){
192
+ const next = work.pop();
193
+ if (!next) {
194
+ return res(results);
195
+ }
196
+ const result = await func(next.item);
197
+ results.push({
198
+ result: result,
199
+ index: next.index
200
+ });
201
+ }
202
+ };
203
+ const queues = Array.from({
204
+ length: limit
205
+ }, ()=>new Promise(processor));
206
+ const results = (await Promise.all(queues)).flat().sort((a, b)=>a.index < b.index ? -1 : 1).map((res)=>res.result);
207
+ return results;
208
+ };
209
+
210
+ const disableDevLogs = ()=>{
211
+ self.__WB_DISABLE_DEV_LOGS = true;
212
+ };
213
+
214
+ function toRequest(input) {
215
+ return typeof input === "string" ? new Request(input) : input;
216
+ }
217
+ class StrategyHandler {
218
+ event;
219
+ request;
220
+ url;
221
+ params;
222
+ _cacheKeys = {};
223
+ _strategy;
224
+ _handlerDeferred;
225
+ _extendLifetimePromises;
226
+ _plugins;
227
+ _pluginStateMap;
228
+ constructor(strategy, options){
229
+ if (process.env.NODE_ENV !== "production") {
230
+ finalAssertExports.isInstance(options.event, ExtendableEvent, {
231
+ moduleName: "serwist",
232
+ className: "StrategyHandler",
233
+ funcName: "constructor",
234
+ paramName: "options.event"
235
+ });
236
+ finalAssertExports.isInstance(options.request, Request, {
237
+ moduleName: "serwist",
238
+ className: "StrategyHandler",
239
+ funcName: "constructor",
240
+ paramName: "options.request"
241
+ });
242
+ }
243
+ this.event = options.event;
244
+ this.request = options.request;
245
+ if (options.url) {
246
+ this.url = options.url;
247
+ this.params = options.params;
248
+ }
249
+ this._strategy = strategy;
250
+ this._handlerDeferred = new Deferred();
251
+ this._extendLifetimePromises = [];
252
+ this._plugins = [
253
+ ...strategy.plugins
254
+ ];
255
+ this._pluginStateMap = new Map();
256
+ for (const plugin of this._plugins){
257
+ this._pluginStateMap.set(plugin, {});
258
+ }
259
+ this.event.waitUntil(this._handlerDeferred.promise);
260
+ }
261
+ async fetch(input) {
262
+ const { event } = this;
263
+ let request = toRequest(input);
264
+ if (request.mode === "navigate" && event instanceof FetchEvent && event.preloadResponse) {
265
+ const possiblePreloadResponse = await event.preloadResponse;
266
+ if (possiblePreloadResponse) {
267
+ if (process.env.NODE_ENV !== "production") {
268
+ logger.log(`Using a preloaded navigation response for '${getFriendlyURL(request.url)}'`);
269
+ }
270
+ return possiblePreloadResponse;
271
+ }
272
+ }
273
+ const originalRequest = this.hasCallback("fetchDidFail") ? request.clone() : null;
274
+ try {
275
+ for (const cb of this.iterateCallbacks("requestWillFetch")){
276
+ request = await cb({
277
+ request: request.clone(),
278
+ event
279
+ });
280
+ }
281
+ } catch (err) {
282
+ if (err instanceof Error) {
283
+ throw new SerwistError("plugin-error-request-will-fetch", {
284
+ thrownErrorMessage: err.message
285
+ });
286
+ }
287
+ }
288
+ const pluginFilteredRequest = request.clone();
289
+ try {
290
+ let fetchResponse;
291
+ fetchResponse = await fetch(request, request.mode === "navigate" ? undefined : this._strategy.fetchOptions);
292
+ if (process.env.NODE_ENV !== "production") {
293
+ logger.debug(`Network request for '${getFriendlyURL(request.url)}' returned a response with status '${fetchResponse.status}'.`);
294
+ }
295
+ for (const callback of this.iterateCallbacks("fetchDidSucceed")){
296
+ fetchResponse = await callback({
297
+ event,
298
+ request: pluginFilteredRequest,
299
+ response: fetchResponse
300
+ });
301
+ }
302
+ return fetchResponse;
303
+ } catch (error) {
304
+ if (process.env.NODE_ENV !== "production") {
305
+ logger.log(`Network request for '${getFriendlyURL(request.url)}' threw an error.`, error);
306
+ }
307
+ if (originalRequest) {
308
+ await this.runCallbacks("fetchDidFail", {
309
+ error: error,
310
+ event,
311
+ originalRequest: originalRequest.clone(),
312
+ request: pluginFilteredRequest.clone()
313
+ });
314
+ }
315
+ throw error;
316
+ }
317
+ }
318
+ async fetchAndCachePut(input) {
319
+ const response = await this.fetch(input);
320
+ const responseClone = response.clone();
321
+ void this.waitUntil(this.cachePut(input, responseClone));
322
+ return response;
323
+ }
324
+ async cacheMatch(key) {
325
+ const request = toRequest(key);
326
+ let cachedResponse;
327
+ const { cacheName, matchOptions } = this._strategy;
328
+ const effectiveRequest = await this.getCacheKey(request, "read");
329
+ const multiMatchOptions = {
330
+ ...matchOptions,
331
+ ...{
332
+ cacheName
333
+ }
334
+ };
335
+ cachedResponse = await caches.match(effectiveRequest, multiMatchOptions);
336
+ if (process.env.NODE_ENV !== "production") {
337
+ if (cachedResponse) {
338
+ logger.debug(`Found a cached response in '${cacheName}'.`);
339
+ } else {
340
+ logger.debug(`No cached response found in '${cacheName}'.`);
341
+ }
342
+ }
343
+ for (const callback of this.iterateCallbacks("cachedResponseWillBeUsed")){
344
+ cachedResponse = await callback({
345
+ cacheName,
346
+ matchOptions,
347
+ cachedResponse,
348
+ request: effectiveRequest,
349
+ event: this.event
350
+ }) || undefined;
351
+ }
352
+ return cachedResponse;
353
+ }
354
+ async cachePut(key, response) {
355
+ const request = toRequest(key);
356
+ await timeout(0);
357
+ const effectiveRequest = await this.getCacheKey(request, "write");
358
+ if (process.env.NODE_ENV !== "production") {
359
+ if (effectiveRequest.method && effectiveRequest.method !== "GET") {
360
+ throw new SerwistError("attempt-to-cache-non-get-request", {
361
+ url: getFriendlyURL(effectiveRequest.url),
362
+ method: effectiveRequest.method
363
+ });
364
+ }
365
+ }
366
+ if (!response) {
367
+ if (process.env.NODE_ENV !== "production") {
368
+ logger.error(`Cannot cache non-existent response for '${getFriendlyURL(effectiveRequest.url)}'.`);
369
+ }
370
+ throw new SerwistError("cache-put-with-no-response", {
371
+ url: getFriendlyURL(effectiveRequest.url)
372
+ });
373
+ }
374
+ const responseToCache = await this._ensureResponseSafeToCache(response);
375
+ if (!responseToCache) {
376
+ if (process.env.NODE_ENV !== "production") {
377
+ logger.debug(`Response '${getFriendlyURL(effectiveRequest.url)}' will not be cached.`, responseToCache);
378
+ }
379
+ return false;
380
+ }
381
+ const { cacheName, matchOptions } = this._strategy;
382
+ const cache = await self.caches.open(cacheName);
383
+ if (process.env.NODE_ENV !== "production") {
384
+ const vary = response.headers.get("Vary");
385
+ if (vary && matchOptions?.ignoreVary !== true) {
386
+ logger.debug(`The response for ${getFriendlyURL(effectiveRequest.url)} has a 'Vary: ${vary}' header. Consider setting the {ignoreVary: true} option on your strategy to ensure cache matching and deletion works as expected.`);
387
+ }
388
+ }
389
+ const hasCacheUpdateCallback = this.hasCallback("cacheDidUpdate");
390
+ const oldResponse = hasCacheUpdateCallback ? await cacheMatchIgnoreParams(cache, effectiveRequest.clone(), [
391
+ "__WB_REVISION__"
392
+ ], matchOptions) : null;
393
+ if (process.env.NODE_ENV !== "production") {
394
+ logger.debug(`Updating the '${cacheName}' cache with a new Response for ${getFriendlyURL(effectiveRequest.url)}.`);
395
+ }
396
+ try {
397
+ await cache.put(effectiveRequest, hasCacheUpdateCallback ? responseToCache.clone() : responseToCache);
398
+ } catch (error) {
399
+ if (error instanceof Error) {
400
+ if (error.name === "QuotaExceededError") {
401
+ await executeQuotaErrorCallbacks();
402
+ }
403
+ throw error;
404
+ }
405
+ }
406
+ for (const callback of this.iterateCallbacks("cacheDidUpdate")){
407
+ await callback({
408
+ cacheName,
409
+ oldResponse,
410
+ newResponse: responseToCache.clone(),
411
+ request: effectiveRequest,
412
+ event: this.event
413
+ });
414
+ }
415
+ return true;
416
+ }
417
+ async getCacheKey(request, mode) {
418
+ const key = `${request.url} | ${mode}`;
419
+ if (!this._cacheKeys[key]) {
420
+ let effectiveRequest = request;
421
+ for (const callback of this.iterateCallbacks("cacheKeyWillBeUsed")){
422
+ effectiveRequest = toRequest(await callback({
423
+ mode,
424
+ request: effectiveRequest,
425
+ event: this.event,
426
+ params: this.params
427
+ }));
428
+ }
429
+ this._cacheKeys[key] = effectiveRequest;
430
+ }
431
+ return this._cacheKeys[key];
432
+ }
433
+ hasCallback(name) {
434
+ for (const plugin of this._strategy.plugins){
435
+ if (name in plugin) {
436
+ return true;
437
+ }
438
+ }
439
+ return false;
440
+ }
441
+ async runCallbacks(name, param) {
442
+ for (const callback of this.iterateCallbacks(name)){
443
+ await callback(param);
444
+ }
445
+ }
446
+ *iterateCallbacks(name) {
447
+ for (const plugin of this._strategy.plugins){
448
+ if (typeof plugin[name] === "function") {
449
+ const state = this._pluginStateMap.get(plugin);
450
+ const statefulCallback = (param)=>{
451
+ const statefulParam = {
452
+ ...param,
453
+ state
454
+ };
455
+ return plugin[name](statefulParam);
456
+ };
457
+ yield statefulCallback;
458
+ }
459
+ }
460
+ }
461
+ waitUntil(promise) {
462
+ this._extendLifetimePromises.push(promise);
463
+ return promise;
464
+ }
465
+ async doneWaiting() {
466
+ let promise = undefined;
467
+ while(promise = this._extendLifetimePromises.shift()){
468
+ await promise;
469
+ }
470
+ }
471
+ destroy() {
472
+ this._handlerDeferred.resolve(null);
473
+ }
474
+ async _ensureResponseSafeToCache(response) {
475
+ let responseToCache = response;
476
+ let pluginsUsed = false;
477
+ for (const callback of this.iterateCallbacks("cacheWillUpdate")){
478
+ responseToCache = await callback({
479
+ request: this.request,
480
+ response: responseToCache,
481
+ event: this.event
482
+ }) || undefined;
483
+ pluginsUsed = true;
484
+ if (!responseToCache) {
485
+ break;
486
+ }
487
+ }
488
+ if (!pluginsUsed) {
489
+ if (responseToCache && responseToCache.status !== 200) {
490
+ responseToCache = undefined;
491
+ }
492
+ if (process.env.NODE_ENV !== "production") {
493
+ if (responseToCache) {
494
+ if (responseToCache.status !== 200) {
495
+ if (responseToCache.status === 0) {
496
+ logger.warn(`The response for '${this.request.url}' is an opaque response. The caching strategy that you're using will not cache opaque responses by default.`);
497
+ } else {
498
+ logger.debug(`The response for '${this.request.url}' returned a status code of '${response.status}' and won't be cached as a result.`);
499
+ }
500
+ }
501
+ }
502
+ }
503
+ }
504
+ return responseToCache;
505
+ }
506
+ }
507
+
508
+ class Strategy {
509
+ cacheName;
510
+ plugins;
511
+ fetchOptions;
512
+ matchOptions;
513
+ constructor(options = {}){
514
+ this.cacheName = cacheNames.getRuntimeName(options.cacheName);
515
+ this.plugins = options.plugins || [];
516
+ this.fetchOptions = options.fetchOptions;
517
+ this.matchOptions = options.matchOptions;
518
+ }
519
+ handle(options) {
520
+ const [responseDone] = this.handleAll(options);
521
+ return responseDone;
522
+ }
523
+ handleAll(options) {
524
+ if (options instanceof FetchEvent) {
525
+ options = {
526
+ event: options,
527
+ request: options.request
528
+ };
529
+ }
530
+ const event = options.event;
531
+ const request = typeof options.request === "string" ? new Request(options.request) : options.request;
532
+ const handler = new StrategyHandler(this, options.url ? {
533
+ event,
534
+ request,
535
+ url: options.url,
536
+ params: options.params
537
+ } : {
538
+ event,
539
+ request
540
+ });
541
+ const responseDone = this._getResponse(handler, request, event);
542
+ const handlerDone = this._awaitComplete(responseDone, handler, request, event);
543
+ return [
544
+ responseDone,
545
+ handlerDone
546
+ ];
547
+ }
548
+ async _getResponse(handler, request, event) {
549
+ await handler.runCallbacks("handlerWillStart", {
550
+ event,
551
+ request
552
+ });
553
+ let response = undefined;
554
+ try {
555
+ response = await this._handle(request, handler);
556
+ if (response === undefined || response.type === "error") {
557
+ throw new SerwistError("no-response", {
558
+ url: request.url
559
+ });
560
+ }
561
+ } catch (error) {
562
+ if (error instanceof Error) {
563
+ for (const callback of handler.iterateCallbacks("handlerDidError")){
564
+ response = await callback({
565
+ error,
566
+ event,
567
+ request
568
+ });
569
+ if (response !== undefined) {
570
+ break;
571
+ }
572
+ }
573
+ }
574
+ if (!response) {
575
+ throw error;
576
+ }
577
+ if (process.env.NODE_ENV !== "production") {
578
+ throw logger.log(`While responding to '${getFriendlyURL(request.url)}', an ${error instanceof Error ? error.toString() : ""} error occurred. Using a fallback response provided by a handlerDidError plugin.`);
579
+ }
580
+ }
581
+ for (const callback of handler.iterateCallbacks("handlerWillRespond")){
582
+ response = await callback({
583
+ event,
584
+ request,
585
+ response
586
+ });
587
+ }
588
+ return response;
589
+ }
590
+ async _awaitComplete(responseDone, handler, request, event) {
591
+ let response = undefined;
592
+ let error = undefined;
593
+ try {
594
+ response = await responseDone;
595
+ } catch (error) {}
596
+ try {
597
+ await handler.runCallbacks("handlerDidRespond", {
598
+ event,
599
+ request,
600
+ response
601
+ });
602
+ await handler.doneWaiting();
603
+ } catch (waitUntilError) {
604
+ if (waitUntilError instanceof Error) {
605
+ error = waitUntilError;
606
+ }
607
+ }
608
+ await handler.runCallbacks("handlerDidComplete", {
609
+ event,
610
+ request,
611
+ response,
612
+ error
613
+ });
614
+ handler.destroy();
615
+ if (error) {
616
+ throw error;
617
+ }
618
+ }
619
+ }
620
+
621
+ const cacheOkAndOpaquePlugin = {
622
+ cacheWillUpdate: async ({ response })=>{
623
+ if (response.status === 200 || response.status === 0) {
624
+ return response;
625
+ }
626
+ return null;
627
+ }
628
+ };
629
+
630
+ const messages = {
631
+ strategyStart: (strategyName, request)=>`Using ${strategyName} to respond to '${getFriendlyURL(request.url)}'`,
632
+ printFinalResponse: (response)=>{
633
+ if (response) {
634
+ logger.groupCollapsed("View the final response here.");
635
+ logger.log(response || "[No response returned]");
636
+ logger.groupEnd();
637
+ }
638
+ }
639
+ };
640
+
641
+ class NetworkFirst extends Strategy {
642
+ _networkTimeoutSeconds;
643
+ constructor(options = {}){
644
+ super(options);
645
+ if (!this.plugins.some((p)=>"cacheWillUpdate" in p)) {
646
+ this.plugins.unshift(cacheOkAndOpaquePlugin);
647
+ }
648
+ this._networkTimeoutSeconds = options.networkTimeoutSeconds || 0;
649
+ if (process.env.NODE_ENV !== "production") {
650
+ if (this._networkTimeoutSeconds) {
651
+ finalAssertExports.isType(this._networkTimeoutSeconds, "number", {
652
+ moduleName: "serwist",
653
+ className: this.constructor.name,
654
+ funcName: "constructor",
655
+ paramName: "networkTimeoutSeconds"
656
+ });
657
+ }
658
+ }
659
+ }
660
+ async _handle(request, handler) {
661
+ const logs = [];
662
+ if (process.env.NODE_ENV !== "production") {
663
+ finalAssertExports.isInstance(request, Request, {
664
+ moduleName: "serwist",
665
+ className: this.constructor.name,
666
+ funcName: "handle",
667
+ paramName: "makeRequest"
668
+ });
669
+ }
670
+ const promises = [];
671
+ let timeoutId;
672
+ if (this._networkTimeoutSeconds) {
673
+ const { id, promise } = this._getTimeoutPromise({
674
+ request,
675
+ logs,
676
+ handler
677
+ });
678
+ timeoutId = id;
679
+ promises.push(promise);
680
+ }
681
+ const networkPromise = this._getNetworkPromise({
682
+ timeoutId,
683
+ request,
684
+ logs,
685
+ handler
686
+ });
687
+ promises.push(networkPromise);
688
+ const response = await handler.waitUntil((async ()=>{
689
+ return await handler.waitUntil(Promise.race(promises)) || await networkPromise;
690
+ })());
691
+ if (process.env.NODE_ENV !== "production") {
692
+ logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));
693
+ for (const log of logs){
694
+ logger.log(log);
695
+ }
696
+ messages.printFinalResponse(response);
697
+ logger.groupEnd();
698
+ }
699
+ if (!response) {
700
+ throw new SerwistError("no-response", {
701
+ url: request.url
702
+ });
703
+ }
704
+ return response;
705
+ }
706
+ _getTimeoutPromise({ request, logs, handler }) {
707
+ let timeoutId;
708
+ const timeoutPromise = new Promise((resolve)=>{
709
+ const onNetworkTimeout = async ()=>{
710
+ if (process.env.NODE_ENV !== "production") {
711
+ logs.push(`Timing out the network response at ${this._networkTimeoutSeconds} seconds.`);
712
+ }
713
+ resolve(await handler.cacheMatch(request));
714
+ };
715
+ timeoutId = setTimeout(onNetworkTimeout, this._networkTimeoutSeconds * 1000);
716
+ });
717
+ return {
718
+ promise: timeoutPromise,
719
+ id: timeoutId
720
+ };
721
+ }
722
+ async _getNetworkPromise({ timeoutId, request, logs, handler }) {
723
+ let error = undefined;
724
+ let response = undefined;
725
+ try {
726
+ response = await handler.fetchAndCachePut(request);
727
+ } catch (fetchError) {
728
+ if (fetchError instanceof Error) {
729
+ error = fetchError;
730
+ }
731
+ }
732
+ if (timeoutId) {
733
+ clearTimeout(timeoutId);
734
+ }
735
+ if (process.env.NODE_ENV !== "production") {
736
+ if (response) {
737
+ logs.push("Got response from network.");
738
+ } else {
739
+ logs.push("Unable to get a response from the network. Will respond " + "with a cached response.");
740
+ }
741
+ }
742
+ if (error || !response) {
743
+ response = await handler.cacheMatch(request);
744
+ if (process.env.NODE_ENV !== "production") {
745
+ if (response) {
746
+ logs.push(`Found a cached response in the '${this.cacheName}' cache.`);
747
+ } else {
748
+ logs.push(`No response found in the '${this.cacheName}' cache.`);
749
+ }
750
+ }
751
+ }
752
+ return response;
753
+ }
754
+ }
755
+
756
+ class NetworkOnly extends Strategy {
757
+ _networkTimeoutSeconds;
758
+ constructor(options = {}){
759
+ super(options);
760
+ this._networkTimeoutSeconds = options.networkTimeoutSeconds || 0;
761
+ }
762
+ async _handle(request, handler) {
763
+ if (process.env.NODE_ENV !== "production") {
764
+ finalAssertExports.isInstance(request, Request, {
765
+ moduleName: "serwist",
766
+ className: this.constructor.name,
767
+ funcName: "_handle",
768
+ paramName: "request"
769
+ });
770
+ }
771
+ let error = undefined;
772
+ let response;
773
+ try {
774
+ const promises = [
775
+ handler.fetch(request)
776
+ ];
777
+ if (this._networkTimeoutSeconds) {
778
+ const timeoutPromise = timeout(this._networkTimeoutSeconds * 1000);
779
+ promises.push(timeoutPromise);
780
+ }
781
+ response = await Promise.race(promises);
782
+ if (!response) {
783
+ throw new Error(`Timed out the network response after ${this._networkTimeoutSeconds} seconds.`);
784
+ }
785
+ } catch (err) {
786
+ if (err instanceof Error) {
787
+ error = err;
788
+ }
789
+ }
790
+ if (process.env.NODE_ENV !== "production") {
791
+ logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));
792
+ if (response) {
793
+ logger.log("Got response from network.");
794
+ } else {
795
+ logger.log("Unable to get a response from the network.");
796
+ }
797
+ messages.printFinalResponse(response);
798
+ logger.groupEnd();
799
+ }
800
+ if (!response) {
801
+ throw new SerwistError("no-response", {
802
+ url: request.url,
803
+ error
804
+ });
805
+ }
806
+ return response;
807
+ }
808
+ }
809
+
810
+ const BACKGROUND_SYNC_DB_VERSION = 3;
811
+ const BACKGROUND_SYNC_DB_NAME = "serwist-background-sync";
812
+ const REQUEST_OBJECT_STORE_NAME = "requests";
813
+ const QUEUE_NAME_INDEX = "queueName";
814
+ class BackgroundSyncQueueDb {
815
+ _db = null;
816
+ async addEntry(entry) {
817
+ const db = await this.getDb();
818
+ const tx = db.transaction(REQUEST_OBJECT_STORE_NAME, "readwrite", {
819
+ durability: "relaxed"
820
+ });
821
+ await tx.store.add(entry);
822
+ await tx.done;
823
+ }
824
+ async getFirstEntryId() {
825
+ const db = await this.getDb();
826
+ const cursor = await db.transaction(REQUEST_OBJECT_STORE_NAME).store.openCursor();
827
+ return cursor?.value.id;
828
+ }
829
+ async getAllEntriesByQueueName(queueName) {
830
+ const db = await this.getDb();
831
+ const results = await db.getAllFromIndex(REQUEST_OBJECT_STORE_NAME, QUEUE_NAME_INDEX, IDBKeyRange.only(queueName));
832
+ return results ? results : new Array();
833
+ }
834
+ async getEntryCountByQueueName(queueName) {
835
+ const db = await this.getDb();
836
+ return db.countFromIndex(REQUEST_OBJECT_STORE_NAME, QUEUE_NAME_INDEX, IDBKeyRange.only(queueName));
837
+ }
838
+ async deleteEntry(id) {
839
+ const db = await this.getDb();
840
+ await db.delete(REQUEST_OBJECT_STORE_NAME, id);
841
+ }
842
+ async getFirstEntryByQueueName(queueName) {
843
+ return await this.getEndEntryFromIndex(IDBKeyRange.only(queueName), "next");
844
+ }
845
+ async getLastEntryByQueueName(queueName) {
846
+ return await this.getEndEntryFromIndex(IDBKeyRange.only(queueName), "prev");
847
+ }
848
+ async getEndEntryFromIndex(query, direction) {
849
+ const db = await this.getDb();
850
+ const cursor = await db.transaction(REQUEST_OBJECT_STORE_NAME).store.index(QUEUE_NAME_INDEX).openCursor(query, direction);
851
+ return cursor?.value;
852
+ }
853
+ async getDb() {
854
+ if (!this._db) {
855
+ this._db = await openDB(BACKGROUND_SYNC_DB_NAME, BACKGROUND_SYNC_DB_VERSION, {
856
+ upgrade: this._upgradeDb
857
+ });
858
+ }
859
+ return this._db;
860
+ }
861
+ _upgradeDb(db, oldVersion) {
862
+ if (oldVersion > 0 && oldVersion < BACKGROUND_SYNC_DB_VERSION) {
863
+ if (db.objectStoreNames.contains(REQUEST_OBJECT_STORE_NAME)) {
864
+ db.deleteObjectStore(REQUEST_OBJECT_STORE_NAME);
865
+ }
866
+ }
867
+ const objStore = db.createObjectStore(REQUEST_OBJECT_STORE_NAME, {
868
+ autoIncrement: true,
869
+ keyPath: "id"
870
+ });
871
+ objStore.createIndex(QUEUE_NAME_INDEX, QUEUE_NAME_INDEX, {
872
+ unique: false
873
+ });
874
+ }
875
+ }
876
+
877
+ class BackgroundSyncQueueStore {
878
+ _queueName;
879
+ _queueDb;
880
+ constructor(queueName){
881
+ this._queueName = queueName;
882
+ this._queueDb = new BackgroundSyncQueueDb();
883
+ }
884
+ async pushEntry(entry) {
885
+ if (process.env.NODE_ENV !== "production") {
886
+ finalAssertExports.isType(entry, "object", {
887
+ moduleName: "serwist",
888
+ className: "BackgroundSyncQueueStore",
889
+ funcName: "pushEntry",
890
+ paramName: "entry"
891
+ });
892
+ finalAssertExports.isType(entry.requestData, "object", {
893
+ moduleName: "serwist",
894
+ className: "BackgroundSyncQueueStore",
895
+ funcName: "pushEntry",
896
+ paramName: "entry.requestData"
897
+ });
898
+ }
899
+ delete entry.id;
900
+ entry.queueName = this._queueName;
901
+ await this._queueDb.addEntry(entry);
902
+ }
903
+ async unshiftEntry(entry) {
904
+ if (process.env.NODE_ENV !== "production") {
905
+ finalAssertExports.isType(entry, "object", {
906
+ moduleName: "serwist",
907
+ className: "BackgroundSyncQueueStore",
908
+ funcName: "unshiftEntry",
909
+ paramName: "entry"
910
+ });
911
+ finalAssertExports.isType(entry.requestData, "object", {
912
+ moduleName: "serwist",
913
+ className: "BackgroundSyncQueueStore",
914
+ funcName: "unshiftEntry",
915
+ paramName: "entry.requestData"
916
+ });
917
+ }
918
+ const firstId = await this._queueDb.getFirstEntryId();
919
+ if (firstId) {
920
+ entry.id = firstId - 1;
921
+ } else {
922
+ delete entry.id;
923
+ }
924
+ entry.queueName = this._queueName;
925
+ await this._queueDb.addEntry(entry);
926
+ }
927
+ async popEntry() {
928
+ return this._removeEntry(await this._queueDb.getLastEntryByQueueName(this._queueName));
929
+ }
930
+ async shiftEntry() {
931
+ return this._removeEntry(await this._queueDb.getFirstEntryByQueueName(this._queueName));
932
+ }
933
+ async getAll() {
934
+ return await this._queueDb.getAllEntriesByQueueName(this._queueName);
935
+ }
936
+ async size() {
937
+ return await this._queueDb.getEntryCountByQueueName(this._queueName);
938
+ }
939
+ async deleteEntry(id) {
940
+ await this._queueDb.deleteEntry(id);
941
+ }
942
+ async _removeEntry(entry) {
943
+ if (entry) {
944
+ await this.deleteEntry(entry.id);
945
+ }
946
+ return entry;
947
+ }
948
+ }
949
+
950
+ const serializableProperties = [
951
+ "method",
952
+ "referrer",
953
+ "referrerPolicy",
954
+ "mode",
955
+ "credentials",
956
+ "cache",
957
+ "redirect",
958
+ "integrity",
959
+ "keepalive"
960
+ ];
961
+ class StorableRequest {
962
+ _requestData;
963
+ static async fromRequest(request) {
964
+ const requestData = {
965
+ url: request.url,
966
+ headers: {}
967
+ };
968
+ if (request.method !== "GET") {
969
+ requestData.body = await request.clone().arrayBuffer();
970
+ }
971
+ request.headers.forEach((value, key)=>{
972
+ requestData.headers[key] = value;
973
+ });
974
+ for (const prop of serializableProperties){
975
+ if (request[prop] !== undefined) {
976
+ requestData[prop] = request[prop];
977
+ }
978
+ }
979
+ return new StorableRequest(requestData);
980
+ }
981
+ constructor(requestData){
982
+ if (process.env.NODE_ENV !== "production") {
983
+ finalAssertExports.isType(requestData, "object", {
984
+ moduleName: "serwist",
985
+ className: "StorableRequest",
986
+ funcName: "constructor",
987
+ paramName: "requestData"
988
+ });
989
+ finalAssertExports.isType(requestData.url, "string", {
990
+ moduleName: "serwist",
991
+ className: "StorableRequest",
992
+ funcName: "constructor",
993
+ paramName: "requestData.url"
994
+ });
995
+ }
996
+ if (requestData.mode === "navigate") {
997
+ requestData.mode = "same-origin";
998
+ }
999
+ this._requestData = requestData;
1000
+ }
1001
+ toObject() {
1002
+ const requestData = Object.assign({}, this._requestData);
1003
+ requestData.headers = Object.assign({}, this._requestData.headers);
1004
+ if (requestData.body) {
1005
+ requestData.body = requestData.body.slice(0);
1006
+ }
1007
+ return requestData;
1008
+ }
1009
+ toRequest() {
1010
+ return new Request(this._requestData.url, this._requestData);
1011
+ }
1012
+ clone() {
1013
+ return new StorableRequest(this.toObject());
1014
+ }
1015
+ }
1016
+
1017
+ const TAG_PREFIX = "serwist-background-sync";
1018
+ const MAX_RETENTION_TIME = 60 * 24 * 7;
1019
+ const queueNames = new Set();
1020
+ const convertEntry = (queueStoreEntry)=>{
1021
+ const queueEntry = {
1022
+ request: new StorableRequest(queueStoreEntry.requestData).toRequest(),
1023
+ timestamp: queueStoreEntry.timestamp
1024
+ };
1025
+ if (queueStoreEntry.metadata) {
1026
+ queueEntry.metadata = queueStoreEntry.metadata;
1027
+ }
1028
+ return queueEntry;
1029
+ };
1030
+ class BackgroundSyncQueue {
1031
+ _name;
1032
+ _onSync;
1033
+ _maxRetentionTime;
1034
+ _queueStore;
1035
+ _forceSyncFallback;
1036
+ _syncInProgress = false;
1037
+ _requestsAddedDuringSync = false;
1038
+ constructor(name, { forceSyncFallback, onSync, maxRetentionTime } = {}){
1039
+ if (queueNames.has(name)) {
1040
+ throw new SerwistError("duplicate-queue-name", {
1041
+ name
1042
+ });
1043
+ }
1044
+ queueNames.add(name);
1045
+ this._name = name;
1046
+ this._onSync = onSync || this.replayRequests;
1047
+ this._maxRetentionTime = maxRetentionTime || MAX_RETENTION_TIME;
1048
+ this._forceSyncFallback = Boolean(forceSyncFallback);
1049
+ this._queueStore = new BackgroundSyncQueueStore(this._name);
1050
+ this._addSyncListener();
1051
+ }
1052
+ get name() {
1053
+ return this._name;
1054
+ }
1055
+ async pushRequest(entry) {
1056
+ if (process.env.NODE_ENV !== "production") {
1057
+ finalAssertExports.isType(entry, "object", {
1058
+ moduleName: "serwist",
1059
+ className: "BackgroundSyncQueue",
1060
+ funcName: "pushRequest",
1061
+ paramName: "entry"
1062
+ });
1063
+ finalAssertExports.isInstance(entry.request, Request, {
1064
+ moduleName: "serwist",
1065
+ className: "BackgroundSyncQueue",
1066
+ funcName: "pushRequest",
1067
+ paramName: "entry.request"
1068
+ });
1069
+ }
1070
+ await this._addRequest(entry, "push");
1071
+ }
1072
+ async unshiftRequest(entry) {
1073
+ if (process.env.NODE_ENV !== "production") {
1074
+ finalAssertExports.isType(entry, "object", {
1075
+ moduleName: "serwist",
1076
+ className: "BackgroundSyncQueue",
1077
+ funcName: "unshiftRequest",
1078
+ paramName: "entry"
1079
+ });
1080
+ finalAssertExports.isInstance(entry.request, Request, {
1081
+ moduleName: "serwist",
1082
+ className: "BackgroundSyncQueue",
1083
+ funcName: "unshiftRequest",
1084
+ paramName: "entry.request"
1085
+ });
1086
+ }
1087
+ await this._addRequest(entry, "unshift");
1088
+ }
1089
+ async popRequest() {
1090
+ return this._removeRequest("pop");
1091
+ }
1092
+ async shiftRequest() {
1093
+ return this._removeRequest("shift");
1094
+ }
1095
+ async getAll() {
1096
+ const allEntries = await this._queueStore.getAll();
1097
+ const now = Date.now();
1098
+ const unexpiredEntries = [];
1099
+ for (const entry of allEntries){
1100
+ const maxRetentionTimeInMs = this._maxRetentionTime * 60 * 1000;
1101
+ if (now - entry.timestamp > maxRetentionTimeInMs) {
1102
+ await this._queueStore.deleteEntry(entry.id);
1103
+ } else {
1104
+ unexpiredEntries.push(convertEntry(entry));
1105
+ }
1106
+ }
1107
+ return unexpiredEntries;
1108
+ }
1109
+ async size() {
1110
+ return await this._queueStore.size();
1111
+ }
1112
+ async _addRequest({ request, metadata, timestamp = Date.now() }, operation) {
1113
+ const storableRequest = await StorableRequest.fromRequest(request.clone());
1114
+ const entry = {
1115
+ requestData: storableRequest.toObject(),
1116
+ timestamp
1117
+ };
1118
+ if (metadata) {
1119
+ entry.metadata = metadata;
1120
+ }
1121
+ switch(operation){
1122
+ case "push":
1123
+ await this._queueStore.pushEntry(entry);
1124
+ break;
1125
+ case "unshift":
1126
+ await this._queueStore.unshiftEntry(entry);
1127
+ break;
1128
+ }
1129
+ if (process.env.NODE_ENV !== "production") {
1130
+ logger.log(`Request for '${getFriendlyURL(request.url)}' has ` + `been added to background sync queue '${this._name}'.`);
1131
+ }
1132
+ if (this._syncInProgress) {
1133
+ this._requestsAddedDuringSync = true;
1134
+ } else {
1135
+ await this.registerSync();
1136
+ }
1137
+ }
1138
+ async _removeRequest(operation) {
1139
+ const now = Date.now();
1140
+ let entry;
1141
+ switch(operation){
1142
+ case "pop":
1143
+ entry = await this._queueStore.popEntry();
1144
+ break;
1145
+ case "shift":
1146
+ entry = await this._queueStore.shiftEntry();
1147
+ break;
1148
+ }
1149
+ if (entry) {
1150
+ const maxRetentionTimeInMs = this._maxRetentionTime * 60 * 1000;
1151
+ if (now - entry.timestamp > maxRetentionTimeInMs) {
1152
+ return this._removeRequest(operation);
1153
+ }
1154
+ return convertEntry(entry);
1155
+ }
1156
+ return undefined;
1157
+ }
1158
+ async replayRequests() {
1159
+ let entry = undefined;
1160
+ while(entry = await this.shiftRequest()){
1161
+ try {
1162
+ await fetch(entry.request.clone());
1163
+ if (process.env.NODE_ENV !== "production") {
1164
+ logger.log(`Request for '${getFriendlyURL(entry.request.url)}' ` + `has been replayed in queue '${this._name}'`);
1165
+ }
1166
+ } catch (error) {
1167
+ await this.unshiftRequest(entry);
1168
+ if (process.env.NODE_ENV !== "production") {
1169
+ logger.log(`Request for '${getFriendlyURL(entry.request.url)}' ` + `failed to replay, putting it back in queue '${this._name}'`);
1170
+ }
1171
+ throw new SerwistError("queue-replay-failed", {
1172
+ name: this._name
1173
+ });
1174
+ }
1175
+ }
1176
+ if (process.env.NODE_ENV !== "production") {
1177
+ logger.log(`All requests in queue '${this.name}' have successfully replayed; the queue is now empty!`);
1178
+ }
1179
+ }
1180
+ async registerSync() {
1181
+ if ("sync" in self.registration && !this._forceSyncFallback) {
1182
+ try {
1183
+ await self.registration.sync.register(`${TAG_PREFIX}:${this._name}`);
1184
+ } catch (err) {
1185
+ if (process.env.NODE_ENV !== "production") {
1186
+ logger.warn(`Unable to register sync event for '${this._name}'.`, err);
1187
+ }
1188
+ }
1189
+ }
1190
+ }
1191
+ _addSyncListener() {
1192
+ if ("sync" in self.registration && !this._forceSyncFallback) {
1193
+ self.addEventListener("sync", (event)=>{
1194
+ if (event.tag === `${TAG_PREFIX}:${this._name}`) {
1195
+ if (process.env.NODE_ENV !== "production") {
1196
+ logger.log(`Background sync for tag '${event.tag}' has been received`);
1197
+ }
1198
+ const syncComplete = async ()=>{
1199
+ this._syncInProgress = true;
1200
+ let syncError = undefined;
1201
+ try {
1202
+ await this._onSync({
1203
+ queue: this
1204
+ });
1205
+ } catch (error) {
1206
+ if (error instanceof Error) {
1207
+ syncError = error;
1208
+ throw syncError;
1209
+ }
1210
+ } finally{
1211
+ if (this._requestsAddedDuringSync && !(syncError && !event.lastChance)) {
1212
+ await this.registerSync();
1213
+ }
1214
+ this._syncInProgress = false;
1215
+ this._requestsAddedDuringSync = false;
1216
+ }
1217
+ };
1218
+ event.waitUntil(syncComplete());
1219
+ }
1220
+ });
1221
+ } else {
1222
+ if (process.env.NODE_ENV !== "production") {
1223
+ logger.log("Background sync replaying without background sync event");
1224
+ }
1225
+ void this._onSync({
1226
+ queue: this
1227
+ });
1228
+ }
1229
+ }
1230
+ static get _queueNames() {
1231
+ return queueNames;
1232
+ }
1233
+ }
1234
+
1235
+ class BackgroundSyncPlugin {
1236
+ _queue;
1237
+ constructor(name, options){
1238
+ this._queue = new BackgroundSyncQueue(name, options);
1239
+ }
1240
+ async fetchDidFail({ request }) {
1241
+ await this._queue.pushRequest({
1242
+ request
1243
+ });
1244
+ }
1245
+ }
1246
+
1247
+ const copyResponse = async (response, modifier)=>{
1248
+ let origin = null;
1249
+ if (response.url) {
1250
+ const responseURL = new URL(response.url);
1251
+ origin = responseURL.origin;
1252
+ }
1253
+ if (origin !== self.location.origin) {
1254
+ throw new SerwistError("cross-origin-copy-response", {
1255
+ origin
1256
+ });
1257
+ }
1258
+ const clonedResponse = response.clone();
1259
+ const responseInit = {
1260
+ headers: new Headers(clonedResponse.headers),
1261
+ status: clonedResponse.status,
1262
+ statusText: clonedResponse.statusText
1263
+ };
1264
+ const modifiedResponseInit = modifier ? modifier(responseInit) : responseInit;
1265
+ const body = canConstructResponseFromBodyStream() ? clonedResponse.body : await clonedResponse.blob();
1266
+ return new Response(body, modifiedResponseInit);
1267
+ };
1268
+
1269
+ class PrecacheStrategy extends Strategy {
1270
+ _fallbackToNetwork;
1271
+ static defaultPrecacheCacheabilityPlugin = {
1272
+ async cacheWillUpdate ({ response }) {
1273
+ if (!response || response.status >= 400) {
1274
+ return null;
1275
+ }
1276
+ return response;
1277
+ }
1278
+ };
1279
+ static copyRedirectedCacheableResponsesPlugin = {
1280
+ async cacheWillUpdate ({ response }) {
1281
+ return response.redirected ? await copyResponse(response) : response;
1282
+ }
1283
+ };
1284
+ constructor(options = {}){
1285
+ options.cacheName = cacheNames.getPrecacheName(options.cacheName);
1286
+ super(options);
1287
+ this._fallbackToNetwork = options.fallbackToNetwork === false ? false : true;
1288
+ this.plugins.push(PrecacheStrategy.copyRedirectedCacheableResponsesPlugin);
1289
+ }
1290
+ async _handle(request, handler) {
1291
+ const response = await handler.cacheMatch(request);
1292
+ if (response) {
1293
+ return response;
1294
+ }
1295
+ if (handler.event && handler.event.type === "install") {
1296
+ return await this._handleInstall(request, handler);
1297
+ }
1298
+ return await this._handleFetch(request, handler);
1299
+ }
1300
+ async _handleFetch(request, handler) {
1301
+ let response = undefined;
1302
+ const params = handler.params || {};
1303
+ if (this._fallbackToNetwork) {
1304
+ if (process.env.NODE_ENV !== "production") {
1305
+ logger.warn(`The precached response for ${getFriendlyURL(request.url)} in ${this.cacheName} was not found. Falling back to the network.`);
1306
+ }
1307
+ const integrityInManifest = params.integrity;
1308
+ const integrityInRequest = request.integrity;
1309
+ const noIntegrityConflict = !integrityInRequest || integrityInRequest === integrityInManifest;
1310
+ response = await handler.fetch(new Request(request, {
1311
+ integrity: request.mode !== "no-cors" ? integrityInRequest || integrityInManifest : undefined
1312
+ }));
1313
+ if (integrityInManifest && noIntegrityConflict && request.mode !== "no-cors") {
1314
+ this._useDefaultCacheabilityPluginIfNeeded();
1315
+ const wasCached = await handler.cachePut(request, response.clone());
1316
+ if (process.env.NODE_ENV !== "production") {
1317
+ if (wasCached) {
1318
+ logger.log(`A response for ${getFriendlyURL(request.url)} was used to "repair" the precache.`);
1319
+ }
1320
+ }
1321
+ }
1322
+ } else {
1323
+ throw new SerwistError("missing-precache-entry", {
1324
+ cacheName: this.cacheName,
1325
+ url: request.url
1326
+ });
1327
+ }
1328
+ if (process.env.NODE_ENV !== "production") {
1329
+ const cacheKey = params.cacheKey || await handler.getCacheKey(request, "read");
1330
+ logger.groupCollapsed(`Precaching is responding to: ${getFriendlyURL(request.url)}`);
1331
+ logger.log(`Serving the precached url: ${getFriendlyURL(cacheKey instanceof Request ? cacheKey.url : cacheKey)}`);
1332
+ logger.groupCollapsed("View request details here.");
1333
+ logger.log(request);
1334
+ logger.groupEnd();
1335
+ logger.groupCollapsed("View response details here.");
1336
+ logger.log(response);
1337
+ logger.groupEnd();
1338
+ logger.groupEnd();
1339
+ }
1340
+ return response;
1341
+ }
1342
+ async _handleInstall(request, handler) {
1343
+ this._useDefaultCacheabilityPluginIfNeeded();
1344
+ const response = await handler.fetch(request);
1345
+ const wasCached = await handler.cachePut(request, response.clone());
1346
+ if (!wasCached) {
1347
+ throw new SerwistError("bad-precaching-response", {
1348
+ url: request.url,
1349
+ status: response.status
1350
+ });
1351
+ }
1352
+ return response;
1353
+ }
1354
+ _useDefaultCacheabilityPluginIfNeeded() {
1355
+ let defaultPluginIndex = null;
1356
+ let cacheWillUpdatePluginCount = 0;
1357
+ for (const [index, plugin] of this.plugins.entries()){
1358
+ if (plugin === PrecacheStrategy.copyRedirectedCacheableResponsesPlugin) {
1359
+ continue;
1360
+ }
1361
+ if (plugin === PrecacheStrategy.defaultPrecacheCacheabilityPlugin) {
1362
+ defaultPluginIndex = index;
1363
+ }
1364
+ if (plugin.cacheWillUpdate) {
1365
+ cacheWillUpdatePluginCount++;
1366
+ }
1367
+ }
1368
+ if (cacheWillUpdatePluginCount === 0) {
1369
+ this.plugins.push(PrecacheStrategy.defaultPrecacheCacheabilityPlugin);
1370
+ } else if (cacheWillUpdatePluginCount > 1 && defaultPluginIndex !== null) {
1371
+ this.plugins.splice(defaultPluginIndex, 1);
1372
+ }
1373
+ }
1374
+ }
1375
+
1376
+ const isNavigationPreloadSupported = ()=>{
1377
+ return Boolean(self.registration?.navigationPreload);
1378
+ };
1379
+ const enableNavigationPreload = (headerValue)=>{
1380
+ if (isNavigationPreloadSupported()) {
1381
+ self.addEventListener("activate", (event)=>{
1382
+ event.waitUntil(self.registration.navigationPreload.enable().then(()=>{
1383
+ if (headerValue) {
1384
+ void self.registration.navigationPreload.setHeaderValue(headerValue);
1385
+ }
1386
+ if (process.env.NODE_ENV !== "production") {
1387
+ logger.log("Navigation preloading is enabled.");
1388
+ }
1389
+ }));
1390
+ });
1391
+ } else {
1392
+ if (process.env.NODE_ENV !== "production") {
1393
+ logger.log("Navigation preloading is not supported in this browser.");
1394
+ }
1395
+ }
1396
+ };
1397
+ const disableNavigationPreload = ()=>{
1398
+ if (isNavigationPreloadSupported()) {
1399
+ self.addEventListener("activate", (event)=>{
1400
+ event.waitUntil(self.registration.navigationPreload.disable().then(()=>{
1401
+ if (process.env.NODE_ENV !== "production") {
1402
+ logger.log("Navigation preloading is disabled.");
1403
+ }
1404
+ }));
1405
+ });
1406
+ } else {
1407
+ if (process.env.NODE_ENV !== "production") {
1408
+ logger.log("Navigation preloading is not supported in this browser.");
1409
+ }
1410
+ }
1411
+ };
1412
+
1413
+ const setCacheNameDetails = (details)=>{
1414
+ if (process.env.NODE_ENV !== "production") {
1415
+ for (const key of Object.keys(details)){
1416
+ finalAssertExports.isType(details[key], "string", {
1417
+ moduleName: "@serwist/core",
1418
+ funcName: "setCacheNameDetails",
1419
+ paramName: `details.${key}`
1420
+ });
1421
+ }
1422
+ if (details.precache?.length === 0) {
1423
+ throw new SerwistError("invalid-cache-name", {
1424
+ cacheNameId: "precache",
1425
+ value: details.precache
1426
+ });
1427
+ }
1428
+ if (details.runtime?.length === 0) {
1429
+ throw new SerwistError("invalid-cache-name", {
1430
+ cacheNameId: "runtime",
1431
+ value: details.runtime
1432
+ });
1433
+ }
1434
+ if (details.googleAnalytics?.length === 0) {
1435
+ throw new SerwistError("invalid-cache-name", {
1436
+ cacheNameId: "googleAnalytics",
1437
+ value: details.googleAnalytics
1438
+ });
1439
+ }
1440
+ }
1441
+ cacheNames.updateDetails(details);
1442
+ };
1443
+
1444
+ class PrecacheInstallReportPlugin {
1445
+ updatedURLs = [];
1446
+ notUpdatedURLs = [];
1447
+ handlerWillStart = async ({ request, state })=>{
1448
+ if (state) {
1449
+ state.originalRequest = request;
1450
+ }
1451
+ };
1452
+ cachedResponseWillBeUsed = async ({ event, state, cachedResponse })=>{
1453
+ if (event.type === "install") {
1454
+ if (state?.originalRequest && state.originalRequest instanceof Request) {
1455
+ const url = state.originalRequest.url;
1456
+ if (cachedResponse) {
1457
+ this.notUpdatedURLs.push(url);
1458
+ } else {
1459
+ this.updatedURLs.push(url);
1460
+ }
1461
+ }
1462
+ }
1463
+ return cachedResponse;
1464
+ };
1465
+ }
1466
+
1467
+ const REVISION_SEARCH_PARAM = "__WB_REVISION__";
1468
+ const createCacheKey = (entry)=>{
1469
+ if (!entry) {
1470
+ throw new SerwistError("add-to-cache-list-unexpected-type", {
1471
+ entry
1472
+ });
1473
+ }
1474
+ if (typeof entry === "string") {
1475
+ const urlObject = new URL(entry, location.href);
1476
+ return {
1477
+ cacheKey: urlObject.href,
1478
+ url: urlObject.href
1479
+ };
1480
+ }
1481
+ const { revision, url } = entry;
1482
+ if (!url) {
1483
+ throw new SerwistError("add-to-cache-list-unexpected-type", {
1484
+ entry
1485
+ });
1486
+ }
1487
+ if (!revision) {
1488
+ const urlObject = new URL(url, location.href);
1489
+ return {
1490
+ cacheKey: urlObject.href,
1491
+ url: urlObject.href
1492
+ };
1493
+ }
1494
+ const cacheKeyURL = new URL(url, location.href);
1495
+ const originalURL = new URL(url, location.href);
1496
+ cacheKeyURL.searchParams.set(REVISION_SEARCH_PARAM, revision);
1497
+ return {
1498
+ cacheKey: cacheKeyURL.href,
1499
+ url: originalURL.href
1500
+ };
1501
+ };
1502
+
1503
+ const parseRoute = (capture, handler, method)=>{
1504
+ if (typeof capture === "string") {
1505
+ const captureUrl = new URL(capture, location.href);
1506
+ if (process.env.NODE_ENV !== "production") {
1507
+ if (!(capture.startsWith("/") || capture.startsWith("http"))) {
1508
+ throw new SerwistError("invalid-string", {
1509
+ moduleName: "serwist",
1510
+ funcName: "parseRoute",
1511
+ paramName: "capture"
1512
+ });
1513
+ }
1514
+ const valueToCheck = capture.startsWith("http") ? captureUrl.pathname : capture;
1515
+ const wildcards = "[*:?+]";
1516
+ if (new RegExp(`${wildcards}`).exec(valueToCheck)) {
1517
+ 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.`);
1518
+ }
1519
+ }
1520
+ const matchCallback = ({ url })=>{
1521
+ if (process.env.NODE_ENV !== "production") {
1522
+ if (url.pathname === captureUrl.pathname && url.origin !== captureUrl.origin) {
1523
+ 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.`);
1524
+ }
1525
+ }
1526
+ return url.href === captureUrl.href;
1527
+ };
1528
+ return new Route(matchCallback, handler, method);
1529
+ }
1530
+ if (capture instanceof RegExp) {
1531
+ return new RegExpRoute(capture, handler, method);
1532
+ }
1533
+ if (typeof capture === "function") {
1534
+ return new Route(capture, handler, method);
1535
+ }
1536
+ if (capture instanceof Route) {
1537
+ return capture;
1538
+ }
1539
+ throw new SerwistError("unsupported-route-type", {
1540
+ moduleName: "serwist",
1541
+ funcName: "parseRoute",
1542
+ paramName: "capture"
1543
+ });
1544
+ };
1545
+
1546
+ const logGroup = (groupTitle, deletedURLs)=>{
1547
+ logger.groupCollapsed(groupTitle);
1548
+ for (const url of deletedURLs){
1549
+ logger.log(url);
1550
+ }
1551
+ logger.groupEnd();
1552
+ };
1553
+ const printCleanupDetails = (deletedURLs)=>{
1554
+ const deletionCount = deletedURLs.length;
1555
+ if (deletionCount > 0) {
1556
+ logger.groupCollapsed(`During precaching cleanup, ${deletionCount} cached request${deletionCount === 1 ? " was" : "s were"} deleted.`);
1557
+ logGroup("Deleted Cache Requests", deletedURLs);
1558
+ logger.groupEnd();
1559
+ }
1560
+ };
1561
+
1562
+ function _nestedGroup(groupTitle, urls) {
1563
+ if (urls.length === 0) {
1564
+ return;
1565
+ }
1566
+ logger.groupCollapsed(groupTitle);
1567
+ for (const url of urls){
1568
+ logger.log(url);
1569
+ }
1570
+ logger.groupEnd();
1571
+ }
1572
+ const printInstallDetails = (urlsToPrecache, urlsAlreadyPrecached)=>{
1573
+ const precachedCount = urlsToPrecache.length;
1574
+ const alreadyPrecachedCount = urlsAlreadyPrecached.length;
1575
+ if (precachedCount || alreadyPrecachedCount) {
1576
+ let message = `Precaching ${precachedCount} file${precachedCount === 1 ? "" : "s"}.`;
1577
+ if (alreadyPrecachedCount > 0) {
1578
+ message += ` ${alreadyPrecachedCount} ` + `file${alreadyPrecachedCount === 1 ? " is" : "s are"} already cached.`;
1579
+ }
1580
+ logger.groupCollapsed(message);
1581
+ _nestedGroup("View newly precached URLs.", urlsToPrecache);
1582
+ _nestedGroup("View previously precached URLs.", urlsAlreadyPrecached);
1583
+ logger.groupEnd();
1584
+ }
1585
+ };
1586
+
1587
+ export { BackgroundSyncPlugin as B, NetworkOnly as N, PrecacheStrategy as P, Route as R, Strategy as S, NetworkFirst as a, NavigationRoute as b, createCacheKey as c, disableDevLogs as d, enableNavigationPreload as e, printInstallDetails as f, generateURLVariations as g, printCleanupDetails as h, defaultMethod as i, parseRoute as j, PrecacheInstallReportPlugin as k, cacheOkAndOpaquePlugin as l, messages as m, normalizeHandler as n, copyResponse as o, parallel as p, disableNavigationPreload as q, isNavigationPreloadSupported as r, setCacheNameDetails as s, StrategyHandler as t, RegExpRoute as u, BackgroundSyncQueue as v, BackgroundSyncQueueStore as w, StorableRequest as x };