@open-document/core 0.13.3 → 0.14.1

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 (68) hide show
  1. package/dist/{build-CvsOak5B.js → build-I0cgoERP.js} +1 -1
  2. package/dist/{check-CbUBwYmf.js → check-Dys96QSL.js} +3 -3
  3. package/dist/cli/bin.js +10 -21
  4. package/dist/{config-BWtOZ1jc.d.ts → config-cAV1OCuY.d.ts} +9 -1
  5. package/dist/{context-CWgfsHoE.js → context-C-osJW5f.js} +1 -1
  6. package/dist/{dev-B8H2qT6G.js → dev-CC4PrIOC.js} +1 -1
  7. package/dist/{diff-BvIjjgnc.js → diff-DhutD4TJ.js} +2 -2
  8. package/dist/{export-DX30_s2q.js → export-KrajVJO7.js} +3 -3
  9. package/dist/{import-DgsdJT5e.js → import-Yv34za3L.js} +3 -2
  10. package/dist/index.d.ts +2 -2
  11. package/dist/ops/index.d.ts +3 -1
  12. package/dist/ops/index.js +2 -2
  13. package/dist/ops-Dux5HlkH.js +401 -0
  14. package/dist/{preview-DYMUNjXL.js → preview-7eqn9Wzf.js} +1 -1
  15. package/dist/rolldown-runtime-D7D4PA-g.js +13 -0
  16. package/dist/{config-CltJJVsw.js → session-BSbrC5gK.js} +3268 -385
  17. package/dist/{templates-B5Tz0AKb.js → templates-s-VLTSRc.js} +3 -3
  18. package/dist/vite/index.d.ts +1 -1
  19. package/dist/vite/index.js +1 -1
  20. package/package.json +1 -1
  21. package/skills/create-doc/SKILL.md +1 -1
  22. package/skills/doc-authoring/SKILL.md +6 -0
  23. package/src/app/app.tsx +2 -0
  24. package/src/app/components/agent/agent-dock.tsx +75 -0
  25. package/src/app/components/agent/agent-markdown.tsx +45 -0
  26. package/src/app/components/agent/agent-panel.tsx +695 -0
  27. package/src/app/components/agent/agent-presence.tsx +74 -0
  28. package/src/app/components/agent/composer.tsx +120 -0
  29. package/src/app/components/agent/connect-view.tsx +183 -0
  30. package/src/app/components/agent/history-view.tsx +134 -0
  31. package/src/app/components/agent/provider-logo.tsx +23 -0
  32. package/src/app/components/agent/transcript.tsx +717 -0
  33. package/src/app/components/comments/comments-panel.tsx +26 -2
  34. package/src/app/components/inspector/inspector.tsx +17 -0
  35. package/src/app/components/note-markdown.tsx +85 -0
  36. package/src/app/components/page-error-boundary.tsx +84 -0
  37. package/src/app/components/page-frame.tsx +2 -1
  38. package/src/app/components/panel/resize-handle.tsx +129 -0
  39. package/src/app/components/ui/button.tsx +97 -0
  40. package/src/app/components/ui/popover.tsx +144 -0
  41. package/src/app/components/ui/tooltip.tsx +123 -0
  42. package/src/app/lib/agent/use-agent.ts +543 -0
  43. package/src/app/lib/diagnostics.ts +13 -0
  44. package/src/app/lib/export-dom.ts +2 -1
  45. package/src/app/lib/export-pdf.ts +2 -1
  46. package/src/app/lib/i18n-ja/agent-panel.ts +115 -0
  47. package/src/app/lib/i18n-ja/agent.ts +9 -0
  48. package/src/app/lib/i18n-ja/index.ts +9 -1
  49. package/src/app/lib/i18n-ko/agent-panel.ts +114 -0
  50. package/src/app/lib/i18n-ko/agent.ts +9 -0
  51. package/src/app/lib/i18n-ko/index.ts +9 -1
  52. package/src/app/lib/i18n-zh-cn/agent-panel.ts +113 -0
  53. package/src/app/lib/i18n-zh-cn/agent.ts +9 -0
  54. package/src/app/lib/i18n-zh-cn/index.ts +9 -1
  55. package/src/app/lib/i18n-zh-tw/agent-panel.ts +113 -0
  56. package/src/app/lib/i18n-zh-tw/agent.ts +9 -0
  57. package/src/app/lib/i18n-zh-tw/index.ts +9 -1
  58. package/src/app/lib/note-markdown.ts +116 -0
  59. package/src/app/lib/toast.ts +50 -0
  60. package/src/app/lib/use-auto-grow.ts +15 -0
  61. package/src/app/lib/use-doc-titles.ts +28 -0
  62. package/src/app/lib/use-locale.ts +151 -0
  63. package/src/app/lib/utils.ts +4 -0
  64. package/src/app/routes/doc-preview.tsx +103 -0
  65. package/src/app/routes/doc.tsx +118 -11
  66. package/src/app/routes/home.tsx +43 -8
  67. package/src/app/styles.css +193 -0
  68. package/dist/ops-CSR5RlrE.js +0 -1673
@@ -1,1673 +0,0 @@
1
- import { c as isPageSizeName, i as ORIENTATIONS, o as PAGE_SIZE_NAMES, s as isOrientation } from "./sdk-CqNZzbkz.js";
2
- import { t as DOC_ID_RE } from "./open-doc-plugin-DnX5usgI.js";
3
- import { D as createDocument, E as OpsError, F as resolveEntry, j as listDocIds, t as createViteConfig, y as validateAssetName } from "./config-CltJJVsw.js";
4
- import path from "node:path";
5
- import fs from "node:fs/promises";
6
- import { existsSync } from "node:fs";
7
- import { createServer, mergeConfig } from "vite";
8
- import { execFile } from "node:child_process";
9
- import { promisify } from "node:util";
10
- import { Buffer } from "node:buffer";
11
- //#region src/render/session.ts
12
- var RenderUnavailableError = class extends Error {
13
- constructor(message) {
14
- super(message);
15
- this.name = "RenderUnavailableError";
16
- }
17
- };
18
- const INSTALL_HINT = "Headless rendering needs Playwright. Install it in this workspace:\n pnpm add -D playwright && pnpm exec playwright install chromium";
19
- async function loadPlaywright() {
20
- try {
21
- return await import("playwright");
22
- } catch {
23
- throw new RenderUnavailableError(INSTALL_HINT);
24
- }
25
- }
26
- const DEFAULT_TIMEOUT = 6e4;
27
- const PRINT_PAGE_SELECTOR = "#od-print-root .od-print-page";
28
- async function bootServer(userCwd) {
29
- const base = await createViteConfig({
30
- userCwd,
31
- headless: true
32
- });
33
- const config = mergeConfig(base, {
34
- logLevel: "silent",
35
- server: {
36
- port: 0,
37
- strictPort: false,
38
- open: false
39
- }
40
- });
41
- const server = await createServer(config);
42
- await server.listen();
43
- const origin = server.resolvedUrls?.local?.[0]?.replace(/\/$/, "");
44
- if (!origin) {
45
- await server.close();
46
- throw new Error("Could not determine the dev server URL");
47
- }
48
- return {
49
- server,
50
- origin
51
- };
52
- }
53
- async function createRenderSession(opts) {
54
- const { chromium } = await loadPlaywright();
55
- const timeout = opts.timeoutMs ?? DEFAULT_TIMEOUT;
56
- let server = null;
57
- let origin = opts.origin?.replace(/\/$/, "") ?? "";
58
- if (!origin) {
59
- const booted = await bootServer(opts.userCwd);
60
- server = booted.server;
61
- origin = booted.origin;
62
- }
63
- let browser;
64
- try {
65
- browser = await chromium.launch({ headless: true });
66
- } catch (err) {
67
- await server?.close();
68
- throw new RenderUnavailableError(`${INSTALL_HINT}\n\nChromium failed to launch: ${err.message}`);
69
- }
70
- return {
71
- origin,
72
- async open(docId) {
73
- const page = await browser.newPage({
74
- viewport: {
75
- width: 1280,
76
- height: 1024
77
- },
78
- ...opts.deviceScaleFactor !== void 0 ? { deviceScaleFactor: opts.deviceScaleFactor } : {}
79
- });
80
- const errors = [];
81
- page.on("pageerror", (err) => errors.push(String(err?.message ?? err)));
82
- await page.goto(`${origin}/d/${encodeURIComponent(docId)}`, {
83
- waitUntil: "load",
84
- timeout
85
- });
86
- try {
87
- await page.waitForFunction("globalThis.__openDoc ? globalThis.__openDoc.status().ready : false", void 0, { timeout });
88
- } catch {
89
- await page.close();
90
- const detail = errors.length ? `\n${errors.join("\n")}` : "";
91
- throw new Error(`Document "${docId}" never finished rendering.${detail}`);
92
- }
93
- const status = await page.evaluate("globalThis.__openDoc.status()");
94
- const renderer = {
95
- status,
96
- diagnose: () => page.evaluate("globalThis.__openDoc.diagnose()"),
97
- async pdf() {
98
- await page.evaluate("globalThis.__openDoc.preparePrint()");
99
- try {
100
- return await page.pdf({
101
- printBackground: true,
102
- preferCSSPageSize: true,
103
- outline: true,
104
- tagged: true
105
- });
106
- } finally {
107
- await page.evaluate("globalThis.__openDoc.releasePrint()");
108
- }
109
- },
110
- async screenshot(pageNumber) {
111
- if (pageNumber < 1 || pageNumber > status.pageCount) throw new Error(`page ${pageNumber} is out of range — "${docId}" has ${status.pageCount}`);
112
- await page.evaluate("globalThis.__openDoc.preparePrint()");
113
- await page.emulateMedia({ media: "print" });
114
- try {
115
- const sheet = await page.$(`${PRINT_PAGE_SELECTOR}:nth-child(${pageNumber})`);
116
- if (!sheet) throw new Error(`page ${pageNumber} did not render`);
117
- return await sheet.screenshot({ type: "png" });
118
- } finally {
119
- await page.emulateMedia({ media: null });
120
- await page.evaluate("globalThis.__openDoc.releasePrint()");
121
- }
122
- },
123
- async sheets() {
124
- await page.evaluate("globalThis.__openDoc.preparePrint()");
125
- await page.emulateMedia({ media: "print" });
126
- try {
127
- const out = [];
128
- for (let n = 1; n <= status.pageCount; n++) {
129
- const selector = `${PRINT_PAGE_SELECTOR}:nth-child(${n})`;
130
- const sheet = await page.$(selector);
131
- if (!sheet) throw new Error(`page ${n} did not render`);
132
- const png = await sheet.screenshot({ type: "png" });
133
- const text = await page.evaluate(`document.querySelector(${JSON.stringify(selector)})?.innerText ?? ''`);
134
- out.push({
135
- png,
136
- text
137
- });
138
- }
139
- return out;
140
- } finally {
141
- await page.emulateMedia({ media: null });
142
- await page.evaluate("globalThis.__openDoc.releasePrint()");
143
- }
144
- },
145
- html: () => page.evaluate("globalThis.__openDoc.htmlBundle()"),
146
- docx: () => page.evaluate("globalThis.__openDoc.docxBundle()"),
147
- async setRecord(index, pattern) {
148
- const { name } = await page.evaluate(`globalThis.__openDoc.setRecord(${JSON.stringify(index)}, ${pattern === void 0 ? "undefined" : JSON.stringify(pattern)})`);
149
- await page.waitForFunction(`(() => { const s = globalThis.__openDoc.status(); return s.ready && s.record === ${JSON.stringify(index)}; })()`, void 0, { timeout });
150
- renderer.status = await page.evaluate("globalThis.__openDoc.status()");
151
- return name;
152
- },
153
- close: () => page.close()
154
- };
155
- return renderer;
156
- },
157
- async compareImages(before, after) {
158
- const page = await browser.newPage();
159
- try {
160
- const toUrl = (png) => `data:image/png;base64,${Buffer.from(png).toString("base64")}`;
161
- return await page.evaluate(compareInBrowser, {
162
- a: toUrl(before),
163
- b: toUrl(after),
164
- cell: DIFF_CELL
165
- });
166
- } finally {
167
- await page.close();
168
- }
169
- },
170
- async close() {
171
- await browser.close();
172
- await server?.close();
173
- }
174
- };
175
- }
176
- /** Changed pixels are gathered into cells this many px square before boxing. */
177
- const DIFF_CELL = 12;
178
- /**
179
- * Runs in the page. The browser decodes both PNGs, so nothing on the Node side
180
- * has to: draw each onto white, mark every cell where a pixel moved by more
181
- * than antialiasing does, and box the clusters of marked cells. Clusters
182
- * within two cells of each other join, so one edited paragraph is one box.
183
- */
184
- async function compareInBrowser({ a, b, cell }) {
185
- const load = async (src) => {
186
- const image = new Image();
187
- image.src = src;
188
- await image.decode();
189
- return image;
190
- };
191
- const [x, y] = await Promise.all([load(a), load(b)]);
192
- const width = Math.max(x.naturalWidth, y.naturalWidth);
193
- const height = Math.max(x.naturalHeight, y.naturalHeight);
194
- const pixels = (image) => {
195
- const canvas = document.createElement("canvas");
196
- canvas.width = width;
197
- canvas.height = height;
198
- const g = canvas.getContext("2d");
199
- if (!g) throw new Error("no 2D canvas");
200
- g.fillStyle = "#ffffff";
201
- g.fillRect(0, 0, width, height);
202
- g.drawImage(image, 0, 0);
203
- return g.getImageData(0, 0, width, height).data;
204
- };
205
- const p = pixels(x);
206
- const q = pixels(y);
207
- const cols = Math.ceil(width / cell);
208
- const rows = Math.ceil(height / cell);
209
- const hot = new Uint8Array(cols * rows);
210
- let changed = 0;
211
- for (let i = 0; i < p.length; i += 4) {
212
- if (Math.abs((p[i] ?? 0) - (q[i] ?? 0)) + Math.abs((p[i + 1] ?? 0) - (q[i + 1] ?? 0)) + Math.abs((p[i + 2] ?? 0) - (q[i + 2] ?? 0)) <= 48) continue;
213
- changed++;
214
- const px = i / 4 % width;
215
- const py = Math.floor(i / 4 / width);
216
- hot[Math.floor(py / cell) * cols + Math.floor(px / cell)] = 1;
217
- }
218
- const seen = new Uint8Array(cols * rows);
219
- const boxes = [];
220
- for (let start = 0; start < hot.length; start++) {
221
- if (!hot[start] || seen[start]) continue;
222
- let minC = cols;
223
- let maxC = 0;
224
- let minR = rows;
225
- let maxR = 0;
226
- const stack = [start];
227
- seen[start] = 1;
228
- while (stack.length > 0) {
229
- const at = stack.pop();
230
- const c = at % cols;
231
- const r = Math.floor(at / cols);
232
- minC = Math.min(minC, c);
233
- maxC = Math.max(maxC, c);
234
- minR = Math.min(minR, r);
235
- maxR = Math.max(maxR, r);
236
- for (let dr = -2; dr <= 2; dr++) for (let dc = -2; dc <= 2; dc++) {
237
- const nr = r + dr;
238
- const nc = c + dc;
239
- if (nr < 0 || nc < 0 || nr >= rows || nc >= cols) continue;
240
- const next = nr * cols + nc;
241
- if (hot[next] && !seen[next]) {
242
- seen[next] = 1;
243
- stack.push(next);
244
- }
245
- }
246
- }
247
- boxes.push({
248
- x: minC * cell,
249
- y: minR * cell,
250
- width: Math.min(width, (maxC + 1) * cell) - minC * cell,
251
- height: Math.min(height, (maxR + 1) * cell) - minR * cell
252
- });
253
- }
254
- return {
255
- width,
256
- height,
257
- changed: changed / (width * height),
258
- boxes
259
- };
260
- }
261
- //#endregion
262
- //#region src/ops/diff-pages.ts
263
- /** Longest common subsequence over two lists, as pairs of matching indices. */
264
- function lcs(a, b, same) {
265
- const rows = a.length;
266
- const cols = b.length;
267
- const table = Array.from({ length: rows + 1 }, () => new Array(cols + 1).fill(0));
268
- for (let i = rows - 1; i >= 0; i--) for (let j = cols - 1; j >= 0; j--) {
269
- const row = table[i];
270
- const below = table[i + 1];
271
- row[j] = same(a[i], b[j]) ? (below[j + 1] ?? 0) + 1 : Math.max(below[j] ?? 0, row[j + 1] ?? 0);
272
- }
273
- const pairs = [];
274
- let i = 0;
275
- let j = 0;
276
- while (i < rows && j < cols) if (same(a[i], b[j])) {
277
- pairs.push([i, j]);
278
- i++;
279
- j++;
280
- } else if ((table[i + 1]?.[j] ?? 0) >= (table[i]?.[j + 1] ?? 0)) i++;
281
- else j++;
282
- return pairs;
283
- }
284
- /**
285
- * Pairs the sheets of two versions. Pages whose text is unchanged anchor the
286
- * alignment, so a page inserted in the middle shows as one new page rather than
287
- * as every page after it having changed. Between two anchors the remaining
288
- * pages pair up in order; whichever side has more keeps the rest as added or
289
- * removed.
290
- */
291
- function alignPages(before, after) {
292
- const anchors = lcs(before, after, (x, y) => x === y);
293
- const pairs = [];
294
- let i = 0;
295
- let j = 0;
296
- const fill = (untilI, untilJ) => {
297
- while (i < untilI && j < untilJ) pairs.push({
298
- before: i++,
299
- after: j++
300
- });
301
- while (i < untilI) pairs.push({
302
- before: i++,
303
- after: null
304
- });
305
- while (j < untilJ) pairs.push({
306
- before: null,
307
- after: j++
308
- });
309
- };
310
- for (const [ai, aj] of anchors) {
311
- fill(ai, aj);
312
- pairs.push({
313
- before: i++,
314
- after: j++
315
- });
316
- }
317
- fill(before.length, after.length);
318
- return pairs;
319
- }
320
- function textLines(text) {
321
- return text.split("\n").map((line) => line.replace(/\s+/g, " ").trim()).filter((line) => line !== "");
322
- }
323
- /** A line-level diff, in reading order. */
324
- function diffLines(before, after) {
325
- const anchors = lcs(before, after, (x, y) => x === y);
326
- const out = [];
327
- let i = 0;
328
- let j = 0;
329
- for (const [ai, aj] of [...anchors, [before.length, after.length]]) {
330
- while (i < ai) out.push({
331
- op: "remove",
332
- text: before[i++] ?? ""
333
- });
334
- while (j < aj) out.push({
335
- op: "add",
336
- text: after[j++] ?? ""
337
- });
338
- if (i < before.length && j < after.length && ai < before.length) {
339
- out.push({
340
- op: "same",
341
- text: before[i] ?? ""
342
- });
343
- i++;
344
- j++;
345
- }
346
- }
347
- return out;
348
- }
349
- //#endregion
350
- //#region src/ops/diff-report.ts
351
- function escapeHtml(text) {
352
- return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
353
- }
354
- function dataUrl(png) {
355
- return png ? `data:image/png;base64,${Buffer.from(png).toString("base64")}` : "";
356
- }
357
- /** A sheet with its changed regions outlined, as percentages so it scales with the image. */
358
- function sheet(png, boxes, size) {
359
- const marks = boxes.map((box) => {
360
- const left = box.x / size.width * 100;
361
- const top = box.y / size.height * 100;
362
- const width = box.width / size.width * 100;
363
- const height = box.height / size.height * 100;
364
- return `<span class="mark" style="left:${left.toFixed(2)}%;top:${top.toFixed(2)}%;width:${width.toFixed(2)}%;height:${height.toFixed(2)}%"></span>`;
365
- }).join("");
366
- return `<div class="sheet"><img src="${dataUrl(png)}" alt="" />${marks}</div>`;
367
- }
368
- /** PNG width and height, read from the IHDR chunk. */
369
- function sizeOf(png) {
370
- if (!png || png.length < 24) return {
371
- width: 1,
372
- height: 1
373
- };
374
- const view = new DataView(png.buffer, png.byteOffset, png.byteLength);
375
- return {
376
- width: view.getUint32(16) || 1,
377
- height: view.getUint32(20) || 1
378
- };
379
- }
380
- const LABEL = {
381
- same: "Unchanged",
382
- changed: "Changed",
383
- added: "Added",
384
- removed: "Removed"
385
- };
386
- function pageName(change) {
387
- if (change.after !== null && change.before !== null && change.after !== change.before) return `Page ${change.after} <span class="was">(was ${change.before})</span>`;
388
- return `Page ${change.after ?? change.before}`;
389
- }
390
- function section(change, input) {
391
- const before = change.before === null ? void 0 : input.before[change.before - 1];
392
- const after = change.after === null ? void 0 : input.after[change.after - 1];
393
- const head = `<h2>${pageName(change)} <span class="badge ${change.status}">${LABEL[change.status]}</span></h2>`;
394
- if (change.status === "added") return `<section>${head}<div class="pair one"><figure class="added">${sheet(after, [], sizeOf(after))}<figcaption>New</figcaption></figure></div></section>`;
395
- if (change.status === "removed") return `<section>${head}<div class="pair one"><figure class="removed">${sheet(before, [], sizeOf(before))}<figcaption>Removed</figcaption></figure></div></section>`;
396
- const lines = change.lines.map((line) => `<li class="${line.op}"><span>${line.op === "add" ? "+" : "−"}</span>${escapeHtml(line.text)}</li>`).join("");
397
- return `<section>${head}<div class="pair"><figure>${sheet(before, change.boxes, sizeOf(after))}<figcaption>Before · p. ${change.before}</figcaption></figure><figure>${sheet(after, change.boxes, sizeOf(after))}<figcaption>After · p. ${change.after}</figcaption></figure></div>${lines ? `<ul class="lines">${lines}</ul>` : "<p class=\"note\">Only the drawing changed — no text was added or removed.</p>"}</section>`;
398
- }
399
- /**
400
- * The report `open-doc diff` writes: one self-contained HTML file, pictures
401
- * inlined, so it can be sent to a reviewer who has neither the repository nor
402
- * open-doc. Changed pages show before and after side by side with the changed
403
- * regions outlined and the text that moved listed beneath; unchanged pages are
404
- * a single line.
405
- */
406
- function renderDiffReport(input) {
407
- const count = (status) => input.pages.filter((page) => page.status === status).length;
408
- const changed = count("changed");
409
- const added = count("added");
410
- const removed = count("removed");
411
- const unchanged = input.pages.filter((page) => page.status === "same");
412
- const summary = changed + added + removed === 0 ? "No changes." : [
413
- changed && `${changed} changed`,
414
- added && `${added} added`,
415
- removed && `${removed} removed`,
416
- unchanged.length && `${unchanged.length} unchanged`
417
- ].filter(Boolean).join(" · ");
418
- const body = input.pages.filter((page) => page.status !== "same").map((page) => section(page, input)).join("");
419
- const same = unchanged.length ? `<p class="note">Unchanged: ${unchanged.map((page) => `p. ${page.after}`).join(", ")}</p>` : "";
420
- return `<!doctype html>
421
- <html lang="en">
422
- <head>
423
- <meta charset="utf-8" />
424
- <meta name="viewport" content="width=device-width, initial-scale=1" />
425
- <title>${escapeHtml(`${input.title} — changes since ${input.since}`)}</title>
426
- <style>
427
- :root { --text: #16181d; --muted: #6b7280; --rule: #e5e7eb; --bg: #f6f7f9; --add: #15803d; --remove: #b91c1c; --mark: #f59e0b; }
428
- * { box-sizing: border-box; }
429
- body { margin: 0; padding: 32px 16px 64px; background: var(--bg); color: var(--text);
430
- font: 14px/1.5 -apple-system, BlinkMacSystemFont, "Noto Sans TC", "Segoe UI", sans-serif; }
431
- main { max-width: 1100px; margin: 0 auto; }
432
- header h1 { margin: 0 0 4px; font-size: 22px; }
433
- header p { margin: 0; color: var(--muted); }
434
- code { font: 12px ui-monospace, Menlo, monospace; }
435
- .summary { margin: 16px 0 8px; font-weight: 600; }
436
- section { margin-top: 28px; padding-top: 20px; border-top: 1px solid var(--rule); }
437
- h2 { margin: 0 0 12px; font-size: 16px; }
438
- .was { color: var(--muted); font-weight: 400; }
439
- .badge { margin-left: 6px; padding: 1px 8px; border-radius: 999px; font-size: 11px; font-weight: 600; vertical-align: 2px; }
440
- .badge.changed { background: #fef3c7; color: #92400e; }
441
- .badge.added { background: #dcfce7; color: var(--add); }
442
- .badge.removed { background: #fee2e2; color: var(--remove); }
443
- .pair { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
444
- .pair.one { grid-template-columns: minmax(0, 520px); }
445
- @media (max-width: 720px) { .pair { grid-template-columns: 1fr; } }
446
- figure { margin: 0; }
447
- figcaption { margin-top: 6px; color: var(--muted); font-size: 12px; }
448
- .sheet { position: relative; background: #fff; box-shadow: 0 1px 3px rgb(0 0 0 / 0.12); }
449
- .sheet img { display: block; width: 100%; height: auto; }
450
- .added .sheet { outline: 3px solid var(--add); }
451
- .removed .sheet { outline: 3px solid var(--remove); opacity: 0.7; }
452
- .mark { position: absolute; border: 2px solid var(--mark); background: rgb(245 158 11 / 0.12); border-radius: 2px; }
453
- .lines { margin: 14px 0 0; padding: 0; list-style: none; font-size: 13px; }
454
- .lines li { display: flex; gap: 8px; padding: 2px 8px; border-radius: 4px; }
455
- .lines li span { flex: none; width: 1ch; font-weight: 700; }
456
- .lines .add { background: #f0fdf4; color: var(--add); }
457
- .lines .remove { background: #fef2f2; color: var(--remove); text-decoration: line-through; text-decoration-color: rgb(185 28 28 / 0.4); }
458
- .note { color: var(--muted); }
459
- </style>
460
- </head>
461
- <body>
462
- <main>
463
- <header>
464
- <h1>${escapeHtml(input.title)}</h1>
465
- <p>Changes since <code>${escapeHtml(input.since)}</code> (<code>${escapeHtml(input.commit.slice(0, 7))}</code>) · <code>${escapeHtml(input.docId)}</code></p>
466
- </header>
467
- <p class="summary">${summary}</p>
468
- ${same}
469
- ${body}
470
- </main>
471
- </body>
472
- </html>
473
- `;
474
- }
475
- //#endregion
476
- //#region src/ops/diff.ts
477
- const run = promisify(execFile);
478
- const MAX_BUFFER = 67108864;
479
- async function git(cwd, args) {
480
- const { stdout } = await run("git", args, {
481
- cwd,
482
- maxBuffer: MAX_BUFFER
483
- });
484
- return stdout;
485
- }
486
- async function gitBytes(cwd, args) {
487
- const { stdout } = await run("git", args, {
488
- cwd,
489
- maxBuffer: MAX_BUFFER,
490
- encoding: "buffer"
491
- });
492
- return stdout;
493
- }
494
- /**
495
- * The workspace as it was at `commit`, as far as one document needs it: its
496
- * folder, the global assets, and the config. It lives inside the workspace so
497
- * that `react` and `@open-document/core` resolve to the same installed copies
498
- * the current version renders with.
499
- */
500
- async function checkout(ctx, docId, commit) {
501
- const prefix = (await git(ctx.userCwd, ["rev-parse", "--show-prefix"])).trim();
502
- const dir = path.join(ctx.userCwd, ".open-doc-diff", `${commit.slice(0, 12)}-${docId}`);
503
- await fs.rm(dir, {
504
- recursive: true,
505
- force: true
506
- });
507
- const docRel = path.relative(ctx.userCwd, path.join(ctx.docsRoot, docId));
508
- const wanted = [
509
- docRel,
510
- path.relative(ctx.userCwd, ctx.globalAssetsRoot),
511
- "open-doc.config.ts"
512
- ];
513
- let exists = false;
514
- for (const rel of wanted) {
515
- const listed = await git(ctx.userCwd, [
516
- "ls-tree",
517
- "-r",
518
- "--full-tree",
519
- "--name-only",
520
- commit,
521
- "--",
522
- `${prefix}${rel.split(path.sep).join("/")}`
523
- ]);
524
- for (const file of listed.split("\n").filter(Boolean)) {
525
- const local = file.slice(prefix.length);
526
- const target = path.join(dir, local);
527
- await fs.mkdir(path.dirname(target), { recursive: true });
528
- await fs.writeFile(target, await gitBytes(ctx.userCwd, ["show", `${commit}:${file}`]));
529
- if (rel === docRel) exists = true;
530
- }
531
- }
532
- const config = path.join(dir, "open-doc.config.ts");
533
- try {
534
- await fs.access(config);
535
- } catch {
536
- await fs.copyFile(path.join(ctx.userCwd, "open-doc.config.ts"), config).catch(() => {});
537
- }
538
- return {
539
- dir,
540
- exists
541
- };
542
- }
543
- async function sheetsOf(session, docId) {
544
- const renderer = await session.open(docId);
545
- try {
546
- return {
547
- title: renderer.status.title || docId,
548
- sheets: await renderer.sheets()
549
- };
550
- } finally {
551
- await renderer.close();
552
- }
553
- }
554
- async function openSession(userCwd, origin) {
555
- try {
556
- return await createRenderSession({
557
- userCwd,
558
- ...origin ? { origin } : {},
559
- deviceScaleFactor: 1
560
- });
561
- } catch (err) {
562
- if (err instanceof RenderUnavailableError) throw new OpsError(503, err.message);
563
- throw err;
564
- }
565
- }
566
- /**
567
- * What changed in a document since a revision, page by page: the old and new
568
- * sheets rendered through the same print pipeline as an export, paired by
569
- * content, compared as pictures and as text, and written up as a report a
570
- * reviewer can read without the source.
571
- */
572
- async function diffDocument(ctx, docId, opts = {}) {
573
- if (!resolveEntry(ctx, docId)) throw new OpsError(404, `document not found: ${docId}`);
574
- const since = opts.since ?? "HEAD";
575
- let commit;
576
- try {
577
- commit = (await git(ctx.userCwd, [
578
- "rev-parse",
579
- "--verify",
580
- `${since}^{commit}`
581
- ])).trim();
582
- } catch {
583
- throw new OpsError(400, `not a revision in this repository: ${since}`);
584
- }
585
- const outDir = path.resolve(ctx.userCwd, opts.outDir ?? "out");
586
- if (outDir !== ctx.userCwd && !outDir.startsWith(ctx.userCwd + path.sep)) throw new OpsError(400, `outDir must stay inside the workspace: ${opts.outDir}`);
587
- const old = await checkout(ctx, docId, commit);
588
- const current = await openSession(ctx.userCwd, ctx.serverOrigin);
589
- try {
590
- let before = [];
591
- if (old.exists) {
592
- const past = await openSession(old.dir);
593
- try {
594
- before = (await sheetsOf(past, docId)).sheets;
595
- } finally {
596
- await past.close();
597
- }
598
- }
599
- const after = await sheetsOf(current, docId);
600
- const pairs = alignPages(before.map((sheet) => sheet.text), after.sheets.map((sheet) => sheet.text));
601
- const pages = [];
602
- for (const pair of pairs) {
603
- const b = pair.before === null ? null : before[pair.before];
604
- const a = pair.after === null ? null : after.sheets[pair.after];
605
- const page = {
606
- before: pair.before === null ? null : pair.before + 1,
607
- after: pair.after === null ? null : pair.after + 1
608
- };
609
- if (!b || !a) {
610
- pages.push({
611
- ...page,
612
- status: b ? "removed" : "added",
613
- lines: [],
614
- boxes: []
615
- });
616
- continue;
617
- }
618
- const picture = await current.compareImages(b.png, a.png);
619
- const lines = diffLines(textLines(b.text), textLines(a.text)).filter((line) => line.op !== "same");
620
- const same = picture.boxes.length === 0 && lines.length === 0;
621
- pages.push({
622
- ...page,
623
- status: same ? "same" : "changed",
624
- lines,
625
- boxes: picture.boxes
626
- });
627
- }
628
- await fs.mkdir(outDir, { recursive: true });
629
- const file = path.join(outDir, `${docId}-diff.html`);
630
- await fs.writeFile(file, renderDiffReport({
631
- docId,
632
- title: after.title,
633
- since,
634
- commit,
635
- pages,
636
- before: before.map((sheet) => sheet.png),
637
- after: after.sheets.map((sheet) => sheet.png)
638
- }));
639
- return {
640
- docId,
641
- since,
642
- commit,
643
- pages,
644
- file: path.relative(ctx.userCwd, file)
645
- };
646
- } finally {
647
- await current.close();
648
- await fs.rm(old.dir, {
649
- recursive: true,
650
- force: true
651
- });
652
- await fs.rmdir(path.dirname(old.dir)).catch(() => {});
653
- }
654
- }
655
- //#endregion
656
- //#region src/import/lang.ts
657
- const TRADITIONAL = "們這個說為國來會時對過還後點經學發應麼與實體關開種現當於從際";
658
- const SIMPLIFIED = "们这个说为国来会时对过还后点经学发应么与实体关开种现当于从际";
659
- const count = (text, re) => text.match(re)?.length ?? 0;
660
- /**
661
- * The language a Markdown file is written in, when it is one whose sheets
662
- * need to say so — Chinese, Japanese, Korean — or `undefined` for anything
663
- * else, which the document then leaves at its default.
664
- */
665
- function detectLang(text) {
666
- const han = count(text, /\p{Script=Han}/gu);
667
- const kana = count(text, /[\p{Script=Hiragana}\p{Script=Katakana}]/gu);
668
- const hangul = count(text, /\p{Script=Hangul}/gu);
669
- const latin = count(text, /\p{Script=Latin}/gu);
670
- const cjk = han + kana + hangul;
671
- if (cjk === 0 || cjk < latin * .25) return void 0;
672
- if (hangul > han + kana) return "ko";
673
- if (kana > 0 && kana >= han * .05) return "ja";
674
- let traditional = 0;
675
- let simplified = 0;
676
- for (const char of text) {
677
- const t = TRADITIONAL.indexOf(char);
678
- const s = SIMPLIFIED.indexOf(char);
679
- if (t !== -1 && SIMPLIFIED[t] !== char) traditional++;
680
- if (s !== -1 && TRADITIONAL[s] !== char) simplified++;
681
- }
682
- return simplified > traditional ? "zh-Hans" : "zh-Hant";
683
- }
684
- //#endregion
685
- //#region src/import/markdown.ts
686
- const FENCE_RE = /^(```|~~~)\s*([^\s`]*)\s*$/;
687
- const ATX_RE = /^(#{1,6})\s+(.*?)\s*#*\s*$/;
688
- const HR_RE = /^ {0,3}(?:-{3,}|\*{3,}|_{3,})\s*$/;
689
- const QUOTE_RE = /^ {0,3}> ?(.*)$/;
690
- const UL_RE = /^(\s*)([-*+])\s+(.*)$/;
691
- const OL_RE = /^(\s*)(\d{1,9})[.)]\s+(.*)$/;
692
- const SETEXT_RE = /^ {0,3}(=+|-+)\s*$/;
693
- const TABLE_DELIM_RE = /^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/;
694
- function splitLines(source) {
695
- return source.replace(/^/, "").replace(/\r\n?/g, "\n").split("\n");
696
- }
697
- function parseFrontmatter(lines) {
698
- if (lines[0]?.trim() !== "---") return {
699
- frontmatter: {},
700
- rest: lines
701
- };
702
- const end = lines.findIndex((line, i) => i > 0 && line.trim() === "---");
703
- if (end === -1) return {
704
- frontmatter: {},
705
- rest: lines
706
- };
707
- const frontmatter = {};
708
- for (const line of lines.slice(1, end)) {
709
- const match = line.match(/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/);
710
- if (!match) continue;
711
- frontmatter[match[1]] = match[2].trim().replace(/^['"]|['"]$/g, "");
712
- }
713
- return {
714
- frontmatter,
715
- rest: lines.slice(end + 1)
716
- };
717
- }
718
- function splitRow(line) {
719
- const trimmed = line.trim().replace(/^\|/, "").replace(/\|$/, "");
720
- const cells = [];
721
- let current = "";
722
- for (let i = 0; i < trimmed.length; i++) {
723
- const char = trimmed[i];
724
- if (char === "\\" && trimmed[i + 1] === "|") {
725
- current += "|";
726
- i++;
727
- continue;
728
- }
729
- if (char === "|") {
730
- cells.push(current.trim());
731
- current = "";
732
- continue;
733
- }
734
- current += char;
735
- }
736
- cells.push(current.trim());
737
- return cells;
738
- }
739
- function parseAlign(line) {
740
- return splitRow(line).map((cell) => {
741
- const left = cell.startsWith(":");
742
- const right = cell.endsWith(":");
743
- if (left && right) return "center";
744
- if (right) return "right";
745
- if (left) return "left";
746
- return null;
747
- });
748
- }
749
- function indentOf(line) {
750
- return line.length - line.trimStart().length;
751
- }
752
- function isBlockStart(line) {
753
- return ATX_RE.test(line) || HR_RE.test(line) || QUOTE_RE.test(line) || UL_RE.test(line) || OL_RE.test(line) || FENCE_RE.test(line);
754
- }
755
- function parseMarkdown(source) {
756
- const { frontmatter, rest } = parseFrontmatter(splitLines(source));
757
- return {
758
- frontmatter,
759
- blocks: parseBlocks(rest)
760
- };
761
- }
762
- function parseBlocks(lines) {
763
- const blocks = [];
764
- let i = 0;
765
- while (i < lines.length) {
766
- const line = lines[i];
767
- if (line.trim() === "") {
768
- i++;
769
- continue;
770
- }
771
- const fence = line.match(FENCE_RE);
772
- if (fence) {
773
- const marker = fence[1];
774
- const value = [];
775
- i++;
776
- while (i < lines.length && !lines[i].trimStart().startsWith(marker)) {
777
- value.push(lines[i]);
778
- i++;
779
- }
780
- i++;
781
- blocks.push({
782
- type: "code",
783
- lang: fence[2] || null,
784
- value: value.join("\n")
785
- });
786
- continue;
787
- }
788
- const atx = line.match(ATX_RE);
789
- if (atx) {
790
- blocks.push({
791
- type: "heading",
792
- level: atx[1].length,
793
- children: parseInline(atx[2])
794
- });
795
- i++;
796
- continue;
797
- }
798
- if (HR_RE.test(line)) {
799
- blocks.push({ type: "hr" });
800
- i++;
801
- continue;
802
- }
803
- if (QUOTE_RE.test(line)) {
804
- const inner = [];
805
- while (i < lines.length && (QUOTE_RE.test(lines[i]) || lines[i].trim() !== "")) {
806
- const match = lines[i].match(QUOTE_RE);
807
- if (!match && lines[i].trim() === "") break;
808
- inner.push(match ? match[1] : lines[i]);
809
- i++;
810
- }
811
- blocks.push({
812
- type: "quote",
813
- children: parseBlocks(inner)
814
- });
815
- continue;
816
- }
817
- if (UL_RE.test(line) || OL_RE.test(line)) {
818
- const { block, next } = parseList(lines, i);
819
- blocks.push(block);
820
- i = next;
821
- continue;
822
- }
823
- if (line.includes("|") && lines[i + 1] !== void 0 && TABLE_DELIM_RE.test(lines[i + 1])) {
824
- const head = splitRow(line).map(parseInline);
825
- const align = parseAlign(lines[i + 1]);
826
- const rows = [];
827
- i += 2;
828
- while (i < lines.length && lines[i].includes("|") && lines[i].trim() !== "") {
829
- rows.push(splitRow(lines[i]).map(parseInline));
830
- i++;
831
- }
832
- blocks.push({
833
- type: "table",
834
- head,
835
- rows,
836
- align
837
- });
838
- continue;
839
- }
840
- const paragraph = [];
841
- while (i < lines.length && lines[i].trim() !== "") {
842
- const next = lines[i + 1];
843
- if (next !== void 0 && SETEXT_RE.test(next)) {
844
- paragraph.push(lines[i]);
845
- i += 2;
846
- blocks.push({
847
- type: "heading",
848
- level: next.trim().startsWith("=") ? 1 : 2,
849
- children: parseInline(paragraph.join(" "))
850
- });
851
- paragraph.length = 0;
852
- break;
853
- }
854
- if (paragraph.length > 0 && isBlockStart(lines[i])) break;
855
- paragraph.push(lines[i]);
856
- i++;
857
- }
858
- if (paragraph.length > 0) {
859
- const text = paragraph.join("\n");
860
- const figure = asStandaloneImage(text);
861
- blocks.push(figure ?? {
862
- type: "paragraph",
863
- children: parseInline(text)
864
- });
865
- }
866
- }
867
- return blocks;
868
- }
869
- /** An image alone in its paragraph is a figure, not a run of inline content. */
870
- function asStandaloneImage(text) {
871
- const match = text.trim().match(/^!\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)$/);
872
- if (!match) return null;
873
- return {
874
- type: "figure",
875
- alt: match[1],
876
- src: match[2]
877
- };
878
- }
879
- function parseList(lines, start) {
880
- const first = lines[start];
881
- const ordered = OL_RE.test(first);
882
- const startNumber = ordered ? Number(first.match(OL_RE)?.[2] ?? 1) : 1;
883
- const baseIndent = indentOf(first);
884
- const items = [];
885
- let i = start;
886
- let current = null;
887
- const flush = () => {
888
- if (current) items.push(parseBlocks(current));
889
- current = null;
890
- };
891
- while (i < lines.length) {
892
- const line = lines[i];
893
- if (line.trim() === "") {
894
- const next = lines[i + 1];
895
- if (next === void 0 || next.trim() !== "" && indentOf(next) <= baseIndent && !isItem(next)) break;
896
- current?.push("");
897
- i++;
898
- continue;
899
- }
900
- const match = line.match(ordered ? OL_RE : UL_RE) ?? line.match(ordered ? UL_RE : OL_RE);
901
- if (match && indentOf(line) <= baseIndent) {
902
- flush();
903
- current = [match[3]];
904
- i++;
905
- continue;
906
- }
907
- if (indentOf(line) > baseIndent && current) {
908
- current.push(line.slice(Math.min(indentOf(line), baseIndent + 2)));
909
- i++;
910
- continue;
911
- }
912
- break;
913
- }
914
- flush();
915
- return {
916
- block: {
917
- type: "list",
918
- ordered,
919
- start: startNumber,
920
- items
921
- },
922
- next: i
923
- };
924
- function isItem(line) {
925
- return UL_RE.test(line) || OL_RE.test(line);
926
- }
927
- }
928
- const INLINE_RE = /(!\[[^\]]*\]\([^)\s]+(?:\s+"[^"]*")?\))|(\[[^\]]*\]\([^)\s]*(?:\s+"[^"]*")?\))|(`+)([^`]*?)\3|(\*\*|__)(?=\S)([\s\S]*?\S)\5|(\*|_)(?=\S)([\s\S]*?\S)\7|(<[^>\s]+@[^>\s]+>)|(https?:\/\/[^\s<>"')\]]+)/;
929
- function parseInline(source) {
930
- const out = [];
931
- let rest = maskEscapes(source);
932
- const pushText = (value) => {
933
- if (value === "") return;
934
- value.split(/(?: {2}|\\)\n|\n/).forEach((part, index) => {
935
- if (index > 0) out.push({ type: "break" });
936
- const text = unmask(part);
937
- if (text !== "") out.push({
938
- type: "text",
939
- value: text
940
- });
941
- });
942
- };
943
- while (rest.length > 0) {
944
- const match = rest.match(INLINE_RE);
945
- if (!match || match.index === void 0) break;
946
- pushText(rest.slice(0, match.index));
947
- const token = match[0];
948
- if (match[1]) {
949
- const image = token.match(/^!\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)$/);
950
- if (image) out.push({
951
- type: "image",
952
- alt: unmask(image[1]),
953
- src: unmask(image[2])
954
- });
955
- } else if (match[2]) {
956
- const link = token.match(/^\[([^\]]*)\]\(([^)\s]*)(?:\s+"[^"]*")?\)$/);
957
- if (link) out.push({
958
- type: "link",
959
- href: unmask(link[2]),
960
- children: parseInline(link[1])
961
- });
962
- } else if (match[3]) out.push({
963
- type: "code",
964
- value: unmask(match[4].trim())
965
- });
966
- else if (match[5]) out.push({
967
- type: "strong",
968
- children: parseInline(match[6])
969
- });
970
- else if (match[7]) out.push({
971
- type: "em",
972
- children: parseInline(match[8])
973
- });
974
- else if (match[9]) {
975
- const address = token.slice(1, -1);
976
- out.push({
977
- type: "link",
978
- href: `mailto:${address}`,
979
- children: [{
980
- type: "text",
981
- value: address
982
- }]
983
- });
984
- } else if (match[10]) {
985
- const url = unmask(token);
986
- out.push({
987
- type: "link",
988
- href: url,
989
- children: [{
990
- type: "text",
991
- value: url
992
- }]
993
- });
994
- }
995
- rest = rest.slice(match.index + token.length);
996
- }
997
- pushText(rest);
998
- return out;
999
- }
1000
- const ESCAPE_RE = /\\([\\`*_{}[\]()#+\-.!|>~])/g;
1001
- const MASK_RE = /\u0000(\d+)\u0000/g;
1002
- /**
1003
- * The inline scanner is a regex over delimiters, which cannot see a preceding
1004
- * backslash. Escaped characters are swapped for a sentinel before scanning and
1005
- * restored on the way out, so `\*not emphasis\*` survives as literal text.
1006
- */
1007
- function maskEscapes(value) {
1008
- return value.replace(ESCAPE_RE, (_, char) => `\u0000${char.charCodeAt(0)}\u0000`);
1009
- }
1010
- function unmask(value) {
1011
- return value.replace(MASK_RE, (_, code) => String.fromCharCode(Number(code)));
1012
- }
1013
- /** Flattens inline content to plain text — for titles, alt text, and outline labels. */
1014
- function inlineText(nodes) {
1015
- return nodes.map((node) => {
1016
- switch (node.type) {
1017
- case "text":
1018
- case "code": return node.value;
1019
- case "strong":
1020
- case "em":
1021
- case "link": return inlineText(node.children);
1022
- case "image": return node.alt;
1023
- case "break": return " ";
1024
- default: return "";
1025
- }
1026
- }).join("").replace(/\s+/g, " ").trim();
1027
- }
1028
- //#endregion
1029
- //#region src/import/to-tsx.ts
1030
- /** JSX text is written literally; only these characters have to be escaped. */
1031
- function jsxText(text) {
1032
- return text.replace(/[{}<>]/g, (char) => `{'${char}'}`);
1033
- }
1034
- function jsString(value) {
1035
- return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, "\\n")}'`;
1036
- }
1037
- function attr(value) {
1038
- return `"${value.replace(/"/g, "&quot;")}"`;
1039
- }
1040
- function collectImageSources(blocks) {
1041
- const out = [];
1042
- const walkInline = (nodes) => {
1043
- for (const node of nodes) if (node.type === "image") out.push(node.src);
1044
- else if (node.type === "strong" || node.type === "em" || node.type === "link") walkInline(node.children);
1045
- };
1046
- const walk = (list) => {
1047
- for (const block of list) switch (block.type) {
1048
- case "figure":
1049
- out.push(block.src);
1050
- break;
1051
- case "heading":
1052
- case "paragraph":
1053
- walkInline(block.children);
1054
- break;
1055
- case "quote":
1056
- walk(block.children);
1057
- break;
1058
- case "list":
1059
- for (const item of block.items) walk(item);
1060
- break;
1061
- case "table":
1062
- for (const cell of block.head) walkInline(cell);
1063
- for (const row of block.rows) for (const cell of row) walkInline(cell);
1064
- }
1065
- };
1066
- walk(blocks);
1067
- return out;
1068
- }
1069
- function imageSrc(src, images) {
1070
- const known = images?.get(src);
1071
- return known ? `{${known.ident}}` : attr(src);
1072
- }
1073
- function renderInline(nodes, images) {
1074
- return nodes.map((node) => {
1075
- switch (node.type) {
1076
- case "text": return jsxText(node.value);
1077
- case "strong": return `<strong>${renderInline(node.children, images)}</strong>`;
1078
- case "em": return `<em>${renderInline(node.children, images)}</em>`;
1079
- case "code": return `<code style={codeInline}>${jsxText(node.value)}</code>`;
1080
- case "link": return `<a href=${attr(node.href)} style={link}>${renderInline(node.children, images)}</a>`;
1081
- case "image": return `<img src=${imageSrc(node.src, images)} alt=${attr(node.alt)} style={inlineImg} />`;
1082
- case "break": return "<br />";
1083
- default: return "";
1084
- }
1085
- }).join("");
1086
- }
1087
- const HEADING_STYLE = {
1088
- 1: "h1",
1089
- 2: "h2",
1090
- 3: "h3",
1091
- 4: "h4"
1092
- };
1093
- function alignStyle(align) {
1094
- return align && align !== "left" ? ` align={${jsString(align)}}` : "";
1095
- }
1096
- function renderBlock(block, images, indent) {
1097
- const pad = indent;
1098
- switch (block.type) {
1099
- case "heading": {
1100
- const level = Math.min(block.level, 4);
1101
- const tag = level >= 4 ? "h4" : `h${level}`;
1102
- return `${pad}<${tag} style={${HEADING_STYLE[level] ?? "h3"}}>${renderInline(block.children, images)}</${tag}>`;
1103
- }
1104
- case "paragraph": return `${pad}<p style={p}>${renderInline(block.children, images)}</p>`;
1105
- case "hr": return `${pad}<hr style={rule} />`;
1106
- case "code": return `${pad}<pre style={pre}>{${jsString(block.value)}}</pre>`;
1107
- case "quote": return [
1108
- `${pad}<blockquote style={quote}>`,
1109
- ...block.children.map((child) => renderBlock(child, images, `${pad} `)),
1110
- `${pad}</blockquote>`
1111
- ].join("\n");
1112
- case "figure": {
1113
- const caption = block.alt ? `\n${pad} <figcaption style={caption}>${jsxText(block.alt)}</figcaption>` : "";
1114
- return [
1115
- `${pad}<figure style={figure}>`,
1116
- `${pad} <img src=${imageSrc(block.src, images)} alt=${attr(block.alt)} style={img} />${caption}`,
1117
- `${pad}</figure>`
1118
- ].join("\n");
1119
- }
1120
- case "list": {
1121
- const tag = block.ordered ? "ol" : "ul";
1122
- const startAttr = block.ordered && block.start !== 1 ? ` start={${block.start}}` : "";
1123
- const items = block.items.map((item) => {
1124
- const inner = item.map((child, index) => child.type === "paragraph" && index === 0 ? `${renderInline(child.children, images)}` : `\n${renderBlock(child, images, `${pad} `)}`).join("");
1125
- return `${pad} <li style={li}>${inner.startsWith("\n") ? `${inner}\n${pad} ` : inner}</li>`;
1126
- });
1127
- return [
1128
- `${pad}<${tag} style={${tag}}${startAttr}>`,
1129
- ...items,
1130
- `${pad}</${tag}>`
1131
- ].join("\n");
1132
- }
1133
- case "table": {
1134
- const head = block.head.map((cell, i) => `${pad} <Th${alignStyle(block.align[i] ?? null)}>${renderInline(cell, images)}</Th>`).join("\n");
1135
- const rows = block.rows.map((row) => [
1136
- `${pad} <tr>`,
1137
- ...row.map((cell, i) => `${pad} <Td${alignStyle(block.align[i] ?? null)}>${renderInline(cell, images)}</Td>`),
1138
- `${pad} </tr>`
1139
- ].join("\n")).join("\n");
1140
- return [
1141
- `${pad}<table style={table}>`,
1142
- `${pad} <thead>`,
1143
- `${pad} <tr>`,
1144
- head,
1145
- `${pad} </tr>`,
1146
- `${pad} </thead>`,
1147
- `${pad} <tbody>`,
1148
- rows,
1149
- `${pad} </tbody>`,
1150
- `${pad}</table>`
1151
- ].join("\n");
1152
- }
1153
- }
1154
- }
1155
- function titleFrom(parsed, opts) {
1156
- if (opts.title) return opts.title;
1157
- if (parsed.frontmatter.title) return parsed.frontmatter.title;
1158
- const heading = parsed.blocks.find((block) => block.type === "heading" && block.level === 1);
1159
- if (heading && heading.type === "heading") return inlineText(heading.children);
1160
- return opts.docId.replace(/-/g, " ").replace(/^\w/, (c) => c.toUpperCase());
1161
- }
1162
- const STYLES = `const page = {
1163
- width: '100%',
1164
- height: '100%',
1165
- boxSizing: 'border-box' as const,
1166
- padding: 'var(--od-margin)',
1167
- background: 'var(--od-bg)',
1168
- color: 'var(--od-text)',
1169
- fontFamily: 'var(--od-font-body)',
1170
- fontSize: 'var(--od-size-body)',
1171
- lineHeight: 'var(--od-leading)',
1172
- position: 'relative' as const,
1173
- };
1174
-
1175
- const h1 = {
1176
- fontFamily: 'var(--od-font-heading)',
1177
- fontSize: 'var(--od-size-h1)',
1178
- lineHeight: 1.2,
1179
- fontWeight: 650,
1180
- margin: '0 0 18px',
1181
- };
1182
-
1183
- const h2 = { ...h1, fontSize: 'var(--od-size-h2)', margin: '26px 0 12px' };
1184
- const h3 = { ...h1, fontSize: 'var(--od-size-h3)', fontWeight: 600, margin: '20px 0 8px' };
1185
- const h4 = { ...h3, fontSize: 'var(--od-size-body)', margin: '16px 0 6px' };
1186
- const p = { margin: '0 0 12px' };
1187
- // The viewer's CSS reset strips list markers, so both are set back explicitly.
1188
- const ul = { margin: '0 0 12px', paddingLeft: 22, listStyle: 'disc outside' };
1189
- const ol = { ...ul, listStyle: 'decimal outside' };
1190
- const li = { margin: '0 0 5px' };
1191
- const link = { color: 'var(--od-accent)', textDecoration: 'none' };
1192
- const rule = { border: 0, borderTop: '1px solid var(--od-rule)', margin: '20px 0' };
1193
-
1194
- const codeInline = {
1195
- fontFamily: 'var(--od-font-mono)',
1196
- fontSize: '0.92em',
1197
- background: 'var(--od-rule)',
1198
- borderRadius: 3,
1199
- padding: '1px 4px',
1200
- };
1201
-
1202
- const pre = {
1203
- fontFamily: 'var(--od-font-mono)',
1204
- fontSize: 11,
1205
- lineHeight: 1.5,
1206
- background: 'var(--od-rule)',
1207
- borderRadius: 'var(--od-radius)',
1208
- padding: '10px 12px',
1209
- margin: '0 0 14px',
1210
- whiteSpace: 'pre-wrap' as const,
1211
- overflowWrap: 'anywhere' as const,
1212
- };
1213
-
1214
- const quote = {
1215
- margin: '0 0 14px',
1216
- padding: '2px 0 2px 14px',
1217
- borderLeft: '2px solid var(--od-accent)',
1218
- color: 'var(--od-muted)',
1219
- };
1220
-
1221
- const table = {
1222
- width: '100%',
1223
- borderCollapse: 'collapse' as const,
1224
- tableLayout: 'fixed' as const,
1225
- margin: '0 0 16px',
1226
- };
1227
-
1228
- const figure = { margin: '0 0 16px' };
1229
- const img = { width: '100%', display: 'block' as const };
1230
- const inlineImg = { maxWidth: '100%', verticalAlign: 'middle' as const };
1231
- const caption = { fontSize: 'var(--od-size-caption)', color: 'var(--od-muted)', margin: '6px 0 0' };
1232
-
1233
- const Th = ({ children, align = 'left' }: { children?: ReactNode; align?: 'left' | 'center' | 'right' }) => (
1234
- <th
1235
- style={{
1236
- textAlign: align,
1237
- fontFamily: 'var(--od-font-heading)',
1238
- fontSize: 11,
1239
- fontWeight: 600,
1240
- letterSpacing: '0.04em',
1241
- textTransform: 'uppercase',
1242
- color: 'var(--od-muted)',
1243
- borderBottom: '1px solid var(--od-rule)',
1244
- padding: '0 8px 6px',
1245
- }}
1246
- >
1247
- {children}
1248
- </th>
1249
- );
1250
-
1251
- const Td = ({ children, align = 'left' }: { children?: ReactNode; align?: 'left' | 'center' | 'right' }) => (
1252
- <td
1253
- style={{
1254
- textAlign: align,
1255
- fontSize: 12,
1256
- padding: '7px 8px',
1257
- borderBottom: '1px solid var(--od-rule)',
1258
- fontVariantNumeric: align === 'right' ? 'tabular-nums' : undefined,
1259
- }}
1260
- >
1261
- {children}
1262
- </td>
1263
- );
1264
-
1265
- const Footer = () => {
1266
- const n = useDocPageNumber();
1267
- const total = useDocPageCount();
1268
- return (
1269
- <div
1270
- style={{
1271
- position: 'absolute',
1272
- left: 'var(--od-margin)',
1273
- right: 'var(--od-margin)',
1274
- bottom: 40,
1275
- display: 'flex',
1276
- justifyContent: 'space-between',
1277
- fontSize: 'var(--od-size-caption)',
1278
- color: 'var(--od-muted)',
1279
- }}
1280
- >
1281
- <span>{DOC_TITLE}</span>
1282
- <span style={{ fontVariantNumeric: 'tabular-nums' }}>
1283
- {n} / {total}
1284
- </span>
1285
- </div>
1286
- );
1287
- };`;
1288
- const DESIGN = `export const design: DesignSystem = {
1289
- palette: {
1290
- bg: '#ffffff',
1291
- text: '#16181d',
1292
- muted: '#6b7280',
1293
- accent: '#2563eb',
1294
- rule: '#e5e7eb',
1295
- },
1296
- fonts: {
1297
- heading: '-apple-system, BlinkMacSystemFont, "Inter", system-ui, sans-serif',
1298
- body: '-apple-system, BlinkMacSystemFont, "Inter", system-ui, sans-serif',
1299
- mono: 'ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace',
1300
- },
1301
- typeScale: { title: 44, h1: 28, h2: 20, h3: 16, body: 14, caption: 10 },
1302
- margin: 76,
1303
- leading: 1.55,
1304
- radius: 6,
1305
- };`;
1306
- /**
1307
- * Turns parsed markdown into a document module. The output is ordinary authored
1308
- * TSX — inline styles, real heading tags, plain JSX text — so the outline, the
1309
- * inspector, and the design panel all work on an imported document exactly as
1310
- * they do on a hand-written one.
1311
- */
1312
- function generateDocumentSource(parsed, opts) {
1313
- const title = titleFrom(parsed, opts);
1314
- const subtitle = opts.subtitle ?? parsed.frontmatter.subtitle;
1315
- const author = opts.author ?? parsed.frontmatter.author;
1316
- const theme = opts.theme ?? parsed.frontmatter.theme;
1317
- const pageSize = opts.pageSize ?? parsed.frontmatter.pageSize;
1318
- const orientation = opts.orientation ?? parsed.frontmatter.orientation;
1319
- const lang = opts.lang ?? parsed.frontmatter.lang;
1320
- const cover = opts.cover !== false;
1321
- let blocks = parsed.blocks;
1322
- const first = blocks[0];
1323
- if (cover && first?.type === "heading" && first.level === 1 && inlineText(first.children) === title) blocks = blocks.slice(1);
1324
- const images = opts.images;
1325
- const imports = images ? [...images.values()] : [];
1326
- const head = [
1327
- `import type { ReactNode } from 'react';`,
1328
- `import {\n${[
1329
- "type DesignSystem",
1330
- "type DocEntry",
1331
- "type DocMeta",
1332
- ...cover || opts.contents ? ["type DocPage"] : [],
1333
- ...opts.contents ? ["TableOfContents"] : [],
1334
- "flow",
1335
- "useDocPageCount",
1336
- "useDocPageNumber"
1337
- ].map((name) => ` ${name},`).join("\n")}\n} from '@open-document/core';`,
1338
- ...imports.map((image) => `import ${image.ident} from './assets/${image.filename}';`)
1339
- ].join("\n");
1340
- const styles = STYLES.replace("{DOC_TITLE}", jsxText(title));
1341
- const coverPage = cover ? `const Cover: DocPage = () => (
1342
- <div style={{ ...page, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end' }}>
1343
- ${subtitle ? ` <p style={{ fontSize: 12, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--od-accent)', margin: 0 }}>
1344
- ${jsxText(subtitle)}
1345
- </p>\n` : ""} <h1 style={{ ...h1, fontSize: 'var(--od-size-title)', margin: '16px 0 12px' }} data-od-outline="skip">
1346
- ${jsxText(title)}
1347
- </h1>
1348
- ${author ? ` <p style={{ color: 'var(--od-muted)', margin: 0 }}>${jsxText(author)}</p>\n` : ""} </div>
1349
- );` : "";
1350
- const contentsPage = opts.contents ? `const Contents: DocPage = () => (
1351
- <div style={page}>
1352
- <h1 style={h1} data-od-outline="skip">
1353
- Contents
1354
- </h1>
1355
- <TableOfContents maxLevel={2} />
1356
- </div>
1357
- );` : "";
1358
- const body = `const Body = flow(
1359
- <>
1360
- ${blocks.map((block) => renderBlock(block, images, " ")).join("\n")}
1361
- </>,
1362
- { footer: Footer },
1363
- );`;
1364
- const metaFields = [
1365
- ` title: ${jsString(title)},`,
1366
- ...subtitle ? [` subtitle: ${jsString(subtitle)},`] : [],
1367
- ...author ? [` author: ${jsString(author)},`] : [],
1368
- ...pageSize ? [` pageSize: ${jsString(pageSize)},`] : [],
1369
- ...orientation ? [` orientation: ${jsString(orientation)},`] : [],
1370
- ...theme ? [` theme: ${jsString(theme)},`] : [],
1371
- ...lang ? [` lang: ${jsString(lang)},`] : [],
1372
- ` createdAt: ${jsString(opts.createdAt)},`
1373
- ];
1374
- const entries = [
1375
- ...cover ? ["Cover"] : [],
1376
- ...opts.contents ? ["Contents"] : [],
1377
- "Body"
1378
- ];
1379
- return {
1380
- source: [
1381
- head,
1382
- "",
1383
- DESIGN,
1384
- "",
1385
- styles,
1386
- "",
1387
- ...coverPage ? [coverPage, ""] : [],
1388
- ...contentsPage ? [contentsPage, ""] : [],
1389
- body,
1390
- "",
1391
- `export const meta: DocMeta = {\n${metaFields.join("\n")}\n};`,
1392
- `export default [${entries.join(", ")}] satisfies DocEntry[];`,
1393
- ""
1394
- ].join("\n"),
1395
- title,
1396
- blockCount: blocks.length
1397
- };
1398
- }
1399
- //#endregion
1400
- //#region src/ops/import.ts
1401
- const REMOTE_RE = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
1402
- function slugify(value, fallback = "document") {
1403
- const slug = value.normalize("NFKD").toLowerCase().replace(/['"]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60);
1404
- return DOC_ID_RE.test(slug) ? slug : fallback;
1405
- }
1406
- function uniqueId(base, taken) {
1407
- if (!taken.has(base)) return base;
1408
- for (let n = 2; n < 1e3; n++) {
1409
- const candidate = `${base}-${n}`;
1410
- if (!taken.has(candidate)) return candidate;
1411
- }
1412
- throw new OpsError(409, `could not find a free id for ${base}`);
1413
- }
1414
- function identFor(index) {
1415
- return `figure${index + 1}`;
1416
- }
1417
- /**
1418
- * Reads markdown and writes a real open-doc document: `flow()` body, inline
1419
- * styles, a cover, and any local images copied into the document's own assets
1420
- * folder. Nothing about the result is special-cased — it is the same shape an
1421
- * agent would have written by hand, and every editing surface works on it.
1422
- */
1423
- async function importMarkdown(ctx, opts) {
1424
- const sourceFile = opts.file ? path.resolve(ctx.userCwd, opts.file) : null;
1425
- if (sourceFile && !sourceFile.startsWith(ctx.userCwd + path.sep)) throw new OpsError(400, `file must sit inside the workspace: ${opts.file}`);
1426
- let markdown = opts.markdown;
1427
- if (markdown === void 0) {
1428
- if (!sourceFile) throw new OpsError(400, "pass either `markdown` or `file`");
1429
- try {
1430
- markdown = await fs.readFile(sourceFile, "utf8");
1431
- } catch {
1432
- throw new OpsError(404, `file not found: ${opts.file}`);
1433
- }
1434
- }
1435
- if (markdown.trim() === "") throw new OpsError(422, "the markdown is empty");
1436
- const parsed = parseMarkdown(markdown);
1437
- const language = opts.lang ?? (parsed.frontmatter.lang ? void 0 : detectLang(markdown));
1438
- const pageSize = opts.pageSize ?? parsed.frontmatter.pageSize;
1439
- if (pageSize !== void 0 && !isPageSizeName(pageSize)) throw new OpsError(422, `unsupported pageSize \`${pageSize}\` — use ${PAGE_SIZE_NAMES.join(", ")}`);
1440
- const orientation = opts.orientation ?? parsed.frontmatter.orientation;
1441
- if (orientation !== void 0 && !isOrientation(orientation)) throw new OpsError(422, `unsupported orientation \`${orientation}\` — use ${ORIENTATIONS.join(", ")}`);
1442
- const fallbackName = sourceFile ? path.basename(sourceFile).replace(/\.mdx?$/i, "") : "document";
1443
- const requestedId = opts.docId ?? slugify(opts.title ?? parsed.frontmatter.title ?? fallbackName);
1444
- if (opts.docId && !DOC_ID_RE.test(opts.docId)) throw new OpsError(400, `invalid document id: ${opts.docId}`);
1445
- const docId = opts.docId ?? uniqueId(requestedId, new Set(await listDocIds(ctx)));
1446
- const baseDir = sourceFile ? path.dirname(sourceFile) : ctx.userCwd;
1447
- const images = /* @__PURE__ */ new Map();
1448
- const missing = [];
1449
- const staged = [];
1450
- const usedNames = /* @__PURE__ */ new Set();
1451
- for (const src of new Set(collectImageSources(parsed.blocks))) {
1452
- if (REMOTE_RE.test(src)) continue;
1453
- const from = path.resolve(baseDir, src.split(/[?#]/)[0]);
1454
- if (!from.startsWith(ctx.userCwd + path.sep) || !existsSync(from)) {
1455
- missing.push(src);
1456
- continue;
1457
- }
1458
- const safe = validateAssetName(path.basename(from));
1459
- if (!safe) {
1460
- missing.push(src);
1461
- continue;
1462
- }
1463
- const filename = usedNames.has(safe) ? `${images.size + 1}-${safe}` : safe;
1464
- usedNames.add(filename);
1465
- images.set(src, {
1466
- source: src,
1467
- ident: identFor(images.size),
1468
- filename
1469
- });
1470
- staged.push({
1471
- from,
1472
- filename
1473
- });
1474
- }
1475
- const generated = generateDocumentSource(parsed, {
1476
- docId,
1477
- ...opts.title !== void 0 ? { title: opts.title } : {},
1478
- ...opts.subtitle !== void 0 ? { subtitle: opts.subtitle } : {},
1479
- ...opts.author !== void 0 ? { author: opts.author } : {},
1480
- ...opts.theme !== void 0 ? { theme: opts.theme } : {},
1481
- ...opts.pageSize !== void 0 ? { pageSize: opts.pageSize } : {},
1482
- ...opts.orientation !== void 0 ? { orientation: opts.orientation } : {},
1483
- ...language ? { lang: language } : {},
1484
- ...opts.cover !== void 0 ? { cover: opts.cover } : {},
1485
- ...opts.contents !== void 0 ? { contents: opts.contents } : {},
1486
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1487
- images
1488
- });
1489
- const created = await createDocument(ctx, docId, generated.source);
1490
- if (staged.length > 0) {
1491
- const assetsDir = path.join(ctx.docsRoot, docId, "assets");
1492
- await fs.mkdir(assetsDir, { recursive: true });
1493
- for (const { from, filename } of staged) await fs.copyFile(from, path.join(assetsDir, filename));
1494
- }
1495
- return {
1496
- id: created.id,
1497
- entry: created.entry,
1498
- title: generated.title,
1499
- blocks: generated.blockCount,
1500
- assets: staged.map((asset) => asset.filename),
1501
- missingAssets: missing
1502
- };
1503
- }
1504
- //#endregion
1505
- //#region src/ops/layout.ts
1506
- /**
1507
- * Chromium and a Vite server are expensive to start, and an agent checking its
1508
- * work calls these back to back. One session is kept warm and closed once
1509
- * nobody has asked for a while.
1510
- */
1511
- const IDLE_MS = 12e4;
1512
- let shared = null;
1513
- let pending = null;
1514
- let idleTimer = null;
1515
- let leases = 0;
1516
- function armIdleClose() {
1517
- if (idleTimer) clearTimeout(idleTimer);
1518
- idleTimer = setTimeout(() => {
1519
- if (leases > 0) return;
1520
- const current = shared;
1521
- shared = null;
1522
- idleTimer = null;
1523
- current?.session.close().catch(() => {});
1524
- }, IDLE_MS);
1525
- idleTimer.unref?.();
1526
- }
1527
- async function acquire(ctx) {
1528
- if (shared && shared.origin === ctx.serverOrigin) return shared.session;
1529
- if (!pending) {
1530
- const origin = ctx.serverOrigin;
1531
- pending = createRenderSession({
1532
- userCwd: ctx.userCwd,
1533
- origin,
1534
- deviceScaleFactor: 2
1535
- }).then((session) => {
1536
- shared = {
1537
- session,
1538
- origin
1539
- };
1540
- return session;
1541
- }).finally(() => {
1542
- pending = null;
1543
- });
1544
- }
1545
- return pending;
1546
- }
1547
- async function withDoc(ctx, docId, fn) {
1548
- if (!resolveEntry(ctx, docId)) throw new OpsError(404, `document not found: ${docId}`);
1549
- let session;
1550
- try {
1551
- session = await acquire(ctx);
1552
- } catch (err) {
1553
- if (err instanceof RenderUnavailableError) throw new OpsError(501, err.message);
1554
- throw new OpsError(500, err.message);
1555
- }
1556
- leases++;
1557
- let renderer = null;
1558
- try {
1559
- renderer = await session.open(docId);
1560
- return await fn(renderer);
1561
- } catch (err) {
1562
- if (err instanceof OpsError) throw err;
1563
- throw new OpsError(422, err.message);
1564
- } finally {
1565
- await renderer?.close().catch(() => {});
1566
- leases--;
1567
- armIdleClose();
1568
- }
1569
- }
1570
- /** Closes the warm browser. Call before the process exits so nothing lingers. */
1571
- async function closeRenderSession() {
1572
- if (idleTimer) clearTimeout(idleTimer);
1573
- idleTimer = null;
1574
- const current = shared;
1575
- shared = null;
1576
- await current?.session.close().catch(() => {});
1577
- }
1578
- /**
1579
- * Renders the document headlessly at true page size and reports what is wrong
1580
- * with the layout — the part of a document an agent writing React cannot see.
1581
- */
1582
- async function checkLayout(ctx, docId) {
1583
- return withDoc(ctx, docId, async (renderer) => {
1584
- const report = await renderer.diagnose();
1585
- return {
1586
- docId: report.docId || docId,
1587
- title: report.title,
1588
- pageCount: report.pageCount,
1589
- errors: report.findings.filter((f) => f.severity === "error").length,
1590
- warnings: report.findings.filter((f) => f.severity === "warn").length,
1591
- findings: report.findings
1592
- };
1593
- });
1594
- }
1595
- async function renderDocPage(ctx, docId, page) {
1596
- return withDoc(ctx, docId, async (renderer) => {
1597
- const bytes = await renderer.screenshot(page);
1598
- return {
1599
- docId,
1600
- page,
1601
- pageCount: renderer.status.pageCount,
1602
- mimeType: "image/png",
1603
- base64: Buffer.from(bytes).toString("base64")
1604
- };
1605
- });
1606
- }
1607
- function resolveOutDir(ctx, outDir) {
1608
- const resolved = path.resolve(ctx.userCwd, outDir);
1609
- if (resolved !== ctx.userCwd && !resolved.startsWith(ctx.userCwd + path.sep)) throw new OpsError(400, `outDir must stay inside the workspace: ${outDir}`);
1610
- return resolved;
1611
- }
1612
- /**
1613
- * Writes the document's files. With `each`, a document that exports
1614
- * `records` is laid out and written once per row — `name` (or
1615
- * `meta.recordName`) names each row's files.
1616
- */
1617
- async function exportDocument(ctx, docId, opts = {}) {
1618
- const format = opts.format ?? "pdf";
1619
- const dir = resolveOutDir(ctx, opts.outDir ?? "out");
1620
- return withDoc(ctx, docId, async (renderer) => {
1621
- await fs.mkdir(dir, { recursive: true });
1622
- const written = [];
1623
- const taken = /* @__PURE__ */ new Set();
1624
- const write = async (name, bytes) => {
1625
- const file = path.join(dir, name);
1626
- await fs.writeFile(file, bytes);
1627
- written.push(path.relative(ctx.userCwd, file));
1628
- };
1629
- const free = (base) => {
1630
- let name = base;
1631
- for (let n = 2; taken.has(name); n++) name = `${base}-${n}`;
1632
- taken.add(name);
1633
- return name;
1634
- };
1635
- const writeCopy = async (base) => {
1636
- if (format === "pdf") await write(`${base}.pdf`, await renderer.pdf());
1637
- else if (format === "html" || format === "docx") {
1638
- const bundle = format === "html" ? await renderer.html() : await renderer.docx();
1639
- if (!bundle) throw new OpsError(422, `document has no pages: ${docId}`);
1640
- await write(`${base}${path.extname(bundle.filename)}`, Buffer.from(bundle.base64, "base64"));
1641
- } else {
1642
- const width = String(renderer.status.pageCount).length;
1643
- for (let page = 1; page <= renderer.status.pageCount; page++) await write(`${base}-${String(page).padStart(width, "0")}.png`, await renderer.screenshot(page));
1644
- }
1645
- };
1646
- if (!opts.each) {
1647
- await writeCopy(docId);
1648
- return {
1649
- docId,
1650
- format,
1651
- pageCount: renderer.status.pageCount,
1652
- files: written
1653
- };
1654
- }
1655
- const records = renderer.status.records;
1656
- if (records === 0) throw new OpsError(422, `${docId} has no records — export \`records\` (rows from a .csv) to write one copy per row`);
1657
- let pageCount = 0;
1658
- for (let index = 0; index < records; index++) {
1659
- const name = await renderer.setRecord(index, opts.name);
1660
- pageCount += renderer.status.pageCount;
1661
- await writeCopy(free(name));
1662
- }
1663
- return {
1664
- docId,
1665
- format,
1666
- pageCount,
1667
- files: written,
1668
- records
1669
- };
1670
- });
1671
- }
1672
- //#endregion
1673
- export { importMarkdown as a, renderDocPage as i, closeRenderSession as n, slugify as o, exportDocument as r, diffDocument as s, checkLayout as t };