turbopack_dev_server/source/
lazy_instantiated.rs

1use anyhow::Result;
2use turbo_rcstr::RcStr;
3use turbo_tasks::{ResolvedVc, TryJoinIterExt, Vc};
4use turbopack_core::introspect::{Introspectable, IntrospectableChildren};
5
6use super::{ContentSource, route_tree::RouteTree};
7
8/// A functor to get a [ContentSource]. Will be invoked when needed when using
9/// [LazyInstantiatedContentSource].
10#[turbo_tasks::value_trait]
11pub trait GetContentSource {
12    /// Returns the [ContentSource]
13    fn content_source(self: Vc<Self>) -> Vc<Box<dyn ContentSource>>;
14}
15
16/// Wraps the [ContentSource] creation in a way that only creates it when
17/// actually used.
18#[turbo_tasks::value(shared)]
19pub struct LazyInstantiatedContentSource {
20    pub get_source: ResolvedVc<Box<dyn GetContentSource>>,
21}
22
23#[turbo_tasks::value_impl]
24impl ContentSource for LazyInstantiatedContentSource {
25    #[turbo_tasks::function]
26    fn get_routes(&self) -> Vc<RouteTree> {
27        self.get_source.content_source().get_routes()
28    }
29}
30
31#[turbo_tasks::function]
32fn introspectable_type() -> Vc<RcStr> {
33    Vc::cell("lazy instantiated content source".into())
34}
35
36#[turbo_tasks::function]
37fn source_key() -> Vc<RcStr> {
38    Vc::cell("source".into())
39}
40
41#[turbo_tasks::value_impl]
42impl Introspectable for LazyInstantiatedContentSource {
43    #[turbo_tasks::function]
44    fn ty(&self) -> Vc<RcStr> {
45        introspectable_type()
46    }
47
48    #[turbo_tasks::function]
49    async fn children(&self) -> Result<Vc<IntrospectableChildren>> {
50        Ok(Vc::cell(
51            [ResolvedVc::try_sidecast::<Box<dyn Introspectable>>(
52                self.get_source.content_source().to_resolved().await?,
53            )
54            .map(|i| (source_key(), i))]
55            .into_iter()
56            .flatten()
57            .map(|(k, v)| async move { Ok((k.to_resolved().await?, v)) })
58            .try_join()
59            .await?
60            .into_iter()
61            .collect(),
62        ))
63    }
64}