@serwist/strategies 9.0.0-preview.9 → 9.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@serwist/strategies",
3
- "version": "9.0.0-preview.9",
3
+ "version": "9.0.0",
4
4
  "type": "module",
5
5
  "description": "A service worker helper library implementing common caching strategies.",
6
6
  "files": [
@@ -17,7 +17,7 @@
17
17
  ],
18
18
  "author": "Google's Web DevRel Team, Serwist's Team",
19
19
  "license": "MIT",
20
- "repository": "serwist/serwist",
20
+ "repository": "https://github.com/serwist/serwist",
21
21
  "bugs": "https://github.com/serwist/serwist/issues",
22
22
  "homepage": "https://serwist.pages.dev",
23
23
  "main": "./dist/index.js",
@@ -30,12 +30,12 @@
30
30
  "./package.json": "./package.json"
31
31
  },
32
32
  "dependencies": {
33
- "@serwist/core": "9.0.0-preview.9"
33
+ "serwist": "9.0.0"
34
34
  },
35
35
  "devDependencies": {
36
- "rollup": "4.9.6",
37
- "typescript": "5.4.0-dev.20240206",
38
- "@serwist/constants": "9.0.0-preview.9"
36
+ "rollup": "4.14.3",
37
+ "typescript": "5.5.0-dev.20240415",
38
+ "@serwist/configs": "9.0.0"
39
39
  },
40
40
  "peerDependencies": {
41
41
  "typescript": ">=5.0.0"
@@ -47,7 +47,6 @@
47
47
  },
48
48
  "scripts": {
49
49
  "build": "rimraf dist && cross-env NODE_ENV=production rollup --config rollup.config.js",
50
- "dev": "rollup --config rollup.config.js --watch",
51
50
  "lint": "biome lint ./src",
52
51
  "typecheck": "tsc"
53
52
  }
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";
2
+ export type { NetworkFirstOptions, NetworkOnlyOptions, StrategyOptions } from "serwist";
@@ -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,60 +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
- export declare class NetworkFirst extends Strategy {
11
- private readonly _networkTimeoutSeconds;
12
- /**
13
- * An implementation of the [network first](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#network-first-falling-back-to-cache)
14
- * request strategy.
15
- *
16
- * By default, this strategy will cache responses with a 200 status code as
17
- * well as [opaque responses](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses).
18
- * Opaque responses are are cross-origin requests where the response doesn't
19
- * support [CORS](https://enable-cors.org/).
20
- *
21
- * If the network request fails, and there is no cache match, this will throw
22
- * a `SerwistError` exception.
23
- *
24
- * @param options
25
- * This option can be used to combat
26
- * "[lie-fi](https://developers.google.com/web/fundamentals/performance/poor-connectivity/#lie-fi)"
27
- * scenarios.
28
- */
29
- constructor(options?: NetworkFirstOptions);
30
- /**
31
- * @private
32
- * @param request A request to run this strategy for.
33
- * @param handler The event that triggered the request.
34
- * @returns
35
- */
36
- _handle(request: Request, handler: StrategyHandler): Promise<Response>;
37
- /**
38
- * @param options
39
- * @returns
40
- * @private
41
- */
42
- private _getTimeoutPromise;
43
- /**
44
- * @param options
45
- * @param options.timeoutId
46
- * @param options.request
47
- * @param options.logs A reference to the logs Array.
48
- * @param options.event
49
- * @returns
50
- *
51
- * @private
52
- */
53
- _getNetworkPromise({ timeoutId, request, logs, handler, }: {
54
- request: Request;
55
- logs: any[];
56
- timeoutId?: number;
57
- handler: StrategyHandler;
58
- }): Promise<Response | undefined>;
59
- }
60
- //# 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,qBAAa,YAAa,SAAQ,QAAQ;IACxC,OAAO,CAAC,QAAQ,CAAC,sBAAsB,CAAS;IAEhD;;;;;;;;;;;;;;;;OAgBG;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,31 +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
- export declare class NetworkOnly extends Strategy {
11
- private readonly _networkTimeoutSeconds;
12
- /**
13
- * An implementation of the [network only](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#network-only)
14
- * request strategy.
15
- *
16
- * This class is useful if you want to take advantage of any Serwist plugin.
17
- *
18
- * If the network request fails, this will throw a `SerwistError` exception.
19
- *
20
- * @param options
21
- */
22
- constructor(options?: NetworkOnlyOptions);
23
- /**
24
- * @private
25
- * @param request A request to run this strategy for.
26
- * @param handler The event that triggered the request.
27
- * @returns
28
- */
29
- _handle(request: Request, handler: StrategyHandler): Promise<Response>;
30
- }
31
- //# 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,qBAAa,WAAY,SAAQ,QAAQ;IACvC,OAAO,CAAC,QAAQ,CAAC,sBAAsB,CAAS;IAEhD;;;;;;;;;OASG;gBACS,OAAO,GAAE,kBAAuB;IAM5C;;;;;OAKG;IACG,OAAO,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,QAAQ,CAAC;CA+C7E"}
@@ -1,34 +0,0 @@
1
- import type { StrategyOptions } from "./Strategy.js";
2
- import { Strategy } from "./Strategy.js";
3
- import type { StrategyHandler } from "./StrategyHandler.js";
4
- export declare class StaleWhileRevalidate extends Strategy {
5
- /**
6
- * An implementation of the
7
- * [stale-while-revalidate](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#stale-while-revalidate)
8
- * request strategy.
9
- *
10
- * Resources are requested from both the cache and the network in parallel.
11
- * The strategy will respond with the cached version if available, otherwise
12
- * wait for the network response. The cache is updated with the network response
13
- * with each successful request.
14
- *
15
- * By default, this strategy will cache responses with a 200 status code as
16
- * well as [opaque responses](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses).
17
- * Opaque responses are cross-origin requests where the response doesn't
18
- * support [CORS](https://enable-cors.org/).
19
- *
20
- * If the network request fails, and there is no cache match, this will throw
21
- * a `SerwistError` exception.
22
- *
23
- * @param options
24
- */
25
- constructor(options?: StrategyOptions);
26
- /**
27
- * @private
28
- * @param request A request to run this strategy for.
29
- * @param handler The event that triggered the request.
30
- * @returns
31
- */
32
- _handle(request: Request, handler: StrategyHandler): Promise<Response>;
33
- }
34
- //# 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,qBAAa,oBAAqB,SAAQ,QAAQ;IAChD;;;;;;;;;;;;;;;;;;;OAmBG;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://developers.google.com/web/tools/workbox/guides/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;IAsBrF,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,187 +0,0 @@
1
- import type { HandlerCallbackOptions, 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 request the strategy is performing (passed to the strategy's
12
- * `handle()` or `handleAll()` method).
13
- */
14
- request: Request;
15
- /**
16
- * A `URL` instance of `request.url` (if passed to the strategy's
17
- * `handle()` or `handleAll()` method).
18
- * Note: the `url` param will be present if the strategy was invoked
19
- * from a `@serwist/routing.Route` object.
20
- */
21
- url?: URL;
22
- /**
23
- * The event associated with this request.
24
- */
25
- event: ExtendableEvent;
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?: any;
34
- private _cacheKeys;
35
- private readonly _strategy;
36
- private readonly _extendLifetimePromises;
37
- private readonly _handlerDeferred;
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
- /**
52
- * Fetches a given request (and invokes any applicable plugin callback
53
- * methods) using the `fetchOptions` (for non-navigation requests) and
54
- * `plugins` defined on the `Strategy` object.
55
- *
56
- * The following plugin lifecycle methods are invoked when using this method:
57
- * - `requestWillFetch()`
58
- * - `fetchDidSucceed()`
59
- * - `fetchDidFail()`
60
- *
61
- * @param input The URL or request to fetch.
62
- * @returns
63
- */
64
- fetch(input: RequestInfo): Promise<Response>;
65
- /**
66
- * Calls `this.fetch()` and (in the background) runs `this.cachePut()` on
67
- * the response generated by `this.fetch()`.
68
- *
69
- * The call to `this.cachePut()` automatically invokes `this.waitUntil()`,
70
- * so you do not have to manually call `waitUntil()` on the event.
71
- *
72
- * @param input The request or URL to fetch and cache.
73
- * @returns
74
- */
75
- fetchAndCachePut(input: RequestInfo): Promise<Response>;
76
- /**
77
- * Matches a request from the cache (and invokes any applicable plugin
78
- * callback methods) using the `cacheName`, `matchOptions`, and `plugins`
79
- * defined on the strategy object.
80
- *
81
- * The following plugin lifecycle methods are invoked when using this method:
82
- * - cacheKeyWillByUsed()
83
- * - cachedResponseWillByUsed()
84
- *
85
- * @param key The Request or URL to use as the cache key.
86
- * @returns A matching response, if found.
87
- */
88
- cacheMatch(key: RequestInfo): Promise<Response | undefined>;
89
- /**
90
- * Puts a request/response pair in the cache (and invokes any applicable
91
- * plugin callback methods) using the `cacheName` and `plugins` defined on
92
- * the strategy object.
93
- *
94
- * The following plugin lifecycle methods are invoked when using this method:
95
- * - cacheKeyWillByUsed()
96
- * - cacheWillUpdate()
97
- * - cacheDidUpdate()
98
- *
99
- * @param key The request or URL to use as the cache key.
100
- * @param response The response to cache.
101
- * @returns `false` if a cacheWillUpdate caused the response
102
- * not be cached, and `true` otherwise.
103
- */
104
- cachePut(key: RequestInfo, response: Response): Promise<boolean>;
105
- /**
106
- * Checks the list of plugins for the `cacheKeyWillBeUsed` callback, and
107
- * executes any of those callbacks found in sequence. The final `Request`
108
- * object returned by the last plugin is treated as the cache key for cache
109
- * reads and/or writes. If no `cacheKeyWillBeUsed` plugin callbacks have
110
- * been registered, the passed request is returned unmodified
111
- *
112
- * @param request
113
- * @param mode
114
- * @returns
115
- */
116
- getCacheKey(request: Request, mode: "read" | "write"): Promise<Request>;
117
- /**
118
- * Returns true if the strategy has at least one plugin with the given
119
- * callback.
120
- *
121
- * @param name The name of the callback to check for.
122
- * @returns
123
- */
124
- hasCallback<C extends keyof SerwistPlugin>(name: C): boolean;
125
- /**
126
- * Runs all plugin callbacks matching the given name, in order, passing the
127
- * given param object (merged ith the current plugin state) as the only
128
- * argument.
129
- *
130
- * Note: since this method runs all plugins, it's not suitable for cases
131
- * where the return value of a callback needs to be applied prior to calling
132
- * the next callback. See `@serwist/strategies.iterateCallbacks` for how to handle that case.
133
- *
134
- * @param name The name of the callback to run within each plugin.
135
- * @param param The object to pass as the first (and only) param when executing each callback. This object will be merged with the
136
- * current plugin state prior to callback execution.
137
- */
138
- runCallbacks<C extends keyof NonNullable<SerwistPlugin>>(name: C, param: Omit<SerwistPluginCallbackParam[C], "state">): Promise<void>;
139
- /**
140
- * Accepts a callback and returns an iterable of matching plugin callbacks,
141
- * where each callback is wrapped with the current handler state (i.e. when
142
- * you call each callback, whatever object parameter you pass it will
143
- * be merged with the plugin's current state).
144
- *
145
- * @param name The name fo the callback to run
146
- * @returns
147
- */
148
- iterateCallbacks<C extends keyof SerwistPlugin>(name: C): Generator<NonNullable<SerwistPlugin[C]>>;
149
- /**
150
- * Adds a promise to the
151
- * [extend lifetime promises](https://w3c.github.io/ServiceWorker/#extendableevent-extend-lifetime-promises)
152
- * of the event event associated with the request being handled (usually a `FetchEvent`).
153
- *
154
- * Note: you can await
155
- * `@serwist/strategies.StrategyHandler.doneWaiting`
156
- * to know when all added promises have settled.
157
- *
158
- * @param promise A promise to add to the extend lifetime promises of
159
- * the event that triggered the request.
160
- */
161
- waitUntil<T>(promise: Promise<T>): Promise<T>;
162
- /**
163
- * Returns a promise that resolves once all promises passed to
164
- * `@serwist/strategies.StrategyHandler.waitUntil` have settled.
165
- *
166
- * Note: any work done after `doneWaiting()` settles should be manually
167
- * passed to an event's `waitUntil()` method (not this handler's
168
- * `waitUntil()` method), otherwise the service worker thread my be killed
169
- * prior to your work completing.
170
- */
171
- doneWaiting(): Promise<void>;
172
- /**
173
- * Stops running the strategy and immediately resolves any pending
174
- * `waitUntil()` promises.
175
- */
176
- destroy(): void;
177
- /**
178
- * This method will call `cacheWillUpdate` on the available plugins (or use
179
- * status === 200) to determine if the response is safe and valid to cache.
180
- *
181
- * @param response
182
- * @returns
183
- * @private
184
- */
185
- _ensureResponseSafeToCache(response: Response): Promise<Response | undefined>;
186
- }
187
- //# 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,EAAiB,aAAa,EAAE,0BAA0B,EAAE,MAAM,eAAe,CAAC;AAYtH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAM9C;;;;;GAKG;AACH,qBAAa,eAAe;IAC1B;;;OAGG;IACI,OAAO,EAAG,OAAO,CAAC;IACzB;;;;;OAKG;IACI,GAAG,CAAC,EAAE,GAAG,CAAC;IACjB;;OAEG;IACI,KAAK,EAAE,eAAe,CAAC;IAC9B;;;;;;OAMG;IACI,MAAM,CAAC,EAAE,GAAG,CAAC;IAEpB,OAAO,CAAC,UAAU,CAA+B;IAEjD,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAW;IACrC,OAAO,CAAC,QAAQ,CAAC,uBAAuB,CAAiB;IACzD,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAgB;IACjD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAkB;IAC3C,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAoC;IAEpE;;;;;;;;;OASG;gBACS,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,sBAAsB;IA4B/D;;;;;;;;;;;;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
- }