phanpy/public/sw.js

75 lines
1.9 KiB
JavaScript
Raw Normal View History

import { CacheableResponsePlugin } from 'workbox-cacheable-response';
import { ExpirationPlugin } from 'workbox-expiration';
import { RegExpRoute, registerRoute, Route } from 'workbox-routing';
2023-01-10 09:08:10 +00:00
import {
CacheFirst,
NetworkFirst,
StaleWhileRevalidate,
} from 'workbox-strategies';
self.__WB_DISABLE_DEV_LOGS = true;
const imageRoute = new Route(
({ request, sameOrigin }) => {
const isRemote = !sameOrigin;
const isImage = request.destination === 'image';
const isAvatar = request.url.includes('/avatars/');
const isEmoji = request.url.includes('/emoji/');
return isRemote && isImage && (isAvatar || isEmoji);
},
new CacheFirst({
cacheName: 'remote-images',
plugins: [
new ExpirationPlugin({
2023-02-25 02:31:50 +00:00
maxEntries: 50,
maxAgeSeconds: 3 * 24 * 60 * 60, // 3 days
purgeOnQuotaError: true,
}),
new CacheableResponsePlugin({
statuses: [0, 200],
}),
],
}),
);
registerRoute(imageRoute);
2023-02-23 12:54:23 +00:00
// 1-day cache for
// - /api/v1/instance
// - /api/v1/custom_emojis
// - /api/v1/preferences
// - /api/v1/lists/:id
const apiExtendedRoute = new RegExpRoute(
2023-04-05 15:30:26 +00:00
/^https?:\/\/[^\/]+\/api\/v\d+\/(instance|custom_emojis|preferences|lists\/\d+)$/,
new StaleWhileRevalidate({
cacheName: 'api-extended',
plugins: [
new ExpirationPlugin({
maxAgeSeconds: 24 * 60 * 60, // 1 day
}),
new CacheableResponsePlugin({
statuses: [0, 200],
}),
],
}),
);
registerRoute(apiExtendedRoute);
2023-01-02 06:23:00 +00:00
const apiRoute = new RegExpRoute(
// Matches:
// - statuses/:id/context - some contexts are really huge
/^https?:\/\/[^\/]+\/api\/v\d+\/(statuses\/\d+\/context)/,
2023-01-09 17:28:52 +00:00
new NetworkFirst({
2023-01-02 06:23:00 +00:00
cacheName: 'api',
2023-01-09 17:28:52 +00:00
networkTimeoutSeconds: 5,
2023-01-02 06:23:00 +00:00
plugins: [
new ExpirationPlugin({
maxAgeSeconds: 5 * 60, // 5 minutes
}),
new CacheableResponsePlugin({
statuses: [0, 200],
}),
],
}),
);
registerRoute(apiRoute);