-
-
Notifications
You must be signed in to change notification settings - Fork 277
Expand file tree
/
Copy pathsize-report.mjs
More file actions
438 lines (378 loc) · 13.1 KB
/
Copy pathsize-report.mjs
File metadata and controls
438 lines (378 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
#!/usr/bin/env node
import fs from 'node:fs';
import path from 'node:path';
import { execFileSync } from 'node:child_process';
import { performance } from 'node:perf_hooks';
import { gzipSync } from 'node:zlib';
const COMMENT_MARKER = '<!-- agent-device-size-report -->';
const VALUE_ARGS = new Map([
['--cwd', 'cwd'],
['--json', 'json'],
['--markdown', 'markdown'],
['--compare', 'compare'],
['--post-comment', 'postComment'],
['--pr', 'pr'],
['--startup-runs', 'startupRuns'],
]);
const STARTUP_BENCHMARKS = [
{ name: 'CLI --version', args: ['--version'] },
{ name: 'CLI --help', args: ['--help'] },
];
const args = parseArgs(process.argv.slice(2));
const cwd = path.resolve(args.cwd ?? process.cwd());
if (args.postComment) {
await postGitHubComment(args.postComment, args.pr);
process.exit(0);
}
const report = collectReport(cwd, {
startupRuns: parseNonNegativeInteger(args.startupRuns ?? '0', '--startup-runs'),
});
const baseReport = args.compare ? JSON.parse(fs.readFileSync(args.compare, 'utf8')) : null;
if (args.json) {
writeFile(args.json, `${JSON.stringify(report, null, 2)}\n`);
}
const markdown = formatMarkdown(report, baseReport);
if (args.markdown) {
writeFile(args.markdown, markdown);
} else {
process.stdout.write(markdown);
}
function parseArgs(argv) {
const parsed = {};
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
if (assignValueArg(parsed, arg, argv, index)) index += 1;
else if (isHelpArg(arg)) printHelpAndExit();
else throw new Error(`Unknown argument: ${arg}`);
}
return parsed;
}
function assignValueArg(parsed, arg, argv, index) {
const key = VALUE_ARGS.get(arg);
if (!key) return false;
parsed[key] = readValue(argv, index + 1, arg);
return true;
}
function isHelpArg(arg) {
return arg === '--help' || arg === '-h';
}
function printHelpAndExit() {
process.stdout.write(`Usage: node scripts/size-report.mjs [options]
Options:
--cwd <path> Project root to measure. Defaults to cwd.
--json <path> Write the raw size report JSON.
--markdown <path> Write the markdown report.
--compare <path> Compare against a previously written JSON report.
--startup-runs <count> Measure startup medians for side-effect-free CLI commands.
--post-comment <path> Post or update the markdown report on the current PR.
--pr <number> Pull request number for --post-comment.
`);
process.exit(0);
}
function readValue(argv, index, flag) {
const value = argv[index];
if (!value || value.startsWith('--')) {
throw new Error(`${flag} requires a value`);
}
return value;
}
function parseNonNegativeInteger(value, flag) {
const parsed = Number(value);
if (!Number.isInteger(parsed) || parsed < 0) {
throw new Error(`${flag} must be a non-negative integer`);
}
return parsed;
}
function collectReport(root, options) {
const packageJson = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
const jsFiles = walk(path.join(root, 'dist', 'src')).filter((file) => file.endsWith('.js'));
if (jsFiles.length === 0) {
throw new Error('No dist/src JavaScript files found. Run `pnpm build` before measuring size.');
}
prepareGeneratedPackageAssets(root);
const chunks = jsFiles
.map((file) => {
const buffer = fs.readFileSync(file);
return {
path: path.relative(root, file),
rawBytes: buffer.byteLength,
gzipBytes: gzipSync(buffer, { level: 9 }).byteLength,
};
})
.sort((left, right) => right.rawBytes - left.rawBytes);
const js = chunks.reduce(
(total, chunk) => ({
files: total.files + 1,
rawBytes: total.rawBytes + chunk.rawBytes,
gzipBytes: total.gzipBytes + chunk.gzipBytes,
}),
{ files: 0, rawBytes: 0, gzipBytes: 0 },
);
return {
packageName: packageJson.name,
version: packageJson.version,
generatedAt: new Date().toISOString(),
js,
npmPack: collectNpmPack(root),
...(options.startupRuns > 0
? { startup: collectStartupBenchmarks(root, options.startupRuns) }
: {}),
chunks: chunks.slice(0, 20),
};
}
function prepareGeneratedPackageAssets(root) {
const packageAppleRunnerScript = path.join(root, 'scripts', 'package-apple-runner-source.mjs');
if (!fs.existsSync(packageAppleRunnerScript)) {
return;
}
execFileSync(process.execPath, [packageAppleRunnerScript, '--quiet'], {
cwd: root,
stdio: ['ignore', 'ignore', 'inherit'],
});
}
function collectStartupBenchmarks(root, runs) {
return {
runs,
benchmarks: STARTUP_BENCHMARKS.map((benchmark) =>
measureStartupBenchmark(root, benchmark, runs),
),
};
}
function measureStartupBenchmark(root, benchmark, runs) {
const samplesMs = [];
runStartupCommand(root, benchmark.args);
for (let index = 0; index < runs; index += 1) {
const start = performance.now();
runStartupCommand(root, benchmark.args);
samplesMs.push(performance.now() - start);
}
const sortedSamples = [...samplesMs].sort((left, right) => left - right);
return {
name: benchmark.name,
command: `agent-device ${benchmark.args.join(' ')}`,
medianMs: median(sortedSamples),
minMs: sortedSamples[0],
maxMs: sortedSamples.at(-1),
samplesMs,
};
}
function runStartupCommand(root, args) {
execFileSync(process.execPath, ['bin/agent-device.mjs', ...args], {
cwd: root,
stdio: 'ignore',
timeout: 5_000,
});
}
function median(sortedValues) {
const midpoint = Math.floor(sortedValues.length / 2);
return sortedValues.length % 2 === 0
? (sortedValues[midpoint - 1] + sortedValues[midpoint]) / 2
: sortedValues[midpoint];
}
function walk(root) {
if (!fs.existsSync(root)) return [];
const entries = fs.readdirSync(root, { withFileTypes: true });
return entries.flatMap((entry) => {
const entryPath = path.join(root, entry.name);
return entry.isDirectory() ? walk(entryPath) : [entryPath];
});
}
function collectNpmPack(root) {
const cachePath = path.join(root, '.tmp', 'npm-cache');
fs.mkdirSync(cachePath, { recursive: true });
const stdout = execFileSync(
'npm',
['pack', '--dry-run', '--ignore-scripts', '--json', '--cache', cachePath],
{ cwd: root, encoding: 'utf8' },
);
const pack = parseNpmPackOutput(stdout);
return {
filename: pack.filename,
tarballBytes: pack.size,
unpackedBytes: pack.unpackedSize,
files: countNpmPackEntries(pack),
};
}
function parseNpmPackOutput(stdout) {
const parsed = JSON.parse(stdout);
return Array.isArray(parsed) ? parsed[0] : parsed;
}
function countNpmPackEntries(pack) {
if (typeof pack.entryCount === 'number') return pack.entryCount;
return Array.isArray(pack.files) ? pack.files.length : 0;
}
function formatMarkdown(report, baseReport) {
const rows = [
metricRow('JS raw', baseReport?.js.rawBytes, report.js.rawBytes),
metricRow('JS gzip', baseReport?.js.gzipBytes, report.js.gzipBytes),
metricRow('npm tarball', baseReport?.npmPack.tarballBytes, report.npmPack.tarballBytes),
metricRow('npm unpacked', baseReport?.npmPack.unpackedBytes, report.npmPack.unpackedBytes),
];
const changedChunks = baseReport
? formatChangedChunks(report.chunks, baseReport.chunks ?? [])
: formatTopChunks(report.chunks);
const startup = formatStartupBenchmarks(report.startup, baseReport?.startup);
return `${COMMENT_MARKER}
## Size Report
| Metric | Base | Current | Diff |
|---|---:|---:|---:|
${rows.join('\n')}
${startup}
${changedChunks}
`;
}
function metricRow(label, base, current) {
return `| ${label} | ${formatMaybeBytes(base)} | ${formatBytes(current)} | ${formatDiff(base, current)} |`;
}
function formatTopChunks(chunks) {
const rows = chunks.slice(0, 5).map((chunk) => {
return `| \`${chunk.path}\` | ${formatBytes(chunk.rawBytes)} | ${formatBytes(chunk.gzipBytes)} |`;
});
return `Top chunks:
| Chunk | Raw | Gzip |
|---|---:|---:|
${rows.join('\n')}
`;
}
function formatChangedChunks(currentChunks, baseChunks) {
const baseByPath = new Map(baseChunks.map((chunk) => [chunk.path, chunk]));
const rows = currentChunks
.map((chunk) => {
const base = baseByPath.get(chunk.path);
return {
path: chunk.path,
rawDiff: base ? chunk.rawBytes - base.rawBytes : chunk.rawBytes,
gzipDiff: base ? chunk.gzipBytes - base.gzipBytes : chunk.gzipBytes,
};
})
.filter((chunk) => chunk.rawDiff !== 0 || chunk.gzipDiff !== 0)
.sort((left, right) => Math.abs(right.gzipDiff) - Math.abs(left.gzipDiff))
.slice(0, 5)
.map((chunk) => {
return `| \`${chunk.path}\` | ${formatSignedBytes(chunk.rawDiff)} | ${formatSignedBytes(chunk.gzipDiff)} |`;
});
if (rows.length === 0) {
return 'Top changed chunks: no changes in the largest emitted chunks.\n';
}
return `Top changed chunks:
| Chunk | Raw diff | Gzip diff |
|---|---:|---:|
${rows.join('\n')}
`;
}
function formatMaybeBytes(value) {
return typeof value === 'number' ? formatBytes(value) : '-';
}
function formatDiff(base, current) {
return typeof base === 'number' ? formatSignedBytes(current - base) : '-';
}
function formatStartupBenchmarks(startup, baseStartup) {
if (!startup) return '';
const baseByName = new Map(
(baseStartup?.benchmarks ?? []).map((benchmark) => [benchmark.name, benchmark]),
);
const rows = startup.benchmarks.map((benchmark) => {
const base = baseByName.get(benchmark.name);
return `| ${benchmark.name} | ${formatMaybeMs(base?.medianMs)} | ${formatMs(benchmark.medianMs)} | ${formatMsDiff(base?.medianMs, benchmark.medianMs)} |`;
});
return `Startup median (${startup.runs} runs, lower is better):
| Scenario | Base | Current | Diff |
|---|---:|---:|---:|
${rows.join('\n')}
`;
}
function formatMaybeMs(value) {
return typeof value === 'number' ? formatMs(value) : '-';
}
function formatMsDiff(base, current) {
if (typeof base !== 'number') return '-';
const diff = current - base;
if (diff === 0) return '0 ms';
const sign = diff > 0 ? '+' : '-';
return `${sign}${formatMs(Math.abs(diff))}`;
}
function formatMs(value) {
return value < 1000 ? `${value.toFixed(1)} ms` : `${(value / 1000).toFixed(2)} s`;
}
function formatBytes(value) {
const absoluteValue = Math.abs(value);
if (absoluteValue < 1000) return `${value} B`;
if (absoluteValue < 1000 * 1000) return `${(value / 1000).toFixed(1)} kB`;
return `${(value / (1000 * 1000)).toFixed(2)} MB`;
}
function formatSignedBytes(value) {
if (value === 0) return '0 B';
const sign = value > 0 ? '+' : '-';
return `${sign}${formatBytes(Math.abs(value))}`;
}
function writeFile(filePath, contents) {
fs.mkdirSync(path.dirname(path.resolve(filePath)), { recursive: true });
fs.writeFileSync(filePath, contents);
}
async function postGitHubComment(markdownPath, explicitPrNumber) {
const config = readGitHubCommentConfig(explicitPrNumber);
const body = fs.readFileSync(markdownPath, 'utf8');
const commentsUrl = buildCommentsUrl(config.repository, config.prNumber);
const comments = await listGitHubComments(commentsUrl, config.headers);
const existing = comments.find((comment) => comment.body?.includes(COMMENT_MARKER));
await writeGitHubComment(commentsUrl, config.headers, body, existing?.url);
}
function readGitHubCommentConfig(explicitPrNumber) {
const token = process.env.GITHUB_TOKEN;
const repository = process.env.GITHUB_REPOSITORY;
const prNumber = explicitPrNumber ?? process.env.GITHUB_PR_NUMBER;
assertGitHubCommentConfig(token, repository, prNumber);
return {
repository,
prNumber,
headers: buildGitHubHeaders(token),
};
}
function assertGitHubCommentConfig(token, repository, prNumber) {
for (const value of [token, repository, prNumber]) {
if (!value) {
throw new Error(
'GITHUB_TOKEN, GITHUB_REPOSITORY, and PR number are required to post a comment.',
);
}
}
}
function buildGitHubHeaders(token) {
return {
accept: 'application/vnd.github+json',
authorization: `Bearer ${token}`,
'content-type': 'application/json',
'x-github-api-version': '2022-11-28',
};
}
function buildCommentsUrl(repository, prNumber) {
const [owner, repo] = repository.split('/');
return `https://api.github.com/repos/${owner}/${repo}/issues/${prNumber}/comments`;
}
async function listGitHubComments(commentsUrl, headers) {
const response = await fetch(`${commentsUrl}?per_page=100`, { headers });
if (!response.ok) {
throw new Error(`Failed to list PR comments: ${response.status} ${await response.text()}`);
}
return await response.json();
}
async function writeGitHubComment(commentsUrl, headers, body, existingUrl) {
const target = commentWriteTarget(commentsUrl, existingUrl);
const response = await fetch(target.url, {
method: target.method,
headers,
body: JSON.stringify({ body }),
});
await assertGitHubWriteResponse(response, target.action);
}
function commentWriteTarget(commentsUrl, existingUrl) {
if (existingUrl) {
return { url: existingUrl, method: 'PATCH', action: 'update' };
}
return { url: commentsUrl, method: 'POST', action: 'create' };
}
async function assertGitHubWriteResponse(response, action) {
if (!response.ok) {
throw new Error(`Failed to ${action} PR comment: ${response.status} ${await response.text()}`);
}
}