1pub mod client_reference_manifest;
4mod encode_uri_component;
5
6use anyhow::{Context, Result};
7use bincode::{Decode, Encode};
8use serde::{Deserialize, Serialize};
9use serde_json::value::RawValue;
10use turbo_rcstr::RcStr;
11use turbo_tasks::{FxIndexMap, ReadRef, ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt, Vc};
12use turbo_tasks_fs::{File, FileContent, FileSystemPath};
13use turbopack_core::{
14 asset::{Asset, AssetContent},
15 json::RcJsonRawValue,
16 output::{OutputAsset, OutputAssets, OutputAssetsReference, OutputAssetsWithReferenced},
17};
18
19use crate::next_config::RouteHas;
20
21#[derive(Serialize, Default, Debug)]
22pub struct PagesManifest {
23 #[serde(flatten)]
24 pub pages: FxIndexMap<RcStr, RcStr>,
25}
26
27#[derive(Debug)]
28#[turbo_tasks::value(shared)]
29pub struct BuildManifest {
30 pub output_path: FileSystemPath,
31 pub client_relative_path: FileSystemPath,
32
33 pub polyfill_files: Vec<ResolvedVc<Box<dyn OutputAsset>>>,
34 pub root_main_files: Vec<ResolvedVc<Box<dyn OutputAsset>>>,
35 #[bincode(with = "turbo_bincode::indexmap")]
36 pub pages: FxIndexMap<RcStr, ResolvedVc<OutputAssets>>,
37 #[bincode(with = "turbo_bincode::indexmap")]
42 pub root_main_files_per_page: FxIndexMap<RcStr, Vec<ResolvedVc<Box<dyn OutputAsset>>>>,
43 #[bincode(with = "turbo_bincode::indexmap")]
46 pub pages_chunk_group_bootstrap_params: FxIndexMap<RcStr, RcJsonRawValue>,
47 pub chunk_loading_global: RcStr,
49}
50
51#[turbo_tasks::value_impl]
52impl OutputAssetsReference for BuildManifest {
53 #[turbo_tasks::function]
54 async fn references(&self) -> Result<Vc<OutputAssetsWithReferenced>> {
55 let chunks: Vec<ReadRef<OutputAssets>> = self.pages.values().try_join().await?;
56
57 let root_main_files = self
58 .root_main_files
59 .iter()
60 .map(async |c| Ok(c.path().await?.has_extension(".js").then_some(*c)))
61 .try_flat_join()
62 .await?;
63
64 let per_page_files = self
65 .root_main_files_per_page
66 .values()
67 .flatten()
68 .copied()
69 .collect::<Vec<_>>();
70
71 let references = chunks
72 .into_iter()
73 .flatten()
74 .chain(root_main_files)
75 .chain(self.polyfill_files.iter().copied())
76 .chain(per_page_files)
77 .collect();
78
79 Ok(OutputAssetsWithReferenced::from_assets(Vc::cell(
80 references,
81 )))
82 }
83}
84
85#[turbo_tasks::value_impl]
86impl OutputAsset for BuildManifest {
87 #[turbo_tasks::function]
88 async fn path(&self) -> Vc<FileSystemPath> {
89 self.output_path.clone().cell()
90 }
91}
92
93#[turbo_tasks::value_impl]
94impl Asset for BuildManifest {
95 #[turbo_tasks::function]
96 async fn content(&self) -> Result<Vc<AssetContent>> {
97 let client_relative_path = &self.client_relative_path;
98
99 #[derive(Serialize, Default, Debug)]
100 #[serde(rename_all = "camelCase")]
101 pub struct SerializedBuildManifest<'a> {
102 pub dev_files: Vec<RcStr>,
103 pub amp_dev_files: Vec<RcStr>,
104 pub polyfill_files: Vec<RcStr>,
105 pub low_priority_files: Vec<RcStr>,
106 pub root_main_files: Vec<RcStr>,
107 pub pages: FxIndexMap<RcStr, Vec<RcStr>>,
108 pub amp_first_pages: Vec<RcStr>,
109 pub root_main_files_tree: FxIndexMap<RcStr, Vec<RcStr>>,
110 pub pages_chunk_group_bootstrap_params: FxIndexMap<RcStr, &'a RawValue>,
112 pub chunk_loading_global: RcStr,
113 }
114
115 let pages: Vec<(RcStr, Vec<RcStr>)> = self
116 .pages
117 .iter()
118 .map(async |(k, chunks)| {
119 Ok((
120 k.clone(),
121 chunks
122 .await?
123 .iter()
124 .copied()
125 .map(async |chunk| {
126 let chunk_path = chunk.path().await?;
127 Ok(client_relative_path
128 .get_path_to(&chunk_path)
129 .context("client chunk entry path must be inside the client root")?
130 .into())
131 })
132 .try_join()
133 .await?,
134 ))
135 })
136 .try_join()
137 .await?;
138
139 let polyfill_files: Vec<RcStr> = self
140 .polyfill_files
141 .iter()
142 .copied()
143 .map(async |chunk| {
144 let chunk_path = chunk.path().await?;
145 Ok(client_relative_path
146 .get_path_to(&chunk_path)
147 .context("failed to resolve client-relative path to polyfill")?
148 .into())
149 })
150 .try_join()
151 .await?;
152
153 let root_main_files: Vec<RcStr> = self
154 .root_main_files
155 .iter()
156 .map(async |chunk| {
157 let chunk_path = chunk.path().await?;
158 if !chunk_path.has_extension(".js") {
159 Ok(None)
160 } else {
161 Ok(Some(
162 client_relative_path
163 .get_path_to(&chunk_path)
164 .context("failed to resolve client-relative path to root_main_file")?
165 .into(),
166 ))
167 }
168 })
169 .try_flat_join()
170 .await?;
171
172 let root_main_files_tree: Vec<(RcStr, Vec<RcStr>)> = self
173 .root_main_files_per_page
174 .iter()
175 .map(async |(page, per_page_chunks)| {
176 let per_page_paths: Vec<RcStr> = per_page_chunks
177 .iter()
178 .copied()
179 .map(async |chunk| {
180 let chunk_path = chunk.path().await?;
181 Ok(client_relative_path
182 .get_path_to(&chunk_path)
183 .context(
184 "failed to resolve client-relative path to per-page root file",
185 )?
186 .into())
187 })
188 .try_join()
189 .await?;
190 let combined = root_main_files
193 .iter()
194 .cloned()
195 .chain(per_page_paths)
196 .collect();
197 Ok((page.clone(), combined))
198 })
199 .try_join()
200 .await?;
201
202 let manifest = SerializedBuildManifest {
203 pages: FxIndexMap::from_iter(pages),
204 polyfill_files,
205 root_main_files,
206 root_main_files_tree: FxIndexMap::from_iter(root_main_files_tree),
207 pages_chunk_group_bootstrap_params: self
208 .pages_chunk_group_bootstrap_params
209 .iter()
210 .map(|(k, v)| (k.clone(), &**v))
211 .collect(),
212 chunk_loading_global: self.chunk_loading_global.clone(),
213 ..Default::default()
214 };
215
216 Ok(AssetContent::file(
217 FileContent::Content(File::from(serde_json::to_string_pretty(&manifest)?)).cell(),
218 ))
219 }
220}
221
222#[derive(Debug)]
223#[turbo_tasks::value(shared)]
224pub struct ClientBuildManifest {
225 pub output_path: FileSystemPath,
226 pub client_relative_path: FileSystemPath,
227
228 #[bincode(with = "turbo_bincode::indexmap")]
229 pub pages: FxIndexMap<RcStr, ResolvedVc<Box<dyn OutputAsset>>>,
230}
231
232#[turbo_tasks::value_impl]
233impl OutputAssetsReference for ClientBuildManifest {
234 #[turbo_tasks::function]
235 async fn references(&self) -> Result<Vc<OutputAssetsWithReferenced>> {
236 let chunks: Vec<ResolvedVc<Box<dyn OutputAsset>>> = self.pages.values().copied().collect();
237 Ok(OutputAssetsWithReferenced::from_assets(Vc::cell(chunks)))
238 }
239}
240
241#[turbo_tasks::value_impl]
242impl OutputAsset for ClientBuildManifest {
243 #[turbo_tasks::function]
244 async fn path(&self) -> Vc<FileSystemPath> {
245 self.output_path.clone().cell()
246 }
247}
248
249#[turbo_tasks::value_impl]
250impl Asset for ClientBuildManifest {
251 #[turbo_tasks::function]
252 async fn content(&self) -> Result<Vc<AssetContent>> {
253 let client_relative_path = &self.client_relative_path;
254
255 let manifest: FxIndexMap<RcStr, Vec<RcStr>> = self
256 .pages
257 .iter()
258 .map(async |(k, chunk)| {
259 Ok((
260 k.clone(),
261 vec![
262 client_relative_path
263 .get_path_to(&*chunk.path().await?)
264 .context("client chunk entry path must be inside the client root")?
265 .into(),
266 ],
267 ))
268 })
269 .try_join()
270 .await?
271 .into_iter()
272 .collect();
273
274 Ok(AssetContent::file(
275 FileContent::Content(File::from(serde_json::to_string_pretty(&manifest)?)).cell(),
276 ))
277 }
278}
279
280#[derive(Serialize, Debug)]
281#[serde(rename_all = "camelCase", tag = "version")]
282#[allow(clippy::large_enum_variant)]
283pub enum MiddlewaresManifest {
284 #[serde(rename = "2")]
285 MiddlewaresManifestV2(MiddlewaresManifestV2),
286 #[serde(other)]
287 Unsupported,
288}
289
290impl Default for MiddlewaresManifest {
291 fn default() -> Self {
292 Self::MiddlewaresManifestV2(Default::default())
293 }
294}
295
296#[turbo_tasks::task_input]
297#[derive(
298 Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize, Encode, Decode,
299)]
300#[serde(rename_all = "camelCase", default)]
301pub struct ProxyMatcher {
302 #[serde(skip_serializing_if = "Option::is_none")]
304 pub regexp: Option<RcStr>,
305 #[serde(skip_serializing_if = "bool_is_true")]
306 pub locale: bool,
307 #[serde(skip_serializing_if = "Option::is_none")]
308 pub has: Option<Vec<RouteHas>>,
309 #[serde(skip_serializing_if = "Option::is_none")]
310 pub missing: Option<Vec<RouteHas>>,
311 pub original_source: RcStr,
312}
313
314impl Default for ProxyMatcher {
315 fn default() -> Self {
316 Self {
317 regexp: None,
318 locale: true,
319 has: None,
320 missing: None,
321 original_source: Default::default(),
322 }
323 }
324}
325
326fn bool_is_true(b: &bool) -> bool {
327 *b
328}
329
330#[derive(Serialize, Default, Debug)]
331pub struct EdgeFunctionDefinition {
332 pub files: Vec<RcStr>,
333 pub name: RcStr,
334 pub page: RcStr,
335 pub entrypoint: RcStr,
336 pub matchers: Vec<ProxyMatcher>,
337 pub wasm: Vec<AssetBinding>,
338 pub assets: Vec<AssetBinding>,
339 #[serde(skip_serializing_if = "Option::is_none")]
340 pub regions: Option<Regions>,
341 pub env: FxIndexMap<RcStr, RcStr>,
342}
343
344#[derive(Serialize, Default, Debug)]
345pub struct InstrumentationDefinition {
346 pub files: Vec<RcStr>,
347 pub name: RcStr,
348 #[serde(skip_serializing_if = "Vec::is_empty")]
349 pub wasm: Vec<AssetBinding>,
350 #[serde(skip_serializing_if = "Vec::is_empty")]
351 pub assets: Vec<AssetBinding>,
352}
353
354#[derive(Serialize, Default, Debug)]
355#[serde(rename_all = "camelCase")]
356pub struct AssetBinding {
357 pub name: RcStr,
358 pub file_path: RcStr,
359}
360
361#[derive(Serialize, Debug)]
362#[serde(untagged)]
363pub enum Regions {
364 Multiple(Vec<RcStr>),
365 Single(RcStr),
366}
367
368#[derive(Serialize, Default, Debug)]
369pub struct MiddlewaresManifestV2 {
370 pub sorted_middleware: Vec<RcStr>,
371 pub middleware: FxIndexMap<RcStr, EdgeFunctionDefinition>,
372 pub instrumentation: Option<InstrumentationDefinition>,
373 pub functions: FxIndexMap<RcStr, EdgeFunctionDefinition>,
374}
375
376#[derive(Serialize, Default, Debug)]
377#[serde(rename_all = "camelCase")]
378pub struct ReactLoadableManifest {
379 #[serde(flatten)]
380 pub manifest: FxIndexMap<RcStr, ReactLoadableManifestEntry>,
381}
382
383#[derive(Serialize, Default, Debug)]
384#[serde(rename_all = "camelCase")]
385pub struct ReactLoadableManifestEntry {
386 pub id: u32,
387 pub files: Vec<RcStr>,
388}
389
390#[derive(Serialize, Default, Debug)]
391#[serde(rename_all = "camelCase")]
392pub struct NextFontManifest {
393 pub pages: FxIndexMap<RcStr, Vec<RcStr>>,
394 pub app: FxIndexMap<RcStr, Vec<RcStr>>,
395 pub app_using_size_adjust: bool,
396 pub pages_using_size_adjust: bool,
397}
398
399#[derive(Serialize, Default, Debug)]
400#[serde(rename_all = "camelCase")]
401pub struct AppPathsManifest {
402 #[serde(flatten)]
403 pub edge_server_app_paths: PagesManifest,
404 #[serde(flatten)]
405 pub node_server_app_paths: PagesManifest,
406}
407
408#[derive(Serialize, Debug)]
413#[serde(rename_all = "camelCase")]
414pub struct LoadableManifest {
415 pub id: ModuleId,
416 pub files: Vec<RcStr>,
417}
418
419#[derive(Serialize, Default, Debug)]
420#[serde(rename_all = "camelCase")]
421pub struct ServerReferenceManifest<'a> {
422 pub node: FxIndexMap<&'a str, ActionManifestEntry<'a>>,
424 pub edge: FxIndexMap<&'a str, ActionManifestEntry<'a>>,
426}
427
428#[derive(Serialize, Default, Debug)]
429#[serde(rename_all = "camelCase")]
430pub struct ActionManifestEntry<'a> {
431 pub workers: FxIndexMap<&'a str, ActionManifestWorkerEntry<'a>>,
434
435 #[serde(rename = "exportedName")]
436 pub exported_name: &'a str,
437
438 pub filename: &'a str,
439
440 #[serde(skip_serializing_if = "Option::is_none")]
442 pub line: Option<u32>,
443
444 #[serde(skip_serializing_if = "Option::is_none")]
446 pub col: Option<u32>,
447}
448
449#[derive(Serialize, Debug)]
450#[serde(rename_all = "camelCase")]
451pub struct ActionManifestWorkerEntry<'a> {
452 pub module_id: ActionManifestModuleId<'a>,
453 #[serde(rename = "async")]
454 pub is_async: bool,
455 #[serde(skip_serializing_if = "Option::is_none")]
456 pub durability: Option<ActionManifestWorkerEntryDurability<'a>>,
457 #[serde(skip_serializing_if = "Option::is_none")]
462 pub root_param_dependencies: Option<&'a [RcStr]>,
463}
464
465#[derive(Serialize, Debug)]
466#[serde(rename_all = "camelCase")]
467pub struct ActionManifestWorkerEntryDurability<'a> {
468 pub code_hash: &'a str,
469 pub runtime_env_vars_read: &'a [RcStr],
470 pub runtime_env_vars_existence: &'a [RcStr],
471}
472
473#[derive(Serialize, Debug, Clone)]
474#[serde(untagged)]
475pub enum ActionManifestModuleId<'a> {
476 String(&'a str),
477 Number(u64),
478}
479
480#[turbo_tasks::task_input]
481#[derive(
482 Debug, Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize, Encode, Decode,
483)]
484#[serde(rename_all = "kebab-case")]
485pub enum ActionLayer {
486 Rsc,
487 ActionBrowser,
488}
489
490#[derive(Serialize, Debug, Eq, PartialEq, Hash, Clone)]
491#[serde(rename_all = "camelCase")]
492#[serde(untagged)]
493pub enum ModuleId {
494 String(RcStr),
495 Number(u64),
496}
497
498#[derive(Serialize, Default, Debug)]
499#[serde(rename_all = "camelCase")]
500pub struct FontManifest(pub Vec<FontManifestEntry>);
501
502#[derive(Serialize, Default, Debug)]
503#[serde(rename_all = "camelCase")]
504pub struct FontManifestEntry {
505 pub url: RcStr,
506 pub content: RcStr,
507}
508
509#[cfg(test)]
510mod tests {
511 use turbo_rcstr::rcstr;
512
513 use super::*;
514
515 #[test]
516 fn test_middleware_matcher_serialization() {
517 let matchers = vec![
518 ProxyMatcher {
519 regexp: None,
520 locale: false,
521 has: None,
522 missing: None,
523 original_source: rcstr!(""),
524 },
525 ProxyMatcher {
526 regexp: Some(rcstr!(".*")),
527 locale: true,
528 has: Some(vec![RouteHas::Query {
529 key: rcstr!("foo"),
530 value: None,
531 }]),
532 missing: Some(vec![RouteHas::Query {
533 key: rcstr!("bar"),
534 value: Some(rcstr!("value")),
535 }]),
536 original_source: rcstr!("source"),
537 },
538 ];
539
540 let serialized = serde_json::to_string(&matchers).unwrap();
541 let deserialized: Vec<ProxyMatcher> = serde_json::from_str(&serialized).unwrap();
542
543 assert_eq!(matchers, deserialized);
544 }
545}