@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,4 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ export declare function sendPackageAsset(request: IncomingMessage, response: ServerResponse, name: string): Promise<void>;
3
+ export declare function sendMermaid(request: IncomingMessage, response: ServerResponse, encoded: string): Promise<void>;
4
+ export declare function sendEcharts(request: IncomingMessage, response: ServerResponse): Promise<void>;
@@ -0,0 +1,107 @@
1
+ import { readFile, stat } from "node:fs/promises";
2
+ import { createRequire } from "node:module";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { sendText } from "./http-send.js";
6
+ import { decodeRequestPath } from "./request-path.js";
7
+ import { assetHeaders } from "./security.js";
8
+ // The viewer's own files and the scripts it serves from installed packages. Nothing here is read
9
+ // from the repository being viewed: each name a request may reach is fixed or matches a pattern that
10
+ // can only name a file the viewer itself ships.
11
+ // The viewer's own files. Both paths climb one level first, so they resolve to the same files from
12
+ // `dist/` when installed and from `src/` when the tests load the sources.
13
+ const STYLESHEET = fileURLToPath(new URL("../assets/viewer.css", import.meta.url));
14
+ // The tab icon, so a viewer tab stands out among the others a reader has open.
15
+ const FAVICON = fileURLToPath(new URL("../assets/favicon.ico", import.meta.url));
16
+ const CLIENT_DIR = fileURLToPath(new URL("../dist/client/", import.meta.url));
17
+ // The page scripts are the compiled client modules, which import one another by file name. A name
18
+ // is one lowercase segment ending in `.js`, so a request can reach nothing but a compiled module.
19
+ const CLIENT_SCRIPT_NAME = /^[a-z][a-z0-9-]*\.js$/;
20
+ // Mermaid is served from the installed package rather than a CDN: the viewer works offline, behind
21
+ // a proxy, and under a CSP that allows scripts from this origin only. Located through `require`
22
+ // resolution rather than `import.meta.resolve`, which test runners that transform modules do not
23
+ // provide; the package's `default` export condition makes both land on the same file.
24
+ const MERMAID_DIST = path.dirname(createRequire(import.meta.url).resolve("mermaid"));
25
+ const MERMAID_ENTRY = "mermaid.esm.min.mjs";
26
+ const MERMAID_CHUNKS = "chunks/mermaid.esm.min/";
27
+ // ECharts, for the same reasons. Its browser build is one self-contained module, so that one file
28
+ // is the only thing served from the package; any other name under the prefix is not looked up.
29
+ const ECHARTS_SCRIPT = path.join(path.dirname(createRequire(import.meta.url).resolve("echarts")), "echarts.esm.min.mjs");
30
+ // The shipped file an asset name stands for, and its type; `undefined` for any other name, so a
31
+ // request can only ever reach the stylesheet, the icon and the page script's own modules.
32
+ function packageAsset(name) {
33
+ if (name === "viewer.css") {
34
+ return { file: STYLESHEET, type: "text/css; charset=utf-8" };
35
+ }
36
+ if (name === "favicon.ico") {
37
+ return { file: FAVICON, type: "image/x-icon" };
38
+ }
39
+ if (CLIENT_SCRIPT_NAME.test(name)) {
40
+ return {
41
+ file: path.join(CLIENT_DIR, name),
42
+ type: "text/javascript; charset=utf-8",
43
+ };
44
+ }
45
+ return undefined;
46
+ }
47
+ export async function sendPackageAsset(request, response, name) {
48
+ await sendAsset(request, response, packageAsset(name));
49
+ }
50
+ export async function sendMermaid(request, response, encoded) {
51
+ const relPath = decodeRequestPath(encoded);
52
+ const allowed = relPath === MERMAID_ENTRY ||
53
+ (relPath?.startsWith(MERMAID_CHUNKS) === true && relPath.endsWith(".mjs"));
54
+ await sendScript(request, response, allowed ? path.join(MERMAID_DIST, ...relPath.split("/")) : undefined);
55
+ }
56
+ export function sendEcharts(request, response) {
57
+ return sendScript(request, response, ECHARTS_SCRIPT);
58
+ }
59
+ // A script from an installed package; `file` is undefined when the request named nothing the
60
+ // caller allows.
61
+ async function sendScript(request, response, file) {
62
+ await sendAsset(request, response, file === undefined
63
+ ? undefined
64
+ : { file, type: "text/javascript; charset=utf-8" });
65
+ }
66
+ /**
67
+ * One shipped file, or `304 Not Modified` when the browser already holds this version of it.
68
+ *
69
+ * Every page loads the stylesheet and three dozen script modules, the local graph a megabyte of
70
+ * ECharts. Answered in full each time, a page waited for the stylesheet before it was drawn and the
71
+ * graph for ECharts to be read and compiled again on every navigation. The browser still asks each
72
+ * time (`no-cache`), so files rebuilt while the viewer runs are what the next page gets; it is only
73
+ * told, from the file's size and modification time, that what it has is still current, and keeps the
74
+ * scripts it has compiled.
75
+ */
76
+ async function sendAsset(request, response, asset) {
77
+ const info = asset === undefined
78
+ ? undefined
79
+ : await stat(asset.file).catch(() => undefined);
80
+ if (asset === undefined || info?.isFile() !== true) {
81
+ sendText(response, 404, "Not found.");
82
+ return;
83
+ }
84
+ const etag = `W/"${info.size.toString(16)}-${Math.trunc(info.mtimeMs).toString(16)}"`;
85
+ if (matches(request.headers["if-none-match"], etag)) {
86
+ response.writeHead(304, { ...assetHeaders(), ETag: etag }).end();
87
+ return;
88
+ }
89
+ const body = await readFile(asset.file).catch(() => undefined);
90
+ if (body === undefined) {
91
+ sendText(response, 404, "Not found.");
92
+ return;
93
+ }
94
+ response.writeHead(200, {
95
+ ...assetHeaders(),
96
+ "Content-Type": asset.type,
97
+ ETag: etag,
98
+ });
99
+ response.end(request.method === "HEAD" ? undefined : body);
100
+ }
101
+ // Whether an `If-None-Match` header names this version; it may list several, or be `*`.
102
+ function matches(header, etag) {
103
+ return (header?.split(",").some((tag) => {
104
+ const value = tag.trim();
105
+ return value === "*" || value === etag || `W/${value}` === etag;
106
+ }) === true);
107
+ }
@@ -0,0 +1,8 @@
1
+ import { type BlameLine } from "@wastech-mdlint/core";
2
+ import type { LineAnnotator } from "./render-document.js";
3
+ /**
4
+ * The margin note of each block, from one blame of the file. A block with a line not yet committed
5
+ * says so, since that is the newest change of all. `showAuthor` is off where the page is read from
6
+ * other machines: an author's name is a person's, kept to this machine as absolute paths are.
7
+ */
8
+ export declare function blameAnnotator(lines: readonly (BlameLine | undefined)[], showAuthor: boolean): LineAnnotator;
package/dist/blame.js ADDED
@@ -0,0 +1,54 @@
1
+ import { compareStrings } from "@wastech-mdlint/core";
2
+ // Blame in the margin: for each block, the commit that last touched any of its lines, from core's
3
+ // `git blame`. A block is one unit to a reader, so the newest of its lines speaks for it — a paragraph
4
+ // edited yesterday reads as edited yesterday, however old its other lines are.
5
+ /**
6
+ * The margin note of each block, from one blame of the file. A block with a line not yet committed
7
+ * says so, since that is the newest change of all. `showAuthor` is off where the page is read from
8
+ * other machines: an author's name is a person's, kept to this machine as absolute paths are.
9
+ */
10
+ export function blameAnnotator(lines, showAuthor) {
11
+ return (start, end) => {
12
+ const newest = newestLine(lines, start, end);
13
+ if (newest === "uncommitted") {
14
+ return { text: "uncommitted", title: "Not committed yet" };
15
+ }
16
+ if (newest?.commit === undefined) {
17
+ return undefined;
18
+ }
19
+ const short = newest.short ?? newest.commit.slice(0, 7);
20
+ const date = newest.date ?? "";
21
+ const author = showAuthor && newest.author !== undefined && newest.author !== ""
22
+ ? ` · ${newest.author}`
23
+ : "";
24
+ return {
25
+ text: `${short} ${date}`.trim(),
26
+ title: `${short} · ${date}${author} — ${newest.subject ?? ""}`,
27
+ };
28
+ };
29
+ }
30
+ // The newest blamed line from `start` to `end`, one-based and inclusive, or "uncommitted" as soon as
31
+ // one line is not committed yet.
32
+ function newestLine(lines, start, end) {
33
+ let newest;
34
+ for (let line = start; line <= end; line += 1) {
35
+ const entry = lines[line - 1];
36
+ if (entry === undefined) {
37
+ continue;
38
+ }
39
+ if (entry.commit === undefined) {
40
+ return "uncommitted";
41
+ }
42
+ if (isNewer(entry, newest)) {
43
+ newest = entry;
44
+ }
45
+ }
46
+ return newest;
47
+ }
48
+ // By date, then by commit name, so two commits of one day always pick the same one.
49
+ function isNewer(entry, newest) {
50
+ return (newest === undefined ||
51
+ compareStrings(entry.date ?? "", newest.date ?? "") > 0 ||
52
+ (entry.date === newest.date &&
53
+ compareStrings(entry.commit ?? "", newest.commit ?? "") > 0));
54
+ }
@@ -0,0 +1,8 @@
1
+ import type { Review } from "./changes.js";
2
+ import type { DashboardChange } from "./dashboard.js";
3
+ import type { GraphChanges } from "./graph-view.js";
4
+ import type { ReviewContext } from "./changes.js";
5
+ /** Per document on disk: its letter when the branch changed it, and the findings it gained and lost. */
6
+ export declare function dashboardChanges(review: Review, context: ReviewContext): Map<string, DashboardChange>;
7
+ /** The changed and affected documents and the links the branch made and broke. */
8
+ export declare function graphChanges(review: Review, context: ReviewContext): GraphChanges;
@@ -0,0 +1,49 @@
1
+ // The review of a branch, restated for the pages that show it beside everything else: the dashboard's
2
+ // Branch column and the graph's marks. Both read the work-tree review, as they show the files on
3
+ // disk, and take every fact from it and its context rather than comparing anything again.
4
+ /** Per document on disk: its letter when the branch changed it, and the findings it gained and lost. */
5
+ export function dashboardChanges(review, context) {
6
+ const renamed = renames(review);
7
+ const changes = new Map();
8
+ const entry = (relPath) => {
9
+ let change = changes.get(relPath);
10
+ if (change === undefined) {
11
+ change = { findingsAdded: 0, findingsRemoved: 0 };
12
+ changes.set(relPath, change);
13
+ }
14
+ return change;
15
+ };
16
+ for (const document of review.documents) {
17
+ if (document.status !== "D") {
18
+ entry(document.path).status = document.status;
19
+ }
20
+ }
21
+ for (const message of context.delta.findings.added) {
22
+ entry(message.filePath).findingsAdded += 1;
23
+ }
24
+ for (const message of context.delta.findings.removed) {
25
+ const relPath = renamed.get(message.filePath) ?? message.filePath;
26
+ // A finding in a document the branch deleted has no row to go on.
27
+ if (review.snapshot.documents.has(relPath)) {
28
+ entry(relPath).findingsRemoved += 1;
29
+ }
30
+ }
31
+ return changes;
32
+ }
33
+ /** The changed and affected documents and the links the branch made and broke. */
34
+ export function graphChanges(review, context) {
35
+ const { affected } = context.delta;
36
+ return {
37
+ status: new Map(review.documents.flatMap((document) => document.status === "D" ? [] : [[document.path, document.status]])),
38
+ affected: new Set([
39
+ ...affected.findings.map((entry) => entry.path),
40
+ ...affected.codeLinks.map((link) => link.from),
41
+ ...affected.linking.map((entry) => entry.path),
42
+ ]),
43
+ links: context.delta.links,
44
+ renamed: renames(review),
45
+ };
46
+ }
47
+ function renames(review) {
48
+ return new Map(review.documents.flatMap((document) => document.oldPath === undefined ? [] : [[document.oldPath, document.path]]));
49
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,67 @@
1
+ import { parentPort } from "node:worker_threads";
2
+ import { buildContextGraph, lintContext, loadContext, parseConfiguration, } from "@wastech-mdlint/core";
3
+ // The thread a config preview's lint runs on. A candidate config can carry custom-rule patterns the
4
+ // reader is still typing, and one that backtracks catastrophically (`(a+)+$` against a long run of
5
+ // `a`) holds whatever thread runs it for as long as it likes. On the server's own thread that froze
6
+ // every page, the live-reload stream and Ctrl+C with it; here the server can stop it by terminating
7
+ // the thread.
8
+ // The corpus's parsed documents as last sent. The server sends them again only when its corpus has
9
+ // replaced its document map, so a burst of previews pays for one copy, not one per keystroke.
10
+ let documents = new Map();
11
+ // The graph over `documents` for the link settings it was built with: a preview that changes only
12
+ // rules lints against the same graph every time.
13
+ let graph;
14
+ parentPort?.on("message", (job) => {
15
+ void answer(job).then((reply) => parentPort?.postMessage(reply), (error) => parentPort?.postMessage({
16
+ ok: false,
17
+ reason: "failed",
18
+ message: error.message,
19
+ }));
20
+ });
21
+ async function answer(job) {
22
+ if (job.documents !== undefined) {
23
+ // Read-only on the server's side; what arrives here is the thread's own structured copy, a
24
+ // plain `Map` nothing else holds.
25
+ documents = job.documents;
26
+ graph = undefined;
27
+ }
28
+ // Validated by the server before the job was sent; parsed again here because a loaded config
29
+ // carries compiled rules, which do not cross a thread boundary.
30
+ const candidate = parseConfiguration({
31
+ text: job.text,
32
+ cwd: job.rootDir,
33
+ configPath: job.configPath,
34
+ });
35
+ let context;
36
+ if (job.sameScope) {
37
+ const { siteRouter, idRef } = candidate.settings;
38
+ const key = JSON.stringify([siteRouter, idRef]);
39
+ if (graph?.key !== key) {
40
+ graph = {
41
+ key,
42
+ graph: buildContextGraph(documents, { siteRouter, idRef }),
43
+ };
44
+ }
45
+ context = { documents, graph: graph.graph };
46
+ }
47
+ else {
48
+ // A new `include`, `exclude` or `respectGitignore` decides which files are documents, so only
49
+ // core's own discovery and parse of that scope can answer it.
50
+ context = await loadContext({
51
+ cwd: job.rootDir,
52
+ config: candidate.config,
53
+ settings: candidate.settings,
54
+ });
55
+ }
56
+ const result = lintContext({
57
+ cwd: job.rootDir,
58
+ context,
59
+ rules: candidate.rules,
60
+ settings: candidate.settings,
61
+ });
62
+ return {
63
+ ok: true,
64
+ messages: result.messages,
65
+ documentCount: context.documents.size,
66
+ };
67
+ }
@@ -0,0 +1,39 @@
1
+ import type { LintMessage, ParsedDocument } from "@wastech-mdlint/core";
2
+ /** What the worker is asked: one preview's lint. */
3
+ export type CandidateLintJob = {
4
+ rootDir: string;
5
+ configPath: string;
6
+ text: string;
7
+ sameScope: boolean;
8
+ documents?: ReadonlyMap<string, ParsedDocument>;
9
+ };
10
+ export type CandidateLintAnswer = {
11
+ ok: true;
12
+ messages: LintMessage[];
13
+ documentCount: number;
14
+ } | {
15
+ ok: false;
16
+ reason: "timeout" | "failed" | "abandoned";
17
+ message: string;
18
+ };
19
+ export declare const CANDIDATE_LINT_TIMEOUT_MS = 15000;
20
+ export declare class CandidateLinter {
21
+ private readonly timeoutMs;
22
+ private readonly workerUrl;
23
+ private worker;
24
+ private sent;
25
+ private queue;
26
+ constructor(timeoutMs?: number, workerUrl?: URL);
27
+ /**
28
+ * Lints `job` once the jobs before it are done. A job whose `signal` has aborted by then — the
29
+ * page asked for a newer preview and dropped this request — is not run: the editor aborts the
30
+ * older preview on every change, and running each in turn would put the newest one behind them
31
+ * all, up to the time limit apiece when the reader is typing into a pattern that runs away.
32
+ */
33
+ lint(job: Omit<CandidateLintJob, "documents"> & {
34
+ documents: ReadonlyMap<string, ParsedDocument>;
35
+ }, signal?: AbortSignal): Promise<CandidateLintAnswer>;
36
+ /** Stops the worker, if one is running; the next job starts a new one. */
37
+ close(): Promise<void>;
38
+ private run;
39
+ }
@@ -0,0 +1,115 @@
1
+ import { Worker } from "node:worker_threads";
2
+ // Long enough for a rules-only change over a few thousand documents, or a new scope's discovery and
3
+ // parse, and short enough that a reader whose half-typed pattern runs away is told so promptly.
4
+ export const CANDIDATE_LINT_TIMEOUT_MS = 15_000;
5
+ // The built worker module beside this one's built form. Spelled through `dist` so it resolves from
6
+ // the source tree too, where the test suite imports this file: there is no runnable `.js` under
7
+ // `src`, and a worker thread loads its module with Node's own loader, not the test runner's.
8
+ const WORKER_URL = new URL("../dist/candidate-lint-worker.js", import.meta.url);
9
+ export class CandidateLinter {
10
+ timeoutMs;
11
+ workerUrl;
12
+ worker;
13
+ // The document map the current worker holds, by identity: the corpus replaces the map whenever a
14
+ // document changes, so a different object is exactly "send them again".
15
+ sent;
16
+ // One job at a time: the worker answers in order, and a job that times out must take only its own
17
+ // worker down.
18
+ queue = Promise.resolve();
19
+ constructor(timeoutMs = CANDIDATE_LINT_TIMEOUT_MS, workerUrl = WORKER_URL) {
20
+ this.timeoutMs = timeoutMs;
21
+ this.workerUrl = workerUrl;
22
+ }
23
+ /**
24
+ * Lints `job` once the jobs before it are done. A job whose `signal` has aborted by then — the
25
+ * page asked for a newer preview and dropped this request — is not run: the editor aborts the
26
+ * older preview on every change, and running each in turn would put the newest one behind them
27
+ * all, up to the time limit apiece when the reader is typing into a pattern that runs away.
28
+ */
29
+ lint(job, signal) {
30
+ const run = this.queue.then(() => signal?.aborted === true
31
+ ? {
32
+ ok: false,
33
+ reason: "abandoned",
34
+ message: "The preview was no longer wanted.",
35
+ }
36
+ : this.run(job));
37
+ this.queue = run.catch(() => undefined);
38
+ return run;
39
+ }
40
+ /** Stops the worker, if one is running; the next job starts a new one. */
41
+ async close() {
42
+ const worker = this.worker;
43
+ this.worker = undefined;
44
+ this.sent = undefined;
45
+ await worker?.terminate();
46
+ }
47
+ run(job) {
48
+ if (this.worker === undefined) {
49
+ // Without the parent's Node flags, which a worker inherits by default: a flag that only means
50
+ // something for the main entry (`--input-type`, a test runner's loader hooks) makes the
51
+ // worker's own module fail to start.
52
+ this.worker = new Worker(this.workerUrl, { execArgv: [] });
53
+ // Never what keeps the viewer's process alive: a missed `close` must not stop it exiting.
54
+ this.worker.unref();
55
+ this.sent = undefined;
56
+ }
57
+ const worker = this.worker;
58
+ const documentsSent = this.sent === job.documents;
59
+ const message = {
60
+ rootDir: job.rootDir,
61
+ configPath: job.configPath,
62
+ text: job.text,
63
+ sameScope: job.sameScope,
64
+ ...(documentsSent ? {} : { documents: job.documents }),
65
+ };
66
+ return new Promise((resolve) => {
67
+ const settle = (answer, stop) => {
68
+ clearTimeout(timer);
69
+ worker.off("message", onMessage);
70
+ worker.off("error", onError);
71
+ worker.off("exit", onExit);
72
+ if (stop && this.worker === worker) {
73
+ this.worker = undefined;
74
+ this.sent = undefined;
75
+ void worker.terminate();
76
+ }
77
+ resolve(answer);
78
+ };
79
+ const onMessage = (answer) => {
80
+ settle(answer, false);
81
+ };
82
+ const onError = (error) => {
83
+ settle({ ok: false, reason: "failed", message: error.message }, true);
84
+ };
85
+ const onExit = () => {
86
+ settle({
87
+ ok: false,
88
+ reason: "failed",
89
+ message: "The preview's lint stopped before it answered.",
90
+ }, true);
91
+ };
92
+ const timer = setTimeout(() => {
93
+ settle({
94
+ ok: false,
95
+ reason: "timeout",
96
+ message: `The preview's lint did not finish within ${String(this.timeoutMs / 1000)} seconds and was stopped. A custom rule's pattern that backtracks without end, such as (a+)+$, does this.`,
97
+ }, true);
98
+ }, this.timeoutMs);
99
+ worker.on("message", onMessage);
100
+ worker.on("error", onError);
101
+ worker.on("exit", onExit);
102
+ try {
103
+ worker.postMessage(message);
104
+ }
105
+ catch (error) {
106
+ // Nothing reached the worker, so what it holds is unknown: it is stopped like a failed one,
107
+ // rather than left with a timer that would later stop it under another job.
108
+ settle({ ok: false, reason: "failed", message: error.message }, true);
109
+ return;
110
+ }
111
+ // Only once the worker has them: a later job then sends nothing it already holds.
112
+ this.sent = job.documents;
113
+ });
114
+ }
115
+ }
@@ -0,0 +1,38 @@
1
+ import type { Element } from "hast";
2
+ import { type DocumentReview } from "./changes.js";
3
+ import { type Baseline, type DocumentMark, type SectionMark } from "./review-state.js";
4
+ /**
5
+ * How a changed document's page shows its changes: marked on the rendered text, as its source diff
6
+ * in place of the text, or not at all. Kept in the address (`?diff=`), so a reload and a shared link
7
+ * show the same view; anything else there is the default, `rendered`.
8
+ */
9
+ export type DiffView = "rendered" | "source" | "off";
10
+ export declare function diffViewOf(params: URLSearchParams): DiffView;
11
+ /** What the line above a changed document says about the reader's review of it. */
12
+ export type BannerReview = {
13
+ mark: DocumentMark;
14
+ sections: ReadonlyMap<string, SectionMark>;
15
+ baseline: Baseline;
16
+ since?: DocumentReview;
17
+ };
18
+ export declare const BASELINES: readonly (readonly [Baseline, string])[];
19
+ /**
20
+ * The line above a changed document's text: what the branch did to it, the switch between the
21
+ * views of its changes, and the way to its card on the Changes page. Rendered with the page, from the
22
+ * review the page was marked with, so it is there without script and nothing below it moves once
23
+ * the page has loaded. The switch is a row of links, which work without script too.
24
+ *
25
+ * The stylesheet pins the line under the header while the text scrolls, so the views and the
26
+ * "Viewed" mark stay in reach on a long document. The commits that last touched the document are
27
+ * therefore not part of it: opened inside a pinned line, their list would cover the text it was
28
+ * meant to sit above. The page renders them below the line instead, as it does for any document.
29
+ */
30
+ export declare function renderChangeBanner(review: DocumentReview, view: DiffView, reviewed?: BannerReview): Element;
31
+ /**
32
+ * The commits that last touched a document, asked of git only when the reader opens it: the page
33
+ * itself never waits for a walk through history. Hidden until the script that loads it has run.
34
+ * Placed below a changed document's banner, or alone above an unchanged one's text.
35
+ */
36
+ export declare function historyDetails(relPath: string): Element;
37
+ export declare function documentViewHref(page: string, view: DiffView, baseline: Baseline): string;
38
+ export declare function changesHref(worktree: boolean, baseline: Baseline): string;
@@ -0,0 +1,108 @@
1
+ import { h } from "hastscript";
2
+ import { stats, statusBadge, statusName } from "./change-diff.js";
3
+ import { changeCardId } from "./changes.js";
4
+ import { documentHref } from "./render-document.js";
5
+ import { reviewChip, reviewToggle, } from "./review-state.js";
6
+ export function diffViewOf(params) {
7
+ const value = params.get("diff");
8
+ return value === "source" || value === "off" ? value : "rendered";
9
+ }
10
+ const DIFF_VIEWS = [
11
+ ["rendered", "Rendered"],
12
+ ["source", "Source"],
13
+ ["off", "Off"],
14
+ ];
15
+ export const BASELINES = [
16
+ ["base", "Base branch"],
17
+ ["review", "My last review"],
18
+ ];
19
+ /**
20
+ * The line above a changed document's text: what the branch did to it, the switch between the
21
+ * views of its changes, and the way to its card on the Changes page. Rendered with the page, from the
22
+ * review the page was marked with, so it is there without script and nothing below it moves once
23
+ * the page has loaded. The switch is a row of links, which work without script too.
24
+ *
25
+ * The stylesheet pins the line under the header while the text scrolls, so the views and the
26
+ * "Viewed" mark stay in reach on a long document. The commits that last touched the document are
27
+ * therefore not part of it: opened inside a pinned line, their list would cover the text it was
28
+ * meant to sit above. The page renders them below the line instead, as it does for any document.
29
+ */
30
+ export function renderChangeBanner(review, view, reviewed) {
31
+ const page = documentHref(review.path);
32
+ const baseline = reviewed?.baseline ?? "base";
33
+ return h("div.changes-banner", [
34
+ statusBadge(review.status),
35
+ h("span.changes-banner-text", bannerText(review, reviewed, baseline)),
36
+ reviewChip(reviewed?.mark),
37
+ reviewed === undefined
38
+ ? undefined
39
+ : reviewToggle(review, reviewed.mark, true),
40
+ baselineSwitch(page, view, baseline, reviewed),
41
+ h("nav.changes-view.segmented.is-compact.is-even", { ariaLabel: "Show the changes" }, DIFF_VIEWS.map(([value, label]) => h("a.segment", {
42
+ href: documentViewHref(page, value, baseline),
43
+ ariaCurrent: value === view ? "page" : undefined,
44
+ }, label))),
45
+ h("a.changes-banner-link", {
46
+ href: `${changesHref(true, baseline)}#${changeCardId(review.path)}`,
47
+ }, "Changes page"),
48
+ ]);
49
+ }
50
+ // What the branch did to the document, or — compared with the reader's last review — what changed
51
+ // since then.
52
+ function bannerText(review, reviewed, baseline) {
53
+ const since = baseline === "review" ? reviewed?.since : undefined;
54
+ if (since === undefined) {
55
+ const from = review.oldPath === undefined ? "" : `, from ${review.oldPath}`;
56
+ return `${statusName(review.status)} in this branch${from} · ${stats(review.diff)}`;
57
+ }
58
+ if (since.diff.hunks.length === 0 && !since.diff.newlineAtEndChanged) {
59
+ return "Unchanged since your review";
60
+ }
61
+ return `Changed since your review · ${stats(since.diff)}`;
62
+ }
63
+ // Offered where an earlier version was reviewed, and kept on a reviewed document while it is in use,
64
+ // so the way back is there. A document never reviewed has nothing to compare with.
65
+ function baselineSwitch(page, view, baseline, reviewed) {
66
+ if (reviewed === undefined ||
67
+ !(reviewed.mark.status === "changed" ||
68
+ (reviewed.mark.status === "reviewed" && baseline === "review"))) {
69
+ return undefined;
70
+ }
71
+ return h("nav.changes-since.segmented.is-compact.is-even", { ariaLabel: "Compare with" }, BASELINES.map(([value, label]) => h("a.segment", {
72
+ href: documentViewHref(page, view, value),
73
+ ariaCurrent: value === baseline ? "page" : undefined,
74
+ }, label)));
75
+ }
76
+ /**
77
+ * The commits that last touched a document, asked of git only when the reader opens it: the page
78
+ * itself never waits for a walk through history. Hidden until the script that loads it has run.
79
+ * Placed below a changed document's banner, or alone above an unchanged one's text.
80
+ */
81
+ export function historyDetails(relPath) {
82
+ return h("details.changes-history", { hidden: true, dataPath: relPath }, [
83
+ h("summary", "History"),
84
+ h("ol.changes-history-list"),
85
+ ]);
86
+ }
87
+ export function documentViewHref(page, view, baseline) {
88
+ const params = new URLSearchParams();
89
+ if (view !== "rendered") {
90
+ params.set("diff", view);
91
+ }
92
+ if (baseline === "review") {
93
+ params.set("since", "review");
94
+ }
95
+ const query = params.toString();
96
+ return query === "" ? page : `${page}?${query}`;
97
+ }
98
+ export function changesHref(worktree, baseline) {
99
+ const params = new URLSearchParams();
100
+ if (!worktree) {
101
+ params.set("worktree", "0");
102
+ }
103
+ if (baseline === "review") {
104
+ params.set("since", "review");
105
+ }
106
+ const query = params.toString();
107
+ return query === "" ? "/changes" : `/changes?${query}`;
108
+ }
@@ -0,0 +1,23 @@
1
+ import type { Element } from "hast";
2
+ import { type GitChange, type TextDiff } from "@wastech-mdlint/core";
3
+ /** The word a status letter stands for, as the badge's title and the banner's sentence say it. */
4
+ export declare function statusName(status: GitChange["status"]): string;
5
+ export declare function statusBadge(status: GitChange["status"]): Element;
6
+ export declare function stats(diff: TextDiff): string;
7
+ export declare function plural(count: number, noun: string): string;
8
+ /**
9
+ * Each hunk of a diff on its own, inert inside a `<template>` until the page script shows one beside
10
+ * the block it changed. Rendered here, by the code that renders the Changes page, so the browser
11
+ * never draws a diff of its own that could disagree with it.
12
+ */
13
+ export declare function renderHunkTemplate(diff: TextDiff): Element;
14
+ /**
15
+ * A diff as a table: base and head line numbers, a marker, the line. A paired line's changed words —
16
+ * or cells — are `del` and `ins`, so they read as changes to assistive technology as well as by color.
17
+ * A line moved elsewhere says where to, and the line it became says where from.
18
+ *
19
+ * With `headText`, the unchanged lines between the hunks are in the table too, hidden, each run in a
20
+ * body of its own behind a button the page script shows: the context a reader opens around a change
21
+ * comes from the server that drew the diff, so the browser never computes a line of its own.
22
+ */
23
+ export declare function renderDiff(diff: TextDiff, headText?: string): Element;