@blundergoat/gruff-ts 0.1.0 → 0.2.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.
- package/CHANGELOG.md +35 -11
- package/CONTRIBUTING.md +3 -3
- package/README.md +141 -183
- package/docs/README.md +23 -0
- package/docs/ci-integration.md +63 -0
- package/docs/{CONFIGURATION.md → configuration.md} +41 -20
- package/docs/dashboard.md +36 -0
- package/docs/output-formats.md +65 -0
- package/docs/{RELEASING.md → releasing.md} +17 -14
- package/docs/{REPORTS_AND_CI.md → reports-and-ci.md} +5 -2
- package/docs/rules.md +177 -0
- package/package.json +2 -2
- package/scripts/bump-version.sh +83 -18
- package/scripts/dependency-install.sh +96 -0
- package/scripts/dependency-update.sh +177 -0
- package/scripts/preflight-checks.sh +38 -0
- package/src/analyser.ts +9 -24
- package/src/blocks.ts +66 -12
- package/src/class-rules.ts +5 -6
- package/src/cli-program.ts +216 -39
- package/src/cli.ts +4 -1
- package/src/comment-rules.ts +2 -0
- package/src/config-load-error.ts +18 -0
- package/src/config-preservation.ts +64 -0
- package/src/config.ts +155 -29
- package/src/constants.ts +10 -2
- package/src/dashboard.ts +1 -1
- package/src/dead-code-rules.ts +62 -16
- package/src/doc-rules.ts +3 -3
- package/src/findings-helpers.ts +17 -0
- package/src/init-config.ts +308 -0
- package/src/line-rules.ts +64 -12
- package/src/naming-pushers.ts +7 -32
- package/src/pillar-summary.ts +129 -0
- package/src/project-config-rules.ts +1 -1
- package/src/report-html.ts +404 -0
- package/src/report-renderers.ts +210 -406
- package/src/rule-list.ts +65 -1
- package/src/rules.ts +36 -37
- package/src/safety-rules.ts +9 -4
- package/src/scoring.ts +41 -9
- package/src/test-block-rules.ts +43 -1
- package/src/test-fixtures.ts +13 -7
- package/src/text-scans.ts +1 -152
- package/src/types.ts +32 -6
package/src/report-renderers.ts
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
// Text,
|
|
1
|
+
// Text, SARIF, hotspot, markdown, GitHub, and summary renderers for the stable analysis report.
|
|
2
|
+
// HTML output and dashboard chrome live in `report-html.ts` so this module stays under the
|
|
3
|
+
// `size.file-length` threshold; both files source `buildPillarRows` + `grade` from
|
|
4
|
+
// `pillar-summary.ts` so the cross-format Pillars table stays byte-aligned.
|
|
2
5
|
import type { AnalysisReport, Finding, OutputFormat, Severity } from "./types.ts";
|
|
6
|
+
import { OUTPUT_VOLUME_HINT_THRESHOLD } from "./constants.ts";
|
|
7
|
+
import { countRuleSeverities } from "./findings-helpers.ts";
|
|
8
|
+
import { buildPillarRows, type PillarRow } from "./pillar-summary.ts";
|
|
3
9
|
import { ruleDescriptors } from "./rules.ts";
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
{ label: "21+", minimum: 21 },
|
|
7
|
-
{ label: "16-20", minimum: 16 },
|
|
8
|
-
{ label: "11-15", minimum: 11 },
|
|
9
|
-
{ label: "6-10", minimum: 6 },
|
|
10
|
-
{ label: "1-5", minimum: 1 },
|
|
11
|
-
] as const;
|
|
10
|
+
import { renderHtml } from "./report-html.ts";
|
|
11
|
+
import { severityGradeBreakdown } from "./scoring.ts";
|
|
12
12
|
|
|
13
13
|
/*
|
|
14
14
|
* Format dispatcher. `hotspot` is emitted inline (smallest schema) while every other format has a
|
|
@@ -26,7 +26,7 @@ function renderReport(report: AnalysisReport, format: OutputFormat): string {
|
|
|
26
26
|
case "github":
|
|
27
27
|
return renderGithub(report);
|
|
28
28
|
case "hotspot":
|
|
29
|
-
return JSON.stringify({ schemaVersion: "gruff.hotspot.v1", tool: report.tool, score: report.score.composite, files: report.score.topOffenders }, null, 2);
|
|
29
|
+
return JSON.stringify({ schemaVersion: "gruff.hotspot.v1", tool: report.tool, score: report.score.composite, files: report.score.topOffenders.slice(0, 10) }, null, 2);
|
|
30
30
|
case "sarif":
|
|
31
31
|
return renderSarif(report);
|
|
32
32
|
case "text":
|
|
@@ -179,35 +179,82 @@ function sarifLevel(severity: Severity): "error" | "warning" | "note" {
|
|
|
179
179
|
* because the CLI should be able to improve wording/layout without a schema bump; callers that need
|
|
180
180
|
* durable machine output should use `analyse --format=json` instead.
|
|
181
181
|
*/
|
|
182
|
-
function renderSummary(report: AnalysisReport, elapsedMs?: number, pathLabel?: string): string {
|
|
183
|
-
const pillarCounts = countBy(report.findings, (finding) => finding.pillar);
|
|
182
|
+
function renderSummary(report: AnalysisReport, elapsedMs?: number, pathLabel?: string, top = 10): string {
|
|
184
183
|
const ruleCounts = countBy(report.findings, (finding) => finding.ruleId);
|
|
184
|
+
const pillarRows = buildPillarRows(report);
|
|
185
|
+
const breakdown = severityGradeBreakdown(report.findings);
|
|
185
186
|
const lines = [
|
|
186
187
|
`gruff-ts ${report.tool.version} summary`,
|
|
187
188
|
`Path: ${pathLabel ?? report.run.projectRoot}`,
|
|
188
189
|
...(typeof elapsedMs === "number" ? [`Duration: ${formatSummaryDuration(elapsedMs)}`] : []),
|
|
189
|
-
`
|
|
190
|
+
`Composite: ${report.score.grade} (${report.score.composite.toFixed(1)})`,
|
|
191
|
+
` Errors: ${breakdown.error.grade} (${breakdown.error.count})`,
|
|
192
|
+
` Warnings: ${breakdown.warning.grade} (${breakdown.warning.count})`,
|
|
193
|
+
` Advisory: ${breakdown.advisory.grade} (${breakdown.advisory.count})`,
|
|
190
194
|
`Findings: ${report.summary.total} total, ${report.summary.error} error, ${report.summary.warning} warning, ${report.summary.advisory} advisory`,
|
|
191
195
|
`Analysed files: ${report.paths.analysedFiles}`,
|
|
196
|
+
...(report.baseline ? [summaryBaselineLine(report.baseline)] : []),
|
|
192
197
|
];
|
|
193
198
|
if (report.diagnostics.length > 0) {
|
|
194
199
|
lines.push("", "Diagnostics:", ...report.diagnostics.map(summaryDiagnosticLine));
|
|
195
200
|
}
|
|
196
|
-
lines.push("",
|
|
197
|
-
lines.push(
|
|
198
|
-
lines.push(
|
|
199
|
-
lines.push(
|
|
200
|
-
lines.push("", "Top file offenders:");
|
|
201
|
+
lines.push("", ...renderPillarsBlock(pillarRows));
|
|
202
|
+
lines.push("", `Top ${top} rules:`);
|
|
203
|
+
lines.push(...renderRankedRuleRows(report.findings, top));
|
|
204
|
+
lines.push("", `Top ${top} file offenders:`);
|
|
201
205
|
lines.push(
|
|
202
206
|
...(
|
|
203
207
|
report.score.topOffenders.length === 0
|
|
204
208
|
? ["- No file offenders."]
|
|
205
|
-
: report.score.topOffenders.map((offender) => `- ${offender.filePath}: ${offender.findings} findings,
|
|
209
|
+
: report.score.topOffenders.slice(0, top).map((offender) => `- ${offender.filePath}: ${offender.findings} findings, quality ${offender.score.toFixed(1)}/100`)
|
|
206
210
|
),
|
|
207
211
|
);
|
|
208
212
|
return `${lines.join("\n")}\n`;
|
|
209
213
|
}
|
|
210
214
|
|
|
215
|
+
/*
|
|
216
|
+
* Renders the stable public `gruff.summary.v2` JSON contract for the `summary --format=json` flow.
|
|
217
|
+
* Phase 2 of the cross-port harmonisation replaces the flat `{pillar, count}` shape with rich
|
|
218
|
+
* per-pillar objects carrying grade, score, applicability, and per-severity counts (findings,
|
|
219
|
+
* advisory, warning, error). The schema-version string is bumped because downstream CI consumers
|
|
220
|
+
* parse this payload and the field-set is no longer compatible with v1; scope/score/topRules/
|
|
221
|
+
* topOffenders remain unchanged.
|
|
222
|
+
*/
|
|
223
|
+
function renderSummaryJson(report: AnalysisReport, elapsedMs?: number, pathLabel?: string, top = 10): string {
|
|
224
|
+
const ruleCounts = countBy(report.findings, (finding) => finding.ruleId);
|
|
225
|
+
const pillarRows = buildPillarRows(report);
|
|
226
|
+
const payload = {
|
|
227
|
+
schemaVersion: "gruff.summary.v2",
|
|
228
|
+
tool: report.tool,
|
|
229
|
+
scope: {
|
|
230
|
+
paths: pathLabel ?? report.run.projectRoot,
|
|
231
|
+
projectRoot: report.run.projectRoot,
|
|
232
|
+
analysedFiles: report.paths.analysedFiles,
|
|
233
|
+
ignoredPaths: report.paths.ignoredPaths.length,
|
|
234
|
+
missingPaths: report.paths.missingPaths.length,
|
|
235
|
+
diagnostics: report.diagnostics.length,
|
|
236
|
+
elapsedSeconds: typeof elapsedMs === "number" ? Number((elapsedMs / 1000).toFixed(3)) : undefined,
|
|
237
|
+
},
|
|
238
|
+
score: report.score,
|
|
239
|
+
findings: report.summary,
|
|
240
|
+
baseline: report.baseline,
|
|
241
|
+
pillars: pillarRows.map((row) => ({
|
|
242
|
+
pillar: row.pillar,
|
|
243
|
+
grade: row.grade,
|
|
244
|
+
score: row.score,
|
|
245
|
+
penalty: row.penalty,
|
|
246
|
+
applicable: row.isApplicable,
|
|
247
|
+
findings: row.findings,
|
|
248
|
+
advisory: row.advisory,
|
|
249
|
+
warning: row.warning,
|
|
250
|
+
error: row.error,
|
|
251
|
+
})),
|
|
252
|
+
topRules: renderRankedCountRows(ruleCounts, top),
|
|
253
|
+
topOffenders: report.score.topOffenders.slice(0, top),
|
|
254
|
+
};
|
|
255
|
+
return `${JSON.stringify(payload, null, 2)}\n`;
|
|
256
|
+
}
|
|
257
|
+
|
|
211
258
|
// Shared text formatter for diagnostic rows in plain-text summaries and the `text` format. Stable
|
|
212
259
|
// "- {type}: {message} (path)" shape is part of the contract that scripts grepping the text output
|
|
213
260
|
// rely on, so the format must stay deterministic across both call sites.
|
|
@@ -216,6 +263,15 @@ function summaryDiagnosticLine(diagnostic: AnalysisReport["diagnostics"][number]
|
|
|
216
263
|
return `- ${diagnostic.diagnosticType}: ${diagnostic.message}${location}`;
|
|
217
264
|
}
|
|
218
265
|
|
|
266
|
+
// Documents the summary baseline contract so suppressed findings are not mistaken for a clean scan.
|
|
267
|
+
function summaryBaselineLine(baseline: NonNullable<AnalysisReport["baseline"]>): string {
|
|
268
|
+
if (baseline.generated) {
|
|
269
|
+
return `Baseline: generated ${baseline.path}; current findings still shown`;
|
|
270
|
+
}
|
|
271
|
+
const findingNoun = baseline.suppressed === 1 ? "finding" : "findings";
|
|
272
|
+
return `Baseline: ${baseline.source} ${baseline.path}; suppressed ${baseline.suppressed} ${findingNoun}`;
|
|
273
|
+
}
|
|
274
|
+
|
|
219
275
|
// Human-sized summary runtime without pretending sub-millisecond precision is useful.
|
|
220
276
|
function formatSummaryDuration(elapsedMs: number): string {
|
|
221
277
|
const bounded = Math.max(0, elapsedMs);
|
|
@@ -234,24 +290,102 @@ function countBy<T extends string>(findings: Finding[], keyFor: (finding: Findin
|
|
|
234
290
|
return counts;
|
|
235
291
|
}
|
|
236
292
|
|
|
237
|
-
|
|
293
|
+
/*
|
|
294
|
+
* Text renderer for the `Pillars` block in `gruff-ts summary`. Column widths are computed from the
|
|
295
|
+
* actual data (max pillar-name length, max digits per severity column) with a 3-char minimum value
|
|
296
|
+
* width so single-digit cells still leave visual breathing room before the next column. This
|
|
297
|
+
* matches the cross-port canonical byte-for-byte layout: leading "Pillars" header, 2-space row
|
|
298
|
+
* indent, pillar name padded to max-name-width + 1 space, single-letter grade, 1-space separator,
|
|
299
|
+
* score right-aligned in 6 chars with 2 decimals, then findings/advisory/warning/error cells
|
|
300
|
+
* separated by 3 spaces and trimmed of trailing whitespace on the final column.
|
|
301
|
+
*/
|
|
302
|
+
function renderPillarsBlock(rows: PillarRow[]): string[] {
|
|
303
|
+
if (rows.length === 0) {
|
|
304
|
+
return ["Pillars", " (none)"];
|
|
305
|
+
}
|
|
306
|
+
const nameWidth = Math.max(...rows.map((row) => row.pillar.length));
|
|
307
|
+
const findingsWidth = Math.max(3, ...rows.map((row) => String(row.findings).length));
|
|
308
|
+
const advisoryWidth = Math.max(3, ...rows.map((row) => String(row.advisory).length));
|
|
309
|
+
const warningWidth = Math.max(3, ...rows.map((row) => String(row.warning).length));
|
|
310
|
+
const errorWidth = Math.max(3, ...rows.map((row) => String(row.error).length));
|
|
311
|
+
const lines = ["Pillars"];
|
|
312
|
+
for (const row of rows) {
|
|
313
|
+
const name = row.pillar.padEnd(nameWidth);
|
|
314
|
+
const score = row.score.toFixed(2).padStart(6);
|
|
315
|
+
const findingsCell = `findings=${String(row.findings).padEnd(findingsWidth)}`;
|
|
316
|
+
const advisoryCell = `advisory=${String(row.advisory).padEnd(advisoryWidth)}`;
|
|
317
|
+
const warningCell = `warning=${String(row.warning).padEnd(warningWidth)}`;
|
|
318
|
+
const errorCell = `error=${String(row.error).padEnd(errorWidth)}`;
|
|
319
|
+
const line = ` ${name} ${row.grade} ${score} ${findingsCell} ${advisoryCell} ${warningCell} ${errorCell}`.replace(/\s+$/, "");
|
|
320
|
+
lines.push(line);
|
|
321
|
+
}
|
|
322
|
+
return lines;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/*
|
|
326
|
+
* Enriched top-N rules renderer. Replaces the plain `- <ruleId>: <count>` form with a per-severity
|
|
327
|
+
* split plus the rule's one-line description, so an operator triaging 1000+ findings can see
|
|
328
|
+
* whether the top entry is one error or four hundred advisories at a glance. Description text is
|
|
329
|
+
* truncated to `DESCRIPTION_BODY_LIMIT` characters with an ellipsis so the row stays legible at 100
|
|
330
|
+
* columns. Sort order is preserved (count DESC, ruleId ASC) to keep the row-at-position-[0] stable.
|
|
331
|
+
*/
|
|
332
|
+
function renderRankedRuleRows(findings: Finding[], limit?: number): string[] {
|
|
333
|
+
const severities = countRuleSeverities(findings);
|
|
334
|
+
if (severities.size === 0) {
|
|
335
|
+
return ["- No rule findings."];
|
|
336
|
+
}
|
|
337
|
+
const descriptions = new Map(ruleDescriptors().map((descriptor) => [descriptor.ruleId, descriptor.description]));
|
|
338
|
+
const limited = [...severities.entries()]
|
|
339
|
+
.sort(([leftKey, leftCounts], [rightKey, rightCounts]) => rightCounts.total - leftCounts.total || leftKey.localeCompare(rightKey))
|
|
340
|
+
.slice(0, limit ?? severities.size);
|
|
341
|
+
return limited.map(([ruleId, counts]) => {
|
|
342
|
+
const description = truncateDescription(descriptions.get(ruleId) ?? "");
|
|
343
|
+
return `- ${ruleId}: ${counts.total} (${counts.error} err / ${counts.warning} warn / ${counts.advisory} adv) - ${description}`;
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/*
|
|
348
|
+
* 60-char description budget that keeps the rule-row line under ~100 columns even with the longest
|
|
349
|
+
* ruleId and severity-split. The trailing ellipsis is a single Unicode glyph so terminals that
|
|
350
|
+
* don't render `...` still see the truncation marker.
|
|
351
|
+
*/
|
|
352
|
+
const DESCRIPTION_BODY_LIMIT = 60;
|
|
353
|
+
|
|
354
|
+
// Applies the description budget to a single rule's description so each rule row in the summary
|
|
355
|
+
// Top-N block fits on one terminal line. Returns the input unchanged when already short.
|
|
356
|
+
function truncateDescription(text: string): string {
|
|
357
|
+
return text.length <= DESCRIPTION_BODY_LIMIT ? text : `${text.slice(0, DESCRIPTION_BODY_LIMIT).trimEnd()}…`;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function renderRankedCounts<T extends string>(counts: Map<T, number>, emptyText: string, limit?: number): string[] {
|
|
238
361
|
if (counts.size === 0) {
|
|
239
362
|
return [`- ${emptyText}`];
|
|
240
363
|
}
|
|
241
364
|
return [...counts.entries()]
|
|
242
365
|
.sort(([leftKey, leftCount], [rightKey, rightCount]) => rightCount - leftCount || leftKey.localeCompare(rightKey))
|
|
243
|
-
.slice(0,
|
|
366
|
+
.slice(0, limit ?? counts.size)
|
|
244
367
|
.map(([key, count]) => `- ${key}: ${count}`);
|
|
245
368
|
}
|
|
246
369
|
|
|
370
|
+
function renderRankedCountRows<T extends string>(counts: Map<T, number>, limit?: number): Array<{ name: T; count: number }> {
|
|
371
|
+
return [...counts.entries()]
|
|
372
|
+
.sort(([leftKey, leftCount], [rightKey, rightCount]) => rightCount - leftCount || leftKey.localeCompare(rightKey))
|
|
373
|
+
.slice(0, limit ?? counts.size)
|
|
374
|
+
.map(([name, count]) => ({ name, count }));
|
|
375
|
+
}
|
|
376
|
+
|
|
247
377
|
/*
|
|
248
378
|
* Default terminal output. Findings are listed verbatim (no truncation) - the analyser keeps them
|
|
249
379
|
* sorted into the stable order, so piping into `grep` produces deterministic results.
|
|
250
380
|
*/
|
|
251
381
|
function renderText(report: AnalysisReport): string {
|
|
382
|
+
const breakdown = severityGradeBreakdown(report.findings);
|
|
252
383
|
const lines = [
|
|
253
384
|
`gruff-ts ${report.tool.version}`,
|
|
254
|
-
`
|
|
385
|
+
`Composite: ${report.score.grade} (${report.score.composite.toFixed(1)}) | Findings: ${report.summary.advisory} advisory, ${report.summary.warning} warning, ${report.summary.error} error`,
|
|
386
|
+
` Errors: ${breakdown.error.grade} (${breakdown.error.count})`,
|
|
387
|
+
` Warnings: ${breakdown.warning.grade} (${breakdown.warning.count})`,
|
|
388
|
+
` Advisory: ${breakdown.advisory.grade} (${breakdown.advisory.count})`,
|
|
255
389
|
`Analysed files: ${report.paths.analysedFiles}`,
|
|
256
390
|
];
|
|
257
391
|
if (report.diagnostics.length > 0) {
|
|
@@ -260,22 +394,72 @@ function renderText(report: AnalysisReport): string {
|
|
|
260
394
|
if (report.findings.length > 0) {
|
|
261
395
|
lines.push("", "Findings:", ...report.findings.map((finding) => `- [${finding.severity}] ${finding.filePath}:${finding.line ?? 1} ${finding.ruleId} - ${finding.message}`));
|
|
262
396
|
}
|
|
397
|
+
if (report.findings.length >= OUTPUT_VOLUME_HINT_THRESHOLD) {
|
|
398
|
+
lines.push("", `Tip: ${report.findings.length} findings is more than a flat list usefully shows. Try \`gruff-ts summary --top=20\` for a per-rule digest.`);
|
|
399
|
+
}
|
|
263
400
|
return `${lines.join("\n")}\n`;
|
|
264
401
|
}
|
|
265
402
|
|
|
266
|
-
|
|
267
|
-
|
|
403
|
+
/*
|
|
404
|
+
* Markdown renderer for the `gruff.analysis.v2` report. Truncates to 50 findings because Markdown
|
|
405
|
+
* previews (PR comments, READMEs) start mangling longer tables; the JSON and HTML renderers stay
|
|
406
|
+
* the canonical full-fidelity output. Public contract / invariant: the Pillars table is inserted
|
|
407
|
+
* between the severity counts and the per-finding list so CI logs and PR comment previews see it
|
|
408
|
+
* first, and it shares its row data and sort order with the text/JSON/HTML pillar renderers via
|
|
409
|
+
* `buildPillarRows` so all four surfaces stay deterministic and byte-aligned across runs.
|
|
410
|
+
*/
|
|
268
411
|
function renderMarkdown(report: AnalysisReport): string {
|
|
412
|
+
const breakdown = severityGradeBreakdown(report.findings);
|
|
269
413
|
return [
|
|
270
414
|
"# gruff-ts report",
|
|
271
415
|
"",
|
|
272
|
-
`
|
|
416
|
+
`Composite: **${report.score.grade} (${report.score.composite.toFixed(1)})**`,
|
|
417
|
+
`- Errors: ${breakdown.error.grade} (${breakdown.error.count})`,
|
|
418
|
+
`- Warnings: ${breakdown.warning.grade} (${breakdown.warning.count})`,
|
|
419
|
+
`- Advisory: ${breakdown.advisory.grade} (${breakdown.advisory.count})`,
|
|
273
420
|
"",
|
|
274
421
|
`Findings: ${report.summary.advisory} advisory, ${report.summary.warning} warning, ${report.summary.error} error.`,
|
|
422
|
+
"",
|
|
423
|
+
...renderMarkdownPillarsTable(buildPillarRows(report)),
|
|
424
|
+
"",
|
|
275
425
|
...report.findings.slice(0, 50).map((finding) => `- \`${finding.ruleId}\` \`${finding.filePath}\`:${finding.line ?? 1} - ${finding.message}`),
|
|
276
426
|
].join("\n");
|
|
277
427
|
}
|
|
278
428
|
|
|
429
|
+
/*
|
|
430
|
+
* Canonical 7-column Pillars table shared by the cross-port markdown contract. The header,
|
|
431
|
+
* separator (right-aligned numeric columns), and row format match the gruff-go markdown reporter
|
|
432
|
+
* byte-for-byte so downstream tooling (PR comment scrapers, dashboards parsing the markdown body)
|
|
433
|
+
* keys off a single shape. Row order is sourced from `buildPillarRows` (findings DESC, then pillar
|
|
434
|
+
* ASC); scores render with two decimals; pipes in pillar/grade cells are escaped so a future
|
|
435
|
+
* pillar/grade name containing `|` cannot break the table.
|
|
436
|
+
*/
|
|
437
|
+
function renderMarkdownPillarsTable(rows: PillarRow[]): string[] {
|
|
438
|
+
const lines = [
|
|
439
|
+
"## Pillars",
|
|
440
|
+
"",
|
|
441
|
+
"| Pillar | Grade | Score | Findings | Advisory | Warning | Error |",
|
|
442
|
+
"| --- | --- | ---: | ---: | ---: | ---: | ---: |",
|
|
443
|
+
];
|
|
444
|
+
if (rows.length === 0) {
|
|
445
|
+
lines.push("| _(none)_ | | | | | | |");
|
|
446
|
+
return lines;
|
|
447
|
+
}
|
|
448
|
+
for (const row of rows) {
|
|
449
|
+
lines.push(
|
|
450
|
+
`| ${escapeMarkdownCell(row.pillar)} | ${escapeMarkdownCell(row.grade)} | ${row.score.toFixed(2)} | ${row.findings} | ${row.advisory} | ${row.warning} | ${row.error} |`,
|
|
451
|
+
);
|
|
452
|
+
}
|
|
453
|
+
return lines;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// Escapes the pipe character so a pillar/grade name containing `|` cannot terminate the table row.
|
|
457
|
+
// Markdown's table syntax has no other reserved cell characters - newlines are already impossible
|
|
458
|
+
// inside a single-line `lines.push` interpolation - so this single replacement is sufficient.
|
|
459
|
+
function escapeMarkdownCell(cell: string): string {
|
|
460
|
+
return cell.replaceAll("|", "\\|");
|
|
461
|
+
}
|
|
462
|
+
|
|
279
463
|
// GitHub Actions `::workflow command` syntax. Public contract invariant: file/title properties
|
|
280
464
|
// must be normalized and command-escaped before interpolation because commas and colons delimit the property list.
|
|
281
465
|
function renderGithub(report: AnalysisReport): string {
|
|
@@ -290,380 +474,6 @@ function githubAnnotationPath(filePath: string): string {
|
|
|
290
474
|
return filePath.replaceAll("\\", "/").replace(/^(?:\.\/)+/, "");
|
|
291
475
|
}
|
|
292
476
|
|
|
293
|
-
// Extra metadata appended to dashboard-served HTML. Static-file consumers never see it because the
|
|
294
|
-
// CLI calls `renderHtml` without this argument; only the dashboard route passes it in.
|
|
295
|
-
interface DashboardRenderContext {
|
|
296
|
-
projectRoot: string;
|
|
297
|
-
scanPath: string;
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
/*
|
|
301
|
-
* Self-contained HTML output (CSS inlined, no external assets) so reports can be archived or
|
|
302
|
-
* emailed. The schema invariant: every Finding listed in the report must be reachable through
|
|
303
|
-
* deep links - the on-page JS in `dashboardJs` relies on stable `data-path` attributes.
|
|
304
|
-
*/
|
|
305
|
-
function renderHtml(report: AnalysisReport, dashboardContext?: DashboardRenderContext): string {
|
|
306
|
-
const bodySections = [
|
|
307
|
-
htmlMasthead(report),
|
|
308
|
-
htmlDiagnostics(report),
|
|
309
|
-
dashboardContext ? htmlDashboardContext(dashboardContext) : "",
|
|
310
|
-
htmlVerdict(report),
|
|
311
|
-
htmlPillars(report),
|
|
312
|
-
htmlOffenders(report),
|
|
313
|
-
htmlDistribution(report),
|
|
314
|
-
htmlFindings(report),
|
|
315
|
-
htmlFooter(report),
|
|
316
|
-
].join("\n");
|
|
317
|
-
return `<!doctype html>
|
|
318
|
-
<html lang="en-NZ">
|
|
319
|
-
<head>
|
|
320
|
-
<meta charset="utf-8">
|
|
321
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
322
|
-
<title>gruff-ts report - ${escapeHtml(report.score.grade)}</title>
|
|
323
|
-
<style>${htmlReportCss(report.diagnostics.length > 0)}</style>
|
|
324
|
-
</head>
|
|
325
|
-
<body>
|
|
326
|
-
<main class="paper"><span class="corner-tr"></span><span class="corner-bl"></span>
|
|
327
|
-
${bodySections}
|
|
328
|
-
</main>
|
|
329
|
-
</body>
|
|
330
|
-
</html>`;
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
// Top banner: path count, format, fail-on, schema version. The schemaVersion text is the
|
|
334
|
-
// contract surface - operators eyeball it to confirm the report shape they expect.
|
|
335
|
-
function htmlMasthead(report: AnalysisReport): string {
|
|
336
|
-
const paths = report.paths.analysedFiles === 0 ? "." : `${report.paths.analysedFiles} analysed ${report.paths.analysedFiles === 1 ? "file" : "files"}`;
|
|
337
|
-
return `<header class="masthead"><div class="brand"><div class="wordmark">gruff</div><div class="tagline">ts/js code quality - inspection report</div></div><div class="meta">${htmlMetaRow("paths", paths)}${htmlMetaRow("format", report.run.format)}${htmlMetaRow("fail", report.run.failOn)}${htmlMetaRow("schema", report.schemaVersion)}<div class="inspection-id">gruff-ts ${escapeHtml(report.tool.version)}</div></div></header>`;
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
// Single key/value row. Both inputs are escaped - they reach this function as user-influenced
|
|
341
|
-
// strings (paths, format names) and would otherwise enable injection in archived reports.
|
|
342
|
-
function htmlMetaRow(label: string, metaValue: string): string {
|
|
343
|
-
const escapedLabel = escapeHtml(label);
|
|
344
|
-
const escapedValue = escapeHtml(metaValue);
|
|
345
|
-
return `<div><span class="label">${escapedLabel}</span><span class="val">${escapedValue}</span></div>`;
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
// Diagnostics are parse/IO failures, not normal findings. HTML renders them before score sections
|
|
349
|
-
// because partial scans must remain visibly incomplete; omitting empty diagnostics is the stable contract.
|
|
350
|
-
function htmlDiagnostics(report: AnalysisReport): string {
|
|
351
|
-
if (report.diagnostics.length === 0) {
|
|
352
|
-
return "";
|
|
353
|
-
}
|
|
354
|
-
const diagnostics = report.diagnostics.map(htmlDiagnosticEntry).join("");
|
|
355
|
-
return `<section class="diagnostics"><h2 class="section-head">diagnostics <span class="aside">run messages</span></h2><div class="diagnostic-list">${diagnostics}</div></section>`;
|
|
356
|
-
}
|
|
357
|
-
|
|
358
|
-
// HTML markup for one diagnostic entry. The `diagnostic-type`/`diagnostic-message`/`diagnostic-location`
|
|
359
|
-
// span classes are part of the stable HTML report contract - the dashboard CSS and any downstream
|
|
360
|
-
// scraping keys off them, so the structure here must stay invariant across renderer changes.
|
|
361
|
-
function htmlDiagnosticEntry(diagnostic: AnalysisReport["diagnostics"][number]): string {
|
|
362
|
-
const lineSuffix = diagnostic.line ? `:${diagnostic.line}` : "";
|
|
363
|
-
const location = diagnostic.filePath
|
|
364
|
-
? `<span class="diagnostic-location">${escapeHtml(diagnostic.filePath)}${lineSuffix}</span>`
|
|
365
|
-
: "";
|
|
366
|
-
return `<div class="diagnostic"><span class="diagnostic-type">${escapeHtml(diagnostic.diagnosticType)}</span><span class="diagnostic-message">${escapeHtml(diagnostic.message)}</span>${location}</div>`;
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
// Dashboard-only banner that names the project root and scan path. Static reports never include
|
|
370
|
-
// this; both inputs are user-controlled query parameters and are escaped before reaching HTML.
|
|
371
|
-
function htmlDashboardContext(context: DashboardRenderContext): string {
|
|
372
|
-
const escapedProjectRoot = escapeHtml(context.projectRoot);
|
|
373
|
-
const escapedScanPath = escapeHtml(context.scanPath);
|
|
374
|
-
return `<section class="dashboard-context"><h2 class="section-head">dashboard scan <span class="aside">local run</span></h2><div class="dashboard-context-grid"><div><span class="label">Project root</span><span class="val">${escapedProjectRoot}</span></div><div><span class="label">Path</span><span class="val">${escapedScanPath}</span></div></div></section>`;
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
/*
|
|
378
|
-
* The grade stamp + four stat cards. The verdict shape is part of the stable visual contract that
|
|
379
|
-
* the dashboard relies on for parity with static reports.
|
|
380
|
-
*/
|
|
381
|
-
function htmlVerdict(report: AnalysisReport): string {
|
|
382
|
-
const gradeCssClass = gradeClass(report.score.grade);
|
|
383
|
-
const escapedGrade = escapeHtml(report.score.grade);
|
|
384
|
-
const scoreText = report.score.composite.toFixed(1);
|
|
385
|
-
const escapedSummary = escapeHtml(verdictSummary(report));
|
|
386
|
-
const stats = `${htmlStat(String(report.summary.total), "findings", "")}${htmlStat(String(report.summary.error), "errors", "fail")}${htmlStat(String(report.summary.warning), "warnings", "warn")}${htmlStat(String(report.summary.advisory), "advisories", "note")}`;
|
|
387
|
-
return `<section class="verdict"><div class="grade-stamp ${gradeCssClass}"><div class="grade-letter">${escapedGrade}</div><div class="grade-score">${scoreText} / 100</div></div><div class="verdict-body"><div class="verdict-headline">Inspection complete.<br><em>${escapedSummary}</em></div><div class="verdict-stats">${stats}</div></div></section>`;
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
// Headline sentence. Counts only warning/error findings - advisories are intentionally excluded
|
|
391
|
-
// from the verdict text because they are below the stable "needs attention" threshold.
|
|
392
|
-
function verdictSummary(report: AnalysisReport): string {
|
|
393
|
-
const thresholdFindings = report.summary.warning + report.summary.error;
|
|
394
|
-
if (thresholdFindings === 0) {
|
|
395
|
-
return "No warning or error findings flagged.";
|
|
396
|
-
}
|
|
397
|
-
const pillars = new Set(report.findings.filter((finding) => finding.severity === "warning" || finding.severity === "error").map((finding) => finding.pillar));
|
|
398
|
-
return `${thresholdFindings} ${thresholdFindings === 1 ? "finding" : "findings"} at warning or error severity across ${pillars.size} ${pillars.size === 1 ? "pillar" : "pillars"}.`;
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
// One stat card (number + label). `className` is a curated, non-escaped CSS class - callers must
|
|
402
|
-
// not pass user input here or it would break the layout in archived reports.
|
|
403
|
-
function htmlStat(number: string, label: string, className: string): string {
|
|
404
|
-
const escapedClassName = escapeHtml(className);
|
|
405
|
-
const escapedNumber = escapeHtml(number);
|
|
406
|
-
const escapedLabel = escapeHtml(label);
|
|
407
|
-
return `<div class="stat"><div class="num ${escapedClassName}">${escapedNumber}</div><div class="lbl">${escapedLabel}</div></div>`;
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
/*
|
|
411
|
-
* Pillar score grid in the same order the analyser produced - the stable composite score is the
|
|
412
|
-
* mean of these pillars (see `scoreReport`), so visual order matches the headline-grade derivation.
|
|
413
|
-
*/
|
|
414
|
-
function htmlPillars(report: AnalysisReport): string {
|
|
415
|
-
const items =
|
|
416
|
-
report.score.pillars.length === 0
|
|
417
|
-
? '<div class="empty">No pillar findings.</div>'
|
|
418
|
-
: report.score.pillars
|
|
419
|
-
.map((pillar) => {
|
|
420
|
-
const letter = grade(pillar.score);
|
|
421
|
-
return `<div class="pillar"><div class="name">${escapeHtml(pillar.pillar)}</div><div class="grade ${gradeClass(letter)}">${letter}</div><div class="breakdown"><div class="row"><span class="key">score</span><span class="val">${pillar.score.toFixed(1)}</span></div><div class="row"><span class="key">findings</span><span class="val">${pillar.findings}</span></div></div></div>`;
|
|
422
|
-
})
|
|
423
|
-
.join("");
|
|
424
|
-
return `<section class="pillars"><h2 class="section-head">pillar grades <span class="aside">weighted composite</span></h2><div class="pillar-grid">${items}</div></section>`;
|
|
425
|
-
}
|
|
426
|
-
|
|
427
|
-
// Top-10 offender table, ordered by ascending score (worst first). `scoreReport` already truncated
|
|
428
|
-
// the list to 10 - this stable, deterministic limit is part of the public report contract.
|
|
429
|
-
function htmlOffenders(report: AnalysisReport): string {
|
|
430
|
-
const rows =
|
|
431
|
-
report.score.topOffenders.length === 0
|
|
432
|
-
? '<tr><td colspan="4">No offenders found.</td></tr>'
|
|
433
|
-
: report.score.topOffenders
|
|
434
|
-
.map((file) => {
|
|
435
|
-
const letter = grade(file.score);
|
|
436
|
-
return `<tr><td class="file-path">${htmlLocation(file.filePath)}</td><td class="num">${file.score.toFixed(1)}</td><td class="num">${file.findings}</td><td class="num"><span class="grade-pill ${gradeClass(letter)}">${letter}</span></td></tr>`;
|
|
437
|
-
})
|
|
438
|
-
.join("");
|
|
439
|
-
return `<section class="offenders"><h2 class="section-head">top offenders <span class="aside">sorted by score</span></h2><table class="offender-list"><thead><tr><th scope="col">file</th><th scope="col" class="num">score</th><th scope="col" class="num">findings</th><th scope="col" class="num">grade</th></tr></thead><tbody>${rows}</tbody></table></section>`;
|
|
440
|
-
}
|
|
441
|
-
|
|
442
|
-
/*
|
|
443
|
-
* Histogram of cyclomatic-complexity buckets. The 5 fixed buckets are part of the stable visual
|
|
444
|
-
* vocabulary maintainers learn over time - adding a new bucket would invalidate that mental model.
|
|
445
|
-
*/
|
|
446
|
-
function htmlDistribution(report: AnalysisReport): string {
|
|
447
|
-
const distribution = cyclomaticDistribution(report);
|
|
448
|
-
const max = Math.max(1, ...Object.values(distribution));
|
|
449
|
-
const bars = Object.entries(distribution)
|
|
450
|
-
.map(([label, count]) => {
|
|
451
|
-
const height = Math.max(4, Math.round((count / max) * 100));
|
|
452
|
-
const className = label === "16-20" || label === "21+" ? " fail" : label === "11-15" ? " warn" : "";
|
|
453
|
-
return `<div class="bar${className}" style="height:${height}%;"><span class="count">${count}</span></div>`;
|
|
454
|
-
})
|
|
455
|
-
.join("");
|
|
456
|
-
const axis = Object.keys(distribution)
|
|
457
|
-
.map((label) => `<span>${escapeHtml(label)}</span>`)
|
|
458
|
-
.join("");
|
|
459
|
-
return `<section class="chart-section"><h2 class="section-head">distribution <span class="aside">cyclomatic complexity</span></h2><p class="chart-summary">${escapeHtml(cyclomaticSummary(distribution))}</p><div class="chart-card"><div class="title">cyclomatic complexity - flagged functions</div><div class="histogram">${bars}</div><div class="histogram-axis">${axis}</div></div></section>`;
|
|
460
|
-
}
|
|
461
|
-
|
|
462
|
-
/*
|
|
463
|
-
* Pre-seeded with zero counts for every bucket so the resulting record has a stable key order
|
|
464
|
-
* in JSON dumps. Findings outside `complexity.cyclomatic` are ignored - see `cyclomaticFindingBucket`.
|
|
465
|
-
*/
|
|
466
|
-
function cyclomaticDistribution(report: AnalysisReport): Record<string, number> {
|
|
467
|
-
const distribution: Record<string, number> = { "1-5": 0, "6-10": 0, "11-15": 0, "16-20": 0, "21+": 0 };
|
|
468
|
-
for (const finding of report.findings) {
|
|
469
|
-
const bucket = cyclomaticFindingBucket(finding);
|
|
470
|
-
if (bucket) {
|
|
471
|
-
distribution[bucket] = (distribution[bucket] ?? 0) + 1;
|
|
472
|
-
}
|
|
473
|
-
}
|
|
474
|
-
return distribution;
|
|
475
|
-
}
|
|
476
|
-
|
|
477
|
-
// Extracts the cyclomatic number from the finding message because the metadata schema doesn't
|
|
478
|
-
// expose it as a top-level field - coupling the renderer to the message text is acceptable here
|
|
479
|
-
// because the message format is itself part of the stable rule contract.
|
|
480
|
-
function cyclomaticFindingBucket(finding: Finding): string | undefined {
|
|
481
|
-
if (finding.ruleId !== "complexity.cyclomatic") {
|
|
482
|
-
return undefined;
|
|
483
|
-
}
|
|
484
|
-
const match = finding.message.match(/cyclomatic complexity (\d+)/);
|
|
485
|
-
const complexityValue = match?.[1] ? Number(match[1]) : undefined;
|
|
486
|
-
return complexityValue === undefined ? undefined : cyclomaticBucket(complexityValue);
|
|
487
|
-
}
|
|
488
|
-
|
|
489
|
-
// Linear walk in descending-minimum order so the first match wins - required because `21+` and
|
|
490
|
-
// `16-20` would otherwise both apply to a value of 25.
|
|
491
|
-
function cyclomaticBucket(complexityValue: number): string | undefined {
|
|
492
|
-
for (const bucket of CYCLOMATIC_BUCKETS) {
|
|
493
|
-
if (complexityValue >= bucket.minimum) {
|
|
494
|
-
return bucket.label;
|
|
495
|
-
}
|
|
496
|
-
}
|
|
497
|
-
return undefined;
|
|
498
|
-
}
|
|
499
|
-
|
|
500
|
-
// One-line caption that quantifies how many functions exceed CC=10. The pluralisation handling
|
|
501
|
-
// matters - "1 functions exceed" reads poorly enough that a reviewer would file it as a regression.
|
|
502
|
-
function cyclomaticSummary(distribution: Record<string, number>): string {
|
|
503
|
-
const moderate = distribution["11-15"] ?? 0;
|
|
504
|
-
const high = distribution["16-20"] ?? 0;
|
|
505
|
-
const severe = distribution["21+"] ?? 0;
|
|
506
|
-
const exceeds = moderate + high + severe;
|
|
507
|
-
return `${exceeds} ${exceeds === 1 ? "function" : "functions"} ${exceeds === 1 ? "exceeds" : "exceed"} CC 10 (${moderate} in 11-15, ${high} in 16-20, ${severe} at 21+).`;
|
|
508
|
-
}
|
|
509
|
-
|
|
510
|
-
// Caps the list at 250 entries because the inline-CSS report becomes painful to scroll past that.
|
|
511
|
-
// The footer caveat shows "first 250 of N" so the truncation stable and visible.
|
|
512
|
-
function htmlFindings(report: AnalysisReport): string {
|
|
513
|
-
const findings =
|
|
514
|
-
report.findings.length === 0
|
|
515
|
-
? '<div class="empty">No findings.</div>'
|
|
516
|
-
: report.findings
|
|
517
|
-
.slice(0, 250)
|
|
518
|
-
.map(
|
|
519
|
-
(finding) =>
|
|
520
|
-
`<div class="finding"><div class="severity ${severityClass(finding.severity)}">${escapeHtml(finding.severity)}</div><div class="finding-body"><h3 class="rule">${escapeHtml(finding.ruleId)}</h3><div class="msg">${escapeHtml(finding.message)}</div><div class="loc"><code>${htmlLocation(finding.filePath, finding.line)}</code></div></div><div class="points"><b>${escapeHtml(finding.pillar)}</b></div></div>`,
|
|
521
|
-
)
|
|
522
|
-
.join("");
|
|
523
|
-
const capped = report.findings.length > 250 ? ` <span class="aside">first 250 of ${report.findings.length}</span>` : ` <span class="aside">${report.findings.length} shown</span>`;
|
|
524
|
-
return `<section class="findings"><h2 class="section-head">flagged findings${capped}</h2><div class="findings-list">${findings}</div></section>`;
|
|
525
|
-
}
|
|
526
|
-
|
|
527
|
-
/*
|
|
528
|
-
* Page-bottom strip with tool version and schema string - those are the two stable identifiers a
|
|
529
|
-
* reviewer can use to reproduce a historical report.
|
|
530
|
-
*/
|
|
531
|
-
function htmlFooter(report: AnalysisReport): string {
|
|
532
|
-
const escapedVersion = escapeHtml(report.tool.version);
|
|
533
|
-
const escapedSchemaVersion = escapeHtml(report.schemaVersion);
|
|
534
|
-
return `<footer class="footer"><div class="left">gruff-ts - v${escapedVersion}</div><div class="center">strong opinions, opinionated defaults</div><div class="right">schema - ${escapedSchemaVersion}</div></footer>`;
|
|
535
|
-
}
|
|
536
|
-
|
|
537
|
-
// Renders a keyboard-focusable location pill. `data-path` is what the dashboard JS keys off when
|
|
538
|
-
// the user clicks to deep-link; both attributes go through `escapeHtml` because filePath is user-influenced.
|
|
539
|
-
function htmlLocation(filePath: string, line?: number): string {
|
|
540
|
-
const text = line === undefined ? filePath : `${filePath}:${line}`;
|
|
541
|
-
return `<span class="loc-link" tabindex="0" data-path="${escapeHtml(text)}">${escapeHtml(text)}</span>`;
|
|
542
|
-
}
|
|
543
|
-
|
|
544
|
-
// CSS class suffix used by severity badges and grade letters. Returning a curated literal (never
|
|
545
|
-
// arbitrary user text) is what keeps `htmlStat`/`htmlFinding` safe to interpolate without escaping.
|
|
546
|
-
function severityClass(severity: Severity): string {
|
|
547
|
-
return severity === "error" ? "fail" : severity === "warning" ? "warn" : "note";
|
|
548
|
-
}
|
|
549
|
-
|
|
550
|
-
// Constrains grade text to known CSS suffixes before interpolation. Unknown future grades degrade
|
|
551
|
-
// to neutral styling instead of creating user-influenced class names.
|
|
552
|
-
function gradeClass(gradeValue: string): string {
|
|
553
|
-
const letter = gradeValue[0]?.toLowerCase() ?? "n";
|
|
554
|
-
return ["a", "b", "c", "d", "f"].includes(letter) ? letter : "n";
|
|
555
|
-
}
|
|
556
|
-
|
|
557
|
-
// Single inline stylesheet for both static reports and dashboard-served pages. `shouldIncludeDiagnostics`
|
|
558
|
-
// appends the diagnostic-section rules only when the report actually has them, keeping clean
|
|
559
|
-
// reports leaner. Hand-maintained CSS - no preprocessor.
|
|
560
|
-
function htmlReportCss(shouldIncludeDiagnostics: boolean): string {
|
|
561
|
-
const baseCss = `:root{--ink:#0d0c0a;--ink-2:#161412;--ink-3:#1f1c19;--paper:#f3e9d2;--paper-dim:#b5ab94;--paper-mute:#7d735f;--rule:#2a2622;--forge:#e85d04;--grade-a:#7fa15a;--grade-b:#b8b450;--grade-c:#d08c36;--grade-d:#c2552b;--grade-f:#8b2828;--advisory:#b5ab94;--serif:Georgia,'Iowan Old Style',serif;--mono:'JetBrains Mono','IBM Plex Mono',ui-monospace,monospace}*{box-sizing:border-box;margin:0;padding:0}html{background:var(--ink);scrollbar-gutter:stable}body{font-family:var(--mono);color:var(--paper);background:var(--ink);min-height:100vh;line-height:1.5;font-size:14px;padding:48px 32px}.paper{max-width:1180px;margin:0 auto 24px;background:var(--ink-2);border:1px solid var(--rule);position:relative;padding:56px 64px 48px;scrollbar-gutter:stable}.corner-tr,.corner-bl,.paper:before,.paper:after{content:'';position:absolute;width:22px;height:22px;border:1px solid var(--forge)}.paper:before{top:12px;left:12px;border-right:0;border-bottom:0}.paper:after{bottom:12px;right:12px;border-left:0;border-top:0}.corner-tr{top:12px;right:12px;border-left:0;border-bottom:0}.corner-bl{bottom:12px;left:12px;border-right:0;border-top:0}.masthead{display:grid;grid-template-columns:1fr auto;gap:32px;padding-bottom:28px;border-bottom:1px solid var(--rule);align-items:end}.wordmark{font-family:var(--serif);font-weight:900;font-size:96px;line-height:.85;color:var(--paper);font-style:italic}.wordmark:after{content:'-ts';color:var(--forge);font-style:normal;font-size:.45em;margin-left:.15em;vertical-align:super}.tagline{margin-top:12px;font-size:11px;letter-spacing:0;color:var(--paper-mute);text-transform:uppercase}.meta{text-align:right;font-size:11px;color:var(--paper-dim);line-height:1.9}.label{color:var(--paper-mute);text-transform:uppercase;letter-spacing:0;margin-right:8px}.val{color:var(--paper)}.inspection-id{margin-top:10px;color:var(--forge);font-weight:700;font-size:12px;letter-spacing:0}.section-head{font-size:11px;letter-spacing:0;color:var(--paper-mute);text-transform:uppercase;padding-bottom:16px;margin-bottom:20px;border-bottom:1px solid var(--rule);display:flex;justify-content:space-between;align-items:baseline;font-family:var(--mono);font-weight:500;line-height:1.5}.section-head:before{content:'>';margin-right:10px;color:var(--forge);font-family:var(--serif);font-size:14px;font-style:italic}.aside{color:var(--paper-mute);font-size:10px;letter-spacing:0}.verdict{display:grid;grid-template-columns:auto 1fr;gap:56px;padding:48px 0;border-bottom:1px solid var(--rule);align-items:center}.grade-stamp{width:220px;height:220px;border:3px solid currentColor;color:var(--grade-b);display:flex;flex-direction:column;align-items:center;justify-content:center;transform:rotate(-4deg)}.grade-stamp.a,.grade.a,.grade-pill.a{color:var(--grade-a)}.grade-stamp.b,.grade.b,.grade-pill.b{color:var(--grade-b)}.grade-stamp.c,.grade.c,.grade-pill.c{color:var(--grade-c)}.grade-stamp.d,.grade.d,.grade-pill.d{color:var(--grade-d)}.grade-stamp.f,.grade.f,.grade-pill.f{color:var(--grade-f)}.grade-letter{font-family:var(--serif);font-style:italic;font-weight:900;font-size:112px;line-height:1}.grade-score{font-size:13px;letter-spacing:0}.verdict-body{display:flex;flex-direction:column;gap:18px}.verdict-headline{font-family:var(--serif);font-style:italic;font-weight:600;font-size:38px;line-height:1.15}.verdict-headline em{color:var(--forge)}.verdict-stats{display:grid;grid-template-columns:repeat(4,1fr);border-top:1px solid var(--rule);padding-top:20px}.stat{border-right:1px solid var(--rule);padding:0 18px}.stat:first-child{padding-left:0}.stat:last-child{border-right:0}.verdict-stats .num{font-family:var(--serif);font-weight:800;font-size:32px;line-height:1}.verdict-stats .num.warn{color:var(--grade-c)}.verdict-stats .num.fail{color:var(--grade-f)}.verdict-stats .num.note{color:var(--advisory)}.lbl{font-size:10px;text-transform:uppercase;letter-spacing:0;color:var(--paper-mute);margin-top:8px}.pillars,.offenders,.chart-section{padding:48px 0;border-bottom:1px solid var(--rule)}.pillar-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:1px;background:var(--rule);border:1px solid var(--rule)}.pillar{background:var(--ink-2);padding:24px 20px;display:flex;flex-direction:column;gap:14px}.pillar .name{font-size:10px;text-transform:uppercase;letter-spacing:0;color:var(--paper-mute)}.pillar .grade{font-family:var(--serif);font-weight:800;font-style:italic;font-size:52px;line-height:.9}.breakdown{font-size:11px;color:var(--paper-dim);line-height:1.7}.row{display:flex;justify-content:space-between;gap:8px}.key{color:var(--paper-mute)}table{width:100%;border-collapse:collapse;font-size:13px;table-layout:auto;font-family:var(--mono)}th{text-align:left;font-size:10px;text-transform:uppercase;letter-spacing:0;color:var(--paper-mute);font-weight:500;padding:12px 14px 12px 0;border-bottom:1px solid var(--rule)}th:last-child,td:last-child{padding-right:0}th.num,td.num{text-align:right;padding-left:18px}td{padding:14px 14px 14px 0;border-bottom:1px solid var(--ink-3);color:var(--paper-dim);font-size:13px;font-family:var(--mono);font-weight:500;line-height:1.4}td.num{color:var(--paper);font-variant-numeric:tabular-nums}.file-path{color:var(--paper);font-weight:500}.grade-pill{display:inline-block;font-family:var(--serif);font-style:italic;font-weight:800;font-size:18px;line-height:1;padding:4px 10px;border:1.5px solid currentColor;min-width:36px;text-align:center}.chart-summary{color:var(--paper-dim);font-size:12px;margin:-6px 0 18px}.chart-card{border:1px solid var(--rule);padding:24px;background:var(--ink-3)}.title{font-size:10px;text-transform:uppercase;letter-spacing:0;color:var(--paper-mute);margin-bottom:24px}.histogram{display:flex;align-items:flex-end;gap:6px;height:180px;padding-bottom:20px;border-bottom:1px solid var(--rule)}.bar{flex:1;background:var(--forge);position:relative;min-height:4px}.bar.warn{background:var(--grade-c)}.bar.fail{background:var(--grade-f)}.bar .count{position:absolute;top:-22px;left:50%;transform:translateX(-50%);font-size:11px}.histogram-axis{display:flex;gap:6px;margin-top:8px;font-size:10px;color:var(--paper-mute)}.histogram-axis span{flex:1;text-align:center}.findings{padding:48px 0}.finding{display:grid;grid-template-columns:auto 1fr auto;gap:24px;padding:18px 0;border-bottom:1px solid var(--ink-3);align-items:start}.severity{font-size:9px;text-transform:uppercase;letter-spacing:0;padding:4px 10px;border:1px solid currentColor;margin-top:2px;min-width:76px;text-align:center}.severity.fail{color:var(--grade-f)}.severity.warn{color:var(--grade-c)}.severity.note{color:var(--paper-mute)}.rule{font-size:10px;color:var(--forge);text-transform:uppercase;letter-spacing:0;margin-bottom:6px;font-family:var(--mono);font-weight:700;line-height:1.5}.msg{font-family:var(--serif);font-weight:500;font-size:17px;color:var(--paper);line-height:1.4}.loc{font-size:11px;color:var(--paper-mute);margin-top:8px}.loc code{color:var(--paper-dim);background:var(--ink-3);padding:1px 6px;border:1px solid var(--rule)}.loc-link{color:inherit;text-decoration:none}.loc-link:focus-visible{outline:2px solid var(--forge);outline-offset:3px}.points{font-size:10px;color:var(--paper-mute);text-align:right;letter-spacing:0;min-width:96px;padding-left:12px}.empty{color:var(--paper-dim);font-size:12px}.footer{margin-top:48px;padding-top:24px;border-top:1px solid var(--rule);display:grid;grid-template-columns:1fr auto 1fr;gap:24px;align-items:center;font-size:10px;color:var(--paper-mute);letter-spacing:0;text-transform:uppercase}.center{font-family:var(--serif);font-style:italic;font-size:13px;color:var(--paper-dim);text-transform:none;letter-spacing:0}.right{text-align:right}@media(max-width:900px){body{padding:16px}.paper{padding:28px 20px}.wordmark{font-size:64px}.masthead,.verdict{grid-template-columns:1fr}.meta{text-align:left}.grade-stamp{margin:0 auto}.pillar-grid{grid-template-columns:repeat(2,1fr)}.verdict-stats{grid-template-columns:repeat(2,1fr);gap:16px}.stat{border-right:0;padding:0}.verdict-headline{font-size:28px}.footer{grid-template-columns:1fr}.center,.right{text-align:left}}@media(max-width:560px){.pillar-grid{grid-template-columns:1fr}.finding{grid-template-columns:1fr}.points{text-align:left;padding-left:0}.verdict-stats{grid-template-columns:1fr}.histogram{height:140px}}`;
|
|
562
|
-
const reportCss = `${baseCss}.dashboard-context{padding:28px 0;border-bottom:1px solid var(--rule)}.dashboard-context-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px}.dashboard-context-grid>div{border:1px solid var(--rule);background:var(--ink-3);padding:12px 14px}.dashboard-context .label{display:block;margin:0 0 6px}.dashboard-context .val{overflow-wrap:anywhere}@media(max-width:700px){.dashboard-context-grid{grid-template-columns:1fr}}@media(max-width:560px){.offender-list thead{display:none}.offender-list,.offender-list tbody,.offender-list tr,.offender-list td{display:block;width:100%}.offender-list tr{border-bottom:1px solid var(--ink-3);padding:10px 0}.offender-list td{border-bottom:0;padding:6px 0}.offender-list td.num{text-align:left;padding-left:0}}`;
|
|
563
|
-
if (!shouldIncludeDiagnostics) {
|
|
564
|
-
return reportCss;
|
|
565
|
-
}
|
|
566
|
-
return `${reportCss}.diagnostics{padding:28px 0 0}.diagnostic-list{display:grid;gap:10px}.diagnostic{display:grid;grid-template-columns:auto 1fr;gap:10px 14px;border:1px solid var(--rule);background:var(--ink-3);padding:12px 14px;color:var(--paper-dim);font-size:12px}.diagnostic-type{text-transform:uppercase;letter-spacing:0;color:var(--forge);font-size:10px}.diagnostic-location{grid-column:2;color:var(--paper-mute);font-size:11px}`;
|
|
567
|
-
}
|
|
568
|
-
|
|
569
|
-
// Top-level dashboard chrome: iframe that loads the scan + a slide-out controls panel. The iframe
|
|
570
|
-
// arrangement is what lets the dashboard reload scans without losing the control form state.
|
|
571
|
-
function dashboardHomeHtml(projectRoot: string, scanPath: string): string {
|
|
572
|
-
const initialScan = dashboardScanUrl(projectRoot, scanPath);
|
|
573
|
-
return `<!doctype html>
|
|
574
|
-
<html lang="en">
|
|
575
|
-
<head>
|
|
576
|
-
<meta charset="utf-8">
|
|
577
|
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
578
|
-
<title>gruff-ts dashboard</title>
|
|
579
|
-
<style>${dashboardCss()}</style>
|
|
580
|
-
</head>
|
|
581
|
-
<body>
|
|
582
|
-
<iframe class="report-frame" name="report-frame" title="gruff-ts report" src="${escapeHtml(initialScan)}"></iframe>
|
|
583
|
-
<button class="controls-toggle" type="button" aria-expanded="false" aria-controls="controls-panel" title="Dashboard controls">⚙</button>
|
|
584
|
-
<aside class="controls-panel" id="controls-panel" hidden>
|
|
585
|
-
<header class="controls-head">
|
|
586
|
-
<h1>Dashboard controls</h1>
|
|
587
|
-
<p>local scan settings</p>
|
|
588
|
-
</header>
|
|
589
|
-
<form class="scan-form" data-scan-form action="/scan" method="get" target="report-frame">
|
|
590
|
-
<label>Project root <input name="projectRoot" value="${escapeHtml(projectRoot)}" autocomplete="off"></label>
|
|
591
|
-
<label>Paths <input name="path" value="${escapeHtml(scanPath)}" autocomplete="off"></label>
|
|
592
|
-
<div class="scan-state"><span>Status</span><strong data-scan-status>Loading report</strong></div>
|
|
593
|
-
<div class="actions">
|
|
594
|
-
<button class="secondary" type="button" data-refresh>Refresh</button>
|
|
595
|
-
<button type="submit">Run scan</button>
|
|
596
|
-
</div>
|
|
597
|
-
</form>
|
|
598
|
-
</aside>
|
|
599
|
-
<script>${dashboardJs()}</script>
|
|
600
|
-
</body>
|
|
601
|
-
</html>`;
|
|
602
|
-
}
|
|
603
|
-
|
|
604
|
-
// URLSearchParams handles encoding so the projectRoot/scanPath values are safe to embed in `src`.
|
|
605
|
-
function dashboardScanUrl(projectRoot: string, scanPath: string): string {
|
|
606
|
-
const params = new URLSearchParams({ projectRoot, path: scanPath });
|
|
607
|
-
return `/scan?${params.toString()}`;
|
|
608
|
-
}
|
|
609
|
-
|
|
610
|
-
// Friendly failure page served when `renderDashboardScan` catches an analyser throw. All inputs
|
|
611
|
-
// are escaped - `message` is the error text and could contain attacker-controlled file path fragments.
|
|
612
|
-
function dashboardErrorHtml(message: string, projectRoot: string, scanPath: string): string {
|
|
613
|
-
const escapedMessage = escapeHtml(message);
|
|
614
|
-
const escapedProjectRoot = escapeHtml(projectRoot);
|
|
615
|
-
const escapedScanPath = escapeHtml(scanPath);
|
|
616
|
-
return `<!doctype html>
|
|
617
|
-
<html lang="en-NZ">
|
|
618
|
-
<head>
|
|
619
|
-
<meta charset="utf-8">
|
|
620
|
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
621
|
-
<title>gruff-ts dashboard scan failed</title>
|
|
622
|
-
<style>${dashboardCss()}</style>
|
|
623
|
-
</head>
|
|
624
|
-
<body class="error-page">
|
|
625
|
-
<main class="scan-error">
|
|
626
|
-
<h1>Scan failed</h1>
|
|
627
|
-
<p>${escapedMessage}</p>
|
|
628
|
-
<dl>
|
|
629
|
-
<dt>Project root</dt><dd>${escapedProjectRoot}</dd>
|
|
630
|
-
<dt>Paths</dt><dd>${escapedScanPath}</dd>
|
|
631
|
-
</dl>
|
|
632
|
-
</main>
|
|
633
|
-
</body>
|
|
634
|
-
</html>`;
|
|
635
|
-
}
|
|
636
|
-
|
|
637
|
-
// Inline stylesheet shared by the dashboard shell and its error page. Inlined (not linked) so the
|
|
638
|
-
// dashboard works without separate asset routes - keeping it self-contained matters for offline use.
|
|
639
|
-
function dashboardCss(): string {
|
|
640
|
-
return `:root{color-scheme:dark;--ink:#0d0c0a;--ink-2:#161412;--panel:#1f1c19;--paper:#f3e9d2;--paper-dim:#b5ab94;--paper-mute:#7d735f;--rule:#2a2622;--forge:#e85d04;--forge-dark:#b94402;--mono:'JetBrains Mono','IBM Plex Mono',ui-monospace,monospace}*{box-sizing:border-box}html,body{height:100%;margin:0;background:var(--ink);color:var(--paper);font-family:var(--mono);font-size:14px;line-height:1.5}.report-frame{position:fixed;inset:0;width:100%;height:100%;border:0;background:var(--ink)}.controls-toggle{position:fixed;top:18px;right:18px;z-index:3;width:44px;height:44px;border:1px solid rgba(232,93,4,.75);border-radius:8px;background:var(--forge);color:#170b05;font:700 22px/1 var(--mono);display:grid;place-items:center;cursor:pointer;box-shadow:0 16px 36px rgba(0,0,0,.38)}.controls-toggle:hover,.controls-toggle:focus-visible{background:#ff7a1a;outline:2px solid rgba(243,233,210,.75);outline-offset:3px}.controls-panel{position:fixed;z-index:2;top:74px;right:18px;width:min(420px,calc(100vw - 36px));max-height:calc(100vh - 92px);overflow:auto;background:rgba(31,28,25,.98);border:1px solid var(--rule);border-radius:8px;padding:20px;box-shadow:0 24px 70px rgba(0,0,0,.5)}[hidden]{display:none!important}.controls-head{border-bottom:1px solid var(--rule);padding-bottom:14px;margin-bottom:16px}.controls-head h1{margin:0;font-size:18px;font-weight:800}.controls-head p{margin:4px 0 0;color:var(--paper-mute);font-size:12px;text-transform:uppercase}.scan-form{display:grid;gap:14px}.scan-form label{display:grid;gap:6px;color:var(--paper-dim);font-size:12px;text-transform:uppercase}.scan-form input{width:100%;font:inherit;color:var(--paper);background:var(--ink-2);border:1px solid var(--rule);border-radius:6px;padding:10px 11px;min-width:0}.scan-form input:focus{outline:2px solid var(--forge);outline-offset:2px}.scan-state{display:flex;justify-content:space-between;gap:12px;border:1px solid var(--rule);background:var(--ink-2);border-radius:6px;padding:10px 11px;color:var(--paper-mute)}.scan-state strong{color:var(--paper);font-weight:700;text-align:right}.actions{display:grid;grid-template-columns:1fr 1fr;gap:10px}.actions button{font:inherit;border:1px solid var(--forge);border-radius:6px;padding:10px 12px;background:var(--forge);color:#170b05;font-weight:800;cursor:pointer}.actions button.secondary{background:transparent;color:var(--paper);border-color:var(--rule)}.actions button:disabled{opacity:.6;cursor:wait}.scan-error{max-width:720px;margin:8vh auto;padding:48px;background:var(--panel);border:1px solid var(--rule);color:var(--paper)}.scan-error h1{margin:0 0 16px;font-size:28px}.scan-error p{color:var(--paper-dim);overflow-wrap:anywhere}.scan-error dl{display:grid;grid-template-columns:auto 1fr;gap:8px 16px;margin:24px 0 0}.scan-error dt{color:var(--paper-mute);text-transform:uppercase}.scan-error dd{margin:0;overflow-wrap:anywhere}@media(max-width:560px){.controls-toggle{top:12px;right:12px}.controls-panel{top:64px;right:12px;width:calc(100vw - 24px);max-height:calc(100vh - 76px);padding:16px}.actions{grid-template-columns:1fr}.scan-error{margin:0;min-height:100vh;padding:28px 20px}.scan-error dl{grid-template-columns:1fr}}`;
|
|
641
|
-
}
|
|
642
|
-
|
|
643
|
-
// Inline `<script>` body served with the dashboard shell. Updates the URL via history.replaceState
|
|
644
|
-
// so a maintainer can copy the current scan's URL and reproduce it later without re-typing controls.
|
|
645
|
-
function dashboardJs(): string {
|
|
646
|
-
return `const form=document.querySelector("[data-scan-form]");const frame=document.querySelector(".report-frame");const toggle=document.querySelector(".controls-toggle");const panel=document.querySelector(".controls-panel");const refresh=document.querySelector("[data-refresh]");const status=document.querySelector("[data-scan-status]");function setOpen(open){panel.hidden=!open;toggle.setAttribute("aria-expanded",String(open));if(open){const input=form.querySelector("input");if(input){input.focus();}}}function params(){return new URLSearchParams(new FormData(form));}function runScan(){const query=params();status.textContent="Scanning";refresh.disabled=true;form.querySelector("button[type=submit]").disabled=true;frame.src="/scan?"+query.toString();history.replaceState(null,"","/?"+query.toString());}toggle.addEventListener("click",()=>setOpen(panel.hidden));document.addEventListener("keydown",(event)=>{if(event.key==="Escape"){setOpen(false);}});form.addEventListener("submit",(event)=>{event.preventDefault();runScan();});refresh.addEventListener("click",runScan);frame.addEventListener("load",()=>{status.textContent="Ready";refresh.disabled=false;form.querySelector("button[type=submit]").disabled=false;});`;
|
|
647
|
-
}
|
|
648
|
-
|
|
649
|
-
// Composite-score → letter grade conversion. 90/80/70/60 boundaries are part of the stable rule
|
|
650
|
-
// surface; changing them would shift every historical report grade and the headline on the dashboard.
|
|
651
|
-
function grade(score: number): string {
|
|
652
|
-
if (score >= 90) {
|
|
653
|
-
return "A";
|
|
654
|
-
}
|
|
655
|
-
if (score >= 80) {
|
|
656
|
-
return "B";
|
|
657
|
-
}
|
|
658
|
-
if (score >= 70) {
|
|
659
|
-
return "C";
|
|
660
|
-
}
|
|
661
|
-
if (score >= 60) {
|
|
662
|
-
return "D";
|
|
663
|
-
}
|
|
664
|
-
return "F";
|
|
665
|
-
}
|
|
666
|
-
|
|
667
477
|
// Three GitHub annotation levels - gruff's "advisory" collapses to "notice" because Actions has
|
|
668
478
|
// no fourth tier and "notice" is the documented soft-warning level.
|
|
669
479
|
function githubLevel(severity: Severity): "notice" | "warning" | "error" {
|
|
@@ -682,10 +492,4 @@ function escapeCommandProperty(propertyText: string): string {
|
|
|
682
492
|
return escapeCommand(propertyText).replaceAll(":", "%3A").replaceAll(",", "%2C");
|
|
683
493
|
}
|
|
684
494
|
|
|
685
|
-
|
|
686
|
-
// don't get double-encoded; missing escapes here would enable script injection in archived reports.
|
|
687
|
-
function escapeHtml(htmlText: string): string {
|
|
688
|
-
return htmlText.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """);
|
|
689
|
-
}
|
|
690
|
-
|
|
691
|
-
export { dashboardErrorHtml, dashboardHomeHtml, grade, renderHtml, renderReport, renderSummary };
|
|
495
|
+
export { renderReport, renderSummary, renderSummaryJson };
|