@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/CHANGELOG.md +17 -1
- package/README.md +47 -46
- package/SECURITY.md +1 -1
- package/assets/references/diagram-types.md +3 -3
- package/assets/references/mermaid-authoring.md +10 -9
- package/assets/references/troubleshooting.md +5 -27
- package/assets/references/xml-authoring.md +5 -3
- package/docs/reference.md +75 -73
- package/docs/visual-review-implementation-tasks.md +4 -2
- package/example/README.md +9 -9
- package/example/drawme-architecture.drawio +5 -5
- package/example/drawme-how-it-works.drawio +7 -7
- package/example/drawme-installation-guide.drawio +6 -6
- package/package.json +5 -3
- package/src/animate.ts +124 -88
- package/src/animation.ts +105 -109
- package/src/diagram-files.ts +159 -0
- package/src/dom.ts +5 -0
- package/src/drawio.ts +330 -558
- package/src/editable-import.ts +228 -0
- package/src/explain.ts +81 -88
- package/src/export-plan.ts +175 -0
- package/src/fitcanvas.ts +29 -25
- package/src/geometry.ts +68 -29
- package/src/index.ts +201 -142
- package/src/motion.ts +251 -163
- package/src/png.ts +233 -34
- package/src/renderer.ts +361 -0
- package/src/shapesearch.ts +33 -32
- package/src/storyboard.ts +41 -26
- package/src/svg-helpers.ts +129 -0
- package/src/svgexport.ts +6 -9
- package/src/validate.ts +686 -292
- package/src/workflow.ts +41 -30
package/src/drawio.ts
CHANGED
|
@@ -1,256 +1,44 @@
|
|
|
1
|
-
/**
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
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 {
|
|
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
|
|
21
|
-
export
|
|
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
|
-
|
|
251
|
-
|
|
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
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
50
|
+
export interface PreparedExport {
|
|
51
|
+
readonly publicationDestination: string;
|
|
52
|
+
commit(): ExportResult;
|
|
53
|
+
dispose(): Promise<void>;
|
|
54
|
+
}
|
|
266
55
|
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
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
|
-
|
|
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
|
-
|
|
308
|
-
|
|
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
|
-
|
|
331
|
-
|
|
332
|
-
|
|
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
|
-
/**
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
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
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
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
|
|
390
|
-
const
|
|
391
|
-
|
|
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
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
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
|
-
|
|
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
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
const
|
|
444
|
-
|
|
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(
|
|
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
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
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
|
-
|
|
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
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
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
|
-
|
|
532
|
-
|
|
533
|
-
|
|
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
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
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
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
const
|
|
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
|
-
|
|
560
|
-
|
|
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
|
-
|
|
563
|
-
|
|
564
|
-
|
|
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
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
}
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
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
|
-
/**
|
|
582
|
-
export
|
|
583
|
-
|
|
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
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
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
|
}
|