-
Notifications
You must be signed in to change notification settings - Fork 27.2k
/
next-app-loader.ts
679 lines (592 loc) · 20.3 KB
/
next-app-loader.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
import type webpack from 'webpack'
import { PAGE_SEGMENT, type ValueOf } from '../../../shared/lib/constants'
import type { ModuleReference, CollectedMetadata } from './metadata/types'
import path from 'path'
import { stringify } from 'querystring'
import chalk from 'next/dist/compiled/chalk'
import { getModuleBuildInfo } from './get-module-build-info'
import { verifyRootLayout } from '../../../lib/verifyRootLayout'
import * as Log from '../../output/log'
import { APP_DIR_ALIAS, WEBPACK_RESOURCE_QUERIES } from '../../../lib/constants'
import {
createMetadataExportsCode,
createStaticMetadataFromRoute,
} from './metadata/discover'
import { promises as fs } from 'fs'
import { isAppRouteRoute } from '../../../lib/is-app-route-route'
import { isMetadataRoute } from '../../../lib/metadata/is-metadata-route'
import { NextConfig } from '../../../server/config-shared'
import { AppPathnameNormalizer } from '../../../server/future/normalizers/built/app/app-pathname-normalizer'
import { RouteKind } from '../../../server/future/route-kind'
import { AppRouteRouteModuleOptions } from '../../../server/future/route-modules/app-route/module'
import { AppBundlePathNormalizer } from '../../../server/future/normalizers/built/app/app-bundle-path-normalizer'
import { MiddlewareConfig } from '../../analysis/get-page-static-info'
export type AppLoaderOptions = {
name: string
page: string
pagePath: string
appDir: string
appPaths: readonly string[] | null
preferredRegion: string | string[] | undefined
pageExtensions: string[]
assetPrefix: string
rootDir?: string
tsconfigPath?: string
isDev?: boolean
basePath: string
nextConfigOutput?: NextConfig['output']
middlewareConfig: string
}
type AppLoader = webpack.LoaderDefinitionFunction<AppLoaderOptions>
const FILE_TYPES = {
layout: 'layout',
template: 'template',
error: 'error',
loading: 'loading',
'not-found': 'not-found',
} as const
const GLOBAL_ERROR_FILE_TYPE = 'global-error'
const PARALLEL_CHILDREN_SEGMENT = 'children$'
type DirResolver = (pathToResolve: string) => string
type PathResolver = (
pathname: string
) => Promise<string | undefined> | string | undefined
export type MetadataResolver = (
dir: string,
filename: string,
extensions: readonly string[]
) => Promise<string | undefined>
export type ComponentsType = {
readonly [componentKey in ValueOf<typeof FILE_TYPES>]?: ModuleReference
} & {
readonly page?: ModuleReference
} & {
readonly metadata?: CollectedMetadata
} & {
readonly defaultPage?: ModuleReference
}
async function createAppRouteCode({
name,
page,
pagePath,
resolveAppRoute,
pageExtensions,
nextConfigOutput,
}: {
name: string
page: string
pagePath: string
resolveAppRoute: PathResolver
pageExtensions: string[]
nextConfigOutput: NextConfig['output']
}): Promise<string> {
// routePath is the path to the route handler file,
// but could be aliased e.g. private-next-app-dir/favicon.ico
const routePath = pagePath.replace(/[\\/]/, '/')
// This, when used with the resolver will give us the pathname to the built
// route handler file.
let resolvedPagePath = await resolveAppRoute(routePath)
if (!resolvedPagePath) {
throw new Error(
`Invariant: could not resolve page path for ${name} at ${routePath}`
)
}
// If this is a metadata route, then we need to use the metadata loader for
// the route to ensure that the route is generated.
const filename = path.parse(resolvedPagePath).name
if (isMetadataRoute(name) && filename !== 'route') {
resolvedPagePath = `next-metadata-route-loader?${stringify({
page,
pageExtensions,
})}!${resolvedPagePath + '?' + WEBPACK_RESOURCE_QUERIES.metadata}`
}
// References the route handler file to load found in `./routes/${kind}.ts`.
// TODO: allow switching to the different kinds of routes
const kind = 'app-route'
const pathname = new AppPathnameNormalizer().normalize(page)
const bundlePath = new AppBundlePathNormalizer().normalize(page)
// This is providing the options defined by the route options type found at
// ./routes/${kind}.ts. This is stringified here so that the literal for
// `userland` can reference the variable for `userland` that's in scope for
// the loader code.
const options: Omit<AppRouteRouteModuleOptions, 'userland'> = {
definition: {
kind: RouteKind.APP_ROUTE,
page,
pathname,
filename,
bundlePath,
},
resolvedPagePath,
nextConfigOutput,
}
return `
import 'next/dist/server/node-polyfill-headers'
import RouteModule from 'next/dist/server/future/route-modules/${kind}/module'
import * as userland from ${JSON.stringify(resolvedPagePath)}
const options = ${JSON.stringify(options)}
const routeModule = new RouteModule({
...options,
userland,
})
// Pull out the exports that we need to expose from the module. This should
// be eliminated when we've moved the other routes to the new format. These
// are used to hook into the route.
const {
requestAsyncStorage,
staticGenerationAsyncStorage,
serverHooks,
headerHooks,
staticGenerationBailout
} = routeModule
const originalPathname = "${page}"
export {
routeModule,
requestAsyncStorage,
staticGenerationAsyncStorage,
serverHooks,
headerHooks,
staticGenerationBailout,
originalPathname
}`
}
const normalizeParallelKey = (key: string) =>
key.startsWith('@') ? key.slice(1) : key
const isDirectory = async (pathname: string) => {
try {
const stat = await fs.stat(pathname)
return stat.isDirectory()
} catch (err) {
return false
}
}
async function createTreeCodeFromPath(
pagePath: string,
{
resolveDir,
resolver,
resolveParallelSegments,
metadataResolver,
pageExtensions,
basePath,
}: {
resolveDir: DirResolver
resolver: PathResolver
metadataResolver: MetadataResolver
resolveParallelSegments: (
pathname: string
) => [key: string, segment: string | string[]][]
loaderContext: webpack.LoaderContext<AppLoaderOptions>
pageExtensions: string[]
basePath: string
}
): Promise<{
treeCode: string
pages: string
rootLayout: string | undefined
globalError: string | undefined
}> {
const splittedPath = pagePath.split(/[\\/]/)
const appDirPrefix = splittedPath[0]
const pages: string[] = []
let rootLayout: string | undefined
let globalError: string | undefined
async function resolveAdjacentParallelSegments(
segmentPath: string
): Promise<string[]> {
const absoluteSegmentPath = await resolveDir(
`${appDirPrefix}${segmentPath}`
)
if (!absoluteSegmentPath) {
return []
}
const segmentIsDirectory = await isDirectory(absoluteSegmentPath)
if (!segmentIsDirectory) {
return []
}
// We need to resolve all parallel routes in this level.
const files = await fs.readdir(absoluteSegmentPath)
const parallelSegments: string[] = ['children']
await Promise.all(
files.map(async (file) => {
const filePath = path.join(absoluteSegmentPath, file)
const stat = await fs.stat(filePath)
if (stat.isDirectory() && file.startsWith('@')) {
parallelSegments.push(file)
}
})
)
return parallelSegments
}
async function createSubtreePropsFromSegmentPath(
segments: string[]
): Promise<{
treeCode: string
}> {
const segmentPath = segments.join('/')
// Existing tree are the children of the current segment
const props: Record<string, string> = {}
const isRootLayer = segments.length === 0
const isRootLayoutOrRootPage = segments.length <= 1
// We need to resolve all parallel routes in this level.
const parallelSegments: [key: string, segment: string | string[]][] = []
if (isRootLayer) {
parallelSegments.push(['children', ''])
} else {
parallelSegments.push(...resolveParallelSegments(segmentPath))
}
let metadata: Awaited<ReturnType<typeof createStaticMetadataFromRoute>> =
null
const routerDirPath = `${appDirPrefix}${segmentPath}`
const resolvedRouteDir = await resolveDir(routerDirPath)
if (resolvedRouteDir) {
metadata = await createStaticMetadataFromRoute(resolvedRouteDir, {
basePath,
segment: segmentPath,
metadataResolver,
isRootLayoutOrRootPage,
pageExtensions,
})
}
for (const [parallelKey, parallelSegment] of parallelSegments) {
if (parallelSegment === PAGE_SEGMENT) {
const matchedPagePath = `${appDirPrefix}${segmentPath}${
parallelKey === 'children' ? '' : `/${parallelKey}`
}/page`
const resolvedPagePath = await resolver(matchedPagePath)
if (resolvedPagePath) pages.push(resolvedPagePath)
// Use '' for segment as it's the page. There can't be a segment called '' so this is the safest way to add it.
props[normalizeParallelKey(parallelKey)] = `['__PAGE__', {}, {
page: [() => import(/* webpackMode: "eager" */ ${JSON.stringify(
resolvedPagePath
)}), ${JSON.stringify(resolvedPagePath)}],
${createMetadataExportsCode(metadata)}
}]`
continue
}
const subSegmentPath = [...segments]
if (parallelKey !== 'children') {
subSegmentPath.push(parallelKey)
}
const normalizedParallelSegments = Array.isArray(parallelSegment)
? parallelSegment.slice(0, 1)
: [parallelSegment]
subSegmentPath.push(
...normalizedParallelSegments.filter(
(segment) =>
segment !== PAGE_SEGMENT && segment !== PARALLEL_CHILDREN_SEGMENT
)
)
const { treeCode: subtreeCode } = await createSubtreePropsFromSegmentPath(
subSegmentPath
)
const parallelSegmentPath = subSegmentPath.join('/')
// `page` is not included here as it's added above.
const filePaths = await Promise.all(
Object.values(FILE_TYPES).map(async (file) => {
return [
file,
await resolver(
`${appDirPrefix}${
// TODO-APP: parallelSegmentPath sometimes ends in `/` but sometimes it doesn't. This should be consistent.
parallelSegmentPath.endsWith('/')
? parallelSegmentPath
: parallelSegmentPath + '/'
}${file}`
),
] as const
})
)
const definedFilePaths = filePaths.filter(
([, filePath]) => filePath !== undefined
)
if (!rootLayout) {
const layoutPath = definedFilePaths.find(
([type]) => type === 'layout'
)?.[1]
rootLayout = layoutPath
if (layoutPath) {
globalError = await resolver(
`${path.dirname(layoutPath)}/${GLOBAL_ERROR_FILE_TYPE}`
)
}
}
let parallelSegmentKey = Array.isArray(parallelSegment)
? parallelSegment[0]
: parallelSegment
parallelSegmentKey =
parallelSegmentKey === PARALLEL_CHILDREN_SEGMENT
? 'children'
: parallelSegmentKey
props[normalizeParallelKey(parallelKey)] = `[
'${parallelSegmentKey}',
${subtreeCode},
{
${definedFilePaths
.map(([file, filePath]) => {
return `'${file}': [() => import(/* webpackMode: "eager" */ ${JSON.stringify(
filePath
)}), ${JSON.stringify(filePath)}],`
})
.join('\n')}
${createMetadataExportsCode(metadata)}
}
]`
}
const adjacentParallelSegments = await resolveAdjacentParallelSegments(
segmentPath
)
for (const adjacentParallelSegment of adjacentParallelSegments) {
if (!props[normalizeParallelKey(adjacentParallelSegment)]) {
const actualSegment =
adjacentParallelSegment === 'children' ? '' : adjacentParallelSegment
const defaultPath =
(await resolver(
`${appDirPrefix}${segmentPath}/${actualSegment}/default`
)) ?? 'next/dist/client/components/parallel-route-default'
props[normalizeParallelKey(adjacentParallelSegment)] = `[
'__DEFAULT__',
{},
{
defaultPage: [() => import(/* webpackMode: "eager" */ ${JSON.stringify(
defaultPath
)}), ${JSON.stringify(defaultPath)}],
}
]`
}
}
return {
treeCode: `{
${Object.entries(props)
.map(([key, value]) => `${key}: ${value}`)
.join(',\n')}
}`,
}
}
const { treeCode } = await createSubtreePropsFromSegmentPath([])
return {
treeCode: `const tree = ${treeCode}.children;`,
pages: `const pages = ${JSON.stringify(pages)};`,
rootLayout,
globalError,
}
}
function createAbsolutePath(appDir: string, pathToTurnAbsolute: string) {
return (
pathToTurnAbsolute
// Replace all POSIX path separators with the current OS path separator
.replace(/\//g, path.sep)
.replace(/^private-next-app-dir/, appDir)
)
}
const nextAppLoader: AppLoader = async function nextAppLoader() {
const loaderOptions = this.getOptions()
const {
name,
appDir,
appPaths,
pagePath,
pageExtensions,
rootDir,
tsconfigPath,
isDev,
nextConfigOutput,
preferredRegion,
basePath,
middlewareConfig: middlewareConfigBase64,
} = loaderOptions
const buildInfo = getModuleBuildInfo((this as any)._module)
const page = name.replace(/^app/, '')
const middlewareConfig: MiddlewareConfig = JSON.parse(
Buffer.from(middlewareConfigBase64, 'base64').toString()
)
buildInfo.route = {
page,
absolutePagePath: createAbsolutePath(appDir, pagePath),
preferredRegion,
middlewareConfig,
}
const extensions = pageExtensions.map((extension) => `.${extension}`)
const normalizedAppPaths =
typeof appPaths === 'string' ? [appPaths] : appPaths || []
const resolveParallelSegments = (
pathname: string
): [string, string | string[]][] => {
const matched: Record<string, string | string[]> = {}
for (const appPath of normalizedAppPaths) {
if (appPath.startsWith(pathname + '/')) {
const rest = appPath.slice(pathname.length + 1).split('/')
// It is the actual page, mark it specially.
if (rest.length === 1 && rest[0] === 'page') {
matched.children = PAGE_SEGMENT
continue
}
const isParallelRoute = rest[0].startsWith('@')
if (isParallelRoute && rest.length === 2 && rest[1] === 'page') {
matched[rest[0]] = [PAGE_SEGMENT]
continue
}
if (isParallelRoute) {
// we insert a special marker in order to also process layout/etc files at the slot level
matched[rest[0]] = [PARALLEL_CHILDREN_SEGMENT, ...rest.slice(1)]
continue
}
matched.children = rest[0]
}
}
return Object.entries(matched)
}
const resolveDir: DirResolver = (pathToResolve) => {
return createAbsolutePath(appDir, pathToResolve)
}
const resolveAppRoute: PathResolver = (pathToResolve) => {
return createAbsolutePath(appDir, pathToResolve)
}
// Cached checker to see if a file exists in a given directory.
// This can be more efficient than checking them with `fs.stat` one by one
// because all the thousands of files are likely in a few possible directories.
// Note that it should only be cached for this compilation, not globally.
const filesInDir = new Map<string, Set<string>>()
const fileExistsInDirectory = async (dirname: string, fileName: string) => {
const existingFiles = filesInDir.get(dirname)
if (existingFiles) {
return existingFiles.has(fileName)
}
try {
const files = await fs.readdir(dirname, { withFileTypes: true })
const fileNames = new Set<string>()
for (const file of files) {
if (file.isFile()) {
fileNames.add(file.name)
}
}
filesInDir.set(dirname, fileNames)
return fileNames.has(fileName)
} catch (err) {
return false
}
}
const resolver: PathResolver = async (pathname) => {
const absolutePath = createAbsolutePath(appDir, pathname)
const filenameIndex = absolutePath.lastIndexOf(path.sep)
const dirname = absolutePath.slice(0, filenameIndex)
const filename = absolutePath.slice(filenameIndex + 1)
let result: string | undefined
for (const ext of extensions) {
const absolutePathWithExtension = `${absolutePath}${ext}`
if (
!result &&
(await fileExistsInDirectory(dirname, `${filename}${ext}`))
) {
result = absolutePathWithExtension
}
// Call `addMissingDependency` for all files even if they didn't match,
// because they might be added or removed during development.
this.addMissingDependency(absolutePathWithExtension)
}
return result
}
const metadataResolver: MetadataResolver = async (
dirname,
filename,
exts
) => {
const absoluteDir = createAbsolutePath(appDir, dirname)
let result: string | undefined
for (const ext of exts) {
// Compared to `resolver` above the exts do not have the `.` included already, so it's added here.
const filenameWithExt = `${filename}.${ext}`
const absolutePathWithExtension = `${absoluteDir}${path.sep}${filenameWithExt}`
if (!result && (await fileExistsInDirectory(dirname, filenameWithExt))) {
result = absolutePathWithExtension
}
// Call `addMissingDependency` for all files even if they didn't match,
// because they might be added or removed during development.
this.addMissingDependency(absolutePathWithExtension)
}
return result
}
if (isAppRouteRoute(name)) {
return createAppRouteCode({
// TODO: investigate if the local `page` is the same as the loaderOptions.page
page: loaderOptions.page,
name,
pagePath,
resolveAppRoute,
pageExtensions,
nextConfigOutput,
})
}
let treeCodeResult = await createTreeCodeFromPath(pagePath, {
resolveDir,
resolver,
metadataResolver,
resolveParallelSegments,
loaderContext: this,
pageExtensions,
basePath,
})
if (!treeCodeResult.rootLayout) {
if (!isDev) {
// If we're building and missing a root layout, exit the build
Log.error(
`${chalk.bold(
pagePath.replace(`${APP_DIR_ALIAS}/`, '')
)} doesn't have a root layout. To fix this error, make sure every page has a root layout.`
)
process.exit(1)
} else {
// In dev we'll try to create a root layout
const [createdRootLayout, rootLayoutPath] = await verifyRootLayout({
appDir: appDir,
dir: rootDir!,
tsconfigPath: tsconfigPath!,
pagePath,
pageExtensions,
})
if (!createdRootLayout) {
let message = `${chalk.bold(
pagePath.replace(`${APP_DIR_ALIAS}/`, '')
)} doesn't have a root layout. `
if (rootLayoutPath) {
message += `We tried to create ${chalk.bold(
path.relative(this._compiler?.context ?? '', rootLayoutPath)
)} for you but something went wrong.`
} else {
message +=
'To fix this error, make sure every page has a root layout.'
}
throw new Error(message)
}
// Clear fs cache, get the new result with the created root layout.
filesInDir.clear()
treeCodeResult = await createTreeCodeFromPath(pagePath, {
resolveDir,
resolver,
metadataResolver,
resolveParallelSegments,
loaderContext: this,
pageExtensions,
basePath,
})
}
}
// Prefer to modify next/src/server/app-render/entry-base.ts since this is shared with Turbopack.
// Any changes to this code should be reflected in Turbopack's app_source.rs and/or app-renderer.tsx as well.
const result = `
export ${treeCodeResult.treeCode}
export ${treeCodeResult.pages}
export { default as GlobalError } from ${JSON.stringify(
treeCodeResult.globalError || 'next/dist/client/components/error-boundary'
)}
export const originalPathname = ${JSON.stringify(page)}
export const __next_app__ = {
require: __webpack_require__,
// all modules are in the entry chunk, so we never actually need to load chunks in webpack
loadChunk: () => Promise.resolve()
}
export * from 'next/dist/server/app-render/entry-base'
`
return result
}
export default nextAppLoader