@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,577 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ Copyright 2018 Google LLC
5
+
6
+ Use of this source code is governed by an MIT-style
7
+ license that can be found in the LICENSE file or at
8
+ https://opensource.org/licenses/MIT.
9
+ */ const _cacheNameDetails = {
10
+ googleAnalytics: "googleAnalytics",
11
+ precache: "precache-v2",
12
+ prefix: "serwist",
13
+ runtime: "runtime",
14
+ suffix: typeof registration !== "undefined" ? registration.scope : ""
15
+ };
16
+ const _createCacheName = (cacheName)=>{
17
+ return [
18
+ _cacheNameDetails.prefix,
19
+ cacheName,
20
+ _cacheNameDetails.suffix
21
+ ].filter((value)=>value && value.length > 0).join("-");
22
+ };
23
+ const eachCacheNameDetail = (fn)=>{
24
+ for (const key of Object.keys(_cacheNameDetails)){
25
+ fn(key);
26
+ }
27
+ };
28
+ const cacheNames$1 = {
29
+ updateDetails: (details)=>{
30
+ eachCacheNameDetail((key)=>{
31
+ const detail = details[key];
32
+ if (typeof detail === "string") {
33
+ _cacheNameDetails[key] = detail;
34
+ }
35
+ });
36
+ },
37
+ getGoogleAnalyticsName: (userCacheName)=>{
38
+ return userCacheName || _createCacheName(_cacheNameDetails.googleAnalytics);
39
+ },
40
+ getPrecacheName: (userCacheName)=>{
41
+ return userCacheName || _createCacheName(_cacheNameDetails.precache);
42
+ },
43
+ getPrefix: ()=>{
44
+ return _cacheNameDetails.prefix;
45
+ },
46
+ getRuntimeName: (userCacheName)=>{
47
+ return userCacheName || _createCacheName(_cacheNameDetails.runtime);
48
+ },
49
+ getSuffix: ()=>{
50
+ return _cacheNameDetails.suffix;
51
+ }
52
+ };
53
+
54
+ /**
55
+ * Get the current cache names and prefix/suffix used by Workbox.
56
+ *
57
+ * `cacheNames.precache` is used for precached assets,
58
+ * `cacheNames.googleAnalytics` is used by `@serwist/google-analytics` to
59
+ * store `analytics.js`, and `cacheNames.runtime` is used for everything else.
60
+ *
61
+ * `cacheNames.prefix` can be used to retrieve just the current prefix value.
62
+ * `cacheNames.suffix` can be used to retrieve just the current suffix value.
63
+ *
64
+ * @returns An object with `precache`, `runtime`, `prefix`, and `googleAnalytics` properties.
65
+ */ const cacheNames = {
66
+ get googleAnalytics () {
67
+ return cacheNames$1.getGoogleAnalyticsName();
68
+ },
69
+ get precache () {
70
+ return cacheNames$1.getPrecacheName();
71
+ },
72
+ get prefix () {
73
+ return cacheNames$1.getPrefix();
74
+ },
75
+ get runtime () {
76
+ return cacheNames$1.getRuntimeName();
77
+ },
78
+ get suffix () {
79
+ return cacheNames$1.getSuffix();
80
+ }
81
+ };
82
+
83
+ /*
84
+ Copyright 2019 Google LLC
85
+
86
+ Use of this source code is governed by an MIT-style
87
+ license that can be found in the LICENSE file or at
88
+ https://opensource.org/licenses/MIT.
89
+ */ // Give TypeScript the correct global.
90
+ /**
91
+ * Claim any currently available clients once the service worker
92
+ * becomes active. This is normally used in conjunction with `skipWaiting()`.
93
+ */ function clientsClaim() {
94
+ self.addEventListener("activate", ()=>self.clients.claim());
95
+ }
96
+
97
+ /*
98
+ Copyright 2019 Google LLC
99
+
100
+ Use of this source code is governed by an MIT-style
101
+ license that can be found in the LICENSE file or at
102
+ https://opensource.org/licenses/MIT.
103
+ */ let supportStatus;
104
+ /**
105
+ * A utility function that determines whether the current browser supports
106
+ * constructing a new `Response` from a `response.body` stream.
107
+ *
108
+ * @returns `true`, if the current browser can successfully construct
109
+ * a `Response` from a `response.body` stream, `false` otherwise.
110
+ * @private
111
+ */ function canConstructResponseFromBodyStream() {
112
+ if (supportStatus === undefined) {
113
+ const testResponse = new Response("");
114
+ if ("body" in testResponse) {
115
+ try {
116
+ new Response(testResponse.body);
117
+ supportStatus = true;
118
+ } catch (error) {
119
+ supportStatus = false;
120
+ }
121
+ }
122
+ supportStatus = false;
123
+ }
124
+ return supportStatus;
125
+ }
126
+
127
+ /*
128
+ Copyright 2018 Google LLC
129
+
130
+ Use of this source code is governed by an MIT-style
131
+ license that can be found in the LICENSE file or at
132
+ https://opensource.org/licenses/MIT.
133
+ */ const messages = {
134
+ "invalid-value": ({ paramName, validValueDescription, value })=>{
135
+ if (!paramName || !validValueDescription) {
136
+ throw new Error(`Unexpected input to 'invalid-value' error.`);
137
+ }
138
+ return `The '${paramName}' parameter was given a value with an ` + `unexpected value. ${validValueDescription} Received a value of ` + `${JSON.stringify(value)}.`;
139
+ },
140
+ "not-an-array": ({ moduleName, className, funcName, paramName })=>{
141
+ if (!moduleName || !className || !funcName || !paramName) {
142
+ throw new Error(`Unexpected input to 'not-an-array' error.`);
143
+ }
144
+ return `The parameter '${paramName}' passed into ` + `'${moduleName}.${className}.${funcName}()' must be an array.`;
145
+ },
146
+ "incorrect-type": ({ expectedType, paramName, moduleName, className, funcName })=>{
147
+ if (!expectedType || !paramName || !moduleName || !funcName) {
148
+ throw new Error(`Unexpected input to 'incorrect-type' error.`);
149
+ }
150
+ const classNameStr = className ? `${className}.` : "";
151
+ return `The parameter '${paramName}' passed into ` + `'${moduleName}.${classNameStr}` + `${funcName}()' must be of type ${expectedType}.`;
152
+ },
153
+ "incorrect-class": ({ expectedClassName, paramName, moduleName, className, funcName, isReturnValueProblem })=>{
154
+ if (!expectedClassName || !moduleName || !funcName) {
155
+ throw new Error(`Unexpected input to 'incorrect-class' error.`);
156
+ }
157
+ const classNameStr = className ? `${className}.` : "";
158
+ if (isReturnValueProblem) {
159
+ return `The return value from ` + `'${moduleName}.${classNameStr}${funcName}()' ` + `must be an instance of class ${expectedClassName}.`;
160
+ }
161
+ return `The parameter '${paramName}' passed into ` + `'${moduleName}.${classNameStr}${funcName}()' ` + `must be an instance of class ${expectedClassName}.`;
162
+ },
163
+ "missing-a-method": ({ expectedMethod, paramName, moduleName, className, funcName })=>{
164
+ if (!expectedMethod || !paramName || !moduleName || !className || !funcName) {
165
+ throw new Error(`Unexpected input to 'missing-a-method' error.`);
166
+ }
167
+ return `${moduleName}.${className}.${funcName}() expected the ` + `'${paramName}' parameter to expose a '${expectedMethod}' method.`;
168
+ },
169
+ "add-to-cache-list-unexpected-type": ({ entry })=>{
170
+ 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.`;
171
+ },
172
+ "add-to-cache-list-conflicting-entries": ({ firstEntry, secondEntry })=>{
173
+ if (!firstEntry || !secondEntry) {
174
+ throw new Error(`Unexpected input to ` + `'add-to-cache-list-duplicate-entries' error.`);
175
+ }
176
+ 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.`;
177
+ },
178
+ "plugin-error-request-will-fetch": ({ thrownErrorMessage })=>{
179
+ if (!thrownErrorMessage) {
180
+ throw new Error(`Unexpected input to ` + `'plugin-error-request-will-fetch', error.`);
181
+ }
182
+ return `An error was thrown by a plugins 'requestWillFetch()' method. ` + `The thrown error message was: '${thrownErrorMessage}'.`;
183
+ },
184
+ "invalid-cache-name": ({ cacheNameId, value })=>{
185
+ if (!cacheNameId) {
186
+ throw new Error(`Expected a 'cacheNameId' for error 'invalid-cache-name'`);
187
+ }
188
+ return `You must provide a name containing at least one character for ` + `setCacheDetails({${cacheNameId}: '...'}). Received a value of ` + `'${JSON.stringify(value)}'`;
189
+ },
190
+ "unregister-route-but-not-found-with-method": ({ method })=>{
191
+ if (!method) {
192
+ throw new Error(`Unexpected input to ` + `'unregister-route-but-not-found-with-method' error.`);
193
+ }
194
+ return `The route you're trying to unregister was not previously ` + `registered for the method type '${method}'.`;
195
+ },
196
+ "unregister-route-route-not-registered": ()=>{
197
+ return `The route you're trying to unregister was not previously ` + `registered.`;
198
+ },
199
+ "queue-replay-failed": ({ name })=>{
200
+ return `Replaying the background sync queue '${name}' failed.`;
201
+ },
202
+ "duplicate-queue-name": ({ name })=>{
203
+ return `The Queue name '${name}' is already being used. ` + `All instances of backgroundSync.Queue must be given unique names.`;
204
+ },
205
+ "expired-test-without-max-age": ({ methodName, paramName })=>{
206
+ return `The '${methodName}()' method can only be used when the ` + `'${paramName}' is used in the constructor.`;
207
+ },
208
+ "unsupported-route-type": ({ moduleName, className, funcName, paramName })=>{
209
+ return `The supplied '${paramName}' parameter was an unsupported type. ` + `Please check the docs for ${moduleName}.${className}.${funcName} for ` + `valid input types.`;
210
+ },
211
+ "not-array-of-class": ({ value, expectedClass, moduleName, className, funcName, paramName })=>{
212
+ 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.`;
213
+ },
214
+ "max-entries-or-age-required": ({ moduleName, className, funcName })=>{
215
+ return `You must define either config.maxEntries or config.maxAgeSeconds` + `in ${moduleName}.${className}.${funcName}`;
216
+ },
217
+ "statuses-or-headers-required": ({ moduleName, className, funcName })=>{
218
+ return `You must define either config.statuses or config.headers` + `in ${moduleName}.${className}.${funcName}`;
219
+ },
220
+ "invalid-string": ({ moduleName, funcName, paramName })=>{
221
+ if (!paramName || !moduleName || !funcName) {
222
+ throw new Error(`Unexpected input to 'invalid-string' error.`);
223
+ }
224
+ 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.`;
225
+ },
226
+ "channel-name-required": ()=>{
227
+ return `You must provide a channelName to construct a ` + `BroadcastCacheUpdate instance.`;
228
+ },
229
+ "invalid-responses-are-same-args": ()=>{
230
+ return `The arguments passed into responsesAreSame() appear to be ` + `invalid. Please ensure valid Responses are used.`;
231
+ },
232
+ "expire-custom-caches-only": ()=>{
233
+ return `You must provide a 'cacheName' property when using the ` + `expiration plugin with a runtime caching strategy.`;
234
+ },
235
+ "unit-must-be-bytes": ({ normalizedRangeHeader })=>{
236
+ if (!normalizedRangeHeader) {
237
+ throw new Error(`Unexpected input to 'unit-must-be-bytes' error.`);
238
+ }
239
+ return `The 'unit' portion of the Range header must be set to 'bytes'. ` + `The Range header provided was "${normalizedRangeHeader}"`;
240
+ },
241
+ "single-range-only": ({ normalizedRangeHeader })=>{
242
+ if (!normalizedRangeHeader) {
243
+ throw new Error(`Unexpected input to 'single-range-only' error.`);
244
+ }
245
+ return `Multiple ranges are not supported. Please use a single start ` + `value, and optional end value. The Range header provided was ` + `"${normalizedRangeHeader}"`;
246
+ },
247
+ "invalid-range-values": ({ normalizedRangeHeader })=>{
248
+ if (!normalizedRangeHeader) {
249
+ throw new Error(`Unexpected input to 'invalid-range-values' error.`);
250
+ }
251
+ 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}"`;
252
+ },
253
+ "no-range-header": ()=>{
254
+ return `No Range header was found in the Request provided.`;
255
+ },
256
+ "range-not-satisfiable": ({ size, start, end })=>{
257
+ return `The start (${start}) and end (${end}) values in the Range are ` + `not satisfiable by the cached response, which is ${size} bytes.`;
258
+ },
259
+ "attempt-to-cache-non-get-request": ({ url, method })=>{
260
+ return `Unable to cache '${url}' because it is a '${method}' request and ` + `only 'GET' requests can be cached.`;
261
+ },
262
+ "cache-put-with-no-response": ({ url })=>{
263
+ return `There was an attempt to cache '${url}' but the response was not ` + `defined.`;
264
+ },
265
+ "no-response": ({ url, error })=>{
266
+ let message = `The strategy could not generate a response for '${url}'.`;
267
+ if (error) {
268
+ message += ` The underlying error is ${error}.`;
269
+ }
270
+ return message;
271
+ },
272
+ "bad-precaching-response": ({ url, status })=>{
273
+ return `The precaching request for '${url}' failed` + (status ? ` with an HTTP status of ${status}.` : `.`);
274
+ },
275
+ "non-precached-url": ({ url })=>{
276
+ return `createHandlerBoundToURL('${url}') was called, but that URL is ` + `not precached. Please pass in a URL that is precached instead.`;
277
+ },
278
+ "add-to-cache-list-conflicting-integrities": ({ url })=>{
279
+ return `Two of the entries passed to ` + `'@serwist/precaching.PrecacheController.addToCacheList()' had the URL ` + `${url} with different integrity values. Please remove one of them.`;
280
+ },
281
+ "missing-precache-entry": ({ cacheName, url })=>{
282
+ return `Unable to find a precached response in ${cacheName} for ${url}.`;
283
+ },
284
+ "cross-origin-copy-response": ({ origin })=>{
285
+ return `@serwist/core.copyResponse() can only be used with same-origin ` + `responses. It was passed a response with origin ${origin}.`;
286
+ },
287
+ "opaque-streams-source": ({ type })=>{
288
+ const message = `One of the @serwist/streams sources resulted in an ` + `'${type}' response.`;
289
+ if (type === "opaqueredirect") {
290
+ return `${message} Please do not use a navigation request that results ` + `in a redirect as a source.`;
291
+ }
292
+ return `${message} Please ensure your sources are CORS-enabled.`;
293
+ }
294
+ };
295
+
296
+ const fallback = (code, ...args)=>{
297
+ let msg = code;
298
+ if (args.length > 0) {
299
+ msg += ` :: ${JSON.stringify(args)}`;
300
+ }
301
+ return msg;
302
+ };
303
+ const generatorFunction = (code, details = {})=>{
304
+ const message = messages[code];
305
+ if (!message) {
306
+ throw new Error(`Unable to find message for code '${code}'.`);
307
+ }
308
+ return message(details);
309
+ };
310
+ const messageGenerator = process.env.NODE_ENV === "production" ? fallback : generatorFunction;
311
+
312
+ /**
313
+ * Serwist errors should be thrown with this class.
314
+ * This allows use to ensure the type easily in tests,
315
+ * helps developers identify errors from Serwist
316
+ * easily and allows use to optimise error
317
+ * messages correctly.
318
+ *
319
+ * @private
320
+ */ class SerwistError extends Error {
321
+ details;
322
+ /**
323
+ *
324
+ * @param errorCode The error code that
325
+ * identifies this particular error.
326
+ * @param details Any relevant arguments
327
+ * that will help developers identify issues should
328
+ * be added as a key on the context object.
329
+ */ constructor(errorCode, details){
330
+ const message = messageGenerator(errorCode, details);
331
+ super(message);
332
+ this.name = errorCode;
333
+ this.details = details;
334
+ }
335
+ }
336
+
337
+ /**
338
+ * Allows developers to copy a response and modify its `headers`, `status`,
339
+ * or `statusText` values (the values settable via a
340
+ * [`ResponseInit`](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#Syntax)
341
+ * object in the constructor).
342
+ * To modify these values, pass a function as the second argument. That
343
+ * function will be invoked with a single object with the response properties
344
+ * `{headers, status, statusText}`. The return value of this function will
345
+ * be used as the `ResponseInit` for the new `Response`. To change the values
346
+ * either modify the passed parameter(s) and return it, or return a totally
347
+ * new object.
348
+ *
349
+ * This method is intentionally limited to same-origin responses, regardless of
350
+ * whether CORS was used or not.
351
+ *
352
+ * @param response
353
+ * @param modifier
354
+ */ async function copyResponse(response, modifier) {
355
+ let origin = null;
356
+ // If response.url isn't set, assume it's cross-origin and keep origin null.
357
+ if (response.url) {
358
+ const responseURL = new URL(response.url);
359
+ origin = responseURL.origin;
360
+ }
361
+ if (origin !== self.location.origin) {
362
+ throw new SerwistError("cross-origin-copy-response", {
363
+ origin
364
+ });
365
+ }
366
+ const clonedResponse = response.clone();
367
+ // Create a fresh `ResponseInit` object by cloning the headers.
368
+ const responseInit = {
369
+ headers: new Headers(clonedResponse.headers),
370
+ status: clonedResponse.status,
371
+ statusText: clonedResponse.statusText
372
+ };
373
+ // Apply any user modifications.
374
+ const modifiedResponseInit = modifier ? modifier(responseInit) : responseInit;
375
+ // Create the new response from the body stream and `ResponseInit`
376
+ // modifications. Note: not all browsers support the Response.body stream,
377
+ // so fall back to reading the entire body into memory as a blob.
378
+ const body = canConstructResponseFromBodyStream() ? clonedResponse.body : await clonedResponse.blob();
379
+ return new Response(body, modifiedResponseInit);
380
+ }
381
+
382
+ /*
383
+ * This method throws if the supplied value is not an array.
384
+ * The destructed values are required to produce a meaningful error for users.
385
+ * The destructed and restructured object is so it's clear what is
386
+ * needed.
387
+ */ const isArray = (value, details)=>{
388
+ if (!Array.isArray(value)) {
389
+ throw new SerwistError("not-an-array", details);
390
+ }
391
+ };
392
+ const hasMethod = (object, expectedMethod, details)=>{
393
+ const type = typeof object[expectedMethod];
394
+ if (type !== "function") {
395
+ details["expectedMethod"] = expectedMethod;
396
+ throw new SerwistError("missing-a-method", details);
397
+ }
398
+ };
399
+ const isType = (object, expectedType, details)=>{
400
+ if (typeof object !== expectedType) {
401
+ details["expectedType"] = expectedType;
402
+ throw new SerwistError("incorrect-type", details);
403
+ }
404
+ };
405
+ const isInstance = (object, // Need the general type to do the check later.
406
+ // eslint-disable-next-line @typescript-eslint/ban-types
407
+ expectedClass, details)=>{
408
+ if (!(object instanceof expectedClass)) {
409
+ details["expectedClassName"] = expectedClass.name;
410
+ throw new SerwistError("incorrect-class", details);
411
+ }
412
+ };
413
+ const isOneOf = (value, validValues, details)=>{
414
+ if (!validValues.includes(value)) {
415
+ details["validValueDescription"] = `Valid values are ${JSON.stringify(validValues)}.`;
416
+ throw new SerwistError("invalid-value", details);
417
+ }
418
+ };
419
+ const isArrayOfClass = (value, // Need general type to do check later.
420
+ expectedClass, details)=>{
421
+ const error = new SerwistError("not-array-of-class", details);
422
+ if (!Array.isArray(value)) {
423
+ throw error;
424
+ }
425
+ for (const item of value){
426
+ if (!(item instanceof expectedClass)) {
427
+ throw error;
428
+ }
429
+ }
430
+ };
431
+ const finalAssertExports = process.env.NODE_ENV === "production" ? null : {
432
+ hasMethod,
433
+ isArray,
434
+ isInstance,
435
+ isOneOf,
436
+ isType,
437
+ isArrayOfClass
438
+ };
439
+
440
+ /*
441
+ Copyright 2019 Google LLC
442
+ Use of this source code is governed by an MIT-style
443
+ license that can be found in the LICENSE file or at
444
+ https://opensource.org/licenses/MIT.
445
+ */ // logger is used inside of both service workers and the window global scope.
446
+ const logger = process.env.NODE_ENV === "production" ? null : (()=>{
447
+ // Don't overwrite this value if it's already set.
448
+ // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923
449
+ if (!("__WB_DISABLE_DEV_LOGS" in globalThis)) {
450
+ self.__WB_DISABLE_DEV_LOGS = false;
451
+ }
452
+ let inGroup = false;
453
+ const methodToColorMap = {
454
+ debug: `#7f8c8d`,
455
+ log: `#2ecc71`,
456
+ warn: `#f39c12`,
457
+ error: `#c0392b`,
458
+ groupCollapsed: `#3498db`,
459
+ groupEnd: null
460
+ };
461
+ const print = function(method, args) {
462
+ if (self.__WB_DISABLE_DEV_LOGS) {
463
+ return;
464
+ }
465
+ if (method === "groupCollapsed") {
466
+ // Safari doesn't print all console.groupCollapsed() arguments:
467
+ // https://bugs.webkit.org/show_bug.cgi?id=182754
468
+ if (typeof navigator !== "undefined" && /^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
469
+ console[method](...args);
470
+ return;
471
+ }
472
+ }
473
+ const styles = [
474
+ `background: ${methodToColorMap[method]}`,
475
+ `border-radius: 0.5em`,
476
+ `color: white`,
477
+ `font-weight: bold`,
478
+ `padding: 2px 0.5em`
479
+ ];
480
+ // When in a group, the serwist prefix is not displayed.
481
+ const logPrefix = inGroup ? [] : [
482
+ "%cserwist",
483
+ styles.join(";")
484
+ ];
485
+ console[method](...logPrefix, ...args);
486
+ if (method === "groupCollapsed") {
487
+ inGroup = true;
488
+ }
489
+ if (method === "groupEnd") {
490
+ inGroup = false;
491
+ }
492
+ };
493
+ // eslint-disable-next-line @typescript-eslint/ban-types
494
+ const api = {};
495
+ const loggerMethods = Object.keys(methodToColorMap);
496
+ for (const key of loggerMethods){
497
+ const method = key;
498
+ api[method] = (...args)=>{
499
+ print(method, args);
500
+ };
501
+ }
502
+ return api;
503
+ })();
504
+
505
+ /*
506
+ Copyright 2018 Google LLC
507
+
508
+ Use of this source code is governed by an MIT-style
509
+ license that can be found in the LICENSE file or at
510
+ https://opensource.org/licenses/MIT.
511
+ */ // Callbacks to be executed whenever there's a quota error.
512
+ // Can't change Function type right now.
513
+ // eslint-disable-next-line @typescript-eslint/ban-types
514
+ const quotaErrorCallbacks = new Set();
515
+
516
+ /**
517
+ * Adds a function to the set of quotaErrorCallbacks that will be executed if
518
+ * there's a quota error.
519
+ *
520
+ * @param callback
521
+ */ // Can't change Function type
522
+ // eslint-disable-next-line @typescript-eslint/ban-types
523
+ function registerQuotaErrorCallback(callback) {
524
+ if (process.env.NODE_ENV !== "production") {
525
+ finalAssertExports.isType(callback, "function", {
526
+ moduleName: "@serwist/core",
527
+ funcName: "register",
528
+ paramName: "callback"
529
+ });
530
+ }
531
+ quotaErrorCallbacks.add(callback);
532
+ if (process.env.NODE_ENV !== "production") {
533
+ logger.log("Registered a callback to respond to quota errors.", callback);
534
+ }
535
+ }
536
+
537
+ /**
538
+ * Modifies the default cache names used by the Serwist packages.
539
+ * Cache names are generated as `<prefix>-<Cache Name>-<suffix>`.
540
+ *
541
+ * @param details
542
+ */ function setCacheNameDetails(details) {
543
+ if (process.env.NODE_ENV !== "production") {
544
+ Object.keys(details).forEach((key)=>{
545
+ finalAssertExports.isType(details[key], "string", {
546
+ moduleName: "@serwist/core",
547
+ funcName: "setCacheNameDetails",
548
+ paramName: `details.${key}`
549
+ });
550
+ });
551
+ if (details["precache"]?.length === 0) {
552
+ throw new SerwistError("invalid-cache-name", {
553
+ cacheNameId: "precache",
554
+ value: details["precache"]
555
+ });
556
+ }
557
+ if (details["runtime"]?.length === 0) {
558
+ throw new SerwistError("invalid-cache-name", {
559
+ cacheNameId: "runtime",
560
+ value: details["runtime"]
561
+ });
562
+ }
563
+ if (details["googleAnalytics"]?.length === 0) {
564
+ throw new SerwistError("invalid-cache-name", {
565
+ cacheNameId: "googleAnalytics",
566
+ value: details["googleAnalytics"]
567
+ });
568
+ }
569
+ }
570
+ cacheNames$1.updateDetails(details);
571
+ }
572
+
573
+ exports.cacheNames = cacheNames;
574
+ exports.clientsClaim = clientsClaim;
575
+ exports.copyResponse = copyResponse;
576
+ exports.registerQuotaErrorCallback = registerQuotaErrorCallback;
577
+ exports.setCacheNameDetails = setCacheNameDetails;
@@ -0,0 +1,2 @@
1
+ export declare const messageGenerator: ((code: string, ...args: any[]) => string) | ((code: string, details?: {}) => string);
2
+ //# sourceMappingURL=messageGenerator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"messageGenerator.d.ts","sourceRoot":"","sources":["../../../src/models/messages/messageGenerator.ts"],"names":[],"mappings":"AA2BA,eAAO,MAAM,gBAAgB,UAjBL,MAAM,WAAW,GAAG,EAAE,uBAQb,MAAM,0BAS6D,CAAC"}
@@ -0,0 +1,9 @@
1
+ interface LoggableObject {
2
+ [key: string]: string | number;
3
+ }
4
+ interface MessageMap {
5
+ [messageID: string]: (param: LoggableObject) => string;
6
+ }
7
+ export declare const messages: MessageMap;
8
+ export {};
9
+ //# sourceMappingURL=messages.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../../src/models/messages/messages.ts"],"names":[],"mappings":"AAQA,UAAU,cAAc;IACtB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;CAChC;AACD,UAAU,UAAU;IAClB,CAAC,SAAS,EAAE,MAAM,GAAG,CAAC,KAAK,EAAE,cAAc,KAAK,MAAM,CAAC;CACxD;AAED,eAAO,MAAM,QAAQ,EAAE,UA2PtB,CAAC"}
@@ -0,0 +1,10 @@
1
+ export declare const enum pluginEvents {
2
+ CACHE_DID_UPDATE = "cacheDidUpdate",
3
+ CACHE_KEY_WILL_BE_USED = "cacheKeyWillBeUsed",
4
+ CACHE_WILL_UPDATE = "cacheWillUpdate",
5
+ CACHED_RESPONSE_WILL_BE_USED = "cachedResponseWillBeUsed",
6
+ FETCH_DID_FAIL = "fetchDidFail",
7
+ FETCH_DID_SUCCEED = "fetchDidSucceed",
8
+ REQUEST_WILL_FETCH = "requestWillFetch"
9
+ }
10
+ //# sourceMappingURL=pluginEvents.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pluginEvents.d.ts","sourceRoot":"","sources":["../../src/models/pluginEvents.ts"],"names":[],"mappings":"AAQA,0BAAkB,YAAY;IAC5B,gBAAgB,mBAAmB;IACnC,sBAAsB,uBAAuB;IAC7C,iBAAiB,oBAAoB;IACrC,4BAA4B,6BAA6B;IACzD,cAAc,iBAAiB;IAC/B,iBAAiB,oBAAoB;IACrC,kBAAkB,qBAAqB;CACxC"}
@@ -0,0 +1,3 @@
1
+ declare const quotaErrorCallbacks: Set<Function>;
2
+ export { quotaErrorCallbacks };
3
+ //# sourceMappingURL=quotaErrorCallbacks.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"quotaErrorCallbacks.d.ts","sourceRoot":"","sources":["../../src/models/quotaErrorCallbacks.ts"],"names":[],"mappings":"AAWA,QAAA,MAAM,mBAAmB,EAAE,GAAG,CAAC,QAAQ,CAAa,CAAC;AAErD,OAAO,EAAE,mBAAmB,EAAE,CAAC"}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Adds a function to the set of quotaErrorCallbacks that will be executed if
3
+ * there's a quota error.
4
+ *
5
+ * @param callback
6
+ */
7
+ declare function registerQuotaErrorCallback(callback: Function): void;
8
+ export { registerQuotaErrorCallback };
9
+ //# sourceMappingURL=registerQuotaErrorCallback.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registerQuotaErrorCallback.d.ts","sourceRoot":"","sources":["../src/registerQuotaErrorCallback.ts"],"names":[],"mappings":"AAYA;;;;;GAKG;AAGH,iBAAS,0BAA0B,CAAC,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAc5D;AAED,OAAO,EAAE,0BAA0B,EAAE,CAAC"}
@@ -0,0 +1,10 @@
1
+ import type { PartialCacheNameDetails } from "./_private/cacheNames.js";
2
+ /**
3
+ * Modifies the default cache names used by the Serwist packages.
4
+ * Cache names are generated as `<prefix>-<Cache Name>-<suffix>`.
5
+ *
6
+ * @param details
7
+ */
8
+ declare function setCacheNameDetails(details: PartialCacheNameDetails): void;
9
+ export { setCacheNameDetails };
10
+ //# sourceMappingURL=setCacheNameDetails.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setCacheNameDetails.d.ts","sourceRoot":"","sources":["../src/setCacheNameDetails.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AAIxE;;;;;GAKG;AACH,iBAAS,mBAAmB,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI,CAiCnE;AAED,OAAO,EAAE,mBAAmB,EAAE,CAAC"}