/
utils.ts
843 lines (727 loc) · 20.1 KB
/
utils.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
import zlib from 'zlib';
import path from 'path';
import fs from 'fs-extra';
import semver from 'semver';
import { ZipFile } from 'yazl';
import crc32 from 'buffer-crc32';
import { Sema } from 'async-sema';
import resolveFrom from 'resolve-from';
import {
Files,
FileFsRef,
streamToBuffer,
Lambda,
isSymbolicLink,
} from '@now/build-utils';
import { Route, Source, NowHeader, NowRewrite } from '@now/routing-utils';
type stringMap = { [key: string]: string };
export interface EnvConfig {
[name: string]: string | undefined;
}
// Identify /[param]/ in route string
// eslint-disable-next-line no-useless-escape
const TEST_DYNAMIC_ROUTE = /\/\[[^\/]+?\](?=\/|$)/;
function isDynamicRoute(route: string): boolean {
route = route.startsWith('/') ? route : `/${route}`;
return TEST_DYNAMIC_ROUTE.test(route);
}
/**
* Validate if the entrypoint is allowed to be used
*/
function validateEntrypoint(entrypoint: string) {
if (
!/package\.json$/.exec(entrypoint) &&
!/next\.config\.js$/.exec(entrypoint)
) {
throw new Error(
'Specified "src" for "@now/next" has to be "package.json" or "next.config.js"'
);
}
}
/**
* Exclude certain files from the files object
*/
function excludeFiles(
files: Files,
matcher: (filePath: string) => boolean
): Files {
return Object.keys(files).reduce((newFiles, filePath) => {
if (matcher(filePath)) {
return newFiles;
}
return {
...newFiles,
[filePath]: files[filePath],
};
}, {});
}
/**
* Exclude package manager lockfiles from files
*/
function excludeLockFiles(files: Files): Files {
const newFiles = files;
if (newFiles['package-lock.json']) {
delete newFiles['package-lock.json'];
}
if (newFiles['yarn.lock']) {
delete newFiles['yarn.lock'];
}
return files;
}
/**
* Enforce specific package.json configuration for smallest possible lambda
*/
function normalizePackageJson(
defaultPackageJson: {
dependencies?: stringMap;
devDependencies?: stringMap;
scripts?: stringMap;
} = {}
) {
const dependencies: stringMap = {};
const devDependencies: stringMap = {
...defaultPackageJson.dependencies,
...defaultPackageJson.devDependencies,
};
if (devDependencies.react) {
dependencies.react = devDependencies.react;
delete devDependencies.react;
}
if (devDependencies['react-dom']) {
dependencies['react-dom'] = devDependencies['react-dom'];
delete devDependencies['react-dom'];
}
delete devDependencies['next-server'];
return {
...defaultPackageJson,
dependencies: {
// react and react-dom can be overwritten
react: 'latest',
'react-dom': 'latest',
...dependencies, // override react if user provided it
// next-server is forced to canary
'next-server': 'v7.0.2-canary.49',
},
devDependencies: {
...devDependencies,
// next is forced to canary
next: 'v7.0.2-canary.49',
},
scripts: {
...defaultPackageJson.scripts,
'now-build':
'NODE_OPTIONS=--max_old_space_size=3000 next build --lambdas',
},
};
}
async function getNextConfig(workPath: string, entryPath: string) {
const entryConfig = path.join(entryPath, './next.config.js');
if (await fs.pathExists(entryConfig)) {
return fs.readFile(entryConfig, 'utf8');
}
const workConfig = path.join(workPath, './next.config.js');
if (await fs.pathExists(workConfig)) {
return fs.readFile(workConfig, 'utf8');
}
return null;
}
function pathIsInside(firstPath: string, secondPath: string) {
return !path.relative(firstPath, secondPath).startsWith('..');
}
function getPathsInside(entryDirectory: string, files: Files) {
const watch: string[] = [];
for (const file of Object.keys(files)) {
// If the file is outside of the entrypoint directory, we do
// not want to monitor it for changes.
if (!pathIsInside(entryDirectory, file)) {
continue;
}
watch.push(file);
}
return watch;
}
function normalizePage(page: string): string {
// Resolve on anything that doesn't start with `/`
if (!page.startsWith('/')) {
page = `/${page}`;
}
// remove '/index' from the end
page = page.replace(/\/index$/, '/');
return page;
}
async function getRoutes(
entryPath: string,
entryDirectory: string,
pathsInside: string[],
files: Files,
url: string
): Promise<Route[]> {
let pagesDir = '';
const filesInside: Files = {};
const prefix = entryDirectory === `.` ? `/` : `/${entryDirectory}/`;
const fileKeys = Object.keys(files);
for (const file of fileKeys) {
if (!pathsInside.includes(file)) {
continue;
}
if (!pagesDir) {
if (file.startsWith(path.join(entryDirectory, 'pages'))) {
pagesDir = 'pages';
}
}
filesInside[file] = files[file];
}
// If default pages dir isn't found check for `src/pages`
if (
!pagesDir &&
fileKeys.some(file =>
file.startsWith(path.join(entryDirectory, 'src/pages'))
)
) {
pagesDir = 'src/pages';
}
const routes: Route[] = [
{
src: `${prefix}_next/(.*)`,
dest: `${url}/_next/$1`,
},
{
src: `${prefix}static/(.*)`,
dest: `${url}/static/$1`,
},
];
const filePaths = Object.keys(filesInside);
const dynamicPages = [];
for (const file of filePaths) {
const relativePath = path.relative(entryDirectory, file);
const isPage = pathIsInside(pagesDir, relativePath);
if (!isPage) {
continue;
}
const relativeToPages = path.relative(pagesDir, relativePath);
const extension = path.extname(relativeToPages);
const pageName = relativeToPages.replace(extension, '').replace(/\\/g, '/');
if (pageName.startsWith('_')) {
continue;
}
if (isDynamicRoute(pageName)) {
dynamicPages.push(normalizePage(pageName));
continue;
}
routes.push({
src: `${prefix}${pageName}`,
dest: `${url}/${pageName}`,
});
if (pageName.endsWith('index')) {
const resolvedIndex = pageName.replace('/index', '').replace('index', '');
routes.push({
src: `${prefix}${resolvedIndex}`,
dest: `${url}/${resolvedIndex}`,
});
}
}
routes.push(
...(await getDynamicRoutes(entryPath, entryDirectory, dynamicPages).then(
arr =>
arr.map((route: Source) => {
// convert to make entire RegExp match as one group
route.src = route.src
.replace('^', `^${prefix}(`)
.replace('(\\/', '(')
.replace('$', ')$');
route.dest = `${url}/$1`;
return route;
})
))
);
// Add public folder routes
for (const file of filePaths) {
const relativePath = path.relative(entryDirectory, file);
const isPublic = pathIsInside('public', relativePath);
if (!isPublic) continue;
const fileName = path.relative('public', relativePath);
const route: Source = {
src: `${prefix}${fileName}`,
dest: `${url}/${fileName}`,
};
// Only add the route if a page is not already using it
if (!routes.some(r => (r as Source).src === route.src)) {
routes.push(route);
}
}
return routes;
}
// TODO: update to use type from @now/routing-utils after
// adding permanent: true/false handling
export type Redirect = NowRewrite & {
statusCode?: number;
permanent?: boolean;
};
type RoutesManifestRegex = {
regex: string;
regexKeys: string[];
};
export type RoutesManifest = {
pages404: boolean;
basePath: string | undefined;
redirects: (Redirect & RoutesManifestRegex)[];
rewrites: (NowRewrite & RoutesManifestRegex)[];
headers?: (NowHeader & RoutesManifestRegex)[];
dynamicRoutes: {
page: string;
regex: string;
}[];
version: number;
dataRoutes?: Array<{ page: string; dataRouteRegex: string }>;
};
export async function getRoutesManifest(
entryPath: string,
nextVersion?: string
): Promise<RoutesManifest | undefined> {
const shouldHaveManifest =
nextVersion && semver.gte(nextVersion, '9.1.4-canary.0');
if (!shouldHaveManifest) return;
const pathRoutesManifest = path.join(
entryPath,
'.next',
'routes-manifest.json'
);
const hasRoutesManifest = await fs
.access(pathRoutesManifest)
.then(() => true)
.catch(() => false);
if (shouldHaveManifest && !hasRoutesManifest) {
throw new Error(
`A routes-manifest.json couldn't be found. This could be due to a failure during the build`
);
}
// eslint-disable-next-line @typescript-eslint/no-var-requires
const routesManifest: RoutesManifest = require(pathRoutesManifest);
return routesManifest;
}
export async function getDynamicRoutes(
entryPath: string,
entryDirectory: string,
dynamicPages: string[],
isDev?: boolean,
routesManifest?: RoutesManifest
): Promise<Source[]> {
if (!dynamicPages.length) {
return [];
}
if (routesManifest) {
switch (routesManifest.version) {
case 1:
case 2: {
return routesManifest.dynamicRoutes.map(
({ page, regex }: { page: string; regex: string }) => {
return {
src: regex,
dest: !isDev ? path.join('/', entryDirectory, page) : page,
};
}
);
}
default: {
// update MIN_ROUTES_MANIFEST_VERSION
throw new Error(
'This version of `@now/next` does not support the version of Next.js you are trying to deploy.\n' +
'Please upgrade your `@now/next` builder and try again. Contact support if this continues to happen.'
);
}
}
}
// FALLBACK:
// When `routes-manifest.json` does not exist (old Next.js versions), we'll try to
// require the methods we need from Next.js' internals.
let getRouteRegex:
| ((pageName: string) => { re: RegExp })
| undefined = undefined;
let getSortedRoutes: ((normalizedPages: string[]) => string[]) | undefined;
try {
({ getRouteRegex, getSortedRoutes } = require(resolveFrom(
entryPath,
'next-server/dist/lib/router/utils'
)));
if (typeof getRouteRegex !== 'function') {
getRouteRegex = undefined;
}
} catch (_) {} // eslint-disable-line no-empty
if (!getRouteRegex || !getSortedRoutes) {
try {
({ getRouteRegex, getSortedRoutes } = require(resolveFrom(
entryPath,
'next/dist/next-server/lib/router/utils'
)));
if (typeof getRouteRegex !== 'function') {
getRouteRegex = undefined;
}
} catch (_) {} // eslint-disable-line no-empty
}
if (!getRouteRegex || !getSortedRoutes) {
throw new Error(
'Found usage of dynamic routes but not on a new enough version of Next.js.'
);
}
const pageMatchers = getSortedRoutes(dynamicPages).map(pageName => ({
pageName,
matcher: getRouteRegex && getRouteRegex(pageName).re,
}));
const routes: Source[] = [];
pageMatchers.forEach(pageMatcher => {
// in `now dev` we don't need to prefix the destination
const dest = !isDev
? path.join('/', entryDirectory, pageMatcher.pageName)
: pageMatcher.pageName;
if (pageMatcher && pageMatcher.matcher) {
routes.push({
src: pageMatcher.matcher.source,
dest,
});
}
});
return routes;
}
function syncEnvVars(base: EnvConfig, removeEnv: EnvConfig, addEnv: EnvConfig) {
// Remove any env vars from `removeEnv`
// that are not present in the `addEnv`
const addKeys = new Set(Object.keys(addEnv));
for (const name of Object.keys(removeEnv)) {
if (!addKeys.has(name)) {
delete base[name];
}
}
// Add in the keys from `addEnv`
Object.assign(base, addEnv);
}
export const ExperimentalTraceVersion = `9.0.4-canary.1`;
export type PseudoLayer = {
[fileName: string]: PseudoFile | PseudoSymbolicLink;
};
export type PseudoFile = {
isSymlink: false;
crc32: number;
compBuffer: Buffer;
uncompressedSize: number;
mode: number;
};
export type PseudoSymbolicLink = {
isSymlink: true;
file: FileFsRef;
symlinkTarget: string;
};
const compressBuffer = (buf: Buffer): Promise<Buffer> => {
return new Promise((resolve, reject) => {
zlib.deflateRaw(
buf,
{ level: zlib.constants.Z_BEST_COMPRESSION },
(err, compBuf) => {
if (err) return reject(err);
resolve(compBuf);
}
);
});
};
export async function createPseudoLayer(files: {
[fileName: string]: FileFsRef;
}): Promise<PseudoLayer> {
const pseudoLayer: PseudoLayer = {};
for (const fileName of Object.keys(files)) {
const file = files[fileName];
if (isSymbolicLink(file.mode)) {
pseudoLayer[fileName] = {
file,
isSymlink: true,
symlinkTarget: await fs.readlink(file.fsPath),
};
} else {
const origBuffer = await streamToBuffer(file.toStream());
const compBuffer = await compressBuffer(origBuffer);
pseudoLayer[fileName] = {
compBuffer,
isSymlink: false,
crc32: crc32.unsigned(origBuffer),
uncompressedSize: origBuffer.byteLength,
mode: file.mode,
};
}
}
return pseudoLayer;
}
interface CreateLambdaFromPseudoLayersOptions {
files: Files;
layers: PseudoLayer[];
handler: string;
runtime: string;
memory?: number;
maxDuration?: number;
environment?: { [name: string]: string };
}
// measured with 1, 2, 5, 10, and `os.cpus().length || 5`
// and sema(1) produced the best results
const createLambdaSema = new Sema(1);
export async function createLambdaFromPseudoLayers({
files,
layers,
handler,
runtime,
memory,
maxDuration,
environment = {},
}: CreateLambdaFromPseudoLayersOptions) {
await createLambdaSema.acquire();
const zipFile = new ZipFile();
const addedFiles = new Set();
const names = Object.keys(files).sort();
const symlinkTargets = new Map<string, string>();
for (const name of names) {
const file = files[name];
if (file.mode && isSymbolicLink(file.mode) && file.type === 'FileFsRef') {
const symlinkTarget = await fs.readlink((file as FileFsRef).fsPath);
symlinkTargets.set(name, symlinkTarget);
}
}
// apply pseudo layers (already compressed objects)
for (const layer of layers) {
for (const seedKey of Object.keys(layer)) {
const item = layer[seedKey];
if (item.isSymlink) {
const { symlinkTarget, file } = item;
zipFile.addBuffer(Buffer.from(symlinkTarget, 'utf8'), seedKey, {
mode: file.mode,
});
continue;
}
const { compBuffer, crc32, uncompressedSize, mode } = item;
// @ts-ignore: `addDeflatedBuffer` is a valid function, but missing on the type
zipFile.addDeflatedBuffer(compBuffer, seedKey, {
crc32,
uncompressedSize,
mode: mode,
});
addedFiles.add(seedKey);
}
}
for (const fileName of Object.keys(files)) {
// was already added in a pseudo layer
if (addedFiles.has(fileName)) continue;
const file = files[fileName];
const symlinkTarget = symlinkTargets.get(fileName);
if (typeof symlinkTarget === 'string') {
zipFile.addBuffer(Buffer.from(symlinkTarget, 'utf8'), fileName, {
mode: file.mode,
});
} else {
const fileBuffer = await streamToBuffer(file.toStream());
zipFile.addBuffer(fileBuffer, fileName);
}
}
zipFile.end();
const zipBuffer = await streamToBuffer(zipFile.outputStream);
createLambdaSema.release();
return new Lambda({
handler,
runtime,
zipBuffer,
memory,
maxDuration,
environment,
});
}
export type NextPrerenderedRoutes = {
bypassToken: string | null;
routes: {
[route: string]: {
initialRevalidate: number | false;
dataRoute: string;
srcRoute: string | null;
};
};
lazyRoutes: {
[route: string]: {
fallback?: string;
routeRegex: string;
dataRoute: string;
dataRouteRegex: string;
};
};
};
export async function getExportIntent(
entryPath: string
): Promise<false | { trailingSlash: boolean }> {
const pathExportMarker = path.join(entryPath, '.next', 'export-marker.json');
const hasExportMarker: boolean = await fs
.access(pathExportMarker, fs.constants.F_OK)
.then(() => true)
.catch(() => false);
if (!hasExportMarker) {
return false;
}
const manifest: {
version: 1;
exportTrailingSlash: boolean;
hasExportPathMap: boolean;
} = JSON.parse(await fs.readFile(pathExportMarker, 'utf8'));
switch (manifest.version) {
case 1: {
if (manifest.hasExportPathMap !== true) {
return false;
}
return { trailingSlash: manifest.exportTrailingSlash };
}
default: {
return false;
}
}
}
export async function getExportStatus(
entryPath: string
): Promise<false | { success: boolean; outDirectory: string }> {
const pathExportDetail = path.join(entryPath, '.next', 'export-detail.json');
const hasExportDetail: boolean = await fs
.access(pathExportDetail, fs.constants.F_OK)
.then(() => true)
.catch(() => false);
if (!hasExportDetail) {
return false;
}
const manifest: {
version: 1;
success: boolean;
outDirectory: string;
} = JSON.parse(await fs.readFile(pathExportDetail, 'utf8'));
switch (manifest.version) {
case 1: {
return {
success: !!manifest.success,
outDirectory: manifest.outDirectory,
};
}
default: {
return false;
}
}
}
export async function getPrerenderManifest(
entryPath: string
): Promise<NextPrerenderedRoutes> {
const pathPrerenderManifest = path.join(
entryPath,
'.next',
'prerender-manifest.json'
);
const hasManifest: boolean = await fs
.access(pathPrerenderManifest, fs.constants.F_OK)
.then(() => true)
.catch(() => false);
if (!hasManifest) {
return { routes: {}, lazyRoutes: {}, bypassToken: null };
}
const manifest: {
version: 1;
routes: {
[key: string]: {
initialRevalidateSeconds: number | false;
dataRoute: string;
srcRoute: string | null;
};
};
dynamicRoutes: {
[key: string]: {
fallback?: string;
routeRegex: string;
dataRoute: string;
dataRouteRegex: string;
};
};
preview?: {
previewModeId: string;
};
} = JSON.parse(await fs.readFile(pathPrerenderManifest, 'utf8'));
switch (manifest.version) {
case 1: {
const routes = Object.keys(manifest.routes);
const lazyRoutes = Object.keys(manifest.dynamicRoutes);
const ret: NextPrerenderedRoutes = {
routes: {},
lazyRoutes: {},
bypassToken:
(manifest.preview && manifest.preview.previewModeId) || null,
};
routes.forEach(route => {
const {
initialRevalidateSeconds,
dataRoute,
srcRoute,
} = manifest.routes[route];
ret.routes[route] = {
initialRevalidate:
initialRevalidateSeconds === false
? false
: Math.max(1, initialRevalidateSeconds),
dataRoute,
srcRoute,
};
});
lazyRoutes.forEach(lazyRoute => {
const {
routeRegex,
fallback,
dataRoute,
dataRouteRegex,
} = manifest.dynamicRoutes[lazyRoute];
ret.lazyRoutes[lazyRoute] = {
routeRegex,
fallback,
dataRoute,
dataRouteRegex,
};
});
return ret;
}
default: {
return { routes: {}, lazyRoutes: {}, bypassToken: null };
}
}
}
// We only need this once per build
let _usesSrcCache: boolean | undefined;
async function usesSrcDirectory(workPath: string): Promise<boolean> {
if (!_usesSrcCache) {
const source = path.join(workPath, 'src', 'pages');
try {
if ((await fs.stat(source)).isDirectory()) {
_usesSrcCache = true;
}
} catch (_err) {
_usesSrcCache = false;
}
}
return Boolean(_usesSrcCache);
}
async function getSourceFilePathFromPage({
workPath,
page,
}: {
workPath: string;
page: string;
}) {
if (await usesSrcDirectory(workPath)) {
return path.join('src', 'pages', page);
}
return path.join('pages', page);
}
export {
excludeFiles,
validateEntrypoint,
excludeLockFiles,
normalizePackageJson,
getNextConfig,
getPathsInside,
getRoutes,
stringMap,
syncEnvVars,
normalizePage,
isDynamicRoute,
getSourceFilePathFromPage,
};