@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,231 @@
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
+ interface LoggableObject {
10
+ [key: string]: string | number;
11
+ }
12
+ interface MessageMap {
13
+ [messageID: string]: (param: LoggableObject) => string;
14
+ }
15
+
16
+ export const messages: MessageMap = {
17
+ "invalid-value": ({ paramName, validValueDescription, value }) => {
18
+ if (!paramName || !validValueDescription) {
19
+ throw new Error(`Unexpected input to 'invalid-value' error.`);
20
+ }
21
+ return (
22
+ `The '${paramName}' parameter was given a value with an ` +
23
+ `unexpected value. ${validValueDescription} Received a value of ` +
24
+ `${JSON.stringify(value)}.`
25
+ );
26
+ },
27
+
28
+ "not-an-array": ({ moduleName, className, funcName, paramName }) => {
29
+ if (!moduleName || !className || !funcName || !paramName) {
30
+ throw new Error(`Unexpected input to 'not-an-array' error.`);
31
+ }
32
+ return `The parameter '${paramName}' passed into ` + `'${moduleName}.${className}.${funcName}()' must be an array.`;
33
+ },
34
+
35
+ "incorrect-type": ({ expectedType, paramName, moduleName, className, funcName }) => {
36
+ if (!expectedType || !paramName || !moduleName || !funcName) {
37
+ throw new Error(`Unexpected input to 'incorrect-type' error.`);
38
+ }
39
+ const classNameStr = className ? `${className}.` : "";
40
+ return `The parameter '${paramName}' passed into ` + `'${moduleName}.${classNameStr}` + `${funcName}()' must be of type ${expectedType}.`;
41
+ },
42
+
43
+ "incorrect-class": ({ expectedClassName, paramName, moduleName, className, funcName, isReturnValueProblem }) => {
44
+ if (!expectedClassName || !moduleName || !funcName) {
45
+ throw new Error(`Unexpected input to 'incorrect-class' error.`);
46
+ }
47
+ const classNameStr = className ? `${className}.` : "";
48
+ if (isReturnValueProblem) {
49
+ return `The return value from '${moduleName}.${classNameStr}${funcName}()' must be an instance of class ${expectedClassName}.`;
50
+ }
51
+
52
+ return (
53
+ `The parameter '${paramName}' passed into ` +
54
+ `'${moduleName}.${classNameStr}${funcName}()' ` +
55
+ `must be an instance of class ${expectedClassName}.`
56
+ );
57
+ },
58
+
59
+ "missing-a-method": ({ expectedMethod, paramName, moduleName, className, funcName }) => {
60
+ if (!expectedMethod || !paramName || !moduleName || !className || !funcName) {
61
+ throw new Error(`Unexpected input to 'missing-a-method' error.`);
62
+ }
63
+ return `${moduleName}.${className}.${funcName}() expected the ` + `'${paramName}' parameter to expose a '${expectedMethod}' method.`;
64
+ },
65
+
66
+ "add-to-cache-list-unexpected-type": ({ entry }) => {
67
+ return `An unexpected entry was passed to '@serwist/precaching.PrecacheController.addToCacheList()' The entry '${JSON.stringify(
68
+ entry,
69
+ )}' isn't supported. You must supply an array of strings with one or more characters, objects with a url property or Request objects.`;
70
+ },
71
+
72
+ "add-to-cache-list-conflicting-entries": ({ firstEntry, secondEntry }) => {
73
+ if (!firstEntry || !secondEntry) {
74
+ throw new Error("Unexpected input to " + `'add-to-cache-list-duplicate-entries' error.`);
75
+ }
76
+
77
+ 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.`;
78
+ },
79
+
80
+ "plugin-error-request-will-fetch": ({ thrownErrorMessage }) => {
81
+ if (!thrownErrorMessage) {
82
+ throw new Error("Unexpected input to " + `'plugin-error-request-will-fetch', error.`);
83
+ }
84
+
85
+ return `An error was thrown by a plugins 'requestWillFetch()' method. The thrown error message was: '${thrownErrorMessage}'.`;
86
+ },
87
+
88
+ "invalid-cache-name": ({ cacheNameId, value }) => {
89
+ if (!cacheNameId) {
90
+ throw new Error(`Expected a 'cacheNameId' for error 'invalid-cache-name'`);
91
+ }
92
+
93
+ return `You must provide a name containing at least one character for setCacheDetails({${cacheNameId}: '...'}). Received a value of '${JSON.stringify(
94
+ value,
95
+ )}'`;
96
+ },
97
+
98
+ "unregister-route-but-not-found-with-method": ({ method }) => {
99
+ if (!method) {
100
+ throw new Error("Unexpected input to " + `'unregister-route-but-not-found-with-method' error.`);
101
+ }
102
+
103
+ return `The route you're trying to unregister was not previously registered for the method type '${method}'.`;
104
+ },
105
+
106
+ "unregister-route-route-not-registered": () => {
107
+ return `The route you're trying to unregister was not previously ` + "registered.";
108
+ },
109
+
110
+ "queue-replay-failed": ({ name }) => {
111
+ return `Replaying the background sync queue '${name}' failed.`;
112
+ },
113
+
114
+ "duplicate-queue-name": ({ name }) => {
115
+ return `The Queue name '${name}' is already being used. All instances of backgroundSync.Queue must be given unique names.`;
116
+ },
117
+
118
+ "expired-test-without-max-age": ({ methodName, paramName }) => {
119
+ return `The '${methodName}()' method can only be used when the ` + `'${paramName}' is used in the constructor.`;
120
+ },
121
+
122
+ "unsupported-route-type": ({ moduleName, className, funcName, paramName }) => {
123
+ return `The supplied '${paramName}' parameter was an unsupported type. Please check the docs for ${moduleName}.${className}.${funcName} for valid input types.`;
124
+ },
125
+
126
+ "not-array-of-class": ({ value, expectedClass, moduleName, className, funcName, paramName }) => {
127
+ return `The supplied '${paramName}' parameter must be an array of '${expectedClass}' objects. Received '${JSON.stringify(
128
+ value,
129
+ )},'. Please check the call to ${moduleName}.${className}.${funcName}() to fix the issue.`;
130
+ },
131
+
132
+ "max-entries-or-age-required": ({ moduleName, className, funcName }) => {
133
+ return `You must define either config.maxEntries or config.maxAgeSecondsin ${moduleName}.${className}.${funcName}`;
134
+ },
135
+
136
+ "statuses-or-headers-required": ({ moduleName, className, funcName }) => {
137
+ return `You must define either config.statuses or config.headersin ${moduleName}.${className}.${funcName}`;
138
+ },
139
+
140
+ "invalid-string": ({ moduleName, funcName, paramName }) => {
141
+ if (!paramName || !moduleName || !funcName) {
142
+ throw new Error(`Unexpected input to 'invalid-string' error.`);
143
+ }
144
+ 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.`;
145
+ },
146
+
147
+ "channel-name-required": () => {
148
+ return "You must provide a channelName to construct a " + "BroadcastCacheUpdate instance.";
149
+ },
150
+
151
+ "invalid-responses-are-same-args": () => {
152
+ return "The arguments passed into responsesAreSame() appear to be " + "invalid. Please ensure valid Responses are used.";
153
+ },
154
+
155
+ "expire-custom-caches-only": () => {
156
+ return `You must provide a 'cacheName' property when using the ` + "expiration plugin with a runtime caching strategy.";
157
+ },
158
+
159
+ "unit-must-be-bytes": ({ normalizedRangeHeader }) => {
160
+ if (!normalizedRangeHeader) {
161
+ throw new Error(`Unexpected input to 'unit-must-be-bytes' error.`);
162
+ }
163
+ return `The 'unit' portion of the Range header must be set to 'bytes'. The Range header provided was "${normalizedRangeHeader}"`;
164
+ },
165
+
166
+ "single-range-only": ({ normalizedRangeHeader }) => {
167
+ if (!normalizedRangeHeader) {
168
+ throw new Error(`Unexpected input to 'single-range-only' error.`);
169
+ }
170
+ return `Multiple ranges are not supported. Please use a single start value, and optional end value. The Range header provided was "${normalizedRangeHeader}"`;
171
+ },
172
+
173
+ "invalid-range-values": ({ normalizedRangeHeader }) => {
174
+ if (!normalizedRangeHeader) {
175
+ throw new Error(`Unexpected input to 'invalid-range-values' error.`);
176
+ }
177
+ 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}"`;
178
+ },
179
+
180
+ "no-range-header": () => {
181
+ return "No Range header was found in the Request provided.";
182
+ },
183
+
184
+ "range-not-satisfiable": ({ size, start, end }) => {
185
+ return `The start (${start}) and end (${end}) values in the Range are ` + `not satisfiable by the cached response, which is ${size} bytes.`;
186
+ },
187
+
188
+ "attempt-to-cache-non-get-request": ({ url, method }) => {
189
+ return `Unable to cache '${url}' because it is a '${method}' request and only 'GET' requests can be cached.`;
190
+ },
191
+
192
+ "cache-put-with-no-response": ({ url }) => {
193
+ return `There was an attempt to cache '${url}' but the response was not defined.`;
194
+ },
195
+
196
+ "no-response": ({ url, error }) => {
197
+ let message = `The strategy could not generate a response for '${url}'.`;
198
+ if (error) {
199
+ message += ` The underlying error is ${error}.`;
200
+ }
201
+ return message;
202
+ },
203
+
204
+ "bad-precaching-response": ({ url, status }) => {
205
+ return `The precaching request for '${url}' failed${status ? ` with an HTTP status of ${status}.` : "."}`;
206
+ },
207
+
208
+ "non-precached-url": ({ url }) => {
209
+ return `createHandlerBoundToURL('${url}') was called, but that URL is not precached. Please pass in a URL that is precached instead.`;
210
+ },
211
+
212
+ "add-to-cache-list-conflicting-integrities": ({ url }) => {
213
+ return `Two of the entries passed to '@serwist/precaching.PrecacheController.addToCacheList()' had the URL ${url} with different integrity values. Please remove one of them.`;
214
+ },
215
+
216
+ "missing-precache-entry": ({ cacheName, url }) => {
217
+ return `Unable to find a precached response in ${cacheName} for ${url}.`;
218
+ },
219
+
220
+ "cross-origin-copy-response": ({ origin }) => {
221
+ return `@serwist/core.copyResponse() can only be used with same-origin responses. It was passed a response with origin ${origin}.`;
222
+ },
223
+
224
+ "opaque-streams-source": ({ type }) => {
225
+ const message = `One of the @serwist/streams sources resulted in an '${type}' response.`;
226
+ if (type === "opaqueredirect") {
227
+ return `${message} Please do not use a navigation request that results in a redirect as a source.`;
228
+ }
229
+ return `${message} Please ensure your sources are CORS-enabled.`;
230
+ },
231
+ };
@@ -0,0 +1,17 @@
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
+ export enum pluginEvents {
10
+ CACHE_DID_UPDATE = "cacheDidUpdate",
11
+ CACHE_KEY_WILL_BE_USED = "cacheKeyWillBeUsed",
12
+ CACHE_WILL_UPDATE = "cacheWillUpdate",
13
+ CACHED_RESPONSE_WILL_BE_USED = "cachedResponseWillBeUsed",
14
+ FETCH_DID_FAIL = "fetchDidFail",
15
+ FETCH_DID_SUCCEED = "fetchDidSucceed",
16
+ REQUEST_WILL_FETCH = "requestWillFetch",
17
+ }
@@ -0,0 +1,13 @@
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
+ // Callbacks to be executed whenever there's a quota error.
10
+ // biome-ignore lint/complexity/noBannedTypes: Can't change Function type right now.
11
+ const quotaErrorCallbacks: Set<Function> = new Set();
12
+
13
+ export { quotaErrorCallbacks };
@@ -0,0 +1,36 @@
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 { assert } from "./_private/assert.js";
10
+ import { logger } from "./_private/logger.js";
11
+ import { quotaErrorCallbacks } from "./models/quotaErrorCallbacks.js";
12
+
13
+ /**
14
+ * Adds a function to the set of quotaErrorCallbacks that will be executed if
15
+ * there's a quota error.
16
+ *
17
+ * @param callback
18
+ */
19
+ // biome-ignore lint/complexity/noBannedTypes: Can't change Function type
20
+ function registerQuotaErrorCallback(callback: Function): void {
21
+ if (process.env.NODE_ENV !== "production") {
22
+ assert!.isType(callback, "function", {
23
+ moduleName: "@serwist/core",
24
+ funcName: "register",
25
+ paramName: "callback",
26
+ });
27
+ }
28
+
29
+ quotaErrorCallbacks.add(callback);
30
+
31
+ if (process.env.NODE_ENV !== "production") {
32
+ logger.log("Registered a callback to respond to quota errors.", callback);
33
+ }
34
+ }
35
+
36
+ export { registerQuotaErrorCallback };
@@ -0,0 +1,55 @@
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 { assert } from "./_private/assert.js";
11
+ import type { PartialCacheNameDetails } from "./_private/cacheNames.js";
12
+ import { cacheNames } from "./_private/cacheNames.js";
13
+
14
+ /**
15
+ * Modifies the default cache names used by the Serwist packages.
16
+ * Cache names are generated as `<prefix>-<Cache Name>-<suffix>`.
17
+ *
18
+ * @param details
19
+ */
20
+ function setCacheNameDetails(details: PartialCacheNameDetails): void {
21
+ if (process.env.NODE_ENV !== "production") {
22
+ for (const key of Object.keys(details)) {
23
+ assert!.isType(details[key], "string", {
24
+ moduleName: "@serwist/core",
25
+ funcName: "setCacheNameDetails",
26
+ paramName: `details.${key}`,
27
+ });
28
+ }
29
+
30
+ if (details.precache?.length === 0) {
31
+ throw new SerwistError("invalid-cache-name", {
32
+ cacheNameId: "precache",
33
+ value: details.precache,
34
+ });
35
+ }
36
+
37
+ if (details.runtime?.length === 0) {
38
+ throw new SerwistError("invalid-cache-name", {
39
+ cacheNameId: "runtime",
40
+ value: details.runtime,
41
+ });
42
+ }
43
+
44
+ if (details.googleAnalytics?.length === 0) {
45
+ throw new SerwistError("invalid-cache-name", {
46
+ cacheNameId: "googleAnalytics",
47
+ value: details.googleAnalytics,
48
+ });
49
+ }
50
+ }
51
+
52
+ cacheNames.updateDetails(details);
53
+ }
54
+
55
+ export { setCacheNameDetails };
package/src/types.ts ADDED
@@ -0,0 +1,315 @@
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
+ export interface MapLikeObject {
10
+ [key: string]: any;
11
+ }
12
+
13
+ /**
14
+ * Using a plain `MapLikeObject` for now, but could extend/restrict this
15
+ * in the future.
16
+ */
17
+ export type PluginState = MapLikeObject;
18
+
19
+ /**
20
+ * Options passed to a `RouteMatchCallback` function.
21
+ */
22
+ export interface RouteMatchCallbackOptions {
23
+ event: ExtendableEvent;
24
+ request: Request;
25
+ sameOrigin: boolean;
26
+ url: URL;
27
+ }
28
+
29
+ /**
30
+ * The "match" callback is used to determine if a `Route` should apply for a
31
+ * particular URL and request. When matching occurs in response to a fetch
32
+ * event from the client, the `event` object is also supplied. However, since
33
+ * the match callback can be invoked outside of a fetch event, matching logic
34
+ * should not assume the `event` object will always be available.
35
+ * If the match callback returns a truthy value, the matching route's
36
+ * `RouteHandlerCallback` will be invoked immediately. If the value returned
37
+ * is a non-empty array or object, that value will be set on the handler's
38
+ * `options.params` argument.
39
+ */
40
+ export interface RouteMatchCallback {
41
+ (options: RouteMatchCallbackOptions): any;
42
+ }
43
+
44
+ /**
45
+ * Options passed to a `RouteHandlerCallback` function.
46
+ */
47
+ export declare interface RouteHandlerCallbackOptions {
48
+ /**
49
+ * The event associated with the request.
50
+ */
51
+ event: ExtendableEvent;
52
+ /**
53
+ * A request to run this strategy for.
54
+ */
55
+ request: Request;
56
+ url: URL;
57
+ /**
58
+ * The return value from `@serwist/routing`'s `matchCallback` (if applicable).
59
+ */
60
+ params?: string[] | MapLikeObject;
61
+ }
62
+ /**
63
+ * Options passed to a `ManualHandlerCallback` function.
64
+ */
65
+ export interface ManualHandlerCallbackOptions {
66
+ /**
67
+ * The event associated with the request.
68
+ */
69
+ event: ExtendableEvent;
70
+ /**
71
+ * A request to run this strategy for.
72
+ */
73
+ request: Request | string;
74
+ }
75
+
76
+ export type HandlerCallbackOptions = RouteHandlerCallbackOptions | ManualHandlerCallbackOptions;
77
+
78
+ /**
79
+ * The "handler" callback is invoked whenever a `Router` matches a URL/Request
80
+ * to a `Route` via its `RouteMatchCallback`. This handler callback should
81
+ * return a `Promise` that resolves with a `Response`.
82
+ *
83
+ * If a non-empty array or object is returned by the `RouteMatchCallback` it
84
+ * will be passed in as this handler's `options.params` argument.
85
+ */
86
+ export interface RouteHandlerCallback {
87
+ (options: RouteHandlerCallbackOptions): Promise<Response>;
88
+ }
89
+
90
+ /**
91
+ * The "handler" callback is invoked whenever a `Router` matches a URL/Request
92
+ * to a `Route` via its `RouteMatchCallback`. This handler callback should
93
+ * return a `Promise` that resolves with a `Response`.
94
+ *
95
+ * If a non-empty array or object is returned by the `RouteMatchCallback` it
96
+ * will be passed in as this handler's `options.params` argument.
97
+ */
98
+ export interface ManualHandlerCallback {
99
+ (options: ManualHandlerCallbackOptions): Promise<Response>;
100
+ }
101
+
102
+ /**
103
+ * An object with a `handle` method of type `RouteHandlerCallback`.
104
+ *
105
+ * A `Route` object can be created with either an `RouteHandlerCallback`
106
+ * function or this `RouteHandler` object. The benefit of the `RouteHandler`
107
+ * is it can be extended (as is done by the `@serwist/strategies` package).
108
+ */
109
+ export interface RouteHandlerObject {
110
+ handle: RouteHandlerCallback;
111
+ }
112
+
113
+ /**
114
+ * Either a `RouteHandlerCallback` or a `RouteHandlerObject`.
115
+ * Most APIs in `@serwist/routing` that accept route handlers take either.
116
+ */
117
+ export type RouteHandler = RouteHandlerCallback | RouteHandlerObject;
118
+
119
+ export interface HandlerWillStartCallbackParam {
120
+ request: Request;
121
+ event: ExtendableEvent;
122
+ state?: PluginState;
123
+ }
124
+
125
+ export interface HandlerWillStartCallback {
126
+ (param: HandlerWillStartCallbackParam): Promise<any>;
127
+ }
128
+
129
+ export interface CacheDidUpdateCallbackParam {
130
+ /**
131
+ * Name of the cache the responses belong to. This is included in the
132
+ * broadcast message.
133
+ */
134
+ cacheName: string;
135
+ /**
136
+ * Possibly updated response to compare.
137
+ */
138
+ newResponse: Response;
139
+ /**
140
+ * The `Request` object for the cached entry.
141
+ */
142
+ request: Request;
143
+ /**
144
+ * The event that triggered this possible cache update.
145
+ */
146
+ event: ExtendableEvent;
147
+ /**
148
+ * Cached response to compare.
149
+ */
150
+ oldResponse?: Response | null;
151
+ state?: PluginState;
152
+ }
153
+
154
+ export interface CacheDidUpdateCallback {
155
+ (param: CacheDidUpdateCallbackParam): Promise<any>;
156
+ }
157
+
158
+ export interface CacheKeyWillBeUsedCallbackParam {
159
+ mode: string;
160
+ request: Request;
161
+ event: ExtendableEvent;
162
+ params?: any;
163
+ state?: PluginState;
164
+ }
165
+
166
+ export interface CacheKeyWillBeUsedCallback {
167
+ (param: CacheKeyWillBeUsedCallbackParam): Promise<Request | string>;
168
+ }
169
+
170
+ export interface CacheWillUpdateCallbackParam {
171
+ request: Request;
172
+ response: Response;
173
+ event: ExtendableEvent;
174
+ state?: PluginState;
175
+ }
176
+
177
+ export interface CacheWillUpdateCallback {
178
+ (param: CacheWillUpdateCallbackParam): Promise<any>;
179
+ }
180
+
181
+ export interface CachedResponseWillBeUsedCallbackParam {
182
+ /**
183
+ * Name of the cache the response is in.
184
+ */
185
+ cacheName: string;
186
+ /**
187
+ * The original request, which may or may not
188
+ * contain a Range: header.
189
+ */
190
+ request: Request;
191
+ /**
192
+ * The complete cached `Response` object that's been read
193
+ * from a cache and whose freshness should be checked.
194
+ */
195
+ cachedResponse?: Response;
196
+ event: ExtendableEvent;
197
+ matchOptions?: CacheQueryOptions;
198
+ state?: PluginState;
199
+ }
200
+
201
+ export interface CachedResponseWillBeUsedCallback {
202
+ (param: CachedResponseWillBeUsedCallbackParam): Promise<any>;
203
+ }
204
+
205
+ export interface FetchDidFailCallbackParam {
206
+ error: Error;
207
+ originalRequest: Request;
208
+ request: Request;
209
+ event: ExtendableEvent;
210
+ state?: PluginState;
211
+ }
212
+
213
+ export interface FetchDidFailCallback {
214
+ (param: FetchDidFailCallbackParam): Promise<any>;
215
+ }
216
+
217
+ export interface FetchDidSucceedCallbackParam {
218
+ request: Request;
219
+ response: Response;
220
+ event: ExtendableEvent;
221
+ state?: PluginState;
222
+ }
223
+
224
+ export interface FetchDidSucceedCallback {
225
+ (param: FetchDidSucceedCallbackParam): Promise<Response>;
226
+ }
227
+
228
+ export interface RequestWillFetchCallbackParam {
229
+ request: Request;
230
+ event: ExtendableEvent;
231
+ state?: PluginState;
232
+ }
233
+
234
+ export interface RequestWillFetchCallback {
235
+ (param: RequestWillFetchCallbackParam): Promise<Request>;
236
+ }
237
+
238
+ export interface HandlerWillRespondCallbackParam {
239
+ request: Request;
240
+ response: Response;
241
+ event: ExtendableEvent;
242
+ state?: PluginState;
243
+ }
244
+
245
+ export interface HandlerWillRespondCallback {
246
+ (param: HandlerWillRespondCallbackParam): Promise<Response>;
247
+ }
248
+
249
+ export interface HandlerDidErrorCallbackParam {
250
+ request: Request;
251
+ event: ExtendableEvent;
252
+ error: Error;
253
+ state?: PluginState;
254
+ }
255
+
256
+ export interface HandlerDidErrorCallback {
257
+ (param: HandlerDidErrorCallbackParam): Promise<Response | undefined>;
258
+ }
259
+
260
+ export interface HandlerDidRespondCallbackParam {
261
+ request: Request;
262
+ event: ExtendableEvent;
263
+ response?: Response;
264
+ state?: PluginState;
265
+ }
266
+
267
+ export interface HandlerDidRespondCallback {
268
+ (param: HandlerDidRespondCallbackParam): Promise<any>;
269
+ }
270
+
271
+ export interface HandlerDidCompleteCallbackParam {
272
+ request: Request;
273
+ error?: Error;
274
+ event: ExtendableEvent;
275
+ response?: Response;
276
+ state?: PluginState;
277
+ }
278
+
279
+ export interface HandlerDidCompleteCallback {
280
+ (param: HandlerDidCompleteCallbackParam): Promise<any>;
281
+ }
282
+
283
+ /**
284
+ * An object with optional lifecycle callback properties for the fetch and
285
+ * cache operations.
286
+ */
287
+ export declare interface SerwistPlugin {
288
+ cacheDidUpdate?: CacheDidUpdateCallback;
289
+ cachedResponseWillBeUsed?: CachedResponseWillBeUsedCallback;
290
+ cacheKeyWillBeUsed?: CacheKeyWillBeUsedCallback;
291
+ cacheWillUpdate?: CacheWillUpdateCallback;
292
+ fetchDidFail?: FetchDidFailCallback;
293
+ fetchDidSucceed?: FetchDidSucceedCallback;
294
+ handlerDidComplete?: HandlerDidCompleteCallback;
295
+ handlerDidError?: HandlerDidErrorCallback;
296
+ handlerDidRespond?: HandlerDidRespondCallback;
297
+ handlerWillRespond?: HandlerWillRespondCallback;
298
+ handlerWillStart?: HandlerWillStartCallback;
299
+ requestWillFetch?: RequestWillFetchCallback;
300
+ }
301
+
302
+ export interface SerwistPluginCallbackParam {
303
+ cacheDidUpdate: CacheDidUpdateCallbackParam;
304
+ cachedResponseWillBeUsed: CachedResponseWillBeUsedCallbackParam;
305
+ cacheKeyWillBeUsed: CacheKeyWillBeUsedCallbackParam;
306
+ cacheWillUpdate: CacheWillUpdateCallbackParam;
307
+ fetchDidFail: FetchDidFailCallbackParam;
308
+ fetchDidSucceed: FetchDidSucceedCallbackParam;
309
+ handlerDidComplete: HandlerDidCompleteCallbackParam;
310
+ handlerDidError: HandlerDidErrorCallbackParam;
311
+ handlerDidRespond: HandlerDidRespondCallbackParam;
312
+ handlerWillRespond: HandlerWillRespondCallbackParam;
313
+ handlerWillStart: HandlerWillStartCallbackParam;
314
+ requestWillFetch: RequestWillFetchCallbackParam;
315
+ }
@@ -0,0 +1,15 @@
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 type { SerwistPlugin } from "../types.js";
10
+
11
+ export const pluginUtils = {
12
+ filter: (plugins: SerwistPlugin[], callbackName: string): SerwistPlugin[] => {
13
+ return plugins.filter((plugin) => callbackName in plugin);
14
+ },
15
+ };