diff --git a/.github/workflows/size.yml b/.github/workflows/size.yml index 6a90047017..5448ff184f 100644 --- a/.github/workflows/size.yml +++ b/.github/workflows/size.yml @@ -35,6 +35,13 @@ jobs: - name: Setup toolchain uses: ./.github/actions/setup-node-pnpm + - name: Select affected plugins + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: | + node scripts/size-report-plugin-plan.mjs "$BASE_SHA" "$HEAD_SHA" /tmp/agent-device-plugin-size-plan + - name: Preserve report scripts run: | mkdir -p /tmp/agent-device-size-report @@ -65,6 +72,7 @@ jobs: fi node /tmp/agent-device-size-report/size-report.mjs \ --startup-runs 7 \ + --plugins /tmp/agent-device-plugin-size-plan/base.json \ --json /tmp/agent-device-size-base.json # Save immediately: the job-end dist belongs to the PR head, not the base. @@ -83,6 +91,7 @@ jobs: pnpm size \ --compare /tmp/agent-device-size-base.json \ --startup-runs 7 \ + --plugins /tmp/agent-device-plugin-size-plan/head.json \ --json .tmp/size-report.json \ --markdown .tmp/size-report.md cp /tmp/agent-device-size-base.json .tmp/size-report-base.json diff --git a/scripts/__tests__/size-report-package.test.ts b/scripts/__tests__/size-report-package.test.ts index 96b49bc6c1..31f167b911 100644 --- a/scripts/__tests__/size-report-package.test.ts +++ b/scripts/__tests__/size-report-package.test.ts @@ -6,6 +6,7 @@ import { promisify } from 'node:util'; import { test } from 'vitest'; import { mkdtempForTest } from '@agent-device/test-kit'; import { formatMarkdown } from '../size-report.mjs'; +import { planPluginSizes } from '../size-report-plugin-plan.mjs'; import { assertBundledLicenseNotices, assertPublishPackageContents, @@ -625,12 +626,227 @@ test('Markdown emphasizes total install size and startup without duplicate break assert.match(markdown, /\| Package \(download\) \| 90 B \| 100 B \| \+10 B \|/); assert.match(markdown, /\| CLI --help \| 25.0 ms \| 20.0 ms \| -5.0 ms \|/); assert.doesNotMatch(markdown, /JS raw|JS gzip|npm bundled|components|Top.*chunks|packed files/); + assert.doesNotMatch(markdown, /Affected plugins/); assert.match( formatMarkdown(current, null), /\| Installed \(including dependencies\) \| - \| 350 B \| - \|/, ); }); +test('Markdown compares measured plugins and labels added and removed packages', () => { + const core = { + npmPack: { tarballBytes: 100, unpackedBytes: 300 }, + cleanInstalled: { totalBytes: 350 }, + }; + const plugin = { + name: '@agent-device/one', + installedBytes: 60, + unpackedBytes: 30, + tarballBytes: 10, + }; + const markdown = formatMarkdown( + { + ...core, + plugins: [ + { ...plugin, installedBytes: 65 }, + { ...plugin, name: '@agent-device/new' }, + ], + }, + { ...core, plugins: [plugin, { ...plugin, name: '@agent-device/old' }] }, + ); + assert.match( + markdown, + /\| `@agent-device\/one` \| 60 B → 65 B \(\+5 B\) \| 30 B → 30 B \(0 B\) \| 10 B → 10 B \(0 B\) \|/, + ); + assert.match(markdown, /\| `@agent-device\/new` \| 60 B \(new\)/); + assert.match(markdown, /\| `@agent-device\/old` \| 60 B → removed/); + assert.doesNotMatch(formatMarkdown(core, { ...core, plugins: [plugin] }), /Affected plugins/); + assert.match( + formatMarkdown({ ...core, plugins: [] }, { ...core, plugins: [plugin] }), + /\| `@agent-device\/one` \| 60 B → removed/, + ); +}); + +test('exhausted plugin budget keeps the core report and identifies unmeasured sizes', async () => { + const cwd = await mkdtempForTest('size-plugin-budget-'); + const plan = join(cwd, 'plan.json'); + await writeFile(plan, JSON.stringify([{ name: '@agent-device/one', directory: 'packages/one' }])); + const modulePath = join(import.meta.dirname, '../size-report-plugins.mjs'); + const { stdout, stderr } = await execFileAsync( + process.execPath, + [ + '--input-type=module', + '-e', + `const { measurePluginSizes } = await import(process.argv[1]); + let time = 0; + performance.now = () => (time += 120_000); + console.log(JSON.stringify(measurePluginSizes(process.cwd(), process.argv[2])));`, + modulePath, + plan, + ], + { cwd }, + ); + assert.match(stderr, /@agent-device\/one: Plugin measurement budget exhausted/); + const unmeasured = JSON.parse(stdout); + const core = { + npmPack: { tarballBytes: 100, unpackedBytes: 300 }, + cleanInstalled: { totalBytes: 350 }, + }; + const before = { + ...core, + plugins: [ + { name: '@agent-device/one', installedBytes: 60, unpackedBytes: 30, tarballBytes: 10 }, + ], + }; + const after = { ...core, plugins: unmeasured }; + const markdown = formatMarkdown(after, before); + assert.match(markdown, /\| Package \(download\) \| 100 B \| 100 B \| 0 B \|/); + assert.match( + markdown, + /\| `@agent-device\/one` \| 60 B → unavailable \| 30 B → unavailable \| 10 B → unavailable \|/, + ); + assert.match(formatMarkdown(before, after), /\| `@agent-device\/one` \| unavailable → 60 B \|/); +}); + +const one = { + directory: 'packages/one', + manifest: { + name: '@agent-device/one', + exports: { './agent-device': './dist/agent-device.mjs' }, + devDependencies: { '@agent-device/build-piece': 'workspace:*' }, + }, +}; +const two = { + directory: 'packages/two', + manifest: { name: '@agent-device/two', agentDevicePlugin: {} }, +}; +const buildPiece = { + directory: 'packages/build-piece', + manifest: { name: '@agent-device/build-piece', private: true }, +}; +const workspace = [one, two, buildPiece]; +const oneEntry = { directory: one.directory, name: one.manifest.name }; +const twoEntry = { directory: two.directory, name: two.manifest.name }; + +test('plugin plan follows changed build inputs without selecting unrelated plugins', () => { + assert.deepEqual( + planPluginSizes(workspace, workspace, ['src/cli.ts', 'packages/one/src/only.test.ts']), + { base: [], head: [] }, + ); + assert.deepEqual(planPluginSizes(workspace, workspace, ['packages/build-piece/src/index.ts']), { + base: [oneEntry], + head: [oneEntry], + }); + assert.deepEqual(planPluginSizes(workspace, workspace, ['bundler/two/build.mjs']), { + base: [twoEntry], + head: [twoEntry], + }); + assert.deepEqual(planPluginSizes(workspace, workspace, ['tsconfig.lib.json']), { + base: [oneEntry, twoEntry], + head: [oneEntry, twoEntry], + }); +}); + +test('plugin plan selects published v2-only providers by their export', async () => { + const providers = await Promise.all( + ['tizen', 'webos'].map(async (provider) => { + const directory = `packages/provider-${provider}`; + const manifest = JSON.parse( + await readFile(join(import.meta.dirname, '../..', directory, 'package.json'), 'utf8'), + ); + return { directory, manifest }; + }), + ); + for (const { directory, manifest } of providers) { + const entry = { directory, name: manifest.name }; + assert.deepEqual(planPluginSizes(providers, providers, [`${directory}/src/index.ts`]), { + base: [entry], + head: [entry], + }); + } +}); + +test('plugin plan follows a changed lockfile importer', () => { + const base = { importers: { 'packages/one': {}, 'packages/two': {} } }; + const head = { + importers: { + ...base.importers, + 'packages/two': { + dependencies: { 'external-lib': { specifier: '^1.0.0', version: '1.0.0' } }, + }, + }, + }; + assert.deepEqual(planPluginSizes(workspace, workspace, ['pnpm-lock.yaml'], { base, head }), { + base: [twoEntry], + head: [twoEntry], + }); +}); + +test('plugin plans measure added and removed plugins only where they exist', () => { + const other = [two, buildPiece]; + assert.deepEqual(planPluginSizes(other, workspace, ['packages/one/package.json']), { + base: [], + head: [oneEntry], + }); + assert.deepEqual(planPluginSizes(workspace, other, ['packages/one/package.json']), { + base: [oneEntry], + head: [], + }); +}); + +test('plugin selection ignores upstream-only changes in a diverged checkout', async () => { + const cwd = await mkdtempForTest('size-plugin-merge-base-'); + const git = async (...args: string[]) => + ( + await execFileAsync( + 'git', + [ + '-c', + 'user.name=Fixture', + '-c', + 'user.email=fixture@example.com', + '-c', + 'commit.gpgsign=false', + '-c', + 'core.hooksPath=/dev/null', + ...args, + ], + { cwd }, + ) + ).stdout.trim(); + await git('init', '-q'); + for (const { directory, manifest } of workspace) { + await mkdir(join(cwd, directory), { recursive: true }); + await writeFile(join(cwd, directory, 'package.json'), JSON.stringify(manifest)); + } + const lock = join(cwd, 'pnpm-lock.yaml'); + await writeFile(lock, 'settings: {excludeLinksFromLockfile: false}\n'); + await git('add', '.'); + await git('commit', '-qm', 'fork point'); + const fork = await git('rev-parse', 'HEAD'); + await git('mv', two.directory, 'packages/moved-two'); + await writeFile(lock, 'settings: {excludeLinksFromLockfile: true}\n'); + await git('commit', '-qam', 'upstream only'); + const base = await git('rev-parse', 'HEAD'); + await git('checkout', '-q', '--detach', fork); + await writeFile( + lock, + 'settings: {excludeLinksFromLockfile: false}\nimporters: {packages/two: {}}\n', + ); + await git('commit', '-qam', 'PR change'); + + const output = join(cwd, 'plan'); + await execFileAsync( + process.execPath, + [join(import.meta.dirname, '../size-report-plugin-plan.mjs'), base, 'HEAD', output], + { cwd }, + ); + assert.deepEqual(JSON.parse(await readFile(join(output, 'base.json'), 'utf8')), [ + { ...twoEntry, directory: 'packages/moved-two' }, + ]); + assert.deepEqual(JSON.parse(await readFile(join(output, 'head.json'), 'utf8')), [twoEntry]); +}); + test('base measurement uses the measured revision package asset policy', async () => { const workflow = await readFile( join(import.meta.dirname, '../../.github/workflows/size.yml'), diff --git a/scripts/size-report-install.d.mts b/scripts/size-report-install.d.mts index 0e7aa19f56..41a39a0b7f 100644 --- a/scripts/size-report-install.d.mts +++ b/scripts/size-report-install.d.mts @@ -5,6 +5,7 @@ export type DirectoryMeasurement = { packageBytes: number; files: number }; export function measureCleanInstalledPackage( tarballPath: string, packageName: string, + timeout?: number, ): DirectoryMeasurement & { totalBytes: number }; export function assertInstalledSnapshotBridge(packageDir: string): void; diff --git a/scripts/size-report-install.mjs b/scripts/size-report-install.mjs index 9b56ff2ae6..b73f51b1de 100644 --- a/scripts/size-report-install.mjs +++ b/scripts/size-report-install.mjs @@ -4,7 +4,7 @@ import os from 'node:os'; import path from 'node:path'; import { assertSnapshotBridgeAssets, SNAPSHOT_BRIDGE_ASSET_PATHS } from './size-report-package.mjs'; -export function measureCleanInstalledPackage(tarballPath, packageName) { +export function measureCleanInstalledPackage(tarballPath, packageName, timeout = 5 * 60_000) { const workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-device-size-install-')); const consumerDir = path.join(workDir, 'consumer'); const npmCache = path.join(workDir, 'npm-cache'); @@ -27,7 +27,7 @@ export function measureCleanInstalledPackage(tarballPath, packageName) { cwd: consumerDir, env: { ...process.env, npm_config_cache: npmCache }, stdio: ['ignore', 'ignore', 'inherit'], - timeout: 5 * 60 * 1000, + timeout, }, ); const packageDir = path.join(consumerDir, 'node_modules', packageName); diff --git a/scripts/size-report-plugin-plan.d.mts b/scripts/size-report-plugin-plan.d.mts new file mode 100644 index 0000000000..ebebe39b03 --- /dev/null +++ b/scripts/size-report-plugin-plan.d.mts @@ -0,0 +1,14 @@ +type WorkspacePackage = Readonly<{ + directory: string; + manifest: Readonly<{ name: string } & Record>; +}>; + +type PluginPlanEntry = Readonly<{ directory: string; name: string }>; + +export function planPluginSizes( + base: readonly WorkspacePackage[], + head: readonly WorkspacePackage[], + files: readonly string[], + lockfiles?: { base: Record; head: Record }, + comparisonBase?: readonly WorkspacePackage[], +): { base: PluginPlanEntry[]; head: PluginPlanEntry[] }; diff --git a/scripts/size-report-plugin-plan.mjs b/scripts/size-report-plugin-plan.mjs new file mode 100644 index 0000000000..b1cdc876a9 --- /dev/null +++ b/scripts/size-report-plugin-plan.mjs @@ -0,0 +1,181 @@ +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { isDeepStrictEqual } from 'node:util'; +import { parse } from 'yaml'; + +const MANIFEST = /^packages\/[^/]+\/package\.json$/; +const TEST_PATH = /(?:^|\/)(?:__tests__|test|tests)\/|\.(?:test|spec|fixtures)\.[cm]?[jt]sx?$/; +const SHARED_BUILD_INPUT = + /^(?:package\.json|pnpm-workspace\.yaml|\.npmrc|LICENSE|tsconfig[^/]*\.json|scripts\/lib\/bundled-license-notices\.ts)$/; +const ROOT_PLUGIN_INPUT = /^src\/sdk\//; +const BUILD_TOOLS = ['tsdown', 'typescript', '@typescript/native-preview', 'rollup-plugin-license']; + +function git(...args) { + return execFileSync('git', args, { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 }); +} + +function workspaceAt(ref) { + const files = git('ls-tree', '-r', '--name-only', '-z', ref, '--', 'packages').split('\0'); + return files + .filter((file) => MANIFEST.test(file)) + .map((file) => ({ + directory: path.posix.dirname(file), + manifest: JSON.parse(git('show', `${ref}:${file}`)), + })); +} + +function isPublishedPlugin({ manifest }) { + if (manifest.private === true) return false; + const exports = manifest.exports; + const hasPluginExport = + exports !== null && typeof exports === 'object' && Object.hasOwn(exports, './agent-device'); + return hasPluginExport || manifest.agentDevicePlugin !== undefined; +} + +function workspaceClosure(plugin, byName) { + const seen = new Set(); + const pending = [plugin]; + while (pending.length > 0) { + const pkg = pending.pop(); + if (seen.has(pkg.directory)) continue; + seen.add(pkg.directory); + const { dependencies, optionalDependencies, peerDependencies, devDependencies } = pkg.manifest; + for (const [name, source] of Object.entries({ + ...dependencies, + ...optionalDependencies, + ...peerDependencies, + ...devDependencies, + })) { + if (!source.startsWith('workspace:') || name === '@agent-device/test-kit') continue; + const dependency = byName.get(name); + if (dependency) pending.push(dependency); + } + } + return seen; +} + +function changedLockInputs(base, head) { + const { + importers: before = {}, + packages: beforePackages = {}, + snapshots: beforeSnapshots = {}, + ...baseSettings + } = base; + const { + importers: after = {}, + packages: afterPackages = {}, + snapshots: afterSnapshots = {}, + ...headSettings + } = head; + const rootToolsChanged = BUILD_TOOLS.some( + (name) => + !isDeepStrictEqual(before['.']?.devDependencies?.[name], after['.']?.devDependencies?.[name]), + ); + // A lock entry can keep its identity while its transitive resolutions or integrity change. + const shared = + !isDeepStrictEqual(baseSettings, headSettings) || + rootToolsChanged || + changedExistingEntries(beforePackages, afterPackages) || + changedExistingEntries(beforeSnapshots, afterSnapshots); + const directories = new Set( + [...new Set([...Object.keys(before), ...Object.keys(after)])].filter( + (directory) => directory !== '.' && !isDeepStrictEqual(before[directory], after[directory]), + ), + ); + return { shared, directories }; +} + +function changedExistingEntries(before, after) { + return Object.keys(before).some( + (key) => Object.hasOwn(after, key) && !isDeepStrictEqual(before[key], after[key]), + ); +} + +function buildOwner(file) { + if (file === 'scripts/lib/jpeg-decoder-only.ts') return 'maestro'; + return /^(?:build|bundler)\/([^/]+)(?:\/|$)/.exec(file)?.[1]; +} + +function affectedPlugins(workspace, files, lock, knownBuildOwners) { + const byName = new Map(workspace.map((pkg) => [pkg.manifest.name, pkg])); + const shared = + lock.shared || + files.some((file) => { + if (SHARED_BUILD_INPUT.test(file) || ROOT_PLUGIN_INPUT.test(file)) return true; + const owner = buildOwner(file); + return owner !== undefined && !knownBuildOwners.has(owner); + }); + return workspace.filter(isPublishedPlugin).filter((pkg) => { + if (shared) return true; + const closure = workspaceClosure(pkg, byName); + if ([...closure].some((directory) => lock.directories.has(directory))) return true; + const owner = pkg.manifest.name.split('/').at(-1); + const sourcePrefixes = [...closure].map((directory) => `${directory}/`); + return files.some( + (file) => + buildOwner(file) === owner || sourcePrefixes.some((prefix) => file.startsWith(prefix)), + ); + }); +} + +function affectedPluginNames(base, head, files, lockfiles) { + const lock = lockfiles + ? changedLockInputs(lockfiles.base, lockfiles.head) + : { shared: false, directories: new Set() }; + const knownBuildOwners = new Set( + [...base, ...head].filter(isPublishedPlugin).map((pkg) => pkg.manifest.name.split('/').at(-1)), + ); + // The same Maestro build inputs can feed the core on branches where it is built in. + knownBuildOwners.add('maestro'); + const productionFiles = files.filter((file) => !TEST_PATH.test(file)); + return new Set( + [ + ...affectedPlugins(base, productionFiles, lock, knownBuildOwners), + ...affectedPlugins(head, productionFiles, lock, knownBuildOwners), + ].map((pkg) => pkg.manifest.name), + ); +} + +function measurementEntries(workspace, names) { + return workspace + .filter(isPublishedPlugin) + .filter((pkg) => names.has(pkg.manifest.name)) + .map(({ directory, manifest }) => ({ directory, name: manifest.name })); +} + +export function planPluginSizes(base, head, files, lockfiles, comparisonBase = base) { + const names = affectedPluginNames(base, head, files, lockfiles); + return { base: measurementEntries(comparisonBase, names), head: measurementEntries(head, names) }; +} + +if (process.argv[1] && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url) { + const [base, head, output] = process.argv.slice(2); + if (!base || !head || !output) { + throw new Error('Usage: node scripts/size-report-plugin-plan.mjs '); + } + const fork = git('merge-base', base, head).trim(); + const files = git('diff', '--name-only', '--no-renames', '-z', fork, head, '--').split('\0'); + const lockfiles = files.includes('pnpm-lock.yaml') + ? { + base: parse(git('show', `${fork}:pnpm-lock.yaml`)), + head: parse(git('show', `${head}:pnpm-lock.yaml`)), + } + : undefined; + const forkWorkspace = workspaceAt(fork); + const plugins = planPluginSizes( + forkWorkspace, + workspaceAt(head), + files, + lockfiles, + base === fork ? forkWorkspace : workspaceAt(base), + ); + fs.mkdirSync(output, { recursive: true }); + for (const [side, entries] of Object.entries(plugins)) { + fs.writeFileSync(path.join(output, `${side}.json`), JSON.stringify(entries)); + process.stdout.write( + `Plugin sizes (${side}): ${entries.map((entry) => entry.name).join(', ') || 'none'}\n`, + ); + } +} diff --git a/scripts/size-report-plugins.mjs b/scripts/size-report-plugins.mjs new file mode 100644 index 0000000000..7639b452a0 --- /dev/null +++ b/scripts/size-report-plugins.mjs @@ -0,0 +1,91 @@ +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { formatBytes, formatDiff } from './size-report-format.mjs'; +import { measureCleanInstalledPackage, measureDirectory } from './size-report-install.mjs'; + +// Base and head each share this allowance across their selected plugins. +const PLUGIN_MEASUREMENT_BUDGET_MS = 90_000; + +export function measurePluginSizes(root, planPath) { + const plugins = JSON.parse(fs.readFileSync(planPath, 'utf8')); + const deadline = performance.now() + PLUGIN_MEASUREMENT_BUDGET_MS; + return plugins.map((plugin) => { + try { + return measurePlugin(root, plugin, deadline); + } catch (error) { + process.stderr.write(`Could not measure plugin ${plugin.name}: ${error.message}\n`); + return { name: plugin.name, unavailable: true }; + } + }); +} + +function remainingTime(deadline) { + const timeout = Math.ceil(deadline - performance.now()); + if (timeout <= 0) throw new Error('Plugin measurement budget exhausted.'); + return timeout; +} + +function measurePlugin(root, { name, directory }, deadline) { + const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-device-plugin-size-')); + try { + const tarball = path.join(scratch, 'plugin.tgz'); + execFileSync('pnpm', ['pack', '--out', tarball], { + cwd: path.join(root, directory), + stdio: ['ignore', 'ignore', 'inherit'], + timeout: remainingTime(deadline), + }); + execFileSync('tar', ['-xzf', tarball, '-C', scratch], { timeout: remainingTime(deadline) }); + const packageDir = path.join(scratch, 'package'); + const manifest = JSON.parse(fs.readFileSync(path.join(packageDir, 'package.json'), 'utf8')); + if (manifest.name !== name) throw new Error(`Expected to pack ${name}, got ${manifest.name}.`); + const unpackedBytes = measureDirectory(packageDir).packageBytes; + return { + name, + unpackedBytes, + tarballBytes: fs.statSync(tarball).size, + installedBytes: measureCleanInstalledPackage(tarball, name, remainingTime(deadline)) + .totalBytes, + }; + } finally { + fs.rmSync(scratch, { recursive: true, force: true }); + } +} + +export function formatPluginSizes(plugins, basePlugins = []) { + const current = new Map(plugins.map((plugin) => [plugin.name, plugin])); + const base = new Map(basePlugins.map((plugin) => [plugin.name, plugin])); + const names = [...new Set([...current.keys(), ...base.keys()])].sort(); + if (names.length === 0) return ''; + const rows = names.map((name) => { + const before = base.get(name); + const after = current.get(name); + const metrics = ['installedBytes', 'unpackedBytes', 'tarballBytes']; + const cells = metrics.map((metric) => + formatPluginMetric(pluginMetric(before, metric), pluginMetric(after, metric)), + ); + return `| \`${name}\` | ${cells.join(' | ')} |`; + }); + return `### Affected plugins + +| Plugin | Installed (including dependencies) | Unpacked | Download | +|---|---:|---:|---:| +${rows.join('\n')} + +`; +} + +function pluginMetric(plugin, metric) { + return plugin?.unavailable ? 'unavailable' : plugin?.[metric]; +} + +function formatPluginMetric(base, current) { + if (base === 'unavailable' || current === 'unavailable') { + const display = (value) => (typeof value === 'number' ? formatBytes(value) : (value ?? '-')); + return `${display(base)} → ${display(current)}`; + } + if (current === undefined) return `${formatBytes(base)} → removed`; + if (base === undefined) return `${formatBytes(current)} (new)`; + return `${formatBytes(base)} → ${formatBytes(current)} (${formatDiff(base, current)})`; +} diff --git a/scripts/size-report.d.mts b/scripts/size-report.d.mts index 8fc1d1d0ac..ff54599d46 100644 --- a/scripts/size-report.d.mts +++ b/scripts/size-report.d.mts @@ -3,6 +3,15 @@ export type SizeReport = Readonly<{ npmPack: Readonly<{ tarballBytes: number; unpackedBytes: number }>; cleanInstalled: Readonly<{ totalBytes: number }>; + plugins?: readonly ( + | Readonly<{ + name: string; + unpackedBytes: number; + tarballBytes: number; + installedBytes: number; + }> + | Readonly<{ name: string; unavailable: true }> + )[]; startup?: Readonly<{ runs: number; benchmarks: readonly Readonly<{ name: string; medianMs: number }>[]; diff --git a/scripts/size-report.mjs b/scripts/size-report.mjs index 2104885707..473b894f60 100644 --- a/scripts/size-report.mjs +++ b/scripts/size-report.mjs @@ -9,6 +9,7 @@ import { formatBytes, formatDiff, formatMaybeBytes } from './size-report-format. import { collectNpmPack } from './size-report-package.mjs'; import { measureCleanInstalledPackage } from './size-report-install.mjs'; import { preparePublishAssets } from './prepare-publish-assets.mjs'; +import { formatPluginSizes, measurePluginSizes } from './size-report-plugins.mjs'; const COMMENT_MARKER = ''; const GITHUB_REQUEST_ATTEMPTS = 4; @@ -23,6 +24,7 @@ const VALUE_ARGS = new Map([ ['--post-comment', 'postComment'], ['--pr', 'pr'], ['--startup-runs', 'startupRuns'], + ['--plugins', 'plugins'], ]); const STARTUP_BENCHMARKS = [ @@ -46,6 +48,7 @@ async function run() { const report = collectReport(cwd, { startupRuns: parseNonNegativeInteger(args.startupRuns ?? '0', '--startup-runs'), }); + if (args.plugins) report.plugins = measurePluginSizes(cwd, args.plugins); const baseReport = args.compare ? JSON.parse(fs.readFileSync(args.compare, 'utf8')) : null; if (args.json) { @@ -96,6 +99,7 @@ Options: --markdown Write the markdown report. --compare Compare against a previously written JSON report. --startup-runs Measure startup medians for side-effect-free CLI commands. + --plugins Measure the plugin packages selected in this JSON plan. --post-comment Post or update the markdown report on the current PR. --pr Pull request number for --post-comment. `); @@ -203,6 +207,8 @@ function walk(root) { } function formatMarkdown(report, baseReport) { + const pluginSizes = + report.plugins === undefined ? '' : formatPluginSizes(report.plugins, baseReport?.plugins); const rows = [ metricRow( 'Installed (including dependencies)', @@ -223,7 +229,7 @@ function formatMarkdown(report, baseReport) { |---|---:|---:|---:| ${rows.join('\n')} -${formatStartupBenchmarks(report.startup, baseReport?.startup)}`; +${formatStartupBenchmarks(report.startup, baseReport?.startup)}${pluginSizes}`; } function metricRow(label, base, current) {