Skip to content
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

feat: support getResolve in external function context #8577

Merged
merged 3 commits into from
Dec 6, 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
7 changes: 6 additions & 1 deletion crates/node_binding/binding.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,11 @@ export declare class JsStats {
getLogging(acceptedTypes: number): Array<JsStatsLogging>
}

export declare class RawExternalItemFnCtx {
data(): RawExternalItemFnCtxData
getResolver(): JsResolver
}

export declare class Rspack {
constructor(options: RawOptions, builtinPlugins: Array<BuiltinPlugin>, registerJsTaps: RegisterJsTaps, outputFilesystem: ThreadsafeNodeFS, resolverFactoryReference: JsResolverFactory)
setNonSkippableRegisters(kinds: Array<RegisterJsTapKind>): void
Expand Down Expand Up @@ -1397,7 +1402,7 @@ export interface RawExposeOptions {
import: Array<string>
}

export interface RawExternalItemFnCtx {
export interface RawExternalItemFnCtxData {
request: string
context: string
dependencyType: string
Expand Down
42 changes: 39 additions & 3 deletions crates/rspack_binding_options/src/options/raw_external.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
use std::collections::HashMap;
use std::fmt::Debug;
use std::sync::Arc;

use napi::bindgen_prelude::Either4;
use napi_derive::napi;
use rspack_core::ExternalItemFnCtx;
use rspack_binding_values::JsResolver;
use rspack_core::{ExternalItem, ExternalItemFnResult, ExternalItemValue};
use rspack_core::{ExternalItemFnCtx, ResolveOptionsWithDependencyType, ResolverFactory};
use rspack_napi::threadsafe_function::ThreadsafeFunction;
use rspack_regex::RspackRegex;

Expand Down Expand Up @@ -68,15 +70,47 @@ pub struct ContextInfo {
pub issuer: String,
}

#[derive(Debug, Clone)]
#[napi(object)]
#[derive(Debug)]
#[napi]
pub struct RawExternalItemFnCtx {
request: String,
context: String,
dependency_type: String,
context_info: ContextInfo,
resolve_options_with_dependency_type: ResolveOptionsWithDependencyType,
resolver_factory: Arc<ResolverFactory>,
}

#[derive(Debug)]
#[napi(object)]
pub struct RawExternalItemFnCtxData {
pub request: String,
pub context: String,
pub dependency_type: String,
pub context_info: ContextInfo,
}

#[napi]
impl RawExternalItemFnCtx {
#[napi]
pub fn data(&self) -> RawExternalItemFnCtxData {
RawExternalItemFnCtxData {
request: self.request.clone(),
context: self.context.clone(),
dependency_type: self.dependency_type.clone(),
context_info: self.context_info.clone(),
}
}

#[napi]
pub fn get_resolver(&self) -> JsResolver {
JsResolver::new(
self.resolver_factory.clone(),
self.resolve_options_with_dependency_type.clone(),
)
}
}

impl From<ExternalItemFnCtx> for RawExternalItemFnCtx {
fn from(value: ExternalItemFnCtx) -> Self {
Self {
Expand All @@ -86,6 +120,8 @@ impl From<ExternalItemFnCtx> for RawExternalItemFnCtx {
context_info: ContextInfo {
issuer: value.context_info.issuer,
},
resolve_options_with_dependency_type: value.resolve_options_with_dependency_type,
resolver_factory: value.resolver_factory,
}
}
}
Expand Down
1 change: 1 addition & 0 deletions crates/rspack_binding_values/src/resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use crate::raw_resolve::{
};

#[napi]
#[derive(Debug)]
pub struct JsResolver {
resolver_factory: Arc<ResolverFactory>,
resolver: Arc<Resolver>,
Expand Down
6 changes: 4 additions & 2 deletions crates/rspack_core/src/compiler/make/repair/factorize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use crate::{
utils::task_loop::{Task, TaskResult, TaskType},
BoxDependency, CompilationId, CompilerOptions, Context, ExportInfoData, ExportsInfoData,
ModuleFactory, ModuleFactoryCreateData, ModuleFactoryResult, ModuleIdentifier, ModuleLayer,
ModuleProfile, Resolve,
ModuleProfile, Resolve, ResolverFactory,
};

#[derive(Debug)]
Expand All @@ -24,9 +24,10 @@ pub struct FactorizeTask {
pub issuer: Option<Box<str>>,
pub issuer_layer: Option<ModuleLayer>,
pub dependencies: Vec<BoxDependency>,
pub resolve_options: Option<Box<Resolve>>,
pub resolve_options: Option<Arc<Resolve>>,
pub options: Arc<CompilerOptions>,
pub current_profile: Option<Box<ModuleProfile>>,
pub resolver_factory: Arc<ResolverFactory>,
}

#[async_trait::async_trait]
Expand Down Expand Up @@ -89,6 +90,7 @@ impl Task<MakeTaskContext> for FactorizeTask {
issuer: self.issuer,
issuer_identifier: self.original_module_identifier,
issuer_layer,
resolver_factory: self.resolver_factory,

file_dependencies: Default::default(),
missing_dependencies: Default::default(),
Expand Down
1 change: 1 addition & 0 deletions crates/rspack_core/src/compiler/make/repair/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ pub async fn repair(
resolve_options: parent_module.and_then(|module| module.get_resolve_options()),
options: compilation.options.clone(),
current_profile,
resolver_factory: compilation.resolver_factory.clone(),
}))
})
.collect::<Vec<_>>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ impl Task<MakeTaskContext> for ProcessDependenciesTask {
resolve_options: module.get_resolve_options(),
options: context.compiler_options.clone(),
current_profile,
resolver_factory: context.resolver_factory.clone(),
}));
}
Ok(res)
Expand Down
1 change: 1 addition & 0 deletions crates/rspack_core/src/compiler/module_executor/entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ impl Task<MakeTaskContext> for EntryTask {
.compiler_options
.profile
.then(Box::<ModuleProfile>::default),
resolver_factory: context.resolver_factory.clone(),
})])
}
}
4 changes: 2 additions & 2 deletions crates/rspack_core/src/concatenated_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ pub struct RootModuleContext {
pub readable_identifier: String,
pub name_for_condition: Option<Box<str>>,
pub lib_indent: Option<String>,
pub resolve_options: Option<Box<Resolve>>,
pub resolve_options: Option<Arc<Resolve>>,
pub code_generation_dependencies: Option<Vec<Box<dyn ModuleDependency>>>,
pub presentational_dependencies: Option<Vec<Box<dyn DependencyTemplate>>>,
pub context: Option<Context>,
Expand Down Expand Up @@ -1361,7 +1361,7 @@ impl Module for ConcatenatedModule {
self.root_module_ctxt.lib_indent.clone().map(Cow::Owned)
}

fn get_resolve_options(&self) -> Option<Box<Resolve>> {
fn get_resolve_options(&self) -> Option<Arc<Resolve>> {
self.root_module_ctxt.resolve_options.clone()
}

Expand Down
2 changes: 1 addition & 1 deletion crates/rspack_core/src/context_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ pub struct ContextModuleOptions {
pub resource_fragment: String,
pub context_options: ContextOptions,
pub layer: Option<ModuleLayer>,
pub resolve_options: Option<Box<Resolve>>,
pub resolve_options: Option<Arc<Resolve>>,
pub type_prefix: ContextTypePrefix,
}

Expand Down
5 changes: 4 additions & 1 deletion crates/rspack_core/src/context_module_factory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,10 @@ impl ContextModuleFactory {
tracing::trace!("resolving context module path {}", options.resource);

let resolver = &resolver_factory.get(ResolveOptionsWithDependencyType {
resolve_options: options.resolve_options.clone(),
resolve_options: options
.resolve_options
.clone()
.map(|r| Box::new(Arc::unwrap_or_clone(r))),
resolve_to_context: false,
dependency_category: options.context_options.category,
});
Expand Down
2 changes: 1 addition & 1 deletion crates/rspack_core/src/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,7 @@ pub trait Module:
/// Resolve options matched by module rules.
/// e.g `javascript/esm` may have special resolving options like `fullySpecified`.
/// `css` and `css/module` may have special resolving options like `preferRelative`.
fn get_resolve_options(&self) -> Option<Box<Resolve>> {
fn get_resolve_options(&self) -> Option<Arc<Resolve>> {
None
}

Expand Down
5 changes: 3 additions & 2 deletions crates/rspack_core/src/module_factory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,20 @@ use rustc_hash::FxHashSet as HashSet;

use crate::{
BoxDependency, BoxModule, CompilationId, CompilerOptions, Context, ModuleIdentifier, ModuleLayer,
Resolve,
Resolve, ResolverFactory,
};

#[derive(Debug, Clone)]
pub struct ModuleFactoryCreateData {
pub compilation_id: CompilationId,
pub resolve_options: Option<Box<Resolve>>,
pub resolve_options: Option<Arc<Resolve>>,
pub options: Arc<CompilerOptions>,
pub context: Context,
pub dependencies: Vec<BoxDependency>,
pub issuer: Option<Box<str>>,
pub issuer_identifier: Option<ModuleIdentifier>,
pub issuer_layer: Option<ModuleLayer>,
pub resolver_factory: Arc<ResolverFactory>,

pub file_dependencies: HashSet<ArcPath>,
pub context_dependencies: HashSet<ArcPath>,
Expand Down
6 changes: 3 additions & 3 deletions crates/rspack_core/src/normal_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ pub struct NormalModule {
source: NormalModuleSource,

/// Resolve options derived from [Rule.resolve]
resolve_options: Option<Box<Resolve>>,
resolve_options: Option<Arc<Resolve>>,
/// Parser options derived from [Rule.parser]
parser_options: Option<ParserOptions>,
/// Generator options derived from [Rule.generator]
Expand Down Expand Up @@ -197,7 +197,7 @@ impl NormalModule {
generator_options: Option<GeneratorOptions>,
match_resource: Option<ResourceData>,
resource_data: Arc<ResourceData>,
resolve_options: Option<Box<Resolve>>,
resolve_options: Option<Arc<Resolve>>,
loaders: Vec<BoxLoader>,
) -> Self {
let module_type = module_type.into();
Expand Down Expand Up @@ -720,7 +720,7 @@ impl Module for NormalModule {
Some(Cow::Owned(ident))
}

fn get_resolve_options(&self) -> Option<Box<Resolve>> {
fn get_resolve_options(&self) -> Option<Arc<Resolve>> {
self.resolve_options.clone()
}

Expand Down
6 changes: 3 additions & 3 deletions crates/rspack_core/src/normal_module_factory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,7 @@ impl NormalModuleFactory {
span: dependency_source_span,
// take the options is safe here, because it
// is not used in after_resolve hooks
resolve_options: data.resolve_options.take(),
resolve_options: data.resolve_options.clone(),
resolve_to_context: false,
optional: dependency_optional,
file_dependencies: &mut file_dependencies,
Expand Down Expand Up @@ -641,7 +641,7 @@ impl NormalModuleFactory {
Ok(rules)
}

fn calculate_resolve_options(&self, module_rules: &[&ModuleRuleEffect]) -> Option<Box<Resolve>> {
fn calculate_resolve_options(&self, module_rules: &[&ModuleRuleEffect]) -> Option<Arc<Resolve>> {
let mut resolved: Option<Resolve> = None;
for rule in module_rules {
if let Some(rule_resolve) = &rule.resolve {
Expand All @@ -652,7 +652,7 @@ impl NormalModuleFactory {
}
}
}
resolved.map(Box::new)
resolved.map(Arc::new)
}

fn calculate_side_effects(&self, module_rules: &[&ModuleRuleEffect]) -> Option<bool> {
Expand Down
6 changes: 5 additions & 1 deletion crates/rspack_core/src/options/externals.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
use std::fmt::Debug;
use std::{fmt::Debug, sync::Arc};

use futures::future::BoxFuture;
use rspack_error::Result;
use rspack_regex::RspackRegex;
use rustc_hash::FxHashMap as HashMap;

use crate::{ResolveOptionsWithDependencyType, ResolverFactory};

pub type Externals = Vec<ExternalItem>;

#[derive(Debug)]
Expand All @@ -26,6 +28,8 @@ pub struct ExternalItemFnCtx {
pub context: String,
pub dependency_type: String,
pub context_info: ContextInfo,
pub resolve_options_with_dependency_type: ResolveOptionsWithDependencyType,
pub resolver_factory: Arc<ResolverFactory>,
}

pub struct ExternalItemFnResult {
Expand Down
12 changes: 9 additions & 3 deletions crates/rspack_core/src/resolver/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use std::borrow::Borrow;
use std::fmt;
use std::fs;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::LazyLock;

use regex::Regex;
Expand Down Expand Up @@ -41,7 +42,7 @@ pub struct ResolveArgs<'a> {
pub dependency_type: &'a DependencyType,
pub dependency_category: &'a DependencyCategory,
pub span: Option<ErrorSpan>,
pub resolve_options: Option<Box<Resolve>>,
pub resolve_options: Option<Arc<Resolve>>,
pub resolve_to_context: bool,
pub optional: bool,
pub file_dependencies: &'a mut FxHashSet<PathBuf>,
Expand Down Expand Up @@ -94,7 +95,9 @@ pub fn resolve_for_error_hints(
plugin_driver: &SharedPluginDriver,
) -> Option<String> {
let dep = ResolveOptionsWithDependencyType {
resolve_options: args.resolve_options.clone(),
resolve_options: args
.resolve_options
.map(|r| Box::new(Arc::unwrap_or_clone(r))),
resolve_to_context: args.resolve_to_context,
dependency_category: *args.dependency_category,
};
Expand Down Expand Up @@ -284,7 +287,10 @@ pub async fn resolve(
plugin_driver: &SharedPluginDriver,
) -> Result<ResolveResult, Error> {
let dep = ResolveOptionsWithDependencyType {
resolve_options: args.resolve_options.clone(),
resolve_options: args
.resolve_options
.clone()
.map(|r| Box::new(Arc::unwrap_or_clone(r))),
resolve_to_context: args.resolve_to_context,
dependency_category: *args.dependency_category,
};
Expand Down
17 changes: 15 additions & 2 deletions crates/rspack_plugin_externals/src/plugin.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use std::fmt::Debug;
use std::sync::LazyLock;
use std::{fmt::Debug, sync::Arc};

use regex::Regex;
use rspack_core::{
ApplyContext, BoxModule, CompilerOptions, ContextInfo, DependencyMeta, ExternalItem,
ExternalItemFnCtx, ExternalItemValue, ExternalModule, ExternalRequest, ExternalRequestValue,
ExternalType, ExternalTypeEnum, ModuleDependency, ModuleExt, ModuleFactoryCreateData,
NormalModuleFactoryFactorize, Plugin, PluginContext,
NormalModuleFactoryFactorize, Plugin, PluginContext, ResolveOptionsWithDependencyType,
};
use rspack_error::Result;
use rspack_hook::{plugin, plugin_hook};
Expand Down Expand Up @@ -182,6 +182,19 @@ async fn factorize(&self, data: &mut ModuleFactoryCreateData) -> Result<Option<B
.clone()
.map_or("".to_string(), |i| i.to_string()),
},
resolve_options_with_dependency_type: ResolveOptionsWithDependencyType {
resolve_options: data
.resolve_options
.clone()
.map(|r| Box::new(Arc::unwrap_or_clone(r))),
resolve_to_context: false,
dependency_category: *data
.dependencies
.first()
.expect("Expected at least one dependency")
.category(),
},
resolver_factory: data.resolver_factory.clone(),
})
.await?;
if let Some(r) = result.result {
Expand Down
1 change: 1 addition & 0 deletions crates/rspack_plugin_lazy_compilation/src/factory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ impl ModuleFactory for LazyCompilationDependencyFactory {
issuer: proxy_data.issuer.clone(),
issuer_layer: proxy_data.issuer_layer.clone(),
issuer_identifier: proxy_data.issuer_identifier,
resolver_factory: proxy_data.resolver_factory.clone(),
file_dependencies: proxy_data.file_dependencies.clone(),
context_dependencies: proxy_data.context_dependencies.clone(),
missing_dependencies: proxy_data.missing_dependencies.clone(),
Expand Down
Loading
Loading