这是indexloc提供的服务,不要输入任何密码
Skip to content

add support for dynamic requests in require() and import() #7398

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Feb 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions crates/turbo-tasks/src/debug/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,12 @@ pub trait ValueDebugFormat {
fn value_debug_format(&self, depth: usize) -> ValueDebugFormatString;
}

impl ValueDebugFormat for String {
fn value_debug_format(&self, _depth: usize) -> ValueDebugFormatString {
ValueDebugFormatString::Sync(format!("{:#?}", self))
}
}

// Use autoref specialization [1] to implement `ValueDebugFormat` for `T:
// Debug` as a fallback if `T` does not implement it directly, hence the `for
// &T` clause.
Expand Down
96 changes: 58 additions & 38 deletions crates/turbopack-core/src/resolve/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,18 @@ impl ResolveResult {
affecting_sources: self.affecting_sources.clone(),
}
}

pub fn add_conditions<'a>(&mut self, conditions: impl IntoIterator<Item = (&'a str, bool)>) {
let mut primary = self.primary.drain(..).collect::<Vec<_>>();
for (k, v) in conditions {
for (key, _) in primary.iter_mut() {
key.conditions.insert(k.to_string(), v);
}
}
for (k, v) in primary {
self.primary.insert(k, v);
}
}
}

#[turbo_tasks::value_impl]
Expand Down Expand Up @@ -1512,8 +1524,11 @@ async fn resolve_internal_inline(
.await?,
);
}
PatternMatch::Directory(_, path) => {
results.push(resolve_into_folder(*path, options, *query));
PatternMatch::Directory(matched_pattern, path) => {
results.push(
resolve_into_folder(*path, options, *query)
.with_request(matched_pattern.clone()),
);
}
}
}
Expand Down Expand Up @@ -1795,33 +1810,16 @@ async fn resolve_relative_request(
.await?;

for m in matches.iter() {
match m {
PatternMatch::File(matched_pattern, path) => {
let mut matches_without_extension = false;
for ext in options_value.extensions.iter() {
let Some(matched_pattern) = matched_pattern.strip_suffix(ext) else {
continue;
};
if path_pattern.is_match(matched_pattern) {
results.push(
resolved(
RequestKey::new(matched_pattern.to_string()),
*path,
lookup_path,
request,
options_value,
options,
query,
)
.await?,
);
matches_without_extension = true;
}
}
if !matches_without_extension || path_pattern.is_match(matched_pattern) {
if let PatternMatch::File(matched_pattern, path) = m {
let mut matches_without_extension = false;
for ext in options_value.extensions.iter() {
let Some(matched_pattern) = matched_pattern.strip_suffix(ext) else {
continue;
};
if path_pattern.is_match(matched_pattern) {
results.push(
resolved(
RequestKey::new(matched_pattern.clone()),
RequestKey::new(matched_pattern.to_string()),
*path,
lookup_path,
request,
Expand All @@ -1831,13 +1829,33 @@ async fn resolve_relative_request(
)
.await?,
);
matches_without_extension = true;
}
}
PatternMatch::Directory(_, path) => {
results.push(resolve_into_folder(*path, options, query));
if !matches_without_extension || path_pattern.is_match(matched_pattern) {
results.push(
resolved(
RequestKey::new(matched_pattern.clone()),
*path,
lookup_path,
request,
options_value,
options,
query,
)
.await?,
);
}
}
}
// Directory matches must be resolved AFTER file matches
for m in matches.iter() {
if let PatternMatch::Directory(matched_pattern, path) = m {
results.push(
resolve_into_folder(*path, options, query).with_request(matched_pattern.clone()),
);
}
}

Ok(merge_results(results))
}
Expand Down Expand Up @@ -2266,16 +2284,18 @@ async fn handle_exports_imports_field(
}
}

{
let mut duplicates_set = HashSet::new();
results.retain(|item| duplicates_set.insert(*item));
}

let mut resolved_results = Vec::new();
for path in results {
if let Some(path) = normalize_path(path) {
let request = Request::parse(Value::new(format!("./{}", path).into()));
resolved_results.push(resolve_internal_boxed(package_path, request, options).await?);
for (result_path, conditions) in results {
if let Some(result_path) = normalize_path(result_path) {
let request = Request::parse(Value::new(format!("./{}", result_path).into()));
let resolve_result = resolve_internal_boxed(package_path, request, options).await?;
if conditions.is_empty() {
resolved_results.push(resolve_result.with_request(path.to_string()));
} else {
let mut resolve_result = resolve_result.await?.with_request_ref(path.to_string());
resolve_result.add_conditions(conditions);
resolved_results.push(resolve_result.cell());
}
}
}

Expand Down
14 changes: 12 additions & 2 deletions crates/turbopack-core/src/resolve/remap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ impl SubpathValue {
conditions: &BTreeMap<String, ConditionValue>,
unspecified_condition: &ConditionValue,
condition_overrides: &mut HashMap<&'a str, ConditionValue>,
target: &mut Vec<&'a str>,
target: &mut Vec<(&'a str, Vec<(&'a str, bool)>)>,
) -> bool {
match self {
SubpathValue::Alternatives(list) => {
Expand Down Expand Up @@ -150,7 +150,17 @@ impl SubpathValue {
false
}
SubpathValue::Result(r) => {
target.push(r);
target.push((
r,
condition_overrides
.iter()
.filter_map(|(k, v)| match v {
ConditionValue::Set => Some((*k, true)),
ConditionValue::Unset => Some((*k, false)),
ConditionValue::Unknown => None,
})
.collect(),
));
true
}
SubpathValue::Excluded => true,
Expand Down
5 changes: 3 additions & 2 deletions crates/turbopack-ecmascript-runtime/js/src/build/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ type ExternalImport = (id: ModuleId) => Promise<Exports | EsmNamespaceObject>;
type ResolveAbsolutePath = (modulePath?: string) => string;

interface TurbopackNodeBuildContext extends TurbopackBaseContext {
p: ResolveAbsolutePath;
P: ResolveAbsolutePath;
R: ResolvePathFromModule;
x: ExternalRequire;
y: ExternalImport;
Expand Down Expand Up @@ -179,6 +179,7 @@ function instantiateModule(id: ModuleId, source: SourceInfo): Module {
i: esmImport.bind(null, module),
s: esmExport.bind(null, module, module.exports),
j: dynamicExport.bind(null, module, module.exports),
p: moduleLookup,
v: exportValue.bind(null, module),
n: exportNamespace.bind(null, module),
m: module,
Expand All @@ -188,7 +189,7 @@ function instantiateModule(id: ModuleId, source: SourceInfo): Module {
w: loadWebAssembly,
u: loadWebAssemblyModule,
g: globalThis,
p: resolveAbsolutePath,
P: resolveAbsolutePath,
U: relativeURL,
R: createResolvePathFromModule(r),
__dirname: module.id.replace(/(^|\/)[\/]+$/, ""),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,7 @@ function instantiateModule(id: ModuleId, source: SourceInfo): Module {
i: esmImport.bind(null, module),
s: esmExport.bind(null, module, module.exports),
j: dynamicExport.bind(null, module, module.exports),
p: moduleLookup,
v: exportValue.bind(null, module),
n: exportNamespace.bind(null, module),
m: module,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ type EsmExport = (exportGetters: Record<string, () => any>) => void;
type ExportValue = (value: any) => void;
type ExportNamespace = (namespace: any) => void;
type DynamicExport = (object: Record<string, any>) => void;
type ModuleLookup = (
object: Record<string, any>,
name: string,
returnPromise?: boolean
) => any;

type LoadChunk = (chunkPath: ChunkPath) => Promise<any> | undefined;
type LoadWebAssembly = (
Expand Down Expand Up @@ -61,6 +66,7 @@ interface TurbopackBaseContext {
i: EsmImport;
s: EsmExport;
j: DynamicExport;
p: ModuleLookup;
v: ExportValue;
n: ExportNamespace;
m: Module;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,28 @@ function dynamicExport(
}
}

/**
* Access one entry from a mapping from name to functor.
*/
function moduleLookup(
map: Record<string, () => any>,
name: string,
returnPromise: boolean = false
) {
if (hasOwnProperty.call(map, name)) {
return map[name]();
}
const e = new Error(`Cannot find module '${name}'`);
(e as any).code = "MODULE_NOT_FOUND";
if (returnPromise) {
return Promise.resolve().then(() => {
throw e;
});
} else {
throw e;
}
}

function exportValue(module: Module, value: any) {
module.exports = value;
}
Expand Down
3 changes: 2 additions & 1 deletion crates/turbopack-ecmascript/src/chunk/item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,8 @@ impl EcmascriptChunkItemContent {
"M: __turbopack_modules__",
"l: __turbopack_load__",
"j: __turbopack_dynamic__",
"p: __turbopack_resolve_absolute_path__",
"p: __turbopack_lookup__",
"P: __turbopack_resolve_absolute_path__",
"U: __turbopack_relative_url__",
"R: __turbopack_resolve_module_id_path__",
"g: global",
Expand Down
74 changes: 35 additions & 39 deletions crates/turbopack-ecmascript/src/references/amd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize};
use swc_core::{
common::DUMMY_SP,
ecma::{
ast::{CallExpr, Callee, Expr, ExprOrSpread},
ast::{CallExpr, Callee, Expr, ExprOrSpread, Lit},
utils::private_ident,
},
quote, quote_expr,
Expand Down Expand Up @@ -83,11 +83,12 @@ impl ValueToString for AmdDefineAssetReference {
#[turbo_tasks::value_impl]
impl ChunkableModuleReference for AmdDefineAssetReference {}

#[derive(
ValueDebugFormat, Debug, PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, Copy, Clone,
)]
#[derive(ValueDebugFormat, Debug, PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, Clone)]
pub enum AmdDefineDependencyElement {
Request(Vc<Request>),
Request {
request: Vc<Request>,
request_str: String,
},
Exports,
Module,
Require,
Expand Down Expand Up @@ -147,24 +148,25 @@ impl CodeGenerateable for AmdDefineWithDependenciesCodeGen {
.iter()
.map(|element| async move {
Ok(match element {
AmdDefineDependencyElement::Request(request) => {
ResolvedElement::PatternMapping(
PatternMapping::resolve_request(
*request,
AmdDefineDependencyElement::Request {
request,
request_str,
} => ResolvedElement::PatternMapping {
pattern_mapping: PatternMapping::resolve_request(
*request,
self.origin,
Vc::upcast(chunking_context),
cjs_resolve(
self.origin,
Vc::upcast(chunking_context),
cjs_resolve(
self.origin,
*request,
Some(self.issue_source),
try_to_severity(self.in_try),
),
Value::new(ChunkItem),
)
.await?,
request.await?.request(),
*request,
Some(self.issue_source),
try_to_severity(self.in_try),
),
Value::new(ChunkItem),
)
}
.await?,
request_str: request_str.to_string(),
},
AmdDefineDependencyElement::Exports => {
ResolvedElement::Expr(quote!("exports" as Expr))
}
Expand Down Expand Up @@ -193,7 +195,10 @@ impl CodeGenerateable for AmdDefineWithDependenciesCodeGen {
}

enum ResolvedElement {
PatternMapping(ReadRef<PatternMapping>, Option<String>),
PatternMapping {
pattern_mapping: ReadRef<PatternMapping>,
request_str: String,
},
Expr(Expr),
}

Expand All @@ -219,23 +224,14 @@ fn transform_amd_factory(
let deps = resolved_elements
.iter()
.map(|element| match element {
ResolvedElement::PatternMapping(pm, req) => match &**pm {
PatternMapping::Invalid => quote_expr!("undefined"),
pm => {
let arg = if let Some(req) = req {
pm.apply(req.as_str().into())
} else {
pm.create()
};

if pm.is_internal_import() {
quote_expr!("__turbopack_require__($arg)", arg: Expr = arg)
} else {
quote_expr!("__turbopack_external_require__($arg)", arg: Expr = arg)
}
}
},
ResolvedElement::Expr(expr) => Box::new(expr.clone()),
ResolvedElement::PatternMapping {
pattern_mapping: pm,
request_str: request,
} => {
let key_expr = Expr::Lit(Lit::Str(request.as_str().into()));
pm.create_require(key_expr)
}
ResolvedElement::Expr(expr) => expr.clone(),
})
.map(ExprOrSpread::from)
.collect();
Expand Down
Loading