@kodycodes/cli 3.47.0 → 3.48.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 (50) hide show
  1. package/README.md +23 -0
  2. package/dist/app-check/browser-tools.d.ts +72 -0
  3. package/dist/app-check/report.d.ts +109 -0
  4. package/dist/app-check/run-app-check.d.ts +25 -0
  5. package/dist/bin.js +1 -1
  6. package/dist/cached-npm-install.d.ts +30 -0
  7. package/dist/{chunk-XGYBIVUK.js → chunk-3DKGYN4Q.js} +2 -2
  8. package/dist/{chunk-2NSRT4L5.js → chunk-47DJTN4E.js} +2 -2
  9. package/dist/{chunk-M5L4EUF2.js → chunk-DT3SAUMT.js} +2 -2
  10. package/dist/{chunk-F5GC4QLC.js → chunk-EVGK6IY3.js} +83 -14
  11. package/dist/chunk-EVGK6IY3.js.map +6 -0
  12. package/dist/chunk-GKW646CF.js +170 -0
  13. package/dist/chunk-GKW646CF.js.map +6 -0
  14. package/dist/{chunk-WRCYQJ57.js → chunk-L4ORHUZF.js} +16 -146
  15. package/dist/chunk-L4ORHUZF.js.map +6 -0
  16. package/dist/{chunk-S3MKSHYO.js → chunk-LDCAJZWH.js} +5 -3
  17. package/dist/chunk-LDCAJZWH.js.map +6 -0
  18. package/dist/cli.d.ts +2 -1
  19. package/dist/cli.js +1 -1
  20. package/dist/{commands-PEKGP2T7.js → commands-A4WYM7MB.js} +2 -2
  21. package/dist/{dev-command-CO2LJ5H6.js → dev-command-QZHEF7TI.js} +6 -5
  22. package/dist/dev-command-QZHEF7TI.js.map +6 -0
  23. package/dist/{execute-local-package-LBUVTXNQ.js → execute-local-package-TPS5PA5Y.js} +5 -4
  24. package/dist/execute-local-package-TPS5PA5Y.js.map +6 -0
  25. package/dist/{local-execute-WU2VVDEQ.js → local-execute-XG2GEGTQ.js} +3 -2
  26. package/dist/local-execute-XG2GEGTQ.js.map +6 -0
  27. package/dist/{local-kody-JHFC4YKZ.js → local-kody-EQCQHPKF.js} +4 -3
  28. package/dist/{local-package-run-JYHWVV77.js → local-package-run-JREJCWDW.js} +4 -3
  29. package/dist/mock/ensure-msw.d.ts +0 -6
  30. package/dist/{mock-fetch-gateway-3QFVMR6R.js → mock-fetch-gateway-N5IKHGZM.js} +3 -2
  31. package/dist/{mock-server-TZLF3XME.js → mock-server-S5C3IINS.js} +4 -3
  32. package/dist/run-app-check-QDQQY4LU.js +800 -0
  33. package/dist/run-app-check-QDQQY4LU.js.map +6 -0
  34. package/dist/{run-executor-H7WSZMLV.js → run-executor-6JJ3T3WB.js} +2 -2
  35. package/package.json +1 -1
  36. package/dist/chunk-F5GC4QLC.js.map +0 -6
  37. package/dist/chunk-S3MKSHYO.js.map +0 -6
  38. package/dist/chunk-WRCYQJ57.js.map +0 -6
  39. package/dist/dev-command-CO2LJ5H6.js.map +0 -6
  40. package/dist/execute-local-package-LBUVTXNQ.js.map +0 -6
  41. package/dist/local-execute-WU2VVDEQ.js.map +0 -6
  42. /package/dist/{chunk-XGYBIVUK.js.map → chunk-3DKGYN4Q.js.map} +0 -0
  43. /package/dist/{chunk-2NSRT4L5.js.map → chunk-47DJTN4E.js.map} +0 -0
  44. /package/dist/{chunk-M5L4EUF2.js.map → chunk-DT3SAUMT.js.map} +0 -0
  45. /package/dist/{commands-PEKGP2T7.js.map → commands-A4WYM7MB.js.map} +0 -0
  46. /package/dist/{local-kody-JHFC4YKZ.js.map → local-kody-EQCQHPKF.js.map} +0 -0
  47. /package/dist/{local-package-run-JYHWVV77.js.map → local-package-run-JREJCWDW.js.map} +0 -0
  48. /package/dist/{mock-fetch-gateway-3QFVMR6R.js.map → mock-fetch-gateway-N5IKHGZM.js.map} +0 -0
  49. /package/dist/{mock-server-TZLF3XME.js.map → mock-server-S5C3IINS.js.map} +0 -0
  50. /package/dist/{run-executor-H7WSZMLV.js.map → run-executor-6JJ3T3WB.js.map} +0 -0
@@ -0,0 +1,800 @@
1
+ import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
+ import {
3
+ ensureCachedNpmPackages
4
+ } from "./chunk-GKW646CF.js";
5
+ import "./chunk-LQNGII7U.js";
6
+ import {
7
+ loadPackageManifest
8
+ } from "./chunk-EMEUJKXR.js";
9
+ import {
10
+ StructuredCliError
11
+ } from "./chunk-42R5NM3P.js";
12
+ import {
13
+ userCacheDir
14
+ } from "./chunk-VHYJU2U2.js";
15
+ import "./chunk-YVWOK4LV.js";
16
+ import "./chunk-UW6AWLXX.js";
17
+
18
+ // src/app-check/run-app-check.ts
19
+ import { spawn as spawn2 } from "node:child_process";
20
+ import { mkdir, writeFile } from "node:fs/promises";
21
+ import { createServer } from "node:net";
22
+ import { join as join2, resolve } from "node:path";
23
+ import { createInterface } from "node:readline";
24
+
25
+ // src/app-check/browser-tools.ts
26
+ import { spawn } from "node:child_process";
27
+ import { existsSync } from "node:fs";
28
+ import { createRequire } from "node:module";
29
+ import { join } from "node:path";
30
+ import { pathToFileURL } from "node:url";
31
+ var appCheckDependencies = {
32
+ "playwright-core": "1.63.0",
33
+ lighthouse: "13.6.0",
34
+ "axe-core": "4.14.0",
35
+ "chrome-launcher": "1.2.3"
36
+ };
37
+ function appCheckToolsRoot(cacheDir) {
38
+ const key = Object.entries(appCheckDependencies).map(([name, version]) => `${name.replace("/", "+")}@${version}`).join("_");
39
+ return join(cacheDir, "deps", "app-check", key);
40
+ }
41
+ async function loadAppCheckTools(input) {
42
+ const env = input.env ?? process.env;
43
+ const root = appCheckToolsRoot(userCacheDir(env));
44
+ try {
45
+ await ensureCachedNpmPackages({
46
+ root,
47
+ dependencies: { ...appCheckDependencies },
48
+ env,
49
+ timeoutMs: 3e5,
50
+ onInstall: () => input.onStatus(
51
+ "kody app check: installing Playwright, axe-core, and Lighthouse into the Kody cache (first run only)\u2026"
52
+ )
53
+ });
54
+ } catch (error) {
55
+ throw toolsInstallFailedError({
56
+ reason: error instanceof Error ? error.message : String(error),
57
+ root
58
+ });
59
+ }
60
+ const require2 = createRequire(join(root, "package.json"));
61
+ const importFromCache = async (specifier) => await import(pathToFileURL(require2.resolve(specifier)).href);
62
+ const playwright = await importFromCache("playwright-core");
63
+ const chromium = playwright.default.chromium;
64
+ await ensureChromium({ chromium, root, env, onStatus: input.onStatus });
65
+ const axe = await importFromCache("axe-core");
66
+ const axeSource = axe.default.source;
67
+ const lighthouse = (await importFromCache("lighthouse")).default;
68
+ const launch = (await importFromCache("chrome-launcher")).launch;
69
+ return { chromium, axeSource, lighthouse, launchChrome: launch };
70
+ }
71
+ async function ensureChromium(input) {
72
+ if (existsSync(input.chromium.executablePath())) return;
73
+ input.onStatus(
74
+ "kody app check: downloading the Playwright Chromium browser (first run only)\u2026"
75
+ );
76
+ const require2 = createRequire(join(input.root, "package.json"));
77
+ const cli = join(
78
+ require2.resolve("playwright-core/package.json"),
79
+ "..",
80
+ "cli.js"
81
+ );
82
+ const reason = await new Promise((resolve2) => {
83
+ const child = spawn(
84
+ process.execPath,
85
+ [cli, "install", "chromium", "--no-shell"],
86
+ {
87
+ env: input.env,
88
+ windowsHide: true,
89
+ stdio: ["ignore", "ignore", "pipe"]
90
+ }
91
+ );
92
+ let stderr = "";
93
+ child.stderr?.on("data", (chunk) => {
94
+ stderr = `${stderr}${chunk.toString("utf8")}`.slice(-16e3);
95
+ });
96
+ const timer = setTimeout(() => {
97
+ child.kill("SIGTERM");
98
+ resolve2("the download timed out after 600s");
99
+ }, 6e5);
100
+ child.on("error", (error) => {
101
+ clearTimeout(timer);
102
+ resolve2(error.message);
103
+ });
104
+ child.on("close", (code) => {
105
+ clearTimeout(timer);
106
+ resolve2(
107
+ code === 0 ? null : stderr.trim().split("\n").at(-1) ?? `playwright install exited ${code}`
108
+ );
109
+ });
110
+ });
111
+ if (reason !== null || !existsSync(input.chromium.executablePath())) {
112
+ throw new StructuredCliError({
113
+ code: "browser_download_failed",
114
+ message: `Could not download the Playwright Chromium browser for kody app check (${reason ?? "the browser executable is still missing"}).`,
115
+ where: input.chromium.executablePath(),
116
+ fix: "Connect to the network and run `kody app check` again. Behind a proxy, set HTTPS_PROXY. To use a browser folder you already have, set PLAYWRIGHT_BROWSERS_PATH."
117
+ });
118
+ }
119
+ }
120
+ function toolsInstallFailedError(input) {
121
+ const specs = Object.entries(appCheckDependencies).map(([name, version]) => `${name}@${version}`).join(" ");
122
+ return new StructuredCliError({
123
+ code: "app_check_tools_install_failed",
124
+ message: `Could not install the kody app check tools (${input.reason}).`,
125
+ where: input.root,
126
+ fix: `Connect to the network and run \`kody app check\` again so the CLI can install ${specs} into the Kody cache. Offline? Set KODY_CACHE_DIR to a writable cache where those packages are already installed.`,
127
+ details: { packages: specs, cacheDir: input.root }
128
+ });
129
+ }
130
+
131
+ // src/app-check/report.ts
132
+ var lighthouseCategories = [
133
+ "performance",
134
+ "accessibility",
135
+ "best-practices",
136
+ "seo"
137
+ ];
138
+ var lighthouseThresholds = {
139
+ performance: 50,
140
+ accessibility: 90,
141
+ "best-practices": 90,
142
+ seo: 90
143
+ };
144
+ var impactRank = {
145
+ critical: 0,
146
+ serious: 1,
147
+ moderate: 2,
148
+ minor: 3
149
+ };
150
+ var markdownListLimit = 10;
151
+ var markdownSelectorLimit = 3;
152
+ function mergeAccessibilityRules(variants) {
153
+ const byId = /* @__PURE__ */ new Map();
154
+ for (const variant of variants) {
155
+ const variantKey = `${variant.viewport}-${variant.colorScheme}`;
156
+ for (const violation of variant.violations) {
157
+ const impact = violation.impact ?? "minor";
158
+ const existing = byId.get(violation.id);
159
+ const rule = existing ?? {
160
+ id: violation.id,
161
+ impact,
162
+ help: violation.help,
163
+ helpUrl: violation.helpUrl,
164
+ selectors: [],
165
+ variants: []
166
+ };
167
+ if (impactRank[impact] < impactRank[rule.impact]) rule.impact = impact;
168
+ if (!rule.variants.includes(variantKey)) rule.variants.push(variantKey);
169
+ for (const node of violation.nodes) {
170
+ const selector = node.target.join(" ");
171
+ if (!rule.selectors.includes(selector)) rule.selectors.push(selector);
172
+ }
173
+ byId.set(violation.id, rule);
174
+ }
175
+ }
176
+ return [...byId.values()].sort(
177
+ (a, b) => impactRank[a.impact] - impactRank[b.impact] || b.selectors.length - a.selectors.length || a.id.localeCompare(b.id)
178
+ );
179
+ }
180
+ function dedupeConsoleErrors(entries) {
181
+ const byMessage = /* @__PURE__ */ new Map();
182
+ for (const entry of entries) {
183
+ const message = entry.message.trim();
184
+ if (!message) continue;
185
+ const existing = byMessage.get(message);
186
+ if (existing) {
187
+ existing.count += 1;
188
+ if (!existing.sources.includes(entry.source))
189
+ existing.sources.push(entry.source);
190
+ continue;
191
+ }
192
+ byMessage.set(message, { message, sources: [entry.source], count: 1 });
193
+ }
194
+ return [...byMessage.values()].sort((a, b) => b.count - a.count);
195
+ }
196
+ function categoryLabel(category) {
197
+ switch (category) {
198
+ case "performance":
199
+ return "Performance";
200
+ case "accessibility":
201
+ return "Accessibility";
202
+ case "best-practices":
203
+ return "Best practices";
204
+ case "seo":
205
+ return "SEO";
206
+ }
207
+ }
208
+ function firstLine(text) {
209
+ return text.split("\n")[0]?.trim() ?? "";
210
+ }
211
+ function sentence(text) {
212
+ return /[.!?]$/.test(text) ? text : `${text}.`;
213
+ }
214
+ function collectIssues(input) {
215
+ const issues = [];
216
+ const badStatus = input.screenshots.find(
217
+ (shot) => shot.status !== null && shot.status >= 400
218
+ );
219
+ if (badStatus) {
220
+ issues.push({
221
+ kind: "page_status",
222
+ message: `The page responded with HTTP ${badStatus.status}. Fix the app so its root route renders.`
223
+ });
224
+ }
225
+ for (const error of input.consoleErrors) {
226
+ issues.push({
227
+ kind: "console",
228
+ message: `Console error: ${sentence(firstLine(error.message))}`
229
+ });
230
+ }
231
+ for (const rule of input.rules) {
232
+ if (rule.impact !== "critical" && rule.impact !== "serious") continue;
233
+ issues.push({
234
+ kind: "accessibility",
235
+ message: `Accessibility (${rule.impact}) ${rule.id}: ${rule.help} (${rule.selectors[0] ?? "page"}).`
236
+ });
237
+ }
238
+ if (input.lighthouse.error) {
239
+ issues.push({
240
+ kind: "lighthouse",
241
+ message: `Lighthouse could not score the page: ${sentence(firstLine(input.lighthouse.error))}`
242
+ });
243
+ }
244
+ const belowThreshold = lighthouseCategories.map((category) => ({
245
+ category,
246
+ score: input.lighthouse.scores[category]
247
+ })).filter(
248
+ (entry) => entry.score !== null && entry.score < lighthouseThresholds[entry.category]
249
+ ).sort(
250
+ (a, b) => a.score - lighthouseThresholds[a.category] - (b.score - lighthouseThresholds[b.category])
251
+ );
252
+ for (const { category, score } of belowThreshold) {
253
+ issues.push({
254
+ kind: "lighthouse",
255
+ message: `Lighthouse ${categoryLabel(category).toLowerCase()} is ${score} (target ${lighthouseThresholds[category]} or more).`
256
+ });
257
+ }
258
+ return issues;
259
+ }
260
+ function summarize(input) {
261
+ const [top, ...rest] = input.issues;
262
+ if (top) {
263
+ const more = rest.length > 0 ? ` ${rest.length === 1 ? "1 more issue follows" : `${rest.length} more issues follow`} below.` : "";
264
+ return `Result: FAIL. Most important issue: ${top.message}${more} Fix the issues, then run \`kody app check\` again.`;
265
+ }
266
+ const minor = input.rules[0];
267
+ return minor ? `Result: PASS. No console errors, no critical or serious accessibility violations, and Lighthouse scores meet their targets. Worth fixing next: ${minor.id} (${minor.impact}): ${minor.help}.` : "Result: PASS. No console errors, no accessibility violations, and Lighthouse scores meet their targets.";
268
+ }
269
+ function buildAppCheckReport(input) {
270
+ const rules = mergeAccessibilityRules(input.axe);
271
+ const consoleErrors = dedupeConsoleErrors(input.consoleEntries);
272
+ const issues = collectIssues({
273
+ screenshots: input.screenshots,
274
+ rules,
275
+ lighthouse: input.lighthouse,
276
+ consoleErrors
277
+ });
278
+ for (const variant of input.axe) {
279
+ if (!variant.error) continue;
280
+ issues.push({
281
+ kind: "accessibility",
282
+ message: `axe could not check ${variant.viewport} ${variant.colorScheme}: ${sentence(firstLine(variant.error))}`
283
+ });
284
+ }
285
+ return {
286
+ version: 1,
287
+ result: issues.length === 0 ? "pass" : "fail",
288
+ summary: summarize({ issues, rules }),
289
+ package: input.package,
290
+ url: input.url,
291
+ target: input.target,
292
+ checkedAt: input.checkedAt,
293
+ outputDir: input.outputDir,
294
+ issues,
295
+ screenshots: input.screenshots,
296
+ accessibility: { rules, variants: input.axe },
297
+ lighthouse: { ...input.lighthouse, thresholds: lighthouseThresholds },
298
+ console: { errors: consoleErrors, entries: input.consoleEntries }
299
+ };
300
+ }
301
+ function inlineCode(text) {
302
+ const clean = text.replace(/\s+/g, " ").trim();
303
+ const fence = clean.includes("`") ? "``" : "`";
304
+ return `${fence}${clean}${fence}`;
305
+ }
306
+ function truncate(text, max) {
307
+ return text.length > max ? `${text.slice(0, max - 3)}...` : text;
308
+ }
309
+ function remainder(count, noun) {
310
+ return count > 0 ? ["", `And ${count} more ${noun} in app-check.json.`] : [];
311
+ }
312
+ function formatAppCheckMarkdown(report) {
313
+ const lines = [
314
+ `# kody app check: ${report.package.name}`,
315
+ "",
316
+ report.summary,
317
+ "",
318
+ `Checked ${report.url} (target ${report.target}) at ${report.checkedAt}.`,
319
+ "",
320
+ "## Screenshots",
321
+ ""
322
+ ];
323
+ for (const shot of report.screenshots) {
324
+ lines.push(`- ${shot.viewport} ${shot.colorScheme}: ${shot.path}`);
325
+ }
326
+ lines.push("", "## Accessibility violations", "");
327
+ const rules = report.accessibility.rules;
328
+ if (rules.length === 0) {
329
+ lines.push("None found.");
330
+ } else {
331
+ for (const rule of rules.slice(0, markdownListLimit)) {
332
+ const selectors = rule.selectors.slice(0, markdownSelectorLimit).map((selector) => inlineCode(truncate(selector, 120))).join(", ");
333
+ const extraSelectors = rule.selectors.length - markdownSelectorLimit;
334
+ lines.push(
335
+ `- **${rule.impact}** ${rule.id}: ${rule.help}. Selectors: ${selectors}${extraSelectors > 0 ? ` and ${extraSelectors} more` : ""}. ${rule.helpUrl}`
336
+ );
337
+ }
338
+ lines.push(
339
+ ...remainder(
340
+ rules.length - markdownListLimit,
341
+ rules.length - markdownListLimit === 1 ? "rule" : "rules"
342
+ )
343
+ );
344
+ }
345
+ const axeErrors = report.accessibility.variants.filter(
346
+ (variant) => variant.error
347
+ );
348
+ for (const variant of axeErrors) {
349
+ lines.push(
350
+ "",
351
+ `axe could not check ${variant.viewport} ${variant.colorScheme}: ${firstLine(variant.error ?? "")}`
352
+ );
353
+ }
354
+ lines.push("", "## Lighthouse scores", "");
355
+ if (report.lighthouse.error) {
356
+ lines.push(
357
+ `Lighthouse could not score the page: ${firstLine(report.lighthouse.error)}`,
358
+ ""
359
+ );
360
+ }
361
+ for (const category of lighthouseCategories) {
362
+ const score = report.lighthouse.scores[category];
363
+ lines.push(
364
+ `- ${categoryLabel(category)}: ${score ?? "not scored"} (target ${lighthouseThresholds[category]})`
365
+ );
366
+ }
367
+ lines.push("", "## Console errors", "");
368
+ const errors = report.console.errors;
369
+ if (errors.length === 0) {
370
+ lines.push("None.");
371
+ } else {
372
+ for (const error of errors.slice(0, markdownListLimit)) {
373
+ lines.push(
374
+ `- ${inlineCode(truncate(firstLine(error.message), 300))}${error.count > 1 ? ` (${error.count} times)` : ""}`
375
+ );
376
+ }
377
+ lines.push(
378
+ ...remainder(
379
+ errors.length - markdownListLimit,
380
+ errors.length - markdownListLimit === 1 ? "error" : "errors"
381
+ )
382
+ );
383
+ }
384
+ lines.push("");
385
+ return lines.join("\n");
386
+ }
387
+
388
+ // src/app-check/run-app-check.ts
389
+ var viewports = {
390
+ desktop: {
391
+ viewport: { width: 1280, height: 800 },
392
+ deviceScaleFactor: 1,
393
+ isMobile: false,
394
+ hasTouch: false
395
+ },
396
+ mobile: {
397
+ viewport: { width: 390, height: 844 },
398
+ deviceScaleFactor: 2,
399
+ isMobile: true,
400
+ hasTouch: true
401
+ }
402
+ };
403
+ var colorSchemes = ["light", "dark"];
404
+ var previewReadyTimeoutMs = 18e4;
405
+ var pageTimeoutMs = 3e4;
406
+ function defaultAppCheckOutputDir(packageRoot) {
407
+ return join2(packageRoot, ".kody", "app-check");
408
+ }
409
+ async function runAppCheck(input) {
410
+ const manifest = await loadPackageManifest(
411
+ resolve(input.packageDir ?? process.cwd())
412
+ );
413
+ if (!manifest.app) {
414
+ throw new StructuredCliError({
415
+ code: "dev_surface_missing",
416
+ message: `${manifest.name} has no kody.app.entry, so there is no app to check.`,
417
+ where: manifest.root,
418
+ fix: 'Set `"kody": { "app": { "entry": "./app/router.ts" } }` in package.json, then run `kody app check` again.'
419
+ });
420
+ }
421
+ const outputDir = resolve(
422
+ input.outputDir ?? defaultAppCheckOutputDir(manifest.root)
423
+ );
424
+ const ownsOutputDir = input.outputDir === void 0;
425
+ const status = (message) => input.io.stderr(`${message}
426
+ `);
427
+ const tools = await loadAppCheckTools({
428
+ ...input.env ? { env: input.env } : {},
429
+ onStatus: status
430
+ });
431
+ await mkdir(outputDir, { recursive: true });
432
+ if (ownsOutputDir) await writeFile(join2(outputDir, ".gitignore"), "*\n");
433
+ const consoleEntries = [];
434
+ status(`kody app check: starting the kody dev preview for ${manifest.name}\u2026`);
435
+ const preview = await startDevPreview({
436
+ packageRoot: manifest.root,
437
+ target: input.target,
438
+ ...input.org ? { org: input.org } : {},
439
+ ...input.env ? { env: input.env } : {},
440
+ onServerError: (message) => consoleEntries.push({ source: "server", message })
441
+ });
442
+ let report;
443
+ try {
444
+ status(`kody app check: rendering ${preview.url}\u2026`);
445
+ const browser = await launchBrowser(tools);
446
+ let screenshots;
447
+ let axe;
448
+ try {
449
+ ;
450
+ ({ screenshots, axe } = await renderVariants({
451
+ browser,
452
+ tools,
453
+ url: preview.url,
454
+ outputDir,
455
+ consoleEntries,
456
+ onStatus: status
457
+ }));
458
+ } finally {
459
+ await browser.close().catch(
460
+ (error) => status(
461
+ `kody app check: could not close the browser (${errorText(error)}).`
462
+ )
463
+ );
464
+ }
465
+ status("kody app check: running Lighthouse\u2026");
466
+ const lighthouse = await runLighthouse({ tools, url: preview.url });
467
+ report = buildAppCheckReport({
468
+ package: { name: manifest.name, root: manifest.root },
469
+ url: preview.url,
470
+ target: input.target,
471
+ checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
472
+ outputDir,
473
+ screenshots,
474
+ axe,
475
+ lighthouse,
476
+ consoleEntries
477
+ });
478
+ } finally {
479
+ await preview.close();
480
+ }
481
+ const markdownPath = join2(outputDir, "app-check.md");
482
+ const jsonPath = join2(outputDir, "app-check.json");
483
+ await writeFile(markdownPath, formatAppCheckMarkdown(report));
484
+ await writeFile(jsonPath, `${JSON.stringify(report, null, 2)}
485
+ `);
486
+ if (input.json) {
487
+ input.io.stdout(
488
+ `${JSON.stringify({
489
+ result: report.result,
490
+ summary: report.summary,
491
+ markdown: markdownPath,
492
+ json: jsonPath
493
+ })}
494
+ `
495
+ );
496
+ } else {
497
+ input.io.stdout(
498
+ `${report.summary}
499
+
500
+ Report: ${markdownPath}
501
+ Full results: ${jsonPath}
502
+ `
503
+ );
504
+ }
505
+ return 0;
506
+ }
507
+ async function freePort() {
508
+ return await new Promise((resolvePort, reject) => {
509
+ const server = createServer();
510
+ server.once("error", reject);
511
+ server.listen(0, "127.0.0.1", () => {
512
+ const address = server.address();
513
+ const port = typeof address === "object" && address ? address.port : 0;
514
+ server.close(() => resolvePort(port));
515
+ });
516
+ });
517
+ }
518
+ async function startDevPreview(input) {
519
+ const cliEntry = process.argv[1];
520
+ if (!cliEntry) {
521
+ throw new StructuredCliError({
522
+ code: "app_check_preview_failed",
523
+ message: "Could not find the running kody CLI entry to start the preview.",
524
+ fix: "Run `kody app check` through the `kody` command."
525
+ });
526
+ }
527
+ const port = await freePort();
528
+ const child = spawn2(
529
+ process.execPath,
530
+ [
531
+ ...process.execArgv,
532
+ cliEntry,
533
+ "dev",
534
+ "serve",
535
+ "--json",
536
+ "--no-live-reload",
537
+ "--port",
538
+ String(port),
539
+ "--target",
540
+ input.target,
541
+ ...input.org ? ["--org", input.org] : []
542
+ ],
543
+ {
544
+ cwd: input.packageRoot,
545
+ env: input.env ?? process.env,
546
+ stdio: ["ignore", "pipe", "pipe"],
547
+ windowsHide: true
548
+ }
549
+ );
550
+ let stderrTail = "";
551
+ child.stderr?.on("data", (chunk) => {
552
+ stderrTail = `${stderrTail}${chunk.toString("utf8")}`.slice(-8e3);
553
+ });
554
+ const exitCodes = {
555
+ SIGINT: 130,
556
+ SIGTERM: 143,
557
+ SIGHUP: 129
558
+ };
559
+ const onSignal = (signal) => {
560
+ void stopChild(child).finally(() => process.exit(exitCodes[signal] ?? 1));
561
+ };
562
+ for (const signal of Object.keys(exitCodes)) {
563
+ process.once(signal, onSignal);
564
+ }
565
+ const close = async () => {
566
+ for (const signal of Object.keys(exitCodes)) {
567
+ process.off(signal, onSignal);
568
+ }
569
+ await stopChild(child);
570
+ };
571
+ const ready = new Promise((resolveReady, reject) => {
572
+ const timer = setTimeout(() => {
573
+ reject(
574
+ previewFailedError(
575
+ `it was not ready after ${previewReadyTimeoutMs / 1e3}s`,
576
+ stderrTail
577
+ )
578
+ );
579
+ }, previewReadyTimeoutMs);
580
+ child.once("error", (error) => {
581
+ clearTimeout(timer);
582
+ reject(previewFailedError(error.message, stderrTail));
583
+ });
584
+ child.once("exit", (code) => {
585
+ clearTimeout(timer);
586
+ reject(
587
+ previewFailedError(`kody dev exited with code ${code}`, stderrTail)
588
+ );
589
+ });
590
+ const lines = createInterface({ input: child.stdout });
591
+ lines.on("line", (line) => {
592
+ let event;
593
+ try {
594
+ event = JSON.parse(line);
595
+ } catch {
596
+ return;
597
+ }
598
+ if (event.type === "ready") {
599
+ clearTimeout(timer);
600
+ resolveReady(event.url);
601
+ return;
602
+ }
603
+ const message = serverErrorMessage(event);
604
+ if (message) input.onServerError(message);
605
+ });
606
+ });
607
+ try {
608
+ return { url: await ready, close };
609
+ } catch (error) {
610
+ await close();
611
+ throw error;
612
+ }
613
+ }
614
+ function serverErrorMessage(event) {
615
+ switch (event.type) {
616
+ case "runtime_error":
617
+ return event.request ? `${event.message} (${event.request.method} ${event.request.path})` : event.message;
618
+ case "build_error":
619
+ return event.file ? `Build error in ${event.file}${event.line !== null ? `:${event.line}` : ""}: ${event.message}` : `Build error: ${event.message}`;
620
+ case "log":
621
+ return event.level === "error" ? event.message : null;
622
+ default:
623
+ return null;
624
+ }
625
+ }
626
+ function previewFailedError(reason, stderr) {
627
+ const tail = stderr.trim().split("\n").slice(-5).join("\n");
628
+ return new StructuredCliError({
629
+ code: "app_check_preview_failed",
630
+ message: `The kody dev preview did not start (${reason}).${tail ? `
631
+ ${tail}` : ""}`,
632
+ fix: "Run `kody dev` in the package to see the full error, fix it, then run `kody app check` again."
633
+ });
634
+ }
635
+ async function stopChild(child) {
636
+ if (child.exitCode !== null || child.signalCode !== null) return;
637
+ const exited = new Promise(
638
+ (resolveExit) => child.once("exit", () => resolveExit())
639
+ );
640
+ child.kill("SIGTERM");
641
+ const timer = setTimeout(() => child.kill("SIGKILL"), 1e4);
642
+ await exited;
643
+ clearTimeout(timer);
644
+ }
645
+ async function launchBrowser(tools) {
646
+ try {
647
+ return await tools.chromium.launch({ headless: true, channel: "chromium" });
648
+ } catch (error) {
649
+ throw new StructuredCliError({
650
+ code: "browser_launch_failed",
651
+ message: `Could not launch Playwright Chromium (${error instanceof Error ? firstLine2(error.message) : String(error)}).`,
652
+ where: tools.chromium.executablePath(),
653
+ fix: "On Linux, install the browser system libraries with `npx playwright install-deps chromium`, then run `kody app check` again."
654
+ });
655
+ }
656
+ }
657
+ function errorText(error) {
658
+ return error instanceof Error ? error.message : String(error);
659
+ }
660
+ function firstLine2(text) {
661
+ return text.split("\n")[0]?.trim() ?? "";
662
+ }
663
+ async function renderVariants(input) {
664
+ const screenshots = [];
665
+ const axe = [];
666
+ for (const viewport of ["desktop", "mobile"]) {
667
+ for (const colorScheme of colorSchemes) {
668
+ const context = await input.browser.newContext({
669
+ ...viewports[viewport],
670
+ colorScheme
671
+ });
672
+ try {
673
+ const page = await context.newPage();
674
+ page.on("console", (message) => {
675
+ const msg = message;
676
+ if (msg.type() !== "error") return;
677
+ const url = msg.location().url;
678
+ input.consoleEntries.push({
679
+ source: "browser",
680
+ message: msg.text(),
681
+ viewport,
682
+ colorScheme,
683
+ ...url ? { url } : {}
684
+ });
685
+ });
686
+ page.on("pageerror", (error) => {
687
+ const err = error;
688
+ input.consoleEntries.push({
689
+ source: "page",
690
+ message: err.message || String(err),
691
+ viewport,
692
+ colorScheme
693
+ });
694
+ });
695
+ const variant = `${viewport} ${colorScheme}`;
696
+ const response = await page.goto(input.url, { waitUntil: "load", timeout: pageTimeoutMs }).catch((error) => {
697
+ input.consoleEntries.push({
698
+ source: "page",
699
+ message: `Page did not finish loading: ${firstLine2(errorText(error))}`,
700
+ viewport,
701
+ colorScheme
702
+ });
703
+ return null;
704
+ });
705
+ await page.waitForLoadState("networkidle", { timeout: 5e3 }).catch(
706
+ () => input.onStatus(
707
+ `kody app check: ${variant} still had network activity after 5s; capturing it as is.`
708
+ )
709
+ );
710
+ const path = join2(input.outputDir, `${viewport}-${colorScheme}.png`);
711
+ await page.screenshot({ path, fullPage: true });
712
+ screenshots.push({
713
+ viewport,
714
+ colorScheme,
715
+ path,
716
+ status: response ? response.status() : null
717
+ });
718
+ axe.push({
719
+ viewport,
720
+ colorScheme,
721
+ ...await runAxe(page, input.tools.axeSource)
722
+ });
723
+ } finally {
724
+ await context.close().catch(
725
+ (error) => input.onStatus(
726
+ `kody app check: could not close the ${viewport} ${colorScheme} page (${errorText(error)}).`
727
+ )
728
+ );
729
+ }
730
+ }
731
+ }
732
+ return { screenshots, axe };
733
+ }
734
+ async function runAxe(page, axeSource) {
735
+ try {
736
+ await page.addScriptTag({ content: axeSource });
737
+ const violations = await page.evaluate(async () => {
738
+ const axe = globalThis.axe;
739
+ const result = await axe.run();
740
+ return result.violations.map((violation) => ({
741
+ id: violation.id,
742
+ impact: violation.impact,
743
+ help: violation.help,
744
+ helpUrl: violation.helpUrl,
745
+ description: violation.description,
746
+ nodes: violation.nodes.map((node) => ({
747
+ target: node.target.map(String),
748
+ html: node.html,
749
+ failureSummary: node.failureSummary
750
+ }))
751
+ }));
752
+ });
753
+ return { violations };
754
+ } catch (error) {
755
+ return {
756
+ violations: [],
757
+ error: error instanceof Error ? error.message : String(error)
758
+ };
759
+ }
760
+ }
761
+ async function runLighthouse(input) {
762
+ const empty = Object.fromEntries(
763
+ lighthouseCategories.map((category) => [category, null])
764
+ );
765
+ let chrome;
766
+ try {
767
+ chrome = await input.tools.launchChrome({
768
+ chromePath: input.tools.chromium.executablePath(),
769
+ chromeFlags: ["--headless=new", "--no-sandbox", "--disable-gpu"]
770
+ });
771
+ const result = await input.tools.lighthouse(input.url, {
772
+ port: chrome.port,
773
+ output: "json",
774
+ logLevel: "error",
775
+ onlyCategories: [...lighthouseCategories]
776
+ });
777
+ const lhr = result?.lhr;
778
+ if (!lhr) return { scores: empty, error: "Lighthouse returned no result." };
779
+ const scores = { ...empty };
780
+ for (const category of lighthouseCategories) {
781
+ const score = lhr.categories[category]?.score;
782
+ scores[category] = typeof score === "number" ? Math.round(score * 100) : null;
783
+ }
784
+ return {
785
+ scores,
786
+ ...lhr.runtimeError?.message ? { error: lhr.runtimeError.message } : {}
787
+ };
788
+ } catch (error) {
789
+ return {
790
+ scores: empty,
791
+ error: error instanceof Error ? error.message : String(error)
792
+ };
793
+ } finally {
794
+ await chrome?.kill();
795
+ }
796
+ }
797
+ export {
798
+ runAppCheck
799
+ };
800
+ //# sourceMappingURL=run-app-check-QDQQY4LU.js.map