@wastech-mdlint/viewer 0.0.0-stage → 0.4.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 (189) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +86 -2
  3. package/assets/favicon.ico +0 -0
  4. package/assets/viewer.css +4184 -0
  5. package/dist/asset-routes.d.ts +4 -0
  6. package/dist/asset-routes.js +107 -0
  7. package/dist/blame.d.ts +8 -0
  8. package/dist/blame.js +54 -0
  9. package/dist/branch-changes.d.ts +8 -0
  10. package/dist/branch-changes.js +49 -0
  11. package/dist/candidate-lint-worker.d.ts +1 -0
  12. package/dist/candidate-lint-worker.js +67 -0
  13. package/dist/candidate-lint.d.ts +39 -0
  14. package/dist/candidate-lint.js +115 -0
  15. package/dist/change-banner.d.ts +38 -0
  16. package/dist/change-banner.js +108 -0
  17. package/dist/change-diff.d.ts +23 -0
  18. package/dist/change-diff.js +140 -0
  19. package/dist/change-marks.d.ts +32 -0
  20. package/dist/change-marks.js +363 -0
  21. package/dist/changes-article.d.ts +15 -0
  22. package/dist/changes-article.js +244 -0
  23. package/dist/changes-routes.d.ts +12 -0
  24. package/dist/changes-routes.js +271 -0
  25. package/dist/changes.d.ts +113 -0
  26. package/dist/changes.js +324 -0
  27. package/dist/cli-args.d.ts +21 -0
  28. package/dist/cli-args.js +93 -0
  29. package/dist/client/banner-height.d.ts +1 -0
  30. package/dist/client/banner-height.js +33 -0
  31. package/dist/client/change-marks.d.ts +1 -0
  32. package/dist/client/change-marks.js +56 -0
  33. package/dist/client/changes.d.ts +1 -0
  34. package/dist/client/changes.js +183 -0
  35. package/dist/client/chart-option.d.ts +3 -0
  36. package/dist/client/chart-option.js +76 -0
  37. package/dist/client/charts.d.ts +1 -0
  38. package/dist/client/charts.js +54 -0
  39. package/dist/client/clipboard.d.ts +1 -0
  40. package/dist/client/clipboard.js +43 -0
  41. package/dist/client/code-copy.d.ts +1 -0
  42. package/dist/client/code-copy.js +29 -0
  43. package/dist/client/column-resize.d.ts +1 -0
  44. package/dist/client/column-resize.js +120 -0
  45. package/dist/client/config-dom.d.ts +13 -0
  46. package/dist/client/config-dom.js +47 -0
  47. package/dist/client/config-draft.d.ts +73 -0
  48. package/dist/client/config-draft.js +218 -0
  49. package/dist/client/config-editor.d.ts +3 -0
  50. package/dist/client/config-editor.js +677 -0
  51. package/dist/client/config-fields.d.ts +35 -0
  52. package/dist/client/config-fields.js +339 -0
  53. package/dist/client/config-json.d.ts +18 -0
  54. package/dist/client/config-json.js +96 -0
  55. package/dist/client/config-preview.d.ts +9 -0
  56. package/dist/client/config-preview.js +91 -0
  57. package/dist/client/config-rules.d.ts +14 -0
  58. package/dist/client/config-rules.js +202 -0
  59. package/dist/client/config-types.d.ts +91 -0
  60. package/dist/client/config-types.js +4 -0
  61. package/dist/client/copy-path.d.ts +1 -0
  62. package/dist/client/copy-path.js +32 -0
  63. package/dist/client/dashboard-requests.d.ts +11 -0
  64. package/dist/client/dashboard-requests.js +28 -0
  65. package/dist/client/dashboard.d.ts +1 -0
  66. package/dist/client/dashboard.js +119 -0
  67. package/dist/client/diagnostics.d.ts +1 -0
  68. package/dist/client/diagnostics.js +164 -0
  69. package/dist/client/diagrams.d.ts +1 -0
  70. package/dist/client/diagrams.js +81 -0
  71. package/dist/client/diff-expand.d.ts +1 -0
  72. package/dist/client/diff-expand.js +42 -0
  73. package/dist/client/display-settings-model.d.ts +74 -0
  74. package/dist/client/display-settings-model.js +229 -0
  75. package/dist/client/display-settings.d.ts +1 -0
  76. package/dist/client/display-settings.js +411 -0
  77. package/dist/client/echarts.d.ts +30 -0
  78. package/dist/client/echarts.js +14 -0
  79. package/dist/client/graph-layout.d.ts +88 -0
  80. package/dist/client/graph-layout.js +198 -0
  81. package/dist/client/graph.d.ts +2 -0
  82. package/dist/client/graph.js +566 -0
  83. package/dist/client/history.d.ts +21 -0
  84. package/dist/client/history.js +86 -0
  85. package/dist/client/live-reload-model.d.ts +28 -0
  86. package/dist/client/live-reload-model.js +52 -0
  87. package/dist/client/live-reload.d.ts +9 -0
  88. package/dist/client/live-reload.js +138 -0
  89. package/dist/client/menu.d.ts +14 -0
  90. package/dist/client/menu.js +176 -0
  91. package/dist/client/navigation-feedback.d.ts +1 -0
  92. package/dist/client/navigation-feedback.js +141 -0
  93. package/dist/client/open-config.d.ts +1 -0
  94. package/dist/client/open-config.js +48 -0
  95. package/dist/client/outline-spy.d.ts +1 -0
  96. package/dist/client/outline-spy.js +60 -0
  97. package/dist/client/prompts.d.ts +7 -0
  98. package/dist/client/prompts.js +65 -0
  99. package/dist/client/review.d.ts +1 -0
  100. package/dist/client/review.js +379 -0
  101. package/dist/client/search.d.ts +1 -0
  102. package/dist/client/search.js +199 -0
  103. package/dist/client/segmented.d.ts +13 -0
  104. package/dist/client/segmented.js +70 -0
  105. package/dist/client/source-lines.d.ts +16 -0
  106. package/dist/client/source-lines.js +47 -0
  107. package/dist/client/theme-toggle.d.ts +10 -0
  108. package/dist/client/theme-toggle.js +100 -0
  109. package/dist/client/theme.d.ts +0 -0
  110. package/dist/client/theme.js +50 -0
  111. package/dist/client/tree-marks.d.ts +31 -0
  112. package/dist/client/tree-marks.js +102 -0
  113. package/dist/client/tree-state.d.ts +0 -0
  114. package/dist/client/tree-state.js +179 -0
  115. package/dist/client/viewer.d.ts +1 -0
  116. package/dist/client/viewer.js +53 -0
  117. package/dist/config-editor.d.ts +166 -0
  118. package/dist/config-editor.js +378 -0
  119. package/dist/config-routes.d.ts +18 -0
  120. package/dist/config-routes.js +213 -0
  121. package/dist/context-view.d.ts +41 -0
  122. package/dist/context-view.js +295 -0
  123. package/dist/corpus-routes.d.ts +31 -0
  124. package/dist/corpus-routes.js +258 -0
  125. package/dist/corpus.d.ts +134 -0
  126. package/dist/corpus.js +653 -0
  127. package/dist/dashboard-article.d.ts +14 -0
  128. package/dist/dashboard-article.js +290 -0
  129. package/dist/dashboard.d.ts +94 -0
  130. package/dist/dashboard.js +468 -0
  131. package/dist/diagnostics.d.ts +23 -0
  132. package/dist/diagnostics.js +44 -0
  133. package/dist/document-routes.d.ts +39 -0
  134. package/dist/document-routes.js +396 -0
  135. package/dist/event-hub.d.ts +39 -0
  136. package/dist/event-hub.js +120 -0
  137. package/dist/findings-panel.d.ts +4 -0
  138. package/dist/findings-panel.js +74 -0
  139. package/dist/folder-page.d.ts +8 -0
  140. package/dist/folder-page.js +74 -0
  141. package/dist/graph-view.d.ts +66 -0
  142. package/dist/graph-view.js +236 -0
  143. package/dist/highlight.d.ts +24 -0
  144. package/dist/highlight.js +100 -0
  145. package/dist/http-send.d.ts +9 -0
  146. package/dist/http-send.js +53 -0
  147. package/dist/index.d.ts +2 -0
  148. package/dist/index.js +72 -0
  149. package/dist/open-file.d.ts +36 -0
  150. package/dist/open-file.js +87 -0
  151. package/dist/page-tree.d.ts +3 -0
  152. package/dist/page-tree.js +105 -0
  153. package/dist/page.d.ts +73 -0
  154. package/dist/page.js +478 -0
  155. package/dist/prompts.d.ts +25 -0
  156. package/dist/prompts.js +82 -0
  157. package/dist/render-cache.d.ts +23 -0
  158. package/dist/render-cache.js +38 -0
  159. package/dist/render-document.d.ts +60 -0
  160. package/dist/render-document.js +440 -0
  161. package/dist/request-path.d.ts +17 -0
  162. package/dist/request-path.js +51 -0
  163. package/dist/review-context.d.ts +24 -0
  164. package/dist/review-context.js +109 -0
  165. package/dist/review-queries.d.ts +26 -0
  166. package/dist/review-queries.js +69 -0
  167. package/dist/review-state.d.ts +106 -0
  168. package/dist/review-state.js +251 -0
  169. package/dist/review-store.d.ts +145 -0
  170. package/dist/review-store.js +530 -0
  171. package/dist/router.d.ts +28 -0
  172. package/dist/router.js +294 -0
  173. package/dist/search.d.ts +22 -0
  174. package/dist/search.js +164 -0
  175. package/dist/security.d.ts +95 -0
  176. package/dist/security.js +196 -0
  177. package/dist/server.d.ts +21 -0
  178. package/dist/server.js +224 -0
  179. package/dist/speculation-rules.d.ts +4 -0
  180. package/dist/speculation-rules.js +49 -0
  181. package/dist/state-dir.d.ts +6 -0
  182. package/dist/state-dir.js +31 -0
  183. package/dist/tree-marks.d.ts +49 -0
  184. package/dist/tree-marks.js +108 -0
  185. package/dist/viewer-context.d.ts +37 -0
  186. package/dist/viewer-context.js +74 -0
  187. package/dist/watch.d.ts +41 -0
  188. package/dist/watch.js +135 -0
  189. package/package.json +57 -4
@@ -0,0 +1,295 @@
1
+ import { h } from "hastscript";
2
+ import { documentHref, fileHref } from "./render-document.js";
3
+ // The context delta laid out: in the summary of the Changes page, on each document's card, as the
4
+ // group of unchanged documents the change reaches, on the config's card, and as JSON. Everything
5
+ // shown is computed by core; this module only words it and draws it.
6
+ // A list of findings on the page stops here, with how many more there are; the JSON lists them all.
7
+ const LISTED_FINDINGS = 50;
8
+ export function countFindings(messages) {
9
+ const errors = messages.filter((message) => message.severity === "error").length;
10
+ return { errors, warnings: messages.length - errors };
11
+ }
12
+ /**
13
+ * What the change does to findings, in words: "+1 error, +2 warnings, −3 findings", or nothing when
14
+ * it adds and removes none. The same wording on the summary and on every row, so a reader learns it
15
+ * once — and a test reads the page's numbers back from it.
16
+ */
17
+ export function findingsText(delta) {
18
+ const added = countFindings(delta.added);
19
+ const parts = [
20
+ added.errors > 0 ? `+${plural(added.errors, "error")}` : undefined,
21
+ added.warnings > 0 ? `+${plural(added.warnings, "warning")}` : undefined,
22
+ delta.removed.length > 0
23
+ ? `−${plural(delta.removed.length, "finding")}`
24
+ : undefined,
25
+ ].filter((part) => part !== undefined);
26
+ return parts.length === 0 ? undefined : parts.join(", ");
27
+ }
28
+ /** The summary's lines about the context: findings, every session's budget, and what is approximate. */
29
+ export function renderContextSummary(context) {
30
+ const { delta } = context;
31
+ const findings = findingsText(delta.findings);
32
+ return [
33
+ h("p.changes-findings", findings === undefined
34
+ ? "Findings: none added or removed."
35
+ : `Findings: ${findings}.`),
36
+ ...delta.eager.map(renderEagerChange),
37
+ ...contextNotes(context).map((note) => h("p.changes-note", note)),
38
+ ];
39
+ }
40
+ /**
41
+ * The approximations behind the numbers, said where the numbers are. Links to files other than
42
+ * documents are checked against the files on disk on both sides, because a lint needs a real
43
+ * directory to look in; and a config whose scope changed is still read through the current scope.
44
+ */
45
+ export function contextNotes(context) {
46
+ return [
47
+ "Links to files other than documents are checked against the files as they are now on both sides, so a link to a file the branch deleted reads as fine at the base.",
48
+ ...(context.delta.scopeChanged
49
+ ? [
50
+ "The config's include, exclude or respectGitignore changed; the base is still read as the documents the current config selects.",
51
+ ]
52
+ : []),
53
+ ...context.configProblems,
54
+ ];
55
+ }
56
+ function renderEagerChange(change) {
57
+ const over = change.head !== undefined && change.head > change.maxTokens;
58
+ return h(over ? "p.changes-eager.changes-eager-over" : "p.changes-eager", eagerText(change));
59
+ }
60
+ /** "CLAUDE.md eager context 8921 → 10.7k tokens (+1856, budget 10k)". */
61
+ export function eagerText(change) {
62
+ const budget = `budget ${tokens(change.maxTokens)}`;
63
+ if (change.base === undefined) {
64
+ return `${change.entrypoint} eager context, new: ${tokens(change.head ?? 0)} tokens (${budget})`;
65
+ }
66
+ if (change.head === undefined) {
67
+ return `${change.entrypoint} eager context, gone: was ${tokens(change.base)} tokens (${budget})`;
68
+ }
69
+ return `${change.entrypoint} eager context ${tokens(change.base)} → ${tokens(change.head)} tokens (${signed(change.head - change.base, tokens)}, ${budget})`;
70
+ }
71
+ /** A changed document's context on its card: its size, its findings and its links, each when moved. */
72
+ export function renderDocumentContext(delta) {
73
+ const size = sizeText(delta.base, delta.head);
74
+ const parts = [
75
+ size === undefined ? undefined : h("p.change-size", size),
76
+ renderFindingList(delta.findings),
77
+ renderLinkList(delta.links),
78
+ ].filter((part) => part !== undefined);
79
+ return parts.length === 0 ? undefined : h("div.change-context", parts);
80
+ }
81
+ function sizeText(base, head) {
82
+ if (base === undefined && head === undefined) {
83
+ return undefined;
84
+ }
85
+ const measure = (pick, unit, format) => {
86
+ if (base === undefined) {
87
+ return `${format(pick(head))} ${unit}`;
88
+ }
89
+ if (head === undefined) {
90
+ return `was ${format(pick(base))} ${unit}`;
91
+ }
92
+ // Compared and subtracted as shown, so a few bytes that round to the same tenth of a KB read as
93
+ // no change, and the difference is the difference of the two numbers on screen.
94
+ const before = pick(base);
95
+ const after = pick(head);
96
+ return before === after
97
+ ? `${format(after)} ${unit}`
98
+ : `${format(before)} → ${format(after)} ${unit} (${signed(after - before, format)})`;
99
+ };
100
+ return [
101
+ measure((metrics) => metrics.tokens, "tokens", String),
102
+ measure((metrics) => metrics.lines, "lines", String),
103
+ measure((metrics) => tenthsOfKilobytes(metrics.bytes), "KB", (value) => value.toFixed(1)),
104
+ ].join(" · ");
105
+ }
106
+ function renderFindingList(delta) {
107
+ if (delta.added.length === 0 && delta.removed.length === 0) {
108
+ return undefined;
109
+ }
110
+ const entries = [
111
+ ...delta.added.map((message) => ({ message, sign: "added" })),
112
+ ...delta.removed.map((message) => ({ message, sign: "removed" })),
113
+ ];
114
+ return h("div.change-findings-list", [
115
+ h("p.change-context-title", `Findings: ${findingsText(delta)}`),
116
+ h("ul", entries
117
+ .slice(0, LISTED_FINDINGS)
118
+ .map(({ message, sign }) => h(`li.change-finding.change-finding-${sign}`, [
119
+ h("span.change-finding-sign", sign === "added" ? "+" : "−"),
120
+ " ",
121
+ findingLine(message),
122
+ ]))),
123
+ entries.length > LISTED_FINDINGS
124
+ ? h("p.change-more", `And ${entries.length - LISTED_FINDINGS} more, listed in /api/changes.`)
125
+ : undefined,
126
+ ]);
127
+ }
128
+ function findingLine(message) {
129
+ return [
130
+ h(`span.severity-${message.severity}`, message.severity),
131
+ " ",
132
+ h("code", message.ruleId),
133
+ message.line > 0 ? ` line ${message.line}: ` : ": ",
134
+ message.message,
135
+ ];
136
+ }
137
+ function renderLinkList(links) {
138
+ if (links.added.length === 0 && links.removed.length === 0) {
139
+ return undefined;
140
+ }
141
+ const row = (edge, sign) => h(`li.change-link.change-link-${sign}`, [
142
+ h("span.change-finding-sign", sign === "added" ? "+" : "−"),
143
+ ` ${edge.type} → `,
144
+ h("code", edge.to),
145
+ ]);
146
+ return h("div.change-links-list", [
147
+ h("p.change-context-title", `Links: ${[
148
+ links.added.length > 0 ? `+${links.added.length}` : undefined,
149
+ links.removed.length > 0 ? `−${links.removed.length}` : undefined,
150
+ ]
151
+ .filter((part) => part !== undefined)
152
+ .join(", ")}`),
153
+ h("ul", [
154
+ ...links.added.map((edge) => row(edge, "added")),
155
+ ...links.removed.map((edge) => row(edge, "removed")),
156
+ ]),
157
+ ]);
158
+ }
159
+ /**
160
+ * The unchanged documents the change reaches: those with findings they did not have, those linking
161
+ * into code lines that moved under them, and — folded, since a much-linked document would flood the
162
+ * page — those linking to a changed document.
163
+ */
164
+ export function renderAffected(delta) {
165
+ const { findings, codeLinks, linking } = delta.affected;
166
+ if (findings.length === 0 && codeLinks.length === 0 && linking.length === 0) {
167
+ return undefined;
168
+ }
169
+ return h("section.changes-affected", { ariaLabel: "Affected documents" }, [
170
+ h("h2", "Affected documents"),
171
+ h("p.changes-note", "Documents this branch did not change, which the change still reaches."),
172
+ findings.length === 0
173
+ ? undefined
174
+ : h("div.affected-group", [
175
+ h("h3", "With new findings"),
176
+ h("ul.affected-findings", findings.map((entry) => h("li", [
177
+ h("a", { href: documentHref(entry.path) }, entry.path),
178
+ h("ul", entry.added
179
+ .slice(0, LISTED_FINDINGS)
180
+ .map((message) => h("li", findingLine(message)))),
181
+ ]))),
182
+ ]),
183
+ codeLinks.length === 0
184
+ ? undefined
185
+ : h("div.affected-group", [
186
+ h("h3", "Linking into changed code lines"),
187
+ h("ul.affected-code", codeLinks.map((link) => {
188
+ const fragment = link.start === link.end
189
+ ? `L${link.start}`
190
+ : `L${link.start}-L${link.end}`;
191
+ return h("li", [
192
+ h("a", { href: documentHref(link.from) }, link.from),
193
+ ` line ${link.line} → `,
194
+ h("a", { href: `${fileHref(link.target)}#${fragment}` }, `${link.target}#${fragment}`),
195
+ ]);
196
+ })),
197
+ ]),
198
+ linking.length === 0
199
+ ? undefined
200
+ : h("details.affected-linking", [
201
+ h("summary", `${plural(linking.length, "document")} link to changed documents`),
202
+ h("ul", linking.map((entry) => h("li", [
203
+ h("a", { href: documentHref(entry.path) }, entry.path),
204
+ " → ",
205
+ ...entry.targets.flatMap((target, index) => [
206
+ index === 0 ? "" : ", ",
207
+ h("code", target),
208
+ ]),
209
+ ]))),
210
+ ]),
211
+ ]);
212
+ }
213
+ /** On the config's card: what the config change alone does to findings over the head's documents. */
214
+ export function renderConfigOnly(delta) {
215
+ if (delta === undefined) {
216
+ return h("p.change-note", "Both sides are linted with the same rules, so the config change alone changes no finding.");
217
+ }
218
+ const text = findingsText(delta);
219
+ return h("div.change-context", [
220
+ h("p.change-context-title", text === undefined
221
+ ? "The config change alone adds and removes no finding over the current documents."
222
+ : `The config change alone, over the current documents: ${text}`),
223
+ text === undefined ? undefined : renderFindingList(delta),
224
+ ]);
225
+ }
226
+ /** A finding as JSON carries it: its place and its words, without the rule's internal data. */
227
+ export function findingPayload(message) {
228
+ return {
229
+ filePath: message.filePath,
230
+ line: message.line,
231
+ ruleId: message.ruleId,
232
+ severity: message.severity,
233
+ message: message.message,
234
+ };
235
+ }
236
+ export function findingsPayload(delta) {
237
+ return {
238
+ added: delta.added.map(findingPayload),
239
+ removed: delta.removed.map(findingPayload),
240
+ };
241
+ }
242
+ /** One changed document's context, as JSON. */
243
+ export function documentContextPayload(delta) {
244
+ return {
245
+ findings: findingsPayload(delta.findings),
246
+ size: { base: delta.base ?? null, head: delta.head ?? null },
247
+ links: {
248
+ added: delta.links.added.map(edgePayload),
249
+ removed: delta.links.removed.map(edgePayload),
250
+ },
251
+ };
252
+ }
253
+ function edgePayload(edge) {
254
+ return { from: edge.from, to: edge.to, type: edge.type };
255
+ }
256
+ /** The whole review's context, as JSON, beside what `/api/changes` already lists. */
257
+ export function contextPayload(context) {
258
+ const { delta } = context;
259
+ return {
260
+ findings: {
261
+ added: countFindings(delta.findings.added),
262
+ removed: countFindings(delta.findings.removed),
263
+ },
264
+ eagerContext: delta.eager,
265
+ affected: {
266
+ findings: delta.affected.findings.map((entry) => ({
267
+ path: entry.path,
268
+ added: entry.added.map(findingPayload),
269
+ })),
270
+ codeLinks: delta.affected.codeLinks,
271
+ linking: delta.affected.linking,
272
+ },
273
+ notes: contextNotes(context),
274
+ };
275
+ }
276
+ // Token counts as a reader compares them with a budget: exact below ten thousand, then in thousands
277
+ // to one decimal, cut down rather than rounded, so a total just under its budget never reads as the
278
+ // budget itself (9,994 would round to "10k"). Written out by hand rather than with a locale's number
279
+ // format, which would differ between machines. Only ever handed a count of zero or more.
280
+ function tokens(value) {
281
+ if (value < 10_000) {
282
+ return String(value);
283
+ }
284
+ return `${(Math.floor(value / 100) / 10).toFixed(1).replace(/\.0$/, "")}k`;
285
+ }
286
+ // KB to the tenth shown, as a number, so two sizes are compared and subtracted at that precision.
287
+ function tenthsOfKilobytes(bytes) {
288
+ return Math.round(bytes / 102.4) / 10;
289
+ }
290
+ function signed(value, format) {
291
+ return value < 0 ? `−${format(-value)}` : `+${format(value)}`;
292
+ }
293
+ function plural(count, noun) {
294
+ return `${count} ${noun}${count === 1 ? "" : "s"}`;
295
+ }
@@ -0,0 +1,31 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import type { ViewerContext } from "./viewer-context.js";
3
+ export declare class CorpusRoutes {
4
+ private readonly ctx;
5
+ constructor(ctx: ViewerContext);
6
+ sendSearchPage(request: IncomingMessage, response: ServerResponse, query: string): Promise<void>;
7
+ /**
8
+ * The listing a link to a folder without a README opens. `folder` is only compared with the
9
+ * corpus's own folders, never joined onto a filesystem path, so a request cannot list a directory
10
+ * by naming it: what it lists is what the corpus already holds.
11
+ */
12
+ sendFolderPage(request: IncomingMessage, response: ServerResponse, folder: string | undefined): Promise<void>;
13
+ sendSearchData(response: ServerResponse, query: string): void;
14
+ private parseGraphRequest;
15
+ private graphWithChanges;
16
+ sendGraphPage(request: IncomingMessage, response: ServerResponse, params: URLSearchParams): Promise<void>;
17
+ sendGraphData(response: ServerResponse, params: URLSearchParams): Promise<void>;
18
+ sendNeighbors(response: ServerResponse, params: URLSearchParams): Promise<void>;
19
+ private dashboardSource;
20
+ sendDashboardPage(request: IncomingMessage, response: ServerResponse, params: URLSearchParams): Promise<void>;
21
+ sendDashboardData(response: ServerResponse, params: URLSearchParams): Promise<void>;
22
+ sendDiagnostics(response: ServerResponse, params: URLSearchParams): void;
23
+ /**
24
+ * `/api/diagnostics/panel?path=…`: a document's findings panel as the page draws it, for the page
25
+ * script to put in place of its own after a lint, so the panel has one renderer. Empty when the
26
+ * document has no findings; `204` while the first lint is still running, when the page keeps what
27
+ * it shows.
28
+ */
29
+ sendDiagnosticsPanel(response: ServerResponse, params: URLSearchParams): void;
30
+ sendPrompts(response: ServerResponse, params: URLSearchParams): Promise<void>;
31
+ }
@@ -0,0 +1,258 @@
1
+ import { toHtml } from "hast-util-to-html";
2
+ import { h } from "hastscript";
3
+ import { compareStrings } from "@wastech-mdlint/core";
4
+ import { dashboardChanges, graphChanges } from "./branch-changes.js";
5
+ import { buildDashboard, dashboardCsv, parseDashboardQuery, } from "./dashboard.js";
6
+ import { renderDashboardArticle } from "./dashboard-article.js";
7
+ import { buildGraphView, buildNeighborhoodView, graphFolders, renderGraphArticle, withChanges, } from "./graph-view.js";
8
+ import { sendHtml, sendJson } from "./http-send.js";
9
+ import { renderFindingsPanel } from "./findings-panel.js";
10
+ import { renderFolderArticle } from "./folder-page.js";
11
+ import { findingPrompts } from "./prompts.js";
12
+ import { workTreeChanges } from "./review-queries.js";
13
+ import { pageHeaders } from "./security.js";
14
+ // The pages about the corpus as a whole — search, the link graph, the dashboard — and the findings
15
+ // and fix prompts every document page asks for.
16
+ const FOLDER_NOT_FOUND = "No folder at this address holds corpus documents.";
17
+ const GRAPH_NOT_FOUND = "The graph shows a folder that holds corpus documents, and can highlight a document in the corpus; this address names something else.";
18
+ export class CorpusRoutes {
19
+ ctx;
20
+ constructor(ctx) {
21
+ this.ctx = ctx;
22
+ }
23
+ async sendSearchPage(request, response, query) {
24
+ const hits = this.ctx.search.search(this.ctx.corpus.documents, query);
25
+ const article = query.trim().length === 0
26
+ ? [h("h1", "Search"), h("p", "Type a word or phrase to search for.")]
27
+ : [
28
+ h("h1", `Search: ${query}`),
29
+ hits.length === 0
30
+ ? h("p", "No documents match.")
31
+ : h("ol.search-page-results", hits.map((hit) => h("li", [
32
+ h("a.search-hit-title", { href: hit.href }, [
33
+ ...markTerms(hit.title, hit.terms),
34
+ ]),
35
+ h("div.search-hit-path", hit.path),
36
+ h("p.search-hit-snippet", [
37
+ ...markTerms(hit.snippet, hit.terms),
38
+ ]),
39
+ ]))),
40
+ ];
41
+ sendHtml(response, 200, await this.ctx.page({
42
+ title: query ? `Search: ${query}` : "Search",
43
+ article,
44
+ query,
45
+ }), request.method === "HEAD");
46
+ }
47
+ /**
48
+ * The listing a link to a folder without a README opens. `folder` is only compared with the
49
+ * corpus's own folders, never joined onto a filesystem path, so a request cannot list a directory
50
+ * by naming it: what it lists is what the corpus already holds.
51
+ */
52
+ async sendFolderPage(request, response, folder) {
53
+ const { corpus } = this.ctx;
54
+ if (folder === undefined || !corpus.folders.has(folder)) {
55
+ await this.ctx.sendNotFound(request, response, FOLDER_NOT_FOUND);
56
+ return;
57
+ }
58
+ sendHtml(response, 200, await this.ctx.page({
59
+ title: folder === "" ? "All documents" : `${folder}/`,
60
+ article: renderFolderArticle(folder, corpus.documents),
61
+ ...(folder === "" ? {} : { displayPath: `${folder}/` }),
62
+ }), request.method === "HEAD");
63
+ }
64
+ sendSearchData(response, query) {
65
+ sendJson(response, {
66
+ query,
67
+ results: this.ctx.search.search(this.ctx.corpus.documents, query),
68
+ });
69
+ }
70
+ // The folder and focused document a graph request names, or `undefined` when either is not part of
71
+ // the corpus. Both are only compared against the corpus's own paths, never joined onto a
72
+ // filesystem path, so nothing a request writes here reaches the disk.
73
+ parseGraphRequest(params) {
74
+ const folder = params.get("folder") ?? "";
75
+ // `focus=` with nothing after it, as a hand-edited address may carry, focuses nothing.
76
+ const focusParam = params.get("focus");
77
+ const focus = focusParam === null || focusParam === "" ? undefined : focusParam;
78
+ if ((folder !== "" &&
79
+ !graphFolders(this.ctx.corpus.documents.keys()).includes(folder)) ||
80
+ (focus !== undefined && !this.ctx.corpus.documents.has(focus))) {
81
+ return undefined;
82
+ }
83
+ return { folder, focus };
84
+ }
85
+ // `changes=1` marks the branch's changes on a graph view; without it, or without a branch to
86
+ // compare, the view is the graph as it is.
87
+ async graphWithChanges(view, params) {
88
+ if (params.get("changes") !== "1") {
89
+ return view;
90
+ }
91
+ const branch = await workTreeChanges(this.ctx);
92
+ return branch === undefined
93
+ ? view
94
+ : withChanges(view, this.ctx.corpus.graph, graphChanges(branch.review, branch.context));
95
+ }
96
+ async sendGraphPage(request, response, params) {
97
+ const graphRequest = this.parseGraphRequest(params);
98
+ if (graphRequest === undefined) {
99
+ await this.ctx.sendNotFound(request, response, GRAPH_NOT_FOUND);
100
+ return;
101
+ }
102
+ const view = await this.graphWithChanges(buildGraphView(this.ctx.corpus.graph, this.ctx.corpus.documents, graphRequest.folder, graphRequest.focus), params);
103
+ sendHtml(response, 200, await this.ctx.page({
104
+ title: "Link graph",
105
+ section: "graph",
106
+ article: renderGraphArticle(view, graphFolders(this.ctx.corpus.documents.keys()), graphRequest.focus, this.ctx.changes === undefined
107
+ ? undefined
108
+ : { shown: params.get("changes") === "1" }),
109
+ }), request.method === "HEAD");
110
+ }
111
+ async sendGraphData(response, params) {
112
+ const graphRequest = this.parseGraphRequest(params);
113
+ if (graphRequest === undefined) {
114
+ sendJson(response, { error: GRAPH_NOT_FOUND }, 404);
115
+ return;
116
+ }
117
+ sendJson(response, await this.graphWithChanges(buildGraphView(this.ctx.corpus.graph, this.ctx.corpus.documents, graphRequest.folder, graphRequest.focus), params));
118
+ }
119
+ async sendNeighbors(response, params) {
120
+ // Only ever compared against the corpus's own paths, like the graph's parameters.
121
+ const relPath = params.get("path") ?? "";
122
+ if (!this.ctx.corpus.documents.has(relPath)) {
123
+ sendJson(response, { error: "This path is not a document in the corpus." }, 404);
124
+ return;
125
+ }
126
+ sendJson(response, await this.graphWithChanges(buildNeighborhoodView(this.ctx.corpus.graph, this.ctx.corpus.documents, relPath), params));
127
+ }
128
+ async dashboardSource() {
129
+ const findings = this.ctx.diagnostics.messagesByFile;
130
+ // The rules a reader can pick: the ones the config runs, plus any other id a finding carries,
131
+ // such as the report about a malformed suppression comment.
132
+ const ruleIds = new Set(this.ctx.corpus.configuration.rules
133
+ .filter(({ severity }) => severity !== "off")
134
+ .map(({ rule }) => rule.id));
135
+ for (const messages of findings?.values() ?? []) {
136
+ for (const message of messages) {
137
+ ruleIds.add(message.ruleId);
138
+ }
139
+ }
140
+ const branch = await workTreeChanges(this.ctx);
141
+ return {
142
+ documents: this.ctx.corpus.documents,
143
+ graph: this.ctx.corpus.graph,
144
+ findings,
145
+ ruleIds: [...ruleIds].sort(compareStrings),
146
+ folders: graphFolders(this.ctx.corpus.documents.keys()),
147
+ ...(branch === undefined
148
+ ? {}
149
+ : { changes: dashboardChanges(branch.review, branch.context) }),
150
+ };
151
+ }
152
+ async sendDashboardPage(request, response, params) {
153
+ const source = await this.dashboardSource();
154
+ const parsed = parseDashboardQuery(params, source);
155
+ sendHtml(response, parsed.ok ? 200 : 400, await this.ctx.page({
156
+ title: "Dashboard",
157
+ section: "dashboard",
158
+ firstScreen: true,
159
+ article: renderDashboardArticle(parsed.ok
160
+ ? {
161
+ params,
162
+ source,
163
+ ok: true,
164
+ query: parsed.query,
165
+ result: buildDashboard(source, parsed.query),
166
+ }
167
+ : { params, source, ok: false, message: parsed.message }),
168
+ }), request.method === "HEAD");
169
+ }
170
+ async sendDashboardData(response, params) {
171
+ const source = await this.dashboardSource();
172
+ const parsed = parseDashboardQuery(params, source, ["format"]);
173
+ const format = params.get("format") ?? "";
174
+ if (!parsed.ok || !["", "json", "csv"].includes(format)) {
175
+ sendJson(response, {
176
+ error: parsed.ok
177
+ ? `Unknown format "${format}": use csv or json.`
178
+ : parsed.message,
179
+ }, 400);
180
+ return;
181
+ }
182
+ const result = buildDashboard(source, parsed.query);
183
+ if (format === "csv") {
184
+ response.writeHead(200, {
185
+ ...pageHeaders(),
186
+ "Content-Type": "text/csv; charset=utf-8",
187
+ "Content-Disposition": 'attachment; filename="dashboard.csv"',
188
+ });
189
+ response.end(dashboardCsv(result));
190
+ return;
191
+ }
192
+ sendJson(response, { query: parsed.query, ...result }, 200, format === "json"
193
+ ? { "Content-Disposition": 'attachment; filename="dashboard.json"' }
194
+ : {});
195
+ }
196
+ sendDiagnostics(response, params) {
197
+ if (!this.ctx.diagnostics.ready) {
198
+ sendJson(response, { status: "pending" });
199
+ return;
200
+ }
201
+ const relPath = params.get("path");
202
+ if (relPath === null) {
203
+ sendJson(response, {
204
+ status: "ready",
205
+ files: this.ctx.diagnostics.summary(),
206
+ });
207
+ return;
208
+ }
209
+ const document = this.ctx.corpus.documents.get(relPath);
210
+ sendJson(response, {
211
+ status: "ready",
212
+ findings: document === undefined ? [] : this.ctx.diagnostics.findings(document),
213
+ });
214
+ }
215
+ /**
216
+ * `/api/diagnostics/panel?path=…`: a document's findings panel as the page draws it, for the page
217
+ * script to put in place of its own after a lint, so the panel has one renderer. Empty when the
218
+ * document has no findings; `204` while the first lint is still running, when the page keeps what
219
+ * it shows.
220
+ */
221
+ sendDiagnosticsPanel(response, params) {
222
+ if (!this.ctx.diagnostics.ready) {
223
+ response.writeHead(204, pageHeaders()).end();
224
+ return;
225
+ }
226
+ const relPath = params.get("path");
227
+ const document = relPath === null ? undefined : this.ctx.corpus.documents.get(relPath);
228
+ const panel = relPath === null || document === undefined
229
+ ? undefined
230
+ : renderFindingsPanel(relPath, this.ctx.diagnostics.findings(document));
231
+ sendHtml(response, 200, panel === undefined ? "" : toHtml(panel));
232
+ }
233
+ async sendPrompts(response, params) {
234
+ const line = params.get("line");
235
+ const answer = await findingPrompts({
236
+ corpus: this.ctx.corpus,
237
+ findings: this.ctx.diagnostics.messagesByFile,
238
+ // Only ever compared against the corpus's own paths and the findings' own rule ids.
239
+ filePath: params.get("path") ?? "",
240
+ ruleId: params.get("rule") ?? undefined,
241
+ line: line === null ? undefined : Number(line),
242
+ });
243
+ sendJson(response, answer.body, answer.status);
244
+ }
245
+ }
246
+ // The server-rendered twin of the client's highlighting: matched words wrapped in <mark>, built as
247
+ // hast so the text around them is escaped.
248
+ function markTerms(text, terms) {
249
+ const escaped = terms
250
+ .filter((term) => term.length > 0)
251
+ .map((term) => term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
252
+ if (escaped.length === 0) {
253
+ return [{ type: "text", value: text }];
254
+ }
255
+ return text
256
+ .split(new RegExp(`(${escaped.join("|")})`, "giu"))
257
+ .map((part, index) => index % 2 === 0 ? { type: "text", value: part } : h("mark", part));
258
+ }