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
CacheTimestampsModel._getId
private _getId(url: string): string { return `${this._cacheName}|${normalizeURL(url)}`; }
/** * Takes a URL and returns an ID that will be unique in the object store. * * @param url * @returns * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/expiration/models/CacheTimestampsModel.ts#L63-L65
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
CacheTimestampsModel._upgradeDb
private _upgradeDb(db: IDBPDatabase<CacheDbSchema>) { const objStore = db.createObjectStore(CACHE_OBJECT_STORE, { keyPath: "id", }); // TODO(philipwalton): once we don't have to support EdgeHTML, we can // create a single index with the keyPath `['cacheName', 'timestamp']` // instead of doing...
/** * Performs an upgrade of indexedDB. * * @param db * * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/expiration/models/CacheTimestampsModel.ts#L74-L84
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
CacheTimestampsModel._upgradeDbAndDeleteOldDbs
private _upgradeDbAndDeleteOldDbs(db: IDBPDatabase<CacheDbSchema>) { this._upgradeDb(db); if (this._cacheName) { void deleteDB(this._cacheName); } }
/** * Performs an upgrade of indexedDB and deletes deprecated DBs. * * @param db * * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/expiration/models/CacheTimestampsModel.ts#L93-L98
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
CacheTimestampsModel.setTimestamp
async setTimestamp(url: string, timestamp: number): Promise<void> { url = normalizeURL(url); const entry = { id: this._getId(url), cacheName: this._cacheName, url, timestamp, } satisfies CacheTimestampsModelEntry; const db = await this.getDb(); const tx = db.transaction(CACH...
/** * @param url * @param timestamp * * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/expiration/models/CacheTimestampsModel.ts#L106-L121
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
CacheTimestampsModel.getTimestamp
async getTimestamp(url: string): Promise<number | undefined> { const db = await this.getDb(); const entry = await db.get(CACHE_OBJECT_STORE, this._getId(url)); return entry?.timestamp; }
/** * Returns the timestamp stored for a given URL. * * @param url * @returns * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/expiration/models/CacheTimestampsModel.ts#L130-L134
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
CacheTimestampsModel.expireEntries
async expireEntries(minTimestamp: number, maxCount?: number): Promise<string[]> { const db = await this.getDb(); let cursor = await db.transaction(CACHE_OBJECT_STORE, "readwrite").store.index("timestamp").openCursor(null, "prev"); const urlsDeleted: string[] = []; let entriesNotDeletedCount = 0; whi...
/** * Iterates through all the entries in the object store (from newest to * oldest) and removes entries once either `maxCount` is reached or the * entry's timestamp is less than `minTimestamp`. * * @param minTimestamp * @param maxCount * @returns * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/expiration/models/CacheTimestampsModel.ts#L146-L169
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
CacheTimestampsModel.getDb
private async getDb() { if (!this._db) { this._db = await openDB(DB_NAME, 1, { upgrade: this._upgradeDbAndDeleteOldDbs.bind(this), }); } return this._db; }
/** * Returns an open connection to the database. * * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/expiration/models/CacheTimestampsModel.ts#L176-L183
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...
/** * 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 functi...
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/googleAnalytics/initializeGoogleAnalytics.ts#L61-L122
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, "GE...
/** * 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/lib/googleAnalytics/initializeGoogleAnalytics.ts#L131-L139
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/lib/googleAnalytics/initializeGoogleAnalytics.ts#L148-L154
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/lib/googleAnalytics/initializeGoogleAnalytics.ts#L163-L169
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/lib/googleAnalytics/initializeGoogleAnalytics.ts#L178-L184
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
PrecacheFallbackPlugin.constructor
constructor({ fallbackUrls, serwist }: PrecacheFallbackPluginOptions) { this._fallbackUrls = fallbackUrls; this._serwist = serwist; }
/** * Constructs a new instance with the associated `fallbackUrls`. * * @param config */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/precaching/PrecacheFallbackPlugin.ts#L53-L56
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._serwist.matchPrecache(fallback); if (fallbackResponse !== undefined) { return fallbackResponse; }...
/** * @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/lib/precaching/PrecacheFallbackPlugin.ts#L63-L78
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
RangeRequestsPlugin.cachedResponseWillBeUsed
cachedResponseWillBeUsed: SerwistPlugin["cachedResponseWillBeUsed"] = async ({ request, cachedResponse }) => { // Only return a sliced response if there's something valid in the cache, // and there's a Range: header in the request. if (cachedResponse && request.headers.has("range")) { return await cre...
/** * @param options * @returns If request contains a `Range` header, then a * partial response whose body is a subset of `cachedResponse` is * returned. Otherwise, `cachedResponse` is returned as-is. * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/rangeRequests/RangeRequestsPlugin.ts
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
CacheFirst._handle
async _handle(request: Request, handler: StrategyHandler): Promise<Response> { const logs = []; if (process.env.NODE_ENV !== "production") { assert!.isInstance(request, Request, { moduleName: "serwist", className: this.constructor.name, funcName: "makeRequest", paramName: ...
/** * @private * @param request A request to run this strategy for. * @param handler The event that triggered the request. * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/strategies/CacheFirst.ts#L34-L87
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
CacheOnly._handle
async _handle(request: Request, handler: StrategyHandler): Promise<Response> { if (process.env.NODE_ENV !== "production") { assert!.isInstance(request, Request, { moduleName: "serwist", className: this.constructor.name, funcName: "makeRequest", paramName: "request", }); ...
/** * @private * @param request A request to run this strategy for. * @param handler The event that triggered the request. * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/strategies/CacheOnly.ts#L31-L58
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
NetworkFirst.constructor
constructor(options: NetworkFirstOptions = {}) { super(options); // If this instance contains no plugins with a 'cacheWillUpdate' callback, // prepend the `cacheOkAndOpaquePlugin` plugin to the plugins list. if (!this.plugins.some((p) => "cacheWillUpdate" in p)) { this.plugins.unshift(cacheOkAndO...
/** * @param options * This option can be used to combat * "[lie-fi](https://developers.google.com/web/fundamentals/performance/poor-connectivity/#lie-fi)" * scenarios. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/strategies/NetworkFirst.ts#L45-L65
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
NetworkFirst._handle
async _handle(request: Request, handler: StrategyHandler): Promise<Response> { const logs: any[] = []; if (process.env.NODE_ENV !== "production") { assert!.isInstance(request, Request, { moduleName: "serwist", className: this.constructor.name, funcName: "handle", paramName...
/** * @private * @param request A request to run this strategy for. * @param handler The event that triggered the request. * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/strategies/NetworkFirst.ts#L73-L135
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
NetworkFirst._getTimeoutPromise
private _getTimeoutPromise({ request, logs, handler, }: { request: Request; /** * A reference to the logs array. */ logs: any[]; handler: StrategyHandler; }): { promise: Promise<Response | undefined>; id?: number } { // biome-ignore lint/suspicious/noImplicitAnyLet: setTime...
/** * @param options * @returns * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/strategies/NetworkFirst.ts#L142-L170
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
NetworkFirst._getNetworkPromise
async _getNetworkPromise({ timeoutId, request, logs, handler, }: { request: Request; logs: any[]; timeoutId?: number; handler: StrategyHandler; }): Promise<Response | undefined> { let error: Error | undefined = undefined; let response: Response | undefined = undefined; tr...
/** * @param options * @param options.timeoutId * @param options.request * @param options.logs A reference to the logs Array. * @param options.event * @returns * * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/strategies/NetworkFirst.ts#L182-L228
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
NetworkOnly.constructor
constructor(options: NetworkOnlyOptions = {}) { super(options); this._networkTimeoutSeconds = options.networkTimeoutSeconds || 0; }
/** * @param options */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/strategies/NetworkOnly.ts#L39-L43
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
NetworkOnly._handle
async _handle(request: Request, handler: StrategyHandler): Promise<Response> { if (process.env.NODE_ENV !== "production") { assert!.isInstance(request, Request, { moduleName: "serwist", className: this.constructor.name, funcName: "_handle", paramName: "request", }); }...
/** * @private * @param request A request to run this strategy for. * @param handler The event that triggered the request. * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/strategies/NetworkOnly.ts#L51-L97
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
PrecacheStrategy.constructor
constructor(options: PrecacheStrategyOptions = {}) { options.cacheName = privateCacheNames.getPrecacheName(options.cacheName); super(options); this._fallbackToNetwork = options.fallbackToNetwork === false ? false : true; // Redirected responses cannot be used to satisfy a navigation request, so /...
/** * @param options */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/strategies/PrecacheStrategy.ts#L61-L73
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
PrecacheStrategy._handle
async _handle(request: Request, handler: StrategyHandler): Promise<Response> { const preloadResponse = await handler.getPreloadResponse(); if (preloadResponse) { return preloadResponse; } const response = await handler.cacheMatch(request); if (response) { return response; } /...
/** * @private * @param request A request to run this strategy for. * @param handler The event that triggered the request. * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/strategies/PrecacheStrategy.ts#L81-L103
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
PrecacheStrategy._useDefaultCacheabilityPluginIfNeeded
_useDefaultCacheabilityPluginIfNeeded(): void { let defaultPluginIndex: number | null = null; let cacheWillUpdatePluginCount = 0; for (const [index, plugin] of this.plugins.entries()) { // Ignore the copy redirected plugin when determining what to do. if (plugin === PrecacheStrategy.copyRedirec...
/** * This method is complex, as there a number of things to account for: * * The `plugins` array can be set at construction, and/or it might be added to * to at any time before the strategy is used. * * At the time the strategy is used (i.e. during an `install` event), there * needs to be at least...
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/strategies/PrecacheStrategy.ts#L226-L253
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
StaleWhileRevalidate.constructor
constructor(options: StrategyOptions = {}) { super(options); // If this instance contains no plugins with a 'cacheWillUpdate' callback, // prepend the `cacheOkAndOpaquePlugin` plugin to the plugins list. if (!this.plugins.some((p) => "cacheWillUpdate" in p)) { this.plugins.unshift(cacheOkAndOpaqu...
/** * @param options */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/strategies/StaleWhileRevalidate.ts#L40-L48
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
StaleWhileRevalidate._handle
async _handle(request: Request, handler: StrategyHandler): Promise<Response> { const logs = []; if (process.env.NODE_ENV !== "production") { assert!.isInstance(request, Request, { moduleName: "serwist", className: this.constructor.name, funcName: "handle", paramName: "requ...
/** * @private * @param request A request to run this strategy for. * @param handler The event that triggered the request. * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/strategies/StaleWhileRevalidate.ts#L56-L109
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
StrategyHandler.constructor
constructor( strategy: Strategy, options: HandlerCallbackOptions & { request: HandlerCallbackOptions["request"] & Request; }, ) { if (process.env.NODE_ENV !== "production") { assert!.isInstance(options.event, ExtendableEvent, { moduleName: "serwist", className: "StrategyHan...
/** * Creates a new instance associated with the passed strategy and event * that's handling the request. * * The constructor also initializes the state that will be passed to each of * the plugins handling this request. * * @param strategy * @param options */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/strategies/StrategyHandler.ts#L75-L115
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
StrategyHandler.fetch
async fetch(input: RequestInfo): Promise<Response> { const { event } = this; let request: Request = toRequest(input); const preloadResponse = await this.getPreloadResponse(); if (preloadResponse) { return preloadResponse; } // If there is a fetchDidFail plugin, we need to save a clone o...
/** * Fetches a given request (and invokes any applicable plugin callback * methods), taking the `fetchOptions` (for non-navigation requests) and * `plugins` provided to the {@linkcode Strategy} object into account. * * The following plugin lifecycle methods are invoked when using this method: * - `re...
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/strategies/StrategyHandler.ts#L130-L197
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
StrategyHandler.fetchAndCachePut
async fetchAndCachePut(input: RequestInfo): Promise<Response> { const response = await this.fetch(input); const responseClone = response.clone(); void this.waitUntil(this.cachePut(input, responseClone)); return response; }
/** * Calls `this.fetch()` and (in the background) caches the generated response. * * The call to `this.cachePut()` automatically invokes `this.waitUntil()`, * so you do not have to call `waitUntil()` yourself. * * @param input The request or URL to fetch and cache. * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/strategies/StrategyHandler.ts#L208-L215
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
StrategyHandler.cacheMatch
async cacheMatch(key: RequestInfo): Promise<Response | undefined> { const request: Request = toRequest(key); let cachedResponse: Response | undefined; const { cacheName, matchOptions } = this._strategy; const effectiveRequest = await this.getCacheKey(request, "read"); const multiMatchOptions = { .....
/** * Matches a request from the cache (and invokes any applicable plugin * callback method) using the `cacheName`, `matchOptions`, and `plugins` * provided to the `Strategy` object. * * The following lifecycle methods are invoked when using this method: * - `cacheKeyWillBeUsed` * - `cachedResponse...
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/strategies/StrategyHandler.ts#L229-L258
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
StrategyHandler.cachePut
async cachePut(key: RequestInfo, response: Response): Promise<boolean> { const request: Request = toRequest(key); // Run in the next task to avoid blocking other cache reads. // https://github.com/w3c/ServiceWorker/issues/1397 await timeout(0); const effectiveRequest = await this.getCacheKey(reque...
/** * Puts a request/response pair into the cache (and invokes any applicable * plugin callback method) using the `cacheName` and `plugins` provided to * the {@linkcode Strategy} object. * * The following plugin lifecycle methods are invoked when using this method: * - `cacheKeyWillBeUsed` * - `cac...
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/strategies/StrategyHandler.ts#L275-L367
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
StrategyHandler.getCacheKey
async getCacheKey(request: Request, mode: "read" | "write"): Promise<Request> { const key = `${request.url} | ${mode}`; if (!this._cacheKeys[key]) { let effectiveRequest = request; for (const callback of this.iterateCallbacks("cacheKeyWillBeUsed")) { effectiveRequest = toRequest( ...
/** * Checks the `plugins` provided to the {@linkcode Strategy} object for `cacheKeyWillBeUsed` * callbacks and executes found callbacks in sequence. The final `Request` * object returned by the last plugin is treated as the cache key for cache * reads and/or writes. If no `cacheKeyWillBeUsed` plugin callba...
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/strategies/StrategyHandler.ts#L380-L399
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
StrategyHandler.hasCallback
hasCallback<C extends keyof SerwistPlugin>(name: C): boolean { for (const plugin of this._strategy.plugins) { if (name in plugin) { return true; } } return false; }
/** * Returns `true` if the strategy has at least one plugin with the given * callback. * * @param name The name of the callback to check for. * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/strategies/StrategyHandler.ts#L408-L415
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
StrategyHandler.runCallbacks
async runCallbacks<C extends keyof NonNullable<SerwistPlugin>>(name: C, param: Omit<SerwistPluginCallbackParam[C], "state">): Promise<void> { for (const callback of this.iterateCallbacks(name)) { // TODO(philipwalton): not sure why `any` is needed. It seems like // this should work with `as SerwistPlugi...
/** * Runs all plugin callbacks matching the given name, in order, passing the * given param object as the only argument. * * Note: since this method runs all plugins, it's not suitable for cases * where the return value of a callback needs to be applied prior to calling * the next callback. See {@lin...
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/strategies/StrategyHandler.ts#L429-L435
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
StrategyHandler.iterateCallbacks
*iterateCallbacks<C extends keyof SerwistPlugin>(name: C): Generator<NonNullable<SerwistPlugin[C]>> { for (const plugin of this._strategy.plugins) { if (typeof plugin[name] === "function") { const state = this._pluginStateMap.get(plugin); const statefulCallback = (param: Omit<SerwistPluginCall...
/** * Accepts a callback name and returns an iterable of matching plugin callbacks. * * @param name The name fo the callback to run * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/strategies/StrategyHandler.ts#L443-L457
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
StrategyHandler.waitUntil
waitUntil<T>(promise: Promise<T>): Promise<T> { this._extendLifetimePromises.push(promise); return promise; }
/** * Adds a promise to the * [extend lifetime promises](https://w3c.github.io/ServiceWorker/#extendableevent-extend-lifetime-promises) * of the event event associated with the request being handled (usually a `FetchEvent`). * * Note: you can await {@linkcode StrategyHandler.doneWaiting} to know when all...
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/strategies/StrategyHandler.ts#L469-L472
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
StrategyHandler.doneWaiting
async doneWaiting(): Promise<void> { let promise: Promise<any> | undefined = undefined; while ((promise = this._extendLifetimePromises.shift())) { await promise; } }
/** * Returns a promise that resolves once all promises passed to * `this.waitUntil()` have settled. * * Note: any work done after `doneWaiting()` settles should be manually * passed to an event's `waitUntil()` method (not `this.waitUntil()`), otherwise * the service worker thread may be killed prior ...
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/strategies/StrategyHandler.ts#L482-L487
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
StrategyHandler.destroy
destroy(): void { this._handlerDeferred.resolve(null); }
/** * Stops running the strategy and immediately resolves any pending * `waitUntil()` promise. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/strategies/StrategyHandler.ts#L493-L495
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
StrategyHandler.getPreloadResponse
async getPreloadResponse(): Promise<Response | undefined> { if (this.event instanceof FetchEvent && this.event.request.mode === "navigate" && "preloadResponse" in this.event) { try { const possiblePreloadResponse = (await this.event.preloadResponse) as Response | undefined; if (possiblePreload...
/** * This method checks if the navigation preload `Response` is available. * * @param request * @param event * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/strategies/StrategyHandler.ts#L504-L522
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
StrategyHandler._ensureResponseSafeToCache
async _ensureResponseSafeToCache(response: Response): Promise<Response | undefined> { let responseToCache: Response | undefined = response; let pluginsUsed = false; for (const callback of this.iterateCallbacks("cacheWillUpdate")) { responseToCache = (await callback({ request: this.r...
/** * This method will call `cacheWillUpdate` on the available plugins (or use * status === 200) to determine if the response is safe and valid to cache. * * @param response * @returns * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/lib/strategies/StrategyHandler.ts#L532-L566
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
Deferred.constructor
constructor() { this.promise = new Promise((resolve, reject) => { this.resolve = resolve; this.reject = reject; }); }
/** * Creates a promise and exposes its resolve and reject functions as methods. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/utils/Deferred.ts#L25-L30
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
SerwistError.constructor
constructor(errorCode: MessageKey, details?: MapLikeObject) { const message = messageGenerator(errorCode, details); super(message); this.name = errorCode; this.details = details; }
/** * * @param errorCode The error code that * identifies this particular error. * @param details Any relevant arguments * that will help developers identify issues should * be added as a key on the context object. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/utils/SerwistError.ts#L33-L40
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
isArray
const isArray = (value: any[], details: MapLikeObject) => { if (!Array.isArray(value)) { throw new SerwistError("not-an-array", details); } };
/* * This method throws if the supplied value is not an array. * The destructed values are required to produce a meaningful error for users. * The destructed and restructured object is so it's clear what is * needed. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/utils/assert.ts#L18-L22
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
stripParams
function stripParams(fullURL: string, ignoreParams: string[]) { const strippedURL = new URL(fullURL); for (const param of ignoreParams) { strippedURL.searchParams.delete(param); } return strippedURL.href; }
/* Copyright 2020 Google LLC Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/utils/cacheMatchIgnoreParams.ts#L8-L14
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
cacheMatchIgnoreParams
async function cacheMatchIgnoreParams( cache: Cache, request: Request, ignoreParams: string[], matchOptions?: CacheQueryOptions, ): Promise<Response | undefined> { const strippedRequestURL = stripParams(request.url, ignoreParams); // If the request doesn't include any ignored params, match as normal. if ...
/** * Matches an item in the cache, ignoring specific URL params. This is similar * to the `ignoreSearch` option, but it allows you to ignore just specific * params (while continuing to match on the others). * * @private * @param cache * @param request * @param matchOptions * @param ignoreParams * @returns *...
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/utils/cacheMatchIgnoreParams.ts#L28-L52
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
canConstructReadableStream
function canConstructReadableStream(): boolean { if (supportStatus === undefined) { // See https://github.com/GoogleChrome/workbox/issues/1473 try { new ReadableStream({ start() {} }); supportStatus = true; } catch (error) { supportStatus = false; } } return supportStatus; }
/** * A utility function that determines whether the current browser supports * constructing a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream) * object. * * @returns `true`, if the current browser can successfully construct a `ReadableStream`, `false` otherwise. ...
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/utils/canConstructReadableStream.ts#L20-L32
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
canConstructResponseFromBodyStream
function canConstructResponseFromBodyStream(): boolean { if (supportStatus === undefined) { const testResponse = new Response(""); if ("body" in testResponse) { try { new Response(testResponse.body); supportStatus = true; } catch (error) { supportStatus = false; } ...
/** * A utility function that determines whether the current browser supports * constructing a new response from a `response.body` stream. * * @returns `true`, if the current browser can successfully construct * a response from a `response.body` stream, `false` otherwise. * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/utils/canConstructResponseFromBodyStream.ts#L19-L35
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
getFriendlyURL
const getFriendlyURL = (url: URL | string): string => { const urlObj = new URL(String(url), location.href); // See https://github.com/GoogleChrome/workbox/issues/2323 // We want to include everything, except for the origin if it's same-origin. return urlObj.href.replace(new RegExp(`^${location.origin}`), ""); }...
/* Copyright 2018 Google LLC Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/utils/getFriendlyURL.ts#L9-L14
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
logGroup
const logGroup = (groupTitle: string, deletedURLs: string[]) => { logger.groupCollapsed(groupTitle); for (const url of deletedURLs) { logger.log(url); } logger.groupEnd(); };
/** * @param groupTitle * @param deletedURLs * * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/utils/printCleanupDetails.ts#L17-L25
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
_nestedGroup
function _nestedGroup(groupTitle: string, urls: string[]): void { if (urls.length === 0) { return; } logger.groupCollapsed(groupTitle); for (const url of urls) { logger.log(url); } logger.groupEnd(); }
/** * @param groupTitle * @param urls * * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/utils/printInstallDetails.ts#L17-L29
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
withSerwistInit
const withSerwistInit = (userOptions: InjectManifestOptions): ((nextConfig?: NextConfig) => NextConfig) => { return (nextConfig = {}) => ({ ...nextConfig, webpack(config: Configuration, options) { const webpack: typeof Webpack = options.webpack; const { dev } = options; const basePath = ...
/** * Integrates Serwist into your Next.js app. * @param userOptions * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/next/src/index.ts#L21-L234
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
_getReaderFromSource
function _getReaderFromSource(source: StreamSource): ReadableStreamReader<unknown> { if (source instanceof Response) { // See https://github.com/GoogleChrome/workbox/issues/2998 if (source.body) { return source.body.getReader(); } throw new SerwistError("opaque-streams-source", { type: source.ty...
/** * Takes either a Response, a ReadableStream, or a * [BodyInit](https://fetch.spec.whatwg.org/#bodyinit) and returns the * ReadableStreamReader object associated with it. * * @param source * @returns * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/streams/src/concatenate.ts#L22-L34
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
concatenate
function concatenate(sourcePromises: Promise<StreamSource>[]): { done: Promise<void>; stream: ReadableStream; } { if (process.env.NODE_ENV !== "production") { assert!.isArray(sourcePromises, { moduleName: "@serwist/streams", funcName: "concatenate", paramName: "sourcePromises", }); } ...
/** * Takes multiple source Promises, each of which could resolve to a Response, a * ReadableStream, or a [BodyInit](https://fetch.spec.whatwg.org/#bodyinit). * * Returns an object exposing a ReadableStream with each individual stream's * data returned in sequence, along with a Promise which signals when the * st...
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/streams/src/concatenate.ts#L47-L129
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
concatenateToResponse
function concatenateToResponse(sourcePromises: Promise<StreamSource>[], headersInit: HeadersInit): { done: Promise<void>; response: Response } { const { done, stream } = concatenate(sourcePromises); const headers = createHeaders(headersInit); const response = new Response(stream, { headers }); return { done, ...
/** * Takes multiple source Promises, each of which could resolve to a Response, a * ReadableStream, or a [BodyInit](https://fetch.spec.whatwg.org/#bodyinit), * along with a * [HeadersInit](https://fetch.spec.whatwg.org/#typedefdef-headersinit). * * Returns an object exposing a Response whose body consists of eac...
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/streams/src/concatenateToResponse.ts#L27-L34
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
createHeaders
function createHeaders(headersInit = {}): Headers { // See https://github.com/GoogleChrome/workbox/issues/1461 const headers = new Headers(headersInit); if (!headers.has("content-type")) { headers.set("content-type", "text/html"); } return headers; }
/* Copyright 2018 Google LLC Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/streams/src/utils/createHeaders.ts#L20-L27
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
InjectManifest.constructor
constructor(config: InjectManifestOptions) { // We are essentially lying to TypeScript. When `handleMake` // is called, `this.config` will be replaced by a validated config. this.config = config as InjectManifestOptionsComplete; this.alreadyCalled = false; this.webpack = null!; }
/** * Creates an instance of InjectManifest. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/webpack-plugin/src/inject-manifest.ts#L47-L53
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
InjectManifest.propagateWebpackConfig
private propagateWebpackConfig(compiler: Compiler): void { this.webpack = compiler.webpack; const parsedSwSrc = path.parse(this.config.swSrc); // Because this.config is listed last, properties that are already set // there take precedence over derived properties from the compiler. this.config = { ...
/** * @param compiler default compiler object passed from webpack * * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/webpack-plugin/src/inject-manifest.ts#L60-L71
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
InjectManifest.getManifestEntries
private async getManifestEntries(compilation: Compilation, config: InjectManifestOptionsComplete) { if (config.disablePrecacheManifest) { return { size: 0, sortedEntries: undefined, manifestString: "undefined", }; } // See https://github.com/GoogleChrome/workbox/issues/1...
/** * `getManifestEntriesFromCompilation` with a few additional checks. * * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/webpack-plugin/src/inject-manifest.ts#L78-L115
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
InjectManifest.apply
apply(compiler: Compiler): void { this.propagateWebpackConfig(compiler); compiler.hooks.make.tapPromise(this.constructor.name, (compilation) => this.handleMake(compiler, compilation).catch((error: WebpackError) => { compilation.errors.push(error); }), ); // webpack should not be nu...
/** * @param compiler default compiler object passed from webpack * * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/webpack-plugin/src/inject-manifest.ts#L122-L149
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
InjectManifest.addSrcToAssets
private addSrcToAssets(compiler: Compiler, compilation: Compilation): void { const source = compiler.inputFileSystem!.readFileSync!(this.config.swSrc); compilation.emitAsset(this.config.swDest!, new this.webpack.sources.RawSource(source)); }
/** * @param compiler The webpack parent compiler. * @param compilation The webpack compilation. * * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/webpack-plugin/src/inject-manifest.ts#L157-L160
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
InjectManifest.handleMake
private async handleMake(compiler: Compiler, compilation: Compilation): Promise<void> { this.config = await validateInjectManifestOptions(this.config); this.config.swDest = relativeToOutputPath(compilation, this.config.swDest!); _generatedAssetNames.add(this.config.swDest); if (this.config.compileSrc) ...
/** * @param compiler The webpack parent compiler. * @param compilation The webpack compilation. * * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/webpack-plugin/src/inject-manifest.ts#L168-L190
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
InjectManifest.addAssets
private async addAssets(compilation: Compilation): Promise<void> { const config = Object.assign({}, this.config); const { size, sortedEntries, manifestString } = await this.getManifestEntries(compilation, config); // See https://webpack.js.org/contribute/plugin-patterns/#monitoring-the-watch-graph com...
/** * @param compilation The webpack compilation. * * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/webpack-plugin/src/inject-manifest.ts#L197-L245
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
ChildCompilationPlugin.apply
apply(compiler: Compiler) { compiler.hooks.make.tapPromise(this.constructor.name, (compilation) => performChildCompilation( compiler, compilation, this.constructor.name, this.src, relativeToOutputPath(compilation, this.dest), this.plugins, ).catch((error: ...
/** * @param compiler default compiler object passed from webpack * * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/webpack-plugin/src/lib/child-compilation-plugin.ts#L31-L44
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
checkConditions
const checkConditions = ( asset: Asset, compilation: Compilation, conditions: Array<string | RegExp | ((arg0: any) => boolean)> = [], ): boolean => { for (const condition of conditions) { if (typeof condition === "function") { return condition({ asset, compilation }); //return compilation !== n...
/** * For a given asset, checks whether at least one of the conditions matches. * * @param asset The webpack asset in question. This will be passed * to any functions that are listed as conditions. * @param compilation The webpack compilation. This will be passed * to any functions that are listed as conditions. ...
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/webpack-plugin/src/lib/get-manifest-entries-from-compilation.ts#L28-L46
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
getNamesOfAssetsInChunkOrGroup
const getNamesOfAssetsInChunkOrGroup = (compilation: Compilation, chunkOrGroup: string): string[] | null => { const chunkGroup = compilation.namedChunkGroups?.get(chunkOrGroup); if (chunkGroup) { const assetNames = []; for (const chunk of chunkGroup.chunks) { assetNames.push(...getNamesOfAssetsInChunk...
/** * Returns the names of all the assets in all the chunks in a chunk group, * if provided a chunk group name. * Otherwise, if provided a chunk name, return all the assets in that chunk. * Otherwise, if there isn't a chunk group or chunk with that name, return null. * * @param compilation * @param chunkOrGroup ...
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/webpack-plugin/src/lib/get-manifest-entries-from-compilation.ts#L59-L75
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
getNamesOfAssetsInChunk
const getNamesOfAssetsInChunk = (chunk: Chunk): string[] => { const assetNames: string[] = []; assetNames.push(...chunk.files); // This only appears to be set in webpack v5. if (chunk.auxiliaryFiles) { assetNames.push(...chunk.auxiliaryFiles); } return assetNames; };
/** * Returns the names of all the assets in a chunk. * * @param chunk * @returns * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/webpack-plugin/src/lib/get-manifest-entries-from-compilation.ts#L84-L95
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
filterAssets
const filterAssets = (compilation: Compilation, config: InjectManifestOptions): Set<Asset> => { const filteredAssets = new Set<Asset>(); const assets = compilation.getAssets(); const allowedAssetNames = new Set<string>(); // See https://github.com/GoogleChrome/workbox/issues/1287 if (Array.isArray(config.chu...
/** * Filters the set of assets out, based on the configuration options provided: * - chunks and excludeChunks, for chunkName-based criteria. * - include and exclude, for more general criteria. * * @param compilation The webpack compilation. * @param config The validated configuration, obtained from the plugin. ...
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/webpack-plugin/src/lib/get-manifest-entries-from-compilation.ts#L108-L177
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
Serwist.constructor
constructor(scriptURL: string | TrustedScriptURL, registerOptions: RegistrationOptions = {}) { super(); this._scriptURL = scriptURL; this._registerOptions = registerOptions; // Add a message listener immediately since messages received during // page load are buffered only until the DOMContentLoad...
/** * Creates a new Serwist instance with a script URL and service worker * options. The script URL and options are the same as those used when * calling [navigator.serviceWorker.register(scriptURL, options)](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register). * * @param sc...
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/window/src/Serwist.ts#L71-L81
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
Serwist.register
async register({ immediate = false, }: { /** * Setting this to true will register the service worker immediately, * even if the window has not loaded (not recommended). */ immediate?: boolean; } = {}): Promise<ServiceWorkerRegistration | undefined> { if (process.env.NODE_ENV !== "prod...
/** * Registers a service worker for this instances script URL and service * worker options. By default this method delays registration until after * the window has loaded. * * @param options */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/window/src/Serwist.ts#L90-L185
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
Serwist.update
async update(): Promise<void> { if (!this._registration) { if (process.env.NODE_ENV !== "production") { logger.error("Cannot update a Serwist instance without being registered. Register the Serwist instance first."); } return; } // Try to update registration await this._regist...
/** * Checks for updates of the registered service worker. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/window/src/Serwist.ts#L190-L200
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
Serwist.active
get active(): Promise<ServiceWorker> { return this._activeDeferred.promise; }
/** * Resolves to the service worker registered by this instance as soon as it * is active. If a service worker was already controlling at registration * time then it will resolve to that if the script URLs (and optionally * script versions) match, otherwise it will wait until an update is found * and ac...
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/window/src/Serwist.ts#L211-L213
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
Serwist.controlling
get controlling(): Promise<ServiceWorker> { return this._controllingDeferred.promise; }
/** * Resolves to the service worker registered by this instance as soon as it * is controlling the page. If a service worker was already controlling at * registration time then it will resolve to that if the script URLs (and * optionally script versions) match, otherwise it will wait until an update * i...
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/window/src/Serwist.ts#L227-L229
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
Serwist.getSW
getSW(): Promise<ServiceWorker> { // If `this._sw` is set, resolve with that as we want `getSW()` to // return the correct (new) service worker if an update is found. return this._sw !== undefined ? Promise.resolve(this._sw) : this._swDeferred.promise; }
/** * Resolves with a reference to a service worker that matches the script URL * of this instance, as soon as it's available. * * If, at registration time, there's already an active or waiting service * worker with a matching script URL, it will be used (with the waiting * service worker taking prece...
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/window/src/Serwist.ts#L246-L250
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
Serwist.messageSW
async messageSW(data: any): Promise<any> { const sw = await this.getSW(); return messageSW(sw, data); }
// We might be able to change the 'data' type to Record<string, unknown> in the future.
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/window/src/Serwist.ts#L264-L267
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
Serwist.messageSkipWaiting
messageSkipWaiting(): void { if (this._registration?.waiting) { void messageSW(this._registration.waiting, SKIP_WAITING_MESSAGE); } }
/** * Sends a `{ type: "SKIP_WAITING" }` message to the service worker that is * currently waiting and associated with the current registration. * * If there is no current registration, or no service worker is waiting, * calling this will have no effect. */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/window/src/Serwist.ts#L276-L280
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
Serwist._getControllingSWIfCompatible
private _getControllingSWIfCompatible() { const controller = navigator.serviceWorker.controller; if (controller && urlsMatch(controller.scriptURL, this._scriptURL.toString())) { return controller; } return undefined; }
/** * Checks for a service worker already controlling the page and returns * it if its script URL matches. * * @private * @returns */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/window/src/Serwist.ts#L289-L295
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
Serwist._registerScript
private async _registerScript() { try { // this._scriptURL may be a TrustedScriptURL, but there's no support for // passing that to register() in lib.dom right now. // https://github.com/GoogleChrome/workbox/issues/2855 const reg = await navigator.serviceWorker.register(this._scriptURL as st...
/** * Registers a service worker for this instances script URL and register * options and tracks the time registration was complete. * * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/window/src/Serwist.ts#L303-L323
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
Serwist._onControllerChange
private readonly _onUpdateFound = (originalEvent: Event) => { // `this._registration` will never be `undefined` after an update is found. const registration = this._registration!; const installingSW = registration.installing as ServiceWorker; // If the script URL passed to `navigator.serviceWorker.regi...
/** * @private * @param originalEvent */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/window/src/Serwist.ts
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
SerwistEventTarget.addEventListener
addEventListener<K extends keyof SerwistEventMap>(type: K, listener: (event: SerwistEventMap[K]) => any): void { const foo = this._getEventListenersByType(type); foo.add(listener as ListenerCallback); }
/** * @param type * @param listener * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/window/src/utils/SerwistEventTarget.ts#L27-L30
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
SerwistEventTarget.removeEventListener
removeEventListener<K extends keyof SerwistEventMap>(type: K, listener: (event: SerwistEventMap[K]) => any): void { this._getEventListenersByType(type).delete(listener as ListenerCallback); }
/** * @param type * @param listener * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/window/src/utils/SerwistEventTarget.ts#L37-L39
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
SerwistEventTarget.dispatchEvent
dispatchEvent(event: SerwistEvent<any>): void { event.target = this; const listeners = this._getEventListenersByType(event.type); for (const listener of listeners) { listener(event); } }
/** * @param event * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/window/src/utils/SerwistEventTarget.ts#L45-L52
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
serwist
github_2023
serwist
typescript
SerwistEventTarget._getEventListenersByType
private _getEventListenersByType(type: keyof SerwistEventMap) { if (!this._eventListenerRegistry.has(type)) { this._eventListenerRegistry.set(type, new Set()); } return this._eventListenerRegistry.get(type)!; }
/** * Returns a Set of listeners associated with the passed event type. * If no handlers have been registered, an empty Set is returned. * * @param type The event type. * @returns An array of handler functions. * @private */
https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/window/src/utils/SerwistEventTarget.ts#L62-L67
9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f
codeshell-vscode
github_2023
WisdomShell
typescript
CodeShellCompletionProvider.provideInlineCompletionItems
public async provideInlineCompletionItems(document: TextDocument, position: Position, context: InlineCompletionContext, token: CancellationToken): ProviderResult<InlineCompletionItem[] | InlineCompletionList> { let autoTriggerEnabled = CODESHELL_CONFIG.get("AutoTriggerCompletion") as boolean; if (contex...
// because ASYNC and PROMISE
https://github.com/WisdomShell/codeshell-vscode/blob/00c045b1c08fea8df7adcfa354b443ecdc1fa429/src/CodeShellCompletionProvider.ts#L16-L52
00c045b1c08fea8df7adcfa354b443ecdc1fa429
we-drawing
github_2023
liruifengv
typescript
BingImageCreator.createImage
async createImage(prompt: string) { const encodedPrompt = encodeURIComponent(prompt); let formData = new FormData(); formData.append("q", encodedPrompt); formData.append("qa", "ds"); console.log("Sending request..."); // rt=3 or rt=4 const url = `${BING_URL}/image...
/** * Create image * @param prompt - The prompt * @returns The image links */
https://github.com/liruifengv/we-drawing/blob/0a555f208d7c7421d44ba9dd37ec926338f54411/src/bing-image-creator.ts#L24-L47
0a555f208d7c7421d44ba9dd37ec926338f54411
we-drawing
github_2023
liruifengv
typescript
BingImageCreator.getResults
async getResults(getResultUrl: string) { const response = await fetch(getResultUrl, { method: "GET", mode: "cors", credentials: "include", headers: { cookie: this._cookie, ...HEADERS, }, }); if (response....
/** * Get the result * @param getResultUrl - The result url * @returns The result */
https://github.com/liruifengv/we-drawing/blob/0a555f208d7c7421d44ba9dd37ec926338f54411/src/bing-image-creator.ts#L113-L132
0a555f208d7c7421d44ba9dd37ec926338f54411
we-drawing
github_2023
liruifengv
typescript
BingImageCreator.parseResult
parseResult(result: string) { console.log("Parsing result..."); // Use regex to search for src="" const regex = /src="([^"]*)"/g; const matches = [...result.matchAll(regex)].map((match) => match[1]); console.log("Found", matches.length, "images"); // # Remove size limit ...
/** * Parse the result * @param result - The result * @returns The image links */
https://github.com/liruifengv/we-drawing/blob/0a555f208d7c7421d44ba9dd37ec926338f54411/src/bing-image-creator.ts#L138-L163
0a555f208d7c7421d44ba9dd37ec926338f54411
we-drawing
github_2023
liruifengv
typescript
getSentence
async function getSentence(): Promise<SentenceResponse> { try { const res = await fetch(SENTENCE_API); const data: SentenceResponse = await res.json(); return data; } catch (e) { throw new Error("Request Sentence failed: ", e); } }
/** * Get the sentence * @returns SentenceResponse * @throws {Error} The error **/
https://github.com/liruifengv/we-drawing/blob/0a555f208d7c7421d44ba9dd37ec926338f54411/src/get-up.ts#L12-L20
0a555f208d7c7421d44ba9dd37ec926338f54411
denokv
github_2023
denoland
typescript
commitBatch
const commitBatch = async (n: number) => { const atomic = kv.atomic(); for (let i = 0; i < n; i++) { atomic.set(["batch", i], `${i}`); } return await atomic.commit(); };
// KV atomic mutation limits (currently 10 per atomic batch)
https://github.com/denoland/denokv/blob/7edec27ef2dba02ca3570aff25f4764706129ab0/npm/src/e2e.ts#L576-L582
7edec27ef2dba02ca3570aff25f4764706129ab0
denokv
github_2023
denoland
typescript
toArray
async function toArray<T>(iter: AsyncIterableIterator<T>): Promise<T[]> { const rt: T[] = []; for await (const item of iter) { rt.push(item); } return rt; }
//
https://github.com/denoland/denokv/blob/7edec27ef2dba02ca3570aff25f4764706129ab0/npm/src/e2e.ts#L656-L662
7edec27ef2dba02ca3570aff25f4764706129ab0
denokv
github_2023
denoland
typescript
clear
async function clear(service: KvService, path: string) { const kv = await service.openKv(path); const keys: KvKey[] = []; for await (const { key } of kv.list({ prefix: [] })) { keys.push(key); } for (const batch of chunk(keys, 1000)) { let tx = kv.atomic(); for (const key of batch) { tx = tx...
//
https://github.com/denoland/denokv/blob/7edec27ef2dba02ca3570aff25f4764706129ab0/npm/src/e2e_test.ts#L56-L70
7edec27ef2dba02ca3570aff25f4764706129ab0
denokv
github_2023
denoland
typescript
InMemoryKv.getOne
private getOne<T>(key: KvKey): KvEntryMaybe<T> { const row = this.rows.find(keyRow(packKey(key))); return row ? { key, value: copyValueIfNecessary(row[1]) as T, versionstamp: row[2] } : { key, value: null, versionstamp: null }; }
//
https://github.com/denoland/denokv/blob/7edec27ef2dba02ca3570aff25f4764706129ab0/npm/src/in_memory.ts#L357-L362
7edec27ef2dba02ca3570aff25f4764706129ab0
denokv
github_2023
denoland
typescript
checkValueHolder
function checkValueHolder(obj: unknown) { const valid = typeof obj === "object" && obj !== null && !Array.isArray(obj) && "value" in obj && typeof obj.value === "bigint"; if (!valid) throw new Error(`Expected bigint holder, found: ${obj}`); }
//
https://github.com/denoland/denokv/blob/7edec27ef2dba02ca3570aff25f4764706129ab0/npm/src/kv_u64.ts#L37-L41
7edec27ef2dba02ca3570aff25f4764706129ab0
denokv
github_2023
denoland
typescript
GenericKvListIterator.return
return?(value?: any): Promise<IteratorResult<KvEntry<T>, any>> { return this.generator.return(value); }
// deno-lint-ignore no-explicit-any
https://github.com/denoland/denokv/blob/7edec27ef2dba02ca3570aff25f4764706129ab0/npm/src/kv_util.ts#L197-L199
7edec27ef2dba02ca3570aff25f4764706129ab0
denokv
github_2023
denoland
typescript
GenericKvListIterator.throw
throw?(e?: any): Promise<IteratorResult<KvEntry<T>, any>> { return this.generator.throw(e); }
// deno-lint-ignore no-explicit-any
https://github.com/denoland/denokv/blob/7edec27ef2dba02ca3570aff25f4764706129ab0/npm/src/kv_util.ts#L202-L204
7edec27ef2dba02ca3570aff25f4764706129ab0
denokv
github_2023
denoland
typescript
Expirer.runExpirer
private runExpirer() { const { expireFn } = this; const newMinExpires = expireFn(); this.minExpires = newMinExpires; if (newMinExpires !== undefined) { this.rescheduleExpirer(newMinExpires); } else { clearTimeout(this.expirerTimeout); } }
//
https://github.com/denoland/denokv/blob/7edec27ef2dba02ca3570aff25f4764706129ab0/npm/src/kv_util.ts#L465-L474
7edec27ef2dba02ca3570aff25f4764706129ab0
denokv
github_2023
denoland
typescript
resolveEndpointUrl
function resolveEndpointUrl(url: string, responseUrl: string): string { const u = new URL(url, responseUrl); const str = u.toString(); return u.pathname === "/" ? str.substring(0, str.length - 1) : str; }
//
https://github.com/denoland/denokv/blob/7edec27ef2dba02ca3570aff25f4764706129ab0/npm/src/remote.ts#L94-L98
7edec27ef2dba02ca3570aff25f4764706129ab0
denokv
github_2023
denoland
typescript
RemoteKv.locateEndpointUrl
private async locateEndpointUrl( consistency: KvConsistencyLevel, forceRefetch = false, ): Promise<string> { const { url, accessToken, debug, fetcher, maxRetries, supportedVersions } = this; if (forceRefetch || computeExpiresInMillis(this.metadata) < 1000 * 60 * 5) { this.metadata = await ...
//
https://github.com/denoland/denokv/blob/7edec27ef2dba02ca3570aff25f4764706129ab0/npm/src/remote.ts#L500-L528
7edec27ef2dba02ca3570aff25f4764706129ab0
siyuan-unlock
github_2023
appdev
typescript
BlockPanel.constructor
constructor(options: { app: App, targetElement?: HTMLElement, nodeIds?: string[], defIds?: string[], isBacklink: boolean, x?: number, y?: number }) { this.id = genUUID(); this.targetElement = options.targetElement; this.nodeIds = option...
// x,y 和 targetElement 二选一必传
https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/block/Panel.ts#L34-L146
d6bf65b650165c80c1feadb9c6e19fe01a26105d