@serwist/core 8.4.3 → 9.0.0-preview.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 (118) hide show
  1. package/dist/_private/Deferred.d.ts +1 -0
  2. package/dist/_private/Deferred.d.ts.map +1 -0
  3. package/dist/_private/SerwistError.d.ts +1 -0
  4. package/dist/_private/SerwistError.d.ts.map +1 -0
  5. package/dist/_private/assert.d.ts +1 -0
  6. package/dist/_private/assert.d.ts.map +1 -0
  7. package/dist/_private/cacheMatchIgnoreParams.d.ts +1 -0
  8. package/dist/_private/cacheMatchIgnoreParams.d.ts.map +1 -0
  9. package/dist/_private/cacheNames.d.ts +1 -0
  10. package/dist/_private/cacheNames.d.ts.map +1 -0
  11. package/dist/_private/canConstructReadableStream.d.ts +1 -0
  12. package/dist/_private/canConstructReadableStream.d.ts.map +1 -0
  13. package/dist/_private/canConstructResponseFromBodyStream.d.ts +1 -0
  14. package/dist/_private/canConstructResponseFromBodyStream.d.ts.map +1 -0
  15. package/dist/_private/dontWaitFor.d.ts +1 -0
  16. package/dist/_private/dontWaitFor.d.ts.map +1 -0
  17. package/dist/_private/executeQuotaErrorCallbacks.d.ts +1 -0
  18. package/dist/_private/executeQuotaErrorCallbacks.d.ts.map +1 -0
  19. package/dist/_private/getFriendlyURL.d.ts +1 -0
  20. package/dist/_private/getFriendlyURL.d.ts.map +1 -0
  21. package/dist/_private/logger.d.ts +1 -0
  22. package/dist/_private/logger.d.ts.map +1 -0
  23. package/dist/_private/resultingClientExists.d.ts +1 -0
  24. package/dist/_private/resultingClientExists.d.ts.map +1 -0
  25. package/dist/_private/timeout.d.ts +1 -0
  26. package/dist/_private/timeout.d.ts.map +1 -0
  27. package/dist/_private/waitUntil.d.ts +1 -0
  28. package/dist/_private/waitUntil.d.ts.map +1 -0
  29. package/dist/cacheNames.d.ts +1 -0
  30. package/dist/cacheNames.d.ts.map +1 -0
  31. package/dist/clientsClaim.d.ts +1 -0
  32. package/dist/clientsClaim.d.ts.map +1 -0
  33. package/dist/copyResponse.d.ts +1 -0
  34. package/dist/copyResponse.d.ts.map +1 -0
  35. package/dist/index.d.ts +1 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.internal.d.ts +1 -0
  38. package/dist/index.internal.d.ts.map +1 -0
  39. package/dist/index.internal.js +2 -2
  40. package/dist/index.js +1 -1
  41. package/dist/models/messages/messageGenerator.d.ts +1 -0
  42. package/dist/models/messages/messageGenerator.d.ts.map +1 -0
  43. package/dist/models/messages/messages.d.ts +1 -0
  44. package/dist/models/messages/messages.d.ts.map +1 -0
  45. package/dist/models/pluginEvents.d.ts +1 -0
  46. package/dist/models/pluginEvents.d.ts.map +1 -0
  47. package/dist/models/quotaErrorCallbacks.d.ts +1 -0
  48. package/dist/models/quotaErrorCallbacks.d.ts.map +1 -0
  49. package/dist/registerQuotaErrorCallback.d.ts +1 -0
  50. package/dist/registerQuotaErrorCallback.d.ts.map +1 -0
  51. package/dist/setCacheNameDetails.d.ts +1 -0
  52. package/dist/setCacheNameDetails.d.ts.map +1 -0
  53. package/dist/types.d.ts +1 -0
  54. package/dist/types.d.ts.map +1 -0
  55. package/dist/utils/pluginUtils.d.ts +1 -0
  56. package/dist/utils/pluginUtils.d.ts.map +1 -0
  57. package/dist/utils/welcome.d.ts +1 -0
  58. package/dist/utils/welcome.d.ts.map +1 -0
  59. package/package.json +18 -22
  60. package/src/_private/Deferred.ts +33 -0
  61. package/src/_private/SerwistError.ts +42 -0
  62. package/src/_private/assert.ts +89 -0
  63. package/src/_private/cacheMatchIgnoreParams.ts +54 -0
  64. package/src/_private/cacheNames.ts +87 -0
  65. package/src/_private/canConstructReadableStream.ts +34 -0
  66. package/src/_private/canConstructResponseFromBodyStream.ts +37 -0
  67. package/src/_private/dontWaitFor.ts +16 -0
  68. package/src/_private/executeQuotaErrorCallbacks.ts +35 -0
  69. package/src/_private/getFriendlyURL.ts +16 -0
  70. package/src/_private/logger.ts +92 -0
  71. package/src/_private/resultingClientExists.ts +58 -0
  72. package/src/_private/timeout.ts +19 -0
  73. package/src/_private/waitUntil.ts +23 -0
  74. package/src/cacheNames.ts +41 -0
  75. package/src/clientsClaim.ts +20 -0
  76. package/src/copyResponse.ts +62 -0
  77. package/src/index.internal.ts +33 -0
  78. package/{dist/index.d.cts → src/index.ts} +9 -0
  79. package/src/models/messages/messageGenerator.ts +28 -0
  80. package/src/models/messages/messages.ts +231 -0
  81. package/src/models/pluginEvents.ts +17 -0
  82. package/src/models/quotaErrorCallbacks.ts +13 -0
  83. package/src/registerQuotaErrorCallback.ts +36 -0
  84. package/src/setCacheNameDetails.ts +55 -0
  85. package/src/types.ts +315 -0
  86. package/src/utils/pluginUtils.ts +15 -0
  87. package/src/utils/welcome.ts +25 -0
  88. package/dist/_private/Deferred.d.cts +0 -18
  89. package/dist/_private/SerwistError.d.cts +0 -23
  90. package/dist/_private/assert.d.cts +0 -10
  91. package/dist/_private/cacheMatchIgnoreParams.d.cts +0 -14
  92. package/dist/_private/cacheNames.d.cts +0 -39
  93. package/dist/_private/canConstructReadableStream.d.cts +0 -11
  94. package/dist/_private/canConstructResponseFromBodyStream.d.cts +0 -10
  95. package/dist/_private/dontWaitFor.d.cts +0 -6
  96. package/dist/_private/executeQuotaErrorCallbacks.d.cts +0 -8
  97. package/dist/_private/getFriendlyURL.d.cts +0 -2
  98. package/dist/_private/logger.d.cts +0 -10
  99. package/dist/_private/resultingClientExists.d.cts +0 -11
  100. package/dist/_private/timeout.d.cts +0 -9
  101. package/dist/_private/waitUntil.d.cts +0 -0
  102. package/dist/cacheNames.d.cts +0 -20
  103. package/dist/clientsClaim.d.cts +0 -6
  104. package/dist/copyResponse.d.cts +0 -20
  105. package/dist/index.cjs +0 -153
  106. package/dist/index.internal.cjs +0 -243
  107. package/dist/index.internal.d.cts +0 -0
  108. package/dist/models/messages/messageGenerator.d.cts +0 -1
  109. package/dist/models/messages/messages.d.cts +0 -8
  110. package/dist/models/pluginEvents.d.cts +0 -9
  111. package/dist/models/quotaErrorCallbacks.d.cts +0 -2
  112. package/dist/quotaErrorCallbacks.cjs +0 -432
  113. package/dist/registerQuotaErrorCallback.d.cts +0 -0
  114. package/dist/setCacheNameDetails.d.cts +0 -0
  115. package/dist/types.d.cts +0 -272
  116. package/dist/utils/pluginUtils.d.cts +0 -4
  117. package/dist/utils/welcome.d.cts +0 -1
  118. /package/dist/{quotaErrorCallbacks.js → chunks/quotaErrorCallbacks.js} +0 -0
@@ -0,0 +1,87 @@
1
+ /*
2
+ Copyright 2018 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ declare let registration: ServiceWorkerRegistration | undefined;
10
+
11
+ export interface CacheNameDetails {
12
+ googleAnalytics: string;
13
+ precache: string;
14
+ prefix: string;
15
+ runtime: string;
16
+ suffix: string;
17
+ }
18
+
19
+ export interface PartialCacheNameDetails {
20
+ /**
21
+ * The string to add to the beginning of the precache and runtime cache names.
22
+ */
23
+ prefix?: string;
24
+ /**
25
+ * The string to add to the end of the precache and runtime cache names.
26
+ */
27
+ suffix?: string;
28
+ /**
29
+ * The cache name to use for precache caching.
30
+ */
31
+ precache?: string;
32
+ /**
33
+ * The cache name to use for runtime caching.
34
+ */
35
+ runtime?: string;
36
+ /**
37
+ * The cache name to use for `@serwist/google-analytics` caching.
38
+ */
39
+ googleAnalytics?: string;
40
+ [propName: string]: string | undefined;
41
+ }
42
+
43
+ export type CacheNameDetailsProp = "googleAnalytics" | "precache" | "prefix" | "runtime" | "suffix";
44
+
45
+ const _cacheNameDetails: CacheNameDetails = {
46
+ googleAnalytics: "googleAnalytics",
47
+ precache: "precache-v2",
48
+ prefix: "serwist",
49
+ runtime: "runtime",
50
+ suffix: typeof registration !== "undefined" ? registration.scope : "",
51
+ };
52
+
53
+ const _createCacheName = (cacheName: string): string => {
54
+ return [_cacheNameDetails.prefix, cacheName, _cacheNameDetails.suffix].filter((value) => value && value.length > 0).join("-");
55
+ };
56
+
57
+ const eachCacheNameDetail = (fn: (key: CacheNameDetailsProp) => void): void => {
58
+ for (const key of Object.keys(_cacheNameDetails)) {
59
+ fn(key as CacheNameDetailsProp);
60
+ }
61
+ };
62
+
63
+ export const cacheNames = {
64
+ updateDetails: (details: PartialCacheNameDetails): void => {
65
+ eachCacheNameDetail((key: CacheNameDetailsProp): void => {
66
+ const detail = details[key];
67
+ if (typeof detail === "string") {
68
+ _cacheNameDetails[key] = detail;
69
+ }
70
+ });
71
+ },
72
+ getGoogleAnalyticsName: (userCacheName?: string): string => {
73
+ return userCacheName || _createCacheName(_cacheNameDetails.googleAnalytics);
74
+ },
75
+ getPrecacheName: (userCacheName?: string): string => {
76
+ return userCacheName || _createCacheName(_cacheNameDetails.precache);
77
+ },
78
+ getPrefix: (): string => {
79
+ return _cacheNameDetails.prefix;
80
+ },
81
+ getRuntimeName: (userCacheName?: string): string => {
82
+ return userCacheName || _createCacheName(_cacheNameDetails.runtime);
83
+ },
84
+ getSuffix: (): string => {
85
+ return _cacheNameDetails.suffix;
86
+ },
87
+ };
@@ -0,0 +1,34 @@
1
+ /*
2
+ Copyright 2019 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ let supportStatus: boolean | undefined;
10
+
11
+ /**
12
+ * A utility function that determines whether the current browser supports
13
+ * constructing a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream)
14
+ * object.
15
+ *
16
+ * @returns `true`, if the current browser can successfully construct a `ReadableStream`, `false` otherwise.
17
+ *
18
+ * @private
19
+ */
20
+ function canConstructReadableStream(): boolean {
21
+ if (supportStatus === undefined) {
22
+ // See https://github.com/GoogleChrome/workbox/issues/1473
23
+ try {
24
+ new ReadableStream({ start() {} });
25
+ supportStatus = true;
26
+ } catch (error) {
27
+ supportStatus = false;
28
+ }
29
+ }
30
+
31
+ return supportStatus;
32
+ }
33
+
34
+ export { canConstructReadableStream };
@@ -0,0 +1,37 @@
1
+ /*
2
+ Copyright 2019 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ let supportStatus: boolean | undefined;
10
+
11
+ /**
12
+ * A utility function that determines whether the current browser supports
13
+ * constructing a new `Response` from a `response.body` stream.
14
+ *
15
+ * @returns `true`, if the current browser can successfully construct
16
+ * a `Response` from a `response.body` stream, `false` otherwise.
17
+ * @private
18
+ */
19
+ function canConstructResponseFromBodyStream(): boolean {
20
+ if (supportStatus === undefined) {
21
+ const testResponse = new Response("");
22
+
23
+ if ("body" in testResponse) {
24
+ try {
25
+ new Response(testResponse.body);
26
+ supportStatus = true;
27
+ } catch (error) {
28
+ supportStatus = false;
29
+ }
30
+ }
31
+ supportStatus = false;
32
+ }
33
+
34
+ return supportStatus;
35
+ }
36
+
37
+ export { canConstructResponseFromBodyStream };
@@ -0,0 +1,16 @@
1
+ /*
2
+ Copyright 2019 Google LLC
3
+ Use of this source code is governed by an MIT-style
4
+ license that can be found in the LICENSE file or at
5
+ https://opensource.org/licenses/MIT.
6
+ */
7
+
8
+ /**
9
+ * A helper function that prevents a promise from being flagged as unused.
10
+ *
11
+ * @private
12
+ **/
13
+ export function dontWaitFor(promise: Promise<any>): void {
14
+ // Effective no-op.
15
+ void promise.then(() => {});
16
+ }
@@ -0,0 +1,35 @@
1
+ /*
2
+ Copyright 2018 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ import { logger } from "../_private/logger.js";
10
+ import { quotaErrorCallbacks } from "../models/quotaErrorCallbacks.js";
11
+
12
+ /**
13
+ * Runs all of the callback functions, one at a time sequentially, in the order
14
+ * in which they were registered.
15
+ *
16
+ * @private
17
+ */
18
+ async function executeQuotaErrorCallbacks(): Promise<void> {
19
+ if (process.env.NODE_ENV !== "production") {
20
+ logger.log(`About to run ${quotaErrorCallbacks.size} callbacks to clean up caches.`);
21
+ }
22
+
23
+ for (const callback of quotaErrorCallbacks) {
24
+ await callback();
25
+ if (process.env.NODE_ENV !== "production") {
26
+ logger.log(callback, "is complete.");
27
+ }
28
+ }
29
+
30
+ if (process.env.NODE_ENV !== "production") {
31
+ logger.log("Finished running callbacks.");
32
+ }
33
+ }
34
+
35
+ export { executeQuotaErrorCallbacks };
@@ -0,0 +1,16 @@
1
+ /*
2
+ Copyright 2018 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ const getFriendlyURL = (url: URL | string): string => {
10
+ const urlObj = new URL(String(url), location.href);
11
+ // See https://github.com/GoogleChrome/workbox/issues/2323
12
+ // We want to include everything, except for the origin if it's same-origin.
13
+ return urlObj.href.replace(new RegExp(`^${location.origin}`), "");
14
+ };
15
+
16
+ export { getFriendlyURL };
@@ -0,0 +1,92 @@
1
+ /*
2
+ Copyright 2019 Google LLC
3
+ Use of this source code is governed by an MIT-style
4
+ license that can be found in the LICENSE file or at
5
+ https://opensource.org/licenses/MIT.
6
+ */
7
+
8
+ // logger is used inside of both service workers and the window global scope.
9
+ declare global {
10
+ interface WorkerGlobalScope {
11
+ __WB_DISABLE_DEV_LOGS: boolean;
12
+ }
13
+
14
+ interface Window {
15
+ __WB_DISABLE_DEV_LOGS: boolean;
16
+ }
17
+ }
18
+
19
+ type LoggerMethods = "debug" | "log" | "warn" | "error" | "groupCollapsed" | "groupEnd";
20
+
21
+ const logger = (
22
+ process.env.NODE_ENV === "production"
23
+ ? null
24
+ : (() => {
25
+ // Don't overwrite this value if it's already set.
26
+ // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923
27
+ if (!("__WB_DISABLE_DEV_LOGS" in globalThis)) {
28
+ self.__WB_DISABLE_DEV_LOGS = false;
29
+ }
30
+
31
+ let inGroup = false;
32
+
33
+ const methodToColorMap: { [methodName: string]: string | null } = {
34
+ debug: "#7f8c8d", // Gray
35
+ log: "#2ecc71", // Green
36
+ warn: "#f39c12", // Yellow
37
+ error: "#c0392b", // Red
38
+ groupCollapsed: "#3498db", // Blue
39
+ groupEnd: null, // No colored prefix on groupEnd
40
+ };
41
+
42
+ const print = (method: LoggerMethods, args: any[]) => {
43
+ if (self.__WB_DISABLE_DEV_LOGS) {
44
+ return;
45
+ }
46
+
47
+ if (method === "groupCollapsed") {
48
+ // Safari doesn't print all console.groupCollapsed() arguments:
49
+ // https://bugs.webkit.org/show_bug.cgi?id=182754
50
+ if (typeof navigator !== "undefined" && /^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
51
+ console[method](...args);
52
+ return;
53
+ }
54
+ }
55
+
56
+ const styles = [
57
+ `background: ${methodToColorMap[method]!}`,
58
+ "border-radius: 0.5em",
59
+ "color: white",
60
+ "font-weight: bold",
61
+ "padding: 2px 0.5em",
62
+ ];
63
+
64
+ // When in a group, the serwist prefix is not displayed.
65
+ const logPrefix = inGroup ? [] : ["%cserwist", styles.join(";")];
66
+
67
+ console[method](...logPrefix, ...args);
68
+
69
+ if (method === "groupCollapsed") {
70
+ inGroup = true;
71
+ }
72
+ if (method === "groupEnd") {
73
+ inGroup = false;
74
+ }
75
+ };
76
+ // biome-ignore lint/complexity/noBannedTypes: Unknown reason
77
+ const api: { [methodName: string]: Function } = {};
78
+ const loggerMethods = Object.keys(methodToColorMap);
79
+
80
+ for (const key of loggerMethods) {
81
+ const method = key as LoggerMethods;
82
+
83
+ api[method] = (...args: any[]) => {
84
+ print(method, args);
85
+ };
86
+ }
87
+
88
+ return api as unknown;
89
+ })()
90
+ ) as Console;
91
+
92
+ export { logger };
@@ -0,0 +1,58 @@
1
+ /*
2
+ Copyright 2019 Google LLC
3
+ Use of this source code is governed by an MIT-style
4
+ license that can be found in the LICENSE file or at
5
+ https://opensource.org/licenses/MIT.
6
+ */
7
+
8
+ import { timeout } from "./timeout.js";
9
+
10
+ // Give TypeScript the correct global.
11
+ declare let self: ServiceWorkerGlobalScope;
12
+
13
+ const MAX_RETRY_TIME = 2000;
14
+
15
+ /**
16
+ * Returns a promise that resolves to a window client matching the passed
17
+ * `resultingClientId`. For browsers that don't support `resultingClientId`
18
+ * or if waiting for the resulting client to apper takes too long, resolve to
19
+ * `undefined`.
20
+ *
21
+ * @param resultingClientId
22
+ * @returns
23
+ * @private
24
+ */
25
+ export async function resultingClientExists(resultingClientId?: string): Promise<Client | undefined> {
26
+ if (!resultingClientId) {
27
+ return;
28
+ }
29
+
30
+ let existingWindows = await self.clients.matchAll({ type: "window" });
31
+ const existingWindowIds = new Set(existingWindows.map((w) => w.id));
32
+
33
+ let resultingWindow: Client | undefined = undefined;
34
+ const startTime = performance.now();
35
+
36
+ // Only wait up to `MAX_RETRY_TIME` to find a matching client.
37
+ while (performance.now() - startTime < MAX_RETRY_TIME) {
38
+ existingWindows = await self.clients.matchAll({ type: "window" });
39
+
40
+ resultingWindow = existingWindows.find((w) => {
41
+ if (resultingClientId) {
42
+ // If we have a `resultingClientId`, we can match on that.
43
+ return w.id === resultingClientId;
44
+ }
45
+ // Otherwise match on finding a window not in `existingWindowIds`.
46
+ return !existingWindowIds.has(w.id);
47
+ });
48
+
49
+ if (resultingWindow) {
50
+ break;
51
+ }
52
+
53
+ // Sleep for 100ms and retry.
54
+ await timeout(100);
55
+ }
56
+
57
+ return resultingWindow;
58
+ }
@@ -0,0 +1,19 @@
1
+ /*
2
+ Copyright 2019 Google LLC
3
+ Use of this source code is governed by an MIT-style
4
+ license that can be found in the LICENSE file or at
5
+ https://opensource.org/licenses/MIT.
6
+ */
7
+
8
+ /**
9
+ * Returns a promise that resolves and the passed number of milliseconds.
10
+ * This utility is an async/await-friendly version of `setTimeout`.
11
+ *
12
+ * @param ms
13
+ * @returns
14
+ * @private
15
+ */
16
+
17
+ export function timeout(ms: number): Promise<unknown> {
18
+ return new Promise((resolve) => setTimeout(resolve, ms));
19
+ }
@@ -0,0 +1,23 @@
1
+ /*
2
+ Copyright 2020 Google LLC
3
+ Use of this source code is governed by an MIT-style
4
+ license that can be found in the LICENSE file or at
5
+ https://opensource.org/licenses/MIT.
6
+ */
7
+
8
+ /**
9
+ * A utility method that makes it easier to use `event.waitUntil` with
10
+ * async functions and return the result.
11
+ *
12
+ * @param event
13
+ * @param asyncFn
14
+ * @returns
15
+ * @private
16
+ */
17
+ function waitUntil(event: ExtendableEvent, asyncFn: () => Promise<any>): Promise<any> {
18
+ const returnPromise = asyncFn();
19
+ event.waitUntil(returnPromise);
20
+ return returnPromise;
21
+ }
22
+
23
+ export { waitUntil };
@@ -0,0 +1,41 @@
1
+ /*
2
+ Copyright 2019 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ import { cacheNames as _cacheNames } from "./_private/cacheNames.js";
10
+
11
+ /**
12
+ * Get the current cache names and prefix/suffix used by Workbox.
13
+ *
14
+ * `cacheNames.precache` is used for precached assets,
15
+ * `cacheNames.googleAnalytics` is used by `@serwist/google-analytics` to
16
+ * store `analytics.js`, and `cacheNames.runtime` is used for everything else.
17
+ *
18
+ * `cacheNames.prefix` can be used to retrieve just the current prefix value.
19
+ * `cacheNames.suffix` can be used to retrieve just the current suffix value.
20
+ *
21
+ * @returns An object with `precache`, `runtime`, `prefix`, and `googleAnalytics` properties.
22
+ */
23
+ const cacheNames = {
24
+ get googleAnalytics(): string {
25
+ return _cacheNames.getGoogleAnalyticsName();
26
+ },
27
+ get precache(): string {
28
+ return _cacheNames.getPrecacheName();
29
+ },
30
+ get prefix(): string {
31
+ return _cacheNames.getPrefix();
32
+ },
33
+ get runtime(): string {
34
+ return _cacheNames.getRuntimeName();
35
+ },
36
+ get suffix(): string {
37
+ return _cacheNames.getSuffix();
38
+ },
39
+ };
40
+
41
+ export { cacheNames };
@@ -0,0 +1,20 @@
1
+ /*
2
+ Copyright 2019 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ // Give TypeScript the correct global.
10
+ declare let self: ServiceWorkerGlobalScope;
11
+
12
+ /**
13
+ * Claim any currently available clients once the service worker
14
+ * becomes active. This is normally used in conjunction with `skipWaiting()`.
15
+ */
16
+ function clientsClaim(): void {
17
+ self.addEventListener("activate", () => self.clients.claim());
18
+ }
19
+
20
+ export { clientsClaim };
@@ -0,0 +1,62 @@
1
+ /*
2
+ Copyright 2019 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ import { SerwistError } from "./_private/SerwistError.js";
10
+ import { canConstructResponseFromBodyStream } from "./_private/canConstructResponseFromBodyStream.js";
11
+
12
+ /**
13
+ * Allows developers to copy a response and modify its `headers`, `status`,
14
+ * or `statusText` values (the values settable via a
15
+ * [`ResponseInit`](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#Syntax)
16
+ * object in the constructor).
17
+ * To modify these values, pass a function as the second argument. That
18
+ * function will be invoked with a single object with the response properties
19
+ * `{headers, status, statusText}`. The return value of this function will
20
+ * be used as the `ResponseInit` for the new `Response`. To change the values
21
+ * either modify the passed parameter(s) and return it, or return a totally
22
+ * new object.
23
+ *
24
+ * This method is intentionally limited to same-origin responses, regardless of
25
+ * whether CORS was used or not.
26
+ *
27
+ * @param response
28
+ * @param modifier
29
+ */
30
+ async function copyResponse(response: Response, modifier?: (responseInit: ResponseInit) => ResponseInit): Promise<Response> {
31
+ let origin = null;
32
+ // If response.url isn't set, assume it's cross-origin and keep origin null.
33
+ if (response.url) {
34
+ const responseURL = new URL(response.url);
35
+ origin = responseURL.origin;
36
+ }
37
+
38
+ if (origin !== self.location.origin) {
39
+ throw new SerwistError("cross-origin-copy-response", { origin });
40
+ }
41
+
42
+ const clonedResponse = response.clone();
43
+
44
+ // Create a fresh `ResponseInit` object by cloning the headers.
45
+ const responseInit: ResponseInit = {
46
+ headers: new Headers(clonedResponse.headers),
47
+ status: clonedResponse.status,
48
+ statusText: clonedResponse.statusText,
49
+ };
50
+
51
+ // Apply any user modifications.
52
+ const modifiedResponseInit = modifier ? modifier(responseInit) : responseInit;
53
+
54
+ // Create the new response from the body stream and `ResponseInit`
55
+ // modifications. Note: not all browsers support the Response.body stream,
56
+ // so fall back to reading the entire body into memory as a blob.
57
+ const body = canConstructResponseFromBodyStream() ? clonedResponse.body : await clonedResponse.blob();
58
+
59
+ return new Response(body, modifiedResponseInit);
60
+ }
61
+
62
+ export { copyResponse };
@@ -0,0 +1,33 @@
1
+ import { Deferred } from "./_private/Deferred.js";
2
+ import { SerwistError } from "./_private/SerwistError.js";
3
+ import { assert } from "./_private/assert.js";
4
+ import { cacheMatchIgnoreParams } from "./_private/cacheMatchIgnoreParams.js";
5
+ import { cacheNames as privateCacheNames } from "./_private/cacheNames.js";
6
+ import { canConstructReadableStream } from "./_private/canConstructReadableStream.js";
7
+ import { canConstructResponseFromBodyStream } from "./_private/canConstructResponseFromBodyStream.js";
8
+ import { dontWaitFor } from "./_private/dontWaitFor.js";
9
+ import { executeQuotaErrorCallbacks } from "./_private/executeQuotaErrorCallbacks.js";
10
+ import { getFriendlyURL } from "./_private/getFriendlyURL.js";
11
+ import { logger } from "./_private/logger.js";
12
+ import { resultingClientExists } from "./_private/resultingClientExists.js";
13
+ import { timeout } from "./_private/timeout.js";
14
+ import { waitUntil } from "./_private/waitUntil.js";
15
+
16
+ // Serwist's internal functions, classes, variables, and more. Feel free to use them,
17
+ // but they are not documented. Note: they do follow semver.
18
+ export {
19
+ assert,
20
+ cacheMatchIgnoreParams,
21
+ canConstructReadableStream,
22
+ canConstructResponseFromBodyStream,
23
+ Deferred,
24
+ dontWaitFor,
25
+ executeQuotaErrorCallbacks,
26
+ getFriendlyURL,
27
+ logger,
28
+ privateCacheNames,
29
+ resultingClientExists,
30
+ SerwistError,
31
+ timeout,
32
+ waitUntil,
33
+ };
@@ -1,11 +1,20 @@
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
+ */
1
8
  import { cacheNames } from "./cacheNames.js";
2
9
  import { clientsClaim } from "./clientsClaim.js";
3
10
  import { copyResponse } from "./copyResponse.js";
4
11
  import { registerQuotaErrorCallback } from "./registerQuotaErrorCallback.js";
5
12
  import { setCacheNameDetails } from "./setCacheNameDetails.js";
13
+
6
14
  /**
7
15
  * All Serwist libraries use `@serwist/core` for shared code as well as
8
16
  * setting default values that need to be shared (like cache names).
9
17
  */
10
18
  export { cacheNames, clientsClaim, copyResponse, registerQuotaErrorCallback, setCacheNameDetails };
19
+
11
20
  export * from "./types.js";
@@ -0,0 +1,28 @@
1
+ /*
2
+ Copyright 2018 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ import { messages } from "./messages.js";
10
+
11
+ const fallback = (code: string, ...args: any[]) => {
12
+ let msg = code;
13
+ if (args.length > 0) {
14
+ msg += ` :: ${JSON.stringify(args)}`;
15
+ }
16
+ return msg;
17
+ };
18
+
19
+ const generatorFunction = (code: string, details = {}) => {
20
+ const message = messages[code];
21
+ if (!message) {
22
+ throw new Error(`Unable to find message for code '${code}'.`);
23
+ }
24
+
25
+ return message(details);
26
+ };
27
+
28
+ export const messageGenerator = process.env.NODE_ENV === "production" ? fallback : generatorFunction;