@bleedingdev/modern-js-builder 3.9.0-ultramodern.8 → 3.9.3-ultramodern.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,19 +7,26 @@ var __rspack_import_meta_dirname__ = __rspack_dirname(__rspack_fileURLToPath(imp
7
7
  const ASYNC_STORAGE_PATTERN = /universal[/\\]async_storage/;
8
8
  const SERVER_LOADER_ENTRY_PATTERN = /[/\\](?:server-loader-combined|route-server-loaders)\.js$/;
9
9
  const RENDER_RSC_SOURCE_PATTERN = /render[/\\].*[/\\]server[/\\]rsc/;
10
- const RENDER_RSC_RSLIB_ENTRY_PATTERN = /render[/\\]dist[/\\]esm[/\\]rsc(?:Worker)?\.mjs$/;
11
- const RENDER_RSC_RUNTIME = '@modern-js/render/rsc';
12
- const RENDER_RSC_WORKER_RUNTIME = '@modern-js/render/rsc-worker';
10
+ const RENDER_RSC_RSLIB_ENTRY_PATTERN = /render[/\\]dist[/\\]esm[/\\]rsc(?:\.edge)?\.mjs$/;
13
11
  const RSC_COMMON_LAYER = 'rsc-common';
14
12
  const ENTRY_NAME_VAR = '__MODERN_JS_ENTRY_NAME';
15
13
  const ROUTE_DATA_FILE_PATTERN = /[/\\]routes[/\\](?:.*[/\\])?(?:layout|page|\$)\.(?:loader|data)\.[tj]sx?(?:\?.*)?$/;
16
14
  const createVirtualModule = (content)=>`data:text/javascript,${encodeURIComponent(content)}`;
15
+ const resolveRscEnvironments = (environments)=>{
16
+ const resolved = {
17
+ server: environments?.server ?? 'server',
18
+ client: environments?.client ?? 'client'
19
+ };
20
+ for (const [role, name] of Object.entries(resolved))if ('string' != typeof name || !name.trim()) throw new TypeError(`RSC ${role} environment must have a nonempty name`);
21
+ return resolved;
22
+ };
17
23
  const isAsyncStorageExclude = (exclude)=>{
18
24
  if ('string' == typeof exclude) return ASYNC_STORAGE_PATTERN.test(exclude);
19
25
  if (exclude instanceof RegExp) return exclude.test('universal/async_storage') || exclude.test('universal\\async_storage');
20
26
  return false;
21
27
  };
22
- function pluginRscConfig() {
28
+ function pluginRscConfig(environments, rscLayerMatchers = []) {
29
+ const serverEnvironment = resolveRscEnvironments(environments).server;
23
30
  return {
24
31
  name: 'builder:rsc-config',
25
32
  setup (api) {
@@ -32,9 +39,8 @@ function pluginRscConfig() {
32
39
  return layersCache;
33
40
  };
34
41
  api.modifyBundlerChain({
35
- handler: (chain, { isServer })=>{
36
- if (isServer) {
37
- chain.resolve.alias.set(`${RENDER_RSC_RUNTIME}$`, RENDER_RSC_WORKER_RUNTIME);
42
+ handler: (chain, { isServer, environment })=>{
43
+ if (isServer || environment.name === serverEnvironment) {
38
44
  let emptyModulePath;
39
45
  try {
40
46
  emptyModulePath = require.resolve('../shared/rsc/rscEmptyModule');
@@ -57,9 +63,25 @@ function pluginRscConfig() {
57
63
  order: 'pre'
58
64
  });
59
65
  api.modifyRspackConfig(async (config, utils)=>{
60
- const isServer = 'node' === config.target || 'node' === utils.target || utils.environment?.name === 'server';
66
+ const isServer = 'node' === config.target || 'node' === utils.target || utils.environment?.name === serverEnvironment;
61
67
  if (!isServer) return;
62
68
  const Layers = await getLayers();
69
+ if (utils.environment?.name !== serverEnvironment && rscLayerMatchers.length > 0) {
70
+ config.module ??= {};
71
+ config.module.rules ??= [];
72
+ config.module.rules.push({
73
+ test: rscLayerMatchers,
74
+ layer: Layers.rsc
75
+ }, {
76
+ issuerLayer: Layers.rsc,
77
+ resolve: {
78
+ conditionNames: [
79
+ 'react-server',
80
+ '...'
81
+ ]
82
+ }
83
+ });
84
+ }
63
85
  if (config.entry) {
64
86
  const entries = config.entry;
65
87
  const newEntries = {};
@@ -96,8 +118,8 @@ function pluginRscConfig() {
96
118
  });
97
119
  }
98
120
  });
99
- api.modifyBundlerChain((chain, { isServer, isWebWorker })=>{
100
- if (!isServer && !isWebWorker) {
121
+ api.modifyBundlerChain((chain, { isServer, isWebWorker, environment })=>{
122
+ if (!isServer && !isWebWorker && environment.name !== serverEnvironment) {
101
123
  const entries = chain.entryPoints.entries();
102
124
  if (entries && 'object' == typeof entries) for (const entryName of Object.keys(entries)){
103
125
  const entryPoint = chain.entry(entryName);
@@ -111,13 +133,12 @@ function pluginRscConfig() {
111
133
  }
112
134
  async function getRscPlugins(enableRsc, internalDirectory, environments) {
113
135
  if (enableRsc) {
136
+ const rscEnvironments = resolveRscEnvironments(environments);
114
137
  const rscLayerMatchers = createRscLayerMatchers(internalDirectory);
115
138
  const { pluginRSC } = await import("rsbuild-plugin-rsc");
116
139
  return [
117
140
  pluginRSC({
118
- ...environments ? {
119
- environments
120
- } : {},
141
+ environments: rscEnvironments,
121
142
  layers: {
122
143
  ssr: SERVER_LOADER_ENTRY_PATTERN,
123
144
  rsc: [
@@ -128,7 +149,7 @@ async function getRscPlugins(enableRsc, internalDirectory, environments) {
128
149
  ]
129
150
  }
130
151
  }),
131
- pluginRscConfig()
152
+ pluginRscConfig(rscEnvironments, rscLayerMatchers)
132
153
  ];
133
154
  }
134
155
  return [];
@@ -2,7 +2,6 @@ import "node:module";
2
2
  import { mergeRsbuildConfig } from "@rsbuild/core";
3
3
  import { pluginCssMinimizer } from "@rsbuild/plugin-css-minimizer";
4
4
  import { pluginLess } from "@rsbuild/plugin-less";
5
- import { pluginReact } from "@rsbuild/plugin-react";
6
5
  import { pluginSass } from "@rsbuild/plugin-sass";
7
6
  import { pluginDevtool } from "../plugins/devtools.mjs";
8
7
  import { pluginEmitRouteFile } from "../plugins/emitRouteFile.mjs";
@@ -11,7 +10,9 @@ import { pluginGlobalVars } from "../plugins/globalVars.mjs";
11
10
  import { pluginHtmlMinifierTerser } from "../plugins/htmlMinify.mjs";
12
11
  import { pluginRuntimeChunk } from "../plugins/runtimeChunk.mjs";
13
12
  import { transformToRsbuildServerOptions } from "./devServer.mjs";
14
- import { NODE_MODULES_REGEX } from "./utils.mjs";
13
+ import { normalizeLessOptions, normalizeSassOptions, resolveSvgrOptions } from "./pluginOptions.mjs";
14
+ import { withTsgoDefaults } from "./tsgo.mjs";
15
+ import { NODE_MODULES_REGEX, SERVICE_WORKER_ENVIRONMENT_NAME } from "./utils.mjs";
15
16
  const CSS_MODULES_REGEX = /\.modules?\.\w+$/i;
16
17
  const GLOBAL_CSS_REGEX = /\.global\.\w+$/;
17
18
  const DEFAULT_CSS_MINIFIER_OPTIONS = {
@@ -37,7 +38,7 @@ function removeUndefinedKey(obj) {
37
38
  }
38
39
  async function parseCommonConfig(builderConfig, options) {
39
40
  const frameworkConfigPath = options?.frameworkConfigPath;
40
- const { plugins: [...plugins] = [], splitChunks, performance: { ...performanceConfig } = {}, output: { module = false, enableCssModuleTSDeclaration, disableCssModuleExtension, disableTsChecker, disableSvgr, svgDefaultExport, assetsRetry, enableAssetManifest, sourceMap, convertToRem, polyfill, dataUriLimit = 10000, distPath = {}, ...outputConfig } = {}, html: { outputStructure, appIcon, ...htmlConfig } = {}, source: { alias, globalVars, transformImport, reactCompiler, ...sourceConfig } = {}, dev = {}, server = {}, security: { checkSyntax, sri, ...securityConfig } = {}, tools: { devServer, tsChecker, minifyCss, less, sass, htmlPlugin, autoprefixer, ...toolsConfig } = {}, environments = {}, resolve = {} } = builderConfig;
41
+ const { plugins: [...plugins] = [], splitChunks, performance: { ...performanceConfig } = {}, output: { module = false, enableCssModuleTSDeclaration, disableCssModuleExtension, disableTsChecker, disableSvgr, svgDefaultExport, assetsRetry, enableAssetManifest, sourceMap, convertToRem, polyfill, dataUriLimit = 10000, distPath = {}, ...outputConfig } = {}, html: { outputStructure, appIcon, ...htmlConfig } = {}, source: { alias, globalVars, transformImport, reactCompiler, ...sourceConfig } = {}, dev = {}, server = {}, security: { checkSyntax, sri, ...securityConfig } = {}, tools: { devServer, tsChecker, minifyCss, less, sass, svgr, htmlPlugin, autoprefixer, ...toolsConfig } = {}, environments = {}, resolve = {} } = builderConfig;
41
42
  let combinedAlias;
42
43
  if (alias || resolve.alias) combinedAlias = [].concat(alias ?? []).concat(resolve.alias ?? []);
43
44
  const rsbuildConfig = {
@@ -120,12 +121,8 @@ async function parseCommonConfig(builderConfig, options) {
120
121
  sourceMap
121
122
  }),
122
123
  pluginEmitRouteFile(),
123
- pluginSass({
124
- sassLoaderOptions: sass
125
- }),
126
- pluginLess({
127
- lessLoaderOptions: less
128
- }),
124
+ pluginSass(normalizeSassOptions(sass)),
125
+ pluginLess(normalizeLessOptions(less)),
129
126
  pluginEnvironmentDefaults(distPath),
130
127
  pluginHtmlMinifierTerser()
131
128
  ];
@@ -136,7 +133,7 @@ async function parseCommonConfig(builderConfig, options) {
136
133
  if (!disableTsChecker) {
137
134
  const { pluginTypeCheck } = await import("@rsbuild/plugin-type-check");
138
135
  rsbuildPlugins.push(pluginTypeCheck({
139
- tsCheckerOptions: tsChecker
136
+ tsCheckerOptions: withTsgoDefaults(tsChecker, options?.cwd ?? process.cwd())
140
137
  }));
141
138
  }
142
139
  if (convertToRem) {
@@ -152,19 +149,44 @@ async function parseCommonConfig(builderConfig, options) {
152
149
  const { pluginSourceBuild } = await import("@rsbuild/plugin-source-build");
153
150
  rsbuildPlugins.push(pluginSourceBuild(true === sourceBuild ? {} : sourceBuild));
154
151
  }
155
- rsbuildPlugins.push(pluginReact(options?.disableReactCompiler || void 0 === reactCompiler ? {} : {
156
- reactCompiler
157
- }));
158
- if (!disableSvgr) {
159
- const { pluginSvgr } = await import("@rsbuild/plugin-svgr");
160
- rsbuildPlugins.push(pluginSvgr({
161
- mixedImport: true,
162
- parallel: true,
163
- svgrOptions: {
164
- exportType: 'component' === svgDefaultExport ? 'default' : 'named'
165
- }
166
- }));
167
- }
152
+ rsbuildPlugins.push({
153
+ name: 'rsbuild:react',
154
+ async setup (api) {
155
+ const { pluginReact } = await import("@rsbuild/plugin-react");
156
+ return pluginReact().setup(api);
157
+ }
158
+ });
159
+ if (!options?.disableReactCompiler && void 0 !== reactCompiler) rsbuildPlugins.push({
160
+ name: 'builder:react-compiler',
161
+ setup (api) {
162
+ api.modifyEnvironmentConfig((config, { name, mergeEnvironmentConfig })=>'web' === config.output.target && name !== SERVICE_WORKER_ENVIRONMENT_NAME ? mergeEnvironmentConfig({
163
+ tools: {
164
+ swc: {
165
+ jsc: {
166
+ transform: {
167
+ reactCompiler
168
+ }
169
+ }
170
+ }
171
+ }
172
+ }, config) : config);
173
+ }
174
+ });
175
+ const svgrOptions = resolveSvgrOptions({
176
+ svgr,
177
+ disableSvgr,
178
+ svgDefaultExport
179
+ });
180
+ if (false !== svgrOptions) rsbuildPlugins.push({
181
+ name: 'rsbuild:svgr',
182
+ pre: [
183
+ 'rsbuild:react'
184
+ ],
185
+ async setup (api) {
186
+ const { pluginSvgr } = await import("@rsbuild/plugin-svgr");
187
+ await pluginSvgr(svgrOptions).setup(api);
188
+ }
189
+ });
168
190
  if (assetsRetry) {
169
191
  const { pluginAssetsRetry } = await import("@rsbuild/plugin-assets-retry");
170
192
  rsbuildPlugins.push(pluginAssetsRetry(assetsRetry));
@@ -0,0 +1,76 @@
1
+ import "node:module";
2
+ import { applyOptionsChain, isDevCommand, logger } from "@modern-js/utils";
3
+ const LESS_PLUGIN_KEYS = [
4
+ 'lessLoaderOptions',
5
+ 'include',
6
+ 'exclude',
7
+ 'parallel'
8
+ ];
9
+ const SASS_PLUGIN_KEYS = [
10
+ 'sassLoaderOptions',
11
+ 'include',
12
+ 'exclude',
13
+ 'rewriteUrls'
14
+ ];
15
+ const warned = new Set();
16
+ const resetPluginOptionsWarnings = ()=>{
17
+ warned.clear();
18
+ };
19
+ const warnOnceInDev = (key, message)=>{
20
+ if (!isDevCommand() || warned.has(key)) return;
21
+ warned.add(key);
22
+ logger.warn(message);
23
+ };
24
+ const isPlainObject = (value)=>'object' == typeof value && null !== value && !Array.isArray(value);
25
+ const isPluginLevelOptions = (value, pluginKeys)=>isPlainObject(value) && pluginKeys.some((key)=>key in value);
26
+ const isEmptyObject = (value)=>isPlainObject(value) && 0 === Object.keys(value).length;
27
+ const warnIgnoredKeys = (name, value, pluginKeys, loaderOptionsKey)=>{
28
+ const pluginLevel = Object.keys(value).filter((key)=>pluginKeys.includes(key));
29
+ const ignored = Object.keys(value).filter((key)=>!pluginKeys.includes(key));
30
+ if (0 === ignored.length) return;
31
+ warnOnceInDev(`${name}:mixed`, `\`${name}\` contains plugin-level options (${pluginLevel.join(', ')}) together with other keys (${ignored.join(', ')}). The whole object is passed to the plugin, so the other keys are ignored. Move loader options under \`${loaderOptionsKey}\`.`);
32
+ };
33
+ const normalizeLessOptions = (less)=>{
34
+ if (isPluginLevelOptions(less, LESS_PLUGIN_KEYS)) {
35
+ warnIgnoredKeys('tools.less', less, LESS_PLUGIN_KEYS, 'lessLoaderOptions');
36
+ return less;
37
+ }
38
+ if (void 0 !== less && !isEmptyObject(less)) warnOnceInDev('tools.less', "`tools.less` now accepts the full options of @rsbuild/plugin-less. Passing less-loader options directly is deprecated and will stop working in the next major version. Move them under `lessLoaderOptions`:\n before: tools: { less: { lessOptions: { javascriptEnabled: true } } }\n after: tools: { less: { lessLoaderOptions: { lessOptions: { javascriptEnabled: true } } } }");
39
+ return {
40
+ lessLoaderOptions: less
41
+ };
42
+ };
43
+ const normalizeSassOptions = (sass)=>{
44
+ if (isPluginLevelOptions(sass, SASS_PLUGIN_KEYS)) {
45
+ warnIgnoredKeys('tools.sass', sass, SASS_PLUGIN_KEYS, 'sassLoaderOptions');
46
+ return sass;
47
+ }
48
+ if (void 0 !== sass && !isEmptyObject(sass)) warnOnceInDev('tools.sass', "`tools.sass` now accepts the full options of @rsbuild/plugin-sass. Passing sass-loader options directly is deprecated and will stop working in the next major version. Move them under `sassLoaderOptions`:\n before: tools: { sass: { sassOptions: { quietDeps: true } } }\n after: tools: { sass: { sassLoaderOptions: { sassOptions: { quietDeps: true } } } }");
49
+ return {
50
+ sassLoaderOptions: sass
51
+ };
52
+ };
53
+ const mergeSvgrOptions = (target, source)=>{
54
+ const svgrOptions = source.svgrOptions ? {
55
+ ...target.svgrOptions,
56
+ ...source.svgrOptions
57
+ } : target.svgrOptions;
58
+ return Object.assign(target, source, {
59
+ svgrOptions
60
+ });
61
+ };
62
+ const resolveSvgrOptions = ({ svgr, disableSvgr, svgDefaultExport })=>{
63
+ if (void 0 !== disableSvgr) warnOnceInDev('output.disableSvgr', disableSvgr ? '`output.disableSvgr` is deprecated and will be removed in the next major version. Use `tools: { svgr: false }` instead.' : '`output.disableSvgr` is deprecated and will be removed in the next major version. SVGR is enabled by default, so `output.disableSvgr: false` can be removed (or use `tools: { svgr: {} }` to keep it explicit).');
64
+ if (void 0 !== svgDefaultExport) warnOnceInDev('output.svgDefaultExport', "`output.svgDefaultExport` is deprecated and will be removed in the next major version. Use `tools.svgr.svgrOptions.exportType` instead:\n before: output: { svgDefaultExport: 'component' }\n after: tools: { svgr: { svgrOptions: { exportType: 'default' } } }\n ('url' maps to exportType: 'named')");
65
+ if (false === svgr) return false;
66
+ if (void 0 === svgr && disableSvgr) return false;
67
+ const defaults = {
68
+ mixedImport: true,
69
+ parallel: true,
70
+ svgrOptions: {
71
+ exportType: 'component' === svgDefaultExport ? 'default' : 'named'
72
+ }
73
+ };
74
+ return applyOptionsChain(defaults, svgr, void 0, mergeSvgrOptions);
75
+ };
76
+ export { normalizeLessOptions, normalizeSassOptions, resetPluginOptionsWarnings, resolveSvgrOptions };
@@ -0,0 +1,199 @@
1
+ import "node:module";
2
+ import { createHash } from "node:crypto";
3
+ import node_fs from "node:fs";
4
+ import { createRequire } from "node:module";
5
+ import node_path from "node:path";
6
+ import { json5 } from "@modern-js/utils";
7
+ const builderRequire = createRequire(import.meta.url);
8
+ const STABLE_TSGO_PACKAGE = "typescript/package.json";
9
+ const TSGO_CHECKER_DIR = node_path.join('.modern-js', 'tsgo');
10
+ const tryResolve = (request, rootPath)=>{
11
+ try {
12
+ return builderRequire.resolve(request, {
13
+ paths: [
14
+ rootPath
15
+ ]
16
+ });
17
+ } catch {
18
+ return;
19
+ }
20
+ };
21
+ const resolveTsgoPackagePath = (rootPath)=>{
22
+ const packageJsonPath = tryResolve(STABLE_TSGO_PACKAGE, rootPath) ?? builderRequire.resolve(STABLE_TSGO_PACKAGE);
23
+ const packageJson = JSON.parse(node_fs.readFileSync(packageJsonPath, 'utf8'));
24
+ if ("typescript" !== packageJson.name || '7.0.2' !== packageJson.version) throw new Error(`The native type checker requires typescript@7.0.2; found ${String(packageJson.name)}@${String(packageJson.version)} at ${packageJsonPath}.`);
25
+ return packageJsonPath;
26
+ };
27
+ const toPosixPath = (input)=>input.replaceAll(node_path.sep, '/');
28
+ const asTsConfigPath = (request)=>{
29
+ if (node_path.extname(request)) return [
30
+ request
31
+ ];
32
+ return [
33
+ request,
34
+ `${request}.json`
35
+ ];
36
+ };
37
+ const resolveExtends = (request, configDirectory)=>{
38
+ const configRequire = createRequire(node_path.join(configDirectory, 'tsconfig.json'));
39
+ for (const candidate of asTsConfigPath(request)){
40
+ if (candidate.startsWith('.') || node_path.isAbsolute(candidate)) {
41
+ const resolved = node_path.resolve(configDirectory, candidate);
42
+ if (node_fs.existsSync(resolved)) return resolved;
43
+ continue;
44
+ }
45
+ try {
46
+ return configRequire.resolve(candidate);
47
+ } catch {}
48
+ }
49
+ };
50
+ const PATH_COMPILER_OPTIONS = [
51
+ 'rootDir',
52
+ 'outDir',
53
+ 'declarationDir'
54
+ ];
55
+ const absolutiseConfigPaths = (compilerOptions, configDirectory)=>{
56
+ if (!compilerOptions) return {};
57
+ const resolved = {
58
+ ...compilerOptions
59
+ };
60
+ for (const option of PATH_COMPILER_OPTIONS){
61
+ const value = resolved[option];
62
+ if ('string' == typeof value && !node_path.isAbsolute(value)) resolved[option] = node_path.resolve(configDirectory, value);
63
+ }
64
+ return resolved;
65
+ };
66
+ const readTsConfig = (configFile, visited = new Set())=>{
67
+ if (visited.has(configFile) || !node_fs.existsSync(configFile)) return {};
68
+ visited.add(configFile);
69
+ const config = json5.parse(node_fs.readFileSync(configFile, 'utf8'));
70
+ const configDirectory = node_path.dirname(configFile);
71
+ const extendsList = Array.isArray(config.extends) ? config.extends : config.extends ? [
72
+ config.extends
73
+ ] : [];
74
+ const baseConfig = extendsList.reduce((merged, request)=>{
75
+ const resolved = resolveExtends(request, configDirectory);
76
+ if (!resolved) return merged;
77
+ const parentConfig = readTsConfig(resolved, visited);
78
+ return {
79
+ ...merged,
80
+ compilerOptions: {
81
+ ...merged.compilerOptions ?? {},
82
+ ...parentConfig.compilerOptions ?? {}
83
+ }
84
+ };
85
+ }, {});
86
+ return {
87
+ ...baseConfig,
88
+ compilerOptions: {
89
+ ...baseConfig.compilerOptions ?? {},
90
+ ...absolutiseConfigPaths(config.compilerOptions, configDirectory)
91
+ }
92
+ };
93
+ };
94
+ const readProjectReferences = (configFile)=>{
95
+ if (!node_fs.existsSync(configFile)) return [];
96
+ const config = json5.parse(node_fs.readFileSync(configFile, 'utf8'));
97
+ if (!Array.isArray(config.references)) return [];
98
+ const configDirectory = node_path.dirname(configFile);
99
+ return config.references.filter((reference)=>'string' == typeof reference?.path).map((reference)=>({
100
+ ...reference,
101
+ path: toPosixPath(node_path.resolve(configDirectory, reference.path))
102
+ }));
103
+ };
104
+ const toRelativeConfigPath = (fromDirectory, target)=>{
105
+ const relative = toPosixPath(node_path.relative(fromDirectory, target));
106
+ if (relative.startsWith('.')) return relative;
107
+ return `./${relative}`;
108
+ };
109
+ const writeFileIfChanged = (file, content)=>{
110
+ if (node_fs.existsSync(file) && node_fs.readFileSync(file, 'utf8') === content) return;
111
+ node_fs.writeFileSync(file, content);
112
+ };
113
+ const defaultTsgoCheckerConfigFile = (configFile)=>{
114
+ const hash = createHash('sha1').update(configFile).digest('hex').slice(0, 10);
115
+ return node_path.join(node_path.dirname(configFile), TSGO_CHECKER_DIR, `tsconfig.${hash}.json`);
116
+ };
117
+ const createTsgoCheckerConfig = (configFile, checkerConfigFile = defaultTsgoCheckerConfigFile(configFile))=>{
118
+ const configDirectory = node_path.dirname(configFile);
119
+ const checkerConfigDirectory = node_path.dirname(checkerConfigFile);
120
+ const tsConfig = readTsConfig(configFile);
121
+ const compilerOptions = {
122
+ baseUrl: null
123
+ };
124
+ const declaredRootDir = tsConfig.compilerOptions?.rootDir;
125
+ if ('string' == typeof declaredRootDir) compilerOptions.rootDir = toPosixPath(declaredRootDir);
126
+ else compilerOptions.rootDir = toPosixPath(configDirectory);
127
+ const moduleResolution = String(tsConfig.compilerOptions?.moduleResolution).toLowerCase();
128
+ if ([
129
+ 'node',
130
+ 'node10'
131
+ ].includes(moduleResolution)) compilerOptions.moduleResolution = null;
132
+ const references = readProjectReferences(configFile);
133
+ const checkerConfig = {
134
+ extends: toRelativeConfigPath(checkerConfigDirectory, configFile),
135
+ compilerOptions,
136
+ ...references.length > 0 ? {
137
+ references
138
+ } : {}
139
+ };
140
+ node_fs.mkdirSync(checkerConfigDirectory, {
141
+ recursive: true
142
+ });
143
+ writeFileIfChanged(checkerConfigFile, `${JSON.stringify(checkerConfig, null, 2)}\n`);
144
+ return checkerConfigFile;
145
+ };
146
+ const refreshTsgoCheckerConfig = (checkerConfigFile)=>{
147
+ const checkerConfigDirectory = node_path.dirname(checkerConfigFile);
148
+ if ('tsgo' !== node_path.basename(checkerConfigDirectory) || '.modern-js' !== node_path.basename(node_path.dirname(checkerConfigDirectory)) || !node_fs.existsSync(checkerConfigFile)) return;
149
+ let checkerConfig;
150
+ try {
151
+ checkerConfig = json5.parse(node_fs.readFileSync(checkerConfigFile, 'utf8'));
152
+ } catch {
153
+ return;
154
+ }
155
+ if ('string' != typeof checkerConfig.extends) return;
156
+ const projectConfigFile = node_path.resolve(checkerConfigDirectory, checkerConfig.extends);
157
+ if (node_fs.existsSync(projectConfigFile)) try {
158
+ createTsgoCheckerConfig(projectConfigFile, checkerConfigFile);
159
+ } catch {}
160
+ return projectConfigFile;
161
+ };
162
+ const normalizeTsgoConfig = (config, rootPath)=>{
163
+ const { typescript } = config;
164
+ if (typescript?.tsgo === false) return config;
165
+ const compilerOptions = {
166
+ ...typescript?.configOverwrite?.compilerOptions ?? {},
167
+ baseUrl: null
168
+ };
169
+ if ([
170
+ 'node',
171
+ 'node10'
172
+ ].includes(String(compilerOptions.moduleResolution).toLowerCase())) compilerOptions.moduleResolution = null;
173
+ config.typescript = {
174
+ ...typescript,
175
+ configOverwrite: {
176
+ ...typescript?.configOverwrite ?? {},
177
+ compilerOptions
178
+ }
179
+ };
180
+ if (typescript?.configFile) config.typescript.configFile = createTsgoCheckerConfig(node_path.resolve(rootPath, typescript.configFile));
181
+ return config;
182
+ };
183
+ const withTsgoDefaults = (userOptions, rootPath)=>{
184
+ const tsgoPath = resolveTsgoPackagePath(rootPath);
185
+ const userChain = userOptions ? Array.isArray(userOptions) ? userOptions : [
186
+ userOptions
187
+ ] : [];
188
+ return [
189
+ {
190
+ typescript: {
191
+ tsgo: true,
192
+ typescriptPath: tsgoPath
193
+ }
194
+ },
195
+ ...userChain,
196
+ (config)=>normalizeTsgoConfig(config, rootPath)
197
+ ];
198
+ };
199
+ export { refreshTsgoCheckerConfig, withTsgoDefaults };
@@ -2,7 +2,8 @@ import { type BuilderInstance, createRspackBuilder } from './createBuilder.js';
2
2
  import type { CreateBuilderOptions } from './types.js';
3
3
  export { type ChainIdentifier, type ConfigChain, logger, type NormalizedConfig, type RsbuildConfig, type RsbuildContext, type RsbuildPlugin, type RsbuildPlugins, type RsbuildTarget, type Rspack, type RspackChain, } from '@rsbuild/core';
4
4
  export { parseConfig as parseRspackConfig } from './createBuilder.js';
5
+ export { refreshTsgoCheckerConfig } from './shared/tsgo.js';
5
6
  export { castArray, isHtmlDisabled, RUNTIME_CHUNK_NAME, RUNTIME_CHUNK_REGEX, SERVICE_WORKER_ENVIRONMENT_NAME, } from './shared/utils.js';
6
- export type { BuilderConfig, BundlerType, CacheGroup, MetaOptions, MultiStats, RspackConfig, Stats, ToolsDevServerConfig, } from './types.js';
7
+ export type { BuilderConfig, BuilderSvgOptions, BundlerType, CacheGroup, MetaOptions, MultiStats, RspackConfig, Stats, ToolsDevServerConfig, } from './types.js';
7
8
  export type { BuilderInstance, CreateBuilderOptions };
8
9
  export { createRspackBuilder as createBuilder };
@@ -8,7 +8,10 @@ import type { RsbuildPlugin } from '@rsbuild/core';
8
8
  * 4. Adding entry name virtual module for client-side entries
9
9
  * 5. Adding 'use server-entry' directive to route components
10
10
  */
11
- export declare function pluginRscConfig(): RsbuildPlugin;
11
+ export declare function pluginRscConfig(environments?: {
12
+ server?: string;
13
+ client?: string;
14
+ }, rscLayerMatchers?: RegExp[]): RsbuildPlugin;
12
15
  /**
13
16
  * Get RSC plugins based on configuration
14
17
  * @param enableRsc - Whether RSC is enabled
@@ -0,0 +1,32 @@
1
+ import type { PluginLessOptions } from '@rsbuild/plugin-less';
2
+ import type { PluginSassOptions } from '../sass/index.js';
3
+ import type { PluginSvgrOptions, SvgDefaultExport } from '@rsbuild/plugin-svgr';
4
+ import type { BuilderConfig } from '../types.js';
5
+ type BuilderToolsConfig = NonNullable<BuilderConfig['tools']>;
6
+ /** Reset the warn-once state. Only meant for unit tests. */
7
+ export declare const resetPluginOptionsWarnings: () => void;
8
+ /**
9
+ * `tools.less` accepts either the full options of `@rsbuild/plugin-less`
10
+ * or, for backward compatibility, the less-loader options directly
11
+ * (object, function or array form). The legacy form is wrapped into
12
+ * `lessLoaderOptions` so the generated bundler config stays unchanged.
13
+ */
14
+ export declare const normalizeLessOptions: (less: BuilderToolsConfig['less']) => PluginLessOptions;
15
+ /**
16
+ * Same as {@link normalizeLessOptions} for `tools.sass`.
17
+ */
18
+ export declare const normalizeSassOptions: (sass: BuilderToolsConfig['sass']) => PluginSassOptions;
19
+ /**
20
+ * Resolve the options passed to `@rsbuild/plugin-svgr`, or `false` when the
21
+ * plugin should not be registered.
22
+ *
23
+ * `tools.svgr` takes precedence over the deprecated `output.disableSvgr` and
24
+ * `output.svgDefaultExport`; the two legacy options keep working when
25
+ * `tools.svgr` is not set.
26
+ */
27
+ export declare const resolveSvgrOptions: ({ svgr, disableSvgr, svgDefaultExport, }: {
28
+ svgr: BuilderToolsConfig['svgr'];
29
+ disableSvgr?: boolean;
30
+ svgDefaultExport?: SvgDefaultExport;
31
+ }) => PluginSvgrOptions | false;
32
+ export {};
@@ -0,0 +1,25 @@
1
+ import type { PluginTypeCheckerOptions } from '@rsbuild/plugin-type-check';
2
+ type TsCheckerChain = NonNullable<PluginTypeCheckerOptions['tsCheckerOptions']>;
3
+ type TsCheckerFn = Extract<TsCheckerChain, (config: never) => unknown>;
4
+ export type TsCheckerOptions = Parameters<TsCheckerFn>[0];
5
+ /**
6
+ * Regenerate a checker config from the project config it `extends`.
7
+ *
8
+ * The generated file is written once, at builder configuration; everything it
9
+ * inherits through `extends` is read fresh by the compiler on every check, but
10
+ * the values it has to restate (`references`, the pinned `rootDir`, the
11
+ * `moduleResolution` override) would otherwise stay frozen for the life of a
12
+ * `modern dev` session. The checker calls this before each run so an edit to
13
+ * the project's tsconfig - adding, removing or retargeting a project reference -
14
+ * takes effect on the next compilation instead of the next restart.
15
+ *
16
+ * Returns the project config the checker config was derived from, so the caller
17
+ * can watch it; `undefined` when the file is not a generated checker config.
18
+ */
19
+ export declare const refreshTsgoCheckerConfig: (checkerConfigFile: string) => string | undefined;
20
+ /**
21
+ * Type checking uses the canonical stable TypeScript 7.0.2 package by default,
22
+ * supplied by the project or the builder's declared production dependency.
23
+ */
24
+ export declare const withTsgoDefaults: (userOptions: TsCheckerChain | undefined, rootPath: string) => TsCheckerChain;
25
+ export {};
@@ -1,16 +1,20 @@
1
- import type { AliasOption } from '@modern-js/utils';
1
+ import type { AliasOption } from '@modern-js/utils/alias';
2
2
  import type { ConfigChain, ConfigChainWithContext, DevConfig, DistPathConfig, EnvironmentConfig, HtmlConfig, OutputConfig, Polyfill, RsbuildConfig, RsbuildPluginAPI, RsbuildPlugins, RsbuildTarget, Rspack, SecurityConfig, ServerConfig, SourceConfig, ToolsConfig } from '@rsbuild/core';
3
3
  import type { PluginAssetsRetryOptions } from '@rsbuild/plugin-assets-retry';
4
4
  import type { PluginCheckSyntaxOptions } from '@rsbuild/plugin-check-syntax';
5
5
  import type { PluginCssMinimizerOptions } from './css-minimizer/index.js';
6
6
  import type { PluginLessOptions } from '@rsbuild/plugin-less';
7
- import type { PluginReactOptions } from '@rsbuild/plugin-react';
8
7
  import type { PluginRemOptions } from '@rsbuild/plugin-rem';
9
8
  import type { PluginSassOptions } from './sass/index.js';
10
9
  import type { PluginSourceBuildOptions } from '@rsbuild/plugin-source-build';
11
- type SvgDefaultExport = 'component' | 'url';
12
10
  import type { PluginTypeCheckerOptions } from '@rsbuild/plugin-type-check';
13
11
  import type { Options as AutoprefixerOptions } from 'autoprefixer';
12
+ /** Renderer-owned SVG compiler options, registered by the selected React owner. */
13
+ export interface BuilderSvgOptions {
14
+ }
15
+ type RegisteredSvgOptions = BuilderSvgOptions extends {
16
+ options: infer Options;
17
+ } ? Options : never;
14
18
  export type CacheGroup = Rspack.OptimizationSplitChunksCacheGroup;
15
19
  export type Stats = Omit<Rspack.Stats, '#private' | 'hash' | 'startTime' | 'endTime'>;
16
20
  export type RspackConfig = Rspack.Configuration;
@@ -105,13 +109,29 @@ export type BuilderExtraConfig = {
105
109
  */
106
110
  minifyCss?: PluginCssMinimizerOptions['pluginOptions'];
107
111
  /**
108
- * Modify the config of [less-loader](https://github.com/webpack-contrib/less-loader).
112
+ * Modify the options of [@rsbuild/plugin-less](https://rsbuild.rs/plugins/list/plugin-less),
113
+ * such as `lessLoaderOptions`, `include`, `exclude` and `parallel`.
114
+ *
115
+ * Passing the [less-loader](https://github.com/webpack-contrib/less-loader)
116
+ * options directly is still supported for backward compatibility, but is
117
+ * deprecated: move them under `lessLoaderOptions`.
109
118
  */
110
- less?: PluginLessOptions['lessLoaderOptions'];
119
+ less?: PluginLessOptions['lessLoaderOptions'] | PluginLessOptions;
111
120
  /**
112
- * Modify the config of [sass-loader](https://github.com/webpack-contrib/sass-loader).
121
+ * Modify the options of [@rsbuild/plugin-sass](https://rsbuild.rs/plugins/list/plugin-sass),
122
+ * such as `sassLoaderOptions`, `include`, `exclude` and `rewriteUrls`.
123
+ *
124
+ * Passing the [sass-loader](https://github.com/webpack-contrib/sass-loader)
125
+ * options directly is still supported for backward compatibility, but is
126
+ * deprecated: move them under `sassLoaderOptions`.
113
127
  */
114
- sass?: PluginSassOptions['sassLoaderOptions'];
128
+ sass?: PluginSassOptions['sassLoaderOptions'] | PluginSassOptions;
129
+ /**
130
+ * Modify the options of [@rsbuild/plugin-svgr](https://rsbuild.rs/plugins/list/plugin-svgr),
131
+ * such as `svgrOptions`, `parallel`, `exclude` and `query`.
132
+ * Set to `false` to disable SVGR; all `.svg` files are then treated as static assets.
133
+ */
134
+ svgr?: [RegisteredSvgOptions] extends [never] ? false : ConfigChain<RegisteredSvgOptions> | false;
115
135
  };
116
136
  dev?: {
117
137
  /** Set the page URL to open when the server starts. */
@@ -150,10 +170,13 @@ export type BuilderExtraConfig = {
150
170
  * The transform is enabled by default through Rsbuild's SWC integration.
151
171
  * Set this to `false` to disable it.
152
172
  *
173
+ * Only browser environments (`output.target: 'web'`) are compiled;
174
+ * `node` and `web-worker` (SSR, BFF) environments never are.
175
+ *
153
176
  * For React 17 or 18, install `react-compiler-runtime` and set the
154
177
  * matching target version, for example `{ target: '18' }`.
155
178
  */
156
- reactCompiler?: PluginReactOptions['reactCompiler'];
179
+ reactCompiler?: Rspack.SwcLoaderTransformConfig['reactCompiler'];
157
180
  };
158
181
  output?: {
159
182
  /**
@@ -186,10 +209,14 @@ export type BuilderExtraConfig = {
186
209
  disableTsChecker?: boolean;
187
210
  /**
188
211
  * Configure the default export type of SVG files.
212
+ * @deprecated Use `tools.svgr.svgrOptions.exportType` instead:
213
+ * `'component'` maps to `exportType: 'default'`, `'url'` maps to `exportType: 'named'`.
189
214
  */
190
- svgDefaultExport?: SvgDefaultExport;
215
+ svgDefaultExport?: 'component' | 'url';
191
216
  /**
192
217
  * Whether to transform SVGs into React components. If true, will treat all .svg files as assets.
218
+ * @deprecated Use `tools.svgr` instead: `output.disableSvgr: true` maps to `tools.svgr: false`;
219
+ * `false` is the default behavior and can simply be removed.
193
220
  */
194
221
  disableSvgr?: boolean;
195
222
  };