repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
serwist
github_2023
serwist
typescript
Serwist.matchPrecache
async matchPrecache(request: string | Request): Promise<Response | undefined> { const url = request instanceof Request ? request.url : request; const cacheKey = this.getPrecacheKeyForUrl(url); if (cacheKey) { const cache = await self.caches.open(this.precacheStrategy.cacheName); return cache.match(cacheKey); } return 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 */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/Serwist.ts#L632-L640
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
Serwist.createHandlerBoundToUrl
createHandlerBoundToUrl(url: string): RouteHandlerCallback { const cacheKey = this.getPrecacheKeyForUrl(url); if (!cacheKey) { throw new SerwistError("non-precached-url", { url }); } return (options) => { options.request = new Request(url); options.params = { cacheKey, ...options.params }; return this.precacheStrategy.handle(options); }; }
/** * 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 */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/Serwist.ts#L649-L660
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
Serwist.handleRequest
handleRequest({ request, event, }: { /** * The request to handle. */ request: Request; /** * The event that triggered the request. */ event: ExtendableEvent; }): Promise<Response> | undefined { if (process.env.NODE_ENV !== "production") { assert!.isInstance(request, Request, { moduleName: "serwist", className: "Serwist", funcName: "handleRequest", paramName: "options.request", }); } const url = new URL(request.url, location.href); if (!url.protocol.startsWith("http")) { if (process.env.NODE_ENV !== "production") { logger.debug("Router only supports URLs that start with 'http'."); } return; } const sameOrigin = url.origin === location.origin; const { params, route } = this.findMatchingRoute({ event, request, sameOrigin, url, }); let handler = route?.handler; const debugMessages = []; if (process.env.NODE_ENV !== "production") { if (handler) { debugMessages.push(["Found a route to handle this request:", route]); if (params) { debugMessages.push([`Passing the following params to the route's handler:`, params]); } } } // If we don't have a handler because there was no matching route, then // fall back to defaultHandler if that's defined. const method = request.method as HTTPMethod; if (!handler && this._defaultHandlerMap.has(method)) { if (process.env.NODE_ENV !== "production") { debugMessages.push(`Failed to find a matching route. Falling back to the default handler for ${method}.`); } handler = this._defaultHandlerMap.get(method); } if (!handler) { if (process.env.NODE_ENV !== "production") { // No handler so Serwist will do nothing. If logs is set of debug // i.e. verbose, we should print out this information. logger.debug(`No route found for: ${getFriendlyURL(url)}`); } return; } if (process.env.NODE_ENV !== "production") { // We have a handler, meaning Serwist is going to handle the route. // print the routing details to the console. logger.groupCollapsed(`Router is responding to: ${getFriendlyURL(url)}`); for (const msg of debugMessages) { if (Array.isArray(msg)) { logger.log(...msg); } else { logger.log(msg); } } logger.groupEnd(); } // Wrap in try and catch in case the handle method throws a synchronous // error. It should still callback to the catch handler. let responsePromise: Promise<Response>; try { responsePromise = handler.handle({ url, request, event, params }); } catch (err) { responsePromise = Promise.reject(err); } // Get route's catch handler, if it exists const catchHandler = route?.catchHandler; if (responsePromise instanceof Promise && (this._catchHandler || catchHandler)) { responsePromise = responsePromise.catch(async (err) => { // If there's a route catch handler, process that first if (catchHandler) { if (process.env.NODE_ENV !== "production") { // Still include URL here as it will be async from the console group // and may not make sense without the URL logger.groupCollapsed(`Error thrown when responding to: ${getFriendlyURL(url)}. Falling back to route's Catch Handler.`); logger.error("Error thrown by:", route); logger.error(err); logger.groupEnd(); } try { return await catchHandler.handle({ url, request, event, params }); } catch (catchErr) { if (catchErr instanceof Error) { err = catchErr; } } } if (this._catchHandler) { if (process.env.NODE_ENV !== "production") { // Still include URL here as it will be async from the console group // and may not make sense without the URL logger.groupCollapsed(`Error thrown when responding to: ${getFriendlyURL(url)}. Falling back to global Catch Handler.`); logger.error("Error thrown by:", route); logger.error(err); logger.groupEnd(); } return this._catchHandler.handle({ url, request, event }); } throw err; }); } return responsePromise; }
/** * 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. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/Serwist.ts#L671-L807
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
Serwist.findMatchingRoute
findMatchingRoute({ url, sameOrigin, request, event }: RouteMatchCallbackOptions): { route?: Route; params?: RouteHandlerCallbackOptions["params"]; } { const routes = this._routes.get(request.method as HTTPMethod) || []; for (const route of routes) { let params: Promise<any> | undefined; // route.match returns type any, not possible to change right now. const matchResult = route.match({ url, sameOrigin, request, event }); if (matchResult) { if (process.env.NODE_ENV !== "production") { // Warn developers that using an async matchCallback is almost always // not the right thing to do. if (matchResult instanceof Promise) { logger.warn( `While routing ${getFriendlyURL( url, )}, an async matchCallback function was used. Please convert the following route to use a synchronous matchCallback function:`, route, ); } } // See https://github.com/GoogleChrome/workbox/issues/2079 // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment params = matchResult; if (Array.isArray(params) && params.length === 0) { // Instead of passing an empty array in as params, use undefined. params = undefined; } else if ( matchResult.constructor === Object && // eslint-disable-line Object.keys(matchResult).length === 0 ) { // Instead of passing an empty object in as params, use undefined. params = undefined; } else if (typeof matchResult === "boolean") { // For the boolean value true (rather than just something truth-y), // don't set params. // See https://github.com/GoogleChrome/workbox/pull/2134#issuecomment-513924353 params = undefined; } // Return early if have a match. return { route, params }; } } // If no match was found above, return and empty object. return {}; }
/** * 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. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/Serwist.ts#L818-L866
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
PrecacheController.constructor
constructor({ cacheName, plugins = [], fallbackToNetwork = true, concurrentPrecaching = 1 }: PrecacheControllerOptions = {}) { this._concurrentPrecaching = concurrentPrecaching; this._strategy = new PrecacheStrategy({ cacheName: privateCacheNames.getPrecacheName(cacheName), plugins: [...plugins, new PrecacheCacheKeyPlugin({ precacheController: this })], fallbackToNetwork, }); // Bind the install and activate methods to the instance. this.install = this.install.bind(this); this.activate = this.activate.bind(this); }
/** * Create a new PrecacheController. * * @param options */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/PrecacheController.ts#L68-L78
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
PrecacheController.strategy
get strategy(): Strategy { return this._strategy; }
/** * The strategy created by this controller and * used to cache assets and respond to `fetch` events. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/PrecacheController.ts#L84-L86
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
PrecacheController.precache
precache(entries: (PrecacheEntry | string)[]): void { this.addToCacheList(entries); if (!this._installAndActiveListenersAdded) { self.addEventListener("install", this.install); self.addEventListener("activate", this.activate); this._installAndActiveListenersAdded = true; } }
/** * Adds items to the precache list, removing any duplicates and * stores the files in the precache cache when the service * worker installs. * * This method can be called multiple times. * * @param entries Array of entries to precache. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/PrecacheController.ts#L97-L105
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
PrecacheController.addToCacheList
addToCacheList(entries: (PrecacheEntry | string)[]): void { if (process.env.NODE_ENV !== "production") { assert!.isArray(entries, { moduleName: "serwist/legacy", className: "PrecacheController", funcName: "addToCacheList", paramName: "entries", }); } const urlsToWarnAbout: string[] = []; for (const entry of entries) { // See https://github.com/GoogleChrome/workbox/issues/2259 if (typeof entry === "string") { urlsToWarnAbout.push(entry); } else if (entry && !entry.integrity && entry.revision === undefined) { urlsToWarnAbout.push(entry.url); } const { cacheKey, url } = createCacheKey(entry); const cacheMode = typeof entry !== "string" && entry.revision ? "reload" : "default"; if (this._urlsToCacheKeys.has(url) && this._urlsToCacheKeys.get(url) !== cacheKey) { throw new SerwistError("add-to-cache-list-conflicting-entries", { firstEntry: this._urlsToCacheKeys.get(url), secondEntry: cacheKey, }); } if (typeof entry !== "string" && entry.integrity) { if (this._cacheKeysToIntegrities.has(cacheKey) && this._cacheKeysToIntegrities.get(cacheKey) !== entry.integrity) { throw new SerwistError("add-to-cache-list-conflicting-integrities", { url, }); } this._cacheKeysToIntegrities.set(cacheKey, entry.integrity); } this._urlsToCacheKeys.set(url, cacheKey); this._urlsToCacheModes.set(url, cacheMode); if (urlsToWarnAbout.length > 0) { const warningMessage = `Serwist is precaching URLs without revision info: ${urlsToWarnAbout.join( ", ", )}\nThis is generally NOT safe. Learn more at https://bit.ly/wb-precache`; if (process.env.NODE_ENV === "production") { // Use console directly to display this warning without bloating // bundle sizes by pulling in all of the logger codebase in prod. console.warn(warningMessage); } else { logger.warn(warningMessage); } } } }
/** * This method will add items to the precache list, removing duplicates * and ensuring the information is valid. * * @param entries Array of entries to precache. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/PrecacheController.ts#L113-L167
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
PrecacheController.install
install(event: ExtendableEvent): Promise<InstallResult> { return waitUntil<InstallResult>(event, async () => { const installReportPlugin = new PrecacheInstallReportPlugin(); this.strategy.plugins.push(installReportPlugin); await parallel(this._concurrentPrecaching, Array.from(this._urlsToCacheKeys.entries()), async ([url, cacheKey]): Promise<void> => { const integrity = this._cacheKeysToIntegrities.get(cacheKey); const cacheMode = this._urlsToCacheModes.get(url); const request = new Request(url, { integrity, cache: cacheMode, credentials: "same-origin", }); await Promise.all( this.strategy.handleAll({ event, request, url: new URL(request.url), params: { cacheKey }, }), ); }); const { updatedURLs, notUpdatedURLs } = installReportPlugin; if (process.env.NODE_ENV !== "production") { printInstallDetails(updatedURLs, notUpdatedURLs); } return { updatedURLs, notUpdatedURLs }; }); }
/** * Precaches new and updated assets. Call this method from the service worker * 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 */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/PrecacheController.ts#L179-L212
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
PrecacheController.activate
activate(event: ExtendableEvent): Promise<CleanupResult> { return waitUntil<CleanupResult>(event, async () => { const cache = await self.caches.open(this.strategy.cacheName); const currentlyCachedRequests = await cache.keys(); const expectedCacheKeys = new Set(this._urlsToCacheKeys.values()); const deletedCacheRequests: string[] = []; for (const request of currentlyCachedRequests) { if (!expectedCacheKeys.has(request.url)) { await cache.delete(request); deletedCacheRequests.push(request.url); } } if (process.env.NODE_ENV !== "production") { printCleanupDetails(deletedCacheRequests); } return { deletedCacheRequests }; }); }
/** * Deletes assets that are no longer present in the current precache manifest. * Call this method from the service worker 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 */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/PrecacheController.ts#L224-L245
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
PrecacheController.getURLsToCacheKeys
getURLsToCacheKeys(): Map<string, string> { return this._urlsToCacheKeys; }
/** * 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. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/PrecacheController.ts#L253-L255
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
PrecacheController.getCachedURLs
getCachedURLs(): string[] { return [...this._urlsToCacheKeys.keys()]; }
/** * Returns a list of all the URLs that have been precached by the current * service worker. * * @returns The precached URLs. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/PrecacheController.ts#L263-L265
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
PrecacheController.getCacheKeyForURL
getCacheKeyForURL(url: string): string | undefined { const urlObject = new URL(url, location.href); return this._urlsToCacheKeys.get(urlObject.href); }
/** * 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. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/PrecacheController.ts#L276-L279
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
PrecacheController.getIntegrityForCacheKey
getIntegrityForCacheKey(cacheKey: string): string | undefined { return this._cacheKeysToIntegrities.get(cacheKey); }
/** * @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. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/PrecacheController.ts#L286-L288
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
PrecacheController.matchPrecache
async matchPrecache(request: string | Request): Promise<Response | undefined> { const url = request instanceof Request ? request.url : request; const cacheKey = this.getCacheKeyForURL(url); if (cacheKey) { const cache = await self.caches.open(this.strategy.cacheName); return cache.match(cacheKey); } return 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 */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/PrecacheController.ts#L308-L316
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
PrecacheController.createHandlerBoundToURL
createHandlerBoundToURL(url: string): RouteHandlerCallback { const cacheKey = this.getCacheKeyForURL(url); if (!cacheKey) { throw new SerwistError("non-precached-url", { url }); } return (options) => { options.request = new Request(url); options.params = { cacheKey, ...options.params }; return this.strategy.handle(options); }; }
/** * 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 */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/PrecacheController.ts#L325-L336
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
PrecacheFallbackPlugin.constructor
constructor({ fallbackUrls, precacheController }: PrecacheFallbackPluginOptions) { this._fallbackUrls = fallbackUrls; this._precacheController = precacheController || getSingletonPrecacheController(); }
/** * Constructs a new instance with the associated `fallbackUrls`. * * @param config */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/PrecacheFallbackPlugin.ts#L66-L69
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
PrecacheFallbackPlugin.handlerDidError
async handlerDidError(param: HandlerDidErrorCallbackParam) { for (const fallback of this._fallbackUrls) { if (typeof fallback === "string") { const fallbackResponse = await this._precacheController.matchPrecache(fallback); if (fallbackResponse !== undefined) { return fallbackResponse; } } else if (fallback.matcher(param)) { const fallbackResponse = await this._precacheController.matchPrecache(fallback.url); if (fallbackResponse !== undefined) { return fallbackResponse; } } } return undefined; }
/** * @returns The precache response for one of the fallback URLs, or `undefined` if * nothing satisfies the conditions. * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/PrecacheFallbackPlugin.ts#L76-L91
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
PrecacheRoute.constructor
constructor(precacheController: PrecacheController, options?: PrecacheRouteOptions) { const match: RouteMatchCallback = ({ request }: RouteMatchCallbackOptions) => { const urlsToCacheKeys = precacheController.getURLsToCacheKeys(); for (const possibleURL of generateURLVariations(request.url, options)) { const cacheKey = urlsToCacheKeys.get(possibleURL); if (cacheKey) { const integrity = precacheController.getIntegrityForCacheKey(cacheKey); return { cacheKey, integrity }; } } if (process.env.NODE_ENV !== "production") { logger.debug(`Precaching did not find a match for ${getFriendlyURL(request.url)}`); } return; }; super(match, precacheController.strategy); }
/** * @param precacheController A {@linkcode PrecacheController} * instance used to both match requests and respond to `fetch` events. * @param options Options to control how requests are matched * against the list of precached URLs. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/PrecacheRoute.ts#L30-L47
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
Router.constructor
constructor() { this._routes = new Map(); this._defaultHandlerMap = new Map(); }
/** * Initializes a new Router. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/Router.ts#L53-L56
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
Router.routes
get routes(): Map<HTTPMethod, Route[]> { return this._routes; }
/** * @returns routes A `Map` of HTTP method name (`'GET'`, etc.) to an array of all * the corresponding {@linkcode Route} instances that are registered. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/Router.ts#L62-L64
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
Router.addFetchListener
addFetchListener(): void { if (!this._fetchListenerHandler) { this._fetchListenerHandler = (event) => { const { request } = event; const responsePromise = this.handleRequest({ request, event }); if (responsePromise) { event.respondWith(responsePromise); } }; self.addEventListener("fetch", this._fetchListenerHandler); } }
/** * Adds a `fetch` event listener to respond to events when a route matches * the event's request. Effectively no-op if `addFetchListener` has been * called, but `removeFetchListener` has not. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/Router.ts#L71-L82
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
Router.removeFetchListener
removeFetchListener(): void { if (this._fetchListenerHandler) { self.removeEventListener("fetch", this._fetchListenerHandler); this._fetchListenerHandler = null; } }
/** * Removes `fetch` event listener added by `addFetchListener`. * Effectively no-op if either `addFetchListener` has not been called or, * if it has, so has `removeFetchListener`. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/Router.ts#L89-L94
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
Router.addCacheListener
addCacheListener(): void { if (!this._cacheListenerHandler) { this._cacheListenerHandler = (event) => { if (event.data && event.data.type === "CACHE_URLS") { const { payload }: CacheURLsMessageData = event.data; if (process.env.NODE_ENV !== "production") { logger.debug("Caching URLs from the window", payload.urlsToCache); } const requestPromises = Promise.all( payload.urlsToCache.map((entry: string | [string, RequestInit?]) => { if (typeof entry === "string") { entry = [entry]; } const request = new Request(...entry); return this.handleRequest({ request, event }); }), ); event.waitUntil(requestPromises); // If a MessageChannel was used, reply to the message on success. if (event.ports?.[0]) { void requestPromises.then(() => event.ports[0].postMessage(true)); } } }; self.addEventListener("message", this._cacheListenerHandler); } }
/** * Adds a `message` event listener for URLs to cache from the window. * This is useful to cache resources loaded on the page prior to when the * service worker started controlling it. Effectively no-op if `addCacheListener` * has been called, but `removeCacheListener` hasn't. * * The format of the message data sent from the window should be as follows. * Where the `urlsToCache` array may consist of URL strings or an array of * URL string + `requestInit` object (the same as you'd pass to `fetch()`). * * ``` * { * type: 'CACHE_URLS', * payload: { * urlsToCache: [ * './script1.js', * './script2.js', * ['./script3.js', {mode: 'no-cors'}], * ], * }, * } * ``` */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/Router.ts#L119-L150
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
Router.removeCacheListener
removeCacheListener(): void { if (this._cacheListenerHandler) { self.removeEventListener("message", this._cacheListenerHandler); } }
/** * Removes the `message` event listener added by `addCacheListener`. * Effectively no-op if either `addCacheListener` has not been called or, * if it has, so has `removeCacheListener`. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/Router.ts#L157-L161
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
Router.handleRequest
handleRequest({ request, event, }: { /** * The request to handle. */ request: Request; /** * The event that triggered the request. */ event: ExtendableEvent; }): Promise<Response> | undefined { if (process.env.NODE_ENV !== "production") { assert!.isInstance(request, Request, { moduleName: "serwist/legacy", className: "Router", funcName: "handleRequest", paramName: "options.request", }); } const url = new URL(request.url, location.href); if (!url.protocol.startsWith("http")) { if (process.env.NODE_ENV !== "production") { logger.debug("Router only supports URLs that start with 'http'."); } return; } const sameOrigin = url.origin === location.origin; const { params, route } = this.findMatchingRoute({ event, request, sameOrigin, url, }); let handler = route?.handler; const debugMessages = []; if (process.env.NODE_ENV !== "production") { if (handler) { debugMessages.push(["Found a route to handle this request:", route]); if (params) { debugMessages.push([`Passing the following params to the route's handler:`, params]); } } } // If we don't have a handler because there was no matching route, then // fall back to defaultHandler if that's defined. const method = request.method as HTTPMethod; if (!handler && this._defaultHandlerMap.has(method)) { if (process.env.NODE_ENV !== "production") { debugMessages.push(`Failed to find a matching route. Falling back to the default handler for ${method}.`); } handler = this._defaultHandlerMap.get(method); } if (!handler) { if (process.env.NODE_ENV !== "production") { // No handler so Serwist will do nothing. If logs is set of debug // i.e. verbose, we should print out this information. logger.debug(`No route found for: ${getFriendlyURL(url)}`); } return; } if (process.env.NODE_ENV !== "production") { // We have a handler, meaning Serwist is going to handle the route. // print the routing details to the console. logger.groupCollapsed(`Router is responding to: ${getFriendlyURL(url)}`); for (const msg of debugMessages) { if (Array.isArray(msg)) { logger.log(...msg); } else { logger.log(msg); } } logger.groupEnd(); } // Wrap in try and catch in case the handle method throws a synchronous // error. It should still callback to the catch handler. let responsePromise: Promise<Response>; try { responsePromise = handler.handle({ url, request, event, params }); } catch (err) { responsePromise = Promise.reject(err); } // Get route's catch handler, if it exists const catchHandler = route?.catchHandler; if (responsePromise instanceof Promise && (this._catchHandler || catchHandler)) { responsePromise = responsePromise.catch(async (err) => { // If there's a route catch handler, process that first if (catchHandler) { if (process.env.NODE_ENV !== "production") { // Still include URL here as it will be async from the console group // and may not make sense without the URL logger.groupCollapsed(`Error thrown when responding to: ${getFriendlyURL(url)}. Falling back to route's Catch Handler.`); logger.error("Error thrown by:", route); logger.error(err); logger.groupEnd(); } try { return await catchHandler.handle({ url, request, event, params }); } catch (catchErr) { if (catchErr instanceof Error) { err = catchErr; } } } if (this._catchHandler) { if (process.env.NODE_ENV !== "production") { // Still include URL here as it will be async from the console group // and may not make sense without the URL logger.groupCollapsed(`Error thrown when responding to: ${getFriendlyURL(url)}. Falling back to global Catch Handler.`); logger.error("Error thrown by:", route); logger.error(err); logger.groupEnd(); } return this._catchHandler.handle({ url, request, event }); } throw err; }); } return responsePromise; }
/** * Apply the routing rules to a `fetch` event 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 `defaultHandler`, `undefined` * is returned. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/Router.ts#L172-L308
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
Router.findMatchingRoute
findMatchingRoute({ url, sameOrigin, request, event }: RouteMatchCallbackOptions): { route?: Route; params?: RouteHandlerCallbackOptions["params"]; } { const routes = this._routes.get(request.method as HTTPMethod) || []; for (const route of routes) { let params: Promise<any> | undefined; // route.match returns type any, not possible to change right now. const matchResult = route.match({ url, sameOrigin, request, event }); if (matchResult) { if (process.env.NODE_ENV !== "production") { // Warn developers that using an async matchCallback is almost always // not the right thing to do. if (matchResult instanceof Promise) { logger.warn( `While routing ${getFriendlyURL( url, )}, an async matchCallback function was used. Please convert the following route to use a synchronous matchCallback function:`, route, ); } } // See https://github.com/GoogleChrome/workbox/issues/2079 // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment params = matchResult; if (Array.isArray(params) && params.length === 0) { // Instead of passing an empty array in as params, use undefined. params = undefined; } else if ( matchResult.constructor === Object && // eslint-disable-line Object.keys(matchResult).length === 0 ) { // Instead of passing an empty object in as params, use undefined. params = undefined; } else if (typeof matchResult === "boolean") { // For the boolean value true (rather than just something truth-y), // don't set params. // See https://github.com/GoogleChrome/workbox/pull/2134#issuecomment-513924353 params = undefined; } // Return early if have a match. return { route, params }; } } // If no match was found above, return and empty object. return {}; }
/** * 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. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/Router.ts#L319-L367
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
Router.setDefaultHandler
setDefaultHandler(handler: RouteHandler, method: HTTPMethod = defaultMethod): void { this._defaultHandlerMap.set(method, normalizeHandler(handler)); }
/** * 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'`. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/Router.ts#L382-L384
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
Router.setCatchHandler
setCatchHandler(handler: RouteHandler): void { this._catchHandler = normalizeHandler(handler); }
/** * If a `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. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/Router.ts#L393-L395
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
Router.registerCapture
registerCapture(capture: RegExp | string | RouteMatchCallback | Route, handler?: RouteHandler, method?: HTTPMethod): Route { const route = parseRoute(capture, handler, method); this.registerRoute(route); return route; }
/** * 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. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/Router.ts#L407-L411
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
Router.registerRoute
registerRoute(route: Route): void { if (process.env.NODE_ENV !== "production") { assert!.isType(route, "object", { moduleName: "serwist/legacy", className: "Router", funcName: "registerRoute", paramName: "route", }); assert!.hasMethod(route, "match", { moduleName: "serwist/legacy", className: "Router", funcName: "registerRoute", paramName: "route", }); assert!.isType(route.handler, "object", { moduleName: "serwist/legacy", className: "Router", funcName: "registerRoute", paramName: "route", }); assert!.hasMethod(route.handler, "handle", { moduleName: "serwist/legacy", className: "Router", funcName: "registerRoute", paramName: "route.handler", }); assert!.isType(route.method, "string", { moduleName: "serwist/legacy", className: "Router", funcName: "registerRoute", paramName: "route.method", }); } if (!this._routes.has(route.method)) { this._routes.set(route.method, []); } // Give precedence to all of the earlier routes by adding this additional // route to the end of the array. this._routes.get(route.method)!.push(route); }
/** * Registers a route with the router. * * @param route The route to register. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/Router.ts#L418-L463
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
Router.unregisterRoute
unregisterRoute(route: Route): void { if (!this._routes.has(route.method)) { throw new SerwistError("unregister-route-but-not-found-with-method", { method: route.method, }); } const routeIndex = this._routes.get(route.method)!.indexOf(route); if (routeIndex > -1) { this._routes.get(route.method)!.splice(routeIndex, 1); } else { throw new SerwistError("unregister-route-route-not-registered"); } }
/** * Unregisters a route from the router. * * @param route The route to unregister. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/Router.ts#L470-L483
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
createOnSyncCallback
const createOnSyncCallback = (config: Pick<GoogleAnalyticsInitializeOptions, "parameterOverrides" | "hitFilter">) => { return async ({ queue }: { queue: BackgroundSyncQueue }) => { let entry: BackgroundSyncQueueEntry | undefined = undefined; while ((entry = await queue.shiftRequest())) { const { request, timestamp } = entry; const url = new URL(request.url); try { // Measurement protocol requests can set their payload parameters in // either the URL query string (for GET requests) or the POST body. const params = request.method === "POST" ? new URLSearchParams(await request.clone().text()) : url.searchParams; // Calculate the qt param, accounting for the fact that an existing // qt param may be present and should be updated rather than replaced. const originalHitTime = timestamp! - (Number(params.get("qt")) || 0); const queueTime = Date.now() - originalHitTime; // Set the qt param prior to applying hitFilter or parameterOverrides. params.set("qt", String(queueTime)); // Apply `parameterOverrides`, if set. if (config.parameterOverrides) { for (const param of Object.keys(config.parameterOverrides)) { const value = config.parameterOverrides[param]; params.set(param, value); } } // Apply `hitFilter`, if set. if (typeof config.hitFilter === "function") { config.hitFilter.call(null, params); } // Retry the fetch. Ignore URL search params from the URL as they're // now in the post body. await fetch( new Request(url.origin + url.pathname, { body: params.toString(), method: "POST", mode: "cors", credentials: "omit", headers: { "Content-Type": "text/plain" }, }), ); if (process.env.NODE_ENV !== "production") { logger.log(`Request for '${getFriendlyURL(url.href)}' has been replayed`); } } catch (err) { await queue.unshiftRequest(entry); if (process.env.NODE_ENV !== "production") { logger.log(`Request for '${getFriendlyURL(url.href)}' failed to replay, putting it back in the queue.`); } throw err; } } if (process.env.NODE_ENV !== "production") { logger.log("All Google Analytics request successfully replayed; " + "the queue is now empty!"); } }; };
/** * Creates the requestWillDequeue callback to be used with the background * sync plugin. The callback takes the failed request and adds the * `qt` param based on the current time, as well as applies any other * user-defined hit modifications. * * @param config * @returns The requestWillDequeue callback function. * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/initializeGoogleAnalytics.ts#L69-L130
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
createCollectRoutes
const createCollectRoutes = (bgSyncPlugin: BackgroundSyncPlugin) => { const match = ({ url }: RouteMatchCallbackOptions) => url.hostname === GOOGLE_ANALYTICS_HOST && COLLECT_PATHS_REGEX.test(url.pathname); const handler = new NetworkOnly({ plugins: [bgSyncPlugin], }); return [new Route(match, handler, "GET"), new Route(match, handler, "POST")]; };
/** * Creates GET and POST routes to catch failed Measurement Protocol hits. * * @param bgSyncPlugin * @returns The created routes. * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/initializeGoogleAnalytics.ts#L139-L147
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
createAnalyticsJsRoute
const createAnalyticsJsRoute = (cacheName: string) => { const match = ({ url }: RouteMatchCallbackOptions) => url.hostname === GOOGLE_ANALYTICS_HOST && url.pathname === ANALYTICS_JS_PATH; const handler = new NetworkFirst({ cacheName }); return new Route(match, handler, "GET"); };
/** * Creates a route with a network first strategy for the analytics.js script. * * @param cacheName * @returns The created route. * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/initializeGoogleAnalytics.ts#L156-L162
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
createGtagJsRoute
const createGtagJsRoute = (cacheName: string) => { const match = ({ url }: RouteMatchCallbackOptions) => url.hostname === GTM_HOST && url.pathname === GTAG_JS_PATH; const handler = new NetworkFirst({ cacheName }); return new Route(match, handler, "GET"); };
/** * Creates a route with a network first strategy for the gtag.js script. * * @param cacheName * @returns The created route. * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/initializeGoogleAnalytics.ts#L171-L177
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
createGtmJsRoute
const createGtmJsRoute = (cacheName: string) => { const match = ({ url }: RouteMatchCallbackOptions) => url.hostname === GTM_HOST && url.pathname === GTM_JS_PATH; const handler = new NetworkFirst({ cacheName }); return new Route(match, handler, "GET"); };
/** * Creates a route with a network first strategy for the gtm.js script. * * @param cacheName * @returns The created route. * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/legacy/initializeGoogleAnalytics.ts#L186-L192
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncPlugin.constructor
constructor(name: string, options?: BackgroundSyncQueueOptions) { this._queue = new BackgroundSyncQueue(name, options); }
/** * @param name See the {@linkcode BackgroundSyncQueue} * documentation for parameter details. * @param options See the {@linkcode BackgroundSyncQueue} * documentation for parameter details. * @see https://serwist.pages.dev/docs/serwist/core/background-sync-queue */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncPlugin.ts#L27-L29
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncPlugin.fetchDidFail
async fetchDidFail({ request }: FetchDidFailCallbackParam) { await this._queue.pushRequest({ request }); }
/** * @param options * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncPlugin.ts#L35-L37
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
convertEntry
const convertEntry = (queueStoreEntry: UnidentifiedQueueStoreEntry): BackgroundSyncQueueEntry => { const queueEntry: BackgroundSyncQueueEntry = { request: new StorableRequest(queueStoreEntry.requestData).toRequest(), timestamp: queueStoreEntry.timestamp, }; if (queueStoreEntry.metadata) { queueEntry.metadata = queueStoreEntry.metadata; } return queueEntry; };
/** * Converts a QueueStore entry into the format exposed by Queue. This entails * converting the request data into a real request and omitting the `id` and * `queueName` properties. * * @param queueStoreEntry * @returns * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueue.ts#L109-L118
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueue.constructor
constructor(name: string, { forceSyncFallback, onSync, maxRetentionTime }: BackgroundSyncQueueOptions = {}) { // Ensure the store name is not already being used if (queueNames.has(name)) { throw new SerwistError("duplicate-queue-name", { name }); } queueNames.add(name); this._name = name; this._onSync = onSync || this.replayRequests; this._maxRetentionTime = maxRetentionTime || MAX_RETENTION_TIME; this._forceSyncFallback = Boolean(forceSyncFallback); this._queueStore = new BackgroundSyncQueueStore(this._name); this._addSyncListener(); }
/** * Creates an instance of Queue with the given options * * @param name The unique name for this queue. This name must be * unique as it's used to register sync events and store requests * in IndexedDB specific to this instance. An error will be thrown if * a duplicate name is detected. * @param options */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueue.ts#L143-L157
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueue.name
get name(): string { return this._name; }
/** * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueue.ts#L162-L164
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueue.pushRequest
async pushRequest(entry: BackgroundSyncQueueEntry): Promise<void> { if (process.env.NODE_ENV !== "production") { assert!.isType(entry, "object", { moduleName: "serwist", className: "BackgroundSyncQueue", funcName: "pushRequest", paramName: "entry", }); assert!.isInstance(entry.request, Request, { moduleName: "serwist", className: "BackgroundSyncQueue", funcName: "pushRequest", paramName: "entry.request", }); } await this._addRequest(entry, "push"); }
/** * Stores the passed request in IndexedDB (with its timestamp and any * metadata) at the end of the queue. * * @param entry */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueue.ts#L172-L189
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueue.unshiftRequest
async unshiftRequest(entry: BackgroundSyncQueueEntry): Promise<void> { if (process.env.NODE_ENV !== "production") { assert!.isType(entry, "object", { moduleName: "serwist", className: "BackgroundSyncQueue", funcName: "unshiftRequest", paramName: "entry", }); assert!.isInstance(entry.request, Request, { moduleName: "serwist", className: "BackgroundSyncQueue", funcName: "unshiftRequest", paramName: "entry.request", }); } await this._addRequest(entry, "unshift"); }
/** * Stores the passed request in IndexedDB (with its timestamp and any * metadata) at the beginning of the queue. * * @param entry */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueue.ts#L197-L214
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueue.popRequest
async popRequest(): Promise<BackgroundSyncQueueEntry | undefined> { return this._removeRequest("pop"); }
/** * Removes and returns the last request in the queue (along with its * timestamp and any metadata). * * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueue.ts#L222-L224
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueue.shiftRequest
async shiftRequest(): Promise<BackgroundSyncQueueEntry | undefined> { return this._removeRequest("shift"); }
/** * Removes and returns the first request in the queue (along with its * timestamp and any metadata). * * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueue.ts#L232-L234
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueue.getAll
async getAll(): Promise<BackgroundSyncQueueEntry[]> { const allEntries = await this._queueStore.getAll(); const now = Date.now(); const unexpiredEntries = []; for (const entry of allEntries) { // Ignore requests older than maxRetentionTime. Call this function // recursively until an unexpired request is found. const maxRetentionTimeInMs = this._maxRetentionTime * 60 * 1000; if (now - entry.timestamp > maxRetentionTimeInMs) { await this._queueStore.deleteEntry(entry.id); } else { unexpiredEntries.push(convertEntry(entry)); } } return unexpiredEntries; }
/** * Returns all the entries that have not expired (per `maxRetentionTime`). * Any expired entries are removed from the queue. * * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueue.ts#L242-L259
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueue.size
async size(): Promise<number> { return await this._queueStore.size(); }
/** * Returns the number of entries present in the queue. * Note that expired entries (per `maxRetentionTime`) are also included in this count. * * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueue.ts#L267-L269
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueue._addRequest
async _addRequest({ request, metadata, timestamp = Date.now() }: BackgroundSyncQueueEntry, operation: "push" | "unshift"): Promise<void> { const storableRequest = await StorableRequest.fromRequest(request.clone()); const entry: UnidentifiedQueueStoreEntry = { requestData: storableRequest.toObject(), timestamp, }; // Only include metadata if it's present. if (metadata) { entry.metadata = metadata; } switch (operation) { case "push": await this._queueStore.pushEntry(entry); break; case "unshift": await this._queueStore.unshiftEntry(entry); break; } if (process.env.NODE_ENV !== "production") { logger.log(`Request for '${getFriendlyURL(request.url)}' has ` + `been added to background sync queue '${this._name}'.`); } // Don't register for a sync if we're in the middle of a sync. Instead, // we wait until the sync is complete and call register if // `this._requestsAddedDuringSync` is true. if (this._syncInProgress) { this._requestsAddedDuringSync = true; } else { await this.registerSync(); } }
/** * Adds the entry to the QueueStore and registers for a sync event. * * @param entry * @param operation * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueue.ts#L278-L311
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueue._removeRequest
async _removeRequest(operation: "pop" | "shift"): Promise<BackgroundSyncQueueEntry | undefined> { const now = Date.now(); let entry: BackgroundSyncQueueStoreEntry | undefined; switch (operation) { case "pop": entry = await this._queueStore.popEntry(); break; case "shift": entry = await this._queueStore.shiftEntry(); break; } if (entry) { // Ignore requests older than maxRetentionTime. Call this function // recursively until an unexpired request is found. const maxRetentionTimeInMs = this._maxRetentionTime * 60 * 1000; if (now - entry.timestamp > maxRetentionTimeInMs) { return this._removeRequest(operation); } return convertEntry(entry); } return undefined; }
/** * Removes and returns the first or last (depending on `operation`) entry * from the {@linkcode BackgroundSyncQueueStore} that's not older than the `maxRetentionTime`. * * @param operation * @returns * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueue.ts#L321-L345
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueue.replayRequests
async replayRequests(): Promise<void> { let entry: BackgroundSyncQueueEntry | undefined = undefined; while ((entry = await this.shiftRequest())) { try { await fetch(entry.request.clone()); if (process.env.NODE_ENV !== "production") { logger.log(`Request for '${getFriendlyURL(entry.request.url)}' ` + `has been replayed in queue '${this._name}'`); } } catch (error) { await this.unshiftRequest(entry); if (process.env.NODE_ENV !== "production") { logger.log(`Request for '${getFriendlyURL(entry.request.url)}' ` + `failed to replay, putting it back in queue '${this._name}'`); } throw new SerwistError("queue-replay-failed", { name: this._name }); } } if (process.env.NODE_ENV !== "production") { logger.log(`All requests in queue '${this.name}' have successfully replayed; the queue is now empty!`); } }
/** * Loops through each request in the queue and attempts to re-fetch it. * If any request fails to re-fetch, it's put back in the same position in * the queue (which registers a retry for the next sync event). */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueue.ts#L352-L373
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueue.registerSync
async registerSync(): Promise<void> { // See https://github.com/GoogleChrome/workbox/issues/2393 if ("sync" in self.registration && !this._forceSyncFallback) { try { await self.registration.sync.register(`${TAG_PREFIX}:${this._name}`); } catch (err) { // This means the registration failed for some reason, possibly due to // the user disabling it. if (process.env.NODE_ENV !== "production") { logger.warn(`Unable to register sync event for '${this._name}'.`, err); } } } }
/** * Registers a sync event with a tag unique to this instance. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueue.ts#L378-L391
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueue._addSyncListener
private _addSyncListener() { // See https://github.com/GoogleChrome/workbox/issues/2393 if ("sync" in self.registration && !this._forceSyncFallback) { self.addEventListener("sync", (event: SyncEvent) => { if (event.tag === `${TAG_PREFIX}:${this._name}`) { if (process.env.NODE_ENV !== "production") { logger.log(`Background sync for tag '${event.tag}' has been received`); } const syncComplete = async () => { this._syncInProgress = true; let syncError: Error | undefined = undefined; try { await this._onSync({ queue: this }); } catch (error) { if (error instanceof Error) { syncError = error; // Rethrow the error. Note: the logic in the finally clause // will run before this gets rethrown. throw syncError; } } finally { // New items may have been added to the queue during the sync, // so we need to register for a new sync if that's happened... // Unless there was an error during the sync, in which // case the browser will automatically retry later, as long // as `event.lastChance` is not true. if (this._requestsAddedDuringSync && !(syncError && !event.lastChance)) { await this.registerSync(); } this._syncInProgress = false; this._requestsAddedDuringSync = false; } }; event.waitUntil(syncComplete()); } }); } else { if (process.env.NODE_ENV !== "production") { logger.log("Background sync replaying without background sync event"); } // If the browser doesn't support background sync, or the developer has // opted-in to not using it, retry every time the service worker starts up // as a fallback. void this._onSync({ queue: this }); } }
/** * In sync-supporting browsers, this adds a listener for the sync event. * In non-sync-supporting browsers, or if _forceSyncFallback is true, this * will retry the queue on service worker startup. * * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueue.ts#L400-L449
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueue._queueNames
static get _queueNames(): Set<string> { return queueNames; }
/** * Returns the set of queue names. This is primarily used to reset the list * of queue names in tests. * * @returns * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueue.ts#L458-L460
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueueDb.addEntry
async addEntry(entry: UnidentifiedQueueStoreEntry): Promise<void> { const db = await this.getDb(); const tx = db.transaction(REQUEST_OBJECT_STORE_NAME, "readwrite", { durability: "relaxed", }); await tx.store.add(entry as BackgroundSyncQueueStoreEntry); await tx.done; }
/** * Add QueueStoreEntry to underlying db. * * @param entry */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueueDb.ts#L55-L62
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueueDb.getFirstEntryId
async getFirstEntryId(): Promise<number | undefined> { const db = await this.getDb(); const cursor = await db.transaction(REQUEST_OBJECT_STORE_NAME).store.openCursor(); return cursor?.value.id; }
/** * Returns the first entry id in the ObjectStore. * * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueueDb.ts#L69-L73
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueueDb.getAllEntriesByQueueName
async getAllEntriesByQueueName(queueName: string): Promise<BackgroundSyncQueueStoreEntry[]> { const db = await this.getDb(); const results = await db.getAllFromIndex(REQUEST_OBJECT_STORE_NAME, QUEUE_NAME_INDEX, IDBKeyRange.only(queueName)); return results ? results : new Array<BackgroundSyncQueueStoreEntry>(); }
/** * Get all the entries filtered by index * * @param queueName * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueueDb.ts#L81-L85
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueueDb.getEntryCountByQueueName
async getEntryCountByQueueName(queueName: string): Promise<number> { const db = await this.getDb(); return db.countFromIndex(REQUEST_OBJECT_STORE_NAME, QUEUE_NAME_INDEX, IDBKeyRange.only(queueName)); }
/** * Returns the number of entries filtered by index * * @param queueName * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueueDb.ts#L93-L96
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueueDb.deleteEntry
async deleteEntry(id: number): Promise<void> { const db = await this.getDb(); await db.delete(REQUEST_OBJECT_STORE_NAME, id); }
/** * Deletes a single entry by id. * * @param id the id of the entry to be deleted */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueueDb.ts#L103-L106
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueueDb.getFirstEntryByQueueName
async getFirstEntryByQueueName(queueName: string): Promise<BackgroundSyncQueueStoreEntry | undefined> { return await this.getEndEntryFromIndex(IDBKeyRange.only(queueName), "next"); }
/** * * @param queueName * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueueDb.ts#L113-L115
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueueDb.getLastEntryByQueueName
async getLastEntryByQueueName(queueName: string): Promise<BackgroundSyncQueueStoreEntry | undefined> { return await this.getEndEntryFromIndex(IDBKeyRange.only(queueName), "prev"); }
/** * * @param queueName * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueueDb.ts#L122-L124
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueueDb.getEndEntryFromIndex
async getEndEntryFromIndex(query: IDBKeyRange, direction: IDBCursorDirection): Promise<BackgroundSyncQueueStoreEntry | undefined> { const db = await this.getDb(); const cursor = await db.transaction(REQUEST_OBJECT_STORE_NAME).store.index(QUEUE_NAME_INDEX).openCursor(query, direction); return cursor?.value; }
/** * Returns either the first or the last entries, depending on direction. * Filtered by index. * * @param direction * @param query * @returns * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueueDb.ts#L135-L140
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueueDb.getDb
private async getDb() { if (!this._db) { this._db = await openDB(BACKGROUND_SYNC_DB_NAME, BACKGROUND_SYNC_DB_VERSION, { upgrade: this._upgradeDb, }); } return this._db; }
/** * Returns an open connection to the database. * * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueueDb.ts#L147-L154
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueueDb._upgradeDb
private _upgradeDb(db: IDBPDatabase<BackgroundSyncQueueDBSchema>, oldVersion: number) { if (oldVersion > 0 && oldVersion < BACKGROUND_SYNC_DB_VERSION) { if (db.objectStoreNames.contains(REQUEST_OBJECT_STORE_NAME)) { db.deleteObjectStore(REQUEST_OBJECT_STORE_NAME); } } const objStore = db.createObjectStore(REQUEST_OBJECT_STORE_NAME, { autoIncrement: true, keyPath: "id", }); objStore.createIndex(QUEUE_NAME_INDEX, QUEUE_NAME_INDEX, { unique: false }); }
/** * Upgrades QueueDB * * @param db * @param oldVersion * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueueDb.ts#L163-L175
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueueStore.constructor
constructor(queueName: string) { this._queueName = queueName; this._queueDb = new BackgroundSyncQueueDb(); }
/** * Associates this instance with a Queue instance, so entries added can be * identified by their queue name. * * @param queueName */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueueStore.ts#L29-L32
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueueStore.pushEntry
async pushEntry(entry: UnidentifiedQueueStoreEntry): Promise<void> { if (process.env.NODE_ENV !== "production") { assert!.isType(entry, "object", { moduleName: "serwist", className: "BackgroundSyncQueueStore", funcName: "pushEntry", paramName: "entry", }); assert!.isType(entry.requestData, "object", { moduleName: "serwist", className: "BackgroundSyncQueueStore", funcName: "pushEntry", paramName: "entry.requestData", }); } // biome-ignore lint/performance/noDelete: Don't specify an ID since one is automatically generated. delete entry.id; entry.queueName = this._queueName; await this._queueDb.addEntry(entry); }
/** * Append an entry last in the queue. * * @param entry */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueueStore.ts#L39-L60
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueueStore.unshiftEntry
async unshiftEntry(entry: UnidentifiedQueueStoreEntry): Promise<void> { if (process.env.NODE_ENV !== "production") { assert!.isType(entry, "object", { moduleName: "serwist", className: "BackgroundSyncQueueStore", funcName: "unshiftEntry", paramName: "entry", }); assert!.isType(entry.requestData, "object", { moduleName: "serwist", className: "BackgroundSyncQueueStore", funcName: "unshiftEntry", paramName: "entry.requestData", }); } const firstId = await this._queueDb.getFirstEntryId(); if (firstId) { // Pick an ID one less than the lowest ID in the object store. entry.id = firstId - 1; } else { // biome-ignore lint/performance/noDelete: Let the auto-incrementor assign the ID. delete entry.id; } entry.queueName = this._queueName; await this._queueDb.addEntry(entry); }
/** * Prepend an entry first in the queue. * * @param entry */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueueStore.ts#L67-L95
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueueStore.popEntry
async popEntry(): Promise<BackgroundSyncQueueStoreEntry | undefined> { return this._removeEntry(await this._queueDb.getLastEntryByQueueName(this._queueName)); }
/** * Removes and returns the last entry in the queue matching the `queueName`. * * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueueStore.ts#L102-L104
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueueStore.shiftEntry
async shiftEntry(): Promise<BackgroundSyncQueueStoreEntry | undefined> { return this._removeEntry(await this._queueDb.getFirstEntryByQueueName(this._queueName)); }
/** * Removes and returns the first entry in the queue matching the `queueName`. * * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueueStore.ts#L111-L113
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueueStore.getAll
async getAll(): Promise<BackgroundSyncQueueStoreEntry[]> { return await this._queueDb.getAllEntriesByQueueName(this._queueName); }
/** * Returns all entries in the store matching the `queueName`. * * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueueStore.ts#L120-L122
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueueStore.size
async size(): Promise<number> { return await this._queueDb.getEntryCountByQueueName(this._queueName); }
/** * Returns the number of entries in the store matching the `queueName`. * * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueueStore.ts#L129-L131
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueueStore.deleteEntry
async deleteEntry(id: number): Promise<void> { await this._queueDb.deleteEntry(id); }
/** * Deletes the entry for the given ID. * * WARNING: this method does not ensure the deleted entry belongs to this * queue (i.e. matches the `queueName`). But this limitation is acceptable * as this class is not publicly exposed. An additional check would make * this method slower than it needs to be. * * @param id */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueueStore.ts#L143-L145
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BackgroundSyncQueueStore._removeEntry
async _removeEntry(entry?: BackgroundSyncQueueStoreEntry): Promise<BackgroundSyncQueueStoreEntry | undefined> { if (entry) { await this.deleteEntry(entry.id); } return entry; }
/** * Removes and returns the first or last entry in the queue (based on the * `direction` argument) matching the `queueName`. * * @returns * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/BackgroundSyncQueueStore.ts#L154-L159
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
StorableRequest.fromRequest
static async fromRequest(request: Request): Promise<StorableRequest> { const requestData: RequestData = { url: request.url, headers: {}, }; // Set the body if present. if (request.method !== "GET") { // Use ArrayBuffer to support non-text request bodies. // NOTE: we can't use Blobs becuse Safari doesn't support storing // Blobs in IndexedDB in some cases: // https://github.com/dfahlander/Dexie.js/issues/618#issuecomment-398348457 requestData.body = await request.clone().arrayBuffer(); } request.headers.forEach((value, key) => { requestData.headers[key] = value; }); // Add all other serializable request properties for (const prop of serializableProperties) { if (request[prop] !== undefined) { requestData[prop] = request[prop]; } } return new StorableRequest(requestData); }
/** * Converts a Request object to a plain object that can be structured * cloned or stringified to JSON. * * @param request * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/StorableRequest.ts#L49-L76
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
StorableRequest.constructor
constructor(requestData: RequestData) { if (process.env.NODE_ENV !== "production") { assert!.isType(requestData, "object", { moduleName: "serwist", className: "StorableRequest", funcName: "constructor", paramName: "requestData", }); assert!.isType(requestData.url, "string", { moduleName: "serwist", className: "StorableRequest", funcName: "constructor", paramName: "requestData.url", }); } // If the request's mode is `navigate`, convert it to `same-origin` since // navigation requests can't be constructed via script. if (requestData.mode === "navigate") { requestData.mode = "same-origin"; } this._requestData = requestData; }
/** * Accepts an object of request data that can be used to construct a * `Request` object but can also be stored in IndexedDB. * * @param requestData An object of request data that includes the `url` plus any relevant property of * [`requestInit`](https://fetch.spec.whatwg.org/#requestinit). */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/StorableRequest.ts#L85-L108
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
StorableRequest.toObject
toObject(): RequestData { const requestData = Object.assign({}, this._requestData); requestData.headers = Object.assign({}, this._requestData.headers); if (requestData.body) { requestData.body = requestData.body.slice(0); } return requestData; }
/** * Returns a deep clone of the instance's `requestData` object. * * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/StorableRequest.ts#L115-L123
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
StorableRequest.toRequest
toRequest(): Request { return new Request(this._requestData.url, this._requestData); }
/** * Converts this instance to a Request. * * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/StorableRequest.ts#L130-L132
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
StorableRequest.clone
clone(): StorableRequest { return new StorableRequest(this.toObject()); }
/** * Creates and returns a deep clone of the instance. * * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/backgroundSync/StorableRequest.ts#L139-L141
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
defaultPayloadGenerator
const defaultPayloadGenerator = (data: CacheDidUpdateCallbackParam): BroadcastPayload => { return { cacheName: data.cacheName, updatedURL: data.request.url, }; };
/** * Generates the default payload used in update messages. By default the * payload includes the `cacheName` and `updatedURL` fields. * * @returns * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/broadcastUpdate/BroadcastCacheUpdate.ts#L37-L42
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BroadcastCacheUpdate.constructor
constructor({ generatePayload, headersToCheck, notifyAllClients }: BroadcastCacheUpdateOptions = {}) { this._headersToCheck = headersToCheck || BROADCAST_UPDATE_DEFAULT_HEADERS; this._generatePayload = generatePayload || defaultPayloadGenerator; this._notifyAllClients = notifyAllClients ?? BROADCAST_UPDATE_DEFAULT_NOTIFY; }
/** * Construct an instance of `BroadcastCacheUpdate`. * * @param options */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/broadcastUpdate/BroadcastCacheUpdate.ts#L61-L65
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BroadcastCacheUpdate.notifyIfUpdated
async notifyIfUpdated(options: CacheDidUpdateCallbackParam): Promise<void> { if (process.env.NODE_ENV !== "production") { assert!.isType(options.cacheName, "string", { moduleName: "serwist", className: "BroadcastCacheUpdate", funcName: "notifyIfUpdated", paramName: "cacheName", }); assert!.isInstance(options.newResponse, Response, { moduleName: "serwist", className: "BroadcastCacheUpdate", funcName: "notifyIfUpdated", paramName: "newResponse", }); assert!.isInstance(options.request, Request, { moduleName: "serwist", className: "BroadcastCacheUpdate", funcName: "notifyIfUpdated", paramName: "request", }); } // Without two responses there is nothing to compare. if (!options.oldResponse) { return; } if (!responsesAreSame(options.oldResponse, options.newResponse, this._headersToCheck)) { if (process.env.NODE_ENV !== "production") { logger.log("Newer response found (and cached) for:", options.request.url); } const messageData = { type: BROADCAST_UPDATE_MESSAGE_TYPE, meta: BROADCAST_UPDATE_MESSAGE_META, payload: this._generatePayload(options), } satisfies BroadcastMessage; // For navigation requests, wait until the new window client exists // before sending the message if (options.request.mode === "navigate") { let resultingClientId: string | undefined; if (options.event instanceof FetchEvent) { resultingClientId = options.event.resultingClientId; } const resultingWin = await resultingClientExists(resultingClientId); // Safari does not currently implement postMessage buffering and // there's no good way to feature detect that, so to increase the // chances of the message being delivered in Safari, we add a timeout. // We also do this if `resultingClientExists()` didn't return a client, // which means it timed out, so it's worth waiting a bit longer. if (!resultingWin || isSafari) { // 3500 is chosen because (according to CrUX data) 80% of mobile // websites hit the DOMContentLoaded event in less than 3.5 seconds. // And presumably sites implementing service worker are on the // higher end of the performance spectrum. await timeout(3500); } } if (this._notifyAllClients) { const windows = await self.clients.matchAll({ type: "window" }); for (const win of windows) { win.postMessage(messageData); } } else { // See https://github.com/GoogleChrome/workbox/issues/2895 if (options.event instanceof FetchEvent) { const client = await self.clients.get(options.event.clientId); client?.postMessage(messageData); } } } }
/** * Compares two responses and sends a message (via `postMessage()`) to all window clients if the * responses differ. Neither of the Responses can be opaque. * * The message that's posted has the following format (where `payload` can * be customized via the `generatePayload` option the instance is created * with): * * ``` * { * type: 'CACHE_UPDATED', * meta: 'workbox-broadcast-update', * payload: { * cacheName: 'the-cache-name', * updatedURL: 'https://example.com/' * } * } * ``` * * @param options * @returns Resolves once the update is sent. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/broadcastUpdate/BroadcastCacheUpdate.ts#L89-L164
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BroadcastUpdatePlugin.constructor
constructor(options?: BroadcastCacheUpdateOptions) { this._broadcastUpdate = new BroadcastCacheUpdate(options); }
/** * Construct a {@linkcode BroadcastCacheUpdate} instance with * the passed options and calls its {@linkcode BroadcastCacheUpdate.notifyIfUpdated} * method whenever the plugin's {@linkcode BroadcastUpdatePlugin.cacheDidUpdate} callback * is invoked. * * @param options */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/broadcastUpdate/BroadcastUpdatePlugin.ts#L28-L30
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
BroadcastUpdatePlugin.cacheDidUpdate
cacheDidUpdate(options: CacheDidUpdateCallbackParam) { void this._broadcastUpdate.notifyIfUpdated(options); }
/** * @private * @param options The input object to this function. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/broadcastUpdate/BroadcastUpdatePlugin.ts#L36-L38
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
CacheableResponse.constructor
constructor(config: CacheableResponseOptions = {}) { if (process.env.NODE_ENV !== "production") { if (!(config.statuses || config.headers)) { throw new SerwistError("statuses-or-headers-required", { moduleName: "serwist", className: "CacheableResponse", funcName: "constructor", }); } if (config.statuses) { assert!.isArray(config.statuses, { moduleName: "serwist", className: "CacheableResponse", funcName: "constructor", paramName: "config.statuses", }); } if (config.headers) { assert!.isType(config.headers, "object", { moduleName: "serwist", className: "CacheableResponse", funcName: "constructor", paramName: "config.headers", }); } } this._statuses = config.statuses; if (config.headers) { this._headers = new Headers(config.headers); } }
/** * To construct a new `CacheableResponse` instance you must provide at least * one of the `config` properties. * * If both `statuses` and `headers` are specified, then both conditions must * be met for the response to be considered cacheable. * * @param config */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/cacheableResponse/CacheableResponse.ts#L44-L77
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
CacheableResponse.isResponseCacheable
isResponseCacheable(response: Response): boolean { if (process.env.NODE_ENV !== "production") { assert!.isInstance(response, Response, { moduleName: "serwist", className: "CacheableResponse", funcName: "isResponseCacheable", paramName: "response", }); } let cacheable = true; if (this._statuses) { cacheable = this._statuses.includes(response.status); } if (this._headers && cacheable) { for (const [headerName, headerValue] of this._headers.entries()) { if (response.headers.get(headerName) !== headerValue) { cacheable = false; break; } } } if (process.env.NODE_ENV !== "production") { if (!cacheable) { logger.groupCollapsed( `The request for '${getFriendlyURL(response.url)}' returned a response that does not meet the criteria for being cached.`, ); logger.groupCollapsed("View cacheability criteria here."); logger.log(`Cacheable statuses: ${JSON.stringify(this._statuses)}`); logger.log(`Cacheable headers: ${JSON.stringify(this._headers, null, 2)}`); logger.groupEnd(); const logFriendlyHeaders: { [key: string]: string } = {}; response.headers.forEach((value, key) => { logFriendlyHeaders[key] = value; }); logger.groupCollapsed("View response status and headers here."); logger.log(`Response status: ${response.status}`); logger.log(`Response headers: ${JSON.stringify(logFriendlyHeaders, null, 2)}`); logger.groupEnd(); logger.groupCollapsed("View full response details here."); logger.log(response.headers); logger.log(response); logger.groupEnd(); logger.groupEnd(); } } return cacheable; }
/** * Checks a response to see whether it's cacheable or not. * * @param response The response whose cacheability is being * checked. * @returns `true` if the response is cacheable, and `false` * otherwise. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/cacheableResponse/CacheableResponse.ts#L87-L143
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
CacheableResponsePlugin.constructor
constructor(config: CacheableResponseOptions) { this._cacheableResponse = new CacheableResponse(config); }
/** * To construct a new `CacheableResponsePlugin` instance you must provide at * least one of the `config` properties. * * If both `statuses` and `headers` are specified, then both conditions must * be met for the response to be considered cacheable. * * @param config */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/cacheableResponse/CacheableResponsePlugin.ts#L30-L32
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
CacheableResponsePlugin.cacheWillUpdate
cacheWillUpdate: SerwistPlugin["cacheWillUpdate"] = async ({ response }) => { if (this._cacheableResponse.isResponseCacheable(response)) { return response; } return null; }
/** * @param options * @returns * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/cacheableResponse/CacheableResponsePlugin.ts
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
CacheExpiration.constructor
constructor(cacheName: string, config: CacheExpirationConfig = {}) { if (process.env.NODE_ENV !== "production") { assert!.isType(cacheName, "string", { moduleName: "serwist", className: "CacheExpiration", funcName: "constructor", paramName: "cacheName", }); if (!(config.maxEntries || config.maxAgeSeconds)) { throw new SerwistError("max-entries-or-age-required", { moduleName: "serwist", className: "CacheExpiration", funcName: "constructor", }); } if (config.maxEntries) { assert!.isType(config.maxEntries, "number", { moduleName: "serwist", className: "CacheExpiration", funcName: "constructor", paramName: "config.maxEntries", }); } if (config.maxAgeSeconds) { assert!.isType(config.maxAgeSeconds, "number", { moduleName: "serwist", className: "CacheExpiration", funcName: "constructor", paramName: "config.maxAgeSeconds", }); } } this._maxEntries = config.maxEntries; this._maxAgeSeconds = config.maxAgeSeconds; this._matchOptions = config.matchOptions; this._cacheName = cacheName; this._timestampModel = new CacheTimestampsModel(cacheName); }
/** * To construct a new `CacheExpiration` instance you must provide at least * one of the `config` properties. * * @param cacheName Name of the cache to apply restrictions to. * @param config */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/expiration/CacheExpiration.ts#L51-L92
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
CacheExpiration.expireEntries
async expireEntries(): Promise<void> { if (this._isRunning) { this._rerunRequested = true; return; } this._isRunning = true; const minTimestamp = this._maxAgeSeconds ? Date.now() - this._maxAgeSeconds * 1000 : 0; const urlsExpired = await this._timestampModel.expireEntries(minTimestamp, this._maxEntries); // Delete URLs from the cache const cache = await self.caches.open(this._cacheName); for (const url of urlsExpired) { await cache.delete(url, this._matchOptions); } if (process.env.NODE_ENV !== "production") { if (urlsExpired.length > 0) { logger.groupCollapsed( `Expired ${urlsExpired.length} ` + `${urlsExpired.length === 1 ? "entry" : "entries"} and removed ` + `${urlsExpired.length === 1 ? "it" : "them"} from the ` + `'${this._cacheName}' cache.`, ); logger.log(`Expired the following ${urlsExpired.length === 1 ? "URL" : "URLs"}:`); for (const url of urlsExpired) { logger.log(` ${url}`); } logger.groupEnd(); } else { logger.debug("Cache expiration ran and found no entries to remove."); } } this._isRunning = false; if (this._rerunRequested) { this._rerunRequested = false; void this.expireEntries(); } }
/** * Expires entries for the given cache and given criteria. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/expiration/CacheExpiration.ts#L97-L137
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
CacheExpiration.updateTimestamp
async updateTimestamp(url: string): Promise<void> { if (process.env.NODE_ENV !== "production") { assert!.isType(url, "string", { moduleName: "serwist", className: "CacheExpiration", funcName: "updateTimestamp", paramName: "url", }); } await this._timestampModel.setTimestamp(url, Date.now()); }
/** * Updates the timestamp for the given URL, allowing it to be correctly * tracked by the class. * * @param url */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/expiration/CacheExpiration.ts#L145-L156
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
CacheExpiration.isURLExpired
async isURLExpired(url: string): Promise<boolean> { if (!this._maxAgeSeconds) { if (process.env.NODE_ENV !== "production") { throw new SerwistError("expired-test-without-max-age", { methodName: "isURLExpired", paramName: "maxAgeSeconds", }); } return false; } const timestamp = await this._timestampModel.getTimestamp(url); const expireOlderThan = Date.now() - this._maxAgeSeconds * 1000; return timestamp !== undefined ? timestamp < expireOlderThan : true; }
/** * Checks if a URL has expired or not before it's used. * * This looks the timestamp up in IndexedDB and can be slow. * * Note: This method does not remove an expired entry, call * `expireEntries()` to remove such entries instead. * * @param url * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/expiration/CacheExpiration.ts#L169-L182
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
CacheExpiration.delete
async delete(): Promise<void> { // Make sure we don't attempt another rerun if we're called in the middle of // a cache expiration. this._rerunRequested = false; await this._timestampModel.expireEntries(Number.POSITIVE_INFINITY); // Expires all. }
/** * Removes the IndexedDB used to keep track of cache expiration metadata. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/expiration/CacheExpiration.ts#L187-L192
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
ExpirationPlugin.constructor
constructor(config: ExpirationPluginOptions = {}) { if (process.env.NODE_ENV !== "production") { if (!(config.maxEntries || config.maxAgeSeconds)) { throw new SerwistError("max-entries-or-age-required", { moduleName: "serwist", className: "ExpirationPlugin", funcName: "constructor", }); } if (config.maxEntries) { assert!.isType(config.maxEntries, "number", { moduleName: "serwist", className: "ExpirationPlugin", funcName: "constructor", paramName: "config.maxEntries", }); } if (config.maxAgeSeconds) { assert!.isType(config.maxAgeSeconds, "number", { moduleName: "serwist", className: "ExpirationPlugin", funcName: "constructor", paramName: "config.maxAgeSeconds", }); } if (config.maxAgeFrom) { assert!.isType(config.maxAgeFrom, "string", { moduleName: "serwist", className: "ExpirationPlugin", funcName: "constructor", paramName: "config.maxAgeFrom", }); } } this._config = config; this._cacheExpirations = new Map(); if (!this._config.maxAgeFrom) { this._config.maxAgeFrom = "last-fetched"; } if (this._config.purgeOnQuotaError) { registerQuotaErrorCallback(() => this.deleteCacheAndMetadata()); } }
/** * @param config */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/expiration/ExpirationPlugin.ts#L76-L124
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
ExpirationPlugin._getCacheExpiration
private _getCacheExpiration(cacheName: string): CacheExpiration { if (cacheName === privateCacheNames.getRuntimeName()) { throw new SerwistError("expire-custom-caches-only"); } let cacheExpiration = this._cacheExpirations.get(cacheName); if (!cacheExpiration) { cacheExpiration = new CacheExpiration(cacheName, this._config); this._cacheExpirations.set(cacheName, cacheExpiration); } return cacheExpiration; }
/** * A simple helper method to return a CacheExpiration instance for a given * cache name. * * @param cacheName * @returns * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/expiration/ExpirationPlugin.ts#L134-L145
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
ExpirationPlugin.cachedResponseWillBeUsed
cachedResponseWillBeUsed({ event, cacheName, request, cachedResponse }: CachedResponseWillBeUsedCallbackParam) { if (!cachedResponse) { return null; } const isFresh = this._isResponseDateFresh(cachedResponse); // Expire entries to ensure that even if the expiration date has // expired, it'll only be used once. const cacheExpiration = this._getCacheExpiration(cacheName); const isMaxAgeFromLastUsed = this._config.maxAgeFrom === "last-used"; const done = (async () => { // Update the metadata for the request URL to the current timestamp. // Only applies if `maxAgeFrom` is `"last-used"`, since the current // lifecycle callback is `cachedResponseWillBeUsed`. // This needs to be called before `expireEntries()` so as to avoid // this URL being marked as expired. if (isMaxAgeFromLastUsed) { await cacheExpiration.updateTimestamp(request.url); } await cacheExpiration.expireEntries(); })(); try { event.waitUntil(done); } catch (error) { if (process.env.NODE_ENV !== "production") { if (event instanceof FetchEvent) { logger.warn(`Unable to ensure service worker stays alive when updating cache entry for '${getFriendlyURL(event.request.url)}'.`); } } } return isFresh ? cachedResponse : null; }
/** * A lifecycle callback that will be triggered automatically when a * response is about to be returned from a [`Cache`](https://developer.mozilla.org/en-US/docs/Web/API/Cache). * It allows the response to be inspected for freshness and * prevents it from being used if the response's `Date` header value is * older than the configured `maxAgeSeconds`. * * @param options * @returns `cachedResponse` if it is fresh and `null` if it is stale or * not available. * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/expiration/ExpirationPlugin.ts#L159-L194
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
ExpirationPlugin._isResponseDateFresh
private _isResponseDateFresh(cachedResponse: Response): boolean { const isMaxAgeFromLastUsed = this._config.maxAgeFrom === "last-used"; // If `maxAgeFrom` is `"last-used"`, the `Date` header doesn't really // matter since it is about when the response was created. if (isMaxAgeFromLastUsed) { return true; } const now = Date.now(); if (!this._config.maxAgeSeconds) { return true; } // Check if the `Date` header will suffice a quick expiration check. // See https://github.com/GoogleChromeLabs/sw-toolbox/issues/164 for // discussion. const dateHeaderTimestamp = this._getDateHeaderTimestamp(cachedResponse); if (dateHeaderTimestamp === null) { // Unable to parse date, so assume it's fresh. return true; } // If we have a valid headerTime, then our response is fresh if the // headerTime plus maxAgeSeconds is greater than the current time. return dateHeaderTimestamp >= now - this._config.maxAgeSeconds * 1000; }
/** * @param cachedResponse * @returns * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/expiration/ExpirationPlugin.ts#L201-L223
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
ExpirationPlugin._getDateHeaderTimestamp
private _getDateHeaderTimestamp(cachedResponse: Response): number | null { if (!cachedResponse.headers.has("date")) { return null; } const dateHeader = cachedResponse.headers.get("date")!; const parsedDate = new Date(dateHeader); const headerTime = parsedDate.getTime(); // If the `Date` header is invalid for some reason, `parsedDate.getTime()` // will return NaN. if (Number.isNaN(headerTime)) { return null; } return headerTime; }
/** * Extracts the `Date` header and parse it into an useful value. * * @param cachedResponse * @returns * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/expiration/ExpirationPlugin.ts#L232-L248
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
ExpirationPlugin.cacheDidUpdate
async cacheDidUpdate({ cacheName, request }: CacheDidUpdateCallbackParam) { if (process.env.NODE_ENV !== "production") { assert!.isType(cacheName, "string", { moduleName: "serwist", className: "Plugin", funcName: "cacheDidUpdate", paramName: "cacheName", }); assert!.isInstance(request, Request, { moduleName: "serwist", className: "Plugin", funcName: "cacheDidUpdate", paramName: "request", }); } const cacheExpiration = this._getCacheExpiration(cacheName); await cacheExpiration.updateTimestamp(request.url); await cacheExpiration.expireEntries(); }
/** * A lifecycle callback that will be triggered automatically when an entry is added * to a cache. * * @param options * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/expiration/ExpirationPlugin.ts#L257-L276
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
ExpirationPlugin.deleteCacheAndMetadata
async deleteCacheAndMetadata(): Promise<void> { // Do this one at a time instead of all at once via `Promise.all()` to // reduce the chance of inconsistency if a promise rejects. for (const [cacheName, cacheExpiration] of this._cacheExpirations) { await self.caches.delete(cacheName); await cacheExpiration.delete(); } // Reset this._cacheExpirations to its initial state. this._cacheExpirations = new Map(); }
/** * Deletes the underlying `Cache` instance associated with this instance and the metadata * from IndexedDB used to keep track of expiration details for each `Cache` instance. * * When using cache expiration, calling this method is preferable to calling * `caches.delete()` directly, since this will ensure that the IndexedDB * metadata is also cleanly removed and that open IndexedDB instances are deleted. * * Note that if you're *not* using cache expiration for a given cache, calling * `caches.delete()` and passing in the cache's name should be sufficient. * There is no Serwist-specific method needed for cleanup in that case. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/expiration/ExpirationPlugin.ts#L290-L300
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
CacheTimestampsModel.constructor
constructor(cacheName: string) { this._cacheName = cacheName; }
/** * * @param cacheName * * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/expiration/models/CacheTimestampsModel.ts#L52-L54
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f