@serwist/core 8.1.0 → 8.2.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 (36) hide show
  1. package/dist/_private/Deferred.d.cts +18 -0
  2. package/dist/_private/SerwistError.d.cts +23 -0
  3. package/dist/_private/assert.d.cts +10 -0
  4. package/dist/_private/cacheMatchIgnoreParams.d.cts +14 -0
  5. package/dist/_private/cacheNames.d.cts +39 -0
  6. package/dist/_private/canConstructReadableStream.d.cts +11 -0
  7. package/dist/_private/canConstructResponseFromBodyStream.d.cts +10 -0
  8. package/dist/_private/dontWaitFor.d.cts +6 -0
  9. package/dist/_private/executeQuotaErrorCallbacks.d.cts +8 -0
  10. package/dist/_private/getFriendlyURL.d.cts +2 -0
  11. package/dist/_private/logger.d.cts +10 -0
  12. package/dist/_private/resultingClientExists.d.cts +11 -0
  13. package/dist/_private/timeout.d.cts +9 -0
  14. package/dist/_private/waitUntil.d.cts +11 -0
  15. package/dist/cacheNames.d.cts +20 -0
  16. package/dist/clientsClaim.d.cts +6 -0
  17. package/dist/copyResponse.d.cts +20 -0
  18. package/dist/index.cjs +154 -0
  19. package/dist/index.d.cts +0 -0
  20. package/dist/index.internal.cjs +244 -0
  21. package/dist/index.internal.js +7 -429
  22. package/dist/index.js +1 -424
  23. package/dist/models/messages/messageGenerator.d.cts +1 -0
  24. package/dist/models/messages/messages.d.cts +8 -0
  25. package/dist/models/pluginEvents.d.cts +9 -0
  26. package/dist/models/quotaErrorCallbacks.d.cts +2 -0
  27. package/dist/{index.internal.old.cjs → quotaErrorCallbacks-efexit-Y.js} +81 -322
  28. package/dist/{index.old.cjs → quotaErrorCallbacks-t3P-jWKl.js} +6 -150
  29. package/dist/registerQuotaErrorCallback.d.cts +8 -0
  30. package/dist/setCacheNameDetails.d.cts +9 -0
  31. package/dist/types.d.cts +272 -0
  32. package/dist/utils/pluginUtils.d.cts +4 -0
  33. package/dist/utils/welcome.d.cts +1 -0
  34. package/package.json +7 -7
  35. package/dist/index.old.d.cts +0 -11
  36. /package/dist/{index.internal.old.d.cts → index.internal.d.cts} +0 -0
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The Deferred class composes Promises in a way that allows for them to be
3
+ * resolved or rejected from outside the constructor. In most cases promises
4
+ * should be used directly, but Deferreds can be necessary when the logic to
5
+ * resolve a promise must be separate.
6
+ *
7
+ * @private
8
+ */
9
+ declare class Deferred<T> {
10
+ promise: Promise<T>;
11
+ resolve: (value: T) => void;
12
+ reject: (reason?: any) => void;
13
+ /**
14
+ * Creates a promise and exposes its resolve and reject functions as methods.
15
+ */
16
+ constructor();
17
+ }
18
+ export { Deferred };
@@ -0,0 +1,23 @@
1
+ import type { MapLikeObject } from "../types.js";
2
+ /**
3
+ * Serwist errors should be thrown with this class.
4
+ * This allows use to ensure the type easily in tests,
5
+ * helps developers identify errors from Serwist
6
+ * easily and allows use to optimise error
7
+ * messages correctly.
8
+ *
9
+ * @private
10
+ */
11
+ declare class SerwistError extends Error {
12
+ details?: MapLikeObject;
13
+ /**
14
+ *
15
+ * @param errorCode The error code that
16
+ * identifies this particular error.
17
+ * @param details Any relevant arguments
18
+ * that will help developers identify issues should
19
+ * be added as a key on the context object.
20
+ */
21
+ constructor(errorCode: string, details?: MapLikeObject);
22
+ }
23
+ export { SerwistError };
@@ -0,0 +1,10 @@
1
+ import type { MapLikeObject } from "../types.js";
2
+ declare const finalAssertExports: {
3
+ hasMethod: (object: MapLikeObject, expectedMethod: string, details: MapLikeObject) => void;
4
+ isArray: (value: any[], details: MapLikeObject) => void;
5
+ isInstance: (object: unknown, expectedClass: Function, details: MapLikeObject) => void;
6
+ isOneOf: (value: any, validValues: any[], details: MapLikeObject) => void;
7
+ isType: (object: unknown, expectedType: string, details: MapLikeObject) => void;
8
+ isArrayOfClass: (value: any, expectedClass: Function, details: MapLikeObject) => void;
9
+ } | null;
10
+ export { finalAssertExports as assert };
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Matches an item in the cache, ignoring specific URL params. This is similar
3
+ * to the `ignoreSearch` option, but it allows you to ignore just specific
4
+ * params (while continuing to match on the others).
5
+ *
6
+ * @private
7
+ * @param cache
8
+ * @param request
9
+ * @param matchOptions
10
+ * @param ignoreParams
11
+ * @returns
12
+ */
13
+ declare function cacheMatchIgnoreParams(cache: Cache, request: Request, ignoreParams: string[], matchOptions?: CacheQueryOptions): Promise<Response | undefined>;
14
+ export { cacheMatchIgnoreParams };
@@ -0,0 +1,39 @@
1
+ export interface CacheNameDetails {
2
+ googleAnalytics: string;
3
+ precache: string;
4
+ prefix: string;
5
+ runtime: string;
6
+ suffix: string;
7
+ }
8
+ export interface PartialCacheNameDetails {
9
+ /**
10
+ * The string to add to the beginning of the precache and runtime cache names.
11
+ */
12
+ prefix?: string;
13
+ /**
14
+ * The string to add to the end of the precache and runtime cache names.
15
+ */
16
+ suffix?: string;
17
+ /**
18
+ * The cache name to use for precache caching.
19
+ */
20
+ precache?: string;
21
+ /**
22
+ * The cache name to use for runtime caching.
23
+ */
24
+ runtime?: string;
25
+ /**
26
+ * The cache name to use for `@serwist/google-analytics` caching.
27
+ */
28
+ googleAnalytics?: string;
29
+ [propName: string]: string | undefined;
30
+ }
31
+ export type CacheNameDetailsProp = "googleAnalytics" | "precache" | "prefix" | "runtime" | "suffix";
32
+ export declare const cacheNames: {
33
+ updateDetails: (details: PartialCacheNameDetails) => void;
34
+ getGoogleAnalyticsName: (userCacheName?: string) => string;
35
+ getPrecacheName: (userCacheName?: string) => string;
36
+ getPrefix: () => string;
37
+ getRuntimeName: (userCacheName?: string) => string;
38
+ getSuffix: () => string;
39
+ };
@@ -0,0 +1,11 @@
1
+ /**
2
+ * A utility function that determines whether the current browser supports
3
+ * constructing a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream)
4
+ * object.
5
+ *
6
+ * @returns `true`, if the current browser can successfully construct a `ReadableStream`, `false` otherwise.
7
+ *
8
+ * @private
9
+ */
10
+ declare function canConstructReadableStream(): boolean;
11
+ export { canConstructReadableStream };
@@ -0,0 +1,10 @@
1
+ /**
2
+ * A utility function that determines whether the current browser supports
3
+ * constructing a new `Response` from a `response.body` stream.
4
+ *
5
+ * @returns `true`, if the current browser can successfully construct
6
+ * a `Response` from a `response.body` stream, `false` otherwise.
7
+ * @private
8
+ */
9
+ declare function canConstructResponseFromBodyStream(): boolean;
10
+ export { canConstructResponseFromBodyStream };
@@ -0,0 +1,6 @@
1
+ /**
2
+ * A helper function that prevents a promise from being flagged as unused.
3
+ *
4
+ * @private
5
+ **/
6
+ export declare function dontWaitFor(promise: Promise<any>): void;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Runs all of the callback functions, one at a time sequentially, in the order
3
+ * in which they were registered.
4
+ *
5
+ * @private
6
+ */
7
+ declare function executeQuotaErrorCallbacks(): Promise<void>;
8
+ export { executeQuotaErrorCallbacks };
@@ -0,0 +1,2 @@
1
+ declare const getFriendlyURL: (url: URL | string) => string;
2
+ export { getFriendlyURL };
@@ -0,0 +1,10 @@
1
+ declare global {
2
+ interface WorkerGlobalScope {
3
+ __WB_DISABLE_DEV_LOGS: boolean;
4
+ }
5
+ interface Window {
6
+ __WB_DISABLE_DEV_LOGS: boolean;
7
+ }
8
+ }
9
+ declare const logger: Console;
10
+ export { logger };
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Returns a promise that resolves to a window client matching the passed
3
+ * `resultingClientId`. For browsers that don't support `resultingClientId`
4
+ * or if waiting for the resulting client to apper takes too long, resolve to
5
+ * `undefined`.
6
+ *
7
+ * @param resultingClientId
8
+ * @returns
9
+ * @private
10
+ */
11
+ export declare function resultingClientExists(resultingClientId?: string): Promise<Client | undefined>;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Returns a promise that resolves and the passed number of milliseconds.
3
+ * This utility is an async/await-friendly version of `setTimeout`.
4
+ *
5
+ * @param ms
6
+ * @returns
7
+ * @private
8
+ */
9
+ export declare function timeout(ms: number): Promise<unknown>;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * A utility method that makes it easier to use `event.waitUntil` with
3
+ * async functions and return the result.
4
+ *
5
+ * @param event
6
+ * @param asyncFn
7
+ * @returns
8
+ * @private
9
+ */
10
+ declare function waitUntil(event: ExtendableEvent, asyncFn: () => Promise<any>): Promise<any>;
11
+ export { waitUntil };
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Get the current cache names and prefix/suffix used by Workbox.
3
+ *
4
+ * `cacheNames.precache` is used for precached assets,
5
+ * `cacheNames.googleAnalytics` is used by `@serwist/google-analytics` to
6
+ * store `analytics.js`, and `cacheNames.runtime` is used for everything else.
7
+ *
8
+ * `cacheNames.prefix` can be used to retrieve just the current prefix value.
9
+ * `cacheNames.suffix` can be used to retrieve just the current suffix value.
10
+ *
11
+ * @returns An object with `precache`, `runtime`, `prefix`, and `googleAnalytics` properties.
12
+ */
13
+ declare const cacheNames: {
14
+ readonly googleAnalytics: string;
15
+ readonly precache: string;
16
+ readonly prefix: string;
17
+ readonly runtime: string;
18
+ readonly suffix: string;
19
+ };
20
+ export { cacheNames };
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Claim any currently available clients once the service worker
3
+ * becomes active. This is normally used in conjunction with `skipWaiting()`.
4
+ */
5
+ declare function clientsClaim(): void;
6
+ export { clientsClaim };
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Allows developers to copy a response and modify its `headers`, `status`,
3
+ * or `statusText` values (the values settable via a
4
+ * [`ResponseInit`](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#Syntax)
5
+ * object in the constructor).
6
+ * To modify these values, pass a function as the second argument. That
7
+ * function will be invoked with a single object with the response properties
8
+ * `{headers, status, statusText}`. The return value of this function will
9
+ * be used as the `ResponseInit` for the new `Response`. To change the values
10
+ * either modify the passed parameter(s) and return it, or return a totally
11
+ * new object.
12
+ *
13
+ * This method is intentionally limited to same-origin responses, regardless of
14
+ * whether CORS was used or not.
15
+ *
16
+ * @param response
17
+ * @param modifier
18
+ */
19
+ declare function copyResponse(response: Response, modifier?: (responseInit: ResponseInit) => ResponseInit): Promise<Response>;
20
+ export { copyResponse };
package/dist/index.cjs ADDED
@@ -0,0 +1,154 @@
1
+ 'use strict';
2
+
3
+ var quotaErrorCallbacks = require('./quotaErrorCallbacks-t3P-jWKl.js');
4
+
5
+ /**
6
+ * Get the current cache names and prefix/suffix used by Workbox.
7
+ *
8
+ * `cacheNames.precache` is used for precached assets,
9
+ * `cacheNames.googleAnalytics` is used by `@serwist/google-analytics` to
10
+ * store `analytics.js`, and `cacheNames.runtime` is used for everything else.
11
+ *
12
+ * `cacheNames.prefix` can be used to retrieve just the current prefix value.
13
+ * `cacheNames.suffix` can be used to retrieve just the current suffix value.
14
+ *
15
+ * @returns An object with `precache`, `runtime`, `prefix`, and `googleAnalytics` properties.
16
+ */ const cacheNames = {
17
+ get googleAnalytics () {
18
+ return quotaErrorCallbacks.cacheNames.getGoogleAnalyticsName();
19
+ },
20
+ get precache () {
21
+ return quotaErrorCallbacks.cacheNames.getPrecacheName();
22
+ },
23
+ get prefix () {
24
+ return quotaErrorCallbacks.cacheNames.getPrefix();
25
+ },
26
+ get runtime () {
27
+ return quotaErrorCallbacks.cacheNames.getRuntimeName();
28
+ },
29
+ get suffix () {
30
+ return quotaErrorCallbacks.cacheNames.getSuffix();
31
+ }
32
+ };
33
+
34
+ /*
35
+ Copyright 2019 Google LLC
36
+
37
+ Use of this source code is governed by an MIT-style
38
+ license that can be found in the LICENSE file or at
39
+ https://opensource.org/licenses/MIT.
40
+ */ // Give TypeScript the correct global.
41
+ /**
42
+ * Claim any currently available clients once the service worker
43
+ * becomes active. This is normally used in conjunction with `skipWaiting()`.
44
+ */ function clientsClaim() {
45
+ self.addEventListener("activate", ()=>self.clients.claim());
46
+ }
47
+
48
+ /**
49
+ * Allows developers to copy a response and modify its `headers`, `status`,
50
+ * or `statusText` values (the values settable via a
51
+ * [`ResponseInit`](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#Syntax)
52
+ * object in the constructor).
53
+ * To modify these values, pass a function as the second argument. That
54
+ * function will be invoked with a single object with the response properties
55
+ * `{headers, status, statusText}`. The return value of this function will
56
+ * be used as the `ResponseInit` for the new `Response`. To change the values
57
+ * either modify the passed parameter(s) and return it, or return a totally
58
+ * new object.
59
+ *
60
+ * This method is intentionally limited to same-origin responses, regardless of
61
+ * whether CORS was used or not.
62
+ *
63
+ * @param response
64
+ * @param modifier
65
+ */ async function copyResponse(response, modifier) {
66
+ let origin = null;
67
+ // If response.url isn't set, assume it's cross-origin and keep origin null.
68
+ if (response.url) {
69
+ const responseURL = new URL(response.url);
70
+ origin = responseURL.origin;
71
+ }
72
+ if (origin !== self.location.origin) {
73
+ throw new quotaErrorCallbacks.SerwistError("cross-origin-copy-response", {
74
+ origin
75
+ });
76
+ }
77
+ const clonedResponse = response.clone();
78
+ // Create a fresh `ResponseInit` object by cloning the headers.
79
+ const responseInit = {
80
+ headers: new Headers(clonedResponse.headers),
81
+ status: clonedResponse.status,
82
+ statusText: clonedResponse.statusText
83
+ };
84
+ // Apply any user modifications.
85
+ const modifiedResponseInit = modifier ? modifier(responseInit) : responseInit;
86
+ // Create the new response from the body stream and `ResponseInit`
87
+ // modifications. Note: not all browsers support the Response.body stream,
88
+ // so fall back to reading the entire body into memory as a blob.
89
+ const body = quotaErrorCallbacks.canConstructResponseFromBodyStream() ? clonedResponse.body : await clonedResponse.blob();
90
+ return new Response(body, modifiedResponseInit);
91
+ }
92
+
93
+ /**
94
+ * Adds a function to the set of quotaErrorCallbacks that will be executed if
95
+ * there's a quota error.
96
+ *
97
+ * @param callback
98
+ */ // Can't change Function type
99
+ // eslint-disable-next-line @typescript-eslint/ban-types
100
+ function registerQuotaErrorCallback(callback) {
101
+ if (process.env.NODE_ENV !== "production") {
102
+ quotaErrorCallbacks.finalAssertExports.isType(callback, "function", {
103
+ moduleName: "@serwist/core",
104
+ funcName: "register",
105
+ paramName: "callback"
106
+ });
107
+ }
108
+ quotaErrorCallbacks.quotaErrorCallbacks.add(callback);
109
+ if (process.env.NODE_ENV !== "production") {
110
+ quotaErrorCallbacks.logger.log("Registered a callback to respond to quota errors.", callback);
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Modifies the default cache names used by the Serwist packages.
116
+ * Cache names are generated as `<prefix>-<Cache Name>-<suffix>`.
117
+ *
118
+ * @param details
119
+ */ function setCacheNameDetails(details) {
120
+ if (process.env.NODE_ENV !== "production") {
121
+ Object.keys(details).forEach((key)=>{
122
+ quotaErrorCallbacks.finalAssertExports.isType(details[key], "string", {
123
+ moduleName: "@serwist/core",
124
+ funcName: "setCacheNameDetails",
125
+ paramName: `details.${key}`
126
+ });
127
+ });
128
+ if (details["precache"]?.length === 0) {
129
+ throw new quotaErrorCallbacks.SerwistError("invalid-cache-name", {
130
+ cacheNameId: "precache",
131
+ value: details["precache"]
132
+ });
133
+ }
134
+ if (details["runtime"]?.length === 0) {
135
+ throw new quotaErrorCallbacks.SerwistError("invalid-cache-name", {
136
+ cacheNameId: "runtime",
137
+ value: details["runtime"]
138
+ });
139
+ }
140
+ if (details["googleAnalytics"]?.length === 0) {
141
+ throw new quotaErrorCallbacks.SerwistError("invalid-cache-name", {
142
+ cacheNameId: "googleAnalytics",
143
+ value: details["googleAnalytics"]
144
+ });
145
+ }
146
+ }
147
+ quotaErrorCallbacks.cacheNames.updateDetails(details);
148
+ }
149
+
150
+ exports.cacheNames = cacheNames;
151
+ exports.clientsClaim = clientsClaim;
152
+ exports.copyResponse = copyResponse;
153
+ exports.registerQuotaErrorCallback = registerQuotaErrorCallback;
154
+ exports.setCacheNameDetails = setCacheNameDetails;
File without changes
@@ -0,0 +1,244 @@
1
+ 'use strict';
2
+
3
+ var quotaErrorCallbacks = require('./quotaErrorCallbacks-t3P-jWKl.js');
4
+
5
+ /*
6
+ Copyright 2020 Google LLC
7
+ Use of this source code is governed by an MIT-style
8
+ license that can be found in the LICENSE file or at
9
+ https://opensource.org/licenses/MIT.
10
+ */ function stripParams(fullURL, ignoreParams) {
11
+ const strippedURL = new URL(fullURL);
12
+ for (const param of ignoreParams){
13
+ strippedURL.searchParams.delete(param);
14
+ }
15
+ return strippedURL.href;
16
+ }
17
+ /**
18
+ * Matches an item in the cache, ignoring specific URL params. This is similar
19
+ * to the `ignoreSearch` option, but it allows you to ignore just specific
20
+ * params (while continuing to match on the others).
21
+ *
22
+ * @private
23
+ * @param cache
24
+ * @param request
25
+ * @param matchOptions
26
+ * @param ignoreParams
27
+ * @returns
28
+ */ async function cacheMatchIgnoreParams(cache, request, ignoreParams, matchOptions) {
29
+ const strippedRequestURL = stripParams(request.url, ignoreParams);
30
+ // If the request doesn't include any ignored params, match as normal.
31
+ if (request.url === strippedRequestURL) {
32
+ return cache.match(request, matchOptions);
33
+ }
34
+ // Otherwise, match by comparing keys
35
+ const keysOptions = {
36
+ ...matchOptions,
37
+ ignoreSearch: true
38
+ };
39
+ const cacheKeys = await cache.keys(request, keysOptions);
40
+ for (const cacheKey of cacheKeys){
41
+ const strippedCacheKeyURL = stripParams(cacheKey.url, ignoreParams);
42
+ if (strippedRequestURL === strippedCacheKeyURL) {
43
+ return cache.match(cacheKey, matchOptions);
44
+ }
45
+ }
46
+ return;
47
+ }
48
+
49
+ /*
50
+ Copyright 2019 Google LLC
51
+
52
+ Use of this source code is governed by an MIT-style
53
+ license that can be found in the LICENSE file or at
54
+ https://opensource.org/licenses/MIT.
55
+ */ let supportStatus;
56
+ /**
57
+ * A utility function that determines whether the current browser supports
58
+ * constructing a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream)
59
+ * object.
60
+ *
61
+ * @returns `true`, if the current browser can successfully construct a `ReadableStream`, `false` otherwise.
62
+ *
63
+ * @private
64
+ */ function canConstructReadableStream() {
65
+ if (supportStatus === undefined) {
66
+ // See https://github.com/GoogleChrome/workbox/issues/1473
67
+ try {
68
+ new ReadableStream({
69
+ start () {}
70
+ });
71
+ supportStatus = true;
72
+ } catch (error) {
73
+ supportStatus = false;
74
+ }
75
+ }
76
+ return supportStatus;
77
+ }
78
+
79
+ /*
80
+ Copyright 2018 Google LLC
81
+
82
+ Use of this source code is governed by an MIT-style
83
+ license that can be found in the LICENSE file or at
84
+ https://opensource.org/licenses/MIT.
85
+ */ /**
86
+ * The Deferred class composes Promises in a way that allows for them to be
87
+ * resolved or rejected from outside the constructor. In most cases promises
88
+ * should be used directly, but Deferreds can be necessary when the logic to
89
+ * resolve a promise must be separate.
90
+ *
91
+ * @private
92
+ */ class Deferred {
93
+ promise;
94
+ resolve;
95
+ reject;
96
+ /**
97
+ * Creates a promise and exposes its resolve and reject functions as methods.
98
+ */ constructor(){
99
+ this.promise = new Promise((resolve, reject)=>{
100
+ this.resolve = resolve;
101
+ this.reject = reject;
102
+ });
103
+ }
104
+ }
105
+
106
+ /*
107
+ Copyright 2019 Google LLC
108
+ Use of this source code is governed by an MIT-style
109
+ license that can be found in the LICENSE file or at
110
+ https://opensource.org/licenses/MIT.
111
+ */ /**
112
+ * A helper function that prevents a promise from being flagged as unused.
113
+ *
114
+ * @private
115
+ **/ function dontWaitFor(promise) {
116
+ // Effective no-op.
117
+ void promise.then(()=>{});
118
+ }
119
+
120
+ /**
121
+ * Runs all of the callback functions, one at a time sequentially, in the order
122
+ * in which they were registered.
123
+ *
124
+ * @private
125
+ */ async function executeQuotaErrorCallbacks() {
126
+ if (process.env.NODE_ENV !== "production") {
127
+ quotaErrorCallbacks.logger.log(`About to run ${quotaErrorCallbacks.quotaErrorCallbacks.size} ` + `callbacks to clean up caches.`);
128
+ }
129
+ for (const callback of quotaErrorCallbacks.quotaErrorCallbacks){
130
+ await callback();
131
+ if (process.env.NODE_ENV !== "production") {
132
+ quotaErrorCallbacks.logger.log(callback, "is complete.");
133
+ }
134
+ }
135
+ if (process.env.NODE_ENV !== "production") {
136
+ quotaErrorCallbacks.logger.log("Finished running callbacks.");
137
+ }
138
+ }
139
+
140
+ /*
141
+ Copyright 2018 Google LLC
142
+
143
+ Use of this source code is governed by an MIT-style
144
+ license that can be found in the LICENSE file or at
145
+ https://opensource.org/licenses/MIT.
146
+ */ const getFriendlyURL = (url)=>{
147
+ const urlObj = new URL(String(url), location.href);
148
+ // See https://github.com/GoogleChrome/workbox/issues/2323
149
+ // We want to include everything, except for the origin if it's same-origin.
150
+ return urlObj.href.replace(new RegExp(`^${location.origin}`), "");
151
+ };
152
+
153
+ /*
154
+ Copyright 2019 Google LLC
155
+ Use of this source code is governed by an MIT-style
156
+ license that can be found in the LICENSE file or at
157
+ https://opensource.org/licenses/MIT.
158
+ */ /**
159
+ * Returns a promise that resolves and the passed number of milliseconds.
160
+ * This utility is an async/await-friendly version of `setTimeout`.
161
+ *
162
+ * @param ms
163
+ * @returns
164
+ * @private
165
+ */ function timeout(ms) {
166
+ return new Promise((resolve)=>setTimeout(resolve, ms));
167
+ }
168
+
169
+ const MAX_RETRY_TIME = 2000;
170
+ /**
171
+ * Returns a promise that resolves to a window client matching the passed
172
+ * `resultingClientId`. For browsers that don't support `resultingClientId`
173
+ * or if waiting for the resulting client to apper takes too long, resolve to
174
+ * `undefined`.
175
+ *
176
+ * @param resultingClientId
177
+ * @returns
178
+ * @private
179
+ */ async function resultingClientExists(resultingClientId) {
180
+ if (!resultingClientId) {
181
+ return;
182
+ }
183
+ let existingWindows = await self.clients.matchAll({
184
+ type: "window"
185
+ });
186
+ const existingWindowIds = new Set(existingWindows.map((w)=>w.id));
187
+ let resultingWindow;
188
+ const startTime = performance.now();
189
+ // Only wait up to `MAX_RETRY_TIME` to find a matching client.
190
+ while(performance.now() - startTime < MAX_RETRY_TIME){
191
+ existingWindows = await self.clients.matchAll({
192
+ type: "window"
193
+ });
194
+ resultingWindow = existingWindows.find((w)=>{
195
+ if (resultingClientId) {
196
+ // If we have a `resultingClientId`, we can match on that.
197
+ return w.id === resultingClientId;
198
+ } else {
199
+ // Otherwise match on finding a window not in `existingWindowIds`.
200
+ return !existingWindowIds.has(w.id);
201
+ }
202
+ });
203
+ if (resultingWindow) {
204
+ break;
205
+ }
206
+ // Sleep for 100ms and retry.
207
+ await timeout(100);
208
+ }
209
+ return resultingWindow;
210
+ }
211
+
212
+ /*
213
+ Copyright 2020 Google LLC
214
+ Use of this source code is governed by an MIT-style
215
+ license that can be found in the LICENSE file or at
216
+ https://opensource.org/licenses/MIT.
217
+ */ /**
218
+ * A utility method that makes it easier to use `event.waitUntil` with
219
+ * async functions and return the result.
220
+ *
221
+ * @param event
222
+ * @param asyncFn
223
+ * @returns
224
+ * @private
225
+ */ function waitUntil(event, asyncFn) {
226
+ const returnPromise = asyncFn();
227
+ event.waitUntil(returnPromise);
228
+ return returnPromise;
229
+ }
230
+
231
+ exports.SerwistError = quotaErrorCallbacks.SerwistError;
232
+ exports.assert = quotaErrorCallbacks.finalAssertExports;
233
+ exports.canConstructResponseFromBodyStream = quotaErrorCallbacks.canConstructResponseFromBodyStream;
234
+ exports.logger = quotaErrorCallbacks.logger;
235
+ exports.privateCacheNames = quotaErrorCallbacks.cacheNames;
236
+ exports.Deferred = Deferred;
237
+ exports.cacheMatchIgnoreParams = cacheMatchIgnoreParams;
238
+ exports.canConstructReadableStream = canConstructReadableStream;
239
+ exports.dontWaitFor = dontWaitFor;
240
+ exports.executeQuotaErrorCallbacks = executeQuotaErrorCallbacks;
241
+ exports.getFriendlyURL = getFriendlyURL;
242
+ exports.resultingClientExists = resultingClientExists;
243
+ exports.timeout = timeout;
244
+ exports.waitUntil = waitUntil;