@senad-d/drawme 0.1.10 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/drawio.ts CHANGED
@@ -1,256 +1,44 @@
1
- /**
2
- * draw.io desktop CLI wrapper: binary resolution + export. Encodes the tricky
3
- * flag knowledge for focused previews vs final export, the vision width cap,
4
- * `-e` PNG IEND repair, page indexing, and headless-Linux handling so callers never
5
- * hand-build a draw.io command line.
6
- */
7
- import { spawn } from "node:child_process";
8
- import { existsSync, realpathSync } from "node:fs";
9
- import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
10
- import { basename, dirname, extname, join, resolve } from "node:path";
11
- import { platform, tmpdir } from "node:os";
12
- import { repairPng } from "./png";
13
- import { enhanceAnimatedSvg, type AnimatedSvgSummary } from "./animation";
14
- import { DEFAULT_FIT_MARGIN } from "./fitcanvas";
1
+ /** Public draw.io facade and verified export publication boundary. */
2
+ import { createHash } from "node:crypto";
3
+ import {
4
+ type BigIntStats, accessSync, chmodSync, chownSync, constants, existsSync, lstatSync, readlinkSync,
5
+ realpathSync, renameSync, statSync, unlinkSync,
6
+ } from "node:fs";
7
+ import { mkdtemp, readFile, rm } from "node:fs/promises";
8
+ import { basename, dirname, join, sep } from "node:path";
15
9
  import { DOMParser } from "@xmldom/xmldom";
16
- import { type DomEl, childrenByTag, firstByTag } from "./dom";
10
+ import { enhanceAnimatedSvg, type AnimatedSvgSummary } from "./animation";
11
+ import { readDiagramXml, sessionPath, withDiagramFiles } from "./diagram-files";
12
+ import { type DomEl, childrenByTag, firstByTag, graphModel } from "./dom";
13
+ import {
14
+ type ExportFormat, type ExportMode, type ExportOptions, type ExportPlan,
15
+ MAX_FINAL_RASTER_PIXELS, MAX_REVIEW_SIDE, planExport,
16
+ } from "./export-plan";
17
17
  import { collectCellsWithIds, contentBounds } from "./geometry";
18
+ import { inspectPng, repairPng } from "./png";
19
+ import { INDEX_MIN, invokeRenderer, rendererUnavailable, resolveBinary, supportsPageIndex } from "./renderer";
20
+ import { assertStandaloneImages } from "./svg-helpers";
18
21
  import { finishSvgFile } from "./svgexport";
19
22
 
20
- export type ExportFormat = "png" | "svg" | "pdf" | "jpg";
21
- export type ExportMode = "preview" | "final";
22
-
23
- export interface DrawioInfo {
24
- available: boolean;
25
- binary?: string;
26
- version?: string;
27
- major?: number;
28
- /** Mermaid import and the `--layout` pass both need draw.io v30+. */
29
- supportsMermaid?: boolean;
30
- supportsLayout?: boolean;
31
- }
32
-
33
- export interface ExportOptions {
34
- input: string;
35
- format?: ExportFormat;
36
- mode?: ExportMode;
37
- output?: string;
38
- scale?: number;
39
- width?: number;
40
- height?: number;
41
- transparent?: boolean;
42
- border?: number;
43
- pageIndex?: number;
44
- embed?: boolean;
45
- /** Require and verify animation in a final SVG, compiling portable page sequences when present. */
46
- animated?: boolean;
47
- binary?: string;
48
- }
49
-
50
- export interface ExportPlan {
51
- format: ExportFormat;
52
- mode: ExportMode;
53
- embed: boolean;
54
- animated: boolean;
55
- output: string;
56
- /** Export flags ending with `-o <output>`. The input path is appended after these. */
57
- args: string[];
58
- input: string;
59
- /** Flags that must go AFTER the input path on Linux (draw.io argument-parsing quirk). */
60
- linuxExtra: string[];
61
- /** SVG only: outer margin DrawMe adds after export (draw.io's own SVG border is uneven). */
62
- svgMargin: number;
63
- }
64
-
65
- /** Candidate binary names and paths in resolution order. */
66
- const CANDIDATES = [
67
- "drawio", // Homebrew cask, jgraph .deb/.rpm, Arch AUR
68
- "draw.io", // older builds / custom symlinks
69
- "/Applications/draw.io.app/Contents/MacOS/draw.io", // macOS .app bundle
70
- String.raw`C:\Program Files\draw.io\draw.io.exe`, // Windows
71
- String.raw`C:\Program Files (x86)\draw.io\draw.io.exe`,
72
- "/mnt/c/Program Files/draw.io/draw.io.exe", // WSL2
73
- ];
74
-
75
- /**
76
- * Run a command and collect its output. Off Windows the child leads its own process
77
- * group, so a timeout ends the whole tree (xvfb-run, Xvfb, Electron), not only the
78
- * direct child: SIGTERM first so xvfb-run can clean up, SIGKILL after a grace period.
79
- */
80
- export function run(bin: string, args: string[], timeout = 120_000): Promise<{ stdout: string; stderr: string }> {
81
- return new Promise((resolve, reject) => {
82
- const group = platform() !== "win32";
83
- const child = spawn(bin, args, { detached: group, stdio: ["ignore", "pipe", "pipe"] });
84
- let stdout = "";
85
- let stderr = "";
86
- let timedOut = false;
87
- let killTimer: NodeJS.Timeout | undefined;
88
- child.stdout.on("data", (chunk: Buffer) => (stdout += chunk.toString()));
89
- child.stderr.on("data", (chunk: Buffer) => (stderr += chunk.toString()));
90
- const timer = setTimeout(() => {
91
- timedOut = true;
92
- killTree(child.pid, group, "SIGTERM");
93
- killTimer = setTimeout(() => killTree(child.pid, group, "SIGKILL"), 5_000);
94
- }, timeout);
95
- child.on("error", (err) => {
96
- clearTimeout(timer);
97
- reject(Object.assign(err, { stderr }));
98
- });
99
- child.on("close", (code, signal) => {
100
- clearTimeout(timer);
101
- if (timedOut) {
102
- // Reap anything in the group that ignored SIGTERM.
103
- clearTimeout(killTimer);
104
- killTree(child.pid, group, "SIGKILL");
105
- }
106
- if (code === 0 && !timedOut) {
107
- resolve({ stdout, stderr });
108
- return;
109
- }
110
- const exitReason = signal ?? `code ${code}`;
111
- const why = timedOut ? `timed out after ${timeout / 1000}s` : `exited with ${exitReason}`;
112
- reject(Object.assign(new Error(`${bin} ${why}`), { code, signal, stderr }));
113
- });
114
- });
115
- }
116
-
117
- function killTree(pid: number | undefined, group: boolean, signal: NodeJS.Signals): void {
118
- if (pid === undefined) return;
119
- try {
120
- process.kill(group ? -pid : pid, signal);
121
- } catch {
122
- // already gone
123
- }
124
- }
125
-
126
- function parseMajor(version: string): number {
127
- const m = /(\d+)/.exec(version);
128
- return m ? Number.parseInt(m[1], 10) : 0;
129
- }
130
-
131
- /**
132
- * Resolve the draw.io CLI. Tries an explicit `override` first, then the standard
133
- * candidates. Absolute paths are existence-checked before spawning; PATH names are
134
- * probed with `--version` (a short timeout guards the sandbox-hang case).
135
- */
136
- export async function resolveBinary(override?: string): Promise<DrawioInfo> {
137
- const candidates = override ? [override, ...CANDIDATES] : CANDIDATES;
138
- const tried = new Set<string>();
139
- for (const bin of candidates) {
140
- if (tried.has(bin)) continue;
141
- tried.add(bin);
142
- const looksLikePath = bin.includes("/") || bin.includes("\\");
143
- if (looksLikePath && !existsSync(bin)) continue;
144
- try {
145
- const { stdout } = await run(bin, ["--version"], 15_000);
146
- const version = stdout.trim().split(/\r?\n/)[0] ?? "";
147
- if (version) {
148
- const major = parseMajor(version);
149
- return { available: true, binary: bin, version, major, supportsMermaid: major >= 30, supportsLayout: major >= 30 };
150
- }
151
- } catch {
152
- // not this one — try the next candidate
153
- }
154
- }
155
- return { available: false };
156
- }
157
-
158
- /** Derive a default output path next to the input, using the `.drawio.png` convention when embedding. */
159
- export function deriveOutput(input: string, format: ExportFormat, embed: boolean): string {
160
- const dir = dirname(input);
161
- const ext = extname(input);
162
- const base = ext ? basename(input).slice(0, -ext.length) : basename(input);
163
- if (format === "png" && embed) return join(dir, `${base}.drawio.png`);
164
- return join(dir, `${base}.${format}`);
165
- }
166
-
167
- /**
168
- * Build the full export plan (no side effects) so the argument logic is unit-testable.
169
- *
170
- * Export planning rules:
171
- * - preview → never `-e`, width-capped at 2000px (Claude vision rejects >2576px)
172
- * - final → `-e` for png/svg/pdf (jpg can't embed), raster scale 2
173
- * - animated → final SVG only; defaults the format to SVG and verifies motion after export
174
- * - `--width` and `-s` are never combined; an explicit width/height wins
175
- * - `-t` (transparent) is PNG-only; `--page-index` is 1-based
176
- * - the outer margin defaults to the canvas-fit margin in diagram units. draw.io
177
- * applies `-b` unevenly with `-s` (left/top get border × scale) and with SVG
178
- * (the canvas grows by 3 × border), so a scaled raster is sized with `--width`
179
- * from `contentWidth`, and SVG is exported borderless and padded afterwards.
180
- */
181
- export function planExport(
182
- opts: ExportOptions,
183
- plat: string = platform(),
184
- isRoot = false,
185
- contentWidth?: number,
186
- ): ExportPlan {
187
- const animated = opts.animated ?? false;
188
- const format = opts.format ?? (animated ? "svg" : "png");
189
- const mode = opts.mode ?? "final";
190
- if (animated && format !== "svg") throw new Error("animated export requires format='svg'");
191
- if (animated && mode !== "final") throw new Error("animated export requires mode='final'; use a PNG preview for review");
192
- const embed = opts.embed ?? (mode === "final" && format !== "jpg");
193
- const output = opts.output ?? deriveOutput(opts.input, format, embed);
194
- const raster = format === "png" || format === "jpg";
195
-
196
- const margin = opts.border ?? DEFAULT_FIT_MARGIN;
197
- const args: string[] = ["-x", "-f", format];
198
- if (embed) args.push("-e");
199
- const border = planExportSize(opts, mode, raster, contentWidth, margin, args);
200
- // draw.io crops exports to the content, so the border is the image's only outer margin.
201
- args.push("-b", String(format === "svg" ? 0 : border));
202
- if (opts.transparent && format === "png") args.push("-t");
203
- if (opts.pageIndex != null) args.push("--page-index", String(opts.pageIndex));
204
- args.push("-o", output);
205
-
206
- // On Linux these must trail the input filename, or draw.io treats them as the input.
207
- const linuxExtra: string[] = [];
208
- if (plat === "linux") {
209
- linuxExtra.push("--disable-gpu");
210
- if (isRoot) linuxExtra.push("--no-sandbox");
211
- }
212
- return { format, mode, embed, animated, output, args, input: opts.input, linuxExtra, svgMargin: format === "svg" ? margin : 0 };
213
- }
214
-
215
- function planExportSize(
216
- opts: ExportOptions, mode: ExportMode, raster: boolean, contentWidth: number | undefined,
217
- margin: number, args: string[],
218
- ): number {
219
- if (opts.width != null) args.push("--width", String(opts.width));
220
- else if (opts.height != null) args.push("--height", String(opts.height));
221
- else if (raster) {
222
- if (mode === "preview") args.push("--width", "2000");
223
- else {
224
- const scale = opts.scale ?? 2;
225
- if (contentWidth !== undefined && contentWidth > 0 && scale !== 1) {
226
- // With --width the border is in output pixels and applied evenly.
227
- const border = Math.round(margin * scale);
228
- args.push("--width", String(Math.round(contentWidth * scale + 2 * border)));
229
- return border;
230
- }
231
- args.push("-s", String(scale));
232
- }
233
- }
234
- return margin;
235
- }
23
+ export * from "./editable-import";
24
+ export * from "./export-plan";
25
+ export * from "./renderer";
236
26
 
237
27
  export interface ExportResult {
238
28
  output: string;
239
29
  format: ExportFormat;
240
30
  mode: ExportMode;
241
31
  embed: boolean;
242
- /** True only when animated SVG export was explicitly requested and verified. */
32
+ /** True only when native animated SVG export was explicitly requested and verified. */
243
33
  animated: boolean;
244
34
  animation?: AnimatedSvgSummary;
245
35
  binary: string;
246
36
  version?: string;
247
37
  /** True if the truncated `-e` PNG IEND chunk was repaired after export. */
248
38
  repaired: boolean;
249
- /**
250
- * True when this preview replaced an earlier tracked preview for the same
251
- * source — including a re-export over the same output path, where nothing is
252
- * removed from disk. Always false for final exports.
253
- */
39
+ /** Exact verified bytes of an unembedded PNG, whether or not it is a preview. */
40
+ artifactSha256?: string;
41
+ /** True when a preview replaced an earlier tracked preview of the same source. */
254
42
  replacedPreview: boolean;
255
43
  /** Superseded preview artifacts removed after this successful preview or final export. */
256
44
  removedPreviews: string[];
@@ -259,19 +47,22 @@ export interface ExportResult {
259
47
  command: string;
260
48
  }
261
49
 
262
- /** Successful preview outputs still present, grouped by their canonical source path. */
263
- const previewOutputs = new Map<string, Map<string, string>>();
264
- /** Serialize exports per source so concurrent preview calls cannot leave multiple latest artifacts. */
265
- const exportQueues = new Map<string, Promise<void>>();
50
+ export interface PreparedExport {
51
+ readonly publicationDestination: string;
52
+ commit(): ExportResult;
53
+ dispose(): Promise<void>;
54
+ }
266
55
 
267
- function sourceKey(input: string): string {
268
- try {
269
- return realpathSync(input);
270
- } catch {
271
- return resolve(input);
272
- }
56
+ interface TrackedPreview {
57
+ displayPath: string;
58
+ /** Never unlink the target of a user-supplied output symlink. */
59
+ removable: boolean;
60
+ file: BigIntStats;
273
61
  }
274
62
 
63
+ /** Preview ownership snapshots, grouped by canonical source and destination. */
64
+ const previewOutputs = new Map<string, Map<string, TrackedPreview>>();
65
+
275
66
  interface PreviewCleanup {
276
67
  removed: string[];
277
68
  warnings: string[];
@@ -279,358 +70,339 @@ interface PreviewCleanup {
279
70
  replaced: boolean;
280
71
  }
281
72
 
282
- /**
283
- * Keep the newly exported preview and retire every older tracked preview for the
284
- * same source. Cleanup happens only after the replacement exists, so a failed
285
- * export never destroys the last usable review image.
286
- */
287
- async function replaceTrackedPreview(input: string, latestOutput: string): Promise<PreviewCleanup> {
288
- const key = sourceKey(input);
289
- const previous = previewOutputs.get(key) ?? new Map<string, string>();
290
- const latestPath = resolve(latestOutput);
291
- const retained = new Map<string, string>([[latestPath, latestOutput]]);
292
- const removed: string[] = [];
293
- const warnings: string[] = [];
294
-
295
- const cleanup = await deletePreviewFiles(previous, latestPath);
296
- for (const result of cleanup) {
297
- if (result.warning !== undefined) {
298
- retained.set(result.path, result.displayPath);
299
- warnings.push(result.warning);
300
- } else if (result.existed) removed.push(result.displayPath);
301
- }
302
-
303
- previewOutputs.set(key, retained);
304
- return { removed, warnings, replaced: previous.size > 0 };
73
+ function fileAt(path: string): BigIntStats | undefined {
74
+ return lstatSync(path, { bigint: true, throwIfNoEntry: false });
305
75
  }
306
76
 
307
- async function removeTrackedPreviews(input: string, finalOutput: string): Promise<PreviewCleanup> {
308
- const key = sourceKey(input);
309
- const previews = previewOutputs.get(key);
310
- if (!previews) return { removed: [], warnings: [], replaced: false };
311
-
312
- previewOutputs.delete(key);
313
- const finalPath = resolve(finalOutput);
314
- const removed: string[] = [];
315
- const warnings: string[] = [];
316
- const retry = new Map<string, string>();
317
-
318
- const cleanup = await deletePreviewFiles(previews, finalPath);
319
- for (const result of cleanup) {
320
- if (result.warning !== undefined) {
321
- retry.set(result.path, result.displayPath);
322
- warnings.push(result.warning);
323
- } else if (result.existed) removed.push(result.displayPath);
324
- }
325
-
326
- if (retry.size > 0) previewOutputs.set(key, retry);
327
- return { removed, warnings, replaced: false };
77
+ function sameFile(a: BigIntStats, b: BigIntStats): boolean {
78
+ return a.dev === b.dev && a.ino === b.ino;
328
79
  }
329
80
 
330
- interface PreviewDeletion {
331
- path: string;
332
- displayPath: string;
333
- existed: boolean;
334
- warning?: string;
81
+ function stillOwned(current: BigIntStats | undefined, tracked: TrackedPreview): boolean {
82
+ return current?.isFile() === true && sameFile(current, tracked.file) && current.ctimeNs === tracked.file.ctimeNs &&
83
+ current.mtimeNs === tracked.file.mtimeNs && current.size === tracked.file.size;
335
84
  }
336
85
 
337
- /** Independent file deletions run concurrently; receipts retain insertion order. */
338
- async function deletePreviewFiles(previews: Map<string, string>, protectedPath: string): Promise<PreviewDeletion[]> {
339
- return Promise.all(
340
- [...previews].filter(([path]) => path !== protectedPath).map(async ([path, displayPath]) => {
341
- const existed = existsSync(path);
342
- try {
343
- await rm(path, { force: true });
344
- return { path, displayPath, existed };
345
- } catch (error) {
346
- const message = error instanceof Error ? error.message : String(error);
347
- return { path, displayPath, existed, warning: `${displayPath}: ${message}` };
86
+ /** Check and unlink without yielding to another export between those operations. */
87
+ function retirePreviews(key: string, destination: string, latest: TrackedPreview | undefined): PreviewCleanup {
88
+ const removed: string[] = [];
89
+ const warnings: string[] = [];
90
+ const retained = new Map<string, TrackedPreview>();
91
+ let replaced = false;
92
+ if (latest) retained.set(destination, latest);
93
+ for (const [path, preview] of previewOutputs.get(key) ?? []) {
94
+ if (path === destination) continue;
95
+ try {
96
+ const current = fileAt(path);
97
+ if (current && !current.isFile()) {
98
+ warnings.push(`${preview.displayPath}: no longer a regular file; left in place`);
99
+ } else if (stillOwned(current, preview)) {
100
+ replaced = true;
101
+ if (preview.removable) {
102
+ unlinkSync(path);
103
+ removed.push(preview.displayPath);
104
+ }
348
105
  }
349
- }),
350
- );
351
- }
352
-
353
- async function withSourceExportQueue<T>(input: string, action: () => Promise<T>): Promise<T> {
354
- const key = sourceKey(input);
355
- const previous = exportQueues.get(key) ?? Promise.resolve();
356
- let release = (): void => {};
357
- const current = new Promise<void>((resolveCurrent) => {
358
- release = resolveCurrent;
359
- });
360
- const tail = previous.then(() => current);
361
- exportQueues.set(key, tail);
362
-
363
- await previous;
364
- try {
365
- return await action();
366
- } finally {
367
- release();
368
- if (exportQueues.get(key) === tail) exportQueues.delete(key);
106
+ } catch (error) {
107
+ retained.set(path, preview);
108
+ warnings.push(`${preview.displayPath}: ${(error as Error).message}`);
109
+ }
369
110
  }
370
- }
371
-
372
- /** Width of the visible content of a page in diagram units, or undefined when it cannot be measured. */
373
- export async function pageContentWidth(input: string, pageIndex: number): Promise<number | undefined> {
374
- try {
375
- const root = new DOMParser().parseFromString(await readFile(input, "utf8"), "text/xml").documentElement as unknown as DomEl | null;
376
- if (!root) return undefined;
377
- const pages = childrenByTag(root, "diagram");
378
- const page = pages.length > 0 ? pages[pageIndex - 1] : root;
379
- const model = page && (page.tagName === "mxGraphModel" ? page : firstByTag(page, "mxGraphModel"));
380
- if (!model) return undefined;
381
- const { cells, ids } = collectCellsWithIds(firstByTag(model, "root"));
382
- const bounds = contentBounds(cells, ids);
383
- return bounds ? bounds.maxX - bounds.minX : undefined;
384
- } catch {
385
- return undefined;
111
+ if (retained.size > 0) previewOutputs.set(key, retained);
112
+ else previewOutputs.delete(key);
113
+ return { removed, warnings, replaced: latest !== undefined && replaced };
114
+ }
115
+
116
+ function diagramPages(xml: string): DomEl[] {
117
+ const root = new DOMParser({ onError(level) {
118
+ if (level !== "warning") throw new Error("invalid diagram XML");
119
+ } }).parseFromString(xml, "text/xml").documentElement as unknown as DomEl | null;
120
+ if (!root) return [];
121
+ return root.tagName === "mxGraphModel" || root.tagName === "diagram" ? [root] : childrenByTag(root, "diagram");
122
+ }
123
+
124
+ function measurePage(page: DomEl | undefined): { width: number; height: number } | undefined {
125
+ const model = page && graphModel(page);
126
+ if (!model) return undefined;
127
+ const { cells, ids } = collectCellsWithIds(firstByTag(model, "root"));
128
+ const bounds = contentBounds(cells, ids);
129
+ return bounds ? { width: bounds.maxX - bounds.minX, height: bounds.maxY - bounds.minY } : undefined;
130
+ }
131
+
132
+ /** Size of visible page content, or undefined for a missing or unmeasurable page. */
133
+ export async function pageContentSize(input: string, pageIndex: number): Promise<{ width: number; height: number } | undefined> {
134
+ return measurePage(diagramPages(await readDiagramXml(input))[pageIndex - 1]);
135
+ }
136
+
137
+ /** Internal alias guard also used for a storyboard generated from a diagram. */
138
+ export function rejectSourceAlias(input: string, output: string): void {
139
+ const source = statSync(input, { bigint: true });
140
+ const destination = statSync(output, { bigint: true, throwIfNoEntry: false });
141
+ if (destination && sameFile(source, destination)) throw new Error(`output aliases the input file: ${output}`);
142
+ }
143
+
144
+ function publicationPath(output: string): string {
145
+ let path = output;
146
+ const seen = new Set<string>();
147
+ for (;;) {
148
+ if (path.endsWith("/") || path.endsWith(sep)) throw new Error(`export destination must name a file: ${output}`);
149
+ const parent = realpathSync.native(dirname(path));
150
+ const entry = join(parent, basename(path));
151
+ if (!fileAt(entry)?.isSymbolicLink()) return entry;
152
+ if (seen.has(entry)) throw new Error(`export destination has a symlink loop: ${output}`);
153
+ seen.add(entry);
154
+ path = sessionPath(parent, readlinkSync(entry));
386
155
  }
387
156
  }
388
157
 
389
- function isRootUser(): boolean {
390
- const getuid = (process as NodeJS.Process & { getuid?: () => number }).getuid;
391
- return typeof getuid === "function" && getuid() === 0;
158
+ function checkDestination(destination: string): BigIntStats | undefined {
159
+ const existing = fileAt(destination);
160
+ if (existing && !existing.isFile()) throw new Error(`export destination is not a regular file: ${destination}`);
161
+ accessSync(dirname(destination), constants.W_OK | constants.X_OK);
162
+ if (existing) accessSync(destination, constants.W_OK);
163
+ return existing;
392
164
  }
393
165
 
394
- /**
395
- * Xvfb screen for an export: draw.io fails (UnknownVizError, then hangs) when the
396
- * requested raster is wider than the virtual screen. The height is unknown when only
397
- * a width is requested, so the larger requested side sizes both, plus a margin,
398
- * floored at 1280x1024 and capped at 8192.
399
- */
400
- export function xvfbScreen(args: string[]): string {
401
- const want = Math.max(flagNumber(args, "--width"), flagNumber(args, "--height"));
402
- const side = want > 0 ? Math.min(8192, want + 256) : 0;
403
- return `${Math.max(1280, side)}x${Math.max(1024, side)}x24`;
404
- }
405
-
406
- function flagNumber(args: string[], flag: string): number {
407
- const i = args.indexOf(flag);
408
- return i >= 0 ? Number(args[i + 1]) || 0 : 0;
409
- }
410
-
411
- /** Run the export, wrapping in `xvfb-run` on headless Linux and falling back to a direct call if it's absent. */
412
- async function invoke(binary: string, fullArgs: string[]): Promise<string> {
413
- if (platform() === "linux" && !process.env.DISPLAY) {
414
- const screen = `-screen 0 ${xvfbScreen(fullArgs)}`;
415
- try {
416
- await run("xvfb-run", ["-a", `--server-args=${screen}`, binary, ...fullArgs]);
417
- return `xvfb-run -a --server-args="${screen}" ${binary} ${fullArgs.join(" ")}`;
418
- } catch (e) {
419
- if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
420
- // xvfb-run not installed — fall through to a direct call
166
+ /** Renaming over a file must not broaden access to its contents. */
167
+ function preserveFileAccess(existing: BigIntStats, staged: string): void {
168
+ const rendered = statSync(staged, { bigint: true });
169
+ if (existing.uid !== rendered.uid || existing.gid !== rendered.gid) {
170
+ chownSync(staged, Number(existing.uid), Number(existing.gid));
171
+ }
172
+ chmodSync(staged, Number(existing.mode & 0o777n));
173
+ }
174
+
175
+ function checkPublication(
176
+ plan: ExportPlan, key: string, destination: string, implicitPreview: boolean,
177
+ ) {
178
+ if (publicationPath(plan.output) !== destination) throw new Error(`export destination changed: ${plan.output}`);
179
+ rejectSourceAlias(plan.input, destination);
180
+ const existing = checkDestination(destination);
181
+ const linked = fileAt(plan.output)?.isSymbolicLink() === true;
182
+ const previous = plan.mode === "preview" ? previewOutputs.get(key)?.get(destination) : undefined;
183
+ const replaced = previous !== undefined && stillOwned(existing, previous);
184
+ if (implicitPreview && (linked || (existing && !(replaced && previous?.removable)))) {
185
+ throw new Error(`preview destination is already in use: ${plan.output}; choose an explicit output`);
186
+ }
187
+ return { existing, linked, replaced };
188
+ }
189
+
190
+ function requireRenderedFile(plan: ExportPlan, staged: string): BigIntStats {
191
+ const file = fileAt(staged);
192
+ if (!file) throw new Error(`draw.io reported no error but the output was not created: ${plan.output}`);
193
+ if (!file.isFile()) throw new Error(`draw.io output is not a regular file: ${plan.output}`);
194
+ return file;
195
+ }
196
+
197
+ interface RasterSize { width: number; height: number }
198
+
199
+ /** Read the SOF dimensions, skipping length-prefixed JPEG marker segments, not searching compressed data. */
200
+ function jpegSize(data: Buffer): RasterSize | undefined {
201
+ if (data.length < 4 || data.readUInt16BE(0) !== 0xffd8 || data.readUInt16BE(data.length - 2) !== 0xffd9) return;
202
+ let offset = 2;
203
+ let size: RasterSize | undefined;
204
+ while (offset + 3 < data.length && data[offset++] === 0xff) {
205
+ while (data[offset] === 0xff) offset++;
206
+ const marker = data[offset++];
207
+ if (offset + 2 > data.length || marker === 0 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd9)) return;
208
+ const length = data.readUInt16BE(offset);
209
+ if (length < 2 || offset + length > data.length - 2) return;
210
+ if (marker === 0xda) return length >= 6 && offset + length < data.length - 2 ? size : undefined;
211
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
212
+ if (size || length < 11 || length !== 8 + 3 * data[offset + 7]) return;
213
+ const height = data.readUInt16BE(offset + 3);
214
+ const width = data.readUInt16BE(offset + 5);
215
+ if (!width || !height) return;
216
+ size = { width, height };
421
217
  }
218
+ offset += length;
422
219
  }
423
- await run(binary, fullArgs);
424
- return `${binary} ${fullArgs.join(" ")}`;
425
220
  }
426
221
 
427
- /**
428
- * Export a `.drawio` file to PNG/SVG/PDF/JPG. Resolves the binary, runs the CLI,
429
- * and (for embedded PNG) repairs the truncated IEND chunk. Throws on missing
430
- * input, missing CLI, or a failed export.
431
- */
432
- export async function exportDiagram(opts: ExportOptions): Promise<ExportResult> {
433
- if (!existsSync(opts.input)) throw new Error(`input file not found: ${opts.input}`);
434
- return withSourceExportQueue(opts.input, () => exportDiagramQueued(opts));
222
+ function exceedsReview(plan: ExportPlan, size: RasterSize): boolean {
223
+ return plan.mode === "preview" && Math.max(size.width, size.height) > MAX_REVIEW_SIDE;
435
224
  }
436
225
 
437
- async function invokeExport(binary: string, args: string[]): Promise<string> {
438
- try {
439
- return await invoke(binary, args);
440
- } catch (e) {
441
- const message = e instanceof Error ? e.message : String(e);
442
- const stderr = (e as { stderr?: string }).stderr?.trim();
443
- const detail = stderr ? `${message}\n${stderr}` : message;
444
- throw new Error(`draw.io export failed: ${detail}`, { cause: e });
226
+ async function verifyRenderedFile(plan: ExportPlan, staged: string): Promise<{
227
+ repaired: boolean; artifactSha256?: string; oversized?: RasterSize;
228
+ }> {
229
+ requireRenderedFile(plan, staged);
230
+ if (plan.format === "png") {
231
+ if (plan.embed) return { repaired: await repairPng(staged, true) };
232
+ const data = await readFile(staged);
233
+ const png = inspectPng(data);
234
+ if (png.editable) throw new Error("draw.io returned editable metadata in an unembedded PNG");
235
+ if (exceedsReview(plan, png)) return { repaired: false, oversized: png };
236
+ return { repaired: false, artifactSha256: createHash("sha256").update(data).digest("hex") };
445
237
  }
446
- }
447
-
448
- async function exportDiagramQueued(opts: ExportOptions): Promise<ExportResult> {
449
- const info = await resolveBinary(opts.binary);
450
- if (!info.available || !info.binary) {
451
- throw new Error(
452
- "draw.io CLI not found. Install draw.io desktop (macOS: `brew install --cask drawio`; " +
453
- "others: https://github.com/jgraph/drawio-desktop/releases), or pass an explicit `binary` path.",
454
- );
455
- }
456
-
457
- const plan = planExport(opts, platform(), isRootUser(), await pageContentWidth(opts.input, opts.pageIndex ?? 1));
458
- const fullArgs = [...plan.args, plan.input, ...plan.linuxExtra];
459
-
460
- const command = await invokeExport(info.binary, fullArgs);
461
- if (!existsSync(plan.output)) {
462
- throw new Error(`draw.io reported no error but the output was not created: ${plan.output}`);
463
- }
464
-
465
- const repaired = plan.embed && plan.format === "png" ? await repairPng(plan.output) : false;
466
- // Every SVG gets an even outer margin and shows its authored colors, matching PNG/PDF output in any viewer.
467
238
  if (plan.format === "svg") {
468
239
  try {
469
- await finishSvgFile(plan.output, plan.svgMargin);
240
+ await finishSvgFile(staged, plan.svgMargin);
470
241
  } catch (error) {
471
- await rm(plan.output, { force: true });
472
242
  throw new Error(`SVG post-processing failed: ${(error as Error).message}`, { cause: error });
473
243
  }
474
- }
475
- let animation: AnimatedSvgSummary | undefined;
476
- if (plan.animated) {
477
- try {
478
- animation = await enhanceAnimatedSvg(plan.input, plan.output, opts.pageIndex ?? 1);
479
- } catch (error) {
480
- await rm(plan.output, { force: true });
481
- throw new Error(`animated SVG verification failed: ${(error as Error).message}`, { cause: error });
244
+ } else {
245
+ const data = await readFile(staged);
246
+ if (plan.format === "jpg") {
247
+ const size = jpegSize(data);
248
+ if (!size) throw new Error(`draw.io output is not a complete JPG: ${plan.output}`);
249
+ if (size.width * size.height > MAX_FINAL_RASTER_PIXELS) {
250
+ throw new Error(`draw.io output exceeds the ${MAX_FINAL_RASTER_PIXELS}-pixel JPG limit`);
251
+ }
252
+ if (exceedsReview(plan, size)) return { repaired: false, oversized: size };
253
+ } else if (data.subarray(0, 5).toString("ascii") !== "%PDF-" || !data.subarray(-32).toString("ascii").trimEnd().endsWith("%%EOF")) {
254
+ throw new Error(`draw.io output is not a complete PDF: ${plan.output}`);
482
255
  }
483
256
  }
484
- const cleanup =
485
- plan.mode === "preview"
486
- ? await replaceTrackedPreview(plan.input, plan.output)
487
- : await removeTrackedPreviews(plan.input, plan.output);
488
- return {
489
- output: plan.output,
490
- format: plan.format,
491
- mode: plan.mode,
492
- embed: plan.embed,
493
- animated: plan.animated,
494
- animation,
495
- binary: info.binary,
496
- version: info.version,
497
- repaired,
498
- replacedPreview: cleanup.replaced,
499
- removedPreviews: cleanup.removed,
500
- previewCleanupWarnings: cleanup.warnings,
501
- command,
502
- };
503
- }
504
-
505
- // --- Mermaid → .drawio conversion + ELK auto-layout (both need draw.io v30+) ---
506
-
507
- /** Default `.drawio` output path derived from a source file. */
508
- function drawioOutputFor(src: string): string {
509
- const dir = dirname(src);
510
- const ext = extname(src);
511
- const base = ext ? basename(src).slice(0, -ext.length) : basename(src);
512
- return join(dir, `${base}.drawio`);
257
+ return { repaired: false };
513
258
  }
514
259
 
515
- async function requireBinary(minMajor: number, feature: string, override?: string): Promise<DrawioInfo & { binary: string }> {
516
- const info = await resolveBinary(override);
517
- if (!info.available || !info.binary) {
518
- throw new Error(
519
- "draw.io CLI not found. Install draw.io desktop (macOS: `brew install --cask drawio`; " +
520
- "others: https://github.com/jgraph/drawio-desktop/releases), or pass an explicit `binary` path.",
521
- );
522
- }
523
- if ((info.major ?? 0) < minMajor) {
524
- throw new Error(
525
- `${feature} needs draw.io v${minMajor}+, but ${info.version} is installed. Upgrade with \`brew upgrade --cask drawio\`.`,
526
- );
260
+ async function invokeExport(binary: string, args: string[], signal: AbortSignal | undefined): Promise<string> {
261
+ try {
262
+ return await invokeRenderer(binary, args, signal);
263
+ } catch (error) {
264
+ if (error instanceof Error && error.name === "AbortError") throw error;
265
+ // Runtime supplies only a safe launch/exit/timeout error; child exceptions and output are not its cause.
266
+ throw new Error(`draw.io export failed: ${(error as Error).message}`, { cause: error });
527
267
  }
528
- return info as DrawioInfo & { binary: string };
529
268
  }
530
269
 
531
- /** Args for a Mermaid → .drawio conversion (pure, for testing). */
532
- export function mermaidArgs(mmdPath: string, output: string): string[] {
533
- return ["-x", "-f", "xml", "-o", output, mmdPath];
270
+ async function renderVerified(plan: ExportPlan, staged: string, input: string, binary: string, signal?: AbortSignal) {
271
+ // draw.io selects the encoder from the staged suffix even when -f is given.
272
+ const args = [...plan.args.slice(0, -1), staged, input, ...plan.linuxExtra];
273
+ for (let attempt = 0; ; attempt++) {
274
+ signal?.throwIfAborted();
275
+ const command = await invokeExport(binary, args, signal);
276
+ signal?.throwIfAborted();
277
+ const { oversized, ...verified } = await verifyRenderedFile(plan, staged);
278
+ if (!oversized) return { ...verified, command };
279
+ // Correct for the actual aspect of unmeasurable content (e.g. compressed pages).
280
+ // An uncooperative renderer gets at most one retry, and must create fresh output.
281
+ const axis = args.findIndex((arg) => arg === "--width" || arg === "--height");
282
+ const border = Number(args[args.indexOf("-b") + 1]);
283
+ const requested = Number(args[axis + 1]);
284
+ const smaller = Math.floor(requested * (MAX_REVIEW_SIDE - 2) / Math.max(oversized.width, oversized.height));
285
+ if (attempt || axis < 0 || smaller <= 2 * border || smaller >= requested) {
286
+ throw new Error(`draw.io preview exceeds the ${MAX_REVIEW_SIDE}px review side limit`);
287
+ }
288
+ args[axis + 1] = String(smaller);
289
+ unlinkSync(staged);
290
+ }
534
291
  }
535
292
 
536
- export interface MermaidOptions {
537
- /** Path to a `.mmd` file. */
538
- input?: string;
539
- /** Inline Mermaid text (written to a temp `.mmd`); used when `input` is omitted. */
540
- mermaid?: string;
541
- output?: string;
542
- binary?: string;
543
- }
544
- export interface MermaidResult {
545
- output: string;
546
- binary: string;
547
- version?: string;
548
- command: string;
293
+ async function finalizeAnimatedSvg(
294
+ plan: ExportPlan, input: string, staged: string, pageIndex: number | undefined, finishStagedSvg?: (path: string) => Promise<void>,
295
+ ): Promise<AnimatedSvgSummary | undefined> {
296
+ if (plan.format !== "svg" || !(plan.animated || finishStagedSvg)) return;
297
+ try {
298
+ const animation = plan.animated ? await enhanceAnimatedSvg(input, staged, pageIndex) : undefined;
299
+ await finishStagedSvg?.(staged);
300
+ requireRenderedFile(plan, staged);
301
+ assertStandaloneImages(await readFile(staged, "utf8"));
302
+ return animation;
303
+ } catch (error) {
304
+ throw new Error(`animated SVG verification failed: ${(error as Error).message}`, { cause: error });
305
+ }
549
306
  }
550
307
 
551
- /**
552
- * Convert Mermaid text to a native `.drawio` (structure + automatic layout) via
553
- * the CLI. Requires draw.io v30+. Never applies `--layout` afterwards — the
554
- * conversion is already laid out.
555
- */
556
- export async function convertMermaid(opts: MermaidOptions): Promise<MermaidResult> {
557
- const info = await requireBinary(30, "Mermaid conversion", opts.binary);
308
+ /** Render and verify privately. Callers must already hold the needed diagram reservations. */
309
+ export async function prepareExport(
310
+ opts: ExportOptions, renderInput: string, finishStagedSvg?: (path: string) => Promise<void>,
311
+ ): Promise<PreparedExport> {
312
+ const { signal } = opts;
313
+ signal?.throwIfAborted();
314
+ const cwd = process.cwd();
315
+ const source = sessionPath(cwd, opts.input);
316
+ const renderPath = sessionPath(cwd, renderInput);
317
+ const explicit = opts.output === undefined ? undefined : sessionPath(cwd, opts.output);
318
+ if (explicit !== undefined) {
319
+ // Preserve alias rejection even if the request also has a conflicting suffix.
320
+ rejectSourceAlias(source, explicit);
321
+ checkDestination(publicationPath(explicit));
322
+ }
323
+ if (opts.pageIndex !== undefined && (!Number.isSafeInteger(opts.pageIndex) || opts.pageIndex <= 0)) {
324
+ throw new Error("pageIndex must be a positive integer");
325
+ }
326
+ const pages = diagramPages(await readDiagramXml(renderPath));
327
+ if (opts.pageIndex !== undefined && opts.pageIndex > pages.length) {
328
+ throw new Error(`pageIndex ${opts.pageIndex} is out of range (${pages.length} pages)`);
329
+ }
330
+ const content = measurePage(pages[(opts.pageIndex ?? 1) - 1]);
331
+ // Keep the caller's spelling in receipts; only filesystem/CLI operands are anchored.
332
+ const plan = planExport(opts, undefined, false, content?.width, content?.height);
333
+ const output = plan.output;
334
+ plan.input = source;
335
+ plan.output = sessionPath(cwd, output);
336
+ const destination = publicationPath(plan.output);
337
+ const key = realpathSync.native(source);
338
+ const implicitPreview = plan.mode === "preview" && explicit === undefined;
339
+ checkPublication(plan, key, destination, implicitPreview);
340
+
341
+ const info = await resolveBinary(opts.binary, signal);
342
+ const { binary } = info;
343
+ if (!info.available || !binary) throw new Error(rendererUnavailable(info));
344
+ if (opts.pageIndex !== undefined && !supportsPageIndex(info.version)) {
345
+ throw new Error(`explicit pageIndex requires draw.io ${INDEX_MIN} or later (found ${info.version ?? "unknown version"})`);
346
+ }
558
347
 
559
- let mmdPath = opts.input;
560
- let tempDir: string | undefined;
348
+ signal?.throwIfAborted();
349
+ const stageDir = await mkdtemp(join(dirname(destination), ".drawme-export-"));
350
+ const staged = join(stageDir, `artifact.${plan.format}`);
351
+ const dispose = () => rm(stageDir, { recursive: true, force: true });
561
352
  try {
562
- if (!mmdPath) {
563
- if (!opts.mermaid?.trim()) {
564
- throw new Error("provide either `input` (a .mmd file path) or `mermaid` (inline Mermaid text)");
353
+ const verified = await renderVerified(plan, staged, renderPath, binary, signal);
354
+ const animation = await finalizeAnimatedSvg(plan, renderPath, staged, opts.pageIndex, finishStagedSvg);
355
+ const stagedFile = requireRenderedFile(plan, staged);
356
+ const check = () => {
357
+ signal?.throwIfAborted();
358
+ const currentStage = requireRenderedFile(plan, staged);
359
+ if (!sameFile(stagedFile, currentStage) || stagedFile.size !== currentStage.size || stagedFile.mtimeNs !== currentStage.mtimeNs) {
360
+ throw new Error(`verified draw.io output changed before publication: ${output}`);
565
361
  }
566
- tempDir = await mkdtemp(join(tmpdir(), "drawme-mmd-"));
567
- mmdPath = join(tempDir, "diagram.mmd");
568
- await writeFile(mmdPath, opts.mermaid, "utf8");
569
- } else if (!existsSync(mmdPath)) {
570
- throw new Error(`input file not found: ${mmdPath}`);
571
- }
572
- const output = opts.output ?? (opts.input ? drawioOutputFor(opts.input) : join(process.cwd(), "diagram.drawio"));
573
- const command = await invoke(info.binary, mermaidArgs(mmdPath, output));
574
- if (!existsSync(output)) throw new Error(`conversion produced no output: ${output}`);
575
- return { output, binary: info.binary, version: info.version, command };
576
- } finally {
577
- if (tempDir) await rm(tempDir, { recursive: true, force: true });
362
+ const current = checkPublication(plan, key, destination, implicitPreview);
363
+ if (current.existing) preserveFileAccess(current.existing, staged);
364
+ return current;
365
+ };
366
+ check();
367
+ return {
368
+ get publicationDestination() {
369
+ // Paired callers can recheck both targets before touching either public file.
370
+ check();
371
+ return destination;
372
+ },
373
+ commit() {
374
+ const { linked, replaced } = check();
375
+ signal?.throwIfAborted();
376
+ renameSync(staged, destination);
377
+ const published = plan.mode === "preview" ? fileAt(destination) : undefined;
378
+ const latest = published && sameFile(published, stagedFile)
379
+ ? { displayPath: output, removable: !linked, file: published }
380
+ : undefined;
381
+ const cleanup = retirePreviews(key, destination, latest);
382
+ return {
383
+ ...verified, output, format: plan.format, mode: plan.mode, embed: plan.embed, animated: plan.animated,
384
+ animation, binary, version: info.version, replacedPreview: replaced || cleanup.replaced,
385
+ removedPreviews: cleanup.removed, previewCleanupWarnings: cleanup.warnings,
386
+ };
387
+ },
388
+ dispose,
389
+ };
390
+ } catch (error) {
391
+ await dispose();
392
+ throw error;
578
393
  }
579
394
  }
580
395
 
581
- /** ELK layout presets the CLI accepts. Any other value opens a modal that hangs headless runs. */
582
- export const LAYOUT_PRESETS = ["verticalFlow", "horizontalFlow", "verticalTree", "horizontalTree", "radialTree", "organic"] as const;
583
- export type LayoutPreset = (typeof LAYOUT_PRESETS)[number];
584
-
585
- /** Args for an ELK `--layout` pass (pure, for testing). */
586
- export function layoutArgs(input: string, preset: LayoutPreset, output: string): string[] {
587
- return ["-x", "-f", "xml", "--layout", preset, "-o", output, input];
588
- }
589
-
590
- export interface LayoutOptions {
591
- input: string;
592
- preset: LayoutPreset;
593
- /** Defaults to a sibling `<name>.layout.drawio` (never overwrites the input unless you pass it explicitly). */
594
- output?: string;
595
- binary?: string;
596
- }
597
- export interface LayoutResult {
598
- output: string;
599
- preset: LayoutPreset;
600
- binary: string;
601
- version?: string;
602
- command: string;
603
- }
604
-
605
- /**
606
- * Re-place nodes and route edges with an ELK layout preset via the CLI. Requires
607
- * draw.io v30+. The preset is validated against a strict allowlist first — an
608
- * unknown value would open a modal error dialog that hangs a headless run.
609
- */
610
- export async function applyLayout(opts: LayoutOptions): Promise<LayoutResult> {
611
- if (!LAYOUT_PRESETS.includes(opts.preset)) {
612
- throw new Error(`unknown layout preset '${opts.preset}'. Allowed: ${LAYOUT_PRESETS.join(", ")}`);
613
- }
396
+ /** Reserve the source once and commit matched, verified bytes before retiring previews. */
397
+ export async function exportDiagram(opts: ExportOptions, finishStagedSvg?: (path: string) => Promise<void>): Promise<ExportResult> {
398
+ opts.signal?.throwIfAborted();
614
399
  if (!existsSync(opts.input)) throw new Error(`input file not found: ${opts.input}`);
615
- const info = await requireBinary(30, "The --layout pass", opts.binary);
616
- const output = opts.output ?? join(dirname(opts.input), `${basename(opts.input, extname(opts.input))}.layout.drawio`);
617
- const command = await invoke(info.binary, layoutArgs(opts.input, opts.preset, output));
618
- if (!existsSync(output)) throw new Error(`layout produced no output: ${output}`);
619
- return { output, preset: opts.preset, binary: info.binary, version: info.version, command };
620
- }
621
-
622
- /** Open a file in the OS default handler (draw.io desktop for `.drawio`). No version gate. */
623
- export async function openFile(path: string): Promise<{ opener: string }> {
624
- if (!existsSync(path)) throw new Error(`file not found: ${path}`);
625
- const plat = platform();
626
- if (plat === "darwin") {
627
- await run("open", [path], 15_000);
628
- return { opener: "open" };
629
- }
630
- if (plat === "win32") {
631
- await run("cmd", ["/c", "start", "", path], 15_000);
632
- return { opener: "start" };
633
- }
634
- await run("xdg-open", [path], 15_000);
635
- return { opener: "xdg-open" };
400
+ return withDiagramFiles([opts.input], opts.signal, async () => {
401
+ const prepared = await prepareExport(opts, opts.input, finishStagedSvg);
402
+ try {
403
+ return prepared.commit();
404
+ } finally {
405
+ await prepared.dispose();
406
+ }
407
+ });
636
408
  }