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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
import type { CacheNodeSeedData, PreloadCallbacks } from './types'
import React from 'react'
import {
  isClientReference,
  isUseCacheFunction,
} from '../../lib/client-and-server-references'
import { getLayoutOrPageModule } from '../lib/app-dir-module'
import type { LoaderTree } from '../lib/app-dir-module'
import { interopDefault } from './interop-default'
import { parseLoaderTree } from './parse-loader-tree'
import type { AppRenderContext, GetDynamicParamFromSegment } from './app-render'
import { createComponentStylesAndScripts } from './create-component-styles-and-scripts'
import { getLayerAssets } from './get-layer-assets'
import { hasLoadingComponentInTree } from './has-loading-component-in-tree'
import { validateRevalidate } from '../lib/patch-fetch'
import { PARALLEL_ROUTE_DEFAULT_PATH } from '../../client/components/builtin/default'
import { getTracer } from '../lib/trace/tracer'
import { NextNodeServerSpan } from '../lib/trace/constants'
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import type { LoadingModuleData } from '../../shared/lib/app-router-context.shared-runtime'
import type { Params } from '../request/params'
import { workUnitAsyncStorage } from './work-unit-async-storage.external'
import { OUTLET_BOUNDARY_NAME } from '../../lib/metadata/metadata-constants'
import type {
  UseCacheLayoutComponentProps,
  UseCachePageComponentProps,
} from '../use-cache/use-cache-wrapper'
import { DEFAULT_SEGMENT_KEY } from '../../shared/lib/segment'
import {
  BOUNDARY_PREFIX,
  BOUNDARY_SUFFIX,
  BUILTIN_PREFIX,
  getConventionPathByType,
  isNextjsBuiltinFilePath,
} from './segment-explorer-path'

/**
 * Use the provided loader tree to create the React Component tree.
 */
export function createComponentTree(props: {
  loaderTree: LoaderTree
  parentParams: Params
  rootLayoutIncluded: boolean
  injectedCSS: Set<string>
  injectedJS: Set<string>
  injectedFontPreloadTags: Set<string>
  getMetadataReady: () => Promise<void>
  getViewportReady: () => Promise<void>
  ctx: AppRenderContext
  missingSlots?: Set<string>
  preloadCallbacks: PreloadCallbacks
  authInterrupts: boolean
  StreamingMetadataOutlet: React.ComponentType | null
}): Promise<CacheNodeSeedData> {
  return getTracer().trace(
    NextNodeServerSpan.createComponentTree,
    {
      spanName: 'build component tree',
    },
    () => createComponentTreeInternal(props, true)
  )
}

function errorMissingDefaultExport(
  pagePath: string,
  convention: string
): never {
  const normalizedPagePath = pagePath === '/' ? '' : pagePath
  throw new Error(
    `The default export is not a React Component in "${normalizedPagePath}/${convention}"`
  )
}

const cacheNodeKey = 'c'

async function createComponentTreeInternal(
  {
    loaderTree: tree,
    parentParams,
    rootLayoutIncluded,
    injectedCSS,
    injectedJS,
    injectedFontPreloadTags,
    getViewportReady,
    getMetadataReady,
    ctx,
    missingSlots,
    preloadCallbacks,
    authInterrupts,
    StreamingMetadataOutlet,
  }: {
    loaderTree: LoaderTree
    parentParams: Params
    rootLayoutIncluded: boolean
    injectedCSS: Set<string>
    injectedJS: Set<string>
    injectedFontPreloadTags: Set<string>
    getViewportReady: () => Promise<void>
    getMetadataReady: () => Promise<void>
    ctx: AppRenderContext
    missingSlots?: Set<string>
    preloadCallbacks: PreloadCallbacks
    authInterrupts: boolean
    StreamingMetadataOutlet: React.ComponentType | null
  },
  isRoot: boolean
): Promise<CacheNodeSeedData> {
  const {
    renderOpts: { nextConfigOutput, experimental },
    workStore,
    componentMod: {
      SegmentViewNode,
      HTTPAccessFallbackBoundary,
      LayoutRouter,
      RenderFromTemplateContext,
      OutletBoundary,
      ClientPageRoot,
      ClientSegmentRoot,
      createServerSearchParamsForServerPage,
      createPrerenderSearchParamsForClientPage,
      createServerParamsForServerSegment,
      createPrerenderParamsForClientSegment,
      serverHooks: { DynamicServerError },
      Postpone,
    },
    pagePath,
    getDynamicParamFromSegment,
    isPrefetch,
    query,
  } = ctx

  const { page, conventionPath, segment, modules, parallelRoutes } =
    parseLoaderTree(tree)

  const {
    layout,
    template,
    error,
    loading,
    'not-found': notFound,
    forbidden,
    unauthorized,
  } = modules

  const injectedCSSWithCurrentLayout = new Set(injectedCSS)
  const injectedJSWithCurrentLayout = new Set(injectedJS)
  const injectedFontPreloadTagsWithCurrentLayout = new Set(
    injectedFontPreloadTags
  )

  const layerAssets = getLayerAssets({
    preloadCallbacks,
    ctx,
    layoutOrPagePath: conventionPath,
    injectedCSS: injectedCSSWithCurrentLayout,
    injectedJS: injectedJSWithCurrentLayout,
    injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout,
  })

  const [Template, templateStyles, templateScripts] = template
    ? await createComponentStylesAndScripts({
        ctx,
        filePath: template[1],
        getComponent: template[0],
        injectedCSS: injectedCSSWithCurrentLayout,
        injectedJS: injectedJSWithCurrentLayout,
      })
    : [React.Fragment]

  const [ErrorComponent, errorStyles, errorScripts] = error
    ? await createComponentStylesAndScripts({
        ctx,
        filePath: error[1],
        getComponent: error[0],
        injectedCSS: injectedCSSWithCurrentLayout,
        injectedJS: injectedJSWithCurrentLayout,
      })
    : []

  const [Loading, loadingStyles, loadingScripts] = loading
    ? await createComponentStylesAndScripts({
        ctx,
        filePath: loading[1],
        getComponent: loading[0],
        injectedCSS: injectedCSSWithCurrentLayout,
        injectedJS: injectedJSWithCurrentLayout,
      })
    : []

  const isLayout = typeof layout !== 'undefined'
  const isPage = typeof page !== 'undefined'
  const { mod: layoutOrPageMod, modType } = await getTracer().trace(
    NextNodeServerSpan.getLayoutOrPageModule,
    {
      hideSpan: !(isLayout || isPage),
      spanName: 'resolve segment modules',
      attributes: {
        'next.segment': segment,
      },
    },
    () => getLayoutOrPageModule(tree)
  )

  const gracefullyDegrade = !!ctx.renderOpts.botType

  /**
   * Checks if the current segment is a root layout.
   */
  const rootLayoutAtThisLevel = isLayout && !rootLayoutIncluded
  /**
   * Checks if the current segment or any level above it has a root layout.
   */
  const rootLayoutIncludedAtThisLevelOrAbove =
    rootLayoutIncluded || rootLayoutAtThisLevel

  const [NotFound, notFoundStyles] = notFound
    ? await createComponentStylesAndScripts({
        ctx,
        filePath: notFound[1],
        getComponent: notFound[0],
        injectedCSS: injectedCSSWithCurrentLayout,
        injectedJS: injectedJSWithCurrentLayout,
      })
    : []

  const [Forbidden, forbiddenStyles] =
    authInterrupts && forbidden
      ? await createComponentStylesAndScripts({
          ctx,
          filePath: forbidden[1],
          getComponent: forbidden[0],
          injectedCSS: injectedCSSWithCurrentLayout,
          injectedJS: injectedJSWithCurrentLayout,
        })
      : []

  const [Unauthorized, unauthorizedStyles] =
    authInterrupts && unauthorized
      ? await createComponentStylesAndScripts({
          ctx,
          filePath: unauthorized[1],
          getComponent: unauthorized[0],
          injectedCSS: injectedCSSWithCurrentLayout,
          injectedJS: injectedJSWithCurrentLayout,
        })
      : []

  let dynamic = layoutOrPageMod?.dynamic

  if (nextConfigOutput === 'export') {
    if (!dynamic || dynamic === 'auto') {
      dynamic = 'error'
    } else if (dynamic === 'force-dynamic') {
      // force-dynamic is always incompatible with 'export'. We must interrupt the build
      throw new StaticGenBailoutError(
        `Page with \`dynamic = "force-dynamic"\` couldn't be exported. \`output: "export"\` requires all pages be renderable statically because there is no runtime server to dynamically render routes in this output format. Learn more: https://nextjs.org/docs/app/building-your-application/deploying/static-exports`
      )
    }
  }

  if (typeof dynamic === 'string') {
    // the nested most config wins so we only force-static
    // if it's configured above any parent that configured
    // otherwise
    if (dynamic === 'error') {
      workStore.dynamicShouldError = true
    } else if (dynamic === 'force-dynamic') {
      workStore.forceDynamic = true

      // TODO: (PPR) remove this bailout once PPR is the default
      if (workStore.isStaticGeneration && !experimental.isRoutePPREnabled) {
        // If the postpone API isn't available, we can't postpone the render and
        // therefore we can't use the dynamic API.
        const err = new DynamicServerError(
          `Page with \`dynamic = "force-dynamic"\` won't be rendered statically.`
        )
        workStore.dynamicUsageDescription = err.message
        workStore.dynamicUsageStack = err.stack
        throw err
      }
    } else {
      workStore.dynamicShouldError = false
      workStore.forceStatic = dynamic === 'force-static'
    }
  }

  if (typeof layoutOrPageMod?.fetchCache === 'string') {
    workStore.fetchCache = layoutOrPageMod?.fetchCache
  }

  if (typeof layoutOrPageMod?.revalidate !== 'undefined') {
    validateRevalidate(layoutOrPageMod?.revalidate, workStore.route)
  }

  if (typeof layoutOrPageMod?.revalidate === 'number') {
    const defaultRevalidate = layoutOrPageMod.revalidate as number

    const workUnitStore = workUnitAsyncStorage.getStore()

    if (workUnitStore) {
      switch (workUnitStore.type) {
        case 'prerender':
        case 'prerender-legacy':
        case 'prerender-ppr':
          if (workUnitStore.revalidate > defaultRevalidate) {
            workUnitStore.revalidate = defaultRevalidate
          }
          break
        case 'request':
          // A request store doesn't have a revalidate property.
          break
        // createComponentTree is not called for these stores:
        case 'cache':
        case 'private-cache':
        case 'prerender-client':
        case 'unstable-cache':
          break
        default:
          workUnitStore satisfies never
      }
    }

    if (
      !workStore.forceStatic &&
      workStore.isStaticGeneration &&
      defaultRevalidate === 0 &&
      // If the postpone API isn't available, we can't postpone the render and
      // therefore we can't use the dynamic API.
      !experimental.isRoutePPREnabled
    ) {
      const dynamicUsageDescription = `revalidate: 0 configured ${segment}`
      workStore.dynamicUsageDescription = dynamicUsageDescription

      throw new DynamicServerError(dynamicUsageDescription)
    }
  }

  const isStaticGeneration = workStore.isStaticGeneration

  // Assume the segment we're rendering contains only partial data if PPR is
  // enabled and this is a statically generated response. This is used by the
  // client Segment Cache after a prefetch to determine if it can skip the
  // second request to fill in the dynamic data.
  //
  // It's OK for this to be `true` when the data is actually fully static, but
  // it's not OK for this to be `false` when the data possibly contains holes.
  // Although the value here is overly pessimistic, for prefetches, it will be
  // replaced by a more specific value when the data is later processed into
  // per-segment responses (see collect-segment-data.tsx)
  //
  // For dynamic requests, this must always be `false` because dynamic responses
  // are never partial.
  const isPossiblyPartialResponse =
    isStaticGeneration && experimental.isRoutePPREnabled === true

  const LayoutOrPage: React.ComponentType<any> | undefined = layoutOrPageMod
    ? interopDefault(layoutOrPageMod)
    : undefined

  /**
   * The React Component to render.
   */
  let MaybeComponent = LayoutOrPage

  if (process.env.NODE_ENV === 'development') {
    const { isValidElementType } =
      require('next/dist/compiled/react-is') as typeof import('next/dist/compiled/react-is')
    if (
      typeof MaybeComponent !== 'undefined' &&
      !isValidElementType(MaybeComponent)
    ) {
      errorMissingDefaultExport(pagePath, modType ?? 'page')
    }

    if (
      typeof ErrorComponent !== 'undefined' &&
      !isValidElementType(ErrorComponent)
    ) {
      errorMissingDefaultExport(pagePath, 'error')
    }

    if (typeof Loading !== 'undefined' && !isValidElementType(Loading)) {
      errorMissingDefaultExport(pagePath, 'loading')
    }

    if (typeof NotFound !== 'undefined' && !isValidElementType(NotFound)) {
      errorMissingDefaultExport(pagePath, 'not-found')
    }

    if (typeof Forbidden !== 'undefined' && !isValidElementType(Forbidden)) {
      errorMissingDefaultExport(pagePath, 'forbidden')
    }

    if (
      typeof Unauthorized !== 'undefined' &&
      !isValidElementType(Unauthorized)
    ) {
      errorMissingDefaultExport(pagePath, 'unauthorized')
    }
  }

  // Handle dynamic segment params.
  const segmentParam = getDynamicParamFromSegment(segment)

  // Create object holding the parent params and current params
  let currentParams: Params = parentParams
  if (segmentParam && segmentParam.value !== null) {
    currentParams = {
      ...parentParams,
      [segmentParam.param]: segmentParam.value,
    }
  }

  // Resolve the segment param
  const actualSegment = segmentParam ? segmentParam.treeSegment : segment
  const isSegmentViewEnabled =
    process.env.NODE_ENV === 'development' &&
    ctx.renderOpts.devtoolSegmentExplorer
  const dir =
    process.env.NEXT_RUNTIME === 'edge'
      ? process.env.__NEXT_EDGE_PROJECT_DIR!
      : ctx.renderOpts.dir || ''

  // Use the same condition to render metadataOutlet as metadata
  const metadataOutlet = StreamingMetadataOutlet ? (
    <StreamingMetadataOutlet />
  ) : (
    <MetadataOutlet ready={getMetadataReady} />
  )

  const [notFoundElement, notFoundFilePath] =
    await createBoundaryConventionElement({
      ctx,
      conventionName: 'not-found',
      Component: NotFound,
      styles: notFoundStyles,
      tree,
    })

  const [forbiddenElement] = await createBoundaryConventionElement({
    ctx,
    conventionName: 'forbidden',
    Component: Forbidden,
    styles: forbiddenStyles,
    tree,
  })

  const [unauthorizedElement] = await createBoundaryConventionElement({
    ctx,
    conventionName: 'unauthorized',
    Component: Unauthorized,
    styles: unauthorizedStyles,
    tree,
  })

  // TODO: Combine this `map` traversal with the loop below that turns the array
  // into an object.
  const parallelRouteMap = await Promise.all(
    Object.keys(parallelRoutes).map(
      async (
        parallelRouteKey
      ): Promise<[string, React.ReactNode, CacheNodeSeedData | null]> => {
        const isChildrenRouteKey = parallelRouteKey === 'children'
        const parallelRoute = parallelRoutes[parallelRouteKey]

        const notFoundComponent = isChildrenRouteKey
          ? notFoundElement
          : undefined

        const forbiddenComponent = isChildrenRouteKey
          ? forbiddenElement
          : undefined

        const unauthorizedComponent = isChildrenRouteKey
          ? unauthorizedElement
          : undefined

        // if we're prefetching and that there's a Loading component, we bail out
        // otherwise we keep rendering for the prefetch.
        // We also want to bail out if there's no Loading component in the tree.
        let childCacheNodeSeedData: CacheNodeSeedData | null = null

        if (
          // Before PPR, the way instant navigations work in Next.js is we
          // prefetch everything up to the first route segment that defines a
          // loading.tsx boundary. (We do the same if there's no loading
          // boundary in the entire tree, because we don't want to prefetch too
          // much) The rest of the tree is deferred until the actual navigation.
          // It does not take into account whether the data is dynamic — even if
          // the tree is completely static, it will still defer everything
          // inside the loading boundary.
          //
          // This behavior predates PPR and is only relevant if the
          // PPR flag is not enabled.
          isPrefetch &&
          (Loading || !hasLoadingComponentInTree(parallelRoute)) &&
          // The approach with PPR is different — loading.tsx behaves like a
          // regular Suspense boundary and has no special behavior.
          //
          // With PPR, we prefetch as deeply as possible, and only defer when
          // dynamic data is accessed. If so, we only defer the nearest parent
          // Suspense boundary of the dynamic data access, regardless of whether
          // the boundary is defined by loading.tsx or a normal <Suspense>
          // component in userspace.
          //
          // NOTE: In practice this usually means we'll end up prefetching more
          // than we were before PPR, which may or may not be considered a
          // performance regression by some apps. The plan is to address this
          // before General Availability of PPR by introducing granular
          // per-segment fetching, so we can reuse as much of the tree as
          // possible during both prefetches and dynamic navigations. But during
          // the beta period, we should be clear about this trade off in our
          // communications.
          !experimental.isRoutePPREnabled
        ) {
          // Don't prefetch this child. This will trigger a lazy fetch by the
          // client router.
        } else {
          // Create the child component

          if (process.env.NODE_ENV === 'development' && missingSlots) {
            // When we detect the default fallback (which triggers a 404), we collect the missing slots
            // to provide more helpful debug information during development mode.
            const parsedTree = parseLoaderTree(parallelRoute)
            if (
              parsedTree.conventionPath?.endsWith(PARALLEL_ROUTE_DEFAULT_PATH)
            ) {
              missingSlots.add(parallelRouteKey)
            }
          }

          const seedData = await createComponentTreeInternal(
            {
              loaderTree: parallelRoute,
              parentParams: currentParams,
              rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove,
              injectedCSS: injectedCSSWithCurrentLayout,
              injectedJS: injectedJSWithCurrentLayout,
              injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout,
              // `getMetadataReady` and `getViewportReady` are used to conditionally throw. In the case of parallel routes we will have more than one page
              // but we only want to throw on the first one.
              getMetadataReady: isChildrenRouteKey
                ? getMetadataReady
                : () => Promise.resolve(),
              getViewportReady: isChildrenRouteKey
                ? getViewportReady
                : () => Promise.resolve(),
              ctx,
              missingSlots,
              preloadCallbacks,
              authInterrupts,
              // `StreamingMetadataOutlet` is used to conditionally throw. In the case of parallel routes we will have more than one page
              // but we only want to throw on the first one.
              StreamingMetadataOutlet: isChildrenRouteKey
                ? StreamingMetadataOutlet
                : null,
            },
            false
          )

          childCacheNodeSeedData = seedData
        }

        const templateNode = (
          <Template>
            <RenderFromTemplateContext />
          </Template>
        )

        const templateFilePath = getConventionPathByType(tree, dir, 'template')
        const errorFilePath = getConventionPathByType(tree, dir, 'error')
        const loadingFilePath = getConventionPathByType(tree, dir, 'loading')
        const globalErrorFilePath = isRoot
          ? getConventionPathByType(tree, dir, 'global-error')
          : undefined

        const wrappedErrorStyles =
          isSegmentViewEnabled && errorFilePath ? (
            <SegmentViewNode type="error" pagePath={errorFilePath}>
              {errorStyles}
            </SegmentViewNode>
          ) : (
            errorStyles
          )

        // Add a suffix to avoid conflict with the segment view node representing rendered file.
        // existence: not-found.tsx@boundary
        // rendered: not-found.tsx
        const fileNameSuffix = BOUNDARY_SUFFIX
        const segmentViewBoundaries = isSegmentViewEnabled ? (
          <>
            {notFoundFilePath && (
              <SegmentViewNode
                type={`${BOUNDARY_PREFIX}not-found`}
                pagePath={notFoundFilePath + fileNameSuffix}
              />
            )}
            {loadingFilePath && (
              <SegmentViewNode
                type={`${BOUNDARY_PREFIX}loading`}
                pagePath={loadingFilePath + fileNameSuffix}
              />
            )}
            {errorFilePath && (
              <SegmentViewNode
                type={`${BOUNDARY_PREFIX}error`}
                pagePath={errorFilePath + fileNameSuffix}
              />
            )}
            {/* Only show global-error when it's the builtin one */}
            {globalErrorFilePath && (
              <SegmentViewNode
                type={`${BOUNDARY_PREFIX}global-error`}
                pagePath={
                  isNextjsBuiltinFilePath(globalErrorFilePath)
                    ? `${BUILTIN_PREFIX}global-error.js${fileNameSuffix}`
                    : globalErrorFilePath
                }
              />
            )}
            {/* do not surface forbidden and unauthorized boundaries yet as they're unstable */}
          </>
        ) : null

        return [
          parallelRouteKey,
          <LayoutRouter
            parallelRouterKey={parallelRouteKey}
            // TODO-APP: Add test for loading returning `undefined`. This currently can't be tested as the `webdriver()` tab will wait for the full page to load before returning.
            error={ErrorComponent}
            errorStyles={wrappedErrorStyles}
            errorScripts={errorScripts}
            template={
              // Only render SegmentViewNode when there's an actual template
              isSegmentViewEnabled && templateFilePath ? (
                <SegmentViewNode type="template" pagePath={templateFilePath}>
                  {templateNode}
                </SegmentViewNode>
              ) : (
                templateNode
              )
            }
            templateStyles={templateStyles}
            templateScripts={templateScripts}
            notFound={notFoundComponent}
            forbidden={forbiddenComponent}
            unauthorized={unauthorizedComponent}
            {...(isSegmentViewEnabled && { segmentViewBoundaries })}
            // Since gracefullyDegrade only applies to bots, only
            // pass it when we're in a bot context to avoid extra bytes.
            {...(gracefullyDegrade && { gracefullyDegrade })}
          />,
          childCacheNodeSeedData,
        ]
      }
    )
  )

  // Convert the parallel route map into an object after all promises have been resolved.
  let parallelRouteProps: { [key: string]: React.ReactNode } = {}
  let parallelRouteCacheNodeSeedData: {
    [key: string]: CacheNodeSeedData | null
  } = {}
  for (const parallelRoute of parallelRouteMap) {
    const [parallelRouteKey, parallelRouteProp, flightData] = parallelRoute
    parallelRouteProps[parallelRouteKey] = parallelRouteProp
    parallelRouteCacheNodeSeedData[parallelRouteKey] = flightData
  }

  let loadingElement = Loading ? <Loading key="l" /> : null
  const loadingFilePath = getConventionPathByType(tree, dir, 'loading')
  if (isSegmentViewEnabled && loadingElement) {
    if (loadingFilePath) {
      loadingElement = (
        <SegmentViewNode
          key={cacheNodeKey + '-loading'}
          type="loading"
          pagePath={loadingFilePath}
        >
          {loadingElement}
        </SegmentViewNode>
      )
    }
  }

  const loadingData: LoadingModuleData = loadingElement
    ? [loadingElement, loadingStyles, loadingScripts]
    : null

  // When the segment does not have a layout or page we still have to add the layout router to ensure the path holds the loading component
  if (!MaybeComponent) {
    return [
      actualSegment,
      <React.Fragment key={cacheNodeKey}>
        {layerAssets}
        {parallelRouteProps.children}
      </React.Fragment>,
      parallelRouteCacheNodeSeedData,
      loadingData,
      isPossiblyPartialResponse,
    ]
  }

  const Component = MaybeComponent
  // If force-dynamic is used and the current render supports postponing, we
  // replace it with a node that will postpone the render. This ensures that the
  // postpone is invoked during the react render phase and not during the next
  // render phase.
  // @TODO this does not actually do what it seems like it would or should do. The idea is that
  // if we are rendering in a force-dynamic mode and we can postpone we should only make the segments
  // that ask for force-dynamic to be dynamic, allowing other segments to still prerender. However
  // because this comes after the children traversal and the static generation store is mutated every segment
  // along the parent path of a force-dynamic segment will hit this condition effectively making the entire
  // render force-dynamic. We should refactor this function so that we can correctly track which segments
  // need to be dynamic
  if (
    workStore.isStaticGeneration &&
    workStore.forceDynamic &&
    experimental.isRoutePPREnabled
  ) {
    return [
      actualSegment,
      <React.Fragment key={cacheNodeKey}>
        <Postpone
          reason='dynamic = "force-dynamic" was used'
          route={workStore.route}
        />
        {layerAssets}
      </React.Fragment>,
      parallelRouteCacheNodeSeedData,
      loadingData,
      true,
    ]
  }

  const isClientComponent = isClientReference(layoutOrPageMod)

  if (
    process.env.NODE_ENV === 'development' &&
    'params' in parallelRouteProps
  ) {
    // @TODO consider making this an error and running the check in build as well
    console.error(
      `"params" is a reserved prop in Layouts and Pages and cannot be used as the name of a parallel route in ${segment}`
    )
  }

  if (isPage) {
    const PageComponent = Component

    // Assign searchParams to props if this is a page
    let pageElement: React.ReactNode
    if (isClientComponent) {
      if (isStaticGeneration) {
        const promiseOfParams =
          createPrerenderParamsForClientSegment(currentParams)
        const promiseOfSearchParams =
          createPrerenderSearchParamsForClientPage(workStore)
        pageElement = (
          <ClientPageRoot
            Component={PageComponent}
            searchParams={query}
            params={currentParams}
            promises={[promiseOfSearchParams, promiseOfParams]}
          />
        )
      } else {
        pageElement = (
          <ClientPageRoot
            Component={PageComponent}
            searchParams={query}
            params={currentParams}
          />
        )
      }
    } else {
      // If we are passing params to a server component Page we need to track
      // their usage in case the current render mode tracks dynamic API usage.
      const params = createServerParamsForServerSegment(
        currentParams,
        workStore
      )

      // If we are passing searchParams to a server component Page we need to
      // track their usage in case the current render mode tracks dynamic API
      // usage.
      let searchParams = createServerSearchParamsForServerPage(query, workStore)

      if (isUseCacheFunction(PageComponent)) {
        const UseCachePageComponent: React.ComponentType<UseCachePageComponentProps> =
          PageComponent

        pageElement = (
          <UseCachePageComponent
            params={params}
            searchParams={searchParams}
            $$isPageComponent
          />
        )
      } else {
        pageElement = (
          <PageComponent params={params} searchParams={searchParams} />
        )
      }
    }

    const isDefaultSegment = segment === DEFAULT_SEGMENT_KEY
    const pageFilePath =
      getConventionPathByType(tree, dir, 'page') ??
      getConventionPathByType(tree, dir, 'defaultPage')
    const segmentType = isDefaultSegment ? 'default' : 'page'
    const wrappedPageElement =
      isSegmentViewEnabled && pageFilePath ? (
        <SegmentViewNode
          key={cacheNodeKey + '-' + segmentType}
          type={segmentType}
          pagePath={pageFilePath}
        >
          {pageElement}
        </SegmentViewNode>
      ) : (
        pageElement
      )

    return [
      actualSegment,
      <React.Fragment key={cacheNodeKey}>
        {wrappedPageElement}
        {layerAssets}
        <OutletBoundary>
          <MetadataOutlet ready={getViewportReady} />
          {metadataOutlet}
        </OutletBoundary>
      </React.Fragment>,
      parallelRouteCacheNodeSeedData,
      loadingData,
      isPossiblyPartialResponse,
    ]
  } else {
    const SegmentComponent = Component
    const isRootLayoutWithChildrenSlotAndAtLeastOneMoreSlot =
      rootLayoutAtThisLevel &&
      'children' in parallelRoutes &&
      Object.keys(parallelRoutes).length > 1

    let segmentNode: React.ReactNode

    if (isClientComponent) {
      let clientSegment: React.ReactNode

      if (isStaticGeneration) {
        const promiseOfParams =
          createPrerenderParamsForClientSegment(currentParams)

        clientSegment = (
          <ClientSegmentRoot
            Component={SegmentComponent}
            slots={parallelRouteProps}
            params={currentParams}
            promise={promiseOfParams}
          />
        )
      } else {
        clientSegment = (
          <ClientSegmentRoot
            Component={SegmentComponent}
            slots={parallelRouteProps}
            params={currentParams}
          />
        )
      }

      if (isRootLayoutWithChildrenSlotAndAtLeastOneMoreSlot) {
        let notfoundClientSegment: React.ReactNode
        let forbiddenClientSegment: React.ReactNode
        let unauthorizedClientSegment: React.ReactNode
        // TODO-APP: This is a hack to support unmatched parallel routes, which will throw `notFound()`.
        // This ensures that a `HTTPAccessFallbackBoundary` is available for when that happens,
        // but it's not ideal, as it needlessly invokes the `NotFound` component and renders the `RootLayout` twice.
        // We should instead look into handling the fallback behavior differently in development mode so that it doesn't
        // rely on the `NotFound` behavior.
        notfoundClientSegment = createErrorBoundaryClientSegmentRoot({
          ErrorBoundaryComponent: NotFound,
          errorElement: notFoundElement,
          ClientSegmentRoot,
          layerAssets,
          SegmentComponent,
          currentParams,
        })
        forbiddenClientSegment = createErrorBoundaryClientSegmentRoot({
          ErrorBoundaryComponent: Forbidden,
          errorElement: forbiddenElement,
          ClientSegmentRoot,
          layerAssets,
          SegmentComponent,
          currentParams,
        })
        unauthorizedClientSegment = createErrorBoundaryClientSegmentRoot({
          ErrorBoundaryComponent: Unauthorized,
          errorElement: unauthorizedElement,
          ClientSegmentRoot,
          layerAssets,
          SegmentComponent,
          currentParams,
        })
        if (
          notfoundClientSegment ||
          forbiddenClientSegment ||
          unauthorizedClientSegment
        ) {
          segmentNode = (
            <HTTPAccessFallbackBoundary
              key={cacheNodeKey}
              notFound={notfoundClientSegment}
              forbidden={forbiddenClientSegment}
              unauthorized={unauthorizedClientSegment}
            >
              {layerAssets}
              {clientSegment}
            </HTTPAccessFallbackBoundary>
          )
        } else {
          segmentNode = (
            <React.Fragment key={cacheNodeKey}>
              {layerAssets}
              {clientSegment}
            </React.Fragment>
          )
        }
      } else {
        segmentNode = (
          <React.Fragment key={cacheNodeKey}>
            {layerAssets}
            {clientSegment}
          </React.Fragment>
        )
      }
    } else {
      const params = createServerParamsForServerSegment(
        currentParams,
        workStore
      )

      let serverSegment: React.ReactNode

      if (isUseCacheFunction(SegmentComponent)) {
        const UseCacheLayoutComponent: React.ComponentType<UseCacheLayoutComponentProps> =
          SegmentComponent

        serverSegment = (
          <UseCacheLayoutComponent
            {...parallelRouteProps}
            params={params}
            $$isLayoutComponent
          />
        )
      } else {
        serverSegment = (
          <SegmentComponent {...parallelRouteProps} params={params} />
        )
      }

      if (isRootLayoutWithChildrenSlotAndAtLeastOneMoreSlot) {
        // TODO-APP: This is a hack to support unmatched parallel routes, which will throw `notFound()`.
        // This ensures that a `HTTPAccessFallbackBoundary` is available for when that happens,
        // but it's not ideal, as it needlessly invokes the `NotFound` component and renders the `RootLayout` twice.
        // We should instead look into handling the fallback behavior differently in development mode so that it doesn't
        // rely on the `NotFound` behavior.
        segmentNode = (
          <HTTPAccessFallbackBoundary
            key={cacheNodeKey}
            notFound={
              notFoundElement ? (
                <>
                  {layerAssets}
                  <SegmentComponent params={params}>
                    {notFoundStyles}
                    {notFoundElement}
                  </SegmentComponent>
                </>
              ) : undefined
            }
          >
            {layerAssets}
            {serverSegment}
          </HTTPAccessFallbackBoundary>
        )
      } else {
        segmentNode = (
          <React.Fragment key={cacheNodeKey}>
            {layerAssets}
            {serverSegment}
          </React.Fragment>
        )
      }
    }

    const layoutFilePath = getConventionPathByType(tree, dir, 'layout')
    const wrappedSegmentNode =
      isSegmentViewEnabled && layoutFilePath ? (
        <SegmentViewNode key="layout" type="layout" pagePath={layoutFilePath}>
          {segmentNode}
        </SegmentViewNode>
      ) : (
        segmentNode
      )

    // For layouts we just render the component
    return [
      actualSegment,
      wrappedSegmentNode,
      parallelRouteCacheNodeSeedData,
      loadingData,
      isPossiblyPartialResponse,
    ]
  }
}

async function MetadataOutlet({
  ready,
}: {
  ready: () => Promise<void> & { status?: string; value?: unknown }
}) {
  const r = ready()
  // We can avoid a extra microtask by unwrapping the instrumented promise directly if available.
  if (r.status === 'rejected') {
    throw r.value
  } else if (r.status !== 'fulfilled') {
    await r
  }
  return null
}
MetadataOutlet.displayName = OUTLET_BOUNDARY_NAME

function createErrorBoundaryClientSegmentRoot({
  ErrorBoundaryComponent,
  errorElement,
  ClientSegmentRoot,
  layerAssets,
  SegmentComponent,
  currentParams,
}: {
  ErrorBoundaryComponent: React.ComponentType<any> | undefined
  errorElement: React.ReactNode
  ClientSegmentRoot: React.ComponentType<any>
  layerAssets: React.ReactNode
  SegmentComponent: React.ComponentType<any>
  currentParams: Params
}) {
  if (ErrorBoundaryComponent) {
    const notFoundParallelRouteProps = {
      children: errorElement,
    }
    return (
      <>
        {layerAssets}
        <ClientSegmentRoot
          Component={SegmentComponent}
          slots={notFoundParallelRouteProps}
          params={currentParams}
        />
      </>
    )
  }
  return null
}

export function getRootParams(
  loaderTree: LoaderTree,
  getDynamicParamFromSegment: GetDynamicParamFromSegment
): Params {
  return getRootParamsImpl({}, loaderTree, getDynamicParamFromSegment)
}

function getRootParamsImpl(
  parentParams: Params,
  loaderTree: LoaderTree,
  getDynamicParamFromSegment: GetDynamicParamFromSegment
): Params {
  const {
    segment,
    modules: { layout },
    parallelRoutes,
  } = parseLoaderTree(loaderTree)

  const segmentParam = getDynamicParamFromSegment(segment)

  let currentParams: Params = parentParams
  if (segmentParam && segmentParam.value !== null) {
    currentParams = {
      ...parentParams,
      [segmentParam.param]: segmentParam.value,
    }
  }

  const isRootLayout = typeof layout !== 'undefined'

  if (isRootLayout) {
    return currentParams
  } else if (!parallelRoutes.children) {
    // This should really be an error but there are bugs in Turbopack that cause
    // the _not-found LoaderTree to not have any layouts. For rootParams sake
    // this is somewhat irrelevant when you are not customizing the 404 page.
    // If you are customizing 404
    // TODO update rootParams to make all params optional if `/app/not-found.tsx` is defined
    return currentParams
  } else {
    return getRootParamsImpl(
      currentParams,
      // We stop looking for root params as soon as we hit the first layout
      // and it is not possible to use parallel route children above the root layout
      // so every parallelRoutes object that this function can visit will necessarily
      // have a single `children` prop and no others.
      parallelRoutes.children,
      getDynamicParamFromSegment
    )
  }
}

async function createBoundaryConventionElement({
  ctx,
  conventionName,
  Component,
  styles,
  tree,
}: {
  ctx: AppRenderContext
  conventionName:
    | 'not-found'
    | 'error'
    | 'loading'
    | 'forbidden'
    | 'unauthorized'
  Component: React.ComponentType<any> | undefined
  styles: React.ReactNode | undefined
  tree: LoaderTree
}) {
  const isSegmentViewEnabled =
    process.env.NODE_ENV === 'development' &&
    ctx.renderOpts.devtoolSegmentExplorer
  const dir =
    process.env.NEXT_RUNTIME === 'edge'
      ? process.env.__NEXT_EDGE_PROJECT_DIR!
      : ctx.renderOpts.dir || ''
  const { SegmentViewNode } = ctx.componentMod
  const element = Component ? (
    <>
      <Component />
      {styles}
    </>
  ) : undefined

  const pagePath = getConventionPathByType(tree, dir, conventionName)

  const wrappedElement =
    isSegmentViewEnabled && element ? (
      <SegmentViewNode
        key={cacheNodeKey + '-' + conventionName}
        type={conventionName}
        pagePath={pagePath!}
      >
        {element}
      </SegmentViewNode>
    ) : (
      element
    )

  return [wrappedElement, pagePath] as const
}