Unverified Commit 3abe2518 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Turbopack: fix NFT of readFileSync of relative path (#84155)

Tests are missing

Previously, `readFileSync("./data/foo.txt")` was relative to the current file, not relative to `process.cwd()`
parent 43500816
...@@ -998,7 +998,7 @@ impl Project { ...@@ -998,7 +998,7 @@ impl Project {
let this = self.await?; let this = self.await?;
Ok(get_server_compile_time_info( Ok(get_server_compile_time_info(
// `/ROOT` corresponds to `[project]/`, so we need exactly the `path` part. // `/ROOT` corresponds to `[project]/`, so we need exactly the `path` part.
format!("/ROOT/{}", self.project_path().await?.path).into(), self.project_path(),
this.define_env.nodejs(), this.define_env.nodejs(),
self.current_node_js_version(), self.current_node_js_version(),
)) ))
......
...@@ -358,7 +358,7 @@ async fn next_server_free_vars(define_env: Vc<OptionEnvMap>) -> Result<Vc<FreeVa ...@@ -358,7 +358,7 @@ async fn next_server_free_vars(define_env: Vc<OptionEnvMap>) -> Result<Vc<FreeVa
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn get_server_compile_time_info( pub async fn get_server_compile_time_info(
cwd: RcStr, cwd: Vc<FileSystemPath>,
define_env: Vc<OptionEnvMap>, define_env: Vc<OptionEnvMap>,
node_version: ResolvedVc<NodeJsVersion>, node_version: ResolvedVc<NodeJsVersion>,
) -> Result<Vc<CompileTimeInfo>> { ) -> Result<Vc<CompileTimeInfo>> {
...@@ -367,7 +367,7 @@ pub async fn get_server_compile_time_info( ...@@ -367,7 +367,7 @@ pub async fn get_server_compile_time_info(
NodeJsEnvironment { NodeJsEnvironment {
compile_target: CompileTarget::current().to_resolved().await?, compile_target: CompileTarget::current().to_resolved().await?,
node_version, node_version,
cwd: ResolvedVc::cell(Some(cwd)), cwd: ResolvedVc::cell(Some(cwd.owned().await?)),
} }
.resolved_cell(), .resolved_cell(),
)) ))
......
...@@ -3,7 +3,10 @@ import path from 'path' ...@@ -3,7 +3,10 @@ import path from 'path'
import 'foo' import 'foo'
const projectDir = process.cwd() const projectDir = process.cwd()
path.join(projectDir, 'app', 'static-from-app.txt') path.join(projectDir, 'data', 'static-from-app-cwd.txt')
path.join('data', 'static-from-app-rel-join.txt')
path.join('data', 'static-from-app-rel-read.txt')
export default function Page() { export default function Page() {
return 'hello' return 'hello'
......
import path from 'path' import path from 'path'
const projectDir = process.cwd() const projectDir = process.cwd()
path.join(projectDir, 'app', 'static-from-pkg.txt') path.join(projectDir, 'data', 'static-from-pkg.txt')
path.join('data', 'static-from-pkg.txt')
globalThis.myDirname = __dirname
path.join(globalThis.myDirname, 'foo.txt')
export default 'foo' export default 'foo'
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
describe('standalone mode - NFT in node_modules', () => { describe('standalone mode - tracing', () => {
const dependencies = require('./package.json').dependencies const dependencies = require('./package.json').dependencies
const { next, skipped } = nextTestSetup({ const { next, skipped } = nextTestSetup({
...@@ -13,10 +13,30 @@ describe('standalone mode - NFT in node_modules', () => { ...@@ -13,10 +13,30 @@ describe('standalone mode - NFT in node_modules', () => {
return return
} }
it('should not trace process.cwd calls in node_modules', async () => { it('should trace process.cwd calls in node_modules', async () => {
let trace = await next.readJSON('.next/server/app/page.js.nft.json') let trace = await next.readJSON('.next/server/app/page.js.nft.json')
expect(trace.files).toContain('../../../app/static-from-app.txt') // should trace process.cwd and relative calls relative to the root
expect(trace.files).toContain('../../../data/static-from-app-cwd.txt')
if (process.env.IS_TURBOPACK_TEST) {
// Webpack doesn't trace these relative reference
expect(trace.files).toContain(
'../../../data/static-from-app-rel-join.txt'
)
expect(trace.files).toContain(
'../../../data/static-from-app-rel-read.txt'
)
}
if (process.env.IS_TURBOPACK_TEST) {
// Webpack doesn't trace these relative reference
expect(trace.files).toContainEqual(
expect.stringMatching(/.*\/node_modules\/foo\/foo.txt/)
)
}
// should not trace process.cwd or relative calls in node_modules (only relative to file)
expect(trace.files).not.toContain('../../../app/static-from-pkg.txt') expect(trace.files).not.toContain('../../../app/static-from-pkg.txt')
expect(trace.files).not.toContain('../../../foo/foo.txt')
}) })
}) })
...@@ -9,6 +9,7 @@ use swc_core::ecma::preset_env::{Version, Versions}; ...@@ -9,6 +9,7 @@ use swc_core::ecma::preset_env::{Version, Versions};
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, TaskInput, Vc}; use turbo_tasks::{ResolvedVc, TaskInput, Vc};
use turbo_tasks_env::ProcessEnv; use turbo_tasks_env::ProcessEnv;
use turbo_tasks_fs::FileSystemPathOption;
use crate::target::CompileTarget; use crate::target::CompileTarget;
...@@ -213,7 +214,7 @@ impl Environment { ...@@ -213,7 +214,7 @@ impl Environment {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn cwd(&self) -> Result<Vc<Option<RcStr>>> { pub async fn cwd(&self) -> Result<Vc<FileSystemPathOption>> {
let env = self; let env = self;
Ok(match env.execution { Ok(match env.execution {
ExecutionEnvironment::NodeJsBuildTime(env) ExecutionEnvironment::NodeJsBuildTime(env)
...@@ -258,7 +259,7 @@ pub struct NodeJsEnvironment { ...@@ -258,7 +259,7 @@ pub struct NodeJsEnvironment {
pub compile_target: ResolvedVc<CompileTarget>, pub compile_target: ResolvedVc<CompileTarget>,
pub node_version: ResolvedVc<NodeJsVersion>, pub node_version: ResolvedVc<NodeJsVersion>,
// user specified process.cwd // user specified process.cwd
pub cwd: ResolvedVc<Option<RcStr>>, pub cwd: ResolvedVc<FileSystemPathOption>,
} }
impl Default for NodeJsEnvironment { impl Default for NodeJsEnvironment {
......
...@@ -15,7 +15,7 @@ use crate::analyzer::RequireContextValue; ...@@ -15,7 +15,7 @@ use crate::analyzer::RequireContextValue;
pub async fn replace_well_known( pub async fn replace_well_known(
value: JsValue, value: JsValue,
compile_time_info: Vc<CompileTimeInfo>, compile_time_info: Vc<CompileTimeInfo>,
define_process_cwd: bool, allow_project_root_tracing: bool,
) -> Result<(JsValue, bool)> { ) -> Result<(JsValue, bool)> {
Ok(match value { Ok(match value {
JsValue::Call(_, box JsValue::WellKnownFunction(kind), args) => ( JsValue::Call(_, box JsValue::WellKnownFunction(kind), args) => (
...@@ -24,7 +24,7 @@ pub async fn replace_well_known( ...@@ -24,7 +24,7 @@ pub async fn replace_well_known(
JsValue::unknown_empty(false, "this is not analyzed yet"), JsValue::unknown_empty(false, "this is not analyzed yet"),
args, args,
compile_time_info, compile_time_info,
define_process_cwd, allow_project_root_tracing,
) )
.await?, .await?,
true, true,
...@@ -69,7 +69,7 @@ pub async fn well_known_function_call( ...@@ -69,7 +69,7 @@ pub async fn well_known_function_call(
_this: JsValue, _this: JsValue,
args: Vec<JsValue>, args: Vec<JsValue>,
compile_time_info: Vc<CompileTimeInfo>, compile_time_info: Vc<CompileTimeInfo>,
define_process_cwd: bool, allow_project_root_tracing: bool,
) -> Result<JsValue> { ) -> Result<JsValue> {
Ok(match kind { Ok(match kind {
WellKnownFunctionKind::ObjectAssign => object_assign(args), WellKnownFunctionKind::ObjectAssign => object_assign(args),
...@@ -103,9 +103,10 @@ pub async fn well_known_function_call( ...@@ -103,9 +103,10 @@ pub async fn well_known_function_call(
.as_str() .as_str()
.into(), .into(),
WellKnownFunctionKind::ProcessCwd => { WellKnownFunctionKind::ProcessCwd => {
if define_process_cwd && let Some(cwd) = &*compile_time_info.environment().cwd().await? if allow_project_root_tracing
&& let Some(cwd) = &*compile_time_info.environment().cwd().await?
{ {
cwd.clone().into() format!("/ROOT/{}", cwd.path).into()
} else { } else {
JsValue::unknown( JsValue::unknown(
JsValue::call(Box::new(JsValue::WellKnownFunction(kind)), args), JsValue::call(Box::new(JsValue::WellKnownFunction(kind)), args),
......
...@@ -427,7 +427,10 @@ struct AnalysisState<'a> { ...@@ -427,7 +427,10 @@ struct AnalysisState<'a> {
origin: ResolvedVc<Box<dyn ResolveOrigin>>, origin: ResolvedVc<Box<dyn ResolveOrigin>>,
compile_time_info: ResolvedVc<CompileTimeInfo>, compile_time_info: ResolvedVc<CompileTimeInfo>,
var_graph: &'a VarGraph, var_graph: &'a VarGraph,
define_process_cwd: bool, /// Whether to allow tracing to reference files from the project root. This is used to prevent
/// random node_modules packages from tracing the entire project due to some dynamic
/// `path.join(foo, bar)` call.
allow_project_root_tracing: bool,
/// This is the current state of known values of function /// This is the current state of known values of function
/// arguments. /// arguments.
fun_args_values: Mutex<FxHashMap<u32, Vec<JsValue>>>, fun_args_values: Mutex<FxHashMap<u32, Vec<JsValue>>>,
...@@ -460,7 +463,7 @@ impl AnalysisState<'_> { ...@@ -460,7 +463,7 @@ impl AnalysisState<'_> {
&self.free_var_references, &self.free_var_references,
self.var_graph, self.var_graph,
attributes, attributes,
self.define_process_cwd, self.allow_project_root_tracing,
) )
}, },
&self.fun_args_values, &self.fun_args_values,
...@@ -962,7 +965,12 @@ pub async fn analyze_ecmascript_module_internal( ...@@ -962,7 +965,12 @@ pub async fn analyze_ecmascript_module_internal(
origin, origin,
compile_time_info, compile_time_info,
var_graph: &var_graph, var_graph: &var_graph,
define_process_cwd: !source.ident().path().await?.path.contains("/node_modules/"), allow_project_root_tracing: !source
.ident()
.path()
.await?
.path
.contains("/node_modules/"),
fun_args_values: Default::default(), fun_args_values: Default::default(),
var_cache: Default::default(), var_cache: Default::default(),
first_import_meta: true, first_import_meta: true,
...@@ -1606,6 +1614,7 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>( ...@@ -1606,6 +1614,7 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>(
ignore_dynamic_requests, ignore_dynamic_requests,
url_rewrite_behavior, url_rewrite_behavior,
collect_affecting_sources, collect_affecting_sources,
allow_project_root_tracing,
.. ..
} = state; } = state;
fn explain_args(args: &[JsValue]) -> (String, String) { fn explain_args(args: &[JsValue]) -> (String, String) {
...@@ -1722,6 +1731,18 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>( ...@@ -1722,6 +1731,18 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>(
return Ok(()); return Ok(());
} }
let get_traced_project_dir = async || {
// readFileSync("./foo") should always be relative to the project root, but this is
// dangerous inside of node_modules as it can cause a lot of false positives in the
// tracing, if some package does `path.join(dynamic)`, it would include everything from
// the project root as well.
if allow_project_root_tracing {
compile_time_info.environment().cwd().owned().await
} else {
Ok(Some(source.ident().path().await?.parent()))
}
};
match func { match func {
JsValue::Alternatives { JsValue::Alternatives {
total_nodes: _, total_nodes: _,
...@@ -1950,11 +1971,17 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>( ...@@ -1950,11 +1971,17 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>(
return Ok(()); return Ok(());
} }
} }
if let Some(context_dir) = get_traced_project_dir().await? {
analysis.add_reference( analysis.add_reference(
FileSourceReference::new(*source, Pattern::new(pat), collect_affecting_sources) FileSourceReference::new(
context_dir,
Pattern::new(pat),
collect_affecting_sources,
)
.to_resolved() .to_resolved()
.await?, .await?,
); );
}
return Ok(()); return Ok(());
} }
let (args, hints) = explain_args(&args); let (args, hints) = explain_args(&args);
...@@ -1999,11 +2026,13 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>( ...@@ -1999,11 +2026,13 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>(
return Ok(()); return Ok(());
} }
} }
if let Some(context_dir) = get_traced_project_dir().await? {
analysis.add_reference( analysis.add_reference(
FileSourceReference::new(*source, Pattern::new(pat), collect_affecting_sources) DirAssetReference::new(context_dir, Pattern::new(pat))
.to_resolved() .to_resolved()
.await?, .await?,
); );
}
return Ok(()); return Ok(());
} }
...@@ -2039,11 +2068,13 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>( ...@@ -2039,11 +2068,13 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>(
return Ok(()); return Ok(());
} }
} }
if let Some(context_dir) = get_traced_project_dir().await? {
analysis.add_reference( analysis.add_reference(
DirAssetReference::new(*source, Pattern::new(pat)) DirAssetReference::new(context_dir, Pattern::new(pat))
.to_resolved() .to_resolved()
.await?, .await?,
); );
}
return Ok(()); return Ok(());
} }
JsValue::WellKnownFunction(WellKnownFunctionKind::ChildProcessSpawnMethod(name)) JsValue::WellKnownFunction(WellKnownFunctionKind::ChildProcessSpawnMethod(name))
...@@ -2087,10 +2118,12 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>( ...@@ -2087,10 +2118,12 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>(
if dynamic { if dynamic {
show_dynamic_warning = true; show_dynamic_warning = true;
} }
if !dynamic || !ignore_dynamic_requests { if (!dynamic || !ignore_dynamic_requests)
&& let Some(context_dir) = get_traced_project_dir().await?
{
analysis.add_reference( analysis.add_reference(
FileSourceReference::new( FileSourceReference::new(
*source, context_dir,
Pattern::new(pat), Pattern::new(pat),
collect_affecting_sources, collect_affecting_sources,
) )
...@@ -2321,11 +2354,13 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>( ...@@ -2321,11 +2354,13 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>(
.await?; .await?;
js_value_to_pattern(&linked_func_call) js_value_to_pattern(&linked_func_call)
}; };
if let Some(context_dir) = get_traced_project_dir().await? {
analysis.add_reference( analysis.add_reference(
DirAssetReference::new(*source, Pattern::new(abs_pattern)) DirAssetReference::new(context_dir, Pattern::new(abs_pattern))
.to_resolved() .to_resolved()
.await?, .await?,
); );
}
return Ok(()); return Ok(());
} }
} }
...@@ -2384,11 +2419,13 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>( ...@@ -2384,11 +2419,13 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>(
.await?; .await?;
js_value_to_pattern(&linked_func_call) js_value_to_pattern(&linked_func_call)
}; };
if let Some(context_dir) = get_traced_project_dir().await? {
analysis.add_reference( analysis.add_reference(
DirAssetReference::new(*source, Pattern::new(abs_pattern)) DirAssetReference::new(context_dir, Pattern::new(abs_pattern))
.to_resolved() .to_resolved()
.await?, .await?,
); );
}
return Ok(()); return Ok(());
} }
let (args, hints) = explain_args(&args); let (args, hints) = explain_args(&args);
...@@ -2436,6 +2473,7 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>( ...@@ -2436,6 +2473,7 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>(
if args.len() == 2 if args.len() == 2
&& let Some(JsValue::Object { parts, .. }) = args.get(1) && let Some(JsValue::Object { parts, .. }) = args.get(1)
{ {
if let Some(context_dir) = get_traced_project_dir().await? {
let resolved_dirs = parts let resolved_dirs = parts
.iter() .iter()
.filter_map(|object_part| match object_part { .filter_map(|object_part| match object_part {
...@@ -2449,7 +2487,10 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>( ...@@ -2449,7 +2487,10 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>(
}) })
.flatten() .flatten()
.map(|dir| { .map(|dir| {
DirAssetReference::new(*source, Pattern::new(Pattern::Constant(dir.into()))) DirAssetReference::new(
context_dir.clone(),
Pattern::new(Pattern::Constant(dir.into())),
)
.to_resolved() .to_resolved()
}) })
.try_join() .try_join()
...@@ -2458,6 +2499,7 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>( ...@@ -2458,6 +2499,7 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>(
for resolved_dir_ref in resolved_dirs { for resolved_dir_ref in resolved_dirs {
analysis.add_reference(resolved_dir_ref); analysis.add_reference(resolved_dir_ref);
} }
}
return Ok(()); return Ok(());
} }
...@@ -2929,7 +2971,7 @@ async fn value_visitor( ...@@ -2929,7 +2971,7 @@ async fn value_visitor(
>, >,
var_graph: &VarGraph, var_graph: &VarGraph,
attributes: &ImportAttributes, attributes: &ImportAttributes,
define_process_cwd: bool, allow_project_root_tracing: bool,
) -> Result<(JsValue, bool)> { ) -> Result<(JsValue, bool)> {
let (mut v, modified) = value_visitor_inner( let (mut v, modified) = value_visitor_inner(
origin, origin,
...@@ -2938,7 +2980,7 @@ async fn value_visitor( ...@@ -2938,7 +2980,7 @@ async fn value_visitor(
free_var_references, free_var_references,
var_graph, var_graph,
attributes, attributes,
define_process_cwd, allow_project_root_tracing,
) )
.await?; .await?;
v.normalize_shallow(); v.normalize_shallow();
...@@ -2955,7 +2997,7 @@ async fn value_visitor_inner( ...@@ -2955,7 +2997,7 @@ async fn value_visitor_inner(
>, >,
var_graph: &VarGraph, var_graph: &VarGraph,
attributes: &ImportAttributes, attributes: &ImportAttributes,
define_process_cwd: bool, allow_project_root_tracing: bool,
) -> Result<(JsValue, bool)> { ) -> Result<(JsValue, bool)> {
let ImportAttributes { ignore, .. } = *attributes; let ImportAttributes { ignore, .. } = *attributes;
// This check is just an optimization // This check is just an optimization
...@@ -3082,7 +3124,7 @@ async fn value_visitor_inner( ...@@ -3082,7 +3124,7 @@ async fn value_visitor_inner(
} }
_ => { _ => {
let (mut v, mut modified) = let (mut v, mut modified) =
replace_well_known(v, compile_time_info, define_process_cwd).await?; replace_well_known(v, compile_time_info, allow_project_root_tracing).await?;
modified = replace_builtin(&mut v) || modified; modified = replace_builtin(&mut v) || modified;
modified = modified || v.make_nested_operations_unknown(); modified = modified || v.make_nested_operations_unknown();
return Ok((v, modified)); return Ok((v, modified));
......
...@@ -12,7 +12,6 @@ use turbopack_core::{ ...@@ -12,7 +12,6 @@ use turbopack_core::{
ModuleResolveResult, RequestKey, ModuleResolveResult, RequestKey,
pattern::{Pattern, PatternMatch, read_matches}, pattern::{Pattern, PatternMatch, read_matches},
}, },
source::Source,
}; };
#[turbo_tasks::value] #[turbo_tasks::value]
...@@ -58,20 +57,20 @@ impl ValueToString for PackageJsonReference { ...@@ -58,20 +57,20 @@ impl ValueToString for PackageJsonReference {
#[turbo_tasks::value] #[turbo_tasks::value]
#[derive(Hash, Debug)] #[derive(Hash, Debug)]
pub struct DirAssetReference { pub struct DirAssetReference {
pub source: ResolvedVc<Box<dyn Source>>, pub context_dir: FileSystemPath,
pub path: ResolvedVc<Pattern>, pub path: ResolvedVc<Pattern>,
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl DirAssetReference { impl DirAssetReference {
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn new(source: ResolvedVc<Box<dyn Source>>, path: ResolvedVc<Pattern>) -> Vc<Self> { pub fn new(context_dir: FileSystemPath, path: ResolvedVc<Pattern>) -> Vc<Self> {
Self::cell(DirAssetReference { source, path }) Self::cell(DirAssetReference { context_dir, path })
} }
} }
async fn resolve_reference_from_dir( async fn resolve_reference_from_dir(
parent_path: FileSystemPath, context_dir: FileSystemPath,
path: Vc<Pattern>, path: Vc<Pattern>,
) -> Result<Vc<ModuleResolveResult>> { ) -> Result<Vc<ModuleResolveResult>> {
let path_ref = path.await?; let path_ref = path.await?;
...@@ -83,7 +82,7 @@ async fn resolve_reference_from_dir( ...@@ -83,7 +82,7 @@ async fn resolve_reference_from_dir(
let abs_matches = if let Some(abs_path) = &abs_path { let abs_matches = if let Some(abs_path) = &abs_path {
Some( Some(
read_matches( read_matches(
parent_path.root().owned().await?, context_dir.root().owned().await?,
rcstr!("/ROOT/"), rcstr!("/ROOT/"),
true, true,
Pattern::new(abs_path.or_any_nested_file()), Pattern::new(abs_path.or_any_nested_file()),
...@@ -96,7 +95,7 @@ async fn resolve_reference_from_dir( ...@@ -96,7 +95,7 @@ async fn resolve_reference_from_dir(
let rel_matches = if let Some(rel_path) = &rel_path { let rel_matches = if let Some(rel_path) = &rel_path {
Some( Some(
read_matches( read_matches(
parent_path, context_dir,
rcstr!(""), rcstr!(""),
true, true,
Pattern::new(rel_path.or_any_nested_file()), Pattern::new(rel_path.or_any_nested_file()),
...@@ -149,12 +148,11 @@ async fn resolve_reference_from_dir( ...@@ -149,12 +148,11 @@ async fn resolve_reference_from_dir(
impl ModuleReference for DirAssetReference { impl ModuleReference for DirAssetReference {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn resolve_reference(&self) -> Result<Vc<ModuleResolveResult>> { async fn resolve_reference(&self) -> Result<Vc<ModuleResolveResult>> {
let parent_path = self.source.ident().path().await?.parent();
let span = tracing::info_span!( let span = tracing::info_span!(
"trace directory", "trace directory",
pattern = display(self.path.to_string().await?) pattern = display(self.path.to_string().await?)
); );
resolve_reference_from_dir(parent_path, *self.path) resolve_reference_from_dir(self.context_dir.clone(), *self.path)
.instrument(span) .instrument(span)
.await .await
} }
......
...@@ -2,31 +2,31 @@ use anyhow::Result; ...@@ -2,31 +2,31 @@ use anyhow::Result;
use tracing::Instrument; use tracing::Instrument;
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, ValueToString, Vc}; use turbo_tasks::{ResolvedVc, ValueToString, Vc};
use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{ use turbopack_core::{
chunk::{ChunkableModuleReference, ChunkingType, ChunkingTypeOption}, chunk::{ChunkableModuleReference, ChunkingType, ChunkingTypeOption},
reference::ModuleReference, reference::ModuleReference,
resolve::{ModuleResolveResult, pattern::Pattern, resolve_raw}, resolve::{ModuleResolveResult, pattern::Pattern, resolve_raw},
source::Source,
}; };
#[turbo_tasks::value] #[turbo_tasks::value]
#[derive(Hash, Debug)] #[derive(Hash, Debug)]
pub struct FileSourceReference { pub struct FileSourceReference {
pub source: ResolvedVc<Box<dyn Source>>, context_dir: FileSystemPath,
pub path: ResolvedVc<Pattern>, path: ResolvedVc<Pattern>,
pub collect_affecting_sources: bool, collect_affecting_sources: bool,
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl FileSourceReference { impl FileSourceReference {
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn new( pub fn new(
source: ResolvedVc<Box<dyn Source>>, context_dir: FileSystemPath,
path: ResolvedVc<Pattern>, path: ResolvedVc<Pattern>,
collect_affecting_sources: bool, collect_affecting_sources: bool,
) -> Vc<Self> { ) -> Vc<Self> {
Self::cell(FileSourceReference { Self::cell(FileSourceReference {
source, context_dir,
path, path,
collect_affecting_sources, collect_affecting_sources,
}) })
...@@ -37,15 +37,13 @@ impl FileSourceReference { ...@@ -37,15 +37,13 @@ impl FileSourceReference {
impl ModuleReference for FileSourceReference { impl ModuleReference for FileSourceReference {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn resolve_reference(&self) -> Result<Vc<ModuleResolveResult>> { async fn resolve_reference(&self) -> Result<Vc<ModuleResolveResult>> {
let context_dir = self.source.ident().path().await?.parent();
let span = tracing::info_span!( let span = tracing::info_span!(
"trace file", "trace file",
pattern = display(self.path.to_string().await?) pattern = display(self.path.to_string().await?)
); );
async { async {
resolve_raw( resolve_raw(
context_dir, self.context_dir.clone(),
*self.path, *self.path,
self.collect_affecting_sources, self.collect_affecting_sources,
/* force_in_lookup_dir */ false, /* force_in_lookup_dir */ false,
......
...@@ -351,7 +351,11 @@ async fn node_file_trace_operation( ...@@ -351,7 +351,11 @@ async fn node_file_trace_operation(
let source = FileSource::new(input); let source = FileSource::new(input);
let environment = Environment::new(ExecutionEnvironment::NodeJsLambda( let environment = Environment::new(ExecutionEnvironment::NodeJsLambda(
NodeJsEnvironment::default().resolved_cell(), NodeJsEnvironment {
cwd: ResolvedVc::cell(Some(input_dir.join("tests/node-file-trace/integration")?)),
..Default::default()
}
.resolved_cell(),
)); ));
let module_asset_context = ModuleAssetContext::new( let module_asset_context = ModuleAssetContext::new(
Default::default(), Default::default(),
......
...@@ -186,9 +186,13 @@ async fn node_file_trace_operation(package_root: RcStr, input: RcStr) -> Result< ...@@ -186,9 +186,13 @@ async fn node_file_trace_operation(package_root: RcStr, input: RcStr) -> Result<
let input_dir = workspace_fs.root().owned().await?; let input_dir = workspace_fs.root().owned().await?;
let input = input_dir.join(&input)?; let input = input_dir.join(&input)?;
let source = FileSource::new(input); let source = FileSource::new(input.clone());
let environment = Environment::new(ExecutionEnvironment::NodeJsLambda( let environment = Environment::new(ExecutionEnvironment::NodeJsLambda(
NodeJsEnvironment::default().resolved_cell(), NodeJsEnvironment {
cwd: ResolvedVc::cell(Some(input.parent())),
..Default::default()
}
.resolved_cell(),
)); ));
let module_asset_context = ModuleAssetContext::new( let module_asset_context = ModuleAssetContext::new(
Default::default(), Default::default(),
......
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