@bymaksym/loadline 0.1.0 → 1.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 (115) hide show
  1. package/README.md +272 -45
  2. package/dist/cli/cli/args.js +97 -116
  3. package/dist/cli/cli/gates.js +80 -14
  4. package/dist/cli/cli/main.js +275 -31
  5. package/dist/cli/cli/memory.js +114 -0
  6. package/dist/cli/cli/read/declared.js +52 -0
  7. package/dist/cli/cli/read/locate.js +214 -0
  8. package/dist/cli/cli/{read-build.js → read/read-build.js} +156 -87
  9. package/dist/cli/cli/read/read-config.js +120 -0
  10. package/dist/cli/cli/render/html-report.js +111 -0
  11. package/dist/cli/cli/render/render-agent.js +114 -0
  12. package/dist/cli/cli/render/render-asked.js +104 -0
  13. package/dist/cli/cli/render/render-badge.js +140 -0
  14. package/dist/cli/cli/{render-json.js → render/render-json.js} +26 -10
  15. package/dist/cli/cli/{render-markdown.js → render/render-markdown.js} +6 -6
  16. package/dist/cli/cli/{render-pr.js → render/render-pr.js} +37 -15
  17. package/dist/cli/cli/{render-sarif.js → render/render-sarif.js} +11 -6
  18. package/dist/cli/cli/{render-text.js → render/render-text.js} +169 -127
  19. package/dist/cli/cli/render/terminal.js +55 -0
  20. package/dist/cli/cli/report.js +76 -29
  21. package/dist/cli/cli/self-check.js +19 -23
  22. package/dist/cli/cli/since-last.js +45 -0
  23. package/dist/cli/cli/text/text-errors.js +124 -0
  24. package/dist/cli/cli/text/text.js +343 -0
  25. package/dist/cli/cli/text/usage.js +240 -0
  26. package/dist/cli/src/app/core/analysis/analysis.js +68 -24
  27. package/dist/cli/src/app/core/analysis/{barrels.js → graph/barrels.js} +10 -3
  28. package/dist/cli/src/app/core/analysis/{blast.js → graph/blast.js} +56 -17
  29. package/dist/cli/src/app/core/analysis/{cycles.js → graph/cycles.js} +1 -1
  30. package/dist/cli/src/app/core/analysis/{importers.js → graph/importers.js} +1 -1
  31. package/dist/cli/src/app/core/analysis/{insights.js → graph/insights.js} +10 -4
  32. package/dist/cli/src/app/core/analysis/invariant.js +1 -1
  33. package/dist/cli/src/app/core/analysis/metafile.types.js +21 -7
  34. package/dist/cli/src/app/core/analysis/{delivery.js → screens/delivery.js} +1 -1
  35. package/dist/cli/src/app/core/analysis/{entries.js → screens/entries.js} +87 -11
  36. package/dist/cli/src/app/core/analysis/screens/marks.js +32 -0
  37. package/dist/cli/src/app/core/analysis/screens/route-files.js +116 -0
  38. package/dist/cli/src/app/core/analysis/{sourcemap.js → sourcemap/sourcemap.js} +106 -7
  39. package/dist/cli/src/app/core/analysis/{split-drift.js → sourcemap/split-drift.js} +13 -7
  40. package/dist/cli/src/app/core/analysis/tool.js +83 -0
  41. package/dist/cli/src/app/core/assets/assets.js +137 -16
  42. package/dist/cli/src/app/core/baseline/baseline.js +0 -0
  43. package/dist/cli/src/app/core/{intake → build-text}/index-html.js +234 -29
  44. package/dist/cli/src/app/core/build-text/route-table.js +178 -0
  45. package/dist/cli/src/app/core/build-text/tool-marks.js +54 -0
  46. package/dist/cli/src/app/core/caching/caching.js +123 -45
  47. package/dist/cli/src/app/core/caching/from-analysis.js +20 -4
  48. package/dist/cli/src/app/core/config/config-text.js +90 -0
  49. package/dist/cli/src/app/core/config/config-values.js +358 -0
  50. package/dist/cli/src/app/core/config/loadline-config.js +81 -16
  51. package/dist/cli/src/app/core/config/merge-config.js +98 -0
  52. package/dist/cli/src/app/core/deps/deps.js +141 -23
  53. package/dist/cli/src/app/core/deps/pins.js +63 -0
  54. package/dist/cli/src/app/core/export/summary.js +54 -12
  55. package/dist/cli/src/app/core/findings/actions.js +65 -6
  56. package/dist/cli/src/app/core/findings/bundle/boot-single.js +76 -0
  57. package/dist/cli/src/app/core/findings/bundle/dupes.js +68 -0
  58. package/dist/cli/src/app/core/findings/{graph.js → bundle/graph.js} +32 -20
  59. package/dist/cli/src/app/core/findings/{own-in-boot.js → bundle/own-in-boot.js} +9 -5
  60. package/dist/cli/src/app/core/findings/{requests.js → bundle/requests.js} +3 -3
  61. package/dist/cli/src/app/core/findings/{shipped.js → bundle/shipped.js} +30 -18
  62. package/dist/cli/src/app/core/findings/compose.js +6 -1
  63. package/dist/cli/src/app/core/findings/effort.js +4 -0
  64. package/dist/cli/src/app/core/findings/finding.types.js +2 -0
  65. package/dist/cli/src/app/core/findings/findings.js +68 -55
  66. package/dist/cli/src/app/core/findings/{assets.js → folder/assets.js} +65 -16
  67. package/dist/cli/src/app/core/findings/{caching.js → folder/caching.js} +17 -10
  68. package/dist/cli/src/app/core/findings/{page.js → folder/page.js} +6 -2
  69. package/dist/cli/src/app/core/findings/{scan.js → folder/scan.js} +37 -13
  70. package/dist/cli/src/app/core/findings/kind-names.js +163 -0
  71. package/dist/cli/src/app/core/findings/{deps.js → supplied/deps.js} +13 -8
  72. package/dist/cli/src/app/core/findings/supplied/forbidden.js +71 -0
  73. package/dist/cli/src/app/core/findings/{situation.js → supplied/situation.js} +2 -2
  74. package/dist/cli/src/app/core/findings/text/causes.js +39 -0
  75. package/dist/cli/src/app/core/findings/text/finding-html.js +33 -0
  76. package/dist/cli/src/app/core/findings/{finding-text.js → text/finding-text.js} +307 -103
  77. package/dist/cli/src/app/core/findings/text/tool-advice.js +97 -0
  78. package/dist/cli/src/app/core/format/format.utils.js +172 -18
  79. package/dist/cli/src/app/core/format/ownership.js +93 -0
  80. package/dist/cli/src/app/core/i18n/en.js +180 -61
  81. package/dist/cli/src/app/core/i18n/es.js +192 -68
  82. package/dist/cli/src/app/core/intake/bundle-graph.js +285 -46
  83. package/dist/cli/src/app/core/intake/dist-files.js +87 -16
  84. package/dist/cli/src/app/core/intake/embedded.js +56 -0
  85. package/dist/cli/src/app/core/intake/unreached.js +139 -0
  86. package/dist/cli/src/app/core/intake/webpack-modules.js +185 -0
  87. package/dist/cli/src/app/core/intake/webpack-stats.js +298 -0
  88. package/dist/cli/src/app/core/project/budget-advice.js +14 -10
  89. package/dist/cli/src/app/core/project/project-context.js +89 -19
  90. package/dist/cli/src/app/core/project/project-name.js +36 -0
  91. package/dist/cli/src/app/core/scan/scan.js +116 -39
  92. package/dist/cli/src/app/core/scan/secrets.js +0 -0
  93. package/dist/cli/src/app/core/situation/situation-text.js +23 -0
  94. package/dist/cli/src/app/core/situation/situation.js +9 -8
  95. package/dist/cli/src/app/core/timing/timing.js +5 -2
  96. package/dist/cli/src/app/core/whatif/defer.js +29 -4
  97. package/dist/cli/src/app/core/whatif/source-importers.js +58 -0
  98. package/dist/cli/src/app/core/whatif/why.js +102 -0
  99. package/dist/cli/src/app/state/report-messages.utils.js +1 -4
  100. package/docs/CONFIG-REFERENCE.md +230 -0
  101. package/docs/CONFIG.md +511 -0
  102. package/docs/HOW-IT-WORKS.md +286 -25
  103. package/loadline.html +26 -24
  104. package/loadline.schema.json +1209 -0
  105. package/package.json +71 -35
  106. package/dist/cli/cli/text.js +0 -180
  107. package/dist/cli/src/app/core/findings/finding-html.js +0 -13
  108. /package/dist/cli/cli/{read-build.types.js → read/read-build.types.js} +0 -0
  109. /package/dist/cli/cli/{render-json.types.js → render/render-json.types.js} +0 -0
  110. /package/dist/cli/cli/{text.types.js → text/text.types.js} +0 -0
  111. /package/dist/cli/src/app/core/analysis/{exclusive.js → graph/exclusive.js} +0 -0
  112. /package/dist/cli/src/app/core/analysis/{insights.types.js → graph/insights.types.js} +0 -0
  113. /package/dist/cli/src/app/core/analysis/{module-graph.js → graph/module-graph.js} +0 -0
  114. /package/dist/cli/src/app/core/analysis/{sourcemap.types.js → sourcemap/sourcemap.types.js} +0 -0
  115. /package/dist/cli/src/app/core/findings/{finding-plain.js → text/finding-plain.js} +0 -0
@@ -19,6 +19,7 @@
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
20
  exports.readDeps = exports.readAudit = exports.readLock = void 0;
21
21
  const json_utils_1 = require("../json/json.utils");
22
+ const pins_1 = require("./pins");
22
23
  /** ` /lodash@4.17.21:` in pnpm, `"node_modules/lodash": {` in npm, `lodash@^4.0.0:` in yarn. */
23
24
  const PNPM_ENTRY = /^ {2}\/?((?:@[^/@]+\/)?[^@/\s]+)@([^(:\s]+)/;
24
25
  const YARN_ENTRY = /^"?((?:@[^/@]+\/)?[^@/\s]+)@[^:]*:?$/;
@@ -34,6 +35,15 @@ const nameFromPath = (path) => {
34
35
  const parts = rest.split('/');
35
36
  return (parts[0]?.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0]) ?? null;
36
37
  };
38
+ /** One line of a JSON-lines file, or `null` for one that is not JSON. */
39
+ const safeJson = (line) => {
40
+ try {
41
+ return JSON.parse(line);
42
+ }
43
+ catch {
44
+ return null;
45
+ }
46
+ };
37
47
  /** The `version` of one lock entry, when the entry is an object carrying one. */
38
48
  const versionOf = (entry) => (0, json_utils_1.asText)((0, json_utils_1.asRecord)(entry)?.['version']);
39
49
  const readNpmLock = (lock) => {
@@ -42,9 +52,11 @@ const readNpmLock = (lock) => {
42
52
  for (const [path, entry] of installed) {
43
53
  const name = nameFromPath(path);
44
54
  const version = versionOf(entry);
45
- if (name && version) {
46
- found.set(`${name}@${version}`, { name, version, requiredBy: [] });
55
+ if (!name || !version) {
56
+ continue;
47
57
  }
58
+ const declares = Object.fromEntries(Object.entries((0, json_utils_1.asRecord)((0, json_utils_1.asRecord)(entry)?.['dependencies']) ?? {}).filter((pair) => typeof pair[1] === 'string'));
59
+ found.set(`${name}@${version}`, { name, version, requiredBy: [], declares });
48
60
  }
49
61
  // The older format, for a lock file written before npm 7. Same two fields, one level in.
50
62
  const older = Object.entries((0, json_utils_1.asRecord)(lock['dependencies']) ?? {});
@@ -63,12 +75,32 @@ const readNpmLock = (lock) => {
63
75
  * does not use `DOMParser`: what is wanted is two fields per entry, and a parser would be the only
64
76
  * runtime dependency of a tool whose whole point is having none.
65
77
  */
66
- const readYamlLock = (text) => {
78
+ const readYamlLock = (text, yarn) => {
67
79
  const found = new Map();
68
80
  const lines = text.split('\n');
69
81
  let pending = null;
82
+ /** The yarn entry whose `dependencies:` block is being read, if one is. */
83
+ let current = null;
84
+ let inDependencies = false;
70
85
  for (const line of lines) {
71
- const pnpm = PNPM_ENTRY.exec(line);
86
+ // A yarn entry's own dependencies, with the range each one is declared at. pnpm writes a
87
+ // block of the same shape under `snapshots:` with **resolved** versions, which would read
88
+ // as every dependency pinned exactly — so this is only done for yarn.
89
+ if (yarn && current) {
90
+ if (/^ {2}dependencies:\s*$/.test(line)) {
91
+ inDependencies = true;
92
+ continue;
93
+ }
94
+ const dependency = /^ {4}"?((?:@[^\s"/]+\/)?[^\s":]+)"?:?\s+"?([^"\s]+)"?\s*$/.exec(line);
95
+ if (inDependencies && dependency?.[1] && dependency[2]) {
96
+ current.declares = { ...current.declares, [dependency[1]]: dependency[2] };
97
+ continue;
98
+ }
99
+ if (!/^ {4}/.test(line)) {
100
+ inDependencies = false;
101
+ }
102
+ }
103
+ const pnpm = yarn ? null : PNPM_ENTRY.exec(line);
72
104
  if (pnpm?.[1] && pnpm[2]) {
73
105
  found.set(`${pnpm[1]}@${pnpm[2]}`, { name: pnpm[1], version: pnpm[2], requiredBy: [] });
74
106
  pending = null;
@@ -77,11 +109,17 @@ const readYamlLock = (text) => {
77
109
  // yarn writes the name on one line and the version on the next.
78
110
  const version = YARN_VERSION.exec(line);
79
111
  if (pending && version?.[1]) {
80
- found.set(`${pending}@${version[1]}`, { name: pending, version: version[1], requiredBy: [] });
112
+ current = { name: pending, version: version[1], requiredBy: [] };
113
+ found.set(`${pending}@${version[1]}`, current);
81
114
  pending = null;
82
115
  continue;
83
116
  }
84
- pending = YARN_ENTRY.exec(line)?.[1] ?? null;
117
+ const entry = YARN_ENTRY.exec(line)?.[1] ?? null;
118
+ if (entry) {
119
+ current = null;
120
+ inDependencies = false;
121
+ }
122
+ pending = entry;
85
123
  }
86
124
  return [...found.values()];
87
125
  };
@@ -98,7 +136,7 @@ const readLock = (name, text) => {
98
136
  const lock = (0, json_utils_1.asRecord)(parsed);
99
137
  return lock ? readNpmLock(lock) : null;
100
138
  }
101
- return /lock\.ya?ml$|yarn\.lock$/i.test(name) ? readYamlLock(text) : null;
139
+ return /lock\.ya?ml$|yarn\.lock$/i.test(name) ? readYamlLock(text, /yarn\.lock$/i.test(name)) : null;
102
140
  };
103
141
  exports.readLock = readLock;
104
142
  /**
@@ -107,7 +145,8 @@ exports.readLock = readLock;
107
145
  * Nothing here checks a version range against a version: an advisory is attributed to a package by
108
146
  * name, and the range is printed so whoever reads it can judge. Matching ranges properly needs a
109
147
  * semver implementation, and being approximately right about whether somebody is vulnerable is
110
- * worse than being explicit about what is and is not known.
148
+ * worse than being explicit about what is and is not known. The one exact comparison made is
149
+ * between installed versions, when the report names them: see `affectsShipped`.
111
150
  */
112
151
  const readAudit = (text) => {
113
152
  let parsed;
@@ -115,7 +154,24 @@ const readAudit = (text) => {
115
154
  parsed = JSON.parse(text);
116
155
  }
117
156
  catch {
118
- return null;
157
+ // `yarn audit --json` writes one object per line. The advisories in it are npm 6's, so they
158
+ // are gathered into npm 6's shape and read like one; yarn repeats an advisory once per path
159
+ // it is reached by, and the id keeps one of each.
160
+ const advisories = {};
161
+ for (const line of text.split('\n')) {
162
+ const entry = (0, json_utils_1.asRecord)(safeJson(line));
163
+ const advisory = entry?.['type'] === 'auditAdvisory' ? (0, json_utils_1.asRecord)((0, json_utils_1.asRecord)(entry['data'])?.['advisory']) : null;
164
+ if (!advisory) {
165
+ continue;
166
+ }
167
+ const id = advisory['id'];
168
+ const key = typeof id === 'number' || typeof id === 'string' ? String(id) : `#${Object.keys(advisories).length}`;
169
+ advisories[key] = advisory;
170
+ }
171
+ if (Object.keys(advisories).length === 0 && !text.includes('"auditSummary"')) {
172
+ return null;
173
+ }
174
+ parsed = { advisories };
119
175
  }
120
176
  // An audit report is an object. `null`, a list and a bare number are all valid JSON, and the
121
177
  // shape this used to assert made reading a property off any of them a crash rather than a
@@ -140,7 +196,7 @@ const readAudit = (text) => {
140
196
  severity: severityOf(entry['severity']),
141
197
  title: (0, json_utils_1.asText)(detail?.['title']) ?? name,
142
198
  url: (0, json_utils_1.asText)(detail?.['url']),
143
- range: (0, json_utils_1.asText)(detail?.['range']),
199
+ range: (0, json_utils_1.asText)(detail?.['range']) ?? (0, json_utils_1.asText)(entry['range']),
144
200
  // npm's `fixAvailable` is either `false` or an object naming a package and a version
145
201
  // to move to — which is not the same as "this advisory is fixed in X". Rather than
146
202
  // reword it into something it does not say, it is left out.
@@ -153,16 +209,23 @@ const readAudit = (text) => {
153
209
  for (const value of listed) {
154
210
  const entry = (0, json_utils_1.asRecord)(value);
155
211
  const module = (0, json_utils_1.asText)(entry?.['module_name']);
156
- if (entry && module) {
157
- found.push({
158
- package: module,
159
- severity: severityOf(entry['severity']),
160
- title: (0, json_utils_1.asText)(entry['title']) ?? module,
161
- url: (0, json_utils_1.asText)(entry['url']),
162
- range: null,
163
- fixedIn: null,
164
- });
212
+ if (!entry || !module) {
213
+ continue;
165
214
  }
215
+ // pnpm writes this shape too, with what npm 6 left out: the range, what fixes it, and the
216
+ // versions actually installed. Read as `null`, the report printed no range at all.
217
+ const versions = ((0, json_utils_1.asArray)(entry['findings']) ?? [])
218
+ .map(finding => (0, json_utils_1.asText)((0, json_utils_1.asRecord)(finding)?.['version']))
219
+ .filter(version => version !== null);
220
+ found.push({
221
+ package: module,
222
+ severity: severityOf(entry['severity']),
223
+ title: (0, json_utils_1.asText)(entry['title']) ?? module,
224
+ url: (0, json_utils_1.asText)(entry['url']),
225
+ range: (0, json_utils_1.asText)(entry['vulnerable_versions']),
226
+ fixedIn: (0, json_utils_1.asText)(entry['patched_versions']),
227
+ ...(versions.length > 0 && { versions }),
228
+ });
166
229
  }
167
230
  // Neither key present means this JSON was not an audit report at all, which is not the same
168
231
  // answer as an audit report with nothing in it.
@@ -170,12 +233,30 @@ const readAudit = (text) => {
170
233
  };
171
234
  exports.readAudit = readAudit;
172
235
  const RANK = { critical: 0, high: 1, moderate: 2, low: 3, info: 4 };
236
+ /**
237
+ * The version of `pkg` a module path names, when pnpm laid it out: `.pnpm/devalue@6.0.2/…`.
238
+ * `null` in every other layout, and when the segment is some other package's.
239
+ */
240
+ const PNPM_SEGMENT = /\.pnpm\/((?:@[^/+]+\+)?[^@/]+)@([^/_]+)/;
241
+ const shippedVersionOf = (path, pkg) => {
242
+ const match = PNPM_SEGMENT.exec(path);
243
+ return match?.[1]?.replace('+', '/') === pkg ? (match[2] ?? null) : null;
244
+ };
245
+ /**
246
+ * Whether the advisory is about the copy that ships. Only answered "no" when both sides name exact
247
+ * versions and they share none: an audit of a Nuxt app reported six advisories against
248
+ * `devalue <=5.9.2` as in the first load, raised them to `high` and failed `--fail-on high`, while
249
+ * the browser carried `devalue@6.0.2` and 5.9.2 was a copy only the server had. Anything less
250
+ * certain than that stays reported, which is the side to be wrong on.
251
+ */
252
+ const affectsShipped = (advisory, shipped) => !advisory.versions || !shipped || shipped.size === 0 || advisory.versions.some(version => shipped.has(version));
173
253
  /**
174
254
  * The crossing. What every figure here is about is the word **shipped**: an advisory whose package
175
255
  * never reaches a browser is real and is not what this report is for.
176
256
  */
177
257
  const readDeps = (input) => {
178
258
  const shippedBytes = new Map();
259
+ const shippedVersions = new Map();
179
260
  for (const module of input.modules) {
180
261
  if (!module.pkg) {
181
262
  continue;
@@ -184,22 +265,58 @@ const readDeps = (input) => {
184
265
  entry.bytes += module.bytes;
185
266
  entry.inBoot ||= module.places.some(place => input.boot.has(place.chunk));
186
267
  shippedBytes.set(module.pkg, entry);
268
+ const version = shippedVersionOf(module.path, module.pkg);
269
+ if (version) {
270
+ shippedVersions.set(module.pkg, (shippedVersions.get(module.pkg) ?? new Set()).add(version));
271
+ }
187
272
  }
273
+ const ships = (advisory) => shippedBytes.has(advisory.package) && affectsShipped(advisory, shippedVersions.get(advisory.package));
188
274
  const byName = new Map();
189
275
  const locked = input.lock ?? [];
276
+ const parents = new Map();
190
277
  for (const entry of locked) {
191
278
  byName.set(entry.name, [...(byName.get(entry.name) ?? []), entry]);
279
+ const declared = Object.keys(entry.declares ?? {});
280
+ for (const dependency of declared) {
281
+ parents.set(dependency, (parents.get(dependency) ?? new Set()).add(entry.name));
282
+ }
192
283
  }
284
+ /**
285
+ * The shortest chain from something the project asked for to the package that pulls `name` in,
286
+ * walked up what each lock entry declares. Nothing filled `requiredBy`, so "each one comes with
287
+ * the dependency chain that pulls it" was printed over chains that were always empty. Empty
288
+ * still when the lock does not record what each entry declares (pnpm's does not here) or when
289
+ * nothing the project asked for is up the chain.
290
+ */
291
+ const chainOf = (name) => {
292
+ const seen = new Set([name]);
293
+ const queue = [[name]];
294
+ for (let path = queue.shift(); path; path = queue.shift()) {
295
+ const above = parents.get(path[0] ?? '') ?? [];
296
+ for (const parent of above) {
297
+ if (seen.has(parent)) {
298
+ continue;
299
+ }
300
+ const longer = [parent, ...path];
301
+ if (input.direct.has(parent)) {
302
+ return longer.slice(0, -1);
303
+ }
304
+ seen.add(parent);
305
+ queue.push(longer);
306
+ }
307
+ }
308
+ return byName.get(name)?.[0]?.requiredBy ?? [];
309
+ };
193
310
  const advisories = input.advisories ?? [];
194
311
  const shipped = advisories
195
- .filter(advisory => shippedBytes.has(advisory.package))
312
+ .filter(advisory => ships(advisory))
196
313
  .map(advisory => {
197
314
  const where = shippedBytes.get(advisory.package);
198
315
  return {
199
316
  ...advisory,
200
317
  bytes: where?.bytes ?? 0,
201
318
  inBoot: where?.inBoot ?? false,
202
- chain: byName.get(advisory.package)?.[0]?.requiredBy ?? [],
319
+ chain: chainOf(advisory.package),
203
320
  };
204
321
  })
205
322
  .toSorted((a, b) => Number(b.inBoot) - Number(a.inBoot) || RANK[a.severity] - RANK[b.severity]);
@@ -207,19 +324,20 @@ const readDeps = (input) => {
207
324
  lockRead: input.lock !== null,
208
325
  auditRead: input.advisories !== null,
209
326
  shipped,
210
- notShipped: advisories.filter(advisory => !shippedBytes.has(advisory.package)),
327
+ notShipped: advisories.filter(advisory => !ships(advisory)),
211
328
  transitive: [...shippedBytes]
212
329
  .filter(([name]) => input.direct.size > 0 && !input.direct.has(name))
213
330
  .map(([name, entry]) => ({
214
331
  name,
215
332
  bytes: entry.bytes,
216
333
  inBoot: entry.inBoot,
217
- chain: byName.get(name)?.[0]?.requiredBy ?? [],
334
+ chain: chainOf(name),
218
335
  }))
219
336
  .toSorted((a, b) => b.bytes - a.bytes),
220
337
  multipleVersions: [...byName]
221
338
  .filter(([name, entries]) => entries.length > 1 && shippedBytes.has(name))
222
339
  .map(([name, entries]) => ({ name, versions: entries.map(entry => entry.version) })),
340
+ declared: (0, pins_1.declaredFromLock)(input.lock),
223
341
  };
224
342
  };
225
343
  exports.readDeps = readDeps;
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ /**
3
+ * Whether a duplicated package can be deduplicated at all.
4
+ *
5
+ * "Force the resolution with an override" is the right advice when the two ranges overlap and the
6
+ * wrong one when a dependency **pins** an exact version: `@firebase/app` asks for `idb` at exactly
7
+ * `7.1.1`, and the only way to collapse that copy onto another is to hand Firebase a version it
8
+ * was never released against. When the two copies are a major version apart, that is a breaking
9
+ * change inside somebody else's package, and the report used to suggest it without a word.
10
+ *
11
+ * The ranges come from what the project already has: a `package-lock.json` or a `yarn.lock` write
12
+ * each package's declared dependencies, and the command reads the `package.json` of the parent in
13
+ * `node_modules` when the lock is pnpm's, which records resolved versions only. Nothing is fetched.
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.pinsOf = exports.declaredFromLock = void 0;
17
+ /** `7.1.1`, `=7.1.1`, `v7.1.1`, `npm:7.1.1`: a single version, no range operator anywhere. */
18
+ const EXACT = /^(?:npm:)?[=v]?(\d+)\.(\d+)\.(\d+)(?:-[\w.-]+)?(?:\+[\w.-]+)?$/;
19
+ const majorOf = (version) => /^(?:npm:)?[=v]?(\d+)\./.exec(version ?? '')?.[1] ?? null;
20
+ /** What the lock file itself says each package declares. npm and yarn write it; pnpm does not. */
21
+ const declaredFromLock = (lock) => {
22
+ const declared = new Map();
23
+ const entries = lock ?? [];
24
+ for (const entry of entries) {
25
+ if (entry.declares && Object.keys(entry.declares).length > 0) {
26
+ declared.set(entry.name, { ...declared.get(entry.name), ...entry.declares });
27
+ }
28
+ }
29
+ return declared;
30
+ };
31
+ exports.declaredFromLock = declaredFromLock;
32
+ /** The pins of each duplicated package, by package name. Empty when nothing is pinned. */
33
+ const pinsOf = (duplicates, declared) => {
34
+ const found = new Map();
35
+ if (!declared || declared.size === 0) {
36
+ return found;
37
+ }
38
+ /** The pin one parent puts on one copy, or `null` when what it declares is a range. */
39
+ const pinOf = (dupe, copy, parent) => {
40
+ const range = declared.get(parent)?.[dupe.name]?.trim();
41
+ const exact = range ? EXACT.exec(range) : null;
42
+ if (!range || !exact) {
43
+ return null;
44
+ }
45
+ const others = dupe.copies.filter(other => other !== copy).map(other => majorOf(other.version));
46
+ return {
47
+ parent,
48
+ range,
49
+ version: `${exact[1]}.${exact[2]}.${exact[3]}`,
50
+ majorApart: others.some(major => major !== null && major !== exact[1]),
51
+ };
52
+ };
53
+ for (const dupe of duplicates) {
54
+ const pins = dupe.copies
55
+ .flatMap(copy => copy.viaPackages.map(parent => pinOf(dupe, copy, parent)))
56
+ .filter((pin) => pin !== null);
57
+ if (pins.length > 0) {
58
+ found.set(dupe.name, pins);
59
+ }
60
+ }
61
+ return found;
62
+ };
63
+ exports.pinsOf = pinsOf;
@@ -12,17 +12,24 @@
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
13
  exports.summaryText = void 0;
14
14
  const actions_1 = require("../findings/actions");
15
+ const finding_plain_1 = require("../findings/text/finding-plain");
15
16
  const format_utils_1 = require("../format/format.utils");
17
+ const defer_1 = require("../whatif/defer");
16
18
  const WORDS = {
17
19
  en: {
18
20
  boot: 'Bootstrap',
19
21
  trip: 'First trip',
20
22
  screens: 'Screens',
21
23
  worst: 'Heaviest screen',
22
- signals: 'Signals',
24
+ signals: (shown, all) => `Signals to review: ${shown} of ${all}`,
23
25
  actions: 'What to fix first',
24
26
  saving: 'All of it is worth',
25
- none: 'nothing that can be measured',
27
+ whatIf: 'What if it were deferred',
28
+ gatesPassed: 'Gates: all passed',
29
+ gatesBroken: (count) => `Gates: ${count} broken`,
30
+ without: (target, saved, after) => ` without ${target}: ${saved} off the first load, which would then weigh ${after}`,
31
+ unknown: (target) => ` without ${target}: cannot be measured, this build does not say which file imports which`,
32
+ opaque: 'No source maps: what each chunk weighs is known, what is inside it is not.',
26
33
  tail: (unit) => `— Loadline, figures ${unit}`,
27
34
  },
28
35
  es: {
@@ -30,10 +37,15 @@ const WORDS = {
30
37
  trip: 'Primer viaje',
31
38
  screens: 'Pantallas',
32
39
  worst: 'Pantalla más pesada',
33
- signals: 'Señales',
34
- actions: 'Qué arreglar primero',
40
+ signals: (shown, all) => `Señales a revisar: ${shown} de ${all}`,
41
+ actions: 'Qué arreglo primero',
35
42
  saving: 'Todo junto vale',
36
- none: 'nada que se pueda medir',
43
+ whatIf: 'Y si se difiriera',
44
+ gatesPassed: 'Gates: todos pasan',
45
+ gatesBroken: (count) => `Gates: ${count} ${count === 1 ? 'roto' : 'rotos'}`,
46
+ without: (target, saved, after) => ` sin ${target}: ${saved} menos en la primera carga, que pasaría a pesar ${after}`,
47
+ unknown: (target) => ` sin ${target}: no se puede medir, este build no dice qué fichero importa a cuál`,
48
+ opaque: 'Sin source maps: se sabe lo que pesa cada chunk, no lo que hay dentro.',
37
49
  tail: (unit) => `— Loadline, cifras ${unit}`,
38
50
  },
39
51
  };
@@ -46,25 +58,55 @@ const summaryText = (input) => {
46
58
  const { analysis, comparison } = input;
47
59
  const worst = analysis.screens[0];
48
60
  const problems = input.findings.filter(finding => finding.severity === 'high' || finding.severity === 'mid');
61
+ const scale = (0, actions_1.unitScale)(analysis);
49
62
  const total = (0, actions_1.totalSaving)(analysis, input.findings);
63
+ const actions = (0, actions_1.rankActions)(input.findings).slice(0, 3);
64
+ const whatIf = input.whatIf ?? [];
65
+ const opaque = (0, defer_1.blindBoot)(analysis);
50
66
  const bootLine = comparison
51
67
  ? `${(0, format_utils_1.formatBytes)(analysis.bootBytes)} (${(0, format_utils_1.formatDelta)(comparison.boot.diff)} vs ${comparison.baselineName})`
52
68
  : (0, format_utils_1.formatBytes)(analysis.bootBytes);
53
69
  const lines = [
54
70
  `Loadline · ${input.name}`,
71
+ // Up here and not in a signal: it decides how every line below is read, and a paste is
72
+ // read once, from the top.
73
+ ...(opaque ? [words.opaque] : []),
55
74
  '',
56
75
  `${words.boot}: ${bootLine}`,
76
+ ...(input.since ? [input.since] : []),
57
77
  ...(input.firstTrip === null ? [] : [`${words.trip}: ${(0, format_utils_1.formatBytes)(input.firstTrip)}`]),
58
78
  `${words.screens}: ${analysis.screens.length}`,
59
79
  ...(worst ? [`${words.worst}: ${worst.label} — ${(0, format_utils_1.formatBytes)(worst.total)}`] : []),
60
- `${words.signals}: ${problems.length}`,
80
+ // The ones worth a look, out of all of them: "Signals: 2" next to another format's 7
81
+ // read as two reports disagreeing.
82
+ words.signals(problems.length, input.findings.length),
83
+ // A pipeline that went red has to say why in the step that turned it red: the summary is
84
+ // the format recommended for a job log, and it used to exit 1 without naming the gate.
85
+ ...(input.gates === undefined
86
+ ? []
87
+ : input.gates.length === 0
88
+ ? [words.gatesPassed]
89
+ : [words.gatesBroken(input.gates.length), ...input.gates.map(line => ` x ${line}`)]),
90
+ ...(actions.length > 0
91
+ ? [
92
+ '',
93
+ `${words.actions}:`,
94
+ ...actions.map((action, index) => ` ${index + 1}. ${(0, finding_plain_1.plainText)(action.finding.title)}${action.saving > 0 ? ` — ${(0, actions_1.formatSaving)(action.saving, scale)}` : ''}`),
95
+ ]
96
+ : []),
97
+ // Only when there is something to say. "All of it is worth: nothing that can be measured"
98
+ // was a line in every paste that carried no information at all.
99
+ ...(total.counted > 0 && total.bytes > 0 ? ['', `${words.saving}: ${(0, actions_1.formatSaving)(total.bytes, scale)}`] : []),
100
+ ...(whatIf.length > 0
101
+ ? [
102
+ '',
103
+ `${words.whatIf}:`,
104
+ ...whatIf.map(result => result.measurable
105
+ ? words.without(result.target, (0, actions_1.formatSaving)(result.saved, scale), (0, actions_1.formatRemaining)(analysis, result.saved, result.after))
106
+ : words.unknown(result.target)),
107
+ ]
108
+ : []),
61
109
  '',
62
- `${words.actions}:`,
63
- ...(0, actions_1.rankActions)(input.findings)
64
- .slice(0, 3)
65
- .map((action, index) => ` ${index + 1}. ${action.finding.title}${action.saving > 0 ? ` — ${(0, format_utils_1.formatBytes)(action.saving)}` : ''}`),
66
- '',
67
- `${words.saving}: ${total.counted > 0 ? (0, format_utils_1.formatBytes)(total.bytes) : words.none}`,
68
110
  words.tail(input.unit),
69
111
  ];
70
112
  return `${lines.join('\n')}\n`;
@@ -12,7 +12,8 @@
12
12
  * what removing both gives. It is one walk of the graph with every named file taken out at once.
13
13
  */
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.rankActions = exports.totalSaving = void 0;
15
+ exports.rankActions = exports.savingInUnit = exports.savingWords = exports.formatRemaining = exports.remainingInUnit = exports.formatSaving = exports.inUnit = exports.unitScale = exports.RAW_SCALE = exports.totalSaving = void 0;
16
+ const format_utils_1 = require("../format/format.utils");
16
17
  const effort_1 = require("./effort");
17
18
  /**
18
19
  * Everything the signals are worth together.
@@ -38,12 +39,69 @@ const totalSaving = (analysis, findings) => {
38
39
  return { bytes, before: insights.bootTotal, after: Math.max(0, insights.bootTotal - bytes), counted };
39
40
  };
40
41
  exports.totalSaving = totalSaving;
42
+ /** A raw report: nothing converted, nothing estimated. */
43
+ exports.RAW_SCALE = { ratio: 1, estimated: false };
44
+ const unitScale = (analysis) => {
45
+ const estimated = analysis.bootRawBytes > 0 && analysis.bootBytes !== analysis.bootRawBytes;
46
+ return { ratio: estimated ? analysis.bootBytes / analysis.bootRawBytes : 1, estimated };
47
+ };
48
+ exports.unitScale = unitScale;
49
+ /** Raw bytes in the report's unit. */
50
+ const inUnit = (bytes, scale) => Math.round(bytes * scale.ratio);
51
+ exports.inUnit = inUnit;
52
+ /** A saving as it is printed: `≈93 kB` when it is an estimate, `302 kB` when it is not. Zero is exact. */
53
+ const formatSaving = (bytes, scale) => `${scale.estimated && bytes > 0 ? '≈' : ''}${(0, format_utils_1.formatBytes)((0, exports.inUnit)(bytes, scale))}`;
54
+ exports.formatSaving = formatSaving;
55
+ /**
56
+ * The first load a saving leaves, in the report's unit. Converted, it comes off the bootstrap the
57
+ * report heads with — not off the raw walk, which is a different figure in a different unit.
58
+ */
59
+ const remainingInUnit = (analysis, saved, rawAfter) => {
60
+ const scale = (0, exports.unitScale)(analysis);
61
+ return scale.estimated ? Math.max(0, analysis.bootBytes - (0, exports.inUnit)(saved, scale)) : rawAfter;
62
+ };
63
+ exports.remainingInUnit = remainingInUnit;
64
+ /** That first load as it is printed, with `≈` when it is an estimate. */
65
+ const formatRemaining = (analysis, saved, rawAfter) => `${(0, exports.unitScale)(analysis).estimated ? '≈' : ''}${(0, format_utils_1.formatBytes)((0, exports.remainingInUnit)(analysis, saved, rawAfter))}`;
66
+ exports.formatRemaining = formatRemaining;
67
+ /**
68
+ * The figures of "fixing all of it would take X off, leaving it at about Y", as text. `after`
69
+ * carries no `≈`: the sentence it goes into already says "about".
70
+ */
71
+ const savingWords = (analysis, total) => {
72
+ const scale = (0, exports.unitScale)(analysis);
73
+ return {
74
+ saving: (0, exports.formatSaving)(total.bytes, scale),
75
+ after: (0, format_utils_1.formatBytes)((0, exports.remainingInUnit)(analysis, total.bytes, total.after)),
76
+ estimated: scale.estimated,
77
+ };
78
+ };
79
+ exports.savingWords = savingWords;
80
+ /** What all of it is worth, in the report's unit: the saving and the first load it leaves. */
81
+ const savingInUnit = (analysis, total) => {
82
+ const scale = (0, exports.unitScale)(analysis);
83
+ return {
84
+ bytes: (0, exports.inUnit)(total.bytes, scale),
85
+ after: (0, exports.remainingInUnit)(analysis, total.bytes, total.after),
86
+ estimated: scale.estimated,
87
+ };
88
+ };
89
+ exports.savingInUnit = savingInUnit;
90
+ /** Most severe first. `ok` never reaches the list: a verdict that all is well is not a task. */
91
+ const SEVERITY_RANK = { high: 0, mid: 1, info: 2, ok: 3 };
41
92
  /**
42
93
  * The signals in the order somebody would do them.
43
94
  *
95
+ * **Severity first, then bytes per unit of effort.** Sorting by score alone put twelve medium and
96
+ * informative signals ahead of a high one that names no saving in kilobytes — a key leaked into the
97
+ * bundle saves nothing and is still the first thing anybody should touch. The score orders within a
98
+ * severity, which is where comparing kilobytes against effort makes sense.
99
+ *
44
100
  * Only what can be acted on: a signal whose effort is `none` is context — a verdict, a note about
45
101
  * the report itself, a growth against the baseline — and putting "the bootstrap has grown" on a
46
- * list of things to do would be a category mistake.
102
+ * list of things to do would be a category mistake. **A high one is the exception**: whatever its
103
+ * effort, leaving it out of "what to fix first" is how the summary came to list three medium
104
+ * signals and skip the one that mattered.
47
105
  */
48
106
  const rankActions = (findings) => findings
49
107
  .map((finding) => {
@@ -52,8 +110,9 @@ const rankActions = (findings) => findings
52
110
  const weight = effort_1.EFFORT_WEIGHT[effort];
53
111
  return { finding, saving, effort, score: weight > 0 ? saving / weight : 0 };
54
112
  })
55
- .filter(action => action.effort !== 'none')
56
- .toSorted((a, b) => b.score - a.score ||
57
- // With nothing to weigh them by, the severity the signal already carries decides.
58
- Number(b.finding.severity === 'high') - Number(a.finding.severity === 'high'));
113
+ .filter(action => action.effort !== 'none' || action.finding.severity === 'high')
114
+ .filter(action => action.finding.severity !== 'ok')
115
+ .toSorted((a, b) => SEVERITY_RANK[a.finding.severity] - SEVERITY_RANK[b.finding.severity] ||
116
+ b.score - a.score ||
117
+ b.saving - a.saving);
59
118
  exports.rankActions = rankActions;
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ /**
3
+ * A package in the bootstrap that one file of the project imports, and that file is code everybody
4
+ * runs rather than a screen.
5
+ *
6
+ * `bootLazy` covers the case where that one importer is a lazy screen. This is the other one, and
7
+ * the one that came up in the field: Teams, Firebase and ua-parser-js each in the bootstrap of one
8
+ * application, each imported by a single service, and the only way to see it was to read the list
9
+ * of importers row by row. One importer is an address — one place to decide whether the package is
10
+ * needed before the first paint or only when something happens — and that is the whole signal.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.buildBootSingleFindings = void 0;
14
+ const format_utils_1 = require("../../format/format.utils");
15
+ const finding_html_1 = require("../text/finding-html");
16
+ const finding_text_1 = require("../text/finding-text");
17
+ /**
18
+ * Packages a bootstrap needs by definition: the framework, its runtime and the helpers every file
19
+ * compiles against. One file importing `@angular/platform-browser` is `main.ts` starting the app,
20
+ * not a candidate for deferring.
21
+ */
22
+ const FRAMEWORK = /^(?:@angular\/|zone\.js$|tslib$|rxjs$|react$|react-dom$|vue$|@vue\/|svelte$|preact$|solid-js$)/;
23
+ /**
24
+ * The files the application starts from, and the root component it renders first. Whatever they
25
+ * import is on the path to the first paint by construction: an icon library the shell imports is
26
+ * drawn before anything else, and calling it a candidate for deferring was the first false positive
27
+ * this signal produced, on the example build.
28
+ */
29
+ const ENTRY_FILE = /(?:^|\/)(?:(?:main|polyfills|index)(?:\.[\w-]+)?|app(?:\.component)?)\.[cm]?[jt]sx?$/;
30
+ /**
31
+ * @param skip packages another signal already names, so the same package is not two cards.
32
+ */
33
+ const buildBootSingleFindings = (analysis, lang, c, skip) => {
34
+ const insights = analysis.insights();
35
+ const filesOf = (bucket) => insights.filesByBucket.get(bucket) ?? [];
36
+ const screens = new Set(analysis.screens.map(screen => screen.source));
37
+ const single = analysis.bootBuckets
38
+ .filter(bucket => !bucket.isProjectCode && bucket.bytes >= c.bootPackageMinBytes)
39
+ .filter(bucket => !skip.has(bucket.name) && !FRAMEWORK.test(bucket.name))
40
+ .map(bucket => ({ bucket, importers: [...(analysis.packageImporters.get(bucket.name) ?? [])] }))
41
+ .filter(({ importers }) => {
42
+ const [only] = importers;
43
+ return importers.length === 1 && !!only && !screens.has(only) && !ENTRY_FILE.test(only);
44
+ })
45
+ .map(({ bucket, importers }) => ({
46
+ name: bucket.name,
47
+ bytes: bucket.bytes,
48
+ importer: importers[0] ?? '',
49
+ saving: insights.exclusive.get(bucket.name) ?? 0,
50
+ }))
51
+ .toSorted((a, b) => b.saving - a.saving || b.bytes - a.bytes);
52
+ const first = single[0];
53
+ if (!first) {
54
+ return [];
55
+ }
56
+ const files = single.flatMap(entry => filesOf(entry.name));
57
+ return [
58
+ {
59
+ severity: 'mid',
60
+ target: { tab: 'boot', key: first.name },
61
+ kind: 'bootSingle',
62
+ saving: insights.exclusiveOf(files),
63
+ sources: files,
64
+ ...finding_text_1.TEXT[lang].bootSingle({
65
+ count: single.length,
66
+ pkg: first.name,
67
+ importer: (0, format_utils_1.baseName)(first.importer),
68
+ size: (0, format_utils_1.formatBytes)(single.reduce((sum, entry) => sum + entry.bytes, 0)),
69
+ list: single
70
+ .map(entry => `${(0, finding_html_1.mono)(entry.name)} (${(0, format_utils_1.formatBytes)(entry.bytes)}) ← ${(0, finding_html_1.mono)(entry.importer)}`)
71
+ .join(' · '),
72
+ }),
73
+ },
74
+ ];
75
+ };
76
+ exports.buildBootSingleFindings = buildBootSingleFindings;