arui-scripts 25.0.2 → 25.1.0

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.
@@ -1,18 +1,24 @@
1
1
  ts-jest[versions] (WARN) Version 6.0.2 of typescript installed has not been tested with ts-jest. If you're experiencing issues, consider using a supported version (>=4.3.0 <6.0.0-0). Please do not report issues in ts-jest if you are using unsupported versions.
2
- PASS src/commands/util/__tests__/build-size-budgets.tests.ts (31.021 s)
3
- PASS src/configs/util/__tests__/register-ts-node.tests.ts (6.028 s)
2
+ PASS src/commands/util/__tests__/build-size-budgets.tests.ts (27.986 s)
3
+ PASS src/commands/bundle-diff/__tests__/report.tests.ts
4
+ PASS src/commands/util/__tests__/rsdoctor-snapshot.tests.ts
5
+ PASS src/configs/util/__tests__/register-ts-node.tests.ts
4
6
  PASS src/plugins/__tests__/attribute-module-css.tests.ts
7
+ PASS src/commands/bundle-diff/__tests__/snapshot.tests.ts
5
8
  PASS src/configs/util/__tests__/find-plugin.tests.ts
6
9
  PASS src/configs/__tests__/rspack-client-assets.tests.ts
7
10
  PASS src/commands/util/__tests__/run-compilers.tests.ts
8
- PASS src/plugins/postcss-global-variables/utils/__tests__/add-global-variable.tests.ts
11
+ PASS src/commands/build/__tests__/client.tests.ts
9
12
  PASS src/bin/__tests__/create-cli.tests.ts
13
+ PASS src/plugins/postcss-global-variables/utils/__tests__/add-global-variable.tests.ts
14
+ PASS src/commands/bundle-diff/__tests__/comment.tests.ts
10
15
  PASS src/configs/app-configs/__tests__/update-with-presets.tests.ts
11
16
  PASS src/configs/util/__tests__/create-watch-ignore-regex.tests.ts
12
17
  PASS src/configs/util/__tests__/apply-overrides.tests.ts
13
18
  PASS src/commands/util/__tests__/artifacts-deprecations.tests.ts
14
19
  PASS src/configs/app-configs/__tests__/update-with-env.tests.ts
15
20
  PASS src/configs/__tests__/rspack-client-modules.tests.ts
21
+ PASS src/commands/bundle-diff/__tests__/index.tests.ts
16
22
  PASS src/configs/app-configs/__tests__/update-with-package.tests.ts
17
23
  PASS src/configs/util/__tests__/compress-with-dcb.test.ts
18
24
  PASS src/configs/util/__tests__/get-polyfills.tests.ts
@@ -23,8 +29,8 @@ PASS src/configs/app-configs/__tests__/validate-build-size-budgets.tests.ts
23
29
  PASS src/plugins/postcss-global-variables/utils/__tests__/get-media-query-name.tests.ts
24
30
  PASS src/configs/app-configs/__tests__/validate-settings-keys.tests.ts
25
31
 
26
- Test Suites: 23 passed, 23 total
27
- Tests: 108 passed, 108 total
32
+ Test Suites: 29 passed, 29 total
33
+ Tests: 165 passed, 165 total
28
34
  Snapshots: 0 total
29
- Time: 42.147 s
35
+ Time: 42.131 s
30
36
  Ran all test suites.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # arui-scripts
2
2
 
3
+ ## 25.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#622](https://github.com/core-ds/arui-scripts/pull/622) [`d7399f91`](https://github.com/core-ds/arui-scripts/commit/d7399f91d45a969d96820f4ca25543dbafa8c4d4) Thanks [@dmitrbrvsk](https://github.com/dmitrbrvsk)! - Добавлена команда `bundle-diff` для сравнения размеров клиентских бандлов двух production сборок.
8
+ Она создает отчеты Rsdoctor в HTML и JSON, а также markdown комментарий для pull request с таблицей изменений и ссылками на отчеты.
9
+
10
+ Данные production сборки сохраняются при запуске `arui-scripts build` с переменной `ARUI_SCRIPTS_RSDOCTOR_OUTPUT`, результат сборки при этом не меняется.
11
+
12
+ Примеры использования и настройка CI описаны в [документации](docs/commands.md#bundle-diff).
13
+
3
14
  ## 25.0.2
4
15
 
5
16
  ### Patch Changes
package/README.md CHANGED
@@ -19,6 +19,32 @@ yarn start
19
19
  CLI `arui-scripts` поддерживает глобальные флаги `--help`, `--version` и справку по командам
20
20
  `arui-scripts <команда> --help`. Подробнее в [CLI](docs/cli.md).
21
21
 
22
+ Команду `bundle-diff` можно запускать локально или в CI/CD.
23
+
24
+ Для анализа изменений клиентских бандлов необходимы snapshot двух production сборок:
25
+
26
+ - `current`: snapshot текущей сборки PR
27
+ - `baseline`: snapshot сборки целевой ветки PR
28
+
29
+ Сохранить snapshot текущей сборки можно командой:
30
+
31
+ ```bash
32
+ ARUI_SCRIPTS_RSDOCTOR_OUTPUT=rsdoctor/current yarn build
33
+ ```
34
+
35
+ Сохраните snapshot успешной сборки целевой ветки. Перед сравнением поместите snapshot
36
+ нужного коммита целевой ветки в каталог `rsdoctor/baseline`, затем запустите команду:
37
+
38
+ ```bash
39
+ arui-scripts bundle-diff --current rsdoctor/current --baseline rsdoctor/baseline
40
+ ```
41
+
42
+ Команда `bundle-diff` не скачивает baseline автоматически. При запуске в CI/CD настройте
43
+ получение и сохранение snapshot в пайплайне (при локальном запуске нужно подготовить вручную).
44
+
45
+ Команда создает HTML/JSON diff и markdown комментарий с таблицей размеров и ссылками на отчеты.
46
+ Подробнее, включая использование в CI, в [документации bundle-diff](docs/commands.md#bundle-diff).
47
+
22
48
  Использование
23
49
 
24
50
  ===
@@ -3,6 +3,12 @@ export type CliCommand = {
3
3
  description: string;
4
4
  help?: string;
5
5
  passthrough?: boolean;
6
- load: () => void;
6
+ load: (options: Record<string, string | boolean>) => void;
7
+ options?: Array<{
8
+ flags: string;
9
+ description: string;
10
+ required?: boolean;
11
+ defaultValue?: string;
12
+ }>;
7
13
  };
8
14
  export declare const commands: CliCommand[];
@@ -77,4 +77,29 @@ exports.commands = [
77
77
  description: 'postchangelog-хук standard-version: формирует описание версии в CHANGELOG.md',
78
78
  load: () => require('../commands/changelog'),
79
79
  },
80
+ {
81
+ name: 'bundle-diff',
82
+ description: 'Генерирует Rsdoctor html diff и markdown комментарий для CI',
83
+ options: [
84
+ {
85
+ flags: '--current <directory>',
86
+ description: 'Каталог данных текущей сборки',
87
+ required: true,
88
+ },
89
+ { flags: '--baseline <directory>', description: 'Каталог данных базовой сборки' },
90
+ {
91
+ flags: '--output <directory>',
92
+ description: 'Каталог отчетов',
93
+ defaultValue: 'rsdoctor/diff',
94
+ },
95
+ {
96
+ flags: '--report-url <url>',
97
+ description: 'URL опубликованного каталога HTML отчетов',
98
+ },
99
+ { flags: '--current-label <label>', description: 'Коммит текущей сборки' },
100
+ { flags: '--baseline-label <label>', description: 'Ветка и коммит базовой сборки' },
101
+ ],
102
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
103
+ load: (options) => require('../commands/bundle-diff').run(options),
104
+ },
80
105
  ];
@@ -21,7 +21,16 @@ function createCli() {
21
21
  ? `\n ${chalk_1.default.bgCyan.black(' arui-scripts ')} ${chalk_1.default.dim(`v${version}`)}\n`
22
22
  : '');
23
23
  commands_registry_1.commands.forEach((cmd) => {
24
+ var _a;
24
25
  const command = program.command(cmd.name).description(cmd.description).action(cmd.load);
26
+ (_a = cmd.options) === null || _a === void 0 ? void 0 : _a.forEach(({ flags, description, required, defaultValue }) => {
27
+ if (required) {
28
+ command.requiredOption(flags, description, defaultValue);
29
+ }
30
+ else {
31
+ command.option(flags, description, defaultValue);
32
+ }
33
+ });
25
34
  if (cmd.passthrough) {
26
35
  // --help/-h пробрасываем в jest/vitest/docker, а не показываем help commander.
27
36
  command.allowUnknownOption().allowExcessArguments().helpOption(false);
@@ -19,6 +19,7 @@ const build_size_budgets_1 = require("../util/build-size-budgets");
19
19
  const client_assets_sizes_1 = require("../util/client-assets-sizes");
20
20
  const load_browserslist_1 = require("../util/load-browserslist");
21
21
  const print_build_error_1 = require("../util/print-build-error");
22
+ const rsdoctor_snapshot_1 = require("../util/rsdoctor-snapshot");
22
23
  const build_wrapper_1 = __importDefault(require("./build-wrapper"));
23
24
  (0, load_browserslist_1.loadBrowserslist)();
24
25
  console.log(chalk_1.default.magenta('Building client...'));
@@ -38,6 +39,7 @@ function printOutputSizes(webpackConfig, stats) {
38
39
  function main() {
39
40
  return __awaiter(this, void 0, void 0, function* () {
40
41
  try {
42
+ const snapshot = yield (0, rsdoctor_snapshot_1.enableRsdoctor)(rspack_client_prod_1.rspackClientConfig, process.env.ARUI_SCRIPTS_RSDOCTOR_OUTPUT, app_configs_1.configs.appSrc);
41
43
  const { stats, warnings } = yield (0, build_wrapper_1.default)(rspack_client_prod_1.rspackClientConfig);
42
44
  if (warnings.length) {
43
45
  console.log(chalk_1.default.yellow('Client compiled with warnings.\n'));
@@ -58,6 +60,9 @@ function main() {
58
60
  else {
59
61
  yield printOutputSizes(rspack_client_prod_1.rspackClientConfig, stats);
60
62
  }
63
+ if (snapshot) {
64
+ yield (0, rsdoctor_snapshot_1.writeRsdoctorSnapshot)(snapshot);
65
+ }
61
66
  }
62
67
  catch (err) {
63
68
  if (err instanceof build_size_budgets_1.BuildSizeBudgetError) {
@@ -0,0 +1,4 @@
1
+ export declare function createSnapshot(directory: string, name: string, bundles: Array<{
2
+ name: string;
3
+ js: number;
4
+ }>): Promise<string>;
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.createSnapshot = createSnapshot;
16
+ const path_1 = __importDefault(require("path"));
17
+ const fs_extra_1 = __importDefault(require("fs-extra"));
18
+ const rsdoctor_snapshot_1 = require("../../util/rsdoctor-snapshot");
19
+ function createSnapshot(directory, name, bundles) {
20
+ return __awaiter(this, void 0, void 0, function* () {
21
+ const root = path_1.default.join(directory, name);
22
+ yield fs_extra_1.default.ensureDir(root);
23
+ yield fs_extra_1.default.writeJson(path_1.default.join(root, 'index.json'), {
24
+ schemaVersion: 1,
25
+ rsdoctorVersion: rsdoctor_snapshot_1.rsdoctorVersion,
26
+ bundles: bundles.map((bundle, index) => ({ name: bundle.name, dataFile: `${index}.json` })),
27
+ });
28
+ yield Promise.all(bundles.map((bundle, index) => fs_extra_1.default.writeJson(path_1.default.join(root, `${index}.json`), {
29
+ data: {
30
+ chunkGraph: {
31
+ assets: [
32
+ { path: 'main.js', size: bundle.js, chunks: [] },
33
+ { path: 'main.css', size: 100, chunks: [] },
34
+ { path: 'index.html', size: 20, chunks: [] },
35
+ { path: 'image.png', size: 80, chunks: [] },
36
+ { path: 'main.js.map', size: 9999, chunks: [] },
37
+ { path: 'main.js.LICENSE.txt', size: 9999, chunks: [] },
38
+ { path: 'main.js.gz', size: 9999, chunks: [] },
39
+ { path: 'main.js.br', size: 9999, chunks: [] },
40
+ ],
41
+ chunks: [],
42
+ entrypoints: [],
43
+ },
44
+ moduleGraph: { modules: [] },
45
+ packageGraph: { packages: [] },
46
+ },
47
+ })));
48
+ return root;
49
+ });
50
+ }
@@ -0,0 +1,13 @@
1
+ import { type Bundle } from './snapshot';
2
+ export type BundleComparison = {
3
+ name: string;
4
+ status: 'added';
5
+ } | {
6
+ name: string;
7
+ status: 'removed';
8
+ } | {
9
+ name: string;
10
+ status: 'compared';
11
+ htmlFile: string;
12
+ };
13
+ export declare function generateArtifacts(current: Bundle[], baseline: Bundle[] | undefined, output: string): Promise<BundleComparison[]>;
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.generateArtifacts = generateArtifacts;
16
+ const path_1 = __importDefault(require("path"));
17
+ const cli_1 = require("@rsdoctor/cli");
18
+ const fs_extra_1 = __importDefault(require("fs-extra"));
19
+ function generateReport(current, baseline, output, index) {
20
+ return __awaiter(this, void 0, void 0, function* () {
21
+ const htmlFile = `client-${index}.html`;
22
+ const htmlPath = path_1.default.join(output, htmlFile);
23
+ yield (0, cli_1.execute)('bundle-diff', {
24
+ baseline,
25
+ current,
26
+ html: true,
27
+ open: false,
28
+ output: htmlPath,
29
+ });
30
+ if (!(yield fs_extra_1.default.pathExists(htmlPath))) {
31
+ throw new Error(`Rsdoctor did not generate ${htmlFile}`);
32
+ }
33
+ yield (0, cli_1.execute)('bundle-diff', {
34
+ baseline,
35
+ current,
36
+ json: path_1.default.join(output, `client-${index}.json`),
37
+ });
38
+ return htmlFile;
39
+ });
40
+ }
41
+ function generateArtifacts(current, baseline, output) {
42
+ return __awaiter(this, void 0, void 0, function* () {
43
+ yield fs_extra_1.default.ensureDir(output);
44
+ // удаляем только отчеты, так как в --output могут лежать входные snapshot и посторонние файлы
45
+ const oldFiles = (yield fs_extra_1.default.readdir(output)).filter((file) => /^client-\d+\.(html|json)$/.test(file) || ['comment.md', 'summary.json'].includes(file));
46
+ yield Promise.all(oldFiles.map((file) => fs_extra_1.default.remove(path_1.default.join(output, file))));
47
+ if (baseline === undefined) {
48
+ return [];
49
+ }
50
+ const comparisons = [];
51
+ const currentNames = new Set(current.map(({ name }) => name));
52
+ for (const [index, bundle] of current.entries()) {
53
+ const previous = baseline.find(({ name }) => name === bundle.name);
54
+ if (previous === undefined) {
55
+ comparisons.push({ name: bundle.name, status: 'added' });
56
+ }
57
+ else {
58
+ // eslint-disable-next-line no-await-in-loop
59
+ const htmlFile = yield generateReport(bundle.file, previous.file, output, index);
60
+ comparisons.push({ name: bundle.name, status: 'compared', htmlFile });
61
+ }
62
+ }
63
+ baseline.forEach(({ name }) => {
64
+ if (!currentNames.has(name)) {
65
+ comparisons.push({ name, status: 'removed' });
66
+ }
67
+ });
68
+ return comparisons;
69
+ });
70
+ }
@@ -0,0 +1,15 @@
1
+ import { type BundleComparison } from './artifacts';
2
+ import { type Sizes } from './sizes';
3
+ export type BaselineIssue = 'missing' | 'incompatible';
4
+ type CommentOptions = {
5
+ current: Sizes;
6
+ baseline?: Sizes;
7
+ baselineIssue?: BaselineIssue;
8
+ comparisons: BundleComparison[];
9
+ reportUrl?: string;
10
+ currentLabel?: string;
11
+ baselineLabel?: string;
12
+ };
13
+ export declare function formatChange(current: number, baseline: number): string;
14
+ export declare function createComment(options: CommentOptions): string;
15
+ export {};
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.formatChange = formatChange;
7
+ exports.createComment = createComment;
8
+ const filesize_1 = __importDefault(require("filesize"));
9
+ const rsdoctor_snapshot_1 = require("../util/rsdoctor-snapshot");
10
+ const baselineIssueMessages = {
11
+ missing: 'Baseline для точного коммита целевой ветки отсутствует. Запустите ее сборку с rsdoctor и повторите сборку PR. Сравнение и HTML diff пока недоступны.',
12
+ incompatible: 'Baseline несовместим с текущей сборкой (версия Rsdoctor или формат snapshot). ' +
13
+ `Текущая версия Rsdoctor: ${rsdoctor_snapshot_1.rsdoctorVersion}. ` +
14
+ 'Для сравнения необходимо пересобрать baseline с совместимой версией Rsdoctor и форматом snapshot.',
15
+ };
16
+ function formatChange(current, baseline) {
17
+ const delta = current - baseline;
18
+ // filesize сам добавляет минус к отрицательным значениям
19
+ const sign = delta > 0 ? '+' : '';
20
+ let percent = '0.0%';
21
+ if (baseline > 0) {
22
+ percent = `${sign}${((delta / baseline) * 100).toFixed(1)}%`;
23
+ }
24
+ else if (current > 0) {
25
+ percent = 'new';
26
+ }
27
+ return `${sign}${(0, filesize_1.default)(delta)} (${percent})`;
28
+ }
29
+ function escapeMarkdown(text) {
30
+ return text.replace(/[\\`*_{}[\]<>|]/g, '\\$&').replace(/[\r\n]/g, ' ');
31
+ }
32
+ function createComment(options) {
33
+ var _a;
34
+ const { current, baseline, comparisons, reportUrl } = options;
35
+ const lines = [
36
+ '## Rsdoctor Bundle Diff Analysis',
37
+ '',
38
+ `Current: ${escapeMarkdown(options.currentLabel || 'current build')}`,
39
+ `Baseline: ${escapeMarkdown(options.baselineLabel || 'target branch')}`,
40
+ '',
41
+ '| Metric | Current | Baseline | Change |',
42
+ '| --- | ---: | ---: | ---: |',
43
+ ];
44
+ const metrics = [
45
+ ['total', '📊 Total Size'],
46
+ ['js', '📄 JavaScript'],
47
+ ['css', '🎨 CSS'],
48
+ ['html', '🌐 HTML'],
49
+ ['other', '📁 Other Assets'],
50
+ ];
51
+ metrics.forEach(([key, label]) => {
52
+ lines.push(`| ${label} | ${(0, filesize_1.default)(current[key])} | ${baseline ? (0, filesize_1.default)(baseline[key]) : ''} | ${baseline ? formatChange(current[key], baseline[key]) : ''} |`);
53
+ });
54
+ lines.push('', 'Размеры emitted assets без source maps и предсжатых .gz/.br копий, по правилам Rsdoctor.');
55
+ if (baseline === undefined) {
56
+ lines.push('', baselineIssueMessages[(_a = options.baselineIssue) !== null && _a !== void 0 ? _a : 'missing']);
57
+ }
58
+ else {
59
+ comparisons.forEach((comparison) => {
60
+ const name = escapeMarkdown(comparison.name);
61
+ if (comparison.status === 'added') {
62
+ lines.push('', `Новая клиентская конфигурация: ${name}. Размер включен в таблицу; HTML diff для нее недоступен.`);
63
+ }
64
+ else if (comparison.status === 'removed') {
65
+ lines.push('', `Удаленная клиентская конфигурация: ${name}. Размер включен в изменение таблицы.`);
66
+ }
67
+ else {
68
+ const link = reportUrl
69
+ ? new URL(comparison.htmlFile, `${reportUrl.replace(/\/$/, '')}/`).href
70
+ : comparison.htmlFile;
71
+ lines.push('', `[📦 Bundle Diff Report: ${name}](${link})`);
72
+ }
73
+ });
74
+ }
75
+ lines.push('');
76
+ return lines.join('\n');
77
+ }
@@ -0,0 +1,2 @@
1
+ import { type BundleDiffOptions } from './report';
2
+ export declare function run(options: BundleDiffOptions): Promise<void>;
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.run = run;
13
+ const report_1 = require("./report");
14
+ function run(options) {
15
+ return __awaiter(this, void 0, void 0, function* () {
16
+ try {
17
+ yield (0, report_1.generateBundleDiff)(options);
18
+ console.log(`Rsdoctor bundle diff written to ${options.output}`);
19
+ }
20
+ catch (error) {
21
+ console.error('Rsdoctor bundle diff failed:', error);
22
+ process.exitCode = 1;
23
+ }
24
+ });
25
+ }
@@ -0,0 +1,9 @@
1
+ export type BundleDiffOptions = {
2
+ current: string;
3
+ baseline?: string;
4
+ output: string;
5
+ reportUrl?: string;
6
+ currentLabel?: string;
7
+ baselineLabel?: string;
8
+ };
9
+ export declare function generateBundleDiff(options: BundleDiffOptions): Promise<void>;
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.generateBundleDiff = generateBundleDiff;
16
+ const path_1 = __importDefault(require("path"));
17
+ const fs_extra_1 = __importDefault(require("fs-extra"));
18
+ const artifacts_1 = require("./artifacts");
19
+ const comment_1 = require("./comment");
20
+ const sizes_1 = require("./sizes");
21
+ const snapshot_1 = require("./snapshot");
22
+ // Отсутствующий или несовместимый baseline не мешает показать текущие размеры.
23
+ function readBaseline(directory) {
24
+ return __awaiter(this, void 0, void 0, function* () {
25
+ if (!directory || !(yield fs_extra_1.default.pathExists(path_1.default.join(directory, 'index.json')))) {
26
+ return { issue: 'missing' };
27
+ }
28
+ try {
29
+ return { bundles: yield (0, snapshot_1.readSnapshot)(directory) };
30
+ }
31
+ catch (error) {
32
+ if (!(error instanceof snapshot_1.IncompatibleSnapshotError)) {
33
+ throw error;
34
+ }
35
+ console.warn(error.message);
36
+ return { issue: 'incompatible' };
37
+ }
38
+ });
39
+ }
40
+ function generateBundleDiff(options) {
41
+ return __awaiter(this, void 0, void 0, function* () {
42
+ const current = yield (0, snapshot_1.readSnapshot)(options.current);
43
+ const baseline = yield readBaseline(options.baseline);
44
+ const output = path_1.default.resolve(options.output);
45
+ const currentSizes = (0, sizes_1.getSizes)(current);
46
+ const baselineSizes = baseline.bundles ? (0, sizes_1.getSizes)(baseline.bundles) : undefined;
47
+ const comparisons = yield (0, artifacts_1.generateArtifacts)(current, baseline.bundles, output);
48
+ const comment = (0, comment_1.createComment)({
49
+ current: currentSizes,
50
+ baseline: baselineSizes,
51
+ baselineIssue: baseline.issue,
52
+ comparisons,
53
+ reportUrl: options.reportUrl,
54
+ currentLabel: options.currentLabel,
55
+ baselineLabel: options.baselineLabel,
56
+ });
57
+ yield fs_extra_1.default.writeFile(path_1.default.join(output, 'comment.md'), comment, 'utf8');
58
+ yield fs_extra_1.default.writeJson(path_1.default.join(output, 'summary.json'), { current: currentSizes, baseline: baselineSizes || null }, { spaces: 2 });
59
+ });
60
+ }
@@ -0,0 +1,9 @@
1
+ import { type Bundle } from './snapshot';
2
+ export type Sizes = {
3
+ total: number;
4
+ js: number;
5
+ css: number;
6
+ html: number;
7
+ other: number;
8
+ };
9
+ export declare function getSizes(bundles: Bundle[]): Sizes;
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getSizes = getSizes;
4
+ const common_1 = require("@rsdoctor/utils/common");
5
+ // Предсжатые копии дублируют те же JS и CSS, поэтому не входят в размеры.
6
+ const PRECOMPRESSED_ASSET = /\.(gz|br)$/;
7
+ function getSizes(bundles) {
8
+ return bundles.reduce((sizes, { data: { chunkGraph } }) => {
9
+ const summary = common_1.Graph.getAssetsSummary(chunkGraph.assets.filter((asset) => !PRECOMPRESSED_ASSET.test(asset.path)), chunkGraph.chunks, { withFileContent: false });
10
+ const total = summary.all.total.size;
11
+ const js = summary.js.total.size;
12
+ const css = summary.css.total.size;
13
+ const html = summary.html.total.size;
14
+ return {
15
+ total: sizes.total + total,
16
+ js: sizes.js + js,
17
+ css: sizes.css + css,
18
+ html: sizes.html + html,
19
+ other: sizes.other + total - js - css - html,
20
+ };
21
+ }, { total: 0, js: 0, css: 0, html: 0, other: 0 });
22
+ }
@@ -0,0 +1,9 @@
1
+ import { type SDK } from '@rsdoctor/types';
2
+ export type Bundle = {
3
+ name: string;
4
+ file: string;
5
+ data: SDK.BuilderStoreData;
6
+ };
7
+ export declare class IncompatibleSnapshotError extends Error {
8
+ }
9
+ export declare function readSnapshot(directory: string): Promise<Bundle[]>;
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.IncompatibleSnapshotError = void 0;
16
+ exports.readSnapshot = readSnapshot;
17
+ const path_1 = __importDefault(require("path"));
18
+ const fs_extra_1 = __importDefault(require("fs-extra"));
19
+ const rsdoctor_snapshot_1 = require("../util/rsdoctor-snapshot");
20
+ class IncompatibleSnapshotError extends Error {
21
+ }
22
+ exports.IncompatibleSnapshotError = IncompatibleSnapshotError;
23
+ function readSnapshot(directory) {
24
+ return __awaiter(this, void 0, void 0, function* () {
25
+ const root = path_1.default.resolve(directory);
26
+ const snapshot = yield fs_extra_1.default.readJson(path_1.default.join(root, 'index.json'));
27
+ if (snapshot.schemaVersion !== 1 || snapshot.rsdoctorVersion !== rsdoctor_snapshot_1.rsdoctorVersion) {
28
+ throw new IncompatibleSnapshotError(`Incompatible Rsdoctor snapshot ${root}: schema ${snapshot.schemaVersion}, Rsdoctor ${snapshot.rsdoctorVersion}; expected schema 1, Rsdoctor ${rsdoctor_snapshot_1.rsdoctorVersion}`);
29
+ }
30
+ if (!Array.isArray(snapshot.bundles) || !snapshot.bundles.length) {
31
+ throw new Error(`Invalid Rsdoctor snapshot: ${root}`);
32
+ }
33
+ const names = new Set();
34
+ return Promise.all(snapshot.bundles.map((_a) => __awaiter(this, [_a], void 0, function* ({ name, dataFile }) {
35
+ var _b, _c, _d, _e;
36
+ if (typeof name !== 'string' ||
37
+ !name ||
38
+ names.has(name) ||
39
+ typeof dataFile !== 'string') {
40
+ throw new Error(`Invalid or duplicate bundle in ${root}`);
41
+ }
42
+ names.add(name);
43
+ const file = path_1.default.resolve(root, dataFile);
44
+ const relative = path_1.default.relative(root, file);
45
+ if (relative.startsWith(`..${path_1.default.sep}`) ||
46
+ relative === '..' ||
47
+ path_1.default.isAbsolute(relative)) {
48
+ throw new Error(`Bundle data must be inside its snapshot: ${dataFile}`);
49
+ }
50
+ const { data } = yield fs_extra_1.default.readJson(file);
51
+ if (!Array.isArray((_b = data === null || data === void 0 ? void 0 : data.chunkGraph) === null || _b === void 0 ? void 0 : _b.assets) ||
52
+ !Array.isArray((_c = data === null || data === void 0 ? void 0 : data.chunkGraph) === null || _c === void 0 ? void 0 : _c.chunks) ||
53
+ !Array.isArray((_d = data === null || data === void 0 ? void 0 : data.moduleGraph) === null || _d === void 0 ? void 0 : _d.modules) ||
54
+ !Array.isArray((_e = data === null || data === void 0 ? void 0 : data.packageGraph) === null || _e === void 0 ? void 0 : _e.packages)) {
55
+ throw new Error(`Invalid Rsdoctor data: ${file}`);
56
+ }
57
+ if (data.chunkGraph.assets.some((asset) => typeof asset.path !== 'string' ||
58
+ !Number.isFinite(asset.size) ||
59
+ asset.size < 0)) {
60
+ throw new Error(`Invalid asset size in ${file}`);
61
+ }
62
+ return { name, file, data };
63
+ })));
64
+ });
65
+ }
@@ -0,0 +1,18 @@
1
+ import { type Configuration } from '@rspack/core';
2
+ export declare const rsdoctorVersion: string;
3
+ export type RsdoctorSnapshot = {
4
+ schemaVersion: 1;
5
+ rsdoctorVersion: string;
6
+ bundles: Array<{
7
+ name: string;
8
+ dataFile: string;
9
+ }>;
10
+ };
11
+ type SnapshotOutput = {
12
+ directory: string;
13
+ snapshot: RsdoctorSnapshot;
14
+ };
15
+ export declare function enableRsdoctor(configuration: Configuration | Configuration[], outputDirectory: string | undefined, sourceRoot: string): Promise<SnapshotOutput | undefined>;
16
+ export declare function normalizeWorkspacePaths(value: unknown, root: string): unknown;
17
+ export declare function writeRsdoctorSnapshot({ directory, snapshot, }: SnapshotOutput): Promise<void>;
18
+ export {};