@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
@@ -22,9 +22,13 @@
22
22
  * needs file-to-file edges, is the one thing a folder cannot answer and the report leaves empty.
23
23
  */
24
24
  Object.defineProperty(exports, "__esModule", { value: true });
25
- exports.readBundleGraph = exports.entrySourceOf = exports.resolveFrom = void 0;
26
- const sourcemap_1 = require("../analysis/sourcemap");
25
+ exports.readFolderGraph = exports.readBundleGraph = exports.entrySourceOf = exports.resolveFrom = void 0;
26
+ const sourcemap_1 = require("../analysis/sourcemap/sourcemap");
27
+ const index_html_1 = require("../build-text/index-html");
28
+ const route_table_1 = require("../build-text/route-table");
29
+ const tool_marks_1 = require("../build-text/tool-marks");
27
30
  const format_utils_1 = require("../format/format.utils");
31
+ const unreached_1 = require("./unreached");
28
32
  const JS_FILE = /\.m?js$/i;
29
33
  /**
30
34
  * `import … from "x"`, `export … from "x"` and the bare `import "x"`. All three make the browser
@@ -34,8 +38,49 @@ const JS_FILE = /\.m?js$/i;
34
38
  const STATIC_IMPORT = /\b(?:import|export)\b(?:[^'"`;()]+\bfrom\s*)?['"]([^'"]+)['"]/g;
35
39
  /** `import("x")` in the three quotes a minifier may leave behind — Rolldown writes backticks. */
36
40
  const DYNAMIC_IMPORT = /\bimport\s*\(\s*(['"`])([^'"`]+)\1\s*\)/g;
37
- /** Vite's table of preloadable files, written once at the top of any chunk that needs one. */
38
- const MAP_DEPS_TABLE = /__vite__mapDeps\s*=[^[]*\[([^\]]*)\]/;
41
+ /**
42
+ * The module formats that came before ES modules write their graph in plain sight too, as a list of
43
+ * strings: AMD's `define(["./a.js"], …)` and SystemJS's `System.register(["./a.js"], …)`, with an
44
+ * optional module name in front. Polymer's es5 and es6 builds are AMD, Stencil's and Vite's legacy
45
+ * copies SystemJS. Read as ES modules alone, Polymer's came out as a 2 kB bootstrap of nothing but
46
+ * the loader, zero screens and 1.1 MB "in no figure here". What these load lazily — `require([…])`
47
+ * under whatever name the minifier left, SystemJS's `module.import("./x.js")` — is the string
48
+ * fallback's and `DYNAMIC_IMPORT`'s job respectively.
49
+ */
50
+ const DEPENDENCY_LIST = /\b(?:define|System\.register)\s*\(\s*(?:(['"])[^'"]*\1\s*,\s*)?\[([^\]]*)\]/g;
51
+ /** `importScripts("a.js", "b.js")`: how a classic worker, a service worker above all, pulls in code. */
52
+ const IMPORT_SCRIPTS = /\bimportScripts\s*\(([^)]*)\)/g;
53
+ /**
54
+ * A service worker registered from the code: `navigator.serviceWorker.register("/sw.js")`, or
55
+ * Workbox's `new Workbox("/sw.js")`. Its file runs beside the page and never as part of a screen,
56
+ * so it and what it imports leave the figures; read as nothing at all, it was listed with the
57
+ * leftovers of an old build.
58
+ */
59
+ const SERVICE_WORKER = /\b(?:serviceWorker\s*\.\s*register|new\s+Workbox)\s*\(\s*(['"`])([^'"`]+)\1/g;
60
+ /**
61
+ * Any quoted string, for the last way a chunk gets named: by a string that is not an import at all.
62
+ * Loaders written before `import()` was usable — Stencil's, Polymer's `require([…])`, any hand-made
63
+ * one — build the file name at run time from an id (``import(`./${id}.entry.js`)``) and keep the ids
64
+ * as plain strings. Bounded, so a long string costs its length and no more; and the quotes are looked
65
+ * at rather than consumed, so a string holding the other kind of quote cannot put every string after
66
+ * it out of step.
67
+ */
68
+ const STRING_LITERAL = /(?<=['"`])([^'"`\s\\]{4,300})(?=['"`])/g;
69
+ /**
70
+ * `new Worker(new URL("x.js", import.meta.url))`, which is how Vite writes a worker — with a
71
+ * `""+` in front of the URL and its `.href` after it — and `SharedWorker` the same. The name is
72
+ * relative to the chunk holding it, whether or not it starts with `./`.
73
+ */
74
+ const WORKER = /\bnew\s+(?:Shared)?Worker\s*\(\s*(?:(?:""|''|``)\s*\+\s*)?new\s+URL\s*\(\s*(['"`])([^'"`]+)\1\s*,\s*import\.meta\.url/g;
75
+ /**
76
+ * Vite's table of preloadable files, written once at the top of any chunk that needs one.
77
+ *
78
+ * Two shapes. Vite 5.1 onwards: `const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=[…])))`.
79
+ * Vite 5.0: a function at the end of the chunk that fills `__vite__mapDeps.viteFileDeps=[…]` on its
80
+ * first call. Reading only the first, Excalidraw (Vite 5.0) had every preload list dropped and its
81
+ * lazy features counted one round trip deeper than the browser takes them.
82
+ */
83
+ const MAP_DEPS_TABLE = /__vite__mapDeps(?:\.viteFileDeps)?\s*=[^[]*\[([^\]]*)\]/;
39
84
  /** Each use of that table: the indices of the files that one dynamic import asks for. */
40
85
  const MAP_DEPS_CALL = /__vite__mapDeps\(\s*\[([^\]]*)\]\s*\)/g;
41
86
  /** The same list written out instead of indexed, which is what an unminified build carries. */
@@ -61,8 +106,14 @@ const QUOTED = /['"`]([^'"`]+)['"`]/g;
61
106
  * `react-scripts build` as a good build — one bootstrap, zero screens, "nothing stands out" — which
62
107
  * is the same failure Next.js produced before it was checked, from the same rule missing a shape.
63
108
  * `__webpack_require__` is no help as a fallback here: the minifier mangles it to one letter.
109
+ *
110
+ * ⚠️ Before webpack 5 the registry was called `webpackJsonp` — `window.webpackJsonp=…||[]` in
111
+ * webpack 4, `window["webpackJsonp"]=function` in webpack 3 — which is what Create React App 1 to
112
+ * 3 and Vue CLI shipped. Without it, a webpack 4 build of three lazy routes (`fixtures/webpack4-app`)
113
+ * came out as one bootstrap of 1 kB, zero screens, and its four other chunks not mentioned at all.
114
+ * A webpack build of a single chunk writes no registry and is still read: it has no graph to lose.
64
115
  */
65
- const LOADER_RUNTIME = /webpackChunk\w*\s*(?:\|\|)?=|__webpack_require__\s*\(|globalThis\.TURBOPACK|__next_f\.push/;
116
+ const LOADER_RUNTIME = /webpackChunk\w*\s*(?:\|\|)?=|webpackJsonp\w*["']?\]?\s*=|__webpack_require__\s*\(|globalThis\.TURBOPACK|__next_f\.push/;
66
117
  /** Where a chunk says its map is. Absent from a build that ships none, which is most of them. */
67
118
  const MAP_URL = /\/\/#\s*sourceMappingURL=(\S+)/;
68
119
  /** The hash a bundler appends to a chunk name, which is not part of the module it came from. */
@@ -116,11 +167,35 @@ const positionOf = (starts, offset) => {
116
167
  }
117
168
  return { line: low, column: offset - (starts[low] ?? 0) };
118
169
  };
170
+ /**
171
+ * One name of a preload list as a file of the folder, or `''` when it is none.
172
+ *
173
+ * Vite writes these relative to the root of the folder (`assets/x.js`) with the default `base`, and
174
+ * relative to the chunk holding the list (`./x.js`) with `base: './'` — and Nuxt always does the
175
+ * latter. Read only from the root, `./x.js` named a file that is not there, the whole list was
176
+ * dropped, and every screen of a Nuxt app, or of a Vite app built for a subfolder, Electron or
177
+ * Tauri, came out one round trip deeper than the browser takes it.
178
+ */
179
+ const preloadPath = (chunk, name, exists) => {
180
+ const fromRoot = (0, exports.resolveFrom)('', name);
181
+ if (exists(fromRoot)) {
182
+ return fromRoot;
183
+ }
184
+ const fromChunk = (0, exports.resolveFrom)(chunk, name);
185
+ return exists(fromChunk) ? fromChunk : '';
186
+ };
119
187
  /** Every file name of a preload list, resolved, or `null` when one of them is not a file here. */
120
- const groupOf = (names, exists) => {
121
- const paths = names.map(name => (0, exports.resolveFrom)('', name));
122
- return paths.length > 1 && paths.every(path => path !== '' && exists(path)) ? paths : null;
188
+ const groupOf = (chunk, names, exists) => {
189
+ const paths = names.map(name => preloadPath(chunk, name, exists));
190
+ return paths.length > 1 && paths.every(path => path !== '') ? paths : null;
123
191
  };
192
+ /**
193
+ * The lazy import each preload call belongs to: the last `import()` written before it, and after the
194
+ * call before it. Vite writes the pair as one expression — `__vitePreload(() => import("./x.js"),
195
+ * __vite__mapDeps([4,5,3]))` — whatever `.then()` sits between them, so the nearest one back is the
196
+ * one it goes with.
197
+ */
198
+ const importBefore = (imports, from, to) => imports.findLast(entry => entry.index > from && entry.index < to)?.target ?? null;
124
199
  /**
125
200
  * The preload lists of a chunk: the sets of files Vite asks for in one go.
126
201
  *
@@ -129,33 +204,39 @@ const groupOf = (names, exists) => {
129
204
  * this. Without reading these, every screen of a Vite application would be counted one round trip
130
205
  * deeper than it is.
131
206
  */
132
- const groupsIn = (code, exists) => {
207
+ const groupsIn = (chunk, code, imports, exists) => {
133
208
  const groups = [];
134
209
  const table = MAP_DEPS_TABLE.exec(code);
135
210
  const files = table ? [...(table[1] ?? '').matchAll(QUOTED)].map(match => match[1] ?? '') : [];
211
+ let previousCall = -1;
136
212
  for (const call of code.matchAll(MAP_DEPS_CALL)) {
137
213
  const names = (call[1] ?? '').split(',').map(index => files[Number(index.trim())] ?? '');
138
- const group = groupOf(names, exists);
214
+ const group = groupOf(chunk, names, exists);
139
215
  if (group) {
140
- groups.push(group);
216
+ groups.push({ files: group, target: importBefore(imports, previousCall, call.index) });
141
217
  }
218
+ previousCall = call.index;
142
219
  }
143
220
  for (const list of code.matchAll(PATH_LIST)) {
144
221
  // The table itself is a list of file names, and would otherwise read as one huge group.
145
222
  const inTable = !!table && list.index >= table.index && list.index < table.index + table[0].length;
146
223
  const group = inTable
147
224
  ? null
148
- : groupOf([...list[0].matchAll(QUOTED)].map(m => m[1] ?? ''), exists);
225
+ : groupOf(chunk, [...list[0].matchAll(QUOTED)].map(m => m[1] ?? ''), exists);
149
226
  if (group) {
150
- groups.push(group);
227
+ groups.push({ files: group, target: null });
151
228
  }
152
229
  }
153
230
  return groups;
154
231
  };
155
232
  /** Reads one chunk: its edges and its preload lists, plus who wrote each dynamic import. */
156
- const readChunk = (chunk, code, segments, exists) => {
233
+ const readChunk = (chunk, code, segments, exists, root, keys, routeKeys) => {
157
234
  const statics = new Set();
158
235
  const dynamics = [];
236
+ const imports = [];
237
+ const routes = [];
238
+ const mentions = new Set();
239
+ const registers = new Set();
159
240
  const mapped = segments.length > 0;
160
241
  const starts = mapped ? lineStartsOf(code) : [];
161
242
  for (const match of code.matchAll(STATIC_IMPORT)) {
@@ -164,20 +245,93 @@ const readChunk = (chunk, code, segments, exists) => {
164
245
  statics.add(target);
165
246
  }
166
247
  }
248
+ // AMD and SystemJS dependencies, and a classic worker's `importScripts`: fetched before the
249
+ // module runs, so they travel with it like a static import. A dependency list names modules
250
+ // relative to the chunk, or to the root of the site; whichever of the two is a file wins.
251
+ const lists = [
252
+ ...[...code.matchAll(DEPENDENCY_LIST)].map(match => match[2] ?? ''),
253
+ ...[...code.matchAll(IMPORT_SCRIPTS)].map(match => match[1] ?? ''),
254
+ ];
255
+ for (const list of lists) {
256
+ for (const [, name = ''] of list.matchAll(QUOTED)) {
257
+ // An AMD module id usually leaves the extension off — Rollup's `amd` output and
258
+ // RequireJS both write `"./shared-1a2b3c4d"` — so the name with `.js` is tried too.
259
+ const relative = /^\.{0,2}\//.test(name) ? name : `./${name}`;
260
+ const target = [(0, exports.resolveFrom)(chunk, relative), (0, exports.resolveFrom)('', name)]
261
+ .flatMap(path => [path, `${path}.js`])
262
+ .find(path => path !== chunk && exists(path));
263
+ if (target) {
264
+ statics.add(target);
265
+ }
266
+ }
267
+ }
268
+ for (const match of code.matchAll(SERVICE_WORKER)) {
269
+ const name = match[2] ?? '';
270
+ const target = [(0, exports.resolveFrom)('', name), (0, exports.resolveFrom)(chunk, name)].find(path => exists(path));
271
+ if (target) {
272
+ registers.add(target);
273
+ }
274
+ }
275
+ for (const match of code.matchAll(STRING_LITERAL)) {
276
+ const target = (0, unreached_1.mentionedBy)(match[1] ?? '', keys);
277
+ if (target && target !== chunk) {
278
+ mentions.add(target);
279
+ }
280
+ }
281
+ for (const { id, tag } of (0, tool_marks_1.stencilComponentsIn)(code)) {
282
+ const target = (0, exports.resolveFrom)(chunk, `./${id}.entry.js`);
283
+ if (exists(target)) {
284
+ routes.push({ target, route: { path: '', name: tag } });
285
+ }
286
+ }
287
+ for (const { specifier, route } of (0, route_table_1.sapperRoutesIn)(code)) {
288
+ const target = (0, exports.resolveFrom)(chunk, specifier);
289
+ if (exists(target)) {
290
+ routes.push({ target, route });
291
+ }
292
+ }
167
293
  for (const match of code.matchAll(DYNAMIC_IMPORT)) {
168
294
  const target = (0, exports.resolveFrom)(chunk, match[2] ?? '');
169
295
  if (target === chunk || !exists(target)) {
170
296
  continue;
171
297
  }
298
+ imports.push({ index: match.index, target });
299
+ const route = (0, route_table_1.routeBefore)(code, match.index, routeKeys);
300
+ if (route) {
301
+ routes.push({ target, route });
302
+ }
172
303
  // Which of the files inside this chunk wrote the import. The map answers it exactly, so
173
304
  // "who lazy-loads this screen" is read rather than guessed even in a chunk holding thirty
174
305
  // files. Without a map it stays open and the entry of the chunk answers for it later.
175
306
  const position = mapped ? positionOf(starts, match.index) : null;
176
307
  const from = position ? (0, sourcemap_1.sourceAt)(segments, position.line, position.column) : null;
177
- dynamics.push({ target, from: from ? (0, sourcemap_1.sourcePathOf)(from) : null });
308
+ dynamics.push({ target, from: from ? (0, sourcemap_1.sourcePathOf)(from, root) : null });
178
309
  }
179
- return { statics: [...statics], dynamics, groups: groupsIn(code, exists) };
310
+ // A worker is a chunk started on demand like any `import()`, written another way. Missed, its
311
+ // chunk read as unreachable — "possibly a service worker" — and its weight belonged nowhere.
312
+ for (const match of code.matchAll(WORKER)) {
313
+ const name = match[2] ?? '';
314
+ const target = (0, exports.resolveFrom)(chunk, /^\.{0,2}\//.test(name) ? name : `./${name}`);
315
+ if (target === chunk || !exists(target)) {
316
+ continue;
317
+ }
318
+ const position = mapped ? positionOf(starts, match.index) : null;
319
+ const from = position ? (0, sourcemap_1.sourceAt)(segments, position.line, position.column) : null;
320
+ dynamics.push({ target, from: from ? (0, sourcemap_1.sourcePathOf)(from, root) : null });
321
+ }
322
+ const stencil = routes.some(entry => entry.route.path === '' && entry.target.endsWith('.entry.js'));
323
+ return {
324
+ statics: [...statics],
325
+ dynamics,
326
+ groups: groupsIn(chunk, code, imports, exists),
327
+ routes,
328
+ mentions: [...mentions],
329
+ registers: [...registers],
330
+ tools: (0, tool_marks_1.toolsIn)(code, stencil),
331
+ };
180
332
  };
333
+ /** A template or a stylesheet: compiled into a module, never one a chunk can start at. */
334
+ const NOT_A_MODULE = /\.(?:html?|css|scss|sass|less|styl)$/i;
181
335
  /**
182
336
  * Which source file a chunk starts at.
183
337
  *
@@ -186,6 +340,11 @@ const readChunk = (chunk, code, segments, exists) => {
186
340
  * `orders.page-DgHWSolo.js` came from the source called `orders.page`. When neither settles it the
187
341
  * last source is taken, because a chunk is written dependencies first and the module it exists for
188
342
  * goes at the end.
343
+ *
344
+ * The last *module*: Angular names every chunk `chunk-<hash>.js` and lists a component's template
345
+ * after the component, so the last source of a lazy screen is `orders.page.html`. Taken as is, a
346
+ * real build named all eight of its screens after their templates, and its signals sent people to
347
+ * open an `.html` to change an import.
189
348
  */
190
349
  const entrySourceOf = (chunk, sources) => {
191
350
  if (sources.length <= 1) {
@@ -193,13 +352,18 @@ const entrySourceOf = (chunk, sources) => {
193
352
  }
194
353
  const stem = (0, format_utils_1.baseName)(chunk).replace(JS_FILE, '').replace(HASH, '');
195
354
  const named = sources.find(source => (0, format_utils_1.baseName)(source).replace(/\.[^.]+$/, '') === stem);
196
- return named ?? sources.at(-1) ?? null;
355
+ return named ?? sources.findLast(source => !NOT_A_MODULE.test(source)) ?? sources.at(-1) ?? null;
197
356
  };
198
357
  exports.entrySourceOf = entrySourceOf;
199
358
  /** The map of a chunk, when the folder ships one next to it. */
200
359
  const mapOf = async (chunk, code, byPath) => {
201
360
  const url = MAP_URL.exec(code)?.[1];
202
- const named = url && !url.startsWith('data:') ? byPath.get((0, exports.resolveFrom)(chunk.path, url)) : undefined;
361
+ // A source map URL is relative to the chunk, as any URL in a script is: `vendor-1a2b.map` sits
362
+ // next to `assets/vendor-3c4d.js`. Read from the root of the folder, as a preload list is,
363
+ // Ember's maps — named with a hash of their own, so `${chunk}.map` misses them too — were not
364
+ // found, and the report said a folder holding three of them had none.
365
+ const relative = url && !/^(?:\.{0,2}\/|[a-z]+:)/i.test(url) ? `./${url}` : url;
366
+ const named = relative && !relative.startsWith('data:') ? byPath.get((0, exports.resolveFrom)(chunk.path, relative)) : undefined;
203
367
  const file = named ?? byPath.get(`${chunk.path}.map`);
204
368
  if (!file) {
205
369
  return null;
@@ -214,22 +378,29 @@ const mapOf = async (chunk, code, byPath) => {
214
378
  }
215
379
  };
216
380
  /** Reads every chunk of the folder once: text, map, edges and weights. */
217
- const readChunks = async (chunks, byPath) => {
381
+ const readChunks = async (chunks, byPath, routeKeys) => {
218
382
  const read = new Map();
219
383
  const splits = new Map();
220
384
  const runtimes = new Set();
221
385
  const exists = (path) => byPath.has(path);
386
+ // Every map first, because where the project starts is decided across all of them.
387
+ const loaded = [];
222
388
  for (const chunk of chunks) {
223
389
  const code = await chunk.text();
224
390
  if (LOADER_RUNTIME.test(code)) {
225
391
  runtimes.add(chunk.path);
226
392
  }
227
- const map = await mapOf(chunk, code, byPath);
393
+ loaded.push({ chunk, code, map: await mapOf(chunk, code, byPath) });
394
+ }
395
+ const roots = (0, sourcemap_1.projectRootsOf)(loaded.map(({ map }) => map?.sources ?? []));
396
+ const keys = (0, unreached_1.mentionKeysOf)(chunks.map(chunk => chunk.path));
397
+ for (const [index, { chunk, code, map }] of loaded.entries()) {
228
398
  const segments = map ? (0, sourcemap_1.segmentsOf)(map) : [];
399
+ const root = roots[index] ?? '';
229
400
  const raw = map ? (0, sourcemap_1.bytesBySource)(map, code) : new Map();
230
401
  const split = new Map();
231
402
  for (const [source, bytes] of raw) {
232
- const path = (0, sourcemap_1.sourcePathOf)(source);
403
+ const path = (0, sourcemap_1.sourcePathOf)(source, root);
233
404
  split.set(path, (split.get(path) ?? 0) + bytes);
234
405
  }
235
406
  if (raw.size > 0) {
@@ -237,23 +408,31 @@ const readChunks = async (chunks, byPath) => {
237
408
  // is the same object whichever of the two paths produced it.
238
409
  splits.set((0, format_utils_1.baseName)(chunk.path), raw);
239
410
  }
240
- const sources = map ? map.sources.map(source => (0, sourcemap_1.sourcePathOf)(source)) : [];
241
- read.set(chunk.path, { ...readChunk(chunk.path, code, segments, exists), split, sources });
411
+ const sources = map ? map.sources.map(source => (0, sourcemap_1.sourcePathOf)(source, root)) : [];
412
+ read.set(chunk.path, {
413
+ ...readChunk(chunk.path, code, segments, exists, root, keys, routeKeys),
414
+ split,
415
+ sources,
416
+ });
242
417
  }
243
418
  return { read, splits, runtimes };
244
419
  };
245
420
  /**
246
421
  * Which chunks the loader asks for in the same round trip, from the preload lists.
247
422
  *
248
- * A list only means something once it is tied to the import it belongs to, and what ties it is that
249
- * exactly one of its files is a chunk this same chunk lazily imports. When two of them are, the
250
- * list is left alone: counting a screen as arriving with something it does not would understate the
251
- * round trips, and that is the direction that flatters the build.
423
+ * A list only means something once it is tied to the import it belongs to. The call it sits in ties
424
+ * it when it was read next to one; otherwise what ties it is that exactly one of its files is a
425
+ * chunk this same chunk lazily imports. When two of them are and nothing says which, the list is
426
+ * left alone: counting a screen as arriving with something it does not would understate the round
427
+ * trips, and that is the direction that flatters the build.
252
428
  */
253
429
  const parallelOf = (read) => {
254
430
  const parallel = new Map();
255
431
  const targetOf = (group, lazy) => {
256
- const inside = group.filter(path => lazy.has(path));
432
+ if (group.target !== null && lazy.has(group.target) && group.files.includes(group.target)) {
433
+ return group.target;
434
+ }
435
+ const inside = group.files.filter(path => lazy.has(path));
257
436
  return inside.length === 1 ? (inside[0] ?? null) : null;
258
437
  };
259
438
  for (const info of read.values()) {
@@ -263,7 +442,7 @@ const parallelOf = (read) => {
263
442
  if (!target) {
264
443
  continue;
265
444
  }
266
- const rest = group.filter(path => path !== target);
445
+ const rest = group.files.filter(path => path !== target);
267
446
  parallel.set(target, [...new Set([...(parallel.get(target) ?? []), ...rest])]);
268
447
  }
269
448
  }
@@ -277,29 +456,54 @@ const parallelOf = (read) => {
277
456
  * chunk from a shared one: a bundler writes the shared code of an application into
278
457
  * its entry chunk, so the entry ends up imported by its own children and cannot be
279
458
  * found by looking for a chunk that nobody imports.
459
+ * @param page what else the page says about its scripts: the `nomodule` ones, and the service
460
+ * workers it registers. Both are files of the build no screen downloads.
280
461
  */
281
- const readBundleGraph = async (files, entries) => {
462
+ const readBundleGraph = async (files, entries, page = {}) => {
282
463
  const byPath = new Map(files.map(file => [file.path, file]));
283
464
  const chunks = files.filter(file => JS_FILE.test(file.path));
284
- const { read, splits, runtimes } = await readChunks(chunks, byPath);
285
- const roots = chunks.filter(chunk => entries.has((0, format_utils_1.baseName)(chunk.path))).map(chunk => chunk.path);
465
+ const { read, splits, runtimes } = await readChunks(chunks, byPath, (0, route_table_1.routeKeyPattern)(page.routeKeys));
466
+ const named = (names) => chunks.filter(chunk => names?.has((0, format_utils_1.baseName)(chunk.path))).map(chunk => chunk.path);
467
+ const ignored = page.ignored ?? new Set();
468
+ const modernRoots = named(entries).filter(path => !ignored.has(path));
469
+ const legacyRoots = named(page.legacy).filter(path => !modernRoots.includes(path) && !ignored.has(path));
470
+ // A page that starts nothing but a `nomodule` script is a build for old browsers only, and then
471
+ // that copy is the one there is to read.
472
+ const roots = modernRoots.length > 0 ? modernRoots : legacyRoots;
286
473
  if (roots.length === 0) {
287
474
  throw new Error('NO_PAGE');
288
475
  }
289
476
  const lazyTargets = new Set([...read.values()].flatMap(info => info.dynamics.map(entry => entry.target)));
290
477
  /**
291
- * A folder whose entry carries a run-time loader and where nothing lazily imports anything is
292
- * not an ES module bundle: it is webpack's or Turbopack's output, and its graph is a table of
293
- * numbers this cannot read. Saying so is the whole point — pointed at a Next.js export, the
294
- * report came out as one bootstrap of seven files, zero screens and "nothing stands out".
478
+ * A folder whose entry carries a run-time loader, where nothing lazily imports anything, and
479
+ * where other chunks register themselves with that loader is not an ES module bundle: it is
480
+ * webpack's or Turbopack's output, and its graph is a table of numbers this cannot read. Saying
481
+ * so is the whole point — pointed at a Next.js export, the report came out as one bootstrap of
482
+ * seven files, zero screens and "nothing stands out".
295
483
  *
296
- * Both halves are required on purpose. The marker alone would refuse an ES module bundle that
297
- * happens to carry one webpack-built dependency; no lazy edges alone is a perfectly ordinary
298
- * application with every route eager, which is a build this reads correctly today.
484
+ * All three halves are required on purpose. The marker alone would refuse an ES module bundle
485
+ * that happens to carry one webpack-built dependency; no lazy edges alone is a perfectly
486
+ * ordinary application with every route eager. And the loader with nothing else carrying the
487
+ * marker is a loader with nothing to load: an Ember build ships ember-auto-import's webpack
488
+ * runtime inside `vendor.js` with no chunk for it, and was refused as a Next.js app.
299
489
  */
300
- if (lazyTargets.size === 0 && roots.some(root => runtimes.has(root))) {
490
+ const loaded = [...runtimes].some(path => !roots.includes(path));
491
+ if (lazyTargets.size === 0 && roots.some(root => runtimes.has(root)) && loaded) {
301
492
  throw new Error('NOT_ESM_GRAPH');
302
493
  }
494
+ const workerRoots = new Set([...named(page.workers), ...[...read.values()].flatMap(info => info.registers)]);
495
+ const byName = (0, unreached_1.lazyByName)(read, roots, new Set([...legacyRoots, ...workerRoots, ...ignored]));
496
+ for (const target of byName) {
497
+ lazyTargets.add(target);
498
+ }
499
+ const offPage = (0, unreached_1.offPageOf)(read, roots, roots === modernRoots ? legacyRoots : [], workerRoots);
500
+ // What `loadline.json` says no screen downloads, when nothing the application imports reaches it.
501
+ const reached = (0, unreached_1.reachOver)(read, roots);
502
+ for (const path of ignored) {
503
+ if (!reached.has(path)) {
504
+ offPage.set(path, 'ignored');
505
+ }
506
+ }
303
507
  const entryChunks = new Set([...roots, ...lazyTargets]);
304
508
  /**
305
509
  * The name the source graph knows a chunk by. It is a real file when the maps said so, and the
@@ -309,12 +513,15 @@ const readBundleGraph = async (files, entries) => {
309
513
  const sourceKeys = new Map([...read].map(([chunk, info]) => [chunk, (0, exports.entrySourceOf)(chunk, info.sources) ?? chunk]));
310
514
  const inputs = {};
311
515
  const inputOf = (path) => (inputs[path] ??= { bytes: 0, imports: [] });
312
- for (const info of read.values()) {
516
+ // What no screen downloads stays out of the source graph too: the legacy copy carries every
517
+ // source of the modern one a second time, and counted, every file would weigh double.
518
+ const onPage = [...read].filter(([chunk]) => !offPage.has(chunk));
519
+ for (const [, info] of onPage) {
313
520
  for (const [source, bytes] of info.split) {
314
521
  inputOf(source).bytes += bytes;
315
522
  }
316
523
  }
317
- for (const [chunk, info] of read) {
524
+ for (const [chunk, info] of onPage) {
318
525
  for (const { target, from } of info.dynamics) {
319
526
  const importer = from ?? sourceKeys.get(chunk);
320
527
  const imported = sourceKeys.get(target);
@@ -340,8 +547,39 @@ const readBundleGraph = async (files, entries) => {
340
547
  if (entryChunks.has(chunk.path)) {
341
548
  output.entryPoint = sourceKeys.get(chunk.path) ?? chunk.path;
342
549
  }
550
+ const away = offPage.get(chunk.path);
551
+ if (away) {
552
+ output.offPage = away;
553
+ }
343
554
  outputs[chunk.path] = output;
344
555
  }
345
- return { meta: { inputs, outputs }, parallel: parallelOf(read), splits };
556
+ // Every route a chunk is the page of, once each: vue-router sends three routes to one `Home`.
557
+ const routes = new Map();
558
+ const found = [...read.values()].flatMap(info => info.routes);
559
+ for (const { target, route } of found) {
560
+ const known = routes.get(target) ?? [];
561
+ if (known.every(other => !(other.path === route.path && other.name === route.name))) {
562
+ routes.set(target, [...known, route]);
563
+ }
564
+ }
565
+ const builtBy = (0, tool_marks_1.builtByOf)(page.html ?? null, [...read.values()].map(info => info.tools));
566
+ return { meta: { inputs, outputs, builtBy, readFrom: 'folder' }, parallel: parallelOf(read), splits, routes };
346
567
  };
347
568
  exports.readBundleGraph = readBundleGraph;
569
+ /**
570
+ * The graph of a folder, read with everything its page says: where execution starts, what only an
571
+ * old browser runs and which service workers it registers. The one way in for the page and the
572
+ * command alike, so the two never read a page differently.
573
+ */
574
+ const readFolderGraph = (files, html, hints = {}) => {
575
+ const scripts = html ? (0, index_html_1.scriptsIn)(html) : null;
576
+ const named = (patterns = []) => files.filter(file => JS_FILE.test(file.path) && patterns.some(pattern => (0, format_utils_1.namedBy)(pattern, file.path)));
577
+ return (0, exports.readBundleGraph)(files, new Set([...(scripts?.entries ?? []), ...named(hints.entries).map(file => (0, format_utils_1.baseName)(file.path))]), {
578
+ legacy: new Set(scripts?.legacy),
579
+ workers: new Set(scripts?.workers),
580
+ ignored: new Set(named(hints.ignore).map(file => file.path)),
581
+ html,
582
+ ...(hints.routeKeys && { routeKeys: hints.routeKeys }),
583
+ });
584
+ };
585
+ exports.readFolderGraph = readFolderGraph;