-
Notifications
You must be signed in to change notification settings - Fork 148
/
Copy pathbuild.ts
774 lines (685 loc) · 24 KB
/
build.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
import cp from "node:child_process";
import fs from "node:fs";
import { createRequire as topLevelCreateRequire } from "node:module";
import path from "node:path";
import url from "node:url";
import {
build as buildAsync,
BuildOptions as ESBuildOptions,
buildSync,
} from "esbuild";
import { minifyAll } from "./minimize-js.js";
import openNextPlugin from "./plugin.js";
interface BuildOptions {
/**
* Minify the server bundle.
* @default false
*/
minify?: boolean;
/**
* Print debug information.
* @default false
*/
debug?: boolean;
/**
* The command to build the Next.js app.
* @default `npm run build`, `yarn build`, or `pnpm build` based on the lock file found in the app's directory or any of its parent directories.
* @example
* ```ts
* build({
* buildCommand: "pnpm custom:build",
* });
* ```
*/
buildCommand?: string;
/**
* The path to the target folder of build output from the `buildCommand` option (the path which will contain the `.next` and `.open-next` folders). This path is relative from the current process.cwd().
* @default "."
*/
buildOutputPath?: string;
/**
* The path to the root of the Next.js app's source code. This path is relative from the current process.cwd().
* @default "."
*/
appPath?: string;
}
const require = topLevelCreateRequire(import.meta.url);
const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
let options: ReturnType<typeof normalizeOptions>;
export type PublicFiles = {
files: string[];
};
export async function build(opts: BuildOptions = {}) {
const { root: monorepoRoot, packager } = findMonorepoRoot(
path.join(process.cwd(), opts.appPath || "."),
);
// Initialize options
options = normalizeOptions(opts, monorepoRoot);
// Pre-build validation
checkRunningInsideNextjsApp();
printNextjsVersion();
printOpenNextVersion();
// Build Next.js app
printHeader("Building Next.js app");
setStandaloneBuildMode(monorepoRoot);
await buildNextjsApp(packager);
// Generate deployable bundle
printHeader("Generating bundle");
initOutputDir();
createStaticAssets();
createCacheAssets(monorepoRoot);
await createServerBundle(monorepoRoot);
createRevalidationBundle();
createImageOptimizationBundle();
createWarmerBundle();
if (options.minify) {
await minifyServerBundle();
}
}
function normalizeOptions(opts: BuildOptions, root: string) {
const appPath = path.join(process.cwd(), opts.appPath || ".");
const buildOutputPath = path.join(process.cwd(), opts.buildOutputPath || ".");
const outputDir = path.join(buildOutputPath, ".open-next");
const nextPackageJsonPath = findNextPackageJsonPath(appPath, root);
return {
openNextVersion: getOpenNextVersion(),
nextVersion: getNextVersion(nextPackageJsonPath),
nextPackageJsonPath,
appPath,
appBuildOutputPath: buildOutputPath,
appPublicPath: path.join(appPath, "public"),
outputDir,
tempDir: path.join(outputDir, ".build"),
minify: opts.minify ?? Boolean(process.env.OPEN_NEXT_MINIFY) ?? false,
debug: opts.debug ?? Boolean(process.env.OPEN_NEXT_DEBUG) ?? false,
buildCommand: opts.buildCommand,
};
}
function checkRunningInsideNextjsApp() {
const { appPath } = options;
const extension = ["js", "cjs", "mjs"].find((ext) =>
fs.existsSync(path.join(appPath, `next.config.${ext}`)),
);
if (!extension) {
console.error(
"Error: next.config.js not found. Please make sure you are running this command inside a Next.js app.",
);
process.exit(1);
}
}
function findMonorepoRoot(appPath: string) {
let currentPath = appPath;
while (currentPath !== "/") {
const found = [
{ file: "package-lock.json", packager: "npm" as const },
{ file: "yarn.lock", packager: "yarn" as const },
{ file: "pnpm-lock.yaml", packager: "pnpm" as const },
].find((f) => fs.existsSync(path.join(currentPath, f.file)));
if (found) {
if (currentPath !== appPath) {
console.info("Monorepo detected at", currentPath);
}
return { root: currentPath, packager: found.packager };
}
currentPath = path.dirname(currentPath);
}
// note: a lock file (package-lock.json, yarn.lock, or pnpm-lock.yaml) is
// not found in the app's directory or any of its parent directories.
// We are going to assume that the app is not part of a monorepo.
return { root: appPath, packager: "npm" as const };
}
function findNextPackageJsonPath(appPath: string, root: string) {
// This is needed for the case where the app is a single-version monorepo and the package.json is in the root of the monorepo
return fs.existsSync(path.join(appPath, "./package.json"))
? path.join(appPath, "./package.json")
: path.join(root, "./package.json");
}
function setStandaloneBuildMode(monorepoRoot: string) {
// Equivalent to setting `target: "standalone"` in next.config.js
process.env.NEXT_PRIVATE_STANDALONE = "true";
// Equivalent to setting `experimental.outputFileTracingRoot` in next.config.js
process.env.NEXT_PRIVATE_OUTPUT_TRACE_ROOT = monorepoRoot;
}
function buildNextjsApp(packager: "npm" | "yarn" | "pnpm") {
const { nextPackageJsonPath } = options;
const command =
options.buildCommand ??
(packager === "npm" ? "npm run build" : `${packager} build`);
cp.execSync(command, {
stdio: "inherit",
cwd: path.dirname(nextPackageJsonPath),
});
}
function printHeader(header: string) {
header = `OpenNext — ${header}`;
console.info(
[
"",
"┌" + "─".repeat(header.length + 2) + "┐",
`│ ${header} │`,
"└" + "─".repeat(header.length + 2) + "┘",
"",
].join("\n"),
);
}
function printNextjsVersion() {
const { appPath } = options;
cp.spawnSync(
"node",
[
"-e",
`"console.info('Next.js v' + require('next/package.json').version)"`,
],
{
stdio: "inherit",
cwd: appPath,
shell: true,
},
);
}
function printOpenNextVersion() {
const { openNextVersion } = options;
console.info(`OpenNext v${openNextVersion}`);
}
function initOutputDir() {
const { outputDir, tempDir } = options;
fs.rmSync(outputDir, { recursive: true, force: true });
fs.mkdirSync(tempDir, { recursive: true });
}
function createWarmerBundle() {
console.info(`Bundling warmer function...`);
const { outputDir } = options;
// Create output folder
const outputPath = path.join(outputDir, "warmer-function");
fs.mkdirSync(outputPath, { recursive: true });
// Build Lambda code
// note: bundle in OpenNext package b/c the adatper relys on the
// "serverless-http" package which is not a dependency in user's
// Next.js app.
esbuildSync({
entryPoints: [path.join(__dirname, "adapters", "warmer-function.js")],
external: ["next"],
outfile: path.join(outputPath, "index.mjs"),
banner: {
js: [
"import { createRequire as topLevelCreateRequire } from 'module';",
"const require = topLevelCreateRequire(import.meta.url);",
"import bannerUrl from 'url';",
"const __dirname = bannerUrl.fileURLToPath(new URL('.', import.meta.url));",
].join(""),
},
});
}
async function minifyServerBundle() {
console.info(`Minimizing server function...`);
const { outputDir } = options;
await minifyAll(path.join(outputDir, "server-function"), {
compress_json: true,
mangle: true,
});
}
function createRevalidationBundle() {
console.info(`Bundling revalidation function...`);
const { appBuildOutputPath, outputDir } = options;
// Create output folder
const outputPath = path.join(outputDir, "revalidation-function");
fs.mkdirSync(outputPath, { recursive: true });
// Build Lambda code
esbuildSync({
external: ["next", "styled-jsx", "react"],
entryPoints: [path.join(__dirname, "adapters", "revalidate.js")],
outfile: path.join(outputPath, "index.mjs"),
});
// Copy over .next/prerender-manifest.json file
fs.copyFileSync(
path.join(appBuildOutputPath, ".next", "prerender-manifest.json"),
path.join(outputPath, "prerender-manifest.json"),
);
}
function createImageOptimizationBundle() {
console.info(`Bundling image optimization function...`);
const { appPath, appBuildOutputPath, outputDir } = options;
// Create output folder
const outputPath = path.join(outputDir, "image-optimization-function");
fs.mkdirSync(outputPath, { recursive: true });
// Build Lambda code (1st pass)
// note: bundle in OpenNext package b/c the adapter relies on the
// "@aws-sdk/client-s3" package which is not a dependency in user's
// Next.js app.
esbuildSync({
entryPoints: [
path.join(__dirname, "adapters", "image-optimization-adapter.js"),
],
external: ["sharp", "next"],
outfile: path.join(outputPath, "index.mjs"),
});
// Build Lambda code (2nd pass)
// note: bundle in user's Next.js app again b/c the adapter relies on the
// "next" package. And the "next" package from user's app should
// be used.
esbuildSync({
entryPoints: [path.join(outputPath, "index.mjs")],
external: ["sharp"],
allowOverwrite: true,
outfile: path.join(outputPath, "index.mjs"),
banner: {
js: [
"import { createRequire as topLevelCreateRequire } from 'module';",
"const require = topLevelCreateRequire(import.meta.url);",
"import bannerUrl from 'url';",
"const __dirname = bannerUrl.fileURLToPath(new URL('.', import.meta.url));",
].join("\n"),
},
});
// Copy over .next/required-server-files.json file
fs.mkdirSync(path.join(outputPath, ".next"));
fs.copyFileSync(
path.join(appBuildOutputPath, ".next/required-server-files.json"),
path.join(outputPath, ".next/required-server-files.json"),
);
// Sharp provides pre-build binaries for all platforms. https://github.com/lovell/sharp/blob/main/docs/install.md#cross-platform
// Target should be same as used by Lambda, see https://github.com/sst/sst/blob/ca6f763fdfddd099ce2260202d0ce48c72e211ea/packages/sst/src/constructs/NextjsSite.ts#L114
// For SHARP_IGNORE_GLOBAL_LIBVIPS see: https://github.com/lovell/sharp/blob/main/docs/install.md#aws-lambda
const nodeOutputPath = path.resolve(outputPath);
//check if we are running in Windows environment then set env variables accordingly.
cp.execSync(
`npm install --arch=arm64 --platform=linux --target=18 --libc=glibc --prefix="${nodeOutputPath}" [email protected]`,
{
stdio: "inherit",
cwd: appPath,
env: {
...process.env,
SHARP_IGNORE_GLOBAL_LIBVIPS: "1",
},
},
);
}
function createStaticAssets() {
console.info(`Bundling static assets...`);
const { appBuildOutputPath, appPublicPath, outputDir } = options;
// Create output folder
const outputPath = path.join(outputDir, "assets");
fs.mkdirSync(outputPath, { recursive: true });
// Next.js outputs assets into multiple files. Copy into the same directory.
// Copy over:
// - .next/BUILD_ID => _next/BUILD_ID
// - .next/static => _next/static
// - public/* => *
fs.copyFileSync(
path.join(appBuildOutputPath, ".next/BUILD_ID"),
path.join(outputPath, "BUILD_ID"),
);
fs.cpSync(
path.join(appBuildOutputPath, ".next/static"),
path.join(outputPath, "_next", "static"),
{ recursive: true },
);
if (fs.existsSync(appPublicPath)) {
fs.cpSync(appPublicPath, outputPath, { recursive: true });
}
}
function createCacheAssets(monorepoRoot: string) {
console.info(`Bundling cache assets...`);
const { appBuildOutputPath, outputDir } = options;
const packagePath = path.relative(monorepoRoot, appBuildOutputPath);
const buildId = getBuildId(appBuildOutputPath);
// Copy pages to cache folder
const dotNextPath = path.join(
appBuildOutputPath,
".next/standalone",
packagePath,
);
const outputPath = path.join(outputDir, "cache", buildId);
[".next/server/pages", ".next/server/app"]
.map((dir) => path.join(dotNextPath, dir))
.filter(fs.existsSync)
.forEach((dir) => fs.cpSync(dir, outputPath, { recursive: true }));
// Remove non-cache files
const htmlPages = getHtmlPages(dotNextPath);
removeFiles(
outputPath,
(file) =>
file.endsWith(".js") ||
file.endsWith(".js.nft.json") ||
(file.endsWith(".html") && htmlPages.has(file)),
);
// Copy fetch-cache to cache folder
const fetchCachePath = path.join(
appBuildOutputPath,
".next/cache/fetch-cache",
);
if (fs.existsSync(fetchCachePath)) {
const fetchOutputPath = path.join(outputDir, "cache", "__fetch", buildId);
fs.mkdirSync(fetchOutputPath, { recursive: true });
fs.cpSync(fetchCachePath, fetchOutputPath, { recursive: true });
}
}
/***************************/
/* Server Helper Functions */
/***************************/
async function createServerBundle(monorepoRoot: string) {
console.info(`Bundling server function...`);
const { appPath, appBuildOutputPath, outputDir } = options;
// Create output folder
const outputPath = path.join(outputDir, "server-function");
fs.mkdirSync(outputPath, { recursive: true });
// Resolve path to the Next.js app if inside the monorepo
// note: if user's app is inside a monorepo, standalone mode places
// `node_modules` inside `.next/standalone`, and others inside
// `.next/standalone/package/path` (ie. `.next`, `server.js`).
// We need to output the handler file inside the package path.
const isMonorepo = monorepoRoot !== appPath;
const packagePath = path.relative(monorepoRoot, appBuildOutputPath);
// Copy over standalone output files
// note: if user uses pnpm as the package manager, node_modules contain
// symlinks. We don't want to resolve the symlinks when copying.
fs.cpSync(path.join(appBuildOutputPath, ".next/standalone"), outputPath, {
recursive: true,
verbatimSymlinks: true,
});
// Standalone output already has a Node server "server.js", remove it.
// It will be replaced with the Lambda handler.
fs.rmSync(path.join(outputPath, packagePath, "server.js"), { force: true });
// Build Lambda code
// note: bundle in OpenNext package b/c the adapter relies on the
// "serverless-http" package which is not a dependency in user's
// Next.js app.
const plugins =
compareSemver(options.nextVersion, "13.4.13") >= 0
? [
openNextPlugin({
target: /plugins\/serverHandler\.js/g,
replacements: ["./serverHandler.replacement.js"],
}),
openNextPlugin({
target: /plugins\/util\.js/g,
replacements: ["./util.replacement.js"],
}),
openNextPlugin({
target: /plugins\/routing\/default\.js/g,
replacements: ["./default.replacement.js"],
}),
]
: undefined;
if (plugins) {
console.log(
`Applying plugins:: [${plugins
.map(({ name }) => name)
.join(",")}] for Next version: ${options.nextVersion}`,
);
}
await esbuildAsync({
entryPoints: [path.join(__dirname, "adapters", "server-adapter.js")],
external: ["next"],
outfile: path.join(outputPath, packagePath, "index.mjs"),
banner: {
js: [
"import { createRequire as topLevelCreateRequire } from 'module';",
"const require = topLevelCreateRequire(import.meta.url);",
"import bannerUrl from 'url';",
"const __dirname = bannerUrl.fileURLToPath(new URL('.', import.meta.url));",
].join(""),
},
plugins,
});
if (isMonorepo) {
addMonorepoEntrypoint(outputPath, packagePath);
}
addPublicFilesList(outputPath, packagePath);
injectMiddlewareGeolocation(outputPath, packagePath);
removeCachedPages(outputPath, packagePath);
addCacheHandler(outputPath);
if (options.minify) {
removeNodeModule(path.join(outputPath, "node_modules"), [
"@esbuild",
"prisma/libquery_engine-darwin-arm64.dylib.node",
"@swc/core-darwin-arm64",
"@swc/core",
"better-sqlite3",
"esbuild",
"webpack",
"uglify-js",
// "react", // TODO: remove react/react-dom when nextjs updates its precompile versions
// "react-dom",
"@webassemblyjs",
"uglify-js",
"sass",
"caniuse-lite",
]);
}
}
function addMonorepoEntrypoint(outputPath: string, packagePath: string) {
// Note: in the monorepo case, the handler file is output to
// `.next/standalone/package/path/index.mjs`, but we want
// the Lambda function to be able to find the handler at
// the root of the bundle. We will create a dummy `index.mjs`
// that re-exports the real handler.
// Always use posix path for import path
const packagePosixPath = packagePath.split(path.sep).join(path.posix.sep);
fs.writeFileSync(
path.join(outputPath, "index.mjs"),
[`export * from "./${packagePosixPath}/index.mjs";`].join(""),
);
}
function injectMiddlewareGeolocation(outputPath: string, packagePath: string) {
// WORKAROUND: Set `NextRequest` geolocation data — https://github.com/serverless-stack/open-next#workaround-set-nextrequest-geolocation-data
const basePath = path.join(outputPath, packagePath, ".next", "server");
const rootMiddlewarePath = path.join(basePath, "middleware.js");
const srcMiddlewarePath = path.join(basePath, "src", "middleware.js");
if (fs.existsSync(rootMiddlewarePath)) {
inject(rootMiddlewarePath);
} else if (fs.existsSync(srcMiddlewarePath)) {
inject(srcMiddlewarePath);
}
function inject(middlewarePath: string) {
const content = fs.readFileSync(middlewarePath, "utf-8");
fs.writeFileSync(
middlewarePath,
content.replace(
"geo: init.geo || {}",
`geo: init.geo || {
country: this.headers.get("cloudfront-viewer-country"),
countryName: this.headers.get("cloudfront-viewer-country-name"),
region: this.headers.get("cloudfront-viewer-country-region"),
regionName: this.headers.get("cloudfront-viewer-country-region-name"),
city: this.headers.get("cloudfront-viewer-city"),
postalCode: this.headers.get("cloudfront-viewer-postal-code"),
timeZone: this.headers.get("cloudfront-viewer-time-zone"),
latitude: this.headers.get("cloudfront-viewer-latitude"),
longitude: this.headers.get("cloudfront-viewer-longitude"),
metroCode: this.headers.get("cloudfront-viewer-metro-code"),
}`,
),
);
}
}
function addPublicFilesList(outputPath: string, packagePath: string) {
// Get a list of all files in /public
const { appPublicPath } = options;
const acc: PublicFiles = { files: [] };
function processDirectory(pathInPublic: string) {
const files = fs.readdirSync(path.join(appPublicPath, pathInPublic), {
withFileTypes: true,
});
for (const file of files) {
file.isDirectory()
? processDirectory(path.join(pathInPublic, file.name))
: acc.files.push(path.posix.join(pathInPublic, file.name));
}
}
if (fs.existsSync(appPublicPath)) {
processDirectory("/");
}
// Save the list
const outputOpenNextPath = path.join(outputPath, packagePath, ".open-next");
fs.mkdirSync(outputOpenNextPath, { recursive: true });
fs.writeFileSync(
path.join(outputOpenNextPath, "public-files.json"),
JSON.stringify(acc),
);
}
function removeCachedPages(outputPath: string, packagePath: string) {
// Pre-rendered pages will be served out from S3 by the cache handler
const dotNextPath = path.join(outputPath, packagePath);
const isFallbackTruePage = /\[.*\]/;
const htmlPages = getHtmlPages(dotNextPath);
[".next/server/pages", ".next/server/app"]
.map((dir) => path.join(dotNextPath, dir))
.filter(fs.existsSync)
.forEach((dir) =>
removeFiles(
dir,
(file) =>
file.endsWith(".json") ||
file.endsWith(".rsc") ||
file.endsWith(".meta") ||
(file.endsWith(".html") &&
// do not remove static HTML files
!htmlPages.has(file) &&
// do not remove HTML files with "[param].html" format
// b/c they are used for "fallback:true" pages
!isFallbackTruePage.test(file)),
),
);
}
function addCacheHandler(outputPath: string) {
esbuildSync({
external: ["next", "styled-jsx", "react"],
entryPoints: [path.join(__dirname, "adapters", "cache.js")],
outfile: path.join(outputPath, "cache.cjs"),
target: ["node18"],
format: "cjs",
});
}
/********************/
/* Helper Functions */
/********************/
function esbuildSync(esbuildOptions: ESBuildOptions) {
const { openNextVersion, debug } = options;
const result = buildSync({
target: "esnext",
format: "esm",
platform: "node",
bundle: true,
minify: debug ? false : true,
sourcemap: debug ? "inline" : false,
...esbuildOptions,
define: {
...esbuildOptions.define,
"process.env.OPEN_NEXT_DEBUG": process.env.OPEN_NEXT_DEBUG
? "true"
: "false",
"process.env.OPEN_NEXT_VERSION": `"${openNextVersion}"`,
},
});
if (result.errors.length > 0) {
result.errors.forEach((error) => console.error(error));
throw new Error(
`There was a problem bundling ${
(esbuildOptions.entryPoints as string[])[0]
}.`,
);
}
}
async function esbuildAsync(esbuildOptions: ESBuildOptions) {
const { openNextVersion, debug } = options;
const result = await buildAsync({
target: "esnext",
format: "esm",
platform: "node",
bundle: true,
minify: debug ? false : true,
sourcemap: debug ? "inline" : false,
...esbuildOptions,
// "process.env.OPEN_NEXT_DEBUG" determines if the logger writes to console.log
define: {
...esbuildOptions.define,
"process.env.OPEN_NEXT_DEBUG": process.env.OPEN_NEXT_DEBUG
? "true"
: "false",
"process.env.OPEN_NEXT_VERSION": `"${openNextVersion}"`,
},
});
if (result.errors.length > 0) {
result.errors.forEach((error) => console.error(error));
throw new Error(
`There was a problem bundling ${
(esbuildOptions.entryPoints as string[])[0]
}.`,
);
}
}
function removeFiles(
root: string,
conditionFn: (file: string) => boolean,
searchingDir: string = "",
) {
fs.readdirSync(path.join(root, searchingDir)).forEach((file) => {
const filePath = path.join(root, searchingDir, file);
if (fs.statSync(filePath).isDirectory()) {
removeFiles(root, conditionFn, path.join(searchingDir, file));
return;
}
if (conditionFn(path.join(searchingDir, file))) {
fs.rmSync(filePath, { force: true });
}
});
}
function getHtmlPages(dotNextPath: string) {
// Get a list of HTML pages
//
// sample return value:
// Set([
// '404.html',
// 'csr.html',
// 'image-html-tag.html',
// ])
const manifestPath = path.join(
dotNextPath,
".next/server/pages-manifest.json",
);
const manifest = fs.readFileSync(manifestPath, "utf-8");
return Object.entries(JSON.parse(manifest))
.filter(([_, value]) => (value as string).endsWith(".html"))
.map(([_, value]) => (value as string).replace(/^pages\//, ""))
.reduce((acc, page) => {
acc.add(page);
return acc;
}, new Set<string>());
}
function getBuildId(dotNextPath: string) {
return fs
.readFileSync(path.join(dotNextPath, ".next/BUILD_ID"), "utf-8")
.trim();
}
function getOpenNextVersion() {
return require(path.join(__dirname, "../package.json")).version;
}
function getNextVersion(nextPackageJsonPath: string) {
const version = require(nextPackageJsonPath).dependencies.next;
// Drop the -canary.n suffix
return version.split("-")[0];
}
function compareSemver(v1: string, v2: string): number {
if (v1 === "latest") return 1;
if (/^[^\d]/.test(v1)) {
v1 = v1.substring(1);
}
if (/^[^\d]/.test(v2)) {
v2 = v2.substring(1);
}
const [major1, minor1, patch1] = v1.split(".").map(Number);
const [major2, minor2, patch2] = v2.split(".").map(Number);
if (major1 !== major2) return major1 - major2;
if (minor1 !== minor2) return minor1 - minor2;
return patch1 - patch2;
}
function removeNodeModule(nodeModulesPath: string, modules: string[]) {
console.log("removing: ", modules);
for (const module of modules) {
fs.rmSync(path.join(nodeModulesPath, module), {
force: true,
recursive: true,
});
}
}