@rsdoctor/core 2.0.0-alpha.2 → 2.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/26.js +220 -157
  2. package/dist/630.js +28 -17
  3. package/dist/630.js.LICENSE.txt +1 -1
  4. package/dist/build-utils/build/json.d.ts +1 -1
  5. package/dist/build-utils/build/loader/probeLoaderPlugin.d.ts +1 -0
  6. package/dist/build-utils/build/server.d.ts +1 -2
  7. package/dist/index.d.ts +2 -2
  8. package/dist/index.js +405 -164
  9. package/dist/inner-plugins/plugins/bundle.d.ts +1 -1
  10. package/dist/inner-plugins/plugins/errors.d.ts +1 -0
  11. package/dist/inner-plugins/plugins/loader.d.ts +2 -0
  12. package/dist/inner-plugins/plugins/plugins.d.ts +1 -1
  13. package/dist/inner-plugins/plugins/summary.d.ts +3 -2
  14. package/dist/inner-plugins/utils/config.d.ts +3 -1
  15. package/dist/inner-plugins/utils/normalize-config.d.ts +3 -8
  16. package/dist/inner-plugins/utils/ruleWarnings.d.ts +2 -0
  17. package/dist/inner-plugins/utils/sdk.d.ts +2 -1
  18. package/dist/proxy-loader.js +7 -3
  19. package/dist/rspack-plugin/index.d.ts +0 -1
  20. package/dist/rspack-plugin/plugin.d.ts +47 -17
  21. package/dist/rspack-plugin/session.d.ts +19 -0
  22. package/dist/rspack-plugin/writeStore.d.ts +2 -0
  23. package/dist/rule-utils/parser/utils.d.ts +3 -6
  24. package/dist/rules/rules/ecma-version-check/index.d.ts +1 -1
  25. package/dist/sdk/multiple/controller.d.ts +13 -2
  26. package/dist/sdk/multiple/primary.d.ts +14 -6
  27. package/dist/sdk/sdk/core.d.ts +3 -2
  28. package/dist/sdk/sdk/types.d.ts +1 -1
  29. package/dist/sdk/utils/index.d.ts +1 -0
  30. package/dist/sdk/utils/manifestSharding.d.ts +16 -0
  31. package/dist/types/loader.d.ts +5 -0
  32. package/dist/types/plugin.d.ts +0 -8
  33. package/package.json +27 -28
  34. package/dist/rspack-plugin/multiple.d.ts +0 -8
package/dist/index.js CHANGED
@@ -1,7 +1,6 @@
1
- let globalController;
2
- import { createRequire as external_node_module_createRequire } from "node:module";
1
+ import "node:module";
3
2
  import { __webpack_require__ } from "./rslib-runtime.js";
4
- import node_fs, { existsSync } from "node:fs";
3
+ import node_fs from "node:fs";
5
4
  import fs_extra from "fs-extra";
6
5
  import path_0 from "path";
7
6
  import { createRequire } from "module";
@@ -23,11 +22,13 @@ import node_path, { join, dirname as __rspack_dirname } from "node:path";
23
22
  import { promisify } from "node:util";
24
23
  import { randomBytes } from "crypto";
25
24
  import raw_body from "raw-body";
26
- import { createBrotliDecompress, createGunzip, createInflate } from "node:zlib";
25
+ import { createBrotliDecompress, createDeflate, createGunzip, createInflate } from "node:zlib";
27
26
  import node_process from "node:process";
28
27
  import { AsyncSeriesHook } from "@rspack/lite-tapable";
29
- import { setSDK, logger as rsdoctorLogger, logger_time, timeEnd, color, stringify } from "./630.js";
30
- import { InternalResolverPlugin, getYarnVersion, InternalPluginsPlugin, normalizeUserConfig, getRspackNativePlugin, InternalSummaryPlugin, InternalBundlePlugin, getNpmVersion, ensureModulesChunksGraphFn, getNodeVersion, fs_extra as external_fs_extra_fs_extra, handleBriefModeReport, processCompilerConfig, InternalLoaderPlugin, getCPUInfo, defaultPort, getPnpmVersion, FileSharding, createServer, getMemoryInfo, normalizeRspackUserOptions, defaultHost, InternalErrorReporterPlugin, getPortSync, InternalRulesPlugin, DevToolError, ProbeLoaderPlugin } from "./26.js";
28
+ import node_fs_promises from "node:fs/promises";
29
+ import { Readable } from "node:stream";
30
+ import { setSDK, logger as rsdoctorLogger, logger_time, timeEnd, color, stringify, registerSDK } from "./630.js";
31
+ import { InternalResolverPlugin, getYarnVersion, InternalPluginsPlugin, getRspackNativePlugin, InternalSummaryPlugin, ensureModulesChunksGraphFn, getNpmVersion, InternalBundlePlugin, isCompilerWatching, getNodeVersion, fs_extra as external_fs_extra_fs_extra, handleBriefModeReport, processCompilerConfig, InternalLoaderPlugin, normalizeRspackUserOptions, defaultPort, getCPUInfo, getPnpmVersion, createServer, getMemoryInfo, InternalErrorReporterPlugin, defaultHost, ProbeLoaderPlugin, getPortSync, InternalRulesPlugin, DevToolError } from "./26.js";
31
32
  import { fileURLToPath as __rspack_fileURLToPath } from "node:url";
32
33
  var date, __rspack_import_meta_dirname__ = __rspack_dirname(__rspack_fileURLToPath(import.meta.url)), apis_namespaceObject = {};
33
34
  __webpack_require__.r(apis_namespaceObject), __webpack_require__.d(apis_namespaceObject, {
@@ -278,8 +279,8 @@ class BaseAPI {
278
279
  return key.includes('.') && (res = key.split('.').reduce((t, k)=>t[k], data)), res;
279
280
  }
280
281
  }
281
- function _ts_metadata(k, v) {
282
- if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
282
+ function _ts_metadata(metadataKey, metadataValue) {
283
+ if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(metadataKey, metadataValue);
283
284
  }
284
285
  class AlertsAPI extends BaseAPI {
285
286
  async getPackageRelationAlertDetails() {
@@ -296,8 +297,8 @@ function bundle_diff_ts_decorate(decorators, target, key, desc) {
296
297
  else for(var i = decorators.length - 1; i >= 0; i--)(d = decorators[i]) && (r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r);
297
298
  return c > 3 && r && Object.defineProperty(target, key, r), r;
298
299
  }
299
- function bundle_diff_ts_metadata(k, v) {
300
- if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
300
+ function bundle_diff_ts_metadata(metadataKey, metadataValue) {
301
+ if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(metadataKey, metadataValue);
301
302
  }
302
303
  !function(decorators, target, key, desc) {
303
304
  var d, c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc;
@@ -336,8 +337,8 @@ function data_ts_decorate(decorators, target, key, desc) {
336
337
  else for(var i = decorators.length - 1; i >= 0; i--)(d = decorators[i]) && (r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r);
337
338
  return c > 3 && r && Object.defineProperty(target, key, r), r;
338
339
  }
339
- function data_ts_metadata(k, v) {
340
- if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
340
+ function data_ts_metadata(metadataKey, metadataValue) {
341
+ if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(metadataKey, metadataValue);
341
342
  }
342
343
  bundle_diff_ts_decorate([
343
344
  Router.get(SDK.ServerAPI.API.GetBundleDiffSummary),
@@ -361,8 +362,8 @@ class DataAPI extends BaseAPI {
361
362
  await server.sendAPIDataToClient(api, data);
362
363
  }
363
364
  }
364
- function fs_ts_metadata(k, v) {
365
- if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
365
+ function fs_ts_metadata(metadataKey, metadataValue) {
366
+ if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(metadataKey, metadataValue);
366
367
  }
367
368
  data_ts_decorate([
368
369
  Router.post(SDK.ServerAPI.API.LoadDataByKey),
@@ -387,8 +388,8 @@ function loader_ts_decorate(decorators, target, key, desc) {
387
388
  else for(var i = decorators.length - 1; i >= 0; i--)(d = decorators[i]) && (r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r);
388
389
  return c > 3 && r && Object.defineProperty(target, key, r), r;
389
390
  }
390
- function loader_ts_metadata(k, v) {
391
- if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
391
+ function loader_ts_metadata(metadataKey, metadataValue) {
392
+ if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(metadataKey, metadataValue);
392
393
  }
393
394
  !function(decorators, target, key, desc) {
394
395
  var d, c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc;
@@ -438,11 +439,12 @@ class LoaderAPI extends BaseAPI {
438
439
  });
439
440
  }
440
441
  async getLoaderFileInputAndOutput() {
441
- let { req } = this.ctx, { file, loader, loaderIndex } = req.body;
442
+ let { req } = this.ctx, { file, loader, loaderIndex, isPitch } = req.body;
442
443
  return this.dataLoader.loadAPI(SDK.ServerAPI.API.GetLoaderFileInputAndOutput, {
443
444
  file,
444
445
  loader,
445
- loaderIndex
446
+ loaderIndex,
447
+ isPitch
446
448
  });
447
449
  }
448
450
  }
@@ -452,8 +454,8 @@ function graph_ts_decorate(decorators, target, key, desc) {
452
454
  else for(var i = decorators.length - 1; i >= 0; i--)(d = decorators[i]) && (r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r);
453
455
  return c > 3 && r && Object.defineProperty(target, key, r), r;
454
456
  }
455
- function graph_ts_metadata(k, v) {
456
- if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
457
+ function graph_ts_metadata(metadataKey, metadataValue) {
458
+ if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(metadataKey, metadataValue);
457
459
  }
458
460
  loader_ts_decorate([
459
461
  Router.post(SDK.ServerAPI.API.ReportLoader),
@@ -554,8 +556,8 @@ function plugin_ts_decorate(decorators, target, key, desc) {
554
556
  else for(var i = decorators.length - 1; i >= 0; i--)(d = decorators[i]) && (r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r);
555
557
  return c > 3 && r && Object.defineProperty(target, key, r), r;
556
558
  }
557
- function plugin_ts_metadata(k, v) {
558
- if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
559
+ function plugin_ts_metadata(metadataKey, metadataValue) {
560
+ if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(metadataKey, metadataValue);
559
561
  }
560
562
  graph_ts_decorate([
561
563
  Router.post(SDK.ServerAPI.API.GetAssetsSummary),
@@ -616,8 +618,8 @@ function project_ts_decorate(decorators, target, key, desc) {
616
618
  else for(var i = decorators.length - 1; i >= 0; i--)(d = decorators[i]) && (r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r);
617
619
  return c > 3 && r && Object.defineProperty(target, key, r), r;
618
620
  }
619
- function project_ts_metadata(k, v) {
620
- if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
621
+ function project_ts_metadata(metadataKey, metadataValue) {
622
+ if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(metadataKey, metadataValue);
621
623
  }
622
624
  plugin_ts_decorate([
623
625
  Router.post(SDK.ServerAPI.API.GetPluginSummary),
@@ -652,8 +654,8 @@ class ProjectAPI extends BaseAPI {
652
654
  return this.dataLoader.loadAPI(SDK.ServerAPI.API.GetClientRoutes);
653
655
  }
654
656
  }
655
- function renderer_ts_metadata(k, v) {
656
- if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
657
+ function renderer_ts_metadata(metadataKey, metadataValue) {
658
+ if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(metadataKey, metadataValue);
657
659
  }
658
660
  project_ts_decorate([
659
661
  Router.get(SDK.ServerAPI.API.Env),
@@ -689,8 +691,8 @@ function resolver_ts_decorate(decorators, target, key, desc) {
689
691
  else for(var i = decorators.length - 1; i >= 0; i--)(d = decorators[i]) && (r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r);
690
692
  return c > 3 && r && Object.defineProperty(target, key, r), r;
691
693
  }
692
- function resolver_ts_metadata(k, v) {
693
- if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
694
+ function resolver_ts_metadata(metadataKey, metadataValue) {
695
+ if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(metadataKey, metadataValue);
694
696
  }
695
697
  !function(decorators, target, key, desc) {
696
698
  var d, c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc;
@@ -1059,7 +1061,7 @@ class RsdoctorServer {
1059
1061
  }
1060
1062
  async openClientPage(...args) {
1061
1063
  let relativeUrl = this.getClientUrl(...args), needEncodeURI = args[0] === Client.RsdoctorClientRoutes.BundleDiff, url = `http://${this.host}:${this.port}${relativeUrl}`, localhostUrl = `http://localhost:${this.port}${relativeUrl}`;
1062
- await openBrowser(localhostUrl, !needEncodeURI), this._printServerUrl && rsdoctorLogger.info(`${color.green(`${this.sdk.name} compiler's`)} analyzer running on: ${color.cyan(url)}`);
1064
+ await openBrowser(localhostUrl, !needEncodeURI), this._printServerUrl && rsdoctorLogger.info(`Analyzer running on: ${color.cyan(url)}`);
1063
1065
  }
1064
1066
  sendAPIDataToClient(api, msg) {
1065
1067
  this._socket?.sendAPIData(api, msg);
@@ -1085,6 +1087,41 @@ function findRoot(startDir = process.cwd()) {
1085
1087
  }
1086
1088
  return firstPkgDir || null;
1087
1089
  }
1090
+ async function writeManifestShards(jsonFragments, folder, options = {}) {
1091
+ if (0 === jsonFragments.length) throw Error('Cannot write empty JSON fragments.');
1092
+ let { index = 0, shardSize = 10485760, compressionLevel } = options;
1093
+ if (!Number.isSafeInteger(shardSize) || shardSize <= 0) throw Error('Manifest shard size must be a positive integer.');
1094
+ if (void 0 !== compressionLevel && (!Number.isInteger(compressionLevel) || compressionLevel < 0 || compressionLevel > 9)) throw RangeError('`compressionLevel` must be an integer between 0 and 9.');
1095
+ await node_fs_promises.mkdir(folder, {
1096
+ recursive: !0
1097
+ });
1098
+ let files = [], shardParts = [], shardLength = 0, flushShard = async ()=>{
1099
+ if (0 === shardLength) return;
1100
+ let basename = String(index + files.length), filePath = node_path.resolve(folder, basename);
1101
+ await node_fs_promises.writeFile(filePath, shardParts.join(''), 'utf8'), files.push({
1102
+ path: filePath,
1103
+ basename
1104
+ }), shardParts = [], shardLength = 0;
1105
+ }, appendEncodedText = async (encodedText)=>{
1106
+ let offset = 0;
1107
+ for(; offset < encodedText.length;){
1108
+ let length = Math.min(shardSize - shardLength, encodedText.length - offset);
1109
+ shardParts.push(encodedText.slice(offset, offset + length)), shardLength += length, offset += length, shardLength === shardSize && await flushShard();
1110
+ }
1111
+ }, compressor = Readable.from(jsonFragments, {
1112
+ objectMode: !1
1113
+ }).pipe(createDeflate(void 0 === compressionLevel ? void 0 : {
1114
+ level: compressionLevel
1115
+ })), base64Remainder = Buffer.alloc(0);
1116
+ for await (let chunk of compressor){
1117
+ let compressedChunk = Buffer.from(chunk), bytes = base64Remainder.length ? Buffer.concat([
1118
+ base64Remainder,
1119
+ compressedChunk
1120
+ ]) : compressedChunk, encodableLength = bytes.length - bytes.length % 3;
1121
+ encodableLength > 0 && await appendEncodedText(bytes.subarray(0, encodableLength).toString('base64')), base64Remainder = Buffer.from(bytes.subarray(encodableLength));
1122
+ }
1123
+ return base64Remainder.length > 0 && await appendEncodedText(base64Remainder.toString('base64')), await flushShard(), files;
1124
+ }
1088
1125
  String((date = new Date()).getMonth() + 1).padStart(2, '0'), String(date.getDate()).padStart(2, '0'), date.getFullYear();
1089
1126
  class SDKCore {
1090
1127
  constructor({ name, root }){
@@ -1151,10 +1188,10 @@ class SDKCore {
1151
1188
  this._clientRoutes.add(route);
1152
1189
  }), this.onDataReport();
1153
1190
  }
1154
- async writePieces(storeData, _options) {
1191
+ async writePieces(storeData, options) {
1155
1192
  let { outputDir } = this, manifest = node_path.resolve(outputDir, Constants.RsdoctorOutputManifest);
1156
1193
  this.diskManifestPath = manifest, await external_fs_extra_fs_extra.ensureDir(outputDir);
1157
- let urlsPromiseList = [];
1194
+ let urlsPromiseList = [], compressionLevel = options?.compressionLevel;
1158
1195
  for (let key of Object.keys(storeData)){
1159
1196
  let data = storeData[key];
1160
1197
  if ('object' != typeof data) {
@@ -1172,20 +1209,21 @@ class SDKCore {
1172
1209
  return stringify(data);
1173
1210
  }
1174
1211
  })();
1175
- if (Array.isArray(jsonStr)) {
1176
- let fileOffset = 0;
1177
- for (let str of jsonStr){
1178
- let result = await this.writeToFolder(str, outputDir, key, fileOffset);
1179
- fileOffset += result.files.length, urlsPromiseList.push(result);
1180
- }
1181
- } else urlsPromiseList.push(this.writeToFolder(jsonStr, outputDir, key));
1212
+ Array.isArray(jsonStr) ? urlsPromiseList.push(this.writeJsonFragmentsToFolder(jsonStr, outputDir, key, void 0, compressionLevel)) : urlsPromiseList.push(this.writeToFolder(jsonStr, outputDir, key, void 0, compressionLevel));
1182
1213
  }
1183
1214
  let dataUrls = await Promise.all(urlsPromiseList);
1184
1215
  rsdoctorLogger.debug(`SDKCore.writePieces extraConfig: ${JSON.stringify(this.extraConfig)}`, '[SDKCore.writePieces]'), this.cloudData = {
1185
1216
  client: {
1186
1217
  enableRoutes: this.getClientRoutes()
1187
1218
  },
1188
- data: dataUrls.reduce((t, item)=>(t[item.name] = Array.isArray(item.files) ? item.files.map((e)=>e.path).concat(t[item.name] || []) : item.files, t), {})
1219
+ data: dataUrls.reduce((t, item)=>{
1220
+ if (!Array.isArray(item.files)) return t[item.name] = item.files, t;
1221
+ let previous = t[item.name];
1222
+ return t[item.name] = [
1223
+ ...Array.isArray(previous) ? previous : [],
1224
+ ...item.files.map((e)=>e.path)
1225
+ ], t;
1226
+ }, {})
1189
1227
  };
1190
1228
  }
1191
1229
  async writeManifest() {
@@ -1202,16 +1240,21 @@ class SDKCore {
1202
1240
  manifestDiskPath
1203
1241
  }), manifestDiskPath;
1204
1242
  }
1205
- writeToFolder(jsonStr, dir, key, index) {
1206
- let sharding = new FileSharding(Algorithm.compressText(jsonStr)), folder = node_path.resolve(dir, key);
1207
- return sharding.writeStringToFolder(folder, '', index).then((item)=>({
1208
- name: key,
1209
- files: item.map((el)=>({
1210
- path: node_path.resolve(folder, el.filename),
1211
- basename: el.filename,
1212
- content: el.content
1213
- }))
1214
- }));
1243
+ writeToFolder(jsonStr, dir, key, index, compressionLevel) {
1244
+ return this.writeJsonFragmentsToFolder([
1245
+ jsonStr
1246
+ ], dir, key, index, compressionLevel);
1247
+ }
1248
+ async writeJsonFragmentsToFolder(jsonFragments, dir, key, index, compressionLevel) {
1249
+ if (0 === jsonFragments.length) throw Error(`Cannot write empty JSON fragments for "${key}".`);
1250
+ let folder = node_path.resolve(dir, key);
1251
+ return {
1252
+ name: key,
1253
+ files: await writeManifestShards(jsonFragments, folder, {
1254
+ index,
1255
+ compressionLevel
1256
+ })
1257
+ };
1215
1258
  }
1216
1259
  }
1217
1260
  let client_require = createRequire(import.meta.url), resolveClientDiffHtmlPath = (innerClientPath)=>{
@@ -1290,10 +1333,13 @@ class RsdoctorSDK extends SDKCore {
1290
1333
  let _builtinLoader = data.loaders[0];
1291
1334
  if (_builtinLoader.startAt) this._loaderStart.push(data);
1292
1335
  else if (_builtinLoader.endAt) {
1293
- let matchLoaderStart = this._loaderStart.find((e)=>e.resource.path === data.resource.path && e.loaders[0].loader === _builtinLoader.loader);
1294
- matchLoaderStart && (matchLoaderStart.loaders[0].result = _builtinLoader.result, matchLoaderStart.loaders[0].endAt = _builtinLoader.endAt, this.reportLoader([
1295
- matchLoaderStart
1296
- ]));
1336
+ let matchLoaderStartIndex = this._loaderStart.findIndex((e)=>e.resource.path === data.resource.path && e.resource.queryRaw === data.resource.queryRaw && e.loaders[0].loader === _builtinLoader.loader && e.loaders[0].loaderIndex === _builtinLoader.loaderIndex && e.loaders[0].isPitch === _builtinLoader.isPitch && e.loaders[0].pid === _builtinLoader.pid);
1337
+ if (-1 !== matchLoaderStartIndex) {
1338
+ let [matchLoaderStart] = this._loaderStart.splice(matchLoaderStartIndex, 1);
1339
+ matchLoaderStart.loaders[0].result = _builtinLoader.result, matchLoaderStart.loaders[0].endAt = _builtinLoader.endAt, this.reportLoader([
1340
+ matchLoaderStart
1341
+ ]);
1342
+ }
1297
1343
  }
1298
1344
  }
1299
1345
  reportResolver(data) {
@@ -1377,8 +1423,7 @@ class RsdoctorSDK extends SDKCore {
1377
1423
  return ctx.pid;
1378
1424
  },
1379
1425
  get errors () {
1380
- if (isJsonType && sections && !sections.rules) return [];
1381
- return ctx._errors.map((err)=>err.toData());
1426
+ return isJsonType && sections && !sections.rules ? [] : ctx._errors.map((err)=>err.toData());
1382
1427
  },
1383
1428
  get configs () {
1384
1429
  return ctx._configs.slice();
@@ -1395,7 +1440,7 @@ class RsdoctorSDK extends SDKCore {
1395
1440
  return ctx._loader.slice();
1396
1441
  },
1397
1442
  get moduleGraph () {
1398
- if (isJsonType && sections && !sections.moduleGraph) return {
1443
+ return isJsonType && sections && !sections.moduleGraph ? {
1399
1444
  dependencies: [],
1400
1445
  modules: [],
1401
1446
  moduleGraphModules: [],
@@ -1403,23 +1448,20 @@ class RsdoctorSDK extends SDKCore {
1403
1448
  sideEffects: [],
1404
1449
  variables: [],
1405
1450
  layers: []
1406
- };
1407
- return ctx._moduleGraph.toData({
1451
+ } : ctx._moduleGraph.toData({
1408
1452
  contextPath: ctx._configs?.[0]?.config?.context || '',
1409
1453
  briefOptions
1410
1454
  });
1411
1455
  },
1412
1456
  get chunkGraph () {
1413
- if (isJsonType && sections && !sections.chunkGraph) return {
1457
+ return isJsonType && sections && !sections.chunkGraph ? {
1414
1458
  assets: [],
1415
1459
  chunks: [],
1416
1460
  entrypoints: []
1417
- };
1418
- return ctx._chunkGraph.toData(ctx.type);
1461
+ } : ctx._chunkGraph.toData(ctx.type);
1419
1462
  },
1420
1463
  get moduleCodeMap () {
1421
- if (ctx.extraConfig?.mode === SDK.IMode[SDK.IMode.brief]) return {};
1422
- return ctx._moduleGraph.toCodeData(ctx.type);
1464
+ return ctx.extraConfig?.mode === SDK.IMode[SDK.IMode.brief] ? {} : ctx._moduleGraph.toCodeData(ctx.type);
1423
1465
  },
1424
1466
  get plugin () {
1425
1467
  return {
@@ -1433,8 +1475,7 @@ class RsdoctorSDK extends SDKCore {
1433
1475
  };
1434
1476
  },
1435
1477
  get treeShaking () {
1436
- if (ctx.extraConfig?.mode === SDK.IMode[SDK.IMode.brief] || !ctx.extraConfig?.features?.treeShaking) return;
1437
- return ctx._moduleGraph.toTreeShakingData();
1478
+ if (ctx.extraConfig?.mode !== SDK.IMode[SDK.IMode.brief] && ctx.extraConfig?.features?.treeShaking) return ctx._moduleGraph.toTreeShakingData();
1438
1479
  },
1439
1480
  get otherReports () {
1440
1481
  return {
@@ -1532,157 +1573,277 @@ class RsdoctorSlaveServer extends RsdoctorServer {
1532
1573
  }
1533
1574
  let primary_id = 1;
1534
1575
  class RsdoctorPrimarySDK extends RsdoctorSDK {
1535
- constructor({ name, stage, controller, extraConfig, type }){
1576
+ constructor({ name, displayName, compilerPath, parentCompilerPath, isChild, stage, controller, extraConfig, type }){
1536
1577
  super({
1537
1578
  name,
1538
1579
  root: controller.root,
1539
1580
  config: extraConfig
1540
- });
1581
+ }), this.reportFileName = '';
1541
1582
  let lastSdk = controller.getLastSdk(), port = lastSdk ? lastSdk.server.port + 1 : extraConfig?.server?.port ?? this.server.port;
1542
- this.id = primary_id++, this.stage = 'number' == typeof stage ? stage : 1, this.extraConfig = extraConfig, this.parent = controller, this.server = new RsdoctorSlaveServer(this, port, {
1583
+ this.id = primary_id++, this.stage = 'number' == typeof stage ? stage : 1, this.displayName = displayName || name, this.compilerPath = compilerPath || '', this.parentCompilerPath = parentCompilerPath, this.isChild = !!isChild, this.extraConfig = extraConfig, this.parent = controller, lastSdk && (this.server = new RsdoctorSlaveServer(this, port, {
1543
1584
  cors: extraConfig?.server?.cors
1544
- }), this.type = type, this.setName(name), this.clearSwitch();
1545
- }
1546
- clearSwitch() {
1547
- this.uploadPieces = new Promise((resolve)=>{
1548
- this.finishUploadPieceSwitch = resolve;
1549
- });
1585
+ })), this.type = type, this.setName(name);
1550
1586
  }
1551
1587
  get isMaster() {
1552
1588
  return this.parent.master === this;
1553
1589
  }
1554
- async writePieces() {
1555
- let { name, parent, isMaster, outputDir, finishUploadPieceSwitch } = this;
1556
- this.setOutputDir(isMaster ? outputDir : path_0.join(parent.master.outputDir, '.slaves', name.replace(/\s+/g, '-'))), await super.writePieces(this.getStoreData()), finishUploadPieceSwitch?.();
1590
+ async writePieces(_storeData, options) {
1591
+ this.setOutputDir(this.parent.getCompilerOutputDir(this)), await super.writePieces(this.getStoreData(), options);
1557
1592
  }
1558
1593
  async writeManifest() {
1559
- let { parent, cloudData, dependencies } = this;
1560
- dependencies?.length || await Promise.all(this.parent.slaves.filter((item)=>!item.dependencies?.length).map((item)=>item.uploadPieces)), cloudData && (cloudData.name = this.name, cloudData.series = parent.getSeriesData());
1594
+ let { parent, cloudData } = this;
1595
+ cloudData && parent.isMultiple && (cloudData.name = this.name, cloudData.series = parent.getSeriesData());
1561
1596
  let result = await super.writeManifest();
1562
- return this.clearSwitch(), result;
1597
+ return await parent.refreshManifestSeries(), result;
1598
+ }
1599
+ async refreshManifestSeries() {
1600
+ this.parent.isMultiple && this.cloudData && this.diskManifestPath && (this.cloudData.name = this.name, this.cloudData.series = this.parent.getSeriesData(), await super.writeManifest());
1563
1601
  }
1564
1602
  getSeriesData(serverUrl = !1) {
1565
1603
  return this.parent.getSeriesData(serverUrl);
1566
1604
  }
1567
1605
  setName(name) {
1568
- this._name = this.parent.hasName(name) ? `${name}-${primary_id}` : name;
1606
+ let baseName = name || `compiler-${this.id}`;
1607
+ if (!this.parent.hasName(baseName, this)) {
1608
+ this._name = baseName;
1609
+ return;
1610
+ }
1611
+ let suffix = 2;
1612
+ for(; this.parent.hasName(`${baseName}-${suffix}`, this);)suffix += 1;
1613
+ this._name = `${baseName}-${suffix}`;
1569
1614
  }
1570
1615
  getManifestData() {
1571
1616
  let data = super.getManifestData();
1572
- return data.name = this.name, data.series = this.getSeriesData(!0), data;
1617
+ return this.parent.isMultiple && (data.name = this.name, data.series = this.getSeriesData(!0)), data;
1618
+ }
1619
+ addRsdoctorDataToHTML(storeData, htmlContent) {
1620
+ let result = super.addRsdoctorDataToHTML(storeData, htmlContent);
1621
+ if (!this.parent.isMultiple) return result;
1622
+ let metadata = `<script>window.${Constants.WINDOW_RSDOCTOR_TAG}.name=${JSON.stringify(this.name)};window.${Constants.WINDOW_RSDOCTOR_TAG}.series=${JSON.stringify(this.parent.getBriefSeriesData(this))}</script>`;
1623
+ return result.replace('</body>', `${metadata}</body>`);
1573
1624
  }
1574
1625
  }
1575
1626
  class RsdoctorSDKController {
1576
1627
  constructor(root = process.cwd()){
1577
- this.slaves = [], this.root = '', this.root = root;
1628
+ this.slaves = [], this.activeSlaves = new Set(), this.outputDir = '', this.refreshManifestTask = Promise.resolve(), this.root = '', this.root = root;
1578
1629
  }
1579
1630
  get master() {
1580
- return this.slaves[0];
1631
+ return this.getActiveSlaves()[0];
1632
+ }
1633
+ get isMultiple() {
1634
+ return this.activeSlaves.size > 1;
1581
1635
  }
1582
1636
  getLastSdk() {
1583
1637
  return this.slaves[this.slaves.length - 1];
1584
1638
  }
1585
- hasName(name) {
1586
- return !!this.slaves.find((item)=>item.name === name);
1639
+ hasName(name, exclude) {
1640
+ return !!this.slaves.find((item)=>item !== exclude && item.name === name);
1641
+ }
1642
+ registerSlave(slave) {
1643
+ this.activeSlaves.add(slave);
1644
+ }
1645
+ setOutputDir(slave, outputDir) {
1646
+ slave === this.master && slave !== this.outputOwner && (this.outputDir = outputDir, this.outputOwner = slave, slave.setOutputDir(outputDir));
1647
+ }
1648
+ getCompilerOutputDir(slave) {
1649
+ if (slave === this.master) return this.outputDir || slave.outputDir;
1650
+ let rootOutputDir = this.outputDir || this.master?.outputDir || slave.outputDir;
1651
+ if (slave.isChild) return node_path.join(rootOutputDir, '.slaves', slave.name.replace(/\s+/g, '-'));
1652
+ let name = slave.name.replace(/[^a-zA-Z0-9_$-]+/g, '-').replace(/^-+|-+$/g, '') || `compiler-${slave.id}`;
1653
+ return node_path.join(rootOutputDir, 'compilers', name);
1587
1654
  }
1588
1655
  getSeriesData(serverUrl = !1) {
1589
- return this.slaves.map((item)=>{
1656
+ return this.getActiveSlaves().map((item)=>{
1590
1657
  let data = {
1591
1658
  name: item.name,
1592
- path: item.diskManifestPath,
1593
- stage: item.stage
1659
+ displayName: item.displayName,
1660
+ path: item.reportFileName ? node_path.join(this.getCompilerOutputDir(item), item.reportFileName) : item.diskManifestPath || node_path.resolve(this.getCompilerOutputDir(item), Constants.RsdoctorOutputManifest),
1661
+ stage: item.stage,
1662
+ compilerPath: item.compilerPath,
1663
+ parentCompilerPath: item.parentCompilerPath,
1664
+ isChild: item.isChild
1594
1665
  };
1595
1666
  return serverUrl && (data.origin = item.server.origin), data;
1596
1667
  });
1597
1668
  }
1598
- createSlave({ name, stage, extraConfig, type }) {
1669
+ getBriefSeriesData(current) {
1670
+ let currentOutputDir = this.getCompilerOutputDir(current);
1671
+ return this.getActiveSlaves().map((item)=>({
1672
+ name: item.name,
1673
+ path: node_path.relative(currentOutputDir, node_path.join(this.getCompilerOutputDir(item), item.reportFileName || 'rsdoctor-report.html')).split(node_path.sep).map((segment)=>encodeURIComponent(segment)).join('/'),
1674
+ stage: item.stage
1675
+ }));
1676
+ }
1677
+ createSlave({ name, displayName, compilerPath, parentCompilerPath, isChild, stage, extraConfig, type }) {
1599
1678
  let slave = new RsdoctorPrimarySDK({
1600
1679
  name,
1601
- stage,
1680
+ displayName,
1681
+ compilerPath,
1682
+ parentCompilerPath,
1683
+ isChild,
1684
+ stage: 'number' == typeof stage ? stage : this.slaves.length,
1602
1685
  controller: this,
1603
1686
  extraConfig,
1604
1687
  type
1605
1688
  });
1606
1689
  return this.slaves.push(slave), this.slaves.sort((a, b)=>a.stage - b.stage), slave;
1607
1690
  }
1691
+ refreshManifestSeries() {
1692
+ return this.isMultiple ? (this.refreshManifestTask = this.refreshManifestTask.then(async ()=>{
1693
+ for (let slave of this.getActiveSlaves())await slave.refreshManifestSeries();
1694
+ }), this.refreshManifestTask) : Promise.resolve();
1695
+ }
1696
+ getActiveSlaves() {
1697
+ return this.slaves.filter((item)=>this.activeSlaves.has(item));
1698
+ }
1608
1699
  }
1609
- let packageJson = external_node_module_createRequire(import.meta.url)(existsSync(new URL('../package.json', import.meta.url)) ? '../package.json' : '../../package.json'), pluginTapName = 'RsdoctorRspackPlugin', pluginTapPostOptions = {
1700
+ var package_namespaceObject = JSON.parse('{"name":"@rsdoctor/core","version":"2.0.0-beta.1","repository":{"type":"git","url":"https://github.com/web-infra-dev/rsdoctor","directory":"packages/core"},"license":"MIT","type":"module","exports":{".":{"types":"./dist/index.d.ts","default":"./dist/index.js"},"./proxy-loader":{"types":"./dist/proxy-loader.d.ts","default":"./dist/proxy-loader.js"}},"main":"dist/index.js","types":"dist/index.d.ts","typesVersions":{"*":{".":["./dist/index.d.ts"],"proxy-loader":["./dist/proxy-loader.d.ts"]}},"files":["dist","static"],"scripts":{"build":"rs lib","dev":"npm run start","start":"rs lib -w","test":"rs test"},"dependencies":{"@babel/code-frame":"7.26.2","@rsdoctor/client":"workspace:*","@rsdoctor/shared":"workspace:*","@rspack/lite-tapable":"catalog:","@types/estree":"catalog:","acorn":"^8.10.0","acorn-import-attributes":"^1.9.5","acorn-walk":"8.3.5","browserslist-load-config":"^1.0.3","caniuse-lite":"^1.0.30001810","connect-next":"catalog:","cors":"2.8.6","envinfo":"7.21.0","fs-extra":"catalog:","get-port":"5.1.1","launch-editor":"^2.14.1","lines-and-columns":"2.0.4","open":"^11.0.2","raw-body":"3.0.2","rslog":"^2.1.3","semver":"^7.8.5","sirv":"catalog:","source-map":"catalog:","ws":"8.21.3"},"devDependencies":{"@rsbuild/plugin-check-syntax":"catalog:","@rspack/core":"catalog:","@scripts/test-helper":"workspace:*","@types/babel__code-frame":"7.27.0","@types/cors":"2.8.19","@types/envinfo":"7.8.4","@types/fs-extra":"catalog:","@types/node":"catalog:","@types/semver":"^7.8.0","@types/ws":"^8.18.1","babel-loader":"10.1.1","filesize":"catalog:","json-stream-stringify":"3.0.1","string-loader":"0.0.1","ts-loader":"^9.6.2","tslib":"catalog:","typescript":"catalog:"},"peerDependencies":{"@rspack/core":"^2.0.0"},"peerDependenciesMeta":{"@rspack/core":{"optional":true}},"engines":{"node":">=22.18.0"},"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"}}');
1701
+ let pluginTapName = 'RsdoctorRspackPlugin', pluginTapPostOptions = {
1610
1702
  name: pluginTapName,
1611
1703
  stage: 999
1612
- }, hasGreeted = !1;
1704
+ }, pendingSessions = new Map(), watchWriteStoreOptions = {
1705
+ compressionLevel: 1
1706
+ };
1707
+ function getWriteStoreOptions(compiler) {
1708
+ return isCompilerWatching(compiler) ? watchWriteStoreOptions : void 0;
1709
+ }
1710
+ let hasGreeted = !1;
1711
+ class RsdoctorCompilerContext {
1712
+ constructor(sdk, options){
1713
+ this.sdk = sdk, this.options = options, this.name = pluginTapName, this.isRsdoctorPlugin = !0, this.modulesGraph = new ModuleGraph(), this.applied = !1, this.hasOpenedClientAutomatically = !1;
1714
+ }
1715
+ apply() {}
1716
+ ensureModulesChunksGraphApplied(compiler) {
1717
+ ensureModulesChunksGraphFn(compiler, this);
1718
+ }
1719
+ }
1613
1720
  class RsdoctorRspackPlugin {
1614
1721
  constructor(options){
1615
- this.name = pluginTapName, this.browserIsOpened = !1, this.afterPlugins = (compiler)=>{
1722
+ if (this.name = pluginTapName, this.isRsdoctorPlugin = !0, this.defaultName = pluginTapName, this.compilerContexts = new WeakMap(), this.childPlugins = new Map(), this.appliedCompilerCount = 0, this.afterPlugins = (compiler, context = this.getCompilerContext(compiler))=>{
1616
1723
  logger_time('RsdoctorRspackPlugin.afterPlugins');
1617
1724
  try {
1618
- this.getRspackConfig(compiler);
1725
+ this.getRspackConfig(compiler, context);
1619
1726
  } finally{
1620
1727
  timeEnd('RsdoctorRspackPlugin.afterPlugins');
1621
1728
  }
1622
- }, this.done = async (compiler)=>{
1729
+ }, this.done = async (compiler, context = this.getCompilerContext(compiler))=>{
1623
1730
  logger_time('RsdoctorRspackPlugin.done');
1624
1731
  try {
1625
- rsdoctorLogger.debug('[RsdoctorRspackPlugin] bootstrap(start) in done()'), await this.sdk.bootstrap(), rsdoctorLogger.debug('[RsdoctorRspackPlugin] bootstrap(end) in done()'), this.sdk.addClientRoutes([
1732
+ rsdoctorLogger.debug('[RsdoctorRspackPlugin] bootstrap(start) in done()');
1733
+ let bootstrapTask = this.ensureBootstrap(context);
1734
+ await this.awaitBootstrap(context, bootstrapTask), rsdoctorLogger.debug('[RsdoctorRspackPlugin] bootstrap(end) in done()'), context.sdk.addClientRoutes([
1626
1735
  Manifest.RsdoctorManifestClientRoutes.Overall
1627
- ]), this.outsideInstance && 'parent' in this.sdk && this.sdk.parent.master.setOutputDir(path_0.resolve(this.options.output.reportDir || compiler.outputPath, this.options.output.mode === SDK.IMode[SDK.IMode.brief] ? '' : `./${Constants.RsdoctorOutputFolder}`)), this.sdk.setOutputDir(path_0.resolve(this.options.output.reportDir || compiler.outputPath, this.options.output.mode === SDK.IMode[SDK.IMode.brief] ? '' : `./${Constants.RsdoctorOutputFolder}`)), await this.sdk.writeStore(), this.options.disableClientServer || (this.options.output.mode === SDK.IMode[SDK.IMode.brief] ? await handleBriefModeReport(this.sdk, this.options, this.options.disableClientServer) : await this.sdk.server.openClientPage('homepage')), (this.options.disableClientServer || this.options.output.mode === SDK.IMode[SDK.IMode.brief] && Array.isArray(this.options.output.options?.type) && 1 === this.options.output.options.type.length && 'json' === this.options.output.options.type[0]) && await this.sdk.dispose();
1736
+ ]), context.sdk instanceof RsdoctorPrimarySDK ? context.sdk.setOutputDir(context.sdk.parent.getCompilerOutputDir(context.sdk)) : context.sdk.setOutputDir(this.getOutputDir(compiler)), await context.sdk.writeStore(getWriteStoreOptions(compiler));
1737
+ let isPrimaryCompiler = !(context.sdk instanceof RsdoctorPrimarySDK) || context.sdk.isMaster;
1738
+ this.options.disableClientServer || !isPrimaryCompiler || context.hasOpenedClientAutomatically || (context.hasOpenedClientAutomatically = !0, this.options.output.mode === SDK.IMode[SDK.IMode.brief] ? await handleBriefModeReport(context.sdk, this.options, this.options.disableClientServer) : await context.sdk.server.openClientPage('homepage')), this.shouldDisposeSDK() && await this.disposeSDK(context, bootstrapTask);
1628
1739
  } finally{
1629
1740
  timeEnd('RsdoctorRspackPlugin.done');
1630
1741
  }
1631
- }, this.options = normalizeRspackUserOptions(Object.assign(options || {}, {
1742
+ }, this.childDone = async (compiler, context)=>{
1743
+ let bootstrapTask = this.ensureBootstrap(context);
1744
+ await this.awaitBootstrap(context, bootstrapTask), context.sdk.addClientRoutes([
1745
+ Manifest.RsdoctorManifestClientRoutes.Overall
1746
+ ]), context.sdk instanceof RsdoctorPrimarySDK ? context.sdk.setOutputDir(context.sdk.parent.getCompilerOutputDir(context.sdk)) : context.sdk.setOutputDir(this.getOutputDir(compiler)), await context.sdk.writeStore(getWriteStoreOptions(compiler)), this.shouldDisposeSDK() && await this.disposeSDK(context, bootstrapTask);
1747
+ }, this.childOptions = {
1748
+ ...options,
1632
1749
  supports: {
1633
1750
  ...options?.supports
1634
1751
  }
1635
- }));
1636
- let { port, server, output, innerClientPath, printLog, sdkInstance } = this.options;
1637
- this.sdk = this.options.sdkInstance ?? new RsdoctorSDK({
1638
- port,
1639
- name: pluginTapName,
1640
- root: process.cwd(),
1641
- type: output.reportCodeType,
1642
- config: {
1643
- innerClientPath,
1644
- printLog,
1645
- server,
1646
- mode: output.mode ? output.mode : void 0,
1647
- brief: output.mode === SDK.IMode[SDK.IMode.brief] && output.options || void 0,
1648
- features: {
1649
- treeShaking: this.options.features.treeShaking
1650
- }
1752
+ }, this.options = normalizeRspackUserOptions(this.childOptions), this.outsideInstance = !!this.options.sdkInstance, this.options.sdkInstance) {
1753
+ this.options.sdkInstance instanceof RsdoctorPrimarySDK && (this.controller = this.options.sdkInstance.parent), this.primaryContext = new RsdoctorCompilerContext(this.options.sdkInstance, this.options);
1754
+ return;
1755
+ }
1756
+ this.sessionLease = function(options) {
1757
+ if (!options.multiCompiler.enabled) return {
1758
+ controller: new RsdoctorSDKController(),
1759
+ release () {}
1760
+ };
1761
+ let key = function(options) {
1762
+ let root = process.cwd(), { group } = options.multiCompiler;
1763
+ return group ? [
1764
+ 'group',
1765
+ root,
1766
+ group
1767
+ ].join('\0') : [
1768
+ 'auto',
1769
+ root,
1770
+ options.output.mode,
1771
+ options.output.reportDir,
1772
+ options.server.port ?? ''
1773
+ ].join('\0');
1774
+ }(options), session = pendingSessions.get(key);
1775
+ if (!session) {
1776
+ let controller = new RsdoctorSDKController(), timer = setTimeout(()=>{
1777
+ pendingSessions.get(key)?.controller === controller && pendingSessions.delete(key);
1778
+ }, 0);
1779
+ timer.unref?.(), session = {
1780
+ controller,
1781
+ timer
1782
+ }, pendingSessions.set(key, session);
1651
1783
  }
1652
- }), this.outsideInstance = !!sdkInstance, this.modulesGraph = new ModuleGraph(), this.isRsdoctorPlugin = !0;
1784
+ let { controller } = session;
1785
+ return {
1786
+ controller,
1787
+ release () {
1788
+ let current = pendingSessions.get(key);
1789
+ current?.controller === controller && (clearTimeout(current.timer), pendingSessions.delete(key));
1790
+ }
1791
+ };
1792
+ }(this.options), this.controller = this.sessionLease.controller, this.primaryContext = this.createCompilerContext();
1793
+ }
1794
+ get sdk() {
1795
+ return this.primaryContext.sdk;
1796
+ }
1797
+ get modulesGraph() {
1798
+ return this.primaryContext.modulesGraph;
1799
+ }
1800
+ get _bootstrapTask() {
1801
+ return this.primaryContext.bootstrapTask;
1802
+ }
1803
+ getCompilerSDK(name) {
1804
+ return this.sdk.name === name ? this.sdk : this.sdk instanceof RsdoctorPrimarySDK ? this.sdk.parent.slaves.find((sdk)=>sdk.name === name) : void 0;
1653
1805
  }
1654
1806
  apply(compiler) {
1655
- logger_time('RsdoctorRspackPlugin.apply');
1656
- try {
1657
- hasGreeted || compiler.isChild() || (hasGreeted = !0, rsdoctorLogger.greet(`
1658
- \nRsdoctor v${packageJson.version}\n`)), this._bootstrapTask || (this._bootstrapTask = this.sdk.bootstrap()), compiler.options.name && this.sdk.setName(compiler.options.name), setSDK(this.sdk), compiler.hooks.afterPlugins.tap(pluginTapPostOptions, this.afterPlugins.bind(this, compiler)), compiler.hooks.done.tapPromise({
1659
- ...pluginTapPostOptions,
1660
- stage: pluginTapPostOptions.stage + 100
1661
- }, this.done.bind(this, compiler)), new InternalSummaryPlugin(this).apply(compiler), this.options.features.loader && (new ProbeLoaderPlugin().apply(compiler), this.sdk.addClientRoutes([
1662
- Manifest.RsdoctorManifestClientRoutes.Loaders
1663
- ]), Loader.isVue(compiler) || new InternalLoaderPlugin(this).apply(compiler)), this.options.features.plugins && new InternalPluginsPlugin(this).apply(compiler), this.options.features.bundle && new InternalBundlePlugin(this).apply(compiler), this.options.features.resolver && new InternalResolverPlugin(this).apply(compiler), new InternalRulesPlugin(this).apply(compiler), new InternalErrorReporterPlugin(this).apply(compiler);
1664
- let RsdoctorRspackNativePlugin = getRspackNativePlugin(compiler);
1665
- rsdoctorLogger.debug('[RspackNativePlugin] Enabled'), new RsdoctorRspackNativePlugin({
1666
- moduleGraphFeatures: !0,
1667
- chunkGraphFeatures: !0,
1668
- sourceMapFeatures: {
1669
- cheap: !1,
1670
- module: !1
1671
- }
1672
- }).apply(compiler);
1673
- } finally{
1674
- timeEnd('RsdoctorRspackPlugin.apply');
1807
+ let context = this.getCompilerContext(compiler);
1808
+ if (!context.applied) {
1809
+ context.applied = !0, logger_time('RsdoctorRspackPlugin.apply');
1810
+ try {
1811
+ hasGreeted || compiler.isChild() || (hasGreeted = !0, rsdoctorLogger.greet(`
1812
+ \nRsdoctor v${package_namespaceObject.version}\n`)), this.releasePendingSessionOnRun(compiler), this.ensureBootstrap(context);
1813
+ let compilerName = compiler.name || compiler.options.name || (1 === this.appliedCompilerCount ? this.defaultName : `${this.defaultName}-${this.appliedCompilerCount}`);
1814
+ compiler.isChild() || context.sdk.setName(compilerName), context.sdk instanceof RsdoctorPrimarySDK && (compiler.isChild() || (context.sdk.displayName = compiler.name || compiler.options.name || (1 === this.appliedCompilerCount ? 'Main compiler' : compilerName)), 'dependencies' in compiler.options && (context.sdk.dependencies = compiler.options.dependencies), context.sdk.parent.registerSlave(context.sdk), context.sdk.parent.setOutputDir(context.sdk, this.getOutputDir(compiler)), this.options.output.mode === SDK.IMode[SDK.IMode.brief] && (context.sdk.reportFileName = this.getBriefReportFileName())), compiler.isChild() ? registerSDK(context.sdk) : setSDK(context.sdk), this.applyChildCompilerSupport(compiler, context), compiler.isChild() ? (this.getRspackConfig(compiler, context), compiler.hooks.afterCompile.tapPromise({
1815
+ ...pluginTapPostOptions,
1816
+ stage: pluginTapPostOptions.stage + 100
1817
+ }, ()=>this.childDone(compiler, context))) : (compiler.hooks.afterPlugins.tap(pluginTapPostOptions, ()=>this.afterPlugins(compiler, context)), compiler.hooks.done.tapPromise({
1818
+ ...pluginTapPostOptions,
1819
+ stage: pluginTapPostOptions.stage + 100
1820
+ }, ()=>this.done(compiler, context))), new InternalSummaryPlugin(context).apply(compiler), this.options.features.loader && (compiler.isChild() || new ProbeLoaderPlugin().apply(compiler), context.sdk.addClientRoutes([
1821
+ Manifest.RsdoctorManifestClientRoutes.Loaders
1822
+ ]), Loader.isVue(compiler) || new InternalLoaderPlugin(context).apply(compiler)), this.options.features.plugins && new InternalPluginsPlugin(context).apply(compiler), this.options.features.bundle && new InternalBundlePlugin(context).apply(compiler), this.options.features.resolver && new InternalResolverPlugin(context).apply(compiler), new InternalRulesPlugin(context).apply(compiler), new InternalErrorReporterPlugin(context).apply(compiler);
1823
+ let RsdoctorRspackNativePlugin = getRspackNativePlugin(compiler);
1824
+ rsdoctorLogger.debug('[RspackNativePlugin] Enabled'), new RsdoctorRspackNativePlugin({
1825
+ moduleGraphFeatures: !0,
1826
+ chunkGraphFeatures: !0,
1827
+ sourceMapFeatures: {
1828
+ cheap: !1,
1829
+ module: !1
1830
+ }
1831
+ }).apply(compiler);
1832
+ } finally{
1833
+ timeEnd('RsdoctorRspackPlugin.apply');
1834
+ }
1675
1835
  }
1676
1836
  }
1677
1837
  ensureModulesChunksGraphApplied(compiler) {
1678
- ensureModulesChunksGraphFn(compiler, this);
1838
+ this.getCompilerContext(compiler).ensureModulesChunksGraphApplied(compiler);
1679
1839
  }
1680
- getRspackConfig(compiler) {
1840
+ getRspackConfig(compiler, context = this.getCompilerContext(compiler)) {
1681
1841
  logger_time('RsdoctorRspackPlugin.getRspackConfig');
1682
1842
  try {
1683
- if (compiler.isChild()) return;
1684
- let configuration = processCompilerConfig(compiler.options), { rspackVersion } = compiler.rspack;
1685
- this.sdk.reportConfiguration({
1843
+ let configuration = processCompilerConfig(compiler.options);
1844
+ compiler.isChild() && compiler.name && (configuration.name = compiler.name);
1845
+ let { rspackVersion } = compiler.rspack;
1846
+ context.sdk.reportConfiguration({
1686
1847
  name: 'rspack',
1687
1848
  version: rspackVersion || 'unknown',
1688
1849
  config: configuration,
@@ -1692,34 +1853,114 @@ class RsdoctorRspackPlugin {
1692
1853
  timeEnd('RsdoctorRspackPlugin.getRspackConfig');
1693
1854
  }
1694
1855
  }
1695
- }
1696
- class RsdoctorRspackMultiplePlugin extends RsdoctorRspackPlugin {
1697
- constructor(options = {}){
1698
- let controller = (()=>{
1699
- if (globalController) return globalController;
1700
- let controller = new RsdoctorSDKController();
1701
- return globalController = controller, controller;
1702
- })(), normallizedOptions = normalizeUserConfig(options), instance = controller.createSlave({
1703
- name: options.name || 'Builder',
1704
- stage: options.stage,
1856
+ createCompilerContext() {
1857
+ let controller = this.controller, { output, innerClientPath, printLog, server, features } = this.options;
1858
+ return new RsdoctorCompilerContext(controller.createSlave({
1859
+ name: this.defaultName,
1705
1860
  extraConfig: {
1706
- innerClientPath: normallizedOptions.innerClientPath,
1707
- printLog: normallizedOptions.printLog,
1708
- server: normallizedOptions.server,
1709
- mode: normallizedOptions.output.mode ? normallizedOptions.output.mode : void 0,
1710
- brief: normallizedOptions.output.mode === SDK.IMode[SDK.IMode.brief] && normallizedOptions.output.options || void 0
1861
+ innerClientPath,
1862
+ printLog,
1863
+ server,
1864
+ mode: output.mode || void 0,
1865
+ brief: output.mode === SDK.IMode[SDK.IMode.brief] && output.options || void 0,
1866
+ features: {
1867
+ treeShaking: features.treeShaking
1868
+ }
1711
1869
  },
1712
- type: normallizedOptions.output.reportCodeType
1870
+ type: output.reportCodeType
1871
+ }), this.options);
1872
+ }
1873
+ getCompilerContext(compiler) {
1874
+ let context, existing = this.compilerContexts.get(compiler);
1875
+ if (existing) return existing;
1876
+ if (0 === this.appliedCompilerCount) context = this.primaryContext;
1877
+ else {
1878
+ if (!this.controller) throw Error('[RsdoctorRspackPlugin] A fixed sdkInstance cannot be shared by multiple compilers. Create one plugin instance per compiler with a separate sdkInstance.');
1879
+ if (!this.options.multiCompiler.enabled) throw Error('[RsdoctorRspackPlugin] This plugin instance was applied to multiple compilers while multiCompiler is disabled.');
1880
+ context = this.createCompilerContext();
1881
+ }
1882
+ return this.appliedCompilerCount += 1, this.compilerContexts.set(compiler, context), context;
1883
+ }
1884
+ ensureBootstrap(context) {
1885
+ if (!context.bootstrapTask) {
1886
+ let task = context.sdk.bootstrap();
1887
+ context.bootstrapTask = task, task.catch(()=>{});
1888
+ }
1889
+ return context.bootstrapTask;
1890
+ }
1891
+ async awaitBootstrap(context, bootstrapTask) {
1892
+ try {
1893
+ await bootstrapTask;
1894
+ } catch (error) {
1895
+ throw this.clearBootstrapTask(context, bootstrapTask), error;
1896
+ }
1897
+ }
1898
+ clearBootstrapTask(context, bootstrapTask) {
1899
+ context.bootstrapTask === bootstrapTask && (context.bootstrapTask = void 0);
1900
+ }
1901
+ async disposeSDK(context, bootstrapTask) {
1902
+ await context.sdk.dispose(), this.clearBootstrapTask(context, bootstrapTask);
1903
+ }
1904
+ getOutputDir(compiler) {
1905
+ return node_path.resolve(this.options.output.reportDir || compiler.options.output?.path || compiler.outputPath, this.options.output.mode === SDK.IMode[SDK.IMode.brief] ? '' : `./${Constants.RsdoctorOutputFolder}`);
1906
+ }
1907
+ getBriefReportFileName() {
1908
+ let options = this.options.output.options;
1909
+ return options.type?.includes('html') ? options.htmlOptions?.reportHtmlName || 'rsdoctor-report.html' : options.jsonOptions?.fileName || 'rsdoctor-data.json';
1910
+ }
1911
+ applyChildCompilerSupport(compiler, context) {
1912
+ compiler.hooks.thisCompilation.tap({
1913
+ name: `${pluginTapName}:childCompiler`,
1914
+ stage: -999
1915
+ }, (compilation)=>{
1916
+ compilation.hooks.childCompiler.tap(`${pluginTapName}:childCompiler`, (childCompiler, compilerName, compilerIndex)=>{
1917
+ this.registerChildCompiler(compiler, childCompiler, compilerName, compilerIndex, context);
1918
+ });
1713
1919
  });
1714
- super({
1715
- ...options,
1716
- sdkInstance: instance
1717
- }), this.controller = controller;
1718
1920
  }
1719
- apply(compiler) {
1720
- 'dependencies' in compiler.options && (this.sdk.dependencies = compiler.options.dependencies), super.apply(compiler);
1921
+ registerChildCompiler(parentCompiler, childCompiler, compilerName, compilerIndex, parentContext) {
1922
+ if (!(parentContext.sdk instanceof RsdoctorPrimarySDK)) return;
1923
+ let parentSDK = parentContext.sdk, controller = parentSDK.parent, compilerPath = childCompiler.compilerPath || `${parentCompiler.compilerPath}${compilerName}|${compilerIndex}|`, childKey = `${parentSDK.id}:${compilerPath}`, registeredChild = this.childPlugins.get(childKey);
1924
+ if (registeredChild?.compiler === childCompiler) return;
1925
+ controller.setOutputDir(parentSDK, this.getOutputDir(parentCompiler));
1926
+ let childSDK = (()=>{
1927
+ if (registeredChild) return registeredChild.sdk;
1928
+ let safeCompilerPath = compilerPath.replace(/[^a-zA-Z0-9._-]+/g, '-') || `${compilerName}-${compilerIndex}`, displayName = childCompiler.name || compilerName || `Child compiler ${compilerIndex}`, sdk = controller.createSlave({
1929
+ name: `child-${safeCompilerPath}`,
1930
+ displayName,
1931
+ compilerPath,
1932
+ parentCompilerPath: parentCompiler.compilerPath || '',
1933
+ isChild: !0,
1934
+ stage: parentSDK.stage + (controller.slaves.length + 1) / 1000,
1935
+ extraConfig: parentSDK.extraConfig,
1936
+ type: parentSDK.type
1937
+ });
1938
+ return sdk.dependencies = [
1939
+ parentSDK.name
1940
+ ], sdk;
1941
+ })();
1942
+ this.removeInheritedRsdoctorTaps(childCompiler);
1943
+ let childPlugin = new RsdoctorRspackPlugin({
1944
+ ...this.childOptions,
1945
+ sdkInstance: childSDK
1946
+ });
1947
+ this.childPlugins.set(childKey, {
1948
+ compiler: childCompiler,
1949
+ sdk: childSDK
1950
+ }), childPlugin.apply(childCompiler);
1951
+ }
1952
+ removeInheritedRsdoctorTaps(compiler) {
1953
+ for (let hook of Object.values(compiler.hooks))Array.isArray(hook.taps) && (hook.taps = hook.taps.filter((tap)=>tap.name !== pluginTapName && !tap.name.startsWith(`${pluginTapName}:`)));
1954
+ }
1955
+ shouldDisposeSDK() {
1956
+ return this.options.disableClientServer || this.options.output.mode === SDK.IMode[SDK.IMode.brief] && Array.isArray(this.options.output.options?.type) && 1 === this.options.output.options.type.length && 'json' === this.options.output.options.type[0];
1957
+ }
1958
+ releasePendingSessionOnRun(compiler) {
1959
+ if (!this.sessionLease) return;
1960
+ let release = this.sessionLease.release;
1961
+ compiler.hooks.beforeRun.tap(pluginTapName, release), compiler.hooks.watchRun.tap(pluginTapName, release);
1721
1962
  }
1722
1963
  }
1723
1964
  export { Linter, LinterRule, LinterType, defineRule, rules } from "./26.js";
1724
1965
  export { logger } from "./630.js";
1725
- export { RsdoctorRspackMultiplePlugin, RsdoctorRspackPlugin, RsdoctorSDK, resolveClientDiffHtmlPath };
1966
+ export { RsdoctorRspackPlugin, RsdoctorSDK, resolveClientDiffHtmlPath };