@serwist/sw 9.0.0-preview.17 → 9.0.0-preview.18

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 (251) hide show
  1. package/dist/{Serwist.d.ts → abstractions/Serwist.d.ts} +6 -15
  2. package/dist/abstractions/Serwist.d.ts.map +1 -0
  3. package/dist/abstractions/disableDevLogs.d.ts.map +1 -0
  4. package/dist/{fallbacks.d.ts → abstractions/fallbacks.d.ts} +2 -2
  5. package/dist/abstractions/fallbacks.d.ts.map +1 -0
  6. package/dist/{handlePrecaching.d.ts → abstractions/handlePrecaching.d.ts} +1 -1
  7. package/dist/abstractions/handlePrecaching.d.ts.map +1 -0
  8. package/dist/abstractions/installSerwist.d.ts.map +1 -0
  9. package/dist/abstractions/registerRuntimeCaching.d.ts.map +1 -0
  10. package/dist/{types.d.ts → abstractions/types.d.ts} +1 -1
  11. package/dist/abstractions/types.d.ts.map +1 -0
  12. package/dist/chunks/NavigationRoute.js +54 -0
  13. package/dist/chunks/NetworkOnly.js +193 -0
  14. package/dist/chunks/PrecacheFallbackPlugin.js +573 -0
  15. package/dist/chunks/Strategy.js +410 -0
  16. package/dist/chunks/getOrCreatePrecacheController.js +429 -0
  17. package/dist/chunks/precacheAndRoute.js +112 -0
  18. package/dist/chunks/registerRoute.js +408 -0
  19. package/dist/index.d.ts +8 -8
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +11 -9
  22. package/dist/index.plugins.d.ts +40 -11
  23. package/dist/index.plugins.d.ts.map +1 -1
  24. package/dist/index.plugins.js +671 -5
  25. package/dist/index.precaching.d.ts +24 -0
  26. package/dist/index.precaching.d.ts.map +1 -0
  27. package/dist/index.precaching.js +24 -0
  28. package/dist/index.routing.d.ts +13 -0
  29. package/dist/index.routing.d.ts.map +1 -0
  30. package/dist/index.routing.js +21 -0
  31. package/dist/index.strategies.d.ts +19 -2
  32. package/dist/index.strategies.d.ts.map +1 -1
  33. package/dist/index.strategies.js +146 -1
  34. package/dist/plugins/backgroundSync/BackgroundSyncPlugin.d.ts +23 -0
  35. package/dist/plugins/backgroundSync/BackgroundSyncPlugin.d.ts.map +1 -0
  36. package/dist/plugins/backgroundSync/Queue.d.ts +166 -0
  37. package/dist/plugins/backgroundSync/Queue.d.ts.map +1 -0
  38. package/dist/plugins/backgroundSync/QueueDb.d.ts +90 -0
  39. package/dist/plugins/backgroundSync/QueueDb.d.ts.map +1 -0
  40. package/dist/plugins/backgroundSync/QueueStore.d.ts +75 -0
  41. package/dist/plugins/backgroundSync/QueueStore.d.ts.map +1 -0
  42. package/dist/plugins/backgroundSync/StorableRequest.d.ts +51 -0
  43. package/dist/plugins/backgroundSync/StorableRequest.d.ts.map +1 -0
  44. package/dist/plugins/broadcastUpdate/BroadcastCacheUpdate.d.ts +45 -0
  45. package/dist/plugins/broadcastUpdate/BroadcastCacheUpdate.d.ts.map +1 -0
  46. package/dist/plugins/broadcastUpdate/BroadcastUpdatePlugin.d.ts +27 -0
  47. package/dist/plugins/broadcastUpdate/BroadcastUpdatePlugin.d.ts.map +1 -0
  48. package/dist/plugins/broadcastUpdate/constants.d.ts +5 -0
  49. package/dist/plugins/broadcastUpdate/constants.d.ts.map +1 -0
  50. package/dist/plugins/broadcastUpdate/responsesAreSame.d.ts +11 -0
  51. package/dist/plugins/broadcastUpdate/responsesAreSame.d.ts.map +1 -0
  52. package/dist/plugins/broadcastUpdate/types.d.ts +34 -0
  53. package/dist/plugins/broadcastUpdate/types.d.ts.map +1 -0
  54. package/dist/plugins/cacheableResponse/CacheableResponse.d.ts +40 -0
  55. package/dist/plugins/cacheableResponse/CacheableResponse.d.ts.map +1 -0
  56. package/dist/plugins/cacheableResponse/CacheableResponsePlugin.d.ts +27 -0
  57. package/dist/plugins/cacheableResponse/CacheableResponsePlugin.d.ts.map +1 -0
  58. package/dist/plugins/expiration/CacheExpiration.d.ts +66 -0
  59. package/dist/plugins/expiration/CacheExpiration.d.ts.map +1 -0
  60. package/dist/plugins/expiration/ExpirationPlugin.d.ts +116 -0
  61. package/dist/plugins/expiration/ExpirationPlugin.d.ts.map +1 -0
  62. package/dist/plugins/expiration/models/CacheTimestampsModel.d.ts +73 -0
  63. package/dist/plugins/expiration/models/CacheTimestampsModel.d.ts.map +1 -0
  64. package/dist/plugins/googleAnalytics/constants.d.ts +10 -0
  65. package/dist/plugins/googleAnalytics/constants.d.ts.map +1 -0
  66. package/dist/plugins/googleAnalytics/initialize.d.ts +26 -0
  67. package/dist/plugins/googleAnalytics/initialize.d.ts.map +1 -0
  68. package/dist/plugins/precaching/PrecacheFallbackPlugin.d.ts +54 -0
  69. package/dist/plugins/precaching/PrecacheFallbackPlugin.d.ts.map +1 -0
  70. package/dist/plugins/rangeRequests/RangeRequestsPlugin.d.ts +19 -0
  71. package/dist/plugins/rangeRequests/RangeRequestsPlugin.d.ts.map +1 -0
  72. package/dist/plugins/rangeRequests/createPartialResponse.d.ts +18 -0
  73. package/dist/plugins/rangeRequests/createPartialResponse.d.ts.map +1 -0
  74. package/dist/plugins/rangeRequests/utils/calculateEffectiveBoundaries.d.ts +14 -0
  75. package/dist/plugins/rangeRequests/utils/calculateEffectiveBoundaries.d.ts.map +1 -0
  76. package/dist/plugins/rangeRequests/utils/parseRangeHeader.d.ts +12 -0
  77. package/dist/plugins/rangeRequests/utils/parseRangeHeader.d.ts.map +1 -0
  78. package/dist/precaching/PrecacheController.d.ts +145 -0
  79. package/dist/precaching/PrecacheController.d.ts.map +1 -0
  80. package/dist/precaching/PrecacheRoute.d.ts +20 -0
  81. package/dist/precaching/PrecacheRoute.d.ts.map +1 -0
  82. package/dist/precaching/PrecacheStrategy.d.ts +68 -0
  83. package/dist/precaching/PrecacheStrategy.d.ts.map +1 -0
  84. package/dist/precaching/addPlugins.d.ts +8 -0
  85. package/dist/precaching/addPlugins.d.ts.map +1 -0
  86. package/dist/precaching/addRoute.d.ts +15 -0
  87. package/dist/precaching/addRoute.d.ts.map +1 -0
  88. package/dist/precaching/cleanupOutdatedCaches.d.ts +6 -0
  89. package/dist/precaching/cleanupOutdatedCaches.d.ts.map +1 -0
  90. package/dist/precaching/createHandlerBoundToURL.d.ts +17 -0
  91. package/dist/precaching/createHandlerBoundToURL.d.ts.map +1 -0
  92. package/dist/precaching/getCacheKeyForURL.d.ts +20 -0
  93. package/dist/precaching/getCacheKeyForURL.d.ts.map +1 -0
  94. package/dist/precaching/matchPrecache.d.ts +14 -0
  95. package/dist/precaching/matchPrecache.d.ts.map +1 -0
  96. package/dist/precaching/precache.d.ts +19 -0
  97. package/dist/precaching/precache.d.ts.map +1 -0
  98. package/dist/precaching/precacheAndRoute.d.ts +14 -0
  99. package/dist/precaching/precacheAndRoute.d.ts.map +1 -0
  100. package/dist/precaching/types.d.ts +37 -0
  101. package/dist/precaching/types.d.ts.map +1 -0
  102. package/dist/precaching/utils/PrecacheCacheKeyPlugin.d.ts +17 -0
  103. package/dist/precaching/utils/PrecacheCacheKeyPlugin.d.ts.map +1 -0
  104. package/dist/precaching/utils/PrecacheInstallReportPlugin.d.ts +15 -0
  105. package/dist/precaching/utils/PrecacheInstallReportPlugin.d.ts.map +1 -0
  106. package/dist/precaching/utils/createCacheKey.d.ts +16 -0
  107. package/dist/precaching/utils/createCacheKey.d.ts.map +1 -0
  108. package/dist/precaching/utils/deleteOutdatedCaches.d.ts +18 -0
  109. package/dist/precaching/utils/deleteOutdatedCaches.d.ts.map +1 -0
  110. package/dist/precaching/utils/generateURLVariations.d.ts +12 -0
  111. package/dist/precaching/utils/generateURLVariations.d.ts.map +1 -0
  112. package/dist/precaching/utils/getCacheKeyForURL.d.ts +14 -0
  113. package/dist/precaching/utils/getCacheKeyForURL.d.ts.map +1 -0
  114. package/dist/precaching/utils/getOrCreatePrecacheController.d.ts +7 -0
  115. package/dist/precaching/utils/getOrCreatePrecacheController.d.ts.map +1 -0
  116. package/dist/precaching/utils/printCleanupDetails.d.ts +6 -0
  117. package/dist/precaching/utils/printCleanupDetails.d.ts.map +1 -0
  118. package/dist/precaching/utils/printInstallDetails.d.ts +7 -0
  119. package/dist/precaching/utils/printInstallDetails.d.ts.map +1 -0
  120. package/dist/precaching/utils/removeIgnoredSearchParams.d.ts +12 -0
  121. package/dist/precaching/utils/removeIgnoredSearchParams.d.ts.map +1 -0
  122. package/dist/routing/NavigationRoute.d.ts +57 -0
  123. package/dist/routing/NavigationRoute.d.ts.map +1 -0
  124. package/dist/routing/RegExpRoute.d.ts +24 -0
  125. package/dist/routing/RegExpRoute.d.ts.map +1 -0
  126. package/dist/routing/Route.d.ts +33 -0
  127. package/dist/routing/Route.d.ts.map +1 -0
  128. package/dist/routing/Router.d.ts +124 -0
  129. package/dist/routing/Router.d.ts.map +1 -0
  130. package/dist/routing/registerRoute.d.ts +15 -0
  131. package/dist/routing/registerRoute.d.ts.map +1 -0
  132. package/dist/routing/setCatchHandler.d.ts +9 -0
  133. package/dist/routing/setCatchHandler.d.ts.map +1 -0
  134. package/dist/routing/setDefaultHandler.d.ts +12 -0
  135. package/dist/routing/setDefaultHandler.d.ts.map +1 -0
  136. package/dist/routing/unregisterRoute.d.ts +8 -0
  137. package/dist/routing/unregisterRoute.d.ts.map +1 -0
  138. package/dist/routing/utils/constants.d.ts +15 -0
  139. package/dist/routing/utils/constants.d.ts.map +1 -0
  140. package/dist/routing/utils/getOrCreateDefaultRouter.d.ts +10 -0
  141. package/dist/routing/utils/getOrCreateDefaultRouter.d.ts.map +1 -0
  142. package/dist/routing/utils/normalizeHandler.d.ts +10 -0
  143. package/dist/routing/utils/normalizeHandler.d.ts.map +1 -0
  144. package/dist/routing/utils/parseRoute.d.ts +5 -0
  145. package/dist/routing/utils/parseRoute.d.ts.map +1 -0
  146. package/dist/strategies/CacheFirst.d.ts +23 -0
  147. package/dist/strategies/CacheFirst.d.ts.map +1 -0
  148. package/dist/strategies/CacheOnly.d.ts +20 -0
  149. package/dist/strategies/CacheOnly.d.ts.map +1 -0
  150. package/dist/strategies/NetworkFirst.d.ts +61 -0
  151. package/dist/strategies/NetworkFirst.d.ts.map +1 -0
  152. package/dist/strategies/NetworkOnly.d.ts +32 -0
  153. package/dist/strategies/NetworkOnly.d.ts.map +1 -0
  154. package/dist/strategies/StaleWhileRevalidate.d.ts +35 -0
  155. package/dist/strategies/StaleWhileRevalidate.d.ts.map +1 -0
  156. package/dist/strategies/Strategy.d.ts +83 -0
  157. package/dist/strategies/Strategy.d.ts.map +1 -0
  158. package/dist/strategies/StrategyHandler.d.ts +189 -0
  159. package/dist/strategies/StrategyHandler.d.ts.map +1 -0
  160. package/dist/strategies/plugins/cacheOkAndOpaquePlugin.d.ts +3 -0
  161. package/dist/strategies/plugins/cacheOkAndOpaquePlugin.d.ts.map +1 -0
  162. package/dist/strategies/utils/messages.d.ts +5 -0
  163. package/dist/strategies/utils/messages.d.ts.map +1 -0
  164. package/package.json +20 -14
  165. package/src/{Serwist.ts → abstractions/Serwist.ts} +16 -19
  166. package/src/{fallbacks.ts → abstractions/fallbacks.ts} +5 -5
  167. package/src/{handlePrecaching.ts → abstractions/handlePrecaching.ts} +6 -3
  168. package/src/{installSerwist.ts → abstractions/installSerwist.ts} +2 -2
  169. package/src/{registerRuntimeCaching.ts → abstractions/registerRuntimeCaching.ts} +1 -1
  170. package/src/{types.ts → abstractions/types.ts} +1 -1
  171. package/src/index.plugins.ts +65 -16
  172. package/src/index.precaching.ts +38 -0
  173. package/src/index.routing.ts +14 -0
  174. package/src/index.strategies.ts +22 -2
  175. package/src/index.ts +8 -8
  176. package/src/plugins/backgroundSync/BackgroundSyncPlugin.ts +39 -0
  177. package/src/plugins/backgroundSync/Queue.ts +438 -0
  178. package/src/plugins/backgroundSync/QueueDb.ts +176 -0
  179. package/src/plugins/backgroundSync/QueueStore.ts +161 -0
  180. package/src/plugins/backgroundSync/StorableRequest.ts +142 -0
  181. package/src/plugins/broadcastUpdate/BroadcastCacheUpdate.ts +159 -0
  182. package/src/plugins/broadcastUpdate/BroadcastUpdatePlugin.ts +43 -0
  183. package/src/plugins/broadcastUpdate/constants.ts +12 -0
  184. package/src/plugins/broadcastUpdate/responsesAreSame.ts +48 -0
  185. package/src/plugins/broadcastUpdate/types.ts +37 -0
  186. package/src/plugins/cacheableResponse/CacheableResponse.ts +141 -0
  187. package/src/plugins/cacheableResponse/CacheableResponsePlugin.ts +46 -0
  188. package/src/plugins/expiration/CacheExpiration.ts +192 -0
  189. package/src/plugins/expiration/ExpirationPlugin.ts +297 -0
  190. package/src/plugins/expiration/models/CacheTimestampsModel.ts +184 -0
  191. package/src/plugins/googleAnalytics/constants.ts +22 -0
  192. package/src/plugins/googleAnalytics/initialize.ts +200 -0
  193. package/src/plugins/precaching/PrecacheFallbackPlugin.ts +86 -0
  194. package/src/plugins/rangeRequests/RangeRequestsPlugin.ts +39 -0
  195. package/src/plugins/rangeRequests/createPartialResponse.ts +92 -0
  196. package/src/plugins/rangeRequests/utils/calculateEffectiveBoundaries.ts +58 -0
  197. package/src/plugins/rangeRequests/utils/parseRangeHeader.ts +54 -0
  198. package/src/precaching/PrecacheController.ts +332 -0
  199. package/src/precaching/PrecacheRoute.ts +50 -0
  200. package/src/precaching/PrecacheStrategy.ts +238 -0
  201. package/src/precaching/addPlugins.ts +21 -0
  202. package/src/precaching/addRoute.ts +30 -0
  203. package/src/precaching/cleanupOutdatedCaches.ts +33 -0
  204. package/src/precaching/createHandlerBoundToURL.ts +30 -0
  205. package/src/precaching/getCacheKeyForURL.ts +33 -0
  206. package/src/precaching/matchPrecache.ts +26 -0
  207. package/src/precaching/precache.ts +31 -0
  208. package/src/precaching/precacheAndRoute.ts +27 -0
  209. package/src/precaching/types.ts +46 -0
  210. package/src/precaching/utils/PrecacheCacheKeyPlugin.ts +36 -0
  211. package/src/precaching/utils/PrecacheInstallReportPlugin.ts +49 -0
  212. package/src/precaching/utils/createCacheKey.ts +68 -0
  213. package/src/precaching/utils/deleteOutdatedCaches.ts +40 -0
  214. package/src/precaching/utils/generateURLVariations.ts +55 -0
  215. package/src/precaching/utils/getCacheKeyForURL.ts +36 -0
  216. package/src/precaching/utils/getOrCreatePrecacheController.ts +22 -0
  217. package/src/precaching/utils/printCleanupDetails.ts +38 -0
  218. package/src/precaching/utils/printInstallDetails.ts +53 -0
  219. package/src/precaching/utils/removeIgnoredSearchParams.ts +29 -0
  220. package/src/routing/NavigationRoute.ts +119 -0
  221. package/src/routing/RegExpRoute.ts +74 -0
  222. package/src/routing/Route.ts +68 -0
  223. package/src/routing/Router.ts +432 -0
  224. package/src/routing/registerRoute.ts +33 -0
  225. package/src/routing/setCatchHandler.ts +22 -0
  226. package/src/routing/setDefaultHandler.ts +25 -0
  227. package/src/routing/unregisterRoute.ts +12 -0
  228. package/src/routing/utils/constants.ts +24 -0
  229. package/src/routing/utils/getOrCreateDefaultRouter.ts +29 -0
  230. package/src/routing/utils/normalizeHandler.ts +40 -0
  231. package/src/routing/utils/parseRoute.ts +67 -0
  232. package/src/strategies/CacheFirst.ts +87 -0
  233. package/src/strategies/CacheOnly.ts +58 -0
  234. package/src/strategies/NetworkFirst.ts +228 -0
  235. package/src/strategies/NetworkOnly.ts +96 -0
  236. package/src/strategies/StaleWhileRevalidate.ts +109 -0
  237. package/src/strategies/Strategy.ts +202 -0
  238. package/src/strategies/StrategyHandler.ts +557 -0
  239. package/src/strategies/plugins/cacheOkAndOpaquePlugin.ts +26 -0
  240. package/src/strategies/utils/messages.ts +20 -0
  241. package/dist/Serwist.d.ts.map +0 -1
  242. package/dist/disableDevLogs.d.ts.map +0 -1
  243. package/dist/fallbacks.d.ts.map +0 -1
  244. package/dist/handlePrecaching.d.ts.map +0 -1
  245. package/dist/installSerwist.d.ts.map +0 -1
  246. package/dist/registerRuntimeCaching.d.ts.map +0 -1
  247. package/dist/types.d.ts.map +0 -1
  248. /package/dist/{disableDevLogs.d.ts → abstractions/disableDevLogs.d.ts} +0 -0
  249. /package/dist/{installSerwist.d.ts → abstractions/installSerwist.d.ts} +0 -0
  250. /package/dist/{registerRuntimeCaching.d.ts → abstractions/registerRuntimeCaching.d.ts} +0 -0
  251. /package/src/{disableDevLogs.ts → abstractions/disableDevLogs.ts} +0 -0
@@ -0,0 +1,176 @@
1
+ /*
2
+ Copyright 2021 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ import type { DBSchema, IDBPDatabase } from "idb";
10
+ import { openDB } from "idb";
11
+
12
+ import type { RequestData } from "./StorableRequest.js";
13
+
14
+ interface QueueDBSchema extends DBSchema {
15
+ requests: {
16
+ key: number;
17
+ value: QueueStoreEntry;
18
+ indexes: { queueName: string };
19
+ };
20
+ }
21
+
22
+ const DB_VERSION = 3;
23
+ const DB_NAME = "serwist-background-sync";
24
+ const REQUEST_OBJECT_STORE_NAME = "requests";
25
+ const QUEUE_NAME_INDEX = "queueName";
26
+
27
+ export interface UnidentifiedQueueStoreEntry {
28
+ requestData: RequestData;
29
+ timestamp: number;
30
+ id?: number;
31
+ queueName?: string;
32
+ metadata?: Record<string, unknown>;
33
+ }
34
+
35
+ export interface QueueStoreEntry extends UnidentifiedQueueStoreEntry {
36
+ id: number;
37
+ }
38
+
39
+ /**
40
+ * A class to interact directly an IndexedDB created specifically to save and
41
+ * retrieve QueueStoreEntries. This class encapsulates all the schema details
42
+ * to store the representation of a Queue.
43
+ *
44
+ * @private
45
+ */
46
+
47
+ export class QueueDb {
48
+ private _db: IDBPDatabase<QueueDBSchema> | null = null;
49
+
50
+ /**
51
+ * Add QueueStoreEntry to underlying db.
52
+ *
53
+ * @param entry
54
+ */
55
+ async addEntry(entry: UnidentifiedQueueStoreEntry): Promise<void> {
56
+ const db = await this.getDb();
57
+ const tx = db.transaction(REQUEST_OBJECT_STORE_NAME, "readwrite", {
58
+ durability: "relaxed",
59
+ });
60
+ await tx.store.add(entry as QueueStoreEntry);
61
+ await tx.done;
62
+ }
63
+
64
+ /**
65
+ * Returns the first entry id in the ObjectStore.
66
+ *
67
+ * @returns
68
+ */
69
+ async getFirstEntryId(): Promise<number | undefined> {
70
+ const db = await this.getDb();
71
+ const cursor = await db.transaction(REQUEST_OBJECT_STORE_NAME).store.openCursor();
72
+ return cursor?.value.id;
73
+ }
74
+
75
+ /**
76
+ * Get all the entries filtered by index
77
+ *
78
+ * @param queueName
79
+ * @returns
80
+ */
81
+ async getAllEntriesByQueueName(queueName: string): Promise<QueueStoreEntry[]> {
82
+ const db = await this.getDb();
83
+ const results = await db.getAllFromIndex(REQUEST_OBJECT_STORE_NAME, QUEUE_NAME_INDEX, IDBKeyRange.only(queueName));
84
+ return results ? results : new Array<QueueStoreEntry>();
85
+ }
86
+
87
+ /**
88
+ * Returns the number of entries filtered by index
89
+ *
90
+ * @param queueName
91
+ * @returns
92
+ */
93
+ async getEntryCountByQueueName(queueName: string): Promise<number> {
94
+ const db = await this.getDb();
95
+ return db.countFromIndex(REQUEST_OBJECT_STORE_NAME, QUEUE_NAME_INDEX, IDBKeyRange.only(queueName));
96
+ }
97
+
98
+ /**
99
+ * Deletes a single entry by id.
100
+ *
101
+ * @param id the id of the entry to be deleted
102
+ */
103
+ async deleteEntry(id: number): Promise<void> {
104
+ const db = await this.getDb();
105
+ await db.delete(REQUEST_OBJECT_STORE_NAME, id);
106
+ }
107
+
108
+ /**
109
+ *
110
+ * @param queueName
111
+ * @returns
112
+ */
113
+ async getFirstEntryByQueueName(queueName: string): Promise<QueueStoreEntry | undefined> {
114
+ return await this.getEndEntryFromIndex(IDBKeyRange.only(queueName), "next");
115
+ }
116
+
117
+ /**
118
+ *
119
+ * @param queueName
120
+ * @returns
121
+ */
122
+ async getLastEntryByQueueName(queueName: string): Promise<QueueStoreEntry | undefined> {
123
+ return await this.getEndEntryFromIndex(IDBKeyRange.only(queueName), "prev");
124
+ }
125
+
126
+ /**
127
+ * Returns either the first or the last entries, depending on direction.
128
+ * Filtered by index.
129
+ *
130
+ * @param direction
131
+ * @param query
132
+ * @returns
133
+ * @private
134
+ */
135
+ async getEndEntryFromIndex(query: IDBKeyRange, direction: IDBCursorDirection): Promise<QueueStoreEntry | undefined> {
136
+ const db = await this.getDb();
137
+
138
+ const cursor = await db.transaction(REQUEST_OBJECT_STORE_NAME).store.index(QUEUE_NAME_INDEX).openCursor(query, direction);
139
+ return cursor?.value;
140
+ }
141
+
142
+ /**
143
+ * Returns an open connection to the database.
144
+ *
145
+ * @private
146
+ */
147
+ private async getDb() {
148
+ if (!this._db) {
149
+ this._db = await openDB(DB_NAME, DB_VERSION, {
150
+ upgrade: this._upgradeDb,
151
+ });
152
+ }
153
+ return this._db;
154
+ }
155
+
156
+ /**
157
+ * Upgrades QueueDB
158
+ *
159
+ * @param db
160
+ * @param oldVersion
161
+ * @private
162
+ */
163
+ private _upgradeDb(db: IDBPDatabase<QueueDBSchema>, oldVersion: number) {
164
+ if (oldVersion > 0 && oldVersion < DB_VERSION) {
165
+ if (db.objectStoreNames.contains(REQUEST_OBJECT_STORE_NAME)) {
166
+ db.deleteObjectStore(REQUEST_OBJECT_STORE_NAME);
167
+ }
168
+ }
169
+
170
+ const objStore = db.createObjectStore(REQUEST_OBJECT_STORE_NAME, {
171
+ autoIncrement: true,
172
+ keyPath: "id",
173
+ });
174
+ objStore.createIndex(QUEUE_NAME_INDEX, QUEUE_NAME_INDEX, { unique: false });
175
+ }
176
+ }
@@ -0,0 +1,161 @@
1
+ /*
2
+ Copyright 2018 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+ import { assert } from "@serwist/core/internal";
9
+
10
+ import type { QueueStoreEntry, UnidentifiedQueueStoreEntry } from "./QueueDb.js";
11
+ import { QueueDb } from "./QueueDb.js";
12
+
13
+ /**
14
+ * A class to manage storing requests from a Queue in IndexedDB,
15
+ * indexed by their queue name for easier access.
16
+ *
17
+ * Most developers will not need to access this class directly;
18
+ * it is exposed for advanced use cases.
19
+ */
20
+ export class QueueStore {
21
+ private readonly _queueName: string;
22
+ private readonly _queueDb: QueueDb;
23
+
24
+ /**
25
+ * Associates this instance with a Queue instance, so entries added can be
26
+ * identified by their queue name.
27
+ *
28
+ * @param queueName
29
+ */
30
+ constructor(queueName: string) {
31
+ this._queueName = queueName;
32
+ this._queueDb = new QueueDb();
33
+ }
34
+
35
+ /**
36
+ * Append an entry last in the queue.
37
+ *
38
+ * @param entry
39
+ */
40
+ async pushEntry(entry: UnidentifiedQueueStoreEntry): Promise<void> {
41
+ if (process.env.NODE_ENV !== "production") {
42
+ assert!.isType(entry, "object", {
43
+ moduleName: "@serwist/sw/plugins",
44
+ className: "BackgroundSyncQueueStore",
45
+ funcName: "pushEntry",
46
+ paramName: "entry",
47
+ });
48
+ assert!.isType(entry.requestData, "object", {
49
+ moduleName: "@serwist/sw/plugins",
50
+ className: "BackgroundSyncQueueStore",
51
+ funcName: "pushEntry",
52
+ paramName: "entry.requestData",
53
+ });
54
+ }
55
+
56
+ // biome-ignore lint/performance/noDelete: Don't specify an ID since one is automatically generated.
57
+ delete entry.id;
58
+ entry.queueName = this._queueName;
59
+
60
+ await this._queueDb.addEntry(entry);
61
+ }
62
+
63
+ /**
64
+ * Prepend an entry first in the queue.
65
+ *
66
+ * @param entry
67
+ */
68
+ async unshiftEntry(entry: UnidentifiedQueueStoreEntry): Promise<void> {
69
+ if (process.env.NODE_ENV !== "production") {
70
+ assert!.isType(entry, "object", {
71
+ moduleName: "@serwist/sw/plugins",
72
+ className: "BackgroundSyncQueueStore",
73
+ funcName: "unshiftEntry",
74
+ paramName: "entry",
75
+ });
76
+ assert!.isType(entry.requestData, "object", {
77
+ moduleName: "@serwist/sw/plugins",
78
+ className: "BackgroundSyncQueueStore",
79
+ funcName: "unshiftEntry",
80
+ paramName: "entry.requestData",
81
+ });
82
+ }
83
+
84
+ const firstId = await this._queueDb.getFirstEntryId();
85
+
86
+ if (firstId) {
87
+ // Pick an ID one less than the lowest ID in the object store.
88
+ entry.id = firstId - 1;
89
+ } else {
90
+ // biome-ignore lint/performance/noDelete: Let the auto-incrementor assign the ID.
91
+ delete entry.id;
92
+ }
93
+ entry.queueName = this._queueName;
94
+
95
+ await this._queueDb.addEntry(entry);
96
+ }
97
+
98
+ /**
99
+ * Removes and returns the last entry in the queue matching the `queueName`.
100
+ *
101
+ * @returns
102
+ */
103
+ async popEntry(): Promise<QueueStoreEntry | undefined> {
104
+ return this._removeEntry(await this._queueDb.getLastEntryByQueueName(this._queueName));
105
+ }
106
+
107
+ /**
108
+ * Removes and returns the first entry in the queue matching the `queueName`.
109
+ *
110
+ * @returns
111
+ */
112
+ async shiftEntry(): Promise<QueueStoreEntry | undefined> {
113
+ return this._removeEntry(await this._queueDb.getFirstEntryByQueueName(this._queueName));
114
+ }
115
+
116
+ /**
117
+ * Returns all entries in the store matching the `queueName`.
118
+ *
119
+ * @returns
120
+ */
121
+ async getAll(): Promise<QueueStoreEntry[]> {
122
+ return await this._queueDb.getAllEntriesByQueueName(this._queueName);
123
+ }
124
+
125
+ /**
126
+ * Returns the number of entries in the store matching the `queueName`.
127
+ *
128
+ * @returns
129
+ */
130
+ async size(): Promise<number> {
131
+ return await this._queueDb.getEntryCountByQueueName(this._queueName);
132
+ }
133
+
134
+ /**
135
+ * Deletes the entry for the given ID.
136
+ *
137
+ * WARNING: this method does not ensure the deleted entry belongs to this
138
+ * queue (i.e. matches the `queueName`). But this limitation is acceptable
139
+ * as this class is not publicly exposed. An additional check would make
140
+ * this method slower than it needs to be.
141
+ *
142
+ * @param id
143
+ */
144
+ async deleteEntry(id: number): Promise<void> {
145
+ await this._queueDb.deleteEntry(id);
146
+ }
147
+
148
+ /**
149
+ * Removes and returns the first or last entry in the queue (based on the
150
+ * `direction` argument) matching the `queueName`.
151
+ *
152
+ * @returns
153
+ * @private
154
+ */
155
+ async _removeEntry(entry?: QueueStoreEntry): Promise<QueueStoreEntry | undefined> {
156
+ if (entry) {
157
+ await this.deleteEntry(entry.id);
158
+ }
159
+ return entry;
160
+ }
161
+ }
@@ -0,0 +1,142 @@
1
+ /*
2
+ Copyright 2018 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ import type { MapLikeObject } from "@serwist/core";
10
+ import { assert } from "@serwist/core/internal";
11
+
12
+ type SerializableProperties = "method" | "referrer" | "referrerPolicy" | "mode" | "credentials" | "cache" | "redirect" | "integrity" | "keepalive";
13
+
14
+ const serializableProperties: SerializableProperties[] = [
15
+ "method",
16
+ "referrer",
17
+ "referrerPolicy",
18
+ "mode",
19
+ "credentials",
20
+ "cache",
21
+ "redirect",
22
+ "integrity",
23
+ "keepalive",
24
+ ];
25
+
26
+ export interface RequestData extends MapLikeObject {
27
+ url: string;
28
+ headers: MapLikeObject;
29
+ body?: ArrayBuffer;
30
+ }
31
+
32
+ /**
33
+ * A class to make it easier to serialize and de-serialize requests so they
34
+ * can be stored in IndexedDB.
35
+ *
36
+ * Most developers will not need to access this class directly;
37
+ * it is exposed for advanced use cases.
38
+ */
39
+ export class StorableRequest {
40
+ private readonly _requestData: RequestData;
41
+
42
+ /**
43
+ * Converts a Request object to a plain object that can be structured
44
+ * cloned or JSON-stringified.
45
+ *
46
+ * @param request
47
+ * @returns
48
+ */
49
+ static async fromRequest(request: Request): Promise<StorableRequest> {
50
+ const requestData: RequestData = {
51
+ url: request.url,
52
+ headers: {},
53
+ };
54
+
55
+ // Set the body if present.
56
+ if (request.method !== "GET") {
57
+ // Use ArrayBuffer to support non-text request bodies.
58
+ // NOTE: we can't use Blobs becuse Safari doesn't support storing
59
+ // Blobs in IndexedDB in some cases:
60
+ // https://github.com/dfahlander/Dexie.js/issues/618#issuecomment-398348457
61
+ requestData.body = await request.clone().arrayBuffer();
62
+ }
63
+
64
+ request.headers.forEach((value, key) => {
65
+ requestData.headers[key] = value;
66
+ });
67
+
68
+ // Add all other serializable request properties
69
+ for (const prop of serializableProperties) {
70
+ if (request[prop] !== undefined) {
71
+ requestData[prop] = request[prop];
72
+ }
73
+ }
74
+
75
+ return new StorableRequest(requestData);
76
+ }
77
+
78
+ /**
79
+ * Accepts an object of request data that can be used to construct a
80
+ * `Request` but can also be stored in IndexedDB.
81
+ *
82
+ * @param requestData An object of request data that includes the `url` plus any relevant properties of
83
+ * [requestInit](https://fetch.spec.whatwg.org/#requestinit).
84
+ */
85
+ constructor(requestData: RequestData) {
86
+ if (process.env.NODE_ENV !== "production") {
87
+ assert!.isType(requestData, "object", {
88
+ moduleName: "@serwist/sw/plugins",
89
+ className: "StorableRequest",
90
+ funcName: "constructor",
91
+ paramName: "requestData",
92
+ });
93
+ assert!.isType(requestData.url, "string", {
94
+ moduleName: "@serwist/sw/plugins",
95
+ className: "StorableRequest",
96
+ funcName: "constructor",
97
+ paramName: "requestData.url",
98
+ });
99
+ }
100
+
101
+ // If the request's mode is `navigate`, convert it to `same-origin` since
102
+ // navigation requests can't be constructed via script.
103
+ if (requestData.mode === "navigate") {
104
+ requestData.mode = "same-origin";
105
+ }
106
+
107
+ this._requestData = requestData;
108
+ }
109
+
110
+ /**
111
+ * Returns a deep clone of the instances `_requestData` object.
112
+ *
113
+ * @returns
114
+ */
115
+ toObject(): RequestData {
116
+ const requestData = Object.assign({}, this._requestData);
117
+ requestData.headers = Object.assign({}, this._requestData.headers);
118
+ if (requestData.body) {
119
+ requestData.body = requestData.body.slice(0);
120
+ }
121
+
122
+ return requestData;
123
+ }
124
+
125
+ /**
126
+ * Converts this instance to a Request.
127
+ *
128
+ * @returns
129
+ */
130
+ toRequest(): Request {
131
+ return new Request(this._requestData.url, this._requestData);
132
+ }
133
+
134
+ /**
135
+ * Creates and returns a deep clone of the instance.
136
+ *
137
+ * @returns
138
+ */
139
+ clone(): StorableRequest {
140
+ return new StorableRequest(this.toObject());
141
+ }
142
+ }
@@ -0,0 +1,159 @@
1
+ /*
2
+ Copyright 2018 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ import type { CacheDidUpdateCallbackParam } from "@serwist/core";
10
+ import { assert, logger, resultingClientExists, timeout } from "@serwist/core/internal";
11
+
12
+ import { CACHE_UPDATED_MESSAGE_META, CACHE_UPDATED_MESSAGE_TYPE, defaultHeadersToCheck, defaultNotifyAllClients } from "./constants.js";
13
+ import { responsesAreSame } from "./responsesAreSame.js";
14
+ import type { BroadcastCacheUpdateOptions, BroadcastMessage, BroadcastPayload, BroadcastPayloadGenerator } from "./types.js";
15
+
16
+ // UA-sniff Safari: https://stackoverflow.com/questions/7944460/detect-safari-browser
17
+ // TODO(philipwalton): remove once this Safari bug fix has been released.
18
+ // https://bugs.webkit.org/show_bug.cgi?id=201169
19
+ const isSafari = typeof navigator !== "undefined" && /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
20
+
21
+ // Give TypeScript the correct global.
22
+ declare let self: ServiceWorkerGlobalScope;
23
+ /**
24
+ * Generates the default payload used in update messages. By default the
25
+ * payload includes the `cacheName` and `updatedURL` fields.
26
+ *
27
+ * @returns
28
+ * @private
29
+ */
30
+ const defaultPayloadGenerator = (data: CacheDidUpdateCallbackParam): BroadcastPayload => {
31
+ return {
32
+ cacheName: data.cacheName,
33
+ updatedURL: data.request.url,
34
+ };
35
+ };
36
+
37
+ /**
38
+ * A class that uses the `postMessage()` API to inform any open windows/tabs when
39
+ * a cached response has been updated.
40
+ *
41
+ * For efficiency's sake, the underlying response bodies are not compared;
42
+ * only specific response headers are checked.
43
+ */
44
+ export class BroadcastCacheUpdate {
45
+ private readonly _headersToCheck: string[];
46
+ private readonly _generatePayload: BroadcastPayloadGenerator;
47
+ private readonly _notifyAllClients: boolean;
48
+
49
+ /**
50
+ * Construct a BroadcastCacheUpdate instance with a specific `channelName` to
51
+ * broadcast messages on
52
+ *
53
+ * @param options
54
+ */
55
+ constructor({ generatePayload, headersToCheck, notifyAllClients }: BroadcastCacheUpdateOptions = {}) {
56
+ this._headersToCheck = headersToCheck || defaultHeadersToCheck;
57
+ this._generatePayload = generatePayload || defaultPayloadGenerator;
58
+ this._notifyAllClients = notifyAllClients ?? defaultNotifyAllClients;
59
+ }
60
+
61
+ /**
62
+ * Compares two responses and sends a message (via `postMessage()`) to all window clients if the
63
+ * responses differ. Neither of the Responses can be opaque.
64
+ *
65
+ * The message that's posted has the following format (where `payload` can
66
+ * be customized via the `generatePayload` option the instance is created
67
+ * with):
68
+ *
69
+ * ```
70
+ * {
71
+ * type: 'CACHE_UPDATED',
72
+ * meta: 'workbox-broadcast-update',
73
+ * payload: {
74
+ * cacheName: 'the-cache-name',
75
+ * updatedURL: 'https://example.com/'
76
+ * }
77
+ * }
78
+ * ```
79
+ *
80
+ * @param options
81
+ * @returns Resolves once the update is sent.
82
+ */
83
+ async notifyIfUpdated(options: CacheDidUpdateCallbackParam): Promise<void> {
84
+ if (process.env.NODE_ENV !== "production") {
85
+ assert!.isType(options.cacheName, "string", {
86
+ moduleName: "@serwist/broadcast-update",
87
+ className: "BroadcastCacheUpdate",
88
+ funcName: "notifyIfUpdated",
89
+ paramName: "cacheName",
90
+ });
91
+ assert!.isInstance(options.newResponse, Response, {
92
+ moduleName: "@serwist/broadcast-update",
93
+ className: "BroadcastCacheUpdate",
94
+ funcName: "notifyIfUpdated",
95
+ paramName: "newResponse",
96
+ });
97
+ assert!.isInstance(options.request, Request, {
98
+ moduleName: "@serwist/broadcast-update",
99
+ className: "BroadcastCacheUpdate",
100
+ funcName: "notifyIfUpdated",
101
+ paramName: "request",
102
+ });
103
+ }
104
+
105
+ // Without two responses there is nothing to compare.
106
+ if (!options.oldResponse) {
107
+ return;
108
+ }
109
+
110
+ if (!responsesAreSame(options.oldResponse, options.newResponse, this._headersToCheck)) {
111
+ if (process.env.NODE_ENV !== "production") {
112
+ logger.log("Newer response found (and cached) for:", options.request.url);
113
+ }
114
+
115
+ const messageData = {
116
+ type: CACHE_UPDATED_MESSAGE_TYPE,
117
+ meta: CACHE_UPDATED_MESSAGE_META,
118
+ payload: this._generatePayload(options),
119
+ } satisfies BroadcastMessage;
120
+
121
+ // For navigation requests, wait until the new window client exists
122
+ // before sending the message
123
+ if (options.request.mode === "navigate") {
124
+ let resultingClientId: string | undefined;
125
+ if (options.event instanceof FetchEvent) {
126
+ resultingClientId = options.event.resultingClientId;
127
+ }
128
+
129
+ const resultingWin = await resultingClientExists(resultingClientId);
130
+
131
+ // Safari does not currently implement postMessage buffering and
132
+ // there's no good way to feature detect that, so to increase the
133
+ // chances of the message being delivered in Safari, we add a timeout.
134
+ // We also do this if `resultingClientExists()` didn't return a client,
135
+ // which means it timed out, so it's worth waiting a bit longer.
136
+ if (!resultingWin || isSafari) {
137
+ // 3500 is chosen because (according to CrUX data) 80% of mobile
138
+ // websites hit the DOMContentLoaded event in less than 3.5 seconds.
139
+ // And presumably sites implementing service worker are on the
140
+ // higher end of the performance spectrum.
141
+ await timeout(3500);
142
+ }
143
+ }
144
+
145
+ if (this._notifyAllClients) {
146
+ const windows = await self.clients.matchAll({ type: "window" });
147
+ for (const win of windows) {
148
+ win.postMessage(messageData);
149
+ }
150
+ } else {
151
+ // See https://github.com/GoogleChrome/workbox/issues/2895
152
+ if (options.event instanceof FetchEvent) {
153
+ const client = await self.clients.get(options.event.clientId);
154
+ client?.postMessage(messageData);
155
+ }
156
+ }
157
+ }
158
+ }
159
+ }
@@ -0,0 +1,43 @@
1
+ /*
2
+ Copyright 2018 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ import type { CacheDidUpdateCallbackParam, SerwistPlugin } from "@serwist/core";
10
+
11
+ import { BroadcastCacheUpdate } from "./BroadcastCacheUpdate.js";
12
+ import type { BroadcastCacheUpdateOptions } from "./types.js";
13
+
14
+ /**
15
+ * A class implementing the `cacheDidUpdate` lifecycle callback. It will automatically
16
+ * broadcast a message whenever a cached response is updated.
17
+ */
18
+ export class BroadcastUpdatePlugin implements SerwistPlugin {
19
+ private readonly _broadcastUpdate: BroadcastCacheUpdate;
20
+
21
+ /**
22
+ * Construct a `@serwist/broadcast-update.BroadcastCacheUpdate` instance with
23
+ * the passed options and calls its `notifyIfUpdated` method whenever the
24
+ * plugin's `cacheDidUpdate` callback is invoked.
25
+ *
26
+ * @param options
27
+ */
28
+ constructor(options?: BroadcastCacheUpdateOptions) {
29
+ this._broadcastUpdate = new BroadcastCacheUpdate(options);
30
+ }
31
+
32
+ /**
33
+ * A "lifecycle" callback that will be triggered automatically by
34
+ * `@serwist/build.RuntimeCaching` handlers when an entry is
35
+ * added to a cache.
36
+ *
37
+ * @private
38
+ * @param options The input object to this function.
39
+ */
40
+ cacheDidUpdate(options: CacheDidUpdateCallbackParam) {
41
+ void this._broadcastUpdate.notifyIfUpdated(options);
42
+ }
43
+ }
@@ -0,0 +1,12 @@
1
+ /*
2
+ Copyright 2018 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ export const CACHE_UPDATED_MESSAGE_TYPE = "CACHE_UPDATED";
10
+ export const CACHE_UPDATED_MESSAGE_META = "serwist-broadcast-update";
11
+ export const defaultNotifyAllClients = true;
12
+ export const defaultHeadersToCheck = ["content-length", "etag", "last-modified"];