-
Notifications
You must be signed in to change notification settings - Fork 128
Expand file tree
/
Copy pathapp.rs
More file actions
947 lines (861 loc) · 35.1 KB
/
Copy pathapp.rs
File metadata and controls
947 lines (861 loc) · 35.1 KB
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
use anyhow::{Result, bail};
use pack_core::client::context::{
get_client_module_options_context, get_client_resolve_options_context,
get_client_runtime_entries,
};
use pack_core::config::{Platform, ServerEntry};
use pack_core::server_reference::server_reference_module::ServerReferenceModule;
use pack_core::server_reference::server_reference_transition::ServerReferenceTransition;
use rustc_hash::{FxHashMap, FxHashSet};
use pack_core::server::contexts::{
get_server_module_options_context, get_server_resolve_options_context,
};
use pack_core::util::convert_to_project_relative;
use tracing::Instrument;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{Completion, JoinIterExt, ResolvedVc, TryJoinIterExt, ValueToString, Vc};
use turbopack::{
ModuleAssetContext, module_options::ModuleOptionsContext, transition::TransitionOptions,
};
use turbopack_core::chunk::ChunkingContextExt;
use turbopack_core::output::OutputAssetsWithReferenced;
use turbopack_core::resolve::origin::ResolveOrigin;
use turbopack_core::{
chunk::{
ChunkableModule, ChunkingContext, EvaluatableAsset, EvaluatableAssets,
availability_info::AvailabilityInfo,
},
context::AssetContext,
ident::{AssetIdent, Layer},
module::{Module, Modules},
module_graph::{
GraphEntries, GraphTraversalAction, ModuleGraph,
chunk_group_info::{ChunkGroup, ChunkGroupEntry, EntryHeuristics},
},
output::OutputAssets,
reference_type::{EntryReferenceSubType, ReferenceType},
resolve::{origin::PlainResolveOrigin, parse::Request},
};
use crate::{
endpoint::{Endpoint, EndpointOutput, EndpointOutputPaths, Endpoints},
paths::initial_paths_in_root,
project::Project,
};
use turbopack_resolve::resolve_options_context::ResolveOptionsContext;
#[turbo_tasks::value(transparent)]
pub struct AppEntrypoints(pub Vec<AppEntrypoint>);
#[turbo_tasks::value(transparent)]
pub struct ResolvedAppEntrypoints(pub Vec<ResolvedVc<AppEntrypoint>>);
#[turbo_tasks::value]
pub struct AppProject {
pub project: ResolvedVc<Project>,
pub apps: ResolvedVc<AppEntrypoints>,
}
#[turbo_tasks::value(transparent)]
pub struct OptionAppProject(Option<ResolvedVc<AppProject>>);
#[turbo_tasks::value_impl]
impl AppProject {
#[turbo_tasks::function]
pub fn new(project: ResolvedVc<Project>, apps: ResolvedVc<AppEntrypoints>) -> Vc<Self> {
Self { project, apps }.cell()
}
#[turbo_tasks::function]
pub fn apps(&self) -> Vc<AppEntrypoints> {
*self.apps
}
#[turbo_tasks::function]
pub fn project(&self) -> Vc<Project> {
*self.project
}
#[turbo_tasks::function]
pub async fn app_runtime_entries(self: Vc<Self>) -> Result<Vc<EvaluatableAssets>> {
let project = self.project();
match &*project.platform().await? {
Platform::Node => Ok(EvaluatableAssets::empty()),
Platform::Web => {
let watch = project.await?.watch.enable;
Ok(get_client_runtime_entries(
project.project_path().owned().await?,
project.mode(),
project.config(),
project.execution_context(),
project.pack_path().owned().await?,
Vc::cell(watch),
project.client_hmr_enabled(),
)
.resolve_entries(Vc::upcast(self.app_module_context())))
}
}
}
#[turbo_tasks::function]
pub async fn app_module_context(self: Vc<Self>) -> Result<Vc<ModuleAssetContext>> {
let project = self.project();
let platform = &*project.platform().await?;
let layer = match platform {
Platform::Node => {
Layer::new_with_user_friendly_name(rcstr!("server"), rcstr!("Nodejs"))
}
Platform::Web => {
Layer::new_with_user_friendly_name(rcstr!("client"), rcstr!("Browser"))
}
};
// Build transition options, registering "server-reference" when configured
let mut named_transitions: FxHashMap<
RcStr,
ResolvedVc<Box<dyn turbopack::transition::Transition>>,
> = FxHashMap::default();
let server_config = project.config().server().await?;
if server_config.function.is_some() {
let server_module_options_context = get_server_module_options_context(
project.project_path().owned().await?,
project.execution_context(),
project.server_compile_time_info().environment(),
project.mode(),
project.config(),
)
.to_resolved()
.await?;
let server_resolve_options_context = get_server_resolve_options_context(
project.project_path().owned().await?,
project.mode(),
project.config(),
project.config().server_externals_config(),
project.execution_context(),
project.pack_path().owned().await?,
)
.to_resolved()
.await?;
let transition = ServerReferenceTransition::new(
*project.server_compile_time_info().to_resolved().await?,
*server_module_options_context,
*server_resolve_options_context,
)
.to_resolved()
.await?;
named_transitions.insert(rcstr!("server-reference"), ResolvedVc::upcast(transition));
}
let transition_options = TransitionOptions {
named_transitions,
..Default::default()
}
.cell();
Ok(ModuleAssetContext::new(
transition_options,
project.compile_time_info_for_platform(),
self.app_module_options_context(),
self.app_resolve_options_context(),
layer,
))
}
#[turbo_tasks::function]
async fn app_module_options_context(self: Vc<Self>) -> Result<Vc<ModuleOptionsContext>> {
let project = self.project();
match &*project.platform().await? {
Platform::Node => Ok(get_server_module_options_context(
project.project_path().owned().await?,
project.execution_context(),
project.server_compile_time_info().environment(),
project.mode(),
project.config(),
)),
Platform::Web => Ok(get_client_module_options_context(
project.project_path().owned().await?,
project.execution_context(),
project.client_compile_time_info().environment(),
project.mode(),
project.config(),
Vc::cell(project.await?.watch.enable),
project.pack_path().owned().await?,
)),
}
}
#[turbo_tasks::function]
async fn app_resolve_options_context(self: Vc<Self>) -> Result<Vc<ResolveOptionsContext>> {
let project = self.project();
match &*project.platform().await? {
Platform::Node => Ok(get_server_resolve_options_context(
project.project_path().owned().await?,
project.mode(),
project.config(),
project.config().externals_config(),
project.execution_context(),
project.pack_path().owned().await?,
)),
Platform::Web => Ok(get_client_resolve_options_context(
project.project_path().owned().await?,
project.mode(),
project.config(),
project.execution_context(),
project.pack_path().owned().await?,
)),
}
}
#[turbo_tasks::function]
pub async fn resolved_entrypoints(self: Vc<Self>) -> Result<Vc<ResolvedAppEntrypoints>> {
let this = self.await?;
let project = this.project;
let entrypoints = this
.apps
.await?
.iter()
.map(|entrypoint| async move {
AppEntrypoint {
project,
name: entrypoint.name.clone(),
import: entrypoint.import.clone(),
}
.resolved_cell()
})
.join()
.await;
Ok(ResolvedAppEntrypoints(entrypoints).cell())
}
#[turbo_tasks::function]
pub async fn get_app_endpoints(self: Vc<Self>) -> Result<Vc<Endpoints>> {
let app_project = self.to_resolved().await?;
let this = self.await?;
let project = this.project;
let entrypoints = self.resolved_entrypoints().await?.to_vec();
let endpoints = entrypoints
.iter()
.map(|entrypoint| async move {
let endpoint: Vc<Box<dyn Endpoint>> = Vc::upcast(
AppEndpoint {
app_project,
project,
entrypoints: vec![*entrypoint],
}
.cell(),
);
endpoint.to_resolved().await
})
.try_join()
.await?;
Ok(Endpoints(endpoints).cell())
}
}
#[turbo_tasks::value]
pub struct AppEntrypoint {
pub project: ResolvedVc<Project>,
pub name: RcStr,
pub import: RcStr,
}
#[turbo_tasks::value_impl]
impl AppEntrypoint {
#[turbo_tasks::function]
fn project(&self) -> Vc<Project> {
*self.project
}
#[turbo_tasks::function]
pub async fn app_entry_modules(
self: Vc<Self>,
asset_context: Vc<Box<dyn AssetContext>>,
) -> Result<Vc<Modules>> {
let this = self.await?;
// Handle import path: convert absolute path to relative, keep relative path as-is
let relative_import =
convert_to_project_relative(&this.import, &self.project().project_path().await?.path)?;
let entry_request = Request::relative(
relative_import.into(),
Default::default(),
Default::default(),
false,
);
let origin = PlainResolveOrigin::new(
asset_context,
self.project().project_path().await?.join("_")?,
)
.await?;
let resolve_options = origin.resolve_options();
let asset_context = origin.asset_context();
let origin_path = origin.origin_path();
let ty = ReferenceType::Entry(EntryReferenceSubType::Undefined);
Ok(Vc::cell(
asset_context
.resolve_asset(origin_path, entry_request, resolve_options, ty)
.await?
.primary_modules()
.await?,
))
}
#[turbo_tasks::function]
pub async fn entry_evaluatable_assets(
self: Vc<Self>,
asset_context: Vc<Box<dyn AssetContext>>,
runtime_entries: Vc<EvaluatableAssets>,
) -> Result<Vc<EvaluatableAssets>> {
let runtime_entries = runtime_entries.await?;
let modules = self.app_entry_modules(asset_context).await?;
let mut all_runtime_entries = Vec::with_capacity(modules.len() + runtime_entries.len());
all_runtime_entries.extend(runtime_entries.iter().map(|e| **e));
for &module in &modules {
if let Some(entry) = ResolvedVc::try_downcast::<Box<dyn EvaluatableAsset>>(module) {
all_runtime_entries.push(*entry);
} else {
bail!(
"runtime reference resolved to an asset ({}) that cannot be evaluated",
module.ident().to_string().await?
);
}
}
Ok(EvaluatableAssets::many(all_runtime_entries))
}
#[turbo_tasks::function]
pub async fn module_graph_for_entry(
self: Vc<Self>,
asset_context: Vc<Box<dyn AssetContext>>,
runtime_entries: Vc<EvaluatableAssets>,
) -> Result<Vc<ModuleGraph>> {
let project = self.project();
let evaluatable_assets = self.entry_evaluatable_assets(asset_context, runtime_entries);
Ok(project.module_graph_for_modules(evaluatable_assets))
}
#[turbo_tasks::function]
async fn client_chunk_group(
self: Vc<Self>,
asset_context: Vc<Box<dyn AssetContext>>,
runtime_entries: Vc<EvaluatableAssets>,
) -> Result<Vc<OutputAssetsWithReferenced>> {
async move {
let this = self.await?;
let project = self.project();
let module_graph = self.module_graph_for_entry(asset_context, runtime_entries);
let query = format!("?name={}", this.name);
let app_chunk_group = project
.client_chunking_context()
.evaluated_chunk_group_assets(
AssetIdent::from_path(
project.project_path().await?.join(this.import.as_str())?,
)
.with_query(query.into())
.into_vc(),
ChunkGroup::Entry(
self.entry_evaluatable_assets(asset_context, runtime_entries)
.await?
.iter()
.map(|m| ResolvedVc::upcast(*m))
.collect(),
),
module_graph,
OutputAssets::empty(),
AvailabilityInfo::root(),
);
Ok(app_chunk_group)
}
.instrument(tracing::trace_span!("app chunk rendering"))
.await
}
#[turbo_tasks::function]
async fn server_chunk_group(
self: Vc<Self>,
asset_context: Vc<Box<dyn AssetContext>>,
runtime_entries: Vc<EvaluatableAssets>,
) -> Result<Vc<OutputAssetsWithReferenced>> {
async move {
let this = self.await?;
let project = self.project();
let module_graph = self.module_graph_for_entry(asset_context, runtime_entries);
let name = if this.name.ends_with(".js") {
this.name.as_str()
} else {
&format!("{}.js", this.name)
};
let app_chunk_group = project
.server_chunking_context()
.entry_chunk_group(
project.dist_root().owned().await?.join(name)?,
ChunkGroup::Entry(
self.entry_evaluatable_assets(asset_context, runtime_entries)
.await?
.iter()
.map(|m| ResolvedVc::upcast(*m))
.collect(),
),
module_graph,
OutputAssets::empty(),
OutputAssets::empty(),
AvailabilityInfo::root(),
)
.await?;
Ok(OutputAssetsWithReferenced {
assets: ResolvedVc::cell(vec![app_chunk_group.asset]),
referenced_assets: ResolvedVc::cell(vec![]),
references: ResolvedVc::cell(vec![]),
}
.cell())
}
.instrument(tracing::trace_span!("app chunk rendering"))
.await
}
#[turbo_tasks::function]
pub async fn output_assets_for_entry(
self: Vc<Self>,
asset_context: Vc<Box<dyn AssetContext>>,
runtime_entries: Vc<EvaluatableAssets>,
) -> Result<Vc<OutputAssets>> {
let chunk_group_assets = match &*self.project().platform().await? {
Platform::Node => {
*self
.server_chunk_group(asset_context, runtime_entries)
.await?
.assets
}
Platform::Web => {
*self
.client_chunk_group(asset_context, runtime_entries)
.await?
.assets
}
};
Ok(chunk_group_assets)
}
}
#[turbo_tasks::value]
pub struct AppEndpoint {
app_project: ResolvedVc<AppProject>,
project: ResolvedVc<Project>,
pub entrypoints: Vec<ResolvedVc<AppEntrypoint>>,
}
#[turbo_tasks::value_impl]
impl AppEndpoint {
#[turbo_tasks::function]
pub fn project(&self) -> Vc<Project> {
*self.project
}
}
#[turbo_tasks::value_impl]
impl Endpoint for AppEndpoint {
#[turbo_tasks::function]
async fn entries(self: Vc<Self>) -> Result<Vc<GraphEntries>> {
let this = self.await?;
let asset_context = this.app_project.app_module_context();
let runtime_entries = this.app_project.app_runtime_entries();
let entries = this
.entrypoints
.iter()
.map(|e| async {
let entry_modules = e
.entry_evaluatable_assets(Vc::upcast(asset_context), runtime_entries)
.await?
.iter()
.copied()
.map(ResolvedVc::upcast)
.collect();
Ok(ChunkGroupEntry::Entry {
modules: entry_modules,
heuristics: EntryHeuristics::default(),
})
})
.try_join()
.await?;
Ok(GraphEntries::from_chunk_groups(entries).cell())
}
#[turbo_tasks::function]
async fn output(self: Vc<Self>) -> Result<Vc<EndpointOutput>> {
async move {
let this = self.await?;
let asset_context = this.app_project.app_module_context();
let runtime_entries = this.app_project.app_runtime_entries();
let client_output_assets = {
let mut vcs = this
.entrypoints
.iter()
.map(|e| e.output_assets_for_entry(Vc::upcast(asset_context), runtime_entries))
.collect::<Vec<_>>();
// Copy assets are project-level output. Include the shared task in every
// endpoint so writing any endpoint independently preserves the historical
// aggregated-endpoint behavior. The all-endpoints path deduplicates assets.
vcs.push(this.project.copy_output_assets());
OutputAssets::concat(vcs)
};
// Build server functions as Node.js if configured
let server_config = this.project.config().server().await?;
let server_output = if server_config.function.is_some()
|| server_config
.entry
.as_ref()
.is_some_and(|entry| entry.has_entries())
{
Some(this.app_project.server_output_assets())
} else {
None
};
let dist_root_vc = this.project.dist_root();
let (client_paths, server_output) = futures::future::try_join(
async {
Ok::<_, anyhow::Error>(
initial_paths_in_root(client_output_assets, dist_root_vc)
.await?
.iter()
.cloned()
.collect(),
)
},
async {
match server_output {
Some(server_output) => {
// Drive the independent Server build concurrently with Client path
// discovery while preserving the Vc for the final asset union.
server_output.await?;
Ok(Some(server_output))
}
None => Ok(None),
}
},
)
.await?;
let dist_root = dist_root_vc.await?;
let written_endpoint = EndpointOutputPaths::NodeJs {
server_entry_path: dist_root.path.clone(),
server_paths: vec![],
client_paths,
};
let mut output_assets = client_output_assets;
if let Some(server_output) = server_output {
output_assets = output_assets.concatenate(server_output);
}
Ok(EndpointOutput {
output_assets: output_assets.to_resolved().await?,
output_paths: written_endpoint.resolved_cell(),
project: this.project,
}
.cell())
}
.instrument(tracing::trace_span!("app_output"))
.await
}
#[turbo_tasks::function]
async fn server_changed(self: Vc<Self>) -> Result<Vc<Completion>> {
let this = self.await?;
let server_config = this.project.config().server().await?;
if *this.project.platform().await? == Platform::Web
&& server_config.function.is_none()
&& !server_config
.entry
.as_ref()
.is_some_and(|entry| entry.has_entries())
{
return Ok(Completion::new());
}
let EndpointOutput {
output_assets,
project,
..
} = *self.output().await?;
Ok(project.server_changed(*output_assets))
}
#[turbo_tasks::function]
async fn client_changed(self: Vc<Self>) -> Result<Vc<Completion>> {
let this = self.await?;
if *this.project.platform().await? == Platform::Node {
return Ok(Completion::new());
}
let EndpointOutput {
output_assets,
project,
..
} = *self.output().await?;
Ok(project.client_changed(*output_assets))
}
}
/// Server function build support
#[turbo_tasks::value_impl]
impl AppProject {
/// Discovers `ServerReferenceModule`s in the client module graph and builds
/// their inner server modules as Node.js chunks.
#[turbo_tasks::function]
async fn server_output_assets(self: Vc<Self>) -> Result<Vc<OutputAssets>> {
let this = self.await?;
let project = *this.project;
let entrypoints = self.resolved_entrypoints().await?.to_vec();
let asset_context = Vc::upcast(self.app_module_context());
let runtime_entries = self.app_runtime_entries();
let server_config = project.config().server().await?;
let server_function_assets: Vec<ResolvedVc<Box<dyn EvaluatableAsset>>> =
if server_config.function.is_some() {
// Await all graphs simultaneously for better parallelization.
let resolved_graphs = entrypoints
.iter()
.map(|e| async {
e.module_graph_for_entry(asset_context, runtime_entries)
.await
})
.try_join()
.await?;
// Walk all graphs to find ServerReferenceModule instances.
let mut unique_server_modules = turbo_tasks::FxIndexSet::default();
for graph in &resolved_graphs {
for module in graph.iter_nodes() {
if let Some(server_ref) =
ResolvedVc::try_downcast_type::<ServerReferenceModule>(module)
{
let inner = server_ref.await?;
unique_server_modules.insert(inner.server_module);
}
}
}
// Resolving VCs to strings for a deterministic sorting pass guarantees our
// AST chunk hashes remain tightly identical between runs, following Next.js's
// FxIndexMap/IndexSet pattern for chunking server routines.
let mut pairs = unique_server_modules
.into_iter()
.map(|m| async move { Ok((m.ident().to_string().await?, m)) })
.try_join()
.await?;
pairs.sort_by(|a, b| a.0.cmp(&b.0));
let server_modules: Vec<_> = pairs.into_iter().map(|(_, m)| m).collect();
server_modules
.iter()
.filter_map(|m| ResolvedVc::try_sidecast::<Box<dyn EvaluatableAsset>>(*m))
.collect()
} else {
// A plain server entry does not use the server-reference transition, so its
// build can start without waiting for every client module graph.
Vec::new()
};
let mut entry_specs = Vec::new();
if let Some(entry) = &server_config.entry {
match entry {
ServerEntry::Import(import) => {
entry_specs.push((rcstr!("index"), Some(import.clone()), true, false));
}
ServerEntry::Entries(entries) => {
entry_specs.extend(entries.iter().enumerate().map(|(index, entry)| {
(
entry.name.clone(),
Some(entry.import.clone()),
index == 0,
true,
)
}));
}
}
}
if entry_specs.is_empty() && !server_function_assets.is_empty() {
entry_specs.push((rcstr!("index"), None, true, false));
}
let mut entry_names = turbo_tasks::FxIndexSet::default();
for (name, _, _, _) in &entry_specs {
if !entry_names.insert(name.clone()) {
bail!("duplicate server entry name `{name}`");
}
}
let server_asset_context = if entry_specs.iter().any(|(_, import, _, _)| import.is_some()) {
let server_layer =
Layer::new_with_user_friendly_name(rcstr!("server"), rcstr!("Nodejs"));
let server_compile_time_info = project.server_compile_time_info();
let server_module_options_context = get_server_module_options_context(
project.project_path().owned().await?,
project.execution_context(),
project.server_compile_time_info().environment(),
project.mode(),
project.config(),
);
let server_resolve_options_context = get_server_resolve_options_context(
project.project_path().owned().await?,
project.mode(),
project.config(),
project.config().server_externals_config(),
project.execution_context(),
project.pack_path().owned().await?,
);
Some(Vc::upcast(ModuleAssetContext::new(
TransitionOptions::default().cell(),
server_compile_time_info,
server_module_options_context,
server_resolve_options_context,
server_layer,
)))
} else {
None
};
let project_path = project.project_path().owned().await?;
let mut build_entries = Vec::new();
for (name, entry_import, include_server_functions, preserve_entry_name) in entry_specs {
let mut evaluatable_assets = if include_server_functions {
server_function_assets.clone()
} else {
Vec::new()
};
if let Some(entry_import) = entry_import {
let relative_import =
convert_to_project_relative(&entry_import, &project_path.path)?;
let entry_request = Request::relative(
relative_import.into(),
Default::default(),
Default::default(),
false,
);
let origin = PlainResolveOrigin::new(
server_asset_context.expect("server asset context is created for imports"),
project_path.join("_")?,
)
.await?;
let resolve_options = origin.resolve_options();
let asset_context = origin.asset_context();
let origin_path = origin.origin_path();
let ty = ReferenceType::Entry(EntryReferenceSubType::Undefined);
let modules = asset_context
.resolve_asset(origin_path, entry_request, resolve_options, ty)
.await?
.primary_modules()
.await?;
for &module in &*modules {
if let Some(entry) =
ResolvedVc::try_downcast::<Box<dyn EvaluatableAsset>>(module)
{
evaluatable_assets.push(entry);
}
}
}
if evaluatable_assets.is_empty() {
bail!("server entry `{name}` did not resolve to an evaluatable module");
}
build_entries.push((name, evaluatable_assets, preserve_entry_name));
}
if build_entries.is_empty() {
return Ok(OutputAssets::empty());
}
// Build one graph for all server entries so shared modules can be identified across
// independently emitted entry chunk groups.
let entry_modules = build_entries
.iter()
.map(|(_, assets, _)| {
assets
.iter()
.map(|entry| ResolvedVc::upcast(*entry))
.collect::<Vec<ResolvedVc<Box<dyn Module>>>>()
})
.collect::<Vec<_>>();
let all_entry_modules = entry_modules.iter().flatten().copied().collect::<Vec<_>>();
let initial_server_module_graph =
project.server_fn_module_graph(Vc::cell(all_entry_modules.clone()));
let initial_module_graph = initial_server_module_graph.await?;
let mut module_usage = FxHashMap::default();
for (entry_index, modules) in entry_modules.iter().enumerate() {
initial_module_graph.traverse_nodes_dfs(
modules.iter().copied(),
&mut module_usage,
|module, usage| {
usage
.entry(module)
.or_insert_with(Vec::new)
.push(entry_index);
Ok(GraphTraversalAction::Continue)
},
|_, _| Ok(()),
)?;
}
let entry_module_set = all_entry_modules.iter().copied().collect::<FxHashSet<_>>();
let mut shared_module_groups = FxHashMap::default();
for (module, entry_indices) in module_usage {
if entry_indices.len() <= 1 || entry_module_set.contains(&module) {
continue;
}
if let Some(module) = ResolvedVc::try_sidecast::<Box<dyn ChunkableModule>>(module) {
shared_module_groups
.entry(entry_indices)
.or_insert_with(Vec::new)
.push(module);
}
}
let mut shared_module_groups = shared_module_groups.into_iter().collect::<Vec<_>>();
// A shared module's dependencies are used by at least the same entries, so build wider
// groups first and make them available to the narrower groups that depend on them.
shared_module_groups.sort_by(|(a, _), (b, _)| b.len().cmp(&a.len()).then_with(|| a.cmp(b)));
let shared_modules = shared_module_groups
.iter()
.flat_map(|(_, modules)| modules.iter().copied())
.collect::<Vec<_>>();
// Shared modules are graph roots too, allowing their chunk group to be emitted first and
// marked available while each entry chunk is constructed.
let server_module_graph = if shared_modules.is_empty() {
initial_server_module_graph
} else {
let mut graph_entries = all_entry_modules;
graph_entries.extend(
shared_modules
.iter()
.map(|module| ResolvedVc::upcast(*module)),
);
project.server_fn_module_graph(Vc::cell(graph_entries))
};
let server_chunking_context = project.server_fn_chunking_context();
let mut entry_availability = AvailabilityInfo::root();
let mut shared_assets_by_entry = vec![Vec::<Vc<OutputAssets>>::new(); build_entries.len()];
for (entry_indices, shared_modules) in shared_module_groups {
let shared_name: RcStr = if entry_indices.len() == build_entries.len() {
rcstr!("server-shared")
} else {
format!(
"server-shared-{}",
entry_indices
.iter()
.map(usize::to_string)
.collect::<Vec<_>>()
.join("-")
)
.into()
};
let shared_ident =
AssetIdent::from_path(project_path.join(&format!("{shared_name}.js"))?)
.with_query(format!("?name={shared_name}").into())
.into_vc();
let shared_group = server_chunking_context
.chunk_group(
shared_ident,
ChunkGroup::Entry(
shared_modules
.iter()
.map(|module| ResolvedVc::upcast(*module))
.collect(),
),
server_module_graph,
entry_availability,
)
.await?;
entry_availability = shared_group.availability_info;
for entry_index in entry_indices {
shared_assets_by_entry[entry_index].push(*shared_group.assets);
}
}
let output_assets = build_entries
.iter()
.enumerate()
.map(
|(entry_index, (name, evaluatable_assets, preserve_entry_name))| {
let project_path = project_path.clone();
let shared_assets =
OutputAssets::concat(shared_assets_by_entry[entry_index].clone());
async move {
let modules = evaluatable_assets
.iter()
.map(|entry| ResolvedVc::upcast(*entry))
.collect();
let chunk_query = if *preserve_entry_name {
format!("?name={name}&preserveEntryName=1")
} else {
format!("?name={name}")
};
let ident =
AssetIdent::from_path(project_path.join(&format!("{name}.js"))?)
.with_query(chunk_query.into())
.into_vc();
let chunk_group_result = server_chunking_context
.evaluated_chunk_group(
ident,
ChunkGroup::Entry(modules),
server_module_graph,
shared_assets,
entry_availability,
)
.await?;
Ok(*chunk_group_result.assets)
}
},
)
.try_join()
.await?;
Ok(OutputAssets::concat(output_assets))
}
}