Skip to content

Commit 14435d2

Browse files
committed
ci: compare bundle sizes for key pages
1 parent cd37586 commit 14435d2

1 file changed

Lines changed: 87 additions & 21 deletions

File tree

‎.github/workflows/bundle-size.yml‎

Lines changed: 87 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -39,25 +39,78 @@ jobs:
3939
run: |
4040
node --input-type=module <<'NODE'
4141
import { readdirSync, readFileSync, writeFileSync } from 'node:fs'
42-
import { extname, join } from 'node:path'
42+
import { extname, join, relative, resolve } from 'node:path'
43+
import { pathToFileURL } from 'node:url'
4344
import { gzipSync } from 'node:zlib'
4445
45-
const sizes = { js: 0, jsGzip: 0, css: 0, cssGzip: 0 }
46-
const entries = readdirSync('dist/client/assets', {
46+
const client = 'dist/client'
47+
const totals = { js: 0, jsGzip: 0, css: 0, cssGzip: 0 }
48+
const gzipByHref = new Map()
49+
const entries = readdirSync(join(client, 'assets'), {
4750
recursive: true,
4851
withFileTypes: true,
4952
})
5053
for (const entry of entries) {
5154
const extension = extname(entry.name).slice(1)
5255
if (!entry.isFile() || (extension !== 'js' && extension !== 'css')) continue
53-
const bytes = readFileSync(join(entry.parentPath, entry.name))
54-
sizes[extension] += bytes.length
55-
sizes[`${extension}Gzip`] += gzipSync(bytes).length
56+
const file = join(entry.parentPath, entry.name)
57+
const bytes = readFileSync(file)
58+
const gzip = gzipSync(bytes).length
59+
totals[extension] += bytes.length
60+
totals[`${extension}Gzip`] += gzip
61+
gzipByHref.set(`/${relative(client, file)}`, gzip)
5662
}
57-
if (sizes.js === 0 || sizes.css === 0) {
63+
if (totals.js === 0 || totals.css === 0) {
5864
throw new Error('Expected built JS and CSS in dist/client/assets')
5965
}
60-
writeFileSync(process.env.REPORT_FILE, JSON.stringify(sizes))
66+
67+
const serverAssets = 'dist/server/assets'
68+
const manifestFile = readdirSync(serverAssets).find((file) =>
69+
file.startsWith('_tanstack-start-manifest_'),
70+
)
71+
if (!manifestFile) throw new Error('TanStack Start build manifest is missing')
72+
const { tsrStartManifest } = await import(pathToFileURL(resolve(serverAssets, manifestFile)))
73+
const { routes } = tsrStartManifest()
74+
const parents = new Map()
75+
for (const [id, route] of Object.entries(routes)) {
76+
for (const child of route.children ?? []) parents.set(child, id)
77+
}
78+
79+
const pageRoutes = {
80+
'/': '/',
81+
'/libraries': '/libraries',
82+
'/start/latest': '/_library/start/$version/',
83+
'/router/latest': '/_library/router/$version/',
84+
'/query/latest': '/_library/query/$version/',
85+
'/table/latest': '/_library/table/$version/',
86+
'/charts/latest': '/_library/charts/$version/',
87+
'/ai/latest': '/_library/ai/$version/',
88+
'Docs article': '/_library/$libraryId/$version/docs/$',
89+
'Framework docs article': '/_library/$libraryId/$version/docs/framework/$framework/$',
90+
'/blog': '/blog/',
91+
'/maintainers': '/maintainers',
92+
'/showcase': '/showcase/',
93+
'/chat': '/chat/',
94+
'/chat/c/:conversationId': '/chat/c/$conversationId',
95+
}
96+
const pages = {}
97+
for (const [page, id] of Object.entries(pageRoutes)) {
98+
if (!routes[id]) continue
99+
const matchedRoutes = new Set(['__root__'])
100+
for (let current = id; current; current = parents.get(current)) {
101+
matchedRoutes.add(current)
102+
}
103+
const hrefs = new Set()
104+
for (const matched of matchedRoutes) {
105+
const route = routes[matched]
106+
for (const link of [...(route.preloads ?? []), ...(route.css ?? [])]) {
107+
hrefs.add(typeof link === 'string' ? link : link.href)
108+
}
109+
for (const script of route.scripts ?? []) hrefs.add(script.attrs?.src)
110+
}
111+
pages[page] = [...hrefs].reduce((bytes, href) => bytes + (gzipByHref.get(href) ?? 0), 0)
112+
}
113+
writeFileSync(process.env.REPORT_FILE, JSON.stringify({ totals, pages }))
61114
NODE
62115
- name: Upload bundle sizes
63116
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
@@ -98,11 +151,16 @@ jobs:
98151
]
99152
function readSizes(build) {
100153
const file = join(process.env.RUNNER_TEMP, 'bundle-size', `bundle-size-${build}.json`)
101-
const sizes = JSON.parse(readFileSync(file, 'utf8'))
102-
if (metrics.some(([, key]) => !Number.isSafeInteger(sizes?.[key]) || sizes[key] < 1)) {
154+
const report = JSON.parse(readFileSync(file, 'utf8'))
155+
const validSize = (bytes) => Number.isSafeInteger(bytes) && bytes > 0
156+
if (
157+
metrics.some(([, key]) => !validSize(report.totals?.[key])) ||
158+
!validSize(report.pages?.['/']) ||
159+
Object.values(report.pages).some((bytes) => !validSize(bytes))
160+
) {
103161
throw new Error(`Invalid bundle sizes in ${file}`)
104162
}
105-
return sizes
163+
return report
106164
}
107165
108166
const original = context.payload.pull_request
@@ -111,24 +169,32 @@ jobs:
111169
112170
const main = readSizes('main')
113171
const candidate = readSizes('pr')
114-
const kib = (bytes) => `${(bytes / 1024).toFixed(2)} KiB`
115-
const rows = metrics.map(([label, key]) => {
116-
const before = main[key]
117-
const after = candidate[key]
118-
const delta = after - before
119-
const sign = delta > 0 ? '+' : ''
120-
const change = `${sign}${kib(delta)} (${sign}${(100 * delta / before).toFixed(2)}%)`
172+
const kib = (bytes) => bytes === undefined ? '—' : `${(bytes / 1024).toFixed(2)} KiB`
173+
const sizeRow = (label, before, after) => {
174+
let change = 'Added'
175+
if (after === undefined) change = 'Removed'
176+
else if (before !== undefined) {
177+
const delta = after - before
178+
const sign = delta > 0 ? '+' : ''
179+
change = `${sign}${kib(delta)} (${sign}${(100 * delta / before).toFixed(2)}%)`
180+
}
121181
return `| ${label} | ${kib(before)} | ${kib(after)} | ${change} |`
122-
})
182+
}
183+
const pages = new Set([...Object.keys(main.pages), ...Object.keys(candidate.pages)])
123184
const marker = /^<!-- bundle-size-report:(\d+) -->/
124185
const runUrl = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`
125186
const body = [
126187
`<!-- bundle-size-report:${context.runNumber} -->`,
127-
'### Client bundle size',
128188
'',
129189
'| Asset | Main | PR merge build | Change |',
130190
'| --- | ---: | ---: | ---: |',
131-
...rows,
191+
...metrics.map(([label, key]) => sizeRow(label, main.totals[key], candidate.totals[key])),
192+
'',
193+
'| Page | Main (gzip) | PR merge build (gzip) | Change |',
194+
'| --- | ---: | ---: | ---: |',
195+
...Array.from(pages, (page) => sizeRow(page, main.pages[page], candidate.pages[page])),
196+
'',
197+
'Page sizes sum the JS and CSS in the TanStack Start manifest for each route and its layouts. Shared files count once per page.',
132198
'',
133199
`Compared with main at \`${original.base.sha.slice(0, 7)}\`. Gzip sizes are summed per file. [Build run](${runUrl})`,
134200
].join('\n')

0 commit comments

Comments
 (0)