Unverified Commit ee15ecd6 authored by Steven's avatar Steven Committed by GitHub

Merge branch 'canary' into nft-0-30-1

parents 393c5771 101d2d2a
......@@ -39,6 +39,10 @@ async function main() {
stdio: 'inherit',
shell: true,
})
await execa(`git fetch origin ${tagName}`, {
stdio: 'inherit',
shell: true,
})
await execa(`git reset --hard ${tagName}`, {
stdio: 'inherit',
shell: true,
......
......@@ -176,6 +176,9 @@ struct TurboTasksBackendInner<B: BackingStorage> {
storage: Storage,
/// When true, the backing_storage has data that is not in the local storage.
local_is_partial: AtomicBool,
/// Number of executing operations + Highest bit is set when snapshot is
/// requested. When that bit is set, operations should pause until the
/// snapshot is completed. When the bit is set and in progress counter
......@@ -231,6 +234,9 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
options.active_tracking = false;
}
let small_preallocation = options.small_preallocation;
let next_task_id = backing_storage
.next_free_task_id()
.expect("Failed to get task id");
Self {
options,
start_time: Instant::now(),
......@@ -238,9 +244,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
.next_session_id()
.expect("Failed get session id"),
persisted_task_id_factory: IdFactoryWithReuse::new(
backing_storage
.next_free_task_id()
.expect("Failed to get task id"),
next_task_id,
TaskId::try_from(TRANSIENT_TASK_BIT - 1).unwrap(),
),
transient_task_id_factory: IdFactoryWithReuse::new(
......@@ -250,6 +254,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
persisted_task_cache_log: need_log.then(|| Sharded::new(shard_amount)),
task_cache: BiMap::new(),
transient_tasks: FxDashMap::default(),
local_is_partial: AtomicBool::new(next_task_id != TaskId::MIN),
storage: Storage::new(small_preallocation),
in_progress_operations: AtomicUsize::new(0),
snapshot_request: Mutex::new(SnapshotRequest::new()),
......@@ -910,6 +915,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
return Some(task_type);
}
if self.should_restore()
&& self.local_is_partial.load(Ordering::Acquire)
&& !task_id.is_transient()
&& let Some(task_type) = unsafe {
self.backing_storage
......@@ -1271,16 +1277,21 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
return task_id;
}
let tx = self
.should_restore()
let check_backing_storage =
self.should_restore() && self.local_is_partial.load(Ordering::Acquire);
let tx = check_backing_storage
.then(|| self.backing_storage.start_read_transaction())
.flatten();
let task_id = {
// Safety: `tx` is a valid transaction from `self.backend.backing_storage`.
if let Some(task_id) = unsafe {
self.backing_storage
.forward_lookup_task_cache(tx.as_ref(), &task_type)
.expect("Failed to lookup task id")
check_backing_storage
.then(|| {
self.backing_storage
.forward_lookup_task_cache(tx.as_ref(), &task_type)
.expect("Failed to lookup task id")
})
.flatten()
} {
self.track_cache_hit(&task_type);
let _ = self.task_cache.try_insert(Arc::new(task_type), task_id);
......
......@@ -11,6 +11,7 @@ mod update_output;
use std::{
fmt::{Debug, Formatter},
mem::transmute,
sync::atomic::Ordering,
};
use serde::{Deserialize, Serialize};
......@@ -113,6 +114,12 @@ where
category: TaskDataCategory,
) -> Vec<CachedDataItem> {
if matches!(self.transaction, TransactionState::None) {
let check_backing_storage = self.backend.should_restore()
&& self.backend.local_is_partial.load(Ordering::Acquire);
if !check_backing_storage {
// If we don't need to restore, we can just return an empty vector
return Vec::new();
}
let tx = self.backend.backing_storage.start_read_transaction();
let tx = tx.map(|tx| {
// Safety: self is actually valid for 'a, so it's safe to transmute 'l to 'a
......
......@@ -262,12 +262,11 @@ impl<T: KeyValueDatabase + Send + Sync + 'static> BackingStorageSealed
type ReadTransaction<'l> = T::ReadTransaction<'l>;
fn next_free_task_id(&self) -> Result<TaskId> {
Ok(TaskId::try_from(
self.inner
.get_infra_u32(META_KEY_NEXT_FREE_TASK_ID)
.context("Unable to read next free task id from database")?
.unwrap_or(1),
)?)
Ok(self
.inner
.get_infra_u32(META_KEY_NEXT_FREE_TASK_ID)
.context("Unable to read next free task id from database")?
.map_or(Ok(TaskId::MIN), TaskId::try_from)?)
}
fn next_session_id(&self) -> Result<SessionId> {
......
......@@ -25,6 +25,7 @@ pub mod introspect;
pub mod issue;
pub mod module;
pub mod module_graph;
pub mod node_addon_module;
pub mod output;
pub mod package_json;
pub mod proxied_asset;
......
use std::sync::LazyLock;
use anyhow::Result;
use regex::Regex;
use turbo_rcstr::rcstr;
use turbo_tasks::{FxIndexSet, ResolvedVc, TryJoinIterExt, Vc};
use turbo_tasks_fs::{FileSystemEntryType, FileSystemPath};
use crate::{
asset::{Asset, AssetContent},
file_source::FileSource,
ident::AssetIdent,
module::Module,
raw_module::RawModule,
reference::{ModuleReferences, TracedModuleReference},
resolve::pattern::{Pattern, PatternMatch, read_matches},
source::Source,
};
/// A module corresponding to `.node` files.
#[turbo_tasks::value]
pub struct NodeAddonModule {
source: ResolvedVc<Box<dyn Source>>,
}
#[turbo_tasks::value_impl]
impl NodeAddonModule {
#[turbo_tasks::function]
pub fn new(source: ResolvedVc<Box<dyn Source>>) -> Vc<NodeAddonModule> {
NodeAddonModule { source }.cell()
}
}
#[turbo_tasks::value_impl]
impl Module for NodeAddonModule {
#[turbo_tasks::function]
fn ident(&self) -> Vc<AssetIdent> {
self.source.ident().with_modifier(rcstr!("node addon"))
}
#[turbo_tasks::function]
async fn references(&self) -> Result<Vc<ModuleReferences>> {
static SHARP_BINARY_REGEX: LazyLock<Regex> =
LazyLock::new(|| Regex::new("/sharp-(\\w+-\\w+).node$").unwrap());
let module_path = self.source.ident().path().await?;
// For most .node binaries, we usually assume that they are standalone dynamic library
// binaries that get loaded by some `require` call. So the binary itself doesn't read any
// files by itself, but only when instructed to from the JS side.
//
// For sharp, that is not the case:
// 1. `node_modules/sharp/lib/sharp.js` does `require("@img/sharp-${arch}/sharp.node")`
// which ends up resolving to ...
// 2. @img/sharp-darwin-arm64/lib/sharp-darwin-arm64.node. That is however a dynamic library
// that uses the OS loader to load yet another binary (you can view these via `otool -L`
// on macOS or `ldd` on Linux):
// 3. @img/sharp-libvips-darwin-arm64/libvips.dylib
//
// We could either try to parse the binary and read these dependencies, or (as we do in the
// following) special case sharp and hardcode this dependency.
//
// The JS @vercel/nft implementation has a similar special case:
// https://github.com/vercel/nft/blob/7e915aa02073ec57dc0d6528c419a4baa0f03d40/src/utils/special-cases.ts#L151-L181
if SHARP_BINARY_REGEX.is_match(&module_path.path) {
// module_path might be something like
// node_modules/@img/sharp-darwin-arm64/lib/sharp-darwin-arm64.node
let arch = SHARP_BINARY_REGEX
.captures(&module_path.path)
.unwrap()
.get(1)
.unwrap()
.as_str();
let package_name = format!("@img/sharp-libvips-{arch}");
for folder in [
// This is the list of rpaths (lookup paths) of the shared library, at least on
// macOS and Linux https://github.com/lovell/sharp/blob/c01e272db522a8b7d174bd3be7400a4a87f08702/src/binding.gyp#L158-L201
"../..",
"../../..",
"../../node_modules",
"../../../node_modules",
]
.iter()
.filter_map(|p| module_path.parent().join(p).ok()?.join(&package_name).ok())
{
if matches!(
&*folder.get_type().await?,
FileSystemEntryType::Directory | FileSystemEntryType::Symlink
) {
return Ok(dir_references(folder));
}
}
};
// Most addon modules don't have references to other modules.
Ok(ModuleReferences::empty())
}
}
#[turbo_tasks::value_impl]
impl Asset for NodeAddonModule {
#[turbo_tasks::function]
fn content(&self) -> Vc<AssetContent> {
self.source.content()
}
}
#[turbo_tasks::function]
async fn dir_references(package_dir: FileSystemPath) -> Result<Vc<ModuleReferences>> {
let matches = read_matches(
package_dir.clone(),
rcstr!(""),
true,
Pattern::new(Pattern::Dynamic),
)
.await?;
let mut results: FxIndexSet<FileSystemPath> = FxIndexSet::default();
for pat_match in matches.into_iter() {
match pat_match {
PatternMatch::File(_, file) => {
let realpath = file.realpath_with_links().await?;
results.extend(realpath.symlinks.iter().cloned());
results.insert(realpath.path.clone());
}
PatternMatch::Directory(..) => {}
}
}
Ok(Vc::cell(
results
.into_iter()
.map(async |p| {
Ok(ResolvedVc::upcast(
TracedModuleReference::new(Vc::upcast(RawModule::new(Vc::upcast(
FileSource::new(p),
))))
.to_resolved()
.await?,
))
})
.try_join()
.await?,
))
}
......@@ -42,10 +42,12 @@ use crate::{
raw_module::RawModule,
reference_type::ReferenceType,
resolve::{
alias_map::AliasKey,
node::{node_cjs_resolve_options, node_esm_resolve_options},
parse::stringify_data_uri,
pattern::{PatternMatch, read_matches},
plugin::AfterResolvePlugin,
remap::ReplacedSubpathValueResult,
},
source::{OptionSource, Source, Sources},
};
......@@ -790,7 +792,7 @@ impl ResolveResult {
}
}
pub fn add_conditions<'a>(&mut self, conditions: impl IntoIterator<Item = (&'a str, bool)>) {
pub fn add_conditions(&mut self, conditions: impl IntoIterator<Item = (RcStr, bool)>) {
let mut primary = std::mem::take(&mut self.primary);
for (k, v) in conditions {
for (key, _) in primary.iter_mut() {
......@@ -2694,6 +2696,8 @@ async fn resolve_into_package(
let is_root_match = path.is_match("") || path.is_match("/");
let could_match_others = path.could_match_others("");
let mut export_path_request = path.clone();
export_path_request.push_front(rcstr!(".").into());
for resolve_into_package in options_value.into_package.iter() {
match resolve_into_package {
// handled by the `resolve_into_folder` call below
......@@ -2709,23 +2713,13 @@ async fn resolve_into_package(
continue;
};
let Some(path) = path.as_constant_string() else {
bail!("pattern into an exports field is not implemented yet");
};
let path = if path == "/" {
rcstr!(".")
} else {
format!(".{path}").into()
};
results.push(
handle_exports_imports_field(
package_path.clone(),
package_json_path,
*options,
exports_field,
&path,
export_path_request.clone(),
conditions,
unspecified_conditions,
query,
......@@ -2931,7 +2925,7 @@ async fn handle_exports_imports_field(
package_json_path: FileSystemPath,
options: Vc<ResolveOptions>,
exports_imports_field: &AliasMap<SubpathValue>,
path: &str,
mut path: Pattern,
conditions: &BTreeMap<RcStr, ConditionValue>,
unspecified_conditions: &ConditionValue,
query: RcStr,
......@@ -2939,47 +2933,86 @@ async fn handle_exports_imports_field(
let mut results = Vec::new();
let mut conditions_state = FxHashMap::default();
let req = Pattern::Constant(format!("{path}{query}").into());
let values = exports_imports_field
.lookup(&req)
.map(AliasMatch::try_into_self)
.collect::<Result<Vec<_>>>()?;
if !query.is_empty() {
path.push(query.into());
}
let req = path;
for value in values.iter() {
if value.add_results(
let values = exports_imports_field.lookup(&req);
for value in values {
let value = value?;
if value.output.add_results(
value.prefix,
value.key,
conditions,
unspecified_conditions,
&mut conditions_state,
&mut results,
) {
// Match found, stop (leveraging the lazy `lookup` iterator).
break;
}
}
let mut resolved_results = Vec::new();
for (result_path, conditions) in results {
for ReplacedSubpathValueResult {
result_path,
conditions,
map_prefix,
map_key,
} in results
{
if let Some(result_path) = result_path.with_normalized_path() {
let request = Request::parse(Pattern::Concatenation(vec![
Pattern::Constant(rcstr!("./")),
result_path,
result_path.clone(),
]))
.to_resolved()
.resolve()
.await?;
let resolve_result = Box::pin(resolve_internal_inline(
package_path.clone(),
*request,
request,
options,
))
.await?;
if conditions.is_empty() {
resolved_results.push(resolve_result.with_request(path.into()));
let resolve_result = if let Some(req) = req.as_constant_string() {
resolve_result.with_request(req.clone())
} else {
let mut resolve_result = resolve_result.await?.with_request_ref(path.into());
match map_key {
AliasKey::Exact => resolve_result.with_request(map_prefix.clone().into()),
AliasKey::Wildcard { .. } => {
// - `req` is the user's request (key of the export map)
// - `result_path` is the final request (value of the export map), so
// effectively `'{foo}*{bar}'`
// Because of the assertion in AliasMapLookupIterator, `req` is of the
// form:
// - "prefix...<dynamic>" or
// - "prefix...<dynamic>...suffix"
let mut old_request_key = result_path;
// Remove the Pattern::Constant(rcstr!("./")), from above again
old_request_key.push_front(rcstr!("./").into());
let new_request_key = req.clone();
resolve_result.with_replaced_request_key_pattern(
Pattern::new(old_request_key),
Pattern::new(new_request_key),
)
}
}
};
let resolve_result = if !conditions.is_empty() {
let mut resolve_result = resolve_result.owned().await?;
resolve_result.add_conditions(conditions);
resolved_results.push(resolve_result.cell());
}
resolve_result.cell()
} else {
resolve_result
};
resolved_results.push(resolve_result);
}
}
......@@ -3034,7 +3067,7 @@ async fn resolve_package_internal_with_imports_field(
package_json_path.clone(),
resolve_options,
imports,
specifier,
Pattern::Constant(specifier.clone()),
conditions,
unspecified_conditions,
RcStr::default(),
......
......@@ -418,7 +418,10 @@ async fn import_mapping_to_result(
} else if let Some(request) = request.await?.request() {
request
} else {
bail!("Cannot resolve external reference without request")
bail!(
"Cannot resolve external reference with dynamic request {:?}",
request.request_pattern().await?.describe_as_string()
)
},
*ty,
*traced,
......@@ -434,7 +437,10 @@ async fn import_mapping_to_result(
} else if let Some(request) = request.await?.request() {
request
} else {
bail!("Cannot resolve external reference without request")
bail!(
"Cannot resolve external reference with dynamic request {:?}",
request.request_pattern().await?.describe_as_string()
)
},
ty: *ty,
traced: *traced,
......@@ -517,6 +523,12 @@ impl ImportMap {
// relative requests must not match global wildcard aliases.
let request_pattern = request.request_pattern().await?;
if matches!(*request_pattern, Pattern::Dynamic | Pattern::DynamicNoSlash) {
// You could probably conceive of cases where this isn't correct. But the dynamic will
// just match every single entry in the import map, which is not what we want.
return Ok(ImportMapResult::NoEntry);
}
let (req_rel, rest) = request_pattern.split_could_match("./");
let (req_rel_parent, req_rest) =
rest.map(|r| r.split_could_match("../")).unwrap_or_default();
......@@ -540,12 +552,7 @@ impl ImportMap {
.chain(lookup_rel_parent.into_iter())
.chain(lookup.into_iter())
.map(async |result| {
import_mapping_to_result(
*result.try_join_into_self().await?,
lookup_path.clone(),
request,
)
.await
import_mapping_to_result(*result?.output.await?, lookup_path.clone(), request).await
})
.try_join()
.await?;
......
......@@ -80,6 +80,9 @@ fn longest_common_prefix<'a>(strings: &[&'a str]) -> &'a str {
if strings.is_empty() {
return "";
}
if let [single] = strings {
return single;
}
let first = strings[0];
let mut len = first.len();
for str in &strings[1..] {
......@@ -151,6 +154,10 @@ impl Pattern {
// Concatenations, so extracting the first/only Concatenation child
// elements is enough.
if let Pattern::Constant(c) = self {
return c;
}
fn collect_constant_prefix<'a: 'b, 'b>(pattern: &'a Pattern, result: &mut Vec<&'b str>) {
match pattern {
Pattern::Constant(c) => {
......@@ -328,10 +335,10 @@ impl Pattern {
self.normalize()
}
//// Replace all `*`s in `template` with self.
////
//// Handle top-level alternatives separately so that multiple star placeholders
//// match the same pattern instead of the whole alternative.
/// Replace all `*`s in `template` with self.
///
/// Handle top-level alternatives separately so that multiple star placeholders
/// match the same pattern instead of the whole alternative.
pub fn spread_into_star(&self, template: &str) -> Pattern {
if template.contains("*") {
let alternatives: Box<dyn Iterator<Item = &Pattern>> = match self {
......@@ -388,6 +395,12 @@ impl Pattern {
*self = pat;
return;
}
if let Pattern::Constant(pat) = &pat
&& pat.is_empty()
{
// Short-circuit to ignore when trying to append an empty string.
return;
}
match (self, pat) {
(Pattern::Concatenation(list), Pattern::Concatenation(more)) => {
......@@ -467,6 +480,12 @@ impl Pattern {
pub fn with_normalized_path(&self) -> Option<Pattern> {
let mut new = self.clone();
#[derive(Debug)]
enum PathElement {
Segment(Pattern),
Separator,
}
fn normalize_path_internal(pattern: &mut Pattern) -> Option<()> {
match pattern {
Pattern::Constant(c) => {
......@@ -480,27 +499,49 @@ impl Pattern {
for segment in list.iter() {
match segment {
Pattern::Constant(str) => {
for segment in str.split('/') {
let mut iter = str.split('/').peekable();
while let Some(segment) = iter.next() {
match segment {
"." | "" => {}
"." | "" => {
// Ignore empty segments
continue;
}
".." => {
segments.pop()?;
if segments.is_empty() {
// Leaving root
return None;
}
if let Some(PathElement::Separator) = segments.last()
&& let Some(PathElement::Segment(
Pattern::Constant(_),
)) = segments.get(segments.len() - 2)
{
// Resolve `foo/..`
segments.truncate(segments.len() - 2);
continue;
}
// Keep it, can't pop non-constant segment.
segments.push(PathElement::Segment(Pattern::Constant(
rcstr!(".."),
)));
}
segment => {
segments.push(vec![Pattern::Constant(segment.into())]);
segments.push(PathElement::Segment(Pattern::Constant(
segment.into(),
)));
}
}
}
if str.ends_with("/") {
segments.push(vec![]);
if iter.peek().is_some() {
// If not last, add separator
segments.push(PathElement::Separator);
}
}
}
Pattern::Dynamic | Pattern::DynamicNoSlash => {
if segments.is_empty() {
segments.push(vec![]);
}
let last = segments.last_mut().unwrap();
last.push(segment.clone());
segments.push(PathElement::Segment(segment.clone()));
}
Pattern::Alternatives(_) | Pattern::Concatenation(_) => {
panic!("for with_normalized_path the Pattern must be normalized");
......@@ -510,10 +551,10 @@ impl Pattern {
let separator = rcstr!("/");
*list = segments
.into_iter()
.flat_map(|c| {
std::iter::once(Pattern::Constant(separator.clone())).chain(c)
.map(|c| match c {
PathElement::Segment(p) => p,
PathElement::Separator => Pattern::Constant(separator.clone()),
})
.skip(1)
.collect();
Some(())
}
......@@ -1909,6 +1950,12 @@ mod tests {
Pattern::Constant(rcstr!("a/c/d"))
])
);
assert_eq!(
Pattern::Constant(rcstr!("a/b/"))
.with_normalized_path()
.unwrap(),
Pattern::Constant(rcstr!("a/b"))
);
// Dynamic is a segment itself
assert_eq!(
......@@ -1919,10 +1966,14 @@ mod tests {
])
.with_normalized_path()
.unwrap(),
Pattern::Constant(rcstr!("a/b/c"))
Pattern::Concatenation(vec![
Pattern::Constant(rcstr!("a/b/")),
Pattern::Dynamic,
Pattern::Constant(rcstr!("../c"))
])
);
// Dynamic is only part of the second segment
// Dynamic is part of a segment
assert_eq!(
Pattern::Concatenation(vec![
Pattern::Constant(rcstr!("a/b")),
......@@ -1931,7 +1982,25 @@ mod tests {
])
.with_normalized_path()
.unwrap(),
Pattern::Constant(rcstr!("a/c"))
Pattern::Concatenation(vec![
Pattern::Constant(rcstr!("a/b")),
Pattern::Dynamic,
Pattern::Constant(rcstr!("../c"))
])
);
assert_eq!(
Pattern::Concatenation(vec![
Pattern::Constant(rcstr!("src/")),
Pattern::Dynamic,
Pattern::Constant(rcstr!(".js"))
])
.with_normalized_path()
.unwrap(),
Pattern::Concatenation(vec![
Pattern::Constant(rcstr!("src/")),
Pattern::Dynamic,
Pattern::Constant(rcstr!(".js"))
])
);
}
......
use std::{collections::BTreeMap, fmt::Display, ops::Deref};
use std::{borrow::Cow, collections::BTreeMap, fmt::Display, ops::Deref};
use anyhow::{Result, bail};
use rustc_hash::FxHashMap;
......@@ -12,6 +12,7 @@ use super::{
options::ConditionValue,
pattern::Pattern,
};
use crate::resolve::alias_map::AliasKey;
/// A small helper type to differentiate parsing exports and imports fields.
#[derive(Copy, Clone)]
......@@ -69,44 +70,44 @@ pub enum ReplacedSubpathValue {
impl AliasTemplate for SubpathValue {
type Output<'a>
= Result<ReplacedSubpathValue>
= ReplacedSubpathValue
where
Self: 'a;
fn convert(&self) -> Result<ReplacedSubpathValue> {
Ok(match self {
fn convert(&self) -> ReplacedSubpathValue {
match self {
SubpathValue::Alternatives(list) => ReplacedSubpathValue::Alternatives(
list.iter()
.map(|value: &SubpathValue| value.convert())
.collect::<Result<Vec<_>>>()?,
.collect::<Vec<_>>(),
),
SubpathValue::Conditional(list) => ReplacedSubpathValue::Conditional(
list.iter()
.map(|(condition, value)| Ok((condition.clone(), value.convert()?)))
.collect::<Result<Vec<_>>>()?,
.map(|(condition, value)| (condition.clone(), value.convert()))
.collect::<Vec<_>>(),
),
SubpathValue::Result(value) => ReplacedSubpathValue::Result(value.clone().into()),
SubpathValue::Excluded => ReplacedSubpathValue::Excluded,
})
}
}
fn replace(&self, capture: &Pattern) -> Result<ReplacedSubpathValue> {
Ok(match self {
fn replace(&self, capture: &Pattern) -> ReplacedSubpathValue {
match self {
SubpathValue::Alternatives(list) => ReplacedSubpathValue::Alternatives(
list.iter()
.map(|value: &SubpathValue| value.replace(capture))
.collect::<Result<Vec<_>>>()?,
.collect::<Vec<_>>(),
),
SubpathValue::Conditional(list) => ReplacedSubpathValue::Conditional(
list.iter()
.map(|(condition, value)| Ok((condition.clone(), value.replace(capture)?)))
.collect::<Result<Vec<_>>>()?,
.map(|(condition, value)| (condition.clone(), value.replace(capture)))
.collect::<Vec<_>>(),
),
SubpathValue::Result(value) => {
ReplacedSubpathValue::Result(capture.spread_into_star(value))
}
SubpathValue::Excluded => ReplacedSubpathValue::Excluded,
})
}
}
}
......@@ -230,22 +231,35 @@ impl SubpathValue {
}
}
pub struct ReplacedSubpathValueResult<'a, 'b> {
pub result_path: Pattern,
pub conditions: Vec<(RcStr, bool)>,
pub map_prefix: Cow<'a, str>,
pub map_key: &'b AliasKey,
}
impl ReplacedSubpathValue {
// TODO
#[allow(clippy::type_complexity)]
/// Walks the [ReplacedSubpathValue] and adds results to the `target`
/// vector. It uses the `conditions` to skip or enter conditional
/// results. The state of conditions is stored within
/// `condition_overrides`, which is also exposed to the consumer.
pub fn add_results<'a>(
&'a self,
pub fn add_results<'a, 'b>(
self,
prefix: Cow<'a, str>,
key: &'b AliasKey,
conditions: &BTreeMap<RcStr, ConditionValue>,
unspecified_condition: &ConditionValue,
condition_overrides: &mut FxHashMap<&'a str, ConditionValue>,
target: &mut Vec<(&'a Pattern, Vec<(&'a str, bool)>)>,
condition_overrides: &mut FxHashMap<RcStr, ConditionValue>,
target: &mut Vec<ReplacedSubpathValueResult<'a, 'b>>,
) -> bool {
match self {
ReplacedSubpathValue::Alternatives(list) => {
for value in list {
if value.add_results(
prefix.clone(),
key,
conditions,
unspecified_condition,
condition_overrides,
......@@ -263,12 +277,14 @@ impl ReplacedSubpathValue {
} else {
condition_overrides
.get(condition.as_str())
.or_else(|| conditions.get(condition))
.or_else(|| conditions.get(&condition))
.unwrap_or(unspecified_condition)
};
match condition_value {
ConditionValue::Set => {
if value.add_results(
prefix.clone(),
key,
conditions,
unspecified_condition,
condition_overrides,
......@@ -279,8 +295,10 @@ impl ReplacedSubpathValue {
}
ConditionValue::Unset => {}
ConditionValue::Unknown => {
condition_overrides.insert(condition, ConditionValue::Set);
condition_overrides.insert(condition.clone(), ConditionValue::Set);
if value.add_results(
prefix.clone(),
key,
conditions,
unspecified_condition,
condition_overrides,
......@@ -296,17 +314,19 @@ impl ReplacedSubpathValue {
false
}
ReplacedSubpathValue::Result(r) => {
target.push((
r,
condition_overrides
target.push(ReplacedSubpathValueResult {
result_path: r,
conditions: condition_overrides
.iter()
.filter_map(|(k, v)| match v {
ConditionValue::Set => Some((*k, true)),
ConditionValue::Unset => Some((*k, false)),
ConditionValue::Set => Some((k.clone(), true)),
ConditionValue::Unset => Some((k.clone(), false)),
ConditionValue::Unknown => None,
})
.collect(),
));
map_prefix: prefix,
map_key: key,
});
true
}
ReplacedSubpathValue::Excluded => true,
......
......@@ -20,7 +20,7 @@ use swc_core::{
visit::{fields::*, *},
},
};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::ResolvedVc;
use turbopack_core::source::Source;
......@@ -365,13 +365,18 @@ impl EvalContext {
if idx.is_multiple_of(2) {
let idx = idx / 2;
let e = &e.quasis[idx];
if raw {
values.push(JsValue::from(e.raw.clone()));
// Ignore empty strings quasis, happens frequently with e.g. after the
// placeholder in `something${v}`.
if !e.raw.is_empty() {
values.push(JsValue::from(e.raw.clone()));
}
} else {
match &e.cooked {
Some(v) => {
values.push(JsValue::from(v.clone()));
if !v.is_empty() {
values.push(JsValue::from(v.clone()));
}
}
// This is actually unreachable
None => return JsValue::unknown_empty(true, ""),
......@@ -385,11 +390,11 @@ impl EvalContext {
}
}
if values.len() == 1 {
return values.into_iter().next().unwrap();
match values.len() {
0 => JsValue::Constant(ConstantValue::Str(rcstr!("").into())),
1 => values.into_iter().next().unwrap(),
_ => JsValue::concat(values),
}
JsValue::concat(values)
}
fn eval_ident(&self, i: &Ident) -> JsValue {
......
......@@ -3,7 +3,7 @@
"a",
Constant(
Str(
Atom(
RcStr(
"",
),
),
......
......@@ -4,6 +4,9 @@ function requirePkg(s) {
function requireOrgPkg(s) {
return require(`@org/pkg-${s}`)
}
function requireExportsField(s) {
return require(`exports-${s}/foo`)
}
it('should correctly handle dynamic parts in regular package name', () => {
expect(requirePkg('a').default).toBe('pkg-a')
......@@ -15,3 +18,7 @@ it('should correctly handle dynamic parts in namespaced package name', () => {
expect(requireOrgPkg('b').default).toBe('org/pkg-b')
expect(requireOrgPkg('c').default).toBe('org/pkg-c')
})
it('should correctly handle dynamic parts in regular package name with exports field', () => {
expect(requireExportsField('a').default).toBe('exports-a')
expect(requireExportsField('b').default).toBe('exports-b')
})
function requireRoot(s) {
return require(`pkg/${s}`)
}
function requireExact(s) {
return require(`pkg/exact-${s}`)
}
function requireWildcardSuffix(s) {
return require(`pkg/wildcard-suffix-${s}`)
}
function requireWildcard(s) {
return require(`pkg/wildcard-${s}`)
}
function requireExactAConstantSuffix(s) {
return require(`pkg/${s}exact-a`)
}
it('should correctly handle dynamic requests into exports field (exact)', () => {
// TODO it currently only returns a single entry
// expect(requireExact('a').default).toBe('a')
// expect(requireExact('b').default).toBe('b')
expect(requireExact('c').default).toBe('c')
})
it('should correctly handle dynamic requests into exports field (wildcard with suffix)', () => {
expect(requireWildcardSuffix('a').default).toBe('a')
expect(requireWildcardSuffix('b').default).toBe('b')
expect(requireWildcardSuffix('c').default).toBe('c')
})
it('should correctly handle dynamic requests into exports field (wildcard)', () => {
expect(requireWildcard('a').default).toBe('a')
expect(requireWildcard('b').default).toBe('b')
expect(requireWildcard('c').default).toBe('c')
})
it('should correctly handle dynamic requests into exports field (empty dynamic prefix)', () => {
// TODO it currently only returns a single entry
// expect(requireExactAConstantSuffix('').default).toBe('a')
expect(requireExactAConstantSuffix('sub/').default).toBe('a')
})
it('should correctly handle dynamic requests into exports field (mixed)', () => {
// TODO it currently only returns a single entry
// expect(requireRoot('exact-a').default).toBe('a')
expect(requireRoot('sub/exact-a').default).toBe('a')
// expect(requireRoot('exact-b').default).toBe('b')
// // expect(requireRoot('exact-c').default).toBe('c')
// expect(requireRoot('wildcard-suffix-a').default).toBe('a')
// expect(requireRoot('wildcard-suffix-b').default).toBe('b')
// expect(requireRoot('wildcard-suffix-c').default).toBe('c')
// expect(requireRoot('wildcard-a').default).toBe('a')
// expect(requireRoot('wildcard-b').default).toBe('b')
// expect(requireRoot('wildcard-c').default).toBe('c')
})
{
"name": "pkg",
"version": "0.0.0",
"exports": {
"./exact-a": "./src/a.js",
"./sub/exact-a": "./src/a.js",
"./exact-b": "./src/b.js",
"./exact-c": "./src/c.js",
"./wildcard-suffix-*": "./src/*.js",
"./wildcard-*": "./src/*"
}
}
import { loadSub, loadSubNested, loadSubFallback } from './src/foo'
import { loadSub, /* loadSubNested, */ loadSubFallback } from './src/foo'
it('should support dynamic requests with tsconfig.paths', () => {
expect(loadSub('file2.js').default).toBe('file2')
......@@ -8,9 +8,9 @@ it('should support dynamic requests with tsconfig.paths and without extension',
expect(loadSub('file2').default).toBe('file2')
})
it('should support dynamic requests with tsconfig.paths and multiple dynamic parts', () => {
expect(loadSubNested('file2').default).toBe('file2')
})
// it('should support dynamic requests with tsconfig.paths and multiple dynamic parts', () => {
// expect(loadSubNested('file2').default).toBe('file2')
// })
it('should support dynamic requests with tsconfig.paths fallbacks', () => {
expect(loadSubFallback('file1').default).toBe('file1')
......
......@@ -2,9 +2,10 @@ export function loadSub(v: string) {
return require(`@/sub/${v}`)
}
export function loadSubNested(v: string) {
return require(`@/sub-nested/${v}/${v}.js`)
}
// TODO not supported
// export function loadSubNested(v: string) {
// return require(`@/sub-nested/${v}/${v}.js`)
// }
export function loadSubFallback(v: string) {
return require(`@sub/${v}`)
......
......@@ -39,6 +39,7 @@ use turbopack_core::{
ident::Layer,
issue::{IssueExt, IssueSource, StyledString, module::ModuleIssue},
module::Module,
node_addon_module::NodeAddonModule,
output::OutputAsset,
raw_module::RawModule,
reference_type::{
......@@ -236,6 +237,9 @@ async fn apply_module_type(
}
ModuleType::Json => ResolvedVc::upcast(JsonModuleAsset::new(*source).to_resolved().await?),
ModuleType::Raw => ResolvedVc::upcast(RawModule::new(*source).to_resolved().await?),
ModuleType::NodeAddon => {
ResolvedVc::upcast(NodeAddonModule::new(*source).to_resolved().await?)
}
ModuleType::CssModule => ResolvedVc::upcast(
ModuleCssAsset::new(*source, Vc::upcast(module_asset_context))
.to_resolved()
......
......@@ -414,7 +414,7 @@ impl ModuleOptions {
RuleCondition::any(vec![RuleCondition::ResourcePathEndsWith(
".node".to_string(),
)]),
vec![ModuleRuleEffect::ModuleType(ModuleType::Raw)],
vec![ModuleRuleEffect::ModuleType(ModuleType::NodeAddon)],
),
// WebAssembly
ModuleRule::new(
......
......@@ -119,6 +119,7 @@ pub enum ModuleType {
},
Json,
Raw,
NodeAddon,
CssModule,
Css {
ty: CssModuleAssetType,
......
......@@ -158,6 +158,18 @@ static ALLOC: turbo_tasks_malloc::TurboMalloc = turbo_tasks_malloc::TurboMalloc;
#[case::sentry("integration/sentry.js")]
#[case::sequelize("integration/sequelize.js")]
#[case::serialport("integration/serialport.js")]
#[cfg_attr(
target_os = "windows",
should_panic(expected = "Something went wrong installing the \"sharp\" module"),
case::sharp030("integration/sharp030.js")
)]
#[cfg_attr(not(target_os = "windows"), case::sharp030("integration/sharp030.js"))]
#[cfg_attr(
target_os = "windows",
should_panic(expected = "Something went wrong installing the \"sharp\" module"),
case::sharp033("integration/sharp033.js")
)]
#[cfg_attr(not(target_os = "windows"), case::sharp033("integration/sharp033.js"))]
#[cfg_attr(
target_os = "windows",
should_panic(expected = "Something went wrong installing the \"sharp\" module"),
......
const sharp = require('sharp030')
const path = require('path')
const roundedCorners = Buffer.from(
'<svg><rect x="0" y="0" width="200" height="200" rx="50" ry="50"/></svg>'
)
sharp(roundedCorners).resize(200, 200).png().toBuffer()
sharp(path.resolve(__dirname, 'fixtures/vercel.svg'))
.resize({ width: 100, height: 100 })
.jpeg()
.toBuffer()
const sharp = require('sharp033')
const path = require('path')
const roundedCorners = Buffer.from(
'<svg><rect x="0" y="0" width="200" height="200" rx="50" ry="50"/></svg>'
)
sharp(roundedCorners).resize(200, 200).png().toBuffer()
sharp(path.resolve(__dirname, 'fixtures/vercel.svg'))
.resize({ width: 100, height: 100 })
.jpeg()
.toBuffer()
......@@ -101,7 +101,9 @@
"semver": "^7.1.1",
"sequelize": "^5.9.3",
"serialport": "^13.0.0",
"sharp": "^0.30.0",
"sharp030": "npm:sharp@^0.30.0",
"sharp033": "npm:sharp@^0.33.0",
"sharp": "^0.34.0",
"shiki": "^0.14.5",
"socket.io": "^2.4.0",
"socket.io-client": "^2.2.0",
......
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