@dooc-dev/dooc 0.0.28 → 0.0.30

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 (88) hide show
  1. package/dist/client.global.js +1 -1
  2. package/dist/edit.global.js +220 -221
  3. package/dist/engine/compiler/check.js +5 -3
  4. package/dist/engine/compiler/compile.d.ts +5 -0
  5. package/dist/engine/compiler/compile.js +44 -23
  6. package/dist/engine/compiler/dialect.js +1 -1
  7. package/dist/engine/compiler/document-diff.d.ts +53 -0
  8. package/dist/engine/compiler/document-diff.js +92 -0
  9. package/dist/engine/compiler/export.js +11 -3
  10. package/dist/engine/compiler/files.d.ts +1 -0
  11. package/dist/engine/compiler/files.js +75 -14
  12. package/dist/engine/compiler/from-mdast.js +12 -1
  13. package/dist/engine/compiler/icons.d.ts +7 -7
  14. package/dist/engine/compiler/icons.js +35 -37
  15. package/dist/engine/compiler/manifest.d.ts +1 -0
  16. package/dist/engine/compiler/manifest.js +25 -0
  17. package/dist/engine/compiler/ops.d.ts +2 -2
  18. package/dist/engine/compiler/ops.js +55 -112
  19. package/dist/engine/compiler/resource-index.js +4 -4
  20. package/dist/engine/compiler/root-page.d.ts +13 -0
  21. package/dist/engine/compiler/root-page.js +96 -0
  22. package/dist/engine/compiler/sidebar-removal.d.ts +63 -0
  23. package/dist/engine/compiler/sidebar-removal.js +317 -0
  24. package/dist/engine/compiler/subformats.d.ts +3 -0
  25. package/dist/engine/compiler/subformats.js +126 -32
  26. package/dist/engine/core/blocks.d.ts +5 -0
  27. package/dist/engine/core/content-metadata.d.ts +9 -4
  28. package/dist/engine/core/content-metadata.js +100 -16
  29. package/dist/engine/core/file-embed.d.ts +2 -1
  30. package/dist/engine/core/file-embed.js +4 -0
  31. package/dist/engine/core/files.d.ts +1 -0
  32. package/dist/engine/core/files.js +6 -1
  33. package/dist/engine/core/format-collections.js +2 -2
  34. package/dist/engine/core/formats.d.ts +1 -1
  35. package/dist/engine/core/formats.js +1 -1
  36. package/dist/engine/core/html.d.ts +4 -1
  37. package/dist/engine/core/html.js +13 -6
  38. package/dist/engine/core/icons.d.ts +7 -0
  39. package/dist/engine/core/icons.js +38 -0
  40. package/dist/engine/core/subformats.d.ts +2 -1
  41. package/dist/engine/core/subformats.js +6 -1
  42. package/dist/engine/core/toc-library.d.ts +5 -0
  43. package/dist/engine/core/toc-library.js +27 -0
  44. package/dist/frontend/document-application.d.ts +5 -2
  45. package/dist/frontend/document-application.js +477 -189
  46. package/dist/frontend/edit-dialog.d.ts +1 -0
  47. package/dist/frontend/edit-dialog.js +12 -8
  48. package/dist/frontend/file-references.js +1 -1
  49. package/dist/frontend/locales/eng.json +63 -1
  50. package/dist/frontend/locales/jpn.json +63 -1
  51. package/dist/frontend/locales/zho.json +63 -1
  52. package/dist/frontend/page-jump.js +17 -10
  53. package/dist/frontend/resize.js +38 -12
  54. package/dist/frontend/resource-download.js +7 -1
  55. package/dist/frontend/resource-library.js +1 -0
  56. package/dist/frontend/search.js +2 -0
  57. package/dist/frontend/theme-picker.d.ts +2 -2
  58. package/dist/frontend/theme-picker.js +2 -2
  59. package/dist/frontend/toc-ui.js +13 -0
  60. package/dist/manifest.global.js +193 -192
  61. package/dist/mcp-relay.mjs +8 -4
  62. package/dist/plugins.global.js +49 -49
  63. package/dist/server/cli.js +12 -0
  64. package/dist/server/document-diff-cli.d.ts +1 -0
  65. package/dist/server/document-diff-cli.js +193 -0
  66. package/dist/server/document-diff-report.d.ts +3 -0
  67. package/dist/server/document-diff-report.js +124 -0
  68. package/dist/server/document-diff-sources.d.ts +40 -0
  69. package/dist/server/document-diff-sources.js +128 -0
  70. package/dist/server/document-versions.d.ts +3 -1
  71. package/dist/server/document-versions.js +19 -70
  72. package/dist/server/git-diff.d.ts +1 -0
  73. package/dist/server/git-diff.js +22 -2
  74. package/dist/server/git-document-snapshot.d.ts +2 -0
  75. package/dist/server/git-document-snapshot.js +63 -0
  76. package/dist/server/operation-log.js +2 -0
  77. package/dist/server/serve.d.ts +2 -2
  78. package/dist/server/serve.js +4 -9
  79. package/dist/server/workspace-server.js +6 -10
  80. package/dist/subformats.global.js +478 -74
  81. package/dist/ui.global.js +435 -80
  82. package/dist/workspace/file-operation.d.ts +10 -0
  83. package/dist/workspace/file-operation.js +47 -0
  84. package/dist/workspace/mcp-tools.js +8 -4
  85. package/dist/workspace/site-icon.js +30 -23
  86. package/dist/workspace/textfile.js +8 -8
  87. package/dist/workspace-worker.global.js +261 -202
  88. package/package.json +2 -2
@@ -43,6 +43,7 @@ commands:
43
43
  --url_preview network|embed keep URL references (default) or capture their content
44
44
  --reader-plugins <module> inject an external build plugin module (embed only)
45
45
  check [dooc.yaml] [options] JSON consistency report (check --help for options)
46
+ diff [<to> | <from> <to>] [options] compare documents (text, JSON, HTML or PDF)
46
47
  plugin manage local plugins
47
48
  pack <built-dir> [zip] package bundled JS and assets as a plugin ZIP
48
49
  add <zip> [dooc.yaml] [port] install a local plugin and print login links
@@ -308,6 +309,17 @@ Fonts:
308
309
  }
309
310
  break;
310
311
  }
312
+ case "diff": {
313
+ try {
314
+ const { diffCommand } = await import("./document-diff-cli.js");
315
+ process.exitCode = await diffCommand(args);
316
+ }
317
+ catch (error) {
318
+ console.error(error instanceof Error ? error.message : String(error));
319
+ process.exitCode = 2;
320
+ }
321
+ break;
322
+ }
311
323
  case "check": {
312
324
  const { checkSite } = await import("../engine/compiler/check.js");
313
325
  let report;
@@ -0,0 +1 @@
1
+ export declare const diffCommand: (args: string[]) => Promise<number>;
@@ -0,0 +1,193 @@
1
+ import { execFile } from "node:child_process";
2
+ import { existsSync, lstatSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync, } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
+ import { fileURLToPath, pathToFileURL } from "node:url";
6
+ import { parseArgs, promisify } from "node:util";
7
+ import { exportEntries } from "../engine/compiler/export.js";
8
+ import { withIgnoredFilesCache } from "../engine/compiler/ignored-files.js";
9
+ import { projectRoot } from "../engine/compiler/manifest.js";
10
+ import { isManifestFile, MANIFEST_FILE } from "../engine/core/content-metadata.js";
11
+ import { outputFile, writeBuildOutput } from "./build-output.js";
12
+ import { diffHtml, diffText } from "./document-diff-report.js";
13
+ import { documentComparison } from "./document-diff-sources.js";
14
+ import { git } from "./git.js";
15
+ import { gitHeadFile } from "./workspace.js";
16
+ const usage = `usage: dooc diff [<to> | <from> <to>] [options]
17
+
18
+ dooc diff committed HEAD to saved working files
19
+ dooc diff latest preceding document version to latest
20
+ dooc diff latest~2 latest compare two document versions in order
21
+ dooc diff git:main git:feature compare two Git commits
22
+
23
+ Selectors: current, latest, latest~N, X.Y.Z, git:<ref>.
24
+ One historical selector shows the change introduced by that version or commit.
25
+ Outside Git, the default compares the latest retained snapshot with saved files.
26
+
27
+ --project <path> project folder or manifest (default: ./dooc.yaml)
28
+ --format text|json|html|pdf output format (default: text)
29
+ --out <file> output path (text/JSON default to stdout;
30
+ HTML/PDF default to build/diff.html or diff.pdf)
31
+ --exit-code exit 1 for changes, 0 for no changes, 2 for errors
32
+ --help, -h show this help
33
+
34
+ PDF requires installed Chrome or Chromium. Set DOOC_CHROMIUM to its executable.`;
35
+ const pdf = async (html) => {
36
+ const temporary = mkdtempSync(join(tmpdir(), "dooc-diff-pdf-"));
37
+ try {
38
+ const input = join(temporary, "review.html");
39
+ const output = join(temporary, "review.pdf");
40
+ writeFileSync(input, html);
41
+ const commands = process.env.DOOC_CHROMIUM
42
+ ? [process.env.DOOC_CHROMIUM]
43
+ : [
44
+ "chromium",
45
+ "google-chrome",
46
+ "chromium-browser",
47
+ ...(process.platform === "darwin"
48
+ ? ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"]
49
+ : []),
50
+ ...(process.platform === "win32" ? ["chrome.exe"] : []),
51
+ ];
52
+ for (const command of commands) {
53
+ try {
54
+ await promisify(execFile)(command, [
55
+ "--headless",
56
+ "--disable-background-networking",
57
+ "--disable-extensions",
58
+ "--no-first-run",
59
+ `--user-data-dir=${join(temporary, "profile")}`,
60
+ "--no-pdf-header-footer",
61
+ `--print-to-pdf=${output}`,
62
+ pathToFileURL(input).href,
63
+ ], { timeout: 60_000, windowsHide: true });
64
+ }
65
+ catch (error) {
66
+ if (error.code === "ENOENT")
67
+ continue;
68
+ throw new Error(`Chromium PDF export failed: ${error instanceof Error ? error.message : error}`);
69
+ }
70
+ const data = readFileSync(output);
71
+ if (!data.subarray(0, 5).equals(Buffer.from("%PDF-")) ||
72
+ !data.subarray(-32).includes("%%EOF"))
73
+ throw new Error("Chromium did not produce a complete PDF");
74
+ return data;
75
+ }
76
+ throw new Error("PDF export requires Chrome or Chromium. Set DOOC_CHROMIUM to its executable.");
77
+ }
78
+ finally {
79
+ rmSync(temporary, { recursive: true, force: true });
80
+ }
81
+ };
82
+ const canonical = (path) => {
83
+ let parent = path;
84
+ while (!lstatSync(parent, { throwIfNoEntry: false }))
85
+ parent = dirname(parent);
86
+ return resolve(realpathSync(parent), relative(parent, path));
87
+ };
88
+ const inside = (root, path) => {
89
+ const rel = relative(root, path);
90
+ return rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
91
+ };
92
+ const checkDestination = async (root, path, comparison) => {
93
+ const physical = canonical(path);
94
+ const reject = () => {
95
+ throw new Error(`Cannot overwrite a source or metadata path: ${path}`);
96
+ };
97
+ for (const name of [path, physical])
98
+ if (isManifestFile(basename(name)) ||
99
+ name.split(sep).some((part) => [".git", ".dooc"].includes(part.toLowerCase())))
100
+ reject();
101
+ const info = lstatSync(path, { throwIfNoEntry: false });
102
+ if (info && !info.isFile())
103
+ reject();
104
+ if (gitHeadFile(root)) {
105
+ const metadata = await git(root, [
106
+ "rev-parse",
107
+ "--path-format=absolute",
108
+ "--git-dir",
109
+ "--git-common-dir",
110
+ ]);
111
+ if (metadata
112
+ .trimEnd()
113
+ .split("\n")
114
+ .some((dir) => inside(realpathSync(dir), physical)))
115
+ reject();
116
+ }
117
+ if (!inside(realpathSync(root), physical))
118
+ return;
119
+ const sources = new Set([...comparison.before.files.keys(), ...comparison.after.files.keys()]);
120
+ if (info &&
121
+ comparison.report.from.revision !== "current" &&
122
+ comparison.report.to.revision !== "current") {
123
+ for (const entry of withIgnoredFilesCache(() => exportEntries(root)))
124
+ sources.add(entry.name);
125
+ }
126
+ for (const source of sources) {
127
+ const original = resolve(root, source);
128
+ if (original === path || (existsSync(original) && realpathSync(original) === physical))
129
+ reject();
130
+ }
131
+ };
132
+ export const diffCommand = async (args) => {
133
+ const { values, positionals } = parseArgs({
134
+ args,
135
+ allowPositionals: true,
136
+ options: {
137
+ help: { type: "boolean", short: "h" },
138
+ project: { type: "string" },
139
+ format: { type: "string", default: "text" },
140
+ out: { type: "string" },
141
+ "exit-code": { type: "boolean" },
142
+ },
143
+ });
144
+ if (values.help) {
145
+ console.log(usage);
146
+ return 0;
147
+ }
148
+ if (positionals.length > 2)
149
+ throw new Error("Expected at most two selectors. See dooc diff --help.");
150
+ const format = values.format ?? "text";
151
+ if (!["text", "json", "html", "pdf"].includes(format))
152
+ throw new Error("Expected --format text, json, html or pdf");
153
+ if (values.out === "" || values.project === "")
154
+ throw new Error("Expected a non-empty path");
155
+ let project = values.project ?? MANIFEST_FILE;
156
+ if (/^file:/i.test(project)) {
157
+ const url = new URL(project);
158
+ if (url.username || url.password || url.search || url.hash)
159
+ throw new Error("Invalid local project URL");
160
+ project = fileURLToPath(url);
161
+ }
162
+ const root = projectRoot(statSync(project, { throwIfNoEntry: false })?.isDirectory()
163
+ ? join(project, MANIFEST_FILE)
164
+ : project);
165
+ const output = values.out
166
+ ? resolve(values.out)
167
+ : format === "html" || format === "pdf"
168
+ ? join(dirname(outputFile(root, "html")), `diff.${format}`)
169
+ : undefined;
170
+ const comparison = await documentComparison(root, positionals);
171
+ const { report, before, after } = comparison;
172
+ if (output)
173
+ await checkDestination(root, output, comparison);
174
+ let data;
175
+ if (format === "text")
176
+ data = diffText(report, !output &&
177
+ !!process.stdout.isTTY &&
178
+ process.env.NO_COLOR === undefined &&
179
+ process.env.TERM !== "dumb");
180
+ else if (format === "json")
181
+ data = `${JSON.stringify(report, null, 2)}\n`;
182
+ else {
183
+ const html = diffHtml(report, before, after);
184
+ data = format === "pdf" ? await pdf(html) : html;
185
+ }
186
+ if (output) {
187
+ writeBuildOutput(output, { data });
188
+ console.error(`${output} (${Buffer.byteLength(data)} bytes)`);
189
+ }
190
+ else
191
+ process.stdout.write(data);
192
+ return values["exit-code"] && report.changes.length ? 1 : 0;
193
+ };
@@ -0,0 +1,3 @@
1
+ import type { DiffSnapshot, DocumentDiff } from "../engine/compiler/document-diff.js";
2
+ export declare const diffText: (report: DocumentDiff, color: boolean) => string;
3
+ export declare const diffHtml: (report: DocumentDiff, before: DiffSnapshot, after: DiffSnapshot) => string;
@@ -0,0 +1,124 @@
1
+ import { FILE_HEADERS_ONLY, formatPatch } from "diff";
2
+ import { toBlocks } from "../engine/compiler/from-mdast.js";
3
+ import { blocksHtml, escapeHtml as esc } from "../engine/core/html.js";
4
+ import { parseMdast } from "../engine/core/markdown.js";
5
+ import { DARK_C, LIGHT_C } from "../frontend/theme-picker.js";
6
+ const endpointLabel = (end) => `${end.selector} (${end.version && end.version !== end.selector ? `${end.version}, ` : ""}${end.revision === "current" ? `saved ${end.contentHash.slice(0, 12)}` : end.revision.slice(0, 12)})`;
7
+ const pathLabel = (change) => change.kind === "renamed"
8
+ ? `${change.fromPath} → ${change.toPath}`
9
+ : (change.toPath ?? change.fromPath ?? "");
10
+ const metadata = (change) => {
11
+ const lines = [];
12
+ if (change.binary)
13
+ lines.push(`Binary content omitted (${change.beforeBytes} → ${change.afterBytes} bytes).`);
14
+ if (change.beforeMode && change.afterMode && change.beforeMode !== change.afterMode)
15
+ lines.push(`Mode ${change.beforeMode} → ${change.afterMode}`);
16
+ if (change.beforeLink !== change.afterLink)
17
+ lines.push(`Symlink ${change.beforeLink ?? "(none)"} → ${change.afterLink ?? "(none)"}`);
18
+ return lines;
19
+ };
20
+ export const diffText = (report, color) => {
21
+ const sections = report.changes.map((change) => {
22
+ const lines = [`${change.kind} ${pathLabel(change)}`, ...metadata(change)];
23
+ if (change.hunks.length) {
24
+ const patch = formatPatch({
25
+ oldFileName: change.fromPath ?? "/dev/null",
26
+ newFileName: change.toPath ?? "/dev/null",
27
+ oldHeader: undefined,
28
+ newHeader: undefined,
29
+ // formatPatch adjusts line numbers in place for empty sides.
30
+ hunks: change.hunks.map((hunk) => ({ ...hunk })),
31
+ }, FILE_HEADERS_ONLY);
32
+ lines.push(patch.slice(0, -1));
33
+ }
34
+ return lines.join("\n");
35
+ });
36
+ const text = `${report.scope.manifest}: ${endpointLabel(report.from)} → ${endpointLabel(report.to)}\n\n${sections.join("\n\n") || "No changes."}\n`;
37
+ if (!color)
38
+ return text;
39
+ return text.replace(/^[+-].*$/gm, (line) => `\x1b[${line.startsWith("+") ? 32 : 31}m${line}\x1b[0m`);
40
+ };
41
+ const excerpt = (change, snapshot, before) => {
42
+ const path = before ? change.fromPath : change.toPath;
43
+ if (!path)
44
+ return `<p>File ${before ? "added" : "removed"}.</p>`;
45
+ const sign = before ? "-" : "+";
46
+ const pieces = change.hunks.map((hunk) => hunk.lines
47
+ .filter((line) => line.startsWith(sign) || line.startsWith(" "))
48
+ .map((line) => line.slice(1))
49
+ .join("\n"));
50
+ const literal = () => pieces.map((piece) => `<pre>${esc(piece)}</pre>`).join("");
51
+ if (!/\.md$/i.test(path))
52
+ return literal();
53
+ const source = snapshot.files.get(path)?.data.toString("utf8") ?? "";
54
+ const changed = new Set();
55
+ for (const hunk of change.hunks) {
56
+ let line = before ? hunk.oldStart : hunk.newStart;
57
+ for (const entry of hunk.lines) {
58
+ if (entry.startsWith(sign))
59
+ changed.add(line++);
60
+ else if (entry.startsWith(" "))
61
+ line++;
62
+ }
63
+ }
64
+ const parts = [];
65
+ for (const block of parseMdast(source).children) {
66
+ const pos = block.position;
67
+ if (!pos)
68
+ continue;
69
+ let line = pos.start.line;
70
+ while (line <= pos.end.line && !changed.has(line))
71
+ line++;
72
+ if (line > pos.end.line)
73
+ continue;
74
+ const raw = source.slice(pos.start.offset, pos.end.offset);
75
+ if (["paragraph", "heading", "list", "blockquote", "table"].includes(block.type)) {
76
+ const { blocks } = toBlocks({ type: "root", children: [block] }, source);
77
+ if (blocks.length) {
78
+ parts.push(blocksHtml(blocks));
79
+ continue;
80
+ }
81
+ }
82
+ parts.push(`<pre>${esc(raw)}</pre>`);
83
+ }
84
+ return parts.join("") || literal();
85
+ };
86
+ const css = `:root{${LIGHT_C}}@media(prefers-color-scheme:dark){:root{${DARK_C}}}
87
+ *{box-sizing:border-box}body{max-width:80rem;margin:auto;padding:1.5rem;color:var(--c-fg);background:var(--c-bg0);font:1rem/1.6 system-ui,sans-serif;overflow-wrap:anywhere}
88
+ h1,h2,h3,p{margin:.5em 0}h1{font-size:1.7rem}h2{font-size:1.15rem}h3{font-size:1rem}a{color:var(--c-accent)}nav ul{padding-left:1.3rem}article{border-top:1px solid var(--c-line);padding:1rem 0}
89
+ .pair{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:1rem}.pair section{min-width:0;padding:.75rem;background:var(--c-bg1)}.pair h3{color:var(--c-fg-muted)}
90
+ pre,code,dd{white-space:pre-wrap;overflow-wrap:anywhere}pre{font:0.88rem/1.55 ui-monospace,monospace}.patch span{display:block;min-height:1em}.added{color:var(--c-ok)}.deleted{color:var(--c-danger)}
91
+ summary{cursor:pointer}dt{font-weight:600}dd{margin-left:0}table{border-collapse:collapse}td,th{padding:.2rem .6rem;border:1px solid var(--c-line)}:focus-visible{outline:2px solid var(--c-accent)}
92
+ @media(max-width:45rem){body{padding:.8rem}.pair{grid-template-columns:1fr}}
93
+ @page{size:A4;margin:14mm}@media print{body{padding:0;font-size:10pt;color:#111;background:white}nav,.review-toggle{display:none}.pair{display:block}.pair section{background:white}h2,h3,summary{break-after:avoid}pre{font-size:8pt}.patch span{break-inside:avoid}a{color:inherit}}`;
94
+ export const diffHtml = (report, before, after) => {
95
+ const links = [];
96
+ const articles = [];
97
+ for (const [i, change] of report.changes.entries()) {
98
+ const title = `${esc(change.kind)} · ${esc(pathLabel(change))}`;
99
+ links.push(`<li><a href="#change-${i}">${title}</a></li>`);
100
+ const details = metadata(change)
101
+ .map((line) => `<p>${esc(line)}</p>`)
102
+ .join("");
103
+ const patch = change.hunks
104
+ .map((hunk) => {
105
+ const lines = hunk.lines
106
+ .map((line) => `<span class="${line.startsWith("+") ? "added" : line.startsWith("-") ? "deleted" : ""}">${esc(line)}</span>`)
107
+ .join("");
108
+ return `<pre class="patch"><span>@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@</span>${lines}</pre>`;
109
+ })
110
+ .join("");
111
+ const pair = patch &&
112
+ `<div class="pair"><section><h3>Before</h3>${excerpt(change, before, true)}</section><section><h3>After</h3>${excerpt(change, after, false)}</section></div>
113
+ <details open><summary>Source diff</summary>${patch}</details>`;
114
+ articles.push(`<article id="change-${i}"><h2>${title}</h2>${details}${pair}</article>`);
115
+ }
116
+ const title = `${esc(report.scope.manifest)} · Document diff`;
117
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
118
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'">
119
+ <title>${title}</title><style>${css}</style></head><body><header><h1>${title}</h1>
120
+ <p>${esc(endpointLabel(report.from))} → ${esc(endpointLabel(report.to))}</p>
121
+ <details><summary>Comparison identity</summary><dl><dt>From</dt><dd>${esc(report.from.revision)} · ${report.from.contentHash}</dd><dt>To</dt><dd>${esc(report.to.revision)} · ${report.to.contentHash}</dd><dt>Comparison</dt><dd>${report.comparisonId}</dd></dl></details></header>
122
+ ${links.length ? `<nav aria-label="Changed files"><h2>Changed files (${links.length})</h2><ul>${links.join("")}</ul></nav>` : ""}
123
+ <main>${articles.join("") || "<p>No changes.</p>"}</main></body></html>\n`;
124
+ };
@@ -0,0 +1,40 @@
1
+ import { type DiffSnapshot } from "../engine/compiler/document-diff.js";
2
+ export declare const documentComparison: (root: string, operands: string[]) => Promise<{
3
+ report: {
4
+ schemaVersion: number;
5
+ comparisonId: string;
6
+ coverage: string;
7
+ scope: {
8
+ manifest: string;
9
+ };
10
+ from: {
11
+ contentHash: string;
12
+ selector: string;
13
+ revision: string;
14
+ version?: string;
15
+ };
16
+ to: {
17
+ contentHash: string;
18
+ selector: string;
19
+ revision: string;
20
+ version?: string;
21
+ };
22
+ changes: {
23
+ kind: string;
24
+ fromPath: string | null;
25
+ toPath: string | null;
26
+ binary: boolean;
27
+ hunks: import("diff").StructuredPatchHunk[];
28
+ beforeHash: string | null;
29
+ afterHash: string | null;
30
+ beforeBytes: number;
31
+ afterBytes: number;
32
+ beforeMode: string | null;
33
+ afterMode: string | null;
34
+ beforeLink: string | undefined;
35
+ afterLink: string | undefined;
36
+ }[];
37
+ };
38
+ before: DiffSnapshot;
39
+ after: DiffSnapshot;
40
+ }>;
@@ -0,0 +1,128 @@
1
+ import { lstatSync, readlinkSync, realpathSync } from "node:fs";
2
+ import { isAbsolute, join, relative, sep } from "node:path";
3
+ import { compareDocuments, diffHash, } from "../engine/compiler/document-diff.js";
4
+ import { exportEntries } from "../engine/compiler/export.js";
5
+ import { withIgnoredFilesCache } from "../engine/compiler/ignored-files.js";
6
+ import { manifestFile } from "../engine/compiler/manifest.js";
7
+ import { storedDocumentVersions, storedVersionRoot, } from "../engine/compiler/stored-versions.js";
8
+ import { parseDocumentVersion, parseVersionSelection, selectVersions, } from "../engine/core/document-version.js";
9
+ import { createDocumentVersions } from "./document-versions.js";
10
+ import { git } from "./git.js";
11
+ import { gitHeadFile } from "./workspace.js";
12
+ const capture = (root) => {
13
+ const files = new Map();
14
+ const identity = [];
15
+ let bytes = 0;
16
+ const entries = withIgnoredFilesCache(() => exportEntries(root));
17
+ for (const { name, data } of entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) {
18
+ bytes += data.length;
19
+ if (bytes > 256 * 1024 * 1024)
20
+ throw new Error("Document comparison exceeds 256 MiB per snapshot");
21
+ const path = join(root, name);
22
+ const stat = lstatSync(path);
23
+ const mode = stat.isSymbolicLink() ? "120000" : stat.mode & 0o100 ? "100755" : "100644";
24
+ let link = stat.isSymbolicLink() ? readlinkSync(path) : undefined;
25
+ if (link && isAbsolute(link))
26
+ link = `<project>/${relative(realpathSync(root), link).split(sep).join("/")}`;
27
+ const hash = diffHash(data);
28
+ files.set(name, { data, hash, mode, link });
29
+ identity.push([name, hash, mode, link]);
30
+ }
31
+ return { files, contentHash: diffHash(JSON.stringify(identity)) };
32
+ };
33
+ export const documentComparison = async (root, operands) => {
34
+ const manifest = manifestFile(root);
35
+ const inGit = !!gitHeadFile(root);
36
+ // Historical comparisons may use captured remote sources, never a fresh copy of a moving branch.
37
+ const catalog = createDocumentVersions(root, manifest, null);
38
+ let rows;
39
+ const versions = () => (rows ??= inGit
40
+ ? catalog.list().then((items) => items.filter((item) => item.revision !== "current"))
41
+ : Promise.resolve(selectVersions(storedDocumentVersions(root, manifest), parseVersionSelection("*"))));
42
+ const commit = async (ref) => {
43
+ if (!inGit)
44
+ throw new Error("A git: selector requires a Git workspace");
45
+ if (!ref || ref.startsWith("-") || /[\s:{}\\?*[\]]|\.\./.test(ref))
46
+ throw new Error(`Invalid Git revision: ${ref}`);
47
+ try {
48
+ return (await git(root, ["rev-parse", "--verify", "--end-of-options", `${ref}^{commit}`])).trim();
49
+ }
50
+ catch {
51
+ throw new Error(`Git commit unavailable: ${ref}. Check the ref and fetch missing history.`);
52
+ }
53
+ };
54
+ const endpoint = async (selector, previous = false) => {
55
+ if (selector === "current")
56
+ return { selector, revision: "current" };
57
+ if (selector.startsWith("git:"))
58
+ return { selector, revision: await commit(selector.slice(4)) };
59
+ const latest = /^latest(?:~(\d+))?$/.exec(selector);
60
+ if (!latest) {
61
+ try {
62
+ parseDocumentVersion(selector);
63
+ }
64
+ catch {
65
+ throw new Error(`Unknown selector '${selector}'. Use current, latest, latest~N, X.Y.Z or git:<ref>.`);
66
+ }
67
+ }
68
+ const items = await versions();
69
+ const i = latest
70
+ ? Number(latest[1] ?? 0)
71
+ : items.findIndex((item) => item.version === selector);
72
+ if (!items[i])
73
+ throw new Error(`Document version unavailable: ${selector}`);
74
+ const row = items[i + Number(previous)];
75
+ if (!row)
76
+ throw new Error(`No preceding document version available for ${selector}`);
77
+ return {
78
+ selector: previous ? row.version : selector,
79
+ version: row.version,
80
+ revision: row.revision,
81
+ };
82
+ };
83
+ try {
84
+ const [first, second] = operands;
85
+ let from;
86
+ let to;
87
+ if (first !== undefined && second !== undefined) {
88
+ from = await endpoint(first);
89
+ to = second === first ? from : await endpoint(second);
90
+ }
91
+ else if (first === undefined || first === "current") {
92
+ if (!inGit && !(await versions()).length)
93
+ throw new Error("Comparison requires a committed Git HEAD or a retained document baseline");
94
+ from = await endpoint(inGit ? "git:HEAD" : "latest");
95
+ to = await endpoint("current");
96
+ }
97
+ else {
98
+ to = await endpoint(first);
99
+ if (first.startsWith("git:")) {
100
+ from = {
101
+ selector: `${first}^1`,
102
+ revision: await commit(`${to.revision}^1`).catch(() => {
103
+ throw new Error(`No first parent available for ${first}. Check for an initial commit or shallow history.`);
104
+ }),
105
+ };
106
+ }
107
+ else
108
+ from = await endpoint(first, true);
109
+ }
110
+ const read = async ({ revision }) => {
111
+ if (revision === "current") {
112
+ const snapshot = capture(root);
113
+ if (capture(root).contentHash !== snapshot.contentHash)
114
+ throw new Error("Working files changed during capture. Run dooc diff again.");
115
+ return snapshot;
116
+ }
117
+ return capture(revision.startsWith("hash-")
118
+ ? storedVersionRoot(root, revision, manifest)
119
+ : await catalog.openCommit(revision));
120
+ };
121
+ const before = await read(from);
122
+ const after = from.revision === to.revision ? before : await read(to);
123
+ return { report: compareDocuments(manifest, from, before, to, after), before, after };
124
+ }
125
+ finally {
126
+ catalog.close();
127
+ }
128
+ };
@@ -1,8 +1,10 @@
1
1
  import { type DocumentRevision } from "../engine/core/document-version.js";
2
+ import { prepareDocumentSources } from "./remote-manifests.js";
2
3
  /** Historical sources live in disposable folders; viewing never changes a checkout. */
3
- export declare const createDocumentVersions: (root: string, name?: string) => {
4
+ export declare const createDocumentVersions: (root: string, name?: string, prepareSources?: typeof prepareDocumentSources | null) => {
4
5
  enabled: () => boolean;
5
6
  list: () => Promise<DocumentRevision[]>;
7
+ openCommit: (revision: string) => Promise<string>;
6
8
  versionAt(revision: string): Promise<string | undefined>;
7
9
  open(revision: string): Promise<string>;
8
10
  close(): void;
@@ -1,9 +1,6 @@
1
- import { execFile } from "node:child_process";
2
- import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, unlinkSync, writeFileSync, } from "node:fs";
1
+ import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
2
  import { tmpdir } from "node:os";
4
- import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
5
- import { promisify } from "node:util";
6
- import { unzipSync } from "fflate";
3
+ import { dirname, join } from "node:path";
7
4
  import { exportEntries } from "../engine/compiler/export.js";
8
5
  import { manifestFile, projectRoot, readManifest } from "../engine/compiler/manifest.js";
9
6
  import { storedDocumentVersions, storedVersionRoot, } from "../engine/compiler/stored-versions.js";
@@ -11,70 +8,29 @@ import { textfilePath } from "../engine/compiler/textfile.js";
11
8
  import { versionInput } from "../engine/compiler/version-input.js";
12
9
  import { advanceVersion, parseVersionConfig, parseVersionSelection, selectVersions, } from "../engine/core/document-version.js";
13
10
  import { git } from "./git.js";
11
+ import { gitDocumentSnapshot } from "./git-document-snapshot.js";
14
12
  import { prepareDocumentSources } from "./remote-manifests.js";
15
13
  import { gitHeadFile } from "./workspace.js";
16
14
  /** Historical sources live in disposable folders; viewing never changes a checkout. */
17
- export const createDocumentVersions = (root, name = manifestFile(root)) => {
15
+ export const createDocumentVersions = (root, name = manifestFile(root), prepareSources = prepareDocumentSources) => {
18
16
  let temporary;
19
17
  let cachedHead = "";
20
18
  let pending;
21
19
  const snapshots = new Map();
22
20
  const revisionVersions = new Map();
23
21
  const folder = () => (temporary ??= mkdtempSync(join(tmpdir(), "dooc-versions-")));
24
- const archive = async (revision, destination) => {
25
- if (!/^[a-f\d]{40}(?:[a-f\d]{24})?$/.test(revision))
26
- throw new Error("Invalid document revision");
27
- const repository = (await git(root, ["rev-parse", "--show-toplevel"])).trim();
28
- const prefix = relative(repository, root).replaceAll("\\", "/");
29
- const { stdout } = await promisify(execFile)("git", [
30
- "-C",
31
- repository,
32
- "archive",
33
- "--format=zip",
34
- `${revision}${prefix ? `:${prefix}` : ""}`,
35
- ], { encoding: "buffer", maxBuffer: 256 * 1024 * 1024, timeout: 30_000 });
36
- mkdirSync(destination, { recursive: true });
37
- let total = 0;
38
- const files = unzipSync(stdout, {
39
- filter(file) {
40
- total += file.originalSize;
41
- if (total > 256 * 1024 * 1024)
42
- throw new Error("Historical document exceeds 256 MiB");
43
- return !file.name.endsWith("/");
44
- },
45
- });
46
- for (const [name, data] of Object.entries(files)) {
47
- // Git already selected tracked files; snapshot folders must not reapply ignore rules.
48
- if (basename(name) === ".gitignore" || name.split("/").includes(".git"))
49
- continue;
50
- const path = textfilePath(destination, name);
51
- mkdirSync(dirname(path), { recursive: true });
52
- writeFileSync(path, data);
53
- }
54
- const tree = await git(repository, [
55
- "ls-tree",
56
- "-r",
57
- "-z",
58
- `${revision}${prefix ? `:${prefix}` : ""}`,
59
- ]);
60
- for (const item of tree.split("\0")) {
61
- if (!item.startsWith("120000 "))
62
- continue;
63
- const name = item.slice(item.indexOf("\t") + 1);
64
- if (!files[name] || basename(name) === ".gitignore" || name.split("/").includes(".git"))
65
- continue;
66
- const target = Buffer.from(files[name]).toString("utf8");
67
- const resolved = relative(destination, resolve(destination, dirname(name), target));
68
- if (isAbsolute(target) ||
69
- resolved === ".." ||
70
- resolved.startsWith("../") ||
71
- isAbsolute(resolved))
72
- throw new Error("Historical symlink points outside the document root");
73
- const path = textfilePath(destination, name);
74
- unlinkSync(path);
75
- symlinkSync(target, path);
22
+ const openCommit = (revision) => {
23
+ let snapshot = snapshots.get(revision);
24
+ if (!snapshot) {
25
+ const destination = mkdtempSync(join(folder(), "commit-"));
26
+ snapshot = gitDocumentSnapshot(root, name, revision, destination).catch((error) => {
27
+ snapshots.delete(revision);
28
+ rmSync(destination, { recursive: true, force: true });
29
+ throw error;
30
+ });
31
+ snapshots.set(revision, snapshot);
76
32
  }
77
- return projectRoot(join(destination, name));
33
+ return snapshot;
78
34
  };
79
35
  const load = async (head) => {
80
36
  revisionVersions.clear();
@@ -94,8 +50,8 @@ export const createDocumentVersions = (root, name = manifestFile(root)) => {
94
50
  continue;
95
51
  }
96
52
  try {
97
- const snapshot = await archive(revision, scratch);
98
- await prepareDocumentSources(snapshot);
53
+ const snapshot = await gitDocumentSnapshot(root, name, revision, scratch);
54
+ await prepareSources?.(snapshot);
99
55
  const manifest = readManifest(snapshot);
100
56
  if (manifest.errors.length)
101
57
  throw new Error(manifest.errors.join("\n"));
@@ -162,6 +118,7 @@ export const createDocumentVersions = (root, name = manifestFile(root)) => {
162
118
  return {
163
119
  enabled: () => !!gitHeadFile(root) || !!readManifest(root, name).version,
164
120
  list,
121
+ openCommit,
165
122
  async versionAt(revision) {
166
123
  const rows = await list();
167
124
  const exact = revisionVersions.get(revision) ??
@@ -186,15 +143,7 @@ export const createDocumentVersions = (root, name = manifestFile(root)) => {
186
143
  }
187
144
  if (revision.startsWith("hash-"))
188
145
  return storedVersionRoot(root, revision, name);
189
- let snapshot = snapshots.get(revision);
190
- if (!snapshot) {
191
- snapshot = archive(revision, join(folder(), revision)).catch((error) => {
192
- snapshots.delete(revision);
193
- throw error;
194
- });
195
- snapshots.set(revision, snapshot);
196
- }
197
- return snapshot;
146
+ return openCommit(revision);
198
147
  },
199
148
  close() {
200
149
  if (temporary && existsSync(temporary))