@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,128 @@
1
+ "use strict";
2
+ /**
3
+ * Barrel files, the two kinds.
4
+ *
5
+ * **Yours.** An `index.ts` that re-exports a folder. Somebody writes `import { formatMoney } from
6
+ * '@app/shared'` for one function and forty files arrive, because the barrel names all forty and
7
+ * nothing downstream can tell which one was wanted. It is *the* problem of large Angular
8
+ * applications and no analyser names it, because every one of them stops at the package boundary
9
+ * and this lives inside the project.
10
+ *
11
+ * **Theirs.** The same shape one level up: `lodash` ships six hundred files when what was written
12
+ * was `import { debounce } from 'lodash'`. What identifies it is not the file count on its own —
13
+ * a big library is allowed to be big — but the gap between how many of its files ship and how many
14
+ * of them anything outside the package actually imports.
15
+ *
16
+ * Neither figure needs a file the tool does not already read: the metafile names every input, its
17
+ * imports and who imports it.
18
+ */
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.packageBarrels = exports.ownBarrels = void 0;
21
+ const format_utils_1 = require("../format/format.utils");
22
+ const module_graph_1 = require("./module-graph");
23
+ /**
24
+ * How many bytes of source one re-export line is worth.
25
+ *
26
+ * A barrel cannot be recognised from the metafile by what it says, only by its shape: many imports
27
+ * and hardly any source of its own. `export * from './button';` is about forty characters, and a
28
+ * file averaging under this much source per import is not doing anything else. The bound is
29
+ * deliberately loose — a barrel with a licence header at the top is still a barrel.
30
+ */
31
+ const BYTES_PER_REEXPORT = 160;
32
+ /** Own files whose shape is "a list of re-exports and nothing else". */
33
+ const ownBarrels = (input) => {
34
+ const { graph, inputs, isOwn, shippedBytesOf, minReexports } = input;
35
+ /** A file whose shape says "a list of re-exports": many imports, almost no source of its own. */
36
+ const isBarrel = (id, path) => {
37
+ const data = inputs[path];
38
+ if (!data || !isOwn(path)) {
39
+ return false;
40
+ }
41
+ const reexports = graph.statics[id]?.length ?? 0;
42
+ return reexports >= minReexports && data.bytes <= reexports * BYTES_PER_REEXPORT;
43
+ };
44
+ /**
45
+ * What arrives behind the barrel. Static edges only: what it costs is what comes down with
46
+ * whoever imports it, and a lazy boundary inside is exactly the part that does not.
47
+ */
48
+ const describe = (id, path) => {
49
+ const behind = (0, module_graph_1.reachIds)(graph, [id], graph.statics);
50
+ let pulls = 0;
51
+ let bytes = 0;
52
+ for (const [other, otherPath] of graph.nodes.entries()) {
53
+ pulls += behind[other] ?? 0;
54
+ bytes += (behind[other] ?? 0) * shippedBytesOf(otherPath);
55
+ }
56
+ return {
57
+ path,
58
+ label: input.label(path),
59
+ reexports: graph.statics[id]?.length ?? 0,
60
+ pulls,
61
+ bytes,
62
+ exclusive: input.exclusiveOf([path]),
63
+ importers: (graph.importedBy[id] ?? []).map(other => graph.nodes[other] ?? '').filter(Boolean),
64
+ inBoot: input.inBoot(path),
65
+ };
66
+ };
67
+ // The one that drags the most, first: that is the import worth rewriting.
68
+ return graph.nodes
69
+ .map((path, id) => (isBarrel(id, path) ? describe(id, path) : null))
70
+ .filter(barrel => barrel !== null)
71
+ .toSorted((a, b) => b.exclusive - a.exclusive || b.bytes - a.bytes || b.pulls - a.pulls);
72
+ };
73
+ exports.ownBarrels = ownBarrels;
74
+ /**
75
+ * Packages that ship many more files than anything outside them imports.
76
+ *
77
+ * `entryPoints` is the honest half of the measurement: the metafile records which file of the
78
+ * package something outside it imported, so `lodash/debounce` and `lodash` are told apart without
79
+ * guessing. What it cannot say is how much of what arrived is used — that would need the symbol
80
+ * table — so the report says what came in and what the entry points themselves weigh, and stops
81
+ * there rather than promising a saving it cannot measure.
82
+ */
83
+ const packageBarrels = (input) => {
84
+ const { graph, shippedBytesOf } = input;
85
+ const byPackage = new Map();
86
+ /** One file of one package, added to its package's tally. */
87
+ const count = (id, path) => {
88
+ const pkg = (0, format_utils_1.packageOf)(path);
89
+ const bytes = shippedBytesOf(path);
90
+ if (!pkg || bytes <= 0) {
91
+ return;
92
+ }
93
+ const tally = byPackage.get(pkg) ?? {
94
+ files: new Set(),
95
+ entries: new Set(),
96
+ bytes: 0,
97
+ entryBytes: 0,
98
+ inBoot: false,
99
+ };
100
+ tally.files.add(path);
101
+ tally.bytes += bytes;
102
+ tally.inBoot ||= input.inBoot(path);
103
+ // Imported from outside its own package: that is what "entry point" means here. A file
104
+ // another file of the same package imports is an internal detail, not a way in.
105
+ const fromOutside = (graph.importedBy[id] ?? []).some(other => (0, format_utils_1.packageOf)(graph.nodes[other] ?? '') !== pkg);
106
+ if (fromOutside) {
107
+ tally.entries.add(path);
108
+ tally.entryBytes += bytes;
109
+ }
110
+ byPackage.set(pkg, tally);
111
+ };
112
+ for (const [id, path] of graph.nodes.entries()) {
113
+ count(id, path);
114
+ }
115
+ return [...byPackage]
116
+ .map(([name, tally]) => ({
117
+ name,
118
+ files: tally.files.size,
119
+ entryPoints: tally.entries.size,
120
+ bytes: tally.bytes,
121
+ entryBytes: tally.entryBytes,
122
+ inBoot: tally.inBoot,
123
+ importers: input.importersOf(name),
124
+ }))
125
+ .filter(pkg => pkg.files >= input.minFiles && pkg.entryPoints > 0 && pkg.files >= pkg.entryPoints * input.minRatio)
126
+ .toSorted((a, b) => Number(b.inBoot) - Number(a.inBoot) || b.bytes - a.bytes);
127
+ };
128
+ exports.packageBarrels = packageBarrels;
@@ -0,0 +1,172 @@
1
+ "use strict";
2
+ /**
3
+ * What touching one file costs: which chunks it invalidates and which screens re-download.
4
+ *
5
+ * It answers the question that follows every finding — "is this change small?" — and the answer is
6
+ * not about the file. A one-line change in a file that sits in the bootstrap chunk invalidates that
7
+ * chunk for every visitor who had the previous build cached, and a one-line change in a file only
8
+ * one screen loads costs the people who open that screen. Same diff, two different bills.
9
+ *
10
+ * It is also half the answer about caching: what a deploy makes somebody download again starts
11
+ * here, one file at a time.
12
+ *
13
+ * **And the chunks holding the file are only the first half of the bill.** A bundler writes the
14
+ * hashed name of every chunk it imports into the importing chunk's own bytes, so a chunk whose
15
+ * hash moves drags along everything naming it, which drags along everything naming *that*. The
16
+ * usual shape is not a chain but a hub: one shared chunk — the framework runtime, the `index` —
17
+ * that every route imports and that reaches every route back, so a change to one leaf moves the
18
+ * hub and the hub moves the lot. Both figures are reported, never the second on its own: without
19
+ * "and without the cascade it would have been three chunks" the big number is alarm rather than
20
+ * diagnosis, and it is a property of how the bundler writes specifiers, not of anybody's code.
21
+ */
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.blastRadiusOf = exports.cascadeShapeOf = exports.chunkImportersOf = void 0;
24
+ /**
25
+ * The reverse edges the cascade travels along: for each chunk, the chunks that carry its file name
26
+ * inside them.
27
+ *
28
+ * Both kinds of import, on purpose. What invalidates a chunk is not what the browser fetches next
29
+ * but what is written in its bytes, and `import('./screen-A1B2.js')` puts the hashed name of a lazy
30
+ * chunk in its parent just as plainly as a static import does — which is the whole of what Vite's
31
+ * `__vite__mapDeps` array is.
32
+ */
33
+ const chunkImportersOf = (outputs) => {
34
+ const importers = new Map();
35
+ for (const [chunk, output] of Object.entries(outputs)) {
36
+ // Externals name nothing of this build, and an import of a file the build does not emit
37
+ // has no hash to move.
38
+ const targets = (output.imports ?? []).filter(imp => !imp.external && outputs[imp.path]);
39
+ for (const imp of targets) {
40
+ const known = importers.get(imp.path);
41
+ if (known) {
42
+ if (!known.includes(chunk)) {
43
+ known.push(chunk);
44
+ }
45
+ }
46
+ else {
47
+ importers.set(imp.path, [chunk]);
48
+ }
49
+ }
50
+ }
51
+ return importers;
52
+ };
53
+ exports.chunkImportersOf = chunkImportersOf;
54
+ /**
55
+ * Every chunk reachable backwards from `from` along those edges, excluding `from` itself.
56
+ *
57
+ * Breadth-first and marked on the way in, so the hub-and-spoke shape — where nearly everything
58
+ * reaches nearly everything — is walked once and not once per path.
59
+ */
60
+ const reachedBackwards = (analysis, from) => {
61
+ const seen = new Set(from);
62
+ const out = [];
63
+ const queue = [...from];
64
+ const reach = (chunk) => {
65
+ if (seen.has(chunk)) {
66
+ return;
67
+ }
68
+ seen.add(chunk);
69
+ out.push(chunk);
70
+ queue.push(chunk);
71
+ };
72
+ // The array iterator sees what `reach` pushes while iterating: this is the breadth-first queue.
73
+ for (const chunk of queue) {
74
+ const importers = analysis.chunkImporters.get(chunk) ?? [];
75
+ for (const importer of importers) {
76
+ reach(importer);
77
+ }
78
+ }
79
+ return out;
80
+ };
81
+ /**
82
+ * How many other chunks each chunk names inside itself: the out-degree of the same edges the
83
+ * cascade travels backwards along.
84
+ *
85
+ * `chunkImporters` is keyed the other way — target to the chunks naming it — because that is the
86
+ * direction a cascade spreads. This is the same map read forwards, and it is what says which file
87
+ * is the one carrying everybody's names.
88
+ */
89
+ const namesPerChunk = (analysis) => {
90
+ const counts = new Map();
91
+ for (const naming of analysis.chunkImporters.values()) {
92
+ for (const chunk of naming) {
93
+ counts.set(chunk, (counts.get(chunk) ?? 0) + 1);
94
+ }
95
+ }
96
+ return counts;
97
+ };
98
+ /** Bytes under which a chunk full of names is a runtime map rather than a bundle of code. */
99
+ const RUNTIME_CHUNK_BYTES = 4 * 1024;
100
+ /** From what share of the build a chunk counts as "nearly everything names it". */
101
+ const HUB_SHARE = 0.5;
102
+ /**
103
+ * What the build's own topology says about how far a change travels. See `CascadeShape`.
104
+ */
105
+ const cascadeShapeOf = (analysis) => {
106
+ const counts = namesPerChunk(analysis);
107
+ const total = analysis.allChunks.length;
108
+ const [hub, names] = [...counts].toSorted((a, b) => b[1] - a[1])[0] ?? [null, 0];
109
+ const named = hub ? (analysis.chunkImporters.get(hub)?.length ?? 0) : 0;
110
+ const bytes = hub ? (analysis.chunkOf(hub)?.bytes ?? 0) : 0;
111
+ // A small file that names most of the build and is imported by most of it is the runtime-chunk
112
+ // shape: the names live in one place, so nothing else carries anybody else's.
113
+ const concentrated = total > 0 && names >= total * HUB_SHARE;
114
+ const risk = !hub || !concentrated
115
+ ? 'mid'
116
+ : bytes <= RUNTIME_CHUNK_BYTES
117
+ ? 'low'
118
+ : named >= total * HUB_SHARE
119
+ ? 'high'
120
+ : 'mid';
121
+ return { risk, hub, names, named, bytes };
122
+ };
123
+ exports.cascadeShapeOf = cascadeShapeOf;
124
+ /**
125
+ * @returns `null` when the file ships no bytes: it was tree-shaken away, or it is a type-only
126
+ * module. Saying nothing is right there — a change to it invalidates nothing.
127
+ */
128
+ const blastRadiusOf = (analysis, path) => {
129
+ const entry = analysis.modules.find(module => module.path === path);
130
+ if (!entry || entry.places.length === 0) {
131
+ return null;
132
+ }
133
+ const boot = new Set(analysis.bootChunks);
134
+ const inBoot = entry.places.some(place => boot.has(place.chunk));
135
+ // Which screens load each chunk is already worked out for the shared-chunk figures; the
136
+ // bootstrap is not in that map because it belongs to everybody, which is what `inBoot` says.
137
+ const screens = new Set(entry.places.flatMap(place => analysis.chunkScreens.get(place.chunk) ?? []));
138
+ const held = new Set(entry.places.map(place => place.chunk));
139
+ const invalidatedBytes = [...held].reduce((sum, chunk) => sum + (analysis.chunkOf(chunk)?.bytes ?? 0), 0);
140
+ const cascadeChunks = reachedBackwards(analysis, held);
141
+ const cascadeBytes = cascadeChunks.reduce((sum, chunk) => sum + (analysis.chunkOf(chunk)?.bytes ?? 0), 0);
142
+ const cascadeInBoot = cascadeChunks.some(chunk => boot.has(chunk));
143
+ // Screens the cascade adds, and only those: a screen already re-downloading a chunk that holds
144
+ // the file is not made worse by also re-downloading one that names it.
145
+ const cascadeScreens = new Set(cascadeChunks.flatMap(chunk => analysis.chunkScreens.get(chunk) ?? []).filter(source => !screens.has(source)));
146
+ const buildBytes = analysis.allChunks.reduce((sum, chunk) => sum + (analysis.chunkOf(chunk)?.bytes ?? 0), 0);
147
+ // Which of the dragged-in chunks carries the most names: the amplifier, with its own name on
148
+ // it rather than described in the abstract.
149
+ const counts = namesPerChunk(analysis);
150
+ const [hubChunk, hubNames] = cascadeChunks
151
+ .map(chunk => [chunk, counts.get(chunk) ?? 0])
152
+ .toSorted((a, b) => b[1] - a[1])[0] ?? [null, 0];
153
+ return {
154
+ path,
155
+ places: entry.places,
156
+ invalidatedBytes,
157
+ inBoot,
158
+ screens: inBoot ? analysis.screens.map(screen => screen.source) : [...screens],
159
+ everyScreen: inBoot || (analysis.screens.length > 0 && screens.size === analysis.screens.length),
160
+ cascade: {
161
+ chunks: cascadeChunks,
162
+ bytes: cascadeBytes,
163
+ share: buildBytes > 0 ? (invalidatedBytes + cascadeBytes) / buildBytes : 0,
164
+ screens: cascadeInBoot && !inBoot
165
+ ? analysis.screens.map(screen => screen.source).filter(source => !screens.has(source))
166
+ : [...cascadeScreens],
167
+ // One name inside is an edge, not an amplifier: below two there is nothing to point at.
168
+ hub: hubChunk && hubNames > 1 ? { chunk: hubChunk, names: hubNames } : null,
169
+ },
170
+ };
171
+ };
172
+ exports.blastRadiusOf = blastRadiusOf;
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ /**
3
+ * Cycles in the import graph: `checkout → shared → analytics → checkout`.
4
+ *
5
+ * This is architecture, and architecture is normally somewhere you can only have an opinion. Here
6
+ * it comes out of the same graph as the bytes and ends in bytes: a cycle lengthens import chains —
7
+ * the round trips the report already counts — and it is what stops a bundler from tree-shaking a
8
+ * module, because it cannot prove which half of the loop is needed first.
9
+ *
10
+ * Two readings of the same fact. **By file** is what a person fixes: one import to move. **By
11
+ * folder** is what a person writes a rule about, and it is the one that survives a refactor, since
12
+ * `checkout` importing `shared` importing `checkout` stays true however the files are renamed.
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.folderCycles = exports.fileCycles = void 0;
16
+ const format_utils_1 = require("../format/format.utils");
17
+ const module_graph_1 = require("./module-graph");
18
+ /**
19
+ * Cycles between files.
20
+ *
21
+ * A strongly connected component of forty files is not something anybody can act on, so what is
22
+ * reported per component is the shortest loop through its heaviest member: the circle somebody
23
+ * would draw on a whiteboard, with the file that costs the most on it.
24
+ *
25
+ * Only the project's own files. A cycle inside `node_modules` is real and is not this project's to
26
+ * fix, and reporting it would bury the ones that are.
27
+ */
28
+ const fileCycles = (input) => {
29
+ const { graph } = input;
30
+ // The own-code subgraph, kept at full width so node ids still index the original arrays.
31
+ const own = graph.nodes.map((path, id) => input.isOwn(path) ? (graph.statics[id] ?? []).filter(next => input.isOwn(graph.nodes[next] ?? '')) : []);
32
+ return (0, module_graph_1.stronglyConnected)(own, graph.nodes.length)
33
+ .map((component) => {
34
+ const inside = new Set(component);
35
+ const bytes = component.reduce((sum, id) => sum + input.shippedBytesOf(graph.nodes[id] ?? ''), 0);
36
+ const heaviest = component.toSorted((a, b) => input.shippedBytesOf(graph.nodes[b] ?? '') - input.shippedBytesOf(graph.nodes[a] ?? ''))[0] ?? component[0];
37
+ return {
38
+ steps: (0, module_graph_1.shortestLoop)(own, heaviest ?? 0, inside).map(id => input.label(graph.nodes[id] ?? '')),
39
+ size: component.length,
40
+ bytes,
41
+ inBoot: component.some(id => input.inBoot(graph.nodes[id] ?? '')),
42
+ };
43
+ })
44
+ .toSorted((a, b) => Number(b.inBoot) - Number(a.inBoot) || b.bytes - a.bytes);
45
+ };
46
+ exports.fileCycles = fileCycles;
47
+ /**
48
+ * The same thing between folders of the project, which is the level a rule gets written at.
49
+ *
50
+ * A folder graph is tiny — tens of nodes — so every cycle in it is short enough to print whole.
51
+ */
52
+ const folderCycles = (input) => {
53
+ const { graph } = input;
54
+ const folders = [];
55
+ const index = new Map();
56
+ const idOf = (folder) => {
57
+ const existing = index.get(folder);
58
+ if (existing !== undefined) {
59
+ return existing;
60
+ }
61
+ const id = folders.length;
62
+ folders.push(folder);
63
+ index.set(folder, id);
64
+ return id;
65
+ };
66
+ const bytes = new Map();
67
+ const boot = new Set();
68
+ const edges = new Map();
69
+ /** One own file: its folder's weight, and an edge per folder it imports something from. */
70
+ const place = (id, path) => {
71
+ if (!input.isOwn(path)) {
72
+ return;
73
+ }
74
+ const from = (0, format_utils_1.projectFolderOf)(path);
75
+ const fromId = idOf(from);
76
+ bytes.set(from, (bytes.get(from) ?? 0) + input.shippedBytesOf(path));
77
+ if (input.inBoot(path)) {
78
+ boot.add(from);
79
+ }
80
+ const outgoing = graph.statics[id] ?? [];
81
+ const targets = outgoing
82
+ .map(next => graph.nodes[next] ?? '')
83
+ .filter(target => input.isOwn(target))
84
+ .map(target => (0, format_utils_1.projectFolderOf)(target))
85
+ // A folder importing itself is not a cycle between folders, it is a folder.
86
+ .filter(to => to !== from);
87
+ const set = edges.get(fromId) ?? new Set();
88
+ for (const to of targets) {
89
+ set.add(idOf(to));
90
+ }
91
+ edges.set(fromId, set);
92
+ };
93
+ for (const [id, path] of graph.nodes.entries()) {
94
+ place(id, path);
95
+ }
96
+ const adjacency = folders.map((_, id) => [...(edges.get(id) ?? [])]);
97
+ return (0, module_graph_1.stronglyConnected)(adjacency, folders.length)
98
+ .map((component) => {
99
+ const inside = new Set(component);
100
+ const heaviest = component.toSorted((a, b) => (bytes.get(folders[b] ?? '') ?? 0) - (bytes.get(folders[a] ?? '') ?? 0))[0] ?? component[0];
101
+ return {
102
+ steps: (0, module_graph_1.shortestLoop)(adjacency, heaviest ?? 0, inside).map(id => folders[id] ?? ''),
103
+ size: component.length,
104
+ bytes: component.reduce((sum, id) => sum + (bytes.get(folders[id] ?? '') ?? 0), 0),
105
+ inBoot: component.some(id => boot.has(folders[id] ?? '')),
106
+ };
107
+ })
108
+ .toSorted((a, b) => Number(b.inBoot) - Number(a.inBoot) || b.bytes - a.bytes);
109
+ };
110
+ exports.folderCycles = folderCycles;
@@ -0,0 +1,143 @@
1
+ "use strict";
2
+ /**
3
+ * How each chunk reaches the browser: with the first load or only when something asks for it, and
4
+ * in how many round trips.
5
+ *
6
+ * Eager and lazy come straight out of the import graph and every bundler reports them. The round
7
+ * trips do not, and they are the half that decides when a screen finishes loading: a browser does
8
+ * not know a chunk exists until it has downloaded and parsed the one importing it, so a screen
9
+ * split across
10
+ * three levels of static imports costs three sequential requests however little it weighs. On a
11
+ * connection with 200 ms of latency that is half a second the size figures cannot see.
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.startupOf = exports.criticalChainOf = exports.widthOf = exports.depthOf = exports.wavesFrom = exports.deliveryOf = void 0;
15
+ const format_utils_1 = require("../format/format.utils");
16
+ /** Everyone downloads the bootstrap; anything else waits for a dynamic import to ask for it. */
17
+ const deliveryOf = (zone) => (zone === 'boot' ? 'eager' : 'lazy');
18
+ exports.deliveryOf = deliveryOf;
19
+ /** Edges that make the browser fetch another file as soon as it has parsed this one. */
20
+ const staticImportsOf = (outputs, chunk) => (outputs[chunk]?.imports ?? []).filter(imp => imp.kind === 'import-statement').map(imp => imp.path);
21
+ /**
22
+ * Which round trip each chunk arrives in, walking out from the chunks the browser is already asking
23
+ * for. Breadth-first, because a chunk imported from two places is fetched at the first parent that
24
+ * reveals it, not at the deepest one.
25
+ *
26
+ * @param seeds chunks of the first round trip: a screen's entry, or what `index.html` names
27
+ * @param stop chunks that are already downloaded and end the walk — the bootstrap, seen from a screen
28
+ */
29
+ const wavesFrom = (outputs, seeds, stop = new Set()) => {
30
+ const wave = new Map();
31
+ const queue = [];
32
+ const reach = (chunk, trip) => {
33
+ if (wave.has(chunk) || stop.has(chunk) || !outputs[chunk]) {
34
+ return;
35
+ }
36
+ wave.set(chunk, trip);
37
+ queue.push(chunk);
38
+ };
39
+ for (const seed of seeds) {
40
+ reach(seed, 1);
41
+ }
42
+ // The array iterator sees what gets pushed while iterating: this is the breadth-first queue.
43
+ for (const chunk of queue) {
44
+ for (const target of staticImportsOf(outputs, chunk)) {
45
+ reach(target, (wave.get(chunk) ?? 1) + 1);
46
+ }
47
+ }
48
+ return wave;
49
+ };
50
+ exports.wavesFrom = wavesFrom;
51
+ /** The deepest round trip of a walk, which is what the load actually takes. `0` when there is none. */
52
+ const depthOf = (waves) => Math.max(0, ...waves.values());
53
+ exports.depthOf = depthOf;
54
+ /**
55
+ * How many chunks share the busiest round trip.
56
+ *
57
+ * Depth and width are opposite problems that the depth figure alone reports as the same one. Eight
58
+ * chunks all found on the second trip cost **one** extra trip between them, and naming seven of
59
+ * them in the page saves nothing; four chunks stacked one behind another cost three trips, and
60
+ * every one named removes one. A report that only says "three trips" cannot tell the two apart,
61
+ * and the advice that follows from each is different.
62
+ */
63
+ const widthOf = (waves) => {
64
+ const perWave = new Map();
65
+ for (const trip of waves.values()) {
66
+ perWave.set(trip, (perWave.get(trip) ?? 0) + 1);
67
+ }
68
+ return Math.max(0, ...perWave.values());
69
+ };
70
+ exports.widthOf = widthOf;
71
+ /**
72
+ * One deepest chain of static imports, from a chunk of the first trip down to a chunk of the last.
73
+ *
74
+ * This is the **critical preload set**: the chunks that are actually behind each other, and the
75
+ * only ones where naming a file in the page removes a round trip. Everything else at the same
76
+ * depth arrives on a trip that is being paid anyway.
77
+ *
78
+ * It matters because the honest version of preload advice is a short list and an explicit "not
79
+ * these". A page carrying a tag per late chunk competes with the stylesheet that blocks rendering,
80
+ * and has made first paint measurably worse in real projects; a page carrying two or three tags
81
+ * that shorten the chain has not.
82
+ *
83
+ * @returns the chain in the order the browser discovers it. Empty when the walk has one level.
84
+ */
85
+ const criticalChainOf = (outputs, waves) => {
86
+ const depth = (0, exports.depthOf)(waves);
87
+ if (depth < 2) {
88
+ return [];
89
+ }
90
+ // The deepest chunk, and among equals the heaviest: a chain is only worth naming if what sits
91
+ // at the end of it is worth waiting for.
92
+ const deepest = [...waves]
93
+ .filter(([, trip]) => trip === depth)
94
+ .toSorted((a, b) => (outputs[b[0]]?.bytes ?? 0) - (outputs[a[0]]?.bytes ?? 0))[0]?.[0];
95
+ if (!deepest) {
96
+ return [];
97
+ }
98
+ const chain = [deepest];
99
+ let current = deepest;
100
+ for (let trip = depth - 1; trip >= 1; trip -= 1) {
101
+ // A parent one trip up that statically imports it: that import is the reason the browser
102
+ // could not know about `current` any sooner.
103
+ const parent = [...waves].find(([chunk, at]) => at === trip && staticImportsOf(outputs, chunk).includes(current))?.[0];
104
+ if (!parent) {
105
+ break;
106
+ }
107
+ chain.unshift(parent);
108
+ current = parent;
109
+ }
110
+ return chain;
111
+ };
112
+ exports.criticalChainOf = criticalChainOf;
113
+ /**
114
+ * The first load, measured against what `index.html` announces. Without that file the figure
115
+ * cannot be derived — the graph alone cannot tell a preloaded chunk from one discovered by
116
+ * parsing — so this returns `null` instead of a number.
117
+ *
118
+ * @param announced file names the page tells the browser to fetch, as they appear in its markup
119
+ */
120
+ const startupOf = (outputs, boot, announced) => {
121
+ const seeds = [...boot].filter(chunk => announced.has((0, format_utils_1.baseName)(chunk)));
122
+ if (seeds.length === 0) {
123
+ return null;
124
+ }
125
+ const waves = (0, exports.wavesFrom)(outputs, seeds);
126
+ const depth = Math.max(1, ...[...boot].map(chunk => waves.get(chunk) ?? 1));
127
+ const discovered = [...boot].filter(chunk => (waves.get(chunk) ?? 1) > 1);
128
+ // Grouped as well as listed, because "how many arrive late" is the wrong question on its own:
129
+ // the ones sharing a trip cost that trip once between them, and the ones behind each other
130
+ // cost one apiece. Index 0 is the second trip; nothing in the first is late.
131
+ const byWave = Array.from({ length: Math.max(0, depth - 1) }, () => []);
132
+ for (const chunk of discovered) {
133
+ byWave[(waves.get(chunk) ?? 2) - 2]?.push(chunk);
134
+ }
135
+ return {
136
+ waves: depth,
137
+ discovered,
138
+ byWave,
139
+ width: (0, exports.widthOf)(waves),
140
+ critical: (0, exports.criticalChainOf)(outputs, waves),
141
+ };
142
+ };
143
+ exports.startupOf = startupOf;