1use std::io::Write;
2
3use anyhow::Result;
4use indoc::writedoc;
5use turbo_rcstr::{RcStr, rcstr};
6use turbo_tasks::{ResolvedVc, Vc};
7use turbopack_core::{
8 chunk::AssetSuffix,
9 code_builder::{Code, CodeBuilder},
10 context::AssetContext,
11 environment::{ChunkLoading, Environment},
12};
13use turbopack_ecmascript::utils::StringifyJs;
14
15use crate::{RuntimeType, asset_context::get_runtime_asset_context, embed_js::embed_static_code};
16
17/// Returns the code for the ECMAScript runtime.
18#[turbo_tasks::function]
19pub async fn get_browser_runtime_code(
20 environment: ResolvedVc<Environment>,
21 chunk_base_path: Vc<Option<RcStr>>,
22 asset_suffix: Vc<AssetSuffix>,
23 runtime_type: RuntimeType,
24 output_root_to_root_path: RcStr,
25 generate_source_map: bool,
26) -> Result<Vc<Code>> {
27 let asset_context = get_runtime_asset_context(*environment).resolve().await?;
28
…lines 29–77 unchanged (49 lines)
78 };
79
80 let mut code: CodeBuilder = CodeBuilder::default();
81 let relative_root_path = output_root_to_root_path;
82 let chunk_base_path = chunk_base_path.await?;
83 let chunk_base_path = chunk_base_path.as_ref().map_or_else(|| "", |f| f.as_str());
84 let asset_suffix = asset_suffix.await?;
85
86 writedoc!(
87 code,
88 r#"
89 (() => {{
90 if (!Array.isArray(globalThis.TURBOPACK)) {{
…lines 91–96 unchanged (6 lines)
97 "#,
98 StringifyJs(chunk_base_path),
99 StringifyJs(relative_root_path.as_str()),
100 StringifyJs(chunk_base_path),
101 )?;
102
103 match &*asset_suffix {
104 AssetSuffix::None => {
105 writedoc!(
106 code,
107 r#"
108 const ASSET_SUFFIX = "";
109 "#
110 )?;
111 }
112 AssetSuffix::Constant(suffix) => {
113 writedoc!(
114 code,
115 r#"
116 const ASSET_SUFFIX = {};
117 "#,
118 StringifyJs(suffix.as_str())
119 )?;
120 }
121 AssetSuffix::Inferred => {
122 if chunk_loading == &ChunkLoading::Edge {
123 panic!("AssetSuffix::Inferred is not supported in Edge runtimes");
124 }
125 writedoc!(
126 code,
127 r#"
128 const ASSET_SUFFIX = getAssetSuffixFromScriptSrc();
129 "#
130 )?;
131 }
132 AssetSuffix::FromGlobal(global_name) => {
133 writedoc!(
134 code,
135 r#"
136 const ASSET_SUFFIX = globalThis[{}] || "";
137 "#,
138 StringifyJs(global_name)
139 )?;
140 }
141 }
142
143 code.push_code(&*shared_runtime_utils_code.await?);
144 for runtime_code in runtime_base_code {
145 code.push_code(
146 &*embed_static_code(asset_context, runtime_code.into(), generate_source_map).await?,
…lines 147–228 unchanged (82 lines)