serwist
Version:
A Swiss Army knife for service workers.
284 lines • 11.4 kB
TypeScript
import type { Route } from "./Route.js";
import { type HTTPMethod } from "./constants.js";
import { type GoogleAnalyticsInitializeOptions } from "./lib/googleAnalytics/initializeGoogleAnalytics.js";
import { type PrecacheFallbackEntry } from "./lib/precaching/PrecacheFallbackPlugin.js";
import { Strategy } from "./lib/strategies/Strategy.js";
import type { PrecacheOptions, RouteHandler, RouteHandlerCallback, RouteHandlerCallbackOptions, RouteMatchCallback, RouteMatchCallbackOptions } from "./types.js";
import type { RuntimeCaching } from "./types.js";
import type { CleanupResult, InstallResult, PrecacheEntry } from "./types.js";
export interface FallbackEntry extends PrecacheFallbackEntry {
}
export interface FallbacksOptions {
/**
* A list of fallback entries.
*/
entries: FallbackEntry[];
}
export interface SerwistOptions {
/**
* A list of URLs that should be cached.
*/
precacheEntries?: (PrecacheEntry | string)[];
/**
* Options to customize how Serwist precaches the URLs in the precache list.
*/
precacheOptions?: PrecacheOptions;
/**
* Forces the waiting service worker to become the active one.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/skipWaiting
*/
skipWaiting?: boolean;
/**
* Imports external scripts. They are executed in the order they
* are passed.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts
*/
importScripts?: string[];
/**
* Enables navigation preloading if it is supported.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/navigationPreload
*/
navigationPreload?: boolean;
/**
* Modifies the prefix of the default cache names used by Serwist packages.
*/
cacheId?: string | undefined;
/**
* Claims any currently available clients once the service worker
* becomes active. This is normally used in conjunction with `skipWaiting()`.
*
* @default false
*/
clientsClaim?: boolean;
/**
* A list of caching strategies.
*/
runtimeCaching?: RuntimeCaching[];
/**
* Your configuration for {@linkcode initializeGoogleAnalytics}. This plugin is
* only initialized when this option is not `undefined` or `false`.
*/
offlineAnalyticsConfig?: Omit<GoogleAnalyticsInitializeOptions, "serwist"> | boolean;
/**
* Disables Serwist's logging in development mode.
*
* @default false
*/
disableDevLogs?: boolean;
/**
* Precaches routes so that they can be used as a fallback when
* a {@linkcode Strategy} fails to generate a response.
*
* Note: This option mutates `runtimeCaching`. It also expects the URLs
* defined in `entries` to have been precached beforehand.
*/
fallbacks?: FallbacksOptions;
}
/**
* A class that helps bootstrap the service worker.
*
* @see https://serwist.pages.dev/docs/serwist/core/serwist
*/
export declare class Serwist {
private readonly _urlsToCacheKeys;
private readonly _urlsToCacheModes;
private readonly _cacheKeysToIntegrities;
private _concurrentPrecaching;
private readonly _precacheStrategy;
private readonly _routes;
private readonly _defaultHandlerMap;
private _catchHandler?;
constructor({ precacheEntries, precacheOptions, skipWaiting, importScripts, navigationPreload, cacheId, clientsClaim, runtimeCaching, offlineAnalyticsConfig, disableDevLogs, fallbacks, }?: SerwistOptions);
/**
* The strategy used to precache assets and respond to `fetch` events.
*/
get precacheStrategy(): Strategy;
/**
* A `Map` of HTTP method name (`'GET'`, etc.) to an array of all corresponding registered {@linkcode Route}
* instances.
*/
get routes(): Map<HTTPMethod, Route[]>;
/**
* Adds Serwist's event listeners for you. Before calling it, add your own listeners should you need to.
*/
addEventListeners(): void;
/**
* Adds items to the precache list, removing duplicates and ensuring the information is valid.
*
* @param entries Array of entries to precache.
*/
addToPrecacheList(entries: (PrecacheEntry | string)[]): void;
/**
* Precaches new and updated assets. Call this method from the service worker's
* `install` event.
*
* Note: this method calls `event.waitUntil()` for you, so you do not need
* to call it yourself in your event handlers.
*
* @param event
* @returns
*/
handleInstall(event: ExtendableEvent): Promise<InstallResult>;
/**
* Deletes assets that are no longer present in the current precache manifest.
* Call this method from the service worker's `activate` event.
*
* Note: this method calls `event.waitUntil()` for you, so you do not need
* to call it yourself in your event handlers.
*
* @param event
* @returns
*/
handleActivate(event: ExtendableEvent): Promise<CleanupResult>;
/**
* Gets a `Response` from an appropriate `Route`'s handler. Call this method
* from the service worker's `fetch` event.
* @param event
*/
handleFetch(event: FetchEvent): void;
/**
* Caches new URLs on demand. Call this method from the service worker's
* `message` event. To trigger the handler, send a message of type `"CACHE_URLS"`
* alongside a list of URLs that should be cached as `urlsToCache`.
* @param event
*/
handleCache(event: ExtendableMessageEvent): void;
/**
* Define a default handler that's called when no routes explicitly
* match the incoming request.
*
* Each HTTP method (`'GET'`, `'POST'`, etc.) gets its own default handler.
*
* Without a default handler, unmatched requests will go against the
* network as if there were no service worker present.
*
* @param handler A callback function that returns a `Promise` resulting in a `Response`.
* @param method The HTTP method to associate with this default handler. Each method
* has its own default. Defaults to `'GET'`.
*/
setDefaultHandler(handler: RouteHandler, method?: HTTPMethod): void;
/**
* If a {@linkcode Route} throws an error while handling a request, this handler
* will be called and given a chance to provide a response.
*
* @param handler A callback function that returns a `Promise` resulting
* in a `Response`.
*/
setCatchHandler(handler: RouteHandler): void;
/**
* Registers a `RegExp`, string, or function with a caching
* strategy to the router.
*
* @param capture If the capture param is a {@linkcode Route} object, all other arguments will be ignored.
* @param handler A callback function that returns a `Promise` resulting in a `Response`.
* This parameter is required if `capture` is not a {@linkcode Route} object.
* @param method The HTTP method to match the route against. Defaults to `'GET'`.
* @returns The generated {@linkcode Route} object.
*/
registerCapture<T extends RegExp | string | RouteMatchCallback | Route>(capture: T, handler?: T extends Route ? never : RouteHandler, method?: T extends Route ? never : HTTPMethod): Route;
/**
* Registers a {@linkcode Route} with the router.
*
* @param route The {@linkcode Route} to register.
*/
registerRoute(route: Route): void;
/**
* Unregisters a route from the router.
*
* @param route The {@linkcode Route} object to unregister.
*/
unregisterRoute(route: Route): void;
/**
* Returns a mapping of a precached URL to the corresponding cache key, taking
* into account the revision information for the URL.
*
* @returns A URL to cache key mapping.
*/
getUrlsToPrecacheKeys(): Map<string, string>;
/**
* Returns a list of all the URLs that have been precached by the current
* service worker.
*
* @returns The precached URLs.
*/
getPrecachedUrls(): string[];
/**
* Returns the cache key used for storing a given URL. If that URL is
* unversioned, like "/index.html", then the cache key will be the original
* URL with a search parameter appended to it.
*
* @param url A URL whose cache key you want to look up.
* @returns The versioned URL that corresponds to a cache key
* for the original URL, or undefined if that URL isn't precached.
*/
getPrecacheKeyForUrl(url: string): string | undefined;
/**
* @param url A cache key whose SRI you want to look up.
* @returns The subresource integrity associated with the cache key,
* or undefined if it's not set.
*/
getIntegrityForPrecacheKey(cacheKey: string): string | undefined;
/**
* This acts as a drop-in replacement for
* [`cache.match()`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/match)
* with the following differences:
*
* - It knows what the name of the precache is, and only checks in that cache.
* - It allows you to pass in an "original" URL without versioning parameters,
* and it will automatically look up the correct cache key for the currently
* active revision of that URL.
*
* E.g., `matchPrecache('index.html')` will find the correct precached
* response for the currently active service worker, even if the actual cache
* key is `'/index.html?__WB_REVISION__=1234abcd'`.
*
* @param request The key (without revisioning parameters)
* to look up in the precache.
* @returns
*/
matchPrecache(request: string | Request): Promise<Response | undefined>;
/**
* Returns a function that looks up `url` in the precache (taking into
* account revision information), and returns the corresponding `Response`.
*
* @param url The precached URL which will be used to lookup the response.
* @return
*/
createHandlerBoundToUrl(url: string): RouteHandlerCallback;
/**
* Applies the routing rules to a `FetchEvent` object to get a response from an
* appropriate route.
*
* @param options
* @returns A promise is returned if a registered route can handle the request.
* If there is no matching route and there's no default handler, `undefined`
* is returned.
*/
handleRequest({ request, event, }: {
/**
* The request to handle.
*/
request: Request;
/**
* The event that triggered the request.
*/
event: ExtendableEvent;
}): Promise<Response> | undefined;
/**
* Checks a request and URL (and optionally an event) against the list of
* registered routes, and if there's a match, returns the corresponding
* route along with any params generated by the match.
*
* @param options
* @returns An object with `route` and `params` properties. They are populated
* if a matching route was found or `undefined` otherwise.
*/
findMatchingRoute({ url, sameOrigin, request, event }: RouteMatchCallbackOptions): {
route?: Route;
params?: RouteHandlerCallbackOptions["params"];
};
}
//# sourceMappingURL=Serwist.d.ts.map