@bymaksym/loadline 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +182 -0
  3. package/bin/loadline.js +50 -0
  4. package/dist/cli/cli/args.js +324 -0
  5. package/dist/cli/cli/args.types.js +3 -0
  6. package/dist/cli/cli/gates.js +173 -0
  7. package/dist/cli/cli/gates.types.js +3 -0
  8. package/dist/cli/cli/main.js +156 -0
  9. package/dist/cli/cli/read-build.js +382 -0
  10. package/dist/cli/cli/read-build.types.js +3 -0
  11. package/dist/cli/cli/render-json.js +116 -0
  12. package/dist/cli/cli/render-json.types.js +10 -0
  13. package/dist/cli/cli/render-markdown.js +30 -0
  14. package/dist/cli/cli/render-pr.js +76 -0
  15. package/dist/cli/cli/render-sarif.js +83 -0
  16. package/dist/cli/cli/render-text.js +388 -0
  17. package/dist/cli/cli/report.js +196 -0
  18. package/dist/cli/cli/report.types.js +3 -0
  19. package/dist/cli/cli/self-check.js +85 -0
  20. package/dist/cli/cli/text.js +180 -0
  21. package/dist/cli/cli/text.types.js +10 -0
  22. package/dist/cli/src/app/core/analysis/analysis.js +661 -0
  23. package/dist/cli/src/app/core/analysis/analysis.types.js +6 -0
  24. package/dist/cli/src/app/core/analysis/barrels.js +128 -0
  25. package/dist/cli/src/app/core/analysis/blast.js +172 -0
  26. package/dist/cli/src/app/core/analysis/cycles.js +110 -0
  27. package/dist/cli/src/app/core/analysis/delivery.js +143 -0
  28. package/dist/cli/src/app/core/analysis/entries.js +217 -0
  29. package/dist/cli/src/app/core/analysis/exclusive.js +91 -0
  30. package/dist/cli/src/app/core/analysis/importers.js +38 -0
  31. package/dist/cli/src/app/core/analysis/insights.js +202 -0
  32. package/dist/cli/src/app/core/analysis/insights.types.js +10 -0
  33. package/dist/cli/src/app/core/analysis/invariant.js +69 -0
  34. package/dist/cli/src/app/core/analysis/metafile.types.js +44 -0
  35. package/dist/cli/src/app/core/analysis/module-graph.js +192 -0
  36. package/dist/cli/src/app/core/analysis/sourcemap.js +231 -0
  37. package/dist/cli/src/app/core/analysis/sourcemap.types.js +3 -0
  38. package/dist/cli/src/app/core/analysis/split-drift.js +47 -0
  39. package/dist/cli/src/app/core/assets/assets.js +296 -0
  40. package/dist/cli/src/app/core/assets/assets.types.js +11 -0
  41. package/dist/cli/src/app/core/baseline/baseline.js +0 -0
  42. package/dist/cli/src/app/core/baseline/baseline.types.js +3 -0
  43. package/dist/cli/src/app/core/caching/caching.js +241 -0
  44. package/dist/cli/src/app/core/caching/caching.types.js +10 -0
  45. package/dist/cli/src/app/core/caching/from-analysis.js +73 -0
  46. package/dist/cli/src/app/core/config/loadline-config.js +110 -0
  47. package/dist/cli/src/app/core/config/loadline-config.types.js +12 -0
  48. package/dist/cli/src/app/core/criteria/criteria.js +228 -0
  49. package/dist/cli/src/app/core/criteria/criteria.types.js +3 -0
  50. package/dist/cli/src/app/core/deps/deps.js +225 -0
  51. package/dist/cli/src/app/core/deps/deps.types.js +15 -0
  52. package/dist/cli/src/app/core/export/markdown-table.utils.js +40 -0
  53. package/dist/cli/src/app/core/export/summary.js +72 -0
  54. package/dist/cli/src/app/core/findings/actions.js +59 -0
  55. package/dist/cli/src/app/core/findings/assets.js +130 -0
  56. package/dist/cli/src/app/core/findings/caching.js +165 -0
  57. package/dist/cli/src/app/core/findings/compose.js +41 -0
  58. package/dist/cli/src/app/core/findings/deps.js +66 -0
  59. package/dist/cli/src/app/core/findings/effort.js +117 -0
  60. package/dist/cli/src/app/core/findings/finding-html.js +13 -0
  61. package/dist/cli/src/app/core/findings/finding-plain.js +26 -0
  62. package/dist/cli/src/app/core/findings/finding-text.js +1231 -0
  63. package/dist/cli/src/app/core/findings/finding.types.js +80 -0
  64. package/dist/cli/src/app/core/findings/findings.js +514 -0
  65. package/dist/cli/src/app/core/findings/graph.js +167 -0
  66. package/dist/cli/src/app/core/findings/own-in-boot.js +88 -0
  67. package/dist/cli/src/app/core/findings/page.js +49 -0
  68. package/dist/cli/src/app/core/findings/requests.js +185 -0
  69. package/dist/cli/src/app/core/findings/scan.js +126 -0
  70. package/dist/cli/src/app/core/findings/shipped.js +244 -0
  71. package/dist/cli/src/app/core/findings/situation.js +116 -0
  72. package/dist/cli/src/app/core/format/format.utils.js +204 -0
  73. package/dist/cli/src/app/core/i18n/en.js +819 -0
  74. package/dist/cli/src/app/core/i18n/es.js +822 -0
  75. package/dist/cli/src/app/core/i18n/ui-strings.js +11 -0
  76. package/dist/cli/src/app/core/i18n/ui.js +7 -0
  77. package/dist/cli/src/app/core/intake/bundle-graph.js +346 -0
  78. package/dist/cli/src/app/core/intake/bundle-graph.types.js +3 -0
  79. package/dist/cli/src/app/core/intake/dist-files.js +160 -0
  80. package/dist/cli/src/app/core/intake/index-html.js +292 -0
  81. package/dist/cli/src/app/core/json/json.utils.js +55 -0
  82. package/dist/cli/src/app/core/measurement/measurement.types.js +14 -0
  83. package/dist/cli/src/app/core/project/budget-advice.js +76 -0
  84. package/dist/cli/src/app/core/project/project-context.js +394 -0
  85. package/dist/cli/src/app/core/project/project-context.types.js +3 -0
  86. package/dist/cli/src/app/core/scan/catalog.js +67 -0
  87. package/dist/cli/src/app/core/scan/scan.js +280 -0
  88. package/dist/cli/src/app/core/scan/scan.types.js +10 -0
  89. package/dist/cli/src/app/core/scan/secrets.js +0 -0
  90. package/dist/cli/src/app/core/situation/situation.js +261 -0
  91. package/dist/cli/src/app/core/situation/situation.types.js +19 -0
  92. package/dist/cli/src/app/core/timing/timing.js +87 -0
  93. package/dist/cli/src/app/core/timing/timing.types.js +3 -0
  94. package/dist/cli/src/app/core/whatif/defer.js +68 -0
  95. package/dist/cli/src/app/state/report-messages.utils.js +73 -0
  96. package/docs/HOW-IT-WORKS.md +1087 -0
  97. package/loadline.html +78 -0
  98. package/package.json +154 -0
@@ -0,0 +1,217 @@
1
+ "use strict";
2
+ /**
3
+ * Which outputs the browser actually downloads, and which lazy entries are screens.
4
+ *
5
+ * Both questions used to have an obvious answer and no longer do: a build with server-side
6
+ * rendering writes both sides into one metafile, and a deferred block (`@defer`, a `lazy()` inside
7
+ * a component) produces a lazy entry that looks exactly like a route's. Getting either wrong moves
8
+ * every figure in the report, so they are kept here, apart and tested.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.labelledByWeight = exports.classifyLazyEntries = exports.isDeferredBlock = exports.isRouteGrouper = exports.lazyLoadersOf = exports.browserSide = exports.ROUTE_FILE = void 0;
12
+ const format_utils_1 = require("../format/format.utils");
13
+ /**
14
+ * Where a server build lands **when the path says so**. Angular used to write `server/` into the
15
+ * metafile and most SSR setups still do, but this is only half the answer now: Angular 22 writes
16
+ * `main.server.mjs`, `server.mjs` and a dozen shared chunks with no folder in front of them, and a
17
+ * name rule cannot see those without becoming a list of conventions. The other half is
18
+ * `holdsBrowserSide` below, which does not read names at all.
19
+ */
20
+ const SERVER_OUTPUT = /(^|\/)server\//;
21
+ /** A file that only groups routes: it owns no code of its own. `.jsx`/`.tsx` for the React case. */
22
+ exports.ROUTE_FILE = new RegExp(String.raw `\.(?:${format_utils_1.ROUTE_SUFFIXES.join('|')})\.${format_utils_1.SOURCE_EXTENSION}$`);
23
+ /**
24
+ * A lazy entry that is data rather than a screen: `import('./locales/es.json')`, a table of
25
+ * countries, a dictionary. Nobody navigates to one, and counting them as screens is not a rounding
26
+ * error — Excalidraw lazy-loads fifty languages, and its screens table came out with sixty-one rows
27
+ * for an application that has one screen.
28
+ *
29
+ * Two ways in, because a JSON chunk usually ships without a source map and then the only thing left
30
+ * is what the bundler called the file: the source itself ends in `.json`, or the chunk is named
31
+ * after the JSON it holds (`ru-RU.json-CCWdKmrX.js`, which is Vite's and Rollup's naming). The
32
+ * extension is the file's own, not a convention somebody here chose.
33
+ */
34
+ const DATA_ENTRY = /\.json$|\.json-[\w-]+\.m?js$/;
35
+ /**
36
+ * A view: what Angular calls a component or a page, and what any framework defers inside one.
37
+ *
38
+ * The list of suffixes is the same one that reads a screen's name off its file. They had drifted:
39
+ * `user.view.ts` counted as a view here while the label only knew how to strip `.page` and
40
+ * `.component`, so that screen was listed as `user.view`.
41
+ */
42
+ const VIEW_FILE = new RegExp(String.raw `\.(?:${format_utils_1.VIEW_SUFFIXES.join('|')})\.${format_utils_1.SOURCE_EXTENSION}$`);
43
+ /**
44
+ * The browser side of a build. Nobody downloads the server bundle, and it is usually the bigger of
45
+ * the two, so leaving it in would make the main entry — "the one that reaches the most" — be the
46
+ * server's, and the whole report would be about code no browser ever asks for.
47
+ *
48
+ * Two rules, and the second is the one that holds:
49
+ *
50
+ * 1. The path says `server/`. Cheap, and all there was for a long time.
51
+ * 2. **The browser folder does not hold the file.** When somebody points at the folder the browser
52
+ * is served — which is what `--dist` and the drop zone both take — that folder *is* the answer
53
+ * to "what does a browser download", measured rather than named. An output of the build that is
54
+ * not a file in it is not something anybody downloads, whatever it is called.
55
+ *
56
+ * The second rule is what an Angular 22 build with SSR needs: it writes `main.server.mjs`,
57
+ * `server.mjs`, `polyfills.server.mjs` and nine shared chunks into the same metafile as the browser
58
+ * ones, with no folder in front of any of them. Read with rule 1 alone, that build came out with
59
+ * six screens where it has three — every screen counted once per side — a bootstrap of 744 kB
60
+ * where it is 105, and `express`'s dependencies reported as duplicate packages the browser pays
61
+ * for twice.
62
+ *
63
+ * @param inFolder base names of the files the build folder holds, or `null` when no folder was
64
+ * given and only rule 1 can be applied.
65
+ *
66
+ * How many outputs were left out is returned, so the reader knows this happened instead of
67
+ * wondering why the figures do not match the folder.
68
+ */
69
+ const browserSide = (all, inFolder = null) => {
70
+ const files = Object.keys(all);
71
+ const elsewhere = (file) => SERVER_OUTPUT.test(file) || (inFolder !== null && !inFolder.has((0, format_utils_1.baseName)(file)));
72
+ const server = files.filter(file => elsewhere(file));
73
+ // Leaving everything out is never the answer. It means either a metafile of nothing but server
74
+ // outputs — somebody analysing their server bundle on purpose — or a folder from a different
75
+ // build than the stats file, where every name mismatches. Both are better read whole than
76
+ // reported as an empty application.
77
+ if (server.length === 0 || server.length === files.length) {
78
+ return { outputs: all, serverOutputs: 0 };
79
+ }
80
+ const outputs = Object.fromEntries(files.filter(file => !elsewhere(file)).map(file => [file, all[file]]));
81
+ return { outputs, serverOutputs: server.length };
82
+ };
83
+ exports.browserSide = browserSide;
84
+ /**
85
+ * Own source files that lazily import each file. Who pulls something in is what says whether it is
86
+ * a screen of its own or a piece of one, so it is worked out before the screens are decided — and
87
+ * it doubles as "who lazy-loads this screen", which is where a route's providers go.
88
+ */
89
+ const lazyLoadersOf = (inputs, isOwn) => {
90
+ const loaders = new Map();
91
+ for (const [input, data] of Object.entries(inputs)) {
92
+ if (!isOwn(input)) {
93
+ continue;
94
+ }
95
+ const imports = data.imports ?? [];
96
+ for (const imp of imports) {
97
+ if (imp.kind === 'dynamic-import') {
98
+ loaders.set(imp.path, [...(loaders.get(imp.path) ?? []), input]);
99
+ }
100
+ }
101
+ }
102
+ return loaders;
103
+ };
104
+ exports.lazyLoadersOf = lazyLoadersOf;
105
+ /**
106
+ * Whether a lazy entry only groups routes rather than being one of them. It is measured, not read
107
+ * off the file name: a file that adds practically no bytes of its own to its chunk, holds nothing
108
+ * but dynamic imports and produces a chunk no other file is grouped with has no screen inside it —
109
+ * what it loads is the screen.
110
+ *
111
+ * The three conditions are all needed, and being strict is the point: mistaking a screen for a
112
+ * grouper loses a row of the report, which is the expensive direction to be wrong in. A screen can
113
+ * be small, and a screen can defer a widget and nothing else; what it cannot do is be all three at
114
+ * once, because its own imports are what its chunk carries.
115
+ *
116
+ * `*.routes.ts` still passes by name. Not because the rule needs it — this is what stops the
117
+ * detection from depending on a naming convention that Angular's own style guide is dropping — but
118
+ * because a routes file with a guard or a provider in it has a static import and would otherwise
119
+ * turn into a screen row where there was none before.
120
+ */
121
+ const isRouteGrouper = (entry,
122
+ /**
123
+ * What a grouping file is allowed to weigh inside its own chunk. A table of routes compiles to
124
+ * paths and arrow functions and nothing else; a screen carries at least a template. The
125
+ * recommended kibibyte is well above the first and well below the second, and it is a criterion
126
+ * rather than a constant of this file so it can be moved for a project that sits between them.
127
+ */
128
+ grouperMaxBytes) => {
129
+ const lazyOnly = (imports) => imports.every(imp => imp.kind === 'dynamic-import');
130
+ return (exports.ROUTE_FILE.test(entry.source) ||
131
+ (entry.ownBytes !== null &&
132
+ entry.ownBytes <= grouperMaxBytes &&
133
+ // More than one, because a file that groups routes groups several of them. With a
134
+ // single dynamic import there is nothing left to tell a grouping file from a small
135
+ // screen that defers one widget — which is what a Nuxt page turned out to be, and it
136
+ // disappeared from the screens table while the widget took its row.
137
+ entry.imports.length > 1 &&
138
+ lazyOnly(entry.imports) &&
139
+ lazyOnly(entry.chunkImports)));
140
+ };
141
+ exports.isRouteGrouper = isRouteGrouper;
142
+ /**
143
+ * Whether a lazy entry is a piece of a screen rather than a screen. As deferred blocks become the
144
+ * normal way to split a page, counting them as screens would inflate the count and lower the median
145
+ * with things nobody ever enters.
146
+ *
147
+ * The evidence has to be positive: it is a block only when **every** file that lazily imports it is
148
+ * a view, or is itself one of these lazy entries. Anything else stays a screen, which is what it
149
+ * was before this rule existed.
150
+ *
151
+ * This half is still read off the file name, and the report says so: what a framework calls a view
152
+ * is not measurable from the graph the way a grouping file is. Rather than keep adding names to the
153
+ * expression, the screens table lets a row be reclassified by hand.
154
+ *
155
+ * @param loaders own files that lazily import this source
156
+ * @param lazySources sources of every own lazy entry, to catch a screen deferring another one
157
+ */
158
+ const isDeferredBlock = (loaders, lazySources) => loaders.length > 0 && loaders.every(file => VIEW_FILE.test(file) || lazySources.has(file));
159
+ exports.isDeferredBlock = isDeferredBlock;
160
+ /**
161
+ * What every lazy entry of the project code is: a screen, a piece of one, a file that only groups
162
+ * routes, or data. The answers are worked out together because they depend on each other — a
163
+ * grouping file has to leave before the rest are decided, or the screens under it would look like
164
+ * pieces of it.
165
+ *
166
+ * @param read the build and what has been said about it: the metafile's two halves, how many bytes
167
+ * an entry contributes to its chunk, who lazy-loads each source, and the marks.
168
+ */
169
+ const classifyLazyEntries = (entries, read) => {
170
+ const grouping = new Set(entries
171
+ .filter(entry => (0, exports.isRouteGrouper)({
172
+ source: entry.source,
173
+ ownBytes: read.ownBytesOf(entry.chunk, entry.source),
174
+ imports: read.inputs[entry.source]?.imports ?? [],
175
+ chunkImports: read.outputs[entry.chunk]?.imports ?? [],
176
+ }, read.grouperMaxBytes))
177
+ .map(entry => entry.source));
178
+ /**
179
+ * What counts as "a lazy entry deferring another one", which is half of what makes something a
180
+ * block. The grouping files are left out, marks aside: a screen reached through a lazy routes
181
+ * file is still a screen, and a grouping file somebody promoted to a screen by hand is still a
182
+ * list of somewhere-elses — counting it as a loader would turn every screen under it into a
183
+ * piece of it, which is twelve rows of a real report disappearing on one click.
184
+ */
185
+ const lazySources = new Set(entries.filter(entry => !grouping.has(entry.source)).map(entry => entry.source));
186
+ const kindOf = (entry) => {
187
+ const mark = read.marks?.get(entry.source);
188
+ if (mark) {
189
+ return mark === 'block' ? 'blocks' : 'screens';
190
+ }
191
+ // Data first: a language file is not a screen, not a piece of one and not a routes file,
192
+ // and it is the one of the four that can be told from the file itself.
193
+ if (DATA_ENTRY.test(entry.source)) {
194
+ return 'data';
195
+ }
196
+ if (grouping.has(entry.source)) {
197
+ return 'groupers';
198
+ }
199
+ return (0, exports.isDeferredBlock)(read.loaders.get(entry.source) ?? [], lazySources) ? 'blocks' : 'screens';
200
+ };
201
+ const kinds = {
202
+ screens: [],
203
+ blocks: [],
204
+ groupers: [],
205
+ data: [],
206
+ };
207
+ for (const entry of entries) {
208
+ kinds[kindOf(entry)].push(entry);
209
+ }
210
+ return kinds;
211
+ };
212
+ exports.classifyLazyEntries = classifyLazyEntries;
213
+ /** Lazy entries as the report lists them: name and weight, heaviest first. */
214
+ const labelledByWeight = (entries, label, sizeOf) => entries
215
+ .map(entry => ({ source: entry.source, label: label(entry.source), bytes: sizeOf(entry.chunk) }))
216
+ .toSorted((a, b) => b.bytes - a.bytes);
217
+ exports.labelledByWeight = labelledByWeight;
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ /**
3
+ * Exclusive weight: what the first load would lose if one thing were gone.
4
+ *
5
+ * It is the figure the rest of the report was missing, and without it half of any list of actions
6
+ * is in the wrong order. The bootstrap breakdown says `chart.js` weighs 310 kB. If 240 of those
7
+ * are `d3`, which three other things also pull in, then removing `chart.js` saves 70 kB and the
8
+ * afternoon spent on it buys a fifth of what the number promised.
9
+ *
10
+ * How it is worked out: walk the static import graph from where the application starts, once with
11
+ * everything and once with the candidate's files taken out. What stops arriving is what only came
12
+ * in through it. That is the definition of a dominator, computed the direct way — one walk per
13
+ * candidate — rather than by building a dominator tree, because a dominator tree answers the
14
+ * question for single **nodes** and every candidate here is a **set**: a package is all its files,
15
+ * a folder is all of them too, and the union of what several nodes dominate is not what the set
16
+ * dominates.
17
+ *
18
+ * The figure is raw minified bytes inside the chunk, like every other figure measured at file
19
+ * level: gzip compresses a chunk as a whole, so there is no compressed share of one module.
20
+ */
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ exports.exclusiveByBucket = exports.exclusiveWeigher = void 0;
23
+ const module_graph_1 = require("./module-graph");
24
+ /**
25
+ * @param graph the whole source graph.
26
+ * @param roots the source files the application starts at: the entry point of the main chunk
27
+ * plus any other entry the page starts as well.
28
+ * @param bootBytesOf what one source file weighs inside the bootstrap chunks. `0` for a file that
29
+ * ships somewhere else, which is what makes the answer about the first load and
30
+ * not about the bundle.
31
+ */
32
+ const exclusiveWeigher = (graph, roots, bootBytesOf) => {
33
+ const rootIds = roots.map(file => graph.index.get(file)).filter(id => id !== undefined);
34
+ const weights = new Float64Array(graph.nodes.length);
35
+ for (const [id, path] of graph.nodes.entries()) {
36
+ weights[id] = bootBytesOf(path);
37
+ }
38
+ const whole = (0, module_graph_1.reachIds)(graph, rootIds, graph.statics);
39
+ let total = 0;
40
+ for (let id = 0; id < graph.nodes.length; id++) {
41
+ if (whole[id] === 1) {
42
+ total += weights[id] ?? 0;
43
+ }
44
+ }
45
+ return {
46
+ total,
47
+ bytesOf: file => {
48
+ const id = graph.index.get(file);
49
+ return id === undefined ? 0 : (weights[id] ?? 0);
50
+ },
51
+ of: files => {
52
+ const skip = new Set();
53
+ for (const file of files) {
54
+ const id = graph.index.get(file);
55
+ if (id !== undefined) {
56
+ skip.add(id);
57
+ }
58
+ }
59
+ if (skip.size === 0) {
60
+ return 0;
61
+ }
62
+ const without = (0, module_graph_1.reachIds)(graph, rootIds, graph.statics, skip);
63
+ let saved = 0;
64
+ for (let id = 0; id < graph.nodes.length; id++) {
65
+ if (whole[id] === 1 && without[id] === 0) {
66
+ saved += weights[id] ?? 0;
67
+ }
68
+ }
69
+ return saved;
70
+ },
71
+ };
72
+ };
73
+ exports.exclusiveWeigher = exclusiveWeigher;
74
+ /**
75
+ * The exclusive weight of every bucket of the bootstrap breakdown.
76
+ *
77
+ * One walk per bucket, and a bucket is a package or a folder of the project. On the builds this
78
+ * has been run against — a hundred and sixty buckets over twenty thousand modules — that is a few
79
+ * hundred milliseconds, which is why it is computed once with the analysis and not per keystroke.
80
+ *
81
+ * A bucket whose exclusive weight equals its total weight is the ordinary case: nothing else
82
+ * shares it. The interesting ones are where the two figures disagree, and the report says both.
83
+ */
84
+ const exclusiveByBucket = (weigher, filesByBucket) => {
85
+ const exclusive = new Map();
86
+ for (const [bucket, files] of filesByBucket) {
87
+ exclusive.set(bucket, weigher.of(files));
88
+ }
89
+ return exclusive;
90
+ };
91
+ exports.exclusiveByBucket = exclusiveByBucket;
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ /**
3
+ * Who imports what, read from the source graph.
4
+ *
5
+ * Two maps come out of the same walk, and both answer the same kind of question — "who actually
6
+ * imports this?" — for the two things a report points at: an npm package and a project file.
7
+ * Without the second one, the signals could examine a library in the bootstrap and say nothing at
8
+ * all about a project folder right next to it.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.importGraphOf = void 0;
12
+ const format_utils_1 = require("../format/format.utils");
13
+ const importGraphOf = (inputs, isOwn) => {
14
+ const packages = new Map();
15
+ const ownFiles = new Map();
16
+ const add = (map, key, importer) => {
17
+ const importers = map.get(key) ?? new Set();
18
+ importers.add(importer);
19
+ map.set(key, importers);
20
+ };
21
+ for (const [input, data] of Object.entries(inputs)) {
22
+ if (!isOwn(input)) {
23
+ continue;
24
+ }
25
+ const imports = data.imports ?? [];
26
+ for (const imp of imports) {
27
+ const pkg = (0, format_utils_1.packageOf)(imp.path);
28
+ if (pkg) {
29
+ add(packages, pkg, input);
30
+ }
31
+ else if (isOwn(imp.path)) {
32
+ add(ownFiles, imp.path, input);
33
+ }
34
+ }
35
+ }
36
+ return { packages, ownFiles };
37
+ };
38
+ exports.importGraphOf = importGraphOf;
@@ -0,0 +1,202 @@
1
+ "use strict";
2
+ /**
3
+ * The eight figures that were inside the metafile and were not being read.
4
+ *
5
+ * They are computed in one place, after the analysis has decided what the bootstrap is and where
6
+ * every file lands, because each of them needs both halves: the graph says what imports what, and
7
+ * the split says who pays for it. Nothing here reads a new file.
8
+ *
9
+ * It is a separate module from `analysis.ts` for the reason that file gives about itself: that one
10
+ * computes what the report has always shown, and these are additions that should be readable —
11
+ * and removable — on their own.
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.graphInsightsOf = void 0;
15
+ const format_utils_1 = require("../format/format.utils");
16
+ const barrels_1 = require("./barrels");
17
+ const cycles_1 = require("./cycles");
18
+ const exclusive_1 = require("./exclusive");
19
+ const module_graph_1 = require("./module-graph");
20
+ /** From how many re-exports a file of the project is worth calling a barrel. */
21
+ const MIN_REEXPORTS = 5;
22
+ /** A package under this many files cannot be shipping "far more than anybody imports". */
23
+ const MIN_PACKAGE_FILES = 8;
24
+ /** Files per entry point from which the gap is the finding rather than the library being large. */
25
+ const MIN_BARREL_RATIO = 4;
26
+ /** How much two screens have to share before they are the same screen twice. */
27
+ const TWIN_OVERLAP = 0.9;
28
+ /**
29
+ * A file imported both ways at once.
30
+ *
31
+ * This is the classic silent failure of code splitting and no analyser shows it, because every one
32
+ * of them looks at chunks and this lives on the edges. Someone writes `const Chart = await
33
+ * import('./chart')` and a type import three files away already pulled the same module in
34
+ * statically: the `import()` defers nothing, the module travels on the first load, and the person
35
+ * who wrote it believes otherwise.
36
+ */
37
+ const mixedImports = (inputs, byPath, boot) => {
38
+ const statics = new Map();
39
+ const dynamics = new Map();
40
+ const record = (from, edge) => {
41
+ if (edge.external) {
42
+ return;
43
+ }
44
+ const into = edge.kind === 'dynamic-import' ? dynamics : statics;
45
+ into.set(edge.path, [...(into.get(edge.path) ?? []), from]);
46
+ };
47
+ for (const [from, data] of Object.entries(inputs)) {
48
+ const imports = data.imports ?? [];
49
+ for (const edge of imports) {
50
+ record(from, edge);
51
+ }
52
+ }
53
+ const found = [];
54
+ for (const [path, dynamicImporters] of dynamics) {
55
+ const staticImporters = statics.get(path);
56
+ const entry = byPath.get(path);
57
+ if (!staticImporters || !entry) {
58
+ continue;
59
+ }
60
+ found.push({
61
+ path,
62
+ label: (0, format_utils_1.shortName)(path),
63
+ bytes: entry.bytes,
64
+ staticImporters,
65
+ dynamicImporters,
66
+ inBoot: entry.places.some(place => boot.has(place.chunk)),
67
+ });
68
+ }
69
+ return found.toSorted((a, b) => Number(b.inBoot) - Number(a.inBoot) || b.bytes - a.bytes);
70
+ };
71
+ /**
72
+ * The same file copied into several chunks.
73
+ *
74
+ * Different from a package shipped in two versions, which the report already names: there the two
75
+ * copies are different code. Here they are byte for byte the same module, and the split put it in
76
+ * two places because two sets of screens reach it and neither is a subset of the other. It is
77
+ * money thrown away that appears in no list, and the fix is configuration rather than code.
78
+ */
79
+ const paidTwice = (modules) => modules
80
+ .filter(entry => entry.places.length > 1)
81
+ .map((entry) => ({
82
+ path: entry.path,
83
+ label: entry.label,
84
+ copies: entry.places.length,
85
+ // Everything but the largest copy: one of them was going to be downloaded anyway.
86
+ wasted: entry.bytes - (entry.places[0]?.bytes ?? 0),
87
+ chunks: entry.places.map(place => place.chunkName),
88
+ }))
89
+ .filter(entry => entry.wasted > 0)
90
+ .toSorted((a, b) => b.wasted - a.wasted);
91
+ /**
92
+ * Screens that load almost the same code.
93
+ *
94
+ * Either they are missing a shared chunk — the same modules copied into two of them — or they are
95
+ * one screen written twice. Both answers are something to do, and neither is visible in a table
96
+ * sorted by weight, where the two rows simply look alike.
97
+ */
98
+ const twinScreens = (screens, sizeOf) => {
99
+ const sets = screens.map(screen => ({
100
+ screen,
101
+ chunks: new Set([...screen.ownChunks, ...screen.sharedChunks]),
102
+ }));
103
+ /** The two of them compared. `null` when they are not alike enough to be worth a line. */
104
+ const pairOf = (left, right) => {
105
+ const union = new Set([...left.chunks, ...right.chunks]);
106
+ const common = [...left.chunks].filter(chunk => right.chunks.has(chunk));
107
+ const overlap = union.size === 0 ? 0 : common.length / union.size;
108
+ if (overlap < TWIN_OVERLAP) {
109
+ return null;
110
+ }
111
+ const apart = [...union].filter(chunk => !left.chunks.has(chunk) || !right.chunks.has(chunk));
112
+ return {
113
+ a: left.screen.source,
114
+ b: right.screen.source,
115
+ labelA: left.screen.label,
116
+ labelB: right.screen.label,
117
+ overlap,
118
+ sharedBytes: common.reduce((sum, chunk) => sum + sizeOf(chunk), 0),
119
+ apartBytes: apart.reduce((sum, chunk) => sum + sizeOf(chunk), 0),
120
+ };
121
+ };
122
+ return sets
123
+ .flatMap((left, index) => sets.slice(index + 1).map(right => pairOf(left, right)))
124
+ .filter(pair => pair !== null)
125
+ .toSorted((a, b) => b.overlap - a.overlap || b.sharedBytes - a.sharedBytes);
126
+ };
127
+ /**
128
+ * How much of the first load is code nobody here wrote.
129
+ *
130
+ * It changes the conversation. "Optimise my code" and "review my dependencies" are different
131
+ * weeks of work, and the second one is usually where the kilobytes are; a report that does not
132
+ * say which of the two it is leaves the reader to guess.
133
+ */
134
+ const ownershipOf = (filesByBucket, bootBytesOf) => {
135
+ let theirs = 0;
136
+ let yours = 0;
137
+ const packages = [];
138
+ for (const [bucket, files] of filesByBucket) {
139
+ const bytes = files.reduce((sum, file) => sum + bootBytesOf(file), 0);
140
+ if (bytes <= 0) {
141
+ continue;
142
+ }
143
+ // A bucket is a package when its files come from `node_modules`; the name alone cannot say,
144
+ // since a project folder may be called the same thing as a package.
145
+ if (files.some(file => (0, format_utils_1.packageOf)(file) !== null)) {
146
+ theirs += bytes;
147
+ packages.push({ name: bucket, bytes });
148
+ }
149
+ else {
150
+ yours += bytes;
151
+ }
152
+ }
153
+ const total = theirs + yours;
154
+ return {
155
+ theirs,
156
+ yours,
157
+ theirsRatio: total > 0 ? theirs / total : 0,
158
+ topPackages: packages.toSorted((a, b) => b.bytes - a.bytes),
159
+ };
160
+ };
161
+ const graphInsightsOf = (input) => {
162
+ const graph = (0, module_graph_1.buildModuleGraph)(input.inputs);
163
+ const byPath = new Map(input.modules.map(entry => [entry.path, entry]));
164
+ const shippedBytesOf = (path) => byPath.get(path)?.bytes ?? 0;
165
+ const inBoot = (path) => byPath.get(path)?.places.some(place => input.boot.has(place.chunk)) ?? false;
166
+ const weigher = (0, exclusive_1.exclusiveWeigher)(graph, input.roots, input.bootBytesOf);
167
+ const label = (path) => (0, format_utils_1.shortName)(path);
168
+ const cycleInput = { graph, isOwn: input.isOwn, shippedBytesOf, inBoot, label };
169
+ const twiceOver = paidTwice(input.modules);
170
+ return {
171
+ exclusive: (0, exclusive_1.exclusiveByBucket)(weigher, input.filesByBucket),
172
+ exclusiveOf: weigher.of,
173
+ bootTotal: weigher.total,
174
+ filesByBucket: input.filesByBucket,
175
+ mixedImports: mixedImports(input.inputs, byPath, input.boot),
176
+ ownBarrels: (0, barrels_1.ownBarrels)({
177
+ graph,
178
+ inputs: input.inputs,
179
+ isOwn: input.isOwn,
180
+ shippedBytesOf,
181
+ inBoot,
182
+ exclusiveOf: weigher.of,
183
+ minReexports: MIN_REEXPORTS,
184
+ label: path => path,
185
+ }),
186
+ packageBarrels: (0, barrels_1.packageBarrels)({
187
+ graph,
188
+ shippedBytesOf,
189
+ inBoot,
190
+ importersOf: pkg => [...(input.packageImporters.get(pkg) ?? [])],
191
+ minFiles: MIN_PACKAGE_FILES,
192
+ minRatio: MIN_BARREL_RATIO,
193
+ }),
194
+ cycles: (0, cycles_1.fileCycles)(cycleInput),
195
+ folderCycles: (0, cycles_1.folderCycles)(cycleInput),
196
+ paidTwice: twiceOver,
197
+ paidTwiceBytes: twiceOver.reduce((sum, entry) => sum + entry.wasted, 0),
198
+ twins: twinScreens(input.screens, input.sizeOf),
199
+ ownership: ownershipOf(input.filesByBucket, input.bootBytesOf),
200
+ };
201
+ };
202
+ exports.graphInsightsOf = graphInsightsOf;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ /**
3
+ * The figures that were already inside the metafile and were not being read.
4
+ *
5
+ * Every one of them comes out of the same import graph the rest of the report is built on: no new
6
+ * file is asked for, nothing goes out to the network. They live apart from `analysis.ts` because
7
+ * that file computes what the report has always shown, and because each of these answers a
8
+ * question that used to be answered by opening another tab.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ /**
3
+ * The one check that can catch the tool being wrong about a build it has never seen.
4
+ *
5
+ * Every other test compares Loadline against a fixture somebody wrote, so it only ever catches a
6
+ * change to Loadline. This compares Loadline against **the compiler**: the bootstrap is worked out
7
+ * twice, by two paths that share no code, and the two answers have to be the same set.
8
+ *
9
+ * - One path walks the import graph out from the entry chunk (`analyze`), following static edges.
10
+ * - The other reads what the build wrote into `index.html` — the entry script and the
11
+ * `modulepreload` links — and closes that set under static imports.
12
+ *
13
+ * Neither can be derived from the other: the first knows nothing about the page, and the page names
14
+ * only the chunks the browser is told to fetch early, not the ones it discovers by parsing. When
15
+ * they disagree, something about the shape of the output changed — which is exactly the failure
16
+ * that has happened before and that shows up as a report full of confident wrong numbers rather
17
+ * than as an error.
18
+ *
19
+ * It is a check, not a signal: the answer is about Loadline, not about the build, so it never
20
+ * reaches the report. The command runs it with `--self-check` and the pipeline fails on it.
21
+ */
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.checkBoot = exports.isSameBoot = void 0;
24
+ const format_utils_1 = require("../format/format.utils");
25
+ const delivery_1 = require("./delivery");
26
+ /** Chunk names, in a fixed order: what is being read is a diff, and a diff has to be stable. */
27
+ const byName = (a, b) => a.localeCompare(b);
28
+ /**
29
+ * How much of what the page announces may be unplaceable before the two readings are telling
30
+ * different stories: one chunk in five of what they agreed on.
31
+ *
32
+ * There is a case where the page names a chunk the graph cannot place and nothing is wrong: a
33
+ * dynamic import whose specifier is built at run time. VitePress writes one per page — the page's
34
+ * own data — and no reader of files can follow it, so a strict check was red on every VitePress
35
+ * site there is. A whole build changing shape does not look like that: it does not move one chunk
36
+ * out of ten, it moves most of them.
37
+ */
38
+ const UNPLACED_SHARE = 5;
39
+ const isSameBoot = (check) => check.onlyInGraph.length === 0 && check.agreed > 0 && check.onlyInPage.length * UNPLACED_SHARE <= check.agreed;
40
+ exports.isSameBoot = isSameBoot;
41
+ /**
42
+ * The two answers, compared.
43
+ *
44
+ * @param announced file names `index.html` tells the browser to fetch, as `announcedIn` gives them
45
+ * @param screenChunks lazy chunks the analysis attributes to screens, to tell a route chunk the
46
+ * page preloads from a bootstrap chunk one of the two readers got wrong
47
+ * @returns `null` when the page names no chunk of this build: there is no second path to compare
48
+ * against, and reporting agreement between one answer and nothing would be the worst
49
+ * possible outcome of a check.
50
+ */
51
+ const checkBoot = (outputs, bootChunks, announced, screenChunks = new Set()) => {
52
+ const seeds = Object.keys(outputs).filter(file => announced.has((0, format_utils_1.baseName)(file)));
53
+ if (seeds.length === 0) {
54
+ return null;
55
+ }
56
+ // Same walk the round trips use, run from the page instead of from the entry chunk. What comes
57
+ // back is every chunk the browser ends up holding before it navigates anywhere: the bootstrap.
58
+ const fromPage = new Set((0, delivery_1.wavesFrom)(outputs, seeds).keys());
59
+ const fromGraph = new Set(bootChunks);
60
+ return {
61
+ onlyInGraph: [...fromGraph].filter(chunk => !fromPage.has(chunk)).toSorted(byName),
62
+ onlyInPage: [...fromPage].filter(chunk => !fromGraph.has(chunk) && !screenChunks.has(chunk)).toSorted(byName),
63
+ preloadedRoutes: [...fromPage]
64
+ .filter(chunk => !fromGraph.has(chunk) && screenChunks.has(chunk))
65
+ .toSorted(byName),
66
+ agreed: [...fromGraph].filter(chunk => fromPage.has(chunk)).length,
67
+ };
68
+ };
69
+ exports.checkBoot = checkBoot;
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ /**
3
+ * Types of the esbuild metafile, the only thing Loadline reads.
4
+ * Reference: https://esbuild.github.io/api/#metafile
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.foreignFormat = exports.FOREIGN_FORMATS = exports.isMetafile = void 0;
8
+ const json_utils_1 = require("../json/json.utils");
9
+ /** Checks that what was dropped is a metafile before trying to analyse it. */
10
+ const isMetafile = (value) => !!value && typeof value === 'object' && 'outputs' in value && typeof value.outputs === 'object';
11
+ exports.isMetafile = isMetafile;
12
+ /** The formats by name, for reading one back out of an error code that carries it. */
13
+ exports.FOREIGN_FORMATS = new Set([
14
+ 'webpack',
15
+ 'viteManifest',
16
+ 'visualizer',
17
+ 'unknown',
18
+ ]);
19
+ const foreignFormat = (value) => {
20
+ // A list is rejected here too, which the hand-written check before it let through: every one
21
+ // of the three shapes below is an object keyed by name, and `Object.values` of an array would
22
+ // have read its elements as though they were those entries.
23
+ const data = (0, json_utils_1.asRecord)(value);
24
+ if (!data) {
25
+ return 'unknown';
26
+ }
27
+ // webpack, and everything that copies its stats: Angular's `browser` builder (up to v16), Next,
28
+ // Rspack. Arrays where the metafile has objects.
29
+ if (Array.isArray(data['chunks']) || (Array.isArray(data['modules']) && Array.isArray(data['assets']))) {
30
+ return 'webpack';
31
+ }
32
+ // rollup-plugin-visualizer: the tree it draws, with the bytes of each leaf apart.
33
+ if (data['tree'] && data['nodeParts']) {
34
+ return 'visualizer';
35
+ }
36
+ // Vite's manifest: every value is an entry with the file it produced.
37
+ const values = Object.values(data);
38
+ const looksLikeEntry = (entry) => typeof (0, json_utils_1.asRecord)(entry)?.['file'] === 'string';
39
+ if (values.length > 0 && values.every(entry => looksLikeEntry(entry))) {
40
+ return 'viteManifest';
41
+ }
42
+ return 'unknown';
43
+ };
44
+ exports.foreignFormat = foreignFormat;