@senad-d/drawme 0.1.3 → 0.1.5

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/validate.ts CHANGED
@@ -1,148 +1,63 @@
1
1
  /**
2
- * Deterministic structural linter for `.drawio` files. Catches mistakes a vision
3
- * self-check is slow and unreliable at: dangling edge endpoints, duplicate or
4
- * reserved ids, broken parent references, and (as warnings) off-grid geometry,
5
- * overlapping sibling nodes, and edge-routing defects. Runs without launching
6
- * draw.io.
2
+ * Deterministic structural linter for `.drawio` files. It rejects broken cell
3
+ * contracts and reports conservative geometry/readability findings that can be
4
+ * checked without rendering. Typography and automatically routed connectors
5
+ * still require visual review.
7
6
  */
8
7
  import { readFile } from "node:fs/promises";
9
8
  import { DOMParser } from "@xmldom/xmldom";
10
- import { type DomEl, attr, childrenByTag, directText, elemChildren, firstByTag } from "./dom";
9
+ import { type DomEl, attr, childrenByTag, directText, firstByTag } from "./dom";
10
+ import {
11
+ type ById,
12
+ type ContentBounds,
13
+ type Point,
14
+ type Rect,
15
+ absRect,
16
+ collectCells,
17
+ contentBounds,
18
+ edgeRoute,
19
+ geometryIsRelative,
20
+ hasInvalidNumber,
21
+ isEdgeLabel,
22
+ isVisible,
23
+ pyFloat,
24
+ rect,
25
+ styleNum,
26
+ } from "./geometry";
11
27
 
12
28
  const RESERVED = new Set(["0", "1"]);
13
-
14
- /** [x, y, width, height]. width/height may be NaN when the source omits them. */
15
- type Rect = [number, number, number, number];
16
- type ById = Map<string, DomEl>;
29
+ export const MIN_OUTER_MARGIN = 20;
30
+ const EXCESSIVE_CANVAS_AREA_RATIO = 4;
31
+ const EXCESSIVE_CANVAS_AXIS_RATIO = 0.6;
17
32
 
18
33
  export interface ValidateResult {
19
34
  errors: string[];
20
35
  warnings: string[];
36
+ /** Informational limitations/settings that do not require a source correction. */
37
+ observations: string[];
21
38
  /** Readability score (lower is better); comparable only across variants of the same graph. */
22
39
  score: { total: number; through: number; crossings: number; overlaps: number };
23
40
  }
24
41
 
25
- /** Python `float()` semantics: accepts nan/inf, strict-numeric otherwise; else undefined (≈ ValueError). */
26
- function pyFloat(s: string): number | undefined {
27
- const t = s.trim().toLowerCase();
28
- if (t === "nan" || t === "+nan" || t === "-nan") return Number.NaN;
29
- if (t === "inf" || t === "+inf" || t === "infinity" || t === "+infinity") return Infinity;
30
- if (t === "-inf" || t === "-infinity") return -Infinity;
31
- if (!/^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/.test(t)) return undefined;
32
- const n = Number(t);
33
- return Number.isNaN(n) ? undefined : n;
34
- }
35
-
36
42
  /** Quote an optional attribute consistently in diagnostic messages. */
37
43
  function repr(s: string | null): string {
38
44
  return s === null ? "None" : `'${s}'`;
39
45
  }
40
46
 
41
- function rect(cell: DomEl): Rect | null {
42
- const gy = firstByTag(cell, "mxGeometry");
43
- if (!gy) return null;
44
- const x = pyFloat(attr(gy, "x") ?? "0");
45
- const y = pyFloat(attr(gy, "y") ?? "0");
46
- const w = pyFloat(attr(gy, "width") ?? "nan");
47
- const h = pyFloat(attr(gy, "height") ?? "nan");
48
- if (x === undefined || y === undefined || w === undefined || h === undefined) return null;
49
- return [x, y, w, h];
50
- }
51
-
52
- function hasNaN(r: Rect): boolean {
53
- return r.some((v) => Number.isNaN(v));
54
- }
55
-
56
- /** True for edge labels / relative-positioned child vertices (they legitimately omit w/h). */
57
- function isEdgeLabel(cell: DomEl): boolean {
58
- if ((attr(cell, "style") ?? "").includes("edgeLabel")) return true;
59
- const gy = firstByTag(cell, "mxGeometry");
60
- return gy !== null && gy.getAttribute("relative") === "1";
61
- }
62
-
63
47
  function overlap(a: Rect, b: Rect): boolean {
64
48
  const [ax, ay, aw, ah] = a;
65
49
  const [bx, by, bw, bh] = b;
66
50
  return ax < bx + bw && bx < ax + aw && ay < by + bh && by < ay + ah;
67
51
  }
68
52
 
69
- function styleNum(style: string | null, key: string): number | undefined {
70
- for (const part of (style ?? "").split(";")) {
71
- if (part.startsWith(key + "=")) return pyFloat(part.split("=").slice(1).join("="));
72
- }
73
- return undefined;
74
- }
75
-
76
- /** Absolute (x, y, w, h) of a vertex, summing parent-container offsets. */
77
- function absRect(cell: DomEl, byId: ById): Rect | null {
78
- const r = rect(cell);
79
- if (r === null || hasNaN(r)) return null;
80
- let [x, y] = r;
81
- const [, , w, h] = r;
82
- let parent = attr(cell, "parent");
83
- const seen = new Set<string>();
84
- while (parent && byId.has(parent) && !seen.has(parent)) {
85
- seen.add(parent);
86
- const p = byId.get(parent)!;
87
- if (p.getAttribute("vertex") === "1") {
88
- const pr = rect(p);
89
- if (pr && !hasNaN(pr)) {
90
- x += pr[0];
91
- y += pr[1];
92
- }
93
- }
94
- parent = attr(p, "parent");
95
- }
96
- return [x, y, w, h];
97
- }
98
-
99
- type Point = [number, number];
100
-
101
- /** Absolute point where `edge` meets its source/target vertex (honours exit/entry). */
102
- function endpoint(edge: DomEl, end: "source" | "target", byId: ById): Point | null {
103
- const vid = attr(edge, end);
104
- if (!vid || !byId.has(vid)) return null;
105
- const box = absRect(byId.get(vid)!, byId);
106
- if (box === null) return null;
107
- const [x, y, w, h] = box;
108
- const style = attr(edge, "style") ?? "";
109
- const fx = styleNum(style, end === "source" ? "exitX" : "entryX");
110
- const fy = styleNum(style, end === "source" ? "exitY" : "entryY");
111
- return [x + (fx ?? 0.5) * w, y + (fy ?? 0.5) * h];
112
- }
113
-
114
- function edgeWaypoints(edge: DomEl): Point[] {
115
- const gy = firstByTag(edge, "mxGeometry");
116
- if (!gy) return [];
117
- const arr = firstByTag(gy, "Array");
118
- if (!arr) return [];
119
- const pts: Point[] = [];
120
- for (const pt of childrenByTag(arr, "mxPoint")) {
121
- const px = attr(pt, "x");
122
- const py = attr(pt, "y");
123
- if (px !== null && py !== null) {
124
- const nx = pyFloat(px);
125
- const ny = pyFloat(py);
126
- if (nx !== undefined && ny !== undefined) pts.push([nx, ny]);
127
- }
128
- }
129
- return pts;
130
- }
131
-
132
- /** Absolute polyline for a waypointed edge, or null when auto-routed / unresolved. */
133
- function edgeRoute(edge: DomEl, byId: ById): Point[] | null {
134
- const wp = edgeWaypoints(edge);
135
- if (wp.length === 0) return null;
136
- const s = endpoint(edge, "source", byId);
137
- const t = endpoint(edge, "target", byId);
138
- if (s === null || t === null) return null;
139
- return [s, ...wp, t];
53
+ function styleHas(style: string | null, key: string, expected: string): boolean {
54
+ return (style ?? "").split(";").includes(`${key}=${expected}`);
140
55
  }
141
56
 
142
57
  function orient(a: Point, b: Point, c: Point): number {
143
- const v = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
144
- if (Math.abs(v) < 1e-9) return 0;
145
- return v > 0 ? 1 : -1;
58
+ const value = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
59
+ if (Math.abs(value) < 1e-9) return 0;
60
+ return value > 0 ? 1 : -1;
146
61
  }
147
62
 
148
63
  function segmentsCross(p1: Point, p2: Point, p3: Point, p4: Point): boolean {
@@ -153,9 +68,9 @@ function segmentsCross(p1: Point, p2: Point, p3: Point, p4: Point): boolean {
153
68
  return o1 !== o2 && o3 !== o4 && ![o1, o2, o3, o4].includes(0);
154
69
  }
155
70
 
156
- function pointInRect(p: Point, box: Rect, eps = 1e-6): boolean {
71
+ function pointInRect(point: Point, box: Rect, epsilon = 1e-6): boolean {
157
72
  const [x, y, w, h] = box;
158
- return x + eps < p[0] && p[0] < x + w - eps && y + eps < p[1] && p[1] < y + h - eps;
73
+ return x + epsilon < point[0] && point[0] < x + w - epsilon && y + epsilon < point[1] && point[1] < y + h - epsilon;
159
74
  }
160
75
 
161
76
  function routeHitsRect(points: Point[], box: Rect): boolean {
@@ -166,20 +81,20 @@ function routeHitsRect(points: Point[], box: Rect): boolean {
166
81
  [x + w, y + h],
167
82
  [x, y + h],
168
83
  ];
169
- const borders: [Point, Point][] = corners.map((c, i) => [c, corners[(i + 1) % 4]]);
84
+ const borders: [Point, Point][] = corners.map((corner, index) => [corner, corners[(index + 1) % 4]]);
170
85
  for (let i = 0; i < points.length - 1; i++) {
171
- const a = points[i];
172
- const b = points[i + 1];
173
- if (pointInRect(a, box) || pointInRect(b, box)) return true;
174
- for (const [c, d] of borders) if (segmentsCross(a, b, c, d)) return true;
86
+ const start = points[i];
87
+ const end = points[i + 1];
88
+ if (pointInRect(start, box) || pointInRect(end, box)) return true;
89
+ for (const [a, b] of borders) if (segmentsCross(start, end, a, b)) return true;
175
90
  }
176
91
  return false;
177
92
  }
178
93
 
179
- function routesCross(pa: Point[], pb: Point[]): boolean {
180
- for (let i = 0; i < pa.length - 1; i++)
181
- for (let j = 0; j < pb.length - 1; j++)
182
- if (segmentsCross(pa[i], pa[i + 1], pb[j], pb[j + 1])) return true;
94
+ function routesCross(a: Point[], b: Point[]): boolean {
95
+ for (let i = 0; i < a.length - 1; i++)
96
+ for (let j = 0; j < b.length - 1; j++)
97
+ if (segmentsCross(a[i], a[i + 1], b[j], b[j + 1])) return true;
183
98
  return false;
184
99
  }
185
100
 
@@ -189,10 +104,10 @@ type LeafBox = [string | null, Rect];
189
104
  /** Edges with a resolvable waypointed route, tagged with their id and endpoint ids. */
190
105
  function collectRoutedEdges(cells: DomEl[], ids: ById): RoutedEdge[] {
191
106
  const routed: RoutedEdge[] = [];
192
- for (const c of cells) {
193
- if (c.getAttribute("edge") === "1") {
194
- const pts = edgeRoute(c, ids);
195
- if (pts) routed.push([attr(c, "id"), pts, new Set([attr(c, "source"), attr(c, "target")])]);
107
+ for (const cell of cells) {
108
+ if (cell.getAttribute("edge") === "1" && isVisible(cell, ids)) {
109
+ const points = edgeRoute(cell, ids);
110
+ if (points) routed.push([attr(cell, "id"), points, new Set([attr(cell, "source"), attr(cell, "target")])]);
196
111
  }
197
112
  }
198
113
  return routed;
@@ -201,33 +116,43 @@ function collectRoutedEdges(cells: DomEl[], ids: ById): RoutedEdge[] {
201
116
  /** Absolute boxes of leaf vertices (real nodes, not containers or edge labels). */
202
117
  function collectLeafBoxes(cells: DomEl[], ids: ById, parents: Set<string | null>): LeafBox[] {
203
118
  const leaves: LeafBox[] = [];
204
- for (const c of cells) {
205
- if (c.getAttribute("vertex") === "1" && !parents.has(attr(c, "id")) && !isEdgeLabel(c)) {
206
- const box = absRect(c, ids);
207
- if (box) leaves.push([attr(c, "id"), box]);
119
+ for (const cell of cells) {
120
+ if (
121
+ cell.getAttribute("vertex") === "1" &&
122
+ !parents.has(attr(cell, "id")) &&
123
+ !isEdgeLabel(cell) &&
124
+ !geometryIsRelative(cell) &&
125
+ isVisible(cell, ids)
126
+ ) {
127
+ const box = absRect(cell, ids);
128
+ if (box) leaves.push([attr(cell, "id"), box]);
208
129
  }
209
130
  }
210
131
  return leaves;
211
132
  }
212
133
 
213
134
  function routeThroughWarnings(routed: RoutedEdge[], leaves: LeafBox[]): string[] {
214
- const warns: string[] = [];
215
- for (const [eid, pts, ends] of routed) {
216
- for (const [vid, box] of leaves) {
217
- if (!ends.has(vid) && routeHitsRect(pts, box)) warns.push(`edge ${repr(eid)} routes through vertex ${repr(vid)}`);
135
+ const warnings: string[] = [];
136
+ for (const [edgeId, points, ends] of routed) {
137
+ for (const [vertexId, box] of leaves) {
138
+ if (!ends.has(vertexId) && routeHitsRect(points, box)) {
139
+ warnings.push(`edge ${repr(edgeId)} routes through vertex ${repr(vertexId)}`);
140
+ }
218
141
  }
219
142
  }
220
- return warns;
143
+ return warnings;
221
144
  }
222
145
 
223
146
  function routeCrossWarnings(routed: RoutedEdge[]): string[] {
224
- const warns: string[] = [];
147
+ const warnings: string[] = [];
225
148
  for (let i = 0; i < routed.length; i++) {
226
149
  for (let j = i + 1; j < routed.length; j++) {
227
- if (routesCross(routed[i][1], routed[j][1])) warns.push(`edges ${repr(routed[i][0])} and ${repr(routed[j][0])} cross`);
150
+ if (routesCross(routed[i][1], routed[j][1])) {
151
+ warnings.push(`edges ${repr(routed[i][0])} and ${repr(routed[j][0])} cross`);
152
+ }
228
153
  }
229
154
  }
230
- return warns;
155
+ return warnings;
231
156
  }
232
157
 
233
158
  function geometryWarnings(cells: DomEl[], ids: ById, parents: Set<string | null>): string[] {
@@ -236,140 +161,397 @@ function geometryWarnings(cells: DomEl[], ids: ById, parents: Set<string | null>
236
161
  return [...routeThroughWarnings(routed, leaves), ...routeCrossWarnings(routed)];
237
162
  }
238
163
 
239
- /**
240
- * Fold UserObject/object wrappers (links & metadata) into their inner mxCell so
241
- * the wrapper id resolves for edges that reference it.
242
- */
243
- function collectCells(root: DomEl | null): DomEl[] {
244
- const cells: DomEl[] = [];
245
- for (const child of root ? elemChildren(root) : []) {
246
- if (child.tagName === "mxCell") cells.push(child);
247
- else if (child.tagName === "UserObject" || child.tagName === "object") {
248
- const inner = firstByTag(child, "mxCell");
249
- if (inner) {
250
- inner.setAttribute("id", attr(child, "id") ?? "");
251
- cells.push(inner);
252
- }
253
- }
254
- }
255
- return cells;
256
- }
257
-
258
164
  /** Map every cell by id (blank key for id-less cells); report duplicate ids as errors. */
259
165
  function buildIds(cells: DomEl[], errors: string[]): ById {
260
166
  const ids: ById = new Map();
261
- for (const c of cells) {
262
- const cid = attr(c, "id");
263
- if (cid !== null && ids.has(cid)) errors.push(`duplicate id ${repr(cid)}`);
264
- ids.set(cid ?? "", c);
167
+ for (const cell of cells) {
168
+ const id = attr(cell, "id");
169
+ if (id !== null && ids.has(id)) errors.push(`duplicate id ${repr(id)}`);
170
+ ids.set(id ?? "", cell);
265
171
  }
266
172
  return ids;
267
173
  }
268
174
 
269
- /** Geometry checks for a single non-edge-label vertex. */
270
- function checkVertexGeometry(c: DomEl, cid: string | null, errors: string[], warns: string[]): void {
271
- const r = rect(c);
272
- if (r === null || hasNaN(r)) {
273
- errors.push(`vertex ${repr(cid)} has missing/invalid geometry`);
175
+ /** Geometry checks for a single non-edge-label, non-relative vertex. */
176
+ function checkVertexGeometry(cell: DomEl, id: string | null, errors: string[], warnings: string[]): void {
177
+ const box = rect(cell);
178
+ if (box === null || hasInvalidNumber(box)) {
179
+ errors.push(`vertex ${repr(id)} has missing/invalid geometry`);
274
180
  return;
275
181
  }
276
- const [x, y, w, h] = r;
277
- if (w <= 0 || h <= 0) warns.push(`vertex ${repr(cid)} non-positive size ${String(w)}x${String(h)}`);
278
- if (x < 0 || y < 0) warns.push(`vertex ${repr(cid)} negative position (${String(x)},${String(y)})`);
279
- }
280
-
281
- /** Per-cell reference and geometry checks (parents, edge endpoints, reserved ids, geometry). */
282
- function checkCell(c: DomEl, ids: ById, errors: string[], warns: string[]): void {
283
- const cid = attr(c, "id");
284
- const parent = attr(c, "parent");
285
- const isV = c.getAttribute("vertex") === "1";
286
- const isE = c.getAttribute("edge") === "1";
287
- if (parent !== null && !ids.has(parent)) errors.push(`cell ${repr(cid)} parent ${repr(parent)} does not exist`);
182
+ const [x, y, width, height] = box;
183
+ if (width <= 0 || height <= 0) warnings.push(`vertex ${repr(id)} non-positive size ${String(width)}x${String(height)}`);
184
+ if (x < 0 || y < 0) warnings.push(`vertex ${repr(id)} negative position (${String(x)},${String(y)})`);
185
+ }
186
+
187
+ function checkEdgeGeometry(cell: DomEl, id: string | null, errors: string[]): void {
188
+ const geometry = firstByTag(cell, "mxGeometry");
189
+ if (!geometry) {
190
+ errors.push(`edge ${repr(id)} has missing geometry`);
191
+ return;
192
+ }
193
+ if (attr(geometry, "relative") !== "1" || attr(geometry, "as") !== "geometry") {
194
+ errors.push(`edge ${repr(id)} geometry must have relative='1' and as='geometry'`);
195
+ }
196
+ }
197
+
198
+ function checkCellReferences(cell: DomEl, id: string | null, ids: ById, errors: string[]): void {
199
+ const parent = attr(cell, "parent");
200
+ if (parent !== null && !ids.has(parent)) errors.push(`cell ${repr(id)} parent ${repr(parent)} does not exist`);
288
201
  for (const end of ["source", "target"] as const) {
289
- const ref = attr(c, end);
290
- if (ref && !ids.has(ref)) errors.push(`edge ${repr(cid)} ${end} ${repr(ref)} does not exist`);
202
+ const reference = attr(cell, end);
203
+ if (reference && !ids.has(reference)) errors.push(`edge ${repr(id)} ${end} ${repr(reference)} does not exist`);
291
204
  }
292
- if ((isV || isE) && cid !== null && RESERVED.has(cid)) errors.push(`cell ${repr(cid)} reuses reserved id 0/1`);
293
- if (isV && !isEdgeLabel(c)) checkVertexGeometry(c, cid, errors, warns);
294
205
  }
295
206
 
296
- /** Sibling overlap: leaf vertices only (containers legitimately wrap children). */
297
- function overlapWarnings(cells: DomEl[], parents: Set<string | null>): string[] {
207
+ /** Per-cell reference and geometry checks. */
208
+ function checkCell(cell: DomEl, ids: ById, errors: string[], warnings: string[]): void {
209
+ const id = attr(cell, "id");
210
+ const isVertex = cell.getAttribute("vertex") === "1";
211
+ const isEdge = cell.getAttribute("edge") === "1";
212
+ checkCellReferences(cell, id, ids, errors);
213
+ if ((isVertex || isEdge) && id !== null && RESERVED.has(id)) errors.push(`cell ${repr(id)} reuses reserved id 0/1`);
214
+ if (isVertex && !isEdgeLabel(cell) && !geometryIsRelative(cell)) checkVertexGeometry(cell, id, errors, warnings);
215
+ if (isEdge) checkEdgeGeometry(cell, id, errors);
216
+ }
217
+
218
+ /** Sibling overlap: visible leaf vertices only (containers legitimately wrap children). */
219
+ function overlapWarnings(cells: DomEl[], ids: ById, parents: Set<string | null>): string[] {
298
220
  const boxes: [string | null, string | null, Rect][] = [];
299
- for (const c of cells) {
300
- if (c.getAttribute("vertex") === "1" && !parents.has(attr(c, "id"))) {
301
- const r = rect(c);
302
- if (r && !hasNaN(r)) boxes.push([attr(c, "id"), attr(c, "parent"), r]);
221
+ for (const cell of cells) {
222
+ if (
223
+ cell.getAttribute("vertex") === "1" &&
224
+ !parents.has(attr(cell, "id")) &&
225
+ !isEdgeLabel(cell) &&
226
+ !geometryIsRelative(cell) &&
227
+ isVisible(cell, ids)
228
+ ) {
229
+ const box = rect(cell);
230
+ if (box && !hasInvalidNumber(box)) boxes.push([attr(cell, "id"), attr(cell, "parent"), box]);
303
231
  }
304
232
  }
305
- const warns: string[] = [];
233
+ const warnings: string[] = [];
306
234
  for (let i = 0; i < boxes.length; i++) {
307
235
  for (let j = i + 1; j < boxes.length; j++) {
308
- const [ia, pa, ra] = boxes[i];
309
- const [ib, pb, rb] = boxes[j];
310
- if (pa === pb && overlap(ra, rb)) warns.push(`vertices ${repr(ia)} and ${repr(ib)} overlap`);
236
+ const [aId, aParent, a] = boxes[i];
237
+ const [bId, bParent, b] = boxes[j];
238
+ if (aParent === bParent && overlap(a, b)) warnings.push(`vertices ${repr(aId)} and ${repr(bId)} overlap`);
311
239
  }
312
240
  }
313
- return warns;
241
+ return warnings;
242
+ }
243
+
244
+ function isContainmentCandidate(cell: DomEl, ids: ById): boolean {
245
+ return (
246
+ cell.getAttribute("vertex") === "1" &&
247
+ !geometryIsRelative(cell) &&
248
+ !isEdgeLabel(cell) &&
249
+ isVisible(cell, ids)
250
+ );
251
+ }
252
+
253
+ function overflowSides(childBox: Rect, parentBox: Rect): string[] {
254
+ const [x, y, width, height] = childBox;
255
+ const [px, py, parentWidth, parentHeight] = parentBox;
256
+ const sides: string[] = [];
257
+ if (x < px) sides.push("left");
258
+ if (y < py) sides.push("top");
259
+ if (x + width > px + parentWidth) sides.push("right");
260
+ if (y + height > py + parentHeight) sides.push("bottom");
261
+ return sides;
262
+ }
263
+
264
+ function containmentWarning(cell: DomEl, ids: ById): string | null {
265
+ if (!isContainmentCandidate(cell, ids)) return null;
266
+ const parentId = attr(cell, "parent");
267
+ const parent = parentId ? ids.get(parentId) : undefined;
268
+ if (parent?.getAttribute("vertex") !== "1" || !isVisible(parent, ids)) return null;
269
+ const childBox = absRect(cell, ids);
270
+ const parentBox = absRect(parent, ids);
271
+ if (!childBox || !parentBox) return null;
272
+ const sides = overflowSides(childBox, parentBox);
273
+ if (sides.length === 0) return null;
274
+ return `vertex ${repr(attr(cell, "id"))} extends beyond parent ${repr(parentId)} (${sides.join(", ")})`;
275
+ }
276
+
277
+ function containmentWarnings(cells: DomEl[], ids: ById): string[] {
278
+ return cells
279
+ .map((cell) => containmentWarning(cell, ids))
280
+ .filter((warning): warning is string => warning !== null);
314
281
  }
315
282
 
316
- function checkPage(diagram: DomEl): [string[], string[]] {
283
+ interface PageSettings {
284
+ enabled: boolean;
285
+ width?: number;
286
+ height?: number;
287
+ scale: number;
288
+ }
289
+
290
+ function pageSettings(model: DomEl, warnings: string[], observations: string[]): PageSettings {
291
+ const enabled = attr(model, "page") !== "0";
292
+ if (!enabled) {
293
+ observations.push("page canvas is disabled (infinite canvas); boundary, margin, and empty-space checks skipped");
294
+ return { enabled, scale: 1 };
295
+ }
296
+
297
+ const rawScale = attr(model, "pageScale");
298
+ const parsedScale = rawScale === null ? 1 : pyFloat(rawScale);
299
+ const scale = parsedScale && Number.isFinite(parsedScale) && parsedScale > 0 ? parsedScale : 1;
300
+ if (rawScale !== null && scale !== parsedScale) warnings.push(`invalid pageScale ${repr(rawScale)}; using 1`);
301
+
302
+ const parseDimension = (name: "pageWidth" | "pageHeight"): number | undefined => {
303
+ const raw = attr(model, name);
304
+ if (raw === null) return undefined;
305
+ const value = pyFloat(raw);
306
+ if (value === undefined || !Number.isFinite(value) || value <= 0) {
307
+ warnings.push(`invalid ${name} ${repr(raw)}; page-boundary checks skipped`);
308
+ return undefined;
309
+ }
310
+ return value * scale;
311
+ };
312
+ const width = parseDimension("pageWidth");
313
+ const height = parseDimension("pageHeight");
314
+ if (width === undefined || height === undefined) {
315
+ observations.push(
316
+ "page dimensions are omitted or invalid; boundary, outer-margin, and empty-space checks require both pageWidth and pageHeight",
317
+ );
318
+ }
319
+ return { enabled, width, height, scale };
320
+ }
321
+
322
+ function boundaryWarnings(bounds: ContentBounds, width: number, height: number): string[] {
323
+ const warnings: string[] = [];
324
+ if (bounds.minX < 0) warnings.push(`content extends beyond left page boundary by ${-bounds.minX}px`);
325
+ if (bounds.minY < 0) warnings.push(`content extends beyond top page boundary by ${-bounds.minY}px`);
326
+ if (bounds.maxX > width) warnings.push(`content extends beyond right page boundary by ${bounds.maxX - width}px`);
327
+ if (bounds.maxY > height) warnings.push(`content extends beyond bottom page boundary by ${bounds.maxY - height}px`);
328
+ return warnings;
329
+ }
330
+
331
+ function outerMarginWarning(bounds: ContentBounds, width: number, height: number): string | null {
332
+ const marginSides: string[] = [];
333
+ if (bounds.minX >= 0 && bounds.minX < MIN_OUTER_MARGIN) marginSides.push(`left ${bounds.minX}px`);
334
+ if (bounds.minY >= 0 && bounds.minY < MIN_OUTER_MARGIN) marginSides.push(`top ${bounds.minY}px`);
335
+ const right = width - bounds.maxX;
336
+ const bottom = height - bounds.maxY;
337
+ if (right >= 0 && right < MIN_OUTER_MARGIN) marginSides.push(`right ${right}px`);
338
+ if (bottom >= 0 && bottom < MIN_OUTER_MARGIN) marginSides.push(`bottom ${bottom}px`);
339
+ return marginSides.length > 0
340
+ ? `content outer margin is below ${MIN_OUTER_MARGIN}px (${marginSides.join(", ")})`
341
+ : null;
342
+ }
343
+
344
+ function excessiveCanvasWarning(bounds: ContentBounds, width: number, height: number): string | null {
345
+ const contentWidth = bounds.maxX - bounds.minX;
346
+ const contentHeight = bounds.maxY - bounds.minY;
347
+ if (contentWidth <= 0 || contentHeight <= 0) return null;
348
+ const areaRatio = (width * height) / (contentWidth * contentHeight);
349
+ if (
350
+ areaRatio < EXCESSIVE_CANVAS_AREA_RATIO ||
351
+ contentWidth / width > EXCESSIVE_CANVAS_AXIS_RATIO ||
352
+ contentHeight / height > EXCESSIVE_CANVAS_AXIS_RATIO
353
+ ) {
354
+ return null;
355
+ }
356
+ return `canvas has excessive empty space (content ${contentWidth}x${contentHeight}px within ${width}x${height}px page)`;
357
+ }
358
+
359
+ function canvasWarnings(bounds: ContentBounds | null, settings: PageSettings): string[] {
360
+ if (!bounds || !settings.enabled || settings.width === undefined || settings.height === undefined) return [];
361
+ const { width, height } = settings;
362
+ return [
363
+ ...boundaryWarnings(bounds, width, height),
364
+ outerMarginWarning(bounds, width, height),
365
+ excessiveCanvasWarning(bounds, width, height),
366
+ ].filter((warning): warning is string => warning !== null);
367
+ }
368
+
369
+ function isWhitespace(character: string): boolean {
370
+ return character.trim() === "";
371
+ }
372
+
373
+ function isLineBreakTag(content: string): boolean {
374
+ if (content.slice(0, 2).toLowerCase() !== "br") return false;
375
+ let index = 2;
376
+ while (index < content.length && isWhitespace(content[index])) index++;
377
+ if (content[index] === "/") index++;
378
+ while (index < content.length && isWhitespace(content[index])) index++;
379
+ return index === content.length;
380
+ }
381
+
382
+ /** Remove draw.io's HTML-like label markup in one pass without regex backtracking. */
383
+ function stripLabelMarkup(value: string): string {
384
+ const text: string[] = [];
385
+ let cursor = 0;
386
+ while (cursor < value.length) {
387
+ const open = value.indexOf("<", cursor);
388
+ if (open === -1) {
389
+ text.push(value.slice(cursor));
390
+ break;
391
+ }
392
+ text.push(value.slice(cursor, open));
393
+ const close = value.indexOf(">", open + 1);
394
+ if (close === -1) {
395
+ text.push(value.slice(open));
396
+ break;
397
+ }
398
+ if (close === open + 1) {
399
+ text.push("<");
400
+ cursor = open + 1;
401
+ continue;
402
+ }
403
+ if (isLineBreakTag(value.slice(open + 1, close))) text.push("\n");
404
+ cursor = close + 1;
405
+ }
406
+ return text.join("");
407
+ }
408
+
409
+ function labelText(cell: DomEl): string {
410
+ return stripLabelMarkup(attr(cell, "value") ?? "").replaceAll("&nbsp;", " ").trim();
411
+ }
412
+
413
+ function isCompactBorderPort(cell: DomEl, box: Rect | null): boolean {
414
+ return (
415
+ cell.getAttribute("vertex") === "1" &&
416
+ geometryIsRelative(cell) &&
417
+ !isEdgeLabel(cell) &&
418
+ box !== null &&
419
+ !hasInvalidNumber(box) &&
420
+ box[2] <= 30 &&
421
+ box[3] <= 30
422
+ );
423
+ }
424
+
425
+ function smallFontWarning(cell: DomEl, box: Rect | null): string | null {
426
+ const fontSize = styleNum(attr(cell, "style"), "fontSize");
427
+ const isEdgeText = cell.getAttribute("edge") === "1" || isEdgeLabel(cell);
428
+ const minimum = isEdgeText ? 9 : 10;
429
+ if (
430
+ isCompactBorderPort(cell, box) ||
431
+ fontSize === undefined ||
432
+ !Number.isFinite(fontSize) ||
433
+ fontSize <= 0 ||
434
+ fontSize >= minimum
435
+ ) {
436
+ return null;
437
+ }
438
+ return `${isEdgeText ? "connector label" : "vertex"} ${repr(attr(cell, "id"))} has very small explicit fontSize ${fontSize}px`;
439
+ }
440
+
441
+ function longLabelWarning(cell: DomEl, label: string, box: Rect | null): string | null {
442
+ if (cell.getAttribute("vertex") !== "1" || isEdgeLabel(cell) || geometryIsRelative(cell)) return null;
443
+ if (box === null || hasInvalidNumber(box)) return null;
444
+ const oneLineLength = label.replaceAll("\n", "").length;
445
+ if (
446
+ oneLineLength <= 32 ||
447
+ label.includes("\n") ||
448
+ box[2] >= 160 ||
449
+ styleHas(attr(cell, "style"), "whiteSpace", "wrap")
450
+ ) {
451
+ return null;
452
+ }
453
+ return `vertex ${repr(attr(cell, "id"))} has a long label in narrow geometry without whiteSpace=wrap`;
454
+ }
455
+
456
+ function cellReadabilityWarnings(cell: DomEl): string[] {
457
+ const label = labelText(cell);
458
+ if (!label) return [];
459
+ const box = rect(cell);
460
+ return [smallFontWarning(cell, box), longLabelWarning(cell, label, box)].filter(
461
+ (warning): warning is string => warning !== null,
462
+ );
463
+ }
464
+
465
+ /** Conservative static checks only; uncertain typography remains a visual concern. */
466
+ function readabilityWarnings(cells: DomEl[]): string[] {
467
+ return cells.flatMap(cellReadabilityWarnings);
468
+ }
469
+
470
+ function withPage(name: string, diagnostics: string[]): string[] {
471
+ return diagnostics.map((diagnostic) => `page '${name}': ${diagnostic}`);
472
+ }
473
+
474
+ function checkPage(diagram: DomEl): [string[], string[], string[]] {
317
475
  const name = attr(diagram, "name") ?? "?";
318
476
  const model = firstByTag(diagram, "mxGraphModel");
319
477
  if (!model) {
320
- if (directText(diagram).trim()) return [[], [`page '${name}': compressed, skipped (cannot lint)`]];
321
- return [[`page '${name}': no <mxGraphModel>`], []];
478
+ if (directText(diagram).trim()) return [[], [`page '${name}': compressed, skipped (cannot lint)`], []];
479
+ return [[`page '${name}': no <mxGraphModel>`], [], []];
322
480
  }
323
481
  const cells = collectCells(firstByTag(model, "root"));
324
482
 
325
483
  const errors: string[] = [];
326
- const warns: string[] = [];
484
+ const warnings: string[] = [];
485
+ const observations: string[] = [];
327
486
  const ids = buildIds(cells, errors);
328
487
  const parents = new Set<string | null>();
329
- for (const c of cells) parents.add(attr(c, "parent"));
330
-
331
- for (const c of cells) checkCell(c, ids, errors, warns);
332
- warns.push(...overlapWarnings(cells, parents), ...geometryWarnings(cells, ids, parents));
333
- return [errors, warns];
488
+ for (const cell of cells) parents.add(attr(cell, "parent"));
489
+
490
+ for (const cell of cells) checkCell(cell, ids, errors, warnings);
491
+ warnings.push(
492
+ ...overlapWarnings(cells, ids, parents),
493
+ ...geometryWarnings(cells, ids, parents),
494
+ ...containmentWarnings(cells, ids),
495
+ ...readabilityWarnings(cells),
496
+ );
497
+ const settings = pageSettings(model, warnings, observations);
498
+ warnings.push(...canvasWarnings(contentBounds(cells, ids), settings));
499
+ return [withPage(name, errors), withPage(name, warnings), withPage(name, observations)];
334
500
  }
335
501
 
336
502
  /** Lint a `.drawio` XML string. Throws only on unrecoverable parse failure. */
337
503
  export function validateXml(xml: string): ValidateResult {
338
504
  const doc = new DOMParser().parseFromString(xml, "text/xml");
339
- const rootEl = doc.documentElement as unknown as DomEl | null;
340
- if (!rootEl) throw new Error("no root element (malformed XML)");
341
- const pageList = childrenByTag(rootEl, "diagram");
342
- const pages = pageList.length > 0 ? pageList : [rootEl];
505
+ const root = doc.documentElement as unknown as DomEl | null;
506
+ if (!root) throw new Error("no root element (malformed XML)");
507
+ const pageList = childrenByTag(root, "diagram");
508
+ const pages = pageList.length > 0 ? pageList : [root];
343
509
 
344
510
  const errors: string[] = [];
345
511
  const warnings: string[] = [];
512
+ const observations: string[] = [];
346
513
  for (const page of pages) {
347
- const [e, w] = checkPage(page);
348
- errors.push(...e);
349
- warnings.push(...w);
514
+ const [pageErrors, pageWarnings, pageObservations] = checkPage(page);
515
+ errors.push(...pageErrors);
516
+ warnings.push(...pageWarnings);
517
+ observations.push(...pageObservations);
350
518
  }
351
- const through = warnings.filter((w) => w.includes("routes through")).length;
352
- const crossings = warnings.filter((w) => w.endsWith(" cross")).length;
353
- const overlaps = warnings.filter((w) => w.endsWith(" overlap")).length;
519
+ const through = warnings.filter((warning) => warning.includes("routes through")).length;
520
+ const crossings = warnings.filter((warning) => warning.endsWith(" cross")).length;
521
+ const overlaps = warnings.filter((warning) => warning.endsWith(" overlap")).length;
354
522
  return {
355
523
  errors,
356
524
  warnings,
525
+ observations,
357
526
  score: { total: 20 * through + 10 * crossings + 5 * overlaps, through, crossings, overlaps },
358
527
  };
359
528
  }
360
529
 
530
+ function emptyScore(): ValidateResult["score"] {
531
+ return { total: 0, through: 0, crossings: 0, overlaps: 0 };
532
+ }
533
+
361
534
  /** Read and lint a `.drawio` file. Read/parse failures are returned as errors, never thrown. */
362
535
  export async function validateFile(path: string): Promise<ValidateResult> {
363
- const empty = { total: 0, through: 0, crossings: 0, overlaps: 0 };
364
536
  let xml: string;
365
537
  try {
366
538
  xml = await readFile(path, "utf8");
367
- } catch (e) {
368
- return { errors: [`cannot read ${path}: ${(e as Error).message}`], warnings: [], score: empty };
539
+ } catch (error) {
540
+ return {
541
+ errors: [`cannot read ${path}: ${(error as Error).message}`],
542
+ warnings: [],
543
+ observations: [],
544
+ score: emptyScore(),
545
+ };
369
546
  }
370
547
  try {
371
548
  return validateXml(xml);
372
- } catch (e) {
373
- return { errors: [`cannot parse ${path}: ${(e as Error).message}`], warnings: [], score: empty };
549
+ } catch (error) {
550
+ return {
551
+ errors: [`cannot parse ${path}: ${(error as Error).message}`],
552
+ warnings: [],
553
+ observations: [],
554
+ score: emptyScore(),
555
+ };
374
556
  }
375
557
  }