@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,74 @@
1
+ import { h } from "hastscript";
2
+ import { compareStrings } from "@wastech-mdlint/core";
3
+ import { documentHref, documentTitle, folderHref } from "./render-document.js";
4
+ // The page a link to a folder opens when the folder has no README or index of its own: what GitHub
5
+ // shows for such a link, a listing of the folder. Built only from the corpus's own paths, so it lists
6
+ // documents and the folders that lead to them, never a file the viewer would not serve.
7
+ /**
8
+ * The listing of `folder`: its subfolders that hold documents, then the documents directly in it.
9
+ * The caller checks that `folder` is one of the corpus's folders; an unknown name is a 404, not an
10
+ * empty listing.
11
+ */
12
+ export function renderFolderArticle(folder, documents) {
13
+ const prefix = folder === "" ? "" : `${folder}/`;
14
+ const subfolders = new Set();
15
+ const files = [];
16
+ for (const [relPath, document] of documents) {
17
+ if (!relPath.startsWith(prefix)) {
18
+ continue;
19
+ }
20
+ const rest = relPath.slice(prefix.length);
21
+ const slash = rest.indexOf("/");
22
+ if (slash === -1) {
23
+ files.push(document);
24
+ }
25
+ else {
26
+ subfolders.add(rest.slice(0, slash));
27
+ }
28
+ }
29
+ files.sort((left, right) => compareStrings(left.path, right.path));
30
+ const scope = new URLSearchParams(folder === "" ? {} : { folder }).toString();
31
+ const suffix = scope === "" ? "" : `?${scope}`;
32
+ return [
33
+ h("nav.folder-crumbs", { "aria-label": "Folders" }, crumbs(folder)),
34
+ h("h1", folder === "" ? "All documents" : `${folder}/`),
35
+ h("p.folder-views", [
36
+ "See these documents in ",
37
+ h("a", { href: `/graph${suffix}` }, "the graph"),
38
+ " or ",
39
+ h("a", { href: `/dashboard${suffix}` }, "the dashboard"),
40
+ ".",
41
+ ]),
42
+ h("ul.folder-listing", [
43
+ ...[...subfolders]
44
+ .sort(compareStrings)
45
+ .map((name) => h("li.folder-entry-folder", [
46
+ h("a", { href: folderHref(`${prefix}${name}`) }, `${name}/`),
47
+ ])),
48
+ ...files.map((document) => {
49
+ const name = document.path.slice(prefix.length);
50
+ const title = documentTitle(document);
51
+ // A document without a top-level heading is titled by its file name already.
52
+ return h("li.folder-entry-document", [
53
+ h("a", { href: documentHref(document.path) }, title),
54
+ ...(title === name ? [] : [" ", h("span.folder-entry-name", name)]),
55
+ ]);
56
+ }),
57
+ ]),
58
+ ];
59
+ }
60
+ // Each folder above this one, so a reader can climb back up without the tree.
61
+ function crumbs(folder) {
62
+ const items = [h("a", { href: folderHref("") }, "/")];
63
+ if (folder === "") {
64
+ return items;
65
+ }
66
+ const segments = folder.split("/");
67
+ segments.forEach((segment, index) => {
68
+ const path = segments.slice(0, index + 1).join("/");
69
+ items.push(index === segments.length - 1
70
+ ? h("span", { "aria-current": "page" }, `${segment}/`)
71
+ : h("a", { href: folderHref(path) }, `${segment}/`));
72
+ });
73
+ return items;
74
+ }
@@ -0,0 +1,66 @@
1
+ import type { ElementContent } from "hast";
2
+ import { type ContextGraph, type EdgesDelta, type GitChange, type ParsedDocument } from "@wastech-mdlint/core";
3
+ export type GraphViewNode = {
4
+ path: string;
5
+ title: string;
6
+ href: string;
7
+ group: string;
8
+ inDegree: number;
9
+ outDegree: number;
10
+ change?: GitChange["status"] | "affected";
11
+ };
12
+ export type GraphViewEdge = {
13
+ from: string;
14
+ to: string;
15
+ change?: "added" | "removed";
16
+ };
17
+ export type GraphView = {
18
+ folder: string;
19
+ nodes: GraphViewNode[];
20
+ edges: GraphViewEdge[];
21
+ focus: {
22
+ path: string;
23
+ neighbors: string[];
24
+ } | null;
25
+ };
26
+ /** Every folder that holds a corpus document, directly or further down, in code-point order. */
27
+ export declare function graphFolders(paths: Iterable<string>): string[];
28
+ /**
29
+ * The part of the graph inside `folder`. The caller checks that `folder` is `""` or one of
30
+ * `graphFolders` and that `focus` is a document; an unknown name is a bad request, not an empty view.
31
+ */
32
+ export declare function buildGraphView(graph: ContextGraph, documents: ReadonlyMap<string, ParsedDocument>, folder: string, focus: string | undefined): GraphView;
33
+ /** What the branch did to the graph, from the review of its changes. */
34
+ export type GraphChanges = {
35
+ status: ReadonlyMap<string, GitChange["status"]>;
36
+ affected: ReadonlySet<string>;
37
+ links: EdgesDelta;
38
+ renamed: ReadonlyMap<string, string>;
39
+ };
40
+ /**
41
+ * `view` with the branch's changes marked: changed and affected documents, the pairs it linked, and
42
+ * the pairs it unlinked whose documents are both in view. A pair counts as linked only when every
43
+ * link between the two is new, and as unlinked only when none is left, so a pair that only changed
44
+ * the kind of its link reads as unchanged, as its line does.
45
+ */
46
+ export declare function withChanges(view: GraphView, graph: ContextGraph, changes: GraphChanges): GraphView;
47
+ /**
48
+ * The small graph beside a document: the document, the documents it links to and the ones linking
49
+ * to it, and every link among them — so two neighbors that link to each other show it too. The
50
+ * caller checks that `path` is a document.
51
+ */
52
+ export declare function buildNeighborhoodView(graph: ContextGraph, documents: ReadonlyMap<string, ParsedDocument>, path: string): GraphView;
53
+ /** The documents `path` links to or is linked from, each once, in code-point order. */
54
+ export declare function documentNeighbors(graph: ContextGraph, path: string): string[];
55
+ /**
56
+ * The graph page's article. The picture itself is drawn by the page script from `/api/graph`; what
57
+ * is rendered here works without it: the folder picker as a plain GET form, and the documents in
58
+ * view as a list of links — which is also the only form of the graph a keyboard or a screen reader
59
+ * can use, since the picture is a canvas.
60
+ *
61
+ * `focus` is the document the request asked for, kept in the form even when the chosen folder leaves
62
+ * it out of view, so going back to a folder that holds it lights it again.
63
+ */
64
+ export declare function renderGraphArticle(view: GraphView, folders: readonly string[], focus: string | undefined, changes?: {
65
+ shown: boolean;
66
+ }): ElementContent[];
@@ -0,0 +1,236 @@
1
+ import { h } from "hastscript";
2
+ import { compareStrings, query, } from "@wastech-mdlint/core";
3
+ import { documentHref, documentTitle } from "./render-document.js";
4
+ // The group of a document directly in the repository root, on the whole-corpus view.
5
+ const ROOT_GROUP = "(root)";
6
+ /** Every folder that holds a corpus document, directly or further down, in code-point order. */
7
+ export function graphFolders(paths) {
8
+ const folders = new Set();
9
+ for (const relPath of paths) {
10
+ const segments = relPath.split("/");
11
+ for (let depth = 1; depth < segments.length; depth += 1) {
12
+ folders.add(segments.slice(0, depth).join("/"));
13
+ }
14
+ }
15
+ return [...folders].sort(compareStrings);
16
+ }
17
+ /**
18
+ * The part of the graph inside `folder`. The caller checks that `folder` is `""` or one of
19
+ * `graphFolders` and that `focus` is a document; an unknown name is a bad request, not an empty view.
20
+ */
21
+ export function buildGraphView(graph, documents, folder, focus) {
22
+ const prefix = folder === "" ? "" : `${folder}/`;
23
+ const nodes = graph.nodes
24
+ .filter((node) => node.path.startsWith(prefix))
25
+ .map((node) => {
26
+ const document = documents.get(node.path);
27
+ return {
28
+ path: node.path,
29
+ title: document === undefined ? node.path : documentTitle(document),
30
+ href: documentHref(node.path),
31
+ group: groupOf(node.path, folder),
32
+ inDegree: node.inDegree,
33
+ outDegree: node.outDegree,
34
+ };
35
+ })
36
+ .sort((left, right) => compareStrings(left.path, right.path));
37
+ const inView = new Set(nodes.map((node) => node.path));
38
+ // Core sorts its edges by source, then target, so the pairs come out in that order too and a pair's
39
+ // parallel edges are adjacent.
40
+ const edges = [];
41
+ for (const edge of graph.edges) {
42
+ const previous = edges.at(-1);
43
+ if (inView.has(edge.from) &&
44
+ inView.has(edge.to) &&
45
+ (previous?.from !== edge.from || previous.to !== edge.to)) {
46
+ edges.push({ from: edge.from, to: edge.to });
47
+ }
48
+ }
49
+ return {
50
+ folder,
51
+ nodes,
52
+ edges,
53
+ focus: focus !== undefined && inView.has(focus)
54
+ ? {
55
+ path: focus,
56
+ neighbors: documentNeighbors(graph, focus).filter((path) => inView.has(path)),
57
+ }
58
+ : null,
59
+ };
60
+ }
61
+ /**
62
+ * `view` with the branch's changes marked: changed and affected documents, the pairs it linked, and
63
+ * the pairs it unlinked whose documents are both in view. A pair counts as linked only when every
64
+ * link between the two is new, and as unlinked only when none is left, so a pair that only changed
65
+ * the kind of its link reads as unchanged, as its line does.
66
+ */
67
+ export function withChanges(view, graph, changes) {
68
+ const pair = (from, to) => `${from}\u0000${to}`;
69
+ const count = (keys) => {
70
+ const counts = new Map();
71
+ for (const key of keys) {
72
+ counts.set(key, (counts.get(key) ?? 0) + 1);
73
+ }
74
+ return counts;
75
+ };
76
+ const now = count(graph.edges.map((edge) => pair(edge.from, edge.to)));
77
+ const added = count(changes.links.added.map((edge) => pair(edge.from, edge.to)));
78
+ const moved = (relPath) => changes.renamed.get(relPath) ?? relPath;
79
+ const inView = new Set(view.nodes.map((node) => node.path));
80
+ const removed = new Map();
81
+ for (const edge of changes.links.removed) {
82
+ const from = moved(edge.from);
83
+ const to = moved(edge.to);
84
+ const key = pair(from, to);
85
+ if (!now.has(key) && inView.has(from) && inView.has(to) && from !== to) {
86
+ removed.set(key, { from, to, change: "removed" });
87
+ }
88
+ }
89
+ return {
90
+ ...view,
91
+ nodes: view.nodes.map((node) => {
92
+ const change = changes.status.get(node.path) ??
93
+ (changes.affected.has(node.path) ? "affected" : undefined);
94
+ return change === undefined ? node : { ...node, change };
95
+ }),
96
+ edges: [
97
+ ...view.edges.map((edge) => {
98
+ const key = pair(edge.from, edge.to);
99
+ return added.get(key) === now.get(key)
100
+ ? { ...edge, change: "added" }
101
+ : edge;
102
+ }),
103
+ ...[...removed.values()].sort((left, right) => compareStrings(left.from, right.from) ||
104
+ compareStrings(left.to, right.to)),
105
+ ],
106
+ };
107
+ }
108
+ /**
109
+ * The small graph beside a document: the document, the documents it links to and the ones linking
110
+ * to it, and every link among them — so two neighbors that link to each other show it too. The
111
+ * caller checks that `path` is a document.
112
+ */
113
+ export function buildNeighborhoodView(graph, documents, path) {
114
+ const whole = buildGraphView(graph, documents, "", path);
115
+ const kept = new Set([path, ...(whole.focus?.neighbors ?? [])]);
116
+ return {
117
+ ...whole,
118
+ nodes: whole.nodes.filter((node) => kept.has(node.path)),
119
+ edges: whole.edges.filter((edge) => kept.has(edge.from) && kept.has(edge.to)),
120
+ };
121
+ }
122
+ /** The documents `path` links to or is linked from, each once, in code-point order. */
123
+ export function documentNeighbors(graph, path) {
124
+ const neighbors = new Set();
125
+ for (const direction of ["forward", "reverse"]) {
126
+ for (const visit of query(graph, { start: path, direction, depth: 1 })
127
+ .visited) {
128
+ if (visit.path !== path) {
129
+ neighbors.add(visit.path);
130
+ }
131
+ }
132
+ }
133
+ return [...neighbors].sort(compareStrings);
134
+ }
135
+ /**
136
+ * The graph page's article. The picture itself is drawn by the page script from `/api/graph`; what
137
+ * is rendered here works without it: the folder picker as a plain GET form, and the documents in
138
+ * view as a list of links — which is also the only form of the graph a keyboard or a screen reader
139
+ * can use, since the picture is a canvas.
140
+ *
141
+ * `focus` is the document the request asked for, kept in the form even when the chosen folder leaves
142
+ * it out of view, so going back to a folder that holds it lights it again.
143
+ */
144
+ export function renderGraphArticle(view, folders, focus,
145
+ // Set in a git work tree, where the graph can show the branch's changes: whether it does.
146
+ changes) {
147
+ return [
148
+ h("h1", "Link graph"),
149
+ h("form.graph-controls", { action: "/graph", method: "get" }, [
150
+ h("label", [
151
+ "Folder ",
152
+ h("select", { name: "folder" }, [
153
+ h("option", { value: "", selected: view.folder === "" }, "All documents"),
154
+ ...folders.map((folder) => h("option", { value: folder, selected: folder === view.folder }, folder)),
155
+ ]),
156
+ ]),
157
+ focus === undefined
158
+ ? undefined
159
+ : h("input", { type: "hidden", name: "focus", value: focus }),
160
+ changes === undefined
161
+ ? undefined
162
+ : h("label.graph-changes", [
163
+ h("input", {
164
+ type: "checkbox",
165
+ name: "changes",
166
+ value: "1",
167
+ checked: changes.shown,
168
+ }),
169
+ " Show the branch's changes",
170
+ ]),
171
+ h("button", { type: "submit" }, "Show"),
172
+ ]),
173
+ h("p.graph-summary", graphSummary(view, focus, changes)),
174
+ h("div.graph-canvas", {
175
+ dataFolder: view.folder,
176
+ dataFocus: focus,
177
+ dataChanges: changes?.shown === true ? "1" : undefined,
178
+ }, [
179
+ h("p.graph-placeholder", "The picture is drawn by the page's script. The documents in this view are listed below."),
180
+ ]),
181
+ renderGraphList(view),
182
+ ];
183
+ }
184
+ // The line under the controls: how much is in view, what the branch did to it when that is shown,
185
+ // and which document is highlighted.
186
+ function graphSummary(view, focus, changes) {
187
+ const links = view.edges.filter((edge) => edge.change !== "removed");
188
+ const summary = [
189
+ `${plural(view.nodes.length, "document")}, ${plural(links.length, "link")} between them.`,
190
+ ];
191
+ if (changes?.shown === true) {
192
+ const changed = view.nodes.filter((node) => node.change !== undefined && node.change !== "affected").length;
193
+ const affected = view.nodes.filter((node) => node.change === "affected").length;
194
+ const added = view.edges.filter((edge) => edge.change === "added").length;
195
+ const removed = view.edges.length - links.length;
196
+ summary.push(`This branch changed ${plural(changed, "document")} here and reaches ${affected} more; it linked ${plural(added, "pair")} and unlinked ${removed}.`);
197
+ }
198
+ if (view.focus !== null) {
199
+ summary.push(`${view.focus.path} is highlighted with ${plural(view.focus.neighbors.length, "neighbor")}.`);
200
+ }
201
+ else if (focus !== undefined) {
202
+ summary.push(`${focus} is not in this folder.`);
203
+ }
204
+ return summary.join(" ");
205
+ }
206
+ // The documents in view as a list of links: the graph for a keyboard or a screen reader.
207
+ function renderGraphList(view) {
208
+ return h("details.graph-list", [
209
+ h("summary", `Documents in this view (${view.nodes.length})`),
210
+ h("ul", view.nodes.map((node) => h("li", [
211
+ node.change === undefined || node.change === "affected"
212
+ ? undefined
213
+ : h(`span.change-status.change-status-${node.change}`, node.change),
214
+ node.change === undefined || node.change === "affected"
215
+ ? undefined
216
+ : " ",
217
+ h("a", { href: node.href }, node.title),
218
+ " ",
219
+ h("span.graph-list-path", node.path),
220
+ " ",
221
+ h("span.graph-list-degree", `${node.inDegree} in · ${node.outDegree} out`),
222
+ ]))),
223
+ ]);
224
+ }
225
+ function plural(count, noun) {
226
+ return `${count} ${noun}${count === 1 ? "" : "s"}`;
227
+ }
228
+ function groupOf(relPath, folder) {
229
+ const prefix = folder === "" ? "" : `${folder}/`;
230
+ const rest = relPath.slice(prefix.length);
231
+ const slash = rest.indexOf("/");
232
+ if (slash === -1) {
233
+ return folder === "" ? ROOT_GROUP : folder;
234
+ }
235
+ return `${prefix}${rest.slice(0, slash)}`;
236
+ }
@@ -0,0 +1,24 @@
1
+ import type { Element } from "hast";
2
+ import { type BundledLanguage } from "shiki";
3
+ /** Shiki's id for a fence's info string, or `undefined` when it names no grammar Shiki has. */
4
+ export declare function languageForFence(info: string | undefined): BundledLanguage | undefined;
5
+ /** Shiki's id for a source file shown as a page, chosen by its extension. */
6
+ export declare function languageForPath(relPath: string): BundledLanguage | undefined;
7
+ /**
8
+ * Highlight `code` as the `pre` element Shiki builds. Unknown languages render as plain text through
9
+ * the same path, so every code block has the same markup and styling whether or not it is colored.
10
+ *
11
+ * `lineAnchors` gives each line an `id` of `L<n>`, the fragment GitHub uses for a line of a file, so
12
+ * a document's link to `file.ts#L42` lands on that line of the source view.
13
+ */
14
+ export declare function highlight(code: string, lang: BundledLanguage | undefined, options?: {
15
+ lineAnchors?: boolean;
16
+ }): Promise<Element>;
17
+ /**
18
+ * A highlighted block with a button the page script turns into "copy this code". The block scrolls
19
+ * sideways on its own, and a button inside it would scroll away with the text, so both sit in a
20
+ * wrapper that holds the button in the block's corner. Hidden without script, which the copying
21
+ * needs; the code itself is read from the block when the button is pressed, so the page does not
22
+ * carry every block twice.
23
+ */
24
+ export declare function withCopyButton(block: Element): Element;
@@ -0,0 +1,100 @@
1
+ import { h } from "hastscript";
2
+ import { bundledLanguages, createHighlighter, } from "shiki";
3
+ // Highlighting runs on the server so a page ships no highlighter and no grammars: the browser gets
4
+ // finished markup. Both themes are emitted at once, as `--shiki-light` and `--shiki-dark` variables,
5
+ // so the stylesheet picks one with the page's color scheme and a theme change needs no re-render.
6
+ const THEMES = { light: "github-light", dark: "github-dark" };
7
+ // Grammars load on first use, not up front: Shiki ships a few hundred, a page uses a handful, and
8
+ // loading them all would put seconds on startup for languages nobody wrote.
9
+ let highlighter;
10
+ function getHighlighter() {
11
+ highlighter ??= createHighlighter({
12
+ themes: Object.values(THEMES),
13
+ langs: [],
14
+ });
15
+ return highlighter;
16
+ }
17
+ /** Shiki's id for a fence's info string, or `undefined` when it names no grammar Shiki has. */
18
+ export function languageForFence(info) {
19
+ const lang = info?.trim().split(/\s+/, 1)[0]?.toLowerCase();
20
+ if (lang === undefined || lang.length === 0) {
21
+ return undefined;
22
+ }
23
+ return Object.hasOwn(bundledLanguages, lang)
24
+ ? lang
25
+ : undefined;
26
+ }
27
+ // Extensions whose name is not itself a Shiki language id.
28
+ const EXTENSION_LANGUAGES = {
29
+ cjs: "javascript",
30
+ mjs: "javascript",
31
+ cts: "typescript",
32
+ mts: "typescript",
33
+ yml: "yaml",
34
+ htm: "html",
35
+ ps1: "powershell",
36
+ sh: "shellscript",
37
+ bash: "shellscript",
38
+ zsh: "shellscript",
39
+ txt: "text",
40
+ };
41
+ /** Shiki's id for a source file shown as a page, chosen by its extension. */
42
+ export function languageForPath(relPath) {
43
+ const name = relPath.split("/").pop() ?? "";
44
+ const dot = name.lastIndexOf(".");
45
+ const extension = dot > 0 ? name.slice(dot + 1).toLowerCase() : name.toLowerCase();
46
+ return languageForFence(EXTENSION_LANGUAGES[extension] ?? extension);
47
+ }
48
+ /**
49
+ * Highlight `code` as the `pre` element Shiki builds. Unknown languages render as plain text through
50
+ * the same path, so every code block has the same markup and styling whether or not it is colored.
51
+ *
52
+ * `lineAnchors` gives each line an `id` of `L<n>`, the fragment GitHub uses for a line of a file, so
53
+ * a document's link to `file.ts#L42` lands on that line of the source view.
54
+ */
55
+ export async function highlight(code, lang, options = {}) {
56
+ const instance = await getHighlighter();
57
+ if (lang !== undefined && !instance.getLoadedLanguages().includes(lang)) {
58
+ await instance.loadLanguage(lang);
59
+ }
60
+ const transformers = options.lineAnchors === true
61
+ ? [
62
+ {
63
+ line(node, line) {
64
+ node.properties.id = `L${line}`;
65
+ },
66
+ },
67
+ ]
68
+ : [];
69
+ const root = instance.codeToHast(code, {
70
+ lang: lang ?? "text",
71
+ themes: THEMES,
72
+ // Both themes as variables and neither inline, so the page's theme switch recolors code without
73
+ // a `!important` fight against inline styles.
74
+ defaultColor: false,
75
+ transformers,
76
+ });
77
+ const pre = root.children[0];
78
+ if (pre?.type !== "element") {
79
+ throw new Error("Shiki returned no <pre> element");
80
+ }
81
+ return pre;
82
+ }
83
+ /**
84
+ * A highlighted block with a button the page script turns into "copy this code". The block scrolls
85
+ * sideways on its own, and a button inside it would scroll away with the text, so both sit in a
86
+ * wrapper that holds the button in the block's corner. Hidden without script, which the copying
87
+ * needs; the code itself is read from the block when the button is pressed, so the page does not
88
+ * carry every block twice.
89
+ */
90
+ export function withCopyButton(block) {
91
+ return h("div.code-block", [
92
+ h("button.code-copy", {
93
+ type: "button",
94
+ hidden: true,
95
+ title: "Copy the code",
96
+ ariaLabel: "Copy the code",
97
+ }, "Copy"),
98
+ block,
99
+ ]);
100
+ }
@@ -0,0 +1,9 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ export declare function sendHtml(response: ServerResponse, status: number, html: string, headOnly?: boolean): void;
3
+ export declare function sendJson(response: ServerResponse, data: unknown, status?: number, headers?: Record<string, string>): void;
4
+ export declare function sendText(response: ServerResponse, status: number, text: string): void;
5
+ /**
6
+ * The request body as text, or `undefined` once it passes `limit` bytes. The rest is drained rather
7
+ * than kept, so the refusal can still be sent on the same connection.
8
+ */
9
+ export declare function readBody(request: IncomingMessage, limit: number): Promise<string | undefined>;
@@ -0,0 +1,53 @@
1
+ import { SPECULATION_RULES_PATH } from "./speculation-rules.js";
2
+ import { pageHeaders } from "./security.js";
3
+ // How every route answers. Each carries the same security headers, so no page, payload or refusal is
4
+ // ever sent without the CSP and the framing and sniffing protections a page needs.
5
+ export function sendHtml(response, status, html, headOnly = false) {
6
+ response.writeHead(status, {
7
+ ...pageHeaders(),
8
+ "Content-Type": "text/html; charset=utf-8",
9
+ // Which links the browser may fetch ahead of a click; the rules say why and which.
10
+ "Speculation-Rules": `"${SPECULATION_RULES_PATH}"`,
11
+ });
12
+ response.end(headOnly ? undefined : html);
13
+ }
14
+ export function sendJson(response, data, status = 200, headers = {}) {
15
+ response.writeHead(status, {
16
+ ...pageHeaders(),
17
+ ...headers,
18
+ "Content-Type": "application/json; charset=utf-8",
19
+ });
20
+ response.end(JSON.stringify(data));
21
+ }
22
+ export function sendText(response, status, text) {
23
+ response.writeHead(status, {
24
+ ...pageHeaders(),
25
+ "Content-Type": "text/plain; charset=utf-8",
26
+ });
27
+ response.end(text);
28
+ }
29
+ /**
30
+ * The request body as text, or `undefined` once it passes `limit` bytes. The rest is drained rather
31
+ * than kept, so the refusal can still be sent on the same connection.
32
+ */
33
+ export function readBody(request, limit) {
34
+ return new Promise((resolve, reject) => {
35
+ if (Number(request.headers["content-length"] ?? "0") > limit) {
36
+ request.resume();
37
+ resolve(undefined);
38
+ return;
39
+ }
40
+ const chunks = [];
41
+ let size = 0;
42
+ request.on("data", (chunk) => {
43
+ size += chunk.length;
44
+ if (size <= limit) {
45
+ chunks.push(chunk);
46
+ }
47
+ });
48
+ request.on("end", () => {
49
+ resolve(size > limit ? undefined : Buffer.concat(chunks).toString("utf8"));
50
+ });
51
+ request.on("error", reject);
52
+ });
53
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,72 @@
1
+ #!/usr/bin/env node
2
+ import { stat } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import { isStructuredError } from "@wastech-mdlint/core";
5
+ import { parseCliArgs, USAGE } from "./cli-args.js";
6
+ import { isLoopbackHost } from "./security.js";
7
+ import { startViewer } from "./server.js";
8
+ // This file is the bin and nothing imports it, so it runs unconditionally. The CLI package needs an
9
+ // entrypoint guard because its modules are also imported by tests; here everything testable lives in
10
+ // the other modules.
11
+ const EXIT_USAGE = 2;
12
+ const args = parseCliArgs(process.argv.slice(2));
13
+ if (args.kind === "help") {
14
+ process.stdout.write(USAGE);
15
+ }
16
+ else if (args.kind === "error") {
17
+ process.stderr.write(`wastech-mdlint-viewer: ${args.message}\n\n${USAGE}`);
18
+ process.exitCode = EXIT_USAGE;
19
+ }
20
+ else if ((await stat(args.cwd).catch(() => undefined))?.isDirectory() !== true) {
21
+ // Checked here, with the path as the user typed it, because the error the loader would throw
22
+ // instead names the absolute path and reads as a crash rather than a typo.
23
+ process.stderr.write(`wastech-mdlint-viewer: not a directory: ${args.cwd}\n`);
24
+ process.exitCode = EXIT_USAGE;
25
+ }
26
+ else {
27
+ try {
28
+ // Loading parses the whole corpus and takes seconds on a large repository; without this line
29
+ // the terminal shows nothing until the address appears.
30
+ process.stdout.write("wastech-mdlint-viewer: loading documents…\n");
31
+ const viewer = await startViewer(args);
32
+ process.stdout.write(`wastech-mdlint-viewer: ${viewer.documentCount} documents at ${viewer.url}\n`);
33
+ // On stderr, like any problem: nothing is wrong with the viewer, but something the user asked
34
+ // for (a `--base`, say) cannot be done as asked.
35
+ for (const notice of viewer.notices) {
36
+ process.stderr.write(`wastech-mdlint-viewer: ${notice}\n`);
37
+ }
38
+ if (args.allowConfigWrites) {
39
+ process.stdout.write("wastech-mdlint-viewer: the config page can save changes to the config file.\n");
40
+ }
41
+ if (!isLoopbackHost(args.host)) {
42
+ process.stdout.write(`wastech-mdlint-viewer: bound to ${args.host}, so other machines on the network can read these documents.\n`);
43
+ }
44
+ let closing = false;
45
+ const shutdown = (signal) => {
46
+ // A second signal while closing quits at once, with the code a shell gives a process that
47
+ // signal ended: 128 plus its number, 130 for Ctrl+C and 143 for a SIGTERM. Closing waits for
48
+ // the git and lint work already running, and a git that hangs — on a network file system, a
49
+ // lock, a credential prompt it was told not to show — would otherwise leave the terminal with
50
+ // no way to stop the viewer but killing it from elsewhere.
51
+ if (closing) {
52
+ process.exit(128 + os.constants.signals[signal]);
53
+ }
54
+ closing = true;
55
+ void viewer.close().then(() => process.exit(0));
56
+ };
57
+ process.on("SIGINT", shutdown);
58
+ process.on("SIGTERM", shutdown);
59
+ }
60
+ catch (error) {
61
+ if (isStructuredError(error)) {
62
+ process.stderr.write(`wastech-mdlint-viewer: ${error.message}\n`);
63
+ if (error.hint !== undefined) {
64
+ process.stderr.write(`${error.hint}\n`);
65
+ }
66
+ }
67
+ else {
68
+ process.stderr.write(`wastech-mdlint-viewer: ${error.message}\n`);
69
+ }
70
+ process.exitCode = 1;
71
+ }
72
+ }