-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
server-build.ts
1759 lines (1603 loc) · 51.9 KB
/
server-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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import path from 'path';
import semver from 'semver';
import { Sema } from 'async-sema';
import {
Config,
FileBlob,
FileFsRef,
Lambda,
NodeVersion,
NowBuildError,
Prerender,
debug,
glob,
Files,
BuildResultV2Typical as BuildResult,
} from '@vercel/build-utils';
import { Route, RouteWithHandle } from '@vercel/routing-utils';
import { MAX_AGE_ONE_YEAR } from '.';
import {
NextRequiredServerFilesManifest,
NextImagesManifest,
NextPrerenderedRoutes,
RoutesManifest,
collectTracedFiles,
createPseudoLayer,
createLambdaFromPseudoLayers,
getPageLambdaGroups,
getDynamicRoutes,
localizeDynamicRoutes,
isDynamicRoute,
normalizePage,
getStaticFiles,
onPrerenderRouteInitial,
onPrerenderRoute,
normalizeLocalePath,
PseudoFile,
detectLambdaLimitExceeding,
outputFunctionFileSizeInfo,
MAX_UNCOMPRESSED_LAMBDA_SIZE,
normalizeIndexOutput,
getImagesConfig,
getNextServerPath,
getMiddlewareBundle,
getFilesMapFromReasons,
UnwrapPromise,
} from './utils';
import {
nodeFileTrace,
NodeFileTraceReasons,
NodeFileTraceResult,
} from '@vercel/nft';
import resolveFrom from 'resolve-from';
import fs, { lstat } from 'fs-extra';
import escapeStringRegexp from 'escape-string-regexp';
import prettyBytes from 'pretty-bytes';
// related PR: https://github.com/vercel/next.js/pull/30046
const CORRECT_NOT_FOUND_ROUTES_VERSION = 'v12.0.1';
const CORRECT_MIDDLEWARE_ORDER_VERSION = 'v12.1.7-canary.29';
const NEXT_DATA_MIDDLEWARE_RESOLVING_VERSION = 'v12.1.7-canary.33';
const EMPTY_ALLOW_QUERY_FOR_PRERENDERED_VERSION = 'v12.2.0';
const CORRECTED_MANIFESTS_VERSION = 'v12.2.0';
export async function serverBuild({
dynamicPages,
pagesDir,
config = {},
privateOutputs,
baseDir,
workPath,
entryPath,
nodeVersion,
buildId,
escapedBuildId,
dynamicPrefix,
entryDirectory,
outputDirectory,
redirects,
beforeFilesRewrites,
afterFilesRewrites,
fallbackRewrites,
headers,
dataRoutes,
hasIsr404Page,
hasIsr500Page,
imagesManifest,
wildcardConfig,
routesManifest,
staticPages,
lambdaPages,
nextVersion,
lambdaAppPaths,
canUsePreviewMode,
trailingSlash,
prerenderManifest,
appPathRoutesManifest,
omittedPrerenderRoutes,
trailingSlashRedirects,
isCorrectLocaleAPIRoutes,
lambdaCompressedByteLimit,
requiredServerFilesManifest,
}: {
appPathRoutesManifest?: Record<string, string>;
dynamicPages: string[];
trailingSlash: boolean;
config: Config;
pagesDir: string;
baseDir: string;
canUsePreviewMode: boolean;
omittedPrerenderRoutes: Set<string>;
staticPages: { [key: string]: FileFsRef };
lambdaAppPaths: { [key: string]: FileFsRef };
lambdaPages: { [key: string]: FileFsRef };
privateOutputs: { files: Files; routes: Route[] };
entryPath: string;
dynamicPrefix: string;
buildId: string;
escapedBuildId: string;
wildcardConfig: BuildResult['wildcard'];
nodeVersion: NodeVersion;
entryDirectory: string;
outputDirectory: string;
headers: Route[];
workPath: string;
beforeFilesRewrites: Route[];
afterFilesRewrites: Route[];
fallbackRewrites: Route[];
redirects: Route[];
dataRoutes: Route[];
nextVersion: string;
hasIsr404Page: boolean;
hasIsr500Page: boolean;
trailingSlashRedirects: Route[];
routesManifest: RoutesManifest;
lambdaCompressedByteLimit: number;
isCorrectLocaleAPIRoutes: boolean;
imagesManifest?: NextImagesManifest;
prerenderManifest: NextPrerenderedRoutes;
requiredServerFilesManifest: NextRequiredServerFilesManifest;
}): Promise<BuildResult> {
lambdaPages = Object.assign({}, lambdaPages, lambdaAppPaths);
const lambdas: { [key: string]: Lambda } = {};
const prerenders: { [key: string]: Prerender } = {};
const lambdaPageKeys = Object.keys(lambdaPages);
const internalPages = ['_app.js', '_error.js', '_document.js'];
const pageBuildTraces = await glob('**/*.js.nft.json', pagesDir);
const isEmptyAllowQueryForPrendered = semver.gte(
nextVersion,
EMPTY_ALLOW_QUERY_FOR_PRERENDERED_VERSION
);
let appBuildTraces: UnwrapPromise<ReturnType<typeof glob>> = {};
let appDir: string | null = null;
if (appPathRoutesManifest) {
appDir = path.join(pagesDir, '../app');
appBuildTraces = await glob('**/*.js.nft.json', appDir);
}
const isCorrectNotFoundRoutes = semver.gte(
nextVersion,
CORRECT_NOT_FOUND_ROUTES_VERSION
);
const isCorrectMiddlewareOrder = semver.gte(
nextVersion,
CORRECT_MIDDLEWARE_ORDER_VERSION
);
const isCorrectManifests = semver.gte(
nextVersion,
CORRECTED_MANIFESTS_VERSION
);
let hasStatic500 = !!staticPages[path.posix.join(entryDirectory, '500')];
if (lambdaPageKeys.length === 0) {
throw new NowBuildError({
code: 'NEXT_NO_SERVER_PAGES',
message: 'No server pages were built',
link: 'https://err.sh/vercel/vercel/now-next-no-serverless-pages-built',
});
}
const pageMatchesApi = (page: string) => {
return page.startsWith('api/') || page === 'api.js';
};
const { i18n } = routesManifest;
const hasPages404 = routesManifest.pages404;
let static404Page =
staticPages[path.posix.join(entryDirectory, '404')] && hasPages404
? path.posix.join(entryDirectory, '404')
: staticPages[path.posix.join(entryDirectory, '_errors/404')]
? path.posix.join(entryDirectory, '_errors/404')
: undefined;
if (!static404Page && i18n) {
static404Page = staticPages[
path.posix.join(entryDirectory, i18n.defaultLocale, '404')
]
? path.posix.join(entryDirectory, i18n.defaultLocale, '404')
: undefined;
}
if (!hasStatic500 && i18n) {
hasStatic500 =
!!staticPages[path.posix.join(entryDirectory, i18n.defaultLocale, '500')];
}
const lstatSema = new Sema(25);
const lstatResults: { [key: string]: ReturnType<typeof lstat> } = {};
const nonLambdaSsgPages = new Set<string>();
Object.keys(prerenderManifest.staticRoutes).forEach(route => {
const result = onPrerenderRouteInitial(
prerenderManifest,
canUsePreviewMode,
entryDirectory,
nonLambdaSsgPages,
route,
routesManifest.pages404,
routesManifest,
appDir
);
if (result && result.static404Page) {
static404Page = result.static404Page;
}
if (result && result.static500Page) {
hasStatic500 = true;
}
});
const hasLambdas =
!static404Page ||
lambdaPageKeys.some(
page =>
!internalPages.includes(page) &&
!nonLambdaSsgPages.has('/' + page.replace(/\.js$/, ''))
);
if (lambdaPages['404.js']) {
internalPages.push('404.js');
}
const prerenderRoutes = new Set<string>([
...(canUsePreviewMode ? omittedPrerenderRoutes : []),
...Object.keys(prerenderManifest.blockingFallbackRoutes),
...Object.keys(prerenderManifest.fallbackRoutes),
...Object.keys(prerenderManifest.staticRoutes).map(route => {
const staticRoute = prerenderManifest.staticRoutes[route];
return staticRoute.srcRoute || route;
}),
]);
if (hasLambdas) {
const initialTracingLabel = 'Traced Next.js server files in';
console.time(initialTracingLabel);
const initialTracedFiles: {
[filePath: string]: FileFsRef;
} = {};
let initialFileList: string[];
let initialFileReasons: NodeFileTraceReasons;
let nextServerBuildTrace;
const nextServerFile = resolveFrom(
requiredServerFilesManifest.appDir || entryPath,
`${getNextServerPath(nextVersion)}/next-server.js`
);
try {
// leverage next-server trace from build if available
nextServerBuildTrace = JSON.parse(
await fs.readFile(
path.join(entryPath, outputDirectory, 'next-server.js.nft.json'),
'utf8'
)
);
} catch (_) {
// if the trace is unavailable we trace inside the runtime
}
if (nextServerBuildTrace) {
initialFileList = nextServerBuildTrace.files.map((file: string) => {
return path.relative(
baseDir,
path.join(entryPath, outputDirectory, file)
);
});
initialFileReasons = new Map();
debug('Using next-server.js.nft.json trace from build');
} else {
debug('tracing initial Next.js server files');
const result = await nodeFileTrace([nextServerFile], {
base: baseDir,
cache: {},
processCwd: entryPath,
ignore: [
...requiredServerFilesManifest.ignore.map(file =>
path.join(entryPath, file)
),
'node_modules/next/dist/pages/**/*',
`node_modules/${getNextServerPath(
nextVersion
)}/lib/squoosh/**/*.wasm`,
'node_modules/next/dist/compiled/webpack/(bundle4|bundle5).js',
'node_modules/react/**/*.development.js',
'node_modules/react-dom/**/*.development.js',
'node_modules/use-subscription/**/*.development.js',
'node_modules/sharp/**/*',
],
});
initialFileList = Array.from(result.fileList);
initialFileReasons = result.reasons;
}
debug('collecting initial Next.js server files');
await Promise.all(
initialFileList.map(
collectTracedFiles(
baseDir,
lstatResults,
lstatSema,
initialFileReasons,
initialTracedFiles
)
)
);
debug('creating initial pseudo layer');
const initialPseudoLayer = await createPseudoLayer(initialTracedFiles);
console.timeEnd(initialTracingLabel);
const lambdaCreationLabel = 'Created all serverless functions in';
console.time(lambdaCreationLabel);
const apiPages: string[] = [];
const nonApiPages: string[] = [];
const streamingPages: string[] = [];
lambdaPageKeys.forEach(page => {
if (
internalPages.includes(page) &&
page !== '404.js' &&
!(page === '_error.js' && !(static404Page || lambdaPages['404.js']))
) {
return;
}
const pathname = page.replace(/\.js$/, '');
if (nonLambdaSsgPages.has(pathname)) {
return;
}
if (isDynamicRoute(pathname)) {
dynamicPages.push(normalizePage(pathname));
}
if (pageMatchesApi(page)) {
apiPages.push(page);
} else if (appDir && lambdaAppPaths[page]) {
streamingPages.push(page);
} else {
nonApiPages.push(page);
}
});
const requiredFiles: { [key: string]: FileFsRef } = {};
requiredFiles[path.relative(baseDir, nextServerFile)] = new FileFsRef({
mode: (await fs.lstat(nextServerFile)).mode,
fsPath: nextServerFile,
});
if (static404Page) {
// ensure static 404 page file is included in all lambdas
// for notFound GS(S)P support
if (i18n) {
for (const locale of i18n.locales) {
const static404File =
staticPages[path.posix.join(entryDirectory, locale, '/404')] ||
new FileFsRef({
fsPath: path.join(pagesDir, locale, '/404.html'),
});
requiredFiles[path.relative(baseDir, static404File.fsPath)] =
static404File;
}
} else {
const static404File =
staticPages[static404Page] ||
new FileFsRef({
fsPath: path.join(pagesDir, '/404.html'),
});
requiredFiles[path.relative(baseDir, static404File.fsPath)] =
static404File;
}
}
// TODO: move this into Next.js' required server files manifest
const envFiles = [];
for (const file of await fs.readdir(workPath)) {
const isEnv = file === '.env' || file.startsWith('.env.');
if (isEnv) {
const statResult = await fs.lstat(path.join(workPath, file));
if (statResult.isFile()) {
envFiles.push(file);
}
}
}
for (const envFile of envFiles) {
requiredFiles[path.join(path.relative(baseDir, entryPath), envFile)] =
new FileFsRef({
fsPath: path.join(workPath, envFile),
});
}
await Promise.all(
requiredServerFilesManifest.files.map(async file => {
await lstatSema.acquire();
let fsPath = path.join(
entryPath,
// remove last part of outputDirectory `.next` since this is already
// included in the file path
path.join(outputDirectory, '..'),
file
);
if (requiredServerFilesManifest.appDir) {
fsPath = path.join(requiredServerFilesManifest.appDir, file);
}
const relativePath = path.relative(baseDir, fsPath);
const { mode } = await fs.lstat(fsPath);
lstatSema.release();
requiredFiles[relativePath] = new FileFsRef({
mode,
fsPath,
});
})
);
// add required files and internal pages to initial pseudo layer
// so that we account for these in the size of each page group
const requiredFilesLayer = await createPseudoLayer(requiredFiles);
Object.assign(
initialPseudoLayer.pseudoLayer,
requiredFilesLayer.pseudoLayer
);
initialPseudoLayer.pseudoLayerBytes += requiredFilesLayer.pseudoLayerBytes;
const uncompressedInitialSize = Object.keys(
initialPseudoLayer.pseudoLayer
).reduce((prev, cur) => {
const file = initialPseudoLayer.pseudoLayer[cur] as PseudoFile;
return prev + file.uncompressedSize || 0;
}, 0);
debug(
JSON.stringify(
{
uncompressedInitialSize,
compressedInitialSize: initialPseudoLayer.pseudoLayerBytes,
},
null,
2
)
);
if (
initialPseudoLayer.pseudoLayerBytes > lambdaCompressedByteLimit ||
uncompressedInitialSize > MAX_UNCOMPRESSED_LAMBDA_SIZE
) {
console.log(
`Warning: Max serverless function size of ${prettyBytes(
lambdaCompressedByteLimit
)} compressed or ${prettyBytes(
MAX_UNCOMPRESSED_LAMBDA_SIZE
)} uncompressed reached`
);
outputFunctionFileSizeInfo(
[],
initialPseudoLayer.pseudoLayer,
initialPseudoLayer.pseudoLayerBytes,
uncompressedInitialSize,
{}
);
throw new NowBuildError({
message: `Required files read using Node.js fs library and node_modules exceed max lambda size of ${lambdaCompressedByteLimit} bytes`,
code: 'NEXT_REQUIRED_FILES_LIMIT',
link: 'https://vercel.com/docs/platform/limits#serverless-function-size',
});
}
const launcherData = await fs.readFile(
path.join(__dirname, 'server-launcher.js'),
'utf8'
);
let launcher = launcherData
.replace(
'conf: __NEXT_CONFIG__',
`conf: ${JSON.stringify({
...requiredServerFilesManifest.config,
distDir: path.relative(
requiredServerFilesManifest.appDir || entryPath,
path.join(entryPath, outputDirectory)
),
compress: false,
})}`
)
.replace(
'__NEXT_SERVER_PATH__',
`${getNextServerPath(nextVersion)}/next-server.js`
);
if (
entryDirectory !== '.' &&
path.posix.join('/', entryDirectory) !== routesManifest.basePath
) {
// we normalize the entryDirectory in the request URL since
// Next.js isn't aware of it and it isn't included in the
// x-matched-path header
launcher = launcher.replace(
'// entryDirectory handler',
`req.url = req.url.replace(/^${path.posix
.join('/', entryDirectory)
.replace(/\//g, '\\/')}/, '')`
);
}
const launcherFiles: { [name: string]: FileFsRef | FileBlob } = {
[path.join(
path.relative(baseDir, requiredServerFilesManifest.appDir || entryPath),
'___next_launcher.cjs'
)]: new FileBlob({ data: launcher }),
};
const pageTraces: {
[page: string]: { [key: string]: FileFsRef };
} = {};
const compressedPages: {
[page: string]: PseudoFile;
} = {};
const mergedPageKeys = [
...nonApiPages,
...streamingPages,
...apiPages,
...internalPages,
];
const traceCache = {};
const getOriginalPagePath = (page: string) => {
let originalPagePath = page;
if (appDir && lambdaAppPaths[page]) {
const { fsPath } = lambdaAppPaths[page];
originalPagePath = path.relative(appDir, fsPath);
}
return originalPagePath;
};
const getBuildTraceFile = (page: string) => {
return (
pageBuildTraces[page + '.nft.json'] ||
appBuildTraces[page + '.nft.json']
);
};
const pathsToTrace: string[] = mergedPageKeys
.map(page => {
if (!getBuildTraceFile(page)) {
return lambdaPages[page].fsPath;
}
})
.filter(Boolean) as string[];
let traceResult: NodeFileTraceResult | undefined;
let parentFilesMap: Map<string, Set<string>> | undefined;
if (pathsToTrace.length > 0) {
traceResult = await nodeFileTrace(pathsToTrace, {
base: baseDir,
cache: traceCache,
processCwd: requiredServerFilesManifest.appDir || entryPath,
});
traceResult.esmFileList.forEach(file => traceResult?.fileList.add(file));
parentFilesMap = getFilesMapFromReasons(
traceResult.fileList,
traceResult.reasons
);
}
for (const page of mergedPageKeys) {
const tracedFiles: { [key: string]: FileFsRef } = {};
const originalPagePath = getOriginalPagePath(page);
const pageBuildTrace = getBuildTraceFile(originalPagePath);
let fileList: string[];
let reasons: NodeFileTraceReasons;
if (pageBuildTrace) {
const { files } = JSON.parse(
await fs.readFile(pageBuildTrace.fsPath, 'utf8')
);
// TODO: this will be moved to a separate worker in the future
// although currently this is needed in the lambda
const isAppPath = appDir && lambdaAppPaths[page];
const serverComponentFile = isAppPath
? pageBuildTrace.fsPath.replace(
/\.js\.nft\.json$/,
'.__sc_client__.js'
)
: null;
if (serverComponentFile && (await fs.pathExists(serverComponentFile))) {
files.push(
path.relative(
path.dirname(pageBuildTrace.fsPath),
serverComponentFile
)
);
try {
const scTrace = JSON.parse(
await fs.readFile(`${serverComponentFile}.nft.json`, 'utf8')
);
scTrace.files.forEach((file: string) => files.push(file));
} catch (err) {
/* non-fatal for now */
}
}
fileList = [];
const curPagesDir = isAppPath && appDir ? appDir : pagesDir;
const pageDir = path.dirname(path.join(curPagesDir, originalPagePath));
const normalizedBaseDir = `${baseDir}${
baseDir.endsWith(path.sep) ? '' : path.sep
}`;
files.forEach((file: string) => {
const absolutePath = path.join(pageDir, file);
// ensure we don't attempt including files outside
// of the base dir e.g. `/bin/sh`
if (absolutePath.startsWith(normalizedBaseDir)) {
fileList.push(path.relative(baseDir, absolutePath));
}
});
reasons = new Map();
} else {
fileList = Array.from(
parentFilesMap?.get(
path.relative(baseDir, lambdaPages[page].fsPath)
) || []
);
if (!fileList) {
throw new Error(
`Invariant: Failed to trace ${page}, missing fileList`
);
}
reasons = traceResult?.reasons || new Map();
}
await Promise.all(
fileList.map(
collectTracedFiles(
baseDir,
lstatResults,
lstatSema,
reasons,
tracedFiles
)
)
);
pageTraces[page] = tracedFiles;
compressedPages[page] = (
await createPseudoLayer({
[page]: lambdaPages[page],
})
).pseudoLayer[page] as PseudoFile;
}
const tracedPseudoLayer = await createPseudoLayer(
mergedPageKeys.reduce((prev, page) => {
Object.assign(prev, pageTraces[page]);
return prev;
}, {})
);
const pageExtensions = requiredServerFilesManifest.config?.pageExtensions;
const pageLambdaGroups = await getPageLambdaGroups({
entryPath: requiredServerFilesManifest.appDir || entryPath,
config,
pages: nonApiPages,
prerenderRoutes,
pageTraces,
compressedPages,
tracedPseudoLayer: tracedPseudoLayer.pseudoLayer,
initialPseudoLayer,
lambdaCompressedByteLimit,
initialPseudoLayerUncompressed: uncompressedInitialSize,
internalPages,
pageExtensions,
});
const streamingPageLambdaGroups = await getPageLambdaGroups({
entryPath: requiredServerFilesManifest.appDir || entryPath,
config,
pages: streamingPages,
prerenderRoutes,
pageTraces,
compressedPages,
tracedPseudoLayer: tracedPseudoLayer.pseudoLayer,
initialPseudoLayer,
lambdaCompressedByteLimit,
initialPseudoLayerUncompressed: uncompressedInitialSize,
internalPages,
pageExtensions,
});
for (const group of streamingPageLambdaGroups) {
if (!group.isPrerenders) {
group.isStreaming = true;
}
}
const apiLambdaGroups = await getPageLambdaGroups({
entryPath: requiredServerFilesManifest.appDir || entryPath,
config,
pages: apiPages,
prerenderRoutes,
pageTraces,
compressedPages,
tracedPseudoLayer: tracedPseudoLayer.pseudoLayer,
initialPseudoLayer,
initialPseudoLayerUncompressed: uncompressedInitialSize,
lambdaCompressedByteLimit,
internalPages,
});
debug(
JSON.stringify(
{
apiLambdaGroups: apiLambdaGroups.map(group => ({
pages: group.pages,
isPrerender: group.isPrerenders,
pseudoLayerBytes: group.pseudoLayerBytes,
uncompressedLayerBytes: group.pseudoLayerUncompressedBytes,
})),
pageLambdaGroups: pageLambdaGroups.map(group => ({
pages: group.pages,
isPrerender: group.isPrerenders,
pseudoLayerBytes: group.pseudoLayerBytes,
uncompressedLayerBytes: group.pseudoLayerUncompressedBytes,
})),
streamingPageLambdaGroups: streamingPageLambdaGroups.map(group => ({
pages: group.pages,
isPrerender: group.isPrerenders,
pseudoLayerBytes: group.pseudoLayerBytes,
uncompressedLayerBytes: group.pseudoLayerUncompressedBytes,
})),
nextServerLayerSize: initialPseudoLayer.pseudoLayerBytes,
},
null,
2
)
);
const combinedGroups = [
...pageLambdaGroups,
...streamingPageLambdaGroups,
...apiLambdaGroups,
];
await detectLambdaLimitExceeding(
combinedGroups,
lambdaCompressedByteLimit,
compressedPages
);
for (const group of combinedGroups) {
const groupPageFiles: { [key: string]: PseudoFile } = {};
for (const page of [...group.pages, ...internalPages]) {
const pageFileName = path.normalize(
path.relative(baseDir, lambdaPages[page].fsPath)
);
groupPageFiles[pageFileName] = compressedPages[page];
}
const updatedManifestFiles: { [name: string]: FileBlob } = {};
if (isCorrectManifests) {
// filter dynamic routes to only the included dynamic routes
// in this specific serverless function so that we don't
// accidentally match a dynamic route while resolving that
// is not actually in this specific serverless function
for (const manifest of [
'routes-manifest.json',
'server/pages-manifest.json',
] as const) {
const fsPath = path.join(entryPath, outputDirectory, manifest);
const relativePath = path.relative(baseDir, fsPath);
delete group.pseudoLayer[relativePath];
const manifestData = await fs.readJSON(fsPath);
const normalizedPages = new Set(
group.pages.map(page => {
page = `/${page.replace(/\.js$/, '')}`;
if (page === '/index') page = '/';
return page;
})
);
switch (manifest) {
case 'routes-manifest.json': {
const filterItem = (item: { page: string }) =>
normalizedPages.has(item.page);
manifestData.dynamicRoutes =
manifestData.dynamicRoutes?.filter(filterItem);
manifestData.staticRoutes =
manifestData.staticRoutes?.filter(filterItem);
break;
}
case 'server/pages-manifest.json': {
for (const key of Object.keys(manifestData)) {
if (isDynamicRoute(key) && !normalizedPages.has(key)) {
delete manifestData[key];
}
}
break;
}
default: {
throw new NowBuildError({
message: `Unexpected manifest value ${manifest}, please contact support if this continues`,
code: 'NEXT_MANIFEST_INVARIANT',
});
}
}
updatedManifestFiles[relativePath] = new FileBlob({
contentType: 'application/json',
data: JSON.stringify(manifestData),
});
}
}
const lambda = await createLambdaFromPseudoLayers({
files: {
...launcherFiles,
...updatedManifestFiles,
},
layers: [group.pseudoLayer, groupPageFiles],
handler: path.join(
path.relative(
baseDir,
requiredServerFilesManifest.appDir || entryPath
),
'___next_launcher.cjs'
),
memory: group.memory,
runtime: nodeVersion.runtime,
maxDuration: group.maxDuration,
isStreaming: group.isStreaming,
});
for (const page of group.pages) {
const pageNoExt = page.replace(/\.js$/, '');
let isPrerender = prerenderRoutes.has(
path.join('/', pageNoExt === 'index' ? '' : pageNoExt)
);
if (!isPrerender && routesManifest?.i18n) {
isPrerender = routesManifest.i18n.locales.some(locale => {
return prerenderRoutes.has(
path.join('/', locale, pageNoExt === 'index' ? '' : pageNoExt)
);
});
}
const outputName = normalizeIndexOutput(
path.posix.join(entryDirectory, pageNoExt),
true
);
// we add locale prefixed outputs for SSR pages,
// this is handled in onPrerenderRoute for SSG pages
if (
i18n &&
!isPrerender &&
(!isCorrectLocaleAPIRoutes ||
!(pageNoExt === 'api' || pageNoExt.startsWith('api/')))
) {
for (const locale of i18n.locales) {
lambdas[
normalizeIndexOutput(
path.posix.join(
entryDirectory,
locale,
pageNoExt === 'index' ? '' : pageNoExt
),
true
)
] = lambda;
}
} else {
lambdas[outputName] = lambda;
}
}
}
console.timeEnd(lambdaCreationLabel);
}
const prerenderRoute = onPrerenderRoute({
appDir,
pagesDir,
pageLambdaMap: {},
lambdas,
prerenders,
entryDirectory,
routesManifest,
prerenderManifest,
appPathRoutesManifest,
isServerMode: true,
isSharedLambdas: false,
canUsePreviewMode,
static404Page,
hasPages404: routesManifest.pages404,
isCorrectNotFoundRoutes,
isEmptyAllowQueryForPrendered,
});
Object.keys(prerenderManifest.staticRoutes).forEach(route =>
prerenderRoute(route, {})
);
Object.keys(prerenderManifest.fallbackRoutes).forEach(route =>
prerenderRoute(route, { isFallback: true })
);
Object.keys(prerenderManifest.blockingFallbackRoutes).forEach(route =>
prerenderRoute(route, { isBlocking: true })
);
if (static404Page && canUsePreviewMode) {
omittedPrerenderRoutes.forEach(route => {
prerenderRoute(route, { isOmitted: true });
});
}
prerenderRoutes.forEach(route => {
if (routesManifest?.i18n) {
route = normalizeLocalePath(route, routesManifest.i18n.locales).pathname;
}
delete lambdas[
path.posix.join('.', entryDirectory, route === '/' ? 'index' : route)
];
});
const middleware = await getMiddlewareBundle({
entryPath,
outputDirectory,
routesManifest,
isCorrectMiddlewareOrder,
prerenderBypassToken: prerenderManifest.bypassToken || '',
});
const isNextDataServerResolving =
middleware.staticRoutes.length > 0 &&
semver.gte(nextVersion, NEXT_DATA_MIDDLEWARE_RESOLVING_VERSION);
const dynamicRoutes = await getDynamicRoutes(
entryPath,
entryDirectory,
dynamicPages,
false,
routesManifest,
omittedPrerenderRoutes,
canUsePreviewMode,
prerenderManifest.bypassToken || '',
true,
middleware.dynamicRouteMap
).then(arr =>
localizeDynamicRoutes(
arr,
dynamicPrefix,
entryDirectory,
staticPages,
prerenderManifest,
routesManifest,
true,