frontend-audit 0.0.0-stage → 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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +192 -3
  3. package/dist/cli.mjs +3078 -0
  4. package/package.json +63 -6
package/dist/cli.mjs ADDED
@@ -0,0 +1,3078 @@
1
+ #!/usr/bin/env node
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __esm = (fn, res, err) => function __init() {
5
+ if (err) throw err[0];
6
+ try {
7
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
8
+ } catch (e) {
9
+ throw err = [e], e;
10
+ }
11
+ };
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
16
+
17
+ // packages/core/dist/chrome.js
18
+ async function inspectChrome(port, remainingMs, urls) {
19
+ if (remainingMs < 3e3) {
20
+ return { info: { attached: false, detail: "Chrome was not checked because the time budget was almost gone." }, drafts: [] };
21
+ }
22
+ let pages = [];
23
+ try {
24
+ const response = await fetch(`http://127.0.0.1:${port}/json/list`, { signal: AbortSignal.timeout(800) });
25
+ if (!response.ok)
26
+ throw new Error(`Chrome responded with ${response.status}`);
27
+ pages = await response.json();
28
+ } catch {
29
+ return {
30
+ info: { attached: false, detail: `Chrome was not attached. Start it with --remote-debugging-port=${port} and open the page you want checked.` },
31
+ drafts: []
32
+ };
33
+ }
34
+ const page = pages.find((target) => target.type === "page" && target.webSocketDebuggerUrl && target.url && !target.url.startsWith("chrome") && !target.url.startsWith("devtools"));
35
+ if (!page?.webSocketDebuggerUrl || !page.url) {
36
+ return { info: { attached: false, detail: "Chrome is running, but no page tab is open." }, drafts: [] };
37
+ }
38
+ try {
39
+ const sample = await evaluate(page.webSocketDebuggerUrl);
40
+ return { info: { attached: true, detail: "Read the active Chrome tab.", pageUrl: page.url }, drafts: toDrafts(sample, urls) };
41
+ } catch {
42
+ return { info: { attached: true, detail: "Chrome is open, but the tab timings could not be read.", pageUrl: page.url }, drafts: [] };
43
+ }
44
+ }
45
+ async function evaluate(wsUrl) {
46
+ const ws = new WebSocket(wsUrl);
47
+ await new Promise((resolve, reject) => {
48
+ const timer = setTimeout(() => reject(new Error("timeout")), 2e3);
49
+ ws.addEventListener("open", () => {
50
+ clearTimeout(timer);
51
+ resolve();
52
+ });
53
+ ws.addEventListener("error", () => {
54
+ clearTimeout(timer);
55
+ reject(new Error("socket"));
56
+ });
57
+ });
58
+ try {
59
+ const value = await new Promise((resolve, reject) => {
60
+ const timer = setTimeout(() => reject(new Error("timeout")), 4e3);
61
+ ws.addEventListener("message", (event) => {
62
+ const message = JSON.parse(String(event.data));
63
+ if (message.id !== 1)
64
+ return;
65
+ clearTimeout(timer);
66
+ resolve(message.result?.result?.value);
67
+ });
68
+ ws.send(JSON.stringify({
69
+ id: 1,
70
+ method: "Runtime.evaluate",
71
+ params: {
72
+ returnByValue: true,
73
+ expression: `(() => {
74
+ const resources = performance.getEntriesByType("resource").map((entry) => ({ name: entry.name, duration: entry.duration })).sort((a, b) => b.duration - a.duration).slice(0, 15);
75
+ const longtasks = performance.getEntriesByType("longtask").map((entry) => ({ name: entry.name, duration: entry.duration })).slice(0, 5);
76
+ return { resources, longtasks };
77
+ })()`
78
+ }
79
+ }));
80
+ });
81
+ const sample = value;
82
+ return { resources: sample?.resources ?? [], longtasks: sample?.longtasks ?? [] };
83
+ } finally {
84
+ ws.close();
85
+ }
86
+ }
87
+ function toDrafts(sample, urls) {
88
+ const drafts = [];
89
+ for (const resource of sample.resources) {
90
+ if (resource.duration < 300)
91
+ continue;
92
+ const hit = urls.find((item) => resource.name.includes(item.value) || item.value.includes(pathOf(resource.name)));
93
+ drafts.push({
94
+ ruleId: "chrome.slow-request",
95
+ line: hit?.line ?? 1,
96
+ file: hit?.file ?? "(open tab)",
97
+ detail: hit ? `${Math.round(resource.duration)}ms on ${resource.name}, matched ${hit.file}` : `${Math.round(resource.duration)}ms on ${resource.name}. Attribution unknown.`
98
+ });
99
+ if (drafts.length >= 8)
100
+ break;
101
+ }
102
+ for (const task of sample.longtasks) {
103
+ if (task.duration < 50)
104
+ continue;
105
+ drafts.push({
106
+ ruleId: "chrome.long-task",
107
+ line: 1,
108
+ file: "(open tab)",
109
+ detail: `${Math.round(task.duration)}ms long task. Attribution unknown.`
110
+ });
111
+ }
112
+ return drafts;
113
+ }
114
+ function pathOf(url) {
115
+ try {
116
+ return new URL(url).pathname;
117
+ } catch {
118
+ return url;
119
+ }
120
+ }
121
+ async function activePageUrl(port) {
122
+ try {
123
+ const response = await fetch(`http://127.0.0.1:${port}/json/list`, { signal: AbortSignal.timeout(800) });
124
+ const pages = await response.json();
125
+ return pages.find((target) => target.type === "page" && target.url && !target.url.startsWith("chrome"))?.url;
126
+ } catch {
127
+ return void 0;
128
+ }
129
+ }
130
+ var init_chrome = __esm({
131
+ "packages/core/dist/chrome.js"() {
132
+ "use strict";
133
+ }
134
+ });
135
+
136
+ // packages/core/dist/version.js
137
+ function parseVersion(raw) {
138
+ if (!raw)
139
+ return void 0;
140
+ const match = raw.match(/(\d+)\.(\d+)(?:\.(\d+))?/);
141
+ if (!match)
142
+ return void 0;
143
+ return [Number(match[1]), Number(match[2]), Number(match[3] ?? 0)];
144
+ }
145
+ function compareSemver(left, right) {
146
+ for (let index = 0; index < 3; index += 1) {
147
+ if (left[index] !== right[index])
148
+ return left[index] - right[index];
149
+ }
150
+ return 0;
151
+ }
152
+ function entryMatches(entry, stacks, versions) {
153
+ if (!entry.stacks.includes("shared") && !entry.stacks.some((stack) => stacks.includes(stack))) {
154
+ return false;
155
+ }
156
+ if (!entry.versionOf && !entry.since && !entry.until)
157
+ return true;
158
+ const version = entry.versionOf ? versions[entry.versionOf] : void 0;
159
+ if (!version)
160
+ return entry.onUnknown !== "no" && entry.until === void 0;
161
+ if (entry.since && compareSemver(version, entry.since) < 0)
162
+ return false;
163
+ if (entry.until && compareSemver(version, entry.until) >= 0)
164
+ return false;
165
+ return true;
166
+ }
167
+ function selectEntry(entries, ruleId, stacks, versions) {
168
+ const matches = entries.filter((entry) => entry.id === ruleId && entryMatches(entry, stacks, versions));
169
+ if (matches.length === 0)
170
+ return void 0;
171
+ return matches.sort((left, right) => specificity(right) - specificity(left))[0];
172
+ }
173
+ function specificity(entry) {
174
+ if (!entry.since)
175
+ return 0;
176
+ return entry.since[0] * 1e4 + entry.since[1] * 100 + entry.since[2];
177
+ }
178
+ var init_version = __esm({
179
+ "packages/core/dist/version.js"() {
180
+ "use strict";
181
+ }
182
+ });
183
+
184
+ // packages/core/dist/discover.js
185
+ import fs from "node:fs";
186
+ import path from "node:path";
187
+ function resolveRepoRoot(input) {
188
+ const start = fs.existsSync(input) && fs.statSync(input).isDirectory() ? path.resolve(input) : path.dirname(path.resolve(input));
189
+ let current = start;
190
+ for (; ; ) {
191
+ if (fs.existsSync(path.join(current, ".git")) || fs.existsSync(path.join(current, "pnpm-workspace.yaml")) || fs.existsSync(path.join(current, "nx.json"))) {
192
+ return current;
193
+ }
194
+ const packageFile = path.join(current, "package.json");
195
+ if (fs.existsSync(packageFile)) {
196
+ const info = readPackage(packageFile);
197
+ if (info && Array.isArray(readWorkspaces(packageFile)))
198
+ return current;
199
+ }
200
+ const parent = path.dirname(current);
201
+ if (parent === current)
202
+ return start;
203
+ current = parent;
204
+ }
205
+ }
206
+ function discoverApps(repoRoot) {
207
+ const packageFiles = /* @__PURE__ */ new Set();
208
+ const rootPackage = path.join(repoRoot, "package.json");
209
+ if (fs.existsSync(rootPackage))
210
+ packageFiles.add(rootPackage);
211
+ for (const folder of CHILD_DIRS) {
212
+ collectPackages(path.join(repoRoot, folder), packageFiles, 2);
213
+ }
214
+ const workspaceGlobs = [
215
+ ...readWorkspaceGlobs(repoRoot),
216
+ ...readPnpmGlobs(path.join(repoRoot, "pnpm-workspace.yaml"))
217
+ ];
218
+ for (const glob of workspaceGlobs)
219
+ expandGlob(repoRoot, glob, packageFiles);
220
+ for (const projectRoot of readAngularProjects(path.join(repoRoot, "angular.json"))) {
221
+ const candidate = path.join(repoRoot, projectRoot, "package.json");
222
+ if (fs.existsSync(candidate))
223
+ packageFiles.add(candidate);
224
+ }
225
+ let apps = [...packageFiles].map((file) => toApp(repoRoot, file)).filter((app) => app !== void 0 && app.stacks.length > 0);
226
+ apps = apps.filter((app) => !apps.some((other) => other.root !== app.root && other.root.startsWith(app.root + path.sep)));
227
+ apps.sort((left, right) => left.id.localeCompare(right.id));
228
+ if (apps.length === 0) {
229
+ return [
230
+ {
231
+ id: ".",
232
+ name: path.basename(repoRoot),
233
+ root: repoRoot,
234
+ stacks: [],
235
+ versions: {},
236
+ parsedVersions: {}
237
+ }
238
+ ];
239
+ }
240
+ return apps;
241
+ }
242
+ function describeApp(app) {
243
+ const parts = [];
244
+ for (const [stack, pkg, label] of FRAMEWORK_LABELS) {
245
+ if (app.stacks.includes(stack))
246
+ parts.push(`${label} ${app.versions[pkg] ?? "unknown"}`);
247
+ }
248
+ for (const [stack, pkg, label] of LIBRARY_LABELS) {
249
+ if (!app.stacks.includes(stack))
250
+ continue;
251
+ const version = app.versions[pkg] ?? app.versions["@tanstack/vue-query"] ?? app.versions["@tanstack/angular-query-experimental"];
252
+ parts.push(`${label} ${version ?? "unknown"}`);
253
+ }
254
+ return parts.length > 0 ? parts.join(", ") : "stack not recognized";
255
+ }
256
+ function filterApps(apps, repoRoot, input) {
257
+ const target = path.resolve(input);
258
+ const exists = fs.existsSync(target);
259
+ const isFile = exists && fs.statSync(target).isFile();
260
+ const scope = isFile ? path.dirname(target) : target;
261
+ if (path.resolve(scope) === path.resolve(repoRoot))
262
+ return apps;
263
+ const scoped = apps.filter((app) => scope === app.root || scope.startsWith(app.root + path.sep) || app.root.startsWith(scope + path.sep));
264
+ return scoped.length > 0 ? scoped : apps;
265
+ }
266
+ function toApp(repoRoot, packageFile) {
267
+ const info = readPackage(packageFile);
268
+ if (!info)
269
+ return void 0;
270
+ const root = path.dirname(packageFile);
271
+ const versions = {};
272
+ const parsedVersions = {};
273
+ const stacks = /* @__PURE__ */ new Set();
274
+ for (const [name, range] of Object.entries(info.deps)) {
275
+ const stack = FRAMEWORKS[name] ?? LIBRARIES[name];
276
+ if (!stack)
277
+ continue;
278
+ stacks.add(stack);
279
+ const resolved = resolveVersion(root, name, range);
280
+ versions[name] = resolved.raw;
281
+ parsedVersions[name] = resolved.parsed;
282
+ }
283
+ if (stacks.has("next"))
284
+ stacks.add("react");
285
+ if (stacks.has("nuxt"))
286
+ stacks.add("vue");
287
+ if (stacks.has("react-native"))
288
+ stacks.add("react");
289
+ const id = path.relative(repoRoot, root).replaceAll("\\", "/") || ".";
290
+ return {
291
+ id,
292
+ name: info.name || path.basename(root),
293
+ root,
294
+ stacks: [...stacks],
295
+ versions,
296
+ parsedVersions
297
+ };
298
+ }
299
+ function resolveVersion(appRoot, name, range) {
300
+ const parsed = parseVersion(range);
301
+ if (parsed)
302
+ return { raw: trimRange(range), parsed };
303
+ let current = appRoot;
304
+ for (; ; ) {
305
+ const installed = path.join(current, "node_modules", name, "package.json");
306
+ if (fs.existsSync(installed)) {
307
+ const info = readPackage(installed);
308
+ const version = info?.deps.version ?? readVersionField(installed);
309
+ const installedParsed = parseVersion(version);
310
+ if (installedParsed && version)
311
+ return { raw: version, parsed: installedParsed };
312
+ }
313
+ const parent = path.dirname(current);
314
+ if (parent === current)
315
+ break;
316
+ current = parent;
317
+ }
318
+ return { raw: "unknown", parsed: void 0 };
319
+ }
320
+ function trimRange(range) {
321
+ const match = range.match(/(\d+\.\d+(?:\.\d+)?)/);
322
+ return match ? match[1] : range;
323
+ }
324
+ function readVersionField(file) {
325
+ try {
326
+ const json = JSON.parse(fs.readFileSync(file, "utf8"));
327
+ return json.version;
328
+ } catch {
329
+ return void 0;
330
+ }
331
+ }
332
+ function readPackage(file) {
333
+ try {
334
+ const json = JSON.parse(fs.readFileSync(file, "utf8"));
335
+ return {
336
+ name: json.name,
337
+ deps: { ...json.dependencies ?? {}, ...json.devDependencies ?? {}, ...json.version ? { version: json.version } : {} }
338
+ };
339
+ } catch {
340
+ return void 0;
341
+ }
342
+ }
343
+ function readWorkspaces(file) {
344
+ try {
345
+ const json = JSON.parse(fs.readFileSync(file, "utf8"));
346
+ if (!json.workspaces)
347
+ return void 0;
348
+ if (Array.isArray(json.workspaces))
349
+ return json.workspaces;
350
+ return json.workspaces.packages;
351
+ } catch {
352
+ return void 0;
353
+ }
354
+ }
355
+ function readWorkspaceGlobs(repoRoot) {
356
+ const file = path.join(repoRoot, "package.json");
357
+ return fs.existsSync(file) ? readWorkspaces(file) ?? [] : [];
358
+ }
359
+ function readPnpmGlobs(file) {
360
+ if (!fs.existsSync(file))
361
+ return [];
362
+ const globs = [];
363
+ let inPackages = false;
364
+ for (const line of fs.readFileSync(file, "utf8").split(/\r?\n/)) {
365
+ if (/^packages\s*:/.test(line)) {
366
+ inPackages = true;
367
+ continue;
368
+ }
369
+ if (!inPackages)
370
+ continue;
371
+ const match = line.match(/^\s*-\s*["']?([^"'#]+?)["']?\s*$/);
372
+ if (match)
373
+ globs.push(match[1].trim());
374
+ else if (line.trim() && !line.trim().startsWith("#"))
375
+ inPackages = false;
376
+ }
377
+ return globs;
378
+ }
379
+ function readAngularProjects(file) {
380
+ if (!fs.existsSync(file))
381
+ return [];
382
+ try {
383
+ const json = JSON.parse(fs.readFileSync(file, "utf8"));
384
+ return Object.values(json.projects ?? {}).map((project) => project.root ?? "").filter((root) => root !== "");
385
+ } catch {
386
+ return [];
387
+ }
388
+ }
389
+ function expandGlob(repoRoot, glob, into) {
390
+ const normalized = glob.replaceAll("\\", "/").replace(/\/package\.json$/, "");
391
+ const parts = normalized.split("/");
392
+ walkGlob(repoRoot, parts, into);
393
+ }
394
+ function walkGlob(directory, parts, into) {
395
+ if (!fs.existsSync(directory))
396
+ return;
397
+ if (parts.length === 0) {
398
+ const file = path.join(directory, "package.json");
399
+ if (fs.existsSync(file))
400
+ into.add(file);
401
+ return;
402
+ }
403
+ const [head, ...rest] = parts;
404
+ if (head === "**" || head === "*") {
405
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
406
+ if (!entry.isDirectory() || entry.name === "node_modules")
407
+ continue;
408
+ walkGlob(path.join(directory, entry.name), rest, into);
409
+ if (head === "**")
410
+ walkGlob(path.join(directory, entry.name), parts, into);
411
+ }
412
+ return;
413
+ }
414
+ walkGlob(path.join(directory, head), rest, into);
415
+ }
416
+ function collectPackages(directory, into, depth) {
417
+ if (depth < 0 || !fs.existsSync(directory))
418
+ return;
419
+ const own = path.join(directory, "package.json");
420
+ if (fs.existsSync(own))
421
+ into.add(own);
422
+ if (depth === 0)
423
+ return;
424
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
425
+ if (!entry.isDirectory() || entry.name === "node_modules" || entry.name.startsWith("."))
426
+ continue;
427
+ collectPackages(path.join(directory, entry.name), into, depth - 1);
428
+ }
429
+ }
430
+ var FRAMEWORKS, LIBRARIES, CHILD_DIRS, FRAMEWORK_LABELS, LIBRARY_LABELS;
431
+ var init_discover = __esm({
432
+ "packages/core/dist/discover.js"() {
433
+ "use strict";
434
+ init_version();
435
+ FRAMEWORKS = {
436
+ react: "react",
437
+ "react-native": "react-native",
438
+ next: "next",
439
+ "@angular/core": "angular",
440
+ vue: "vue",
441
+ nuxt: "nuxt",
442
+ svelte: "svelte"
443
+ };
444
+ LIBRARIES = {
445
+ rxjs: "rxjs",
446
+ "@ngrx/store": "ngrx",
447
+ "@reduxjs/toolkit": "redux",
448
+ "@tanstack/react-query": "tanstack-query",
449
+ "@tanstack/vue-query": "tanstack-query",
450
+ "@tanstack/angular-query-experimental": "tanstack-query",
451
+ lodash: "lodash",
452
+ moment: "moment"
453
+ };
454
+ CHILD_DIRS = ["apps", "packages", "projects", "libs"];
455
+ FRAMEWORK_LABELS = [
456
+ ["angular", "@angular/core", "Angular"],
457
+ ["react-native", "react-native", "React Native"],
458
+ ["next", "next", "Next.js"],
459
+ ["nuxt", "nuxt", "Nuxt"],
460
+ ["vue", "vue", "Vue"],
461
+ ["svelte", "svelte", "Svelte"],
462
+ ["react", "react", "React"]
463
+ ];
464
+ LIBRARY_LABELS = [
465
+ ["rxjs", "rxjs", "RxJS"],
466
+ ["ngrx", "@ngrx/store", "NgRx"],
467
+ ["redux", "@reduxjs/toolkit", "Redux Toolkit"],
468
+ ["tanstack-query", "@tanstack/react-query", "TanStack Query"],
469
+ ["lodash", "lodash", "lodash"],
470
+ ["moment", "moment", "Moment"]
471
+ ];
472
+ }
473
+ });
474
+
475
+ // packages/core/dist/fix.js
476
+ import fs2 from "node:fs";
477
+ import path2 from "node:path";
478
+ function applySafeFixes(source) {
479
+ let text = source.replace(/<a\b[^>]*>/gi, fixAnchor);
480
+ const lines = text.split(/\r?\n/);
481
+ let removed = false;
482
+ const next = lines.filter((line) => {
483
+ if (line.trim() === "debugger;") {
484
+ removed = true;
485
+ return false;
486
+ }
487
+ return true;
488
+ });
489
+ if (removed)
490
+ text = next.join("\n");
491
+ return { text, changed: text !== source };
492
+ }
493
+ function ensureAuditGitignore(repoRoot) {
494
+ const file = path2.join(repoRoot, ".gitignore");
495
+ const entry = ".frontend-audit/";
496
+ const current = fs2.existsSync(file) ? fs2.readFileSync(file, "utf8") : "";
497
+ if (current.split(/\r?\n/).some((line) => line.trim() === entry || line.trim() === ".frontend-audit"))
498
+ return false;
499
+ const suffix = current.length > 0 && !current.endsWith("\n") ? "\n" : "";
500
+ fs2.writeFileSync(file, `${current}${suffix}${entry}
501
+ `);
502
+ return true;
503
+ }
504
+ function fixAnchor(tag) {
505
+ if (!/target\s*=\s*["']_blank["']/.test(tag) || /noopener/.test(tag))
506
+ return tag;
507
+ if (/rel\s*=\s*"([^"]*)"/.test(tag)) {
508
+ return tag.replace(/rel\s*=\s*"([^"]*)"/, (_full, rel) => `rel="${mergeRel(rel)}"`);
509
+ }
510
+ if (/rel\s*=\s*'([^']*)'/.test(tag)) {
511
+ return tag.replace(/rel\s*=\s*'([^']*)'/, (_full, rel) => `rel="${mergeRel(rel)}"`);
512
+ }
513
+ return tag.replace(/>$/, ' rel="noopener noreferrer">');
514
+ }
515
+ function mergeRel(rel) {
516
+ const parts = new Set(rel.split(/\s+/).filter(Boolean));
517
+ parts.add("noopener");
518
+ parts.add("noreferrer");
519
+ return [...parts].join(" ");
520
+ }
521
+ var init_fix = __esm({
522
+ "packages/core/dist/fix.js"() {
523
+ "use strict";
524
+ }
525
+ });
526
+
527
+ // packages/core/dist/ignore.js
528
+ import fs3 from "node:fs";
529
+ import path3 from "node:path";
530
+ function loadIgnore(repoRoot) {
531
+ const file = path3.join(repoRoot, "frontend-audit.ignore");
532
+ if (!fs3.existsSync(file))
533
+ return [];
534
+ const rules = [];
535
+ for (const line of fs3.readFileSync(file, "utf8").split(/\r?\n/)) {
536
+ const trimmed = line.trim();
537
+ if (!trimmed || trimmed.startsWith("#"))
538
+ continue;
539
+ const [id, ...rest] = trimmed.split(/\s+/);
540
+ rules.push(rest.length > 0 ? { id, glob: rest.join(" ") } : { id });
541
+ }
542
+ return rules;
543
+ }
544
+ function isIgnored(rules, ruleId, relativeFile) {
545
+ const file = relativeFile.replaceAll("\\", "/");
546
+ return rules.some((rule) => (rule.id === ruleId || rule.id === "*") && (!rule.glob || matchGlob(rule.glob, file)));
547
+ }
548
+ function matchGlob(glob, file) {
549
+ const source = glob.replaceAll("\\", "/");
550
+ let pattern = "";
551
+ for (let index = 0; index < source.length; index += 1) {
552
+ const char = source[index];
553
+ if (char === "*" && source[index + 1] === "*") {
554
+ pattern += ".*";
555
+ index += 1;
556
+ if (source[index + 1] === "/")
557
+ index += 1;
558
+ continue;
559
+ }
560
+ if (char === "*") {
561
+ pattern += "[^/]*";
562
+ continue;
563
+ }
564
+ pattern += /[.+^${}()|[\]\\]/.test(char) ? `\\${char}` : char;
565
+ }
566
+ return new RegExp(`^${pattern}$`).test(file);
567
+ }
568
+ var init_ignore = __esm({
569
+ "packages/core/dist/ignore.js"() {
570
+ "use strict";
571
+ }
572
+ });
573
+
574
+ // packages/core/dist/limits.js
575
+ var BLIND_SPOTS, DEFAULT_BUDGET_MS, QUICK_BUDGET_MS, QUICK_MAX_FILES, DEFAULT_CHROME_PORT;
576
+ var init_limits = __esm({
577
+ "packages/core/dist/limits.js"() {
578
+ "use strict";
579
+ BLIND_SPOTS = [
580
+ "It does not check known-vulnerable npm packages.",
581
+ "It does not time backend APIs except for calls visible on the open Chrome tab.",
582
+ "It does not find memory leaks that are not an obvious missed teardown.",
583
+ "It does not find security bugs outside the known browser sinks in the playbook.",
584
+ "It does not fail CI on new findings."
585
+ ];
586
+ DEFAULT_BUDGET_MS = 5 * 60 * 1e3;
587
+ QUICK_BUDGET_MS = 60 * 1e3;
588
+ QUICK_MAX_FILES = 1500;
589
+ DEFAULT_CHROME_PORT = 9222;
590
+ }
591
+ });
592
+
593
+ // packages/core/dist/lighthouse.js
594
+ async function runLighthouse(url, port, categories, remainingMs) {
595
+ const [major, minor] = process.versions.node.split(".").map(Number);
596
+ if (major < 22 || major === 22 && minor < 19) {
597
+ return { info: { ran: false, detail: `Lighthouse needs Node 22.19 or newer. This is Node ${process.versions.node}.` }, drafts: [] };
598
+ }
599
+ if (remainingMs < 6e4) {
600
+ return { info: { ran: false, detail: "Lighthouse was skipped because less than 60 seconds remained in the budget." }, drafts: [] };
601
+ }
602
+ try {
603
+ const imported = await import("lighthouse").catch(() => {
604
+ throw new Error("the lighthouse package is not installed");
605
+ });
606
+ const lighthouse = imported.default;
607
+ if (!lighthouse)
608
+ throw new Error("Lighthouse did not load");
609
+ const result = await lighthouse(url, { port, logLevel: "error", output: "json" }, {
610
+ extends: "lighthouse:default",
611
+ settings: { onlyCategories: categories }
612
+ });
613
+ const audits = result.lhr?.audits ?? {};
614
+ const drafts = [];
615
+ for (const audit of Object.values(audits)) {
616
+ if (audit.score === null || audit.score === void 0 || audit.score >= 0.9)
617
+ continue;
618
+ if (audit.scoreDisplayMode === "informative" || audit.scoreDisplayMode === "manual" || audit.scoreDisplayMode === "notApplicable")
619
+ continue;
620
+ const description = strip(audit.description ?? "");
621
+ drafts.push({
622
+ ruleId: "lighthouse.opportunity",
623
+ line: 1,
624
+ detail: `${audit.title ?? "Lighthouse"}: ${description}`.slice(0, 500)
625
+ });
626
+ if (drafts.length >= 15)
627
+ break;
628
+ }
629
+ return { info: { ran: true, detail: `Lighthouse ran on ${url}.` }, drafts };
630
+ } catch (error) {
631
+ const message = error instanceof Error ? error.message : "Lighthouse failed";
632
+ return { info: { ran: false, detail: `Lighthouse did not finish: ${message}` }, drafts: [] };
633
+ }
634
+ }
635
+ function strip(value) {
636
+ return value.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1").replace(/<[^>]+>/g, "");
637
+ }
638
+ var init_lighthouse = __esm({
639
+ "packages/core/dist/lighthouse.js"() {
640
+ "use strict";
641
+ }
642
+ });
643
+
644
+ // packages/core/dist/playbook.js
645
+ var react, playbook;
646
+ var init_playbook = __esm({
647
+ "packages/core/dist/playbook.js"() {
648
+ "use strict";
649
+ react = ["react", "next", "react-native"];
650
+ playbook = [
651
+ {
652
+ id: "react.effect-state-loop",
653
+ stacks: react,
654
+ category: "performance",
655
+ severity: "high",
656
+ safety: "assist",
657
+ headline: true,
658
+ title: "Effect updates state it depends on",
659
+ why: "The effect writes state that is also in its dependency list, so every commit schedules another run and the page keeps rendering.",
660
+ fix: "Derive the value during render, or move the write outside the effect. If the effect must sync with an external system, do not put the state you set into the dependency list.",
661
+ docs: [{ title: "You Might Not Need an Effect", url: "https://react.dev/learn/you-might-not-need-an-effect" }],
662
+ plan: [
663
+ "Find the setState call inside the effect and the dependency that matches it.",
664
+ "Compute that value while rendering, or trigger it from the event that owns the change.",
665
+ "Confirm the component commits once for the interaction, not once per frame."
666
+ ]
667
+ },
668
+ {
669
+ id: "react.render-fetch",
670
+ stacks: ["react", "next"],
671
+ category: "performance",
672
+ severity: "high",
673
+ safety: "assist",
674
+ headline: true,
675
+ title: "Network request runs during render",
676
+ why: "A fetch that runs in the component body starts again on every render and races itself.",
677
+ fix: "Move the request into a data library with a cache, or into an effect that depends on the real inputs. In Next.js, prefer a server fetch or a route handler over a client fetch when the data does not depend on the browser.",
678
+ docs: [
679
+ { title: "useEffect", url: "https://react.dev/reference/react/useEffect" },
680
+ { title: "Next.js data fetching", url: "https://nextjs.org/docs/app/building-your-application/data-fetching" }
681
+ ],
682
+ plan: [
683
+ "Remove the fetch from the render path.",
684
+ "Give the request a cache key and a stale time if many components need the same data.",
685
+ "Render a loading state from that cache instead of calling the network while painting."
686
+ ]
687
+ },
688
+ {
689
+ id: "react.context-identity",
690
+ stacks: ["react", "next"],
691
+ category: "performance",
692
+ severity: "medium",
693
+ safety: "assist",
694
+ headline: true,
695
+ title: "Context value is a new object every render",
696
+ why: "An inline object passed to a provider has a new identity each render, so every consumer renders again.",
697
+ fix: "Memoize the context value, or split fast-changing fields into their own provider.",
698
+ docs: [{ title: "Optimizing re-renders when passing objects", url: "https://react.dev/reference/react/useContext" }],
699
+ plan: [
700
+ "Find the provider whose value={{ ... }} sits in the render path.",
701
+ "Wrap that object in useMemo with the fields it actually depends on.",
702
+ "Move rapidly changing state out of a provider that wraps a large tree."
703
+ ]
704
+ },
705
+ {
706
+ id: "react.missing-key",
707
+ stacks: ["react", "next"],
708
+ category: "performance",
709
+ severity: "medium",
710
+ safety: "assist",
711
+ headline: true,
712
+ title: "List render is missing a key",
713
+ why: "Without a stable key, React reuses the wrong child state and does extra DOM work when the list changes.",
714
+ fix: "Pass key={item.id} using an id from the data. Do not use the array index when the list can be reordered, filtered, or inserted into.",
715
+ docs: [{ title: "Rendering lists", url: "https://react.dev/learn/rendering-lists" }],
716
+ plan: [
717
+ "Use a stable id from the item as the key.",
718
+ "Keep the key on the element returned from map, not on a child inside it."
719
+ ]
720
+ },
721
+ {
722
+ id: "react.virtualize",
723
+ stacks: ["react", "next", "react-native"],
724
+ category: "performance",
725
+ severity: "medium",
726
+ safety: "assist",
727
+ headline: true,
728
+ advisory: true,
729
+ title: "Long lists should render only the visible rows",
730
+ why: "Mapping a large collection into the DOM or into native views creates thousands of nodes and slows scroll and the first paint.",
731
+ fix: "Window the list. On the web use a virtualizer. In React Native use FlatList or FlashList with a stable key.",
732
+ docs: [{ title: "React Native FlatList", url: "https://reactnative.dev/docs/flatlist" }],
733
+ plan: [
734
+ "Measure how many rows the screen actually shows.",
735
+ "Render only that window plus a small overscan.",
736
+ "Give each row a stable key and avoid inline objects in the row render."
737
+ ]
738
+ },
739
+ {
740
+ id: "react.manual-memo",
741
+ stacks: ["react", "next"],
742
+ category: "performance",
743
+ severity: "low",
744
+ safety: "assist",
745
+ headline: true,
746
+ versionOf: "react",
747
+ since: [19, 0, 0],
748
+ onUnknown: "no",
749
+ title: "Manual memo on React 19",
750
+ why: "React 19 projects often already run the React Compiler, which memoizes components and values. Extra useMemo and memo calls add noise and can hide a real render problem.",
751
+ fix: "Turn on the React Compiler and remove hand-written memoization that only exists to cache a render. Keep useMemo when you are memoizing a costly calculation the compiler cannot see.",
752
+ docs: [{ title: "React Compiler", url: "https://react.dev/learn/react-compiler" }],
753
+ plan: [
754
+ "Check whether the React Compiler is enabled for this app.",
755
+ "Profile the component before adding memo, useMemo, or useCallback.",
756
+ "Delete memoization that the compiler already covers."
757
+ ]
758
+ },
759
+ {
760
+ id: "next.img-element",
761
+ stacks: ["next"],
762
+ category: "performance",
763
+ severity: "medium",
764
+ safety: "assist",
765
+ headline: true,
766
+ title: "Image is a raw img element",
767
+ why: "A plain img skips Next.js resizing, modern formats, and reserved space, so the page layout shifts and the download is larger than it needs to be.",
768
+ fix: "Use the next/image component, set width and height or fill, and keep remote hosts in images.remotePatterns.",
769
+ docs: [{ title: "next/image", url: "https://nextjs.org/docs/app/getting-started/images" }],
770
+ plan: [
771
+ "Replace img with Image from next/image.",
772
+ "Set the displayed size so the browser can reserve space.",
773
+ "Allow the image host in next.config if the file is remote."
774
+ ]
775
+ },
776
+ {
777
+ id: "next.client-heavy-import",
778
+ stacks: ["next"],
779
+ category: "performance",
780
+ severity: "medium",
781
+ safety: "assist",
782
+ headline: true,
783
+ title: "Client component imports a heavy package",
784
+ why: "A use client file sends every import to the browser. Lodash, Moment, and chart packages are large enough to dominate the route bundle.",
785
+ fix: "Import only the function you call, or load the widget with next/dynamic on the client and keep the page shell as a server component.",
786
+ docs: [{ title: "Client components", url: "https://nextjs.org/docs/app/building-your-application/rendering/client-components" }],
787
+ plan: [
788
+ "Move the heavy import out of the shared client module.",
789
+ "Load it with next/dynamic and ssr: false only if it needs the browser.",
790
+ "Prefer a per-method import when you need a single utility."
791
+ ]
792
+ },
793
+ {
794
+ id: "next.dynamic-import",
795
+ stacks: ["next"],
796
+ category: "performance",
797
+ severity: "low",
798
+ safety: "assist",
799
+ headline: true,
800
+ advisory: true,
801
+ title: "Heavy client widgets should load with next/dynamic",
802
+ why: "Charts, editors, and maps do not need to be in the first JavaScript download for the route.",
803
+ fix: "Load those widgets with next/dynamic so the route shell paints first.",
804
+ docs: [{ title: "next/dynamic", url: "https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading" }],
805
+ plan: [
806
+ "Identify client-only widgets on the route.",
807
+ "Wrap each one in next/dynamic.",
808
+ "Give the dynamic import a small loading placeholder."
809
+ ]
810
+ },
811
+ {
812
+ id: "angular.template-call",
813
+ stacks: ["angular"],
814
+ category: "performance",
815
+ severity: "high",
816
+ safety: "assist",
817
+ headline: true,
818
+ title: "Template calls a function on every change-detection pass",
819
+ why: "Angular runs template expressions on every change-detection cycle. A function call there repeats work for the whole view.",
820
+ fix: "Bind to a field, a pure pipe, or a signal. Compute the value when the inputs change, not inside the template.",
821
+ docs: [{ title: "Angular runtime performance", url: "https://angular.dev/best-practices/runtime-performance" }],
822
+ plan: [
823
+ "Replace {{ getValue() }} and property bindings that call methods.",
824
+ "Store the result in a field or a computed signal.",
825
+ "Keep pipes pure so Angular can skip them when inputs are unchanged."
826
+ ]
827
+ },
828
+ {
829
+ id: "angular.list-track",
830
+ stacks: ["angular"],
831
+ category: "performance",
832
+ severity: "medium",
833
+ safety: "assist",
834
+ headline: true,
835
+ versionOf: "@angular/core",
836
+ until: [17, 0, 0],
837
+ onUnknown: "no",
838
+ title: "ngFor is missing trackBy",
839
+ why: "Without trackBy, Angular destroys and recreates every row when the collection identity changes.",
840
+ fix: "Add trackBy to *ngFor and return a stable id from the item. Add trackBy: identity only as a last resort when the row has no id.",
841
+ docs: [{ title: "Angular template control flow", url: "https://angular.dev/guide/templates/control-flow" }],
842
+ plan: [
843
+ "Add a trackBy method that returns the item id.",
844
+ "Pass it as trackBy: trackById on the *ngFor.",
845
+ "Avoid tracking by the object index when rows move."
846
+ ]
847
+ },
848
+ {
849
+ id: "angular.list-track",
850
+ stacks: ["angular"],
851
+ category: "performance",
852
+ severity: "medium",
853
+ safety: "assist",
854
+ headline: true,
855
+ versionOf: "@angular/core",
856
+ since: [17, 0, 0],
857
+ title: "List is missing a track identity",
858
+ why: "Angular cannot reuse row DOM when a list has no track expression, so updates repaint every row.",
859
+ fix: "Use @for (item of items; track item.id). If a template still uses *ngFor, add trackBy as well, then move it to @for.",
860
+ docs: [{ title: "@for track", url: "https://angular.dev/guide/templates/control-flow" }],
861
+ plan: [
862
+ "Rewrite *ngFor loops to @for with a track expression.",
863
+ "Track a stable id, not the loop index, when rows can move.",
864
+ "Leave the collection itself immutable so the track id stays meaningful."
865
+ ]
866
+ },
867
+ {
868
+ id: "angular.change-detection",
869
+ stacks: ["angular"],
870
+ category: "performance",
871
+ severity: "medium",
872
+ safety: "assist",
873
+ headline: true,
874
+ advisory: true,
875
+ title: "Hot components should skip wasted change detection",
876
+ why: "The default strategy checks a component whenever anything in the tree might have changed. Hot lists and widgets pay for that on every event.",
877
+ fix: "Use ChangeDetectionStrategy.OnPush or signals for components whose inputs are the only reason to render.",
878
+ docs: [{ title: "Skip unnecessary change detection", url: "https://angular.dev/best-practices/runtime-performance" }],
879
+ plan: [
880
+ "Mark presentational components OnPush.",
881
+ "Feed them inputs or signals instead of reading mutable services during the check.",
882
+ "Profile a scroll or click and confirm the hot component is skipped."
883
+ ]
884
+ },
885
+ {
886
+ id: "angular.defer-import",
887
+ stacks: ["angular"],
888
+ category: "performance",
889
+ severity: "low",
890
+ safety: "assist",
891
+ headline: true,
892
+ advisory: true,
893
+ versionOf: "@angular/core",
894
+ since: [17, 0, 0],
895
+ title: "Heavy views can be deferred",
896
+ why: "Importing a large component into the eager route pulls it into the first bundle even when the user has not opened that part of the page.",
897
+ fix: "Use @defer for below-the-fold or rarely used views, or load the route with loadComponent.",
898
+ docs: [{ title: "Deferred loading", url: "https://angular.dev/guide/templates/defer" }],
899
+ plan: [
900
+ "Find components that are not visible on first paint.",
901
+ "Wrap them in @defer with a placeholder.",
902
+ "Keep the eager route limited to the shell and the first view."
903
+ ]
904
+ },
905
+ {
906
+ id: "angular.subscribe-leak",
907
+ stacks: ["angular"],
908
+ category: "performance",
909
+ severity: "high",
910
+ safety: "assist",
911
+ headline: true,
912
+ title: "Subscription is never torn down",
913
+ why: "A component that subscribes and never unsubscribes keeps the callback alive after the view is gone and can repeat work on every emission.",
914
+ fix: "Prefer the async pipe or takeUntilDestroyed. If you subscribe by hand, unsubscribe in ngOnDestroy.",
915
+ docs: [{ title: "RxJS subscription", url: "https://rxjs.dev/guide/subscription" }],
916
+ plan: [
917
+ "Replace the subscribe with an async pipe where the template can own it.",
918
+ "Otherwise add takeUntilDestroyed() inside an injection context.",
919
+ "Confirm the callback stops after the component is destroyed."
920
+ ]
921
+ },
922
+ {
923
+ id: "vue.watch-self",
924
+ stacks: ["vue", "nuxt"],
925
+ category: "performance",
926
+ severity: "high",
927
+ safety: "assist",
928
+ headline: true,
929
+ title: "Watcher writes the source it watches",
930
+ why: "The watcher updates the same ref it depends on, so the flush schedules itself again.",
931
+ fix: "Write a computed value, or watch a different source than the one you assign.",
932
+ docs: [{ title: "Vue watchers", url: "https://vuejs.org/guide/essentials/watchers.html" }],
933
+ plan: [
934
+ "Stop assigning to the watched ref inside its callback.",
935
+ "Move the derived value to computed.",
936
+ "If this is a one-time sync, watch once or gate the write with a comparison."
937
+ ]
938
+ },
939
+ {
940
+ id: "vue.v-for-key",
941
+ stacks: ["vue", "nuxt"],
942
+ category: "performance",
943
+ severity: "medium",
944
+ safety: "assist",
945
+ headline: true,
946
+ title: "v-for is missing a key",
947
+ why: "Vue reuses DOM nodes by position when a v-for has no key, so row state sticks to the wrong item.",
948
+ fix: 'Add :key="item.id" on the v-for element. Use a stable id, not the index, when the list can change order.',
949
+ docs: [{ title: "List rendering", url: "https://vuejs.org/guide/essentials/list.html" }],
950
+ plan: [
951
+ "Put :key on the same element as v-for.",
952
+ "Key by a stable id from the item."
953
+ ]
954
+ },
955
+ {
956
+ id: "vue.deep-watch",
957
+ stacks: ["vue", "nuxt"],
958
+ category: "performance",
959
+ severity: "low",
960
+ safety: "assist",
961
+ headline: true,
962
+ title: "Deep watch walks a large object",
963
+ why: "deep: true traverses the whole object on every change. On a large store or list that work shows up as long tasks.",
964
+ fix: "Watch a specific field or a computed slice instead of the whole object.",
965
+ docs: [{ title: "Deep watchers", url: "https://vuejs.org/guide/essentials/watchers.html#deep-watchers" }],
966
+ plan: [
967
+ "Replace the deep watch with a watch of the one field that matters.",
968
+ "If you need a collection, watch a computed list of ids."
969
+ ]
970
+ },
971
+ {
972
+ id: "nuxt.plugin-component",
973
+ stacks: ["nuxt"],
974
+ category: "performance",
975
+ severity: "medium",
976
+ safety: "assist",
977
+ headline: true,
978
+ title: "Plugin imports a Vue component",
979
+ why: "A Nuxt plugin runs for the app shell. Importing a page component there pulls client UI into every request.",
980
+ fix: "Keep components out of plugins. Load heavy UI inside the page, and mark browser-only widgets with ClientOnly or a Lazy component.",
981
+ docs: [{ title: "Nuxt plugins", url: "https://nuxt.com/docs/guide/directory-structure/plugins" }],
982
+ plan: [
983
+ "Move the component import from the plugin into the page that renders it.",
984
+ "Wrap browser-only UI in ClientOnly."
985
+ ]
986
+ },
987
+ {
988
+ id: "svelte.reactive-loop",
989
+ stacks: ["svelte"],
990
+ category: "performance",
991
+ severity: "high",
992
+ safety: "assist",
993
+ headline: true,
994
+ title: "Reactive statement writes its own input",
995
+ why: "A reactive statement that assigns the variable it reads invalidates itself and runs again.",
996
+ fix: "Assign a different variable, or compute the value in a function that is not reactive on its own output.",
997
+ docs: [{ title: "Svelte reactive statements", url: "https://svelte.dev/docs/svelte/legacy-reactive-assignments" }],
998
+ plan: [
999
+ "Split the input and the derived value into two names.",
1000
+ "Stop writing the input from the statement that reads it."
1001
+ ]
1002
+ },
1003
+ {
1004
+ id: "svelte.each-key",
1005
+ stacks: ["svelte"],
1006
+ category: "performance",
1007
+ severity: "medium",
1008
+ safety: "assist",
1009
+ headline: true,
1010
+ title: "Each block is missing a key",
1011
+ why: "Without a key, Svelte reuses blocks by index and loses per-item state when the list changes.",
1012
+ fix: "Write {#each items as item (item.id)} with a stable id.",
1013
+ docs: [{ title: "Each blocks", url: "https://svelte.dev/docs/svelte/each" }],
1014
+ plan: [
1015
+ "Add a parenthesized key after the each binding.",
1016
+ "Use a stable id from the item."
1017
+ ]
1018
+ },
1019
+ {
1020
+ id: "rn.scrollview-list",
1021
+ stacks: ["react-native"],
1022
+ category: "performance",
1023
+ severity: "high",
1024
+ safety: "assist",
1025
+ headline: true,
1026
+ title: "Long list is rendered inside ScrollView",
1027
+ why: "ScrollView mounts every child at once. A mapped data set becomes hundreds of native views and a slow first paint.",
1028
+ fix: "Render long data with FlatList or FlashList. Keep ScrollView for a short, fixed layout.",
1029
+ docs: [{ title: "Optimizing FlatList", url: "https://reactnative.dev/docs/optimizing-flatlist-configuration" }],
1030
+ plan: [
1031
+ "Replace the ScrollView plus map with FlatList.",
1032
+ "Set keyExtractor to a stable id.",
1033
+ "Move row state out of the parent so rows do not all render together."
1034
+ ]
1035
+ },
1036
+ {
1037
+ id: "rn.inline-style",
1038
+ stacks: ["react-native"],
1039
+ category: "performance",
1040
+ severity: "low",
1041
+ safety: "assist",
1042
+ headline: true,
1043
+ title: "List row gets a new style object while rendering",
1044
+ why: "An inline style object is a new reference every render, so a virtualized row looks dirty even when its data did not change.",
1045
+ fix: "Move the style to StyleSheet.create, or pass a stable style reference into the row.",
1046
+ docs: [{ title: "StyleSheet", url: "https://reactnative.dev/docs/stylesheet" }],
1047
+ plan: [
1048
+ "Create the style once with StyleSheet.create.",
1049
+ "Pass data into a memoized row component.",
1050
+ "Keep renderItem from allocating objects the row does not need."
1051
+ ]
1052
+ },
1053
+ {
1054
+ id: "rn.image-size",
1055
+ stacks: ["react-native"],
1056
+ category: "performance",
1057
+ severity: "low",
1058
+ safety: "assist",
1059
+ headline: true,
1060
+ advisory: true,
1061
+ title: "Remote images need an explicit size",
1062
+ why: "A remote image without width and height cannot reserve space, and the full-resolution file is decoded on the JS and UI threads.",
1063
+ fix: "Set width and height, and request a resized image from the server when the source is large.",
1064
+ docs: [{ title: "Image", url: "https://reactnative.dev/docs/image" }],
1065
+ plan: [
1066
+ "Set a numeric width and height on the Image.",
1067
+ "Ask the API for a size close to the displayed size."
1068
+ ]
1069
+ },
1070
+ {
1071
+ id: "rxjs.nested-subscribe",
1072
+ stacks: ["rxjs", "angular"],
1073
+ category: "performance",
1074
+ severity: "high",
1075
+ safety: "assist",
1076
+ headline: true,
1077
+ title: "Nested subscribe",
1078
+ why: "A subscribe inside another subscribe starts a new inner subscription on every outer emission and drops errors and cancellation on the floor.",
1079
+ fix: "Use an operator such as switchMap, concatMap, or exhaustMap, and subscribe once at the edge.",
1080
+ docs: [{ title: "RxJS subscription", url: "https://rxjs.dev/guide/subscription" }],
1081
+ plan: [
1082
+ "Replace the inner subscribe with switchMap or concatMap.",
1083
+ "Keep a single subscribe, or use the async pipe.",
1084
+ "Make sure unsubscribing the outer observable cancels the inner request."
1085
+ ]
1086
+ },
1087
+ {
1088
+ id: "rxjs.missing-teardown",
1089
+ stacks: ["rxjs"],
1090
+ category: "performance",
1091
+ severity: "high",
1092
+ safety: "assist",
1093
+ headline: true,
1094
+ title: "Observable subscription has no teardown",
1095
+ why: "Without unsubscribe, takeUntil, or firstValueFrom, the subscription stays active after the caller is gone.",
1096
+ fix: "Unsubscribe when the owner is destroyed, or convert a one-shot observable with firstValueFrom.",
1097
+ docs: [{ title: "RxJS subscription", url: "https://rxjs.dev/guide/subscription" }],
1098
+ plan: [
1099
+ "Decide whether the stream is one-shot or long-lived.",
1100
+ "Use firstValueFrom for one-shot work.",
1101
+ "Tear down long-lived subscriptions with the owner's destroy signal."
1102
+ ]
1103
+ },
1104
+ {
1105
+ id: "ngrx.select-store",
1106
+ stacks: ["ngrx"],
1107
+ category: "performance",
1108
+ severity: "medium",
1109
+ safety: "assist",
1110
+ headline: true,
1111
+ title: "Selector returns the whole store",
1112
+ why: "Selecting the root state emits on every dispatch, so every subscriber renders even when its slice did not change.",
1113
+ fix: "Select the smallest slice, and use a memoized createSelector when the view model is derived.",
1114
+ docs: [{ title: "NgRx selectors", url: "https://ngrx.io/guide/store/selectors" }],
1115
+ plan: [
1116
+ "Replace store.select(state => state) with a feature selector.",
1117
+ "Build derived data with createSelector.",
1118
+ "Keep selectors pure so memoization works."
1119
+ ]
1120
+ },
1121
+ {
1122
+ id: "redux.selector-object",
1123
+ stacks: ["redux"],
1124
+ category: "performance",
1125
+ severity: "medium",
1126
+ safety: "assist",
1127
+ headline: true,
1128
+ title: "useSelector returns a new object",
1129
+ why: "useSelector uses reference equality. Returning a fresh object selects a new value on every run and forces a render.",
1130
+ fix: "Select primitive fields separately, or pass a shallowEqual comparator when the result is a view model object.",
1131
+ docs: [{ title: "useSelector equality", url: "https://react-redux.js.org/api/hooks#equality-comparisons-and-updates" }],
1132
+ plan: [
1133
+ "Split the selector into one field per useSelector, or memoize the object.",
1134
+ "If the object is intentional, pass shallowEqual as the second argument."
1135
+ ]
1136
+ },
1137
+ {
1138
+ id: "tanstack.no-staletime",
1139
+ stacks: ["tanstack-query"],
1140
+ category: "performance",
1141
+ severity: "medium",
1142
+ safety: "assist",
1143
+ headline: true,
1144
+ title: "Query has no staleTime",
1145
+ why: "The default stale time is zero, so every new mount refetches. A page that mounts the same query in several components fires a burst of identical requests.",
1146
+ fix: "Set staleTime for data that can be reused, and share one query key across those components.",
1147
+ docs: [{ title: "Important defaults", url: "https://tanstack.com/query/latest/docs/framework/react/guides/important-defaults" }],
1148
+ plan: [
1149
+ "Choose a staleTime that matches how fresh the data must be.",
1150
+ "Use the same query key everywhere that data is read.",
1151
+ "Leave staleTime at zero only for data that must refetch on every mount."
1152
+ ]
1153
+ },
1154
+ {
1155
+ id: "lodash.full-import",
1156
+ stacks: ["lodash"],
1157
+ category: "performance",
1158
+ severity: "medium",
1159
+ safety: "assist",
1160
+ headline: true,
1161
+ title: "Full lodash build is imported",
1162
+ why: 'import _ from "lodash" pulls the whole library into the client bundle when the file only needs one function.',
1163
+ fix: 'Import the function you call, for example import debounce from "lodash/debounce". Do not rewrite call sites automatically.',
1164
+ docs: [{ title: "Lodash per-method packages", url: "https://lodash.com/per-method-packages" }],
1165
+ plan: [
1166
+ "Replace the namespace import with the one method this file uses.",
1167
+ "Check the bundle for a remaining lodash entry."
1168
+ ]
1169
+ },
1170
+ {
1171
+ id: "moment.full-import",
1172
+ stacks: ["moment"],
1173
+ category: "performance",
1174
+ severity: "medium",
1175
+ safety: "assist",
1176
+ headline: true,
1177
+ title: "Moment is imported into client code",
1178
+ why: "Moment ships locales and a large core. A default import puts that weight in the browser bundle.",
1179
+ fix: "Switch the call site to a smaller date library, or ignore locales in the bundler if you must stay on Moment for now.",
1180
+ docs: [{ title: "Moment and webpack", url: "https://momentjs.com/docs/#/use-it/webpack/" }],
1181
+ plan: [
1182
+ "List the Moment calls in this file.",
1183
+ "Replace them with the date library the app already prefers, or drop unused locales in the bundler config."
1184
+ ]
1185
+ },
1186
+ {
1187
+ id: "security.dangerously-set-html",
1188
+ stacks: ["shared"],
1189
+ category: "security",
1190
+ severity: "high",
1191
+ safety: "assist",
1192
+ headline: true,
1193
+ title: "HTML is injected from a string",
1194
+ why: "dangerouslySetInnerHTML parses a string as HTML. If any part of that string comes from a user or an API, it is a cross-site scripting sink.",
1195
+ fix: "Render text as children, or sanitize with a reviewed library and a tight allowlist. Do not switch this automatically.",
1196
+ docs: [{ title: "dangerouslySetInnerHTML", url: "https://react.dev/reference/react-dom/components/common#dangerously-setting-the-inner-html" }],
1197
+ plan: [
1198
+ "Find where the HTML string is built.",
1199
+ "If it is plain text, render it as a child instead of HTML.",
1200
+ "If markup is required, sanitize it and cover the case with a test."
1201
+ ]
1202
+ },
1203
+ {
1204
+ id: "security.inner-html",
1205
+ stacks: ["shared"],
1206
+ category: "security",
1207
+ severity: "high",
1208
+ safety: "assist",
1209
+ headline: true,
1210
+ title: "innerHTML assignment",
1211
+ why: "Assigning innerHTML parses markup and runs in the page origin. It is a scripting sink when the string is not a constant you control.",
1212
+ fix: "Use textContent for text. If you need markup, sanitize it first. Leave the source unchanged until a person confirms the data is trusted.",
1213
+ docs: [{ title: "Element.innerHTML", url: "https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML" }],
1214
+ plan: [
1215
+ "Decide whether the value is text or HTML.",
1216
+ "Use textContent for text.",
1217
+ "Sanitize HTML and keep the allowlist next to the call."
1218
+ ]
1219
+ },
1220
+ {
1221
+ id: "security.eval",
1222
+ stacks: ["shared"],
1223
+ category: "security",
1224
+ severity: "high",
1225
+ safety: "assist",
1226
+ title: "eval executes a string",
1227
+ why: "eval runs its argument as code in the current scope. A string that includes user input is arbitrary code execution in the page.",
1228
+ fix: "Replace eval with a direct call or a JSON parser. Do not delete the call automatically, because the surrounding logic may depend on it.",
1229
+ docs: [{ title: "eval()", url: "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval" }],
1230
+ plan: [
1231
+ "Identify what the string is supposed to do.",
1232
+ "Replace it with JSON.parse for data, or with a normal function call for code.",
1233
+ "Remove the string-building path so it cannot grow back."
1234
+ ]
1235
+ },
1236
+ {
1237
+ id: "security.new-function",
1238
+ stacks: ["shared"],
1239
+ category: "security",
1240
+ severity: "high",
1241
+ safety: "assist",
1242
+ title: "new Function builds code from a string",
1243
+ why: "The Function constructor compiles a string at runtime. It has the same trust problem as eval.",
1244
+ fix: "Call a real function. Keep new Function only for a build step that never runs on user input, and say so next to the call.",
1245
+ docs: [{ title: "Function constructor", url: "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function" }],
1246
+ plan: [
1247
+ "Replace the constructor with a function written in source.",
1248
+ "If the string is a template from your build, move it out of client code."
1249
+ ]
1250
+ },
1251
+ {
1252
+ id: "security.bypass-trust",
1253
+ stacks: ["shared"],
1254
+ category: "security",
1255
+ severity: "high",
1256
+ safety: "assist",
1257
+ headline: true,
1258
+ title: "Angular security trust is bypassed",
1259
+ why: "bypassSecurityTrust* tells Angular the value is safe. If the value includes user or server HTML, the sanitizer will not protect the binding.",
1260
+ fix: "Drop the bypass and let Angular sanitize the binding. If you truly need raw HTML, sanitize first and call bypassSecurityTrustHtml only on the result. Do not remove the call automatically.",
1261
+ docs: [{ title: "Angular security", url: "https://angular.dev/best-practices/security" }],
1262
+ plan: [
1263
+ "Trace the value passed into the bypass call.",
1264
+ "Remove the bypass when the template can use a normal binding.",
1265
+ "When HTML is required, sanitize with an allowlist and add a test for a script payload."
1266
+ ]
1267
+ },
1268
+ {
1269
+ id: "security.postmessage",
1270
+ stacks: ["shared"],
1271
+ category: "security",
1272
+ severity: "medium",
1273
+ safety: "assist",
1274
+ title: "message listener does not check origin",
1275
+ why: "Any window that can get a reference to this page can send a message. Without an origin check, the handler trusts that data.",
1276
+ fix: "Return immediately unless event.origin is the exact origin you expect. Do not compare with indexOf or a partial string.",
1277
+ docs: [{ title: "Window.postMessage", url: "https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage" }],
1278
+ plan: [
1279
+ "List the origins that are allowed to talk to this page.",
1280
+ "Check event.origin against that list before reading event.data.",
1281
+ "Ignore messages that fail the check."
1282
+ ]
1283
+ },
1284
+ {
1285
+ id: "security.open-redirect",
1286
+ stacks: ["shared"],
1287
+ category: "security",
1288
+ severity: "high",
1289
+ safety: "assist",
1290
+ title: "Redirect target is not a fixed URL",
1291
+ why: "Assigning location from a parameter sends the user wherever that parameter points, including an attacker site.",
1292
+ fix: "Allow only relative paths you generate, or match the target against a list of known URLs. Never assign location from a raw query value.",
1293
+ docs: [{ title: "Location.href", url: "https://developer.mozilla.org/en-US/docs/Web/API/Location/href" }],
1294
+ plan: [
1295
+ "Find the source of the URL being assigned.",
1296
+ "Reject absolute URLs unless the host is on an allowlist.",
1297
+ "Prefer router navigation to a route name instead of a raw URL."
1298
+ ]
1299
+ },
1300
+ {
1301
+ id: "security.secret",
1302
+ stacks: ["shared"],
1303
+ category: "security",
1304
+ severity: "high",
1305
+ safety: "assist",
1306
+ headline: true,
1307
+ title: "Secret is hardcoded in client source",
1308
+ why: "Anything shipped to the browser can be read by the user. A live token in source is already exposed, and it will be copied into more logs if the report repeats it.",
1309
+ fix: "Remove the secret from the client, rotate it, and call a backend that holds the credential. The report names the kind of secret and the file, and it does not repeat the value.",
1310
+ docs: [{ title: "OWASP secrets in code", url: "https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html" }],
1311
+ plan: [
1312
+ "Rotate the credential. Assume it is public once it is in client source.",
1313
+ "Delete it from the repository and from build output.",
1314
+ "Move the call behind a server that reads the secret from a secret store."
1315
+ ]
1316
+ },
1317
+ {
1318
+ id: "security.target-blank",
1319
+ stacks: ["shared"],
1320
+ category: "security",
1321
+ severity: "low",
1322
+ safety: "auto",
1323
+ title: "target=_blank is missing rel=noopener",
1324
+ why: "A new tab opened without noopener can let the destination page reach back to window.opener.",
1325
+ fix: 'Add rel="noopener noreferrer" on the anchor. This edit is mechanical and safe to apply.',
1326
+ docs: [{ title: "rel=noopener", url: "https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel/noopener" }],
1327
+ plan: ['Add rel="noopener noreferrer" next to target="_blank".']
1328
+ },
1329
+ {
1330
+ id: "security.debugger",
1331
+ stacks: ["shared"],
1332
+ category: "security",
1333
+ severity: "low",
1334
+ safety: "auto",
1335
+ title: "debugger statement left in source",
1336
+ why: "A leftover debugger statement stops the page whenever DevTools is open and does not belong in the app.",
1337
+ fix: "Remove the debugger statement. This edit is mechanical and safe to apply.",
1338
+ docs: [{ title: "debugger", url: "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger" }],
1339
+ plan: ["Delete the debugger statement."]
1340
+ },
1341
+ {
1342
+ id: "chrome.slow-request",
1343
+ stacks: ["shared"],
1344
+ category: "performance",
1345
+ severity: "medium",
1346
+ safety: "assist",
1347
+ title: "Open page waited on a slow request",
1348
+ why: "A resource on the active tab took long enough to delay the page the developer has open.",
1349
+ fix: "Shrink the payload, cache it, or start it earlier. The finding names the request and the source file when a literal in the project matches the URL.",
1350
+ docs: [{ title: "Network reference", url: "https://developer.chrome.com/docs/devtools/network/reference" }],
1351
+ plan: [
1352
+ "Confirm the request on the open tab.",
1353
+ "Match it to the service or component that builds that URL.",
1354
+ "Cache or trim the response if the same call blocks first paint."
1355
+ ]
1356
+ },
1357
+ {
1358
+ id: "chrome.long-task",
1359
+ stacks: ["shared"],
1360
+ category: "performance",
1361
+ severity: "medium",
1362
+ safety: "assist",
1363
+ title: "Long task on the open page",
1364
+ why: "A task over 50ms blocks input and paint on the tab the developer is looking at.",
1365
+ fix: "Break the work up or move it off the first interaction. Attribution to a single component is unknown unless a script URL maps to a file.",
1366
+ docs: [{ title: "Long tasks", url: "https://developer.chrome.com/docs/devtools/performance/reference" }],
1367
+ plan: [
1368
+ "Record a performance trace of the same tab.",
1369
+ "Find the script that owns the long task.",
1370
+ "Split the work so a frame can paint in between."
1371
+ ]
1372
+ },
1373
+ {
1374
+ id: "lighthouse.opportunity",
1375
+ stacks: ["shared"],
1376
+ category: "lighthouse",
1377
+ severity: "medium",
1378
+ safety: "assist",
1379
+ title: "Lighthouse opportunity",
1380
+ why: "Lighthouse scored this check below the passing threshold on the open page.",
1381
+ fix: "Follow the Lighthouse description in the finding. These items are suggestions. The tool does not edit source from a Lighthouse result.",
1382
+ docs: [{ title: "Lighthouse", url: "https://developer.chrome.com/docs/lighthouse/overview" }],
1383
+ plan: [
1384
+ "Read the Lighthouse item and the savings it reports.",
1385
+ "Change the page or the build, then run Lighthouse again on the same tab."
1386
+ ]
1387
+ }
1388
+ ];
1389
+ }
1390
+ });
1391
+
1392
+ // packages/core/dist/html.js
1393
+ function renderHtml(result) {
1394
+ const findings = result.apps.flatMap((app) => app.findings);
1395
+ const counts = {
1396
+ high: findings.filter((finding) => finding.severity === "high").length,
1397
+ medium: findings.filter((finding) => finding.severity === "medium").length,
1398
+ low: findings.filter((finding) => finding.severity === "low").length
1399
+ };
1400
+ const applied = result.apps.reduce((sum, app) => sum + app.applied.length, 0);
1401
+ return `<!doctype html>
1402
+ <html lang="en">
1403
+ <head>
1404
+ <meta charset="utf-8">
1405
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1406
+ <title>Frontend audit</title>
1407
+ <style>${CSS}</style>
1408
+ </head>
1409
+ <body>
1410
+ <header>
1411
+ <h1>Frontend audit</h1>
1412
+ <p class="meta">${esc(result.mode)} audit \xB7 ${esc(result.repoRoot)}</p>
1413
+ <div class="stats">
1414
+ <div class="stat high"><span>${counts.high}</span>high</div>
1415
+ <div class="stat medium"><span>${counts.medium}</span>medium</div>
1416
+ <div class="stat low"><span>${counts.low}</span>low</div>
1417
+ <div class="stat applied"><span>${applied}</span>applied</div>
1418
+ </div>
1419
+ <p class="meta">Chrome: ${esc(result.chrome.detail)}${result.chrome.pageUrl ? ` (${esc(result.chrome.pageUrl)})` : ""}</p>
1420
+ <p class="meta">Lighthouse: ${esc(result.lighthouse.detail)}</p>
1421
+ ${result.budgetExceeded ? `<p class="warn">The time budget ended before every app was fully scanned.</p>` : ""}
1422
+ <nav class="filters" aria-label="Filter by severity">
1423
+ <label><input type="checkbox" data-sev="high" checked> high</label>
1424
+ <label><input type="checkbox" data-sev="medium" checked> medium</label>
1425
+ <label><input type="checkbox" data-sev="low" checked> low</label>
1426
+ </nav>
1427
+ </header>
1428
+ <main>
1429
+ ${result.apps.map(renderApp).join("\n")}
1430
+ <section class="limits">
1431
+ <h2>What this version does not do</h2>
1432
+ <ul>${BLIND_SPOTS.map((item) => `<li>${esc(item)}</li>`).join("")}</ul>
1433
+ </section>
1434
+ </main>
1435
+ <script>
1436
+ document.querySelectorAll("[data-sev]").forEach(function (box) {
1437
+ box.addEventListener("change", function () {
1438
+ document.querySelectorAll(".finding.sev-" + box.dataset.sev).forEach(function (row) {
1439
+ row.hidden = !box.checked;
1440
+ });
1441
+ });
1442
+ });
1443
+ </script>
1444
+ </body>
1445
+ </html>
1446
+ `;
1447
+ }
1448
+ function renderApp(app) {
1449
+ return `<section class="app">
1450
+ <h2>${esc(app.id)}</h2>
1451
+ <p class="meta">${esc(app.label)}</p>
1452
+ ${app.skipped ? `<p class="warn">Not scanned. The time budget ran out first.</p>` : ""}
1453
+ ${app.truncated ? `<p class="warn">The file walk stopped at the file cap. Results are partial.</p>` : ""}
1454
+ <h3>Open findings</h3>
1455
+ ${app.findings.length === 0 ? `<p class="empty">None.</p>` : app.findings.map(renderFinding).join("\n")}
1456
+ ${list("Applied fixes", app.applied.map((fix) => `<code>${esc(fix.file)}:${fix.line}</code> ${esc(fix.title)}`))}
1457
+ ${list("Safe fixes available with --fix", app.pendingFixes.map((fix) => `<code>${esc(fix.file)}:${fix.line}</code> ${esc(fix.title)}`))}
1458
+ ${app.clean.length > 0 ? `<details class="clean"><summary>Checked with no findings (${app.clean.length})</summary><ul>${app.clean.map((item) => `<li>${esc(item.title)} <code>${esc(item.id)}</code></li>`).join("")}</ul></details>` : ""}
1459
+ ${app.watchNext.length > 0 ? `<details><summary>Review by hand (${app.watchNext.length})</summary><ul>${app.watchNext.map((item) => `<li><strong>${esc(item.title)}</strong> \u2014 ${esc(item.why)} ${item.docs.map(link).join(" ")}</li>`).join("")}</ul></details>` : ""}
1460
+ </section>`;
1461
+ }
1462
+ function renderFinding(finding) {
1463
+ return `<article class="finding sev-${finding.severity}">
1464
+ <div class="head">
1465
+ <span class="badge ${finding.severity}">${finding.severity}</span>
1466
+ <strong>${esc(finding.title)}</strong>
1467
+ <span class="safety">${finding.safety === "auto" ? "safe fix" : "needs review"}</span>
1468
+ </div>
1469
+ <p class="where"><code>${esc(finding.file)}:${finding.line}</code> \xB7 <code>${esc(finding.ruleId)}</code></p>
1470
+ ${finding.secretKind ? `<p class="secret">Secret type: ${esc(finding.secretKind)}. Value [redacted].</p>` : ""}
1471
+ ${finding.detail ? `<p class="detail">${esc(finding.detail)}</p>` : ""}
1472
+ <p>${esc(finding.why)}</p>
1473
+ <p><strong>Fix:</strong> ${esc(finding.fix)}</p>
1474
+ <ol>${finding.plan.map((step) => `<li>${esc(step)}</li>`).join("")}</ol>
1475
+ <p class="docs">${finding.docs.map(link).join(" \xB7 ")}</p>
1476
+ </article>`;
1477
+ }
1478
+ function list(title, items) {
1479
+ if (items.length === 0)
1480
+ return "";
1481
+ return `<h3>${esc(title)}</h3><ul>${items.map((item) => `<li>${item}</li>`).join("")}</ul>`;
1482
+ }
1483
+ function link(doc) {
1484
+ return `<a href="${esc(doc.url)}" rel="noopener noreferrer" target="_blank">${esc(doc.title)}</a>`;
1485
+ }
1486
+ function esc(value) {
1487
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
1488
+ }
1489
+ var CSS;
1490
+ var init_html = __esm({
1491
+ "packages/core/dist/html.js"() {
1492
+ "use strict";
1493
+ init_limits();
1494
+ CSS = `
1495
+ :root { color-scheme: light dark; --bg: #f7f7f8; --card: #fff; --text: #1d1d1f; --muted: #6e6e73; --line: #e2e2e6;
1496
+ --high: #c62828; --medium: #b26a00; --low: #2e6db4; --ok: #2e7d32; }
1497
+ @media (prefers-color-scheme: dark) { :root { --bg: #121214; --card: #1c1c1f; --text: #f2f2f4; --muted: #a1a1a8; --line: #2c2c31; } }
1498
+ * { box-sizing: border-box; }
1499
+ body { margin: 0; font: 15px/1.55 system-ui, -apple-system, "Segoe UI", sans-serif; background: var(--bg); color: var(--text); }
1500
+ header, main { max-width: 980px; margin: 0 auto; padding: 24px; }
1501
+ h1 { margin: 0 0 4px; font-size: 28px; }
1502
+ h2 { margin: 0 0 4px; font-size: 20px; }
1503
+ h3 { margin: 20px 0 8px; font-size: 15px; text-transform: uppercase; letter-spacing: .04em; color: var(--muted); }
1504
+ .meta { margin: 2px 0; color: var(--muted); font-size: 13px; }
1505
+ .warn { padding: 8px 12px; border-left: 3px solid var(--medium); background: var(--card); }
1506
+ .stats { display: flex; gap: 12px; margin: 16px 0; flex-wrap: wrap; }
1507
+ .stat { min-width: 110px; padding: 12px 14px; border-radius: 10px; background: var(--card); border: 1px solid var(--line); color: var(--muted); font-size: 12px; text-transform: uppercase; }
1508
+ .stat span { display: block; font-size: 28px; font-weight: 700; color: var(--text); }
1509
+ .stat.high span { color: var(--high); } .stat.medium span { color: var(--medium); } .stat.low span { color: var(--low); } .stat.applied span { color: var(--ok); }
1510
+ .filters { display: flex; gap: 16px; margin-top: 12px; font-size: 14px; }
1511
+ .app { margin-bottom: 28px; padding: 20px; border-radius: 12px; background: var(--card); border: 1px solid var(--line); }
1512
+ .finding { margin: 10px 0; padding: 14px 16px; border-radius: 10px; border: 1px solid var(--line); border-left: 4px solid var(--low); }
1513
+ .finding.sev-high { border-left-color: var(--high); } .finding.sev-medium { border-left-color: var(--medium); }
1514
+ .finding p { margin: 6px 0; } .finding ol { margin: 6px 0; padding-left: 20px; }
1515
+ .head { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
1516
+ .badge { padding: 1px 8px; border-radius: 999px; color: #fff; font-size: 12px; text-transform: uppercase; }
1517
+ .badge.high { background: var(--high); } .badge.medium { background: var(--medium); } .badge.low { background: var(--low); }
1518
+ .safety { margin-left: auto; color: var(--muted); font-size: 12px; }
1519
+ .where, .docs, .detail { font-size: 13px; color: var(--muted); }
1520
+ .secret { font-size: 13px; color: var(--high); }
1521
+ code { font: 12px ui-monospace, SFMono-Regular, Consolas, monospace; }
1522
+ details { margin-top: 12px; } summary { cursor: pointer; color: var(--muted); }
1523
+ .clean summary { color: var(--ok); }
1524
+ .empty { color: var(--ok); }
1525
+ a { color: var(--low); }
1526
+ .limits { color: var(--muted); font-size: 13px; }
1527
+ `;
1528
+ }
1529
+ });
1530
+
1531
+ // packages/core/dist/pdf.js
1532
+ import fs4 from "node:fs";
1533
+ function writeTextPdf(file, text) {
1534
+ const lines = text.replaceAll("\r\n", "\n").split("\n").flatMap((line) => wrap(line, 90));
1535
+ const pageSize = 48;
1536
+ const pages = [];
1537
+ for (let index = 0; index < Math.max(lines.length, 1); index += pageSize)
1538
+ pages.push(lines.slice(index, index + pageSize));
1539
+ const objects = [];
1540
+ const kids = [];
1541
+ objects.push("<< /Type /Catalog /Pages 2 0 R >>");
1542
+ const pageObjectNumbers = [];
1543
+ let next = 3;
1544
+ for (let index = 0; index < pages.length; index += 1) {
1545
+ pageObjectNumbers.push(next);
1546
+ next += 2;
1547
+ }
1548
+ objects.push(`<< /Type /Pages /Count ${pages.length} /Kids [${pageObjectNumbers.map((number) => `${number} 0 R`).join(" ")}] >>`);
1549
+ pages.forEach((page, index) => {
1550
+ const contentNumber = pageObjectNumbers[index] + 1;
1551
+ kids.push("");
1552
+ const commands = ["BT", "/F1 10 Tf", "50 780 Td", "14 TL", ...page.map((line) => `(${escapePdf(line)}) Tj T*`), "ET"].join("\n");
1553
+ objects.push(`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents ${contentNumber} 0 R /Resources << /Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >> >> >>`);
1554
+ objects.push(`<< /Length ${Buffer.byteLength(commands)} >>
1555
+ stream
1556
+ ${commands}
1557
+ endstream`);
1558
+ });
1559
+ let body = "%PDF-1.4\n";
1560
+ const offsets = [0];
1561
+ objects.forEach((object, index) => {
1562
+ offsets.push(Buffer.byteLength(body));
1563
+ body += `${index + 1} 0 obj
1564
+ ${object}
1565
+ endobj
1566
+ `;
1567
+ });
1568
+ const xref = Buffer.byteLength(body);
1569
+ body += `xref
1570
+ 0 ${objects.length + 1}
1571
+ `;
1572
+ body += "0000000000 65535 f \n";
1573
+ for (const offset of offsets.slice(1))
1574
+ body += `${String(offset).padStart(10, "0")} 00000 n
1575
+ `;
1576
+ body += `trailer << /Size ${objects.length + 1} /Root 1 0 R >>
1577
+ startxref
1578
+ ${xref}
1579
+ %%EOF`;
1580
+ fs4.writeFileSync(file, body);
1581
+ void kids;
1582
+ }
1583
+ function wrap(line, width) {
1584
+ const clean = ascii(line);
1585
+ if (clean.length <= width)
1586
+ return [clean];
1587
+ const rows = [];
1588
+ for (let index = 0; index < clean.length; index += width)
1589
+ rows.push(clean.slice(index, index + width));
1590
+ return rows;
1591
+ }
1592
+ function ascii(value) {
1593
+ return value.replace(/[^\x20-\x7e]/g, " ");
1594
+ }
1595
+ function escapePdf(value) {
1596
+ return ascii(value).replaceAll("\\", "\\\\").replaceAll("(", "\\(").replaceAll(")", "\\)");
1597
+ }
1598
+ var init_pdf = __esm({
1599
+ "packages/core/dist/pdf.js"() {
1600
+ "use strict";
1601
+ }
1602
+ });
1603
+
1604
+ // packages/core/dist/report.js
1605
+ import fs5 from "node:fs";
1606
+ import path4 from "node:path";
1607
+ function writeAuditReports(result, secrets2) {
1608
+ fs5.mkdirSync(result.reportDir, { recursive: true });
1609
+ const markdown = scrub(renderMarkdown(result), secrets2);
1610
+ const plan = scrub(renderPlan(result), secrets2);
1611
+ const json = scrub(JSON.stringify(toJson(result), null, 2), secrets2);
1612
+ const html = scrub(renderHtml(result), secrets2);
1613
+ const summary = scrub(renderSummary(result), secrets2);
1614
+ fs5.writeFileSync(path4.join(result.reportDir, "report.md"), markdown);
1615
+ fs5.writeFileSync(path4.join(result.reportDir, "plan.md"), plan);
1616
+ fs5.writeFileSync(path4.join(result.reportDir, "report.json"), json);
1617
+ fs5.writeFileSync(path4.join(result.reportDir, "report.html"), html);
1618
+ return { ...result, summary };
1619
+ }
1620
+ function exportReport(dir, format) {
1621
+ const reportDir = path4.join(path4.resolve(dir), ".frontend-audit");
1622
+ const markdown = path4.join(reportDir, "report.md");
1623
+ const json = path4.join(reportDir, "report.json");
1624
+ if (!fs5.existsSync(markdown) || !fs5.existsSync(json)) {
1625
+ throw new Error(`No audit report in ${reportDir}. Run frontend-audit audit first.`);
1626
+ }
1627
+ if (format === "md")
1628
+ return markdown;
1629
+ if (format === "json")
1630
+ return json;
1631
+ if (format === "html")
1632
+ return path4.join(reportDir, "report.html");
1633
+ const pdf = path4.join(reportDir, "report.pdf");
1634
+ writeTextPdf(pdf, fs5.readFileSync(markdown, "utf8"));
1635
+ return pdf;
1636
+ }
1637
+ function renderSummary(result) {
1638
+ const findings = result.apps.flatMap((app) => app.findings);
1639
+ const applied = result.apps.reduce((sum, app) => sum + app.applied.length, 0);
1640
+ const counts = count(findings);
1641
+ const lines = [
1642
+ `${capitalize(result.mode)} audit. Detected ${result.apps.length} app${result.apps.length === 1 ? "" : "s"}.`,
1643
+ ...result.apps.map((app) => app.label),
1644
+ `Open findings: ${counts.high} high, ${counts.medium} medium, ${counts.low} low.`,
1645
+ `Applied fixes: ${applied}.`,
1646
+ `Chrome: ${result.chrome.detail}`,
1647
+ `Lighthouse: ${result.lighthouse.detail}`
1648
+ ];
1649
+ if (result.budgetExceeded)
1650
+ lines.push("The time budget ended before every app was fully scanned.");
1651
+ const top = [...findings].sort(bySeverity).slice(0, 5);
1652
+ if (top.length > 0) {
1653
+ lines.push("Top findings:");
1654
+ for (const finding of top)
1655
+ lines.push(`- ${finding.severity} ${finding.ruleId} ${finding.file}:${finding.line}`);
1656
+ }
1657
+ lines.push(`Report: ${path4.join(result.reportDir, "report.html")}`);
1658
+ lines.push(`Markdown: ${path4.join(result.reportDir, "report.md")}`);
1659
+ return lines.join("\n");
1660
+ }
1661
+ function capitalize(value) {
1662
+ return value.charAt(0).toUpperCase() + value.slice(1);
1663
+ }
1664
+ function renderMarkdown(result) {
1665
+ const lines = ["# Frontend audit", "", `Mode: ${result.mode}.`, `Budget: ${result.budgetMs}ms.`, `Chrome: ${result.chrome.detail}`, `Lighthouse: ${result.lighthouse.detail}`, ""];
1666
+ if (result.chrome.pageUrl)
1667
+ lines.push(`Page: ${result.chrome.pageUrl}`, "");
1668
+ for (const app of result.apps)
1669
+ lines.push(...renderApp2(app));
1670
+ lines.push("## Limits", "", ...BLIND_SPOTS.map((item) => `- ${item}`), "");
1671
+ return lines.join("\n");
1672
+ }
1673
+ function renderApp2(app) {
1674
+ const lines = [`## ${app.id}`, "", app.label, ""];
1675
+ if (app.skipped)
1676
+ lines.push("This app was not scanned because the time budget ran out.", "");
1677
+ if (app.truncated)
1678
+ lines.push("File walk stopped at the file cap. Results are partial.", "");
1679
+ lines.push("### Open findings", "");
1680
+ if (app.findings.length === 0)
1681
+ lines.push("None.", "");
1682
+ for (const severity of ["high", "medium", "low"]) {
1683
+ const group = app.findings.filter((finding) => finding.severity === severity);
1684
+ if (group.length === 0)
1685
+ continue;
1686
+ lines.push(`#### ${severity}`, "");
1687
+ for (const finding of group)
1688
+ lines.push(...renderFinding2(finding), "");
1689
+ }
1690
+ lines.push("### Applied", "");
1691
+ if (app.applied.length === 0)
1692
+ lines.push("None.", "");
1693
+ for (const fix of app.applied)
1694
+ lines.push(`- \`${fix.ruleId}\` ${fix.file}:${fix.line} \u2014 ${fix.title}`);
1695
+ if (app.pendingFixes.length > 0) {
1696
+ lines.push("", "### Safe fixes available", "");
1697
+ for (const fix of app.pendingFixes)
1698
+ lines.push(`- \`${fix.ruleId}\` ${fix.file}:${fix.line} \u2014 ${fix.title}`);
1699
+ }
1700
+ lines.push("", "### Checked with no findings", "");
1701
+ if (app.clean.length === 0)
1702
+ lines.push("None.", "");
1703
+ for (const item of app.clean)
1704
+ lines.push(`- ${item.title} (\`${item.id}\`)`);
1705
+ lines.push("", "### Review by hand", "");
1706
+ if (app.watchNext.length === 0)
1707
+ lines.push("None.", "");
1708
+ for (const item of app.watchNext) {
1709
+ const docs = item.docs.map((doc) => doc.url).join(", ");
1710
+ lines.push(`- **${item.title}** (\`${item.id}\`) \u2014 ${item.why} ${docs}`);
1711
+ }
1712
+ lines.push("");
1713
+ return lines;
1714
+ }
1715
+ function renderFinding2(finding) {
1716
+ const lines = [
1717
+ `- **${finding.severity}** \`${finding.ruleId}\` ${finding.file}:${finding.line}`,
1718
+ ` ${finding.why}`,
1719
+ ` **Fix:** ${finding.fix}`,
1720
+ ` **Plan:** ${finding.plan.map((step, index) => `${index + 1}. ${step}`).join(" ")}`,
1721
+ ` **Docs:** ${finding.docs.map((doc) => doc.url).join(", ")}`,
1722
+ ` **Safety:** ${finding.safety}`
1723
+ ];
1724
+ if (finding.secretKind)
1725
+ lines.push(` **Secret:** ${finding.secretKind} [redacted]`);
1726
+ if (finding.detail)
1727
+ lines.push(` **Detail:** ${finding.detail}`);
1728
+ return lines;
1729
+ }
1730
+ function renderPlan(result) {
1731
+ const lines = ["# Remediation plan", ""];
1732
+ for (const app of result.apps) {
1733
+ lines.push(`## ${app.id}`, "", app.label, "");
1734
+ if (app.applied.length > 0) {
1735
+ lines.push("### Already applied", "");
1736
+ for (const fix of app.applied)
1737
+ lines.push(`- ${fix.file}:${fix.line} \`${fix.ruleId}\` ${fix.title}`);
1738
+ lines.push("");
1739
+ }
1740
+ const open = [...app.findings].sort(bySeverity);
1741
+ lines.push("### Open", "");
1742
+ if (open.length === 0)
1743
+ lines.push("None.", "");
1744
+ open.forEach((finding, index) => {
1745
+ lines.push(`${index + 1}. **${finding.severity}** ${finding.file}:${finding.line} \u2014 ${finding.title}`);
1746
+ finding.plan.forEach((step) => lines.push(` - ${step}`));
1747
+ lines.push(` - Docs: ${finding.docs.map((doc) => doc.url).join(", ")}`);
1748
+ });
1749
+ lines.push("", "### Review by hand", "");
1750
+ for (const item of app.watchNext)
1751
+ lines.push(`- ${item.title}: ${item.why}`);
1752
+ lines.push("");
1753
+ }
1754
+ return lines.join("\n");
1755
+ }
1756
+ function toJson(result) {
1757
+ return {
1758
+ version: 1,
1759
+ mode: result.mode,
1760
+ repoRoot: result.repoRoot,
1761
+ budgetMs: result.budgetMs,
1762
+ budgetExceeded: result.budgetExceeded,
1763
+ chrome: result.chrome,
1764
+ lighthouse: result.lighthouse,
1765
+ apps: result.apps.map((app) => ({
1766
+ id: app.id,
1767
+ name: app.name,
1768
+ label: app.label,
1769
+ stacks: app.stacks,
1770
+ versions: app.versions,
1771
+ skipped: app.skipped,
1772
+ truncated: app.truncated,
1773
+ findings: app.findings,
1774
+ applied: app.applied,
1775
+ pendingFixes: app.pendingFixes,
1776
+ clean: app.clean.map((item) => item.id),
1777
+ watchNext: app.watchNext
1778
+ }))
1779
+ };
1780
+ }
1781
+ function count(findings) {
1782
+ return {
1783
+ high: findings.filter((finding) => finding.severity === "high").length,
1784
+ medium: findings.filter((finding) => finding.severity === "medium").length,
1785
+ low: findings.filter((finding) => finding.severity === "low").length
1786
+ };
1787
+ }
1788
+ function bySeverity(left, right) {
1789
+ return SEVERITY_ORDER[left.severity] - SEVERITY_ORDER[right.severity];
1790
+ }
1791
+ function scrub(text, secrets2) {
1792
+ let output = text;
1793
+ for (const secret of secrets2) {
1794
+ if (secret.length < 8)
1795
+ continue;
1796
+ output = output.split(secret).join("[redacted]");
1797
+ }
1798
+ return output;
1799
+ }
1800
+ var SEVERITY_ORDER;
1801
+ var init_report = __esm({
1802
+ "packages/core/dist/report.js"() {
1803
+ "use strict";
1804
+ init_html();
1805
+ init_limits();
1806
+ init_pdf();
1807
+ SEVERITY_ORDER = { high: 0, medium: 1, low: 2 };
1808
+ }
1809
+ });
1810
+
1811
+ // packages/core/dist/rules.js
1812
+ function effectLoops(source) {
1813
+ const drafts = [];
1814
+ const re = /useEffect\s*\(/g;
1815
+ let match;
1816
+ while (match = re.exec(source)) {
1817
+ const open = source.indexOf("(", match.index);
1818
+ const close = matchingParen(source, open);
1819
+ if (close < 0)
1820
+ continue;
1821
+ const body = source.slice(open, close + 1);
1822
+ const deps = body.match(/\[([\s\S]*)\]\s*\)\s*$/);
1823
+ if (!deps)
1824
+ continue;
1825
+ const depNames = deps[1].split(",").map((part) => part.trim().split(".")[0]?.replace(/[^A-Za-z0-9_$]/g, "") ?? "");
1826
+ for (const setCall of body.matchAll(/\bset([A-Z][A-Za-z0-9]*)\s*\(/g)) {
1827
+ const name = setCall[1];
1828
+ const state = name.charAt(0).toLowerCase() + name.slice(1);
1829
+ if (depNames.includes(state)) {
1830
+ drafts.push({ ruleId: "react.effect-state-loop", line: lineOf(source, match.index) });
1831
+ break;
1832
+ }
1833
+ }
1834
+ if (drafts.length >= 10)
1835
+ break;
1836
+ }
1837
+ return drafts;
1838
+ }
1839
+ function renderFetch(source, file) {
1840
+ if (!/\.(tsx|jsx)$/.test(file) && !file.endsWith(".vue"))
1841
+ return [];
1842
+ const masked = maskCalls(source, /use(?:Effect|Callback|Memo)\s*\(/g);
1843
+ const re = /\bfetch\s*\(|\baxios\.(?:get|post|put|delete|request)\s*\(/g;
1844
+ let match;
1845
+ while (match = re.exec(source)) {
1846
+ if (masked[match.index])
1847
+ continue;
1848
+ if (isComment(lineText(source, match.index)))
1849
+ continue;
1850
+ return [{ ruleId: "react.render-fetch", line: lineOf(source, match.index) }];
1851
+ }
1852
+ return [];
1853
+ }
1854
+ function contextIdentity(source, file) {
1855
+ if (!/\.(tsx|jsx)$/.test(file))
1856
+ return [];
1857
+ return capped(source, "react.context-identity", /value=\{\{/g, 3);
1858
+ }
1859
+ function missingKey(source, file) {
1860
+ if (!/\.(tsx|jsx)$/.test(file))
1861
+ return [];
1862
+ const drafts = [];
1863
+ const re = /\.map\s*\(/g;
1864
+ let match;
1865
+ while (match = re.exec(source)) {
1866
+ const window = source.slice(match.index, match.index + 300);
1867
+ if (window.includes("<") && !window.includes("key=")) {
1868
+ drafts.push({ ruleId: "react.missing-key", line: lineOf(source, match.index) });
1869
+ }
1870
+ if (drafts.length >= 5)
1871
+ break;
1872
+ }
1873
+ return drafts;
1874
+ }
1875
+ function manualMemo(source) {
1876
+ const match = source.match(/\b(?:useMemo|memo)\s*\(/);
1877
+ if (!match || match.index === void 0)
1878
+ return [];
1879
+ if (isComment(lineText(source, match.index)))
1880
+ return [];
1881
+ return [{ ruleId: "react.manual-memo", line: lineOf(source, match.index) }];
1882
+ }
1883
+ function nextImage(source, file) {
1884
+ if (!/\.(tsx|jsx)$/.test(file))
1885
+ return [];
1886
+ return capped(source, "next.img-element", /<img\b/g, 5);
1887
+ }
1888
+ function clientHeavyImport(source) {
1889
+ if (!/["']use client["']/.test(source))
1890
+ return [];
1891
+ const match = source.match(/from\s+["'](?:lodash|moment|chart\.js)["']/);
1892
+ if (!match || match.index === void 0)
1893
+ return [];
1894
+ return [{ ruleId: "next.client-heavy-import", line: lineOf(source, match.index) }];
1895
+ }
1896
+ function templateCall(source, file) {
1897
+ if (!file.endsWith(".html") && !file.endsWith(".vue") && !file.endsWith(".ts"))
1898
+ return [];
1899
+ const drafts = [];
1900
+ const lines = source.split(/\r?\n/);
1901
+ for (let index = 0; index < lines.length; index += 1) {
1902
+ const line = lines[index];
1903
+ if (isComment(line) || line.includes("@for") || line.includes("*ngFor"))
1904
+ continue;
1905
+ if (/\{\{[^{}]*\([^{}]*\)[^{}]*\}\}/.test(line) || /\[[^\]]+\]\s*=\s*"[^"]+\([^"]*\)"/.test(line)) {
1906
+ drafts.push({ ruleId: "angular.template-call", line: index + 1 });
1907
+ }
1908
+ if (drafts.length >= 10)
1909
+ break;
1910
+ }
1911
+ return drafts;
1912
+ }
1913
+ function listTrack(source) {
1914
+ const drafts = [];
1915
+ for (const match of source.matchAll(/\*ngFor\s*=\s*"([^"]*)"/g)) {
1916
+ if (!match[1].includes("trackBy") && match.index !== void 0) {
1917
+ drafts.push({ ruleId: "angular.list-track", line: lineOf(source, match.index) });
1918
+ }
1919
+ }
1920
+ for (const match of source.matchAll(/@for\s*\(([\s\S]*?)\)\s*\{/g)) {
1921
+ if (!/\btrack\b/.test(match[1]) && match.index !== void 0) {
1922
+ drafts.push({ ruleId: "angular.list-track", line: lineOf(source, match.index) });
1923
+ }
1924
+ }
1925
+ return drafts.slice(0, 10);
1926
+ }
1927
+ function subscribeLeak(source, _file, stacks) {
1928
+ if (!stacks.includes("angular"))
1929
+ return [];
1930
+ if (/\.subscribe\s*\([\s\S]{0,500}?\.subscribe\s*\(/.test(source))
1931
+ return [];
1932
+ if (!source.includes(".subscribe("))
1933
+ return [];
1934
+ if (/unsubscribe\s*\(|takeUntil(?:Destroyed)?\s*\(|firstValueFrom\s*\(/.test(source))
1935
+ return [];
1936
+ return [{ ruleId: "angular.subscribe-leak", line: lineOf(source, source.indexOf(".subscribe(")) }];
1937
+ }
1938
+ function missingTeardown(source) {
1939
+ if (/\.subscribe\s*\([\s\S]{0,500}?\.subscribe\s*\(/.test(source))
1940
+ return [];
1941
+ if (!source.includes(".subscribe("))
1942
+ return [];
1943
+ if (/unsubscribe\s*\(|takeUntil(?:Destroyed)?\s*\(|firstValueFrom\s*\(/.test(source))
1944
+ return [];
1945
+ return [{ ruleId: "rxjs.missing-teardown", line: lineOf(source, source.indexOf(".subscribe(")) }];
1946
+ }
1947
+ function nestedSubscribe(source) {
1948
+ const match = source.match(/\.subscribe\s*\([\s\S]{0,500}?\.subscribe\s*\(/);
1949
+ if (!match || match.index === void 0)
1950
+ return [];
1951
+ return [{ ruleId: "rxjs.nested-subscribe", line: lineOf(source, match.index) }];
1952
+ }
1953
+ function vueWatchSelf(source) {
1954
+ const re = /watch\s*\(\s*(?:\(\s*\)\s*=>\s*)?([A-Za-z_][A-Za-z0-9_]*)/g;
1955
+ let match;
1956
+ while (match = re.exec(source)) {
1957
+ const name = match[1];
1958
+ const slice = source.slice(match.index, match.index + 400);
1959
+ if (new RegExp(`\\b${name}\\.value\\s*=`).test(slice)) {
1960
+ return [{ ruleId: "vue.watch-self", line: lineOf(source, match.index) }];
1961
+ }
1962
+ }
1963
+ return [];
1964
+ }
1965
+ function vueForKey(source) {
1966
+ return capped(source, "vue.v-for-key", /<[^>]*\bv-for=(?:["'][^"']*["']|\{[^}]*\})[^>]*>/g, 10).filter((draft) => {
1967
+ const line = source.split(/\r?\n/)[draft.line - 1] ?? "";
1968
+ return !line.includes(":key") && !line.includes("v-bind:key");
1969
+ });
1970
+ }
1971
+ function vueDeepWatch(source, file) {
1972
+ if (!file.endsWith(".vue") && !file.endsWith(".ts") && !file.endsWith(".js"))
1973
+ return [];
1974
+ return capped(source, "vue.deep-watch", /deep\s*:\s*true/g, 5);
1975
+ }
1976
+ function nuxtPluginComponent(source, file) {
1977
+ if (!file.replaceAll("\\", "/").includes("/plugins/"))
1978
+ return [];
1979
+ const match = source.match(/import\s+[^;]*\.vue["']/);
1980
+ if (!match || match.index === void 0)
1981
+ return [];
1982
+ return [{ ruleId: "nuxt.plugin-component", line: lineOf(source, match.index) }];
1983
+ }
1984
+ function svelteReactiveLoop(source, file) {
1985
+ if (!file.endsWith(".svelte"))
1986
+ return [];
1987
+ const match = source.match(/\$:\s*([A-Za-z_][\w]*)\s*=[\s\S]{0,80}?\b\1\b/);
1988
+ if (!match || match.index === void 0)
1989
+ return [];
1990
+ return [{ ruleId: "svelte.reactive-loop", line: lineOf(source, match.index) }];
1991
+ }
1992
+ function svelteEachKey(source, file) {
1993
+ if (!file.endsWith(".svelte"))
1994
+ return [];
1995
+ const drafts = [];
1996
+ for (const match of source.matchAll(/\{#each\s+[^}]+\}/g)) {
1997
+ if (!match[0].includes("(") && match.index !== void 0) {
1998
+ drafts.push({ ruleId: "svelte.each-key", line: lineOf(source, match.index) });
1999
+ }
2000
+ }
2001
+ return drafts.slice(0, 10);
2002
+ }
2003
+ function scrollViewList(source) {
2004
+ if (!source.includes("ScrollView") || !source.includes(".map("))
2005
+ return [];
2006
+ if (source.includes("FlatList") || source.includes("FlashList"))
2007
+ return [];
2008
+ return [{ ruleId: "rn.scrollview-list", line: lineOf(source, source.indexOf("ScrollView")) }];
2009
+ }
2010
+ function inlineStyle(source) {
2011
+ if (!source.includes("FlatList") && !source.includes("FlashList"))
2012
+ return [];
2013
+ return capped(source, "rn.inline-style", /style=\{\{/g, 3);
2014
+ }
2015
+ function ngrxSelectStore(source) {
2016
+ return capped(source, "ngrx.select-store", /\.select\(\s*\(?\s*state\s*\)?\s*=>\s*state\b/g, 5);
2017
+ }
2018
+ function reduxSelectorObject(source) {
2019
+ return capped(source, "redux.selector-object", /useSelector\(\s*\(?\s*state\s*\)?\s*=>\s*\(?\s*\{/g, 5);
2020
+ }
2021
+ function tanstackStaleTime(source) {
2022
+ const drafts = [];
2023
+ const re = /useQuery\s*\(/g;
2024
+ let match;
2025
+ while (match = re.exec(source)) {
2026
+ const open = source.indexOf("(", match.index);
2027
+ const close = matchingParen(source, open);
2028
+ const body = close > open ? source.slice(open, close + 1) : source.slice(open, open + 400);
2029
+ if (!body.includes("staleTime"))
2030
+ drafts.push({ ruleId: "tanstack.no-staletime", line: lineOf(source, match.index) });
2031
+ if (drafts.length >= 5)
2032
+ break;
2033
+ }
2034
+ return drafts;
2035
+ }
2036
+ function lodashImport(source) {
2037
+ return capped(source, "lodash.full-import", /import\s+(?:\*\s+as\s+\w+|[_$]\w*|\w+)\s+from\s+["']lodash["']/g, 5);
2038
+ }
2039
+ function momentImport(source) {
2040
+ return capped(source, "moment.full-import", /(?:from\s+["']moment["']|require\(\s*["']moment["']\s*\))/g, 5);
2041
+ }
2042
+ function postMessage(source) {
2043
+ const lines = source.split(/\r?\n/);
2044
+ const drafts = [];
2045
+ for (let index = 0; index < lines.length; index += 1) {
2046
+ if (!/addEventListener\(\s*["']message["']/.test(lines[index]))
2047
+ continue;
2048
+ const window = lines.slice(index, index + 20).join("\n");
2049
+ if (!window.includes("origin"))
2050
+ drafts.push({ ruleId: "security.postmessage", line: index + 1 });
2051
+ if (drafts.length >= 5)
2052
+ break;
2053
+ }
2054
+ return drafts;
2055
+ }
2056
+ function openRedirect(source) {
2057
+ const drafts = [];
2058
+ const lines = source.split(/\r?\n/);
2059
+ for (let index = 0; index < lines.length; index += 1) {
2060
+ const line = lines[index];
2061
+ if (isComment(line))
2062
+ continue;
2063
+ if (/location(?:\.href)?\s*=/.test(line) && !/=\s*["'`]https?:/.test(line) && !/=\s*["'`]\/[^"'`]*["'`]/.test(line)) {
2064
+ drafts.push({ ruleId: "security.open-redirect", line: index + 1 });
2065
+ }
2066
+ }
2067
+ return drafts.slice(0, 5);
2068
+ }
2069
+ function secrets(source) {
2070
+ const drafts = [];
2071
+ for (const pattern of SECRET_PATTERNS) {
2072
+ pattern.re.lastIndex = 0;
2073
+ let match;
2074
+ while (match = pattern.re.exec(source)) {
2075
+ if (isComment(lineText(source, match.index)))
2076
+ continue;
2077
+ drafts.push({
2078
+ ruleId: "security.secret",
2079
+ line: lineOf(source, match.index),
2080
+ secretKind: pattern.kind,
2081
+ secretValue: match[1],
2082
+ detail: pattern.kind
2083
+ });
2084
+ if (drafts.length >= 10)
2085
+ return drafts;
2086
+ }
2087
+ }
2088
+ return drafts;
2089
+ }
2090
+ function targetBlank(source) {
2091
+ const drafts = [];
2092
+ for (const match of source.matchAll(/<a\b[^>]*>/gi)) {
2093
+ const tag = match[0];
2094
+ if (/target\s*=\s*["']_blank["']/.test(tag) && !/noopener/.test(tag) && match.index !== void 0) {
2095
+ drafts.push({ ruleId: "security.target-blank", line: lineOf(source, match.index) });
2096
+ }
2097
+ }
2098
+ return drafts.slice(0, 20);
2099
+ }
2100
+ function debuggerStatement(source) {
2101
+ const drafts = [];
2102
+ const lines = source.split(/\r?\n/);
2103
+ for (let index = 0; index < lines.length; index += 1) {
2104
+ if (lines[index].trim() === "debugger;")
2105
+ drafts.push({ ruleId: "security.debugger", line: index + 1 });
2106
+ }
2107
+ return drafts.slice(0, 10);
2108
+ }
2109
+ function lineHits(source, ruleId, pattern) {
2110
+ const flags = pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`;
2111
+ const re = new RegExp(pattern.source, flags);
2112
+ const drafts = [];
2113
+ let match;
2114
+ while (match = re.exec(source)) {
2115
+ if (isComment(lineText(source, match.index)))
2116
+ continue;
2117
+ drafts.push({ ruleId, line: lineOf(source, match.index) });
2118
+ if (drafts.length >= 10)
2119
+ break;
2120
+ }
2121
+ return drafts;
2122
+ }
2123
+ function capped(source, ruleId, pattern, limit) {
2124
+ return lineHits(source, ruleId, pattern).slice(0, limit);
2125
+ }
2126
+ function lineOf(source, index) {
2127
+ let line = 1;
2128
+ for (let cursor = 0; cursor < index && cursor < source.length; cursor += 1) {
2129
+ if (source.charCodeAt(cursor) === 10)
2130
+ line += 1;
2131
+ }
2132
+ return line;
2133
+ }
2134
+ function lineText(source, index) {
2135
+ const start = source.lastIndexOf("\n", index - 1) + 1;
2136
+ const end = source.indexOf("\n", index);
2137
+ return source.slice(start, end === -1 ? source.length : end);
2138
+ }
2139
+ function isComment(line) {
2140
+ const trimmed = line.trim();
2141
+ return trimmed.startsWith("//") || trimmed.startsWith("*") || trimmed.startsWith("/*") || trimmed.startsWith("<!--");
2142
+ }
2143
+ function matchingParen(source, open) {
2144
+ let depth = 0;
2145
+ for (let index = open; index < source.length; index += 1) {
2146
+ const char = source[index];
2147
+ if (char === "(")
2148
+ depth += 1;
2149
+ else if (char === ")") {
2150
+ depth -= 1;
2151
+ if (depth === 0)
2152
+ return index;
2153
+ }
2154
+ }
2155
+ return -1;
2156
+ }
2157
+ function maskCalls(source, pattern) {
2158
+ const masked = new Array(source.length).fill(false);
2159
+ let match;
2160
+ while (match = pattern.exec(source)) {
2161
+ const open = source.indexOf("(", match.index);
2162
+ const close = matchingParen(source, open);
2163
+ if (close < 0)
2164
+ continue;
2165
+ for (let index = match.index; index <= close; index += 1)
2166
+ masked[index] = true;
2167
+ }
2168
+ return masked;
2169
+ }
2170
+ function extractUrls(source, file) {
2171
+ const hits = [];
2172
+ const re = /["'`](\/api\/[^"'`\s]+)["'`]|["'`](https?:\/\/[^"'`\s]+)["'`]/g;
2173
+ let match;
2174
+ while (match = re.exec(source)) {
2175
+ const value = match[1] ?? match[2];
2176
+ if (!value)
2177
+ continue;
2178
+ hits.push({ file, line: lineOf(source, match.index), value });
2179
+ if (hits.length >= 50)
2180
+ break;
2181
+ }
2182
+ return hits;
2183
+ }
2184
+ var SECRET_PATTERNS, fileRules;
2185
+ var init_rules = __esm({
2186
+ "packages/core/dist/rules.js"() {
2187
+ "use strict";
2188
+ SECRET_PATTERNS = [
2189
+ { kind: "aws-access-key", re: /\b(AKIA[0-9A-Z]{16})\b/g },
2190
+ { kind: "stripe-live-key", re: /\b(sk_live_[0-9A-Za-z]{16,})\b/g },
2191
+ { kind: "github-token", re: /\b(gh_pat_[0-9A-Za-z_]{20,})\b/g },
2192
+ { kind: "private-key", re: /(-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----)/g },
2193
+ { kind: "jwt", re: /\b(eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,})\b/g }
2194
+ ];
2195
+ fileRules = [
2196
+ { id: "react.effect-state-loop", run: effectLoops },
2197
+ { id: "react.render-fetch", run: renderFetch },
2198
+ { id: "react.context-identity", run: contextIdentity },
2199
+ { id: "react.missing-key", run: missingKey },
2200
+ { id: "react.manual-memo", run: manualMemo },
2201
+ { id: "next.img-element", run: nextImage },
2202
+ { id: "next.client-heavy-import", run: clientHeavyImport },
2203
+ { id: "angular.template-call", run: templateCall },
2204
+ { id: "angular.list-track", run: listTrack },
2205
+ { id: "angular.subscribe-leak", run: subscribeLeak },
2206
+ { id: "vue.watch-self", run: vueWatchSelf },
2207
+ { id: "vue.v-for-key", run: vueForKey },
2208
+ { id: "vue.deep-watch", run: vueDeepWatch },
2209
+ { id: "nuxt.plugin-component", run: nuxtPluginComponent },
2210
+ { id: "svelte.reactive-loop", run: svelteReactiveLoop },
2211
+ { id: "svelte.each-key", run: svelteEachKey },
2212
+ { id: "rn.scrollview-list", run: scrollViewList },
2213
+ { id: "rn.inline-style", run: inlineStyle },
2214
+ { id: "rxjs.nested-subscribe", run: nestedSubscribe },
2215
+ { id: "rxjs.missing-teardown", run: (source, _file, stacks) => stacks.includes("angular") ? [] : missingTeardown(source) },
2216
+ { id: "ngrx.select-store", run: ngrxSelectStore },
2217
+ { id: "redux.selector-object", run: reduxSelectorObject },
2218
+ { id: "tanstack.no-staletime", run: tanstackStaleTime },
2219
+ { id: "lodash.full-import", run: lodashImport },
2220
+ { id: "moment.full-import", run: momentImport },
2221
+ { id: "security.dangerously-set-html", run: (source) => lineHits(source, "security.dangerously-set-html", /dangerouslySetInnerHTML/) },
2222
+ { id: "security.inner-html", run: (source) => lineHits(source, "security.inner-html", /\.innerHTML\b|\binnerHTML\s*=/) },
2223
+ { id: "security.eval", run: (source) => lineHits(source, "security.eval", /\beval\s*\(/) },
2224
+ { id: "security.new-function", run: (source) => lineHits(source, "security.new-function", /\bnew\s+Function\s*\(/) },
2225
+ { id: "security.bypass-trust", run: (source) => lineHits(source, "security.bypass-trust", /bypassSecurityTrust[A-Za-z]*/) },
2226
+ { id: "security.postmessage", run: postMessage },
2227
+ { id: "security.open-redirect", run: openRedirect },
2228
+ { id: "security.secret", run: secrets },
2229
+ { id: "security.target-blank", run: targetBlank },
2230
+ { id: "security.debugger", run: debuggerStatement }
2231
+ ];
2232
+ }
2233
+ });
2234
+
2235
+ // packages/core/dist/walk.js
2236
+ import fs6 from "node:fs";
2237
+ import path5 from "node:path";
2238
+ function listSourceFiles(root, scope, maxFiles) {
2239
+ const files = [];
2240
+ const start = scope.startsWith(root) ? scope : root;
2241
+ if (fs6.existsSync(start) && fs6.statSync(start).isFile()) {
2242
+ return isSource(start) ? { files: [start], truncated: false } : { files: [], truncated: false };
2243
+ }
2244
+ const truncated = walk(start, files, maxFiles);
2245
+ return { files, truncated };
2246
+ }
2247
+ function walk(directory, files, maxFiles) {
2248
+ if (files.length >= maxFiles)
2249
+ return true;
2250
+ let entries = [];
2251
+ try {
2252
+ entries = fs6.readdirSync(directory, { withFileTypes: true });
2253
+ } catch {
2254
+ return false;
2255
+ }
2256
+ for (const entry of entries) {
2257
+ if (files.length >= maxFiles)
2258
+ return true;
2259
+ if (entry.name.startsWith(".") || SKIP_DIRS.has(entry.name))
2260
+ continue;
2261
+ const full = path5.join(directory, entry.name);
2262
+ if (entry.isDirectory()) {
2263
+ if (walk(full, files, maxFiles))
2264
+ return true;
2265
+ continue;
2266
+ }
2267
+ if (isSource(full))
2268
+ files.push(full);
2269
+ }
2270
+ return false;
2271
+ }
2272
+ function isSource(file) {
2273
+ const base = path5.basename(file);
2274
+ if (base.endsWith(".d.ts") || base.endsWith(".min.js"))
2275
+ return false;
2276
+ if (/\.(spec|test|stories)\.[cm]?[jt]sx?$/.test(base))
2277
+ return false;
2278
+ return SOURCE_EXT.has(path5.extname(base));
2279
+ }
2280
+ function toPosix(file) {
2281
+ return file.replaceAll("\\", "/");
2282
+ }
2283
+ var SKIP_DIRS, SOURCE_EXT;
2284
+ var init_walk = __esm({
2285
+ "packages/core/dist/walk.js"() {
2286
+ "use strict";
2287
+ SKIP_DIRS = /* @__PURE__ */ new Set([
2288
+ "node_modules",
2289
+ "dist",
2290
+ "build",
2291
+ "coverage",
2292
+ ".git",
2293
+ ".next",
2294
+ ".nuxt",
2295
+ ".angular",
2296
+ ".svelte-kit",
2297
+ "out",
2298
+ ".frontend-audit",
2299
+ "android",
2300
+ "ios",
2301
+ "cypress",
2302
+ "e2e",
2303
+ ".storybook",
2304
+ "generated",
2305
+ "__tests__",
2306
+ "__mocks__",
2307
+ "storybook-static"
2308
+ ]);
2309
+ SOURCE_EXT = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".vue", ".html", ".svelte"]);
2310
+ }
2311
+ });
2312
+
2313
+ // packages/core/dist/audit.js
2314
+ import fs7 from "node:fs";
2315
+ import path6 from "node:path";
2316
+ async function runAudit(options) {
2317
+ const input = path6.resolve(options.dir);
2318
+ if (!fs7.existsSync(input))
2319
+ throw new Error(`Path does not exist: ${input}`);
2320
+ const repoRoot = resolveRepoRoot(input);
2321
+ const mode = options.mode ?? "full";
2322
+ const focus = options.focus ?? (mode === "live" ? "performance" : "all");
2323
+ const budgetMs = options.budgetMs ?? (mode === "quick" ? QUICK_BUDGET_MS : DEFAULT_BUDGET_MS);
2324
+ const maxFiles = mode === "quick" ? QUICK_MAX_FILES : MAX_FILES;
2325
+ const collectStatic = mode !== "live";
2326
+ const started = Date.now();
2327
+ const expired = () => budgetMs === 0 || Date.now() >= started + budgetMs;
2328
+ const ignore = loadIgnore(repoRoot);
2329
+ const secrets2 = /* @__PURE__ */ new Set();
2330
+ const urls = [];
2331
+ let budgetExceeded = false;
2332
+ const apps = filterApps(discoverApps(repoRoot), repoRoot, input);
2333
+ const reports = [];
2334
+ for (const app of apps) {
2335
+ if (expired()) {
2336
+ budgetExceeded = true;
2337
+ reports.push(emptyApp(app));
2338
+ continue;
2339
+ }
2340
+ const scope = scopeFor(app, input);
2341
+ const walked = listSourceFiles(app.root, scope, maxFiles);
2342
+ const findings = [];
2343
+ for (const file of walked.files) {
2344
+ if (expired()) {
2345
+ budgetExceeded = true;
2346
+ break;
2347
+ }
2348
+ let source = "";
2349
+ try {
2350
+ const stat = fs7.statSync(file);
2351
+ if (stat.size > MAX_BYTES)
2352
+ continue;
2353
+ source = fs7.readFileSync(file, "utf8");
2354
+ } catch {
2355
+ continue;
2356
+ }
2357
+ const relative = toPosix(path6.relative(repoRoot, file));
2358
+ if (collectStatic)
2359
+ findings.push(...scanSource(source, relative, app, focus, ignore, secrets2));
2360
+ if (urls.length < 2e3)
2361
+ urls.push(...extractUrls(source, relative));
2362
+ }
2363
+ const report = finishApp(app, findings, walked.truncated || budgetExceeded && walked.files.length > 0 && expired(), focus, collectStatic);
2364
+ reports.push(report);
2365
+ }
2366
+ const fixMode = mode === "live" ? "off" : options.fix ?? "off";
2367
+ if (fixMode === "dry-run") {
2368
+ for (const report of reports)
2369
+ report.pendingFixes = report.findings.filter((finding) => finding.safety === "auto").map(toApplied);
2370
+ } else if (fixMode === "safe") {
2371
+ for (const report of reports)
2372
+ applyAppFixes(report, repoRoot, focus, ignore, secrets2);
2373
+ }
2374
+ for (const report of reports) {
2375
+ report.findings = sortFindings(report.findings.filter((finding) => !isIgnored(ignore, finding.ruleId, finding.file)));
2376
+ report.clean = cleanChecks(report, focus, collectStatic);
2377
+ }
2378
+ let chrome = { attached: false, detail: mode === "quick" ? "Chrome is not used in quick mode." : "Chrome was not checked." };
2379
+ const chromeMode = mode === "quick" ? "off" : options.chrome ?? "auto";
2380
+ if (chromeMode === "auto" && focus !== "security") {
2381
+ const inspected = await inspectChrome(options.chromePort ?? DEFAULT_CHROME_PORT, budgetMs - (Date.now() - started), urls);
2382
+ chrome = inspected.info;
2383
+ const host = reports[0];
2384
+ if (host && inspected.drafts.length > 0) {
2385
+ host.findings.push(...draftsToFindings(inspected.drafts, host, focus, secrets2));
2386
+ host.findings = sortFindings(host.findings);
2387
+ }
2388
+ }
2389
+ let lighthouse = { ran: false, detail: mode === "quick" ? "Lighthouse is not used in quick mode." : "Lighthouse was not requested." };
2390
+ const lighthouseMode = mode === "quick" ? "off" : options.lighthouse ?? (mode === "live" ? options.lighthouseUrl ? "url" : "tab" : "off");
2391
+ if (lighthouseMode !== "off" && focus !== "security") {
2392
+ const port = options.chromePort ?? DEFAULT_CHROME_PORT;
2393
+ const url = lighthouseMode === "url" ? options.lighthouseUrl : await activePageUrl(port);
2394
+ if (!url) {
2395
+ lighthouse = { ran: false, detail: "Lighthouse was skipped because no Chrome tab was available." };
2396
+ } else {
2397
+ const run = await runLighthouse(url, port, options.lighthouseCategories ?? ["performance", "best-practices"], budgetMs - (Date.now() - started));
2398
+ lighthouse = run.info;
2399
+ const host = reports[0];
2400
+ if (host && run.drafts.length > 0) {
2401
+ host.findings.push(...draftsToFindings(run.drafts, host, focus, secrets2));
2402
+ host.findings = sortFindings(host.findings);
2403
+ }
2404
+ }
2405
+ }
2406
+ if (ensureAuditGitignore(repoRoot)) {
2407
+ const host = reports[0];
2408
+ host?.applied.push({
2409
+ ruleId: "project.gitignore",
2410
+ appId: host.id,
2411
+ file: ".gitignore",
2412
+ line: 1,
2413
+ title: "Keep .frontend-audit out of git"
2414
+ });
2415
+ }
2416
+ const result = {
2417
+ mode,
2418
+ repoRoot,
2419
+ apps: reports,
2420
+ chrome,
2421
+ lighthouse,
2422
+ budgetMs,
2423
+ budgetExceeded,
2424
+ reportDir: path6.join(repoRoot, ".frontend-audit"),
2425
+ summary: ""
2426
+ };
2427
+ return writeAuditReports(result, [...secrets2]);
2428
+ }
2429
+ function applyAppFixes(report, repoRoot, focus, ignore, secrets2) {
2430
+ const groups = /* @__PURE__ */ new Map();
2431
+ for (const finding of report.findings) {
2432
+ if (finding.safety !== "auto")
2433
+ continue;
2434
+ const group = groups.get(finding.file) ?? [];
2435
+ group.push(finding);
2436
+ groups.set(finding.file, group);
2437
+ }
2438
+ for (const [relative, oldFindings] of groups) {
2439
+ const absolute = path6.join(repoRoot, relative);
2440
+ if (!fs7.existsSync(absolute) || !fs7.statSync(absolute).isFile())
2441
+ continue;
2442
+ const updated = applySafeFixes(fs7.readFileSync(absolute, "utf8"));
2443
+ if (!updated.changed)
2444
+ continue;
2445
+ fs7.writeFileSync(absolute, updated.text);
2446
+ const app = {
2447
+ id: report.id,
2448
+ name: report.name,
2449
+ root: "",
2450
+ stacks: report.stacks,
2451
+ versions: report.versions,
2452
+ parsedVersions: {}
2453
+ };
2454
+ const parsed = report.versions;
2455
+ app.parsedVersions = Object.fromEntries(Object.entries(parsed).map(([key, value]) => [key, parseLoose(value)]));
2456
+ const rescanned = scanSource(updated.text, relative, app, focus, ignore, secrets2);
2457
+ report.findings = report.findings.filter((finding) => finding.file !== relative).concat(rescanned);
2458
+ const remaining = new Set(rescanned.filter((finding) => finding.safety === "auto").map((finding) => finding.ruleId));
2459
+ for (const finding of oldFindings) {
2460
+ if (!remaining.has(finding.ruleId))
2461
+ report.applied.push(toApplied(finding));
2462
+ }
2463
+ }
2464
+ }
2465
+ function parseLoose(value) {
2466
+ const match = value.match(/(\d+)\.(\d+)(?:\.(\d+))?/);
2467
+ if (!match)
2468
+ return void 0;
2469
+ return [Number(match[1]), Number(match[2]), Number(match[3] ?? 0)];
2470
+ }
2471
+ function scanSource(source, relative, app, focus, ignore, secrets2) {
2472
+ const findings = [];
2473
+ for (const rule of fileRules) {
2474
+ const entry = selectEntry(playbook, rule.id, app.stacks, app.parsedVersions);
2475
+ if (!entry || entry.advisory || !allows(focus, entry.category))
2476
+ continue;
2477
+ for (const draft of rule.run(source, relative, app.stacks)) {
2478
+ const chosen = selectEntry(playbook, draft.ruleId, app.stacks, app.parsedVersions);
2479
+ if (!chosen || !allows(focus, chosen.category) || isIgnored(ignore, draft.ruleId, relative))
2480
+ continue;
2481
+ if (draft.secretValue)
2482
+ secrets2.add(draft.secretValue);
2483
+ findings.push(toFinding(draft, chosen, app.id, draft.file ?? relative));
2484
+ }
2485
+ }
2486
+ return findings;
2487
+ }
2488
+ function draftsToFindings(drafts, app, focus, secrets2) {
2489
+ const versions = Object.fromEntries(Object.entries(app.versions).map(([key, value]) => [key, parseLoose(value)]));
2490
+ const findings = [];
2491
+ for (const draft of drafts) {
2492
+ const entry = selectEntry(playbook, draft.ruleId, app.stacks.length > 0 ? app.stacks : ["shared"], versions);
2493
+ if (!entry || !allows(focus, entry.category))
2494
+ continue;
2495
+ if (draft.secretValue)
2496
+ secrets2.add(draft.secretValue);
2497
+ findings.push(toFinding(draft, entry, app.id, draft.file ?? "(open tab)"));
2498
+ }
2499
+ return findings;
2500
+ }
2501
+ function toFinding(draft, entry, appId, file) {
2502
+ return {
2503
+ ruleId: draft.ruleId,
2504
+ appId,
2505
+ file,
2506
+ line: draft.line,
2507
+ severity: entry.severity,
2508
+ safety: entry.safety,
2509
+ category: entry.category,
2510
+ title: entry.title,
2511
+ why: entry.why,
2512
+ fix: entry.fix,
2513
+ docs: entry.docs,
2514
+ plan: entry.plan,
2515
+ ...draft.secretKind ? { secretKind: draft.secretKind } : {},
2516
+ ...draft.detail ? { detail: draft.detail } : {}
2517
+ };
2518
+ }
2519
+ function toApplied(finding) {
2520
+ return { ruleId: finding.ruleId, appId: finding.appId, file: finding.file, line: finding.line, title: finding.title };
2521
+ }
2522
+ function finishApp(app, findings, truncated, focus = "all", collectStatic = true) {
2523
+ const report = {
2524
+ id: app.id,
2525
+ name: app.name,
2526
+ root: app.root,
2527
+ label: `${app.id} \u2014 ${describeApp(app)}. Chapters: ${app.stacks.length > 0 ? app.stacks.join(", ") : "shared security"}.`,
2528
+ stacks: app.stacks,
2529
+ versions: app.versions,
2530
+ skipped: false,
2531
+ truncated,
2532
+ findings: sortFindings(findings),
2533
+ applied: [],
2534
+ pendingFixes: [],
2535
+ clean: [],
2536
+ watchNext: []
2537
+ };
2538
+ report.clean = cleanChecks(report, focus, collectStatic);
2539
+ report.watchNext = watchNext(report, focus);
2540
+ return report;
2541
+ }
2542
+ function emptyApp(app) {
2543
+ const report = finishApp(app, [], false, "all", false);
2544
+ report.skipped = true;
2545
+ return report;
2546
+ }
2547
+ function cleanChecks(app, focus, collectStatic) {
2548
+ if (!collectStatic || app.skipped)
2549
+ return [];
2550
+ const found = new Set(app.findings.map((finding) => finding.ruleId));
2551
+ const versions = Object.fromEntries(Object.entries(app.versions).map(([key, value]) => [key, parseLoose(value)]));
2552
+ const detectors = new Set(fileRules.map((rule) => rule.id));
2553
+ const items = [];
2554
+ for (const id of detectors) {
2555
+ if (found.has(id))
2556
+ continue;
2557
+ const entry = selectEntry(playbook, id, app.stacks, versions);
2558
+ if (!entry || entry.advisory || !allows(focus, entry.category))
2559
+ continue;
2560
+ items.push({ id: entry.id, title: entry.title, why: entry.why, docs: entry.docs });
2561
+ }
2562
+ return items;
2563
+ }
2564
+ function watchNext(app, focus) {
2565
+ const versions = Object.fromEntries(Object.entries(app.versions).map(([key, value]) => [key, parseLoose(value)]));
2566
+ const items = [];
2567
+ const seen = /* @__PURE__ */ new Set();
2568
+ for (const entry of playbook) {
2569
+ if (!entry.advisory || seen.has(entry.id) || !allows(focus, entry.category))
2570
+ continue;
2571
+ if (!entryMatches(entry, app.stacks, versions))
2572
+ continue;
2573
+ seen.add(entry.id);
2574
+ items.push({ id: entry.id, title: entry.title, why: entry.why, docs: entry.docs });
2575
+ }
2576
+ return items;
2577
+ }
2578
+ function sortFindings(findings) {
2579
+ const rank = { high: 0, medium: 1, low: 2 };
2580
+ return [...findings].sort((left, right) => rank[left.severity] - rank[right.severity] || left.file.localeCompare(right.file) || left.line - right.line);
2581
+ }
2582
+ function allows(focus, category) {
2583
+ if (focus === "all")
2584
+ return true;
2585
+ if (focus === "performance")
2586
+ return category === "performance" || category === "lighthouse";
2587
+ return category === "security";
2588
+ }
2589
+ function scopeFor(app, input) {
2590
+ const target = path6.resolve(input);
2591
+ if (!fs7.existsSync(target))
2592
+ return app.root;
2593
+ if (target === app.root || app.root.startsWith(target + path6.sep))
2594
+ return app.root;
2595
+ if (target.startsWith(app.root + path6.sep) || target === app.root)
2596
+ return target;
2597
+ return app.root;
2598
+ }
2599
+ var MAX_FILES, MAX_BYTES;
2600
+ var init_audit = __esm({
2601
+ "packages/core/dist/audit.js"() {
2602
+ "use strict";
2603
+ init_chrome();
2604
+ init_discover();
2605
+ init_fix();
2606
+ init_ignore();
2607
+ init_limits();
2608
+ init_lighthouse();
2609
+ init_playbook();
2610
+ init_report();
2611
+ init_rules();
2612
+ init_version();
2613
+ init_walk();
2614
+ MAX_FILES = 4e3;
2615
+ MAX_BYTES = 5e5;
2616
+ }
2617
+ });
2618
+
2619
+ // packages/core/dist/guide.js
2620
+ import fs8 from "node:fs";
2621
+ function renderGuide(dir) {
2622
+ if (dir && fs8.existsSync(dir)) {
2623
+ const root = resolveRepoRoot(dir);
2624
+ const apps = filterApps(discoverApps(root), root, dir);
2625
+ if (apps.every((app) => app.stacks.length === 0)) {
2626
+ return ["# Frontend audit guide", "", "No framework was detected in this folder. Showing every chapter.", "", renderGuide(), ""].join("\n");
2627
+ }
2628
+ const lines2 = ["# Frontend audit guide", ""];
2629
+ for (const app of apps) {
2630
+ lines2.push(`## ${app.id} \u2014 ${describeApp(app)}`, "", `Chapters: ${app.stacks.length > 0 ? app.stacks.join(", ") : "shared security"}`, "");
2631
+ lines2.push(...entriesFor(app.stacks, app.parsedVersions));
2632
+ }
2633
+ return lines2.join("\n");
2634
+ }
2635
+ const lines = ["# Frontend audit guide", "", "No project was detected. These are the shipped chapters.", ""];
2636
+ const seen = /* @__PURE__ */ new Set();
2637
+ for (const entry of playbook) {
2638
+ if (seen.has(entry.id + entry.title))
2639
+ continue;
2640
+ seen.add(entry.id + entry.title);
2641
+ lines.push(formatEntry(entry), "");
2642
+ }
2643
+ return lines.join("\n");
2644
+ }
2645
+ function entriesFor(stacks, versions) {
2646
+ const lines = [];
2647
+ const seen = /* @__PURE__ */ new Set();
2648
+ for (const entry of playbook) {
2649
+ if (seen.has(entry.id) || !entryMatches(entry, stacks, versions))
2650
+ continue;
2651
+ seen.add(entry.id);
2652
+ lines.push(formatEntry(entry), "");
2653
+ }
2654
+ return lines;
2655
+ }
2656
+ function formatEntry(entry) {
2657
+ return [
2658
+ `### ${entry.title}`,
2659
+ "",
2660
+ `\`${entry.id}\` \xB7 ${entry.severity} \xB7 ${entry.safety}`,
2661
+ "",
2662
+ entry.why,
2663
+ "",
2664
+ `Fix: ${entry.fix}`,
2665
+ "",
2666
+ "Plan:",
2667
+ ...entry.plan.map((step, index) => `${index + 1}. ${step}`),
2668
+ "",
2669
+ ...entry.docs.map((doc) => `- ${doc.title}: ${doc.url}`)
2670
+ ].join("\n");
2671
+ }
2672
+ var init_guide = __esm({
2673
+ "packages/core/dist/guide.js"() {
2674
+ "use strict";
2675
+ init_discover();
2676
+ init_playbook();
2677
+ init_version();
2678
+ }
2679
+ });
2680
+
2681
+ // packages/core/dist/text.js
2682
+ function parseAuditText(text) {
2683
+ const lower = text.toLowerCase();
2684
+ const performance = lower.includes("performance");
2685
+ const security = lower.includes("security");
2686
+ let focus = "all";
2687
+ if (performance && !security)
2688
+ focus = "performance";
2689
+ if (security && !performance)
2690
+ focus = "security";
2691
+ const match = text.match(/(?:^|[\s"'`])((?:\.\.\/|\.\/|apps\/|packages\/|projects\/|libs\/|src\/)[^\s"'`]*)/);
2692
+ return {
2693
+ focus,
2694
+ ...match?.[1] ? { relativeDir: match[1] } : {},
2695
+ lighthouse: lower.includes("lighthouse")
2696
+ };
2697
+ }
2698
+ var init_text = __esm({
2699
+ "packages/core/dist/text.js"() {
2700
+ "use strict";
2701
+ }
2702
+ });
2703
+
2704
+ // packages/core/dist/index.js
2705
+ var init_dist = __esm({
2706
+ "packages/core/dist/index.js"() {
2707
+ "use strict";
2708
+ init_audit();
2709
+ init_guide();
2710
+ init_report();
2711
+ init_text();
2712
+ init_limits();
2713
+ init_playbook();
2714
+ init_rules();
2715
+ init_version();
2716
+ }
2717
+ });
2718
+
2719
+ // packages/mcp/dist/index.js
2720
+ var dist_exports = {};
2721
+ __export(dist_exports, {
2722
+ startServer: () => startServer
2723
+ });
2724
+ import path7 from "node:path";
2725
+ import { fileURLToPath } from "node:url";
2726
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2727
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
2728
+ import { z } from "zod";
2729
+ async function startServer(options = {}) {
2730
+ const server = new McpServer({ name: "frontend-audit", version: "0.1.0" });
2731
+ const fallbackRoot = options.root ?? process.env.FRONTEND_AUDIT_ROOT;
2732
+ server.registerTool("audit_path", {
2733
+ description: "Audit a frontend repo, folder, or file for performance and client-side security issues. Detects the framework and version. Writes report.html, report.md, plan.md, and report.json to .frontend-audit in the repo. mode full is the default; quick is source-only with a 1 minute budget; live reads the open Chrome tab and runs Lighthouse, and never edits files.",
2734
+ inputSchema: {
2735
+ path: z.string().optional().describe("Repo, directory, or file. Defaults to the open workspace."),
2736
+ mode: z.enum(["full", "quick", "live"]).optional(),
2737
+ focus: z.enum(["performance", "security", "all"]).optional(),
2738
+ budgetMs: z.number().int().nonnegative().optional().describe("Wall-clock budget in milliseconds."),
2739
+ fix: z.enum(["off", "dry-run", "safe"]).optional().describe("safe applies mechanical edits, then scans those files again. Ignored in live mode."),
2740
+ lighthouse: z.enum(["off", "tab", "url"]).optional(),
2741
+ url: z.string().optional().describe("Page for Lighthouse in live mode, or with lighthouse url.")
2742
+ }
2743
+ }, async (args) => tool(async () => {
2744
+ const result = await runAudit({
2745
+ dir: await resolveDir(server, fallbackRoot, args.path),
2746
+ ...args.mode ? { mode: args.mode } : {},
2747
+ ...args.focus ? { focus: args.focus } : {},
2748
+ ...args.budgetMs !== void 0 ? { budgetMs: args.budgetMs } : {},
2749
+ ...args.fix ? { fix: args.fix } : {},
2750
+ ...args.lighthouse ? { lighthouse: args.lighthouse } : args.url ? { lighthouse: "url" } : {},
2751
+ ...args.url ? { lighthouseUrl: args.url } : {}
2752
+ });
2753
+ return result.summary;
2754
+ }));
2755
+ server.registerTool("audit_request", {
2756
+ description: 'Audit from a sentence such as "find performance problems for src/app/checkout". The framework is detected from the project.',
2757
+ inputSchema: {
2758
+ text: z.string(),
2759
+ path: z.string().optional().describe("Workspace or repo root. Defaults to the open workspace."),
2760
+ budgetMs: z.number().int().nonnegative().optional(),
2761
+ fix: z.enum(["off", "dry-run", "safe"]).optional()
2762
+ }
2763
+ }, async (args) => tool(async () => {
2764
+ const root = await resolveDir(server, fallbackRoot, args.path);
2765
+ const request = parseAuditText(args.text);
2766
+ const quick = /\bquick\b/i.test(args.text);
2767
+ const live = /\blive\b/i.test(args.text);
2768
+ const result = await runAudit({
2769
+ dir: request.relativeDir ? path7.resolve(root, request.relativeDir) : root,
2770
+ mode: live ? "live" : quick ? "quick" : "full",
2771
+ focus: request.focus,
2772
+ ...args.budgetMs !== void 0 ? { budgetMs: args.budgetMs } : {},
2773
+ ...args.fix ? { fix: args.fix } : {},
2774
+ ...request.lighthouse ? { lighthouse: "tab" } : {}
2775
+ });
2776
+ return result.summary;
2777
+ }));
2778
+ server.registerTool("watch_page", {
2779
+ description: "Read performance and network timing for the Chrome tab already open on port 9222 and correlate slow calls with project files. Report only.",
2780
+ inputSchema: {
2781
+ path: z.string().optional(),
2782
+ port: z.number().int().optional()
2783
+ }
2784
+ }, async (args) => tool(async () => {
2785
+ const result = await runAudit({
2786
+ dir: await resolveDir(server, fallbackRoot, args.path),
2787
+ mode: "live",
2788
+ lighthouse: "off",
2789
+ ...args.port ? { chromePort: args.port } : {}
2790
+ });
2791
+ return result.summary;
2792
+ }));
2793
+ server.registerTool("export_report", {
2794
+ description: "Return the path of an audit report. html, md, and json already exist after an audit. A PDF is written only when format is pdf.",
2795
+ inputSchema: {
2796
+ path: z.string().optional(),
2797
+ format: z.enum(["html", "md", "json", "pdf"])
2798
+ }
2799
+ }, async (args) => tool(async () => exportReport(await resolveDir(server, fallbackRoot, args.path), args.format)));
2800
+ server.registerTool("guide", {
2801
+ description: "Print the shipped playbook. Audits do not need this. Pass a path to limit the chapters to the detected project.",
2802
+ inputSchema: {
2803
+ path: z.string().optional()
2804
+ }
2805
+ }, async (args) => tool(async () => renderGuide(args.path)));
2806
+ server.registerPrompt("full_audit", {
2807
+ title: "Full frontend audit",
2808
+ description: "Source scan of every detected app, plus the open Chrome tab when available. Report only.",
2809
+ argsSchema: { path: z.string().optional() }
2810
+ }, (args) => prompt(`Call the frontend-audit tool audit_path with mode "full"${pathArg(args.path)}. ${NEXT_STEPS}`));
2811
+ server.registerPrompt("quick_audit", {
2812
+ title: "Quick frontend audit",
2813
+ description: "Source-only scan with a 1 minute budget. Good for a component, route, or folder.",
2814
+ argsSchema: { path: z.string().optional() }
2815
+ }, (args) => prompt(`Call the frontend-audit tool audit_path with mode "quick"${pathArg(args.path)}. ${NEXT_STEPS}`));
2816
+ server.registerPrompt("live_audit", {
2817
+ title: "Live page audit",
2818
+ description: "Read the open Chrome tab and run Lighthouse. Never edits files.",
2819
+ argsSchema: { url: z.string().optional() }
2820
+ }, (args) => prompt(`Call the frontend-audit tool audit_path with mode "live"${args.url ? ` and url "${args.url}"` : ""}. If the summary says Chrome was not attached, tell the user to start Chrome with --remote-debugging-port=9222 and open the page, and do not guess runtime results. ${NEXT_STEPS}`));
2821
+ server.registerPrompt("safe_fix", {
2822
+ title: "Apply safe fixes",
2823
+ description: "Preview the mechanical edits, then apply them after the user confirms.",
2824
+ argsSchema: { path: z.string().optional() }
2825
+ }, (args) => prompt(`Call the frontend-audit tool audit_path with fix "dry-run"${pathArg(args.path)} and show the user which files would change. Only after the user confirms, call it again with fix "safe". ${NEXT_STEPS}`));
2826
+ await server.connect(new StdioServerTransport());
2827
+ }
2828
+ async function resolveDir(server, fallbackRoot, requested) {
2829
+ if (requested && requested.trim() !== "") {
2830
+ if (path7.isAbsolute(requested))
2831
+ return requested;
2832
+ const base = await clientRoot(server) ?? fallbackRoot;
2833
+ if (base)
2834
+ return path7.resolve(base, requested);
2835
+ throw new Error(`"${requested}" is relative, and this client did not share a workspace. Pass an absolute path, or start the server with --root.`);
2836
+ }
2837
+ const root = await clientRoot(server) ?? fallbackRoot;
2838
+ if (root)
2839
+ return root;
2840
+ throw new Error("Pass an absolute path. This client did not share a workspace, and the server was started without --root or FRONTEND_AUDIT_ROOT. It does not scan its own install folder.");
2841
+ }
2842
+ async function clientRoot(server) {
2843
+ if (!server.server.getClientCapabilities()?.roots)
2844
+ return void 0;
2845
+ try {
2846
+ const listed = await server.server.listRoots();
2847
+ const uri = listed.roots.find((root) => root.uri.startsWith("file:"))?.uri;
2848
+ return uri ? fileURLToPath(uri) : void 0;
2849
+ } catch {
2850
+ return void 0;
2851
+ }
2852
+ }
2853
+ function pathArg(value) {
2854
+ return value ? ` and path "${value}"` : "";
2855
+ }
2856
+ function prompt(text) {
2857
+ return { messages: [{ role: "user", content: { type: "text", text } }] };
2858
+ }
2859
+ async function tool(work) {
2860
+ try {
2861
+ return { content: [{ type: "text", text: await work() }] };
2862
+ } catch (error) {
2863
+ const message = error instanceof Error ? error.message : "Audit failed";
2864
+ return { isError: true, content: [{ type: "text", text: message }] };
2865
+ }
2866
+ }
2867
+ var NEXT_STEPS;
2868
+ var init_dist2 = __esm({
2869
+ "packages/mcp/dist/index.js"() {
2870
+ "use strict";
2871
+ init_dist();
2872
+ NEXT_STEPS = "Then summarize the result for the user in plain language: the detected apps and versions, open findings by severity with file and line, applied fixes, and whether Chrome and Lighthouse ran. Give the path to report.html. Do not paste secret values. Offer next steps: explain a finding, run a safe fix, or apply one of the suggested fixes by hand after the user agrees.";
2873
+ }
2874
+ });
2875
+
2876
+ // packages/cli/src/index.ts
2877
+ init_dist();
2878
+ import path8 from "node:path";
2879
+
2880
+ // packages/cli/src/args.ts
2881
+ var DEFAULT_CHROME_PORT2 = 9222;
2882
+ var MODES = /* @__PURE__ */ new Set(["full", "quick", "live"]);
2883
+ var FORMATS = /* @__PURE__ */ new Set(["md", "json", "html", "pdf"]);
2884
+ var COMMANDS = /* @__PURE__ */ new Set(["audit", "watch", "export", "guide", "mcp", "help"]);
2885
+ function parseArgs(argv) {
2886
+ const args = [...argv];
2887
+ let command = "audit";
2888
+ if (args[0] && COMMANDS.has(args[0])) command = args.shift();
2889
+ else if (args[0] === "--help" || args[0] === "-h") command = "help";
2890
+ const parsed = {
2891
+ command,
2892
+ mode: "full",
2893
+ fix: "off",
2894
+ lighthouseCategories: ["performance", "best-practices"],
2895
+ port: DEFAULT_CHROME_PORT2,
2896
+ format: "md"
2897
+ };
2898
+ const text = [];
2899
+ for (let index = 0; index < args.length; index += 1) {
2900
+ const arg = args[index];
2901
+ if (arg === "--audit") continue;
2902
+ if (arg === "--help" || arg === "-h") {
2903
+ parsed.command = "help";
2904
+ continue;
2905
+ }
2906
+ if (arg === "--fix") {
2907
+ if (parsed.fix !== "dry-run") parsed.fix = "safe";
2908
+ continue;
2909
+ }
2910
+ if (arg === "--dry-run") {
2911
+ parsed.fix = "dry-run";
2912
+ continue;
2913
+ }
2914
+ if (arg === "--quick") {
2915
+ parsed.mode = "quick";
2916
+ continue;
2917
+ }
2918
+ if (arg === "--live") {
2919
+ parsed.mode = "live";
2920
+ const next = args[index + 1];
2921
+ if (next && !next.startsWith("--")) {
2922
+ parsed.lighthouseUrl = next;
2923
+ index += 1;
2924
+ }
2925
+ continue;
2926
+ }
2927
+ if (arg === "--mode") {
2928
+ const value = required(args, ++index, arg);
2929
+ if (!MODES.has(value)) throw new Error(`--mode must be full, quick, or live`);
2930
+ parsed.mode = value;
2931
+ continue;
2932
+ }
2933
+ if (arg === "--dir") {
2934
+ parsed.dir = required(args, ++index, arg);
2935
+ continue;
2936
+ }
2937
+ if (arg === "--root") {
2938
+ parsed.root = required(args, ++index, arg);
2939
+ continue;
2940
+ }
2941
+ if (arg === "--focus") {
2942
+ parsed.focus = required(args, ++index, arg);
2943
+ continue;
2944
+ }
2945
+ if (arg === "--budget") {
2946
+ parsed.budgetMs = parseBudget(required(args, ++index, arg));
2947
+ continue;
2948
+ }
2949
+ if (arg === "--port") {
2950
+ parsed.port = Number(required(args, ++index, arg));
2951
+ continue;
2952
+ }
2953
+ if (arg === "--format") {
2954
+ const value = required(args, ++index, arg);
2955
+ if (!FORMATS.has(value)) throw new Error(`--format must be md, json, html, or pdf`);
2956
+ parsed.format = value;
2957
+ continue;
2958
+ }
2959
+ if (arg === "--lighthouse-categories") {
2960
+ parsed.lighthouseCategories = required(args, ++index, arg).split(",").map((item) => item.trim()).filter(Boolean);
2961
+ continue;
2962
+ }
2963
+ if (arg === "--lighthouse") {
2964
+ const next = args[index + 1];
2965
+ if (next && !next.startsWith("--")) {
2966
+ parsed.lighthouse = "url";
2967
+ parsed.lighthouseUrl = next;
2968
+ index += 1;
2969
+ } else {
2970
+ parsed.lighthouse = "tab";
2971
+ }
2972
+ continue;
2973
+ }
2974
+ if (arg.startsWith("--")) throw new Error(`Unknown option ${arg}`);
2975
+ text.push(arg);
2976
+ }
2977
+ if (text.length > 0) parsed.text = text.join(" ");
2978
+ if (parsed.command === "watch") {
2979
+ parsed.mode = "live";
2980
+ if (!parsed.lighthouse) parsed.lighthouse = "off";
2981
+ }
2982
+ if (parsed.mode === "live" && parsed.lighthouseUrl && !parsed.lighthouse) parsed.lighthouse = "url";
2983
+ return parsed;
2984
+ }
2985
+ function parseBudget(value) {
2986
+ const match = value.match(/^(\d+)(ms|s|m)?$/);
2987
+ if (!match) throw new Error(`Cannot read budget "${value}". Use 5m, 30s, or milliseconds.`);
2988
+ const amount = Number(match[1]);
2989
+ if (match[2] === "m") return amount * 6e4;
2990
+ if (match[2] === "s") return amount * 1e3;
2991
+ return amount;
2992
+ }
2993
+ function required(args, index, flag) {
2994
+ const value = args[index];
2995
+ if (!value || value.startsWith("--")) throw new Error(`${flag} needs a value`);
2996
+ return value;
2997
+ }
2998
+ var HELP = `frontend-audit
2999
+
3000
+ Scan a frontend repo for performance and client-side security issues.
3001
+
3002
+ Modes
3003
+ frontend-audit audit --dir <path> full audit (default, 5 minute budget)
3004
+ frontend-audit audit --dir <path> --quick source only, 1 minute budget, no Chrome
3005
+ frontend-audit audit --dir <path> --live [url] open Chrome tab plus Lighthouse, report only
3006
+
3007
+ Options
3008
+ --fix apply safe mechanical edits, then scan those files again
3009
+ --fix --dry-run list those edits and write nothing
3010
+ --focus performance|security|all
3011
+ --lighthouse [url] run Lighthouse in a full audit
3012
+ --budget 5m wall-clock budget (ms, s, or m)
3013
+ --port 9222 Chrome remote debugging port
3014
+
3015
+ Other commands
3016
+ frontend-audit --audit --dir <path> --fix
3017
+ frontend-audit audit "find performance problems for src/app"
3018
+ frontend-audit watch --dir <path>
3019
+ frontend-audit export --dir <path> --format html|md|json|pdf
3020
+ frontend-audit guide
3021
+ frontend-audit mcp [--root <workspace>]
3022
+
3023
+ The framework is detected from the project. You do not pass a framework name.
3024
+ Reports go to <repo>/.frontend-audit: report.html, report.md, plan.md, report.json.
3025
+ `;
3026
+
3027
+ // packages/cli/src/index.ts
3028
+ async function main() {
3029
+ const parsed = parseArgs(process.argv.slice(2));
3030
+ if (parsed.command === "help") {
3031
+ process.stdout.write(HELP);
3032
+ return;
3033
+ }
3034
+ if (parsed.command === "mcp") {
3035
+ const { startServer: startServer2 } = await Promise.resolve().then(() => (init_dist2(), dist_exports));
3036
+ await startServer2({ ...parsed.root ? { root: path8.resolve(parsed.root) } : {} });
3037
+ return;
3038
+ }
3039
+ const cwd = process.cwd();
3040
+ let dir = parsed.dir ? path8.resolve(cwd, parsed.dir) : cwd;
3041
+ let focus = parsed.focus;
3042
+ let lighthouse = parsed.lighthouse;
3043
+ if (parsed.text) {
3044
+ const request = parseAuditText(parsed.text);
3045
+ if (!focus && request.focus !== "all") focus = request.focus;
3046
+ if (request.lighthouse && !lighthouse) lighthouse = "tab";
3047
+ if (request.relativeDir) dir = path8.resolve(dir, request.relativeDir);
3048
+ }
3049
+ if (parsed.command === "guide") {
3050
+ process.stdout.write(renderGuide(dir));
3051
+ return;
3052
+ }
3053
+ if (parsed.command === "export") {
3054
+ process.stdout.write(`${exportReport(dir, parsed.format)}
3055
+ `);
3056
+ return;
3057
+ }
3058
+ const result = await runAudit({
3059
+ dir,
3060
+ mode: parsed.mode,
3061
+ ...focus ? { focus } : {},
3062
+ ...parsed.budgetMs !== void 0 ? { budgetMs: parsed.budgetMs } : {},
3063
+ fix: parsed.fix,
3064
+ chrome: "auto",
3065
+ ...lighthouse ? { lighthouse } : {},
3066
+ ...parsed.lighthouseUrl ? { lighthouseUrl: parsed.lighthouseUrl } : {},
3067
+ lighthouseCategories: parsed.lighthouseCategories,
3068
+ chromePort: parsed.port
3069
+ });
3070
+ process.stdout.write(`${result.summary}
3071
+ `);
3072
+ }
3073
+ main().catch((error) => {
3074
+ const message = error instanceof Error ? error.message : "frontend-audit failed";
3075
+ process.stderr.write(`${message}
3076
+ `);
3077
+ process.exitCode = 1;
3078
+ });