@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,280 @@
1
+ "use strict";
2
+ /**
3
+ * The rest of what reading the build says: development leftovers, licences, third-party services,
4
+ * and what a deployed source map gives away.
5
+ *
6
+ * The three of them share one property worth stating: they are all **free**. The chunk text is
7
+ * already in memory for the compressed sizes, the metafile already names every input, and the maps
8
+ * were already parsed for the per-file weights. None of this costs a request, a registry lookup or
9
+ * a byte leaving the machine.
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.scanBuild = exports.exposureOf = void 0;
13
+ const sourcemap_1 = require("../analysis/sourcemap");
14
+ const format_utils_1 = require("../format/format.utils");
15
+ const json_utils_1 = require("../json/json.utils");
16
+ const catalog_1 = require("./catalog");
17
+ const secrets_1 = require("./secrets");
18
+ /** The legal comments a minifier keeps on purpose: `/*!` and anything with `@license`. */
19
+ const LEGAL_COMMENT = /\/\*[!*][\S\s]*?\*\//g;
20
+ /**
21
+ * Licence identifiers, and how each one has to be treated.
22
+ *
23
+ * The classification is the point, not the name: "you ship GPL code" is only useful next to "and
24
+ * that is the kind that has conditions". Ordered longest-first so `AGPL-3.0` is not read as `GPL`.
25
+ */
26
+ const LICENCES = [
27
+ { id: 'AGPL', pattern: /\bAGPL(?:-\d(?:\.\d)?)?\b/i, class: 'strongCopyleft' },
28
+ { id: 'LGPL', pattern: /\bLGPL(?:-\d(?:\.\d)?)?\b/i, class: 'weakCopyleft' },
29
+ { id: 'GPL', pattern: /\bGPL(?:-\d(?:\.\d)?)?\b/i, class: 'strongCopyleft' },
30
+ { id: 'SSPL', pattern: /\bSSPL\b/i, class: 'strongCopyleft' },
31
+ { id: 'MPL', pattern: /\bMPL(?:-\d(?:\.\d)?)?\b/i, class: 'weakCopyleft' },
32
+ { id: 'EPL', pattern: /\bEPL(?:-\d(?:\.\d)?)?\b/i, class: 'weakCopyleft' },
33
+ { id: 'CC-BY-NC', pattern: /\bCC[ -]BY[ -]NC\b/i, class: 'nonCommercial' },
34
+ { id: 'MIT', pattern: /\bMIT\b/, class: 'permissive' },
35
+ { id: 'Apache-2.0', pattern: /\bApache(?:[ -]License)?[ -]?2\.0\b/i, class: 'permissive' },
36
+ { id: 'BSD', pattern: /\bBSD(?:-\d-Clause)?\b/i, class: 'permissive' },
37
+ { id: 'ISC', pattern: /\bISC\b/, class: 'permissive' },
38
+ ];
39
+ /**
40
+ * Leftovers read from the **text** of the build.
41
+ *
42
+ * Only these two, and that is a correction rather than a limitation. A development build used to be
43
+ * detected by searching the chunks for `react-dom.development` and `__vite_ping` — and the first
44
+ * thing that found was Loadline's own bundle, which carries those strings precisely because it is
45
+ * the tool that looks for them. Any project holding a linter rule, a piece of documentation or
46
+ * another scanner would have got the same wrong answer, stated with the same confidence.
47
+ *
48
+ * `console.log` and `debugger` stay here, but no longer on the strength of the substring alone.
49
+ * "A false one costs nothing" turned out to be wrong in the one place it mattered: `@angular/core`
50
+ * ships a console service whose body is literally `log(n){console.log(n)}`, so every Angular
51
+ * application ever read — five out of five, probes and real projects — was told it had a
52
+ * development leftover in it, pointing at framework code nobody can remove. When there is a source
53
+ * map, the position of each match is resolved to the file it came from and only the project's own
54
+ * ones are counted. When there is not, the count is kept and marked unattributed, and the report
55
+ * says so rather than claiming an author it cannot know.
56
+ */
57
+ const DEV_MARKERS = [
58
+ { kind: 'consoleLogs', pattern: /\bconsole\.log\(/g },
59
+ { kind: 'debugger', pattern: /\bdebugger\b\s*[;}]/g },
60
+ ];
61
+ /**
62
+ * Leftovers read from the **inputs** the metafile names: a fact about what was compiled rather than
63
+ * a guess about what the output says.
64
+ *
65
+ * A file called `react-dom.development.js` is in the bundle or it is not. The string
66
+ * `react-dom.development` appearing somewhere inside a chunk means nothing at all.
67
+ */
68
+ const DEV_INPUTS = [
69
+ { kind: 'reactDev', pattern: /\/(?:react-dom|react|scheduler)[^/]*\/.*\.development\.js$/i },
70
+ { kind: 'devServer', pattern: /node_modules\/(?:webpack-dev-server|sockjs-client|vite\/dist\/client)\//i },
71
+ { kind: 'testFiles', pattern: /\.(?:spec|test|stories|story|cy|e2e)\.[jt]sx?$/i },
72
+ ];
73
+ const licencesOf = (texts) => {
74
+ const found = new Map();
75
+ // Only the first identifier of each comment: a licence header that mentions MIT while granting
76
+ // Apache would otherwise be counted as both.
77
+ const record = (chunk, comment) => {
78
+ const licence = LICENCES.find(entry => entry.pattern.test(comment));
79
+ if (!licence) {
80
+ return;
81
+ }
82
+ const entry = found.get(licence.id) ?? { id: licence.id, class: licence.class, chunks: [], packages: [] };
83
+ if (!entry.chunks.includes(chunk)) {
84
+ entry.chunks.push(chunk);
85
+ }
86
+ // The package name, when the comment carries one. Most do: a bundler copies the header of
87
+ // the file it came from, and those usually start with the library's own name.
88
+ const named = /(?:^|\s)((?:@[\w.-]+\/)?[a-z][\w.-]{2,})(?:\s+v?\d|\.js|\s+\|)/i.exec(comment)?.[1];
89
+ if (named && !entry.packages.includes(named)) {
90
+ entry.packages.push(named);
91
+ }
92
+ found.set(licence.id, entry);
93
+ };
94
+ for (const [chunk, text] of texts) {
95
+ for (const [comment] of text.matchAll(LEGAL_COMMENT)) {
96
+ record(chunk, comment);
97
+ }
98
+ }
99
+ const rank = {
100
+ strongCopyleft: 0,
101
+ nonCommercial: 1,
102
+ weakCopyleft: 2,
103
+ unknown: 3,
104
+ permissive: 4,
105
+ };
106
+ return [...found.values()].toSorted((a, b) => rank[a.class] - rank[b.class]);
107
+ };
108
+ const leftoversOf = (texts, modules, maps) => {
109
+ const found = [];
110
+ const readers = new Map();
111
+ /**
112
+ * Where a position of a chunk came from, when the chunk has a map next to it. Built once per
113
+ * chunk and only for a chunk something matched in, so a build nobody has a leftover in pays
114
+ * nothing for this.
115
+ */
116
+ const readerFor = (chunk, text) => {
117
+ if (readers.has(chunk)) {
118
+ return readers.get(chunk) ?? null;
119
+ }
120
+ const map = maps.find(entry => entry.name === `${chunk}.map`);
121
+ let reader = null;
122
+ try {
123
+ const parsed = map ? JSON.parse(map.text) : null;
124
+ if ((0, sourcemap_1.isSourceMap)(parsed)) {
125
+ const segments = (0, sourcemap_1.segmentsOf)(parsed);
126
+ // Line starts once, so resolving a position is a binary search rather than a
127
+ // count of newlines from the top of a minified megabyte.
128
+ const starts = [0];
129
+ for (let i = text.indexOf('\n'); i !== -1; i = text.indexOf('\n', i + 1)) {
130
+ starts.push(i + 1);
131
+ }
132
+ reader = (index) => {
133
+ let low = 0;
134
+ let high = starts.length - 1;
135
+ while (low < high) {
136
+ const middle = Math.ceil((low + high) / 2);
137
+ if ((starts[middle] ?? 0) <= index) {
138
+ low = middle;
139
+ }
140
+ else {
141
+ high = middle - 1;
142
+ }
143
+ }
144
+ return (0, sourcemap_1.sourceAt)(segments, low, index - (starts[low] ?? 0));
145
+ };
146
+ }
147
+ }
148
+ catch {
149
+ // A map that will not parse says nothing about the build, only about the file.
150
+ }
151
+ readers.set(chunk, reader);
152
+ return reader;
153
+ };
154
+ /**
155
+ * How many of a marker's matches in one chunk are the project's own, and whether that could be
156
+ * decided at all. Without a map the honest answer is "all of them, and I do not know whose".
157
+ */
158
+ const countIn = (chunk, text, pattern) => {
159
+ const hits = [...text.matchAll(pattern)];
160
+ if (hits.length === 0) {
161
+ return { count: 0, attributed: true };
162
+ }
163
+ const reader = readerFor(chunk, text);
164
+ if (!reader) {
165
+ return { count: hits.length, attributed: false };
166
+ }
167
+ const mine = hits.filter(hit => {
168
+ const source = reader(hit.index);
169
+ return source !== null && !source.includes('node_modules');
170
+ });
171
+ return { count: mine.length, attributed: true };
172
+ };
173
+ for (const { kind, pattern } of DEV_MARKERS) {
174
+ let count = 0;
175
+ let attributed = true;
176
+ const where = [];
177
+ for (const [chunk, text] of texts) {
178
+ const hits = countIn(chunk, text, pattern);
179
+ attributed &&= hits.attributed;
180
+ if (hits.count > 0) {
181
+ count += hits.count;
182
+ where.push(chunk);
183
+ }
184
+ }
185
+ if (count > 0) {
186
+ found.push({ kind, count, where, attributed });
187
+ }
188
+ }
189
+ // These are read from the inputs the metafile names rather than from the text of a chunk, so
190
+ // there is nothing to attribute: the file is in the build or it is not.
191
+ for (const { kind, pattern } of DEV_INPUTS) {
192
+ const hit = modules.filter(module => pattern.test(module.path));
193
+ if (hit.length > 0) {
194
+ found.push({ kind, count: hit.length, where: hit.map(module => module.label), attributed: true });
195
+ }
196
+ }
197
+ return found;
198
+ };
199
+ /**
200
+ * How much of the first load is a service rather than the application.
201
+ *
202
+ * The list this reads is in `catalog.ts`, with the argument for why a list is the right tool for
203
+ * this one question and the wrong one everywhere else in this project.
204
+ */
205
+ const thirdPartyOf = (modules, boot) => {
206
+ const byCategory = new Map();
207
+ for (const module of modules) {
208
+ const pkg = module.pkg ?? (0, format_utils_1.packageOf)(module.path);
209
+ const category = pkg ? (0, catalog_1.categoryOf)(pkg) : null;
210
+ if (!pkg || !category) {
211
+ continue;
212
+ }
213
+ const packages = byCategory.get(category) ?? new Map();
214
+ const entry = packages.get(pkg) ?? { bytes: 0, inBoot: false };
215
+ entry.bytes += module.bytes;
216
+ entry.inBoot ||= module.places.some(place => boot.has(place.chunk));
217
+ packages.set(pkg, entry);
218
+ byCategory.set(category, packages);
219
+ }
220
+ return [...byCategory]
221
+ .map(([category, packages]) => {
222
+ const list = [...packages]
223
+ .map(([name, entry]) => ({ name, bytes: entry.bytes, inBoot: entry.inBoot }))
224
+ .toSorted((a, b) => b.bytes - a.bytes);
225
+ return {
226
+ category,
227
+ packages: list,
228
+ bytes: list.reduce((sum, pkg) => sum + pkg.bytes, 0),
229
+ bootBytes: list.filter(pkg => pkg.inBoot).reduce((sum, pkg) => sum + pkg.bytes, 0),
230
+ };
231
+ })
232
+ .toSorted((a, b) => b.bootBytes - a.bootBytes || b.bytes - a.bytes);
233
+ };
234
+ /**
235
+ * What a deployed source map actually gives away.
236
+ *
237
+ * The report has warned that maps are in the folder for a while, and that sentence gets ignored,
238
+ * because "you have source maps published" sounds like a configuration nicety. "You have 1.400
239
+ * files of your source published, here are the paths" does not, and it is the same fact.
240
+ */
241
+ const exposureOf = (maps) => {
242
+ if (maps.length === 0) {
243
+ return null;
244
+ }
245
+ const paths = new Set();
246
+ let hasContent = false;
247
+ let envReferences = 0;
248
+ for (const map of maps) {
249
+ try {
250
+ // Both fields are checked entry by entry rather than asserted whole: the assertion
251
+ // made a map with one non-string in `sources` throw on the first `.includes`, and the
252
+ // catch below then dropped everything that map knew instead of the one bad entry.
253
+ const parsed = (0, json_utils_1.asRecord)(JSON.parse(map.text));
254
+ const sources = ((0, json_utils_1.asArray)(parsed?.['sources']) ?? []).map(source => (0, json_utils_1.asText)(source));
255
+ for (const source of sources) {
256
+ if (source !== null && !source.includes('node_modules')) {
257
+ paths.add(source.replace(/^(?:\.\.\/)+/, ''));
258
+ }
259
+ }
260
+ const contents = (0, json_utils_1.asArray)(parsed?.['sourcesContent']) ?? [];
261
+ hasContent ||= contents.some(content => typeof content === 'string' && content.length > 0);
262
+ for (const content of contents) {
263
+ envReferences += [...((0, json_utils_1.asText)(content) ?? '').matchAll(/\bprocess\.env\.[A-Z][\dA-Z_]{2,}/g)].length;
264
+ }
265
+ }
266
+ catch {
267
+ // A map that will not parse says nothing about the build, only about the file.
268
+ }
269
+ }
270
+ return { maps: maps.length, ownFiles: paths.size, hasContent, paths: [...paths], envReferences };
271
+ };
272
+ exports.exposureOf = exposureOf;
273
+ const scanBuild = (input) => ({
274
+ secrets: (0, secrets_1.findSecrets)(input.texts),
275
+ leftovers: leftoversOf(input.texts, input.modules, input.maps),
276
+ licences: licencesOf(input.texts),
277
+ thirdParty: thirdPartyOf(input.modules, input.boot),
278
+ exposure: (0, exports.exposureOf)(input.maps),
279
+ });
280
+ exports.scanBuild = scanBuild;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ /**
3
+ * What reading the text of the chunks says, beyond how much it weighs.
4
+ *
5
+ * Every one of these comes from files the tool already has open. Nothing is fetched, no registry is
6
+ * consulted, and nothing leaves the machine — the same rule the rest of the tool holds to, and the
7
+ * reason a whole area normally sold as "DevSecOps" fits inside a page that runs from a `file://`
8
+ * URL.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,261 @@
1
+ "use strict";
2
+ /**
3
+ * What the five answers mean, once somebody has given them.
4
+ *
5
+ * The questions are asked in words because that is how people know the answer — "we ship most
6
+ * days", "almost everybody is back on Monday" — and they are used as arithmetic, because the
7
+ * thing they decide is arithmetic. The bridge between the two is this file, and it is deliberately
8
+ * small and readable: a band becomes the middle of its range, the two numbers multiply, and the
9
+ * product is a figure with a unit somebody can argue with.
10
+ *
11
+ * **The one rule everything here obeys**: `unknown` produces `unknown`. Not a default, not the
12
+ * median of the other answers, not "assume the common case". Every function below returns its own
13
+ * `unknown` the moment an input it needs is missing, and the callers are written so that `unknown`
14
+ * leaves the report exactly where it was rather than softening it.
15
+ */
16
+ Object.defineProperty(exports, "__esModule", { value: true });
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
+ /** Nobody has answered anything. It is also what a report with no `loadline.json` runs on. */
19
+ exports.EMPTY_SITUATION = {
20
+ navigation: 'unknown',
21
+ deploys: 'unknown',
22
+ returning: 'unknown',
23
+ connection: 'unknown',
24
+ priority: 'unknown',
25
+ screensPerSession: null,
26
+ deploysPerWeek: null,
27
+ returningPct: null,
28
+ rum: false,
29
+ answeredBy: null,
30
+ answeredAt: null,
31
+ };
32
+ /**
33
+ * The form, in the order it is drawn.
34
+ *
35
+ * One list: the page renders it, the config reader validates against it, and the guard that says
36
+ * every option has copy in both languages walks it. Three copies of this order would be three
37
+ * chances for a question to exist in one of the three places only.
38
+ */
39
+ exports.QUESTIONS = [
40
+ { key: 'navigation', options: ['inAndOut', 'allDay', 'profiles', 'unknown'], raw: 'screensPerSession' },
41
+ { key: 'deploys', options: ['daily', 'weekly', 'monthly', 'unknown'], raw: 'deploysPerWeek' },
42
+ { key: 'returning', options: ['most', 'half', 'few', 'unknown'], raw: 'returningPct' },
43
+ { key: 'connection', options: ['office', 'mobile', 'worldwide', 'unknown'], raw: undefined },
44
+ // The fifth offers no "I don't know" on purpose. It is not a fact to look up: it is which of
45
+ // two waits the team would rather pay, and nobody else can hold that opinion for them. Until
46
+ // it is picked the field is `unknown`, which is a different thing from an answer of "I don't
47
+ // know" and reads on the page as a question nobody has been through yet.
48
+ { key: 'priority', options: ['firstScreen', 'navigation', 'both'], raw: undefined },
49
+ ];
50
+ /** How many of the five have a real answer. `unknown` does not count, which is the whole point. */
51
+ const answeredCount = (situation) => exports.QUESTIONS.filter(question => situation[question.key] !== 'unknown').length;
52
+ exports.answeredCount = answeredCount;
53
+ /** Which of the five are still open, in the order they are asked. */
54
+ const unanswered = (situation) => exports.QUESTIONS.filter(question => situation[question.key] === 'unknown').map(question => question.key);
55
+ exports.unanswered = unanswered;
56
+ // --- from a band to a number ---------------------------------------------------------------------
57
+ /**
58
+ * Releases per week, as each band is worth.
59
+ *
60
+ * The middle of the range somebody picking that band means, not the best case of it. "Several
61
+ * times a day" is a team deploying on merge, which is five working days of it and not thirty-five
62
+ * releases; "every few weeks" is treated as monthly.
63
+ */
64
+ const DEPLOY_RATE = {
65
+ daily: 5,
66
+ weekly: 1,
67
+ monthly: 0.25,
68
+ unknown: null,
69
+ };
70
+ /** The share arriving with a warm cache, as each band is worth. */
71
+ const RETURNING_SHARE = {
72
+ most: 0.8,
73
+ half: 0.5,
74
+ few: 0.15,
75
+ unknown: null,
76
+ };
77
+ /** Distinct screens a session touches, as each band is worth. */
78
+ const SCREENS_PER_SESSION = {
79
+ inAndOut: 1.5,
80
+ allDay: 6,
81
+ profiles: null,
82
+ unknown: null,
83
+ };
84
+ /**
85
+ * A raw figure if there is one, the band's value otherwise.
86
+ *
87
+ * The raw one wins because it is the same answer with less rounding, and because typing 4.5 into
88
+ * a box is something only somebody who looked it up does.
89
+ */
90
+ const resolve = (raw, band) => raw !== null && Number.isFinite(raw) && raw >= 0 ? raw : band;
91
+ /** Releases per week, from whichever of the two the team gave. */
92
+ const deploysPerWeek = (situation) => resolve(situation.deploysPerWeek, DEPLOY_RATE[situation.deploys]);
93
+ exports.deploysPerWeek = deploysPerWeek;
94
+ /** The warm-cache share as a fraction, from whichever of the two the team gave. */
95
+ const returningShare = (situation) => {
96
+ const pct = situation.returningPct;
97
+ const raw = pct !== null && Number.isFinite(pct) && pct >= 0 && pct <= 100 ? pct / 100 : null;
98
+ return resolve(raw, RETURNING_SHARE[situation.returning]);
99
+ };
100
+ exports.returningShare = returningShare;
101
+ // --- what the answers decide -----------------------------------------------------------------
102
+ /**
103
+ * **The figure the whole middle of the questionnaire exists to produce**: how many times a week
104
+ * one person pays the invalidation.
105
+ *
106
+ * `deploys per week × share arriving with a warm cache`. That is the entire model, and it is
107
+ * written in one line on purpose — the report shows the multiplication, not the result, so that
108
+ * anybody who disagrees can see which of the two numbers they disagree with.
109
+ *
110
+ * It is what turns "87 % of the build is re-downloaded" from a number to be alarmed by into a
111
+ * cost: 87 % four times a week is the most expensive line of the report, and 87 % once a quarter
112
+ * to an audience of first-time visitors is nothing at all. Same build, same percentage.
113
+ *
114
+ * `null` when either half is missing, which is most of the time and is not a failure.
115
+ */
116
+ const invalidationsPerWeek = (situation) => {
117
+ const rate = (0, exports.deploysPerWeek)(situation);
118
+ const share = (0, exports.returningShare)(situation);
119
+ return rate === null || share === null ? null : rate * share;
120
+ };
121
+ exports.invalidationsPerWeek = invalidationsPerWeek;
122
+ /**
123
+ * Where those invalidations sit.
124
+ *
125
+ * The two boundaries are conventions and are labelled as such wherever they surface: **two a week**
126
+ * is where a returning visitor notices the download as a habit rather than an event, and below
127
+ * **0.4** — one every couple of weeks or rarer — it is not part of anybody's experience of the
128
+ * application.
129
+ *
130
+ * Only `high` is allowed to raise a severity. `moderate` and `low` change what is said and leave
131
+ * the colour where it was, because a declared answer is not a measurement and the asymmetry rule
132
+ * says evidence this soft may widen what the report claims, never quiet it.
133
+ */
134
+ exports.HIGH_EXPOSURE = 2;
135
+ exports.LOW_EXPOSURE = 0.4;
136
+ const cascadeExposure = (situation) => {
137
+ const perWeek = (0, exports.invalidationsPerWeek)(situation);
138
+ if (perWeek === null) {
139
+ return 'unknown';
140
+ }
141
+ return perWeek >= exports.HIGH_EXPOSURE ? 'high' : perWeek >= exports.LOW_EXPOSURE ? 'moderate' : 'low';
142
+ };
143
+ exports.cascadeExposure = cascadeExposure;
144
+ /**
145
+ * How wide a session is, which is what makes a deferred chunk's coverage mean anything.
146
+ *
147
+ * The band is only overridden by the raw figure when the raw figure is there; two distinct screens
148
+ * a session is the line, and it is a convention like the two above. "There are two or three
149
+ * profiles" stays `mixed` however many screens the median says: a median over two populations is
150
+ * a number about neither of them.
151
+ */
152
+ exports.WIDE_SESSION_SCREENS = 2;
153
+ const sessionBreadth = (situation) => {
154
+ if (situation.navigation === 'profiles') {
155
+ return 'mixed';
156
+ }
157
+ const screens = resolve(situation.screensPerSession, SCREENS_PER_SESSION[situation.navigation]);
158
+ if (screens === null) {
159
+ return 'unknown';
160
+ }
161
+ return screens >= exports.WIDE_SESSION_SCREENS ? 'wide' : 'narrow';
162
+ };
163
+ exports.sessionBreadth = sessionBreadth;
164
+ /**
165
+ * Whether the fourth question should be asked at all.
166
+ *
167
+ * With RUM it should not: the p75 of protocol and round trip is already being collected from real
168
+ * sessions, and a band picked from memory is strictly worse than a figure they have. The page says
169
+ * so instead of drawing the options, and the number goes into `latencyMs`.
170
+ */
171
+ const importsChannel = (situation) => situation.rum;
172
+ exports.importsChannel = importsChannel;
173
+ // --- reading one out of a file ------------------------------------------------------------------
174
+ const OPTIONS = new Map(exports.QUESTIONS.map(question => [question.key, new Set([...question.options, 'unknown'])]));
175
+ const RAW_LIMITS = { screensPerSession: 1000, deploysPerWeek: 1000, returningPct: 100 };
176
+ const readNumber = (value, key) => {
177
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > (RAW_LIMITS[key] ?? 0)) {
178
+ return null;
179
+ }
180
+ return value;
181
+ };
182
+ const readText = (value) => typeof value === 'string' && value.trim().length > 0 ? value.trim() : null;
183
+ const DATE = /^\d{4}-\d{2}-\d{2}$/;
184
+ /**
185
+ * What a `loadline.json` said, with everything it got wrong named rather than thrown.
186
+ *
187
+ * An answer nobody recognises becomes `unknown` and a line to print. It is the same choice the
188
+ * acceptances make and for the same reason: the failure to avoid is a typo silently reading as an
189
+ * answer, because an answer is the only thing here that can move a colour.
190
+ */
191
+ const readSituation = (value) => {
192
+ if (!value || typeof value !== 'object') {
193
+ return { situation: exports.EMPTY_SITUATION, problems: [] };
194
+ }
195
+ const raw = value;
196
+ const problems = [];
197
+ const situation = { ...exports.EMPTY_SITUATION };
198
+ for (const question of exports.QUESTIONS) {
199
+ const answer = raw[question.key];
200
+ if (answer === undefined || answer === null) {
201
+ continue;
202
+ }
203
+ if (typeof answer !== 'string' || !OPTIONS.get(question.key)?.has(answer)) {
204
+ problems.push(`Unknown answer in "situation.${question.key}": ${JSON.stringify(answer)}. It counts as unanswered.`);
205
+ continue;
206
+ }
207
+ // The five fields are five different string unions and the loop knows the key only as one
208
+ // of them, which no narrowing can express. The value was just checked against that very
209
+ // question's own option list, so the assignment is sound and the cast says only that.
210
+ situation[question.key] = answer;
211
+ }
212
+ for (const key of ['screensPerSession', 'deploysPerWeek', 'returningPct']) {
213
+ const given = raw[key];
214
+ if (given === undefined || given === null) {
215
+ continue;
216
+ }
217
+ const number = readNumber(given, key);
218
+ if (number === null) {
219
+ problems.push(`"situation.${key}" is not a number between 0 and ${RAW_LIMITS[key]}. It is ignored.`);
220
+ continue;
221
+ }
222
+ situation[key] = number;
223
+ }
224
+ situation.rum = raw['rum'] === true;
225
+ situation.answeredBy = readText(raw['answeredBy']);
226
+ const answeredAt = readText(raw['answeredAt']);
227
+ if (answeredAt !== null && !DATE.test(answeredAt)) {
228
+ problems.push(`"situation.answeredAt" is not a YYYY-MM-DD date: ${answeredAt}. It is ignored.`);
229
+ }
230
+ else {
231
+ situation.answeredAt = answeredAt;
232
+ }
233
+ return { situation, problems };
234
+ };
235
+ exports.readSituation = readSituation;
236
+ /**
237
+ * How long an answer is taken at face value.
238
+ *
239
+ * A year, which is far longer than the thirty days a pasted measurement gets, and for a reason:
240
+ * this is a fact about how a team works rather than about one connection on one afternoon. It
241
+ * still runs out. Deploy cadence is exactly the thing that changes when a team adopts continuous
242
+ * delivery, and an answer from before that is a false fact with a person's name on it.
243
+ */
244
+ exports.SITUATION_FRESH_DAYS = 365;
245
+ /** Whether an answer has passed its year. `false` when it never said when it was given. */
246
+ const isStaleSituation = (situation, today) => {
247
+ const at = situation.answeredAt;
248
+ if (!at) {
249
+ return false;
250
+ }
251
+ const days = (Date.parse(today) - Date.parse(at)) / 86_400_000;
252
+ return Number.isFinite(days) && days > exports.SITUATION_FRESH_DAYS;
253
+ };
254
+ exports.isStaleSituation = isStaleSituation;
255
+ /** Whether anybody has said anything at all: five bands, three figures and the RUM flag. */
256
+ const hasSituation = (situation) => (0, exports.answeredCount)(situation) > 0 ||
257
+ situation.rum ||
258
+ situation.screensPerSession !== null ||
259
+ situation.deploysPerWeek !== null ||
260
+ situation.returningPct !== null;
261
+ exports.hasSituation = hasSituation;
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ /**
3
+ * The five questions, and the raw figures behind them.
4
+ *
5
+ * Everything here is **declared**: somebody answered. That is worth more than a guess and less
6
+ * than a measurement, and the difference is kept visible everywhere the answers are used — they
7
+ * are never mixed into the same sentence as something a browser reported.
8
+ *
9
+ * The questions exist because four of the report's claims cannot be settled from a build folder,
10
+ * and the tool has been refusing to make them rather than guessing. The refusal is the right
11
+ * default and it is not free: a cascade that re-downloads 87 % of the bundle stays a grey number
12
+ * next to a paragraph explaining what would decide its colour. These answers are what decides it.
13
+ *
14
+ * **The rule they inherit.** A fact may raise severity with evidence and may lower it only with
15
+ * evidence, and `unknown` is not evidence — it never softens anything. That is why every answer
16
+ * type carries `unknown` as a real value rather than leaving the field absent: the code that reads
17
+ * them has to handle "nobody said" on the same line as the rest, where it cannot be forgotten.
18
+ */
19
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ /**
3
+ * Bytes translated into time.
4
+ *
5
+ * `+300 kB` means nothing on a MacBook with fibre, and time is the language a budget is asked for
6
+ * in. Every figure here is arithmetic over what the report already knows: the bytes, the round
7
+ * trips it already counts, and three connection profiles.
8
+ *
9
+ * **This is a model, not a measurement, and the difference is the point of this file.** Nothing
10
+ * here was observed: no browser was opened, no request was timed. The tool has a tab for measured
11
+ * figures and it says "measured" on it; everything produced here has to be labelled an estimate
12
+ * wherever it is shown, and the numbers below are stated with their source so the estimate can be
13
+ * argued with instead of believed.
14
+ *
15
+ * The profiles are the ones the web performance literature has settled on, and they are
16
+ * deliberately the same ones Lighthouse and WebPageTest use, so a figure here can be put next to a
17
+ * figure from those without converting anything:
18
+ *
19
+ * - **Slow 4G**: 1.6 Mbps down, 150 ms round trip. Lighthouse's mobile throttling.
20
+ * - **4G**: 9 Mbps, 85 ms. A good mobile connection, not a perfect one.
21
+ * - **Cable**: 30 Mbps, 28 ms. An office desk.
22
+ *
23
+ * The parse-and-compile figure is the roughest of the three and is worth saying so about: engines
24
+ * differ, and the same script costs several times more on a low-end phone than on a laptop. The
25
+ * coefficient used is one millisecond per kilobyte of **raw** JavaScript, which is the order of
26
+ * magnitude V8 reports for a mid-range Android device. It is used for comparison between figures
27
+ * of the same report far more than as an absolute.
28
+ */
29
+ Object.defineProperty(exports, "__esModule", { value: true });
30
+ exports.formatMs = exports.timingsOf = exports.timingOf = exports.PROFILE_IDS = exports.PROFILES = void 0;
31
+ const KB = 1024;
32
+ /** Bits per second to bytes per second, with the usual ~10 % of protocol overhead taken off. */
33
+ const throughput = (mbps) => Math.round(((mbps * 1_000_000) / 8) * 0.9);
34
+ /** Milliseconds of parse and compile per kilobyte of raw JavaScript, on a mid-range phone. */
35
+ const MS_PER_RAW_KB = 1;
36
+ exports.PROFILES = {
37
+ slow4g: { id: 'slow4g', bytesPerSecond: throughput(1.6), latencyMs: 150 },
38
+ fast4g: { id: 'fast4g', bytesPerSecond: throughput(9), latencyMs: 85 },
39
+ cable: { id: 'cable', bytesPerSecond: throughput(30), latencyMs: 28 },
40
+ };
41
+ exports.PROFILE_IDS = ['slow4g', 'fast4g', 'cable'];
42
+ /**
43
+ * One figure of the report, in milliseconds.
44
+ *
45
+ * @param bytes what travels, in the unit the report is in. Compressed when the folder was read,
46
+ * which is the honest input for the transfer half.
47
+ * @param rawBytes the same thing uncompressed, for the parse half. The two are the same number on
48
+ * a raw report, and then the script figure is right anyway.
49
+ * @param waves round trips, as the report already counts them. Each one costs the latency once
50
+ * before any of its bytes start arriving.
51
+ * @param latency the round-trip time of the **slow mobile** profile, from Criteria. The other two
52
+ * scale with it, so that somebody whose users are on another continent moves all
53
+ * three at once instead of flattening them into one number. `null` keeps the
54
+ * profiles exactly as they are defined above.
55
+ */
56
+ const timingOf = (bytes, rawBytes, waves, profile, latency = null) => {
57
+ // Scaled, not replaced: the three profiles differ in latency as much as in throughput, and a
58
+ // single figure applied to all of them would say a cable connection costs 150 ms per round trip.
59
+ const scale = latency === null ? 1 : latency / exports.PROFILES.slow4g.latencyMs;
60
+ const latencyMs = profile.latencyMs * scale * Math.max(1, waves);
61
+ const transferMs = (bytes / profile.bytesPerSecond) * 1000;
62
+ const scriptMs = (rawBytes / KB) * MS_PER_RAW_KB;
63
+ return {
64
+ profile: profile.id,
65
+ transferMs: Math.round(transferMs),
66
+ latencyMs: Math.round(latencyMs),
67
+ scriptMs: Math.round(scriptMs),
68
+ totalMs: Math.round(transferMs + latencyMs + scriptMs),
69
+ };
70
+ };
71
+ exports.timingOf = timingOf;
72
+ /** The same figure on all three profiles, which is how it is worth reading: as a range. */
73
+ const timingsOf = (bytes, rawBytes, waves, latency = null) => exports.PROFILE_IDS.map(id => (0, exports.timingOf)(bytes, rawBytes, waves, exports.PROFILES[id], latency));
74
+ exports.timingsOf = timingsOf;
75
+ /**
76
+ * Milliseconds as they are read: `340 ms`, `1,20 s`. Seconds from one thousand up, because past
77
+ * that nobody counts in milliseconds.
78
+ */
79
+ const formatMs = (ms, lang = 'en') => {
80
+ if (ms < 1000) {
81
+ return `${Math.round(ms)} ms`;
82
+ }
83
+ const seconds = ms / 1000;
84
+ const digits = seconds >= 10 ? 1 : 2;
85
+ return `${new Intl.NumberFormat(lang, { minimumFractionDigits: digits, maximumFractionDigits: digits }).format(seconds)} s`;
86
+ };
87
+ exports.formatMs = formatMs;
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ /** The shapes of the one part of the report that is a model rather than a measurement. */
3
+ Object.defineProperty(exports, "__esModule", { value: true });