@bymaksym/loadline 1.0.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 (112) hide show
  1. package/README.md +211 -43
  2. package/dist/cli/cli/args.js +79 -128
  3. package/dist/cli/cli/gates.js +80 -14
  4. package/dist/cli/cli/main.js +164 -33
  5. package/dist/cli/cli/memory.js +40 -4
  6. package/dist/cli/cli/{declared.js → read/declared.js} +1 -1
  7. package/dist/cli/cli/read/locate.js +214 -0
  8. package/dist/cli/cli/{read-build.js → read/read-build.js} +149 -84
  9. package/dist/cli/cli/read/read-config.js +120 -0
  10. package/dist/cli/cli/{html-report.js → render/html-report.js} +14 -10
  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} +18 -5
  15. package/dist/cli/cli/{render-markdown.js → render/render-markdown.js} +5 -5
  16. package/dist/cli/cli/{render-pr.js → render/render-pr.js} +33 -13
  17. package/dist/cli/cli/{render-sarif.js → render/render-sarif.js} +8 -3
  18. package/dist/cli/cli/{render-text.js → render/render-text.js} +118 -111
  19. package/dist/cli/cli/render/terminal.js +55 -0
  20. package/dist/cli/cli/report.js +68 -27
  21. package/dist/cli/cli/self-check.js +19 -23
  22. package/dist/cli/cli/since-last.js +2 -2
  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 +63 -23
  27. package/dist/cli/src/app/core/analysis/{barrels.js → graph/barrels.js} +1 -1
  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 +7 -1
  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} +50 -9
  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} +1 -1
  40. package/dist/cli/src/app/core/analysis/tool.js +83 -0
  41. package/dist/cli/src/app/core/assets/assets.js +134 -15
  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 +168 -13
  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 +121 -43
  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 +104 -16
  53. package/dist/cli/src/app/core/export/summary.js +29 -5
  54. package/dist/cli/src/app/core/findings/actions.js +3 -1
  55. package/dist/cli/src/app/core/findings/{boot-single.js → bundle/boot-single.js} +3 -3
  56. package/dist/cli/src/app/core/findings/{dupes.js → bundle/dupes.js} +8 -5
  57. package/dist/cli/src/app/core/findings/{graph.js → bundle/graph.js} +30 -18
  58. package/dist/cli/src/app/core/findings/{own-in-boot.js → bundle/own-in-boot.js} +9 -5
  59. package/dist/cli/src/app/core/findings/{requests.js → bundle/requests.js} +3 -3
  60. package/dist/cli/src/app/core/findings/{shipped.js → bundle/shipped.js} +28 -14
  61. package/dist/cli/src/app/core/findings/compose.js +6 -1
  62. package/dist/cli/src/app/core/findings/effort.js +2 -0
  63. package/dist/cli/src/app/core/findings/finding.types.js +1 -0
  64. package/dist/cli/src/app/core/findings/findings.js +48 -19
  65. package/dist/cli/src/app/core/findings/{assets.js → folder/assets.js} +38 -14
  66. package/dist/cli/src/app/core/findings/{caching.js → folder/caching.js} +16 -9
  67. package/dist/cli/src/app/core/findings/{page.js → folder/page.js} +6 -2
  68. package/dist/cli/src/app/core/findings/{scan.js → folder/scan.js} +25 -11
  69. package/dist/cli/src/app/core/findings/kind-names.js +163 -0
  70. package/dist/cli/src/app/core/findings/{deps.js → supplied/deps.js} +13 -8
  71. package/dist/cli/src/app/core/findings/supplied/forbidden.js +71 -0
  72. package/dist/cli/src/app/core/findings/{situation.js → supplied/situation.js} +2 -2
  73. package/dist/cli/src/app/core/findings/text/causes.js +39 -0
  74. package/dist/cli/src/app/core/findings/{finding-html.js → text/finding-html.js} +8 -1
  75. package/dist/cli/src/app/core/findings/{finding-text.js → text/finding-text.js} +208 -77
  76. package/dist/cli/src/app/core/findings/text/tool-advice.js +97 -0
  77. package/dist/cli/src/app/core/format/format.utils.js +158 -11
  78. package/dist/cli/src/app/core/format/ownership.js +93 -0
  79. package/dist/cli/src/app/core/i18n/en.js +76 -17
  80. package/dist/cli/src/app/core/i18n/es.js +82 -22
  81. package/dist/cli/src/app/core/intake/bundle-graph.js +281 -43
  82. package/dist/cli/src/app/core/intake/dist-files.js +82 -14
  83. package/dist/cli/src/app/core/intake/embedded.js +11 -1
  84. package/dist/cli/src/app/core/intake/unreached.js +139 -0
  85. package/dist/cli/src/app/core/intake/webpack-modules.js +185 -0
  86. package/dist/cli/src/app/core/intake/webpack-stats.js +298 -0
  87. package/dist/cli/src/app/core/project/project-context.js +16 -4
  88. package/dist/cli/src/app/core/project/project-name.js +36 -0
  89. package/dist/cli/src/app/core/scan/scan.js +58 -19
  90. package/dist/cli/src/app/core/scan/secrets.js +23 -3
  91. package/dist/cli/src/app/core/situation/situation-text.js +23 -0
  92. package/dist/cli/src/app/core/situation/situation.js +6 -4
  93. package/dist/cli/src/app/core/timing/timing.js +5 -2
  94. package/dist/cli/src/app/core/whatif/defer.js +29 -4
  95. package/dist/cli/src/app/core/whatif/source-importers.js +58 -0
  96. package/dist/cli/src/app/core/whatif/why.js +102 -0
  97. package/docs/CONFIG-REFERENCE.md +230 -0
  98. package/docs/CONFIG.md +511 -0
  99. package/docs/HOW-IT-WORKS.md +286 -25
  100. package/loadline.html +24 -20
  101. package/loadline.schema.json +1209 -0
  102. package/package.json +35 -29
  103. package/dist/cli/cli/locate.js +0 -60
  104. package/dist/cli/cli/text.js +0 -215
  105. /package/dist/cli/cli/{read-build.types.js → read/read-build.types.js} +0 -0
  106. /package/dist/cli/cli/{render-json.types.js → render/render-json.types.js} +0 -0
  107. /package/dist/cli/cli/{text.types.js → text/text.types.js} +0 -0
  108. /package/dist/cli/src/app/core/analysis/{exclusive.js → graph/exclusive.js} +0 -0
  109. /package/dist/cli/src/app/core/analysis/{insights.types.js → graph/insights.types.js} +0 -0
  110. /package/dist/cli/src/app/core/analysis/{module-graph.js → graph/module-graph.js} +0 -0
  111. /package/dist/cli/src/app/core/analysis/{sourcemap.types.js → sourcemap/sourcemap.types.js} +0 -0
  112. /package/dist/cli/src/app/core/findings/{finding-plain.js → text/finding-plain.js} +0 -0
@@ -0,0 +1,298 @@
1
+ "use strict";
2
+ /**
3
+ * webpack's `stats.json`, read as the metafile everything else analyses.
4
+ *
5
+ * It was refused on purpose until 09/10/2026, with "Statoscope does it better". It is also, by far,
6
+ * what the applications written before 2020 can produce: Angular up to 16, Create React App, Vue
7
+ * CLI, Gatsby, Nuxt 2, Rspack. Their folders cannot be read — the chunks load each other by number —
8
+ * and the stats file has the same three things the metafile has, in another shape:
9
+ *
10
+ * | webpack | metafile |
11
+ * | ---------------------------------------- | ---------------------------------------------- |
12
+ * | `modules[]` (and `chunks[].modules[]`) | `inputs`, with the edges taken from `reasons` |
13
+ * | `chunks[].files` and `assets[].size` | `outputs`, one per file the browser downloads |
14
+ * | `entrypoints[].chunks` | static edges: the files an entry starts with |
15
+ * | `chunks[].origins` | lazy edges: who asked for the chunk, and where |
16
+ *
17
+ * ⚠️ **A module's `size` is its source before minification**, not what it takes in the file. A main
18
+ * chunk of Angular 8 is 2.9 MB of modules in a file of 560 kB. The per-file weights are that size
19
+ * shared out in proportion to what the file weighs, so they add up to the file and the bootstrap
20
+ * by package reads in the unit of everything else. It is an estimate — minification does not shrink
21
+ * every file by the same factor — and a source map in the folder replaces it with a measurement,
22
+ * as it does for every other build.
23
+ */
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.metafileOf = exports.fromWebpackStats = void 0;
26
+ const metafile_types_1 = require("../analysis/metafile.types");
27
+ const json_utils_1 = require("../json/json.utils");
28
+ const webpack_modules_1 = require("./webpack-modules");
29
+ /**
30
+ * The compilation that is the browser's. A build of several configurations writes one per child and
31
+ * nothing at the top: the one with chunks is taken, and of several, not the server's — nobody
32
+ * downloads that — and then the one with the most chunks.
33
+ */
34
+ const compilationOf = (data) => {
35
+ if (((0, json_utils_1.asArray)(data['chunks'])?.length ?? 0) > 0) {
36
+ return data;
37
+ }
38
+ const children = ((0, json_utils_1.asArray)(data['children']) ?? [])
39
+ .map(child => (0, json_utils_1.asRecord)(child))
40
+ .filter((child) => ((0, json_utils_1.asArray)(child?.['chunks'])?.length ?? 0) > 0);
41
+ const browser = children.filter(child => !/server|edge|node/i.test((0, json_utils_1.asText)(child['name']) ?? ''));
42
+ const [best] = (browser.length > 0 ? browser : children).toSorted((a, b) => ((0, json_utils_1.asArray)(b['chunks'])?.length ?? 0) - ((0, json_utils_1.asArray)(a['chunks'])?.length ?? 0));
43
+ return best ?? null;
44
+ };
45
+ const chunksOf = (compilation) => ((0, json_utils_1.asArray)(compilation['chunks']) ?? []).flatMap(item => {
46
+ const chunk = (0, json_utils_1.asRecord)(item);
47
+ if (!chunk) {
48
+ return [];
49
+ }
50
+ const origins = ((0, json_utils_1.asArray)(chunk['origins']) ?? []).flatMap(entry => {
51
+ const origin = (0, json_utils_1.asRecord)(entry);
52
+ const from = (0, json_utils_1.asText)(origin?.['moduleName']) ?? '';
53
+ return origin && from
54
+ ? [{ from, loc: (0, json_utils_1.asText)(origin['loc']) ?? '', request: (0, json_utils_1.asText)(origin['request']) ?? '' }]
55
+ : [];
56
+ });
57
+ return [
58
+ {
59
+ id: String(chunk['id']),
60
+ names: (0, webpack_modules_1.textsOf)(chunk['names']),
61
+ files: (0, webpack_modules_1.textsOf)(chunk['files']),
62
+ initial: chunk['initial'] === true,
63
+ parents: (0, webpack_modules_1.idsOf)(chunk['parents']),
64
+ origins,
65
+ },
66
+ ];
67
+ });
68
+ /** What each emitted file weighs. webpack 5 nests them in groups for the terminal, as it does modules. */
69
+ const assetSizes = (list, into = new Map()) => {
70
+ const items = (0, json_utils_1.asArray)(list) ?? [];
71
+ for (const item of items) {
72
+ const asset = (0, json_utils_1.asRecord)(item);
73
+ const name = (0, json_utils_1.asText)(asset?.['name']);
74
+ if (asset && name && typeof asset['size'] === 'number') {
75
+ into.set(name, asset['size']);
76
+ }
77
+ else if (asset) {
78
+ assetSizes(asset['children'], into);
79
+ }
80
+ }
81
+ return into;
82
+ };
83
+ const isScript = (file) => /\.m?js$/.test(file);
84
+ const isStyle = (file) => file.endsWith('.css');
85
+ /**
86
+ * The source weights of a chunk shared out over what its file weighs, so they add up to the file
87
+ * (see the top of this file). Rounded down, with what rounding lost given to the largest, so the
88
+ * sum is exact: the breakdown that does not add up to the file is a signal of its own (§3.23).
89
+ */
90
+ const shareOut = (parts, bytes) => {
91
+ let total = 0;
92
+ for (const size of parts.values()) {
93
+ total += size;
94
+ }
95
+ if (total === 0) {
96
+ return {};
97
+ }
98
+ const shares = [...parts].map(([path, size]) => [path, Math.floor((size * bytes) / total)]);
99
+ const lost = bytes - shares.reduce((sum, [, share]) => sum + share, 0);
100
+ const largest = shares.reduce((best, entry) => (entry[1] > best[1] ? entry : best), shares[0] ?? ['', 0]);
101
+ return Object.fromEntries(shares.map(([path, share]) => [path, { bytesInOutput: path === largest[0] ? share + lost : share }]));
102
+ };
103
+ const isLazy = (kind) => kind.startsWith('import()');
104
+ const isEntry = (kind) => kind.endsWith('entry');
105
+ /** A worker is a second program beside the page, not a part of it that arrives later. */
106
+ const isWorker = (kind) => kind.includes('Worker');
107
+ const importKind = (kind) => {
108
+ if (isLazy(kind)) {
109
+ return 'dynamic-import';
110
+ }
111
+ if (isWorker(kind) || kind.startsWith('new URL')) {
112
+ return 'url-token';
113
+ }
114
+ return /cjs|require/.test(kind) ? 'require-call' : 'import-statement';
115
+ };
116
+ /**
117
+ * A webpack `stats.json` as a metafile, or `null` when it has no chunk with a script in it — a
118
+ * stats file written with `chunks: false` has nothing to analyse.
119
+ */
120
+ const fromWebpackStats = (value) => {
121
+ const data = (0, json_utils_1.asRecord)(value);
122
+ const compilation = data ? compilationOf(data) : null;
123
+ if (!compilation) {
124
+ return null;
125
+ }
126
+ const chunks = chunksOf(compilation);
127
+ const byId = new Map(chunks.map(chunk => [chunk.id, chunk]));
128
+ const read = { rows: new Map(), concatenated: new Map() };
129
+ (0, webpack_modules_1.collect)({ children: compilation['modules'] }, [], read);
130
+ const rawChunks = (0, json_utils_1.asArray)(compilation['chunks']) ?? [];
131
+ for (const item of rawChunks) {
132
+ const chunk = (0, json_utils_1.asRecord)(item);
133
+ (0, webpack_modules_1.collect)({ children: chunk?.['modules'] }, chunk ? [String(chunk['id'])] : [], read);
134
+ }
135
+ const { rows } = read;
136
+ const sizes = assetSizes(compilation['assets']);
137
+ // --- inputs: every file, and who imports it -------------------------------------------------
138
+ const inputs = {};
139
+ for (const row of rows.values()) {
140
+ const input = (inputs[row.path] ??= { bytes: 0, imports: [] });
141
+ input.bytes += row.size;
142
+ if (row.cjs) {
143
+ input.format = 'cjs';
144
+ }
145
+ }
146
+ const seen = new Set();
147
+ for (const row of rows.values()) {
148
+ for (const reason of row.reasons) {
149
+ if (isEntry(reason.kind)) {
150
+ continue;
151
+ }
152
+ const kind = importKind(reason.kind);
153
+ for (const from of (0, webpack_modules_1.importersOf)(reason, row, read)) {
154
+ const key = `${from}>${row.path}>${kind}`;
155
+ if (from === row.path || seen.has(key)) {
156
+ continue;
157
+ }
158
+ seen.add(key);
159
+ inputs[from]?.imports?.push({ path: row.path, kind });
160
+ }
161
+ }
162
+ }
163
+ // --- outputs: one per file a chunk writes ---------------------------------------------------
164
+ const outputs = {};
165
+ const rowsIn = new Map();
166
+ for (const row of rows.values()) {
167
+ for (const chunk of row.chunks) {
168
+ rowsIn.set(chunk, [...(rowsIn.get(chunk) ?? []), row]);
169
+ }
170
+ }
171
+ const weights = (chunk, style) => {
172
+ const parts = new Map();
173
+ const inChunk = rowsIn.get(chunk) ?? [];
174
+ for (const row of inChunk) {
175
+ if (row.style === style) {
176
+ parts.set(row.path, (parts.get(row.path) ?? 0) + row.size);
177
+ }
178
+ }
179
+ return parts;
180
+ };
181
+ for (const chunk of chunks) {
182
+ const scripts = chunk.files.filter(file => isScript(file));
183
+ const styles = chunk.files.filter(file => isStyle(file));
184
+ for (const [index, file] of [...scripts, ...styles].entries()) {
185
+ const bytes = sizes.get(file) ?? 0;
186
+ const output = { bytes, imports: [] };
187
+ // One script per chunk is the rule; were there two, the modules would be counted twice.
188
+ if (index === 0 || isStyle(file)) {
189
+ output.inputs = shareOut(weights(chunk.id, isStyle(file)), bytes);
190
+ }
191
+ outputs[file] = output;
192
+ }
193
+ }
194
+ const scriptsOf = (chunk) => byId.get(chunk)?.files.filter(file => isScript(file)) ?? [];
195
+ const link = (from, to, kind) => {
196
+ const imports = outputs[from]?.imports;
197
+ if (from !== to && imports?.every(imp => !(imp.path === to && imp.kind === kind))) {
198
+ imports.push({ path: to, kind });
199
+ }
200
+ };
201
+ // --- where the application starts -----------------------------------------------------------
202
+ const entrypoints = Object.entries((0, json_utils_1.asRecord)(compilation['entrypoints']) ?? {});
203
+ for (const [name, raw] of entrypoints) {
204
+ const entry = (0, json_utils_1.asRecord)(raw);
205
+ const named = new Set(((0, json_utils_1.asArray)(entry?.['assets']) ?? []).map(asset => (0, json_utils_1.asText)(asset) ?? (0, json_utils_1.asText)((0, json_utils_1.asRecord)(asset)?.['name']) ?? ''));
206
+ const listed = (0, webpack_modules_1.idsOf)(entry?.['chunks']);
207
+ const ids = listed.length > 0
208
+ ? listed
209
+ : chunks.filter(chunk => chunk.files.some(file => named.has(file))).map(chunk => chunk.id);
210
+ // The chunk named after the entry holds its module; webpack lists it last, after the runtime
211
+ // and the vendors it needs.
212
+ const home = ids.find(id => byId.get(id)?.names.includes(name)) ?? ids.at(-1);
213
+ const [start] = home ? scriptsOf(home) : [];
214
+ const output = start ? outputs[start] : undefined;
215
+ if (!home || !start || !output) {
216
+ continue;
217
+ }
218
+ const module = (rowsIn.get(home) ?? []).find(row => row.reasons.some(reason => isEntry(reason.kind)));
219
+ output.entryPoint = module?.path ?? name;
220
+ for (const id of ids) {
221
+ for (const file of scriptsOf(id)) {
222
+ link(start, file, 'import-statement');
223
+ }
224
+ }
225
+ }
226
+ // --- what arrives later, and who asks for it --------------------------------------------------
227
+ // A lazy chunk group is every chunk sharing one origin: the `import()` at one place in one file.
228
+ // One of them holds the module asked for and is what gets imported; the others — the vendors
229
+ // `splitChunks` moved out, a chunk two routes share — travel with it.
230
+ const groups = new Map();
231
+ for (const chunk of chunks) {
232
+ if (chunk.initial) {
233
+ continue;
234
+ }
235
+ for (const origin of chunk.origins) {
236
+ const key = `${origin.from}|${origin.loc}`;
237
+ const group = groups.get(key) ?? { ...origin, members: [] };
238
+ group.members.push(chunk.id);
239
+ groups.set(key, group);
240
+ }
241
+ }
242
+ const groupsOf = (id) => [...groups.values()].filter(group => group.members.includes(id)).length;
243
+ for (const group of groups.values()) {
244
+ const from = (0, webpack_modules_1.modulePath)(group.from);
245
+ const here = (reason) => (0, webpack_modules_1.modulePath)(reason.from) === from && reason.loc === group.loc;
246
+ const target = group.members
247
+ .flatMap(id => (rowsIn.get(id) ?? [])
248
+ .filter(row => row.reasons.some(reason => here(reason)))
249
+ .map(row => ({ id, row })))
250
+ .at(0);
251
+ if (target?.row.reasons.some(reason => here(reason) && isWorker(reason.kind))) {
252
+ continue;
253
+ }
254
+ const primary = target?.id ??
255
+ group.members.toSorted((a, b) => groupsOf(a) - groupsOf(b) ||
256
+ (sizes.get(scriptsOf(b)[0] ?? '') ?? 0) - (sizes.get(scriptsOf(a)[0] ?? '') ?? 0))[0];
257
+ const [lazy] = primary ? scriptsOf(primary) : [];
258
+ const output = lazy ? outputs[lazy] : undefined;
259
+ if (!primary || !lazy || !output) {
260
+ continue;
261
+ }
262
+ output.entryPoint ??= target?.row.path ?? (from ? (0, webpack_modules_1.requested)(from, group.request) : lazy);
263
+ for (const id of group.members) {
264
+ for (const file of scriptsOf(id)) {
265
+ link(lazy, file, 'import-statement');
266
+ if (file !== lazy && !output.fetchedWith?.includes(file)) {
267
+ output.fetchedWith = [...(output.fetchedWith ?? []), file];
268
+ }
269
+ }
270
+ }
271
+ const holders = new Set([...rows.values()].filter(row => row.path === from).flatMap(row => [...row.chunks]));
272
+ const importers = holders.size > 0 ? holders : new Set(group.members.flatMap(id => byId.get(id)?.parents ?? []));
273
+ for (const id of importers) {
274
+ if (group.members.includes(id)) {
275
+ continue;
276
+ }
277
+ for (const file of scriptsOf(id)) {
278
+ link(file, lazy, 'dynamic-import');
279
+ }
280
+ }
281
+ }
282
+ return Object.keys(outputs).some(file => isScript(file))
283
+ ? { inputs, outputs, builtBy: { bundler: 'webpack' }, readFrom: 'webpack' }
284
+ : null;
285
+ };
286
+ exports.fromWebpackStats = fromWebpackStats;
287
+ /**
288
+ * What a parsed file is as a metafile: itself when it is one, translated when it is webpack's, and
289
+ * `null` otherwise. Every door a stats file comes in by goes through here, so the two formats are
290
+ * read the same way by the page, the command, a baseline and a comparison.
291
+ */
292
+ const metafileOf = (value) => {
293
+ if ((0, metafile_types_1.isMetafile)(value)) {
294
+ return value;
295
+ }
296
+ return (0, metafile_types_1.foreignFormat)(value) === 'webpack' ? (0, exports.fromWebpackStats)(value) : null;
297
+ };
298
+ exports.metafileOf = metafileOf;
@@ -181,8 +181,11 @@ const readPackageJson = (json) => {
181
181
  name: typeof pkg.name === 'string' && pkg.name.trim() ? pkg.name.trim() : null,
182
182
  scripts,
183
183
  // What the project asks for by name. It is what tells a dependency you chose from one that
184
- // came along with something else, which changes the fix and not the weight.
185
- dependencies: Object.keys({ ...pkg.dependencies }),
184
+ // came along with something else, which changes the fix and not the weight. Both lists:
185
+ // a bundled application keeps what it ships in `devDependencies` as often as not — Vite
186
+ // and Nuxt scaffold it that way — and reading `dependencies` alone called `nuxt` itself
187
+ // "a package you never asked for".
188
+ dependencies: Object.keys(deps),
186
189
  zoneDependency: 'zone.js' in deps,
187
190
  angularVersion: typeof angularVersion === 'string' ? angularVersion.replace(/^[\^~>=<\s]+/, '') : null,
188
191
  };
@@ -190,13 +193,15 @@ const readPackageJson = (json) => {
190
193
  exports.readPackageJson = readPackageJson;
191
194
  /**
192
195
  * Is the project zoneless? `angular.json` decides when it lists the polyfills; otherwise the
193
- * absence of `zone.js` in `package.json` does. `null` when neither file is loaded.
196
+ * absence of `zone.js` in `package.json` does — of an Angular project. `null` when neither file is
197
+ * loaded, and for a `package.json` with no `@angular/core`: a Svelte, React or Nuxt app has no
198
+ * zone.js either, and was told its change detection runs on signals.
194
199
  */
195
200
  const isZoneless = (context) => {
196
201
  if (context.angular?.zonePolyfill !== null && context.angular?.zonePolyfill !== undefined) {
197
202
  return !context.angular.zonePolyfill;
198
203
  }
199
- return context.pkg ? !context.pkg.zoneDependency : null;
204
+ return context.pkg?.angularVersion ? !context.pkg.zoneDependency : null;
200
205
  };
201
206
  exports.isZoneless = isZoneless;
202
207
  // --- Pipeline ---------------------------------------------------------------------------------
@@ -371,6 +376,12 @@ const jobOf = (lines, index) => {
371
376
  }
372
377
  return null;
373
378
  };
379
+ /**
380
+ * What an `echo` or a `printf` prints: text, never a command. This project's own pipeline tells
381
+ * whoever broke it to "Run `pnpm build`" from an `echo`, and that message was read as a step
382
+ * building the default configuration.
383
+ */
384
+ const PRINTED = /\b(?:echo|printf)\s+(?:"[^"]*"|'[^']*'|[^&|;]*)/g;
374
385
  /**
375
386
  * Every build command found in a pipeline file, with the configuration it resolves to.
376
387
  * Comments are dropped first: a commented-out `ng build` is not a build.
@@ -390,6 +401,7 @@ const readPipeline = (fileName, text, scripts = {}) => {
390
401
  const command = line
391
402
  .replace(/^\s*-\s*/, '')
392
403
  .replace(/^\s*(?:run|script|before_script|after_script|commands?|steps?|bash|pwsh):\s*/, '')
404
+ .replaceAll(PRINTED, '')
393
405
  .trim();
394
406
  if (!command || /^[\w-]+:$/.test(command)) {
395
407
  continue;
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ /**
3
+ * What the project being analysed is called, from whatever says it.
4
+ *
5
+ * A report has to name what it is about at a glance, and the name used to come only from a
6
+ * `package.json` or an `angular.json` loaded as context — which almost nobody loads — so almost
7
+ * every report was about nothing in particular. The build itself says it too: the page has a
8
+ * `<title>`, and the folder is usually named after the app.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.projectNameOf = void 0;
12
+ /** Folder names that are the build tool's, not the project's: `dist/browser` says nothing. */
13
+ const GENERIC_FOLDERS = new Set([
14
+ 'dist',
15
+ 'build',
16
+ 'browser',
17
+ 'public',
18
+ 'out',
19
+ 'output',
20
+ '.output',
21
+ 'www',
22
+ 'static',
23
+ 'assets',
24
+ 'client',
25
+ 'server',
26
+ ]);
27
+ /** A folder path's most specific segment that is not one of the build tool's own names. */
28
+ const folderName = (folder) => folder
29
+ .replaceAll('\\', '/')
30
+ .split('/')
31
+ .filter(part => part !== '' && part !== '.' && part !== '..')
32
+ .findLast(part => !GENERIC_FOLDERS.has(part.toLowerCase()) && !/\.json$/i.test(part)) ?? null;
33
+ const projectNameOf = (sources) => [sources.packageName, sources.angularProject, sources.pageTitle, sources.folder ? folderName(sources.folder) : null]
34
+ .map(name => name?.trim())
35
+ .find(name => !!name) ?? null;
36
+ exports.projectNameOf = projectNameOf;
@@ -10,8 +10,9 @@
10
10
  */
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.scanBuild = exports.exposureOf = void 0;
13
- const sourcemap_1 = require("../analysis/sourcemap");
13
+ const sourcemap_1 = require("../analysis/sourcemap/sourcemap");
14
14
  const format_utils_1 = require("../format/format.utils");
15
+ const ownership_1 = require("../format/ownership");
15
16
  const json_utils_1 = require("../json/json.utils");
16
17
  const catalog_1 = require("./catalog");
17
18
  const secrets_1 = require("./secrets");
@@ -175,7 +176,7 @@ const envOwners = (modules, readerFor) => {
175
176
  return (chunk, index, match) => {
176
177
  const source = readerFor(chunk)?.(index) ?? null;
177
178
  if (source !== null) {
178
- return source.includes('node_modules') ? (0, format_utils_1.packageOf)(source.replace(/^(?:\.\.\/)+/, '')) : null;
179
+ return (0, format_utils_1.packageOf)(source.replace(/^(?:\.\.\/)+/, ''));
179
180
  }
180
181
  const variable = match.replace(/^process\.env\./, '').toLowerCase();
181
182
  const candidates = new Set([variable, variable.replaceAll('_', '-')]);
@@ -183,6 +184,24 @@ const envOwners = (modules, readerFor) => {
183
184
  return [...inside].find(pkg => candidates.has(pkg.replace(/^@[^/]+\//, ''))) ?? null;
184
185
  };
185
186
  };
187
+ /** Average line length above which a chunk is minified: a minifier writes lines of thousands. */
188
+ const MINIFIED_LINE = 300;
189
+ /** Whether a chunk is minified, read from how long its lines are on average. */
190
+ const isMinified = (text) => text.length / (text.split('\n').length || 1) > MINIFIED_LINE;
191
+ /**
192
+ * Whether a match starts an indented line: in a minified chunk, that is text inside a string,
193
+ * because a minifier writes no line breaks and no indentation of its own. PocketBase ships its API
194
+ * documentation as template literals — `function (e) {↵ console.log(e.record);` — and those
195
+ * examples were 26 "development leftovers". Only asked of a minified chunk: in one that is not, an
196
+ * indented line is how real code looks.
197
+ */
198
+ const startsIndentedLine = (text, index) => {
199
+ let start = index;
200
+ while (start > 0 && index - start < 200 && (text[start - 1] === ' ' || text[start - 1] === '\t')) {
201
+ start--;
202
+ }
203
+ return start < index && text[start - 1] === '\n';
204
+ };
186
205
  const leftoversOf = (texts, modules, readerFor) => {
187
206
  const found = [];
188
207
  /**
@@ -190,7 +209,8 @@ const leftoversOf = (texts, modules, readerFor) => {
190
209
  * decided at all. Without a map the honest answer is "all of them, and I do not know whose".
191
210
  */
192
211
  const countIn = (chunk, text, pattern) => {
193
- const hits = [...text.matchAll(pattern)];
212
+ const minified = isMinified(text);
213
+ const hits = [...text.matchAll(pattern)].filter(hit => !minified || !startsIndentedLine(text, hit.index));
194
214
  if (hits.length === 0) {
195
215
  return { count: 0, attributed: true };
196
216
  }
@@ -200,7 +220,7 @@ const leftoversOf = (texts, modules, readerFor) => {
200
220
  }
201
221
  const mine = hits.filter(hit => {
202
222
  const source = reader(hit.index);
203
- return source !== null && !source.includes('node_modules');
223
+ return source !== null && (0, ownership_1.isOwnFile)(source.replace(/^(?:\.\.\/)+/, ''));
204
224
  });
205
225
  return { count: mine.length, attributed: true };
206
226
  };
@@ -266,6 +286,8 @@ const thirdPartyOf = (modules, boot) => {
266
286
  })
267
287
  .toSorted((a, b) => b.bootBytes - a.bootBytes || b.bytes - a.bytes);
268
288
  };
289
+ /** An environment variable read in source: Node's way, and Vite's. */
290
+ const ENV_REFERENCE = /\b(?:process\.env|import\.meta\.env)\.[A-Z][\dA-Z_]{2,}/g;
269
291
  /**
270
292
  * What a deployed source map actually gives away.
271
293
  *
@@ -277,29 +299,46 @@ const exposureOf = (maps) => {
277
299
  if (maps.length === 0) {
278
300
  return null;
279
301
  }
280
- const paths = new Set();
281
- let hasContent = false;
282
- let envReferences = 0;
283
- for (const map of maps) {
302
+ // Every map read first: where the project starts in their paths is decided across all of them
303
+ // (see `projectRootsOf`), or a build written outside the project listed `excalidraw/…` in front
304
+ // of every one of its 702 files.
305
+ const read = maps.map(map => {
284
306
  try {
285
307
  // Both fields are checked entry by entry rather than asserted whole: the assertion
286
308
  // made a map with one non-string in `sources` throw on the first `.includes`, and the
287
309
  // catch below then dropped everything that map knew instead of the one bad entry.
288
310
  const parsed = (0, json_utils_1.asRecord)(JSON.parse(map.text));
289
- const sources = ((0, json_utils_1.asArray)(parsed?.['sources']) ?? []).map(source => (0, json_utils_1.asText)(source));
290
- for (const source of sources) {
291
- if (source !== null && !source.includes('node_modules')) {
292
- paths.add(source.replace(/^(?:\.\.\/)+/, ''));
293
- }
294
- }
295
- const contents = (0, json_utils_1.asArray)(parsed?.['sourcesContent']) ?? [];
296
- hasContent ||= contents.some(content => typeof content === 'string' && content.length > 0);
297
- for (const content of contents) {
298
- envReferences += [...((0, json_utils_1.asText)(content) ?? '').matchAll(/\bprocess\.env\.[A-Z][\dA-Z_]{2,}/g)].length;
299
- }
311
+ return {
312
+ sources: ((0, json_utils_1.asArray)(parsed?.['sources']) ?? []).map(source => (0, json_utils_1.asText)(source)),
313
+ contents: (0, json_utils_1.asArray)(parsed?.['sourcesContent']) ?? [],
314
+ };
300
315
  }
301
316
  catch {
302
317
  // A map that will not parse says nothing about the build, only about the file.
318
+ return { sources: [], contents: [] };
319
+ }
320
+ });
321
+ const roots = (0, sourcemap_1.projectRootsOf)(read.map(map => map.sources.filter(source => source !== null)));
322
+ const paths = new Set();
323
+ let hasContent = false;
324
+ let envReferences = 0;
325
+ for (const [index, { sources, contents }] of read.entries()) {
326
+ const own = sources.map(source => source !== null && (0, ownership_1.isOwnFile)(source.replace(/^(?:\.\.\/)+/, '')));
327
+ for (const source of sources) {
328
+ if (source !== null && (0, ownership_1.isOwnFile)(source.replace(/^(?:\.\.\/)+/, ''))) {
329
+ // `App.vue?vue&type=script&setup=true&lang.ts` is `App.vue` again: the query is the
330
+ // compiler's, and counting it made one file of the project two.
331
+ paths.add((0, sourcemap_1.sourcePathOf)(source, roots[index] ?? '').replace(/\?.*$/, ''));
332
+ }
333
+ }
334
+ hasContent ||= contents.some(content => typeof content === 'string' && content.length > 0);
335
+ // In the project's own files only: every library checks `process.env.NODE_ENV`, and a Vue
336
+ // app read "394 references to environment variables" when its own code had none of those
337
+ // and one `import.meta.env.VITE_API_HOST`, which was not counted at all.
338
+ for (const [position, content] of contents.entries()) {
339
+ if (own[position]) {
340
+ envReferences += [...((0, json_utils_1.asText)(content) ?? '').matchAll(ENV_REFERENCE)].length;
341
+ }
303
342
  }
304
343
  }
305
344
  return { maps: maps.length, ownFiles: paths.size, hasContent, paths: [...paths], envReferences };
@@ -28,8 +28,16 @@ const URL_TAIL = String.raw `[^\s"'${'`'}]*`;
28
28
  const INTERNAL_HOST = String.raw `https?:\/\/(?:[\w-]+\.)*(?:local|internal|intranet|corp|lan|test)\b${URL_TAIL}`;
29
29
  const PRIVATE_IP = String.raw `https?:\/\/(?:10\.\d{1,3}|192\.168|172\.(?:1[6-9]|2\d|3[01]))\.[\d.]${URL_TAIL}`;
30
30
  const PATTERNS = [
31
- // A PEM block in a browser bundle is never right, whatever it turns out to be a key for.
32
- { kind: 'privateKey', pattern: /-----BEGIN (?:RSA |EC |OPENSSH |PGP )?PRIVATE KEY-----/g, keep: 40 },
31
+ // A PEM block in a browser bundle is never right, whatever it turns out to be a key for. The
32
+ // header with a body after it: the header alone is also what a form shows as the placeholder
33
+ // of a field to paste a key into — PocketBase's Apple sign-in settings do — and that was a
34
+ // `high` at the top of the report, an instruction to rotate a key, and every build failing
35
+ // `--fail-on high`. A body is base64 after a line break, written raw or as `\n` in a string.
36
+ {
37
+ kind: 'privateKey',
38
+ pattern: /-----BEGIN (?:RSA |EC |OPENSSH |PGP )?PRIVATE KEY-----(?:\\[nr]|\s)+[\d+/=A-Za-z]{64}/g,
39
+ keep: 40,
40
+ },
33
41
  { kind: 'awsKey', pattern: /\b(?:AKIA|ASIA)[\dA-Z]{16}\b/g, keep: 4 },
34
42
  { kind: 'googleKey', pattern: /\bAIza[\w-]{35}\b/g, keep: 6 },
35
43
  { kind: 'githubToken', pattern: /\bgh[pousr]_[\dA-Za-z]{36,}\b/g, keep: 5 },
@@ -52,6 +60,12 @@ const PATTERNS = [
52
60
  * off, so it is recognised by its neighbours rather than by a list of known keys.
53
61
  */
54
62
  const FIREBASE_NEIGHBOURS = /\b(?:authDomain|projectId|messagingSenderId|storageBucket|measurementId)\b/;
63
+ /**
64
+ * A build that defines `process.env` itself — `window.process = { env: { NODE_ENV: 'production' } }`
65
+ * in its page, as Polymer's starter kit does on purpose — has left no substitution undone: its
66
+ * `process.env.NODE_ENV` reads a value that is there. It was reported as a secret of medium severity.
67
+ */
68
+ const DEFINES_ENV = /\bprocess\s*=\s*\{\s*env\s*:|\bprocess\.env\s*=[^=]/;
55
69
  /** How far either side of a match its neighbours are looked for: one minified object literal. */
56
70
  const NEIGHBOURHOOD = 400;
57
71
  /** A match with its middle taken out: enough to find it in the file, never enough to use it. */
@@ -63,6 +77,11 @@ const redact = (value, keep) => value.length <= keep * 2 ? value : `${value.slic
63
77
  */
64
78
  const findSecrets = (texts, ownerOf = null) => {
65
79
  const found = new Map();
80
+ // A loop, not `Iterator#some`: this runs on Node 20, which has no iterator helpers.
81
+ let envDefined = false;
82
+ for (const text of texts.values()) {
83
+ envDefined ||= DEFINES_ENV.test(text);
84
+ }
66
85
  /** One match: counted when it was seen before, written down with what explains it when not. */
67
86
  const record = (chunk, text, kind, keep, hit) => {
68
87
  const [match] = hit;
@@ -75,7 +94,8 @@ const findSecrets = (texts, ownerOf = null) => {
75
94
  return;
76
95
  }
77
96
  const around = text.slice(Math.max(0, hit.index - NEIGHBOURHOOD), hit.index + NEIGHBOURHOOD);
78
- const benign = kind === 'googleKey' && FIREBASE_NEIGHBOURS.test(around) ? 'firebaseConfig' : null;
97
+ const firebase = kind === 'googleKey' && FIREBASE_NEIGHBOURS.test(around);
98
+ const benign = firebase ? 'firebaseConfig' : kind === 'envLeftover' && envDefined ? 'envDefined' : null;
79
99
  const owner = kind === 'envLeftover' && ownerOf ? ownerOf(chunk, hit.index, match) : null;
80
100
  found.set(key, { kind, chunk, redacted: redact(match, keep), count: 1, benign, owner });
81
101
  };
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ /**
3
+ * What is said about a `situation` block that got something wrong, in both languages of the report.
4
+ *
5
+ * Here and not in `config/config-text.ts` with the rest of the file's problems, although they are
6
+ * printed alongside them: the reader of the answers lives in this folder, and borrowing its words
7
+ * from `config` closed a loop — `config` reads the answers through this folder, the signals read
8
+ * them too, and `config` names the signals. Its own words are the only thing it needed from there.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.SITUATION_TEXT = void 0;
12
+ exports.SITUATION_TEXT = {
13
+ en: {
14
+ unknownAnswer: (key, given) => `Unknown answer in "situation.${key}": ${given}. It counts as unanswered.`,
15
+ badSituationNumber: (key, limit) => `"situation.${key}" is not a number between 0 and ${limit}. It is ignored.`,
16
+ badAnsweredAt: given => `"situation.answeredAt" is not a YYYY-MM-DD date: ${given}. It is ignored.`,
17
+ },
18
+ es: {
19
+ unknownAnswer: (key, given) => `Respuesta desconocida en "situation.${key}": ${given}. Cuenta como sin responder.`,
20
+ badSituationNumber: (key, limit) => `"situation.${key}" no es un número entre 0 y ${limit}. Se ignora.`,
21
+ badAnsweredAt: given => `"situation.answeredAt" no es una fecha AAAA-MM-DD: ${given}. Se ignora.`,
22
+ },
23
+ };
@@ -15,6 +15,7 @@
15
15
  */
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.hasSituation = exports.isStaleSituation = exports.SITUATION_FRESH_DAYS = exports.readSituation = exports.importsChannel = exports.sessionBreadth = exports.WIDE_SESSION_SCREENS = exports.cascadeExposure = exports.LOW_EXPOSURE = exports.HIGH_EXPOSURE = exports.invalidationsPerWeek = exports.returningShare = exports.deploysPerWeek = exports.unanswered = exports.answeredCount = exports.QUESTIONS = exports.EMPTY_SITUATION = void 0;
18
+ const situation_text_1 = require("./situation-text");
18
19
  /** Nobody has answered anything. It is also what a report with no `loadline.json` runs on. */
19
20
  exports.EMPTY_SITUATION = {
20
21
  navigation: 'unknown',
@@ -187,10 +188,11 @@ const DATE = /^\d{4}-\d{2}-\d{2}$/;
187
188
  * acceptances make and for the same reason: the failure to avoid is a typo silently reading as an
188
189
  * answer, because an answer is the only thing here that can move a colour.
189
190
  */
190
- const readSituation = (value) => {
191
+ const readSituation = (value, lang = 'en') => {
191
192
  if (!value || typeof value !== 'object') {
192
193
  return { situation: exports.EMPTY_SITUATION, problems: [] };
193
194
  }
195
+ const t = situation_text_1.SITUATION_TEXT[lang];
194
196
  const raw = value;
195
197
  const problems = [];
196
198
  const situation = { ...exports.EMPTY_SITUATION };
@@ -200,7 +202,7 @@ const readSituation = (value) => {
200
202
  continue;
201
203
  }
202
204
  if (typeof answer !== 'string' || !OPTIONS.get(question.key)?.has(answer)) {
203
- problems.push(`Unknown answer in "situation.${question.key}": ${JSON.stringify(answer)}. It counts as unanswered.`);
205
+ problems.push(t.unknownAnswer(question.key, JSON.stringify(answer)));
204
206
  continue;
205
207
  }
206
208
  // The five fields are five different string unions and the loop knows the key only as one
@@ -215,7 +217,7 @@ const readSituation = (value) => {
215
217
  }
216
218
  const number = readNumber(given, key);
217
219
  if (number === null) {
218
- problems.push(`"situation.${key}" is not a number between 0 and ${RAW_LIMITS[key]}. It is ignored.`);
220
+ problems.push(t.badSituationNumber(key, RAW_LIMITS[key] ?? 0));
219
221
  continue;
220
222
  }
221
223
  situation[key] = number;
@@ -224,7 +226,7 @@ const readSituation = (value) => {
224
226
  situation.answeredBy = readText(raw['answeredBy']);
225
227
  const answeredAt = readText(raw['answeredAt']);
226
228
  if (answeredAt !== null && !DATE.test(answeredAt)) {
227
- problems.push(`"situation.answeredAt" is not a YYYY-MM-DD date: ${answeredAt}. It is ignored.`);
229
+ problems.push(t.badAnsweredAt(answeredAt));
228
230
  }
229
231
  else {
230
232
  situation.answeredAt = answeredAt;