@nypl/web-reader 3.2.5 → 4.1.0

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 (39) hide show
  1. package/README.md +2 -23
  2. package/dist/cjs/index.js +62 -16
  3. package/dist/cjs/index.js.map +3 -3
  4. package/dist/esm/index.js +1074 -563
  5. package/dist/esm/index.js.map +3 -3
  6. package/dist/types/HtmlReader/types.d.ts +2 -0
  7. package/dist/types/constants.d.ts +26 -0
  8. package/dist/types/index.d.ts +0 -1
  9. package/dist/types/types.d.ts +1 -0
  10. package/dist/types/ui/HtmlSettings.d.ts +1 -0
  11. package/dist/types/ui/ToggleButton.d.ts +5 -2
  12. package/dist/types/ui/icons/Continuous.d.ts +4 -0
  13. package/dist/types/ui/icons/Day.d.ts +4 -0
  14. package/dist/types/ui/icons/EnlargeFont.d.ts +4 -0
  15. package/dist/types/ui/icons/Night.d.ts +4 -0
  16. package/dist/types/ui/icons/Paginated.d.ts +4 -0
  17. package/dist/types/ui/icons/Previous.d.ts +4 -0
  18. package/dist/types/ui/icons/ReaderSettings.d.ts +4 -0
  19. package/dist/types/ui/icons/ReduceFont.d.ts +4 -0
  20. package/dist/types/ui/icons/Reset.d.ts +4 -0
  21. package/dist/types/ui/icons/Sepia.d.ts +4 -0
  22. package/dist/types/ui/icons/TableOfContents.d.ts +4 -0
  23. package/dist/types/ui/icons/ToggleFullScreen.d.ts +4 -0
  24. package/dist/types/ui/icons/ToggleFullScreenExit.d.ts +4 -0
  25. package/dist/types/ui/icons/index.d.ts +14 -0
  26. package/dist/types/ui/menu/use-menu.d.ts +18 -18
  27. package/dist/types/ui/theme/components/button.d.ts +21 -14
  28. package/dist/types/ui/theme/foundations/fonts.d.ts +3 -0
  29. package/dist/types/ui/theme/foundations/typography.d.ts +6 -0
  30. package/package.json +13 -17
  31. package/dist/cjs/ServiceWorker/sw.js +0 -2
  32. package/dist/cjs/ServiceWorker/sw.js.map +0 -7
  33. package/dist/esm/ServiceWorker/sw.js +0 -1749
  34. package/dist/esm/ServiceWorker/sw.js.map +0 -7
  35. package/dist/types/ServiceWorker/client.d.ts +0 -6
  36. package/dist/types/ServiceWorker/constants.d.ts +0 -4
  37. package/dist/types/ServiceWorker/index.d.ts +0 -1
  38. package/dist/types/ServiceWorker/sw.d.ts +0 -19
  39. package/dist/types/ServiceWorker/types.d.ts +0 -13
@@ -1,1749 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __defProps = Object.defineProperties;
3
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
- var __spreadValues = (a, b) => {
9
- for (var prop in b || (b = {}))
10
- if (__hasOwnProp.call(b, prop))
11
- __defNormalProp(a, prop, b[prop]);
12
- if (__getOwnPropSymbols)
13
- for (var prop of __getOwnPropSymbols(b)) {
14
- if (__propIsEnum.call(b, prop))
15
- __defNormalProp(a, prop, b[prop]);
16
- }
17
- return a;
18
- };
19
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
- var __async = (__this, __arguments, generator) => {
21
- return new Promise((resolve, reject) => {
22
- var fulfilled = (value) => {
23
- try {
24
- step(generator.next(value));
25
- } catch (e) {
26
- reject(e);
27
- }
28
- };
29
- var rejected = (value) => {
30
- try {
31
- step(generator.throw(value));
32
- } catch (e) {
33
- reject(e);
34
- }
35
- };
36
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
37
- step((generator = generator.apply(__this, __arguments)).next());
38
- });
39
- };
40
-
41
- // node_modules/workbox-core/_version.js
42
- try {
43
- self["workbox:core:6.2.4"] && _();
44
- } catch (e) {
45
- }
46
-
47
- // node_modules/workbox-core/_private/logger.js
48
- var logger = true ? null : (() => {
49
- if (!("__WB_DISABLE_DEV_LOGS" in self)) {
50
- self.__WB_DISABLE_DEV_LOGS = false;
51
- }
52
- let inGroup = false;
53
- const methodToColorMap = {
54
- debug: `#7f8c8d`,
55
- log: `#2ecc71`,
56
- warn: `#f39c12`,
57
- error: `#c0392b`,
58
- groupCollapsed: `#3498db`,
59
- groupEnd: null
60
- };
61
- const print = function(method, args) {
62
- if (self.__WB_DISABLE_DEV_LOGS) {
63
- return;
64
- }
65
- if (method === "groupCollapsed") {
66
- if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
67
- console[method](...args);
68
- return;
69
- }
70
- }
71
- const styles = [
72
- `background: ${methodToColorMap[method]}`,
73
- `border-radius: 0.5em`,
74
- `color: white`,
75
- `font-weight: bold`,
76
- `padding: 2px 0.5em`
77
- ];
78
- const logPrefix = inGroup ? [] : ["%cworkbox", styles.join(";")];
79
- console[method](...logPrefix, ...args);
80
- if (method === "groupCollapsed") {
81
- inGroup = true;
82
- }
83
- if (method === "groupEnd") {
84
- inGroup = false;
85
- }
86
- };
87
- const api = {};
88
- const loggerMethods = Object.keys(methodToColorMap);
89
- for (const key of loggerMethods) {
90
- const method = key;
91
- api[method] = (...args) => {
92
- print(method, args);
93
- };
94
- }
95
- return api;
96
- })();
97
-
98
- // node_modules/workbox-core/models/messages/messageGenerator.js
99
- var fallback = (code, ...args) => {
100
- let msg = code;
101
- if (args.length > 0) {
102
- msg += ` :: ${JSON.stringify(args)}`;
103
- }
104
- return msg;
105
- };
106
- var messageGenerator = true ? fallback : generatorFunction;
107
-
108
- // node_modules/workbox-core/_private/WorkboxError.js
109
- var WorkboxError = class extends Error {
110
- constructor(errorCode, details) {
111
- const message = messageGenerator(errorCode, details);
112
- super(message);
113
- this.name = errorCode;
114
- this.details = details;
115
- }
116
- };
117
-
118
- // node_modules/workbox-core/models/quotaErrorCallbacks.js
119
- var quotaErrorCallbacks = /* @__PURE__ */ new Set();
120
-
121
- // node_modules/workbox-core/registerQuotaErrorCallback.js
122
- function registerQuotaErrorCallback(callback) {
123
- if (false) {
124
- finalAssertExports.isType(callback, "function", {
125
- moduleName: "workbox-core",
126
- funcName: "register",
127
- paramName: "callback"
128
- });
129
- }
130
- quotaErrorCallbacks.add(callback);
131
- if (false) {
132
- logger.log("Registered a callback to respond to quota errors.", callback);
133
- }
134
- }
135
-
136
- // node_modules/workbox-core/_private/cacheNames.js
137
- var _cacheNameDetails = {
138
- googleAnalytics: "googleAnalytics",
139
- precache: "precache-v2",
140
- prefix: "workbox",
141
- runtime: "runtime",
142
- suffix: typeof registration !== "undefined" ? registration.scope : ""
143
- };
144
- var _createCacheName = (cacheName) => {
145
- return [_cacheNameDetails.prefix, cacheName, _cacheNameDetails.suffix].filter((value) => value && value.length > 0).join("-");
146
- };
147
- var eachCacheNameDetail = (fn) => {
148
- for (const key of Object.keys(_cacheNameDetails)) {
149
- fn(key);
150
- }
151
- };
152
- var cacheNames = {
153
- updateDetails: (details) => {
154
- eachCacheNameDetail((key) => {
155
- if (typeof details[key] === "string") {
156
- _cacheNameDetails[key] = details[key];
157
- }
158
- });
159
- },
160
- getGoogleAnalyticsName: (userCacheName) => {
161
- return userCacheName || _createCacheName(_cacheNameDetails.googleAnalytics);
162
- },
163
- getPrecacheName: (userCacheName) => {
164
- return userCacheName || _createCacheName(_cacheNameDetails.precache);
165
- },
166
- getPrefix: () => {
167
- return _cacheNameDetails.prefix;
168
- },
169
- getRuntimeName: (userCacheName) => {
170
- return userCacheName || _createCacheName(_cacheNameDetails.runtime);
171
- },
172
- getSuffix: () => {
173
- return _cacheNameDetails.suffix;
174
- }
175
- };
176
-
177
- // node_modules/workbox-core/_private/cacheMatchIgnoreParams.js
178
- function stripParams(fullURL, ignoreParams) {
179
- const strippedURL = new URL(fullURL);
180
- for (const param of ignoreParams) {
181
- strippedURL.searchParams.delete(param);
182
- }
183
- return strippedURL.href;
184
- }
185
- function cacheMatchIgnoreParams(cache, request, ignoreParams, matchOptions) {
186
- return __async(this, null, function* () {
187
- const strippedRequestURL = stripParams(request.url, ignoreParams);
188
- if (request.url === strippedRequestURL) {
189
- return cache.match(request, matchOptions);
190
- }
191
- const keysOptions = Object.assign(Object.assign({}, matchOptions), { ignoreSearch: true });
192
- const cacheKeys = yield cache.keys(request, keysOptions);
193
- for (const cacheKey of cacheKeys) {
194
- const strippedCacheKeyURL = stripParams(cacheKey.url, ignoreParams);
195
- if (strippedRequestURL === strippedCacheKeyURL) {
196
- return cache.match(cacheKey, matchOptions);
197
- }
198
- }
199
- return;
200
- });
201
- }
202
-
203
- // node_modules/workbox-core/_private/dontWaitFor.js
204
- function dontWaitFor(promise) {
205
- void promise.then(() => {
206
- });
207
- }
208
-
209
- // node_modules/workbox-core/_private/Deferred.js
210
- var Deferred = class {
211
- constructor() {
212
- this.promise = new Promise((resolve, reject) => {
213
- this.resolve = resolve;
214
- this.reject = reject;
215
- });
216
- }
217
- };
218
-
219
- // node_modules/workbox-core/_private/executeQuotaErrorCallbacks.js
220
- function executeQuotaErrorCallbacks() {
221
- return __async(this, null, function* () {
222
- if (false) {
223
- logger.log(`About to run ${quotaErrorCallbacks.size} callbacks to clean up caches.`);
224
- }
225
- for (const callback of quotaErrorCallbacks) {
226
- yield callback();
227
- if (false) {
228
- logger.log(callback, "is complete.");
229
- }
230
- }
231
- if (false) {
232
- logger.log("Finished running callbacks.");
233
- }
234
- });
235
- }
236
-
237
- // node_modules/workbox-core/_private/getFriendlyURL.js
238
- var getFriendlyURL = (url) => {
239
- const urlObj = new URL(String(url), location.href);
240
- return urlObj.href.replace(new RegExp(`^${location.origin}`), "");
241
- };
242
-
243
- // node_modules/workbox-core/_private/timeout.js
244
- function timeout(ms) {
245
- return new Promise((resolve) => setTimeout(resolve, ms));
246
- }
247
-
248
- // node_modules/workbox-core/clientsClaim.js
249
- function clientsClaim() {
250
- self.addEventListener("activate", () => self.clients.claim());
251
- }
252
-
253
- // node_modules/idb/build/esm/wrap-idb-value.js
254
- var instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);
255
- var idbProxyableTypes;
256
- var cursorAdvanceMethods;
257
- function getIdbProxyableTypes() {
258
- return idbProxyableTypes || (idbProxyableTypes = [
259
- IDBDatabase,
260
- IDBObjectStore,
261
- IDBIndex,
262
- IDBCursor,
263
- IDBTransaction
264
- ]);
265
- }
266
- function getCursorAdvanceMethods() {
267
- return cursorAdvanceMethods || (cursorAdvanceMethods = [
268
- IDBCursor.prototype.advance,
269
- IDBCursor.prototype.continue,
270
- IDBCursor.prototype.continuePrimaryKey
271
- ]);
272
- }
273
- var cursorRequestMap = /* @__PURE__ */ new WeakMap();
274
- var transactionDoneMap = /* @__PURE__ */ new WeakMap();
275
- var transactionStoreNamesMap = /* @__PURE__ */ new WeakMap();
276
- var transformCache = /* @__PURE__ */ new WeakMap();
277
- var reverseTransformCache = /* @__PURE__ */ new WeakMap();
278
- function promisifyRequest(request) {
279
- const promise = new Promise((resolve, reject) => {
280
- const unlisten = () => {
281
- request.removeEventListener("success", success);
282
- request.removeEventListener("error", error);
283
- };
284
- const success = () => {
285
- resolve(wrap(request.result));
286
- unlisten();
287
- };
288
- const error = () => {
289
- reject(request.error);
290
- unlisten();
291
- };
292
- request.addEventListener("success", success);
293
- request.addEventListener("error", error);
294
- });
295
- promise.then((value) => {
296
- if (value instanceof IDBCursor) {
297
- cursorRequestMap.set(value, request);
298
- }
299
- }).catch(() => {
300
- });
301
- reverseTransformCache.set(promise, request);
302
- return promise;
303
- }
304
- function cacheDonePromiseForTransaction(tx) {
305
- if (transactionDoneMap.has(tx))
306
- return;
307
- const done = new Promise((resolve, reject) => {
308
- const unlisten = () => {
309
- tx.removeEventListener("complete", complete);
310
- tx.removeEventListener("error", error);
311
- tx.removeEventListener("abort", error);
312
- };
313
- const complete = () => {
314
- resolve();
315
- unlisten();
316
- };
317
- const error = () => {
318
- reject(tx.error || new DOMException("AbortError", "AbortError"));
319
- unlisten();
320
- };
321
- tx.addEventListener("complete", complete);
322
- tx.addEventListener("error", error);
323
- tx.addEventListener("abort", error);
324
- });
325
- transactionDoneMap.set(tx, done);
326
- }
327
- var idbProxyTraps = {
328
- get(target, prop, receiver) {
329
- if (target instanceof IDBTransaction) {
330
- if (prop === "done")
331
- return transactionDoneMap.get(target);
332
- if (prop === "objectStoreNames") {
333
- return target.objectStoreNames || transactionStoreNamesMap.get(target);
334
- }
335
- if (prop === "store") {
336
- return receiver.objectStoreNames[1] ? void 0 : receiver.objectStore(receiver.objectStoreNames[0]);
337
- }
338
- }
339
- return wrap(target[prop]);
340
- },
341
- set(target, prop, value) {
342
- target[prop] = value;
343
- return true;
344
- },
345
- has(target, prop) {
346
- if (target instanceof IDBTransaction && (prop === "done" || prop === "store")) {
347
- return true;
348
- }
349
- return prop in target;
350
- }
351
- };
352
- function replaceTraps(callback) {
353
- idbProxyTraps = callback(idbProxyTraps);
354
- }
355
- function wrapFunction(func) {
356
- if (func === IDBDatabase.prototype.transaction && !("objectStoreNames" in IDBTransaction.prototype)) {
357
- return function(storeNames, ...args) {
358
- const tx = func.call(unwrap(this), storeNames, ...args);
359
- transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);
360
- return wrap(tx);
361
- };
362
- }
363
- if (getCursorAdvanceMethods().includes(func)) {
364
- return function(...args) {
365
- func.apply(unwrap(this), args);
366
- return wrap(cursorRequestMap.get(this));
367
- };
368
- }
369
- return function(...args) {
370
- return wrap(func.apply(unwrap(this), args));
371
- };
372
- }
373
- function transformCachableValue(value) {
374
- if (typeof value === "function")
375
- return wrapFunction(value);
376
- if (value instanceof IDBTransaction)
377
- cacheDonePromiseForTransaction(value);
378
- if (instanceOfAny(value, getIdbProxyableTypes()))
379
- return new Proxy(value, idbProxyTraps);
380
- return value;
381
- }
382
- function wrap(value) {
383
- if (value instanceof IDBRequest)
384
- return promisifyRequest(value);
385
- if (transformCache.has(value))
386
- return transformCache.get(value);
387
- const newValue = transformCachableValue(value);
388
- if (newValue !== value) {
389
- transformCache.set(value, newValue);
390
- reverseTransformCache.set(newValue, value);
391
- }
392
- return newValue;
393
- }
394
- var unwrap = (value) => reverseTransformCache.get(value);
395
-
396
- // node_modules/idb/build/esm/index.js
397
- function openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {
398
- const request = indexedDB.open(name, version);
399
- const openPromise = wrap(request);
400
- if (upgrade) {
401
- request.addEventListener("upgradeneeded", (event) => {
402
- upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction));
403
- });
404
- }
405
- if (blocked)
406
- request.addEventListener("blocked", () => blocked());
407
- openPromise.then((db) => {
408
- if (terminated)
409
- db.addEventListener("close", () => terminated());
410
- if (blocking)
411
- db.addEventListener("versionchange", () => blocking());
412
- }).catch(() => {
413
- });
414
- return openPromise;
415
- }
416
- function deleteDB(name, { blocked } = {}) {
417
- const request = indexedDB.deleteDatabase(name);
418
- if (blocked)
419
- request.addEventListener("blocked", () => blocked());
420
- return wrap(request).then(() => void 0);
421
- }
422
- var readMethods = ["get", "getKey", "getAll", "getAllKeys", "count"];
423
- var writeMethods = ["put", "add", "delete", "clear"];
424
- var cachedMethods = /* @__PURE__ */ new Map();
425
- function getMethod(target, prop) {
426
- if (!(target instanceof IDBDatabase && !(prop in target) && typeof prop === "string")) {
427
- return;
428
- }
429
- if (cachedMethods.get(prop))
430
- return cachedMethods.get(prop);
431
- const targetFuncName = prop.replace(/FromIndex$/, "");
432
- const useIndex = prop !== targetFuncName;
433
- const isWrite = writeMethods.includes(targetFuncName);
434
- if (!(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) || !(isWrite || readMethods.includes(targetFuncName))) {
435
- return;
436
- }
437
- const method = function(storeName, ...args) {
438
- return __async(this, null, function* () {
439
- const tx = this.transaction(storeName, isWrite ? "readwrite" : "readonly");
440
- let target2 = tx.store;
441
- if (useIndex)
442
- target2 = target2.index(args.shift());
443
- return (yield Promise.all([
444
- target2[targetFuncName](...args),
445
- isWrite && tx.done
446
- ]))[0];
447
- });
448
- };
449
- cachedMethods.set(prop, method);
450
- return method;
451
- }
452
- replaceTraps((oldTraps) => __spreadProps(__spreadValues({}, oldTraps), {
453
- get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),
454
- has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop)
455
- }));
456
-
457
- // node_modules/workbox-expiration/_version.js
458
- try {
459
- self["workbox:expiration:6.2.4"] && _();
460
- } catch (e) {
461
- }
462
-
463
- // node_modules/workbox-expiration/models/CacheTimestampsModel.js
464
- var DB_NAME = "workbox-expiration";
465
- var CACHE_OBJECT_STORE = "cache-entries";
466
- var normalizeURL = (unNormalizedUrl) => {
467
- const url = new URL(unNormalizedUrl, location.href);
468
- url.hash = "";
469
- return url.href;
470
- };
471
- var CacheTimestampsModel = class {
472
- constructor(cacheName) {
473
- this._db = null;
474
- this._cacheName = cacheName;
475
- }
476
- _upgradeDb(db) {
477
- const objStore = db.createObjectStore(CACHE_OBJECT_STORE, { keyPath: "id" });
478
- objStore.createIndex("cacheName", "cacheName", { unique: false });
479
- objStore.createIndex("timestamp", "timestamp", { unique: false });
480
- }
481
- _upgradeDbAndDeleteOldDbs(db) {
482
- this._upgradeDb(db);
483
- if (this._cacheName) {
484
- void deleteDB(this._cacheName);
485
- }
486
- }
487
- setTimestamp(url, timestamp) {
488
- return __async(this, null, function* () {
489
- url = normalizeURL(url);
490
- const entry = {
491
- url,
492
- timestamp,
493
- cacheName: this._cacheName,
494
- id: this._getId(url)
495
- };
496
- const db = yield this.getDb();
497
- const tx = db.transaction(CACHE_OBJECT_STORE, "readwrite", { durability: "relaxed" });
498
- yield tx.store.put(entry);
499
- yield tx.done;
500
- });
501
- }
502
- getTimestamp(url) {
503
- return __async(this, null, function* () {
504
- const db = yield this.getDb();
505
- const entry = yield db.get(CACHE_OBJECT_STORE, this._getId(url));
506
- return entry === null || entry === void 0 ? void 0 : entry.timestamp;
507
- });
508
- }
509
- expireEntries(minTimestamp, maxCount) {
510
- return __async(this, null, function* () {
511
- const db = yield this.getDb();
512
- let cursor = yield db.transaction(CACHE_OBJECT_STORE).store.index("timestamp").openCursor(null, "prev");
513
- const entriesToDelete = [];
514
- let entriesNotDeletedCount = 0;
515
- while (cursor) {
516
- const result = cursor.value;
517
- if (result.cacheName === this._cacheName) {
518
- if (minTimestamp && result.timestamp < minTimestamp || maxCount && entriesNotDeletedCount >= maxCount) {
519
- entriesToDelete.push(cursor.value);
520
- } else {
521
- entriesNotDeletedCount++;
522
- }
523
- }
524
- cursor = yield cursor.continue();
525
- }
526
- const urlsDeleted = [];
527
- for (const entry of entriesToDelete) {
528
- yield db.delete(CACHE_OBJECT_STORE, entry.id);
529
- urlsDeleted.push(entry.url);
530
- }
531
- return urlsDeleted;
532
- });
533
- }
534
- _getId(url) {
535
- return this._cacheName + "|" + normalizeURL(url);
536
- }
537
- getDb() {
538
- return __async(this, null, function* () {
539
- if (!this._db) {
540
- this._db = yield openDB(DB_NAME, 1, {
541
- upgrade: this._upgradeDbAndDeleteOldDbs.bind(this)
542
- });
543
- }
544
- return this._db;
545
- });
546
- }
547
- };
548
-
549
- // node_modules/workbox-expiration/CacheExpiration.js
550
- var CacheExpiration = class {
551
- constructor(cacheName, config = {}) {
552
- this._isRunning = false;
553
- this._rerunRequested = false;
554
- if (false) {
555
- finalAssertExports.isType(cacheName, "string", {
556
- moduleName: "workbox-expiration",
557
- className: "CacheExpiration",
558
- funcName: "constructor",
559
- paramName: "cacheName"
560
- });
561
- if (!(config.maxEntries || config.maxAgeSeconds)) {
562
- throw new WorkboxError("max-entries-or-age-required", {
563
- moduleName: "workbox-expiration",
564
- className: "CacheExpiration",
565
- funcName: "constructor"
566
- });
567
- }
568
- if (config.maxEntries) {
569
- finalAssertExports.isType(config.maxEntries, "number", {
570
- moduleName: "workbox-expiration",
571
- className: "CacheExpiration",
572
- funcName: "constructor",
573
- paramName: "config.maxEntries"
574
- });
575
- }
576
- if (config.maxAgeSeconds) {
577
- finalAssertExports.isType(config.maxAgeSeconds, "number", {
578
- moduleName: "workbox-expiration",
579
- className: "CacheExpiration",
580
- funcName: "constructor",
581
- paramName: "config.maxAgeSeconds"
582
- });
583
- }
584
- }
585
- this._maxEntries = config.maxEntries;
586
- this._maxAgeSeconds = config.maxAgeSeconds;
587
- this._matchOptions = config.matchOptions;
588
- this._cacheName = cacheName;
589
- this._timestampModel = new CacheTimestampsModel(cacheName);
590
- }
591
- expireEntries() {
592
- return __async(this, null, function* () {
593
- if (this._isRunning) {
594
- this._rerunRequested = true;
595
- return;
596
- }
597
- this._isRunning = true;
598
- const minTimestamp = this._maxAgeSeconds ? Date.now() - this._maxAgeSeconds * 1e3 : 0;
599
- const urlsExpired = yield this._timestampModel.expireEntries(minTimestamp, this._maxEntries);
600
- const cache = yield self.caches.open(this._cacheName);
601
- for (const url of urlsExpired) {
602
- yield cache.delete(url, this._matchOptions);
603
- }
604
- if (false) {
605
- if (urlsExpired.length > 0) {
606
- logger.groupCollapsed(`Expired ${urlsExpired.length} ${urlsExpired.length === 1 ? "entry" : "entries"} and removed ${urlsExpired.length === 1 ? "it" : "them"} from the '${this._cacheName}' cache.`);
607
- logger.log(`Expired the following ${urlsExpired.length === 1 ? "URL" : "URLs"}:`);
608
- urlsExpired.forEach((url) => logger.log(` ${url}`));
609
- logger.groupEnd();
610
- } else {
611
- logger.debug(`Cache expiration ran and found no entries to remove.`);
612
- }
613
- }
614
- this._isRunning = false;
615
- if (this._rerunRequested) {
616
- this._rerunRequested = false;
617
- dontWaitFor(this.expireEntries());
618
- }
619
- });
620
- }
621
- updateTimestamp(url) {
622
- return __async(this, null, function* () {
623
- if (false) {
624
- finalAssertExports.isType(url, "string", {
625
- moduleName: "workbox-expiration",
626
- className: "CacheExpiration",
627
- funcName: "updateTimestamp",
628
- paramName: "url"
629
- });
630
- }
631
- yield this._timestampModel.setTimestamp(url, Date.now());
632
- });
633
- }
634
- isURLExpired(url) {
635
- return __async(this, null, function* () {
636
- if (!this._maxAgeSeconds) {
637
- if (false) {
638
- throw new WorkboxError(`expired-test-without-max-age`, {
639
- methodName: "isURLExpired",
640
- paramName: "maxAgeSeconds"
641
- });
642
- }
643
- return false;
644
- } else {
645
- const timestamp = yield this._timestampModel.getTimestamp(url);
646
- const expireOlderThan = Date.now() - this._maxAgeSeconds * 1e3;
647
- return timestamp !== void 0 ? timestamp < expireOlderThan : true;
648
- }
649
- });
650
- }
651
- delete() {
652
- return __async(this, null, function* () {
653
- this._rerunRequested = false;
654
- yield this._timestampModel.expireEntries(Infinity);
655
- });
656
- }
657
- };
658
-
659
- // node_modules/workbox-expiration/ExpirationPlugin.js
660
- var ExpirationPlugin = class {
661
- constructor(config = {}) {
662
- this.cachedResponseWillBeUsed = (_0) => __async(this, [_0], function* ({ event, request, cacheName, cachedResponse }) {
663
- if (!cachedResponse) {
664
- return null;
665
- }
666
- const isFresh = this._isResponseDateFresh(cachedResponse);
667
- const cacheExpiration = this._getCacheExpiration(cacheName);
668
- dontWaitFor(cacheExpiration.expireEntries());
669
- const updateTimestampDone = cacheExpiration.updateTimestamp(request.url);
670
- if (event) {
671
- try {
672
- event.waitUntil(updateTimestampDone);
673
- } catch (error) {
674
- if (false) {
675
- if ("request" in event) {
676
- logger.warn(`Unable to ensure service worker stays alive when updating cache entry for '${getFriendlyURL(event.request.url)}'.`);
677
- }
678
- }
679
- }
680
- }
681
- return isFresh ? cachedResponse : null;
682
- });
683
- this.cacheDidUpdate = (_0) => __async(this, [_0], function* ({ cacheName, request }) {
684
- if (false) {
685
- finalAssertExports.isType(cacheName, "string", {
686
- moduleName: "workbox-expiration",
687
- className: "Plugin",
688
- funcName: "cacheDidUpdate",
689
- paramName: "cacheName"
690
- });
691
- finalAssertExports.isInstance(request, Request, {
692
- moduleName: "workbox-expiration",
693
- className: "Plugin",
694
- funcName: "cacheDidUpdate",
695
- paramName: "request"
696
- });
697
- }
698
- const cacheExpiration = this._getCacheExpiration(cacheName);
699
- yield cacheExpiration.updateTimestamp(request.url);
700
- yield cacheExpiration.expireEntries();
701
- });
702
- if (false) {
703
- if (!(config.maxEntries || config.maxAgeSeconds)) {
704
- throw new WorkboxError("max-entries-or-age-required", {
705
- moduleName: "workbox-expiration",
706
- className: "Plugin",
707
- funcName: "constructor"
708
- });
709
- }
710
- if (config.maxEntries) {
711
- finalAssertExports.isType(config.maxEntries, "number", {
712
- moduleName: "workbox-expiration",
713
- className: "Plugin",
714
- funcName: "constructor",
715
- paramName: "config.maxEntries"
716
- });
717
- }
718
- if (config.maxAgeSeconds) {
719
- finalAssertExports.isType(config.maxAgeSeconds, "number", {
720
- moduleName: "workbox-expiration",
721
- className: "Plugin",
722
- funcName: "constructor",
723
- paramName: "config.maxAgeSeconds"
724
- });
725
- }
726
- }
727
- this._config = config;
728
- this._maxAgeSeconds = config.maxAgeSeconds;
729
- this._cacheExpirations = /* @__PURE__ */ new Map();
730
- if (config.purgeOnQuotaError) {
731
- registerQuotaErrorCallback(() => this.deleteCacheAndMetadata());
732
- }
733
- }
734
- _getCacheExpiration(cacheName) {
735
- if (cacheName === cacheNames.getRuntimeName()) {
736
- throw new WorkboxError("expire-custom-caches-only");
737
- }
738
- let cacheExpiration = this._cacheExpirations.get(cacheName);
739
- if (!cacheExpiration) {
740
- cacheExpiration = new CacheExpiration(cacheName, this._config);
741
- this._cacheExpirations.set(cacheName, cacheExpiration);
742
- }
743
- return cacheExpiration;
744
- }
745
- _isResponseDateFresh(cachedResponse) {
746
- if (!this._maxAgeSeconds) {
747
- return true;
748
- }
749
- const dateHeaderTimestamp = this._getDateHeaderTimestamp(cachedResponse);
750
- if (dateHeaderTimestamp === null) {
751
- return true;
752
- }
753
- const now = Date.now();
754
- return dateHeaderTimestamp >= now - this._maxAgeSeconds * 1e3;
755
- }
756
- _getDateHeaderTimestamp(cachedResponse) {
757
- if (!cachedResponse.headers.has("date")) {
758
- return null;
759
- }
760
- const dateHeader = cachedResponse.headers.get("date");
761
- const parsedDate = new Date(dateHeader);
762
- const headerTime = parsedDate.getTime();
763
- if (isNaN(headerTime)) {
764
- return null;
765
- }
766
- return headerTime;
767
- }
768
- deleteCacheAndMetadata() {
769
- return __async(this, null, function* () {
770
- for (const [cacheName, cacheExpiration] of this._cacheExpirations) {
771
- yield self.caches.delete(cacheName);
772
- yield cacheExpiration.delete();
773
- }
774
- this._cacheExpirations = /* @__PURE__ */ new Map();
775
- });
776
- }
777
- };
778
-
779
- // node_modules/workbox-strategies/_version.js
780
- try {
781
- self["workbox:strategies:6.2.4"] && _();
782
- } catch (e) {
783
- }
784
-
785
- // node_modules/workbox-strategies/StrategyHandler.js
786
- function toRequest(input) {
787
- return typeof input === "string" ? new Request(input) : input;
788
- }
789
- var StrategyHandler = class {
790
- constructor(strategy, options) {
791
- this._cacheKeys = {};
792
- if (false) {
793
- finalAssertExports.isInstance(options.event, ExtendableEvent, {
794
- moduleName: "workbox-strategies",
795
- className: "StrategyHandler",
796
- funcName: "constructor",
797
- paramName: "options.event"
798
- });
799
- }
800
- Object.assign(this, options);
801
- this.event = options.event;
802
- this._strategy = strategy;
803
- this._handlerDeferred = new Deferred();
804
- this._extendLifetimePromises = [];
805
- this._plugins = [...strategy.plugins];
806
- this._pluginStateMap = /* @__PURE__ */ new Map();
807
- for (const plugin of this._plugins) {
808
- this._pluginStateMap.set(plugin, {});
809
- }
810
- this.event.waitUntil(this._handlerDeferred.promise);
811
- }
812
- fetch(input) {
813
- return __async(this, null, function* () {
814
- const { event } = this;
815
- let request = toRequest(input);
816
- if (request.mode === "navigate" && event instanceof FetchEvent && event.preloadResponse) {
817
- const possiblePreloadResponse = yield event.preloadResponse;
818
- if (possiblePreloadResponse) {
819
- if (false) {
820
- logger.log(`Using a preloaded navigation response for '${getFriendlyURL(request.url)}'`);
821
- }
822
- return possiblePreloadResponse;
823
- }
824
- }
825
- const originalRequest = this.hasCallback("fetchDidFail") ? request.clone() : null;
826
- try {
827
- for (const cb of this.iterateCallbacks("requestWillFetch")) {
828
- request = yield cb({ request: request.clone(), event });
829
- }
830
- } catch (err) {
831
- if (err instanceof Error) {
832
- throw new WorkboxError("plugin-error-request-will-fetch", { thrownErrorMessage: err.message });
833
- }
834
- }
835
- const pluginFilteredRequest = request.clone();
836
- try {
837
- let fetchResponse;
838
- fetchResponse = yield fetch(request, request.mode === "navigate" ? void 0 : this._strategy.fetchOptions);
839
- if (false) {
840
- logger.debug(`Network request for '${getFriendlyURL(request.url)}' returned a response with status '${fetchResponse.status}'.`);
841
- }
842
- for (const callback of this.iterateCallbacks("fetchDidSucceed")) {
843
- fetchResponse = yield callback({
844
- event,
845
- request: pluginFilteredRequest,
846
- response: fetchResponse
847
- });
848
- }
849
- return fetchResponse;
850
- } catch (error) {
851
- if (false) {
852
- logger.log(`Network request for '${getFriendlyURL(request.url)}' threw an error.`, error);
853
- }
854
- if (originalRequest) {
855
- yield this.runCallbacks("fetchDidFail", {
856
- error,
857
- event,
858
- originalRequest: originalRequest.clone(),
859
- request: pluginFilteredRequest.clone()
860
- });
861
- }
862
- throw error;
863
- }
864
- });
865
- }
866
- fetchAndCachePut(input) {
867
- return __async(this, null, function* () {
868
- const response = yield this.fetch(input);
869
- const responseClone = response.clone();
870
- void this.waitUntil(this.cachePut(input, responseClone));
871
- return response;
872
- });
873
- }
874
- cacheMatch(key) {
875
- return __async(this, null, function* () {
876
- const request = toRequest(key);
877
- let cachedResponse;
878
- const { cacheName, matchOptions } = this._strategy;
879
- const effectiveRequest = yield this.getCacheKey(request, "read");
880
- const multiMatchOptions = Object.assign(Object.assign({}, matchOptions), { cacheName });
881
- cachedResponse = yield caches.match(effectiveRequest, multiMatchOptions);
882
- if (false) {
883
- if (cachedResponse) {
884
- logger.debug(`Found a cached response in '${cacheName}'.`);
885
- } else {
886
- logger.debug(`No cached response found in '${cacheName}'.`);
887
- }
888
- }
889
- for (const callback of this.iterateCallbacks("cachedResponseWillBeUsed")) {
890
- cachedResponse = (yield callback({
891
- cacheName,
892
- matchOptions,
893
- cachedResponse,
894
- request: effectiveRequest,
895
- event: this.event
896
- })) || void 0;
897
- }
898
- return cachedResponse;
899
- });
900
- }
901
- cachePut(key, response) {
902
- return __async(this, null, function* () {
903
- const request = toRequest(key);
904
- yield timeout(0);
905
- const effectiveRequest = yield this.getCacheKey(request, "write");
906
- if (false) {
907
- if (effectiveRequest.method && effectiveRequest.method !== "GET") {
908
- throw new WorkboxError("attempt-to-cache-non-get-request", {
909
- url: getFriendlyURL(effectiveRequest.url),
910
- method: effectiveRequest.method
911
- });
912
- }
913
- const vary = response.headers.get("Vary");
914
- if (vary) {
915
- 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.`);
916
- }
917
- }
918
- if (!response) {
919
- if (false) {
920
- logger.error(`Cannot cache non-existent response for '${getFriendlyURL(effectiveRequest.url)}'.`);
921
- }
922
- throw new WorkboxError("cache-put-with-no-response", {
923
- url: getFriendlyURL(effectiveRequest.url)
924
- });
925
- }
926
- const responseToCache = yield this._ensureResponseSafeToCache(response);
927
- if (!responseToCache) {
928
- if (false) {
929
- logger.debug(`Response '${getFriendlyURL(effectiveRequest.url)}' will not be cached.`, responseToCache);
930
- }
931
- return false;
932
- }
933
- const { cacheName, matchOptions } = this._strategy;
934
- const cache = yield self.caches.open(cacheName);
935
- const hasCacheUpdateCallback = this.hasCallback("cacheDidUpdate");
936
- const oldResponse = hasCacheUpdateCallback ? yield cacheMatchIgnoreParams(cache, effectiveRequest.clone(), ["__WB_REVISION__"], matchOptions) : null;
937
- if (false) {
938
- logger.debug(`Updating the '${cacheName}' cache with a new Response for ${getFriendlyURL(effectiveRequest.url)}.`);
939
- }
940
- try {
941
- yield cache.put(effectiveRequest, hasCacheUpdateCallback ? responseToCache.clone() : responseToCache);
942
- } catch (error) {
943
- if (error instanceof Error) {
944
- if (error.name === "QuotaExceededError") {
945
- yield executeQuotaErrorCallbacks();
946
- }
947
- throw error;
948
- }
949
- }
950
- for (const callback of this.iterateCallbacks("cacheDidUpdate")) {
951
- yield callback({
952
- cacheName,
953
- oldResponse,
954
- newResponse: responseToCache.clone(),
955
- request: effectiveRequest,
956
- event: this.event
957
- });
958
- }
959
- return true;
960
- });
961
- }
962
- getCacheKey(request, mode) {
963
- return __async(this, null, function* () {
964
- if (!this._cacheKeys[mode]) {
965
- let effectiveRequest = request;
966
- for (const callback of this.iterateCallbacks("cacheKeyWillBeUsed")) {
967
- effectiveRequest = toRequest(yield callback({
968
- mode,
969
- request: effectiveRequest,
970
- event: this.event,
971
- params: this.params
972
- }));
973
- }
974
- this._cacheKeys[mode] = effectiveRequest;
975
- }
976
- return this._cacheKeys[mode];
977
- });
978
- }
979
- hasCallback(name) {
980
- for (const plugin of this._strategy.plugins) {
981
- if (name in plugin) {
982
- return true;
983
- }
984
- }
985
- return false;
986
- }
987
- runCallbacks(name, param) {
988
- return __async(this, null, function* () {
989
- for (const callback of this.iterateCallbacks(name)) {
990
- yield callback(param);
991
- }
992
- });
993
- }
994
- *iterateCallbacks(name) {
995
- for (const plugin of this._strategy.plugins) {
996
- if (typeof plugin[name] === "function") {
997
- const state = this._pluginStateMap.get(plugin);
998
- const statefulCallback = (param) => {
999
- const statefulParam = Object.assign(Object.assign({}, param), { state });
1000
- return plugin[name](statefulParam);
1001
- };
1002
- yield statefulCallback;
1003
- }
1004
- }
1005
- }
1006
- waitUntil(promise) {
1007
- this._extendLifetimePromises.push(promise);
1008
- return promise;
1009
- }
1010
- doneWaiting() {
1011
- return __async(this, null, function* () {
1012
- let promise;
1013
- while (promise = this._extendLifetimePromises.shift()) {
1014
- yield promise;
1015
- }
1016
- });
1017
- }
1018
- destroy() {
1019
- this._handlerDeferred.resolve(null);
1020
- }
1021
- _ensureResponseSafeToCache(response) {
1022
- return __async(this, null, function* () {
1023
- let responseToCache = response;
1024
- let pluginsUsed = false;
1025
- for (const callback of this.iterateCallbacks("cacheWillUpdate")) {
1026
- responseToCache = (yield callback({
1027
- request: this.request,
1028
- response: responseToCache,
1029
- event: this.event
1030
- })) || void 0;
1031
- pluginsUsed = true;
1032
- if (!responseToCache) {
1033
- break;
1034
- }
1035
- }
1036
- if (!pluginsUsed) {
1037
- if (responseToCache && responseToCache.status !== 200) {
1038
- responseToCache = void 0;
1039
- }
1040
- if (false) {
1041
- if (responseToCache) {
1042
- if (responseToCache.status !== 200) {
1043
- if (responseToCache.status === 0) {
1044
- 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.`);
1045
- } else {
1046
- logger.debug(`The response for '${this.request.url}' returned a status code of '${response.status}' and won't be cached as a result.`);
1047
- }
1048
- }
1049
- }
1050
- }
1051
- }
1052
- return responseToCache;
1053
- });
1054
- }
1055
- };
1056
-
1057
- // node_modules/workbox-strategies/Strategy.js
1058
- var Strategy = class {
1059
- constructor(options = {}) {
1060
- this.cacheName = cacheNames.getRuntimeName(options.cacheName);
1061
- this.plugins = options.plugins || [];
1062
- this.fetchOptions = options.fetchOptions;
1063
- this.matchOptions = options.matchOptions;
1064
- }
1065
- handle(options) {
1066
- const [responseDone] = this.handleAll(options);
1067
- return responseDone;
1068
- }
1069
- handleAll(options) {
1070
- if (options instanceof FetchEvent) {
1071
- options = {
1072
- event: options,
1073
- request: options.request
1074
- };
1075
- }
1076
- const event = options.event;
1077
- const request = typeof options.request === "string" ? new Request(options.request) : options.request;
1078
- const params = "params" in options ? options.params : void 0;
1079
- const handler = new StrategyHandler(this, { event, request, params });
1080
- const responseDone = this._getResponse(handler, request, event);
1081
- const handlerDone = this._awaitComplete(responseDone, handler, request, event);
1082
- return [responseDone, handlerDone];
1083
- }
1084
- _getResponse(handler, request, event) {
1085
- return __async(this, null, function* () {
1086
- yield handler.runCallbacks("handlerWillStart", { event, request });
1087
- let response = void 0;
1088
- try {
1089
- response = yield this._handle(request, handler);
1090
- if (!response || response.type === "error") {
1091
- throw new WorkboxError("no-response", { url: request.url });
1092
- }
1093
- } catch (error) {
1094
- if (error instanceof Error) {
1095
- for (const callback of handler.iterateCallbacks("handlerDidError")) {
1096
- response = yield callback({ error, event, request });
1097
- if (response) {
1098
- break;
1099
- }
1100
- }
1101
- }
1102
- if (!response) {
1103
- throw error;
1104
- } else if (false) {
1105
- 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.`);
1106
- }
1107
- }
1108
- for (const callback of handler.iterateCallbacks("handlerWillRespond")) {
1109
- response = yield callback({ event, request, response });
1110
- }
1111
- return response;
1112
- });
1113
- }
1114
- _awaitComplete(responseDone, handler, request, event) {
1115
- return __async(this, null, function* () {
1116
- let response;
1117
- let error;
1118
- try {
1119
- response = yield responseDone;
1120
- } catch (error2) {
1121
- }
1122
- try {
1123
- yield handler.runCallbacks("handlerDidRespond", {
1124
- event,
1125
- request,
1126
- response
1127
- });
1128
- yield handler.doneWaiting();
1129
- } catch (waitUntilError) {
1130
- if (waitUntilError instanceof Error) {
1131
- error = waitUntilError;
1132
- }
1133
- }
1134
- yield handler.runCallbacks("handlerDidComplete", {
1135
- event,
1136
- request,
1137
- response,
1138
- error
1139
- });
1140
- handler.destroy();
1141
- if (error) {
1142
- throw error;
1143
- }
1144
- });
1145
- }
1146
- };
1147
-
1148
- // node_modules/workbox-strategies/CacheFirst.js
1149
- var CacheFirst = class extends Strategy {
1150
- _handle(request, handler) {
1151
- return __async(this, null, function* () {
1152
- const logs = [];
1153
- if (false) {
1154
- finalAssertExports.isInstance(request, Request, {
1155
- moduleName: "workbox-strategies",
1156
- className: this.constructor.name,
1157
- funcName: "makeRequest",
1158
- paramName: "request"
1159
- });
1160
- }
1161
- let response = yield handler.cacheMatch(request);
1162
- let error = void 0;
1163
- if (!response) {
1164
- if (false) {
1165
- logs.push(`No response found in the '${this.cacheName}' cache. Will respond with a network request.`);
1166
- }
1167
- try {
1168
- response = yield handler.fetchAndCachePut(request);
1169
- } catch (err) {
1170
- if (err instanceof Error) {
1171
- error = err;
1172
- }
1173
- }
1174
- if (false) {
1175
- if (response) {
1176
- logs.push(`Got response from network.`);
1177
- } else {
1178
- logs.push(`Unable to get a response from the network.`);
1179
- }
1180
- }
1181
- } else {
1182
- if (false) {
1183
- logs.push(`Found a cached response in the '${this.cacheName}' cache.`);
1184
- }
1185
- }
1186
- if (false) {
1187
- logger.groupCollapsed(messages2.strategyStart(this.constructor.name, request));
1188
- for (const log2 of logs) {
1189
- logger.log(log2);
1190
- }
1191
- messages2.printFinalResponse(response);
1192
- logger.groupEnd();
1193
- }
1194
- if (!response) {
1195
- throw new WorkboxError("no-response", { url: request.url, error });
1196
- }
1197
- return response;
1198
- });
1199
- }
1200
- };
1201
-
1202
- // node_modules/workbox-strategies/plugins/cacheOkAndOpaquePlugin.js
1203
- var cacheOkAndOpaquePlugin = {
1204
- cacheWillUpdate: (_0) => __async(void 0, [_0], function* ({ response }) {
1205
- if (response.status === 200 || response.status === 0) {
1206
- return response;
1207
- }
1208
- return null;
1209
- })
1210
- };
1211
-
1212
- // node_modules/workbox-strategies/StaleWhileRevalidate.js
1213
- var StaleWhileRevalidate = class extends Strategy {
1214
- constructor(options = {}) {
1215
- super(options);
1216
- if (!this.plugins.some((p) => "cacheWillUpdate" in p)) {
1217
- this.plugins.unshift(cacheOkAndOpaquePlugin);
1218
- }
1219
- }
1220
- _handle(request, handler) {
1221
- return __async(this, null, function* () {
1222
- const logs = [];
1223
- if (false) {
1224
- finalAssertExports.isInstance(request, Request, {
1225
- moduleName: "workbox-strategies",
1226
- className: this.constructor.name,
1227
- funcName: "handle",
1228
- paramName: "request"
1229
- });
1230
- }
1231
- const fetchAndCachePromise = handler.fetchAndCachePut(request).catch(() => {
1232
- });
1233
- let response = yield handler.cacheMatch(request);
1234
- let error;
1235
- if (response) {
1236
- if (false) {
1237
- logs.push(`Found a cached response in the '${this.cacheName}' cache. Will update with the network response in the background.`);
1238
- }
1239
- } else {
1240
- if (false) {
1241
- logs.push(`No response found in the '${this.cacheName}' cache. Will wait for the network response.`);
1242
- }
1243
- try {
1244
- response = yield fetchAndCachePromise;
1245
- } catch (err) {
1246
- if (err instanceof Error) {
1247
- error = err;
1248
- }
1249
- }
1250
- }
1251
- if (false) {
1252
- logger.groupCollapsed(messages2.strategyStart(this.constructor.name, request));
1253
- for (const log2 of logs) {
1254
- logger.log(log2);
1255
- }
1256
- messages2.printFinalResponse(response);
1257
- logger.groupEnd();
1258
- }
1259
- if (!response) {
1260
- throw new WorkboxError("no-response", { url: request.url, error });
1261
- }
1262
- return response;
1263
- });
1264
- }
1265
- };
1266
-
1267
- // src/constants.ts
1268
- var IS_DEV = false;
1269
- var HEADER_HEIGHT = 48;
1270
- var FOOTER_HEIGHT = 48;
1271
- var CHROME_HEIGHT = HEADER_HEIGHT + FOOTER_HEIGHT;
1272
- var DEFAULT_HEIGHT = `calc(100vh - ${CHROME_HEIGHT}px)`;
1273
-
1274
- // src/ServiceWorker/constants.ts
1275
- var WEBPUB_CACHE_NAME = "webpub-cache";
1276
- var PRECACHE_PUBLICATIONS = "PRECACHE_PUBLICATIONS";
1277
- var CACHE_EXPIRATION_SECONDS = 7 * 24 * 60 * 60;
1278
-
1279
- // node_modules/workbox-routing/_version.js
1280
- try {
1281
- self["workbox:routing:6.2.4"] && _();
1282
- } catch (e) {
1283
- }
1284
-
1285
- // node_modules/workbox-routing/utils/constants.js
1286
- var defaultMethod = "GET";
1287
-
1288
- // node_modules/workbox-routing/utils/normalizeHandler.js
1289
- var normalizeHandler = (handler) => {
1290
- if (handler && typeof handler === "object") {
1291
- if (false) {
1292
- finalAssertExports.hasMethod(handler, "handle", {
1293
- moduleName: "workbox-routing",
1294
- className: "Route",
1295
- funcName: "constructor",
1296
- paramName: "handler"
1297
- });
1298
- }
1299
- return handler;
1300
- } else {
1301
- if (false) {
1302
- finalAssertExports.isType(handler, "function", {
1303
- moduleName: "workbox-routing",
1304
- className: "Route",
1305
- funcName: "constructor",
1306
- paramName: "handler"
1307
- });
1308
- }
1309
- return { handle: handler };
1310
- }
1311
- };
1312
-
1313
- // node_modules/workbox-routing/Route.js
1314
- var Route = class {
1315
- constructor(match, handler, method = defaultMethod) {
1316
- if (false) {
1317
- finalAssertExports.isType(match, "function", {
1318
- moduleName: "workbox-routing",
1319
- className: "Route",
1320
- funcName: "constructor",
1321
- paramName: "match"
1322
- });
1323
- if (method) {
1324
- finalAssertExports.isOneOf(method, validMethods, { paramName: "method" });
1325
- }
1326
- }
1327
- this.handler = normalizeHandler(handler);
1328
- this.match = match;
1329
- this.method = method;
1330
- }
1331
- setCatchHandler(handler) {
1332
- this.catchHandler = normalizeHandler(handler);
1333
- }
1334
- };
1335
-
1336
- // node_modules/workbox-routing/RegExpRoute.js
1337
- var RegExpRoute = class extends Route {
1338
- constructor(regExp, handler, method) {
1339
- if (false) {
1340
- finalAssertExports.isInstance(regExp, RegExp, {
1341
- moduleName: "workbox-routing",
1342
- className: "RegExpRoute",
1343
- funcName: "constructor",
1344
- paramName: "pattern"
1345
- });
1346
- }
1347
- const match = ({ url }) => {
1348
- const result = regExp.exec(url.href);
1349
- if (!result) {
1350
- return;
1351
- }
1352
- if (url.origin !== location.origin && result.index !== 0) {
1353
- if (false) {
1354
- 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.`);
1355
- }
1356
- return;
1357
- }
1358
- return result.slice(1);
1359
- };
1360
- super(match, handler, method);
1361
- }
1362
- };
1363
-
1364
- // node_modules/workbox-routing/Router.js
1365
- var Router = class {
1366
- constructor() {
1367
- this._routes = /* @__PURE__ */ new Map();
1368
- this._defaultHandlerMap = /* @__PURE__ */ new Map();
1369
- }
1370
- get routes() {
1371
- return this._routes;
1372
- }
1373
- addFetchListener() {
1374
- self.addEventListener("fetch", (event) => {
1375
- const { request } = event;
1376
- const responsePromise = this.handleRequest({ request, event });
1377
- if (responsePromise) {
1378
- event.respondWith(responsePromise);
1379
- }
1380
- });
1381
- }
1382
- addCacheListener() {
1383
- self.addEventListener("message", (event) => {
1384
- if (event.data && event.data.type === "CACHE_URLS") {
1385
- const { payload } = event.data;
1386
- if (false) {
1387
- logger.debug(`Caching URLs from the window`, payload.urlsToCache);
1388
- }
1389
- const requestPromises = Promise.all(payload.urlsToCache.map((entry) => {
1390
- if (typeof entry === "string") {
1391
- entry = [entry];
1392
- }
1393
- const request = new Request(...entry);
1394
- return this.handleRequest({ request, event });
1395
- }));
1396
- event.waitUntil(requestPromises);
1397
- if (event.ports && event.ports[0]) {
1398
- void requestPromises.then(() => event.ports[0].postMessage(true));
1399
- }
1400
- }
1401
- });
1402
- }
1403
- handleRequest({ request, event }) {
1404
- if (false) {
1405
- finalAssertExports.isInstance(request, Request, {
1406
- moduleName: "workbox-routing",
1407
- className: "Router",
1408
- funcName: "handleRequest",
1409
- paramName: "options.request"
1410
- });
1411
- }
1412
- const url = new URL(request.url, location.href);
1413
- if (!url.protocol.startsWith("http")) {
1414
- if (false) {
1415
- logger.debug(`Workbox Router only supports URLs that start with 'http'.`);
1416
- }
1417
- return;
1418
- }
1419
- const sameOrigin = url.origin === location.origin;
1420
- const { params, route } = this.findMatchingRoute({
1421
- event,
1422
- request,
1423
- sameOrigin,
1424
- url
1425
- });
1426
- let handler = route && route.handler;
1427
- const debugMessages = [];
1428
- if (false) {
1429
- if (handler) {
1430
- debugMessages.push([
1431
- `Found a route to handle this request:`,
1432
- route
1433
- ]);
1434
- if (params) {
1435
- debugMessages.push([
1436
- `Passing the following params to the route's handler:`,
1437
- params
1438
- ]);
1439
- }
1440
- }
1441
- }
1442
- const method = request.method;
1443
- if (!handler && this._defaultHandlerMap.has(method)) {
1444
- if (false) {
1445
- debugMessages.push(`Failed to find a matching route. Falling back to the default handler for ${method}.`);
1446
- }
1447
- handler = this._defaultHandlerMap.get(method);
1448
- }
1449
- if (!handler) {
1450
- if (false) {
1451
- logger.debug(`No route found for: ${getFriendlyURL(url)}`);
1452
- }
1453
- return;
1454
- }
1455
- if (false) {
1456
- logger.groupCollapsed(`Router is responding to: ${getFriendlyURL(url)}`);
1457
- debugMessages.forEach((msg) => {
1458
- if (Array.isArray(msg)) {
1459
- logger.log(...msg);
1460
- } else {
1461
- logger.log(msg);
1462
- }
1463
- });
1464
- logger.groupEnd();
1465
- }
1466
- let responsePromise;
1467
- try {
1468
- responsePromise = handler.handle({ url, request, event, params });
1469
- } catch (err) {
1470
- responsePromise = Promise.reject(err);
1471
- }
1472
- const catchHandler = route && route.catchHandler;
1473
- if (responsePromise instanceof Promise && (this._catchHandler || catchHandler)) {
1474
- responsePromise = responsePromise.catch((err) => __async(this, null, function* () {
1475
- if (catchHandler) {
1476
- if (false) {
1477
- logger.groupCollapsed(`Error thrown when responding to: ${getFriendlyURL(url)}. Falling back to route's Catch Handler.`);
1478
- logger.error(`Error thrown by:`, route);
1479
- logger.error(err);
1480
- logger.groupEnd();
1481
- }
1482
- try {
1483
- return yield catchHandler.handle({ url, request, event, params });
1484
- } catch (catchErr) {
1485
- if (catchErr instanceof Error) {
1486
- err = catchErr;
1487
- }
1488
- }
1489
- }
1490
- if (this._catchHandler) {
1491
- if (false) {
1492
- logger.groupCollapsed(`Error thrown when responding to: ${getFriendlyURL(url)}. Falling back to global Catch Handler.`);
1493
- logger.error(`Error thrown by:`, route);
1494
- logger.error(err);
1495
- logger.groupEnd();
1496
- }
1497
- return this._catchHandler.handle({ url, request, event });
1498
- }
1499
- throw err;
1500
- }));
1501
- }
1502
- return responsePromise;
1503
- }
1504
- findMatchingRoute({ url, sameOrigin, request, event }) {
1505
- const routes = this._routes.get(request.method) || [];
1506
- for (const route of routes) {
1507
- let params;
1508
- const matchResult = route.match({ url, sameOrigin, request, event });
1509
- if (matchResult) {
1510
- if (false) {
1511
- if (matchResult instanceof Promise) {
1512
- logger.warn(`While routing ${getFriendlyURL(url)}, an async matchCallback function was used. Please convert the following route to use a synchronous matchCallback function:`, route);
1513
- }
1514
- }
1515
- params = matchResult;
1516
- if (Array.isArray(params) && params.length === 0) {
1517
- params = void 0;
1518
- } else if (matchResult.constructor === Object && Object.keys(matchResult).length === 0) {
1519
- params = void 0;
1520
- } else if (typeof matchResult === "boolean") {
1521
- params = void 0;
1522
- }
1523
- return { route, params };
1524
- }
1525
- }
1526
- return {};
1527
- }
1528
- setDefaultHandler(handler, method = defaultMethod) {
1529
- this._defaultHandlerMap.set(method, normalizeHandler(handler));
1530
- }
1531
- setCatchHandler(handler) {
1532
- this._catchHandler = normalizeHandler(handler);
1533
- }
1534
- registerRoute(route) {
1535
- if (false) {
1536
- finalAssertExports.isType(route, "object", {
1537
- moduleName: "workbox-routing",
1538
- className: "Router",
1539
- funcName: "registerRoute",
1540
- paramName: "route"
1541
- });
1542
- finalAssertExports.hasMethod(route, "match", {
1543
- moduleName: "workbox-routing",
1544
- className: "Router",
1545
- funcName: "registerRoute",
1546
- paramName: "route"
1547
- });
1548
- finalAssertExports.isType(route.handler, "object", {
1549
- moduleName: "workbox-routing",
1550
- className: "Router",
1551
- funcName: "registerRoute",
1552
- paramName: "route"
1553
- });
1554
- finalAssertExports.hasMethod(route.handler, "handle", {
1555
- moduleName: "workbox-routing",
1556
- className: "Router",
1557
- funcName: "registerRoute",
1558
- paramName: "route.handler"
1559
- });
1560
- finalAssertExports.isType(route.method, "string", {
1561
- moduleName: "workbox-routing",
1562
- className: "Router",
1563
- funcName: "registerRoute",
1564
- paramName: "route.method"
1565
- });
1566
- }
1567
- if (!this._routes.has(route.method)) {
1568
- this._routes.set(route.method, []);
1569
- }
1570
- this._routes.get(route.method).push(route);
1571
- }
1572
- unregisterRoute(route) {
1573
- if (!this._routes.has(route.method)) {
1574
- throw new WorkboxError("unregister-route-but-not-found-with-method", {
1575
- method: route.method
1576
- });
1577
- }
1578
- const routeIndex = this._routes.get(route.method).indexOf(route);
1579
- if (routeIndex > -1) {
1580
- this._routes.get(route.method).splice(routeIndex, 1);
1581
- } else {
1582
- throw new WorkboxError("unregister-route-route-not-registered");
1583
- }
1584
- }
1585
- };
1586
-
1587
- // node_modules/workbox-routing/utils/getOrCreateDefaultRouter.js
1588
- var defaultRouter;
1589
- var getOrCreateDefaultRouter = () => {
1590
- if (!defaultRouter) {
1591
- defaultRouter = new Router();
1592
- defaultRouter.addFetchListener();
1593
- defaultRouter.addCacheListener();
1594
- }
1595
- return defaultRouter;
1596
- };
1597
-
1598
- // node_modules/workbox-routing/registerRoute.js
1599
- function registerRoute(capture, handler, method) {
1600
- let route;
1601
- if (typeof capture === "string") {
1602
- const captureUrl = new URL(capture, location.href);
1603
- if (false) {
1604
- if (!(capture.startsWith("/") || capture.startsWith("http"))) {
1605
- throw new WorkboxError("invalid-string", {
1606
- moduleName: "workbox-routing",
1607
- funcName: "registerRoute",
1608
- paramName: "capture"
1609
- });
1610
- }
1611
- const valueToCheck = capture.startsWith("http") ? captureUrl.pathname : capture;
1612
- const wildcards = "[*:?+]";
1613
- if (new RegExp(`${wildcards}`).exec(valueToCheck)) {
1614
- 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.`);
1615
- }
1616
- }
1617
- const matchCallback = ({ url }) => {
1618
- if (false) {
1619
- if (url.pathname === captureUrl.pathname && url.origin !== captureUrl.origin) {
1620
- 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.`);
1621
- }
1622
- }
1623
- return url.href === captureUrl.href;
1624
- };
1625
- route = new Route(matchCallback, handler, method);
1626
- } else if (capture instanceof RegExp) {
1627
- route = new RegExpRoute(capture, handler, method);
1628
- } else if (typeof capture === "function") {
1629
- route = new Route(capture, handler, method);
1630
- } else if (capture instanceof Route) {
1631
- route = capture;
1632
- } else {
1633
- throw new WorkboxError("unsupported-route-type", {
1634
- moduleName: "workbox-routing",
1635
- funcName: "registerRoute",
1636
- paramName: "capture"
1637
- });
1638
- }
1639
- const defaultRouter2 = getOrCreateDefaultRouter();
1640
- defaultRouter2.registerRoute(route);
1641
- return route;
1642
- }
1643
-
1644
- // src/ServiceWorker/sw.ts
1645
- var VERSION = "v2";
1646
- clientsClaim();
1647
- function initWebReaderSW({
1648
- cacheExpirationSeconds = CACHE_EXPIRATION_SECONDS
1649
- } = {}) {
1650
- log("INITIALIZING");
1651
- self.addEventListener("install", (event) => {
1652
- log("INSTALLING ");
1653
- function installSW() {
1654
- return __async(this, null, function* () {
1655
- yield self.skipWaiting();
1656
- log("INSTALLED");
1657
- });
1658
- }
1659
- event.waitUntil(installSW());
1660
- });
1661
- self.addEventListener("message", (event) => __async(this, null, function* () {
1662
- if (event.data.type === PRECACHE_PUBLICATIONS) {
1663
- log("Precaching publications");
1664
- if (typeof event.data.publications !== "object") {
1665
- console.error("Precache event missing publications");
1666
- return;
1667
- }
1668
- yield cachePublications(event.data.publications);
1669
- }
1670
- }));
1671
- const cacheFirst = new CacheFirst({
1672
- cacheName: WEBPUB_CACHE_NAME,
1673
- plugins: [
1674
- new ExpirationPlugin({
1675
- maxAgeSeconds: cacheExpirationSeconds
1676
- })
1677
- ]
1678
- });
1679
- function cachePublications(publications) {
1680
- return __async(this, null, function* () {
1681
- var _a;
1682
- const cache = yield caches.open(WEBPUB_CACHE_NAME);
1683
- for (const pub of publications) {
1684
- for (const url of (_a = pub.swrUrls) != null ? _a : []) {
1685
- log(`Routing ${url}`);
1686
- registerRoute(url, new StaleWhileRevalidate({ cacheName: WEBPUB_CACHE_NAME }));
1687
- }
1688
- }
1689
- const pubResults = yield Promise.allSettled(publications.map((pub) => __async(this, null, function* () {
1690
- const finalManifestUrl = getProxiedUrl(pub.manifestUrl, pub.proxyUrl);
1691
- registerRoute(finalManifestUrl, cacheFirst);
1692
- const match = yield cache.match(finalManifestUrl);
1693
- if (match) {
1694
- return __spreadProps(__spreadValues({}, pub), { manifest: yield match.json() });
1695
- }
1696
- const manifestResponse = yield fetch(finalManifestUrl);
1697
- handleBadResponse(finalManifestUrl, manifestResponse);
1698
- yield cache.put(finalManifestUrl, manifestResponse.clone());
1699
- const manifest = yield manifestResponse.json();
1700
- return __spreadProps(__spreadValues({}, pub), { manifest });
1701
- })));
1702
- const pubs = pubResults.map((result) => result.status === "fulfilled" ? result.value : void 0).filter(isPub);
1703
- const promises = pubs.map((pub) => __async(this, null, function* () {
1704
- var _a2, _b;
1705
- const resourceHrefs = extractHrefs((_a2 = pub.manifest.resources) != null ? _a2 : [], pub.manifestUrl, pub.proxyUrl);
1706
- const readingOrderHrefs = extractHrefs((_b = pub.manifest.readingOrder) != null ? _b : [], pub.manifestUrl, pub.proxyUrl);
1707
- const allResourcesToCache = Array.from(/* @__PURE__ */ new Set([...resourceHrefs, ...readingOrderHrefs]));
1708
- yield Promise.all(allResourcesToCache.map((url) => __async(this, null, function* () {
1709
- registerRoute(url, cacheFirst);
1710
- const match = yield cache.match(url);
1711
- if (match) {
1712
- return;
1713
- }
1714
- const response = yield fetch(url);
1715
- handleBadResponse(url, response);
1716
- return yield cache.put(url, response);
1717
- })));
1718
- }));
1719
- return yield Promise.allSettled(promises);
1720
- });
1721
- }
1722
- }
1723
- function isPub(maybe) {
1724
- return !!maybe;
1725
- }
1726
- function handleBadResponse(url, response) {
1727
- if (!response.ok) {
1728
- const message = `Bad response status for: ${url}. Status: ${response.status}`;
1729
- console.warn(message);
1730
- throw new Error(message);
1731
- }
1732
- }
1733
- function getProxiedUrl(url, proxyUrl) {
1734
- return proxyUrl ? `${proxyUrl}${encodeURIComponent(url)}` : url;
1735
- }
1736
- function getAbsoluteUrl(maybeRelative, manifestUrl, proxyUrl) {
1737
- return getProxiedUrl(new URL(maybeRelative, manifestUrl).toString(), proxyUrl);
1738
- }
1739
- function extractHrefs(links, manifestUrl, proxyUrl) {
1740
- return links.map((res) => getAbsoluteUrl(res.href, manifestUrl, proxyUrl));
1741
- }
1742
- function log(message) {
1743
- if (IS_DEV)
1744
- console.log(`SW (${VERSION}) -`, message);
1745
- }
1746
- export {
1747
- initWebReaderSW as default
1748
- };
1749
- //# sourceMappingURL=sw.js.map