@senad-d/drawme 0.1.2 → 0.1.4

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,24 +1,28 @@
1
1
  /**
2
- * Deterministic structural linter for `.drawio` files — a pure-TypeScript port of
3
- * the skill's `scripts/validate.py`. Catches the class of mistakes a vision
4
- * self-check is slow and unreliable at: dangling edge endpoints, duplicate or
5
- * reserved ids, broken parent references, and (as warnings) off-grid geometry,
6
- * overlapping sibling nodes, and edge-routing defects. Runs without launching
7
- * draw.io. Local-only, no network.
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.
8
6
  */
9
7
  import { readFile } from "node:fs/promises";
10
8
  import { DOMParser } from "@xmldom/xmldom";
11
9
  import { type DomEl, attr, childrenByTag, directText, elemChildren, firstByTag } from "./dom";
12
10
 
13
11
  const RESERVED = new Set(["0", "1"]);
12
+ export const MIN_OUTER_MARGIN = 20;
13
+ const EXCESSIVE_CANVAS_AREA_RATIO = 4;
14
+ const EXCESSIVE_CANVAS_AXIS_RATIO = 0.6;
14
15
 
15
16
  /** [x, y, width, height]. width/height may be NaN when the source omits them. */
16
17
  type Rect = [number, number, number, number];
18
+ type Point = [number, number];
17
19
  type ById = Map<string, DomEl>;
18
20
 
19
21
  export interface ValidateResult {
20
22
  errors: string[];
21
23
  warnings: string[];
24
+ /** Informational limitations/settings that do not require a source correction. */
25
+ observations: string[];
22
26
  /** Readability score (lower is better); comparable only across variants of the same graph. */
23
27
  score: { total: number; through: number; crossings: number; overlaps: number };
24
28
  }
@@ -34,7 +38,7 @@ function pyFloat(s: string): number | undefined {
34
38
  return Number.isNaN(n) ? undefined : n;
35
39
  }
36
40
 
37
- /** Python `repr()` of an optional attribute, for message parity with validate.py. */
41
+ /** Quote an optional attribute consistently in diagnostic messages. */
38
42
  function repr(s: string | null): string {
39
43
  return s === null ? "None" : `'${s}'`;
40
44
  }
@@ -50,15 +54,30 @@ function rect(cell: DomEl): Rect | null {
50
54
  return [x, y, w, h];
51
55
  }
52
56
 
53
- function hasNaN(r: Rect): boolean {
54
- return r.some((v) => Number.isNaN(v));
57
+ function hasInvalidNumber(values: number[]): boolean {
58
+ return values.some((value) => !Number.isFinite(value));
59
+ }
60
+
61
+ function geometryIsRelative(cell: DomEl): boolean {
62
+ return firstByTag(cell, "mxGeometry")?.getAttribute("relative") === "1";
55
63
  }
56
64
 
57
- /** True for edge labels / relative-positioned child vertices (they legitimately omit w/h). */
65
+ /** True for separate edge-label vertices. */
58
66
  function isEdgeLabel(cell: DomEl): boolean {
59
- if ((attr(cell, "style") ?? "").includes("edgeLabel")) return true;
60
- const gy = firstByTag(cell, "mxGeometry");
61
- return gy !== null && gy.getAttribute("relative") === "1";
67
+ return (attr(cell, "style") ?? "").includes("edgeLabel");
68
+ }
69
+
70
+ function isVisible(cell: DomEl, byId: ById): boolean {
71
+ let current: DomEl | undefined = cell;
72
+ const seen = new Set<string>();
73
+ while (current) {
74
+ if (attr(current, "visible") === "0") return false;
75
+ const parent = attr(current, "parent");
76
+ if (!parent || seen.has(parent)) break;
77
+ seen.add(parent);
78
+ current = byId.get(parent);
79
+ }
80
+ return true;
62
81
  }
63
82
 
64
83
  function overlap(a: Rect, b: Rect): boolean {
@@ -74,10 +93,14 @@ function styleNum(style: string | null, key: string): number | undefined {
74
93
  return undefined;
75
94
  }
76
95
 
77
- /** Absolute (x, y, w, h) of a vertex, summing parent-container offsets. */
96
+ function styleHas(style: string | null, key: string, expected: string): boolean {
97
+ return (style ?? "").split(";").includes(`${key}=${expected}`);
98
+ }
99
+
100
+ /** Absolute (x, y, w, h) of a non-relative vertex, summing parent-container offsets. */
78
101
  function absRect(cell: DomEl, byId: ById): Rect | null {
79
102
  const r = rect(cell);
80
- if (r === null || hasNaN(r)) return null;
103
+ if (r === null || hasInvalidNumber(r)) return null;
81
104
  let [x, y] = r;
82
105
  const [, , w, h] = r;
83
106
  let parent = attr(cell, "parent");
@@ -85,9 +108,9 @@ function absRect(cell: DomEl, byId: ById): Rect | null {
85
108
  while (parent && byId.has(parent) && !seen.has(parent)) {
86
109
  seen.add(parent);
87
110
  const p = byId.get(parent)!;
88
- if (p.getAttribute("vertex") === "1") {
111
+ if (p.getAttribute("vertex") === "1" && !geometryIsRelative(p)) {
89
112
  const pr = rect(p);
90
- if (pr && !hasNaN(pr)) {
113
+ if (pr && !hasInvalidNumber(pr)) {
91
114
  x += pr[0];
92
115
  y += pr[1];
93
116
  }
@@ -97,8 +120,6 @@ function absRect(cell: DomEl, byId: ById): Rect | null {
97
120
  return [x, y, w, h];
98
121
  }
99
122
 
100
- type Point = [number, number];
101
-
102
123
  /** Absolute point where `edge` meets its source/target vertex (honours exit/entry). */
103
124
  function endpoint(edge: DomEl, end: "source" | "target", byId: ById): Point | null {
104
125
  const vid = attr(edge, end);
@@ -117,33 +138,73 @@ function edgeWaypoints(edge: DomEl): Point[] {
117
138
  if (!gy) return [];
118
139
  const arr = firstByTag(gy, "Array");
119
140
  if (!arr) return [];
120
- const pts: Point[] = [];
121
- for (const pt of childrenByTag(arr, "mxPoint")) {
122
- const px = attr(pt, "x");
123
- const py = attr(pt, "y");
124
- if (px !== null && py !== null) {
125
- const nx = pyFloat(px);
126
- const ny = pyFloat(py);
127
- if (nx !== undefined && ny !== undefined) pts.push([nx, ny]);
128
- }
141
+ const points: Point[] = [];
142
+ for (const point of childrenByTag(arr, "mxPoint")) {
143
+ const x = pyFloat(attr(point, "x") ?? "");
144
+ const y = pyFloat(attr(point, "y") ?? "");
145
+ if (x !== undefined && y !== undefined && Number.isFinite(x) && Number.isFinite(y)) points.push([x, y]);
129
146
  }
130
- return pts;
147
+ return points;
131
148
  }
132
149
 
133
150
  /** Absolute polyline for a waypointed edge, or null when auto-routed / unresolved. */
134
151
  function edgeRoute(edge: DomEl, byId: ById): Point[] | null {
135
- const wp = edgeWaypoints(edge);
136
- if (wp.length === 0) return null;
137
- const s = endpoint(edge, "source", byId);
138
- const t = endpoint(edge, "target", byId);
139
- if (s === null || t === null) return null;
140
- return [s, ...wp, t];
152
+ const waypoints = edgeWaypoints(edge);
153
+ if (waypoints.length === 0) return null;
154
+ const source = endpoint(edge, "source", byId);
155
+ const target = endpoint(edge, "target", byId);
156
+ if (source === null || target === null) return null;
157
+ return [source, ...waypoints, target];
158
+ }
159
+
160
+ function routeMidpoint(points: Point[]): Point {
161
+ const lengths: number[] = [];
162
+ let total = 0;
163
+ for (let i = 0; i < points.length - 1; i++) {
164
+ const length = Math.hypot(points[i + 1][0] - points[i][0], points[i + 1][1] - points[i][1]);
165
+ lengths.push(length);
166
+ total += length;
167
+ }
168
+ let remaining = total / 2;
169
+ for (let i = 0; i < lengths.length; i++) {
170
+ if (remaining <= lengths[i]) {
171
+ const fraction = lengths[i] === 0 ? 0 : remaining / lengths[i];
172
+ return [
173
+ points[i][0] + fraction * (points[i + 1][0] - points[i][0]),
174
+ points[i][1] + fraction * (points[i + 1][1] - points[i][1]),
175
+ ];
176
+ }
177
+ remaining -= lengths[i];
178
+ }
179
+ return points.at(-1) ?? [0, 0];
180
+ }
181
+
182
+ /** Conservative box for a separately sized label on an explicitly routed edge. */
183
+ function explicitEdgeLabelRect(cell: DomEl, byId: ById): Rect | null {
184
+ if (!isEdgeLabel(cell)) return null;
185
+ const local = rect(cell);
186
+ const parent = attr(cell, "parent");
187
+ const edge = parent ? byId.get(parent) : undefined;
188
+ if (!local || hasInvalidNumber(local) || edge?.getAttribute("edge") !== "1") return null;
189
+ const route = edgeRoute(edge, byId);
190
+ if (!route) return null;
191
+ const [midX, midY] = routeMidpoint(route);
192
+ const geometry = firstByTag(cell, "mxGeometry");
193
+ const offset = geometry
194
+ ? childrenByTag(geometry, "mxPoint").find((point) => attr(point, "as") === "offset")
195
+ : undefined;
196
+ const offsetX = offset ? pyFloat(attr(offset, "x") ?? "0") : 0;
197
+ const offsetY = offset ? pyFloat(attr(offset, "y") ?? "0") : 0;
198
+ if (offsetX === undefined || offsetY === undefined || !Number.isFinite(offsetX) || !Number.isFinite(offsetY)) {
199
+ return null;
200
+ }
201
+ return [midX + offsetX - local[2] / 2, midY + offsetY - local[3] / 2, local[2], local[3]];
141
202
  }
142
203
 
143
204
  function orient(a: Point, b: Point, c: Point): number {
144
- const v = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
145
- if (Math.abs(v) < 1e-9) return 0;
146
- return v > 0 ? 1 : -1;
205
+ const value = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
206
+ if (Math.abs(value) < 1e-9) return 0;
207
+ return value > 0 ? 1 : -1;
147
208
  }
148
209
 
149
210
  function segmentsCross(p1: Point, p2: Point, p3: Point, p4: Point): boolean {
@@ -154,9 +215,9 @@ function segmentsCross(p1: Point, p2: Point, p3: Point, p4: Point): boolean {
154
215
  return o1 !== o2 && o3 !== o4 && ![o1, o2, o3, o4].includes(0);
155
216
  }
156
217
 
157
- function pointInRect(p: Point, box: Rect, eps = 1e-6): boolean {
218
+ function pointInRect(point: Point, box: Rect, epsilon = 1e-6): boolean {
158
219
  const [x, y, w, h] = box;
159
- return x + eps < p[0] && p[0] < x + w - eps && y + eps < p[1] && p[1] < y + h - eps;
220
+ return x + epsilon < point[0] && point[0] < x + w - epsilon && y + epsilon < point[1] && point[1] < y + h - epsilon;
160
221
  }
161
222
 
162
223
  function routeHitsRect(points: Point[], box: Rect): boolean {
@@ -167,20 +228,20 @@ function routeHitsRect(points: Point[], box: Rect): boolean {
167
228
  [x + w, y + h],
168
229
  [x, y + h],
169
230
  ];
170
- const borders: [Point, Point][] = corners.map((c, i) => [c, corners[(i + 1) % 4]]);
231
+ const borders: [Point, Point][] = corners.map((corner, index) => [corner, corners[(index + 1) % 4]]);
171
232
  for (let i = 0; i < points.length - 1; i++) {
172
- const a = points[i];
173
- const b = points[i + 1];
174
- if (pointInRect(a, box) || pointInRect(b, box)) return true;
175
- for (const [c, d] of borders) if (segmentsCross(a, b, c, d)) return true;
233
+ const start = points[i];
234
+ const end = points[i + 1];
235
+ if (pointInRect(start, box) || pointInRect(end, box)) return true;
236
+ for (const [a, b] of borders) if (segmentsCross(start, end, a, b)) return true;
176
237
  }
177
238
  return false;
178
239
  }
179
240
 
180
- function routesCross(pa: Point[], pb: Point[]): boolean {
181
- for (let i = 0; i < pa.length - 1; i++)
182
- for (let j = 0; j < pb.length - 1; j++)
183
- if (segmentsCross(pa[i], pa[i + 1], pb[j], pb[j + 1])) return true;
241
+ function routesCross(a: Point[], b: Point[]): boolean {
242
+ for (let i = 0; i < a.length - 1; i++)
243
+ for (let j = 0; j < b.length - 1; j++)
244
+ if (segmentsCross(a[i], a[i + 1], b[j], b[j + 1])) return true;
184
245
  return false;
185
246
  }
186
247
 
@@ -190,10 +251,10 @@ type LeafBox = [string | null, Rect];
190
251
  /** Edges with a resolvable waypointed route, tagged with their id and endpoint ids. */
191
252
  function collectRoutedEdges(cells: DomEl[], ids: ById): RoutedEdge[] {
192
253
  const routed: RoutedEdge[] = [];
193
- for (const c of cells) {
194
- if (c.getAttribute("edge") === "1") {
195
- const pts = edgeRoute(c, ids);
196
- if (pts) routed.push([attr(c, "id"), pts, new Set([attr(c, "source"), attr(c, "target")])]);
254
+ for (const cell of cells) {
255
+ if (cell.getAttribute("edge") === "1" && isVisible(cell, ids)) {
256
+ const points = edgeRoute(cell, ids);
257
+ if (points) routed.push([attr(cell, "id"), points, new Set([attr(cell, "source"), attr(cell, "target")])]);
197
258
  }
198
259
  }
199
260
  return routed;
@@ -202,33 +263,43 @@ function collectRoutedEdges(cells: DomEl[], ids: ById): RoutedEdge[] {
202
263
  /** Absolute boxes of leaf vertices (real nodes, not containers or edge labels). */
203
264
  function collectLeafBoxes(cells: DomEl[], ids: ById, parents: Set<string | null>): LeafBox[] {
204
265
  const leaves: LeafBox[] = [];
205
- for (const c of cells) {
206
- if (c.getAttribute("vertex") === "1" && !parents.has(attr(c, "id")) && !isEdgeLabel(c)) {
207
- const box = absRect(c, ids);
208
- if (box) leaves.push([attr(c, "id"), box]);
266
+ for (const cell of cells) {
267
+ if (
268
+ cell.getAttribute("vertex") === "1" &&
269
+ !parents.has(attr(cell, "id")) &&
270
+ !isEdgeLabel(cell) &&
271
+ !geometryIsRelative(cell) &&
272
+ isVisible(cell, ids)
273
+ ) {
274
+ const box = absRect(cell, ids);
275
+ if (box) leaves.push([attr(cell, "id"), box]);
209
276
  }
210
277
  }
211
278
  return leaves;
212
279
  }
213
280
 
214
281
  function routeThroughWarnings(routed: RoutedEdge[], leaves: LeafBox[]): string[] {
215
- const warns: string[] = [];
216
- for (const [eid, pts, ends] of routed) {
217
- for (const [vid, box] of leaves) {
218
- if (!ends.has(vid) && routeHitsRect(pts, box)) warns.push(`edge ${repr(eid)} routes through vertex ${repr(vid)}`);
282
+ const warnings: string[] = [];
283
+ for (const [edgeId, points, ends] of routed) {
284
+ for (const [vertexId, box] of leaves) {
285
+ if (!ends.has(vertexId) && routeHitsRect(points, box)) {
286
+ warnings.push(`edge ${repr(edgeId)} routes through vertex ${repr(vertexId)}`);
287
+ }
219
288
  }
220
289
  }
221
- return warns;
290
+ return warnings;
222
291
  }
223
292
 
224
293
  function routeCrossWarnings(routed: RoutedEdge[]): string[] {
225
- const warns: string[] = [];
294
+ const warnings: string[] = [];
226
295
  for (let i = 0; i < routed.length; i++) {
227
296
  for (let j = i + 1; j < routed.length; j++) {
228
- if (routesCross(routed[i][1], routed[j][1])) warns.push(`edges ${repr(routed[i][0])} and ${repr(routed[j][0])} cross`);
297
+ if (routesCross(routed[i][1], routed[j][1])) {
298
+ warnings.push(`edges ${repr(routed[i][0])} and ${repr(routed[j][0])} cross`);
299
+ }
229
300
  }
230
301
  }
231
- return warns;
302
+ return warnings;
232
303
  }
233
304
 
234
305
  function geometryWarnings(cells: DomEl[], ids: ById, parents: Set<string | null>): string[] {
@@ -237,10 +308,7 @@ function geometryWarnings(cells: DomEl[], ids: ById, parents: Set<string | null>
237
308
  return [...routeThroughWarnings(routed, leaves), ...routeCrossWarnings(routed)];
238
309
  }
239
310
 
240
- /**
241
- * Fold UserObject/object wrappers (links & metadata) into their inner mxCell so
242
- * the wrapper id resolves for edges that reference it.
243
- */
311
+ /** Fold UserObject/object wrappers into their inner mxCell so wrapper ids resolve. */
244
312
  function collectCells(root: DomEl | null): DomEl[] {
245
313
  const cells: DomEl[] = [];
246
314
  for (const child of root ? elemChildren(root) : []) {
@@ -259,118 +327,438 @@ function collectCells(root: DomEl | null): DomEl[] {
259
327
  /** Map every cell by id (blank key for id-less cells); report duplicate ids as errors. */
260
328
  function buildIds(cells: DomEl[], errors: string[]): ById {
261
329
  const ids: ById = new Map();
262
- for (const c of cells) {
263
- const cid = attr(c, "id");
264
- if (cid !== null && ids.has(cid)) errors.push(`duplicate id ${repr(cid)}`);
265
- ids.set(cid ?? "", c);
330
+ for (const cell of cells) {
331
+ const id = attr(cell, "id");
332
+ if (id !== null && ids.has(id)) errors.push(`duplicate id ${repr(id)}`);
333
+ ids.set(id ?? "", cell);
266
334
  }
267
335
  return ids;
268
336
  }
269
337
 
270
- /** Geometry checks for a single non-edge-label vertex. */
271
- function checkVertexGeometry(c: DomEl, cid: string | null, errors: string[], warns: string[]): void {
272
- const r = rect(c);
273
- if (r === null || hasNaN(r)) {
274
- errors.push(`vertex ${repr(cid)} has missing/invalid geometry`);
338
+ /** Geometry checks for a single non-edge-label, non-relative vertex. */
339
+ function checkVertexGeometry(cell: DomEl, id: string | null, errors: string[], warnings: string[]): void {
340
+ const box = rect(cell);
341
+ if (box === null || hasInvalidNumber(box)) {
342
+ errors.push(`vertex ${repr(id)} has missing/invalid geometry`);
275
343
  return;
276
344
  }
277
- const [x, y, w, h] = r;
278
- if (w <= 0 || h <= 0) warns.push(`vertex ${repr(cid)} non-positive size ${String(w)}x${String(h)}`);
279
- if (x < 0 || y < 0) warns.push(`vertex ${repr(cid)} negative position (${String(x)},${String(y)})`);
280
- }
281
-
282
- /** Per-cell reference and geometry checks (parents, edge endpoints, reserved ids, geometry). */
283
- function checkCell(c: DomEl, ids: ById, errors: string[], warns: string[]): void {
284
- const cid = attr(c, "id");
285
- const parent = attr(c, "parent");
286
- const isV = c.getAttribute("vertex") === "1";
287
- const isE = c.getAttribute("edge") === "1";
288
- if (parent !== null && !ids.has(parent)) errors.push(`cell ${repr(cid)} parent ${repr(parent)} does not exist`);
345
+ const [x, y, width, height] = box;
346
+ if (width <= 0 || height <= 0) warnings.push(`vertex ${repr(id)} non-positive size ${String(width)}x${String(height)}`);
347
+ if (x < 0 || y < 0) warnings.push(`vertex ${repr(id)} negative position (${String(x)},${String(y)})`);
348
+ }
349
+
350
+ function checkEdgeGeometry(cell: DomEl, id: string | null, errors: string[]): void {
351
+ const geometry = firstByTag(cell, "mxGeometry");
352
+ if (!geometry) {
353
+ errors.push(`edge ${repr(id)} has missing geometry`);
354
+ return;
355
+ }
356
+ if (attr(geometry, "relative") !== "1" || attr(geometry, "as") !== "geometry") {
357
+ errors.push(`edge ${repr(id)} geometry must have relative='1' and as='geometry'`);
358
+ }
359
+ }
360
+
361
+ function checkCellReferences(cell: DomEl, id: string | null, ids: ById, errors: string[]): void {
362
+ const parent = attr(cell, "parent");
363
+ if (parent !== null && !ids.has(parent)) errors.push(`cell ${repr(id)} parent ${repr(parent)} does not exist`);
289
364
  for (const end of ["source", "target"] as const) {
290
- const ref = attr(c, end);
291
- if (ref && !ids.has(ref)) errors.push(`edge ${repr(cid)} ${end} ${repr(ref)} does not exist`);
365
+ const reference = attr(cell, end);
366
+ if (reference && !ids.has(reference)) errors.push(`edge ${repr(id)} ${end} ${repr(reference)} does not exist`);
292
367
  }
293
- if ((isV || isE) && cid !== null && RESERVED.has(cid)) errors.push(`cell ${repr(cid)} reuses reserved id 0/1`);
294
- if (isV && !isEdgeLabel(c)) checkVertexGeometry(c, cid, errors, warns);
295
368
  }
296
369
 
297
- /** Sibling overlap: leaf vertices only (containers legitimately wrap children). */
298
- function overlapWarnings(cells: DomEl[], parents: Set<string | null>): string[] {
370
+ /** Per-cell reference and geometry checks. */
371
+ function checkCell(cell: DomEl, ids: ById, errors: string[], warnings: string[]): void {
372
+ const id = attr(cell, "id");
373
+ const isVertex = cell.getAttribute("vertex") === "1";
374
+ const isEdge = cell.getAttribute("edge") === "1";
375
+ checkCellReferences(cell, id, ids, errors);
376
+ if ((isVertex || isEdge) && id !== null && RESERVED.has(id)) errors.push(`cell ${repr(id)} reuses reserved id 0/1`);
377
+ if (isVertex && !isEdgeLabel(cell) && !geometryIsRelative(cell)) checkVertexGeometry(cell, id, errors, warnings);
378
+ if (isEdge) checkEdgeGeometry(cell, id, errors);
379
+ }
380
+
381
+ /** Sibling overlap: visible leaf vertices only (containers legitimately wrap children). */
382
+ function overlapWarnings(cells: DomEl[], ids: ById, parents: Set<string | null>): string[] {
299
383
  const boxes: [string | null, string | null, Rect][] = [];
300
- for (const c of cells) {
301
- if (c.getAttribute("vertex") === "1" && !parents.has(attr(c, "id"))) {
302
- const r = rect(c);
303
- if (r && !hasNaN(r)) boxes.push([attr(c, "id"), attr(c, "parent"), r]);
384
+ for (const cell of cells) {
385
+ if (
386
+ cell.getAttribute("vertex") === "1" &&
387
+ !parents.has(attr(cell, "id")) &&
388
+ !isEdgeLabel(cell) &&
389
+ !geometryIsRelative(cell) &&
390
+ isVisible(cell, ids)
391
+ ) {
392
+ const box = rect(cell);
393
+ if (box && !hasInvalidNumber(box)) boxes.push([attr(cell, "id"), attr(cell, "parent"), box]);
304
394
  }
305
395
  }
306
- const warns: string[] = [];
396
+ const warnings: string[] = [];
307
397
  for (let i = 0; i < boxes.length; i++) {
308
398
  for (let j = i + 1; j < boxes.length; j++) {
309
- const [ia, pa, ra] = boxes[i];
310
- const [ib, pb, rb] = boxes[j];
311
- if (pa === pb && overlap(ra, rb)) warns.push(`vertices ${repr(ia)} and ${repr(ib)} overlap`);
399
+ const [aId, aParent, a] = boxes[i];
400
+ const [bId, bParent, b] = boxes[j];
401
+ if (aParent === bParent && overlap(a, b)) warnings.push(`vertices ${repr(aId)} and ${repr(bId)} overlap`);
312
402
  }
313
403
  }
314
- return warns;
404
+ return warnings;
405
+ }
406
+
407
+ function isContainmentCandidate(cell: DomEl, ids: ById): boolean {
408
+ return (
409
+ cell.getAttribute("vertex") === "1" &&
410
+ !geometryIsRelative(cell) &&
411
+ !isEdgeLabel(cell) &&
412
+ isVisible(cell, ids)
413
+ );
414
+ }
415
+
416
+ function overflowSides(childBox: Rect, parentBox: Rect): string[] {
417
+ const [x, y, width, height] = childBox;
418
+ const [px, py, parentWidth, parentHeight] = parentBox;
419
+ const sides: string[] = [];
420
+ if (x < px) sides.push("left");
421
+ if (y < py) sides.push("top");
422
+ if (x + width > px + parentWidth) sides.push("right");
423
+ if (y + height > py + parentHeight) sides.push("bottom");
424
+ return sides;
425
+ }
426
+
427
+ function containmentWarning(cell: DomEl, ids: ById): string | null {
428
+ if (!isContainmentCandidate(cell, ids)) return null;
429
+ const parentId = attr(cell, "parent");
430
+ const parent = parentId ? ids.get(parentId) : undefined;
431
+ if (parent?.getAttribute("vertex") !== "1" || !isVisible(parent, ids)) return null;
432
+ const childBox = absRect(cell, ids);
433
+ const parentBox = absRect(parent, ids);
434
+ if (!childBox || !parentBox) return null;
435
+ const sides = overflowSides(childBox, parentBox);
436
+ if (sides.length === 0) return null;
437
+ return `vertex ${repr(attr(cell, "id"))} extends beyond parent ${repr(parentId)} (${sides.join(", ")})`;
438
+ }
439
+
440
+ function containmentWarnings(cells: DomEl[], ids: ById): string[] {
441
+ return cells
442
+ .map((cell) => containmentWarning(cell, ids))
443
+ .filter((warning): warning is string => warning !== null);
444
+ }
445
+
446
+ interface ContentBounds {
447
+ minX: number;
448
+ minY: number;
449
+ maxX: number;
450
+ maxY: number;
451
+ }
452
+
453
+ function addRectToBounds(bounds: ContentBounds | null, box: Rect): ContentBounds {
454
+ const [x, y, width, height] = box;
455
+ const next = bounds ?? { minX: x, minY: y, maxX: x + width, maxY: y + height };
456
+ next.minX = Math.min(next.minX, x);
457
+ next.minY = Math.min(next.minY, y);
458
+ next.maxX = Math.max(next.maxX, x + width);
459
+ next.maxY = Math.max(next.maxY, y + height);
460
+ return next;
461
+ }
462
+
463
+ function addPointToBounds(bounds: ContentBounds | null, point: Point): ContentBounds {
464
+ return addRectToBounds(bounds, [point[0], point[1], 0, 0]);
465
+ }
466
+
467
+ function contentRect(cell: DomEl, ids: ById): Rect | null {
468
+ if (cell.getAttribute("vertex") !== "1") return null;
469
+ if (isEdgeLabel(cell)) return explicitEdgeLabelRect(cell, ids);
470
+ if (geometryIsRelative(cell)) return null;
471
+ return absRect(cell, ids);
315
472
  }
316
473
 
317
- function checkPage(diagram: DomEl): [string[], string[]] {
474
+ function contentWaypoints(cell: DomEl): Point[] {
475
+ return cell.getAttribute("edge") === "1" ? edgeWaypoints(cell) : [];
476
+ }
477
+
478
+ /** Visible vertices/containers, practical edge-label boxes, and explicit waypoints. */
479
+ function contentBounds(cells: DomEl[], ids: ById): ContentBounds | null {
480
+ let bounds: ContentBounds | null = null;
481
+ for (const cell of cells) {
482
+ if (!isVisible(cell, ids)) continue;
483
+ const box = contentRect(cell, ids);
484
+ if (box && !hasInvalidNumber(box)) bounds = addRectToBounds(bounds, box);
485
+ for (const point of contentWaypoints(cell)) bounds = addPointToBounds(bounds, point);
486
+ }
487
+ return bounds;
488
+ }
489
+
490
+ interface PageSettings {
491
+ enabled: boolean;
492
+ width?: number;
493
+ height?: number;
494
+ scale: number;
495
+ }
496
+
497
+ function pageSettings(model: DomEl, warnings: string[], observations: string[]): PageSettings {
498
+ const enabled = attr(model, "page") !== "0";
499
+ if (!enabled) {
500
+ observations.push("page canvas is disabled (infinite canvas); boundary, margin, and empty-space checks skipped");
501
+ return { enabled, scale: 1 };
502
+ }
503
+
504
+ const rawScale = attr(model, "pageScale");
505
+ const parsedScale = rawScale === null ? 1 : pyFloat(rawScale);
506
+ const scale = parsedScale && Number.isFinite(parsedScale) && parsedScale > 0 ? parsedScale : 1;
507
+ if (rawScale !== null && scale !== parsedScale) warnings.push(`invalid pageScale ${repr(rawScale)}; using 1`);
508
+
509
+ const parseDimension = (name: "pageWidth" | "pageHeight"): number | undefined => {
510
+ const raw = attr(model, name);
511
+ if (raw === null) return undefined;
512
+ const value = pyFloat(raw);
513
+ if (value === undefined || !Number.isFinite(value) || value <= 0) {
514
+ warnings.push(`invalid ${name} ${repr(raw)}; page-boundary checks skipped`);
515
+ return undefined;
516
+ }
517
+ return value * scale;
518
+ };
519
+ const width = parseDimension("pageWidth");
520
+ const height = parseDimension("pageHeight");
521
+ if (width === undefined || height === undefined) {
522
+ observations.push(
523
+ "page dimensions are omitted or invalid; boundary, outer-margin, and empty-space checks require both pageWidth and pageHeight",
524
+ );
525
+ }
526
+ return { enabled, width, height, scale };
527
+ }
528
+
529
+ function boundaryWarnings(bounds: ContentBounds, width: number, height: number): string[] {
530
+ const warnings: string[] = [];
531
+ if (bounds.minX < 0) warnings.push(`content extends beyond left page boundary by ${-bounds.minX}px`);
532
+ if (bounds.minY < 0) warnings.push(`content extends beyond top page boundary by ${-bounds.minY}px`);
533
+ if (bounds.maxX > width) warnings.push(`content extends beyond right page boundary by ${bounds.maxX - width}px`);
534
+ if (bounds.maxY > height) warnings.push(`content extends beyond bottom page boundary by ${bounds.maxY - height}px`);
535
+ return warnings;
536
+ }
537
+
538
+ function outerMarginWarning(bounds: ContentBounds, width: number, height: number): string | null {
539
+ const marginSides: string[] = [];
540
+ if (bounds.minX >= 0 && bounds.minX < MIN_OUTER_MARGIN) marginSides.push(`left ${bounds.minX}px`);
541
+ if (bounds.minY >= 0 && bounds.minY < MIN_OUTER_MARGIN) marginSides.push(`top ${bounds.minY}px`);
542
+ const right = width - bounds.maxX;
543
+ const bottom = height - bounds.maxY;
544
+ if (right >= 0 && right < MIN_OUTER_MARGIN) marginSides.push(`right ${right}px`);
545
+ if (bottom >= 0 && bottom < MIN_OUTER_MARGIN) marginSides.push(`bottom ${bottom}px`);
546
+ return marginSides.length > 0
547
+ ? `content outer margin is below ${MIN_OUTER_MARGIN}px (${marginSides.join(", ")})`
548
+ : null;
549
+ }
550
+
551
+ function excessiveCanvasWarning(bounds: ContentBounds, width: number, height: number): string | null {
552
+ const contentWidth = bounds.maxX - bounds.minX;
553
+ const contentHeight = bounds.maxY - bounds.minY;
554
+ if (contentWidth <= 0 || contentHeight <= 0) return null;
555
+ const areaRatio = (width * height) / (contentWidth * contentHeight);
556
+ if (
557
+ areaRatio < EXCESSIVE_CANVAS_AREA_RATIO ||
558
+ contentWidth / width > EXCESSIVE_CANVAS_AXIS_RATIO ||
559
+ contentHeight / height > EXCESSIVE_CANVAS_AXIS_RATIO
560
+ ) {
561
+ return null;
562
+ }
563
+ return `canvas has excessive empty space (content ${contentWidth}x${contentHeight}px within ${width}x${height}px page)`;
564
+ }
565
+
566
+ function canvasWarnings(bounds: ContentBounds | null, settings: PageSettings): string[] {
567
+ if (!bounds || !settings.enabled || settings.width === undefined || settings.height === undefined) return [];
568
+ const { width, height } = settings;
569
+ return [
570
+ ...boundaryWarnings(bounds, width, height),
571
+ outerMarginWarning(bounds, width, height),
572
+ excessiveCanvasWarning(bounds, width, height),
573
+ ].filter((warning): warning is string => warning !== null);
574
+ }
575
+
576
+ function isWhitespace(character: string): boolean {
577
+ return character.trim() === "";
578
+ }
579
+
580
+ function isLineBreakTag(content: string): boolean {
581
+ if (content.slice(0, 2).toLowerCase() !== "br") return false;
582
+ let index = 2;
583
+ while (index < content.length && isWhitespace(content[index])) index++;
584
+ if (content[index] === "/") index++;
585
+ while (index < content.length && isWhitespace(content[index])) index++;
586
+ return index === content.length;
587
+ }
588
+
589
+ /** Remove draw.io's HTML-like label markup in one pass without regex backtracking. */
590
+ function stripLabelMarkup(value: string): string {
591
+ const text: string[] = [];
592
+ let cursor = 0;
593
+ while (cursor < value.length) {
594
+ const open = value.indexOf("<", cursor);
595
+ if (open === -1) {
596
+ text.push(value.slice(cursor));
597
+ break;
598
+ }
599
+ text.push(value.slice(cursor, open));
600
+ const close = value.indexOf(">", open + 1);
601
+ if (close === -1) {
602
+ text.push(value.slice(open));
603
+ break;
604
+ }
605
+ if (close === open + 1) {
606
+ text.push("<");
607
+ cursor = open + 1;
608
+ continue;
609
+ }
610
+ if (isLineBreakTag(value.slice(open + 1, close))) text.push("\n");
611
+ cursor = close + 1;
612
+ }
613
+ return text.join("");
614
+ }
615
+
616
+ function labelText(cell: DomEl): string {
617
+ return stripLabelMarkup(attr(cell, "value") ?? "").replaceAll("&nbsp;", " ").trim();
618
+ }
619
+
620
+ function isCompactBorderPort(cell: DomEl, box: Rect | null): boolean {
621
+ return (
622
+ cell.getAttribute("vertex") === "1" &&
623
+ geometryIsRelative(cell) &&
624
+ !isEdgeLabel(cell) &&
625
+ box !== null &&
626
+ !hasInvalidNumber(box) &&
627
+ box[2] <= 30 &&
628
+ box[3] <= 30
629
+ );
630
+ }
631
+
632
+ function smallFontWarning(cell: DomEl, box: Rect | null): string | null {
633
+ const fontSize = styleNum(attr(cell, "style"), "fontSize");
634
+ const isEdgeText = cell.getAttribute("edge") === "1" || isEdgeLabel(cell);
635
+ const minimum = isEdgeText ? 9 : 10;
636
+ if (
637
+ isCompactBorderPort(cell, box) ||
638
+ fontSize === undefined ||
639
+ !Number.isFinite(fontSize) ||
640
+ fontSize <= 0 ||
641
+ fontSize >= minimum
642
+ ) {
643
+ return null;
644
+ }
645
+ return `${isEdgeText ? "connector label" : "vertex"} ${repr(attr(cell, "id"))} has very small explicit fontSize ${fontSize}px`;
646
+ }
647
+
648
+ function longLabelWarning(cell: DomEl, label: string, box: Rect | null): string | null {
649
+ if (cell.getAttribute("vertex") !== "1" || isEdgeLabel(cell) || geometryIsRelative(cell)) return null;
650
+ if (box === null || hasInvalidNumber(box)) return null;
651
+ const oneLineLength = label.replaceAll("\n", "").length;
652
+ if (
653
+ oneLineLength <= 32 ||
654
+ label.includes("\n") ||
655
+ box[2] >= 160 ||
656
+ styleHas(attr(cell, "style"), "whiteSpace", "wrap")
657
+ ) {
658
+ return null;
659
+ }
660
+ return `vertex ${repr(attr(cell, "id"))} has a long label in narrow geometry without whiteSpace=wrap`;
661
+ }
662
+
663
+ function cellReadabilityWarnings(cell: DomEl): string[] {
664
+ const label = labelText(cell);
665
+ if (!label) return [];
666
+ const box = rect(cell);
667
+ return [smallFontWarning(cell, box), longLabelWarning(cell, label, box)].filter(
668
+ (warning): warning is string => warning !== null,
669
+ );
670
+ }
671
+
672
+ /** Conservative static checks only; uncertain typography remains a visual concern. */
673
+ function readabilityWarnings(cells: DomEl[]): string[] {
674
+ return cells.flatMap(cellReadabilityWarnings);
675
+ }
676
+
677
+ function withPage(name: string, diagnostics: string[]): string[] {
678
+ return diagnostics.map((diagnostic) => `page '${name}': ${diagnostic}`);
679
+ }
680
+
681
+ function checkPage(diagram: DomEl): [string[], string[], string[]] {
318
682
  const name = attr(diagram, "name") ?? "?";
319
683
  const model = firstByTag(diagram, "mxGraphModel");
320
684
  if (!model) {
321
- if (directText(diagram).trim()) return [[], [`page '${name}': compressed, skipped (cannot lint)`]];
322
- return [[`page '${name}': no <mxGraphModel>`], []];
685
+ if (directText(diagram).trim()) return [[], [`page '${name}': compressed, skipped (cannot lint)`], []];
686
+ return [[`page '${name}': no <mxGraphModel>`], [], []];
323
687
  }
324
688
  const cells = collectCells(firstByTag(model, "root"));
325
689
 
326
690
  const errors: string[] = [];
327
- const warns: string[] = [];
691
+ const warnings: string[] = [];
692
+ const observations: string[] = [];
328
693
  const ids = buildIds(cells, errors);
329
694
  const parents = new Set<string | null>();
330
- for (const c of cells) parents.add(attr(c, "parent"));
331
-
332
- for (const c of cells) checkCell(c, ids, errors, warns);
333
- warns.push(...overlapWarnings(cells, parents), ...geometryWarnings(cells, ids, parents));
334
- return [errors, warns];
695
+ for (const cell of cells) parents.add(attr(cell, "parent"));
696
+
697
+ for (const cell of cells) checkCell(cell, ids, errors, warnings);
698
+ warnings.push(
699
+ ...overlapWarnings(cells, ids, parents),
700
+ ...geometryWarnings(cells, ids, parents),
701
+ ...containmentWarnings(cells, ids),
702
+ ...readabilityWarnings(cells),
703
+ );
704
+ const settings = pageSettings(model, warnings, observations);
705
+ warnings.push(...canvasWarnings(contentBounds(cells, ids), settings));
706
+ return [withPage(name, errors), withPage(name, warnings), withPage(name, observations)];
335
707
  }
336
708
 
337
709
  /** Lint a `.drawio` XML string. Throws only on unrecoverable parse failure. */
338
710
  export function validateXml(xml: string): ValidateResult {
339
711
  const doc = new DOMParser().parseFromString(xml, "text/xml");
340
- const rootEl = doc.documentElement as unknown as DomEl | null;
341
- if (!rootEl) throw new Error("no root element (malformed XML)");
342
- const pageList = childrenByTag(rootEl, "diagram");
343
- const pages = pageList.length > 0 ? pageList : [rootEl];
712
+ const root = doc.documentElement as unknown as DomEl | null;
713
+ if (!root) throw new Error("no root element (malformed XML)");
714
+ const pageList = childrenByTag(root, "diagram");
715
+ const pages = pageList.length > 0 ? pageList : [root];
344
716
 
345
717
  const errors: string[] = [];
346
718
  const warnings: string[] = [];
719
+ const observations: string[] = [];
347
720
  for (const page of pages) {
348
- const [e, w] = checkPage(page);
349
- errors.push(...e);
350
- warnings.push(...w);
721
+ const [pageErrors, pageWarnings, pageObservations] = checkPage(page);
722
+ errors.push(...pageErrors);
723
+ warnings.push(...pageWarnings);
724
+ observations.push(...pageObservations);
351
725
  }
352
- const through = warnings.filter((w) => w.includes("routes through")).length;
353
- const crossings = warnings.filter((w) => w.endsWith(" cross")).length;
354
- const overlaps = warnings.filter((w) => w.endsWith(" overlap")).length;
726
+ const through = warnings.filter((warning) => warning.includes("routes through")).length;
727
+ const crossings = warnings.filter((warning) => warning.endsWith(" cross")).length;
728
+ const overlaps = warnings.filter((warning) => warning.endsWith(" overlap")).length;
355
729
  return {
356
730
  errors,
357
731
  warnings,
732
+ observations,
358
733
  score: { total: 20 * through + 10 * crossings + 5 * overlaps, through, crossings, overlaps },
359
734
  };
360
735
  }
361
736
 
737
+ function emptyScore(): ValidateResult["score"] {
738
+ return { total: 0, through: 0, crossings: 0, overlaps: 0 };
739
+ }
740
+
362
741
  /** Read and lint a `.drawio` file. Read/parse failures are returned as errors, never thrown. */
363
742
  export async function validateFile(path: string): Promise<ValidateResult> {
364
- const empty = { total: 0, through: 0, crossings: 0, overlaps: 0 };
365
743
  let xml: string;
366
744
  try {
367
745
  xml = await readFile(path, "utf8");
368
- } catch (e) {
369
- return { errors: [`cannot read ${path}: ${(e as Error).message}`], warnings: [], score: empty };
746
+ } catch (error) {
747
+ return {
748
+ errors: [`cannot read ${path}: ${(error as Error).message}`],
749
+ warnings: [],
750
+ observations: [],
751
+ score: emptyScore(),
752
+ };
370
753
  }
371
754
  try {
372
755
  return validateXml(xml);
373
- } catch (e) {
374
- return { errors: [`cannot parse ${path}: ${(e as Error).message}`], warnings: [], score: empty };
756
+ } catch (error) {
757
+ return {
758
+ errors: [`cannot parse ${path}: ${(error as Error).message}`],
759
+ warnings: [],
760
+ observations: [],
761
+ score: emptyScore(),
762
+ };
375
763
  }
376
764
  }