Skip to content

Commit

Permalink
feat: add resolve_id hook options, include kind and is_entry (#218)
Browse files Browse the repository at this point in the history
  • Loading branch information
underfin authored Nov 10, 2023
1 parent 4e4f20a commit 763dedb
Show file tree
Hide file tree
Showing 9 changed files with 86 additions and 12 deletions.
13 changes: 11 additions & 2 deletions crates/rolldown/src/bundler/module_loader/module_loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use crate::bundler::runtime::RUNTIME_PATH;
use crate::bundler::utils::ast_symbol::AstSymbol;
use crate::bundler::utils::resolve_id::{resolve_id, ResolvedRequestInfo};
use crate::error::{BatchedErrors, BatchedResult};
use crate::SharedResolver;
use crate::{HookResolveIdArgsOptions, SharedResolver};

pub struct ModuleLoader<'a, T: FileSystemExt + Default> {
ctx: ModuleLoaderContext,
Expand Down Expand Up @@ -207,7 +207,16 @@ impl<'a, T: FileSystemExt + 'static + Default> ModuleLoader<'a, T> {
let resolved_ids =
block_on_spawn_all(self.input_options.input.iter().map(|input_item| async move {
let specifier = &input_item.import;
match resolve_id(resolver, plugin_driver, specifier, None, false).await {
match resolve_id(
resolver,
plugin_driver,
specifier,
None,
HookResolveIdArgsOptions { is_entry: true, kind: ImportKind::Import },
false,
)
.await
{
Ok(r) => {
let Some(info) = r else {
return Err(BuildError::unresolved_entry(specifier));
Expand Down
17 changes: 14 additions & 3 deletions crates/rolldown/src/bundler/module_loader/normal_module_task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use crate::{
visitors::scanner::{self, ScanResult},
},
error::BatchedResult,
HookLoadArgs, HookTransformArgs,
HookLoadArgs, HookResolveIdArgsOptions, HookTransformArgs,
};
pub struct NormalModuleTask<'task, T: FileSystemExt + Default> {
ctx: &'task ModuleTaskContext<'task, T>,
Expand Down Expand Up @@ -175,14 +175,16 @@ impl<'task, T: FileSystemExt + Default + 'static> NormalModuleTask<'task, T> {
plugin_driver: &SharedPluginDriver,
importer: &ResourceId,
specifier: &str,
options: HookResolveIdArgsOptions,
) -> BatchedResult<ResolvedRequestInfo> {
// let is_marked_as_external = is_external(specifier, Some(importer.id()), false).await?;

// if is_marked_as_external {
// return Ok(ModuleId::new(specifier, true));
// }

let resolved_id = resolve_id(resolver, plugin_driver, specifier, Some(importer), false).await?;
let resolved_id =
resolve_id(resolver, plugin_driver, specifier, Some(importer), options, false).await?;

match resolved_id {
Some(info) => Ok(info),
Expand Down Expand Up @@ -212,10 +214,19 @@ impl<'task, T: FileSystemExt + Default + 'static> NormalModuleTask<'task, T> {
let resolver = Arc::clone(self.ctx.resolver);
let plugin_driver = Arc::clone(self.ctx.plugin_driver);
let importer = self.path.clone();
let kind = item.kind;
// let is_external = self.is_external.clone();
// let on_warn = self.input_options.on_warn.clone();
tokio::spawn(async move {
Self::resolve_id(&resolver, &plugin_driver, &importer, &specifier).await.map(|id| (idx, id))
Self::resolve_id(
&resolver,
&plugin_driver,
&importer,
&specifier,
HookResolveIdArgsOptions { is_entry: false, kind },
)
.await
.map(|id| (idx, id))
})
});

Expand Down
6 changes: 5 additions & 1 deletion crates/rolldown/src/bundler/utils/resolve_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ use rolldown_error::BuildError;
use rolldown_fs::FileSystemExt;
use rolldown_resolver::Resolver;

use crate::{bundler::plugin_driver::SharedPluginDriver, HookResolveIdArgs};
use crate::{
bundler::plugin_driver::SharedPluginDriver, HookResolveIdArgs, HookResolveIdArgsOptions,
};

#[derive(Debug)]
pub struct ResolvedRequestInfo {
Expand All @@ -18,13 +20,15 @@ pub async fn resolve_id<T: FileSystemExt + Default>(
plugin_driver: &SharedPluginDriver,
request: &str,
importer: Option<&ResourceId>,
options: HookResolveIdArgsOptions,
_preserve_symlinks: bool,
) -> Result<Option<ResolvedRequestInfo>, BuildError> {
// Run plugin resolve_id first, if it is None use internal resolver as fallback
if let Some(r) = plugin_driver
.resolve_id(&HookResolveIdArgs {
importer: importer.map(std::convert::AsRef::as_ref),
source: request,
options,
})
.await?
{
Expand Down
5 changes: 4 additions & 1 deletion crates/rolldown/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ pub use crate::{
},
},
plugin::{
args::{HookBuildEndArgs, HookLoadArgs, HookResolveIdArgs, HookTransformArgs},
args::{
HookBuildEndArgs, HookLoadArgs, HookResolveIdArgs, HookResolveIdArgsOptions,
HookTransformArgs,
},
context::PluginContext,
output::{HookLoadOutput, HookResolveIdOutput},
plugin::{HookLoadReturn, HookNoopReturn, HookResolveIdReturn, HookTransformReturn, Plugin},
Expand Down
10 changes: 10 additions & 0 deletions crates/rolldown/src/plugin/args.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
use rolldown_common::ImportKind;

#[derive(Debug)]
pub struct HookResolveIdArgs<'a> {
pub importer: Option<&'a str>,
pub source: &'a str,
pub options: HookResolveIdArgsOptions,
}

#[derive(Debug, Clone)]
pub struct HookResolveIdArgsOptions {
pub is_entry: bool,
// Rollup hasn't this filed, but since Rolldown support cjs as first citizen, so we need to generate `kind` to distinguish it.
pub kind: ImportKind,
}

#[derive(Debug)]
Expand Down
5 changes: 5 additions & 0 deletions crates/rolldown_binding/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,16 @@ export interface PluginOptions {
resolveId?: (
specifier: string,
importer?: string,
options?: HookResolveIdArgsOptions,
) => Promise<undefined | ResolveIdResult>
load?: (id: string) => Promise<undefined | SourceResult>
transform?: (id: string, code: string) => Promise<undefined | SourceResult>
buildEnd?: (error: string) => Promise<void>
}
export interface HookResolveIdArgsOptions {
isEntry: boolean
kind: string
}
export interface ResolveIdResult {
id: string
external?: boolean
Expand Down
17 changes: 16 additions & 1 deletion crates/rolldown_binding/src/options/input_options/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub struct PluginOptions {
#[derivative(Debug = "ignore")]
#[serde(skip_deserializing)]
#[napi(
ts_type = "(specifier: string, importer?: string) => Promise<undefined | ResolveIdResult>"
ts_type = "(specifier: string, importer?: string, options?: HookResolveIdArgsOptions) => Promise<undefined | ResolveIdResult>"
)]
pub resolve_id: Option<JsFunction>,

Expand All @@ -37,6 +37,21 @@ pub struct PluginOptions {
pub build_end: Option<JsFunction>,
}

#[napi_derive::napi(object)]
#[derive(Deserialize, Default, Derivative)]
#[serde(rename_all = "camelCase")]
#[derivative(Debug)]
pub struct HookResolveIdArgsOptions {
pub is_entry: bool,
pub kind: String,
}

impl From<rolldown::HookResolveIdArgsOptions> for HookResolveIdArgsOptions {
fn from(value: rolldown::HookResolveIdArgsOptions) -> Self {
Self { is_entry: value.is_entry, kind: value.kind.to_string() }
}
}

#[napi_derive::napi(object)]
#[derive(Deserialize, Default, Derivative)]
#[serde(rename_all = "camelCase")]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@ use crate::utils::JsCallback;
use derivative::Derivative;
use rolldown::Plugin;

use super::plugin::{PluginOptions, ResolveIdResult, SourceResult};
use super::plugin::{HookResolveIdArgsOptions, PluginOptions, ResolveIdResult, SourceResult};

pub type BuildStartCallback = JsCallback<(), ()>;
pub type ResolveIdCallback = JsCallback<(String, Option<String>), Option<ResolveIdResult>>;
pub type ResolveIdCallback =
JsCallback<(String, Option<String>, HookResolveIdArgsOptions), Option<ResolveIdResult>>;
pub type LoadCallback = JsCallback<(String,), Option<SourceResult>>;
pub type TransformCallback = JsCallback<(String, String), Option<SourceResult>>;
pub type BuildEndCallback = JsCallback<(Option<String>,), ()>;
Expand Down Expand Up @@ -73,7 +74,11 @@ impl Plugin for JsAdapterPlugin {
) -> rolldown::HookResolveIdReturn {
if let Some(cb) = &self.resolve_id_fn {
let res = cb
.call_async((args.source.to_string(), args.importer.map(|s| s.to_string())))
.call_async((
args.source.to_string(),
args.importer.map(|s| s.to_string()),
args.options.clone().into(),
))
.await
.map_err(|e| e.into_bundle_error())?;

Expand Down
14 changes: 13 additions & 1 deletion crates/rolldown_common/src/import_record.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::fmt::Display;

use oxc::span::Atom;

use crate::module_id::ModuleId;
Expand All @@ -6,7 +8,7 @@ index_vec::define_index_type! {
pub struct ImportRecordId = u32;
}

#[derive(Debug, PartialEq, Eq)]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum ImportKind {
Import,
DynamicImport,
Expand All @@ -19,6 +21,16 @@ impl ImportKind {
}
}

impl Display for ImportKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Import => write!(f, "import-statement"),
Self::DynamicImport => write!(f, "dynamic-import"),
Self::Require => write!(f, "require-call"),
}
}
}

#[derive(Debug)]
pub struct ImportRecord {
// Module Request
Expand Down

0 comments on commit 763dedb

Please sign in to comment.