diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 3ae769e7..15f9846e 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -51,6 +51,10 @@ jobs: if: needs.changes.outputs.lane == 'full' runs-on: ubuntu-24.04-arm timeout-minutes: 10 + # actions: read finds main's size measurement for the run summary. + permissions: + actions: read + contents: read steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0 @@ -73,7 +77,28 @@ jobs: path: coverage/lcov.info if-no-files-found: error - run: pnpm build - - run: pnpm check:size + # The measurement is kept on every run, main's included, as the baseline later pull requests compare against. + - name: Check the size budgets + run: pnpm check:size --json size-report.json --commit "$COMMIT" --base "$BASE" + env: + COMMIT: ${{ github.event.pull_request.head.sha || github.sha }} + BASE: ${{ github.event.pull_request.base.sha || github.event.before }} + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: ${{ !cancelled() && hashFiles('size-report.json') != '' }} + with: + name: size-report + path: size-report.json + if-no-files-found: error + # The pull request comment (report.yml) only runs from main, so the run summary shows the same table before that. + - name: Show the size report + if: ${{ !cancelled() && hashFiles('size-report.json') != '' }} + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + BASE: ${{ github.event.pull_request.base.sha || github.event.before }} + run: | + tools/size-baseline.sh "$REPO" "$BASE" "$RUNNER_TEMP/size-baseline" + node tools/size-report.mjs size-report.json "$RUNNER_TEMP/size-baseline/size-report.json" >> "$GITHUB_STEP_SUMMARY" # The browser suite is most of the run's time, so it is split over parallel runners; each builds its own dist. e2e: diff --git a/.github/workflows/report.yml b/.github/workflows/report.yml new file mode 100644 index 00000000..4962400c --- /dev/null +++ b/.github/workflows/report.yml @@ -0,0 +1,90 @@ +name: Size report + +# Comments a pull request's size measurement against main's. It runs after Check from the default branch's code with its own +# token, so it only reads the run's artifact and never runs the pull request's code, which keeps pull requests from forks safe. +on: + workflow_run: + workflows: [Check] + types: [completed] + +permissions: {} + +# One group per pull request branch, so two quick pushes cannot both find no comment and each create one; the later run waits. +concurrency: + group: size-report-${{ github.event.workflow_run.head_repository.full_name }}-${{ github.event.workflow_run.head_branch }} + +jobs: + report: + if: github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion != 'cancelled' + runs-on: ubuntu-24.04-arm + timeout-minutes: 5 + permissions: + actions: read + contents: read + pull-requests: write + steps: + - name: Check out the trusted renderer + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + - name: Render the report + id: render + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + RUN_ID: ${{ github.event.workflow_run.id }} + run: | + set -euo pipefail + root="$RUNNER_TEMP/size-report" + mkdir -p "$root/run" + echo "root=$root" >> "$GITHUB_OUTPUT" + # A documentation-only run, or one that stopped before measuring, has no artifact. A report larger than 1 MiB is not read. + size=$(gh api "repos/$REPO/actions/runs/$RUN_ID/artifacts?name=size-report" \ + --jq '[.artifacts[] | select(.expired | not)] | first | .size_in_bytes // empty') + if [[ ! $size =~ ^[0-9]+$ ]] || ((size > 1048576)); then + echo "found=false" >> "$GITHUB_OUTPUT" + exit 0 + fi + if ! gh run download "$RUN_ID" -R "$REPO" -n size-report -D "$root/run"; then + echo "found=false" >> "$GITHUB_OUTPUT" + exit 0 + fi + file="$root/run/size-report.json" + if [[ ! -f $file ]] || (($(wc -c < "$file") > 1048576)); then + echo "found=false" >> "$GITHUB_OUTPUT" + exit 0 + fi + base=$(jq -r 'if (.base | type) == "string" and (.base | test("^[0-9a-f]{40}$")) then .base else "" end' "$file" 2>/dev/null || true) + tools/size-baseline.sh "$REPO" "$base" "$root/main" + node tools/size-report.mjs "$file" "$root/main/size-report.json" > "$root/body.md" + echo "found=true" >> "$GITHUB_OUTPUT" + - name: Update the comment on the pull request + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + HEAD_SHA: ${{ github.event.workflow_run.head_sha }} + ROOT: ${{ steps.render.outputs.root }} + FOUND: ${{ steps.render.outputs.found }} + run: | + set -euo pipefail + marker='' + body="$ROOT/body.md" + # Without a measurement the comment is not removed but marked, so numbers from an earlier commit are not read as this one's. + if [[ $FOUND != true ]]; then + printf '**Size report**: commit %s has no size measurement (a documentation-only change, or the run stopped before measuring).\n%s\n' \ + "${HEAD_SHA:0:8}" "$marker" > "$body" + fi + # A pull request from a fork is not listed in the run, so it is found by its head commit. + gh api "repos/$REPO/pulls?state=open&per_page=100" --paginate \ + --jq ".[] | select(.head.sha == \"$HEAD_SHA\" and .base.repo.full_name == \"$REPO\") | .number" > "$ROOT/pulls" + while read -r pr; do + [[ $pr =~ ^[0-9]+$ ]] + comment=$(gh api "repos/$REPO/issues/$pr/comments?per_page=100" --paginate \ + --jq ".[] | select(.user.login == \"github-actions[bot]\" and (.body | contains(\"$marker\"))) | .id" | sed -n 1p) + if [[ -n $comment ]]; then + gh api -X PATCH "repos/$REPO/issues/comments/$comment" -F body=@"$body" > /dev/null + elif [[ $FOUND == true ]]; then + gh api "repos/$REPO/issues/$pr/comments" -F body=@"$body" > /dev/null + fi + done < "$ROOT/pulls" diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index af19712e..abbb9cc0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -176,7 +176,9 @@ Some lists have one home, and everything else reads them: | Visible text comes from catalogues | `check:i18n` | | Size budgets | `check:size` | -`check:size` budgets what a reader downloads, in gzip bytes from the Vite manifest, not the total: the login and Activity startup paths (entry chunk and its static imports, the largest language catalogue, the charts Activity loads), startup CSS, one catalogue, one font stylesheet, each page beyond Activity, the config editor and the mock. The budgets live in `sizeBudget` in `package.json`; a failure names the budget, the measured size, the limit and the largest files. The total is printed for information and does not fail the build. A startup budget that rises needs its reason in the pull request. +`check:size` budgets what a reader downloads, in gzip bytes from the Vite manifest, not the total: the login and Activity startup paths (entry chunk and its static imports, the largest language catalogue, the charts Activity loads), startup CSS, one catalogue, one font stylesheet, each page beyond Activity, the config editor and the mock. The limits live in `sizeBudget` in `package.json`; a failure names the budget, the measured size, the limit and the largest files. The total is printed for information and does not fail the build. + +The limits are fixed ceilings with headroom, not the last measurement, so a feature does not edit them. Each pull request gets a size report instead: a comment, updated on every push, that compares each budget with `main` at the pull request's base and lists the largest parts of any budget that grew; the Check run's summary shows the same table. A change that passes a limit is a signal to slim it down first. Raising a limit is a separate decision, in its own commit, with the reason in the pull request. A reviewer checks the rest by hand: watched and cached reads go through the store, `view.ts` stays pure and tested, components only render, and no engine-specific setting or section name lands outside `src/api/engines`, even as data. diff --git a/tools/check-size.mjs b/tools/check-size.mjs index 1590b6a7..39d6edfe 100644 --- a/tools/check-size.mjs +++ b/tools/check-size.mjs @@ -1,6 +1,11 @@ -import {readdir, readFile} from 'node:fs/promises'; +import {readdir, readFile, writeFile} from 'node:fs/promises'; +import {parseArgs} from 'node:util'; import {gzipSync} from 'node:zlib'; import {checkLimits, evaluate, measure, report, totals} from './size-budget.mjs'; +import {summarize} from './size-report.mjs'; + +// --json also writes the measurement for the size report; --commit and --base name the commit measured and main's commit under it. +const {values: options} = parseArgs({options: {json: {type: 'string'}, commit: {type: 'string'}, base: {type: 'string'}}}); const {sizeBudget} = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8')); checkLimits(sizeBudget); @@ -19,4 +24,5 @@ const results = evaluate(measure(manifest, size), sizeBudget); for (const result of results) console.log(report(result)); const total = totals(sizes); console.log(`total (information only): js ${total.js} bytes gzip, css ${total.css} bytes gzip, ${sizes.size} files`); +if (options.json) await writeFile(options.json, `${JSON.stringify(summarize(results, total, options), null, 2)}\n`); if (results.some(({ok}) => !ok)) process.exitCode = 1; diff --git a/tools/ci-workflows.test.mjs b/tools/ci-workflows.test.mjs index 4b5bdc6b..74303f78 100644 --- a/tools/ci-workflows.test.mjs +++ b/tools/ci-workflows.test.mjs @@ -8,6 +8,7 @@ import {parse} from 'yaml'; const load = name => parse(readFileSync(new URL(`../.github/workflows/${name}.yml`, import.meta.url), 'utf8')); const release = load('release'); const check = load('check'); +const sizeReport = load('report'); const uses = (job, name) => job.steps.find(step => step.uses?.startsWith(`${name}@`)); it('keeps the release write token away from dependency and build steps', () => { @@ -95,3 +96,46 @@ it('publishes standalone assets before honk is available', () => { expect(files).toContain('release/*-${{ env.NPM }}.tar.gz'); expect(release.jobs.sums.steps.some(step => step.run?.includes('sha256sum -- *'))).toBe(true); }); + +it('keeps the size measurement of every Check run and shows it in the run summary', () => { + expect(check.permissions).toEqual({contents: 'read'}); + expect(check.jobs.check.permissions).toEqual({actions: 'read', contents: 'read'}); + const steps = check.jobs.check.steps; + const measure = steps.findIndex(step => step.run?.startsWith('pnpm check:size --json size-report.json')); + const upload = steps.findIndex(step => step.uses?.startsWith('actions/upload-artifact@') && step.with.name === 'size-report'); + const summary = steps.findIndex(step => step.name === 'Show the size report'); + expect(measure).toBeGreaterThan(steps.findIndex(step => step.run === 'pnpm build')); + expect(upload).toBeGreaterThan(measure); + expect(summary).toBeGreaterThan(upload); + // An over-limit build fails the measuring step, and that is when the numbers matter most. + for (const index of [upload, summary]) expect(steps[index].if).toMatch(/!cancelled\(\)/); + expect(steps[summary].run).toMatch(/>> "\$GITHUB_STEP_SUMMARY"/); +}); + +it('comments the size report from the default branch with a write token only in that job', () => { + expect(sizeReport.on.workflow_run.workflows).toEqual(['Check']); + expect(sizeReport.permissions).toEqual({}); + const {report} = sizeReport.jobs; + expect(report.permissions).toEqual({actions: 'read', contents: 'read', 'pull-requests': 'write'}); + expect(report.if).toMatch(/workflow_run\.event == 'pull_request'/); + expect(uses(report, 'actions/checkout').with).toEqual({ref: '${{ github.event.repository.default_branch }}', 'persist-credentials': false}); + const script = report.steps.map(step => step.run ?? '').join('\n'); + expect(script).not.toMatch(/pnpm|npm |npx|git checkout/); + expect(script).toContain(''); + // One group per pull request branch and no cancelling, so a second run waits for the first instead of both creating a comment. + expect(sizeReport.concurrency).toEqual({ + group: 'size-report-${{ github.event.workflow_run.head_repository.full_name }}-${{ github.event.workflow_run.head_branch }}' + }); + expect(script).toMatch(/size_in_bytes/); + expect(script).not.toMatch(/head -n/); + expect(script).toMatch(/-X PATCH "repos\/\$REPO\/issues\/comments\//); +}); + +it('pins every action in every workflow by commit', () => { + expect(sizeReport.jobs.report.steps.filter(step => step.uses).length).toBeGreaterThan(0); + for (const workflow of [check, release, sizeReport]) { + for (const job of Object.values(workflow.jobs)) { + for (const step of job.steps ?? []) if (step.uses) expect(step.uses).toMatch(/^[\w.-]+\/[\w.-]+@[0-9a-f]{40}$/); + } + } +}); diff --git a/tools/size-baseline.sh b/tools/size-baseline.sh new file mode 100755 index 00000000..47435d02 --- /dev/null +++ b/tools/size-baseline.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +# Usage: tools/size-baseline.sh +# Downloads main's size measurement into /size-report.json: the one from main's Check run on the base commit, else +# the one from main's newest successful Check run that still has it. The report names which commit it came from. Without one, +# or when the API fails, it writes nothing and exits 0, so the report shows no baseline instead of failing the run. Needs +# GH_TOKEN with actions: read. +set -uo pipefail + +repo=$1 +base=$2 +dir=$3 +mkdir -p "$dir" +[[ $repo =~ ^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$ ]] || exit 0 +[[ $base =~ ^[0-9a-f]{40}$ ]] || base= +for tool in gh unzip; do + command -v "$tool" >/dev/null || { echo "::warning::size-baseline.sh needs $tool; the report has no baseline" >&2; exit 0; } +done + +# Main's own runs: Check runs only on pushes to main and on pull requests, and a pull request from a fork's main branch has a +# different head repository. +main='select(.workflow_run.head_branch == "main" and .workflow_run.head_repository_id == .workflow_run.repository_id)' +id= +if [[ -n $base ]]; then + for run in $(gh api "repos/$repo/actions/workflows/check.yml/runs?head_sha=$base&branch=main&per_page=20" \ + --jq '.workflow_runs[] | select(.event != "pull_request") | .id' 2>/dev/null); do + id=$(gh api "repos/$repo/actions/runs/$run/artifacts?name=size-report" \ + --jq "[.artifacts[] | select(.expired | not) | $main] | .[0].id // empty" 2>/dev/null) + [[ -n $id ]] && break + done +fi +if [[ -z $id ]]; then + # Main's newest successful Check runs, the first of which that still has its artifact. + for run in $(gh api "repos/$repo/actions/workflows/check.yml/runs?branch=main&event=push&status=success&per_page=20" \ + --jq '.workflow_runs[] | .id' 2>/dev/null); do + id=$(gh api "repos/$repo/actions/runs/$run/artifacts?name=size-report" \ + --jq "[.artifacts[] | select(.expired | not) | $main] | .[0].id // empty" 2>/dev/null) + [[ -n $id ]] && break + done +fi +[[ $id =~ ^[0-9]+$ ]] || exit 0 + +scratch=$(mktemp -d) +trap 'rm -rf "$scratch"' EXIT +gh api "repos/$repo/actions/artifacts/$id/zip" >"$scratch/artifact.zip" 2>/dev/null || exit 0 +unzip -p "$scratch/artifact.zip" size-report.json 2>/dev/null | head -c 1048576 >"$scratch/size-report.json" || exit 0 +[[ -s $scratch/size-report.json ]] && mv "$scratch/size-report.json" "$dir/size-report.json" +exit 0 diff --git a/tools/size-report-fixture/main.json b/tools/size-report-fixture/main.json new file mode 100644 index 00000000..b95a3b72 --- /dev/null +++ b/tools/size-report-fixture/main.json @@ -0,0 +1,30 @@ +{ + "schema": 1, + "commit": "568f266c00000000000000000000000000000000", + "base": null, + "budgets": [ + { + "name": "startupLogin", + "limit": 227000, + "bytes": 216051, + "label": "login", + "parts": [ + {"file": "assets/index-Bx1yQ2aZ.js", "bytes": 150000}, + {"file": "assets/Login-Ab3dE5fG.js", "bytes": 40000}, + {"file": "assets/locale-zh-CN-Qw8rT6yU.js", "bytes": 26051} + ] + }, + {"name": "startupCss", "limit": 34000, "bytes": 31552, "label": "activity", "parts": [{"file": "assets/index-Cd2eF4gH.css", "bytes": 31552}]}, + { + "name": "route", + "limit": 76000, + "bytes": 71925, + "label": "src/features/rules/Rules.tsx", + "parts": [ + {"file": "assets/Rules-Zz9yX8wV.js", "bytes": 50000}, + {"file": "assets/table-Uu7tS6rQ.js", "bytes": 21925} + ] + } + ], + "total": {"js": 900000, "css": 40000} +} diff --git a/tools/size-report-fixture/pr.json b/tools/size-report-fixture/pr.json new file mode 100644 index 00000000..7078975a --- /dev/null +++ b/tools/size-report-fixture/pr.json @@ -0,0 +1,31 @@ +{ + "schema": 1, + "commit": "1a2b3c4d00000000000000000000000000000000", + "base": "568f266c00000000000000000000000000000000", + "budgets": [ + { + "name": "startupLogin", + "limit": 227000, + "bytes": 216471, + "label": "login", + "parts": [ + {"file": "assets/index-Kk1lM2nO.js", "bytes": 150400}, + {"file": "assets/Login-Pp3qR4sT.js", "bytes": 40020}, + {"file": "assets/locale-zh-CN-Qw8rT6yU.js", "bytes": 26051} + ] + }, + {"name": "startupCss", "limit": 34000, "bytes": 31500, "label": "activity", "parts": [{"file": "assets/index-Ee5fG6hI.css", "bytes": 31500}]}, + { + "name": "route", + "limit": 76000, + "bytes": 76210, + "label": "src/features/rules/Rules.tsx", + "parts": [ + {"file": "assets/Rules-Jj1kL2mN.js", "bytes": 52000}, + {"file": "assets/table-Uu7tS6rQ.js", "bytes": 21925}, + {"file": "assets/trace-Vv3wX4yZ.js", "bytes": 2285} + ] + } + ], + "total": {"js": 905000, "css": 39950} +} diff --git a/tools/size-report.mjs b/tools/size-report.mjs new file mode 100644 index 00000000..7e9d9643 --- /dev/null +++ b/tools/size-report.mjs @@ -0,0 +1,136 @@ +// The size report: `check:size --json` writes one measurement per build, and this renders a pull request's measurement against +// main's as the Markdown table CI shows in the run summary and in the pull request comment. The renderer also reads files built +// from a fork's code, so it validates every field and prints names only through `code`. +import {existsSync, readFileSync} from 'node:fs'; +import {pathToFileURL} from 'node:url'; + +export const marker = ''; +const sha = /^[0-9a-f]{40}$/; +const partsKept = 20; +const partsShown = 5; +// A measurement has a handful of budgets; more than these is not one of ours, so it is rejected whole. +const budgetsMax = 50; +const partsMax = 200; + +// The measurement as written to JSON: one row per budget with its worst entry and that entry's largest files. +export function summarize(results, total, {commit, base} = {}) { + return { + schema: 1, + commit: sha.test(commit ?? '') ? commit : null, + base: sha.test(base ?? '') ? base : null, + budgets: results.map(({name, limit, worst}) => ({ + name, + limit, + bytes: worst.bytes, + label: worst.label, + parts: worst.parts.slice(0, partsKept).map(([file, bytes]) => ({file, bytes})) + })), + total + }; +} + +const count = value => (Number.isSafeInteger(value) && value >= 0 ? value : null); +const text = value => (typeof value === 'string' ? value : ''); + +// Keeps what the report needs from a measurement and drops anything malformed, so a bad file shows as missing data. +export function parse(data) { + if (data?.schema !== 1 || !Array.isArray(data.budgets) || data.budgets.length > budgetsMax) return null; + if (data.budgets.some(budget => Array.isArray(budget?.parts) && budget.parts.length > partsMax)) return null; + const budgets = data.budgets + .filter(budget => /^[A-Za-z][A-Za-z0-9]{0,39}$/.test(text(budget?.name))) + .map(({name, limit, bytes, label, parts}) => ({ + name, + limit: count(limit), + bytes: count(bytes), + label: text(label), + parts: (Array.isArray(parts) ? parts : []) + .slice(0, partsKept) + .flatMap(part => (count(part?.bytes) === null ? [] : [{file: text(part.file), bytes: part.bytes}])) + })); + return { + commit: sha.test(text(data.commit)) ? data.commit : null, + base: sha.test(text(data.base)) ? data.base : null, + budgets, + total: {js: count(data.total?.js), css: count(data.total?.css)} + }; +} + +// A name in a code span, reduced to the characters file names and labels use. +const code = value => `\`${value.replace(/[^\w./@?=&()*\- ]/g, '').slice(0, 120) || '?'}\``; +const short = commit => commit.slice(0, 8); +const kb = bytes => (bytes === null ? '—' : `${(bytes / 1000).toFixed(1)} KB`); +const change = (now, before) => (now === null || before === null ? '—' : `${now > before ? '+' : now < before ? '−' : ''}${Math.abs(now - before)} B`); +// Vite names built files `name-hash.ext`; without the hash, a file can be matched across builds. +const unhashed = file => file.replace(/-[\w-]{8}(\.\w+)$/, '-*$1'); + +function partsTable({name, bytes, parts}, before) { + const previous = new Map(); + for (const part of before?.parts ?? []) { + const key = unhashed(part.file); + previous.set(key, previous.has(key) ? null : part.bytes); + } + const rows = parts.slice(0, partsShown).map(part => { + const key = unhashed(part.file); + return `| ${code(key)} | ${kb(part.bytes)} | ${previous.has(key) ? change(part.bytes, previous.get(key)) : before ? 'new' : '—'} |`; + }); + return [`**${name}** (${change(bytes, before?.bytes ?? null)})`, '', '| Part | This PR | Change |', '|---|---|---|', ...rows].join('\n'); +} + +// `current` is this build's measurement; `baseline` is main's, or null when main has none. +export function render(current, baseline) { + if (!current) return `❌ **Size report**: the measurement is missing or unreadable.\n${marker}\n`; + const before = new Map((baseline?.budgets ?? []).map(budget => [budget.name, budget])); + const over = current.budgets.filter(({bytes, limit}) => bytes === null || limit === null || bytes > limit); + const head = current.commit ? `${short(current.commit)} ` : ''; + let against; + if (!baseline) against = 'with no `main` measurement to compare'; + else if (baseline.commit && baseline.commit === current.base) against = `vs \`main\` ${short(baseline.commit)}`; + else { + const missing = current.base ? `, none for the base ${short(current.base)}` : ''; + against = `vs the newest \`main\` measurement${baseline.commit ? ` ${short(baseline.commit)}` : ''}${missing}`; + } + const verdict = over.length ? `${over.length} over limit (${over.map(({name}) => name).join(', ')})` : 'no limits exceeded'; + const lines = [ + `${over.length ? '❌' : '✅'} **Size report** ${head}${against}: ${verdict}`, + '', + 'Gzip bytes each budget counts; a limit is a fixed ceiling in `sizeBudget` in `package.json`.', + '', + '| | This PR | `main` | Change | Limit |', + '|---|---|---|---|---|' + ]; + for (const budget of current.budgets) { + const previous = before.get(budget.name)?.bytes ?? null; + const mark = over.includes(budget) ? '❌ ' : ''; + lines.push( + `| ${mark}${code(budget.name)} (${code(budget.label)}) | ${kb(budget.bytes)} | ${kb(previous)} | ${change(budget.bytes, previous)} | ${kb(budget.limit)} |` + ); + } + const grew = current.budgets.filter(budget => { + const previous = before.get(budget.name)?.bytes; + return budget.bytes !== null && Number.isSafeInteger(previous) && budget.bytes > previous && budget.parts.length; + }); + if (grew.length) { + lines.push('', `
Largest parts of the ${grew.length} ${grew.length === 1 ? 'budget' : 'budgets'} that grew`, ''); + for (const budget of grew) lines.push(partsTable(budget, before.get(budget.name)), ''); + lines.push('
'); + } + if (current.total.js !== null && current.total.css !== null) { + lines.push('', `Everything built, for information: JS ${kb(current.total.js)}, CSS ${kb(current.total.css)}.`); + } + lines.push(marker); + return `${lines.join('\n')}\n`; +} + +const load = path => { + if (!path || !existsSync(path)) return null; + try { + return parse(JSON.parse(readFileSync(path, 'utf8'))); + } catch { + return null; + } +}; + +// node tools/size-report.mjs [] prints the report. +if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) { + process.stdout.write(render(load(process.argv[2]), load(process.argv[3]))); +} diff --git a/tools/size-report.test.mjs b/tools/size-report.test.mjs new file mode 100644 index 00000000..c0546236 --- /dev/null +++ b/tools/size-report.test.mjs @@ -0,0 +1,103 @@ +import {readFileSync} from 'node:fs'; +import {expect, it} from 'vitest'; +import {marker, parse, render, summarize} from './size-report.mjs'; + +const fixture = name => JSON.parse(readFileSync(new URL(`size-report-fixture/${name}.json`, import.meta.url), 'utf8')); +const current = parse(fixture('pr')); +const main = parse(fixture('main')); + +it('renders a pull request against main with the parts of every budget that grew', () => { + expect(render(current, main)).toBe( + [ + '❌ **Size report** 1a2b3c4d vs `main` 568f266c: 1 over limit (route)', + '', + 'Gzip bytes each budget counts; a limit is a fixed ceiling in `sizeBudget` in `package.json`.', + '', + '| | This PR | `main` | Change | Limit |', + '|---|---|---|---|---|', + '| `startupLogin` (`login`) | 216.5 KB | 216.1 KB | +420 B | 227.0 KB |', + '| `startupCss` (`activity`) | 31.5 KB | 31.6 KB | −52 B | 34.0 KB |', + '| ❌ `route` (`src/features/rules/Rules.tsx`) | 76.2 KB | 71.9 KB | +4285 B | 76.0 KB |', + '', + '
Largest parts of the 2 budgets that grew', + '', + '**startupLogin** (+420 B)', + '', + '| Part | This PR | Change |', + '|---|---|---|', + '| `assets/index-*.js` | 150.4 KB | +400 B |', + '| `assets/Login-*.js` | 40.0 KB | +20 B |', + '| `assets/locale-zh-CN-*.js` | 26.1 KB | 0 B |', + '', + '**route** (+4285 B)', + '', + '| Part | This PR | Change |', + '|---|---|---|', + '| `assets/Rules-*.js` | 52.0 KB | +2000 B |', + '| `assets/table-*.js` | 21.9 KB | 0 B |', + '| `assets/trace-*.js` | 2.3 KB | new |', + '', + '
', + '', + 'Everything built, for information: JS 905.0 KB, CSS 40.0 KB.', + marker, + '' + ].join('\n') + ); +}); + +it('says when main has no measurement for the base commit or none at all', () => { + const older = {...main, commit: 'f'.repeat(40)}; + expect(render(current, older).split('\n')[0]).toBe( + '❌ **Size report** 1a2b3c4d vs the newest `main` measurement ffffffff, none for the base 568f266c: 1 over limit (route)' + ); + const report = render(current, null); + expect(report.split('\n')[0]).toBe('❌ **Size report** 1a2b3c4d with no `main` measurement to compare: 1 over limit (route)'); + expect(report).toContain('| `startupLogin` (`login`) | 216.5 KB | — | — | 227.0 KB |'); + expect(report).not.toContain('
'); +}); + +it('passes when every budget is within its limit', () => { + const within = {...current, budgets: current.budgets.map(budget => ({...budget, limit: 1_000_000}))}; + expect(render(within, main).split('\n')[0]).toBe('✅ **Size report** 1a2b3c4d vs `main` 568f266c: no limits exceeded'); + expect(render(within, main)).not.toContain('❌'); +}); + +it('prints names from a fork only as plain code spans', () => { + const hostile = fixture('pr'); + hostile.budgets[0].label = 'login` | \n## heading'; + hostile.budgets[0].parts[0].file = '`](https://example.com)'; + hostile.budgets.push({name: 'evil`name', limit: 1, bytes: 2, label: '', parts: []}); + const report = render(parse(hostile), main); + expect(report).toContain('| `startupLogin` (`login img src=x onerror=alert(1) heading`) |'); + expect(report).toContain('| `(https//example.com)` | 150.4 KB | new |'); + expect(report).not.toMatch(/evil| { + expect(parse({schema: 2, budgets: []})).toBeNull(); + expect(parse(null)).toBeNull(); + const broken = parse({schema: 1, commit: 'not a sha', budgets: [{name: 'route', limit: -1, bytes: 1.5, label: 7, parts: [{file: 'a.js', bytes: 'x'}]}]}); + expect(broken).toEqual({commit: null, base: null, budgets: [{name: 'route', limit: null, bytes: null, label: '', parts: []}], total: {js: null, css: null}}); + expect(render(broken, null)).toContain('| ❌ `route` (`?`) | — | — | — | — |'); + expect(render(null, main)).toBe(`❌ **Size report**: the measurement is missing or unreadable.\n${marker}\n`); +}); + +it('rejects a measurement with too many budgets or parts', () => { + const budget = parts => ({name: 'route', limit: 1, bytes: 1, label: '', parts}); + const part = {file: 'a.js', bytes: 1}; + expect(parse({schema: 1, budgets: Array.from({length: 50}, () => budget([]))})).not.toBeNull(); + expect(parse({schema: 1, budgets: Array.from({length: 51}, () => budget([]))})).toBeNull(); + expect(parse({schema: 1, budgets: [budget(Array.from({length: 200}, () => part))]})).not.toBeNull(); + expect(parse({schema: 1, budgets: [budget(Array.from({length: 201}, () => part))]})).toBeNull(); +}); + +it('writes each budget with its worst entry, its largest parts and the commits measured', () => { + const worst = {bytes: 30, label: 'login', parts: Array.from({length: 25}, (_, index) => [`assets/${index}.js`, 25 - index])}; + const written = summarize([{name: 'startupLogin', limit: 40, ok: true, worst}], {js: 30, css: 0}, {commit: 'a'.repeat(40), base: ''}); + expect(written).toMatchObject({schema: 1, commit: 'a'.repeat(40), base: null, total: {js: 30, css: 0}}); + expect(written.budgets[0]).toMatchObject({name: 'startupLogin', limit: 40, bytes: 30, label: 'login'}); + expect(written.budgets[0].parts).toHaveLength(20); + expect(written.budgets[0].parts[0]).toEqual({file: 'assets/0.js', bytes: 25}); + expect(parse(JSON.parse(JSON.stringify(written))).budgets[0].parts).toHaveLength(20); +});