Repository navigation
Expand file tree
/
Copy pathcompare.js
More file actions
executable file
·348 lines (307 loc) · 13.6 KB
/
Copy pathcompare.js
File metadata and controls
executable file
·348 lines (307 loc) · 13.6 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
#!/usr/bin/env node
/**
* Copyright IBM Corp. 2021, 2025
* SPDX-License-Identifier: MPL-2.0
*/
const originalFilesize = require('filesize')
const numberToWords = require('number-to-words')
const fs = require('fs')
const path = require('path')
const { getBuildOutputDirectory, getOptions } = require('./utils')
// Override default filesize options to display a non-breakable space as a spacer.
const filesize = (bytes, options) => {
return originalFilesize(bytes, {
spacer: ' ',
...options,
})
}
// Pull options from `package.json`
const options = getOptions()
const BUDGET = options.budget
const BUDGET_PERCENT_INCREASE_RED = options.budgetPercentIncreaseRed
// this must be explicitly set to false not to render
const SHOW_DETAILS =
options.showDetails === undefined ? true : options.showDetails
const BUILD_OUTPUT_DIRECTORY = getBuildOutputDirectory(options)
const PACKAGE_NAME = options.name
const SKIP_COMMENT_IF_EMPTY = options.skipCommentIfEmpty
// import the current and base branch bundle stats
const currentBundle = require(path.join(
process.cwd(),
BUILD_OUTPUT_DIRECTORY,
'analyze/__bundle_analysis.json'
))
const baseBundle = require(path.join(
process.cwd(),
BUILD_OUTPUT_DIRECTORY,
'analyze/base/bundle/__bundle_analysis.json'
))
// kick it off
let output = `## 📦 Next.js Bundle Analysis for ${PACKAGE_NAME}
This analysis was generated by the [Next.js Bundle Analysis action](https://github.com/hashicorp/nextjs-bundle-analysis). 🤖
`
// pull the global bundle out, we handle this separately
const globalBundleCurrent = currentBundle.__global
const globalBundleBase = baseBundle.__global
delete currentBundle.__global
delete baseBundle.__global
// calculate the difference between the current bundle and the base branch's
let globalBundleChanges = false
const globalGzipDiff = globalBundleCurrent.gzip - globalBundleBase.gzip
// only report a global bundle size change if we don't have a minimum change
// threshold configured, or if the change is greater than the threshold
if (
globalGzipDiff !== 0 &&
(!('minimumChangeThreshold' in options) ||
Math.abs(globalGzipDiff) > options.minimumChangeThreshold)
) {
globalBundleChanges = {
page: 'global',
raw: globalBundleCurrent.raw,
gzip: globalBundleCurrent.gzip,
gzipDiff: globalGzipDiff,
increase: Math.sign(globalGzipDiff) > 0,
}
}
// now we're going to go through each of the pages in the current bundle and
// run analysis on each one.
const changedPages = []
const newPages = []
for (let page in currentBundle) {
const currentStats = currentBundle[page]
const baseStats = baseBundle[page]
// if the page does't appear in the base bundle, it is a new page, we can
// push this directly to its own category. we also don't compare it to anything
// because its a new page.
if (!baseStats) {
newPages.push({ page, ...currentStats })
} else if (currentStats.gzip !== baseStats.gzip) {
// otherwise, we run a comparsion between the current page and base branch page
// we push these to their own category for rendering later
const rawDiff = currentStats.raw - baseStats.raw
const gzipDiff = currentStats.gzip - baseStats.gzip
const increase = !!Math.sign(gzipDiff)
// only report a page size change if we don't have a minimum change
// threshold configured, or if the change is greater than the threshold
if (
!('minimumChangeThreshold' in options) ||
Math.abs(gzipDiff) > options.minimumChangeThreshold
) {
changedPages.push({ page, ...currentStats, rawDiff, gzipDiff, increase })
}
}
}
// with our data in hand, we now get to a bunch of output formatting.
// we start with any changes to the global bundle.
if (globalBundleChanges) {
// start with the headline, which will render differently depending on whether
// there was an increase of decrease.
output += `### ${
globalBundleChanges.increase ? '⚠️' : '🎉'
} Global Bundle Size ${
globalBundleChanges.increase ? 'Increased' : 'Decreased'
}
`
// this is where we actually generate the table including the changes.
output += markdownTable(globalBundleChanges)
// and we end with some extra details further explaining the data above
if (SHOW_DETAILS) {
output += `\n<details>
<summary>Details</summary>
<p>The <strong>global bundle</strong> is the javascript bundle that loads alongside every page. It is in its own category because its impact is much higher - an increase to its size means that every page on your website loads slower, and a decrease means every page loads faster.</p>
<p>Any third party scripts you have added directly to your app using the <code><script></code> tag are not accounted for in this analysis</p>
<p>If you want further insight into what is behind the changes, give <a href='https://www.npmjs.com/package/@next/bundle-analyzer'>@next/bundle-analyzer</a> a try!</p>
</details>\n\n`
}
}
// next up is the newly added pages
if (newPages.length) {
// this might seem like too much, but I feel like this type of small detail really
// matters <3
const plural = newPages.length > 1 ? 's' : ''
output += `### New Page${plural} Added
The following page${plural} ${
plural === 's' ? 'were' : 'was'
} added to the bundle from the code in this PR:
`
// as before, run the data in as a table
output += markdownTable(newPages, globalBundleCurrent) + '\n'
// there is no "details" section here, didnt't seem necessary. i'm open to one being
// added though!
}
// finally, we run through the pages that existed in the base branch, still exist in the
// current branch, and have changed size.
if (changedPages.length) {
// same flow here as the others:
// - headline that adjusts wording based on number of changes
// - table containing all the resources and info
// - details section
const plural = changedPages.length > 1 ? 's' : ''
output += `### ${titleCase(
numberToWords.toWords(changedPages.length)
)} Page${plural} Changed Size
The following page${plural} changed size from the code in this PR compared to its base branch:
`
output += markdownTable(changedPages, globalBundleCurrent, globalBundleBase)
// this details section is a bit more responsive, it will render slightly different
// details depending on whether a budget is being used, since the information presented
// is quite different.
if (SHOW_DETAILS) {
output += `\n<details>
<summary>Details</summary>
<p>Only the gzipped size is provided here based on <a href='https://twitter.com/slightlylate/status/1412851269211811845'>an expert tip</a>.</p>
<p><strong>First Load</strong> is the size of the global bundle plus the bundle for the individual page. If a user were to show up to your website and land on a given page, the first load size represents the amount of javascript that user would need to download. If <code>next/link</code> is used, subsequent page loads would only need to download that page's bundle (the number in the "Size" column), since the global bundle has already been downloaded.</p>
<p>Any third party scripts you have added directly to your app using the <code><script></code> tag are not accounted for in this analysis</p>
${
BUDGET && globalBundleCurrent
? `<p>The "Budget %" column shows what percentage of your performance budget the <strong>First Load</strong> total takes up. For example, if your budget was 100kb, and a given page's first load size was 10kb, it would be 10% of your budget. You can also see how much this has increased or decreased compared to the base branch of your PR. If this percentage has increased by ${BUDGET_PERCENT_INCREASE_RED}% or more, there will be a red status indicator applied, indicating that special attention should be given to this. If you see "+/- <0.01%" it means that there was a change in bundle size, but it is a trivial enough amount that it can be ignored.</p>`
: `<p>Next to the size is how much the size has increased or decreased compared with the base branch of this PR. If this percentage has increased by ${BUDGET_PERCENT_INCREASE_RED}% or more, there will be a red status indicator applied, indicating that special attention should be given to this.`
}
</details>\n`
}
}
// and finally, if there are no changes at all, we try to be clear about that
const hasNoChanges =
!newPages.length && !changedPages.length && !globalBundleChanges
if (hasNoChanges) {
output += 'This PR introduced no changes to the JavaScript bundle! 🙌'
}
// we add this tag so that our action can be able to easily and consistently find the
// right comment to edit as more commits are pushed.
output += `<!-- __NEXTJS_BUNDLE_${PACKAGE_NAME} -->`
// however, if ignoreIfEmpty is true, set output to an empty string
if (hasNoChanges && SKIP_COMMENT_IF_EMPTY) {
output = ''
}
// log the output, mostly for testing and debugging. this will show up in the
// github actions console.
console.log(output)
// and to cap it off, we write the output to a file which is later read in as comment
// contents by the actions workflow.
fs.writeFileSync(
path.join(
process.cwd(),
BUILD_OUTPUT_DIRECTORY,
'analyze/__bundle_analysis_comment.txt'
),
output.trim()
)
// Util Functions
// this is where the vast majority of the complexity lives, its a single function
// that renders a markdown table displaying a wide range of bundle size data in a
// wide variety of different ways. this could potentially be improved by splitting it
// up into several different functions for rendering the different tables we produce
// (new pages, changed pages, global bundle)
function markdownTable(_data, globalBundleCurrent, globalBundleBase) {
const data = [].concat(_data)
// the table renders different depending on whether the budget option is enabled
// and also some tables do not run budget diffs (new, global)
const showBudget = globalBundleCurrent && BUDGET
const showBudgetDiff = BUDGET && !!globalBundleBase
// first we set up the table headers
return `Page | Size (compressed) | ${
globalBundleCurrent ? `First Load |` : ''
}${showBudget ? ` % of Budget (\`${filesize(BUDGET)}\`) |` : ''}
|---|---|${globalBundleCurrent ? '---|' : ''}${showBudget ? '---|' : ''}
${data
.map((d) => {
// next, we go through each item in the bundle data that was passed in and render
// a row for it. a couple calculations are run upfront to make rendering easier.
const firstLoadSize = globalBundleCurrent
? d.gzip + globalBundleCurrent.gzip
: 0
const budgetPercentage = showBudget
? ((firstLoadSize / BUDGET) * 100).toFixed(2)
: 0
const previousBudgetPercentage =
globalBundleBase && d.gzipDiff
? (
((globalBundleCurrent.gzip + d.gzip + d.gzipDiff) / BUDGET) *
100
).toFixed(2)
: 0
const budgetChange = previousBudgetPercentage
? (previousBudgetPercentage - budgetPercentage).toFixed(2)
: 0
return (
`| \`${d.page}\`` +
renderSize(d, showBudgetDiff) +
renderFirstLoad(globalBundleCurrent, firstLoadSize) +
renderBudgetPercentage(
showBudget,
budgetPercentage,
previousBudgetPercentage,
budgetChange
) +
' |\n'
)
})
.join('')}`
}
// as long as global bundle is passed, render the first load size, which is the global
// bundle plus the size of the current page, representing the total JS required
// in order to land on that page.
function renderFirstLoad(globalBundleCurrent, firstLoadSize) {
if (!globalBundleCurrent) return ''
return ` | ${filesize(firstLoadSize)}`
}
// renders the bundle size of the current page. if there is a diff from the base branch
// size of the page, also displays the size difference, unless there is a budget set and
// the budget has a diff from the base branch, in which case the diff is not rendered.
function renderSize(d, showBudgetDiff) {
const gzd = d.gzipDiff
const percentChange = (gzd / d.gzip) * 100
return ` | \`${filesize(d.gzip)}\`${
gzd && (options.alwaysShowGzipDiff || !showBudgetDiff)
? ` _(${renderStatusIndicator(percentChange)}${filesize(gzd)})_`
: ''
}`
}
// renders the percentage of the budget taken up by the current page's first load js
// for changed pages, also renders the percent change compared to the base branch size
function renderBudgetPercentage(
showBudget,
budgetPercentage,
previousBudgetPercentage,
budgetChange
) {
if (!showBudget) return ''
// we round to 2 decimal places for number values, if there was a change smaller than that
// its displayed as "+/- <0.01%", signaling that it's not a consequential change, but it
// still is a change technically, so we still show it.
const budgetChangeText = ` _(${renderStatusIndicator(budgetChange)}${
budgetChange < 0.01 && budgetChange > -0.01
? '+/- <0.01%'
: budgetChange + '%'
})_`
// only render the budget change for changed pages (indicated by previousBudgetPercentage
// being passed in)
return ` | ${budgetPercentage}%${
previousBudgetPercentage ? budgetChangeText : ''
}`
}
// given a percentage that a metric has changed, renders a colored status indicator
// this makes it easier to call attention to things that need attention
//
// in general:
// - yellow means "keep an eye on this"
// - red means "this is a problem"
// - green means "this is a win"
function renderStatusIndicator(percentageChange) {
let res = ''
if (percentageChange > 0 && percentageChange < BUDGET_PERCENT_INCREASE_RED) {
res += '🟡 +'
} else if (percentageChange >= BUDGET_PERCENT_INCREASE_RED) {
res += '🔴 +'
} else if (percentageChange < 0.01 && percentageChange > -0.01) {
res += ''
} else {
res += '🟢 '
}
return res
}
function titleCase(str) {
return str.replace(/\w\S*/g, (txt) => {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()
})
}