Unverified Commit 373d2c44 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Turbopack: createRequire(new URL("...", import.meta.url)) (#92153)

For more `@vercel/nft` parity
parent b7f99c77
...@@ -1808,6 +1808,10 @@ impl JsValue { ...@@ -1808,6 +1808,10 @@ impl JsValue {
"The dynamic import() method from the ESM specification: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports" "The dynamic import() method from the ESM specification: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports"
), ),
WellKnownFunctionKind::Require => ("require".to_string(), "The require method from CommonJS"), WellKnownFunctionKind::Require => ("require".to_string(), "The require method from CommonJS"),
WellKnownFunctionKind::RequireFrom(rel) => (
format!("createRequire('{rel}')"),
"The return value of Node.js module.createRequire: https://nodejs.org/api/module.html#modulecreaterequirefilename"
),
WellKnownFunctionKind::RequireResolve => ("require.resolve".to_string(), "The require.resolve method from CommonJS"), WellKnownFunctionKind::RequireResolve => ("require.resolve".to_string(), "The require.resolve method from CommonJS"),
WellKnownFunctionKind::RequireContext => ("require.context".to_string(), "The require.context method from webpack"), WellKnownFunctionKind::RequireContext => ("require.context".to_string(), "The require.context method from webpack"),
WellKnownFunctionKind::RequireContextRequire(..) => ("require.context(...)".to_string(), "The require.context(...) method from webpack: https://webpack.js.org/api/module-methods/#requirecontext"), WellKnownFunctionKind::RequireContextRequire(..) => ("require.context(...)".to_string(), "The require.context(...) method from webpack: https://webpack.js.org/api/module-methods/#requirecontext"),
...@@ -3477,6 +3481,8 @@ pub enum WellKnownFunctionKind { ...@@ -3477,6 +3481,8 @@ pub enum WellKnownFunctionKind {
PathResolve(Box<JsValue>), PathResolve(Box<JsValue>),
Import, Import,
Require, Require,
/// `0` is the path to resolve from (relative to the current module).
RequireFrom(Box<ConstantString>),
RequireResolve, RequireResolve,
RequireContext, RequireContext,
RequireContextRequire(RequireContextValue), RequireContextRequire(RequireContextValue),
......
...@@ -2332,6 +2332,57 @@ where ...@@ -2332,6 +2332,57 @@ where
DiagnosticId::Error(errors::failed_to_analyze::ecmascript::REQUIRE.to_string()), DiagnosticId::Error(errors::failed_to_analyze::ecmascript::REQUIRE.to_string()),
) )
} }
WellKnownFunctionKind::RequireFrom(rel) => {
let args = linked_args().await?;
if args.len() == 1 {
let pat = js_value_to_pattern(&args[0]);
if !pat.has_constant_parts() {
let (args, hints) = explain_args(args);
handler.span_warn_with_code(
span,
&format!("createRequire()({args}) is very dynamic{hints}",),
DiagnosticId::Lint(
errors::failed_to_analyze::ecmascript::REQUIRE.to_string(),
),
);
if ignore_dynamic_requests {
analysis.add_code_gen(DynamicExpression::new(ast_path.to_vec().into()));
return Ok(());
}
}
let origin = ResolvedVc::upcast(
PlainResolveOrigin::new(
origin.asset_context(),
origin
.origin_path()
.await?
.parent()
.join(rel.as_str())?
.join("_")?,
)
.to_resolved()
.await?,
);
analysis.add_reference_code_gen(
CjsRequireAssetReference::new(
origin,
Request::parse(pat).to_resolved().await?,
issue_source(source, span),
error_mode,
attributes.chunking_type,
),
ast_path.to_vec().into(),
);
return Ok(());
}
let (args, hints) = explain_args(args);
handler.span_warn_with_code(
span,
&format!("createRequire()({args}) is not statically analyze-able{hints}",),
DiagnosticId::Error(errors::failed_to_analyze::ecmascript::REQUIRE.to_string()),
)
}
WellKnownFunctionKind::Define => { WellKnownFunctionKind::Define => {
analyze_amd_define( analyze_amd_define(
source, source,
...@@ -3592,7 +3643,6 @@ async fn value_visitor_inner( ...@@ -3592,7 +3643,6 @@ async fn value_visitor_inner(
box JsValue::WellKnownFunction(WellKnownFunctionKind::CreateRequire), box JsValue::WellKnownFunction(WellKnownFunctionKind::CreateRequire),
ref args, ref args,
) => { ) => {
// Only support `createRequire(import.meta.url)` for now
if let [ if let [
JsValue::Member( JsValue::Member(
_, _,
...@@ -3602,7 +3652,13 @@ async fn value_visitor_inner( ...@@ -3602,7 +3652,13 @@ async fn value_visitor_inner(
] = &args[..] ] = &args[..]
&& prop.as_str() == "url" && prop.as_str() == "url"
{ {
// `createRequire(import.meta.url)`
JsValue::WellKnownFunction(WellKnownFunctionKind::Require) JsValue::WellKnownFunction(WellKnownFunctionKind::Require)
} else if let [JsValue::Url(rel, JsValueUrlKind::Relative)] = &args[..] {
// `createRequire(new URL("<rel>", import.meta.url))`
JsValue::WellKnownFunction(WellKnownFunctionKind::RequireFrom(Box::new(
rel.clone(),
)))
} else { } else {
v.into_unknown(true, "createRequire() non constant") v.into_unknown(true, "createRequire() non constant")
} }
......
import { createRequire } from 'node:module'
it('createRequire with import.meta.url works', () => {
const require = createRequire(import.meta.url)
const foo = require('./sub/foo.js')
expect(foo).toBe('foo')
})
it('createRequire with URL works', () => {
// Currently (incorrectly) emits an error about `Module not found: Can't resolve './sub/'`
const require = createRequire(new URL('./sub/', import.meta.url))
const foo = require('./foo.js')
expect(foo).toBe('foo')
})
error - [resolve] /turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/create-require/input/index.js:11:32 Module not found: Can't resolve './sub/'
7 | })
8 |
9 | it('createRequire with URL works', () => {
10 | // Currently (incorrectly) emits an error about `Module not found: Can't resolve './sub/'`
+ v--------------------------------v
11 + const require = createRequire(new URL('./sub/', import.meta.url))
+ ^--------------------------------^
12 | const foo = require('./foo.js')
13 | expect(foo).toBe('foo')
14 | })
15 |
| It was not possible to find the requested file.
| Parsed request as written in source code: relative './sub/'
| Path where resolving has started: [project]/turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/create-require/input/index.js
| Type of request: url request
|
\ No newline at end of file
...@@ -116,12 +116,12 @@ static ALLOC: turbo_tasks_malloc::TurboMalloc = turbo_tasks_malloc::TurboMalloc; ...@@ -116,12 +116,12 @@ static ALLOC: turbo_tasks_malloc::TurboMalloc = turbo_tasks_malloc::TurboMalloc;
// #[case::microtime_node_gyp("microtime-node-gyp")] // #[case::microtime_node_gyp("microtime-node-gyp")]
// #[case::mixed_esm_cjs("mixed-esm-cjs")] // #[case::mixed_esm_cjs("mixed-esm-cjs")]
#[case::module_create_require("module-create-require")] #[case::module_create_require("module-create-require")]
// #[case::module_create_require_destructure_namespace("module-create-require-destructure-namespace" #[case::module_create_require_destructure_namespace("module-create-require-destructure-namespace")]
// )] #[case::module_create_require_destructure("module-create-require-destructure")] #[case::module_create_require_destructure("module-create-require-destructure")]
// #[case::module_create_require_ignore_other("module-create-require-ignore-other")] #[case::module_create_require_ignore_other("module-create-require-ignore-other")]
// #[case::module_create_require_named_import("module-create-require-named-import")] #[case::module_create_require_named_import("module-create-require-named-import")]
// #[case::module_create_require_named_require("module-create-require-named-require")] #[case::module_create_require_named_require("module-create-require-named-require")]
// #[case::module_create_require_no_mixed("module-create-require-no-mixed")] #[case::module_create_require_no_mixed("module-create-require-no-mixed")]
// #[case::module_register("module-register")] // #[case::module_register("module-register")]
// #[case::module_require("module-require")] // #[case::module_require("module-require")]
// #[case::module_sync_condition_cjs("module-sync-condition-cjs")] // #[case::module_sync_condition_cjs("module-sync-condition-cjs")]
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment