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 both these indexes.
objStore.createIndex("cacheName", "cacheName", { unique: false });
objStore.createIndex("timestamp", "timestamp", { unique: false });
} | /**
* 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(CACHE_OBJECT_STORE, "readwrite", {
durability: "relaxed",
});
await tx.store.put(entry);
await tx.done;
} | /**
* @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;
while (cursor) {
const result = cursor.value;
// TODO(philipwalton): once we can use a multi-key index, we
// won't have to check `cacheName` here.
if (result.cacheName === this._cacheName) {
// Delete an entry if it's older than the max age or
// if we already have the max number allowed.
if ((minTimestamp && result.timestamp < minTimestamp) || (maxCount && entriesNotDeletedCount >= maxCount)) {
cursor.delete();
urlsDeleted.push(result.url);
} else {
entriesNotDeletedCount++;
}
}
cursor = await cursor.continue();
}
return urlsDeleted;
} | /**
* 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, 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/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, "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/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;
}
} else if (fallback.matcher(param)) {
const fallbackResponse = await this._serwist.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/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 createPartialResponse(request, cachedResponse);
}
// If there was no Range: header, or if cachedResponse wasn't valid, just
// pass it through as-is.
return cachedResponse;
} | /**
* @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: "request",
});
}
let response = await handler.cacheMatch(request);
let error: Error | undefined = undefined;
if (!response) {
if (process.env.NODE_ENV !== "production") {
logs.push(`No response found in the '${this.cacheName}' cache. Will respond with a network request.`);
}
try {
response = await handler.fetchAndCachePut(request);
} catch (err) {
if (err instanceof Error) {
error = err;
}
}
if (process.env.NODE_ENV !== "production") {
if (response) {
logs.push("Got response from network.");
} else {
logs.push("Unable to get a response from the network.");
}
}
} else {
if (process.env.NODE_ENV !== "production") {
logs.push(`Found a cached response in the '${this.cacheName}' cache.`);
}
}
if (process.env.NODE_ENV !== "production") {
logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));
for (const log of logs) {
logger.log(log);
}
messages.printFinalResponse(response);
logger.groupEnd();
}
if (!response) {
throw new SerwistError("no-response", { url: request.url, error });
}
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/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",
});
}
const response = await handler.cacheMatch(request);
if (process.env.NODE_ENV !== "production") {
logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));
if (response) {
logger.log(`Found a cached response in the '${this.cacheName}' cache.`);
messages.printFinalResponse(response);
} else {
logger.log(`No response found in the '${this.cacheName}' cache.`);
}
logger.groupEnd();
}
if (!response) {
throw new SerwistError("no-response", { url: request.url });
}
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/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(cacheOkAndOpaquePlugin);
}
this._networkTimeoutSeconds = options.networkTimeoutSeconds || 0;
if (process.env.NODE_ENV !== "production") {
if (this._networkTimeoutSeconds) {
assert!.isType(this._networkTimeoutSeconds, "number", {
moduleName: "serwist",
className: this.constructor.name,
funcName: "constructor",
paramName: "networkTimeoutSeconds",
});
}
}
} | /**
* @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: "makeRequest",
});
}
const promises: Promise<Response | undefined>[] = [];
let timeoutId: number | undefined;
if (this._networkTimeoutSeconds) {
const { id, promise } = this._getTimeoutPromise({
request,
logs,
handler,
});
timeoutId = id;
promises.push(promise);
}
const networkPromise = this._getNetworkPromise({
timeoutId,
request,
logs,
handler,
});
promises.push(networkPromise);
const response = await handler.waitUntil(
(async () => {
// Promise.race() will resolve as soon as the first promise resolves.
return (
(await handler.waitUntil(Promise.race(promises))) ||
// If Promise.race() resolved with null, it might be due to a network
// timeout + a cache miss. If that were to happen, we'd rather wait until
// the networkPromise resolves instead of returning null.
// Note that it's fine to await an already-resolved promise, so we don't
// have to check to see if it's still "in flight".
(await networkPromise)
);
})(),
);
if (process.env.NODE_ENV !== "production") {
logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));
for (const log of logs) {
logger.log(log);
}
messages.printFinalResponse(response);
logger.groupEnd();
}
if (!response) {
throw new SerwistError("no-response", { url: request.url });
}
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/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: setTimeout is typed with Node.js's typings, so we can't use number | undefined here.
let timeoutId;
const timeoutPromise: Promise<Response | undefined> = new Promise((resolve) => {
const onNetworkTimeout = async () => {
if (process.env.NODE_ENV !== "production") {
logs.push(`Timing out the network response at ${this._networkTimeoutSeconds} seconds.`);
}
resolve(await handler.cacheMatch(request));
};
timeoutId = setTimeout(onNetworkTimeout, this._networkTimeoutSeconds * 1000);
});
return {
promise: timeoutPromise,
id: timeoutId,
};
} | /**
* @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;
try {
response = await handler.fetchAndCachePut(request);
} catch (fetchError) {
if (fetchError instanceof Error) {
error = fetchError;
}
}
if (timeoutId) {
clearTimeout(timeoutId);
}
if (process.env.NODE_ENV !== "production") {
if (response) {
logs.push("Got response from network.");
} else {
logs.push("Unable to get a response from the network. Will respond " + "with a cached response.");
}
}
if (error || !response) {
response = await handler.cacheMatch(request);
if (process.env.NODE_ENV !== "production") {
if (response) {
logs.push(`Found a cached response in the '${this.cacheName}' cache.`);
} else {
logs.push(`No response found in the '${this.cacheName}' cache.`);
}
}
}
return response;
} | /**
* @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",
});
}
let error: Error | undefined = undefined;
let response: Response | undefined;
try {
const promises: Promise<Response | undefined>[] = [handler.fetch(request)];
if (this._networkTimeoutSeconds) {
const timeoutPromise = timeout(this._networkTimeoutSeconds * 1000) as Promise<undefined>;
promises.push(timeoutPromise);
}
response = await Promise.race(promises);
if (!response) {
throw new Error(`Timed out the network response after ${this._networkTimeoutSeconds} seconds.`);
}
} catch (err) {
if (err instanceof Error) {
error = err;
}
}
if (process.env.NODE_ENV !== "production") {
logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));
if (response) {
logger.log("Got response from network.");
} else {
logger.log("Unable to get a response from the network.");
}
messages.printFinalResponse(response);
logger.groupEnd();
}
if (!response) {
throw new SerwistError("no-response", { url: request.url, error });
}
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/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
// any redirected response must be "copied" rather than cloned, so the new
// response doesn't contain the `redirected` flag. See:
// https://bugs.chromium.org/p/chromium/issues/detail?id=669363&desc=2#c1
this.plugins.push(PrecacheStrategy.copyRedirectedCacheableResponsesPlugin);
} | /**
* @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;
}
// If this is an `install` event for an entry that isn't already cached,
// then populate the cache.
if (handler.event && handler.event.type === "install") {
return await this._handleInstall(request, handler);
}
// Getting here means something went wrong. An entry that should have been
// precached wasn't found in the cache.
return await this._handleFetch(request, handler);
} | /**
* @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.copyRedirectedCacheableResponsesPlugin) {
continue;
}
// Save the default plugin's index, in case it needs to be removed.
if (plugin === PrecacheStrategy.defaultPrecacheCacheabilityPlugin) {
defaultPluginIndex = index;
}
if (plugin.cacheWillUpdate) {
cacheWillUpdatePluginCount++;
}
}
if (cacheWillUpdatePluginCount === 0) {
this.plugins.push(PrecacheStrategy.defaultPrecacheCacheabilityPlugin);
} else if (cacheWillUpdatePluginCount > 1 && defaultPluginIndex !== null) {
// Only remove the default plugin; multiple custom plugins are allowed.
this.plugins.splice(defaultPluginIndex, 1);
}
// Nothing needs to be done if cacheWillUpdatePluginCount is 1
} | /**
* 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 one plugin that implements `cacheWillUpdate` in the
* array, other than `copyRedirectedCacheableResponsesPlugin`.
*
* - If this method is called and there are no suitable `cacheWillUpdate`
* plugins, we need to add `defaultPrecacheCacheabilityPlugin`.
*
* - If this method is called and there is exactly one `cacheWillUpdate`, then
* we don't have to do anything (this might be a previously added
* `defaultPrecacheCacheabilityPlugin`, or it might be a custom plugin).
*
* - If this method is called and there is more than one `cacheWillUpdate`,
* then we need to check if one is `defaultPrecacheCacheabilityPlugin`. If so,
* we need to remove it. (This situation is unlikely, but it could happen if
* the strategy is used multiple times, the first without a `cacheWillUpdate`,
* and then later on after manually adding a custom `cacheWillUpdate`.)
*
* See https://github.com/GoogleChrome/workbox/issues/2737 for more context.
*
* @private
*/ | 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(cacheOkAndOpaquePlugin);
}
} | /**
* @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: "request",
});
}
const fetchAndCachePromise = handler.fetchAndCachePut(request).catch(() => {
// Swallow this error because a 'no-response' error will be thrown in
// main handler return flow. This will be in the `waitUntil()` flow.
});
void handler.waitUntil(fetchAndCachePromise);
let response = await handler.cacheMatch(request);
let error: Error | undefined = undefined;
if (response) {
if (process.env.NODE_ENV !== "production") {
logs.push(`Found a cached response in the '${this.cacheName}' cache. Will update with the network response in the background.`);
}
} else {
if (process.env.NODE_ENV !== "production") {
logs.push(`No response found in the '${this.cacheName}' cache. Will wait for the network response.`);
}
try {
// NOTE(philipwalton): Really annoying that we have to type cast here.
// https://github.com/microsoft/TypeScript/issues/20006
response = (await fetchAndCachePromise) as Response | undefined;
} catch (err) {
if (err instanceof Error) {
error = err;
}
}
}
if (process.env.NODE_ENV !== "production") {
logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));
for (const log of logs) {
logger.log(log);
}
messages.printFinalResponse(response);
logger.groupEnd();
}
if (!response) {
throw new SerwistError("no-response", { url: request.url, error });
}
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/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: "StrategyHandler",
funcName: "constructor",
paramName: "options.event",
});
assert!.isInstance(options.request, Request, {
moduleName: "serwist",
className: "StrategyHandler",
funcName: "constructor",
paramName: "options.request",
});
}
this.event = options.event;
this.request = options.request;
if (options.url) {
this.url = options.url;
this.params = options.params;
}
this._strategy = strategy;
this._handlerDeferred = new Deferred();
this._extendLifetimePromises = [];
// Copy the plugins list (since it's mutable on the strategy),
// so any mutations don't affect this handler instance.
this._plugins = [...strategy.plugins];
this._pluginStateMap = new Map();
for (const plugin of this._plugins) {
this._pluginStateMap.set(plugin, {});
}
this.event.waitUntil(this._handlerDeferred.promise);
} | /**
* 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 of the
// original request before it's either modified by a requestWillFetch
// plugin or before the original request's body is consumed via fetch().
const originalRequest = this.hasCallback("fetchDidFail") ? request.clone() : null;
try {
for (const cb of this.iterateCallbacks("requestWillFetch")) {
request = await cb({ request: request.clone(), event });
}
} catch (err) {
if (err instanceof Error) {
throw new SerwistError("plugin-error-request-will-fetch", {
thrownErrorMessage: err.message,
});
}
}
// The request can be altered by plugins with `requestWillFetch` making
// the original request (most likely from a `fetch` event) different
// from the Request we make. Pass both to `fetchDidFail` to aid debugging.
const pluginFilteredRequest: Request = request.clone();
try {
let fetchResponse: Response;
// See https://github.com/GoogleChrome/workbox/issues/1796
fetchResponse = await fetch(request, request.mode === "navigate" ? undefined : this._strategy.fetchOptions);
if (process.env.NODE_ENV !== "production") {
logger.debug(`Network request for '${getFriendlyURL(request.url)}' returned a response with status '${fetchResponse.status}'.`);
}
for (const callback of this.iterateCallbacks("fetchDidSucceed")) {
fetchResponse = await callback({
event,
request: pluginFilteredRequest,
response: fetchResponse,
});
}
return fetchResponse;
} catch (error) {
if (process.env.NODE_ENV !== "production") {
logger.log(`Network request for '${getFriendlyURL(request.url)}' threw an error.`, error);
}
// `originalRequest` will only exist if a `fetchDidFail` callback
// is being used (see above).
if (originalRequest) {
await this.runCallbacks("fetchDidFail", {
error: error as Error,
event,
originalRequest: originalRequest.clone(),
request: pluginFilteredRequest.clone(),
});
}
throw error;
}
} | /**
* 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:
* - `requestWillFetch()`
* - `fetchDidSucceed()`
* - `fetchDidFail()`
*
* @param input The URL or request to fetch.
* @returns
*/ | 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 = { ...matchOptions, ...{ cacheName } };
cachedResponse = await caches.match(effectiveRequest, multiMatchOptions);
if (process.env.NODE_ENV !== "production") {
if (cachedResponse) {
logger.debug(`Found a cached response in '${cacheName}'.`);
} else {
logger.debug(`No cached response found in '${cacheName}'.`);
}
}
for (const callback of this.iterateCallbacks("cachedResponseWillBeUsed")) {
cachedResponse =
(await callback({
cacheName,
matchOptions,
cachedResponse,
request: effectiveRequest,
event: this.event,
})) || undefined;
}
return cachedResponse;
} | /**
* 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`
* - `cachedResponseWillBeUsed`
*
* @param key The `Request` or `URL` object to use as the cache key.
* @returns A matching response, if found.
*/ | 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(request, "write");
if (process.env.NODE_ENV !== "production") {
if (effectiveRequest.method && effectiveRequest.method !== "GET") {
throw new SerwistError("attempt-to-cache-non-get-request", {
url: getFriendlyURL(effectiveRequest.url),
method: effectiveRequest.method,
});
}
}
if (!response) {
if (process.env.NODE_ENV !== "production") {
logger.error(`Cannot cache non-existent response for '${getFriendlyURL(effectiveRequest.url)}'.`);
}
throw new SerwistError("cache-put-with-no-response", {
url: getFriendlyURL(effectiveRequest.url),
});
}
const responseToCache = await this._ensureResponseSafeToCache(response);
if (!responseToCache) {
if (process.env.NODE_ENV !== "production") {
logger.debug(`Response '${getFriendlyURL(effectiveRequest.url)}' will not be cached.`, responseToCache);
}
return false;
}
const { cacheName, matchOptions } = this._strategy;
const cache = await self.caches.open(cacheName);
if (process.env.NODE_ENV !== "production") {
// See https://github.com/GoogleChrome/workbox/issues/2818
const vary = response.headers.get("Vary");
if (vary && matchOptions?.ignoreVary !== true) {
logger.debug(
`The response for ${getFriendlyURL(
effectiveRequest.url,
)} has a 'Vary: ${vary}' header. Consider setting the {ignoreVary: true} option on your strategy to ensure cache matching and deletion works as expected.`,
);
}
}
const hasCacheUpdateCallback = this.hasCallback("cacheDidUpdate");
const oldResponse = hasCacheUpdateCallback
? await cacheMatchIgnoreParams(
// TODO(philipwalton): the `__WB_REVISION__` param is a precaching
// feature. Consider into ways to only add this behavior if using
// precaching.
cache,
effectiveRequest.clone(),
["__WB_REVISION__"],
matchOptions,
)
: null;
if (process.env.NODE_ENV !== "production") {
logger.debug(`Updating the '${cacheName}' cache with a new Response for ${getFriendlyURL(effectiveRequest.url)}.`);
}
try {
await cache.put(effectiveRequest, hasCacheUpdateCallback ? responseToCache.clone() : responseToCache);
} catch (error) {
if (error instanceof Error) {
// See https://developer.mozilla.org/en-US/docs/Web/API/DOMException#exception-QuotaExceededError
if (error.name === "QuotaExceededError") {
await executeQuotaErrorCallbacks();
}
throw error;
}
}
for (const callback of this.iterateCallbacks("cacheDidUpdate")) {
await callback({
cacheName,
oldResponse,
newResponse: responseToCache.clone(),
request: effectiveRequest,
event: this.event,
});
}
return true;
} | /**
* 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`
* - `cacheWillUpdate`
* - `cacheDidUpdate`
*
* @param key The request or URL to use as the cache key.
* @param response The response to cache.
* @returns `false` if a `cacheWillUpdate` caused the response to
* not be cached, and `true` otherwise.
*/ | 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(
await callback({
mode,
request: effectiveRequest,
event: this.event,
params: this.params,
}),
);
}
this._cacheKeys[key] = effectiveRequest;
}
return this._cacheKeys[key];
} | /**
* 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 callbacks have
* been registered, the passed request is returned unmodified.
*
* @param request
* @param mode
* @returns
*/ | 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 SerwistPluginCallbackParam[C]`.
await callback(param as any);
}
} | /**
* 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 {@linkcode StrategyHandler.iterateCallbacks} for how to handle that case.
*
* @param name The name of the callback to run within each plugin.
* @param param The object to pass as the first (and only) param when executing each callback. This object will be merged with the
* current plugin state prior to callback execution.
*/ | 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<SerwistPluginCallbackParam[C], "state">) => {
const statefulParam = { ...param, state };
// TODO(philipwalton): not sure why `any` is needed. It seems like
// this should work with `as WorkboxPluginCallbackParam[C]`.
return plugin[name]!(statefulParam as any);
};
yield statefulCallback as NonNullable<SerwistPlugin[C]>;
}
}
} | /**
* 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 added promises have settled.
*
* @param promise A promise to add to the extend lifetime promises of
* the event that triggered the request.
*/ | 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 to your work completing.
*/ | 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 (possiblePreloadResponse) {
if (process.env.NODE_ENV !== "production") {
logger.log(`Using a preloaded navigation response for '${getFriendlyURL(this.event.request.url)}'`);
}
return possiblePreloadResponse;
}
} catch (error) {
if (process.env.NODE_ENV !== "production") {
logger.error(error);
}
return undefined;
}
}
return undefined;
} | /**
* 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.request,
response: responseToCache,
event: this.event,
})) || undefined;
pluginsUsed = true;
if (!responseToCache) {
break;
}
}
if (!pluginsUsed) {
if (responseToCache && responseToCache.status !== 200) {
if (process.env.NODE_ENV !== "production") {
if (responseToCache.status === 0) {
logger.warn(
`The response for '${this.request.url}' is an opaque response. The caching strategy that you're using will not cache opaque responses by default.`,
);
} else {
logger.debug(`The response for '${this.request.url}' returned a status code of '${response.status}' and won't be cached as a result.`);
}
}
responseToCache = undefined;
}
}
return responseToCache;
} | /**
* 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 (request.url === strippedRequestURL) {
return cache.match(request, matchOptions);
}
// Otherwise, match by comparing keys
const keysOptions = { ...matchOptions, ignoreSearch: true };
const cacheKeys = await cache.keys(request, keysOptions);
for (const cacheKey of cacheKeys) {
const strippedCacheKeyURL = stripParams(cacheKey.url, ignoreParams);
if (strippedRequestURL === strippedCacheKeyURL) {
return cache.match(cacheKey, matchOptions);
}
}
return;
} | /**
* 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.
*
* @private
*/ | 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;
}
}
supportStatus = false;
}
return supportStatus;
} | /**
* 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 = options.config.basePath || "/";
const tsConfigJson = loadTSConfig(options.dir, nextConfig?.typescript?.tsconfigPath);
const {
cacheOnNavigation,
disable,
scope = basePath,
swUrl,
register,
reloadOnOnline,
globPublicPatterns,
...buildOptions
} = validateInjectManifestOptions(userOptions);
if (typeof nextConfig.webpack === "function") {
config = nextConfig.webpack(config, options);
}
if (disable) {
options.isServer && logger.info("Serwist is disabled.");
return config;
}
if (!config.plugins) {
config.plugins = [];
}
const _sw = path.posix.join(basePath, swUrl);
const _scope = path.posix.join(scope, "/");
config.plugins.push(
new webpack.DefinePlugin({
"self.__SERWIST_SW_ENTRY.sw": `'${_sw}'`,
"self.__SERWIST_SW_ENTRY.scope": `'${_scope}'`,
"self.__SERWIST_SW_ENTRY.cacheOnNavigation": `${cacheOnNavigation}`,
"self.__SERWIST_SW_ENTRY.register": `${register}`,
"self.__SERWIST_SW_ENTRY.reloadOnOnline": `${reloadOnOnline}`,
} satisfies Record<`${SerwistNextOptionsKey}.${Exclude<keyof SerwistNextOptions, "swEntryWorker">}`, string | undefined>),
);
const swEntryJs = path.join(dirname, "sw-entry.js");
const entry = config.entry as () => Promise<Record<string, string[] | string>>;
config.entry = async () => {
const entries = await entry();
if (entries["main.js"] && !entries["main.js"].includes(swEntryJs)) {
if (Array.isArray(entries["main.js"])) {
entries["main.js"].unshift(swEntryJs);
} else if (typeof entries["main.js"] === "string") {
entries["main.js"] = [swEntryJs, entries["main.js"]];
}
}
if (entries["main-app"] && !entries["main-app"].includes(swEntryJs)) {
if (Array.isArray(entries["main-app"])) {
entries["main-app"].unshift(swEntryJs);
} else if (typeof entries["main-app"] === "string") {
entries["main-app"] = [swEntryJs, entries["main-app"]];
}
}
return entries;
};
if (!options.isServer) {
if (!register) {
logger.info(
"The service worker will not be automatically registered, please call 'window.serwist.register()' in 'componentDidMount' or 'useEffect'.",
);
if (!tsConfigJson?.compilerOptions?.types?.includes("@serwist/next/typings")) {
logger.info(
"You may also want to add '@serwist/next/typings' to your TypeScript/JavaScript configuration file at 'compilerOptions.types'.",
);
}
}
const {
swSrc: userSwSrc,
swDest: userSwDest,
additionalPrecacheEntries,
exclude,
manifestTransforms = [],
...otherBuildOptions
} = buildOptions;
let swSrc = userSwSrc;
let swDest = userSwDest;
// If these two paths are not absolute, they will be resolved from `compilation.options.output.path`,
// which is `${options.dir}/${nextConfig.destDir}` for Next.js apps, rather than `${options.dir}`
// as an user would expect.
if (!path.isAbsolute(swSrc)) {
swSrc = path.join(options.dir, swSrc);
}
if (!path.isAbsolute(swDest)) {
swDest = path.join(options.dir, swDest);
}
const publicDir = path.resolve(options.dir, "public");
const { dir: destDir, base: destBase } = path.parse(swDest);
const cleanUpList = globSync(["swe-worker-*.js", "swe-worker-*.js.map", destBase, `${destBase}.map`], {
absolute: true,
nodir: true,
cwd: destDir,
});
for (const file of cleanUpList) {
fs.rm(file, { force: true }, (err) => {
if (err) throw err;
});
}
const shouldBuildSWEntryWorker = cacheOnNavigation;
let swEntryPublicPath: string | undefined = undefined;
let swEntryWorkerDest: string | undefined = undefined;
if (shouldBuildSWEntryWorker) {
const swEntryWorkerSrc = path.join(dirname, "sw-entry-worker.js");
const swEntryName = `swe-worker-${getContentHash(swEntryWorkerSrc, dev)}.js`;
swEntryPublicPath = path.posix.join(basePath, swEntryName);
swEntryWorkerDest = path.join(destDir, swEntryName);
config.plugins.push(
new ChildCompilationPlugin({
src: swEntryWorkerSrc,
dest: swEntryWorkerDest,
}),
);
}
config.plugins.push(
new webpack.DefinePlugin({
"self.__SERWIST_SW_ENTRY.swEntryWorker": swEntryPublicPath && `'${swEntryPublicPath}'`,
} satisfies Record<`${SerwistNextOptionsKey}.${Extract<keyof SerwistNextOptions, "swEntryWorker">}`, string | undefined>),
);
logger.event(`Bundling the service worker script with the URL '${_sw}' and the scope '${_scope}'...`);
// Precache files in public folder
let resolvedManifestEntries = additionalPrecacheEntries;
if (!resolvedManifestEntries) {
const publicScan = globSync(globPublicPatterns, {
nodir: true,
cwd: publicDir,
ignore: ["swe-worker-*.js", destBase, `${destBase}.map`],
});
resolvedManifestEntries = publicScan.map((f) => ({
url: path.posix.join(basePath, f),
revision: getFileHash(path.join(publicDir, f)),
}));
}
const publicPath = config.output?.publicPath;
config.plugins.push(
new InjectManifest({
swSrc,
swDest,
disablePrecacheManifest: dev,
additionalPrecacheEntries: dev ? [] : resolvedManifestEntries,
exclude: [
...exclude,
({ asset, compilation }: ExcludeParams) => {
// Same as how `@serwist/webpack-plugin` does it. It is always
// `relativeToOutputPath(compilation, originalSwDest)`.
const swDestRelativeOutput = relativeToOutputPath(compilation, swDest);
const swAsset = compilation.getAsset(swDestRelativeOutput);
return (
// We don't need the service worker to be cached.
asset.name === swAsset?.name ||
asset.name.startsWith("server/") ||
/^((app-|^)build-manifest\.json|react-loadable-manifest\.json)$/.test(asset.name) ||
(dev && !asset.name.startsWith("static/runtime/"))
);
},
],
manifestTransforms: [
...manifestTransforms,
async (manifestEntries, compilation) => {
// This path always uses forward slashes, so it is safe to use it in the following string replace.
const publicDirRelativeOutput = relativeToOutputPath(compilation as Compilation, publicDir);
// `publicPath` is always `${assetPrefix}/_next/` for Next.js apps.
const publicFilesPrefix = `${publicPath}${publicDirRelativeOutput}`;
const manifest = manifestEntries.map((m) => {
m.url = m.url.replace("/_next//static/image", "/_next/static/image").replace("/_next//static/media", "/_next/static/media");
// We remove `${publicPath}/${publicDirRelativeOutput}` because `assetPrefix`
// is not intended for files that are in the public directory and we also want
// to remove `/_next/${publicDirRelativeOutput}` from the URL, since that is not how
// we resolve files in the public directory.
if (m.url.startsWith(publicFilesPrefix)) {
m.url = path.posix.join(basePath, m.url.replace(publicFilesPrefix, ""));
}
m.url = m.url.replace(/\[/g, "%5B").replace(/\]/g, "%5D");
return m;
});
return { manifest, warnings: [] };
},
],
...otherBuildOptions,
}),
);
}
return config;
},
});
}; | /**
* 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.type });
}
if (source instanceof ReadableStream) {
return source.getReader();
}
return new Response(source as BodyInit).body!.getReader();
} | /**
* 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",
});
}
const readerPromises = sourcePromises.map((sourcePromise) => {
return Promise.resolve(sourcePromise).then((source) => {
return _getReaderFromSource(source);
});
});
const streamDeferred: Deferred<void> = new Deferred();
let i = 0;
const logMessages: any[] = [];
const stream = new ReadableStream({
pull(controller: ReadableStreamDefaultController<any>) {
return readerPromises[i]
.then((reader) => {
if (reader instanceof ReadableStreamDefaultReader) {
return reader.read();
}
return;
})
.then((result) => {
if (result?.done) {
if (process.env.NODE_ENV !== "production") {
logMessages.push(["Reached the end of source:", sourcePromises[i]]);
}
i++;
if (i >= readerPromises.length) {
// Log all the messages in the group at once in a single group.
if (process.env.NODE_ENV !== "production") {
logger.groupCollapsed(`Concatenating ${readerPromises.length} sources.`);
for (const message of logMessages) {
if (Array.isArray(message)) {
logger.log(...message);
} else {
logger.log(message);
}
}
logger.log("Finished reading all sources.");
logger.groupEnd();
}
controller.close();
streamDeferred.resolve();
return;
}
// The `pull` method is defined because we're inside it.
return this.pull!(controller);
}
controller.enqueue(result?.value);
})
.catch((error) => {
if (process.env.NODE_ENV !== "production") {
logger.error("An error occurred:", error);
}
streamDeferred.reject(error);
throw error;
});
},
cancel() {
if (process.env.NODE_ENV !== "production") {
logger.warn("The ReadableStream was cancelled.");
}
streamDeferred.resolve();
},
});
return { done: streamDeferred.promise, stream };
} | /**
* 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
* stream is finished (useful for passing to a FetchEvent's waitUntil()).
*
* @param sourcePromises
* @returns
*/ | 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, response };
} | /**
* 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 each individual
* stream's data returned in sequence, along with a Promise which signals when
* the stream is finished (useful for passing to a FetchEvent's waitUntil()).
*
* @param sourcePromises
* @param headersInit If there's no `Content-Type` specified,`'text/html'` will be used by default.
* @returns
*/ | 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 = {
// Use swSrc with a hardcoded .js extension, in case swSrc is a .ts file.
swDest: `${parsedSwSrc.name}.js`,
...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/1790
if (this.alreadyCalled) {
const warningMessage = `${this.constructor.name} has been called multiple times, perhaps due to running webpack in --watch mode. The precache manifest generated after the first call may be inaccurate! Please see https://github.com/GoogleChrome/workbox/issues/1790 for more information.`;
if (!compilation.warnings.some((warning) => warning instanceof Error && warning.message === warningMessage)) {
compilation.warnings.push(new Error(warningMessage) as WebpackError);
}
} else {
this.alreadyCalled = true;
}
// Ensure that we don't precache any of the assets generated by *any*
// instance of this plugin.
config.exclude.push(({ asset }) => _generatedAssetNames.has(asset.name));
const { size, sortedEntries } = await getManifestEntriesFromCompilation(compilation, config);
let manifestString = stringify(sortedEntries);
if (
this.config.compileSrc &&
// See https://github.com/GoogleChrome/workbox/issues/2729
!(compilation.options?.devtool === "eval-cheap-source-map" && compilation.options.optimization?.minimize)
) {
// See https://github.com/GoogleChrome/workbox/issues/2263
manifestString = manifestString.replace(/"/g, `'`);
}
return { size, sortedEntries, manifestString };
} | /**
* `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 null at this point.
const { PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER } = this.webpack.Compilation;
// Specifically hook into thisCompilation, as per
// https://github.com/webpack/webpack/issues/11425#issuecomment-690547848
compiler.hooks.thisCompilation.tap(this.constructor.name, (compilation) => {
compilation.hooks.processAssets.tapPromise(
{
name: this.constructor.name,
// TODO(jeffposnick): This may need to change eventually.
// See https://github.com/webpack/webpack/issues/11822#issuecomment-726184972
stage: PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER - 10,
},
() =>
this.addAssets(compilation).catch((error: WebpackError) => {
compilation.errors.push(error);
}),
);
});
} | /**
* @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) {
await performChildCompilation(
compiler,
compilation,
this.constructor.name,
this.config.swSrc,
this.config.swDest,
this.config.webpackCompilationPlugins,
);
} else {
this.addSrcToAssets(compiler, compilation);
// This used to be a fatal error, but just warn at runtime because we
// can't validate it easily.
if (Array.isArray(this.config.webpackCompilationPlugins) && this.config.webpackCompilationPlugins.length > 0) {
compilation.warnings.push(new Error("'compileSrc' is 'false', so the 'webpackCompilationPlugins' option will be ignored.") as WebpackError);
}
}
} | /**
* @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
compilation.fileDependencies.add(path.resolve(config.swSrc));
const swAsset = compilation.getAsset(config.swDest!);
const swAssetString = swAsset!.source.source().toString();
const globalRegexp = new RegExp(escapeRegExp(config.injectionPoint), "g");
const injectionResults = swAssetString.match(globalRegexp);
if (!injectionResults) {
throw new Error(`Can't find ${config.injectionPoint} in your SW source.`);
}
if (injectionResults.length !== 1) {
throw new Error(
`Multiple instances of ${config.injectionPoint} were found in your SW source. Include it only once. For more info, see https://github.com/GoogleChrome/workbox/issues/2681`,
);
}
const sourcemapAssetName = getSourcemapAssetName(compilation, swAssetString, config.swDest!);
if (sourcemapAssetName) {
_generatedAssetNames.add(sourcemapAssetName);
const sourcemapAsset = compilation.getAsset(sourcemapAssetName);
const { source, map } = await replaceAndUpdateSourceMap({
jsFilename: toUnix(config.swDest!),
originalMap: JSON.parse(sourcemapAsset!.source.source().toString()),
originalSource: swAssetString,
replaceString: manifestString,
searchString: config.injectionPoint,
});
compilation.updateAsset(sourcemapAssetName, new this.webpack.sources.RawSource(map));
compilation.updateAsset(config.swDest!, new this.webpack.sources.RawSource(source));
} else {
// If there's no sourcemap associated with swDest, a simple string
// replacement will suffice.
compilation.updateAsset(config.swDest!, new this.webpack.sources.RawSource(swAssetString.replace(config.injectionPoint, manifestString)));
}
if (compilation.getLogger) {
const logger = compilation.getLogger(this.constructor.name);
logger.info(`The service worker at ${config.swDest ?? ""} will precache ${sortedEntries?.length ?? 0} URLs, totaling ${prettyBytes(size)}.`);
}
} | /**
* @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: WebpackError) => {
compilation.errors.push(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 !== null;
}
if (compilation.compiler.webpack.ModuleFilenameHelpers.matchPart(asset.name, condition)) {
return true;
}
}
// We'll only get here if none of the conditions applied.
return false;
}; | /**
* 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.
* @param conditions
* @returns Whether or not at least one condition matches.
* @private
*/ | 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(chunk));
}
return assetNames;
}
const chunk = compilation.namedChunks?.get(chunkOrGroup);
if (chunk) {
return getNamesOfAssetsInChunk(chunk);
}
// If we get here, there's no chunkGroup or chunk with that name.
return null;
}; | /**
* 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
* @returns
* @private
*/ | 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.chunks)) {
for (const name of config.chunks) {
// See https://github.com/GoogleChrome/workbox/issues/2717
const assetsInChunkOrGroup = getNamesOfAssetsInChunkOrGroup(compilation, name);
if (assetsInChunkOrGroup) {
for (const assetName of assetsInChunkOrGroup) {
allowedAssetNames.add(assetName);
}
} else {
compilation.warnings.push(
new Error(`The chunk '${name}' was provided in your Serwist chunks config, but was not found in the compilation.`) as WebpackError,
);
}
}
}
const deniedAssetNames = new Set();
if (Array.isArray(config.excludeChunks)) {
for (const name of config.excludeChunks) {
// See https://github.com/GoogleChrome/workbox/issues/2717
const assetsInChunkOrGroup = getNamesOfAssetsInChunkOrGroup(compilation, name);
if (assetsInChunkOrGroup) {
for (const assetName of assetsInChunkOrGroup) {
deniedAssetNames.add(assetName);
}
} // Don't warn if the chunk group isn't found.
}
}
for (const asset of assets) {
// chunk based filtering is funky because:
// - Each asset might belong to one or more chunks.
// - If *any* of those chunk names match our config.excludeChunks,
// then we skip that asset.
// - If the config.chunks is defined *and* there's no match
// between at least one of the chunkNames and one entry, then
// we skip that assets as well.
if (deniedAssetNames.has(asset.name)) {
continue;
}
if (Array.isArray(config.chunks) && !allowedAssetNames.has(asset.name)) {
continue;
}
// Next, check asset-level checks via includes/excludes:
const isExcluded = checkConditions(asset, compilation, config.exclude);
if (isExcluded) {
continue;
}
// Treat an empty config.includes as an implicit inclusion.
const isIncluded = !Array.isArray(config.include) || checkConditions(asset, compilation, config.include);
if (!isIncluded) {
continue;
}
// If we've gotten this far, then add the asset.
filteredAssets.add(asset);
}
return filteredAssets;
}; | /**
* 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.
* @returns The assets that should be included in the manifest,
* based on the criteria provided.
* @private
*/ | 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 DOMContentLoaded event:
// https://github.com/GoogleChrome/workbox/issues/2202
navigator.serviceWorker.addEventListener("message", this._onMessage);
} | /**
* 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 scriptURL The service worker script associated with this instance. Using a
* [`TrustedScriptURL`](https://developer.mozilla.org/en-US/docs/Web/API/TrustedScriptURL) is supported.
* @param registerOptions The service worker options associated with this instance.
*/ | 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 !== "production") {
if (this._registrationTime) {
logger.error("Cannot re-register a Serwist instance after it has been registered. Create a new instance instead.");
return;
}
}
if (!immediate && document.readyState !== "complete") {
await new Promise((res) => window.addEventListener("load", res));
}
// Set this flag to true if any service worker was controlling the page
// at registration time.
this._isUpdate = Boolean(navigator.serviceWorker.controller);
// Before registering, attempt to determine if a SW is already controlling
// the page and if that SW script (and version, if specified) matches this
// instance's script.
this._compatibleControllingSW = this._getControllingSWIfCompatible();
this._registration = await this._registerScript();
// If we have a compatible controller, store the controller as the "own"
// SW, resolve active/controlling deferreds and add necessary listeners.
if (this._compatibleControllingSW) {
this._sw = this._compatibleControllingSW;
this._activeDeferred.resolve(this._compatibleControllingSW);
this._controllingDeferred.resolve(this._compatibleControllingSW);
this._compatibleControllingSW.addEventListener("statechange", this._onStateChange, { once: true });
}
// If there's a waiting service worker with a matching URL before the
// `updatefound` event fires, it likely means that this site is open
// in another tab, or the user refreshed the page (and thus the previous
// page wasn't fully unloaded before this page started loading).
// https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting
const waitingSW = this._registration.waiting;
if (waitingSW && urlsMatch(waitingSW.scriptURL, this._scriptURL.toString())) {
// Store the waiting SW as the "own" SW, even if it means overwriting
// a compatible controller.
this._sw = waitingSW;
// Run this in the next microtask, so any code that adds an event
// listener after awaiting `register()` will get this event.
void Promise.resolve().then(() => {
this.dispatchEvent(
new SerwistEvent("waiting", {
sw: waitingSW,
wasWaitingBeforeRegister: true,
}),
);
if (process.env.NODE_ENV !== "production") {
logger.warn("A service worker was already waiting to activate before this script was registered...");
}
});
}
// If an "own" SW is already set, resolve the deferred.
if (this._sw) {
this._swDeferred.resolve(this._sw);
this._ownSWs.add(this._sw);
}
if (process.env.NODE_ENV !== "production") {
logger.log("Successfully registered service worker.", this._scriptURL.toString());
if (navigator.serviceWorker.controller) {
if (this._compatibleControllingSW) {
logger.debug("A service worker with the same script URL is already controlling this page.");
} else {
logger.debug(
"A service worker with a different script URL is currently controlling the page. The browser is now fetching the new script now...",
);
}
}
if (isCurrentPageOutOfScope(this._registerOptions.scope || this._scriptURL.toString())) {
logger.warn("The current page is not in scope for the registered service worker. Was this a mistake?");
}
}
this._registration.addEventListener("updatefound", this._onUpdateFound);
navigator.serviceWorker.addEventListener("controllerchange", this._onControllerChange);
return this._registration;
} | /**
* 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._registration.update();
} | /**
* 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 activates.
*
* @returns
*/ | 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
* is found and starts controlling the page.
* Note: the first time a service worker is installed it will active but
* not start controlling the page unless `clients.claim()` is called in the
* service worker.
*
* @returns
*/ | 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 precedence over the active service worker if both
* match, since the waiting service worker would have been registered more
* recently).
* If there's no matching active or waiting service worker at registration
* time then the promise will not resolve until an update is found and starts
* installing, at which point the installing service worker is used.
*
* @returns
*/ | 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 string, this._registerOptions);
// Keep track of when registration happened, so it can be used in the
// `this._onUpdateFound` heuristic. Also use the presence of this
// property as a way to see if `.register()` has been called.
this._registrationTime = performance.now();
return reg;
} catch (error) {
if (process.env.NODE_ENV !== "production") {
logger.error(error);
}
// Re-throw the error.
throw error;
}
} | /**
* 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.register()` is
// different from the current controlling SW's script URL, we know any
// successful registration calls will trigger an `updatefound` event.
// But if the registered script URL is the same as the current controlling
// SW's script URL, we'll only get an `updatefound` event if the file
// changed since it was last registered. This can be a problem if the user
// opens up the same page in a different tab, and that page registers
// a SW that triggers an update. It's a problem because this page has no
// good way of knowing whether the `updatefound` event came from the SW
// script it registered or from a registration attempt made by a newer
// version of the page running in another tab.
// To minimize the possibility of a false positive, we use the logic here:
const updateLikelyTriggeredExternally =
// Since we enforce only calling `register()` once, and since we don't
// add the `updatefound` event listener until the `register()` call, if
// `_updateFoundCount` is > 0 then it means this method has already
// been called, thus this SW must be external
this._updateFoundCount > 0 ||
// If the script URL of the installing SW is different from this
// instance's script URL, we know it's definitely not from our
// registration.
!urlsMatch(installingSW.scriptURL, this._scriptURL.toString()) ||
// If all of the above are false, then we use a time-based heuristic:
// Any `updatefound` event that occurs long after our registration is
// assumed to be external.
performance.now() > this._registrationTime + REGISTRATION_TIMEOUT_DURATION;
// If any of the above are not true, we assume the update was
// triggered by this instance.
if (updateLikelyTriggeredExternally) {
this._externalSW = installingSW;
registration.removeEventListener("updatefound", this._onUpdateFound);
} else {
// If the update was not triggered externally we know the installing
// SW is the one we registered, so we set it.
this._sw = installingSW;
this._ownSWs.add(installingSW);
this._swDeferred.resolve(installingSW);
if (process.env.NODE_ENV !== "production") {
if (this._isUpdate) {
logger.log("Updated service worker found. Installing now...");
} else {
logger.log("Service worker is installing...");
}
}
}
// Dispatch the `installing` event when the SW is installing.
this.dispatchEvent(
new SerwistEvent("installing", {
sw: installingSW,
originalEvent,
isExternal: updateLikelyTriggeredExternally,
isUpdate: this._isUpdate,
}),
);
// Increment the `updatefound` count, so future invocations of this
// method can be sure they were triggered externally.
++this._updateFoundCount;
// Add a `statechange` listener regardless of whether this update was
// triggered externally, since we have callbacks for both.
installingSW.addEventListener("statechange", this._onStateChange);
} | /**
* @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 (context.triggerKind === InlineCompletionTriggerKind.Automatic) {
if (!autoTriggerEnabled) {
return Promise.resolve(([] as InlineCompletionItem[]));
}
let delay = CODESHELL_CONFIG.get("AutoCompletionDelay") as number;
await sleep(1000 * delay);
if (token.isCancellationRequested) {
return Promise.resolve(([] as InlineCompletionItem[]));
}
}
const fimPrefixCode = this.getFimPrefixCode(document, position);
const fimSuffixCode = this.getFimSuffixCode(document, position);
if (this.isNil(fimPrefixCode) && this.isNil(fimSuffixCode)) {
return Promise.resolve(([] as InlineCompletionItem[]));
}
this.statusBar.text = "$(loading~spin)";
this.statusBar.tooltip = "CodeShell - Working";
return postCompletion(fimPrefixCode, fimSuffixCode).then((response) => {
this.statusBar.text = "$(light-bulb)";
this.statusBar.tooltip = `CodeShell - Ready`;
if (token.isCancellationRequested || !response || this.isNil(response.trim())) {
return Promise.resolve(([] as InlineCompletionItem[]));
}
return [new InlineCompletionItem(response, new Range(position, position))];
}).catch((error) => {
console.error(error);
this.statusBar.text = "$(alert)";
this.statusBar.tooltip = "CodeShell - Error";
window.setStatusBarMessage(`${error}`, 10000);
return Promise.resolve(([] as InlineCompletionItem[]));
}).finally(() => {
});
} | // 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}/images/create?q=${encodedPrompt}&rt=3&FORM=GENCRE`;
try {
const { redirect_url, request_id } = await this.fetchRedirectUrl(url, formData);
return this.fetchResult(encodedPrompt, redirect_url, request_id);
} catch (e) {
// retry 1 time
console.log("retry 1 time");
return this.fetchRedirectUrl(url, formData)
.then((res) => {
return this.fetchResult(encodedPrompt, res.redirect_url, res.request_id);
})
.catch((e) => {
throw new Error(`${e.message}`);
});
}
} | /**
* 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.status !== 200) {
throw new Error("Bad status code");
}
const content = await response.text();
if (!content || content.includes("errorMessage")) {
return null;
} else {
return content;
}
} | /**
* 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
const normal_image_links = matches.map((link) => {
return link.split("?w=")[0];
});
console.log("normal_image_links", normal_image_links);
// Remove Bad Images(https://r.bing.com/rp/xxx)
const safe_image_links = normal_image_links
.filter((link) => !/r.bing.com\/rp/i.test(link))
.filter((link) => !/rp/i.test(link))
.filter((link) => link.startsWith("http"));
safe_image_links.length !== normal_image_links.length && console.log("Detected & Removed bad images");
console.log("safe_image_links", safe_image_links);
// Remove duplicates
const unique_image_links = [...new Set(safe_image_links)];
// No images
if (unique_image_links.length === 0) {
throw new Error("error_no_images");
}
return unique_image_links;
} | /**
* 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.delete(key);
}
await tx.commit();
}
kv.close();
} | // | 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 fetchNewDatabaseMetadata(
url,
accessToken,
debug,
fetcher,
maxRetries,
supportedVersions,
);
}
const { metadata } = this;
const firstStrong =
metadata.endpoints.filter((v) => v.consistency === "strong")[0];
const firstNonStrong =
metadata.endpoints.filter((v) => v.consistency !== "strong")[0];
const endpoint = consistency === "strong"
? firstStrong
: (firstNonStrong ?? firstStrong);
if (endpoint === undefined) {
throw new Error(`Unable to find endpoint for: ${consistency}`);
}
return endpoint.url; // guaranteed not to end in "/"
} | // | 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 = options.nodeIds;
this.defIds = options.defIds || [];
this.app = options.app;
this.x = options.x;
this.y = options.y;
this.isBacklink = options.isBacklink;
this.element = document.createElement("div");
this.element.classList.add("block__popover");
const parentElement = hasClosestByClassName(this.targetElement, "block__popover", true);
let level = 1;
if (parentElement) {
this.element.setAttribute("data-oid", parentElement.getAttribute("data-oid"));
level = parseInt(parentElement.getAttribute("data-level")) + 1;
} else {
this.element.setAttribute("data-oid", this.nodeIds[0]);
}
// 移除同层级其他更高级的 block popover
this.element.setAttribute("data-level", level.toString());
for (let i = 0; i < window.siyuan.blockPanels.length; i++) {
const item = window.siyuan.blockPanels[i];
if (item.element.getAttribute("data-pin") === "false" &&
item.targetElement && parseInt(item.element.getAttribute("data-level")) >= level) {
item.destroy();
i--;
}
}
document.body.insertAdjacentElement("beforeend", this.element);
if (this.targetElement) {
this.targetElement.style.cursor = "wait";
}
this.element.setAttribute("data-pin", "false");
this.element.addEventListener("dblclick", (event) => {
const target = event.target as HTMLElement;
const iconsElement = hasClosestByClassName(target, "block__icons");
if (iconsElement) {
const pingElement = iconsElement.querySelector('[data-type="pin"]');
if (this.element.getAttribute("data-pin") === "true") {
pingElement.setAttribute("aria-label", window.siyuan.languages.pin);
pingElement.querySelector("use").setAttribute("xlink:href", "#iconPin");
this.element.setAttribute("data-pin", "false");
} else {
pingElement.setAttribute("aria-label", window.siyuan.languages.unpin);
pingElement.querySelector("use").setAttribute("xlink:href", "#iconUnpin");
this.element.setAttribute("data-pin", "true");
}
event.preventDefault();
event.stopPropagation();
}
});
this.element.addEventListener("click", (event) => {
if (this.element && window.siyuan.blockPanels.length > 1) {
this.element.style.zIndex = (++window.siyuan.zIndex).toString();
}
let target = event.target as HTMLElement;
while (target && !target.isEqualNode(this.element)) {
if (target.classList.contains("block__icon") || target.classList.contains("block__logo")) {
const type = target.getAttribute("data-type");
if (type === "close") {
this.destroy();
} else if (type === "pin") {
if (this.element.getAttribute("data-pin") === "true") {
target.setAttribute("aria-label", window.siyuan.languages.pin);
target.querySelector("use").setAttribute("xlink:href", "#iconPin");
this.element.setAttribute("data-pin", "false");
} else {
target.setAttribute("aria-label", window.siyuan.languages.unpin);
target.querySelector("use").setAttribute("xlink:href", "#iconUnpin");
this.element.setAttribute("data-pin", "true");
}
} else if (type === "open") {
/// #if !BROWSER
openNewWindowById(this.nodeIds[0]);
/// #endif
} else if (type === "stickTab") {
openFileById({
app: options.app,
id: this.nodeIds[0],
action: this.editors[0].protyle.block.rootID !== this.nodeIds[0] ? [Constants.CB_GET_ALL, Constants.CB_GET_FOCUS] : [Constants.CB_GET_CONTEXT],
});
}
event.preventDefault();
event.stopPropagation();
break;
}
target = target.parentElement;
}
});
/// #if !MOBILE
moveResize(this.element, () => {
const pinElement = this.element.firstElementChild.querySelector('[data-type="pin"]');
pinElement.setAttribute("aria-label", window.siyuan.languages.unpin);
pinElement.querySelector("use").setAttribute("xlink:href", "#iconUnpin");
this.element.setAttribute("data-pin", "true");
});
/// #endif
this.render();
} | // x,y 和 targetElement 二选一必传 | https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/block/Panel.ts#L34-L146 | d6bf65b650165c80c1feadb9c6e19fe01a26105d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.