@serwist/sw 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,10 @@
1
+
2
+ > @serwist/sw@8.0.0 build /home/runner/work/serwist/serwist/packages/sw
3
+ > rimraf dist && cross-env NODE_ENV=production rollup --config rollup.config.js
4
+
5
+ (node:3208) ExperimentalWarning: Import assertions are not a stable feature of the JavaScript language. Avoid relying on their current behavior and syntax as those might change in a future version of Node.js.
6
+ (Use `node --trace-warnings ...` to show where the warning was created)
7
+ (node:3208) ExperimentalWarning: Importing JSON modules is an experimental feature and might change at any time
8
+ 
9
+ src/index.ts → dist/index.old.cjs, dist/index.js...
10
+ created dist/index.old.cjs, dist/index.js in 2.1s
@@ -0,0 +1,4 @@
1
+
2
+ > @serwist/sw@8.0.0 lint /home/runner/work/serwist/serwist/packages/sw
3
+ > eslint src --ext ts,tsx,js,jsx,cjs,mjs
4
+
@@ -0,0 +1,4 @@
1
+
2
+ > @serwist/sw@8.0.0 typecheck /home/runner/work/serwist/serwist/packages/sw
3
+ > tsc
4
+
package/CHANGELOG.md ADDED
@@ -0,0 +1,43 @@
1
+ # @serwist/sw
2
+
3
+ ## 8.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - [`e0313f0`](https://github.com/serwist/serwist/commit/e0313f02f661a07ccbe9edc64e44e1af6136c73e) Thanks [@DuCanhGH](https://github.com/DuCanhGH)! - chore: initial release
8
+
9
+ - Reimagined `@serwist/next`.
10
+ - Removed various options.
11
+ - Removed `aggressiveFrontEndNavCaching` to reassess its usefulness.
12
+ - Removed `browserslist`. Use `swcEnvTargets` instead (TODO: add this option).
13
+ - Custom workers have been removed. You should use `swSrc`.
14
+ - Removed `extendDefaultRuntimeCaching`. Use the spread syntax instead (use `import { defaultCache } from "@serwist/next/browser"` to import the default runtimeCaching array).
15
+ - Temporarily removed `fallbacks` to investigate module-friendly alternatives.
16
+ - Removed `swcMinify`.
17
+ - Removed `watchWorkersInDev`.
18
+ - Removed `cacheStartUrl`, `dynamicStartUrl`, and `dynamicStartUrl`. These shall be re-added only when their use cases are made more clear to me.
19
+ - Merged `workboxOptions` with the plugin's options.
20
+ - Removed `swc-loader`, `terser-minify`, `webpack-builders`,... (we now leverage `ChildCompilationPlugin` to compile workers - this change will be backported to `@ducanh2912/next-pwa@10`)
21
+ - Removed the ability to use GenerateSW. `@serwist/sw.installSerwist` is provided as a replacement.
22
+ - `swSrc` is now a required property.
23
+ - Moved minimum support Next.js version from `11.0.0` to `14.0.0`.
24
+ - Removed GenerateSW (replaced by `@serwist/sw.installSerwist`).
25
+ - See `examples/next-basic/app/sw.ts` to see how `installSerwist` should be used.
26
+ - Repurposed `@serwist/sw`.
27
+ - The old package might be reintroduced if there's demand.
28
+ - **Note:** This is just the initial release, and there is still a lot of ground to cover (a lot of legacy code to be removed, a lot of features to be reintroduced,...). Here's to a bright future for the project :\_)
29
+
30
+ ### Patch Changes
31
+
32
+ - Updated dependencies [[`e0313f0`](https://github.com/serwist/serwist/commit/e0313f02f661a07ccbe9edc64e44e1af6136c73e)]:
33
+ - @serwist/cacheable-response@8.0.0
34
+ - @serwist/navigation-preload@8.0.0
35
+ - @serwist/broadcast-update@8.0.0
36
+ - @serwist/google-analytics@8.0.0
37
+ - @serwist/background-sync@8.0.0
38
+ - @serwist/range-requests@8.0.0
39
+ - @serwist/expiration@8.0.0
40
+ - @serwist/precaching@8.0.0
41
+ - @serwist/strategies@8.0.0
42
+ - @serwist/routing@8.0.0
43
+ - @serwist/core@8.0.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2018 Google LLC, 2019 ShadowWalker w@weiw.io https://weiw.io, 2023 Serwist
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ This module's documentation can be found at https://developers.google.com/web/tools/workbox/modules/workbox-sw
@@ -0,0 +1,2 @@
1
+ export declare const disableDevLogs: () => void;
2
+ //# sourceMappingURL=disableDevLogs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"disableDevLogs.d.ts","sourceRoot":"","sources":["../src/disableDevLogs.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,cAAc,YAE1B,CAAC"}
@@ -0,0 +1,14 @@
1
+ import type { PrecacheEntry, PrecacheRouteOptions } from "@serwist/precaching";
2
+ export type HandlePrecachingOptions = {
3
+ precacheEntries?: (PrecacheEntry | string)[];
4
+ precacheOptions?: PrecacheRouteOptions;
5
+ cleanupOutdatedCaches?: boolean;
6
+ } & ({
7
+ navigateFallback: string;
8
+ navigateFallbackAllowlist?: RegExp[];
9
+ navigateFallbackDenylist?: RegExp[];
10
+ } | {
11
+ navigateFallback?: never;
12
+ });
13
+ export declare const handlePrecaching: ({ precacheEntries, precacheOptions, cleanupOutdatedCaches: shouldCleanupOutdatedCaches, ...options }: HandlePrecachingOptions) => void;
14
+ //# sourceMappingURL=handlePrecaching.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handlePrecaching.d.ts","sourceRoot":"","sources":["../src/handlePrecaching.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAI/E,MAAM,MAAM,uBAAuB,GAAG;IACpC,eAAe,CAAC,EAAE,CAAC,aAAa,GAAG,MAAM,CAAC,EAAE,CAAC;IAC7C,eAAe,CAAC,EAAE,oBAAoB,CAAC;IAEvC,qBAAqB,CAAC,EAAE,OAAO,CAAC;CACjC,GAAG,CAAC;IAAE,gBAAgB,EAAE,MAAM,CAAC;IAAC,yBAAyB,CAAC,EAAE,MAAM,EAAE,CAAC;IAAC,wBAAwB,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,GAAG;IAAE,gBAAgB,CAAC,EAAE,KAAK,CAAA;CAAE,CAAC,CAAC;AAE7I,eAAO,MAAM,gBAAgB,yGAK1B,uBAAuB,SAoBzB,CAAC"}
@@ -0,0 +1,18 @@
1
+ import type { RuntimeCaching } from "@serwist/build";
2
+ import { type GoogleAnalyticsInitializeOptions } from "@serwist/google-analytics/initialize";
3
+ import { disableDevLogs } from "./disableDevLogs.js";
4
+ import { handlePrecaching, type HandlePrecachingOptions } from "./handlePrecaching.js";
5
+ import { registerRuntimeCaching } from "./registerRuntimeCaching.js";
6
+ export type SerwistOptions = HandlePrecachingOptions & {
7
+ skipWaiting?: boolean;
8
+ importScripts?: string[];
9
+ navigationPreload?: boolean;
10
+ cacheId?: string | undefined;
11
+ clientsClaim?: boolean;
12
+ runtimeCaching?: RuntimeCaching[];
13
+ offlineAnalyticsConfig?: GoogleAnalyticsInitializeOptions;
14
+ disableDevLogs?: boolean;
15
+ };
16
+ export declare const installSerwist: ({ precacheEntries, precacheOptions, cleanupOutdatedCaches, skipWaiting: shouldSkipWaiting, importScripts: scriptsToImport, navigationPreload, cacheId, clientsClaim: shouldClaimClients, runtimeCaching, offlineAnalyticsConfig, disableDevLogs: shouldDisableDevLogs, ...options }: SerwistOptions) => void;
17
+ export { disableDevLogs, handlePrecaching, registerRuntimeCaching };
18
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAErD,OAAO,EAAE,KAAK,gCAAgC,EAAc,MAAM,sCAAsC,CAAC;AAGzG,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,gBAAgB,EAAE,KAAK,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AACvF,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AAIrE,MAAM,MAAM,cAAc,GAAG,uBAAuB,GAAG;IACrD,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,cAAc,CAAC,EAAE,cAAc,EAAE,CAAC;IAClC,sBAAsB,CAAC,EAAE,gCAAgC,CAAC;IAC1D,cAAc,CAAC,EAAE,OAAO,CAAC;CAC1B,CAAC;AAEF,eAAO,MAAM,cAAc,wRAcxB,cAAc,SAsChB,CAAC;AAEF,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,sBAAsB,EAAE,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,104 @@
1
+ import { setCacheNameDetails, clientsClaim } from '@serwist/core';
2
+ import { initialize } from '@serwist/google-analytics/initialize';
3
+ import { enable } from '@serwist/navigation-preload';
4
+ import { precacheAndRoute, cleanupOutdatedCaches, createHandlerBoundToURL, PrecacheFallbackPlugin } from '@serwist/precaching';
5
+ import { registerRoute, NavigationRoute } from '@serwist/routing';
6
+ import { BackgroundSyncPlugin } from '@serwist/background-sync';
7
+ import { BroadcastUpdatePlugin } from '@serwist/broadcast-update';
8
+ import { CacheableResponsePlugin } from '@serwist/cacheable-response';
9
+ import { ExpirationPlugin } from '@serwist/expiration';
10
+ import { RangeRequestsPlugin } from '@serwist/range-requests';
11
+ import { CacheFirst, CacheOnly, NetworkFirst, NetworkOnly, StaleWhileRevalidate } from '@serwist/strategies';
12
+
13
+ const disableDevLogs = ()=>{
14
+ self.__WB_DISABLE_DEV_LOGS = true;
15
+ };
16
+
17
+ const handlePrecaching = ({ precacheEntries, precacheOptions, cleanupOutdatedCaches: shouldCleanupOutdatedCaches = false, ...options })=>{
18
+ if (!!precacheEntries && precacheEntries.length > 0) {
19
+ /**
20
+ * The precacheAndRoute() method efficiently caches and responds to
21
+ * requests for URLs in the manifest.
22
+ * See https://goo.gl/S9QRab
23
+ */ precacheAndRoute(precacheEntries, precacheOptions);
24
+ }
25
+ if (shouldCleanupOutdatedCaches) cleanupOutdatedCaches();
26
+ if (options.navigateFallback) {
27
+ registerRoute(new NavigationRoute(createHandlerBoundToURL(options.navigateFallback), {
28
+ allowlist: options.navigateFallbackAllowlist,
29
+ denylist: options.navigateFallbackDenylist
30
+ }));
31
+ }
32
+ };
33
+
34
+ const nonNullable = (value)=>value !== null && value !== undefined;
35
+
36
+ const HANDLER_NAME_TO_METHOD = {
37
+ CacheFirst,
38
+ CacheOnly,
39
+ NetworkFirst,
40
+ NetworkOnly,
41
+ StaleWhileRevalidate
42
+ };
43
+ const registerRuntimeCaching = (...runtimeCachingList)=>{
44
+ for (const rcEntry of runtimeCachingList){
45
+ if (typeof rcEntry.handler === "string") {
46
+ const { cacheName, networkTimeoutSeconds, fetchOptions, matchOptions, plugins, backgroundSync, broadcastUpdate, cacheableResponse, expiration, precacheFallback, rangeRequests } = rcEntry.options; // entry.options is always defined when entry.handler is of type 'string'.
47
+ const Handler = HANDLER_NAME_TO_METHOD[rcEntry.handler];
48
+ registerRoute(rcEntry.urlPattern, new Handler({
49
+ cacheName: cacheName ?? undefined,
50
+ networkTimeoutSeconds,
51
+ fetchOptions,
52
+ matchOptions,
53
+ plugins: [
54
+ ...plugins ?? [],
55
+ backgroundSync && new BackgroundSyncPlugin(backgroundSync.name, backgroundSync.options),
56
+ broadcastUpdate && new BroadcastUpdatePlugin({
57
+ // @ts-expect-error weird...
58
+ channelName: broadcastUpdate.channelName,
59
+ ...broadcastUpdate.options
60
+ }),
61
+ cacheableResponse && new CacheableResponsePlugin(cacheableResponse),
62
+ expiration && new ExpirationPlugin(expiration),
63
+ precacheFallback && new PrecacheFallbackPlugin(precacheFallback),
64
+ rangeRequests ? new RangeRequestsPlugin() : undefined
65
+ ].filter(nonNullable)
66
+ }));
67
+ } else {
68
+ registerRoute(rcEntry.urlPattern, rcEntry.handler, rcEntry.method);
69
+ }
70
+ }
71
+ };
72
+
73
+ const installSerwist = ({ precacheEntries, precacheOptions, cleanupOutdatedCaches, skipWaiting: shouldSkipWaiting = false, importScripts: scriptsToImport, navigationPreload = false, cacheId, clientsClaim: shouldClaimClients = false, runtimeCaching, offlineAnalyticsConfig, disableDevLogs: shouldDisableDevLogs, ...options })=>{
74
+ if (!!scriptsToImport && scriptsToImport.length > 0) self.importScripts(...scriptsToImport);
75
+ if (navigationPreload) enable();
76
+ if (cacheId !== undefined) setCacheNameDetails({
77
+ prefix: cacheId
78
+ });
79
+ if (shouldSkipWaiting) {
80
+ self.skipWaiting();
81
+ } else {
82
+ self.addEventListener("message", (event)=>{
83
+ if (event.data && event.data.type === "SKIP_WAITING") {
84
+ self.skipWaiting();
85
+ }
86
+ });
87
+ }
88
+ if (shouldClaimClients) clientsClaim();
89
+ handlePrecaching({
90
+ precacheEntries,
91
+ precacheOptions,
92
+ cleanupOutdatedCaches,
93
+ ...options.navigateFallback && {
94
+ navigateFallback: options.navigateFallback,
95
+ navigateFallbackAllowlist: options.navigateFallbackAllowlist,
96
+ navigateFallbackDenylist: options.navigateFallbackDenylist
97
+ }
98
+ });
99
+ if (runtimeCaching !== undefined) registerRuntimeCaching(...runtimeCaching);
100
+ if (offlineAnalyticsConfig !== undefined) initialize(offlineAnalyticsConfig);
101
+ if (shouldDisableDevLogs) disableDevLogs();
102
+ };
103
+
104
+ export { disableDevLogs, handlePrecaching, installSerwist, registerRuntimeCaching };
@@ -0,0 +1,109 @@
1
+ 'use strict';
2
+
3
+ var core = require('@serwist/core');
4
+ var initialize = require('@serwist/google-analytics/initialize');
5
+ var navigationPreload = require('@serwist/navigation-preload');
6
+ var precaching = require('@serwist/precaching');
7
+ var routing = require('@serwist/routing');
8
+ var backgroundSync = require('@serwist/background-sync');
9
+ var broadcastUpdate = require('@serwist/broadcast-update');
10
+ var cacheableResponse = require('@serwist/cacheable-response');
11
+ var expiration = require('@serwist/expiration');
12
+ var rangeRequests = require('@serwist/range-requests');
13
+ var strategies = require('@serwist/strategies');
14
+
15
+ const disableDevLogs = ()=>{
16
+ self.__WB_DISABLE_DEV_LOGS = true;
17
+ };
18
+
19
+ const handlePrecaching = ({ precacheEntries, precacheOptions, cleanupOutdatedCaches: shouldCleanupOutdatedCaches = false, ...options })=>{
20
+ if (!!precacheEntries && precacheEntries.length > 0) {
21
+ /**
22
+ * The precacheAndRoute() method efficiently caches and responds to
23
+ * requests for URLs in the manifest.
24
+ * See https://goo.gl/S9QRab
25
+ */ precaching.precacheAndRoute(precacheEntries, precacheOptions);
26
+ }
27
+ if (shouldCleanupOutdatedCaches) precaching.cleanupOutdatedCaches();
28
+ if (options.navigateFallback) {
29
+ routing.registerRoute(new routing.NavigationRoute(precaching.createHandlerBoundToURL(options.navigateFallback), {
30
+ allowlist: options.navigateFallbackAllowlist,
31
+ denylist: options.navigateFallbackDenylist
32
+ }));
33
+ }
34
+ };
35
+
36
+ const nonNullable = (value)=>value !== null && value !== undefined;
37
+
38
+ const HANDLER_NAME_TO_METHOD = {
39
+ CacheFirst: strategies.CacheFirst,
40
+ CacheOnly: strategies.CacheOnly,
41
+ NetworkFirst: strategies.NetworkFirst,
42
+ NetworkOnly: strategies.NetworkOnly,
43
+ StaleWhileRevalidate: strategies.StaleWhileRevalidate
44
+ };
45
+ const registerRuntimeCaching = (...runtimeCachingList)=>{
46
+ for (const rcEntry of runtimeCachingList){
47
+ if (typeof rcEntry.handler === "string") {
48
+ const { cacheName, networkTimeoutSeconds, fetchOptions, matchOptions, plugins, backgroundSync: backgroundSync$1, broadcastUpdate: broadcastUpdate$1, cacheableResponse: cacheableResponse$1, expiration: expiration$1, precacheFallback, rangeRequests: rangeRequests$1 } = rcEntry.options; // entry.options is always defined when entry.handler is of type 'string'.
49
+ const Handler = HANDLER_NAME_TO_METHOD[rcEntry.handler];
50
+ routing.registerRoute(rcEntry.urlPattern, new Handler({
51
+ cacheName: cacheName ?? undefined,
52
+ networkTimeoutSeconds,
53
+ fetchOptions,
54
+ matchOptions,
55
+ plugins: [
56
+ ...plugins ?? [],
57
+ backgroundSync$1 && new backgroundSync.BackgroundSyncPlugin(backgroundSync$1.name, backgroundSync$1.options),
58
+ broadcastUpdate$1 && new broadcastUpdate.BroadcastUpdatePlugin({
59
+ // @ts-expect-error weird...
60
+ channelName: broadcastUpdate$1.channelName,
61
+ ...broadcastUpdate$1.options
62
+ }),
63
+ cacheableResponse$1 && new cacheableResponse.CacheableResponsePlugin(cacheableResponse$1),
64
+ expiration$1 && new expiration.ExpirationPlugin(expiration$1),
65
+ precacheFallback && new precaching.PrecacheFallbackPlugin(precacheFallback),
66
+ rangeRequests$1 ? new rangeRequests.RangeRequestsPlugin() : undefined
67
+ ].filter(nonNullable)
68
+ }));
69
+ } else {
70
+ routing.registerRoute(rcEntry.urlPattern, rcEntry.handler, rcEntry.method);
71
+ }
72
+ }
73
+ };
74
+
75
+ const installSerwist = ({ precacheEntries, precacheOptions, cleanupOutdatedCaches, skipWaiting: shouldSkipWaiting = false, importScripts: scriptsToImport, navigationPreload: navigationPreload$1 = false, cacheId, clientsClaim: shouldClaimClients = false, runtimeCaching, offlineAnalyticsConfig, disableDevLogs: shouldDisableDevLogs, ...options })=>{
76
+ if (!!scriptsToImport && scriptsToImport.length > 0) self.importScripts(...scriptsToImport);
77
+ if (navigationPreload$1) navigationPreload.enable();
78
+ if (cacheId !== undefined) core.setCacheNameDetails({
79
+ prefix: cacheId
80
+ });
81
+ if (shouldSkipWaiting) {
82
+ self.skipWaiting();
83
+ } else {
84
+ self.addEventListener("message", (event)=>{
85
+ if (event.data && event.data.type === "SKIP_WAITING") {
86
+ self.skipWaiting();
87
+ }
88
+ });
89
+ }
90
+ if (shouldClaimClients) core.clientsClaim();
91
+ handlePrecaching({
92
+ precacheEntries,
93
+ precacheOptions,
94
+ cleanupOutdatedCaches,
95
+ ...options.navigateFallback && {
96
+ navigateFallback: options.navigateFallback,
97
+ navigateFallbackAllowlist: options.navigateFallbackAllowlist,
98
+ navigateFallbackDenylist: options.navigateFallbackDenylist
99
+ }
100
+ });
101
+ if (runtimeCaching !== undefined) registerRuntimeCaching(...runtimeCaching);
102
+ if (offlineAnalyticsConfig !== undefined) initialize.initialize(offlineAnalyticsConfig);
103
+ if (shouldDisableDevLogs) disableDevLogs();
104
+ };
105
+
106
+ exports.disableDevLogs = disableDevLogs;
107
+ exports.handlePrecaching = handlePrecaching;
108
+ exports.installSerwist = installSerwist;
109
+ exports.registerRuntimeCaching = registerRuntimeCaching;
@@ -0,0 +1,2 @@
1
+ export declare const nonNullable: <T>(value: T) => value is NonNullable<T>;
2
+ //# sourceMappingURL=nonNullable.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nonNullable.d.ts","sourceRoot":"","sources":["../src/nonNullable.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,WAAW,0CAAkF,CAAC"}
@@ -0,0 +1,3 @@
1
+ import type { RuntimeCaching } from "@serwist/build";
2
+ export declare const registerRuntimeCaching: (...runtimeCachingList: RuntimeCaching[]) => void;
3
+ //# sourceMappingURL=registerRuntimeCaching.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registerRuntimeCaching.d.ts","sourceRoot":"","sources":["../src/registerRuntimeCaching.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAgB,MAAM,gBAAgB,CAAC;AAkBnE,eAAO,MAAM,sBAAsB,0BAA2B,cAAc,EAAE,SA4C7E,CAAC"}
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@serwist/sw",
3
+ "version": "8.0.0",
4
+ "license": "MIT",
5
+ "type": "module",
6
+ "author": "Google's Web DevRel Team, Serwist's Team",
7
+ "description": "This module makes it easy to get started with the Serwist service worker libraries.",
8
+ "repository": "serwist/serwist",
9
+ "bugs": "https://github.com/serwist/serwist/issues",
10
+ "homepage": "https://ducanh-next-pwa.vercel.app",
11
+ "keywords": [
12
+ "serwist",
13
+ "serwistjs",
14
+ "service worker",
15
+ "sw"
16
+ ],
17
+ "module": "./dist/index.js",
18
+ "main": "./dist/index.old.cjs",
19
+ "types": "./dist/index.d.ts",
20
+ "exports": {
21
+ ".": {
22
+ "import": "./dist/index.js",
23
+ "require": "./dist/index.old.cjs",
24
+ "types": "./dist/index.d.ts"
25
+ },
26
+ "./package.json": "./package.json"
27
+ },
28
+ "dependencies": {
29
+ "@serwist/background-sync": "8.0.0",
30
+ "@serwist/broadcast-update": "8.0.0",
31
+ "@serwist/cacheable-response": "8.0.0",
32
+ "@serwist/core": "8.0.0",
33
+ "@serwist/expiration": "8.0.0",
34
+ "@serwist/google-analytics": "8.0.0",
35
+ "@serwist/navigation-preload": "8.0.0",
36
+ "@serwist/precaching": "8.0.0",
37
+ "@serwist/range-requests": "8.0.0",
38
+ "@serwist/routing": "8.0.0",
39
+ "@serwist/strategies": "8.0.0"
40
+ },
41
+ "devDependencies": {
42
+ "rollup": "3.28.1",
43
+ "@serwist/build": "8.0.0",
44
+ "@serwist/constants": "8.0.0"
45
+ },
46
+ "scripts": {
47
+ "build": "rimraf dist && cross-env NODE_ENV=production rollup --config rollup.config.js",
48
+ "lint": "eslint src --ext ts,tsx,js,jsx,cjs,mjs",
49
+ "typecheck": "tsc"
50
+ }
51
+ }
@@ -0,0 +1,27 @@
1
+ // @ts-check
2
+ import { getRollupOptions } from "@serwist/constants/rollup";
3
+
4
+ import packageJson from "./package.json" assert { type: "json" };
5
+
6
+ const isDev = process.env.NODE_ENV === "development";
7
+
8
+ export default getRollupOptions({
9
+ packageJson,
10
+ jsFiles: [
11
+ {
12
+ input: "src/index.ts",
13
+ output: [
14
+ {
15
+ file: "dist/index.old.cjs",
16
+ format: "cjs",
17
+ exports: "named",
18
+ },
19
+ {
20
+ file: "dist/index.js",
21
+ format: "esm",
22
+ },
23
+ ],
24
+ },
25
+ ],
26
+ shouldEmitDeclaration: !isDev,
27
+ });
@@ -0,0 +1,7 @@
1
+ declare const self: WorkerGlobalScope & {
2
+ __WB_DISABLE_DEV_LOGS: boolean;
3
+ };
4
+
5
+ export const disableDevLogs = () => {
6
+ self.__WB_DISABLE_DEV_LOGS = true;
7
+ };
@@ -0,0 +1,37 @@
1
+ import type { PrecacheEntry, PrecacheRouteOptions } from "@serwist/precaching";
2
+ import { cleanupOutdatedCaches, createHandlerBoundToURL, precacheAndRoute } from "@serwist/precaching";
3
+ import { NavigationRoute, registerRoute } from "@serwist/routing";
4
+
5
+ export type HandlePrecachingOptions = {
6
+ precacheEntries?: (PrecacheEntry | string)[];
7
+ precacheOptions?: PrecacheRouteOptions;
8
+
9
+ cleanupOutdatedCaches?: boolean;
10
+ } & ({ navigateFallback: string; navigateFallbackAllowlist?: RegExp[]; navigateFallbackDenylist?: RegExp[] } | { navigateFallback?: never });
11
+
12
+ export const handlePrecaching = ({
13
+ precacheEntries,
14
+ precacheOptions,
15
+ cleanupOutdatedCaches: shouldCleanupOutdatedCaches = false,
16
+ ...options
17
+ }: HandlePrecachingOptions) => {
18
+ if (!!precacheEntries && precacheEntries.length > 0) {
19
+ /**
20
+ * The precacheAndRoute() method efficiently caches and responds to
21
+ * requests for URLs in the manifest.
22
+ * See https://goo.gl/S9QRab
23
+ */
24
+ precacheAndRoute(precacheEntries, precacheOptions);
25
+ }
26
+
27
+ if (shouldCleanupOutdatedCaches) cleanupOutdatedCaches();
28
+
29
+ if (options.navigateFallback) {
30
+ registerRoute(
31
+ new NavigationRoute(createHandlerBoundToURL(options.navigateFallback), {
32
+ allowlist: options.navigateFallbackAllowlist,
33
+ denylist: options.navigateFallbackDenylist,
34
+ })
35
+ );
36
+ }
37
+ };
package/src/index.ts ADDED
@@ -0,0 +1,77 @@
1
+ import type { RuntimeCaching } from "@serwist/build";
2
+ import { clientsClaim, setCacheNameDetails } from "@serwist/core";
3
+ import { type GoogleAnalyticsInitializeOptions, initialize } from "@serwist/google-analytics/initialize";
4
+ import { enable } from "@serwist/navigation-preload";
5
+
6
+ import { disableDevLogs } from "./disableDevLogs.js";
7
+ import { handlePrecaching, type HandlePrecachingOptions } from "./handlePrecaching.js";
8
+ import { registerRuntimeCaching } from "./registerRuntimeCaching.js";
9
+
10
+ declare const self: ServiceWorkerGlobalScope;
11
+
12
+ export type SerwistOptions = HandlePrecachingOptions & {
13
+ skipWaiting?: boolean;
14
+ importScripts?: string[];
15
+ navigationPreload?: boolean;
16
+ cacheId?: string | undefined;
17
+ clientsClaim?: boolean;
18
+ runtimeCaching?: RuntimeCaching[];
19
+ offlineAnalyticsConfig?: GoogleAnalyticsInitializeOptions;
20
+ disableDevLogs?: boolean;
21
+ };
22
+
23
+ export const installSerwist = ({
24
+ precacheEntries,
25
+ precacheOptions,
26
+ cleanupOutdatedCaches,
27
+
28
+ skipWaiting: shouldSkipWaiting = false,
29
+ importScripts: scriptsToImport,
30
+ navigationPreload = false,
31
+ cacheId,
32
+ clientsClaim: shouldClaimClients = false,
33
+ runtimeCaching,
34
+ offlineAnalyticsConfig,
35
+ disableDevLogs: shouldDisableDevLogs,
36
+ ...options
37
+ }: SerwistOptions) => {
38
+ if (!!scriptsToImport && scriptsToImport.length > 0) self.importScripts(...scriptsToImport);
39
+
40
+ if (navigationPreload) enable();
41
+
42
+ if (cacheId !== undefined)
43
+ setCacheNameDetails({
44
+ prefix: cacheId,
45
+ });
46
+
47
+ if (shouldSkipWaiting) {
48
+ self.skipWaiting();
49
+ } else {
50
+ self.addEventListener("message", (event) => {
51
+ if (event.data && event.data.type === "SKIP_WAITING") {
52
+ self.skipWaiting();
53
+ }
54
+ });
55
+ }
56
+
57
+ if (shouldClaimClients) clientsClaim();
58
+
59
+ handlePrecaching({
60
+ precacheEntries,
61
+ precacheOptions,
62
+ cleanupOutdatedCaches,
63
+ ...(options.navigateFallback && {
64
+ navigateFallback: options.navigateFallback,
65
+ navigateFallbackAllowlist: options.navigateFallbackAllowlist,
66
+ navigateFallbackDenylist: options.navigateFallbackDenylist,
67
+ }),
68
+ });
69
+
70
+ if (runtimeCaching !== undefined) registerRuntimeCaching(...runtimeCaching);
71
+
72
+ if (offlineAnalyticsConfig !== undefined) initialize(offlineAnalyticsConfig);
73
+
74
+ if (shouldDisableDevLogs) disableDevLogs();
75
+ };
76
+
77
+ export { disableDevLogs, handlePrecaching, registerRuntimeCaching };
@@ -0,0 +1 @@
1
+ export const nonNullable = <T>(value: T): value is NonNullable<T> => value !== null && value !== undefined;
@@ -0,0 +1,65 @@
1
+ import { BackgroundSyncPlugin } from "@serwist/background-sync";
2
+ import { BroadcastUpdatePlugin } from "@serwist/broadcast-update";
3
+ import type { RuntimeCaching, StrategyName } from "@serwist/build";
4
+ import { CacheableResponsePlugin } from "@serwist/cacheable-response";
5
+ import { ExpirationPlugin } from "@serwist/expiration";
6
+ import { PrecacheFallbackPlugin } from "@serwist/precaching";
7
+ import { RangeRequestsPlugin } from "@serwist/range-requests";
8
+ import { registerRoute } from "@serwist/routing";
9
+ import { CacheFirst, CacheOnly, NetworkFirst, NetworkOnly, StaleWhileRevalidate } from "@serwist/strategies";
10
+
11
+ import { nonNullable } from "./nonNullable.js";
12
+
13
+ const HANDLER_NAME_TO_METHOD = {
14
+ CacheFirst,
15
+ CacheOnly,
16
+ NetworkFirst,
17
+ NetworkOnly,
18
+ StaleWhileRevalidate,
19
+ } satisfies Record<StrategyName, unknown>;
20
+
21
+ export const registerRuntimeCaching = (...runtimeCachingList: RuntimeCaching[]) => {
22
+ for (const rcEntry of runtimeCachingList) {
23
+ if (typeof rcEntry.handler === "string") {
24
+ const {
25
+ cacheName,
26
+ networkTimeoutSeconds,
27
+ fetchOptions,
28
+ matchOptions,
29
+ plugins,
30
+ backgroundSync,
31
+ broadcastUpdate,
32
+ cacheableResponse,
33
+ expiration,
34
+ precacheFallback,
35
+ rangeRequests,
36
+ } = rcEntry.options!; // entry.options is always defined when entry.handler is of type 'string'.
37
+ const Handler = HANDLER_NAME_TO_METHOD[rcEntry.handler];
38
+ registerRoute(
39
+ rcEntry.urlPattern,
40
+ new Handler({
41
+ cacheName: cacheName ?? undefined,
42
+ networkTimeoutSeconds,
43
+ fetchOptions,
44
+ matchOptions,
45
+ plugins: [
46
+ ...(plugins ?? []),
47
+ backgroundSync && new BackgroundSyncPlugin(backgroundSync.name, backgroundSync.options),
48
+ broadcastUpdate &&
49
+ new BroadcastUpdatePlugin({
50
+ // @ts-expect-error weird...
51
+ channelName: broadcastUpdate.channelName,
52
+ ...broadcastUpdate.options,
53
+ }),
54
+ cacheableResponse && new CacheableResponsePlugin(cacheableResponse),
55
+ expiration && new ExpirationPlugin(expiration),
56
+ precacheFallback && new PrecacheFallbackPlugin(precacheFallback),
57
+ rangeRequests ? new RangeRequestsPlugin() : undefined,
58
+ ].filter(nonNullable),
59
+ })
60
+ );
61
+ } else {
62
+ registerRoute(rcEntry.urlPattern, rcEntry.handler, rcEntry.method);
63
+ }
64
+ }
65
+ };
package/tsconfig.json ADDED
@@ -0,0 +1,8 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "module": "NodeNext"
5
+ },
6
+ "include": ["**/*.ts", "rollup.config.js"],
7
+ "exclude": ["dist", "node_modules"]
8
+ }