diff --git a/Cargo.lock b/Cargo.lock index 793dad5..0ba3136 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1580,6 +1580,7 @@ dependencies = [ "rspack_util", "serde", "serde_json", + "swc_change_package_import", "swc_compiler", "swc_config", "swc_core", @@ -4039,6 +4040,7 @@ name = "swc_change_package_import" version = "0.1.0" dependencies = [ "serde", + "serde_json", "swc_core", "testing", ] @@ -6061,4 +6063,4 @@ dependencies = [ "proc-macro2", "quote", "syn 2.0.48", -] \ No newline at end of file +] diff --git a/crates/loader_barrel/Cargo.toml b/crates/loader_barrel/Cargo.toml index 2176855..b36ea3e 100644 --- a/crates/loader_barrel/Cargo.toml +++ b/crates/loader_barrel/Cargo.toml @@ -5,7 +5,7 @@ edition = "2021" [dependencies] lazy_static = "1.4.0" -serde_json = "1.0.100" +serde_json = { workspace = true } futures = { workspace = true } regex = { workspace = true } anyhow = { workspace = true } diff --git a/crates/loader_compilation/Cargo.toml b/crates/loader_compilation/Cargo.toml index 5fdc294..f3924ea 100644 --- a/crates/loader_compilation/Cargo.toml +++ b/crates/loader_compilation/Cargo.toml @@ -20,7 +20,7 @@ rspack_regex = { path = "../.rspack_crates/rspack_regex" } rspack_util = { path = "../.rspack_crates/rspack_util" } regex = { workspace = true } serde = { workspace = true, features = ["derive"] } -serde_json = "1.0.100" +serde_json = { workspace = true } swc_config = { workspace = true } swc_core = { workspace = true, features = [ "base", @@ -34,6 +34,7 @@ swc_env_replacement = { path = "../swc_env_replacement" } swc_keep_export = { path = "../swc_keep_export" } swc_remove_export = { path = "../swc_remove_export" } swc_named_import_transform = { path = "../swc_named_import_transform" } +swc_change_package_import = { path = "../swc_change_package_import" } [dev-dependencies] indexmap = { workspace = true } diff --git a/crates/loader_compilation/src/transform.rs b/crates/loader_compilation/src/transform.rs index 1a35f58..3a4fb3b 100644 --- a/crates/loader_compilation/src/transform.rs +++ b/crates/loader_compilation/src/transform.rs @@ -1,5 +1,4 @@ use std::path::Path; - use anyhow::{Context, Error}; use either::Either; use serde::Deserialize; @@ -9,6 +8,7 @@ use swc_env_replacement::env_replacement; use swc_keep_export::keep_export; use swc_named_import_transform::{named_import_transform, TransformConfig}; use swc_remove_export::remove_export; +use swc_change_package_import::{change_package_import, Config as ImportConfig, SpecificConfigs}; macro_rules! either { ($config:expr, $f:expr) => { @@ -85,6 +85,7 @@ pub struct TransformFeatureOptions { pub keep_export: Option>, pub remove_export: Option>, pub optimize_import: Option>, + pub import_config: Option>, } pub(crate) fn transform<'a>( @@ -98,6 +99,13 @@ pub(crate) fn transform<'a>( packages: options.clone(), }) }), + either!( + feature_options.import_config, + |options: &Vec| { + let import_config = options.to_vec(); + change_package_import(import_config.into_iter().map(ImportConfig::SpecificConfig).collect()) + } + ), either!( Some(&vec!["@uni/env".to_string(), "universal-env".to_string()]), |options: &Vec| { env_replacement(options.clone()) } diff --git a/crates/node_binding/index.d.ts b/crates/node_binding/index.d.ts index 0f7d13d..12a9223 100644 --- a/crates/node_binding/index.d.ts +++ b/crates/node_binding/index.d.ts @@ -3,12 +3,1057 @@ /* auto-generated by NAPI-RS */ +export class ExternalObject { + readonly '': { + readonly '': unique symbol + [K: symbol]: T + } +} +export interface NodeFS { + writeFile: (...args: any[]) => any + removeFile: (...args: any[]) => any + mkdir: (...args: any[]) => any + mkdirp: (...args: any[]) => any +} +export interface ThreadsafeNodeFS { + writeFile: (...args: any[]) => any + removeFile: (...args: any[]) => any + mkdir: (...args: any[]) => any + mkdirp: (...args: any[]) => any + removeDirAll: (...args: any[]) => any +} +export interface JsAssetInfoRelated { + sourceMap?: string +} +export interface JsAssetInfo { + /** if the asset can be long term cached forever (contains a hash) */ + immutable: boolean + /** whether the asset is minimized */ + minimized: boolean + /** + * the value(s) of the full hash used for this asset + * the value(s) of the chunk hash used for this asset + */ + chunkHash: Array + /** + * the value(s) of the module hash used for this asset + * the value(s) of the content hash used for this asset + */ + contentHash: Array + sourceFilename?: string + /** + * size in bytes, only set after asset has been emitted + * when asset is only used for development and doesn't count towards user-facing assets + */ + development: boolean + /** when asset ships data for updating an existing application (HMR) */ + hotModuleReplacement: boolean + /** when asset is javascript and an ESM */ + javascriptModule?: boolean + /** related object to other assets, keyed by type of relation (only points from parent to child) */ + related: JsAssetInfoRelated +} +export interface JsAsset { + name: string + info: JsAssetInfo +} +export interface JsAssetEmittedArgs { + filename: string + outputPath: string + targetPath: string +} +export interface JsChunk { + __inner_ukey: number + __inner_groups: Array + name?: string + id?: string + ids: Array + idNameHints: Array + filenameTemplate?: string + cssFilenameTemplate?: string + files: Array + runtime: Array + hash?: string + contentHash: Record + renderedHash?: string + chunkReasons: Array + auxiliaryFiles: Array +} +export function __chunk_inner_is_only_initial(jsChunkUkey: number, compilation: JsCompilation): boolean +export function __chunk_inner_can_be_initial(jsChunkUkey: number, compilation: JsCompilation): boolean +export function __chunk_inner_has_runtime(jsChunkUkey: number, compilation: JsCompilation): boolean +export function __chunk_inner_get_all_async_chunks(jsChunkUkey: number, compilation: JsCompilation): Array +export function __chunk_inner_get_all_initial_chunks(jsChunkUkey: number, compilation: JsCompilation): Array +export function __chunk_inner_get_all_referenced_chunks(jsChunkUkey: number, compilation: JsCompilation): Array +export interface JsChunkAssetArgs { + chunk: JsChunk + filename: string +} +export function __chunk_graph_inner_get_chunk_modules(jsChunkUkey: number, compilation: JsCompilation): Array +export function __chunk_graph_inner_get_chunk_entry_modules(jsChunkUkey: number, compilation: JsCompilation): Array +export function __chunk_graph_inner_get_chunk_entry_dependent_chunks_iterable(jsChunkUkey: number, compilation: JsCompilation): Array +export function __chunk_graph_inner_get_chunk_modules_iterable_by_source_type(jsChunkUkey: number, sourceType: string, compilation: JsCompilation): Array +export interface JsChunkGroup { + __inner_parents: Array + chunks: Array + index?: number + name?: string +} +export function __chunk_group_inner_get_chunk_group(ukey: number, compilation: JsCompilation): JsChunkGroup +export interface JsCodegenerationResults { + map: Record> +} +export interface JsCodegenerationResult { + sources: Record +} +export interface JsExecuteModuleResult { + fileDependencies: Array + contextDependencies: Array + buildDependencies: Array + missingDependencies: Array + assets: Array + id: number +} +export interface JsBuildTimeExecutionOption { + publicPath?: string + baseUri?: string +} +export interface JsHooks { + processAssetsStageAdditional: (...args: any[]) => any + processAssetsStagePreProcess: (...args: any[]) => any + processAssetsStageDerived: (...args: any[]) => any + processAssetsStageAdditions: (...args: any[]) => any + processAssetsStageNone: (...args: any[]) => any + processAssetsStageOptimize: (...args: any[]) => any + processAssetsStageOptimizeCount: (...args: any[]) => any + processAssetsStageOptimizeCompatibility: (...args: any[]) => any + processAssetsStageOptimizeSize: (...args: any[]) => any + processAssetsStageDevTooling: (...args: any[]) => any + processAssetsStageOptimizeInline: (...args: any[]) => any + processAssetsStageSummarize: (...args: any[]) => any + processAssetsStageOptimizeHash: (...args: any[]) => any + processAssetsStageOptimizeTransfer: (...args: any[]) => any + processAssetsStageAnalyse: (...args: any[]) => any + processAssetsStageReport: (...args: any[]) => any + afterProcessAssets: (...args: any[]) => any + compilation: (...args: any[]) => any + thisCompilation: (...args: any[]) => any + emit: (...args: any[]) => any + assetEmitted: (...args: any[]) => any + shouldEmit: (...args: any[]) => any + afterEmit: (...args: any[]) => any + make: (...args: any[]) => any + optimizeModules: (...args: any[]) => any + afterOptimizeModules: (...args: any[]) => any + optimizeTree: (...args: any[]) => any + optimizeChunkModules: (...args: any[]) => any + beforeCompile: (...args: any[]) => any + afterCompile: (...args: any[]) => any + finishModules: (...args: any[]) => any + finishMake: (...args: any[]) => any + buildModule: (...args: any[]) => any + beforeResolve: (...args: any[]) => any + afterResolve: (...args: any[]) => any + contextModuleFactoryBeforeResolve: (...args: any[]) => any + normalModuleFactoryCreateModule: (...args: any[]) => any + normalModuleFactoryResolveForScheme: (...args: any[]) => any + chunkAsset: (...args: any[]) => any + succeedModule: (...args: any[]) => any + stillValidModule: (...args: any[]) => any + executeModule: (...args: any[]) => any + runtimeModule: (...args: any[]) => any +} +export interface JsModule { + context?: string + originalSource?: JsCompatSource + resource?: string + moduleIdentifier: string + nameForCondition?: string +} +export interface JsExecuteModuleArg { + entry: string + request: string + options: JsBuildTimeExecutionOption + runtimeModules: Array + codegenResults: JsCodegenerationResults + id: number +} +export interface JsRuntimeModule { + source?: JsCompatSource + moduleIdentifier: string + constructorName: string + name: string +} +export interface JsRuntimeModuleArg { + module: JsRuntimeModule + chunk: JsChunk +} +export interface JsResolveForSchemeInput { + resourceData: JsResourceData + scheme: string +} +export interface JsResolveForSchemeResult { + resourceData: JsResourceData + stop: boolean +} +export interface BeforeResolveData { + request: string + context: string +} +export interface AfterResolveData { + request: string + context: string + fileDependencies: Array + contextDependencies: Array + missingDependencies: Array + factoryMeta: FactoryMeta +} +export interface CreateModuleData { + dependencyType: string + resolveDataRequest: string + resourceResolveData: JsResourceData + context: string +} +export interface FactoryMeta { + sideEffectFree?: boolean +} +export interface JsResourceData { + /** Resource with absolute path, query and fragment */ + resource: string + /** Absolute resource path only */ + path: string + /** Resource query with `?` prefix */ + query?: string + /** Resource fragment with `#` prefix */ + fragment?: string +} +export interface PathData { + filename?: string + hash?: string + contentHash?: string + runtime?: string + url?: string + id?: string +} +export interface PathWithInfo { + path: string + info: JsAssetInfo +} +export interface JsCompatSource { + /** Whether the underlying data structure is a `RawSource` */ + isRaw: boolean + /** Whether the underlying value is a buffer or string */ + isBuffer: boolean + source: Buffer + map?: Buffer +} +export interface JsStatsError { + message: string + formatted: string + moduleIdentifier?: string + moduleName?: string + moduleId?: string +} +export interface JsStatsWarning { + message: string + formatted: string + moduleIdentifier?: string + moduleName?: string + moduleId?: string +} +export interface JsStatsLogging { + name: string + type: string + args?: Array + trace?: Array +} +export interface JsStatsAsset { + type: string + name: string + size: number + chunks: Array + chunkNames: Array + info: JsStatsAssetInfo + emitted: boolean +} +export interface JsStatsAssetInfo { + development: boolean + hotModuleReplacement: boolean + sourceFilename?: string +} +export interface JsStatsModule { + type: string + moduleType: string + identifier: string + name: string + id?: string + chunks: Array + size: number + issuer?: string + issuerName?: string + issuerId?: string + issuerPath: Array + nameForCondition?: string + reasons?: Array + assets?: Array + source?: string | Buffer + profile?: JsStatsModuleProfile + orphan: boolean +} +export interface JsStatsModuleProfile { + factory: JsStatsMillisecond + integration: JsStatsMillisecond + building: JsStatsMillisecond +} +export interface JsStatsMillisecond { + secs: number + subsecMillis: number +} +export interface JsStatsModuleIssuer { + identifier: string + name: string + id?: string +} +export interface JsStatsModuleReason { + moduleIdentifier?: string + moduleName?: string + moduleId?: string + type?: string + userRequest?: string +} +export interface JsStatsChunk { + type: string + files: Array + auxiliaryFiles: Array + id?: string + entry: boolean + initial: boolean + names: Array + size: number + modules?: Array + parents?: Array + children?: Array + siblings?: Array +} +export interface JsStatsChunkGroupAsset { + name: string + size: number +} +export interface JsStatsChunkGroup { + name: string + assets: Array + chunks: Array + assetsSize: number +} +export interface JsStatsAssetsByChunkName { + name: string + files: Array +} +export interface JsStatsGetAssets { + assets: Array + assetsByChunkName: Array +} +export interface RawBannerContentFnCtx { + hash: string + chunk: JsChunk + filename: string +} +export interface RawBannerPluginOptions { + banner: string | ((...args: any[]) => any) + entryOnly?: boolean + footer?: boolean + raw?: boolean + test?: string | RegExp | (string | RegExp)[] + include?: string | RegExp | (string | RegExp)[] + exclude?: string | RegExp | (string | RegExp)[] +} +export interface RawBundlerInfoPluginOptions { + version: string + force: boolean | string[] +} +export interface RawCopyPattern { + from: string + to?: string + context?: string + toType?: string + noErrorOnMissing: boolean + force: boolean + priority: number + globOptions: RawCopyGlobOptions + info?: RawInfo +} +export interface RawInfo { + immutable?: boolean + minimized?: boolean + chunkHash?: Array + contentHash?: Array + development?: boolean + hotModuleReplacement?: boolean + related?: RawRelated + version?: string +} +export interface RawRelated { + sourceMap?: string +} +export interface RawCopyGlobOptions { + caseSensitiveMatch?: boolean + dot?: boolean + ignore?: Array +} +export interface RawCopyRspackPluginOptions { + patterns: Array +} +export interface RawHtmlRspackPluginOptions { + /** emitted file name in output path */ + filename?: string + /** template html file */ + template?: string + templateContent?: string + templateParameters?: Record + /** "head", "body" or "false" */ + inject: "head" | "body" | "false" + /** path or `auto` */ + publicPath?: string + /** `blocking`, `defer`, or `module` */ + scriptLoading: "blocking" | "defer" | "module" + /** entry_chunk_name (only entry chunks are supported) */ + chunks?: Array + excludedChunks?: Array + sri?: "sha256" | "sha384" | "sha512" + minify?: boolean + title?: string + favicon?: string + meta?: Record> +} +export interface RawLimitChunkCountPluginOptions { + chunkOverhead?: number + entryChunkMultiplicator?: number + maxChunks: number +} +export interface RawContainerPluginOptions { + name: string + shareScope: string + library: RawLibraryOptions + runtime?: string + filename?: string + exposes: Array + enhanced: boolean +} +export interface RawExposeOptions { + key: string + name?: string + import: Array +} +export interface RawContainerReferencePluginOptions { + remoteType: string + remotes: Array + shareScope?: string + enhanced: boolean +} +export interface RawRemoteOptions { + key: string + external: Array + shareScope: string +} +export interface RawProvideOptions { + key: string + shareKey: string + shareScope: string + version?: string | false | undefined + eager: boolean +} +export interface RawConsumeSharedPluginOptions { + consumes: Array + enhanced: boolean +} +export interface RawConsumeOptions { + key: string + import?: string + importResolved?: string + shareKey: string + shareScope: string + requiredVersion?: string | false | undefined + packageName?: string + strictVersion: boolean + singleton: boolean + eager: boolean +} +export interface RawProgressPluginOptions { + prefix: string + profile: boolean +} +export interface RawExtractComments { + banner?: string | boolean + condition?: string +} +export interface RawSwcJsMinimizerRspackPluginOptions { + extractComments?: RawExtractComments + compress: boolean | string + mangle: boolean | string + format: string + module?: boolean + test?: string | RegExp | (string | RegExp)[] + include?: string | RegExp | (string | RegExp)[] + exclude?: string | RegExp | (string | RegExp)[] +} +export interface RawStyleConfig { + styleLibraryDirectory?: string + custom?: string + css?: string + bool?: boolean +} +export interface RawPluginImportConfig { + libraryName: string + libraryDirectory?: string + customName?: string + customStyleName?: string + style?: RawStyleConfig + camelToDashComponentName?: boolean + transformToDefaultImport?: boolean + ignoreEsComponent?: Array + ignoreStyleComponent?: Array +} +export interface RawReactOptions { + runtime?: "automatic" | "classic" + importSource?: string + pragma?: string + pragmaFrag?: string + throwIfNamespace?: boolean + development?: boolean + useBuiltins?: boolean + useSpread?: boolean + refresh?: boolean +} +export interface RawRelayConfig { + artifactDirectory?: string + language: 'javascript' | 'typescript' | 'flow' +} +export interface RawCssPluginConfig { + modules: RawCssModulesConfig +} +export interface RawCssModulesConfig { + localsConvention: "asIs" | "camelCase" | "camelCaseOnly" | "dashes" | "dashesOnly" + localIdentName: string + exportsOnly: boolean +} +export interface RawBuiltins { + css?: RawCssPluginConfig + treeShaking: string +} +export const enum BuiltinPluginName { + DefinePlugin = 'DefinePlugin', + ProvidePlugin = 'ProvidePlugin', + BannerPlugin = 'BannerPlugin', + ProgressPlugin = 'ProgressPlugin', + EntryPlugin = 'EntryPlugin', + ExternalsPlugin = 'ExternalsPlugin', + NodeTargetPlugin = 'NodeTargetPlugin', + ElectronTargetPlugin = 'ElectronTargetPlugin', + EnableChunkLoadingPlugin = 'EnableChunkLoadingPlugin', + EnableLibraryPlugin = 'EnableLibraryPlugin', + EnableWasmLoadingPlugin = 'EnableWasmLoadingPlugin', + ChunkPrefetchPreloadPlugin = 'ChunkPrefetchPreloadPlugin', + CommonJsChunkFormatPlugin = 'CommonJsChunkFormatPlugin', + ArrayPushCallbackChunkFormatPlugin = 'ArrayPushCallbackChunkFormatPlugin', + ModuleChunkFormatPlugin = 'ModuleChunkFormatPlugin', + HotModuleReplacementPlugin = 'HotModuleReplacementPlugin', + LimitChunkCountPlugin = 'LimitChunkCountPlugin', + WorkerPlugin = 'WorkerPlugin', + WebWorkerTemplatePlugin = 'WebWorkerTemplatePlugin', + MergeDuplicateChunksPlugin = 'MergeDuplicateChunksPlugin', + SplitChunksPlugin = 'SplitChunksPlugin', + ShareRuntimePlugin = 'ShareRuntimePlugin', + ContainerPlugin = 'ContainerPlugin', + ContainerReferencePlugin = 'ContainerReferencePlugin', + ProvideSharedPlugin = 'ProvideSharedPlugin', + ConsumeSharedPlugin = 'ConsumeSharedPlugin', + NamedModuleIdsPlugin = 'NamedModuleIdsPlugin', + DeterministicModuleIdsPlugin = 'DeterministicModuleIdsPlugin', + NamedChunkIdsPlugin = 'NamedChunkIdsPlugin', + DeterministicChunkIdsPlugin = 'DeterministicChunkIdsPlugin', + RealContentHashPlugin = 'RealContentHashPlugin', + RemoveEmptyChunksPlugin = 'RemoveEmptyChunksPlugin', + EnsureChunkConditionsPlugin = 'EnsureChunkConditionsPlugin', + WarnCaseSensitiveModulesPlugin = 'WarnCaseSensitiveModulesPlugin', + DataUriPlugin = 'DataUriPlugin', + FileUriPlugin = 'FileUriPlugin', + RuntimePlugin = 'RuntimePlugin', + JsonModulesPlugin = 'JsonModulesPlugin', + InferAsyncModulesPlugin = 'InferAsyncModulesPlugin', + JavascriptModulesPlugin = 'JavascriptModulesPlugin', + AsyncWebAssemblyModulesPlugin = 'AsyncWebAssemblyModulesPlugin', + AssetModulesPlugin = 'AssetModulesPlugin', + SourceMapDevToolPlugin = 'SourceMapDevToolPlugin', + EvalSourceMapDevToolPlugin = 'EvalSourceMapDevToolPlugin', + SideEffectsFlagPlugin = 'SideEffectsFlagPlugin', + FlagDependencyExportsPlugin = 'FlagDependencyExportsPlugin', + FlagDependencyUsagePlugin = 'FlagDependencyUsagePlugin', + MangleExportsPlugin = 'MangleExportsPlugin', + HttpExternalsRspackPlugin = 'HttpExternalsRspackPlugin', + CopyRspackPlugin = 'CopyRspackPlugin', + HtmlRspackPlugin = 'HtmlRspackPlugin', + SwcJsMinimizerRspackPlugin = 'SwcJsMinimizerRspackPlugin', + SwcCssMinimizerRspackPlugin = 'SwcCssMinimizerRspackPlugin', + BundlerInfoPlugin = 'BundlerInfoPlugin' +} +export interface BuiltinPlugin { + name: BuiltinPluginName + options: unknown + canInherentFromParent?: boolean +} +export interface RawCacheOptions { + type: string + maxGenerations: number + maxAge: number + profile: boolean + buildDependencies: Array + cacheDirectory: string + cacheLocation: string + name: string + version: string +} +export interface RawModuleFilenameTemplateFnCtx { + identifier: string + shortIdentifier: string + resource: string + resourcePath: string + absoluteResourcePath: string + loaders: string + allLoaders: string + query: string + moduleId: string + hash: string + namespace: string +} +export interface RawSourceMapDevToolPluginOptions { + append?: (false | null) | string | Function + columns?: boolean + fallbackModuleFilenameTemplate?: string | Function + fileContext?: string + filename?: (false | null) | string + module?: boolean + moduleFilenameTemplate?: string | Function + namespace?: string + noSources?: boolean + publicPath?: string + sourceRoot?: string + test?: (text: string) => boolean +} +export interface RawEntryPluginOptions { + context: string + entry: string + options: RawEntryOptions +} +export interface RawEntryOptions { + name?: string + runtime?: string + chunkLoading?: string + asyncChunks?: boolean + publicPath?: string + baseUri?: string + filename?: string + library?: RawLibraryOptions +} +export interface RawRspackFuture { + newTreeshaking: boolean +} +export interface RawExperiments { + newSplitChunks: boolean + topLevelAwait: boolean + rspackFuture: RawRspackFuture +} +export interface RawHttpExternalsRspackPluginOptions { + css: boolean + webAsync: boolean +} +export interface RawExternalsPluginOptions { + type: string + externals: (string | RegExp | Record> | ((...args: any[]) => any))[] +} +export interface RawExternalItemFnResult { + externalType?: string + result?: string | boolean | string[] | Record +} +export interface RawExternalItemFnCtx { + request: string + context: string + dependencyType: string +} +export interface RawExternalsPresets { + node: boolean + web: boolean + electron: boolean + electronMain: boolean + electronPreload: boolean + electronRenderer: boolean +} +export interface JsLoaderContext { + /** Content maybe empty in pitching stage */ + content?: Buffer + additionalData?: Buffer + sourceMap?: Buffer + resource: string + resourcePath: string + resourceQuery?: string + resourceFragment?: string + cacheable: boolean + fileDependencies: Array + contextDependencies: Array + missingDependencies: Array + buildDependencies: Array + assetFilenames: Array + currentLoader: string + isPitching: boolean + /** + * Loader index from JS. + * If loaders are dispatched by JS loader runner, + * then, this field is correspondence with loader index in JS side. + * It is useful when loader dispatched on JS side has an builtin loader, for example: builtin:swc-loader, + * Then this field will be used as an hack to test whether it should return an AST or string. + */ + loaderIndexFromJs?: number + /** + * Internal additional data, contains more than `String` + * @internal + */ + additionalDataExternal: ExternalObject<'AdditionalData'> + /** + * Internal loader context + * @internal + */ + contextExternal: ExternalObject<'LoaderRunnerContext'> + /** + * Internal loader diagnostic + * @internal + */ + diagnosticsExternal: ExternalObject<'Diagnostic[]'> + _moduleIdentifier: string +} +/** + * `loader` is for both JS and Rust loaders. + * `options` is + * - a `None` on rust side and handled by js side `getOptions` when + * using with `loader`. + * - a `Some(string)` on rust side, deserialized by `serde_json::from_str` + * and passed to rust side loader in [get_builtin_loader] when using with + * `builtin_loader`. + */ +export interface RawModuleRuleUse { + loader: string + options?: string +} +export interface RawModuleRuleUses { + type: "array" | "function" + arrayUse?: Array + funcUse?: (...args: any[]) => any +} +export interface RawRegexMatcher { + source: string + flags: string +} +export interface RawRuleSetCondition { + type: "string" | "regexp" | "logical" | "array" | "function" + stringMatcher?: string + regexpMatcher?: RawRegexMatcher + logicalMatcher?: Array + arrayMatcher?: Array + funcMatcher?: (value: string) => boolean +} +export interface RawRuleSetLogicalConditions { + and?: Array + or?: Array + not?: RawRuleSetCondition +} +export interface RawModuleRule { + /** + * A conditional match matching an absolute path + query + fragment. + * Note: + * This is a custom matching rule not initially designed by webpack. + * Only for single-threaded environment interoperation purpose. + */ + rspackResource?: RawRuleSetCondition + /** A condition matcher matching an absolute path. */ + test?: RawRuleSetCondition + include?: RawRuleSetCondition + exclude?: RawRuleSetCondition + /** A condition matcher matching an absolute path. */ + resource?: RawRuleSetCondition + /** A condition matcher against the resource query. */ + resourceQuery?: RawRuleSetCondition + resourceFragment?: RawRuleSetCondition + descriptionData?: Record + sideEffects?: boolean + use?: RawModuleRuleUses + type?: string + parser?: RawParserOptions + generator?: RawGeneratorOptions + resolve?: RawResolveOptions + issuer?: RawRuleSetCondition + dependency?: RawRuleSetCondition + scheme?: RawRuleSetCondition + mimetype?: RawRuleSetCondition + oneOf?: Array + rules?: Array + /** Specifies the category of the loader. No value means normal loader. */ + enforce?: 'pre' | 'post' +} +export interface RawParserOptions { + type: "asset" | "javascript" | "unknown" + asset?: RawAssetParserOptions + javascript?: RawJavascriptParserOptions +} +export interface RawJavascriptParserOptions { + dynamicImportMode: string + dynamicImportPreload: string + dynamicImportPrefetch: string + url: string +} +export interface RawAssetParserOptions { + dataUrlCondition?: RawAssetParserDataUrl +} +export interface RawAssetParserDataUrl { + type: "options" + options?: RawAssetParserDataUrlOptions +} +export interface RawAssetParserDataUrlOptions { + maxSize?: number +} +export interface RawGeneratorOptions { + type: "asset" | "asset/inline" | "asset/resource" | "unknown" + asset?: RawAssetGeneratorOptions + assetInline?: RawAssetInlineGeneratorOptions + assetResource?: RawAssetResourceGeneratorOptions +} +export interface RawAssetGeneratorOptions { + filename?: string + publicPath?: string + dataUrl?: RawAssetGeneratorDataUrl +} +export interface RawAssetInlineGeneratorOptions { + dataUrl?: RawAssetGeneratorDataUrl +} +export interface RawAssetResourceGeneratorOptions { + filename?: string + publicPath?: string +} +export interface RawAssetGeneratorDataUrl { + type: "options" + options?: RawAssetGeneratorDataUrlOptions +} +export interface RawAssetGeneratorDataUrlOptions { + encoding?: "base64" | "false" | undefined + mimetype?: string +} +export interface RawModuleOptions { + rules: Array + parser?: Record + generator?: Record +} +export interface RawFuncUseCtx { + resource?: string + realResource?: string + resourceQuery?: string + issuer?: string +} +export interface RawNodeOption { + dirname: string + filename: string + global: string +} +export interface RawOptimizationOptions { + removeAvailableModules: boolean + sideEffects: string + usedExports: string + providedExports: boolean + innerGraph: boolean + mangleExports: string + concatenateModules: boolean +} +export interface RawTrustedTypes { + policyName?: string +} +export interface RawLibraryName { + type: "string" | "array" | "umdObject" + stringPayload?: string + arrayPayload?: Array + umdObjectPayload?: RawLibraryCustomUmdObject +} +export interface RawLibraryCustomUmdObject { + amd?: string + commonjs?: string + root?: Array +} +export interface RawLibraryAuxiliaryComment { + root?: string + commonjs?: string + commonjs2?: string + amd?: string +} +export interface RawLibraryOptions { + name?: RawLibraryName + export?: Array + libraryType: string + umdNamedDefine?: boolean + auxiliaryComment?: RawLibraryAuxiliaryComment + amdContainer?: string +} +export interface RawCrossOriginLoading { + type: "bool" | "string" + stringPayload?: string + boolPayload?: boolean +} +export interface RawOutputOptions { + path: string + clean: boolean + publicPath: string + assetModuleFilename: string + wasmLoading: string + enabledWasmLoadingTypes: Array + webassemblyModuleFilename: string + filename: string + chunkFilename: string + crossOriginLoading: RawCrossOriginLoading + cssFilename: string + cssChunkFilename: string + hotUpdateMainFilename: string + hotUpdateChunkFilename: string + hotUpdateGlobal: string + uniqueName: string + chunkLoadingGlobal: string + library?: RawLibraryOptions + strictModuleErrorHandling: boolean + enabledLibraryTypes?: Array + globalObject: string + importFunctionName: string + iife: boolean + module: boolean + chunkLoading: string + enabledChunkLoadingTypes?: Array + trustedTypes?: RawTrustedTypes + sourceMapFilename: string + hashFunction: string + hashDigest: string + hashDigestLength: number + hashSalt?: string + asyncChunks: boolean + workerChunkLoading: string + workerWasmLoading: string + workerPublicPath: string + scriptType: "module" | "text/javascript" | "false" +} +export interface RawResolveTsconfigOptions { + configFile: string + referencesType: "auto" | "manual" | "disabled" + references?: Array +} +export interface RawResolveOptions { + preferRelative?: boolean + preferAbsolute?: boolean + extensions?: Array + mainFiles?: Array + mainFields?: Array + conditionNames?: Array + alias?: Record> + fallback?: Record> + symlinks?: boolean + tsconfig?: RawResolveTsconfigOptions + modules?: Array + byDependency?: Record + fullySpecified?: boolean + exportsFields?: Array + extensionAlias?: Record> + aliasFields?: Array + restrictions?: Array + roots?: Array +} +export interface RawSnapshotStrategy { + hash: boolean + timestamp: boolean +} +export interface RawSnapshotOptions { + resolve: RawSnapshotStrategy + module: RawSnapshotStrategy +} +export interface RawCacheGroupTestCtx { + module: JsModule +} +export interface RawChunkOptionNameCtx { + module: JsModule +} +export interface RawSplitChunksOptions { + fallbackCacheGroup?: RawFallbackCacheGroupOptions + name?: string | false | Function + cacheGroups?: Array + /** What kind of chunks should be selected. */ + chunks?: RegExp | 'async' | 'initial' | 'all' | Function + automaticNameDelimiter?: string + maxAsyncRequests?: number + maxInitialRequests?: number + minChunks?: number + hidePathInfo?: boolean + minSize?: number + enforceSizeThreshold?: number + minRemainingSize?: number + maxSize?: number + maxAsyncSize?: number + maxInitialSize?: number +} +export interface RawCacheGroupOptions { + key: string + priority?: number + test?: RegExp | string | Function + filename?: string + idHint?: string + /** What kind of chunks should be selected. */ + chunks?: RegExp | 'async' | 'initial' | 'all' + type?: RegExp | string + automaticNameDelimiter?: string + minChunks?: number + minSize?: number + maxSize?: number + maxAsyncSize?: number + maxInitialSize?: number + name?: string | false | Function + reuseExistingChunk?: boolean + enforce?: boolean +} +export interface RawFallbackCacheGroupOptions { + chunks?: RegExp | 'async' | 'initial' | 'all' + minSize?: number + maxSize?: number + maxAsyncSize?: number + maxInitialSize?: number + automaticNameDelimiter?: string +} +export interface RawStatsOptions { + colors: boolean +} +export interface RawOptions { + mode?: undefined | 'production' | 'development' | 'none' + target: Array + context: string + output: RawOutputOptions + resolve: RawResolveOptions + resolveLoader: RawResolveOptions + module: RawModuleOptions + devtool: string + optimization: RawOptimizationOptions + stats: RawStatsOptions + snapshot: RawSnapshotOptions + cache: RawCacheOptions + experiments: RawExperiments + node?: RawNodeOption + profile: boolean + bail: boolean + builtins: RawBuiltins +} export interface RawStrategyOptions { name: string topLevelFrameworks: Array } export interface RawFeatures { splitChunksStrategy?: RawStrategyOptions + assetsManifest?: boolean } export interface RspackRawOptimizationOptions { removeAvailableModules: boolean @@ -17,6 +1062,7 @@ export interface RspackRawOptimizationOptions { providedExports: boolean innerGraph: boolean mangleExports: string + concatenateModules: boolean } export interface RsPackRawOptions { mode?: undefined | 'production' | 'development' | 'none' @@ -29,7 +1075,6 @@ export interface RsPackRawOptions { devtool: string optimization: RspackRawOptimizationOptions stats: RawStatsOptions - devServer: RawDevServer snapshot: RawSnapshotOptions cache: RawCacheOptions experiments: RawExperiments @@ -50,6 +1095,56 @@ export function runBuiltinLoader(builtin: string, options: string | undefined | */ export function registerGlobalTrace(filter: string, layer: "chrome" | "logger", output: string): void export function cleanupGlobalTrace(): void +export class JsCompilation { + updateAsset(filename: string, newSourceOrFunction: JsCompatSource | ((source: JsCompatSource) => JsCompatSource), assetInfoUpdateOrFunction?: JsAssetInfo | ((assetInfo: JsAssetInfo) => JsAssetInfo)): void + getAssets(): Readonly[] + getAsset(name: string): JsAsset | null + getAssetSource(name: string): JsCompatSource | null + getModules(): Array + getChunks(): Array + getNamedChunk(name: string): JsChunk | null + /** + * Only available for those none Js and Css source, + * return true if set module source successfully, false if failed. + */ + setNoneAstModuleSource(moduleIdentifier: string, source: JsCompatSource): boolean + setAssetSource(name: string, source: JsCompatSource): void + deleteAssetSource(name: string): void + getAssetFilenames(): Array + hasAsset(name: string): boolean + emitAsset(filename: string, source: JsCompatSource, assetInfo: JsAssetInfo): void + deleteAsset(filename: string): void + get entrypoints(): Record + get hash(): string | null + getFileDependencies(): Array + getContextDependencies(): Array + getMissingDependencies(): Array + getBuildDependencies(): Array + pushDiagnostic(severity: "error" | "warning", title: string, message: string): void + pushNativeDiagnostics(diagnostics: ExternalObject<'Diagnostic[]'>): void + getStats(): JsStats + getAssetPath(filename: string, data: PathData): string + getAssetPathWithInfo(filename: string, data: PathData): PathWithInfo + getPath(filename: string, data: PathData): string + getPathWithInfo(filename: string, data: PathData): PathWithInfo + addFileDependencies(deps: Array): void + addContextDependencies(deps: Array): void + addMissingDependencies(deps: Array): void + addBuildDependencies(deps: Array): void + rebuildModule(moduleIdentifiers: Array, f: (...args: any[]) => any): void + importModule(request: string, publicPath: string | undefined | null, baseUri: string | undefined | null, originalModule: string | undefined | null, originalModuleContext: string | undefined | null, callback: (...args: any[]) => any): void +} +export class JsStats { + getAssets(): JsStatsGetAssets + getModules(reasons: boolean, moduleAssets: boolean, nestedModules: boolean, source: boolean): Array + getChunks(chunkModules: boolean, chunksRelations: boolean, reasons: boolean, moduleAssets: boolean, nestedModules: boolean, source: boolean): Array + getEntrypoints(): Array + getNamedChunkGroups(): Array + getErrors(): Array + getWarnings(): Array + getLogging(acceptedTypes: number): Array + getHash(): string | null +} export class Rspack { constructor(options: RSPackRawOptions, builtinPlugins: Array, jsHooks: JsHooks | undefined | null, outputFilesystem: ThreadsafeNodeFS, jsLoaderRunner: (...args: any[]) => any) unsafe_set_disabled_hooks(hooks: Array): void diff --git a/crates/node_binding/index.js b/crates/node_binding/index.js index b87c862..65024f8 100644 --- a/crates/node_binding/index.js +++ b/crates/node_binding/index.js @@ -252,8 +252,22 @@ if (!nativeBinding) { throw new Error(`Failed to load native binding`) } -const { runBuiltinLoader, Rspack, registerGlobalTrace, cleanupGlobalTrace } = nativeBinding +const { __chunk_inner_is_only_initial, __chunk_inner_can_be_initial, __chunk_inner_has_runtime, __chunk_inner_get_all_async_chunks, __chunk_inner_get_all_initial_chunks, __chunk_inner_get_all_referenced_chunks, __chunk_graph_inner_get_chunk_modules, __chunk_graph_inner_get_chunk_entry_modules, __chunk_graph_inner_get_chunk_entry_dependent_chunks_iterable, __chunk_graph_inner_get_chunk_modules_iterable_by_source_type, __chunk_group_inner_get_chunk_group, JsCompilation, JsStats, BuiltinPluginName, runBuiltinLoader, Rspack, registerGlobalTrace, cleanupGlobalTrace } = nativeBinding +module.exports.__chunk_inner_is_only_initial = __chunk_inner_is_only_initial +module.exports.__chunk_inner_can_be_initial = __chunk_inner_can_be_initial +module.exports.__chunk_inner_has_runtime = __chunk_inner_has_runtime +module.exports.__chunk_inner_get_all_async_chunks = __chunk_inner_get_all_async_chunks +module.exports.__chunk_inner_get_all_initial_chunks = __chunk_inner_get_all_initial_chunks +module.exports.__chunk_inner_get_all_referenced_chunks = __chunk_inner_get_all_referenced_chunks +module.exports.__chunk_graph_inner_get_chunk_modules = __chunk_graph_inner_get_chunk_modules +module.exports.__chunk_graph_inner_get_chunk_entry_modules = __chunk_graph_inner_get_chunk_entry_modules +module.exports.__chunk_graph_inner_get_chunk_entry_dependent_chunks_iterable = __chunk_graph_inner_get_chunk_entry_dependent_chunks_iterable +module.exports.__chunk_graph_inner_get_chunk_modules_iterable_by_source_type = __chunk_graph_inner_get_chunk_modules_iterable_by_source_type +module.exports.__chunk_group_inner_get_chunk_group = __chunk_group_inner_get_chunk_group +module.exports.JsCompilation = JsCompilation +module.exports.JsStats = JsStats +module.exports.BuiltinPluginName = BuiltinPluginName module.exports.runBuiltinLoader = runBuiltinLoader module.exports.Rspack = Rspack module.exports.registerGlobalTrace = registerGlobalTrace diff --git a/crates/swc_change_package_import/Cargo.toml b/crates/swc_change_package_import/Cargo.toml index 92deb34..4ca80a2 100644 --- a/crates/swc_change_package_import/Cargo.toml +++ b/crates/swc_change_package_import/Cargo.toml @@ -8,6 +8,7 @@ crate-type = ["cdylib", "rlib"] [dependencies] serde = { workspace = true } +serde_json = { workspace = true } swc_core = { workspace = true, features = [ "base", "ecma_ast", diff --git a/crates/swc_change_package_import/src/change_package_import.rs b/crates/swc_change_package_import/src/change_package_import.rs index 8a178c3..421c51e 100644 --- a/crates/swc_change_package_import/src/change_package_import.rs +++ b/crates/swc_change_package_import/src/change_package_import.rs @@ -15,6 +15,10 @@ pub struct ModuleImportVisitor { pub options: Vec, } +pub fn change_package_import(options: Vec) -> impl Fold { + ModuleImportVisitor::new(options) +} + impl ModuleImportVisitor { pub fn new(options: Vec) -> Self { Self { options } diff --git a/crates/swc_change_package_import/src/config.rs b/crates/swc_change_package_import/src/config.rs index 1f31ff3..f23bbf1 100644 --- a/crates/swc_change_package_import/src/config.rs +++ b/crates/swc_change_package_import/src/config.rs @@ -1,6 +1,7 @@ use std::collections::HashMap; +use serde::{Deserialize, Serialize}; -#[derive(Debug)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub enum Config { /// 配置: /// ```rs @@ -42,20 +43,20 @@ pub enum Config { SpecificConfig(SpecificConfigs), } -#[derive(Debug)] +#[derive(Debug, Clone ,Serialize, Deserialize)] pub struct SpecificConfigs { pub name: String, pub map: HashMap, } -#[derive(Debug)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct MapProperty { pub to: String, pub import_type: Option, pub name: Option, } -#[derive(Debug, PartialEq)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub enum ImportType { Named, Default, diff --git a/crates/swc_optimize_barrel/Cargo.toml b/crates/swc_optimize_barrel/Cargo.toml index a275820..3b575c6 100644 --- a/crates/swc_optimize_barrel/Cargo.toml +++ b/crates/swc_optimize_barrel/Cargo.toml @@ -4,7 +4,7 @@ version = "0.1.0" edition = "2021" [dependencies] -serde_json = "1.0.100" +serde_json = { workspace = true } serde = { workspace = true, features = ["derive"] } swc_core = { workspace = true, features = [ "base",