-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjsApi.ts
More file actions
289 lines (250 loc) · 6.73 KB
/
jsApi.ts
File metadata and controls
289 lines (250 loc) · 6.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import assert from 'node:assert';
import { join } from 'node:path';
import { stripVTControlCharacters as stripAnsi } from 'node:util';
import type {
CreateRsbuildOptions,
BuildResult as RsbuildBuildResult,
RsbuildConfig,
RsbuildInstance,
} from '@rsbuild/core';
import { createRsbuild } from '@rsbuild/core';
import express from 'express';
import type { Page } from 'playwright';
import type { LogHelper } from './logs.ts';
import { getRandomPort, gotoPage, noop, toPosixPath } from './utils.ts';
const updateConfigForTest = async (
originalConfig: RsbuildConfig,
cwd: string = process.cwd(),
) => {
const { loadConfig, mergeRsbuildConfig } = await import('@rsbuild/core');
const { content: loadedConfig } = await loadConfig({
cwd,
});
const baseConfig: RsbuildConfig = {
server: {
// make port random to avoid conflict
port: await getRandomPort(),
},
performance: {
buildCache: false,
},
};
const mergedConfig = mergeRsbuildConfig(
baseConfig,
loadedConfig,
originalConfig,
);
return mergedConfig;
};
const filterSourceMaps = (distFiles: Record<string, string>) => {
return Object.entries(distFiles).reduce(
(acc, [key, value]) => {
if (key.endsWith('.map')) {
return acc;
}
acc[key] = value;
return acc;
},
{} as Record<string, string>,
);
};
const collectOutputFiles = (rsbuild: RsbuildInstance) => {
let outputFiles: Record<string, string> = {};
const reset = () => {
outputFiles = {};
};
rsbuild.onBeforeBuild(reset);
rsbuild.onBeforeStartDevServer(reset);
rsbuild.onAfterCreateCompiler(({ compiler }) => {
const compilers = 'compilers' in compiler ? compiler.compilers : [compiler];
for (const compiler of compilers) {
compiler.hooks.emit.tap('CollectAssetsPlugin', (compilation) => {
for (const asset of compilation.getAssets()) {
// skip inlined assets
if (!asset.source) {
continue;
}
const outputPath = compilation.options.output.path;
const assetPath = toPosixPath(
outputPath ? join(outputPath, asset.name) : asset.name,
);
outputFiles[assetPath] = asset.source.source().toString();
}
});
}
});
return () => outputFiles;
};
export type DevOptions = CreateRsbuildOptions & {
logHelper?: LogHelper;
config?: RsbuildConfig;
/**
* Playwright Page instance.
* This method will automatically goto the page.
*/
page?: Page;
/**
* The done of `dev` does not mean the compile is done.
* If your test relies on the completion of compilation you should `waitFirstCompileDone`
* @default true
*/
waitFirstCompileDone?: boolean;
};
/**
* Start the dev server and return the server instance.
*/
export async function dev({
page,
waitFirstCompileDone = true,
logHelper,
...options
}: DevOptions = {}) {
process.env.NODE_ENV = 'development';
options.config = await updateConfigForTest(options.config || {}, options.cwd);
const rsbuild = await createRsbuild(options);
const getOutputFiles = collectOutputFiles(rsbuild);
const wait = waitFirstCompileDone
? new Promise<void>((resolve) => {
rsbuild.onAfterDevCompile(({ isFirstCompile }) => {
if (!isFirstCompile) {
return;
}
resolve();
});
})
: Promise.resolve();
const result = await rsbuild.startDevServer();
await wait;
if (page) {
await gotoPage(page, result);
}
const { distPath } = rsbuild.context;
return {
...result,
...logHelper!,
distPath,
instance: rsbuild,
getDistFiles: ({ sourceMaps }: { sourceMaps?: boolean } = {}) =>
sourceMaps ? getOutputFiles() : filterSourceMaps(getOutputFiles()),
close: async () => {
await result.server.close();
},
};
}
export type BuildOptions = CreateRsbuildOptions & {
logHelper?: LogHelper;
config?: RsbuildConfig;
/**
* Whether to catch the build error.
* @default false
*/
catchBuildError?: boolean;
/**
* Whether to run the server.
* @default false
*/
runServer?: boolean;
/**
* Whether to start preview server after build.
* @default false
*/
preview?: boolean;
/**
* Playwright Page instance.
* This method will automatically run the server and goto the page.
*/
page?: Page;
/**
* Whether to watch files.
*/
watch?: boolean;
};
/**
* Build the project and return the build result.
*/
export async function build({
catchBuildError = false,
runServer = false,
preview = false,
watch = false,
page,
logHelper,
...options
}: BuildOptions = {}) {
process.env.NODE_ENV = 'production';
options.config = await updateConfigForTest(options.config || {}, options.cwd);
const rsbuild = await createRsbuild(options);
const getOutputFiles = collectOutputFiles(rsbuild);
let buildError: Error | undefined;
let buildResult: RsbuildBuildResult | undefined;
try {
buildResult = await rsbuild.build({ watch });
} catch (error) {
buildError = error as Error;
buildError.message = stripAnsi(buildError.message);
if (!catchBuildError) {
throw buildError;
}
}
const { distPath } = rsbuild.context;
let port = 0;
let server = { close: noop };
if (preview) {
const result = await rsbuild.preview();
port = result.port;
server = result.server;
}
if (runServer) {
port = await getRandomPort();
const app = express();
// RSC handler middleware
const rsc = await import(distPath);
app.use(rsc.default.nodeHandler);
// Static file serving
app.use(express.static(distPath));
await new Promise<void>((resolve, reject) => {
const theServer = app.listen(port, (error) => {
if (error) {
reject(error);
return;
}
resolve();
});
server = {
async close() {
theServer.close();
},
};
});
}
const getIndexBundle = async () => {
const [name, content] =
Object.entries(getOutputFiles()).find(
([file]) => file.includes('index') && file.endsWith('.js'),
) || [];
assert(name && content);
return content;
};
if (page) {
await gotoPage(page, { port });
}
return {
...logHelper!,
distPath,
port,
stats: buildResult?.stats,
close: async () => {
await buildResult?.close();
await server.close();
},
buildError,
getDistFiles: ({ sourceMaps }: { sourceMaps?: boolean } = {}) =>
sourceMaps ? getOutputFiles() : filterSourceMaps(getOutputFiles()),
getIndexBundle,
instance: rsbuild,
};
}
export type Build = typeof build;
export type BuildResult = Awaited<ReturnType<Build>>;
export type Dev = typeof dev;
export type DevResult = Awaited<ReturnType<Dev>>;