next_core/
app_structure.rs

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
30// Next.js ignores underscores for routes but you can use %5f to still serve an underscored
31// route.
32fn normalize_underscore(string: &str) -> String {
33    string.replace("%5F", "_")
34}
35
36/// A final route in the app directory.
37#[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/// A single metadata file plus an optional "alt" text file.
89#[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/// A single metadata file.
101#[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/// Metadata file that can be placed in any segment of the app directory.
148#[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    // The page indicates where the metadata is defined and captured.
163    // The steps for capturing metadata (get_directory_tree) and constructing
164    // LoaderTree (directory_tree_to_entrypoints) is separated,
165    // and child loader tree can trickle down metadata when clone / merge components calculates
166    // the actual path incorrectly with fillMetadataSegment.
167    //
168    // This is only being used for the static metadata files.
169    #[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/// Metadata files that can be placed in the root of the app directory.
192#[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    /// key is e.g. "dashboard", "(dashboard)", "@slot"
218    pub subdirectories: BTreeMap<RcStr, ResolvedVc<DirectoryTree>>,
219    pub modules: AppDirModules,
220}
221
222#[turbo_tasks::value]
223#[derive(Clone, Debug)]
224struct PlainDirectoryTree {
225    /// key is e.g. "dashboard", "(dashboard)", "@slot"
226    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/// Finds and returns the [DirectoryTree] of the app directory if existing.
252#[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 = {
273        let dir = dir.value_to_string().await?.to_string();
274        tracing::info_span!("read app directory tree", name = dir)
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        // the file watcher might invalidate things in the wrong order,
287        // and we have to account for the eventual consistency of turbo-tasks
288        // so we just return an empty tree here.
289        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                // Do not process .d.ts files as routes
310                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                // appDir ignores paths starting with an underscore
381                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            // TODO(WEB-952) handle symlinks in app dir
389            _ => {}
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    /// Returns true if there's a page match in this loader tree.
422    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    /// Returns whether the only match in this tree is for a catch-all
437    /// route.
438    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    /// Returns true if this loader tree contains an intercepting route match.
453    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    /// Returns the specificity of the page (i.e. the number of segments
468    /// affecting the path)
469    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            // loader trees should always match for the same path as they are generated by a
633            // turbo tasks function
634            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
843fn page_path_except_parallel(loader_tree: &AppPageLoaderTree) -> Option<AppPage> {
844    if loader_tree.page.iter().any(|v| {
845        matches!(
846            v,
847            PageSegment::CatchAll(..)
848                | PageSegment::OptionalCatchAll(..)
849                | PageSegment::Parallel(..)
850        )
851    }) {
852        return None;
853    }
854
855    if loader_tree.modules.page.is_some() {
856        return Some(loader_tree.page.clone());
857    }
858
859    if let Some(children) = loader_tree.parallel_routes.get("children") {
860        return page_path_except_parallel(children);
861    }
862
863    None
864}
865
866async fn check_duplicate(
867    duplicate: &mut FxHashMap<AppPath, AppPage>,
868    loader_tree: &AppPageLoaderTree,
869    app_dir: FileSystemPath,
870) -> Result<()> {
871    let page_path = page_path_except_parallel(loader_tree);
872
873    if let Some(page_path) = page_path
874        && let Some(prev) = duplicate.insert(AppPath::from(page_path.clone()), page_path.clone())
875        && prev != page_path
876    {
877        DuplicateParallelRouteIssue {
878            app_dir: app_dir.clone(),
879            previously_inserted_page: prev.clone(),
880            page: loader_tree.page.clone(),
881        }
882        .resolved_cell()
883        .emit();
884    }
885
886    Ok(())
887}
888
889#[turbo_tasks::value(transparent)]
890struct AppPageLoaderTreeOption(Option<ResolvedVc<AppPageLoaderTree>>);
891
892/// creates the loader tree for a specific route (pathname / [AppPath])
893#[turbo_tasks::function]
894async fn directory_tree_to_loader_tree(
895    app_dir: FileSystemPath,
896    global_metadata: Vc<GlobalMetadata>,
897    directory_name: RcStr,
898    directory_tree: Vc<DirectoryTree>,
899    app_page: AppPage,
900    // the page this loader tree is constructed for
901    for_app_path: AppPath,
902) -> Result<Vc<AppPageLoaderTreeOption>> {
903    let plain_tree = &*directory_tree.into_plain().await?;
904
905    let tree = directory_tree_to_loader_tree_internal(
906        app_dir,
907        global_metadata,
908        directory_name,
909        plain_tree,
910        app_page,
911        for_app_path,
912        AppDirModules::default(),
913    )
914    .await?;
915
916    Ok(Vc::cell(tree.map(AppPageLoaderTree::resolved_cell)))
917}
918
919/// Checks the current module if it needs to be updated with the default page.
920/// If the module is already set, update the parent module to the same value.
921/// If the parent module is set and module is not set, set the module to the parent module.
922/// If the module and the parent module are not set, set them to the default value.
923///
924/// # Arguments
925/// * `app_dir` - The application directory.
926/// * `module` - The current module to check and update if it is not set.
927/// * `parent_module` - The parent module to update if the current module is set or both are not
928///   set.
929/// * `file_path` - The file path to the default page if neither the current module nor the parent
930///   module is set.
931/// * `is_first_layer_group_route` - If true, the module will be overridden with the parent module
932///   if it is not set.
933async fn check_and_update_module_references(
934    app_dir: FileSystemPath,
935    module: &mut Option<FileSystemPath>,
936    parent_module: &mut Option<FileSystemPath>,
937    file_path: &str,
938    is_first_layer_group_route: bool,
939) -> Result<()> {
940    match (module.as_mut(), parent_module.as_mut()) {
941        // If the module is set, update the parent module to the same value
942        (Some(module), _) => *parent_module = Some(module.clone()),
943        // If we are in a first layer group route and we have a parent module, we want to override
944        // a nonexistent module with the parent module
945        (None, Some(parent_module)) if is_first_layer_group_route => {
946            *module = Some(parent_module.clone())
947        }
948        // If we are not in a first layer group route, and the module is not set, and the parent
949        // module is set, we do nothing
950        (None, Some(_)) => {}
951        // If the module is not set, and the parent module is not set, we override with the default
952        // page. This can only happen in the root directory because after this the parent module
953        // will always be set.
954        (None, None) => {
955            let default_page = get_next_package(app_dir).await?.join(file_path)?;
956            *module = Some(default_page.clone());
957            *parent_module = Some(default_page);
958        }
959    }
960
961    Ok(())
962}
963
964/// Checks if the current directory is the root directory and if the module is not set.
965/// If the module is not set, it will be set to the default page.
966///
967/// # Arguments
968/// * `app_dir` - The application directory.
969/// * `module` - The module to check and update if it is not set.
970/// * `file_path` - The file path to the default page if the module is not set.
971async fn check_and_update_global_module_references(
972    app_dir: FileSystemPath,
973    module: &mut Option<FileSystemPath>,
974    file_path: &str,
975) -> Result<()> {
976    if module.is_none() {
977        *module = Some(get_next_package(app_dir).await?.join(file_path)?);
978    }
979
980    Ok(())
981}
982
983async fn directory_tree_to_loader_tree_internal(
984    app_dir: FileSystemPath,
985    global_metadata: Vc<GlobalMetadata>,
986    directory_name: RcStr,
987    directory_tree: &PlainDirectoryTree,
988    app_page: AppPage,
989    // the page this loader tree is constructed for
990    for_app_path: AppPath,
991    mut parent_modules: AppDirModules,
992) -> Result<Option<AppPageLoaderTree>> {
993    let app_path = AppPath::from(app_page.clone());
994
995    if !for_app_path.contains(&app_path) {
996        return Ok(None);
997    }
998
999    let mut modules = directory_tree.modules.clone();
1000
1001    // Capture the current page for the metadata to calculate segment relative to
1002    // the corresponding page for the static metadata files.
1003    modules.metadata.base_page = Some(app_page.clone());
1004
1005    // the root directory in the app dir.
1006    let is_root_directory = app_page.is_root();
1007
1008    // If the first layer is a group route, we treat it as root layer
1009    let is_first_layer_group_route = app_page.is_first_layer_group_route();
1010
1011    // Handle the non-global modules that should always be overridden for top level groups or set to
1012    // the default page if they are not set.
1013    if is_root_directory || is_first_layer_group_route {
1014        check_and_update_module_references(
1015            app_dir.clone(),
1016            &mut modules.not_found,
1017            &mut parent_modules.not_found,
1018            "dist/client/components/builtin/not-found.js",
1019            is_first_layer_group_route,
1020        )
1021        .await?;
1022
1023        check_and_update_module_references(
1024            app_dir.clone(),
1025            &mut modules.forbidden,
1026            &mut parent_modules.forbidden,
1027            "dist/client/components/builtin/forbidden.js",
1028            is_first_layer_group_route,
1029        )
1030        .await?;
1031
1032        check_and_update_module_references(
1033            app_dir.clone(),
1034            &mut modules.unauthorized,
1035            &mut parent_modules.unauthorized,
1036            "dist/client/components/builtin/unauthorized.js",
1037            is_first_layer_group_route,
1038        )
1039        .await?;
1040    }
1041
1042    if is_root_directory {
1043        check_and_update_global_module_references(
1044            app_dir.clone(),
1045            &mut modules.global_error,
1046            "dist/client/components/builtin/global-error.js",
1047        )
1048        .await?;
1049    }
1050
1051    let mut tree = AppPageLoaderTree {
1052        page: app_page.clone(),
1053        segment: directory_name.clone(),
1054        parallel_routes: FxIndexMap::default(),
1055        modules: modules.without_leaves(),
1056        global_metadata: global_metadata.to_resolved().await?,
1057    };
1058
1059    let current_level_is_parallel_route = is_parallel_route(&directory_name);
1060
1061    if current_level_is_parallel_route {
1062        tree.segment = rcstr!("(slot)");
1063    }
1064
1065    if let Some(page) = (app_path == for_app_path || app_path.is_catchall())
1066        .then_some(modules.page)
1067        .flatten()
1068    {
1069        tree.parallel_routes.insert(
1070            rcstr!("children"),
1071            AppPageLoaderTree {
1072                page: app_page.clone(),
1073                segment: rcstr!("__PAGE__"),
1074                parallel_routes: FxIndexMap::default(),
1075                modules: AppDirModules {
1076                    page: Some(page),
1077                    metadata: modules.metadata,
1078                    ..Default::default()
1079                },
1080                global_metadata: global_metadata.to_resolved().await?,
1081            },
1082        );
1083    }
1084
1085    let mut duplicate = FxHashMap::default();
1086
1087    for (subdir_name, subdirectory) in &directory_tree.subdirectories {
1088        let parallel_route_key = match_parallel_route(subdir_name);
1089
1090        let mut child_app_page = app_page.clone();
1091        let mut illegal_path_error = None;
1092
1093        // When constructing the app_page fails (e. g. due to limitations of the order),
1094        // we only want to emit the error when there are actual pages below that
1095        // directory.
1096        if let Err(e) = child_app_page.push_str(&normalize_underscore(subdir_name)) {
1097            illegal_path_error = Some(e);
1098        }
1099
1100        let subtree = Box::pin(directory_tree_to_loader_tree_internal(
1101            app_dir.clone(),
1102            global_metadata,
1103            subdir_name.clone(),
1104            subdirectory,
1105            child_app_page.clone(),
1106            for_app_path.clone(),
1107            parent_modules.clone(),
1108        ))
1109        .await?;
1110
1111        if let Some(illegal_path) = subtree.as_ref().and(illegal_path_error) {
1112            return Err(illegal_path);
1113        }
1114
1115        if let Some(subtree) = subtree {
1116            if let Some(key) = parallel_route_key {
1117                tree.parallel_routes.insert(key.into(), subtree);
1118                continue;
1119            }
1120
1121            // skip groups which don't have a page match.
1122            if is_group_route(subdir_name) && !subtree.has_page() {
1123                continue;
1124            }
1125
1126            if subtree.has_page() {
1127                check_duplicate(&mut duplicate, &subtree, app_dir.clone()).await?;
1128            }
1129
1130            if let Some(current_tree) = tree.parallel_routes.get("children") {
1131                if current_tree.has_only_catchall()
1132                    && (!subtree.has_only_catchall()
1133                        || current_tree.get_specificity() < subtree.get_specificity())
1134                {
1135                    tree.parallel_routes
1136                        .insert(rcstr!("children"), subtree.clone());
1137                }
1138            } else {
1139                tree.parallel_routes.insert(rcstr!("children"), subtree);
1140            }
1141        } else if let Some(key) = parallel_route_key {
1142            bail!(
1143                "missing page or default for parallel route `{}` (page: {})",
1144                key,
1145                app_page
1146            );
1147        }
1148    }
1149
1150    // make sure we don't have a match for other slots if there's an intercepting route match
1151    // we only check subtrees as the current level could trigger `is_intercepting`
1152    if tree
1153        .parallel_routes
1154        .iter()
1155        .any(|(_, parallel_tree)| parallel_tree.is_intercepting())
1156    {
1157        let mut keys_to_replace = Vec::new();
1158
1159        for (key, parallel_tree) in &tree.parallel_routes {
1160            if !parallel_tree.is_intercepting() {
1161                keys_to_replace.push(key.clone());
1162            }
1163        }
1164
1165        for key in keys_to_replace {
1166            let subdir_name: RcStr = format!("@{key}").into();
1167
1168            let default = if key == "children" {
1169                modules.default.clone()
1170            } else if let Some(subdirectory) = directory_tree.subdirectories.get(&subdir_name) {
1171                subdirectory.modules.default.clone()
1172            } else {
1173                None
1174            };
1175
1176            tree.parallel_routes.insert(
1177                key,
1178                default_route_tree(app_dir.clone(), global_metadata, app_page.clone(), default)
1179                    .await?,
1180            );
1181        }
1182    }
1183
1184    if tree.parallel_routes.is_empty() {
1185        if modules.default.is_some() || current_level_is_parallel_route {
1186            tree = default_route_tree(
1187                app_dir.clone(),
1188                global_metadata,
1189                app_page,
1190                modules.default.clone(),
1191            )
1192            .await?;
1193        } else {
1194            return Ok(None);
1195        }
1196    } else if tree.parallel_routes.get("children").is_none() {
1197        tree.parallel_routes.insert(
1198            rcstr!("children"),
1199            default_route_tree(
1200                app_dir.clone(),
1201                global_metadata,
1202                app_page,
1203                modules.default.clone(),
1204            )
1205            .await?,
1206        );
1207    }
1208
1209    if tree.parallel_routes.len() > 1
1210        && tree.parallel_routes.keys().next().map(|s| s.as_str()) != Some("children")
1211    {
1212        // children must go first for next.js to work correctly
1213        tree.parallel_routes
1214            .move_index(tree.parallel_routes.len() - 1, 0);
1215    }
1216
1217    Ok(Some(tree))
1218}
1219
1220async fn default_route_tree(
1221    app_dir: FileSystemPath,
1222    global_metadata: Vc<GlobalMetadata>,
1223    app_page: AppPage,
1224    default_component: Option<FileSystemPath>,
1225) -> Result<AppPageLoaderTree> {
1226    Ok(AppPageLoaderTree {
1227        page: app_page.clone(),
1228        segment: rcstr!("__DEFAULT__"),
1229        parallel_routes: FxIndexMap::default(),
1230        modules: if let Some(default) = default_component {
1231            AppDirModules {
1232                default: Some(default),
1233                ..Default::default()
1234            }
1235        } else {
1236            // default fallback component
1237            AppDirModules {
1238                default: Some(
1239                    get_next_package(app_dir)
1240                        .await?
1241                        .join("dist/client/components/builtin/default.js")?,
1242                ),
1243                ..Default::default()
1244            }
1245        },
1246        global_metadata: global_metadata.to_resolved().await?,
1247    })
1248}
1249
1250#[turbo_tasks::function]
1251async fn directory_tree_to_entrypoints_internal(
1252    app_dir: FileSystemPath,
1253    global_metadata: ResolvedVc<GlobalMetadata>,
1254    is_global_not_found_enabled: Vc<bool>,
1255    next_mode: Vc<NextMode>,
1256    directory_name: RcStr,
1257    directory_tree: Vc<DirectoryTree>,
1258    app_page: AppPage,
1259    root_layouts: ResolvedVc<FileSystemPathVec>,
1260    root_params: ResolvedVc<RootParamVecOption>,
1261) -> Result<Vc<Entrypoints>> {
1262    let span = tracing::info_span!("build layout trees", name = display(&app_page));
1263    directory_tree_to_entrypoints_internal_untraced(
1264        app_dir,
1265        global_metadata,
1266        is_global_not_found_enabled,
1267        next_mode,
1268        directory_name,
1269        directory_tree,
1270        app_page,
1271        root_layouts,
1272        root_params,
1273    )
1274    .instrument(span)
1275    .await
1276}
1277
1278async fn directory_tree_to_entrypoints_internal_untraced(
1279    app_dir: FileSystemPath,
1280    global_metadata: ResolvedVc<GlobalMetadata>,
1281    is_global_not_found_enabled: Vc<bool>,
1282    next_mode: Vc<NextMode>,
1283    directory_name: RcStr,
1284    directory_tree: Vc<DirectoryTree>,
1285    app_page: AppPage,
1286    root_layouts: ResolvedVc<FileSystemPathVec>,
1287    root_params: ResolvedVc<RootParamVecOption>,
1288) -> Result<Vc<Entrypoints>> {
1289    let mut result = FxIndexMap::default();
1290
1291    let directory_tree_vc = directory_tree;
1292    let directory_tree = &*directory_tree.await?;
1293
1294    let subdirectories = &directory_tree.subdirectories;
1295    let modules = &directory_tree.modules;
1296    // Route can have its own segment config, also can inherit from the layout root
1297    // segment config. https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes#segment-runtime-option
1298    // Pass down layouts from each tree to apply segment config when adding route.
1299    let root_layouts = if let Some(layout) = &modules.layout {
1300        let mut layouts = root_layouts.owned().await?;
1301        layouts.push(layout.clone());
1302        ResolvedVc::cell(layouts)
1303    } else {
1304        root_layouts
1305    };
1306
1307    // TODO: `root_layouts` is a misnomer, they're just parent layouts
1308    let root_params = if root_params.await?.is_none() && (*root_layouts.await?).len() == 1 {
1309        // found a root layout. the params up-to-and-including this point are the root params
1310        // for all child segments
1311        ResolvedVc::cell(Some(
1312            app_page
1313                .0
1314                .iter()
1315                .filter_map(|segment| match segment {
1316                    PageSegment::Dynamic(param)
1317                    | PageSegment::CatchAll(param)
1318                    | PageSegment::OptionalCatchAll(param) => Some(param.clone()),
1319                    _ => None,
1320                })
1321                .collect::<Vec<RcStr>>(),
1322        ))
1323    } else {
1324        root_params
1325    };
1326
1327    if modules.page.is_some() {
1328        let app_path = AppPath::from(app_page.clone());
1329
1330        let loader_tree = *directory_tree_to_loader_tree(
1331            app_dir.clone(),
1332            *global_metadata,
1333            directory_name.clone(),
1334            directory_tree_vc,
1335            app_page.clone(),
1336            app_path,
1337        )
1338        .await?;
1339
1340        add_app_page(
1341            app_dir.clone(),
1342            &mut result,
1343            app_page.complete(PageType::Page)?,
1344            loader_tree.context("loader tree should be created for a page/default")?,
1345            root_params,
1346        );
1347    }
1348
1349    if let Some(route) = &modules.route {
1350        add_app_route(
1351            app_dir.clone(),
1352            &mut result,
1353            app_page.complete(PageType::Route)?,
1354            route.clone(),
1355            root_layouts,
1356            root_params,
1357        );
1358    }
1359
1360    let Metadata {
1361        icon,
1362        apple,
1363        twitter,
1364        open_graph,
1365        sitemap,
1366        base_page: _,
1367    } = &modules.metadata;
1368
1369    for meta in sitemap
1370        .iter()
1371        .cloned()
1372        .chain(icon.iter().cloned().map(MetadataItem::from))
1373        .chain(apple.iter().cloned().map(MetadataItem::from))
1374        .chain(twitter.iter().cloned().map(MetadataItem::from))
1375        .chain(open_graph.iter().cloned().map(MetadataItem::from))
1376    {
1377        let app_page = app_page.clone_push_str(&get_metadata_route_name(meta.clone()).await?)?;
1378
1379        add_app_metadata_route(
1380            app_dir.clone(),
1381            &mut result,
1382            normalize_metadata_route(app_page)?,
1383            meta,
1384            root_params,
1385        );
1386    }
1387
1388    // root path: /
1389    if app_page.is_root() {
1390        let GlobalMetadata {
1391            favicon,
1392            robots,
1393            manifest,
1394        } = &*global_metadata.await?;
1395
1396        for meta in favicon.iter().chain(robots.iter()).chain(manifest.iter()) {
1397            let app_page =
1398                app_page.clone_push_str(&get_metadata_route_name(meta.clone()).await?)?;
1399
1400            add_app_metadata_route(
1401                app_dir.clone(),
1402                &mut result,
1403                normalize_metadata_route(app_page)?,
1404                meta.clone(),
1405                root_params,
1406            );
1407        }
1408
1409        let mut modules = directory_tree.modules.clone();
1410
1411        // fill in the default modules for the not-found entrypoint
1412        if modules.layout.is_none() {
1413            modules.layout = Some(
1414                get_next_package(app_dir.clone())
1415                    .await?
1416                    .join("dist/client/components/builtin/layout.js")?,
1417            );
1418        }
1419
1420        if modules.not_found.is_none() {
1421            modules.not_found = Some(
1422                get_next_package(app_dir.clone())
1423                    .await?
1424                    .join("dist/client/components/builtin/not-found.js")?,
1425            );
1426        }
1427        if modules.forbidden.is_none() {
1428            modules.forbidden = Some(
1429                get_next_package(app_dir.clone())
1430                    .await?
1431                    .join("dist/client/components/builtin/forbidden.js")?,
1432            );
1433        }
1434        if modules.unauthorized.is_none() {
1435            modules.unauthorized = Some(
1436                get_next_package(app_dir.clone())
1437                    .await?
1438                    .join("dist/client/components/builtin/unauthorized.js")?,
1439            );
1440        }
1441
1442        // Next.js has this logic in "collect-app-paths", where the root not-found page
1443        // is considered as its own entry point.
1444
1445        // Determine if we enable the global not-found feature.
1446        let is_global_not_found_enabled = *is_global_not_found_enabled.await?;
1447        let use_global_not_found =
1448            is_global_not_found_enabled || modules.global_not_found.is_some();
1449
1450        let not_found_root_modules = modules.without_leaves();
1451        let not_found_tree = AppPageLoaderTree {
1452            page: app_page.clone(),
1453            segment: directory_name.clone(),
1454            parallel_routes: fxindexmap! {
1455                rcstr!("children") => AppPageLoaderTree {
1456                    page: app_page.clone(),
1457                    segment: rcstr!("/_not-found"),
1458                    parallel_routes: fxindexmap! {
1459                        rcstr!("children") => AppPageLoaderTree {
1460                            page: app_page.clone(),
1461                            segment: rcstr!("__PAGE__"),
1462                            parallel_routes: FxIndexMap::default(),
1463                            modules: if use_global_not_found {
1464                                // if global-not-found.js is present:
1465                                // leaf module only keeps page pointing to empty-stub
1466                                AppDirModules {
1467                                    // page is built-in/empty-stub
1468                                    page: Some(get_next_package(app_dir.clone())
1469                                        .await?
1470                                        .join("dist/client/components/builtin/empty-stub.js")?,
1471                                    ),
1472                                    ..Default::default()
1473                                }
1474                            } else {
1475                                // if global-not-found.js is not present:
1476                                // we search if we can compose root layout with the root not-found.js;
1477                                AppDirModules {
1478                                    page: match modules.not_found {
1479                                        Some(v) => Some(v),
1480                                        None => Some(get_next_package(app_dir.clone())
1481                                            .await?
1482                                            .join("dist/client/components/builtin/not-found.js")?,
1483                                        ),
1484                                    },
1485                                    ..Default::default()
1486                                }
1487                            },
1488                            global_metadata,
1489                        }
1490                    },
1491                    modules: AppDirModules {
1492                        ..Default::default()
1493                    },
1494                    global_metadata,
1495                },
1496            },
1497            modules: AppDirModules {
1498                // `global-not-found.js` does not need a layout since it's included.
1499                // Skip it if it's present.
1500                // Otherwise, we need to compose it with the root layout to compose with
1501                // not-found.js boundary.
1502                layout: if use_global_not_found {
1503                    match modules.global_not_found {
1504                        Some(v) => Some(v),
1505                        None => Some(
1506                            get_next_package(app_dir.clone())
1507                                .await?
1508                                .join("dist/client/components/builtin/global-not-found.js")?,
1509                        ),
1510                    }
1511                } else {
1512                    modules.layout
1513                },
1514                ..not_found_root_modules
1515            },
1516            global_metadata,
1517        }
1518        .resolved_cell();
1519
1520        {
1521            let app_page = app_page
1522                .clone_push_str("_not-found")?
1523                .complete(PageType::Page)?;
1524
1525            add_app_page(
1526                app_dir.clone(),
1527                &mut result,
1528                app_page,
1529                not_found_tree,
1530                root_params,
1531            );
1532        }
1533
1534        // Create production global error page only in build mode
1535        // This aligns with webpack: default Pages entries (including /_error) are only added when
1536        // the build isn't app-only. If the build is app-only (no user pages/api), we should still
1537        // expose the app global error so runtime errors render, but we shouldn't emit it otherwise.
1538        if matches!(*next_mode.await?, NextMode::Build) {
1539            // Use built-in global-error.js to create a `_global-error/page` route.
1540            let global_error_tree = AppPageLoaderTree {
1541                page: app_page.clone(),
1542                segment: directory_name.clone(),
1543                parallel_routes: fxindexmap! {
1544                    rcstr!("children") => AppPageLoaderTree {
1545                        page: app_page.clone(),
1546                        segment: rcstr!("__PAGE__"),
1547                        parallel_routes: FxIndexMap::default(),
1548                        modules: AppDirModules {
1549                            page: Some(get_next_package(app_dir.clone())
1550                                .await?
1551                                .join("dist/client/components/builtin/app-error.js")?),
1552                            ..Default::default()
1553                        },
1554                        global_metadata,
1555                    }
1556                },
1557                modules: AppDirModules::default(),
1558                global_metadata,
1559            }
1560            .resolved_cell();
1561
1562            let app_global_error_page = app_page
1563                .clone_push_str("_global-error")?
1564                .complete(PageType::Page)?;
1565            add_app_page(
1566                app_dir.clone(),
1567                &mut result,
1568                app_global_error_page,
1569                global_error_tree,
1570                root_params,
1571            );
1572        }
1573    }
1574
1575    let app_page = &app_page;
1576    let directory_name = &directory_name;
1577    let subdirectories = subdirectories
1578        .iter()
1579        .map(|(subdir_name, &subdirectory)| {
1580            let app_dir = app_dir.clone();
1581
1582            async move {
1583                let mut child_app_page = app_page.clone();
1584                let mut illegal_path = None;
1585
1586                // When constructing the app_page fails (e. g. due to limitations of the order),
1587                // we only want to emit the error when there are actual pages below that
1588                // directory.
1589                if let Err(e) = child_app_page.push_str(&normalize_underscore(subdir_name)) {
1590                    illegal_path = Some(e);
1591                }
1592
1593                let map = directory_tree_to_entrypoints_internal(
1594                    app_dir.clone(),
1595                    *global_metadata,
1596                    is_global_not_found_enabled,
1597                    next_mode,
1598                    subdir_name.clone(),
1599                    *subdirectory,
1600                    child_app_page.clone(),
1601                    *root_layouts,
1602                    *root_params,
1603                )
1604                .await?;
1605
1606                if let Some(illegal_path) = illegal_path
1607                    && !map.is_empty()
1608                {
1609                    return Err(illegal_path);
1610                }
1611
1612                let mut loader_trees = Vec::new();
1613
1614                for (_, entrypoint) in map.iter() {
1615                    if let Entrypoint::AppPage { ref pages, .. } = *entrypoint {
1616                        for page in pages {
1617                            let app_path = AppPath::from(page.clone());
1618
1619                            let loader_tree = directory_tree_to_loader_tree(
1620                                app_dir.clone(),
1621                                *global_metadata,
1622                                directory_name.clone(),
1623                                directory_tree_vc,
1624                                app_page.clone(),
1625                                app_path,
1626                            );
1627                            loader_trees.push(loader_tree);
1628                        }
1629                    }
1630                }
1631                Ok((map, loader_trees))
1632            }
1633        })
1634        .try_join()
1635        .await?;
1636
1637    for (map, loader_trees) in subdirectories.iter() {
1638        let mut i = 0;
1639        for (_, entrypoint) in map.iter() {
1640            match entrypoint {
1641                Entrypoint::AppPage {
1642                    pages,
1643                    loader_tree: _,
1644                    root_params,
1645                } => {
1646                    for page in pages {
1647                        let loader_tree = *loader_trees[i].await?;
1648                        i += 1;
1649
1650                        add_app_page(
1651                            app_dir.clone(),
1652                            &mut result,
1653                            page.clone(),
1654                            loader_tree
1655                                .context("loader tree should be created for a page/default")?,
1656                            *root_params,
1657                        );
1658                    }
1659                }
1660                Entrypoint::AppRoute {
1661                    page,
1662                    path,
1663                    root_layouts,
1664                    root_params,
1665                } => {
1666                    add_app_route(
1667                        app_dir.clone(),
1668                        &mut result,
1669                        page.clone(),
1670                        path.clone(),
1671                        *root_layouts,
1672                        *root_params,
1673                    );
1674                }
1675                Entrypoint::AppMetadata {
1676                    page,
1677                    metadata,
1678                    root_params,
1679                } => {
1680                    add_app_metadata_route(
1681                        app_dir.clone(),
1682                        &mut result,
1683                        page.clone(),
1684                        metadata.clone(),
1685                        *root_params,
1686                    );
1687                }
1688            }
1689        }
1690    }
1691    Ok(Vc::cell(result))
1692}
1693
1694/// Returns the global metadata for an app directory.
1695#[turbo_tasks::function]
1696pub async fn get_global_metadata(
1697    app_dir: FileSystemPath,
1698    page_extensions: Vc<Vec<RcStr>>,
1699) -> Result<Vc<GlobalMetadata>> {
1700    let DirectoryContent::Entries(entries) = &*app_dir.read_dir().await? else {
1701        bail!("app_dir must be a directory")
1702    };
1703    let mut metadata = GlobalMetadata::default();
1704
1705    for (basename, entry) in entries {
1706        let DirectoryEntry::File(file) = entry else {
1707            continue;
1708        };
1709
1710        let Some(GlobalMetadataFileMatch {
1711            metadata_type,
1712            dynamic,
1713        }) = match_global_metadata_file(basename, &page_extensions.await?)
1714        else {
1715            continue;
1716        };
1717
1718        let entry = match metadata_type {
1719            "favicon" => &mut metadata.favicon,
1720            "manifest" => &mut metadata.manifest,
1721            "robots" => &mut metadata.robots,
1722            _ => continue,
1723        };
1724
1725        if dynamic {
1726            *entry = Some(MetadataItem::Dynamic { path: file.clone() });
1727        } else {
1728            *entry = Some(MetadataItem::Static { path: file.clone() });
1729        }
1730        // TODO(WEB-952) handle symlinks in app dir
1731    }
1732
1733    Ok(metadata.cell())
1734}
1735
1736#[turbo_tasks::value(shared)]
1737struct DirectoryTreeIssue {
1738    pub severity: IssueSeverity,
1739    pub app_dir: FileSystemPath,
1740    pub message: ResolvedVc<StyledString>,
1741}
1742
1743#[turbo_tasks::value_impl]
1744impl Issue for DirectoryTreeIssue {
1745    fn severity(&self) -> IssueSeverity {
1746        self.severity
1747    }
1748
1749    #[turbo_tasks::function]
1750    fn title(&self) -> Vc<StyledString> {
1751        StyledString::Text(rcstr!("An issue occurred while preparing your Next.js app")).cell()
1752    }
1753
1754    #[turbo_tasks::function]
1755    fn stage(&self) -> Vc<IssueStage> {
1756        IssueStage::AppStructure.cell()
1757    }
1758
1759    #[turbo_tasks::function]
1760    fn file_path(&self) -> Vc<FileSystemPath> {
1761        self.app_dir.clone().cell()
1762    }
1763
1764    #[turbo_tasks::function]
1765    fn description(&self) -> Vc<OptionStyledString> {
1766        Vc::cell(Some(self.message))
1767    }
1768}