@serwist/strategies 9.0.0-preview.16 → 9.0.0-preview.18

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@serwist/strategies",
3
- "version": "9.0.0-preview.16",
3
+ "version": "9.0.0-preview.18",
4
4
  "type": "module",
5
5
  "description": "A service worker helper library implementing common caching strategies.",
6
6
  "files": [
@@ -30,12 +30,12 @@
30
30
  "./package.json": "./package.json"
31
31
  },
32
32
  "dependencies": {
33
- "@serwist/core": "9.0.0-preview.16"
33
+ "@serwist/sw": "9.0.0-preview.18"
34
34
  },
35
35
  "devDependencies": {
36
36
  "rollup": "4.13.0",
37
37
  "typescript": "5.5.0-dev.20240323",
38
- "@serwist/constants": "9.0.0-preview.16"
38
+ "@serwist/constants": "9.0.0-preview.18"
39
39
  },
40
40
  "peerDependencies": {
41
41
  "typescript": ">=5.0.0"
package/src/index.ts CHANGED
@@ -1,34 +1,2 @@
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 { CacheFirst } from "./CacheFirst.js";
10
- import { CacheOnly } from "./CacheOnly.js";
11
- import type { NetworkFirstOptions } from "./NetworkFirst.js";
12
- import { NetworkFirst } from "./NetworkFirst.js";
13
- import type { NetworkOnlyOptions } from "./NetworkOnly.js";
14
- import { NetworkOnly } from "./NetworkOnly.js";
15
- import { StaleWhileRevalidate } from "./StaleWhileRevalidate.js";
16
- import type { StrategyOptions } from "./Strategy.js";
17
- import { Strategy } from "./Strategy.js";
18
- import { StrategyHandler } from "./StrategyHandler.js";
19
-
20
- // See https://github.com/GoogleChrome/workbox/issues/2946
21
- declare global {
22
- interface FetchEvent {
23
- // See https://github.com/GoogleChrome/workbox/issues/2974
24
- readonly preloadResponse: Promise<any>;
25
- }
26
- }
27
-
28
- /**
29
- * There are common caching strategies that most service workers will need
30
- * and use. This module provides simple implementations of these strategies.
31
- */
32
- export { CacheFirst, CacheOnly, NetworkFirst, NetworkOnly, StaleWhileRevalidate, Strategy, StrategyHandler };
33
-
34
- export type { NetworkFirstOptions, NetworkOnlyOptions, StrategyOptions };
1
+ export { CacheFirst, CacheOnly, NetworkFirst, NetworkOnly, StaleWhileRevalidate, Strategy, StrategyHandler } from "@serwist/sw/strategies";
2
+ export type { NetworkFirstOptions, NetworkOnlyOptions, StrategyOptions } from "@serwist/sw/strategies";
@@ -1,23 +0,0 @@
1
- import { Strategy } from "./Strategy.js";
2
- import type { StrategyHandler } from "./StrategyHandler.js";
3
- /**
4
- * An implementation of the [cache first](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#cache_first_falling_back_to_network)
5
- * request strategy.
6
- *
7
- * A cache first strategy is useful for assets that have been revisioned,
8
- * such as URLs like `/styles/example.a8f5f1.css`, since they
9
- * can be cached for long periods of time.
10
- *
11
- * If the network request fails, and there is no cache match, this will throw
12
- * a `SerwistError` exception.
13
- */
14
- export declare class CacheFirst extends Strategy {
15
- /**
16
- * @private
17
- * @param request A request to run this strategy for.
18
- * @param handler The event that triggered the request.
19
- * @returns
20
- */
21
- _handle(request: Request, handler: StrategyHandler): Promise<Response>;
22
- }
23
- //# sourceMappingURL=CacheFirst.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"CacheFirst.d.ts","sourceRoot":"","sources":["../src/CacheFirst.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAG5D;;;;;;;;;;GAUG;AACH,qBAAa,UAAW,SAAQ,QAAQ;IACtC;;;;;OAKG;IACG,OAAO,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,QAAQ,CAAC;CAsD7E"}
@@ -1,20 +0,0 @@
1
- import { Strategy } from "./Strategy.js";
2
- import type { StrategyHandler } from "./StrategyHandler.js";
3
- /**
4
- * An implementation of the [cache only](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#cache-only)
5
- * request strategy.
6
- *
7
- * This class is useful if you want to take advantage of any Serwist plugin.
8
- *
9
- * If there is no cache match, this will throw a `SerwistError` exception.
10
- */
11
- export declare class CacheOnly extends Strategy {
12
- /**
13
- * @private
14
- * @param request A request to run this strategy for.
15
- * @param handler The event that triggered the request.
16
- * @returns
17
- */
18
- _handle(request: Request, handler: StrategyHandler): Promise<Response>;
19
- }
20
- //# sourceMappingURL=CacheOnly.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"CacheOnly.d.ts","sourceRoot":"","sources":["../src/CacheOnly.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAG5D;;;;;;;GAOG;AACH,qBAAa,SAAU,SAAQ,QAAQ;IACrC;;;;;OAKG;IACG,OAAO,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,QAAQ,CAAC;CA4B7E"}
@@ -1,61 +0,0 @@
1
- import type { StrategyOptions } from "./Strategy.js";
2
- import { Strategy } from "./Strategy.js";
3
- import type { StrategyHandler } from "./StrategyHandler.js";
4
- export interface NetworkFirstOptions extends StrategyOptions {
5
- /**
6
- * If set, any network requests that fail to respond within the timeout will fallback to the cache.
7
- */
8
- networkTimeoutSeconds?: number;
9
- }
10
- /**
11
- * An implementation of the [network first](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#network-first-falling-back-to-cache)
12
- * request strategy.
13
- *
14
- * By default, this strategy will cache responses with a 200 status code as
15
- * well as [opaque responses](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses).
16
- * Opaque responses are are cross-origin requests where the response doesn't
17
- * support [CORS](https://enable-cors.org/).
18
- *
19
- * If the network request fails, and there is no cache match, this will throw
20
- * a `SerwistError` exception.
21
- */
22
- export declare class NetworkFirst extends Strategy {
23
- private readonly _networkTimeoutSeconds;
24
- /**
25
- * @param options
26
- * This option can be used to combat
27
- * "[lie-fi](https://developers.google.com/web/fundamentals/performance/poor-connectivity/#lie-fi)"
28
- * scenarios.
29
- */
30
- constructor(options?: NetworkFirstOptions);
31
- /**
32
- * @private
33
- * @param request A request to run this strategy for.
34
- * @param handler The event that triggered the request.
35
- * @returns
36
- */
37
- _handle(request: Request, handler: StrategyHandler): Promise<Response>;
38
- /**
39
- * @param options
40
- * @returns
41
- * @private
42
- */
43
- private _getTimeoutPromise;
44
- /**
45
- * @param options
46
- * @param options.timeoutId
47
- * @param options.request
48
- * @param options.logs A reference to the logs Array.
49
- * @param options.event
50
- * @returns
51
- *
52
- * @private
53
- */
54
- _getNetworkPromise({ timeoutId, request, logs, handler, }: {
55
- request: Request;
56
- logs: any[];
57
- timeoutId?: number;
58
- handler: StrategyHandler;
59
- }): Promise<Response | undefined>;
60
- }
61
- //# sourceMappingURL=NetworkFirst.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"NetworkFirst.d.ts","sourceRoot":"","sources":["../src/NetworkFirst.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAI5D,MAAM,WAAW,mBAAoB,SAAQ,eAAe;IAC1D;;OAEG;IACH,qBAAqB,CAAC,EAAE,MAAM,CAAC;CAChC;AAED;;;;;;;;;;;GAWG;AACH,qBAAa,YAAa,SAAQ,QAAQ;IACxC,OAAO,CAAC,QAAQ,CAAC,sBAAsB,CAAS;IAChD;;;;;OAKG;gBACS,OAAO,GAAE,mBAAwB;IAsB7C;;;;;OAKG;IACG,OAAO,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,QAAQ,CAAC;IAgE5E;;;;OAIG;IACH,OAAO,CAAC,kBAAkB;IA8B1B;;;;;;;;;OASG;IACG,kBAAkB,CAAC,EACvB,SAAS,EACT,OAAO,EACP,IAAI,EACJ,OAAO,GACR,EAAE;QACD,OAAO,EAAE,OAAO,CAAC;QACjB,IAAI,EAAE,GAAG,EAAE,CAAC;QACZ,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,OAAO,EAAE,eAAe,CAAC;KAC1B,GAAG,OAAO,CAAC,QAAQ,GAAG,SAAS,CAAC;CAqClC"}
@@ -1,32 +0,0 @@
1
- import type { StrategyOptions } from "./Strategy.js";
2
- import { Strategy } from "./Strategy.js";
3
- import type { StrategyHandler } from "./StrategyHandler.js";
4
- export interface NetworkOnlyOptions extends Omit<StrategyOptions, "cacheName" | "matchOptions"> {
5
- /**
6
- * If set, any network requests that fail to respond within the timeout will result in a network error.
7
- */
8
- networkTimeoutSeconds?: number;
9
- }
10
- /**
11
- * An implementation of the [network only](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#network-only)
12
- * request strategy.
13
- *
14
- * This class is useful if you want to take advantage of any Serwist plugin.
15
- *
16
- * If the network request fails, this will throw a `SerwistError` exception.
17
- */
18
- export declare class NetworkOnly extends Strategy {
19
- private readonly _networkTimeoutSeconds;
20
- /**
21
- * @param options
22
- */
23
- constructor(options?: NetworkOnlyOptions);
24
- /**
25
- * @private
26
- * @param request A request to run this strategy for.
27
- * @param handler The event that triggered the request.
28
- * @returns
29
- */
30
- _handle(request: Request, handler: StrategyHandler): Promise<Response>;
31
- }
32
- //# sourceMappingURL=NetworkOnly.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"NetworkOnly.d.ts","sourceRoot":"","sources":["../src/NetworkOnly.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAG5D,MAAM,WAAW,kBAAmB,SAAQ,IAAI,CAAC,eAAe,EAAE,WAAW,GAAG,cAAc,CAAC;IAC7F;;OAEG;IACH,qBAAqB,CAAC,EAAE,MAAM,CAAC;CAChC;AAED;;;;;;;GAOG;AACH,qBAAa,WAAY,SAAQ,QAAQ;IACvC,OAAO,CAAC,QAAQ,CAAC,sBAAsB,CAAS;IAEhD;;OAEG;gBACS,OAAO,GAAE,kBAAuB;IAM5C;;;;;OAKG;IACG,OAAO,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,QAAQ,CAAC;CA+C7E"}
@@ -1,35 +0,0 @@
1
- import type { StrategyOptions } from "./Strategy.js";
2
- import { Strategy } from "./Strategy.js";
3
- import type { StrategyHandler } from "./StrategyHandler.js";
4
- /**
5
- * An implementation of the
6
- * [stale-while-revalidate](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#stale-while-revalidate)
7
- * request strategy.
8
- *
9
- * Resources are requested from both the cache and the network in parallel.
10
- * The strategy will respond with the cached version if available, otherwise
11
- * wait for the network response. The cache is updated with the network response
12
- * with each successful request.
13
- *
14
- * By default, this strategy will cache responses with a 200 status code as
15
- * well as [opaque responses](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses).
16
- * Opaque responses are cross-origin requests where the response doesn't
17
- * support [CORS](https://enable-cors.org/).
18
- *
19
- * If the network request fails, and there is no cache match, this will throw
20
- * a `SerwistError` exception.
21
- */
22
- export declare class StaleWhileRevalidate extends Strategy {
23
- /**
24
- * @param options
25
- */
26
- constructor(options?: StrategyOptions);
27
- /**
28
- * @private
29
- * @param request A request to run this strategy for.
30
- * @param handler The event that triggered the request.
31
- * @returns
32
- */
33
- _handle(request: Request, handler: StrategyHandler): Promise<Response>;
34
- }
35
- //# sourceMappingURL=StaleWhileRevalidate.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"StaleWhileRevalidate.d.ts","sourceRoot":"","sources":["../src/StaleWhileRevalidate.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAI5D;;;;;;;;;;;;;;;;;GAiBG;AACH,qBAAa,oBAAqB,SAAQ,QAAQ;IAChD;;OAEG;gBACS,OAAO,GAAE,eAAoB;IAUzC;;;;;OAKG;IACG,OAAO,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,QAAQ,CAAC;CAsD7E"}
@@ -1,83 +0,0 @@
1
- import type { HandlerCallbackOptions, RouteHandlerObject, SerwistPlugin } from "@serwist/core";
2
- import { StrategyHandler } from "./StrategyHandler.js";
3
- export interface StrategyOptions {
4
- /**
5
- * Cache name to store and retrieve requests. Defaults to cache names provided by `@serwist/core`.
6
- */
7
- cacheName?: string;
8
- /**
9
- * [Plugins](https://developer.chrome.com/docs/workbox/using-plugins)
10
- * to use in conjunction with this caching strategy.
11
- */
12
- plugins?: SerwistPlugin[];
13
- /**
14
- * Values passed along to the [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)
15
- * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796) `fetch()` requests made by this strategy.
16
- */
17
- fetchOptions?: RequestInit;
18
- /**
19
- * The [`CacheQueryOptions`](https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions)
20
- * for any `cache.match()` or `cache.put()` calls made by this strategy.
21
- */
22
- matchOptions?: CacheQueryOptions;
23
- }
24
- /**
25
- * Classes extending the `Strategy` based class should implement this method,
26
- * and leverage `@serwist/strategies`'s `StrategyHandler` arg to perform all
27
- * fetching and cache logic, which will ensure all relevant cache, cache options,
28
- * fetch options and plugins are used (per the current strategy instance).
29
- */
30
- export declare abstract class Strategy implements RouteHandlerObject {
31
- cacheName: string;
32
- plugins: SerwistPlugin[];
33
- fetchOptions?: RequestInit;
34
- matchOptions?: CacheQueryOptions;
35
- protected abstract _handle(request: Request, handler: StrategyHandler): Promise<Response | undefined>;
36
- /**
37
- * Creates a new instance of the strategy and sets all documented option
38
- * properties as public instance properties.
39
- *
40
- * Note: if a custom strategy class extends the base Strategy class and does
41
- * not need more than these properties, it does not need to define its own
42
- * constructor.
43
- *
44
- * @param options
45
- */
46
- constructor(options?: StrategyOptions);
47
- /**
48
- * Perform a request strategy and returns a `Promise` that will resolve with
49
- * a `Response`, invoking all relevant plugin callbacks.
50
- *
51
- * When a strategy instance is registered with a `@serwist/routing` Route, this method is automatically
52
- * called when the route matches.
53
- *
54
- * Alternatively, this method can be used in a standalone `FetchEvent`
55
- * listener by passing it to `event.respondWith()`.
56
- *
57
- * @param options A `FetchEvent` or an object with the properties listed below.
58
- * @param options.request A request to run this strategy for.
59
- * @param options.event The event associated with the request.
60
- * @param options.url
61
- * @param options.params
62
- */
63
- handle(options: FetchEvent | HandlerCallbackOptions): Promise<Response>;
64
- /**
65
- * Similar to `@serwist/strategies`'s `Strategy.handle`, but
66
- * instead of just returning a `Promise` that resolves to a `Response` it
67
- * it will return an tuple of `[response, done]` promises, where the former
68
- * (`response`) is equivalent to what `handle()` returns, and the latter is a
69
- * Promise that will resolve once any promises that were added to
70
- * `event.waitUntil()` as part of performing the strategy have completed.
71
- *
72
- * You can await the `done` promise to ensure any extra work performed by
73
- * the strategy (usually caching responses) completes successfully.
74
- *
75
- * @param options A `FetchEvent` or `HandlerCallbackOptions` object.
76
- * @returns A tuple of [response, done] promises that can be used to determine when the response resolves as
77
- * well as when the handler has completed all its work.
78
- */
79
- handleAll(options: FetchEvent | HandlerCallbackOptions): [Promise<Response>, Promise<void>];
80
- _getResponse(handler: StrategyHandler, request: Request, event: ExtendableEvent): Promise<Response>;
81
- _awaitComplete(responseDone: Promise<Response>, handler: StrategyHandler, request: Request, event: ExtendableEvent): Promise<void>;
82
- }
83
- //# sourceMappingURL=Strategy.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"Strategy.d.ts","sourceRoot":"","sources":["../src/Strategy.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAG/F,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAEvD,MAAM,WAAW,eAAe;IAC9B;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;OAGG;IACH,OAAO,CAAC,EAAE,aAAa,EAAE,CAAC;IAC1B;;;OAGG;IACH,YAAY,CAAC,EAAE,WAAW,CAAC;IAC3B;;;OAGG;IACH,YAAY,CAAC,EAAE,iBAAiB,CAAC;CAClC;AAED;;;;;GAKG;AACH,8BAAsB,QAAS,YAAW,kBAAkB;IAC1D,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,aAAa,EAAE,CAAC;IACzB,YAAY,CAAC,EAAE,WAAW,CAAC;IAC3B,YAAY,CAAC,EAAE,iBAAiB,CAAC;IAEjC,SAAS,CAAC,QAAQ,CAAC,OAAO,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,QAAQ,GAAG,SAAS,CAAC;IAErG;;;;;;;;;OASG;gBACS,OAAO,GAAE,eAAoB;IAOzC;;;;;;;;;;;;;;;OAeG;IACH,MAAM,CAAC,OAAO,EAAE,UAAU,GAAG,sBAAsB,GAAG,OAAO,CAAC,QAAQ,CAAC;IAKvE;;;;;;;;;;;;;;OAcG;IACH,SAAS,CAAC,OAAO,EAAE,UAAU,GAAG,sBAAsB,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;IAqBrF,YAAY,CAAC,OAAO,EAAE,eAAe,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,eAAe,GAAG,OAAO,CAAC,QAAQ,CAAC;IAyCnG,cAAc,CAAC,YAAY,EAAE,OAAO,CAAC,QAAQ,CAAC,EAAE,OAAO,EAAE,eAAe,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC;CAqCzI"}
@@ -1,189 +0,0 @@
1
- import type { HandlerCallbackOptions, MapLikeObject, SerwistPlugin, SerwistPluginCallbackParam } from "@serwist/core";
2
- import type { Strategy } from "./Strategy.js";
3
- /**
4
- * A class created every time a Strategy instance instance calls `Strategy.handle` or
5
- * `Strategy.handleAll` that wraps all fetch and cache actions around plugin callbacks
6
- * and keeps track of when the strategy is "done" (i.e. all added `event.waitUntil()` promises
7
- * have resolved).
8
- */
9
- export declare class StrategyHandler {
10
- /**
11
- * The event associated with this request.
12
- */
13
- event: ExtendableEvent;
14
- /**
15
- * The request the strategy is performing (passed to the strategy's
16
- * `handle()` or `handleAll()` method).
17
- */
18
- request: Request;
19
- /**
20
- * A `URL` instance of `request.url` (if passed to the strategy's
21
- * `handle()` or `handleAll()` method).
22
- * Note: the `url` param will be present if the strategy was invoked
23
- * from a `@serwist/routing.Route` object.
24
- */
25
- url?: URL;
26
- /**
27
- * A `param` value (if passed to the strategy's
28
- * `handle()` or `handleAll()` method).
29
- * Note: the `param` param will be present if the strategy was invoked
30
- * from a `@serwist/routing.Route` object and the `@serwist/strategies.matchCallback`
31
- * returned a truthy value (it will be that value).
32
- */
33
- params?: string[] | MapLikeObject;
34
- private _cacheKeys;
35
- private readonly _strategy;
36
- private readonly _handlerDeferred;
37
- private readonly _extendLifetimePromises;
38
- private readonly _plugins;
39
- private readonly _pluginStateMap;
40
- /**
41
- * Creates a new instance associated with the passed strategy and event
42
- * that's handling the request.
43
- *
44
- * The constructor also initializes the state that will be passed to each of
45
- * the plugins handling this request.
46
- *
47
- * @param strategy
48
- * @param options
49
- */
50
- constructor(strategy: Strategy, options: HandlerCallbackOptions & {
51
- request: HandlerCallbackOptions["request"] & Request;
52
- });
53
- /**
54
- * Fetches a given request (and invokes any applicable plugin callback
55
- * methods) using the `fetchOptions` (for non-navigation requests) and
56
- * `plugins` defined on the `Strategy` object.
57
- *
58
- * The following plugin lifecycle methods are invoked when using this method:
59
- * - `requestWillFetch()`
60
- * - `fetchDidSucceed()`
61
- * - `fetchDidFail()`
62
- *
63
- * @param input The URL or request to fetch.
64
- * @returns
65
- */
66
- fetch(input: RequestInfo): Promise<Response>;
67
- /**
68
- * Calls `this.fetch()` and (in the background) runs `this.cachePut()` on
69
- * the response generated by `this.fetch()`.
70
- *
71
- * The call to `this.cachePut()` automatically invokes `this.waitUntil()`,
72
- * so you do not have to manually call `waitUntil()` on the event.
73
- *
74
- * @param input The request or URL to fetch and cache.
75
- * @returns
76
- */
77
- fetchAndCachePut(input: RequestInfo): Promise<Response>;
78
- /**
79
- * Matches a request from the cache (and invokes any applicable plugin
80
- * callback methods) using the `cacheName`, `matchOptions`, and `plugins`
81
- * defined on the strategy object.
82
- *
83
- * The following plugin lifecycle methods are invoked when using this method:
84
- * - cacheKeyWillByUsed()
85
- * - cachedResponseWillByUsed()
86
- *
87
- * @param key The Request or URL to use as the cache key.
88
- * @returns A matching response, if found.
89
- */
90
- cacheMatch(key: RequestInfo): Promise<Response | undefined>;
91
- /**
92
- * Puts a request/response pair in the cache (and invokes any applicable
93
- * plugin callback methods) using the `cacheName` and `plugins` defined on
94
- * the strategy object.
95
- *
96
- * The following plugin lifecycle methods are invoked when using this method:
97
- * - cacheKeyWillByUsed()
98
- * - cacheWillUpdate()
99
- * - cacheDidUpdate()
100
- *
101
- * @param key The request or URL to use as the cache key.
102
- * @param response The response to cache.
103
- * @returns `false` if a cacheWillUpdate caused the response
104
- * not be cached, and `true` otherwise.
105
- */
106
- cachePut(key: RequestInfo, response: Response): Promise<boolean>;
107
- /**
108
- * Checks the list of plugins for the `cacheKeyWillBeUsed` callback, and
109
- * executes any of those callbacks found in sequence. The final `Request`
110
- * object returned by the last plugin is treated as the cache key for cache
111
- * reads and/or writes. If no `cacheKeyWillBeUsed` plugin callbacks have
112
- * been registered, the passed request is returned unmodified
113
- *
114
- * @param request
115
- * @param mode
116
- * @returns
117
- */
118
- getCacheKey(request: Request, mode: "read" | "write"): Promise<Request>;
119
- /**
120
- * Returns true if the strategy has at least one plugin with the given
121
- * callback.
122
- *
123
- * @param name The name of the callback to check for.
124
- * @returns
125
- */
126
- hasCallback<C extends keyof SerwistPlugin>(name: C): boolean;
127
- /**
128
- * Runs all plugin callbacks matching the given name, in order, passing the
129
- * given param object (merged ith the current plugin state) as the only
130
- * argument.
131
- *
132
- * Note: since this method runs all plugins, it's not suitable for cases
133
- * where the return value of a callback needs to be applied prior to calling
134
- * the next callback. See `@serwist/strategies.iterateCallbacks` for how to handle that case.
135
- *
136
- * @param name The name of the callback to run within each plugin.
137
- * @param param The object to pass as the first (and only) param when executing each callback. This object will be merged with the
138
- * current plugin state prior to callback execution.
139
- */
140
- runCallbacks<C extends keyof NonNullable<SerwistPlugin>>(name: C, param: Omit<SerwistPluginCallbackParam[C], "state">): Promise<void>;
141
- /**
142
- * Accepts a callback and returns an iterable of matching plugin callbacks,
143
- * where each callback is wrapped with the current handler state (i.e. when
144
- * you call each callback, whatever object parameter you pass it will
145
- * be merged with the plugin's current state).
146
- *
147
- * @param name The name fo the callback to run
148
- * @returns
149
- */
150
- iterateCallbacks<C extends keyof SerwistPlugin>(name: C): Generator<NonNullable<SerwistPlugin[C]>>;
151
- /**
152
- * Adds a promise to the
153
- * [extend lifetime promises](https://w3c.github.io/ServiceWorker/#extendableevent-extend-lifetime-promises)
154
- * of the event event associated with the request being handled (usually a `FetchEvent`).
155
- *
156
- * Note: you can await
157
- * `@serwist/strategies.StrategyHandler.doneWaiting`
158
- * to know when all added promises have settled.
159
- *
160
- * @param promise A promise to add to the extend lifetime promises of
161
- * the event that triggered the request.
162
- */
163
- waitUntil<T>(promise: Promise<T>): Promise<T>;
164
- /**
165
- * Returns a promise that resolves once all promises passed to
166
- * `@serwist/strategies.StrategyHandler.waitUntil` have settled.
167
- *
168
- * Note: any work done after `doneWaiting()` settles should be manually
169
- * passed to an event's `waitUntil()` method (not this handler's
170
- * `waitUntil()` method), otherwise the service worker thread my be killed
171
- * prior to your work completing.
172
- */
173
- doneWaiting(): Promise<void>;
174
- /**
175
- * Stops running the strategy and immediately resolves any pending
176
- * `waitUntil()` promises.
177
- */
178
- destroy(): void;
179
- /**
180
- * This method will call `cacheWillUpdate` on the available plugins (or use
181
- * status === 200) to determine if the response is safe and valid to cache.
182
- *
183
- * @param response
184
- * @returns
185
- * @private
186
- */
187
- _ensureResponseSafeToCache(response: Response): Promise<Response | undefined>;
188
- }
189
- //# sourceMappingURL=StrategyHandler.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"StrategyHandler.d.ts","sourceRoot":"","sources":["../src/StrategyHandler.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,sBAAsB,EAAE,aAAa,EAAE,aAAa,EAAE,0BAA0B,EAAE,MAAM,eAAe,CAAC;AAYtH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAM9C;;;;;GAKG;AACH,qBAAa,eAAe;IAC1B;;OAEG;IACI,KAAK,EAAE,eAAe,CAAC;IAC9B;;;OAGG;IACI,OAAO,EAAE,OAAO,CAAC;IACxB;;;;;OAKG;IACI,GAAG,CAAC,EAAE,GAAG,CAAC;IACjB;;;;;;OAMG;IACI,MAAM,CAAC,EAAE,MAAM,EAAE,GAAG,aAAa,CAAC;IAEzC,OAAO,CAAC,UAAU,CAA+B;IACjD,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAW;IACrC,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAgB;IACjD,OAAO,CAAC,QAAQ,CAAC,uBAAuB,CAAiB;IACzD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAkB;IAC3C,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAoC;IAEpE;;;;;;;;;OASG;gBAED,QAAQ,EAAE,QAAQ,EAClB,OAAO,EAAE,sBAAsB,GAAG;QAChC,OAAO,EAAE,sBAAsB,CAAC,SAAS,CAAC,GAAG,OAAO,CAAC;KACtD;IAsCH;;;;;;;;;;;;OAYG;IACG,KAAK,CAAC,KAAK,EAAE,WAAW,GAAG,OAAO,CAAC,QAAQ,CAAC;IAyElD;;;;;;;;;OASG;IACG,gBAAgB,CAAC,KAAK,EAAE,WAAW,GAAG,OAAO,CAAC,QAAQ,CAAC;IAS7D;;;;;;;;;;;OAWG;IACG,UAAU,CAAC,GAAG,EAAE,WAAW,GAAG,OAAO,CAAC,QAAQ,GAAG,SAAS,CAAC;IA+BjE;;;;;;;;;;;;;;OAcG;IACG,QAAQ,CAAC,GAAG,EAAE,WAAW,EAAE,QAAQ,EAAE,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC;IA8FtE;;;;;;;;;;OAUG;IACG,WAAW,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;IAqB7E;;;;;;OAMG;IACH,WAAW,CAAC,CAAC,SAAS,MAAM,aAAa,EAAE,IAAI,EAAE,CAAC,GAAG,OAAO;IAS5D;;;;;;;;;;;;OAYG;IACG,YAAY,CAAC,CAAC,SAAS,MAAM,WAAW,CAAC,aAAa,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,0BAA0B,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IAQ3I;;;;;;;;OAQG;IACF,gBAAgB,CAAC,CAAC,SAAS,MAAM,aAAa,EAAE,IAAI,EAAE,CAAC,GAAG,SAAS,CAAC,WAAW,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC;IAgBnG;;;;;;;;;;;OAWG;IACH,SAAS,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IAK7C;;;;;;;;OAQG;IACG,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC;IAOlC;;;OAGG;IACH,OAAO,IAAI,IAAI;IAIf;;;;;;;OAOG;IACG,0BAA0B,CAAC,QAAQ,EAAE,QAAQ,GAAG,OAAO,CAAC,QAAQ,GAAG,SAAS,CAAC;CAuCpF"}
@@ -1,3 +0,0 @@
1
- import type { SerwistPlugin } from "@serwist/core";
2
- export declare const cacheOkAndOpaquePlugin: SerwistPlugin;
3
- //# sourceMappingURL=cacheOkAndOpaquePlugin.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"cacheOkAndOpaquePlugin.d.ts","sourceRoot":"","sources":["../../src/plugins/cacheOkAndOpaquePlugin.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAEnD,eAAO,MAAM,sBAAsB,EAAE,aAepC,CAAC"}
@@ -1,5 +0,0 @@
1
- export declare const messages: {
2
- strategyStart: (strategyName: string, request: Request) => string;
3
- printFinalResponse: (response?: Response) => void;
4
- };
5
- //# sourceMappingURL=messages.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../src/utils/messages.ts"],"names":[],"mappings":"AAUA,eAAO,MAAM,QAAQ;kCACW,MAAM,WAAW,OAAO,KAAG,MAAM;oCAC/B,QAAQ,KAAG,IAAI;CAOhD,CAAC"}
package/src/CacheFirst.ts DELETED
@@ -1,87 +0,0 @@
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 { assert, SerwistError, logger } from "@serwist/core/internal";
10
-
11
- import { Strategy } from "./Strategy.js";
12
- import type { StrategyHandler } from "./StrategyHandler.js";
13
- import { messages } from "./utils/messages.js";
14
-
15
- /**
16
- * An implementation of the [cache first](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#cache_first_falling_back_to_network)
17
- * request strategy.
18
- *
19
- * A cache first strategy is useful for assets that have been revisioned,
20
- * such as URLs like `/styles/example.a8f5f1.css`, since they
21
- * can be cached for long periods of time.
22
- *
23
- * If the network request fails, and there is no cache match, this will throw
24
- * a `SerwistError` exception.
25
- */
26
- export class CacheFirst extends Strategy {
27
- /**
28
- * @private
29
- * @param request A request to run this strategy for.
30
- * @param handler The event that triggered the request.
31
- * @returns
32
- */
33
- async _handle(request: Request, handler: StrategyHandler): Promise<Response> {
34
- const logs = [];
35
-
36
- if (process.env.NODE_ENV !== "production") {
37
- assert!.isInstance(request, Request, {
38
- moduleName: "@serwist/strategies",
39
- className: this.constructor.name,
40
- funcName: "makeRequest",
41
- paramName: "request",
42
- });
43
- }
44
-
45
- let response = await handler.cacheMatch(request);
46
-
47
- let error: Error | undefined = undefined;
48
- if (!response) {
49
- if (process.env.NODE_ENV !== "production") {
50
- logs.push(`No response found in the '${this.cacheName}' cache. Will respond with a network request.`);
51
- }
52
- try {
53
- response = await handler.fetchAndCachePut(request);
54
- } catch (err) {
55
- if (err instanceof Error) {
56
- error = err;
57
- }
58
- }
59
-
60
- if (process.env.NODE_ENV !== "production") {
61
- if (response) {
62
- logs.push("Got response from network.");
63
- } else {
64
- logs.push("Unable to get a response from the network.");
65
- }
66
- }
67
- } else {
68
- if (process.env.NODE_ENV !== "production") {
69
- logs.push(`Found a cached response in the '${this.cacheName}' cache.`);
70
- }
71
- }
72
-
73
- if (process.env.NODE_ENV !== "production") {
74
- logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));
75
- for (const log of logs) {
76
- logger.log(log);
77
- }
78
- messages.printFinalResponse(response);
79
- logger.groupEnd();
80
- }
81
-
82
- if (!response) {
83
- throw new SerwistError("no-response", { url: request.url, error });
84
- }
85
- return response;
86
- }
87
- }