@rsbuild/core 0.0.17 → 0.0.18

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 (38) hide show
  1. package/dist/cli/commands.d.ts +3 -0
  2. package/dist/cli/commands.js +4 -2
  3. package/dist/cli/config.d.ts +4 -0
  4. package/dist/cli/index.js +2 -1
  5. package/dist/plugins/define.js +8 -18
  6. package/dist/plugins/index.js +0 -1
  7. package/dist/plugins/nodeAddons.js +10 -17
  8. package/dist/plugins/startUrl.js +11 -15
  9. package/dist/rspack-provider/core/createCompiler.js +7 -5
  10. package/dist/rspack-provider/core/devMiddleware.d.ts +2 -4
  11. package/dist/rspack-provider/core/startDevServer.d.ts +1 -2
  12. package/dist/rspack-provider/core/startDevServer.js +6 -31
  13. package/dist/rspack-provider/plugins/progress.js +5 -1
  14. package/dist/rspack-provider/plugins/swc.js +2 -3
  15. package/dist/rspack-provider/provider.js +5 -3
  16. package/dist/rspack-provider/shared/plugin.js +0 -1
  17. package/dist/server/constants.d.ts +6 -0
  18. package/dist/server/constants.js +49 -0
  19. package/dist/server/dev-middleware/hmr-client/createSocketUrl.d.ts +16 -0
  20. package/dist/server/dev-middleware/hmr-client/createSocketUrl.js +68 -0
  21. package/dist/server/dev-middleware/hmr-client/index.d.ts +1 -0
  22. package/dist/server/dev-middleware/hmr-client/index.js +164 -0
  23. package/dist/server/dev-middleware/index.d.ts +22 -0
  24. package/dist/server/dev-middleware/index.js +90 -0
  25. package/dist/server/dev-middleware/socketServer.d.ts +22 -0
  26. package/dist/server/dev-middleware/socketServer.js +167 -0
  27. package/dist/server/devServer.d.ts +23 -0
  28. package/dist/server/devServer.js +172 -0
  29. package/dist/server/https.d.ts +6 -0
  30. package/dist/server/https.js +50 -0
  31. package/dist/server/index.d.ts +2 -0
  32. package/dist/server/index.js +31 -0
  33. package/dist/server/prodServer.d.ts +26 -0
  34. package/dist/server/prodServer.js +133 -0
  35. package/package.json +31 -5
  36. package/types.d.ts +130 -0
  37. package/dist/plugins/assetsRetry.d.ts +0 -2
  38. package/dist/plugins/assetsRetry.js +0 -66
@@ -0,0 +1,164 @@
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
+ var import_format_stats = require("@rsbuild/shared/format-stats");
26
+ var import_createSocketUrl = require("./createSocketUrl");
27
+ const hadRuntimeError = false;
28
+ const socketUrl = (0, import_createSocketUrl.createSocketUrl)(__resourceQuery);
29
+ const connection = new WebSocket(socketUrl);
30
+ connection.onopen = function() {
31
+ if (typeof console !== "undefined" && typeof console.info === "function") {
32
+ console.info("[HMR] connected.");
33
+ }
34
+ };
35
+ connection.onclose = function() {
36
+ if (typeof console !== "undefined" && typeof console.info === "function") {
37
+ console.info("[HMR] disconnected. Refresh the page if necessary.");
38
+ }
39
+ };
40
+ let isFirstCompilation = true;
41
+ let mostRecentCompilationHash = null;
42
+ let hasCompileErrors = false;
43
+ function clearOutdatedErrors() {
44
+ if (typeof console !== "undefined" && typeof console.clear === "function") {
45
+ if (hasCompileErrors) {
46
+ console.clear();
47
+ }
48
+ }
49
+ }
50
+ function handleSuccess() {
51
+ clearOutdatedErrors();
52
+ const isHotUpdate = !isFirstCompilation;
53
+ isFirstCompilation = false;
54
+ hasCompileErrors = false;
55
+ if (isHotUpdate) {
56
+ tryApplyUpdates();
57
+ }
58
+ }
59
+ function handleWarnings(warnings) {
60
+ clearOutdatedErrors();
61
+ const isHotUpdate = !isFirstCompilation;
62
+ isFirstCompilation = false;
63
+ hasCompileErrors = false;
64
+ function printWarnings() {
65
+ const formatted = (0, import_format_stats.formatStatsMessages)({
66
+ warnings,
67
+ errors: []
68
+ });
69
+ if (typeof console !== "undefined" && typeof console.warn === "function") {
70
+ for (let i = 0; i < formatted.warnings.length; i++) {
71
+ if (i === 5) {
72
+ console.warn(
73
+ "There were more warnings in other files.\nYou can find a complete log in the terminal."
74
+ );
75
+ break;
76
+ }
77
+ console.warn((0, import_strip_ansi.default)(formatted.warnings[i]));
78
+ }
79
+ }
80
+ }
81
+ printWarnings();
82
+ if (isHotUpdate) {
83
+ tryApplyUpdates();
84
+ }
85
+ }
86
+ function handleErrors(errors) {
87
+ clearOutdatedErrors();
88
+ isFirstCompilation = false;
89
+ hasCompileErrors = true;
90
+ const formatted = (0, import_format_stats.formatStatsMessages)({
91
+ errors,
92
+ warnings: []
93
+ });
94
+ if (typeof console !== "undefined" && typeof console.error === "function") {
95
+ for (const error of formatted.errors) {
96
+ console.error((0, import_strip_ansi.default)(error));
97
+ }
98
+ }
99
+ }
100
+ function handleAvailableHash(hash) {
101
+ mostRecentCompilationHash = hash;
102
+ }
103
+ connection.onmessage = function(e) {
104
+ const message = JSON.parse(e.data);
105
+ switch (message.type) {
106
+ case "hash":
107
+ handleAvailableHash(message.data);
108
+ break;
109
+ case "still-ok":
110
+ case "ok":
111
+ handleSuccess();
112
+ break;
113
+ case "content-changed":
114
+ window.location.reload();
115
+ break;
116
+ case "warnings":
117
+ handleWarnings(message.data);
118
+ break;
119
+ case "errors":
120
+ handleErrors(message.data);
121
+ break;
122
+ default:
123
+ }
124
+ };
125
+ function isUpdateAvailable() {
126
+ return mostRecentCompilationHash !== __webpack_hash__;
127
+ }
128
+ function canApplyUpdates() {
129
+ return module.hot.status() === "idle";
130
+ }
131
+ function tryApplyUpdates() {
132
+ if (!module.hot) {
133
+ window.location.reload();
134
+ return;
135
+ }
136
+ if (!isUpdateAvailable() || !canApplyUpdates()) {
137
+ return;
138
+ }
139
+ function handleApplyUpdates(err, updatedModules) {
140
+ const wantsForcedReload = err || !updatedModules || hadRuntimeError;
141
+ if (wantsForcedReload) {
142
+ window.location.reload();
143
+ return;
144
+ }
145
+ if (isUpdateAvailable()) {
146
+ tryApplyUpdates();
147
+ }
148
+ }
149
+ const result = module.hot.check(
150
+ /* autoApply */
151
+ true,
152
+ handleApplyUpdates
153
+ );
154
+ if (result == null ? void 0 : result.then) {
155
+ result.then(
156
+ (updatedModules) => {
157
+ handleApplyUpdates(null, updatedModules);
158
+ },
159
+ (err) => {
160
+ handleApplyUpdates(err, null);
161
+ }
162
+ );
163
+ }
164
+ }
@@ -0,0 +1,22 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ import { Server } from 'http';
4
+ import { EventEmitter } from 'events';
5
+ import type { DevServerOptions, DevMiddlewareAPI, DevMiddleware as CustomDevMiddleware } from '@rsbuild/shared';
6
+ type Options = {
7
+ dev: DevServerOptions;
8
+ devMiddleware?: CustomDevMiddleware;
9
+ };
10
+ export default class DevMiddleware extends EventEmitter {
11
+ middleware?: DevMiddlewareAPI;
12
+ private devOptions;
13
+ private socketServer;
14
+ constructor({
15
+ dev,
16
+ devMiddleware
17
+ }: Options);
18
+ init(app: Server): void;
19
+ sockWrite(type: string, data?: Record<string, any> | string | boolean): void;
20
+ private setupDevMiddleware;
21
+ }
22
+ export {};
@@ -0,0 +1,90 @@
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 dev_middleware_exports = {};
30
+ __export(dev_middleware_exports, {
31
+ default: () => DevMiddleware
32
+ });
33
+ module.exports = __toCommonJS(dev_middleware_exports);
34
+ var import_events = require("events");
35
+ var import_socketServer = __toESM(require("./socketServer"));
36
+ const noop = () => {
37
+ };
38
+ function getHMRClientPath(client) {
39
+ const protocol = (client == null ? void 0 : client.protocol) ? `&protocol=${client.protocol}` : "";
40
+ const host = (client == null ? void 0 : client.host) ? `&host=${client.host}` : "";
41
+ const path = (client == null ? void 0 : client.path) ? `&path=${client.path}` : "";
42
+ const port = (client == null ? void 0 : client.port) ? `&port=${client.port}` : "";
43
+ const clientEntry = `${require.resolve("@rsbuild/core/hmr-client")}?${host}${path}${port}${protocol}`;
44
+ return clientEntry;
45
+ }
46
+ class DevMiddleware extends import_events.EventEmitter {
47
+ constructor({ dev, devMiddleware }) {
48
+ super();
49
+ this.devOptions = dev;
50
+ this.socketServer = new import_socketServer.default(dev);
51
+ if (devMiddleware) {
52
+ this.middleware = this.setupDevMiddleware(devMiddleware);
53
+ }
54
+ }
55
+ init(app) {
56
+ app.on("listening", () => {
57
+ this.socketServer.prepare(app);
58
+ });
59
+ app.on("close", async () => {
60
+ var _a;
61
+ (_a = this.middleware) == null ? void 0 : _a.close(noop);
62
+ this.socketServer.close();
63
+ });
64
+ }
65
+ sockWrite(type, data) {
66
+ this.socketServer.sockWrite(type, data);
67
+ }
68
+ setupDevMiddleware(devMiddleware) {
69
+ const { devOptions } = this;
70
+ const callbacks = {
71
+ onInvalid: () => {
72
+ this.socketServer.sockWrite("invalid");
73
+ },
74
+ onDone: (stats) => {
75
+ this.socketServer.updateStats(stats);
76
+ this.emit("change", stats);
77
+ }
78
+ };
79
+ const enableHMR = this.devOptions.hot || this.devOptions.liveReload;
80
+ const middleware = devMiddleware({
81
+ headers: devOptions.headers,
82
+ stats: false,
83
+ callbacks,
84
+ hmrClientPath: enableHMR ? getHMRClientPath(devOptions.client) : void 0,
85
+ serverSideRender: true,
86
+ ...devOptions.devMiddleware
87
+ });
88
+ return middleware;
89
+ }
90
+ }
@@ -0,0 +1,22 @@
1
+ /// <reference types="node" />
2
+ import { Server } from 'http';
3
+ import ws from 'ws';
4
+ import { Stats, DevServerOptions } from '@rsbuild/shared';
5
+ export default class SocketServer {
6
+ private wsServer;
7
+ private readonly sockets;
8
+ private readonly options;
9
+ private app?;
10
+ private stats?;
11
+ private timer;
12
+ constructor(options: DevServerOptions);
13
+ prepare(app: Server): void;
14
+ updateStats(stats: Stats): void;
15
+ sockWrite(type: string, data?: Record<string, any> | string | boolean): void;
16
+ singleWrite(socket: ws, type: string, data?: Record<string, any> | string | boolean): void;
17
+ close(): void;
18
+ private onConnect;
19
+ private getStats;
20
+ private sendStats;
21
+ private send;
22
+ }
@@ -0,0 +1,167 @@
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 socketServer_exports = {};
30
+ __export(socketServer_exports, {
31
+ default: () => SocketServer
32
+ });
33
+ module.exports = __toCommonJS(socketServer_exports);
34
+ var import_ws = __toESM(require("ws"));
35
+ var import_shared = require("@rsbuild/shared");
36
+ class SocketServer {
37
+ constructor(options) {
38
+ this.sockets = [];
39
+ this.timer = null;
40
+ this.options = options;
41
+ }
42
+ // create socket, install socket handler, bind socket event
43
+ prepare(app) {
44
+ var _a;
45
+ this.app = app;
46
+ this.wsServer = new import_ws.default.Server({
47
+ noServer: true,
48
+ path: (_a = this.options.client) == null ? void 0 : _a.path
49
+ });
50
+ this.app.on("upgrade", (req, sock, head) => {
51
+ if (!this.wsServer.shouldHandle(req)) {
52
+ return;
53
+ }
54
+ this.wsServer.handleUpgrade(req, sock, head, (connection) => {
55
+ this.wsServer.emit("connection", connection, req);
56
+ });
57
+ });
58
+ this.wsServer.on("error", (err) => {
59
+ import_shared.logger.error(err);
60
+ });
61
+ this.timer = setInterval(() => {
62
+ this.wsServer.clients.forEach((socket) => {
63
+ const extWs = socket;
64
+ if (!extWs.isAlive) {
65
+ extWs.terminate();
66
+ } else {
67
+ extWs.isAlive = false;
68
+ extWs.ping(() => {
69
+ });
70
+ }
71
+ });
72
+ }, 3e4);
73
+ this.wsServer.on("connection", (socket) => {
74
+ this.onConnect(socket);
75
+ });
76
+ }
77
+ updateStats(stats) {
78
+ this.stats = stats;
79
+ this.sendStats();
80
+ }
81
+ // write message to each socket
82
+ sockWrite(type, data) {
83
+ this.sockets.forEach((socket) => {
84
+ this.send(socket, JSON.stringify({ type, data }));
85
+ });
86
+ }
87
+ singleWrite(socket, type, data) {
88
+ this.send(socket, JSON.stringify({ type, data }));
89
+ }
90
+ close() {
91
+ this.sockets.forEach((socket) => {
92
+ socket.close();
93
+ });
94
+ if (this.timer) {
95
+ clearInterval(this.timer);
96
+ this.timer = null;
97
+ }
98
+ }
99
+ onConnect(socket) {
100
+ const connection = socket;
101
+ connection.isAlive = true;
102
+ connection.on("pong", () => {
103
+ connection.isAlive = true;
104
+ });
105
+ if (!connection) {
106
+ return;
107
+ }
108
+ this.sockets.push(connection);
109
+ connection.on("close", () => {
110
+ const idx = this.sockets.indexOf(connection);
111
+ if (idx >= 0) {
112
+ this.sockets.splice(idx, 1);
113
+ }
114
+ });
115
+ if (this.options.hot || this.options.hot === "only") {
116
+ this.singleWrite(connection, "hot");
117
+ }
118
+ if (this.options.liveReload) {
119
+ this.singleWrite(connection, "liveReload");
120
+ }
121
+ if (this.stats) {
122
+ this.sendStats(true);
123
+ }
124
+ }
125
+ // get standard stats
126
+ getStats() {
127
+ const curStats = this.stats;
128
+ if (!curStats) {
129
+ return null;
130
+ }
131
+ const defaultStats = {
132
+ all: false,
133
+ hash: true,
134
+ assets: true,
135
+ warnings: true,
136
+ errors: true,
137
+ errorDetails: false
138
+ };
139
+ return curStats.toJson(defaultStats);
140
+ }
141
+ // determine what message should send by stats
142
+ sendStats(force = false) {
143
+ const stats = this.getStats();
144
+ if (!stats) {
145
+ return null;
146
+ }
147
+ const shouldEmit = !force && stats && (!stats.errors || stats.errors.length === 0) && stats.assets && stats.assets.every((asset) => !asset.emitted);
148
+ if (shouldEmit) {
149
+ return this.sockWrite("still-ok");
150
+ }
151
+ this.sockWrite("hash", stats.hash);
152
+ if (stats.errors && stats.errors.length > 0) {
153
+ return this.sockWrite("errors", stats.errors);
154
+ } else if (stats.warnings && stats.warnings.length > 0) {
155
+ return this.sockWrite("warnings", stats.warnings);
156
+ } else {
157
+ return this.sockWrite("ok");
158
+ }
159
+ }
160
+ // send message to connecting socket
161
+ send(connection, message) {
162
+ if (connection.readyState !== 1) {
163
+ return;
164
+ }
165
+ connection.send(message);
166
+ }
167
+ }
@@ -0,0 +1,23 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ /// <reference types="node" />
4
+ import { Server } from 'http';
5
+ import type { ListenOptions } from 'net';
6
+ import { RsbuildDevServerOptions, CreateDevServerOptions, ServerApi } from '@rsbuild/shared';
7
+ import connect from 'connect';
8
+ export declare class RsbuildDevServer {
9
+ private readonly dev;
10
+ private readonly devMiddleware;
11
+ private pwd;
12
+ private app;
13
+ middlewares: connect.Server;
14
+ constructor(options: RsbuildDevServerOptions);
15
+ private getDevOptions;
16
+ private applySetupMiddlewares;
17
+ onInit(app: Server): Promise<void>;
18
+ private applyDefaultMiddlewares;
19
+ createHTTPServer(): Promise<Server<typeof import("http").IncomingMessage, typeof import("http").ServerResponse> | import("https").Server<typeof import("http").IncomingMessage, typeof import("http").ServerResponse>>;
20
+ listen(options?: number | ListenOptions | undefined, listener?: () => void): void;
21
+ close(): void;
22
+ }
23
+ export declare function createDevServer(options: CreateDevServerOptions): Promise<ServerApi>;
@@ -0,0 +1,172 @@
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 devServer_exports = {};
30
+ __export(devServer_exports, {
31
+ RsbuildDevServer: () => RsbuildDevServer,
32
+ createDevServer: () => createDevServer
33
+ });
34
+ module.exports = __toCommonJS(devServer_exports);
35
+ var import_http = require("http");
36
+ var import_https = require("https");
37
+ var import_url = __toESM(require("url"));
38
+ var import_shared = require("@rsbuild/shared");
39
+ var import_constants = require("./constants");
40
+ var import_dev_middleware = __toESM(require("./dev-middleware"));
41
+ var import_deepmerge = require("@rsbuild/shared/deepmerge");
42
+ var import_connect = __toESM(require("connect"));
43
+ class RsbuildDevServer {
44
+ constructor(options) {
45
+ this.middlewares = (0, import_connect.default)();
46
+ this.pwd = options.pwd;
47
+ this.dev = this.getDevOptions(options);
48
+ this.devMiddleware = new import_dev_middleware.default({
49
+ dev: this.dev,
50
+ devMiddleware: options.devMiddleware
51
+ });
52
+ }
53
+ getDevOptions(options) {
54
+ const devOptions = typeof options.dev === "boolean" ? {} : options.dev;
55
+ const defaultOptions = (0, import_constants.getDefaultDevOptions)();
56
+ return (0, import_deepmerge.deepmerge)(defaultOptions, devOptions);
57
+ }
58
+ applySetupMiddlewares() {
59
+ const setupMiddlewares = this.dev.setupMiddlewares || [];
60
+ const serverOptions = {
61
+ sockWrite: (type, data) => this.devMiddleware.sockWrite(type, data)
62
+ };
63
+ const before = [];
64
+ const after = [];
65
+ setupMiddlewares.forEach((handler) => {
66
+ handler(
67
+ {
68
+ unshift: (...handlers) => before.unshift(...handlers),
69
+ push: (...handlers) => after.push(...handlers)
70
+ },
71
+ serverOptions
72
+ );
73
+ });
74
+ return { before, after };
75
+ }
76
+ // Complete the preparation of services
77
+ async onInit(app) {
78
+ this.app = app;
79
+ const { before, after } = this.applySetupMiddlewares();
80
+ before.forEach((fn) => this.middlewares.use(fn));
81
+ await this.applyDefaultMiddlewares(app);
82
+ after.forEach((fn) => this.middlewares.use(fn));
83
+ }
84
+ async applyDefaultMiddlewares(app) {
85
+ const { dev, devMiddleware } = this;
86
+ if (dev.compress) {
87
+ const { default: compression } = await Promise.resolve().then(() => __toESM(require("http-compression")));
88
+ this.middlewares.use((req, res, next) => {
89
+ compression({
90
+ gzip: true,
91
+ brotli: false
92
+ })(req, res, next);
93
+ });
94
+ }
95
+ this.middlewares.use((req, res, next) => {
96
+ res.setHeader("Access-Control-Allow-Origin", "*");
97
+ const path = req.url ? import_url.default.parse(req.url).pathname : "";
98
+ if (path == null ? void 0 : path.includes("hot-update")) {
99
+ res.setHeader("Access-Control-Allow-Credentials", "false");
100
+ }
101
+ const confHeaders = dev.headers;
102
+ if (confHeaders) {
103
+ for (const [key, value] of Object.entries(confHeaders)) {
104
+ res.setHeader(key, value);
105
+ }
106
+ }
107
+ next();
108
+ });
109
+ devMiddleware.init(app);
110
+ devMiddleware.middleware && this.middlewares.use(devMiddleware.middleware);
111
+ if (dev.historyApiFallback) {
112
+ const { default: connectHistoryApiFallback } = await Promise.resolve().then(() => __toESM(require("connect-history-api-fallback")));
113
+ const historyApiFallbackMiddleware = connectHistoryApiFallback(
114
+ // @ts-expect-error
115
+ typeof dev.historyApiFallback === "boolean" ? {} : dev.historyApiFallback
116
+ );
117
+ this.middlewares.use(historyApiFallbackMiddleware);
118
+ devMiddleware.middleware && this.middlewares.use(devMiddleware.middleware);
119
+ }
120
+ }
121
+ async createHTTPServer() {
122
+ const { dev } = this;
123
+ const devHttpsOption = typeof dev === "object" && dev.https;
124
+ if (devHttpsOption) {
125
+ const { genHttpsOptions } = require("./https");
126
+ const httpsOptions = await genHttpsOptions(devHttpsOption, this.pwd);
127
+ return (0, import_https.createServer)(httpsOptions, this.middlewares);
128
+ } else {
129
+ return (0, import_http.createServer)(this.middlewares);
130
+ }
131
+ }
132
+ listen(options, listener) {
133
+ const callback = () => {
134
+ listener == null ? void 0 : listener();
135
+ };
136
+ if (typeof options === "object") {
137
+ this.app.listen(options, callback);
138
+ } else {
139
+ this.app.listen(options || 8080, callback);
140
+ }
141
+ }
142
+ close() {
143
+ this.app.close();
144
+ }
145
+ }
146
+ async function createDevServer(options) {
147
+ var _a;
148
+ const { server: serverOptions = {}, ...devOptions } = options;
149
+ const logger = (_a = serverOptions.logger) != null ? _a : import_shared.logger;
150
+ const devServer = new RsbuildDevServer(devOptions);
151
+ const httpServer = serverOptions.customApp || await devServer.createHTTPServer();
152
+ const server = {
153
+ middlewares: devServer.middlewares,
154
+ init: async () => {
155
+ await devServer.onInit(httpServer);
156
+ },
157
+ // resolvedConfig,
158
+ listen: (options2, cb) => {
159
+ devServer.listen(options2, cb);
160
+ },
161
+ logger,
162
+ close: () => {
163
+ devServer.close();
164
+ }
165
+ };
166
+ return server;
167
+ }
168
+ // Annotate the CommonJS export names for ESM import in node:
169
+ 0 && (module.exports = {
170
+ RsbuildDevServer,
171
+ createDevServer
172
+ });
@@ -0,0 +1,6 @@
1
+ /// <reference types="node" />
2
+ import { type DevServerHttpsOptions } from '@rsbuild/shared';
3
+ export declare const genHttpsOptions: (userOptions: DevServerHttpsOptions, pwd: string) => Promise<{
4
+ key?: Buffer | string;
5
+ cert?: Buffer | string;
6
+ }>;