diff --git a/.github/workflows/bundle-size.yml b/.github/workflows/bundle-size.yml new file mode 100644 index 000000000..9306461c6 --- /dev/null +++ b/.github/workflows/bundle-size.yml @@ -0,0 +1,214 @@ +name: Bundle Size + +on: + pull_request: + branches: [main] + +permissions: + contents: read + +concurrency: + group: bundle-size-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + build: + name: Measure ${{ matrix.build }} bundle + runs-on: ubuntu-latest + strategy: + matrix: + include: + - build: main + ref: ${{ github.event.pull_request.base.sha }} + - build: pr + ref: ${{ github.sha }} + steps: + - name: Checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + ref: ${{ matrix.ref }} + fetch-depth: 0 + persist-credentials: false + - name: Setup Tools + uses: tanstack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main + - name: Build + run: pnpm build + - name: Measure client assets + env: + REPORT_FILE: ${{ runner.temp }}/bundle-size-${{ matrix.build }}.json + run: | + node --input-type=module <<'NODE' + import { readdirSync, readFileSync, writeFileSync } from 'node:fs' + import { extname, join, relative, resolve } from 'node:path' + import { pathToFileURL } from 'node:url' + import { gzipSync } from 'node:zlib' + + const client = 'dist/client' + const totals = { js: 0, jsGzip: 0, css: 0, cssGzip: 0 } + const gzipByHref = new Map() + const entries = readdirSync(join(client, 'assets'), { + recursive: true, + withFileTypes: true, + }) + for (const entry of entries) { + const extension = extname(entry.name).slice(1) + if (!entry.isFile() || (extension !== 'js' && extension !== 'css')) continue + const file = join(entry.parentPath, entry.name) + const bytes = readFileSync(file) + const gzip = gzipSync(bytes).length + totals[extension] += bytes.length + totals[`${extension}Gzip`] += gzip + gzipByHref.set(`/${relative(client, file)}`, gzip) + } + if (totals.js === 0 || totals.css === 0) { + throw new Error('Expected built JS and CSS in dist/client/assets') + } + + const serverAssets = 'dist/server/assets' + const manifestFile = readdirSync(serverAssets).find((file) => + file.startsWith('_tanstack-start-manifest_'), + ) + if (!manifestFile) throw new Error('TanStack Start build manifest is missing') + const { tsrStartManifest } = await import(pathToFileURL(resolve(serverAssets, manifestFile))) + const { routes } = tsrStartManifest() + const parents = new Map() + for (const [id, route] of Object.entries(routes)) { + for (const child of route.children ?? []) parents.set(child, id) + } + + const pageRoutes = { + '/': '/', + '/libraries': '/libraries', + '/start/latest': '/_library/start/$version/', + '/router/latest': '/_library/router/$version/', + '/query/latest': '/_library/query/$version/', + '/table/latest': '/_library/table/$version/', + '/charts/latest': '/_library/charts/$version/', + '/ai/latest': '/_library/ai/$version/', + 'Docs article': '/_library/$libraryId/$version/docs/$', + 'Framework docs article': '/_library/$libraryId/$version/docs/framework/$framework/$', + '/blog': '/blog/', + '/maintainers': '/maintainers', + '/showcase': '/showcase/', + '/chat': '/chat/', + '/chat/c/:conversationId': '/chat/c/$conversationId', + } + const pages = {} + for (const [page, id] of Object.entries(pageRoutes)) { + if (!routes[id]) continue + const matchedRoutes = new Set(['__root__']) + for (let current = id; current; current = parents.get(current)) { + matchedRoutes.add(current) + } + const hrefs = new Set() + for (const matched of matchedRoutes) { + const route = routes[matched] + for (const link of [...(route.preloads ?? []), ...(route.css ?? [])]) { + hrefs.add(typeof link === 'string' ? link : link.href) + } + for (const script of route.scripts ?? []) hrefs.add(script.attrs?.src) + } + pages[page] = [...hrefs].reduce((bytes, href) => bytes + (gzipByHref.get(href) ?? 0), 0) + } + writeFileSync(process.env.REPORT_FILE, JSON.stringify({ totals, pages })) + NODE + - name: Upload bundle sizes + uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 + with: + name: bundle-size-${{ matrix.build }} + path: ${{ runner.temp }}/bundle-size-${{ matrix.build }}.json + if-no-files-found: error + overwrite: true + retention-days: 7 + + comment: + name: Comment on bundle sizes + needs: build + if: >- + github.event.pull_request.head.repo.id == github.event.repository.id && + github.actor != 'dependabot[bot]' + runs-on: ubuntu-latest + permissions: + pull-requests: write + steps: + - name: Download bundle sizes + uses: actions/download-artifact@70fc10c6e5e1ce46ad2ea6f2b72d43f7d47b13c3 # v8.0.0 + with: + pattern: bundle-size-{main,pr} + merge-multiple: true + path: ${{ runner.temp }}/bundle-size + - name: Update pull request comment + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 + with: + script: | + const { readFileSync } = require('node:fs') + const { join } = require('node:path') + const metrics = [ + ['JavaScript', 'js'], + ['JavaScript (gzip)', 'jsGzip'], + ['CSS', 'css'], + ['CSS (gzip)', 'cssGzip'], + ] + function readSizes(build) { + const file = join(process.env.RUNNER_TEMP, 'bundle-size', `bundle-size-${build}.json`) + const report = JSON.parse(readFileSync(file, 'utf8')) + const validSize = (bytes) => Number.isSafeInteger(bytes) && bytes > 0 + if ( + metrics.some(([, key]) => !validSize(report.totals?.[key])) || + !validSize(report.pages?.['/']) || + Object.values(report.pages).some((bytes) => !validSize(bytes)) + ) { + throw new Error(`Invalid bundle sizes in ${file}`) + } + return report + } + + const original = context.payload.pull_request + const { data: pr } = await github.rest.pulls.get({ ...context.repo, pull_number: original.number }) + if (pr.state !== 'open' || pr.base.ref !== 'main' || pr.head.sha !== original.head.sha) return + + const main = readSizes('main') + const candidate = readSizes('pr') + const kib = (bytes) => bytes === undefined ? '—' : `${(bytes / 1024).toFixed(2)} KiB` + const sizeRow = (label, before, after) => { + let change = 'Added' + if (after === undefined) change = 'Removed' + else if (before !== undefined) { + const delta = after - before + const sign = delta > 0 ? '+' : '' + change = `${sign}${kib(delta)} (${sign}${(100 * delta / before).toFixed(2)}%)` + } + return `| ${label} | ${kib(before)} | ${kib(after)} | ${change} |` + } + const pages = new Set([...Object.keys(main.pages), ...Object.keys(candidate.pages)]) + const marker = /^/ + const runUrl = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}` + const body = [ + ``, + '', + '| Asset | Main | PR merge build | Change |', + '| --- | ---: | ---: | ---: |', + ...metrics.map(([label, key]) => sizeRow(label, main.totals[key], candidate.totals[key])), + '', + '| Page | Main (gzip) | PR merge build (gzip) | Change |', + '| --- | ---: | ---: | ---: |', + ...Array.from(pages, (page) => sizeRow(page, main.pages[page], candidate.pages[page])), + '', + 'Page sizes sum the JS and CSS in the TanStack Start manifest for each route and its layouts. Shared files count once per page.', + '', + `Compared with main at \`${original.base.sha.slice(0, 7)}\`. Gzip sizes are summed per file. [Build run](${runUrl})`, + ].join('\n') + + const issue = { ...context.repo, issue_number: pr.number } + for await (const { data: comments } of github.paginate.iterator(github.rest.issues.listComments, issue)) { + const previous = comments.find((comment) => + comment.user?.login === 'github-actions[bot]' && marker.test(comment.body), + ) + if (!previous) continue + const previousRun = Number(previous.body.match(marker)[1]) + if (previousRun <= context.runNumber && previous.body !== body) { + await github.rest.issues.updateComment({ ...context.repo, comment_id: previous.id, body }) + } + return + } + await github.rest.issues.createComment({ ...issue, body })