Skip to main content

turbopack_browser/ecmascript/
content.rs

1use std::io::Write;
2
3use anyhow::Result;
4use either::Either;
5use turbo_rcstr::RcStr;
6use turbo_tasks::{ResolvedVc, Vc, turbobail};
7use turbo_tasks_fs::{File, FileContent};
8use turbopack_core::{
9    asset::AssetContent,
10    chunk::{ChunkingContext, MinifyType, ModuleId},
11    code_builder::{Code, CodeBuilder},
12    output::OutputAsset,
13    source_map::{GenerateSourceMap, SourceMapAsset},
14    version::{MergeableVersionedContent, Version, VersionedContent, VersionedContentMerger},
15};
16use turbopack_ecmascript::{chunk::EcmascriptChunkContent, minify::minify, utils::StringifyJs};
17
18use super::{
19    chunk::EcmascriptBrowserChunk, content_entry::EcmascriptBrowserChunkContentEntries,
20    merged::merger::EcmascriptBrowserChunkContentMerger, version::EcmascriptBrowserChunkVersion,
21};
22use crate::{
23    BrowserChunkingContext,
24    chunking_context::{CURRENT_CHUNK_METHOD_DOCUMENT_CURRENT_SCRIPT_EXPR, CurrentChunkMethod},
25};
26
27#[turbo_tasks::value(serialization = "none")]
28pub struct EcmascriptBrowserChunkContent {
29    pub(super) chunking_context: ResolvedVc<BrowserChunkingContext>,
30    pub(super) chunk: ResolvedVc<EcmascriptBrowserChunk>,
31    pub(super) content: ResolvedVc<EcmascriptChunkContent>,
32    pub(super) source_map: ResolvedVc<SourceMapAsset>,
33}
34
35#[turbo_tasks::value_impl]
36impl EcmascriptBrowserChunkContent {
37    #[turbo_tasks::function]
38    pub(crate) fn new(
39        chunking_context: ResolvedVc<BrowserChunkingContext>,
40        chunk: ResolvedVc<EcmascriptBrowserChunk>,
41        content: ResolvedVc<EcmascriptChunkContent>,
42        source_map: ResolvedVc<SourceMapAsset>,
43    ) -> Result<Vc<Self>> {
44        Ok(EcmascriptBrowserChunkContent {
45            chunking_context,
46            chunk,
47            content,
48            source_map,
49        }
50        .cell())
51    }
52
53    #[turbo_tasks::function]
54    pub fn entries(&self) -> Vc<EcmascriptBrowserChunkContentEntries> {
55        EcmascriptBrowserChunkContentEntries::new(*self.content)
56    }
57}
58
59#[turbo_tasks::value_impl]
60impl EcmascriptBrowserChunkContent {
61    #[turbo_tasks::function]
62    pub(crate) async fn own_version(&self) -> Result<Vc<EcmascriptBrowserChunkVersion>> {
63        Ok(EcmascriptBrowserChunkVersion::new(
64            self.chunking_context.output_root().owned().await?,
65            self.chunk.path().owned().await?,
66            *self.content,
67        ))
68    }
69
70    #[turbo_tasks::function]
71    async fn code(self: Vc<Self>) -> Result<Vc<Code>> {
72        let this = self.await?;
73        let source_maps = *this
74            .chunking_context
75            .reference_chunk_source_maps(*ResolvedVc::upcast(this.chunk))
76            .await?;
77        // Lifetime hack to pull out the var into this scope
78        let chunk_path;
79        let script_or_path = match *this.chunking_context.current_chunk_method().await? {
80            CurrentChunkMethod::StringLiteral => {
81                let output_root = this.chunking_context.output_root().await?;
82                let chunk_path_vc = this.chunk.path();
83                chunk_path = chunk_path_vc.await?;
84                let chunk_server_path = if let Some(path) = output_root.get_path_to(&chunk_path) {
85                    path
86                } else {
87                    turbobail!("chunk path {chunk_path} is not in output root {output_root}");
88                };
89                Either::Left(StringifyJs(chunk_server_path))
90            }
91            CurrentChunkMethod::DocumentCurrentScript => {
92                Either::Right(CURRENT_CHUNK_METHOD_DOCUMENT_CURRENT_SCRIPT_EXPR)
93            }
94        };
95        let mut code = CodeBuilder::new(
96            source_maps,
97            *this.chunking_context.debug_ids_enabled().await?,
98        );
99
100        // When a chunk is executed, it will either register itself with the current
101        // instance of the runtime, or it will push itself onto the list of pending
102        // chunks (using the configured chunk loading global variable).
103        //
104        // When the runtime executes (see the `evaluate` module), it will pick up and
105        // register all pending chunks, and replace the list of pending chunks
106        // with itself so later chunks can register directly with it.
107        let chunk_loading_global = this.chunking_context.chunk_loading_global().await?;
108        write!(
109            code,
110            // `||=` would be better but we need to be es2020 compatible
111            //`x || (x = default)` is better than `x = x || default` simply because we avoid _writing_ the property in the common case.
112            r#"(globalThis[{chunk_loading_global}] || (globalThis[{chunk_loading_global}] = [])).push([{script_or_path},"#,
113            chunk_loading_global = StringifyJs(&chunk_loading_global),
114        )?;
115
116        let content = this.content.await?;
117        let chunk_items = content.chunk_item_code_and_ids().await?;
118        for item in chunk_items {
119            for (id, item_code) in item {
120                write!(code, "\n{}, ", StringifyJs(&id))?;
121                code.push_code(item_code);
122                write!(code, ",")?;
123            }
124        }
125
126        write!(code, "\n]);")?;
127
128        let mut code = code.build();
129
130        if let MinifyType::Minify { mangle } = *this.chunking_context.minify_type().await? {
131            code = minify(code, source_maps, mangle)?;
132        }
133
134        Ok(code.cell())
135    }
136}
137
138#[turbo_tasks::value_impl]
139impl VersionedContent for EcmascriptBrowserChunkContent {
140    #[turbo_tasks::function]
141    async fn content(self: Vc<Self>) -> Result<Vc<AssetContent>> {
142        let this = self.await?;
143
144        Ok(AssetContent::file(
145            FileContent::Content(File::from(
146                self.code()
147                    .to_rope_with_magic_comments(|| *this.source_map)
148                    .await?,
149            ))
150            .cell(),
151        ))
152    }
153
154    #[turbo_tasks::function]
155    fn version(self: Vc<Self>) -> Vc<Box<dyn Version>> {
156        Vc::upcast(self.own_version())
157    }
158}
159
160#[turbo_tasks::value_impl]
161impl MergeableVersionedContent for EcmascriptBrowserChunkContent {
162    #[turbo_tasks::function]
163    fn get_merger(&self) -> Vc<Box<dyn VersionedContentMerger>> {
164        Vc::upcast(EcmascriptBrowserChunkContentMerger::new())
165    }
166}
167
168#[turbo_tasks::value_impl]
169impl GenerateSourceMap for EcmascriptBrowserChunkContent {
170    #[turbo_tasks::function]
171    fn generate_source_map(self: Vc<Self>) -> Vc<FileContent> {
172        self.code().generate_source_map()
173    }
174
175    #[turbo_tasks::function]
176    async fn by_section(self: Vc<Self>, section: RcStr) -> Result<Vc<FileContent>> {
177        // Weirdly, the ContentSource will have already URL decoded the ModuleId, and we
178        // can't reparse that via serde.
179        if let Ok(id) = ModuleId::parse(&section) {
180            let entries = self.entries().await?;
181            for (entry_id, entry) in entries.iter() {
182                if id == *entry_id {
183                    let sm = entry.code.generate_source_map();
184                    return Ok(sm);
185                }
186            }
187        }
188
189        Ok(FileContent::NotFound.cell())
190    }
191}