1use std::collections::BTreeMap;
2
3use anyhow::{Context, Result, bail};
4use indexmap::map::{Entry, OccupiedEntry};
5use rustc_hash::FxHashMap;
6use serde::{Deserialize, Serialize};
7use tracing::Instrument;
8use turbo_rcstr::{RcStr, rcstr};
9use turbo_tasks::{
10 FxIndexMap, FxIndexSet, NonLocalValue, ResolvedVc, TaskInput, TryJoinIterExt, ValueDefault, Vc,
11 debug::ValueDebugFormat, fxindexmap, trace::TraceRawVcs,
12};
13use turbo_tasks_fs::{DirectoryContent, DirectoryEntry, FileSystemEntryType, FileSystemPath};
14use turbopack_core::issue::{
15 Issue, IssueExt, IssueSeverity, IssueStage, OptionStyledString, StyledString,
16};
17
18use crate::{
19 mode::NextMode,
20 next_app::{
21 AppPage, AppPath, PageSegment, PageType,
22 metadata::{
23 GlobalMetadataFileMatch, MetadataFileMatch, match_global_metadata_file,
24 match_local_metadata_file, normalize_metadata_route,
25 },
26 },
27 next_import_map::get_next_package,
28};
29
30fn normalize_underscore(string: &str) -> String {
33 string.replace("%5F", "_")
34}
35
36#[turbo_tasks::value]
38#[derive(Default, Debug, Clone)]
39pub struct AppDirModules {
40 #[serde(skip_serializing_if = "Option::is_none")]
41 pub page: Option<FileSystemPath>,
42 #[serde(skip_serializing_if = "Option::is_none")]
43 pub layout: Option<FileSystemPath>,
44 #[serde(skip_serializing_if = "Option::is_none")]
45 pub error: Option<FileSystemPath>,
46 #[serde(skip_serializing_if = "Option::is_none")]
47 pub global_error: Option<FileSystemPath>,
48 #[serde(skip_serializing_if = "Option::is_none")]
49 pub global_not_found: Option<FileSystemPath>,
50 #[serde(skip_serializing_if = "Option::is_none")]
51 pub loading: Option<FileSystemPath>,
52 #[serde(skip_serializing_if = "Option::is_none")]
53 pub template: Option<FileSystemPath>,
54 #[serde(skip_serializing_if = "Option::is_none")]
55 pub forbidden: Option<FileSystemPath>,
56 #[serde(skip_serializing_if = "Option::is_none")]
57 pub unauthorized: Option<FileSystemPath>,
58 #[serde(skip_serializing_if = "Option::is_none")]
59 pub not_found: Option<FileSystemPath>,
60 #[serde(skip_serializing_if = "Option::is_none")]
61 pub default: Option<FileSystemPath>,
62 #[serde(skip_serializing_if = "Option::is_none")]
63 pub route: Option<FileSystemPath>,
64 #[serde(skip_serializing_if = "Metadata::is_empty", default)]
65 pub metadata: Metadata,
66}
67
68impl AppDirModules {
69 fn without_leaves(&self) -> Self {
70 Self {
71 page: None,
72 layout: self.layout.clone(),
73 error: self.error.clone(),
74 global_error: self.global_error.clone(),
75 global_not_found: self.global_not_found.clone(),
76 loading: self.loading.clone(),
77 template: self.template.clone(),
78 not_found: self.not_found.clone(),
79 forbidden: self.forbidden.clone(),
80 unauthorized: self.unauthorized.clone(),
81 default: None,
82 route: None,
83 metadata: self.metadata.clone(),
84 }
85 }
86}
87
88#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, TraceRawVcs, NonLocalValue)]
90pub enum MetadataWithAltItem {
91 Static {
92 path: FileSystemPath,
93 alt_path: Option<FileSystemPath>,
94 },
95 Dynamic {
96 path: FileSystemPath,
97 },
98}
99
100#[derive(
102 Clone, Debug, Hash, Serialize, Deserialize, PartialEq, Eq, TaskInput, TraceRawVcs, NonLocalValue,
103)]
104pub enum MetadataItem {
105 Static { path: FileSystemPath },
106 Dynamic { path: FileSystemPath },
107}
108
109#[turbo_tasks::function]
110pub async fn get_metadata_route_name(meta: MetadataItem) -> Result<Vc<RcStr>> {
111 Ok(match meta {
112 MetadataItem::Static { path } => Vc::cell(path.file_name().into()),
113 MetadataItem::Dynamic { path } => {
114 let Some(stem) = path.file_stem() else {
115 bail!(
116 "unable to resolve file stem for metadata item at {}",
117 path.value_to_string().await?
118 );
119 };
120
121 match stem {
122 "manifest" => Vc::cell(rcstr!("manifest.webmanifest")),
123 _ => Vc::cell(RcStr::from(stem)),
124 }
125 }
126 })
127}
128
129impl MetadataItem {
130 pub fn into_path(self) -> FileSystemPath {
131 match self {
132 MetadataItem::Static { path } => path,
133 MetadataItem::Dynamic { path } => path,
134 }
135 }
136}
137
138impl From<MetadataWithAltItem> for MetadataItem {
139 fn from(value: MetadataWithAltItem) -> Self {
140 match value {
141 MetadataWithAltItem::Static { path, .. } => MetadataItem::Static { path },
142 MetadataWithAltItem::Dynamic { path } => MetadataItem::Dynamic { path },
143 }
144 }
145}
146
147#[derive(
149 Default, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, TraceRawVcs, NonLocalValue,
150)]
151pub struct Metadata {
152 #[serde(skip_serializing_if = "Vec::is_empty", default)]
153 pub icon: Vec<MetadataWithAltItem>,
154 #[serde(skip_serializing_if = "Vec::is_empty", default)]
155 pub apple: Vec<MetadataWithAltItem>,
156 #[serde(skip_serializing_if = "Vec::is_empty", default)]
157 pub twitter: Vec<MetadataWithAltItem>,
158 #[serde(skip_serializing_if = "Vec::is_empty", default)]
159 pub open_graph: Vec<MetadataWithAltItem>,
160 #[serde(skip_serializing_if = "Option::is_none")]
161 pub sitemap: Option<MetadataItem>,
162 #[serde(skip_serializing_if = "Option::is_none")]
170 pub base_page: Option<AppPage>,
171}
172
173impl Metadata {
174 pub fn is_empty(&self) -> bool {
175 let Metadata {
176 icon,
177 apple,
178 twitter,
179 open_graph,
180 sitemap,
181 base_page: _,
182 } = self;
183 icon.is_empty()
184 && apple.is_empty()
185 && twitter.is_empty()
186 && open_graph.is_empty()
187 && sitemap.is_none()
188 }
189}
190
191#[turbo_tasks::value]
193#[derive(Default, Clone, Debug)]
194pub struct GlobalMetadata {
195 #[serde(skip_serializing_if = "Option::is_none")]
196 pub favicon: Option<MetadataItem>,
197 #[serde(skip_serializing_if = "Option::is_none")]
198 pub robots: Option<MetadataItem>,
199 #[serde(skip_serializing_if = "Option::is_none")]
200 pub manifest: Option<MetadataItem>,
201}
202
203impl GlobalMetadata {
204 pub fn is_empty(&self) -> bool {
205 let GlobalMetadata {
206 favicon,
207 robots,
208 manifest,
209 } = self;
210 favicon.is_none() && robots.is_none() && manifest.is_none()
211 }
212}
213
214#[turbo_tasks::value]
215#[derive(Debug)]
216pub struct DirectoryTree {
217 pub subdirectories: BTreeMap<RcStr, ResolvedVc<DirectoryTree>>,
219 pub modules: AppDirModules,
220}
221
222#[turbo_tasks::value]
223#[derive(Clone, Debug)]
224struct PlainDirectoryTree {
225 pub subdirectories: BTreeMap<RcStr, PlainDirectoryTree>,
227 pub modules: AppDirModules,
228}
229
230#[turbo_tasks::value_impl]
231impl DirectoryTree {
232 #[turbo_tasks::function]
233 pub async fn into_plain(&self) -> Result<Vc<PlainDirectoryTree>> {
234 let mut subdirectories = BTreeMap::new();
235
236 for (name, subdirectory) in &self.subdirectories {
237 subdirectories.insert(name.clone(), subdirectory.into_plain().owned().await?);
238 }
239
240 Ok(PlainDirectoryTree {
241 subdirectories,
242 modules: self.modules.clone(),
243 }
244 .cell())
245 }
246}
247
248#[turbo_tasks::value(transparent)]
249pub struct OptionAppDir(Option<FileSystemPath>);
250
251#[turbo_tasks::function]
253pub async fn find_app_dir(project_path: FileSystemPath) -> Result<Vc<OptionAppDir>> {
254 let app = project_path.join("app")?;
255 let src_app = project_path.join("src/app")?;
256 let app_dir = if *app.get_type().await? == FileSystemEntryType::Directory {
257 app
258 } else if *src_app.get_type().await? == FileSystemEntryType::Directory {
259 src_app
260 } else {
261 return Ok(Vc::cell(None));
262 };
263
264 Ok(Vc::cell(Some(app_dir)))
265}
266
267#[turbo_tasks::function]
268async fn get_directory_tree(
269 dir: FileSystemPath,
270 page_extensions: Vc<Vec<RcStr>>,
271) -> Result<Vc<DirectoryTree>> {
272 let span = tracing::info_span!(
273 "read app directory tree",
274 name = display(dir.value_to_string().await?)
275 );
276 get_directory_tree_internal(dir, page_extensions)
277 .instrument(span)
278 .await
279}
280
281async fn get_directory_tree_internal(
282 dir: FileSystemPath,
283 page_extensions: Vc<Vec<RcStr>>,
284) -> Result<Vc<DirectoryTree>> {
285 let DirectoryContent::Entries(entries) = &*dir.read_dir().await? else {
286 return Ok(DirectoryTree {
290 subdirectories: Default::default(),
291 modules: AppDirModules::default(),
292 }
293 .cell());
294 };
295 let page_extensions_value = page_extensions.await?;
296
297 let mut subdirectories = BTreeMap::new();
298 let mut modules = AppDirModules::default();
299
300 let mut metadata_icon = Vec::new();
301 let mut metadata_apple = Vec::new();
302 let mut metadata_open_graph = Vec::new();
303 let mut metadata_twitter = Vec::new();
304
305 for (basename, entry) in entries {
306 let entry = entry.clone().resolve_symlink().await?;
307 match entry {
308 DirectoryEntry::File(file) => {
309 if basename.ends_with(".d.ts") {
311 continue;
312 }
313 if let Some((stem, ext)) = basename.split_once('.')
314 && page_extensions_value.iter().any(|e| e == ext)
315 {
316 match stem {
317 "page" => modules.page = Some(file.clone()),
318 "layout" => modules.layout = Some(file.clone()),
319 "error" => modules.error = Some(file.clone()),
320 "global-error" => modules.global_error = Some(file.clone()),
321 "global-not-found" => modules.global_not_found = Some(file.clone()),
322 "loading" => modules.loading = Some(file.clone()),
323 "template" => modules.template = Some(file.clone()),
324 "forbidden" => modules.forbidden = Some(file.clone()),
325 "unauthorized" => modules.unauthorized = Some(file.clone()),
326 "not-found" => modules.not_found = Some(file.clone()),
327 "default" => modules.default = Some(file.clone()),
328 "route" => modules.route = Some(file.clone()),
329 _ => {}
330 }
331 }
332
333 let Some(MetadataFileMatch {
334 metadata_type,
335 number,
336 dynamic,
337 }) = match_local_metadata_file(basename.as_str(), &page_extensions_value)
338 else {
339 continue;
340 };
341
342 let entry = match metadata_type {
343 "icon" => &mut metadata_icon,
344 "apple-icon" => &mut metadata_apple,
345 "twitter-image" => &mut metadata_twitter,
346 "opengraph-image" => &mut metadata_open_graph,
347 "sitemap" => {
348 if dynamic {
349 modules.metadata.sitemap = Some(MetadataItem::Dynamic { path: file });
350 } else {
351 modules.metadata.sitemap = Some(MetadataItem::Static { path: file });
352 }
353 continue;
354 }
355 _ => continue,
356 };
357
358 if dynamic {
359 entry.push((number, MetadataWithAltItem::Dynamic { path: file }));
360 continue;
361 }
362
363 let file_name = file.file_name();
364 let basename = file_name
365 .rsplit_once('.')
366 .map_or(file_name, |(basename, _)| basename);
367 let alt_path = file.parent().join(&format!("{basename}.alt.txt"))?;
368 let alt_path = matches!(&*alt_path.get_type().await?, FileSystemEntryType::File)
369 .then_some(alt_path);
370
371 entry.push((
372 number,
373 MetadataWithAltItem::Static {
374 path: file,
375 alt_path,
376 },
377 ));
378 }
379 DirectoryEntry::Directory(dir) => {
380 if !basename.starts_with('_') {
382 let result = get_directory_tree(dir.clone(), page_extensions)
383 .to_resolved()
384 .await?;
385 subdirectories.insert(basename.clone(), result);
386 }
387 }
388 _ => {}
390 }
391 }
392
393 fn sort<T>(mut list: Vec<(Option<u32>, T)>) -> Vec<T> {
394 list.sort_by_key(|(num, _)| *num);
395 list.into_iter().map(|(_, item)| item).collect()
396 }
397
398 modules.metadata.icon = sort(metadata_icon);
399 modules.metadata.apple = sort(metadata_apple);
400 modules.metadata.twitter = sort(metadata_twitter);
401 modules.metadata.open_graph = sort(metadata_open_graph);
402
403 Ok(DirectoryTree {
404 subdirectories,
405 modules,
406 }
407 .cell())
408}
409
410#[turbo_tasks::value]
411#[derive(Debug, Clone)]
412pub struct AppPageLoaderTree {
413 pub page: AppPage,
414 pub segment: RcStr,
415 pub parallel_routes: FxIndexMap<RcStr, AppPageLoaderTree>,
416 pub modules: AppDirModules,
417 pub global_metadata: ResolvedVc<GlobalMetadata>,
418}
419
420impl AppPageLoaderTree {
421 pub fn has_page(&self) -> bool {
423 if &*self.segment == "__PAGE__" {
424 return true;
425 }
426
427 for (_, tree) in &self.parallel_routes {
428 if tree.has_page() {
429 return true;
430 }
431 }
432
433 false
434 }
435
436 pub fn has_only_catchall(&self) -> bool {
439 if &*self.segment == "__PAGE__" && !self.page.is_catchall() {
440 return false;
441 }
442
443 for (_, tree) in &self.parallel_routes {
444 if !tree.has_only_catchall() {
445 return false;
446 }
447 }
448
449 true
450 }
451
452 pub fn is_intercepting(&self) -> bool {
454 if self.page.is_intercepting() && self.has_page() {
455 return true;
456 }
457
458 for (_, tree) in &self.parallel_routes {
459 if tree.is_intercepting() {
460 return true;
461 }
462 }
463
464 false
465 }
466
467 pub fn get_specificity(&self) -> usize {
470 if &*self.segment == "__PAGE__" {
471 return AppPath::from(self.page.clone()).len();
472 }
473
474 let mut specificity = 0;
475
476 for (_, tree) in &self.parallel_routes {
477 specificity = specificity.max(tree.get_specificity());
478 }
479
480 specificity
481 }
482}
483
484#[turbo_tasks::value(transparent)]
485#[derive(Default)]
486pub struct RootParamVecOption(Option<Vec<RcStr>>);
487
488#[turbo_tasks::value_impl]
489impl ValueDefault for RootParamVecOption {
490 #[turbo_tasks::function]
491 fn value_default() -> Vc<Self> {
492 Vc::cell(Default::default())
493 }
494}
495
496#[turbo_tasks::value(transparent)]
497pub struct FileSystemPathVec(Vec<FileSystemPath>);
498
499#[turbo_tasks::value_impl]
500impl ValueDefault for FileSystemPathVec {
501 #[turbo_tasks::function]
502 fn value_default() -> Vc<Self> {
503 Vc::cell(Vec::new())
504 }
505}
506
507#[derive(
508 Clone,
509 PartialEq,
510 Eq,
511 Hash,
512 Serialize,
513 Deserialize,
514 TraceRawVcs,
515 ValueDebugFormat,
516 Debug,
517 TaskInput,
518 NonLocalValue,
519)]
520pub enum Entrypoint {
521 AppPage {
522 pages: Vec<AppPage>,
523 loader_tree: ResolvedVc<AppPageLoaderTree>,
524 root_params: ResolvedVc<RootParamVecOption>,
525 },
526 AppRoute {
527 page: AppPage,
528 path: FileSystemPath,
529 root_layouts: ResolvedVc<FileSystemPathVec>,
530 root_params: ResolvedVc<RootParamVecOption>,
531 },
532 AppMetadata {
533 page: AppPage,
534 metadata: MetadataItem,
535 root_params: ResolvedVc<RootParamVecOption>,
536 },
537}
538
539impl Entrypoint {
540 pub fn page(&self) -> &AppPage {
541 match self {
542 Entrypoint::AppPage { pages, .. } => pages.first().unwrap(),
543 Entrypoint::AppRoute { page, .. } => page,
544 Entrypoint::AppMetadata { page, .. } => page,
545 }
546 }
547 pub fn root_params(&self) -> ResolvedVc<RootParamVecOption> {
548 match self {
549 Entrypoint::AppPage { root_params, .. } => *root_params,
550 Entrypoint::AppRoute { root_params, .. } => *root_params,
551 Entrypoint::AppMetadata { root_params, .. } => *root_params,
552 }
553 }
554}
555
556#[turbo_tasks::value(transparent)]
557pub struct Entrypoints(FxIndexMap<AppPath, Entrypoint>);
558
559fn is_parallel_route(name: &str) -> bool {
560 name.starts_with('@')
561}
562
563fn is_group_route(name: &str) -> bool {
564 name.starts_with('(') && name.ends_with(')')
565}
566
567fn match_parallel_route(name: &str) -> Option<&str> {
568 name.strip_prefix('@')
569}
570
571fn conflict_issue(
572 app_dir: FileSystemPath,
573 e: &'_ OccupiedEntry<'_, AppPath, Entrypoint>,
574 a: &str,
575 b: &str,
576 value_a: &AppPage,
577 value_b: &AppPage,
578) {
579 let item_names = if a == b {
580 format!("{a}s")
581 } else {
582 format!("{a} and {b}")
583 };
584
585 DirectoryTreeIssue {
586 app_dir,
587 message: StyledString::Text(
588 format!(
589 "Conflicting {} at {}: {a} at {value_a} and {b} at {value_b}",
590 item_names,
591 e.key(),
592 )
593 .into(),
594 )
595 .resolved_cell(),
596 severity: IssueSeverity::Error,
597 }
598 .resolved_cell()
599 .emit();
600}
601
602fn add_app_page(
603 app_dir: FileSystemPath,
604 result: &mut FxIndexMap<AppPath, Entrypoint>,
605 page: AppPage,
606 loader_tree: ResolvedVc<AppPageLoaderTree>,
607 root_params: ResolvedVc<RootParamVecOption>,
608) {
609 let mut e = match result.entry(page.clone().into()) {
610 Entry::Occupied(e) => e,
611 Entry::Vacant(e) => {
612 e.insert(Entrypoint::AppPage {
613 pages: vec![page],
614 loader_tree,
615 root_params,
616 });
617 return;
618 }
619 };
620
621 let conflict = |existing_name: &str, existing_page: &AppPage| {
622 conflict_issue(app_dir, &e, "page", existing_name, &page, existing_page);
623 };
624
625 let value = e.get();
626 match value {
627 Entrypoint::AppPage {
628 pages: existing_pages,
629 loader_tree: existing_loader_tree,
630 ..
631 } => {
632 if *existing_loader_tree != loader_tree {
635 conflict("page", existing_pages.first().unwrap());
636 }
637
638 let Entrypoint::AppPage {
639 pages: stored_pages,
640 ..
641 } = e.get_mut()
642 else {
643 unreachable!("Entrypoint::AppPage was already matched");
644 };
645
646 stored_pages.push(page);
647 stored_pages.sort();
648 }
649 Entrypoint::AppRoute {
650 page: existing_page,
651 ..
652 } => {
653 conflict("route", existing_page);
654 }
655 Entrypoint::AppMetadata {
656 page: existing_page,
657 ..
658 } => {
659 conflict("metadata", existing_page);
660 }
661 }
662}
663
664fn add_app_route(
665 app_dir: FileSystemPath,
666 result: &mut FxIndexMap<AppPath, Entrypoint>,
667 page: AppPage,
668 path: FileSystemPath,
669 root_layouts: ResolvedVc<FileSystemPathVec>,
670 root_params: ResolvedVc<RootParamVecOption>,
671) {
672 let e = match result.entry(page.clone().into()) {
673 Entry::Occupied(e) => e,
674 Entry::Vacant(e) => {
675 e.insert(Entrypoint::AppRoute {
676 page,
677 path,
678 root_layouts,
679 root_params,
680 });
681 return;
682 }
683 };
684
685 let conflict = |existing_name: &str, existing_page: &AppPage| {
686 conflict_issue(app_dir, &e, "route", existing_name, &page, existing_page);
687 };
688
689 let value = e.get();
690 match value {
691 Entrypoint::AppPage { pages, .. } => {
692 conflict("page", pages.first().unwrap());
693 }
694 Entrypoint::AppRoute {
695 page: existing_page,
696 ..
697 } => {
698 conflict("route", existing_page);
699 }
700 Entrypoint::AppMetadata {
701 page: existing_page,
702 ..
703 } => {
704 conflict("metadata", existing_page);
705 }
706 }
707}
708
709fn add_app_metadata_route(
710 app_dir: FileSystemPath,
711 result: &mut FxIndexMap<AppPath, Entrypoint>,
712 page: AppPage,
713 metadata: MetadataItem,
714 root_params: ResolvedVc<RootParamVecOption>,
715) {
716 let e = match result.entry(page.clone().into()) {
717 Entry::Occupied(e) => e,
718 Entry::Vacant(e) => {
719 e.insert(Entrypoint::AppMetadata {
720 page,
721 metadata,
722 root_params,
723 });
724 return;
725 }
726 };
727
728 let conflict = |existing_name: &str, existing_page: &AppPage| {
729 conflict_issue(app_dir, &e, "metadata", existing_name, &page, existing_page);
730 };
731
732 let value = e.get();
733 match value {
734 Entrypoint::AppPage { pages, .. } => {
735 conflict("page", pages.first().unwrap());
736 }
737 Entrypoint::AppRoute {
738 page: existing_page,
739 ..
740 } => {
741 conflict("route", existing_page);
742 }
743 Entrypoint::AppMetadata {
744 page: existing_page,
745 ..
746 } => {
747 conflict("metadata", existing_page);
748 }
749 }
750}
751
752#[turbo_tasks::function]
753pub fn get_entrypoints(
754 app_dir: FileSystemPath,
755 page_extensions: Vc<Vec<RcStr>>,
756 is_global_not_found_enabled: Vc<bool>,
757 next_mode: Vc<NextMode>,
758) -> Vc<Entrypoints> {
759 directory_tree_to_entrypoints(
760 app_dir.clone(),
761 get_directory_tree(app_dir.clone(), page_extensions),
762 get_global_metadata(app_dir, page_extensions),
763 is_global_not_found_enabled,
764 next_mode,
765 Default::default(),
766 Default::default(),
767 )
768}
769
770#[turbo_tasks::value(transparent)]
771pub struct CollectedRootParams(FxIndexSet<RcStr>);
772
773#[turbo_tasks::function]
774pub async fn collect_root_params(
775 entrypoints: ResolvedVc<Entrypoints>,
776) -> Result<Vc<CollectedRootParams>> {
777 let mut collected_root_params = FxIndexSet::<RcStr>::default();
778 for (_, entrypoint) in entrypoints.await?.iter() {
779 if let Some(ref root_params) = *entrypoint.root_params().await? {
780 collected_root_params.extend(root_params.iter().cloned());
781 }
782 }
783 Ok(Vc::cell(collected_root_params))
784}
785
786#[turbo_tasks::function]
787fn directory_tree_to_entrypoints(
788 app_dir: FileSystemPath,
789 directory_tree: Vc<DirectoryTree>,
790 global_metadata: Vc<GlobalMetadata>,
791 is_global_not_found_enabled: Vc<bool>,
792 next_mode: Vc<NextMode>,
793 root_layouts: Vc<FileSystemPathVec>,
794 root_params: Vc<RootParamVecOption>,
795) -> Vc<Entrypoints> {
796 directory_tree_to_entrypoints_internal(
797 app_dir,
798 global_metadata,
799 is_global_not_found_enabled,
800 next_mode,
801 rcstr!(""),
802 directory_tree,
803 AppPage::new(),
804 root_layouts,
805 root_params,
806 )
807}
808
809#[turbo_tasks::value]
810struct DuplicateParallelRouteIssue {
811 app_dir: FileSystemPath,
812 previously_inserted_page: AppPage,
813 page: AppPage,
814}
815
816#[turbo_tasks::value_impl]
817impl Issue for DuplicateParallelRouteIssue {
818 #[turbo_tasks::function]
819 fn file_path(&self) -> Result<Vc<FileSystemPath>> {
820 Ok(self.app_dir.join(&self.page.to_string())?.cell())
821 }
822
823 #[turbo_tasks::function]
824 fn stage(self: Vc<Self>) -> Vc<IssueStage> {
825 IssueStage::ProcessModule.cell()
826 }
827
828 #[turbo_tasks::function]
829 async fn title(self: Vc<Self>) -> Result<Vc<StyledString>> {
830 let this = self.await?;
831 Ok(StyledString::Text(
832 format!(
833 "You cannot have two parallel pages that resolve to the same path. Please check \
834 {} and {}.",
835 this.previously_inserted_page, this.page
836 )
837 .into(),
838 )
839 .cell())
840 }
841}
842
843#[turbo_tasks::value]
844struct MissingDefaultParallelRouteIssue {
845 app_dir: FileSystemPath,
846 app_page: AppPage,
847 slot_name: RcStr,
848}
849
850#[turbo_tasks::function]
851fn missing_default_parallel_route_issue(
852 app_dir: FileSystemPath,
853 app_page: AppPage,
854 slot_name: RcStr,
855) -> Vc<MissingDefaultParallelRouteIssue> {
856 MissingDefaultParallelRouteIssue {
857 app_dir,
858 app_page,
859 slot_name,
860 }
861 .cell()
862}
863
864#[turbo_tasks::value_impl]
865impl Issue for MissingDefaultParallelRouteIssue {
866 #[turbo_tasks::function]
867 fn file_path(&self) -> Result<Vc<FileSystemPath>> {
868 Ok(self
869 .app_dir
870 .join(&self.app_page.to_string())?
871 .join(&format!("@{}", self.slot_name))?
872 .cell())
873 }
874
875 #[turbo_tasks::function]
876 fn stage(self: Vc<Self>) -> Vc<IssueStage> {
877 IssueStage::AppStructure.cell()
878 }
879
880 fn severity(&self) -> IssueSeverity {
881 IssueSeverity::Error
882 }
883
884 #[turbo_tasks::function]
885 async fn title(&self) -> Vc<StyledString> {
886 StyledString::Text(
887 format!(
888 "Missing required default.js file for parallel route at {}/@{}",
889 self.app_page, self.slot_name
890 )
891 .into(),
892 )
893 .cell()
894 }
895
896 #[turbo_tasks::function]
897 async fn description(&self) -> Vc<OptionStyledString> {
898 Vc::cell(Some(
899 StyledString::Stack(vec![
900 StyledString::Text(
901 format!(
902 "The parallel route slot \"@{}\" is missing a default.js file. When using \
903 parallel routes, each slot must have a default.js file to serve as a \
904 fallback.",
905 self.slot_name
906 )
907 .into(),
908 ),
909 StyledString::Text(
910 format!(
911 "Create a default.js file at: {}/@{}/default.js",
912 self.app_page, self.slot_name
913 )
914 .into(),
915 ),
916 ])
917 .resolved_cell(),
918 ))
919 }
920
921 #[turbo_tasks::function]
922 fn documentation_link(&self) -> Vc<RcStr> {
923 Vc::cell(rcstr!(
924 "https://nextjs.org/docs/messages/slot-missing-default"
925 ))
926 }
927}
928
929fn page_path_except_parallel(loader_tree: &AppPageLoaderTree) -> Option<AppPage> {
930 if loader_tree.page.iter().any(|v| {
931 matches!(
932 v,
933 PageSegment::CatchAll(..)
934 | PageSegment::OptionalCatchAll(..)
935 | PageSegment::Parallel(..)
936 )
937 }) {
938 return None;
939 }
940
941 if loader_tree.modules.page.is_some() {
942 return Some(loader_tree.page.clone());
943 }
944
945 if let Some(children) = loader_tree.parallel_routes.get("children") {
946 return page_path_except_parallel(children);
947 }
948
949 None
950}
951
952fn has_child_routes(directory_tree: &PlainDirectoryTree) -> bool {
956 for (name, subdirectory) in &directory_tree.subdirectories {
957 if is_parallel_route(name) {
959 continue;
960 }
961
962 if is_group_route(name) {
964 if has_child_routes(subdirectory) {
966 return true;
967 }
968 continue;
969 }
970
971 return true;
973 }
974
975 false
976}
977
978async fn check_duplicate(
979 duplicate: &mut FxHashMap<AppPath, AppPage>,
980 loader_tree: &AppPageLoaderTree,
981 app_dir: FileSystemPath,
982) -> Result<()> {
983 let page_path = page_path_except_parallel(loader_tree);
984
985 if let Some(page_path) = page_path
986 && let Some(prev) = duplicate.insert(AppPath::from(page_path.clone()), page_path.clone())
987 && prev != page_path
988 {
989 DuplicateParallelRouteIssue {
990 app_dir: app_dir.clone(),
991 previously_inserted_page: prev.clone(),
992 page: loader_tree.page.clone(),
993 }
994 .resolved_cell()
995 .emit();
996 }
997
998 Ok(())
999}
1000
1001#[turbo_tasks::value(transparent)]
1002struct AppPageLoaderTreeOption(Option<ResolvedVc<AppPageLoaderTree>>);
1003
1004#[turbo_tasks::function]
1006async fn directory_tree_to_loader_tree(
1007 app_dir: FileSystemPath,
1008 global_metadata: Vc<GlobalMetadata>,
1009 directory_name: RcStr,
1010 directory_tree: Vc<DirectoryTree>,
1011 app_page: AppPage,
1012 for_app_path: AppPath,
1014) -> Result<Vc<AppPageLoaderTreeOption>> {
1015 let plain_tree = &*directory_tree.into_plain().await?;
1016
1017 let tree = directory_tree_to_loader_tree_internal(
1018 app_dir,
1019 global_metadata,
1020 directory_name,
1021 plain_tree,
1022 app_page,
1023 for_app_path,
1024 AppDirModules::default(),
1025 )
1026 .await?;
1027
1028 Ok(Vc::cell(tree.map(AppPageLoaderTree::resolved_cell)))
1029}
1030
1031async fn check_and_update_module_references(
1046 app_dir: FileSystemPath,
1047 module: &mut Option<FileSystemPath>,
1048 parent_module: &mut Option<FileSystemPath>,
1049 file_path: &str,
1050 is_first_layer_group_route: bool,
1051) -> Result<()> {
1052 match (module.as_mut(), parent_module.as_mut()) {
1053 (Some(module), _) => *parent_module = Some(module.clone()),
1055 (None, Some(parent_module)) if is_first_layer_group_route => {
1058 *module = Some(parent_module.clone())
1059 }
1060 (None, Some(_)) => {}
1063 (None, None) => {
1067 let default_page = get_next_package(app_dir).await?.join(file_path)?;
1068 *module = Some(default_page.clone());
1069 *parent_module = Some(default_page);
1070 }
1071 }
1072
1073 Ok(())
1074}
1075
1076async fn check_and_update_global_module_references(
1084 app_dir: FileSystemPath,
1085 module: &mut Option<FileSystemPath>,
1086 file_path: &str,
1087) -> Result<()> {
1088 if module.is_none() {
1089 *module = Some(get_next_package(app_dir).await?.join(file_path)?);
1090 }
1091
1092 Ok(())
1093}
1094
1095async fn directory_tree_to_loader_tree_internal(
1096 app_dir: FileSystemPath,
1097 global_metadata: Vc<GlobalMetadata>,
1098 directory_name: RcStr,
1099 directory_tree: &PlainDirectoryTree,
1100 app_page: AppPage,
1101 for_app_path: AppPath,
1103 mut parent_modules: AppDirModules,
1104) -> Result<Option<AppPageLoaderTree>> {
1105 let app_path = AppPath::from(app_page.clone());
1106
1107 if !for_app_path.contains(&app_path) {
1108 return Ok(None);
1109 }
1110
1111 let mut modules = directory_tree.modules.clone();
1112
1113 modules.metadata.base_page = Some(app_page.clone());
1116
1117 let is_root_directory = app_page.is_root();
1119
1120 let is_first_layer_group_route = app_page.is_first_layer_group_route();
1122
1123 if is_root_directory || is_first_layer_group_route {
1126 check_and_update_module_references(
1127 app_dir.clone(),
1128 &mut modules.not_found,
1129 &mut parent_modules.not_found,
1130 "dist/client/components/builtin/not-found.js",
1131 is_first_layer_group_route,
1132 )
1133 .await?;
1134
1135 check_and_update_module_references(
1136 app_dir.clone(),
1137 &mut modules.forbidden,
1138 &mut parent_modules.forbidden,
1139 "dist/client/components/builtin/forbidden.js",
1140 is_first_layer_group_route,
1141 )
1142 .await?;
1143
1144 check_and_update_module_references(
1145 app_dir.clone(),
1146 &mut modules.unauthorized,
1147 &mut parent_modules.unauthorized,
1148 "dist/client/components/builtin/unauthorized.js",
1149 is_first_layer_group_route,
1150 )
1151 .await?;
1152 }
1153
1154 if is_root_directory {
1155 check_and_update_global_module_references(
1156 app_dir.clone(),
1157 &mut modules.global_error,
1158 "dist/client/components/builtin/global-error.js",
1159 )
1160 .await?;
1161 }
1162
1163 let mut tree = AppPageLoaderTree {
1164 page: app_page.clone(),
1165 segment: directory_name.clone(),
1166 parallel_routes: FxIndexMap::default(),
1167 modules: modules.without_leaves(),
1168 global_metadata: global_metadata.to_resolved().await?,
1169 };
1170
1171 let current_level_is_parallel_route = is_parallel_route(&directory_name);
1172
1173 if current_level_is_parallel_route {
1174 tree.segment = rcstr!("(slot)");
1175 }
1176
1177 if let Some(page) = (app_path == for_app_path || app_path.is_catchall())
1178 .then_some(modules.page)
1179 .flatten()
1180 {
1181 tree.parallel_routes.insert(
1182 rcstr!("children"),
1183 AppPageLoaderTree {
1184 page: app_page.clone(),
1185 segment: rcstr!("__PAGE__"),
1186 parallel_routes: FxIndexMap::default(),
1187 modules: AppDirModules {
1188 page: Some(page),
1189 metadata: modules.metadata,
1190 ..Default::default()
1191 },
1192 global_metadata: global_metadata.to_resolved().await?,
1193 },
1194 );
1195 }
1196
1197 let mut duplicate = FxHashMap::default();
1198
1199 for (subdir_name, subdirectory) in &directory_tree.subdirectories {
1200 let parallel_route_key = match_parallel_route(subdir_name);
1201
1202 let mut child_app_page = app_page.clone();
1203 let mut illegal_path_error = None;
1204
1205 if let Err(e) = child_app_page.push_str(&normalize_underscore(subdir_name)) {
1209 illegal_path_error = Some(e);
1210 }
1211
1212 let subtree = Box::pin(directory_tree_to_loader_tree_internal(
1213 app_dir.clone(),
1214 global_metadata,
1215 subdir_name.clone(),
1216 subdirectory,
1217 child_app_page.clone(),
1218 for_app_path.clone(),
1219 parent_modules.clone(),
1220 ))
1221 .await?;
1222
1223 if let Some(illegal_path) = subtree.as_ref().and(illegal_path_error) {
1224 return Err(illegal_path);
1225 }
1226
1227 if let Some(subtree) = subtree {
1228 if let Some(key) = parallel_route_key {
1229 let is_inside_catchall = app_page.is_catchall();
1230
1231 let is_leaf_segment = !has_child_routes(directory_tree);
1247
1248 if key != "children"
1249 && subdirectory.modules.default.is_none()
1250 && !is_inside_catchall
1251 && !is_leaf_segment
1252 {
1253 missing_default_parallel_route_issue(
1254 app_dir.clone(),
1255 app_page.clone(),
1256 key.into(),
1257 )
1258 .to_resolved()
1259 .await?
1260 .emit();
1261 }
1262
1263 tree.parallel_routes.insert(key.into(), subtree);
1264 continue;
1265 }
1266
1267 if is_group_route(subdir_name) && !subtree.has_page() {
1269 continue;
1270 }
1271
1272 if subtree.has_page() {
1273 check_duplicate(&mut duplicate, &subtree, app_dir.clone()).await?;
1274 }
1275
1276 if let Some(current_tree) = tree.parallel_routes.get("children") {
1277 if current_tree.has_only_catchall()
1278 && (!subtree.has_only_catchall()
1279 || current_tree.get_specificity() < subtree.get_specificity())
1280 {
1281 tree.parallel_routes
1282 .insert(rcstr!("children"), subtree.clone());
1283 }
1284 } else {
1285 tree.parallel_routes.insert(rcstr!("children"), subtree);
1286 }
1287 } else if let Some(key) = parallel_route_key {
1288 bail!(
1289 "missing page or default for parallel route `{}` (page: {})",
1290 key,
1291 app_page
1292 );
1293 }
1294 }
1295
1296 if tree
1299 .parallel_routes
1300 .iter()
1301 .any(|(_, parallel_tree)| parallel_tree.is_intercepting())
1302 {
1303 let mut keys_to_replace = Vec::new();
1304
1305 for (key, parallel_tree) in &tree.parallel_routes {
1306 if !parallel_tree.is_intercepting() {
1307 keys_to_replace.push(key.clone());
1308 }
1309 }
1310
1311 for key in keys_to_replace {
1312 let subdir_name: RcStr = format!("@{key}").into();
1313
1314 let default = if key == "children" {
1315 modules.default.clone()
1316 } else if let Some(subdirectory) = directory_tree.subdirectories.get(&subdir_name) {
1317 subdirectory.modules.default.clone()
1318 } else {
1319 None
1320 };
1321
1322 let is_inside_catchall = app_page.is_catchall();
1323
1324 let is_leaf_segment = !has_child_routes(directory_tree);
1326
1327 if default.is_none() && key != "children" && !is_inside_catchall && !is_leaf_segment {
1332 missing_default_parallel_route_issue(
1333 app_dir.clone(),
1334 app_page.clone(),
1335 key.clone(),
1336 )
1337 .to_resolved()
1338 .await?
1339 .emit();
1340 }
1341
1342 tree.parallel_routes.insert(
1343 key.clone(),
1344 default_route_tree(app_dir.clone(), global_metadata, app_page.clone(), default)
1345 .await?,
1346 );
1347 }
1348 }
1349
1350 if tree.parallel_routes.is_empty() {
1351 if modules.default.is_some() || current_level_is_parallel_route {
1352 tree = default_route_tree(
1353 app_dir.clone(),
1354 global_metadata,
1355 app_page,
1356 modules.default.clone(),
1357 )
1358 .await?;
1359 } else {
1360 return Ok(None);
1361 }
1362 } else if tree.parallel_routes.get("children").is_none() {
1363 tree.parallel_routes.insert(
1364 rcstr!("children"),
1365 default_route_tree(
1366 app_dir.clone(),
1367 global_metadata,
1368 app_page,
1369 modules.default.clone(),
1370 )
1371 .await?,
1372 );
1373 }
1374
1375 if tree.parallel_routes.len() > 1
1376 && tree.parallel_routes.keys().next().map(|s| s.as_str()) != Some("children")
1377 {
1378 tree.parallel_routes
1380 .move_index(tree.parallel_routes.len() - 1, 0);
1381 }
1382
1383 Ok(Some(tree))
1384}
1385
1386async fn default_route_tree(
1387 app_dir: FileSystemPath,
1388 global_metadata: Vc<GlobalMetadata>,
1389 app_page: AppPage,
1390 default_component: Option<FileSystemPath>,
1391) -> Result<AppPageLoaderTree> {
1392 Ok(AppPageLoaderTree {
1393 page: app_page.clone(),
1394 segment: rcstr!("__DEFAULT__"),
1395 parallel_routes: FxIndexMap::default(),
1396 modules: if let Some(default) = default_component {
1397 AppDirModules {
1398 default: Some(default),
1399 ..Default::default()
1400 }
1401 } else {
1402 AppDirModules {
1404 default: Some(
1405 get_next_package(app_dir)
1406 .await?
1407 .join("dist/client/components/builtin/default.js")?,
1408 ),
1409 ..Default::default()
1410 }
1411 },
1412 global_metadata: global_metadata.to_resolved().await?,
1413 })
1414}
1415
1416#[turbo_tasks::function]
1417async fn directory_tree_to_entrypoints_internal(
1418 app_dir: FileSystemPath,
1419 global_metadata: ResolvedVc<GlobalMetadata>,
1420 is_global_not_found_enabled: Vc<bool>,
1421 next_mode: Vc<NextMode>,
1422 directory_name: RcStr,
1423 directory_tree: Vc<DirectoryTree>,
1424 app_page: AppPage,
1425 root_layouts: ResolvedVc<FileSystemPathVec>,
1426 root_params: ResolvedVc<RootParamVecOption>,
1427) -> Result<Vc<Entrypoints>> {
1428 let span = tracing::info_span!("build layout trees", name = display(&app_page));
1429 directory_tree_to_entrypoints_internal_untraced(
1430 app_dir,
1431 global_metadata,
1432 is_global_not_found_enabled,
1433 next_mode,
1434 directory_name,
1435 directory_tree,
1436 app_page,
1437 root_layouts,
1438 root_params,
1439 )
1440 .instrument(span)
1441 .await
1442}
1443
1444async fn directory_tree_to_entrypoints_internal_untraced(
1445 app_dir: FileSystemPath,
1446 global_metadata: ResolvedVc<GlobalMetadata>,
1447 is_global_not_found_enabled: Vc<bool>,
1448 next_mode: Vc<NextMode>,
1449 directory_name: RcStr,
1450 directory_tree: Vc<DirectoryTree>,
1451 app_page: AppPage,
1452 root_layouts: ResolvedVc<FileSystemPathVec>,
1453 root_params: ResolvedVc<RootParamVecOption>,
1454) -> Result<Vc<Entrypoints>> {
1455 let mut result = FxIndexMap::default();
1456
1457 let directory_tree_vc = directory_tree;
1458 let directory_tree = &*directory_tree.await?;
1459
1460 let subdirectories = &directory_tree.subdirectories;
1461 let modules = &directory_tree.modules;
1462 let root_layouts = if let Some(layout) = &modules.layout {
1466 let mut layouts = root_layouts.owned().await?;
1467 layouts.push(layout.clone());
1468 ResolvedVc::cell(layouts)
1469 } else {
1470 root_layouts
1471 };
1472
1473 let root_params = if root_params.await?.is_none() && (*root_layouts.await?).len() == 1 {
1475 ResolvedVc::cell(Some(
1478 app_page
1479 .0
1480 .iter()
1481 .filter_map(|segment| match segment {
1482 PageSegment::Dynamic(param)
1483 | PageSegment::CatchAll(param)
1484 | PageSegment::OptionalCatchAll(param) => Some(param.clone()),
1485 _ => None,
1486 })
1487 .collect::<Vec<RcStr>>(),
1488 ))
1489 } else {
1490 root_params
1491 };
1492
1493 if modules.page.is_some() {
1494 let app_path = AppPath::from(app_page.clone());
1495
1496 let loader_tree = *directory_tree_to_loader_tree(
1497 app_dir.clone(),
1498 *global_metadata,
1499 directory_name.clone(),
1500 directory_tree_vc,
1501 app_page.clone(),
1502 app_path,
1503 )
1504 .await?;
1505
1506 add_app_page(
1507 app_dir.clone(),
1508 &mut result,
1509 app_page.complete(PageType::Page)?,
1510 loader_tree.context("loader tree should be created for a page/default")?,
1511 root_params,
1512 );
1513 }
1514
1515 if let Some(route) = &modules.route {
1516 add_app_route(
1517 app_dir.clone(),
1518 &mut result,
1519 app_page.complete(PageType::Route)?,
1520 route.clone(),
1521 root_layouts,
1522 root_params,
1523 );
1524 }
1525
1526 let Metadata {
1527 icon,
1528 apple,
1529 twitter,
1530 open_graph,
1531 sitemap,
1532 base_page: _,
1533 } = &modules.metadata;
1534
1535 for meta in sitemap
1536 .iter()
1537 .cloned()
1538 .chain(icon.iter().cloned().map(MetadataItem::from))
1539 .chain(apple.iter().cloned().map(MetadataItem::from))
1540 .chain(twitter.iter().cloned().map(MetadataItem::from))
1541 .chain(open_graph.iter().cloned().map(MetadataItem::from))
1542 {
1543 let app_page = app_page.clone_push_str(&get_metadata_route_name(meta.clone()).await?)?;
1544
1545 add_app_metadata_route(
1546 app_dir.clone(),
1547 &mut result,
1548 normalize_metadata_route(app_page)?,
1549 meta,
1550 root_params,
1551 );
1552 }
1553
1554 if app_page.is_root() {
1556 let GlobalMetadata {
1557 favicon,
1558 robots,
1559 manifest,
1560 } = &*global_metadata.await?;
1561
1562 for meta in favicon.iter().chain(robots.iter()).chain(manifest.iter()) {
1563 let app_page =
1564 app_page.clone_push_str(&get_metadata_route_name(meta.clone()).await?)?;
1565
1566 add_app_metadata_route(
1567 app_dir.clone(),
1568 &mut result,
1569 normalize_metadata_route(app_page)?,
1570 meta.clone(),
1571 root_params,
1572 );
1573 }
1574
1575 let mut modules = directory_tree.modules.clone();
1576
1577 if modules.layout.is_none() {
1579 modules.layout = Some(
1580 get_next_package(app_dir.clone())
1581 .await?
1582 .join("dist/client/components/builtin/layout.js")?,
1583 );
1584 }
1585
1586 if modules.not_found.is_none() {
1587 modules.not_found = Some(
1588 get_next_package(app_dir.clone())
1589 .await?
1590 .join("dist/client/components/builtin/not-found.js")?,
1591 );
1592 }
1593 if modules.forbidden.is_none() {
1594 modules.forbidden = Some(
1595 get_next_package(app_dir.clone())
1596 .await?
1597 .join("dist/client/components/builtin/forbidden.js")?,
1598 );
1599 }
1600 if modules.unauthorized.is_none() {
1601 modules.unauthorized = Some(
1602 get_next_package(app_dir.clone())
1603 .await?
1604 .join("dist/client/components/builtin/unauthorized.js")?,
1605 );
1606 }
1607
1608 let is_global_not_found_enabled = *is_global_not_found_enabled.await?;
1613 let use_global_not_found =
1614 is_global_not_found_enabled || modules.global_not_found.is_some();
1615
1616 let not_found_root_modules = modules.without_leaves();
1617 let not_found_tree = AppPageLoaderTree {
1618 page: app_page.clone(),
1619 segment: directory_name.clone(),
1620 parallel_routes: fxindexmap! {
1621 rcstr!("children") => AppPageLoaderTree {
1622 page: app_page.clone(),
1623 segment: rcstr!("/_not-found"),
1624 parallel_routes: fxindexmap! {
1625 rcstr!("children") => AppPageLoaderTree {
1626 page: app_page.clone(),
1627 segment: rcstr!("__PAGE__"),
1628 parallel_routes: FxIndexMap::default(),
1629 modules: if use_global_not_found {
1630 AppDirModules {
1633 page: Some(get_next_package(app_dir.clone())
1635 .await?
1636 .join("dist/client/components/builtin/empty-stub.js")?,
1637 ),
1638 ..Default::default()
1639 }
1640 } else {
1641 AppDirModules {
1644 page: match modules.not_found {
1645 Some(v) => Some(v),
1646 None => Some(get_next_package(app_dir.clone())
1647 .await?
1648 .join("dist/client/components/builtin/not-found.js")?,
1649 ),
1650 },
1651 ..Default::default()
1652 }
1653 },
1654 global_metadata,
1655 }
1656 },
1657 modules: AppDirModules {
1658 ..Default::default()
1659 },
1660 global_metadata,
1661 },
1662 },
1663 modules: AppDirModules {
1664 layout: if use_global_not_found {
1669 match modules.global_not_found {
1670 Some(v) => Some(v),
1671 None => Some(
1672 get_next_package(app_dir.clone())
1673 .await?
1674 .join("dist/client/components/builtin/global-not-found.js")?,
1675 ),
1676 }
1677 } else {
1678 modules.layout
1679 },
1680 ..not_found_root_modules
1681 },
1682 global_metadata,
1683 }
1684 .resolved_cell();
1685
1686 {
1687 let app_page = app_page
1688 .clone_push_str("_not-found")?
1689 .complete(PageType::Page)?;
1690
1691 add_app_page(
1692 app_dir.clone(),
1693 &mut result,
1694 app_page,
1695 not_found_tree,
1696 root_params,
1697 );
1698 }
1699
1700 if matches!(*next_mode.await?, NextMode::Build) {
1705 let global_error_tree = AppPageLoaderTree {
1707 page: app_page.clone(),
1708 segment: directory_name.clone(),
1709 parallel_routes: fxindexmap! {
1710 rcstr!("children") => AppPageLoaderTree {
1711 page: app_page.clone(),
1712 segment: rcstr!("__PAGE__"),
1713 parallel_routes: FxIndexMap::default(),
1714 modules: AppDirModules {
1715 page: Some(get_next_package(app_dir.clone())
1716 .await?
1717 .join("dist/client/components/builtin/app-error.js")?),
1718 ..Default::default()
1719 },
1720 global_metadata,
1721 }
1722 },
1723 modules: AppDirModules::default(),
1724 global_metadata,
1725 }
1726 .resolved_cell();
1727
1728 let app_global_error_page = app_page
1729 .clone_push_str("_global-error")?
1730 .complete(PageType::Page)?;
1731 add_app_page(
1732 app_dir.clone(),
1733 &mut result,
1734 app_global_error_page,
1735 global_error_tree,
1736 root_params,
1737 );
1738 }
1739 }
1740
1741 let app_page = &app_page;
1742 let directory_name = &directory_name;
1743 let subdirectories = subdirectories
1744 .iter()
1745 .map(|(subdir_name, &subdirectory)| {
1746 let app_dir = app_dir.clone();
1747
1748 async move {
1749 let mut child_app_page = app_page.clone();
1750 let mut illegal_path = None;
1751
1752 if let Err(e) = child_app_page.push_str(&normalize_underscore(subdir_name)) {
1756 illegal_path = Some(e);
1757 }
1758
1759 let map = directory_tree_to_entrypoints_internal(
1760 app_dir.clone(),
1761 *global_metadata,
1762 is_global_not_found_enabled,
1763 next_mode,
1764 subdir_name.clone(),
1765 *subdirectory,
1766 child_app_page.clone(),
1767 *root_layouts,
1768 *root_params,
1769 )
1770 .await?;
1771
1772 if let Some(illegal_path) = illegal_path
1773 && !map.is_empty()
1774 {
1775 return Err(illegal_path);
1776 }
1777
1778 let mut loader_trees = Vec::new();
1779
1780 for (_, entrypoint) in map.iter() {
1781 if let Entrypoint::AppPage { ref pages, .. } = *entrypoint {
1782 for page in pages {
1783 let app_path = AppPath::from(page.clone());
1784
1785 let loader_tree = directory_tree_to_loader_tree(
1786 app_dir.clone(),
1787 *global_metadata,
1788 directory_name.clone(),
1789 directory_tree_vc,
1790 app_page.clone(),
1791 app_path,
1792 );
1793 loader_trees.push(loader_tree);
1794 }
1795 }
1796 }
1797 Ok((map, loader_trees))
1798 }
1799 })
1800 .try_join()
1801 .await?;
1802
1803 for (map, loader_trees) in subdirectories.iter() {
1804 let mut i = 0;
1805 for (_, entrypoint) in map.iter() {
1806 match entrypoint {
1807 Entrypoint::AppPage {
1808 pages,
1809 loader_tree: _,
1810 root_params,
1811 } => {
1812 for page in pages {
1813 let loader_tree = *loader_trees[i].await?;
1814 i += 1;
1815
1816 add_app_page(
1817 app_dir.clone(),
1818 &mut result,
1819 page.clone(),
1820 loader_tree
1821 .context("loader tree should be created for a page/default")?,
1822 *root_params,
1823 );
1824 }
1825 }
1826 Entrypoint::AppRoute {
1827 page,
1828 path,
1829 root_layouts,
1830 root_params,
1831 } => {
1832 add_app_route(
1833 app_dir.clone(),
1834 &mut result,
1835 page.clone(),
1836 path.clone(),
1837 *root_layouts,
1838 *root_params,
1839 );
1840 }
1841 Entrypoint::AppMetadata {
1842 page,
1843 metadata,
1844 root_params,
1845 } => {
1846 add_app_metadata_route(
1847 app_dir.clone(),
1848 &mut result,
1849 page.clone(),
1850 metadata.clone(),
1851 *root_params,
1852 );
1853 }
1854 }
1855 }
1856 }
1857 Ok(Vc::cell(result))
1858}
1859
1860#[turbo_tasks::function]
1862pub async fn get_global_metadata(
1863 app_dir: FileSystemPath,
1864 page_extensions: Vc<Vec<RcStr>>,
1865) -> Result<Vc<GlobalMetadata>> {
1866 let DirectoryContent::Entries(entries) = &*app_dir.read_dir().await? else {
1867 bail!("app_dir must be a directory")
1868 };
1869 let mut metadata = GlobalMetadata::default();
1870
1871 for (basename, entry) in entries {
1872 let DirectoryEntry::File(file) = entry else {
1873 continue;
1874 };
1875
1876 let Some(GlobalMetadataFileMatch {
1877 metadata_type,
1878 dynamic,
1879 }) = match_global_metadata_file(basename, &page_extensions.await?)
1880 else {
1881 continue;
1882 };
1883
1884 let entry = match metadata_type {
1885 "favicon" => &mut metadata.favicon,
1886 "manifest" => &mut metadata.manifest,
1887 "robots" => &mut metadata.robots,
1888 _ => continue,
1889 };
1890
1891 if dynamic {
1892 *entry = Some(MetadataItem::Dynamic { path: file.clone() });
1893 } else {
1894 *entry = Some(MetadataItem::Static { path: file.clone() });
1895 }
1896 }
1898
1899 Ok(metadata.cell())
1900}
1901
1902#[turbo_tasks::value(shared)]
1903struct DirectoryTreeIssue {
1904 pub severity: IssueSeverity,
1905 pub app_dir: FileSystemPath,
1906 pub message: ResolvedVc<StyledString>,
1907}
1908
1909#[turbo_tasks::value_impl]
1910impl Issue for DirectoryTreeIssue {
1911 fn severity(&self) -> IssueSeverity {
1912 self.severity
1913 }
1914
1915 #[turbo_tasks::function]
1916 fn title(&self) -> Vc<StyledString> {
1917 StyledString::Text(rcstr!("An issue occurred while preparing your Next.js app")).cell()
1918 }
1919
1920 #[turbo_tasks::function]
1921 fn stage(&self) -> Vc<IssueStage> {
1922 IssueStage::AppStructure.cell()
1923 }
1924
1925 #[turbo_tasks::function]
1926 fn file_path(&self) -> Vc<FileSystemPath> {
1927 self.app_dir.clone().cell()
1928 }
1929
1930 #[turbo_tasks::function]
1931 fn description(&self) -> Vc<OptionStyledString> {
1932 Vc::cell(Some(self.message))
1933 }
1934}