File size: 9,822 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
use anyhow::Result;
use serde_json::Value as JsonValue;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{FxIndexSet, OperationVc, ResolvedVc, Vc};
use turbo_tasks_env::ProcessEnv;
use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{
    introspect::{
        Introspectable, IntrospectableChildren, module::IntrospectableModule,
        output_asset::IntrospectableOutputAsset,
    },
    issue::IssueDescriptionExt,
    module::Module,
    output::OutputAsset,
    version::VersionedContentExt,
};
use turbopack_dev_server::{
    html::DevHtmlAsset,
    source::{
        ContentSource, ContentSourceContent, ContentSourceData, ContentSourceDataVary,
        GetContentSourceContent, ProxyResult,
        asset_graph::AssetGraphContentSource,
        conditional::ConditionalContentSource,
        lazy_instantiated::{GetContentSource, LazyInstantiatedContentSource},
        route_tree::{BaseSegment, RouteTree, RouteType},
    },
};

use super::{
    RenderData,
    render_static::{StaticResult, render_static_operation},
};
use crate::{
    external_asset_entrypoints, get_intermediate_asset, node_entry::NodeEntry,
    route_matcher::RouteMatcher,
};

/// Creates a content source that renders something in Node.js with the passed
/// `entry` when it matches a `path_regex`. Once rendered it serves
/// all assets referenced by the `entry` that are within the `server_root`.
/// It needs a temporary directory (`intermediate_output_path`) to place file
/// for Node.js execution during rendering. The `chunking_context` should emit
/// to this directory.
#[turbo_tasks::function]
pub fn create_node_rendered_source(
    cwd: FileSystemPath,
    env: ResolvedVc<Box<dyn ProcessEnv>>,
    base_segments: Vec<BaseSegment>,
    route_type: RouteType,
    server_root: FileSystemPath,
    route_match: ResolvedVc<Box<dyn RouteMatcher>>,
    pathname: ResolvedVc<RcStr>,
    entry: ResolvedVc<Box<dyn NodeEntry>>,
    fallback_page: ResolvedVc<DevHtmlAsset>,
    render_data: ResolvedVc<JsonValue>,
    debug: bool,
) -> Vc<Box<dyn ContentSource>> {
    let source = NodeRenderContentSource {
        cwd,
        env,
        base_segments,
        route_type,
        server_root,
        route_match,
        pathname,
        entry,
        fallback_page,
        render_data,
        debug,
    }
    .resolved_cell();
    Vc::upcast(ConditionalContentSource::new(
        Vc::upcast(*source),
        Vc::upcast(
            LazyInstantiatedContentSource {
                get_source: ResolvedVc::upcast(source),
            }
            .cell(),
        ),
    ))
}

/// see [create_node_rendered_source]
#[turbo_tasks::value]
pub struct NodeRenderContentSource {
    cwd: FileSystemPath,
    env: ResolvedVc<Box<dyn ProcessEnv>>,
    base_segments: Vec<BaseSegment>,
    route_type: RouteType,
    server_root: FileSystemPath,
    route_match: ResolvedVc<Box<dyn RouteMatcher>>,
    pathname: ResolvedVc<RcStr>,
    entry: ResolvedVc<Box<dyn NodeEntry>>,
    fallback_page: ResolvedVc<DevHtmlAsset>,
    render_data: ResolvedVc<JsonValue>,
    debug: bool,
}

#[turbo_tasks::value_impl]
impl NodeRenderContentSource {
    #[turbo_tasks::function]
    pub fn get_pathname(&self) -> Vc<RcStr> {
        *self.pathname
    }
}

#[turbo_tasks::value_impl]
impl GetContentSource for NodeRenderContentSource {
    /// Returns the [ContentSource] that serves all referenced external
    /// assets. This is wrapped into [LazyInstantiatedContentSource].
    #[turbo_tasks::function]
    async fn content_source(&self) -> Result<Vc<Box<dyn ContentSource>>> {
        let entries = self.entry.entries();
        let mut set = FxIndexSet::default();
        for &reference in self.fallback_page.references().await?.iter() {
            set.insert(reference);
        }
        for &entry in entries.await?.iter() {
            let entry = entry.await?;
            set.extend(
                external_asset_entrypoints(
                    *entry.module,
                    *entry.runtime_entries,
                    *entry.chunking_context,
                    entry.intermediate_output_path.clone(),
                )
                .await?
                .iter()
                .copied(),
            )
        }
        Ok(Vc::upcast(AssetGraphContentSource::new_lazy_multiple(
            self.server_root.clone(),
            Vc::cell(set),
        )))
    }
}

#[turbo_tasks::value_impl]
impl ContentSource for NodeRenderContentSource {
    #[turbo_tasks::function]
    async fn get_routes(self: Vc<Self>) -> Result<Vc<RouteTree>> {
        let this = self.await?;
        Ok(RouteTree::new_route(
            this.base_segments.clone(),
            this.route_type.clone(),
            Vc::upcast(self),
        ))
    }
}

#[turbo_tasks::value_impl]
impl GetContentSourceContent for NodeRenderContentSource {
    #[turbo_tasks::function]
    fn vary(&self) -> Vc<ContentSourceDataVary> {
        ContentSourceDataVary {
            method: true,
            url: true,
            original_url: true,
            raw_headers: true,
            raw_query: true,
            ..Default::default()
        }
        .cell()
    }

    #[turbo_tasks::function]
    async fn get(&self, path: RcStr, data: ContentSourceData) -> Result<Vc<ContentSourceContent>> {
        let pathname = self.pathname.await?;
        let Some(params) = &*self.route_match.params(path.clone()).await? else {
            anyhow::bail!("Non matching path ({}) provided for {}", path, pathname)
        };
        let ContentSourceData {
            method: Some(method),
            url: Some(url),
            original_url: Some(original_url),
            raw_headers: Some(raw_headers),
            raw_query: Some(raw_query),
            ..
        } = &data
        else {
            anyhow::bail!("Missing request data")
        };
        let entry = (*self.entry).entry(data.clone()).await?;
        let result_op = render_static_operation(
            self.cwd.clone(),
            self.env,
            self.server_root.join(&path)?,
            ResolvedVc::upcast(entry.module),
            entry.runtime_entries,
            self.fallback_page,
            entry.chunking_context,
            entry.intermediate_output_path.clone(),
            entry.output_root.clone(),
            entry.project_dir.clone(),
            RenderData {
                params: params.clone(),
                method: method.clone(),
                url: url.clone(),
                original_url: original_url.clone(),
                raw_query: raw_query.clone(),
                raw_headers: raw_headers.clone(),
                path: pathname.as_str().into(),
                data: Some(self.render_data.await?),
            }
            .resolved_cell(),
            self.debug,
        )
        .issue_file_path(
            entry.module.ident().path().owned().await?,
            format!("server-side rendering {pathname}"),
        )
        .await?;
        Ok(match *result_op.connect().await? {
            StaticResult::Content {
                content,
                status_code,
                headers,
            } => ContentSourceContent::static_with_headers(
                content.versioned(),
                status_code,
                *headers,
            ),
            StaticResult::StreamedContent {
                status,
                headers,
                ref body,
            } => {
                ContentSourceContent::HttpProxy(static_streamed_content_to_proxy_result_operation(
                    result_op,
                    ProxyResult {
                        status,
                        headers: headers.owned().await?,
                        body: body.clone(),
                    }
                    .resolved_cell(),
                ))
                .cell()
            }
            StaticResult::Rewrite(rewrite) => ContentSourceContent::Rewrite(rewrite).cell(),
        })
    }
}

#[turbo_tasks::function(operation)]
async fn static_streamed_content_to_proxy_result_operation(
    result_op: OperationVc<StaticResult>,
    proxy_result: ResolvedVc<ProxyResult>,
) -> Result<Vc<ProxyResult>> {
    // we already assume `result_op`'s value here because we're called inside of a match arm, but
    // await `result_op` anyways, so that if it generates any collectible issues, they're captured
    // here.
    let _ = result_op.connect().await?;
    Ok(*proxy_result)
}

#[turbo_tasks::value_impl]
impl Introspectable for NodeRenderContentSource {
    #[turbo_tasks::function]
    fn ty(&self) -> Vc<RcStr> {
        Vc::cell(rcstr!("node render content source"))
    }

    #[turbo_tasks::function]
    fn title(&self) -> Vc<RcStr> {
        *self.pathname
    }

    #[turbo_tasks::function]
    fn details(&self) -> Vc<RcStr> {
        Vc::cell(
            format!(
                "base: {:?}\ntype: {:?}",
                self.base_segments, self.route_type
            )
            .into(),
        )
    }

    #[turbo_tasks::function]
    async fn children(&self) -> Result<Vc<IntrospectableChildren>> {
        let mut set = FxIndexSet::default();
        for &entry in self.entry.entries().await?.iter() {
            let entry = entry.await?;
            set.insert((
                rcstr!("module"),
                IntrospectableModule::new(Vc::upcast(*entry.module))
                    .to_resolved()
                    .await?,
            ));
            set.insert((
                rcstr!("intermediate asset"),
                IntrospectableOutputAsset::new(get_intermediate_asset(
                    *entry.chunking_context,
                    *entry.module,
                    *entry.runtime_entries,
                ))
                .to_resolved()
                .await?,
            ));
        }
        Ok(Vc::cell(set))
    }
}