@serwist/core 8.0.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 (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -0
  3. package/dist/_private/Deferred.d.ts +19 -0
  4. package/dist/_private/Deferred.d.ts.map +1 -0
  5. package/dist/_private/SerwistError.d.ts +24 -0
  6. package/dist/_private/SerwistError.d.ts.map +1 -0
  7. package/dist/_private/assert.d.ts +11 -0
  8. package/dist/_private/assert.d.ts.map +1 -0
  9. package/dist/_private/cacheMatchIgnoreParams.d.ts +15 -0
  10. package/dist/_private/cacheMatchIgnoreParams.d.ts.map +1 -0
  11. package/dist/_private/cacheNames.d.ts +40 -0
  12. package/dist/_private/cacheNames.d.ts.map +1 -0
  13. package/dist/_private/canConstructReadableStream.d.ts +12 -0
  14. package/dist/_private/canConstructReadableStream.d.ts.map +1 -0
  15. package/dist/_private/canConstructResponseFromBodyStream.d.ts +11 -0
  16. package/dist/_private/canConstructResponseFromBodyStream.d.ts.map +1 -0
  17. package/dist/_private/dontWaitFor.d.ts +7 -0
  18. package/dist/_private/dontWaitFor.d.ts.map +1 -0
  19. package/dist/_private/executeQuotaErrorCallbacks.d.ts +9 -0
  20. package/dist/_private/executeQuotaErrorCallbacks.d.ts.map +1 -0
  21. package/dist/_private/getFriendlyURL.d.ts +3 -0
  22. package/dist/_private/getFriendlyURL.d.ts.map +1 -0
  23. package/dist/_private/logger.d.ts +11 -0
  24. package/dist/_private/logger.d.ts.map +1 -0
  25. package/dist/_private/resultingClientExists.d.ts +12 -0
  26. package/dist/_private/resultingClientExists.d.ts.map +1 -0
  27. package/dist/_private/timeout.d.ts +10 -0
  28. package/dist/_private/timeout.d.ts.map +1 -0
  29. package/dist/_private/waitUntil.d.ts +12 -0
  30. package/dist/_private/waitUntil.d.ts.map +1 -0
  31. package/dist/cacheNames.d.ts +21 -0
  32. package/dist/cacheNames.d.ts.map +1 -0
  33. package/dist/clientsClaim.d.ts +7 -0
  34. package/dist/clientsClaim.d.ts.map +1 -0
  35. package/dist/copyResponse.d.ts +21 -0
  36. package/dist/copyResponse.d.ts.map +1 -0
  37. package/dist/index.d.ts +12 -0
  38. package/dist/index.d.ts.map +1 -0
  39. package/dist/index.internal.d.ts +16 -0
  40. package/dist/index.internal.d.ts.map +1 -0
  41. package/dist/index.internal.js +652 -0
  42. package/dist/index.internal.old.cjs +667 -0
  43. package/dist/index.js +571 -0
  44. package/dist/index.old.cjs +577 -0
  45. package/dist/models/messages/messageGenerator.d.ts +2 -0
  46. package/dist/models/messages/messageGenerator.d.ts.map +1 -0
  47. package/dist/models/messages/messages.d.ts +9 -0
  48. package/dist/models/messages/messages.d.ts.map +1 -0
  49. package/dist/models/pluginEvents.d.ts +10 -0
  50. package/dist/models/pluginEvents.d.ts.map +1 -0
  51. package/dist/models/quotaErrorCallbacks.d.ts +3 -0
  52. package/dist/models/quotaErrorCallbacks.d.ts.map +1 -0
  53. package/dist/registerQuotaErrorCallback.d.ts +9 -0
  54. package/dist/registerQuotaErrorCallback.d.ts.map +1 -0
  55. package/dist/setCacheNameDetails.d.ts +10 -0
  56. package/dist/setCacheNameDetails.d.ts.map +1 -0
  57. package/dist/types.d.ts +273 -0
  58. package/dist/types.d.ts.map +1 -0
  59. package/dist/utils/pluginUtils.d.ts +5 -0
  60. package/dist/utils/pluginUtils.d.ts.map +1 -0
  61. package/dist/utils/welcome.d.ts +2 -0
  62. package/dist/utils/welcome.d.ts.map +1 -0
  63. package/package.json +59 -0
@@ -0,0 +1,652 @@
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
+ */ const messages = {
8
+ "invalid-value": ({ paramName, validValueDescription, value })=>{
9
+ if (!paramName || !validValueDescription) {
10
+ throw new Error(`Unexpected input to 'invalid-value' error.`);
11
+ }
12
+ return `The '${paramName}' parameter was given a value with an ` + `unexpected value. ${validValueDescription} Received a value of ` + `${JSON.stringify(value)}.`;
13
+ },
14
+ "not-an-array": ({ moduleName, className, funcName, paramName })=>{
15
+ if (!moduleName || !className || !funcName || !paramName) {
16
+ throw new Error(`Unexpected input to 'not-an-array' error.`);
17
+ }
18
+ return `The parameter '${paramName}' passed into ` + `'${moduleName}.${className}.${funcName}()' must be an array.`;
19
+ },
20
+ "incorrect-type": ({ expectedType, paramName, moduleName, className, funcName })=>{
21
+ if (!expectedType || !paramName || !moduleName || !funcName) {
22
+ throw new Error(`Unexpected input to 'incorrect-type' error.`);
23
+ }
24
+ const classNameStr = className ? `${className}.` : "";
25
+ return `The parameter '${paramName}' passed into ` + `'${moduleName}.${classNameStr}` + `${funcName}()' must be of type ${expectedType}.`;
26
+ },
27
+ "incorrect-class": ({ expectedClassName, paramName, moduleName, className, funcName, isReturnValueProblem })=>{
28
+ if (!expectedClassName || !moduleName || !funcName) {
29
+ throw new Error(`Unexpected input to 'incorrect-class' error.`);
30
+ }
31
+ const classNameStr = className ? `${className}.` : "";
32
+ if (isReturnValueProblem) {
33
+ return `The return value from ` + `'${moduleName}.${classNameStr}${funcName}()' ` + `must be an instance of class ${expectedClassName}.`;
34
+ }
35
+ return `The parameter '${paramName}' passed into ` + `'${moduleName}.${classNameStr}${funcName}()' ` + `must be an instance of class ${expectedClassName}.`;
36
+ },
37
+ "missing-a-method": ({ expectedMethod, paramName, moduleName, className, funcName })=>{
38
+ if (!expectedMethod || !paramName || !moduleName || !className || !funcName) {
39
+ throw new Error(`Unexpected input to 'missing-a-method' error.`);
40
+ }
41
+ return `${moduleName}.${className}.${funcName}() expected the ` + `'${paramName}' parameter to expose a '${expectedMethod}' method.`;
42
+ },
43
+ "add-to-cache-list-unexpected-type": ({ entry })=>{
44
+ return `An unexpected entry was passed to ` + `'@serwist/precaching.PrecacheController.addToCacheList()' The entry ` + `'${JSON.stringify(entry)}' isn't supported. You must supply an array of ` + `strings with one or more characters, objects with a url property or ` + `Request objects.`;
45
+ },
46
+ "add-to-cache-list-conflicting-entries": ({ firstEntry, secondEntry })=>{
47
+ if (!firstEntry || !secondEntry) {
48
+ throw new Error(`Unexpected input to ` + `'add-to-cache-list-duplicate-entries' error.`);
49
+ }
50
+ return `Two of the entries passed to ` + `'@serwist/precaching.PrecacheController.addToCacheList()' had the URL ` + `${firstEntry} but different revision details. Serwist is ` + `unable to cache and version the asset correctly. Please remove one ` + `of the entries.`;
51
+ },
52
+ "plugin-error-request-will-fetch": ({ thrownErrorMessage })=>{
53
+ if (!thrownErrorMessage) {
54
+ throw new Error(`Unexpected input to ` + `'plugin-error-request-will-fetch', error.`);
55
+ }
56
+ return `An error was thrown by a plugins 'requestWillFetch()' method. ` + `The thrown error message was: '${thrownErrorMessage}'.`;
57
+ },
58
+ "invalid-cache-name": ({ cacheNameId, value })=>{
59
+ if (!cacheNameId) {
60
+ throw new Error(`Expected a 'cacheNameId' for error 'invalid-cache-name'`);
61
+ }
62
+ return `You must provide a name containing at least one character for ` + `setCacheDetails({${cacheNameId}: '...'}). Received a value of ` + `'${JSON.stringify(value)}'`;
63
+ },
64
+ "unregister-route-but-not-found-with-method": ({ method })=>{
65
+ if (!method) {
66
+ throw new Error(`Unexpected input to ` + `'unregister-route-but-not-found-with-method' error.`);
67
+ }
68
+ return `The route you're trying to unregister was not previously ` + `registered for the method type '${method}'.`;
69
+ },
70
+ "unregister-route-route-not-registered": ()=>{
71
+ return `The route you're trying to unregister was not previously ` + `registered.`;
72
+ },
73
+ "queue-replay-failed": ({ name })=>{
74
+ return `Replaying the background sync queue '${name}' failed.`;
75
+ },
76
+ "duplicate-queue-name": ({ name })=>{
77
+ return `The Queue name '${name}' is already being used. ` + `All instances of backgroundSync.Queue must be given unique names.`;
78
+ },
79
+ "expired-test-without-max-age": ({ methodName, paramName })=>{
80
+ return `The '${methodName}()' method can only be used when the ` + `'${paramName}' is used in the constructor.`;
81
+ },
82
+ "unsupported-route-type": ({ moduleName, className, funcName, paramName })=>{
83
+ return `The supplied '${paramName}' parameter was an unsupported type. ` + `Please check the docs for ${moduleName}.${className}.${funcName} for ` + `valid input types.`;
84
+ },
85
+ "not-array-of-class": ({ value, expectedClass, moduleName, className, funcName, paramName })=>{
86
+ return `The supplied '${paramName}' parameter must be an array of ` + `'${expectedClass}' objects. Received '${JSON.stringify(value)},'. ` + `Please check the call to ${moduleName}.${className}.${funcName}() ` + `to fix the issue.`;
87
+ },
88
+ "max-entries-or-age-required": ({ moduleName, className, funcName })=>{
89
+ return `You must define either config.maxEntries or config.maxAgeSeconds` + `in ${moduleName}.${className}.${funcName}`;
90
+ },
91
+ "statuses-or-headers-required": ({ moduleName, className, funcName })=>{
92
+ return `You must define either config.statuses or config.headers` + `in ${moduleName}.${className}.${funcName}`;
93
+ },
94
+ "invalid-string": ({ moduleName, funcName, paramName })=>{
95
+ if (!paramName || !moduleName || !funcName) {
96
+ throw new Error(`Unexpected input to 'invalid-string' error.`);
97
+ }
98
+ return `When using strings, the '${paramName}' parameter must start with ` + `'http' (for cross-origin matches) or '/' (for same-origin matches). ` + `Please see the docs for ${moduleName}.${funcName}() for ` + `more info.`;
99
+ },
100
+ "channel-name-required": ()=>{
101
+ return `You must provide a channelName to construct a ` + `BroadcastCacheUpdate instance.`;
102
+ },
103
+ "invalid-responses-are-same-args": ()=>{
104
+ return `The arguments passed into responsesAreSame() appear to be ` + `invalid. Please ensure valid Responses are used.`;
105
+ },
106
+ "expire-custom-caches-only": ()=>{
107
+ return `You must provide a 'cacheName' property when using the ` + `expiration plugin with a runtime caching strategy.`;
108
+ },
109
+ "unit-must-be-bytes": ({ normalizedRangeHeader })=>{
110
+ if (!normalizedRangeHeader) {
111
+ throw new Error(`Unexpected input to 'unit-must-be-bytes' error.`);
112
+ }
113
+ return `The 'unit' portion of the Range header must be set to 'bytes'. ` + `The Range header provided was "${normalizedRangeHeader}"`;
114
+ },
115
+ "single-range-only": ({ normalizedRangeHeader })=>{
116
+ if (!normalizedRangeHeader) {
117
+ throw new Error(`Unexpected input to 'single-range-only' error.`);
118
+ }
119
+ return `Multiple ranges are not supported. Please use a single start ` + `value, and optional end value. The Range header provided was ` + `"${normalizedRangeHeader}"`;
120
+ },
121
+ "invalid-range-values": ({ normalizedRangeHeader })=>{
122
+ if (!normalizedRangeHeader) {
123
+ throw new Error(`Unexpected input to 'invalid-range-values' error.`);
124
+ }
125
+ return `The Range header is missing both start and end values. At least ` + `one of those values is needed. The Range header provided was ` + `"${normalizedRangeHeader}"`;
126
+ },
127
+ "no-range-header": ()=>{
128
+ return `No Range header was found in the Request provided.`;
129
+ },
130
+ "range-not-satisfiable": ({ size, start, end })=>{
131
+ return `The start (${start}) and end (${end}) values in the Range are ` + `not satisfiable by the cached response, which is ${size} bytes.`;
132
+ },
133
+ "attempt-to-cache-non-get-request": ({ url, method })=>{
134
+ return `Unable to cache '${url}' because it is a '${method}' request and ` + `only 'GET' requests can be cached.`;
135
+ },
136
+ "cache-put-with-no-response": ({ url })=>{
137
+ return `There was an attempt to cache '${url}' but the response was not ` + `defined.`;
138
+ },
139
+ "no-response": ({ url, error })=>{
140
+ let message = `The strategy could not generate a response for '${url}'.`;
141
+ if (error) {
142
+ message += ` The underlying error is ${error}.`;
143
+ }
144
+ return message;
145
+ },
146
+ "bad-precaching-response": ({ url, status })=>{
147
+ return `The precaching request for '${url}' failed` + (status ? ` with an HTTP status of ${status}.` : `.`);
148
+ },
149
+ "non-precached-url": ({ url })=>{
150
+ return `createHandlerBoundToURL('${url}') was called, but that URL is ` + `not precached. Please pass in a URL that is precached instead.`;
151
+ },
152
+ "add-to-cache-list-conflicting-integrities": ({ url })=>{
153
+ return `Two of the entries passed to ` + `'@serwist/precaching.PrecacheController.addToCacheList()' had the URL ` + `${url} with different integrity values. Please remove one of them.`;
154
+ },
155
+ "missing-precache-entry": ({ cacheName, url })=>{
156
+ return `Unable to find a precached response in ${cacheName} for ${url}.`;
157
+ },
158
+ "cross-origin-copy-response": ({ origin })=>{
159
+ return `@serwist/core.copyResponse() can only be used with same-origin ` + `responses. It was passed a response with origin ${origin}.`;
160
+ },
161
+ "opaque-streams-source": ({ type })=>{
162
+ const message = `One of the @serwist/streams sources resulted in an ` + `'${type}' response.`;
163
+ if (type === "opaqueredirect") {
164
+ return `${message} Please do not use a navigation request that results ` + `in a redirect as a source.`;
165
+ }
166
+ return `${message} Please ensure your sources are CORS-enabled.`;
167
+ }
168
+ };
169
+
170
+ const fallback = (code, ...args)=>{
171
+ let msg = code;
172
+ if (args.length > 0) {
173
+ msg += ` :: ${JSON.stringify(args)}`;
174
+ }
175
+ return msg;
176
+ };
177
+ const generatorFunction = (code, details = {})=>{
178
+ const message = messages[code];
179
+ if (!message) {
180
+ throw new Error(`Unable to find message for code '${code}'.`);
181
+ }
182
+ return message(details);
183
+ };
184
+ const messageGenerator = process.env.NODE_ENV === "production" ? fallback : generatorFunction;
185
+
186
+ /**
187
+ * Serwist errors should be thrown with this class.
188
+ * This allows use to ensure the type easily in tests,
189
+ * helps developers identify errors from Serwist
190
+ * easily and allows use to optimise error
191
+ * messages correctly.
192
+ *
193
+ * @private
194
+ */ class SerwistError extends Error {
195
+ details;
196
+ /**
197
+ *
198
+ * @param errorCode The error code that
199
+ * identifies this particular error.
200
+ * @param details Any relevant arguments
201
+ * that will help developers identify issues should
202
+ * be added as a key on the context object.
203
+ */ constructor(errorCode, details){
204
+ const message = messageGenerator(errorCode, details);
205
+ super(message);
206
+ this.name = errorCode;
207
+ this.details = details;
208
+ }
209
+ }
210
+
211
+ /*
212
+ * This method throws if the supplied value is not an array.
213
+ * The destructed values are required to produce a meaningful error for users.
214
+ * The destructed and restructured object is so it's clear what is
215
+ * needed.
216
+ */ const isArray = (value, details)=>{
217
+ if (!Array.isArray(value)) {
218
+ throw new SerwistError("not-an-array", details);
219
+ }
220
+ };
221
+ const hasMethod = (object, expectedMethod, details)=>{
222
+ const type = typeof object[expectedMethod];
223
+ if (type !== "function") {
224
+ details["expectedMethod"] = expectedMethod;
225
+ throw new SerwistError("missing-a-method", details);
226
+ }
227
+ };
228
+ const isType = (object, expectedType, details)=>{
229
+ if (typeof object !== expectedType) {
230
+ details["expectedType"] = expectedType;
231
+ throw new SerwistError("incorrect-type", details);
232
+ }
233
+ };
234
+ const isInstance = (object, // Need the general type to do the check later.
235
+ // eslint-disable-next-line @typescript-eslint/ban-types
236
+ expectedClass, details)=>{
237
+ if (!(object instanceof expectedClass)) {
238
+ details["expectedClassName"] = expectedClass.name;
239
+ throw new SerwistError("incorrect-class", details);
240
+ }
241
+ };
242
+ const isOneOf = (value, validValues, details)=>{
243
+ if (!validValues.includes(value)) {
244
+ details["validValueDescription"] = `Valid values are ${JSON.stringify(validValues)}.`;
245
+ throw new SerwistError("invalid-value", details);
246
+ }
247
+ };
248
+ const isArrayOfClass = (value, // Need general type to do check later.
249
+ expectedClass, details)=>{
250
+ const error = new SerwistError("not-array-of-class", details);
251
+ if (!Array.isArray(value)) {
252
+ throw error;
253
+ }
254
+ for (const item of value){
255
+ if (!(item instanceof expectedClass)) {
256
+ throw error;
257
+ }
258
+ }
259
+ };
260
+ const finalAssertExports = process.env.NODE_ENV === "production" ? null : {
261
+ hasMethod,
262
+ isArray,
263
+ isInstance,
264
+ isOneOf,
265
+ isType,
266
+ isArrayOfClass
267
+ };
268
+
269
+ /*
270
+ Copyright 2020 Google LLC
271
+ Use of this source code is governed by an MIT-style
272
+ license that can be found in the LICENSE file or at
273
+ https://opensource.org/licenses/MIT.
274
+ */ function stripParams(fullURL, ignoreParams) {
275
+ const strippedURL = new URL(fullURL);
276
+ for (const param of ignoreParams){
277
+ strippedURL.searchParams.delete(param);
278
+ }
279
+ return strippedURL.href;
280
+ }
281
+ /**
282
+ * Matches an item in the cache, ignoring specific URL params. This is similar
283
+ * to the `ignoreSearch` option, but it allows you to ignore just specific
284
+ * params (while continuing to match on the others).
285
+ *
286
+ * @private
287
+ * @param cache
288
+ * @param request
289
+ * @param matchOptions
290
+ * @param ignoreParams
291
+ * @returns
292
+ */ async function cacheMatchIgnoreParams(cache, request, ignoreParams, matchOptions) {
293
+ const strippedRequestURL = stripParams(request.url, ignoreParams);
294
+ // If the request doesn't include any ignored params, match as normal.
295
+ if (request.url === strippedRequestURL) {
296
+ return cache.match(request, matchOptions);
297
+ }
298
+ // Otherwise, match by comparing keys
299
+ const keysOptions = {
300
+ ...matchOptions,
301
+ ignoreSearch: true
302
+ };
303
+ const cacheKeys = await cache.keys(request, keysOptions);
304
+ for (const cacheKey of cacheKeys){
305
+ const strippedCacheKeyURL = stripParams(cacheKey.url, ignoreParams);
306
+ if (strippedRequestURL === strippedCacheKeyURL) {
307
+ return cache.match(cacheKey, matchOptions);
308
+ }
309
+ }
310
+ return;
311
+ }
312
+
313
+ /*
314
+ Copyright 2018 Google LLC
315
+
316
+ Use of this source code is governed by an MIT-style
317
+ license that can be found in the LICENSE file or at
318
+ https://opensource.org/licenses/MIT.
319
+ */ const _cacheNameDetails = {
320
+ googleAnalytics: "googleAnalytics",
321
+ precache: "precache-v2",
322
+ prefix: "serwist",
323
+ runtime: "runtime",
324
+ suffix: typeof registration !== "undefined" ? registration.scope : ""
325
+ };
326
+ const _createCacheName = (cacheName)=>{
327
+ return [
328
+ _cacheNameDetails.prefix,
329
+ cacheName,
330
+ _cacheNameDetails.suffix
331
+ ].filter((value)=>value && value.length > 0).join("-");
332
+ };
333
+ const eachCacheNameDetail = (fn)=>{
334
+ for (const key of Object.keys(_cacheNameDetails)){
335
+ fn(key);
336
+ }
337
+ };
338
+ const cacheNames = {
339
+ updateDetails: (details)=>{
340
+ eachCacheNameDetail((key)=>{
341
+ const detail = details[key];
342
+ if (typeof detail === "string") {
343
+ _cacheNameDetails[key] = detail;
344
+ }
345
+ });
346
+ },
347
+ getGoogleAnalyticsName: (userCacheName)=>{
348
+ return userCacheName || _createCacheName(_cacheNameDetails.googleAnalytics);
349
+ },
350
+ getPrecacheName: (userCacheName)=>{
351
+ return userCacheName || _createCacheName(_cacheNameDetails.precache);
352
+ },
353
+ getPrefix: ()=>{
354
+ return _cacheNameDetails.prefix;
355
+ },
356
+ getRuntimeName: (userCacheName)=>{
357
+ return userCacheName || _createCacheName(_cacheNameDetails.runtime);
358
+ },
359
+ getSuffix: ()=>{
360
+ return _cacheNameDetails.suffix;
361
+ }
362
+ };
363
+
364
+ /*
365
+ Copyright 2019 Google LLC
366
+
367
+ Use of this source code is governed by an MIT-style
368
+ license that can be found in the LICENSE file or at
369
+ https://opensource.org/licenses/MIT.
370
+ */ let supportStatus$1;
371
+ /**
372
+ * A utility function that determines whether the current browser supports
373
+ * constructing a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream)
374
+ * object.
375
+ *
376
+ * @returns `true`, if the current browser can successfully construct a `ReadableStream`, `false` otherwise.
377
+ *
378
+ * @private
379
+ */ function canConstructReadableStream() {
380
+ if (supportStatus$1 === undefined) {
381
+ // See https://github.com/GoogleChrome/workbox/issues/1473
382
+ try {
383
+ new ReadableStream({
384
+ start () {}
385
+ });
386
+ supportStatus$1 = true;
387
+ } catch (error) {
388
+ supportStatus$1 = false;
389
+ }
390
+ }
391
+ return supportStatus$1;
392
+ }
393
+
394
+ /*
395
+ Copyright 2019 Google LLC
396
+
397
+ Use of this source code is governed by an MIT-style
398
+ license that can be found in the LICENSE file or at
399
+ https://opensource.org/licenses/MIT.
400
+ */ let supportStatus;
401
+ /**
402
+ * A utility function that determines whether the current browser supports
403
+ * constructing a new `Response` from a `response.body` stream.
404
+ *
405
+ * @returns `true`, if the current browser can successfully construct
406
+ * a `Response` from a `response.body` stream, `false` otherwise.
407
+ * @private
408
+ */ function canConstructResponseFromBodyStream() {
409
+ if (supportStatus === undefined) {
410
+ const testResponse = new Response("");
411
+ if ("body" in testResponse) {
412
+ try {
413
+ new Response(testResponse.body);
414
+ supportStatus = true;
415
+ } catch (error) {
416
+ supportStatus = false;
417
+ }
418
+ }
419
+ supportStatus = false;
420
+ }
421
+ return supportStatus;
422
+ }
423
+
424
+ /*
425
+ Copyright 2018 Google LLC
426
+
427
+ Use of this source code is governed by an MIT-style
428
+ license that can be found in the LICENSE file or at
429
+ https://opensource.org/licenses/MIT.
430
+ */ /**
431
+ * The Deferred class composes Promises in a way that allows for them to be
432
+ * resolved or rejected from outside the constructor. In most cases promises
433
+ * should be used directly, but Deferreds can be necessary when the logic to
434
+ * resolve a promise must be separate.
435
+ *
436
+ * @private
437
+ */ class Deferred {
438
+ promise;
439
+ resolve;
440
+ reject;
441
+ /**
442
+ * Creates a promise and exposes its resolve and reject functions as methods.
443
+ */ constructor(){
444
+ this.promise = new Promise((resolve, reject)=>{
445
+ this.resolve = resolve;
446
+ this.reject = reject;
447
+ });
448
+ }
449
+ }
450
+
451
+ /*
452
+ Copyright 2019 Google LLC
453
+ Use of this source code is governed by an MIT-style
454
+ license that can be found in the LICENSE file or at
455
+ https://opensource.org/licenses/MIT.
456
+ */ /**
457
+ * A helper function that prevents a promise from being flagged as unused.
458
+ *
459
+ * @private
460
+ **/ function dontWaitFor(promise) {
461
+ // Effective no-op.
462
+ void promise.then(()=>{});
463
+ }
464
+
465
+ /*
466
+ Copyright 2019 Google LLC
467
+ Use of this source code is governed by an MIT-style
468
+ license that can be found in the LICENSE file or at
469
+ https://opensource.org/licenses/MIT.
470
+ */ // logger is used inside of both service workers and the window global scope.
471
+ const logger = process.env.NODE_ENV === "production" ? null : (()=>{
472
+ // Don't overwrite this value if it's already set.
473
+ // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923
474
+ if (!("__WB_DISABLE_DEV_LOGS" in globalThis)) {
475
+ self.__WB_DISABLE_DEV_LOGS = false;
476
+ }
477
+ let inGroup = false;
478
+ const methodToColorMap = {
479
+ debug: `#7f8c8d`,
480
+ log: `#2ecc71`,
481
+ warn: `#f39c12`,
482
+ error: `#c0392b`,
483
+ groupCollapsed: `#3498db`,
484
+ groupEnd: null
485
+ };
486
+ const print = function(method, args) {
487
+ if (self.__WB_DISABLE_DEV_LOGS) {
488
+ return;
489
+ }
490
+ if (method === "groupCollapsed") {
491
+ // Safari doesn't print all console.groupCollapsed() arguments:
492
+ // https://bugs.webkit.org/show_bug.cgi?id=182754
493
+ if (typeof navigator !== "undefined" && /^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
494
+ console[method](...args);
495
+ return;
496
+ }
497
+ }
498
+ const styles = [
499
+ `background: ${methodToColorMap[method]}`,
500
+ `border-radius: 0.5em`,
501
+ `color: white`,
502
+ `font-weight: bold`,
503
+ `padding: 2px 0.5em`
504
+ ];
505
+ // When in a group, the serwist prefix is not displayed.
506
+ const logPrefix = inGroup ? [] : [
507
+ "%cserwist",
508
+ styles.join(";")
509
+ ];
510
+ console[method](...logPrefix, ...args);
511
+ if (method === "groupCollapsed") {
512
+ inGroup = true;
513
+ }
514
+ if (method === "groupEnd") {
515
+ inGroup = false;
516
+ }
517
+ };
518
+ // eslint-disable-next-line @typescript-eslint/ban-types
519
+ const api = {};
520
+ const loggerMethods = Object.keys(methodToColorMap);
521
+ for (const key of loggerMethods){
522
+ const method = key;
523
+ api[method] = (...args)=>{
524
+ print(method, args);
525
+ };
526
+ }
527
+ return api;
528
+ })();
529
+
530
+ /*
531
+ Copyright 2018 Google LLC
532
+
533
+ Use of this source code is governed by an MIT-style
534
+ license that can be found in the LICENSE file or at
535
+ https://opensource.org/licenses/MIT.
536
+ */ // Callbacks to be executed whenever there's a quota error.
537
+ // Can't change Function type right now.
538
+ // eslint-disable-next-line @typescript-eslint/ban-types
539
+ const quotaErrorCallbacks = new Set();
540
+
541
+ /**
542
+ * Runs all of the callback functions, one at a time sequentially, in the order
543
+ * in which they were registered.
544
+ *
545
+ * @private
546
+ */ async function executeQuotaErrorCallbacks() {
547
+ if (process.env.NODE_ENV !== "production") {
548
+ logger.log(`About to run ${quotaErrorCallbacks.size} ` + `callbacks to clean up caches.`);
549
+ }
550
+ for (const callback of quotaErrorCallbacks){
551
+ await callback();
552
+ if (process.env.NODE_ENV !== "production") {
553
+ logger.log(callback, "is complete.");
554
+ }
555
+ }
556
+ if (process.env.NODE_ENV !== "production") {
557
+ logger.log("Finished running callbacks.");
558
+ }
559
+ }
560
+
561
+ /*
562
+ Copyright 2018 Google LLC
563
+
564
+ Use of this source code is governed by an MIT-style
565
+ license that can be found in the LICENSE file or at
566
+ https://opensource.org/licenses/MIT.
567
+ */ const getFriendlyURL = (url)=>{
568
+ const urlObj = new URL(String(url), location.href);
569
+ // See https://github.com/GoogleChrome/workbox/issues/2323
570
+ // We want to include everything, except for the origin if it's same-origin.
571
+ return urlObj.href.replace(new RegExp(`^${location.origin}`), "");
572
+ };
573
+
574
+ /*
575
+ Copyright 2019 Google LLC
576
+ Use of this source code is governed by an MIT-style
577
+ license that can be found in the LICENSE file or at
578
+ https://opensource.org/licenses/MIT.
579
+ */ /**
580
+ * Returns a promise that resolves and the passed number of milliseconds.
581
+ * This utility is an async/await-friendly version of `setTimeout`.
582
+ *
583
+ * @param ms
584
+ * @returns
585
+ * @private
586
+ */ function timeout(ms) {
587
+ return new Promise((resolve)=>setTimeout(resolve, ms));
588
+ }
589
+
590
+ const MAX_RETRY_TIME = 2000;
591
+ /**
592
+ * Returns a promise that resolves to a window client matching the passed
593
+ * `resultingClientId`. For browsers that don't support `resultingClientId`
594
+ * or if waiting for the resulting client to apper takes too long, resolve to
595
+ * `undefined`.
596
+ *
597
+ * @param resultingClientId
598
+ * @returns
599
+ * @private
600
+ */ async function resultingClientExists(resultingClientId) {
601
+ if (!resultingClientId) {
602
+ return;
603
+ }
604
+ let existingWindows = await self.clients.matchAll({
605
+ type: "window"
606
+ });
607
+ const existingWindowIds = new Set(existingWindows.map((w)=>w.id));
608
+ let resultingWindow;
609
+ const startTime = performance.now();
610
+ // Only wait up to `MAX_RETRY_TIME` to find a matching client.
611
+ while(performance.now() - startTime < MAX_RETRY_TIME){
612
+ existingWindows = await self.clients.matchAll({
613
+ type: "window"
614
+ });
615
+ resultingWindow = existingWindows.find((w)=>{
616
+ if (resultingClientId) {
617
+ // If we have a `resultingClientId`, we can match on that.
618
+ return w.id === resultingClientId;
619
+ } else {
620
+ // Otherwise match on finding a window not in `existingWindowIds`.
621
+ return !existingWindowIds.has(w.id);
622
+ }
623
+ });
624
+ if (resultingWindow) {
625
+ break;
626
+ }
627
+ // Sleep for 100ms and retry.
628
+ await timeout(100);
629
+ }
630
+ return resultingWindow;
631
+ }
632
+
633
+ /*
634
+ Copyright 2020 Google LLC
635
+ Use of this source code is governed by an MIT-style
636
+ license that can be found in the LICENSE file or at
637
+ https://opensource.org/licenses/MIT.
638
+ */ /**
639
+ * A utility method that makes it easier to use `event.waitUntil` with
640
+ * async functions and return the result.
641
+ *
642
+ * @param event
643
+ * @param asyncFn
644
+ * @returns
645
+ * @private
646
+ */ function waitUntil(event, asyncFn) {
647
+ const returnPromise = asyncFn();
648
+ event.waitUntil(returnPromise);
649
+ return returnPromise;
650
+ }
651
+
652
+ export { Deferred, SerwistError, finalAssertExports as assert, cacheMatchIgnoreParams, canConstructReadableStream, canConstructResponseFromBodyStream, dontWaitFor, executeQuotaErrorCallbacks, getFriendlyURL, logger, cacheNames as privateCacheNames, resultingClientExists, timeout, waitUntil };