turbopack_ecmascript/references/
util.rs

1use anyhow::Result;
2use swc_core::{ecma::ast::Expr, quote};
3use turbo_rcstr::{RcStr, rcstr};
4use turbo_tasks::Vc;
5use turbopack_core::{self, resolve::parse::Request};
6
7/// Creates a IIFE expression that throws a "Cannot find module" error for the
8/// given request string
9pub fn throw_module_not_found_expr(request: &str) -> Expr {
10    let message = format!("Cannot find module '{request}'");
11    quote!(
12        "(() => { const e = new Error($message); e.code = 'MODULE_NOT_FOUND'; throw e; })()"
13            as Expr,
14        message: Expr = message.into()
15    )
16}
17
18/// Creates a IIFE expression that throws a "Cannot find module" error for the
19/// given request string
20pub fn throw_module_not_found_error_expr(request: &str, message: &str) -> Expr {
21    let message = format!("Cannot find module '{request}': {message}");
22    quote!(
23        "(() => { const e = new Error($message); e.code = 'MODULE_NOT_FOUND'; throw e; })()"
24            as Expr,
25        message: Expr = message.into()
26    )
27}
28
29#[turbo_tasks::function]
30pub async fn request_to_string(request: Vc<Request>) -> Result<Vc<RcStr>> {
31    Ok(Vc::cell(
32        request
33            .await?
34            .request()
35            // TODO: Handle Request::Dynamic, Request::Alternatives
36            .unwrap_or(rcstr!("unknown")),
37    ))
38}