@rsbuild/core 0.0.19 → 0.0.21

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.
Files changed (51) hide show
  1. package/dist/cli/commands.js +2 -2
  2. package/dist/cli/config.js +19 -2
  3. package/dist/cli/index.d.ts +1 -5
  4. package/dist/cli/index.js +3 -21
  5. package/dist/cli/run.d.ts +7 -0
  6. package/dist/{server/constants.js → cli/run.js} +27 -27
  7. package/dist/plugins/asset.d.ts +1 -1
  8. package/dist/plugins/asset.js +19 -13
  9. package/dist/plugins/cache.js +8 -8
  10. package/dist/plugins/cleanOutput.js +3 -3
  11. package/dist/plugins/fileSize.js +24 -24
  12. package/dist/plugins/html.js +6 -24
  13. package/dist/plugins/index.d.ts +1 -1
  14. package/dist/plugins/index.js +1 -5
  15. package/dist/plugins/inlineChunk.js +2 -7
  16. package/dist/plugins/rem.js +2 -2
  17. package/dist/plugins/splitChunks.js +0 -5
  18. package/dist/plugins/startUrl.js +4 -2
  19. package/dist/rspack-provider/core/initHooks.d.ts +4 -3
  20. package/dist/rspack-provider/core/initPlugins.js +5 -1
  21. package/dist/rspack-provider/index.d.ts +1 -1
  22. package/dist/rspack-provider/plugins/rspack-profile.js +6 -6
  23. package/dist/rspack-provider/plugins/swc.js +1 -2
  24. package/dist/rspack-provider/provider.js +2 -2
  25. package/dist/rspack-provider/rspackLoader/css-modules-typescript-pre-loader/postcss-icss-extract-plugin.d.ts +1 -1
  26. package/dist/rspack-provider/rspackLoader/css-modules-typescript-pre-loader/postcss-icss-extract-plugin.js +4 -4
  27. package/dist/rspack-provider/shared/fs.js +2 -2
  28. package/dist/rspack-provider/shared/plugin.js +1 -4
  29. package/dist/rspack-provider/types/index.d.ts +0 -1
  30. package/dist/rspack-provider/types/index.js +0 -2
  31. package/dist/rspack-provider/types/plugin.d.ts +1 -4
  32. package/dist/server/dev-middleware/hmr-client/createSocketUrl.d.ts +1 -1
  33. package/dist/server/dev-middleware/hmr-client/createSocketUrl.js +1 -1
  34. package/dist/server/dev-middleware/hmr-client/index.js +2 -25
  35. package/dist/server/dev-middleware/index.d.ts +2 -2
  36. package/dist/server/dev-middleware/index.js +1 -1
  37. package/dist/server/dev-middleware/socketServer.d.ts +2 -2
  38. package/dist/server/dev-middleware/socketServer.js +1 -4
  39. package/dist/server/devServer.d.ts +1 -2
  40. package/dist/server/devServer.js +28 -14
  41. package/dist/server/middlewares.d.ts +7 -1
  42. package/dist/server/middlewares.js +70 -2
  43. package/dist/server/prodServer.d.ts +4 -2
  44. package/dist/server/prodServer.js +12 -2
  45. package/dist/server/restart.d.ts +11 -0
  46. package/dist/server/restart.js +64 -0
  47. package/package.json +3 -29
  48. package/types.d.ts +63 -23
  49. package/dist/rspack-provider/types/hooks.d.ts +0 -3
  50. package/dist/rspack-provider/types/hooks.js +0 -16
  51. package/dist/server/constants.d.ts +0 -6
@@ -35,18 +35,18 @@ module.exports = __toCommonJS(rspack_profile_exports);
35
35
  var import_path = __toESM(require("path"));
36
36
  var import_core = require("@rspack/core");
37
37
  var import_inspector = __toESM(require("inspector"));
38
- var import_fs_extra = require("@rsbuild/shared/fs-extra");
39
38
  var import_shared = require("@rsbuild/shared");
39
+ var import_shared2 = require("@rsbuild/shared");
40
40
  const stopProfiler = (output, profileSession) => {
41
41
  if (!profileSession) {
42
42
  return;
43
43
  }
44
44
  profileSession.post("Profiler.stop", (error, param) => {
45
45
  if (error) {
46
- import_shared.logger.error("Failed to generate JS CPU profile:", error);
46
+ import_shared2.logger.error("Failed to generate JS CPU profile:", error);
47
47
  return;
48
48
  }
49
- import_fs_extra.fs.writeFileSync(output, JSON.stringify(param.profile));
49
+ import_shared.fse.writeFileSync(output, JSON.stringify(param.profile));
50
50
  });
51
51
  };
52
52
  const pluginRspackProfile = () => ({
@@ -70,7 +70,7 @@ const pluginRspackProfile = () => ({
70
70
  const cpuProfilePath = import_path.default.join(profileDir, "jscpuprofile.json");
71
71
  const loggingFilePath = import_path.default.join(profileDir, "logging.json");
72
72
  const onStart = () => {
73
- import_fs_extra.fs.ensureDirSync(profileDir);
73
+ import_shared.fse.ensureDirSync(profileDir);
74
74
  if (enableProfileTrace) {
75
75
  (0, import_core.experimental_registerGlobalTrace)("trace", "chrome", traceFilePath);
76
76
  }
@@ -90,13 +90,13 @@ const pluginRspackProfile = () => ({
90
90
  logging: "verbose",
91
91
  loggingTrace: true
92
92
  });
93
- import_fs_extra.fs.writeFileSync(loggingFilePath, JSON.stringify(logging));
93
+ import_shared.fse.writeFileSync(loggingFilePath, JSON.stringify(logging));
94
94
  }
95
95
  });
96
96
  api.onExit(() => {
97
97
  enableProfileTrace && (0, import_core.experimental_cleanupGlobalTrace)();
98
98
  stopProfiler(cpuProfilePath, profileSession);
99
- import_shared.logger.info(`Saved Rspack profile file to ${profileDir}`);
99
+ import_shared2.logger.info(`Saved Rspack profile file to ${profileDir}`);
100
100
  });
101
101
  }
102
102
  });
@@ -33,7 +33,6 @@ __export(swc_exports, {
33
33
  });
34
34
  module.exports = __toCommonJS(swc_exports);
35
35
  var import_shared = require("@rsbuild/shared");
36
- var import_lodash = require("lodash");
37
36
  var path = __toESM(require("path"));
38
37
  const builtinSwcLoaderName = "builtin:swc-loader";
39
38
  async function getDefaultSwcConfig(config, rootPath, target) {
@@ -99,7 +98,7 @@ const pluginSwc = () => ({
99
98
  rule.use(CHAIN_ID.USE.SWC).loader(builtinSwcLoaderName).options(swcConfig);
100
99
  chain.module.rule(CHAIN_ID.RULE.JS_DATA_URI).mimetype({
101
100
  or: ["text/javascript", "application/javascript"]
102
- }).use(CHAIN_ID.USE.SWC).loader(builtinSwcLoaderName).options((0, import_lodash.cloneDeep)(swcConfig));
101
+ }).use(CHAIN_ID.USE.SWC).loader(builtinSwcLoaderName).options((0, import_shared.cloneDeep)(swcConfig));
103
102
  }
104
103
  );
105
104
  api.modifyRspackConfig(async (config) => {
@@ -80,8 +80,8 @@ function rspackProvider({
80
80
  options
81
81
  );
82
82
  },
83
- async preview() {
84
- return (0, import_server.startProdServer)(context, context.config);
83
+ async preview(options) {
84
+ return (0, import_server.startProdServer)(context, context.config, options);
85
85
  },
86
86
  async build(options) {
87
87
  const { build: buildImpl, rspackBuild } = await Promise.resolve().then(() => __toESM(require("./core/build")));
@@ -1,4 +1,4 @@
1
- import type { CssModuleLocalsConvention } from '@rsbuild/shared';
1
+ import { type CssModuleLocalsConvention } from '@rsbuild/shared';
2
2
  import type { AcceptedPlugin as PostCSSPlugin } from 'postcss';
3
3
  export type PostcssParsePluginOptions = {
4
4
  exportLocalsConvention: CssModuleLocalsConvention;
@@ -22,16 +22,16 @@ __export(postcss_icss_extract_plugin_exports, {
22
22
  });
23
23
  module.exports = __toCommonJS(postcss_icss_extract_plugin_exports);
24
24
  var import_icss_utils = require("@rsbuild/shared/icss-utils");
25
- var import_lodash = require("lodash");
25
+ var import_shared = require("@rsbuild/shared");
26
26
  const dashesCamelCase = (str) => str.replace(/-+(\w)/g, (_match, firstLetter) => firstLetter.toUpperCase());
27
27
  const getExportLocalsConvention = (name, exportLocalsConventionType) => {
28
28
  switch (exportLocalsConventionType) {
29
29
  case "camelCase": {
30
- const camelName = (0, import_lodash.camelCase)(name);
31
- return camelName === name ? [name] : [name, (0, import_lodash.camelCase)(name)];
30
+ const camelName = (0, import_shared.camelCase)(name);
31
+ return camelName === name ? [name] : [name, (0, import_shared.camelCase)(name)];
32
32
  }
33
33
  case "camelCaseOnly": {
34
- return [(0, import_lodash.camelCase)(name)];
34
+ return [(0, import_shared.camelCase)(name)];
35
35
  }
36
36
  case "dashes": {
37
37
  const dashesCamelName = dashesCamelCase(name);
@@ -23,10 +23,10 @@ __export(fs_exports, {
23
23
  module.exports = __toCommonJS(fs_exports);
24
24
  var import_path = require("path");
25
25
  var import_shared = require("@rsbuild/shared");
26
- var import_fs_extra = require("@rsbuild/shared/fs-extra");
26
+ var import_shared2 = require("@rsbuild/shared");
27
27
  const getCompiledPath = (packageName) => {
28
28
  const providerCompilerPath = (0, import_path.join)(__dirname, "../../compiled", packageName);
29
- if (import_fs_extra.fs.existsSync(providerCompilerPath)) {
29
+ if (import_shared2.fse.existsSync(providerCompilerPath)) {
30
30
  return providerCompilerPath;
31
31
  } else {
32
32
  return (0, import_shared.getSharedPkgCompiledPath)(packageName);
@@ -44,10 +44,7 @@ const applyDefaultPlugins = (plugins) => (0, import_shared.awaitableGetter)([
44
44
  plugins.fileSize(),
45
45
  // cleanOutput plugin should before the html plugin
46
46
  plugins.cleanOutput(),
47
- plugins.font(),
48
- plugins.image(),
49
- plugins.media(),
50
- plugins.svg(),
47
+ plugins.asset(),
51
48
  plugins.html(),
52
49
  plugins.wasm(),
53
50
  plugins.moment(),
@@ -1,4 +1,3 @@
1
- export * from './hooks';
2
1
  export * from './plugin';
3
2
  export * from './context';
4
3
  export type { RsbuildConfig, NormalizedConfig, DevConfig, HtmlConfig, ToolsConfig, SourceConfig, OutputConfig, SecurityConfig, PerformanceConfig, NormalizedDevConfig, NormalizedHtmlConfig, NormalizedToolsConfig, NormalizedSourceConfig, NormalizedOutputConfig, NormalizedSecurityConfig, NormalizedPerformanceConfig } from '@rsbuild/shared';
@@ -15,12 +15,10 @@ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "defau
15
15
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
16
16
  var types_exports = {};
17
17
  module.exports = __toCommonJS(types_exports);
18
- __reExport(types_exports, require("./hooks"), module.exports);
19
18
  __reExport(types_exports, require("./plugin"), module.exports);
20
19
  __reExport(types_exports, require("./context"), module.exports);
21
20
  // Annotate the CommonJS export names for ESM import in node:
22
21
  0 && (module.exports = {
23
- ...require("./hooks"),
24
22
  ...require("./plugin"),
25
23
  ...require("./context")
26
24
  });
@@ -1,7 +1,4 @@
1
1
  import type { RsbuildConfig, NormalizedConfig, DefaultRsbuildPluginAPI, RsbuildPlugin as BaseRsbuildPlugin } from '@rsbuild/shared';
2
- import type { ModifyRspackConfigFn } from './hooks';
3
2
  import type { RspackConfig, RspackCompiler, RspackMultiCompiler } from '@rsbuild/shared';
4
- export interface RsbuildPluginAPI extends DefaultRsbuildPluginAPI<RsbuildConfig, NormalizedConfig, RspackConfig, RspackCompiler | RspackMultiCompiler> {
5
- modifyRspackConfig: (fn: ModifyRspackConfigFn) => void;
6
- }
3
+ export interface RsbuildPluginAPI extends DefaultRsbuildPluginAPI<RsbuildConfig, NormalizedConfig, RspackConfig, RspackCompiler | RspackMultiCompiler> {}
7
4
  export type RsbuildPlugin = BaseRsbuildPlugin<RsbuildPluginAPI>;
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * hmr socket connect path
3
3
  */
4
- export declare const HMR_SOCK_PATH = "/webpack-hmr";
4
+ export declare const HMR_SOCK_PATH = "/rsbuild-hmr";
5
5
  export declare function createSocketUrl(resourceQuery: string): string;
6
6
  export declare function formatURL({
7
7
  port,
@@ -23,7 +23,7 @@ __export(createSocketUrl_exports, {
23
23
  formatURL: () => formatURL
24
24
  });
25
25
  module.exports = __toCommonJS(createSocketUrl_exports);
26
- const HMR_SOCK_PATH = "/webpack-hmr";
26
+ const HMR_SOCK_PATH = "/rsbuild-hmr";
27
27
  function createSocketUrl(resourceQuery) {
28
28
  const searchParams = resourceQuery.substr(1).split("&");
29
29
  const options = {};
@@ -1,27 +1,4 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __copyProps = (to, from, except, desc) => {
9
- if (from && typeof from === "object" || typeof from === "function") {
10
- for (let key of __getOwnPropNames(from))
11
- if (!__hasOwnProp.call(to, key) && key !== except)
12
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
- }
14
- return to;
15
- };
16
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
- // If the importer is in node compatibility mode or this is not an ESM
18
- // file that has been converted to a CommonJS file using a Babel-
19
- // compatible transform (i.e. "__esModule" has not been set), then set
20
- // "default" to the CommonJS "module.exports" for node compatibility.
21
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
- mod
23
- ));
24
- var import_strip_ansi = __toESM(require("strip-ansi"));
25
2
  var import_format_stats = require("@rsbuild/shared/format-stats");
26
3
  var import_createSocketUrl = require("./createSocketUrl");
27
4
  const hadRuntimeError = false;
@@ -74,7 +51,7 @@ function handleWarnings(warnings) {
74
51
  );
75
52
  break;
76
53
  }
77
- console.warn((0, import_strip_ansi.default)(formatted.warnings[i]));
54
+ console.warn(formatted.warnings[i]);
78
55
  }
79
56
  }
80
57
  }
@@ -93,7 +70,7 @@ function handleErrors(errors) {
93
70
  });
94
71
  if (typeof console !== "undefined" && typeof console.error === "function") {
95
72
  for (const error of formatted.errors) {
96
- console.error((0, import_strip_ansi.default)(error));
73
+ console.error(error);
97
74
  }
98
75
  }
99
76
  }
@@ -2,9 +2,9 @@
2
2
  /// <reference types="node" />
3
3
  import { Server } from 'http';
4
4
  import { EventEmitter } from 'events';
5
- import type { DevServerOptions, DevMiddlewareAPI, DevMiddleware as CustomDevMiddleware } from '@rsbuild/shared';
5
+ import type { DevConfig, DevMiddlewareAPI, DevMiddleware as CustomDevMiddleware } from '@rsbuild/shared';
6
6
  type Options = {
7
- dev: DevServerOptions;
7
+ dev: DevConfig;
8
8
  devMiddleware?: CustomDevMiddleware;
9
9
  };
10
10
  export default class DevMiddleware extends EventEmitter {
@@ -76,7 +76,7 @@ class DevMiddleware extends import_events.EventEmitter {
76
76
  this.emit("change", stats);
77
77
  }
78
78
  };
79
- const enableHMR = this.devOptions.hot || this.devOptions.liveReload;
79
+ const enableHMR = this.devOptions.hmr;
80
80
  const middleware = devMiddleware({
81
81
  headers: devOptions.headers,
82
82
  stats: false,
@@ -1,7 +1,7 @@
1
1
  /// <reference types="node" />
2
2
  import { Server } from 'http';
3
3
  import ws from 'ws';
4
- import { Stats, DevServerOptions } from '@rsbuild/shared';
4
+ import { Stats, DevConfig } from '@rsbuild/shared';
5
5
  export default class SocketServer {
6
6
  private wsServer;
7
7
  private readonly sockets;
@@ -9,7 +9,7 @@ export default class SocketServer {
9
9
  private app?;
10
10
  private stats?;
11
11
  private timer;
12
- constructor(options: DevServerOptions);
12
+ constructor(options: DevConfig);
13
13
  prepare(app: Server): void;
14
14
  updateStats(stats: Stats): void;
15
15
  sockWrite(type: string, data?: Record<string, any> | string | boolean): void;
@@ -112,12 +112,9 @@ class SocketServer {
112
112
  this.sockets.splice(idx, 1);
113
113
  }
114
114
  });
115
- if (this.options.hot || this.options.hot === "only") {
115
+ if (this.options.hmr) {
116
116
  this.singleWrite(connection, "hot");
117
117
  }
118
- if (this.options.liveReload) {
119
- this.singleWrite(connection, "liveReload");
120
- }
121
118
  if (this.stats) {
122
119
  this.sendStats(true);
123
120
  }
@@ -10,9 +10,9 @@ export declare class RsbuildDevServer {
10
10
  private readonly devMiddleware;
11
11
  private pwd;
12
12
  private app;
13
+ private output;
13
14
  middlewares: connect.Server;
14
15
  constructor(options: RsbuildDevServerOptions);
15
- private getDevOptions;
16
16
  private applySetupMiddlewares;
17
17
  onInit(app: Server): Promise<void>;
18
18
  private applyDefaultMiddlewares;
@@ -27,7 +27,6 @@ export declare function startDevServer<Options extends {
27
27
  compiler,
28
28
  printURLs,
29
29
  strictPort,
30
- serverOptions,
31
30
  logger: customLogger,
32
31
  getPortSilently
33
32
  }?: StartDevServerOptions & {
@@ -36,27 +36,23 @@ var import_http = require("http");
36
36
  var import_https = require("https");
37
37
  var import_url = __toESM(require("url"));
38
38
  var import_shared = require("@rsbuild/shared");
39
- var import_constants = require("./constants");
40
39
  var import_dev_middleware = __toESM(require("./dev-middleware"));
41
- var import_deepmerge = require("@rsbuild/shared/deepmerge");
42
40
  var import_connect = __toESM(require("connect"));
43
41
  var import_proxy = require("./proxy");
44
42
  var import_middlewares = require("./middlewares");
43
+ var import_path = require("path");
44
+ var import_restart = require("./restart");
45
45
  class RsbuildDevServer {
46
46
  constructor(options) {
47
47
  this.middlewares = (0, import_connect.default)();
48
48
  this.pwd = options.pwd;
49
- this.dev = this.getDevOptions(options);
49
+ this.dev = options.dev;
50
+ this.output = options.output;
50
51
  this.devMiddleware = new import_dev_middleware.default({
51
52
  dev: this.dev,
52
53
  devMiddleware: options.devMiddleware
53
54
  });
54
55
  }
55
- getDevOptions(options) {
56
- const devOptions = typeof options.dev === "boolean" ? {} : options.dev;
57
- const defaultOptions = (0, import_constants.getDefaultDevOptions)();
58
- return (0, import_deepmerge.deepmerge)(defaultOptions, devOptions);
59
- }
60
56
  applySetupMiddlewares() {
61
57
  const setupMiddlewares = this.dev.setupMiddlewares || [];
62
58
  const serverOptions = {
@@ -117,6 +113,13 @@ class RsbuildDevServer {
117
113
  }
118
114
  devMiddleware.init(app);
119
115
  devMiddleware.middleware && this.middlewares.use(devMiddleware.middleware);
116
+ this.middlewares.use(
117
+ (0, import_middlewares.getHtmlFallbackMiddleware)({
118
+ distPath: (0, import_path.join)(this.pwd, this.output.distPath),
119
+ assetPrefix: this.output.assetPrefix,
120
+ callback: devMiddleware.middleware
121
+ })
122
+ );
120
123
  if (dev.historyApiFallback) {
121
124
  const { default: connectHistoryApiFallback } = await Promise.resolve().then(() => __toESM(require("connect-history-api-fallback")));
122
125
  const historyApiFallbackMiddleware = connectHistoryApiFallback(
@@ -127,6 +130,7 @@ class RsbuildDevServer {
127
130
  devMiddleware.middleware && this.middlewares.use(devMiddleware.middleware);
128
131
  }
129
132
  this.middlewares.use(import_middlewares.faviconFallbackMiddleware);
133
+ this.middlewares.use(import_middlewares.notFoundMiddleware);
130
134
  }
131
135
  async createHTTPServer() {
132
136
  const { dev } = this;
@@ -158,11 +162,10 @@ async function startDevServer(options, startDevCompile, {
158
162
  compiler,
159
163
  printURLs = true,
160
164
  strictPort = false,
161
- serverOptions = {},
162
165
  logger: customLogger,
163
166
  getPortSilently
164
167
  } = {}) {
165
- var _a;
168
+ var _a, _b, _c, _d, _e;
166
169
  if (!process.env.NODE_ENV) {
167
170
  process.env.NODE_ENV = "development";
168
171
  }
@@ -170,7 +173,6 @@ async function startDevServer(options, startDevCompile, {
170
173
  const logger = customLogger != null ? customLogger : import_shared.logger;
171
174
  const { devServerConfig, port, host, https } = await (0, import_shared.getDevOptions)({
172
175
  rsbuildConfig,
173
- serverOptions,
174
176
  strictPort,
175
177
  getPortSilently
176
178
  });
@@ -182,6 +184,10 @@ async function startDevServer(options, startDevCompile, {
182
184
  };
183
185
  const protocol = https ? "https" : "http";
184
186
  let urls = (0, import_shared.getAddressUrls)(protocol, port, (_a = rsbuildConfig.dev) == null ? void 0 : _a.host);
187
+ const routes = (0, import_shared.formatRoutes)(
188
+ options.context.entry,
189
+ (_c = (_b = rsbuildConfig.output) == null ? void 0 : _b.distPath) == null ? void 0 : _c.html
190
+ );
185
191
  if (printURLs) {
186
192
  if ((0, import_shared.isFunction)(printURLs)) {
187
193
  urls = printURLs(urls);
@@ -189,14 +195,18 @@ async function startDevServer(options, startDevCompile, {
189
195
  throw new Error("Please return an array in the `printURLs` function.");
190
196
  }
191
197
  }
192
- (0, import_shared.printServerURLs)(urls, logger);
198
+ (0, import_shared.printServerURLs)(urls, routes, logger);
193
199
  }
194
200
  (0, import_shared.debug)("create dev server");
195
201
  const devMiddleware = await startDevCompile(options, compiler);
196
202
  const server = new RsbuildDevServer({
197
203
  pwd: options.context.rootPath,
198
204
  devMiddleware,
199
- dev: devServerConfig
205
+ dev: devServerConfig,
206
+ output: {
207
+ distPath: ((_e = (_d = rsbuildConfig.output) == null ? void 0 : _d.distPath) == null ? void 0 : _e.root) || import_shared.ROOT_DIST_DIR,
208
+ assetPrefix: typeof devServerConfig.assetPrefix === "string" && !(0, import_shared.isURL)(devServerConfig.assetPrefix) ? devServerConfig.assetPrefix : ""
209
+ }
200
210
  });
201
211
  (0, import_shared.debug)("create dev server done");
202
212
  await options.context.hooks.onBeforeStartDevServerHook.call();
@@ -214,7 +224,11 @@ async function startDevServer(options, startDevCompile, {
214
224
  throw err;
215
225
  }
216
226
  (0, import_shared.debug)("listen dev server done");
217
- await options.context.hooks.onAfterStartDevServerHook.call({ port });
227
+ await options.context.hooks.onAfterStartDevServerHook.call({
228
+ port,
229
+ routes
230
+ });
231
+ (0, import_restart.registerCleaner)(() => server.close());
218
232
  resolve({
219
233
  port,
220
234
  urls: urls.map((item) => item.url),
@@ -1,2 +1,8 @@
1
1
  import { RequestHandler as Middleware } from '@rsbuild/shared';
2
- export declare const faviconFallbackMiddleware: Middleware;
2
+ export declare const faviconFallbackMiddleware: Middleware;
3
+ export declare const notFoundMiddleware: Middleware;
4
+ export declare const getHtmlFallbackMiddleware: (params: {
5
+ distPath: string;
6
+ assetPrefix: string;
7
+ callback?: Middleware;
8
+ }) => Middleware;
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,12 +17,25 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
  var middlewares_exports = {};
20
30
  __export(middlewares_exports, {
21
- faviconFallbackMiddleware: () => faviconFallbackMiddleware
31
+ faviconFallbackMiddleware: () => faviconFallbackMiddleware,
32
+ getHtmlFallbackMiddleware: () => getHtmlFallbackMiddleware,
33
+ notFoundMiddleware: () => notFoundMiddleware
22
34
  });
23
35
  module.exports = __toCommonJS(middlewares_exports);
36
+ var import_shared = require("@rsbuild/shared");
37
+ var import_path = __toESM(require("path"));
38
+ var import_fs = __toESM(require("fs"));
24
39
  const faviconFallbackMiddleware = (req, res, next) => {
25
40
  if (req.url === "/favicon.ico") {
26
41
  res.statusCode = 204;
@@ -29,7 +44,60 @@ const faviconFallbackMiddleware = (req, res, next) => {
29
44
  next();
30
45
  }
31
46
  };
47
+ const notFoundMiddleware = (_req, res, _next) => {
48
+ res.statusCode = 404;
49
+ res.end();
50
+ };
51
+ const getHtmlFallbackMiddleware = ({ assetPrefix, distPath, callback }) => {
52
+ return (req, res, next) => {
53
+ if (
54
+ // Only accept GET or HEAD
55
+ req.method !== "GET" && req.method !== "HEAD" || // Require Accept header
56
+ !req.headers || typeof req.headers.accept !== "string" || // Ignore JSON requests
57
+ req.headers.accept.includes("application/json") || // Require Accept: text/html or */*
58
+ !(req.headers.accept.includes("text/html") || req.headers.accept.includes("*/*")) || !req.url
59
+ ) {
60
+ return next();
61
+ }
62
+ const { url } = req;
63
+ const pathname = decodeURIComponent(url);
64
+ let outputFileSystem = import_fs.default;
65
+ if (res.locals.webpack) {
66
+ const { devMiddleware } = res.locals.webpack;
67
+ outputFileSystem = devMiddleware.outputFileSystem;
68
+ }
69
+ const tryRewrite = (filePath, newUrl) => {
70
+ var _a;
71
+ if (outputFileSystem.existsSync(filePath) && callback) {
72
+ newUrl = (0, import_shared.urlJoin)(assetPrefix, newUrl);
73
+ (_a = import_shared.debug) == null ? void 0 : _a(`Rewriting ${req.method} ${req.url} to ${newUrl}`);
74
+ req.url = newUrl;
75
+ return callback(req, res, (...args) => {
76
+ req.url = url;
77
+ next(...args);
78
+ });
79
+ }
80
+ };
81
+ if (pathname.endsWith("/")) {
82
+ const newUrl = url + "index.html";
83
+ const filePath = import_path.default.join(distPath, pathname, "index.html");
84
+ tryRewrite(filePath, newUrl);
85
+ } else if (
86
+ // '/main' => '/main.html'
87
+ !pathname.endsWith(".html")
88
+ ) {
89
+ const newUrl = url + ".html";
90
+ const filePath = import_path.default.join(distPath, pathname + ".html");
91
+ tryRewrite(filePath, newUrl);
92
+ } else {
93
+ tryRewrite(import_path.default.join(distPath, pathname), url);
94
+ }
95
+ next();
96
+ };
97
+ };
32
98
  // Annotate the CommonJS export names for ESM import in node:
33
99
  0 && (module.exports = {
34
- faviconFallbackMiddleware
100
+ faviconFallbackMiddleware,
101
+ getHtmlFallbackMiddleware,
102
+ notFoundMiddleware
35
103
  });
@@ -3,7 +3,7 @@
3
3
  import type { ListenOptions } from 'net';
4
4
  import { Server } from 'http';
5
5
  import connect from 'connect';
6
- import { Context, RsbuildConfig, StartServerResult } from '@rsbuild/shared';
6
+ import { Context, RsbuildConfig, StartServerResult, PreviewServerOptions } from '@rsbuild/shared';
7
7
  type RsbuildProdServerOptions = {
8
8
  pwd: string;
9
9
  output: {
@@ -23,5 +23,7 @@ export declare class RsbuildProdServer {
23
23
  listen(options?: number | ListenOptions | undefined, listener?: () => void): void;
24
24
  close(): void;
25
25
  }
26
- export declare function startProdServer(context: Context, rsbuildConfig: RsbuildConfig): Promise<StartServerResult>;
26
+ export declare function startProdServer(context: Context, rsbuildConfig: RsbuildConfig, {
27
+ printURLs
28
+ }?: PreviewServerOptions): Promise<StartServerResult>;
27
29
  export {};
@@ -92,7 +92,7 @@ class RsbuildProdServer {
92
92
  this.app.close();
93
93
  }
94
94
  }
95
- async function startProdServer(context, rsbuildConfig) {
95
+ async function startProdServer(context, rsbuildConfig, { printURLs = true } = {}) {
96
96
  var _a, _b, _c, _d;
97
97
  if (!process.env.NODE_ENV) {
98
98
  process.env.NODE_ENV = "production";
@@ -114,8 +114,18 @@ async function startProdServer(context, rsbuildConfig) {
114
114
  port
115
115
  },
116
116
  () => {
117
+ var _a2, _b2;
117
118
  const urls = (0, import_shared.getAddressUrls)("http", port);
118
- (0, import_shared.printServerURLs)(urls);
119
+ if (printURLs) {
120
+ const routes = (0, import_shared.formatRoutes)(
121
+ context.entry,
122
+ (_b2 = (_a2 = rsbuildConfig.output) == null ? void 0 : _a2.distPath) == null ? void 0 : _b2.html
123
+ );
124
+ (0, import_shared.printServerURLs)(
125
+ (0, import_shared.isFunction)(printURLs) ? printURLs(urls) : urls,
126
+ routes
127
+ );
128
+ }
119
129
  resolve({
120
130
  port,
121
131
  urls: urls.map((item) => item.url),
@@ -0,0 +1,11 @@
1
+ type Cleaner = () => Promise<unknown> | unknown;
2
+ /**
3
+ * Add a cleaner to handle side effects
4
+ */
5
+ export declare const registerCleaner: (cleaner: Cleaner) => void;
6
+ export declare const restartDevServer: ({
7
+ filePath
8
+ }: {
9
+ filePath: string;
10
+ }) => Promise<void>;
11
+ export {};
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var restart_exports = {};
30
+ __export(restart_exports, {
31
+ registerCleaner: () => registerCleaner,
32
+ restartDevServer: () => restartDevServer
33
+ });
34
+ module.exports = __toCommonJS(restart_exports);
35
+ var import_path = __toESM(require("path"));
36
+ var import_shared = require("@rsbuild/shared");
37
+ var import_run = require("../cli/run");
38
+ const cleaners = [];
39
+ const registerCleaner = (cleaner) => {
40
+ cleaners.push(cleaner);
41
+ };
42
+ const clearConsole = () => {
43
+ if (process.stdout.isTTY && !process.env.DEBUG) {
44
+ process.stdout.write("\x1B[H\x1B[2J");
45
+ }
46
+ };
47
+ const restartDevServer = async ({ filePath }) => {
48
+ clearConsole();
49
+ const filename = import_path.default.basename(filePath);
50
+ import_shared.logger.info(`Restart because ${import_shared.color.yellow(filename)} is changed.
51
+ `);
52
+ for (const cleaner of cleaners) {
53
+ await cleaner();
54
+ }
55
+ const rsbuild = await (0, import_run.runCli)({
56
+ isRestart: true
57
+ });
58
+ await rsbuild.startDevServer();
59
+ };
60
+ // Annotate the CommonJS export names for ESM import in node:
61
+ 0 && (module.exports = {
62
+ registerCleaner,
63
+ restartDevServer
64
+ });