-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.ts
237 lines (209 loc) · 9.53 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { InjectManifest } from "@serwist/webpack-plugin";
import { ChildCompilationPlugin, relativeToOutputPath } from "@serwist/webpack-plugin/internal";
import { globSync } from "glob";
import type { NextConfig } from "next";
import type { Compilation, Configuration, default as Webpack } from "webpack";
import type { ExcludeParams, SerwistNextOptions, SerwistNextOptionsKey } from "./internal-types.js";
import { getContentHash, getFileHash, loadTSConfig, logger } from "./lib/index.js";
import type { InjectManifestOptions, InjectManifestOptionsComplete } from "./lib/types.js";
import { validateInjectManifestOptions } from "./lib/validator.js";
const __dirname = fileURLToPath(new URL(".", import.meta.url));
/**
* Integrates Serwist into your Next.js app.
* @param userOptions
* @returns
*/
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;
},
});
};
export default withSerwistInit;
export { validateInjectManifestOptions };
export type { InjectManifestOptions as PluginOptions, InjectManifestOptionsComplete as PluginOptionsComplete };