@rstest/core 0.6.1 → 0.6.2

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.
package/dist/0~628.js DELETED
@@ -1,1090 +0,0 @@
1
- import 'module';
2
- /*#__PURE__*/ import.meta.url;
3
- import * as __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__ from "node:url";
4
- import * as __WEBPACK_EXTERNAL_MODULE_node_v8_d0df5498__ from "node:v8";
5
- import * as __WEBPACK_EXTERNAL_MODULE_node_events_0a6aefe7__ from "node:events";
6
- import * as __WEBPACK_EXTERNAL_MODULE_tinypool__ from "tinypool";
7
- import * as __WEBPACK_EXTERNAL_MODULE_node_inspector_dd9822d6__ from "node:inspector";
8
- export const __webpack_id__ = "628";
9
- export const __webpack_ids__ = [
10
- "628"
11
- ];
12
- export const __webpack_modules__ = {
13
- "./src/core/rsbuild.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
14
- __webpack_require__.d(__webpack_exports__, {
15
- XD: ()=>createRsbuildServer,
16
- zh: ()=>prepareRsbuild
17
- });
18
- var external_node_url_ = __webpack_require__("node:url");
19
- var core_ = __webpack_require__("@rsbuild/core");
20
- var dist = __webpack_require__("../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/index.mjs");
21
- var utils = __webpack_require__("./src/utils/index.ts");
22
- var memory = __webpack_require__("./src/utils/memory.ts");
23
- const RUNTIME_CHUNK_NAME = 'runtime';
24
- const pluginBasic = (context)=>({
25
- name: 'rstest:basic',
26
- setup: (api)=>{
27
- api.modifyEnvironmentConfig(async (config, { mergeEnvironmentConfig, name })=>{
28
- const { normalizedConfig: { resolve, source, output, tools, performance, dev, testEnvironment }, rootPath } = context.projects.find((p)=>p.environmentName === name);
29
- return mergeEnvironmentConfig(config, {
30
- performance,
31
- tools,
32
- resolve,
33
- source,
34
- output,
35
- dev
36
- }, {
37
- source: {
38
- define: {
39
- 'import.meta.rstest': "global['@rstest/core']",
40
- 'import.meta.env': 'process.env'
41
- }
42
- },
43
- output: {
44
- manifest: `${name}-manifest.json`,
45
- sourceMap: {
46
- js: 'source-map'
47
- },
48
- distPath: {
49
- root: context.projects.length > 1 ? `${utils.zZ}/${name}` : utils.zZ
50
- }
51
- },
52
- tools: {
53
- rspack: (config, { isProd, rspack })=>{
54
- config.context = rootPath;
55
- config.mode = isProd ? 'production' : 'development';
56
- config.output ??= {};
57
- config.output.iife = false;
58
- config.output.importFunctionName = '__rstest_dynamic_import__';
59
- config.output.devtoolModuleFilenameTemplate = '[absolute-resource-path]';
60
- if (!config.devtool || !config.devtool.includes('inline')) config.devtool = 'nosources-source-map';
61
- config.plugins.push(new rspack.experiments.RstestPlugin({
62
- injectModulePathName: true,
63
- importMetaPathName: true,
64
- hoistMockModule: true,
65
- manualMockRoot: dist.Ay.resolve(rootPath, '__mocks__')
66
- }));
67
- config.module.parser ??= {};
68
- config.module.parser.javascript = {
69
- importDynamic: false,
70
- requireDynamic: false,
71
- requireAsExpression: false,
72
- requireResolve: false,
73
- ...config.module.parser.javascript || {}
74
- };
75
- config.resolve ??= {};
76
- config.resolve.extensions ??= [];
77
- config.resolve.extensions.push('.cjs');
78
- config.resolve.extensionAlias ??= {};
79
- config.resolve.extensionAlias['.js'] = [
80
- '.js',
81
- '.ts',
82
- '.tsx'
83
- ];
84
- config.resolve.extensionAlias['.jsx'] = [
85
- '.jsx',
86
- '.tsx'
87
- ];
88
- if ('node' === testEnvironment) config.resolve.mainFields = config.resolve.mainFields?.filter((filed)=>'module' !== filed) || [
89
- 'main'
90
- ];
91
- config.resolve.byDependency ??= {};
92
- config.resolve.byDependency.commonjs ??= {};
93
- config.resolve.byDependency.commonjs.mainFields = [
94
- 'main',
95
- '...'
96
- ];
97
- config.optimization = {
98
- moduleIds: 'named',
99
- chunkIds: 'named',
100
- nodeEnv: false,
101
- ...config.optimization || {},
102
- runtimeChunk: {
103
- name: `${name}-${RUNTIME_CHUNK_NAME}`
104
- }
105
- };
106
- }
107
- }
108
- });
109
- });
110
- }
111
- });
112
- var external_node_path_ = __webpack_require__("node:path");
113
- const PLUGIN_CSS_FILTER = 'rstest:css-filter';
114
- const css_filter_dirname = external_node_path_["default"].dirname((0, external_node_url_.fileURLToPath)(import.meta.url));
115
- const pluginCSSFilter = ()=>({
116
- name: PLUGIN_CSS_FILTER,
117
- setup (api) {
118
- api.modifyBundlerChain({
119
- order: 'post',
120
- handler: async (chain, { target, CHAIN_ID, environment })=>{
121
- const emitCss = environment.config.output.emitCss ?? 'web' === target;
122
- if (!emitCss) {
123
- const ruleIds = [
124
- CHAIN_ID.RULE.CSS,
125
- CHAIN_ID.RULE.SASS,
126
- CHAIN_ID.RULE.LESS,
127
- CHAIN_ID.RULE.STYLUS
128
- ];
129
- for (const ruleId of ruleIds){
130
- if (!chain.module.rules.has(ruleId)) continue;
131
- const rule = chain.module.rule(ruleId);
132
- if (!rule.uses.has(CHAIN_ID.USE.CSS)) continue;
133
- const cssLoaderOptions = rule.use(CHAIN_ID.USE.CSS).get('options');
134
- if (cssLoaderOptions.modules && ('object' != typeof cssLoaderOptions.modules || false !== cssLoaderOptions.modules.auto)) rule.use('rstest-css-pre-filter').loader(external_node_path_["default"].join(css_filter_dirname, 'cssFilterLoader.mjs')).options({
135
- modules: cssLoaderOptions.modules
136
- }).after(ruleId);
137
- }
138
- }
139
- }
140
- });
141
- }
142
- });
143
- class TestFileWatchPlugin {
144
- contextToWatch = null;
145
- constructor(contextToWatch){
146
- this.contextToWatch = contextToWatch;
147
- }
148
- apply(compiler) {
149
- compiler.hooks.afterCompile.tap('Rstest:TestFileWatchPlugin', (compilation)=>{
150
- if (null === this.contextToWatch) return;
151
- const contextDep = compilation.contextDependencies;
152
- if (!contextDep.has(this.contextToWatch)) contextDep.add(this.contextToWatch);
153
- });
154
- }
155
- }
156
- const pluginEntryWatch = ({ isWatch, globTestSourceEntries, setupFiles, context })=>({
157
- name: 'rstest:entry-watch',
158
- setup: (api)=>{
159
- api.modifyRspackConfig(async (config, { environment })=>{
160
- if (isWatch) {
161
- config.plugins.push(new TestFileWatchPlugin(environment.config.root));
162
- config.entry = async ()=>{
163
- const sourceEntries = await globTestSourceEntries(environment.name);
164
- return {
165
- ...sourceEntries,
166
- ...setupFiles[environment.name]
167
- };
168
- };
169
- config.watchOptions ??= {};
170
- config.watchOptions.ignored = (0, utils.bg)(config.watchOptions.ignored || []);
171
- if (0 === config.watchOptions.ignored.length) config.watchOptions.ignored.push('**/.git', '**/node_modules');
172
- config.watchOptions.ignored.push(utils.EJ, context.normalizedConfig.coverage.reportsDirectory, '**/*.snap');
173
- const configFilePath = context.projects.find((project)=>project.environmentName === environment.name)?.configFilePath;
174
- if (configFilePath) config.watchOptions.ignored.push(configFilePath);
175
- } else {
176
- config.watch = false;
177
- config.watchOptions ??= {};
178
- config.watchOptions.ignored = '**/**';
179
- const sourceEntries = await globTestSourceEntries(environment.name);
180
- config.entry = {
181
- ...setupFiles[environment.name],
182
- ...sourceEntries
183
- };
184
- }
185
- });
186
- }
187
- });
188
- var external_node_module_ = __webpack_require__("node:module");
189
- const autoExternalNodeModules = ({ context, request, dependencyType, getResolve }, callback)=>{
190
- if (!request) return callback();
191
- if (request.startsWith('@swc/helpers/')) return callback();
192
- const doExternal = (externalPath = request)=>{
193
- callback(void 0, externalPath, 'commonjs' === dependencyType ? 'commonjs' : 'import');
194
- };
195
- const resolver = getResolve?.();
196
- if (!resolver) return callback();
197
- resolver(context, request, (err, resolvePath)=>{
198
- if (err) return callback();
199
- if (resolvePath && /node_modules/.test(resolvePath)) return doExternal(resolvePath);
200
- return callback();
201
- });
202
- };
203
- function autoExternalNodeBuiltin({ request, dependencyType }, callback) {
204
- if (!request) return void callback();
205
- const isNodeBuiltin = (0, external_node_module_.isBuiltin)(request) || utils.Uq.some((builtin)=>{
206
- if ('string' == typeof builtin) return builtin === request;
207
- return builtin.test(request);
208
- });
209
- if (isNodeBuiltin) callback(void 0, request, 'commonjs' === dependencyType ? 'commonjs' : 'module-import');
210
- else callback();
211
- }
212
- const pluginExternal = (context)=>({
213
- name: 'rstest:external',
214
- setup: (api)=>{
215
- api.modifyEnvironmentConfig(async (config, { mergeEnvironmentConfig, name })=>{
216
- const { normalizedConfig: { testEnvironment } } = context.projects.find((p)=>p.environmentName === name);
217
- return mergeEnvironmentConfig(config, {
218
- output: {
219
- externals: 'node' === testEnvironment ? [
220
- autoExternalNodeModules
221
- ] : void 0
222
- },
223
- tools: {
224
- rspack: (config)=>{
225
- config.externals = (0, utils.bg)(config.externals) || [];
226
- config.externals.unshift({
227
- '@rstest/core': 'global @rstest/core'
228
- });
229
- config.externalsPresets ??= {};
230
- config.externalsPresets.node = false;
231
- config.externals.push(autoExternalNodeBuiltin);
232
- }
233
- }
234
- });
235
- });
236
- }
237
- });
238
- class IgnoreModuleNotFoundErrorPlugin {
239
- apply(compiler) {
240
- compiler.hooks.done.tap('Rstest:IgnoreModuleNotFoundPlugin', (stats)=>{
241
- for(let i = stats.compilation.errors.length - 1; i >= 0; i--)if (/Module not found/.test(stats.compilation.errors[i].message)) stats.compilation.errors.splice(i, 1);
242
- });
243
- }
244
- }
245
- const pluginIgnoreResolveError = {
246
- name: 'rstest:ignore-resolve-error',
247
- setup: (api)=>{
248
- api.modifyRspackConfig(async (config)=>{
249
- config.plugins.push(new IgnoreModuleNotFoundErrorPlugin());
250
- config.optimization ??= {};
251
- config.optimization.emitOnErrors = true;
252
- config.ignoreWarnings ??= [];
253
- config.ignoreWarnings.push(/Module not found/);
254
- });
255
- }
256
- };
257
- const enable = void 0 !== __WEBPACK_EXTERNAL_MODULE_node_inspector_dd9822d6__["default"].url();
258
- const pluginInspect = ()=>enable ? {
259
- name: 'rstest:inspect',
260
- setup: (api)=>{
261
- api.modifyRspackConfig(async (config)=>{
262
- config.devtool = 'inline-nosources-source-map';
263
- config.optimization ??= {};
264
- config.optimization.splitChunks = {
265
- ...config.optimization.splitChunks || {},
266
- maxSize: 1048576,
267
- chunks: 'all'
268
- };
269
- });
270
- }
271
- } : null;
272
- var external_node_fs_ = __webpack_require__("node:fs");
273
- const mockRuntime_dirname = external_node_path_["default"].dirname((0, external_node_url_.fileURLToPath)(import.meta.url));
274
- class MockRuntimeRspackPlugin {
275
- apply(compiler) {
276
- const { RuntimeModule } = compiler.webpack;
277
- class RetestImportRuntimeModule extends RuntimeModule {
278
- constructor(){
279
- super('rstest runtime');
280
- }
281
- generate() {
282
- const code = external_node_fs_["default"].readFileSync(external_node_path_["default"].join(mockRuntime_dirname, './mockRuntimeCode.js'), 'utf8');
283
- return code;
284
- }
285
- }
286
- compiler.hooks.compilation.tap('RstestMockPlugin', (compilation)=>{
287
- compilation.hooks.runtimeModule.tap('RstestMockChunkLoadingRuntimePlugin', (module)=>{
288
- if ('require_chunk_loading' === module.name) {
289
- const finalSource = module.source.source.toString('utf-8').replace('for (var moduleId in moreModules) {', "for (var moduleId in moreModules) {\n if (Object.keys(__webpack_require__.rstest_original_modules).includes(moduleId)) continue;");
290
- module.source.source = Buffer.from(finalSource);
291
- }
292
- if ('define_property_getters' === module.name) {
293
- const finalSource = module.source.source.toString('utf-8').replace('enumerable: true, get:', 'enumerable: true, configurable: true, get:');
294
- module.source.source = Buffer.from(finalSource);
295
- }
296
- });
297
- });
298
- compiler.hooks.thisCompilation.tap('RstestMockPlugin', (compilation)=>{
299
- compilation.hooks.additionalTreeRuntimeRequirements.tap('RstestAddMockRuntimePlugin', (chunk)=>{
300
- compilation.addRuntimeModule(chunk, new RetestImportRuntimeModule());
301
- });
302
- });
303
- }
304
- }
305
- const pluginMockRuntime = {
306
- name: 'rstest:mock-runtime',
307
- setup: (api)=>{
308
- api.modifyRspackConfig(async (config)=>{
309
- config.plugins.push(new MockRuntimeRspackPlugin());
310
- });
311
- }
312
- };
313
- class RstestCacheControlPlugin {
314
- apply(compiler) {
315
- const { RuntimeModule } = compiler.webpack;
316
- class RetestCacheControlModule extends RuntimeModule {
317
- constructor(){
318
- super('rstest_cache_control');
319
- }
320
- generate() {
321
- return `
322
- global.setupIds = [];
323
-
324
- function __rstest_clean_core_cache__() {
325
- if (typeof __webpack_require__ === 'undefined') {
326
- return;
327
- }
328
- delete __webpack_module_cache__['@rstest/core'];
329
-
330
- global.setupIds.forEach((id) => {
331
- delete __webpack_module_cache__[id];
332
- });
333
- }
334
-
335
- global.__rstest_clean_core_cache__ = __rstest_clean_core_cache__;
336
- `;
337
- }
338
- }
339
- compiler.hooks.thisCompilation.tap('RstestCacheControlPlugin', (compilation)=>{
340
- compilation.hooks.additionalTreeRuntimeRequirements.tap('RstestAddCacheControlRuntimePlugin', (chunk)=>{
341
- compilation.addRuntimeModule(chunk, new RetestCacheControlModule());
342
- });
343
- });
344
- }
345
- }
346
- const pluginCacheControl = (setupFiles)=>({
347
- name: 'rstest:cache-control',
348
- setup: (api)=>{
349
- api.transform({
350
- test: setupFiles
351
- }, ({ code })=>({
352
- code: `
353
- ${code}
354
- if (global.setupIds && __webpack_module__.id) {
355
- global.setupIds.push(__webpack_module__.id);
356
- }
357
- `
358
- }));
359
- api.modifyRspackConfig(async (config)=>{
360
- config.plugins.push(new RstestCacheControlPlugin());
361
- });
362
- }
363
- });
364
- const rsbuild_dirname = dist.Ay.dirname((0, external_node_url_.fileURLToPath)(import.meta.url));
365
- function parseInlineSourceMapStr(code) {
366
- const inlineSourceMapRegex = /\/\/# sourceMappingURL=data:application\/json(?:;charset=utf-8)?;base64,(.+)\s*$/m;
367
- const match = code.match(inlineSourceMapRegex);
368
- if (!match || !match[1]) return null;
369
- try {
370
- const base64Data = match[1];
371
- const decodedStr = Buffer.from(base64Data, 'base64').toString('utf-8');
372
- return decodedStr;
373
- } catch (_error) {
374
- return null;
375
- }
376
- }
377
- const isMultiCompiler = (compiler)=>'compilers' in compiler && Array.isArray(compiler.compilers);
378
- const prepareRsbuild = async (context, globTestSourceEntries, setupFiles)=>{
379
- const { command, normalizedConfig: { isolate, dev = {}, coverage } } = context;
380
- const debugMode = (0, utils._o)();
381
- core_.logger.level = debugMode ? 'verbose' : 'error';
382
- const writeToDisk = dev.writeToDisk || debugMode;
383
- const rsbuildInstance = await (0, core_.createRsbuild)({
384
- callerName: 'rstest',
385
- rsbuildConfig: {
386
- root: context.rootPath,
387
- server: {
388
- printUrls: false,
389
- strictPort: false,
390
- middlewareMode: true,
391
- compress: false,
392
- cors: false,
393
- publicDir: false
394
- },
395
- dev: {
396
- hmr: false,
397
- writeToDisk
398
- },
399
- environments: Object.fromEntries(context.projects.map((project)=>[
400
- project.environmentName,
401
- {
402
- plugins: project.normalizedConfig.plugins,
403
- root: project.rootPath,
404
- output: {
405
- target: 'node'
406
- }
407
- }
408
- ])),
409
- plugins: [
410
- pluginBasic(context),
411
- pluginIgnoreResolveError,
412
- pluginMockRuntime,
413
- pluginCSSFilter(),
414
- pluginEntryWatch({
415
- globTestSourceEntries,
416
- setupFiles,
417
- context,
418
- isWatch: 'watch' === command
419
- }),
420
- pluginExternal(context),
421
- !isolate ? pluginCacheControl(Object.values(setupFiles).flatMap((files)=>Object.values(files))) : null,
422
- pluginInspect()
423
- ].filter(Boolean)
424
- }
425
- });
426
- if (coverage?.enabled && 'list' !== command) {
427
- const { loadCoverageProvider } = await __webpack_require__.e("603").then(__webpack_require__.bind(__webpack_require__, "./src/coverage/index.ts"));
428
- const { pluginCoverageCore } = await __webpack_require__.e("836").then(__webpack_require__.bind(__webpack_require__, "./src/coverage/plugin.ts"));
429
- const { pluginCoverage } = await loadCoverageProvider(coverage, context.rootPath);
430
- coverage.exclude.push(...Object.values(setupFiles).flatMap((files)=>Object.values(files)));
431
- rsbuildInstance.addPlugins([
432
- pluginCoverage(coverage),
433
- pluginCoverageCore(coverage)
434
- ]);
435
- }
436
- return rsbuildInstance;
437
- };
438
- const calcEntriesToRerun = (entries, chunks, buildData, runtimeChunkName)=>{
439
- const entryToChunkHashesMap = new Map();
440
- const buildChunkHashes = (entry)=>{
441
- const validChunks = (entry.chunks || []).filter((chunk)=>chunk !== runtimeChunkName);
442
- validChunks.forEach((chunkName)=>{
443
- const chunkInfo = chunks?.find((c)=>c.names?.includes(chunkName));
444
- if (chunkInfo) {
445
- const existing = entryToChunkHashesMap.get(entry.testPath) || {};
446
- existing[chunkName] = chunkInfo.hash ?? '';
447
- entryToChunkHashesMap.set(entry.testPath, existing);
448
- }
449
- });
450
- };
451
- (entries || []).forEach(buildChunkHashes);
452
- const entryToChunkHashes = Array.from(entryToChunkHashesMap.entries()).map(([name, chunks])=>({
453
- name,
454
- chunks
455
- }));
456
- const affectedTestPaths = new Set();
457
- const deletedEntries = [];
458
- if (buildData.entryToChunkHashes) {
459
- const prevMap = new Map(buildData.entryToChunkHashes.map((e)=>[
460
- e.name,
461
- e.chunks
462
- ]));
463
- const currentNames = new Set(entryToChunkHashesMap.keys());
464
- deletedEntries.push(...Array.from(prevMap.keys()).filter((name)=>!currentNames.has(name)));
465
- const findAffectedEntry = (testPath)=>{
466
- const currentChunks = entryToChunkHashesMap.get(testPath);
467
- const prevChunks = prevMap.get(testPath);
468
- if (!currentChunks) return;
469
- if (!prevChunks) return void affectedTestPaths.add(testPath);
470
- const hasChanges = Object.entries(currentChunks).some(([chunkName, hash])=>prevChunks[chunkName] !== hash);
471
- if (hasChanges) affectedTestPaths.add(testPath);
472
- };
473
- entryToChunkHashesMap.forEach((_, testPath)=>{
474
- findAffectedEntry(testPath);
475
- });
476
- }
477
- buildData.entryToChunkHashes = entryToChunkHashes;
478
- const affectedEntries = Array.from(affectedTestPaths).map((testPath)=>entries.find((e)=>e.testPath === testPath)).filter((entry)=>void 0 !== entry);
479
- return {
480
- affectedEntries,
481
- deletedEntries
482
- };
483
- };
484
- class AssetsMemorySafeMap extends Map {
485
- set(key, value) {
486
- if (this.has(key)) return this;
487
- if (!(0, memory.i)()) this.clear();
488
- return super.set(key, value);
489
- }
490
- }
491
- const createRsbuildServer = async ({ globTestSourceEntries, setupFiles, rsbuildInstance, inspectedConfig })=>{
492
- let rspackCompiler;
493
- const rstestCompilerPlugin = {
494
- name: 'rstest:compiler',
495
- setup: (api)=>{
496
- api.modifyBundlerChain((chain)=>{
497
- chain.module.rule('rstest-mock-module-doppelgangers').test(/\.(?:js|jsx|mjs|cjs|ts|tsx|mts|cts)$/).with({
498
- rstest: 'importActual'
499
- }).use('import-actual-loader').loader(dist.Ay.resolve(rsbuild_dirname, './importActualLoader.mjs')).end();
500
- });
501
- api.onAfterCreateCompiler(({ compiler })=>{
502
- rspackCompiler = compiler;
503
- });
504
- }
505
- };
506
- rsbuildInstance.addPlugins([
507
- rstestCompilerPlugin
508
- ]);
509
- const devServer = await rsbuildInstance.createDevServer({
510
- getPortSilently: true
511
- });
512
- if ((0, utils._o)()) await rsbuildInstance.inspectConfig({
513
- writeToDisk: true,
514
- extraConfigs: {
515
- rstest: inspectedConfig
516
- }
517
- });
518
- if (!rspackCompiler) throw new Error('rspackCompiler was not initialized');
519
- const outputFileSystem = isMultiCompiler(rspackCompiler) ? rspackCompiler.compilers[0].outputFileSystem : rspackCompiler.outputFileSystem;
520
- if (!outputFileSystem) throw new Error(`Expect outputFileSystem to be defined, but got ${outputFileSystem}`);
521
- const readFile = async (fileName)=>new Promise((resolve, reject)=>{
522
- outputFileSystem.readFile(fileName, (err, data)=>{
523
- if (err) reject(err);
524
- resolve('string' == typeof data ? data : data.toString());
525
- });
526
- });
527
- const buildData = {};
528
- const getEntryFiles = async (manifest, outputPath)=>{
529
- const entryFiles = {};
530
- const entries = Object.keys(manifest.entries);
531
- for (const entry of entries){
532
- const data = manifest.entries[entry];
533
- entryFiles[entry] = ((data?.initial?.js || []).concat(data?.async?.js || []) || []).map((file)=>dist.Ay.join(outputPath, file));
534
- }
535
- return entryFiles;
536
- };
537
- const getRsbuildStats = async ({ environmentName, fileFilters })=>{
538
- const stats = await devServer.environments[environmentName].getStats();
539
- const enableAssetsCache = (0, memory.i)();
540
- const manifest = devServer.environments[environmentName].context.manifest;
541
- const { entrypoints, outputPath, assets, hash, chunks } = stats.toJson({
542
- all: false,
543
- hash: true,
544
- entrypoints: true,
545
- outputPath: true,
546
- assets: true,
547
- relatedAssets: true,
548
- cachedAssets: true,
549
- chunks: true,
550
- timings: true
551
- });
552
- const entryFiles = await getEntryFiles(manifest, outputPath);
553
- const entries = [];
554
- const setupEntries = [];
555
- const sourceEntries = await globTestSourceEntries(environmentName);
556
- for (const entry of Object.keys(entrypoints)){
557
- const e = entrypoints[entry];
558
- const distPath = dist.Ay.join(outputPath, e.assets[e.assets.length - 1].name);
559
- if (setupFiles[environmentName][entry]) setupEntries.push({
560
- distPath,
561
- testPath: setupFiles[environmentName][entry],
562
- files: entryFiles[entry],
563
- chunks: e.chunks || []
564
- });
565
- else if (sourceEntries[entry]) {
566
- if (fileFilters?.length && !fileFilters.includes(sourceEntries[entry])) continue;
567
- entries.push({
568
- distPath,
569
- testPath: sourceEntries[entry],
570
- files: entryFiles[entry],
571
- chunks: e.chunks || []
572
- });
573
- }
574
- }
575
- const inlineSourceMap = 'inline-source-map' === stats.compilation.options.devtool;
576
- const sourceMapPaths = Object.fromEntries(assets.map((asset)=>{
577
- const assetFilePath = dist.Ay.join(outputPath, asset.name);
578
- if (inlineSourceMap) return [
579
- assetFilePath,
580
- assetFilePath
581
- ];
582
- const sourceMapPath = asset?.info.related?.sourceMap?.[0];
583
- if (sourceMapPath) {
584
- const filePath = dist.Ay.join(outputPath, sourceMapPath);
585
- return [
586
- assetFilePath,
587
- filePath
588
- ];
589
- }
590
- return [
591
- assetFilePath,
592
- null
593
- ];
594
- }));
595
- buildData[environmentName] ??= {};
596
- const { affectedEntries, deletedEntries } = calcEntriesToRerun(entries, chunks, buildData[environmentName], `${environmentName}-${RUNTIME_CHUNK_NAME}`);
597
- const cachedAssetFiles = new AssetsMemorySafeMap();
598
- const cachedSourceMaps = new AssetsMemorySafeMap();
599
- const readFileWithCache = async (name)=>{
600
- if (enableAssetsCache && cachedAssetFiles.has(name)) return cachedAssetFiles.get(name);
601
- const content = await readFile(name);
602
- enableAssetsCache && cachedAssetFiles.set(name, content);
603
- return content;
604
- };
605
- const getSourceMap = async (name)=>{
606
- const sourceMapPath = sourceMapPaths[name];
607
- if (!sourceMapPath) return null;
608
- if (enableAssetsCache && cachedSourceMaps.has(name)) return cachedSourceMaps.get(name);
609
- let content = null;
610
- if (inlineSourceMap) {
611
- const file = await readFile(sourceMapPath);
612
- content = parseInlineSourceMapStr(file);
613
- } else {
614
- const sourceMap = await readFile(sourceMapPath);
615
- content = sourceMap;
616
- }
617
- enableAssetsCache && content && cachedSourceMaps.set(name, content);
618
- return content;
619
- };
620
- const assetNames = assets.map((asset)=>dist.Ay.join(outputPath, asset.name));
621
- return {
622
- affectedEntries,
623
- deletedEntries,
624
- hash,
625
- entries,
626
- setupEntries,
627
- assetNames,
628
- getAssetFiles: async (names)=>Object.fromEntries(await Promise.all(names.map(async (name)=>{
629
- const content = await readFileWithCache(name);
630
- return [
631
- name,
632
- content
633
- ];
634
- }))),
635
- getSourceMaps: async (names)=>Object.fromEntries(await Promise.all(names.map(async (name)=>{
636
- const content = await getSourceMap(name);
637
- return [
638
- name,
639
- content
640
- ];
641
- })))
642
- };
643
- };
644
- return {
645
- closeServer: devServer.close,
646
- getRsbuildStats
647
- };
648
- };
649
- },
650
- "./src/pool/index.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
651
- __webpack_require__.d(__webpack_exports__, {
652
- b: ()=>createPool
653
- });
654
- var external_node_os_ = __webpack_require__("node:os");
655
- var pathe_M_eThtNZ = __webpack_require__("../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs");
656
- var utils = __webpack_require__("./src/utils/index.ts");
657
- var memory = __webpack_require__("./src/utils/memory.ts");
658
- var external_node_url_ = __webpack_require__("node:url");
659
- const TYPE_REQUEST = "q";
660
- const TYPE_RESPONSE = "s";
661
- const DEFAULT_TIMEOUT = 6e4;
662
- function defaultSerialize(i) {
663
- return i;
664
- }
665
- const defaultDeserialize = defaultSerialize;
666
- const { clearTimeout: dist_clearTimeout, setTimeout: dist_setTimeout } = globalThis;
667
- const random = Math.random.bind(Math);
668
- function createBirpc(functions, options) {
669
- const { post, on, off = ()=>{}, eventNames = [], serialize = defaultSerialize, deserialize = defaultDeserialize, resolver, bind = "rpc", timeout = DEFAULT_TIMEOUT } = options;
670
- const rpcPromiseMap = /* @__PURE__ */ new Map();
671
- let _promise;
672
- let closed = false;
673
- const rpc = new Proxy({}, {
674
- get (_, method) {
675
- if ("$functions" === method) return functions;
676
- if ("$close" === method) return close;
677
- if ("$rejectPendingCalls" === method) return rejectPendingCalls;
678
- if ("$closed" === method) return closed;
679
- if ("then" === method && !eventNames.includes("then") && !("then" in functions)) return;
680
- const sendEvent = (...args)=>{
681
- post(serialize({
682
- m: method,
683
- a: args,
684
- t: TYPE_REQUEST
685
- }));
686
- };
687
- if (eventNames.includes(method)) {
688
- sendEvent.asEvent = sendEvent;
689
- return sendEvent;
690
- }
691
- const sendCall = async (...args)=>{
692
- if (closed) throw new Error(`[birpc] rpc is closed, cannot call "${method}"`);
693
- if (_promise) try {
694
- await _promise;
695
- } finally{
696
- _promise = void 0;
697
- }
698
- return new Promise((resolve, reject)=>{
699
- const id = nanoid();
700
- let timeoutId;
701
- if (timeout >= 0) {
702
- timeoutId = dist_setTimeout(()=>{
703
- try {
704
- const handleResult = options.onTimeoutError?.(method, args);
705
- if (true !== handleResult) throw new Error(`[birpc] timeout on calling "${method}"`);
706
- } catch (e) {
707
- reject(e);
708
- }
709
- rpcPromiseMap.delete(id);
710
- }, timeout);
711
- if ("object" == typeof timeoutId) timeoutId = timeoutId.unref?.();
712
- }
713
- rpcPromiseMap.set(id, {
714
- resolve,
715
- reject,
716
- timeoutId,
717
- method
718
- });
719
- post(serialize({
720
- m: method,
721
- a: args,
722
- i: id,
723
- t: "q"
724
- }));
725
- });
726
- };
727
- sendCall.asEvent = sendEvent;
728
- return sendCall;
729
- }
730
- });
731
- function close(customError) {
732
- closed = true;
733
- rpcPromiseMap.forEach(({ reject, method })=>{
734
- const error = new Error(`[birpc] rpc is closed, cannot call "${method}"`);
735
- if (customError) {
736
- customError.cause ??= error;
737
- return reject(customError);
738
- }
739
- reject(error);
740
- });
741
- rpcPromiseMap.clear();
742
- off(onMessage);
743
- }
744
- function rejectPendingCalls(handler) {
745
- const entries = Array.from(rpcPromiseMap.values());
746
- const handlerResults = entries.map(({ method, reject })=>{
747
- if (!handler) return reject(new Error(`[birpc]: rejected pending call "${method}".`));
748
- return handler({
749
- method,
750
- reject
751
- });
752
- });
753
- rpcPromiseMap.clear();
754
- return handlerResults;
755
- }
756
- async function onMessage(data, ...extra) {
757
- let msg;
758
- try {
759
- msg = deserialize(data);
760
- } catch (e) {
761
- if (options.onGeneralError?.(e) !== true) throw e;
762
- return;
763
- }
764
- if (msg.t === TYPE_REQUEST) {
765
- const { m: method, a: args } = msg;
766
- let result, error;
767
- const fn = await (resolver ? resolver(method, functions[method]) : functions[method]);
768
- if (fn) try {
769
- result = await fn.apply("rpc" === bind ? rpc : functions, args);
770
- } catch (e) {
771
- error = e;
772
- }
773
- else error = new Error(`[birpc] function "${method}" not found`);
774
- if (msg.i) {
775
- if (error && options.onError) options.onError(error, method, args);
776
- if (error && options.onFunctionError) {
777
- if (true === options.onFunctionError(error, method, args)) return;
778
- }
779
- if (!error) try {
780
- post(serialize({
781
- t: TYPE_RESPONSE,
782
- i: msg.i,
783
- r: result
784
- }), ...extra);
785
- return;
786
- } catch (e) {
787
- error = e;
788
- if (options.onGeneralError?.(e, method, args) !== true) throw e;
789
- }
790
- try {
791
- post(serialize({
792
- t: TYPE_RESPONSE,
793
- i: msg.i,
794
- e: error
795
- }), ...extra);
796
- } catch (e) {
797
- if (options.onGeneralError?.(e, method, args) !== true) throw e;
798
- }
799
- }
800
- } else {
801
- const { i: ack, r: result, e: error } = msg;
802
- const promise = rpcPromiseMap.get(ack);
803
- if (promise) {
804
- dist_clearTimeout(promise.timeoutId);
805
- if (error) promise.reject(error);
806
- else promise.resolve(result);
807
- }
808
- rpcPromiseMap.delete(ack);
809
- }
810
- }
811
- _promise = on(onMessage);
812
- return rpc;
813
- }
814
- const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
815
- function nanoid(size = 21) {
816
- let id = "";
817
- let i = size;
818
- while(i--)id += urlAlphabet[64 * random() | 0];
819
- return id;
820
- }
821
- const forks_filename = (0, external_node_url_.fileURLToPath)(import.meta.url);
822
- const forks_dirname = (0, pathe_M_eThtNZ.d)(forks_filename);
823
- function createChannel(rpcMethods) {
824
- const emitter = new __WEBPACK_EXTERNAL_MODULE_node_events_0a6aefe7__["default"]();
825
- const cleanup = ()=>emitter.removeAllListeners();
826
- const events = {
827
- message: 'message',
828
- response: 'response'
829
- };
830
- const channel = {
831
- onMessage: (callback)=>{
832
- emitter.on(events.message, callback);
833
- },
834
- postMessage: (message)=>{
835
- emitter.emit(events.response, message);
836
- }
837
- };
838
- createBirpc(rpcMethods, {
839
- serialize: __WEBPACK_EXTERNAL_MODULE_node_v8_d0df5498__["default"].serialize,
840
- deserialize: (v)=>__WEBPACK_EXTERNAL_MODULE_node_v8_d0df5498__["default"].deserialize(Buffer.from(v)),
841
- post (v) {
842
- emitter.emit(events.message, v);
843
- },
844
- on (fn) {
845
- emitter.on(events.response, fn);
846
- }
847
- });
848
- return {
849
- channel,
850
- cleanup
851
- };
852
- }
853
- const createForksPool = (poolOptions)=>{
854
- const { maxWorkers: maxThreads, minWorkers: minThreads, env, execArgv = [], isolate = true } = poolOptions;
855
- const options = {
856
- runtime: 'child_process',
857
- filename: (0, pathe_M_eThtNZ.r)(forks_dirname, './worker.js'),
858
- env,
859
- execArgv,
860
- maxThreads,
861
- minThreads,
862
- concurrentTasksPerWorker: 1,
863
- isolateWorkers: isolate
864
- };
865
- const pool = new __WEBPACK_EXTERNAL_MODULE_tinypool__.Tinypool(options);
866
- return {
867
- name: 'forks',
868
- runTest: async ({ options, rpcMethods })=>{
869
- const { channel, cleanup } = createChannel(rpcMethods);
870
- try {
871
- return await pool.run(options, {
872
- channel
873
- });
874
- } finally{
875
- cleanup();
876
- }
877
- },
878
- collectTests: async ({ options, rpcMethods })=>{
879
- const { channel, cleanup } = createChannel(rpcMethods);
880
- try {
881
- return await pool.run(options, {
882
- channel
883
- });
884
- } finally{
885
- cleanup();
886
- }
887
- },
888
- close: ()=>pool.destroy()
889
- };
890
- };
891
- const getNumCpus = ()=>external_node_os_["default"].availableParallelism?.() ?? external_node_os_["default"].cpus().length;
892
- const parseWorkers = (maxWorkers)=>{
893
- const parsed = Number.parseInt(maxWorkers.toString(), 10);
894
- if ('string' == typeof maxWorkers && maxWorkers.trim().endsWith('%')) {
895
- const numCpus = getNumCpus();
896
- const workers = Math.floor(parsed / 100 * numCpus);
897
- return Math.max(workers, 1);
898
- }
899
- return parsed > 0 ? parsed : 1;
900
- };
901
- const getRuntimeConfig = (context)=>{
902
- const { testNamePattern, testTimeout, passWithNoTests, retry, globals, clearMocks, resetMocks, restoreMocks, unstubEnvs, unstubGlobals, maxConcurrency, printConsoleTrace, disableConsoleIntercept, testEnvironment, hookTimeout, isolate, coverage, snapshotFormat, env } = context.normalizedConfig;
903
- return {
904
- env,
905
- testNamePattern,
906
- testTimeout,
907
- hookTimeout,
908
- passWithNoTests,
909
- retry,
910
- globals,
911
- clearMocks,
912
- resetMocks,
913
- restoreMocks,
914
- unstubEnvs,
915
- unstubGlobals,
916
- maxConcurrency,
917
- printConsoleTrace,
918
- disableConsoleIntercept,
919
- testEnvironment,
920
- isolate,
921
- coverage,
922
- snapshotFormat
923
- };
924
- };
925
- const filterAssetsByEntry = async (entryInfo, getAssetFiles, getSourceMaps, setupAssets)=>{
926
- const assetNames = Array.from(new Set([
927
- ...entryInfo.files,
928
- ...setupAssets
929
- ]));
930
- const neededFiles = await getAssetFiles(assetNames);
931
- const neededSourceMaps = await getSourceMaps(assetNames);
932
- return {
933
- assetFiles: neededFiles,
934
- sourceMaps: neededSourceMaps
935
- };
936
- };
937
- const createPool = async ({ context, recommendWorkerCount = 1 / 0 })=>{
938
- const execArgv = process.execArgv.filter((execArg)=>execArg.startsWith('--perf') || execArg.startsWith('--cpu-prof') || execArg.startsWith('--heap-prof') || execArg.startsWith('--diagnostic-dir'));
939
- const numCpus = getNumCpus();
940
- const { normalizedConfig: { pool: poolOptions, isolate }, reporters } = context;
941
- const threadsCount = 'watch' === context.command ? Math.max(Math.floor(numCpus / 2), 1) : Math.max(numCpus - 1, 1);
942
- const recommendCount = 'watch' === context.command ? threadsCount : Math.min(recommendWorkerCount, threadsCount);
943
- const maxWorkers = poolOptions.maxWorkers ? parseWorkers(poolOptions.maxWorkers) : recommendCount;
944
- const minWorkers = poolOptions.minWorkers ? parseWorkers(poolOptions.minWorkers) : maxWorkers < recommendCount ? maxWorkers : recommendCount;
945
- if (maxWorkers < minWorkers) throw `Invalid pool configuration: maxWorkers(${maxWorkers}) cannot be less than minWorkers(${minWorkers}).`;
946
- const pool = createForksPool({
947
- ...poolOptions,
948
- isolate,
949
- maxWorkers,
950
- minWorkers,
951
- execArgv: [
952
- ...poolOptions?.execArgv ?? [],
953
- ...execArgv,
954
- '--experimental-vm-modules',
955
- '--experimental-import-meta-resolve',
956
- '--no-warnings',
957
- (0, utils.C3)() ? '--experimental-detect-module' : void 0
958
- ].filter(Boolean),
959
- env: {
960
- NODE_ENV: 'test',
961
- FORCE_COLOR: '1' === process.env.NO_COLOR ? '0' : '1',
962
- ...process.env
963
- }
964
- });
965
- const rpcMethods = {
966
- onTestCaseResult: async (result)=>{
967
- await Promise.all(reporters.map((reporter)=>reporter.onTestCaseResult?.(result)));
968
- },
969
- onConsoleLog: async (log)=>{
970
- await Promise.all(reporters.map((reporter)=>reporter.onUserConsoleLog?.(log)));
971
- },
972
- onTestFileStart: async (test)=>{
973
- await Promise.all(reporters.map((reporter)=>reporter.onTestFileStart?.(test)));
974
- },
975
- resolveSnapshotPath: (testPath)=>{
976
- const snapExtension = '.snap';
977
- const resolver = context.normalizedConfig.resolveSnapshotPath || (()=>(0, pathe_M_eThtNZ.j)((0, pathe_M_eThtNZ.d)(testPath), '__snapshots__', `${(0, pathe_M_eThtNZ.c)(testPath)}${snapExtension}`));
978
- const snapshotPath = resolver(testPath, snapExtension);
979
- return snapshotPath;
980
- }
981
- };
982
- return {
983
- runTests: async ({ entries, getAssetFiles, getSourceMaps, setupEntries, project, updateSnapshot })=>{
984
- const projectName = context.normalizedConfig.name;
985
- const runtimeConfig = getRuntimeConfig(project);
986
- const setupAssets = setupEntries.flatMap((entry)=>entry.files || []);
987
- const results = await Promise.all(entries.map(async (entryInfo, index)=>{
988
- const result = await pool.runTest({
989
- options: {
990
- entryInfo,
991
- context: {
992
- taskId: index + 1,
993
- project: projectName,
994
- rootPath: context.rootPath,
995
- projectRoot: project.rootPath,
996
- runtimeConfig: (0, utils.Ok)(runtimeConfig)
997
- },
998
- type: 'run',
999
- setupEntries,
1000
- updateSnapshot,
1001
- assets: (0, memory.i)() ? await filterAssetsByEntry(entryInfo, getAssetFiles, getSourceMaps, setupAssets) : void 0
1002
- },
1003
- rpcMethods: {
1004
- ...rpcMethods,
1005
- getAssetsByEntry: async ()=>filterAssetsByEntry(entryInfo, getAssetFiles, getSourceMaps, setupAssets)
1006
- }
1007
- }).catch((err)=>{
1008
- err.fullStack = true;
1009
- return {
1010
- project: projectName,
1011
- testPath: entryInfo.testPath,
1012
- status: 'fail',
1013
- name: '',
1014
- results: [],
1015
- errors: [
1016
- err
1017
- ]
1018
- };
1019
- });
1020
- reporters.map((reporter)=>reporter.onTestFileResult?.(result));
1021
- return result;
1022
- }));
1023
- for (const result of results)if (result.snapshotResult) context.snapshotManager.add(result.snapshotResult);
1024
- const testResults = results.flatMap((r)=>r.results);
1025
- return {
1026
- results,
1027
- testResults,
1028
- project
1029
- };
1030
- },
1031
- collectTests: async ({ entries, getAssetFiles, getSourceMaps, setupEntries, project, updateSnapshot })=>{
1032
- const runtimeConfig = getRuntimeConfig(project);
1033
- const projectName = project.normalizedConfig.name;
1034
- const setupAssets = setupEntries.flatMap((entry)=>entry.files || []);
1035
- return Promise.all(entries.map(async (entryInfo, index)=>pool.collectTests({
1036
- options: {
1037
- entryInfo,
1038
- context: {
1039
- taskId: index + 1,
1040
- project: projectName,
1041
- rootPath: context.rootPath,
1042
- projectRoot: project.rootPath,
1043
- runtimeConfig: (0, utils.Ok)(runtimeConfig)
1044
- },
1045
- type: 'collect',
1046
- setupEntries,
1047
- updateSnapshot,
1048
- assets: (0, memory.i)() ? await filterAssetsByEntry(entryInfo, getAssetFiles, getSourceMaps, setupAssets) : void 0
1049
- },
1050
- rpcMethods: {
1051
- ...rpcMethods,
1052
- getAssetsByEntry: async ()=>filterAssetsByEntry(entryInfo, getAssetFiles, getSourceMaps, setupAssets)
1053
- }
1054
- }).catch((err)=>{
1055
- err.fullStack = true;
1056
- return {
1057
- project: projectName,
1058
- testPath: entryInfo.testPath,
1059
- tests: [],
1060
- errors: [
1061
- err
1062
- ]
1063
- };
1064
- })));
1065
- },
1066
- close: ()=>pool.close()
1067
- };
1068
- };
1069
- },
1070
- "./src/utils/memory.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
1071
- __webpack_require__.d(__webpack_exports__, {
1072
- i: ()=>isMemorySufficient
1073
- });
1074
- var node_process__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("node:process");
1075
- const DefaultMaxHeapSize = 1073741824;
1076
- function isMemorySufficient(options) {
1077
- const { memoryThreshold = 0.7, maxHeapSize = DefaultMaxHeapSize } = options || {};
1078
- if (!node_process__WEBPACK_IMPORTED_MODULE_0__["default"]?.memoryUsage) return true;
1079
- const memoryUsage = node_process__WEBPACK_IMPORTED_MODULE_0__["default"].memoryUsage();
1080
- const heapUsed = memoryUsage.heapUsed;
1081
- const heapTotal = memoryUsage.heapTotal;
1082
- const memoryUsageRatio = heapUsed / heapTotal;
1083
- const isMemorySufficient = memoryUsageRatio < memoryThreshold && heapUsed < maxHeapSize;
1084
- return isMemorySufficient;
1085
- }
1086
- },
1087
- "node:url": function(module) {
1088
- module.exports = __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__;
1089
- }
1090
- };