@senad-d/drawme 0.1.3 → 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,23 +1,28 @@
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
9
  import { type DomEl, attr, childrenByTag, directText, elemChildren, firstByTag } from "./dom";
11
10
 
12
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;
13
15
 
14
16
  /** [x, y, width, height]. width/height may be NaN when the source omits them. */
15
17
  type Rect = [number, number, number, number];
18
+ type Point = [number, number];
16
19
  type ById = Map<string, DomEl>;
17
20
 
18
21
  export interface ValidateResult {
19
22
  errors: string[];
20
23
  warnings: string[];
24
+ /** Informational limitations/settings that do not require a source correction. */
25
+ observations: string[];
21
26
  /** Readability score (lower is better); comparable only across variants of the same graph. */
22
27
  score: { total: number; through: number; crossings: number; overlaps: number };
23
28
  }
@@ -49,15 +54,30 @@ function rect(cell: DomEl): Rect | null {
49
54
  return [x, y, w, h];
50
55
  }
51
56
 
52
- function hasNaN(r: Rect): boolean {
53
- 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";
54
63
  }
55
64
 
56
- /** True for edge labels / relative-positioned child vertices (they legitimately omit w/h). */
65
+ /** True for separate edge-label vertices. */
57
66
  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";
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;
61
81
  }
62
82
 
63
83
  function overlap(a: Rect, b: Rect): boolean {
@@ -73,10 +93,14 @@ function styleNum(style: string | null, key: string): number | undefined {
73
93
  return undefined;
74
94
  }
75
95
 
76
- /** 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. */
77
101
  function absRect(cell: DomEl, byId: ById): Rect | null {
78
102
  const r = rect(cell);
79
- if (r === null || hasNaN(r)) return null;
103
+ if (r === null || hasInvalidNumber(r)) return null;
80
104
  let [x, y] = r;
81
105
  const [, , w, h] = r;
82
106
  let parent = attr(cell, "parent");
@@ -84,9 +108,9 @@ function absRect(cell: DomEl, byId: ById): Rect | null {
84
108
  while (parent && byId.has(parent) && !seen.has(parent)) {
85
109
  seen.add(parent);
86
110
  const p = byId.get(parent)!;
87
- if (p.getAttribute("vertex") === "1") {
111
+ if (p.getAttribute("vertex") === "1" && !geometryIsRelative(p)) {
88
112
  const pr = rect(p);
89
- if (pr && !hasNaN(pr)) {
113
+ if (pr && !hasInvalidNumber(pr)) {
90
114
  x += pr[0];
91
115
  y += pr[1];
92
116
  }
@@ -96,8 +120,6 @@ function absRect(cell: DomEl, byId: ById): Rect | null {
96
120
  return [x, y, w, h];
97
121
  }
98
122
 
99
- type Point = [number, number];
100
-
101
123
  /** Absolute point where `edge` meets its source/target vertex (honours exit/entry). */
102
124
  function endpoint(edge: DomEl, end: "source" | "target", byId: ById): Point | null {
103
125
  const vid = attr(edge, end);
@@ -116,33 +138,73 @@ function edgeWaypoints(edge: DomEl): Point[] {
116
138
  if (!gy) return [];
117
139
  const arr = firstByTag(gy, "Array");
118
140
  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
- }
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]);
128
146
  }
129
- return pts;
147
+ return points;
130
148
  }
131
149
 
132
150
  /** Absolute polyline for a waypointed edge, or null when auto-routed / unresolved. */
133
151
  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];
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]];
140
202
  }
141
203
 
142
204
  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;
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;
146
208
  }
147
209
 
148
210
  function segmentsCross(p1: Point, p2: Point, p3: Point, p4: Point): boolean {
@@ -153,9 +215,9 @@ function segmentsCross(p1: Point, p2: Point, p3: Point, p4: Point): boolean {
153
215
  return o1 !== o2 && o3 !== o4 && ![o1, o2, o3, o4].includes(0);
154
216
  }
155
217
 
156
- function pointInRect(p: Point, box: Rect, eps = 1e-6): boolean {
218
+ function pointInRect(point: Point, box: Rect, epsilon = 1e-6): boolean {
157
219
  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;
220
+ return x + epsilon < point[0] && point[0] < x + w - epsilon && y + epsilon < point[1] && point[1] < y + h - epsilon;
159
221
  }
160
222
 
161
223
  function routeHitsRect(points: Point[], box: Rect): boolean {
@@ -166,20 +228,20 @@ function routeHitsRect(points: Point[], box: Rect): boolean {
166
228
  [x + w, y + h],
167
229
  [x, y + h],
168
230
  ];
169
- 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]]);
170
232
  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;
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;
175
237
  }
176
238
  return false;
177
239
  }
178
240
 
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;
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;
183
245
  return false;
184
246
  }
185
247
 
@@ -189,10 +251,10 @@ type LeafBox = [string | null, Rect];
189
251
  /** Edges with a resolvable waypointed route, tagged with their id and endpoint ids. */
190
252
  function collectRoutedEdges(cells: DomEl[], ids: ById): RoutedEdge[] {
191
253
  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")])]);
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")])]);
196
258
  }
197
259
  }
198
260
  return routed;
@@ -201,33 +263,43 @@ function collectRoutedEdges(cells: DomEl[], ids: ById): RoutedEdge[] {
201
263
  /** Absolute boxes of leaf vertices (real nodes, not containers or edge labels). */
202
264
  function collectLeafBoxes(cells: DomEl[], ids: ById, parents: Set<string | null>): LeafBox[] {
203
265
  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]);
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]);
208
276
  }
209
277
  }
210
278
  return leaves;
211
279
  }
212
280
 
213
281
  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)}`);
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
+ }
218
288
  }
219
289
  }
220
- return warns;
290
+ return warnings;
221
291
  }
222
292
 
223
293
  function routeCrossWarnings(routed: RoutedEdge[]): string[] {
224
- const warns: string[] = [];
294
+ const warnings: string[] = [];
225
295
  for (let i = 0; i < routed.length; i++) {
226
296
  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`);
297
+ if (routesCross(routed[i][1], routed[j][1])) {
298
+ warnings.push(`edges ${repr(routed[i][0])} and ${repr(routed[j][0])} cross`);
299
+ }
228
300
  }
229
301
  }
230
- return warns;
302
+ return warnings;
231
303
  }
232
304
 
233
305
  function geometryWarnings(cells: DomEl[], ids: ById, parents: Set<string | null>): string[] {
@@ -236,10 +308,7 @@ function geometryWarnings(cells: DomEl[], ids: ById, parents: Set<string | null>
236
308
  return [...routeThroughWarnings(routed, leaves), ...routeCrossWarnings(routed)];
237
309
  }
238
310
 
239
- /**
240
- * Fold UserObject/object wrappers (links & metadata) into their inner mxCell so
241
- * the wrapper id resolves for edges that reference it.
242
- */
311
+ /** Fold UserObject/object wrappers into their inner mxCell so wrapper ids resolve. */
243
312
  function collectCells(root: DomEl | null): DomEl[] {
244
313
  const cells: DomEl[] = [];
245
314
  for (const child of root ? elemChildren(root) : []) {
@@ -258,118 +327,438 @@ function collectCells(root: DomEl | null): DomEl[] {
258
327
  /** Map every cell by id (blank key for id-less cells); report duplicate ids as errors. */
259
328
  function buildIds(cells: DomEl[], errors: string[]): ById {
260
329
  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);
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);
265
334
  }
266
335
  return ids;
267
336
  }
268
337
 
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`);
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`);
274
343
  return;
275
344
  }
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`);
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`);
288
364
  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`);
365
+ const reference = attr(cell, end);
366
+ if (reference && !ids.has(reference)) errors.push(`edge ${repr(id)} ${end} ${repr(reference)} does not exist`);
291
367
  }
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
368
  }
295
369
 
296
- /** Sibling overlap: leaf vertices only (containers legitimately wrap children). */
297
- 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[] {
298
383
  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]);
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]);
303
394
  }
304
395
  }
305
- const warns: string[] = [];
396
+ const warnings: string[] = [];
306
397
  for (let i = 0; i < boxes.length; i++) {
307
398
  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`);
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`);
311
402
  }
312
403
  }
313
- 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);
314
472
  }
315
473
 
316
- 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[]] {
317
682
  const name = attr(diagram, "name") ?? "?";
318
683
  const model = firstByTag(diagram, "mxGraphModel");
319
684
  if (!model) {
320
- if (directText(diagram).trim()) return [[], [`page '${name}': compressed, skipped (cannot lint)`]];
321
- return [[`page '${name}': no <mxGraphModel>`], []];
685
+ if (directText(diagram).trim()) return [[], [`page '${name}': compressed, skipped (cannot lint)`], []];
686
+ return [[`page '${name}': no <mxGraphModel>`], [], []];
322
687
  }
323
688
  const cells = collectCells(firstByTag(model, "root"));
324
689
 
325
690
  const errors: string[] = [];
326
- const warns: string[] = [];
691
+ const warnings: string[] = [];
692
+ const observations: string[] = [];
327
693
  const ids = buildIds(cells, errors);
328
694
  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];
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)];
334
707
  }
335
708
 
336
709
  /** Lint a `.drawio` XML string. Throws only on unrecoverable parse failure. */
337
710
  export function validateXml(xml: string): ValidateResult {
338
711
  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];
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];
343
716
 
344
717
  const errors: string[] = [];
345
718
  const warnings: string[] = [];
719
+ const observations: string[] = [];
346
720
  for (const page of pages) {
347
- const [e, w] = checkPage(page);
348
- errors.push(...e);
349
- warnings.push(...w);
721
+ const [pageErrors, pageWarnings, pageObservations] = checkPage(page);
722
+ errors.push(...pageErrors);
723
+ warnings.push(...pageWarnings);
724
+ observations.push(...pageObservations);
350
725
  }
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;
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;
354
729
  return {
355
730
  errors,
356
731
  warnings,
732
+ observations,
357
733
  score: { total: 20 * through + 10 * crossings + 5 * overlaps, through, crossings, overlaps },
358
734
  };
359
735
  }
360
736
 
737
+ function emptyScore(): ValidateResult["score"] {
738
+ return { total: 0, through: 0, crossings: 0, overlaps: 0 };
739
+ }
740
+
361
741
  /** Read and lint a `.drawio` file. Read/parse failures are returned as errors, never thrown. */
362
742
  export async function validateFile(path: string): Promise<ValidateResult> {
363
- const empty = { total: 0, through: 0, crossings: 0, overlaps: 0 };
364
743
  let xml: string;
365
744
  try {
366
745
  xml = await readFile(path, "utf8");
367
- } catch (e) {
368
- 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
+ };
369
753
  }
370
754
  try {
371
755
  return validateXml(xml);
372
- } catch (e) {
373
- 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
+ };
374
763
  }
375
764
  }