@senad-d/drawme 0.1.10 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -1
- package/README.md +47 -46
- package/SECURITY.md +1 -1
- package/assets/references/diagram-types.md +3 -3
- package/assets/references/mermaid-authoring.md +10 -9
- package/assets/references/troubleshooting.md +5 -27
- package/assets/references/xml-authoring.md +5 -3
- package/docs/reference.md +75 -73
- package/docs/visual-review-implementation-tasks.md +4 -2
- package/example/README.md +9 -9
- package/example/drawme-architecture.drawio +5 -5
- package/example/drawme-how-it-works.drawio +7 -7
- package/example/drawme-installation-guide.drawio +6 -6
- package/package.json +5 -3
- package/src/animate.ts +124 -88
- package/src/animation.ts +105 -109
- package/src/diagram-files.ts +159 -0
- package/src/dom.ts +5 -0
- package/src/drawio.ts +330 -558
- package/src/editable-import.ts +228 -0
- package/src/explain.ts +81 -88
- package/src/export-plan.ts +175 -0
- package/src/fitcanvas.ts +29 -25
- package/src/geometry.ts +68 -29
- package/src/index.ts +201 -142
- package/src/motion.ts +251 -163
- package/src/png.ts +233 -34
- package/src/renderer.ts +361 -0
- package/src/shapesearch.ts +33 -32
- package/src/storyboard.ts +41 -26
- package/src/svg-helpers.ts +129 -0
- package/src/svgexport.ts +6 -9
- package/src/validate.ts +686 -292
- package/src/workflow.ts +41 -30
package/src/validate.ts
CHANGED
|
@@ -4,11 +4,11 @@
|
|
|
4
4
|
* checked without rendering. Typography and automatically routed connectors
|
|
5
5
|
* still require visual review.
|
|
6
6
|
*/
|
|
7
|
-
import { readFile } from "node:fs/promises";
|
|
8
7
|
import { DOMParser } from "@xmldom/xmldom";
|
|
9
|
-
import {
|
|
8
|
+
import { DEFAULT_XML_BYTES, DiagramLimitError, readDiagramXml } from "./diagram-files";
|
|
9
|
+
import { ELEMENT_NODE, type DomEl, attr, childrenByTag, directText, firstByTag, graphModel } from "./dom";
|
|
10
10
|
import { analyzeAnimationPage } from "./animation";
|
|
11
|
-
import { analyzeStoredMotion } from "./motion";
|
|
11
|
+
import { analyzeStoredMotion, readStoredMotion } from "./motion";
|
|
12
12
|
import {
|
|
13
13
|
type ById,
|
|
14
14
|
type ContentBounds,
|
|
@@ -27,7 +27,7 @@ import {
|
|
|
27
27
|
isVisible,
|
|
28
28
|
pyFloat,
|
|
29
29
|
rect,
|
|
30
|
-
|
|
30
|
+
routeLabelPoint,
|
|
31
31
|
styleNum,
|
|
32
32
|
} from "./geometry";
|
|
33
33
|
|
|
@@ -41,13 +41,115 @@ export interface ValidateResult {
|
|
|
41
41
|
warnings: string[];
|
|
42
42
|
/** Informational limitations/settings that do not require a source correction. */
|
|
43
43
|
observations: string[];
|
|
44
|
-
/** Readability score (lower is better); comparable only across variants of the same graph. */
|
|
44
|
+
/** Readability score (lower is better); comparable only across complete variants of the same graph. */
|
|
45
45
|
score: { total: number; through: number; crossings: number; overlaps: number; anchors: number };
|
|
46
|
+
complete: boolean;
|
|
47
|
+
limit?: "bytes" | "pages" | "cells" | "work" | "diagnostics";
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
interface ValidationLimits {
|
|
51
|
+
maxBytes: number;
|
|
52
|
+
maxPages: number;
|
|
53
|
+
maxCellsPerPage: number;
|
|
54
|
+
maxWork: number;
|
|
55
|
+
maxDiagnostics: number;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const DEFAULT_LIMITS: ValidationLimits = {
|
|
59
|
+
maxBytes: DEFAULT_XML_BYTES,
|
|
60
|
+
maxPages: 128,
|
|
61
|
+
maxCellsPerPage: 10_000,
|
|
62
|
+
maxWork: 100_000,
|
|
63
|
+
maxDiagnostics: 200,
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
function validationLimits(overrides?: Partial<ValidationLimits>): ValidationLimits {
|
|
67
|
+
const limits = { ...DEFAULT_LIMITS, ...overrides };
|
|
68
|
+
for (const [name, value] of Object.entries(limits)) {
|
|
69
|
+
if (!Number.isSafeInteger(value) || value <= 0 || value === Number.MAX_SAFE_INTEGER) {
|
|
70
|
+
throw new RangeError(`invalid validation limit: ${name}`);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return limits;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
type Severity = "errors" | "warnings" | "observations";
|
|
77
|
+
const FINDING_WEIGHTS = { through: 20, crossings: 10, overlaps: 5, anchors: 8, other: 0 } as const;
|
|
78
|
+
type FindingKind = keyof typeof FINDING_WEIGHTS;
|
|
79
|
+
type Message = string | (() => string);
|
|
80
|
+
type Finding = (severity: Severity, message: Message, kind?: FindingKind) => void;
|
|
81
|
+
|
|
82
|
+
const MAX_MESSAGE_LENGTH = 1024;
|
|
83
|
+
|
|
84
|
+
function abbreviated(text: string, length = MAX_MESSAGE_LENGTH): string {
|
|
85
|
+
return text.length > length ? `${text.slice(0, length - 1)}…` : text;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
class ValidationStop extends Error {
|
|
89
|
+
constructor(readonly limit: NonNullable<ValidateResult["limit"]>, message: string) {
|
|
90
|
+
super(message);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
class ValidationReport {
|
|
95
|
+
readonly result: ValidateResult = {
|
|
96
|
+
errors: [], warnings: [], observations: [],
|
|
97
|
+
score: { total: 0, through: 0, crossings: 0, overlaps: 0, anchors: 0 },
|
|
98
|
+
complete: true,
|
|
99
|
+
};
|
|
100
|
+
private workLeft: number;
|
|
101
|
+
private lastFinding?: { severity: Severity; kind: FindingKind };
|
|
102
|
+
private diagnosticCount = 0;
|
|
103
|
+
|
|
104
|
+
constructor(readonly limits: ValidationLimits) {
|
|
105
|
+
this.workLeft = limits.maxWork;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
checkWork(stage: string, units: number): void {
|
|
109
|
+
if (units > this.workLeft) {
|
|
110
|
+
throw new ValidationStop("work", `work limit of ${this.limits.maxWork} exceeded during ${stage}`);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
spend(stage: string, units = 1): void {
|
|
115
|
+
this.checkWork(stage, units);
|
|
116
|
+
this.workLeft -= units;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
stopDiagnosticsAtCap(): void {
|
|
120
|
+
if (this.diagnosticCount >= this.limits.maxDiagnostics) {
|
|
121
|
+
throw new ValidationStop("diagnostics", `diagnostic limit of ${this.limits.maxDiagnostics} reached`);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
add(severity: Severity, message: Message, kind: FindingKind = "other", prefix = ""): void {
|
|
126
|
+
this.stopDiagnosticsAtCap();
|
|
127
|
+
this.spend("diagnostic creation");
|
|
128
|
+
this.result[severity].push(abbreviated(prefix + (typeof message === "function" ? message() : message)));
|
|
129
|
+
if (kind !== "other") this.result.score[kind]++;
|
|
130
|
+
this.result.score.total += FINDING_WEIGHTS[kind];
|
|
131
|
+
this.lastFinding = { severity, kind };
|
|
132
|
+
this.diagnosticCount++;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
incomplete(message: string, limit?: ValidateResult["limit"]): ValidateResult {
|
|
136
|
+
// The blocking explanation counts toward the same cap as every other item.
|
|
137
|
+
if (this.diagnosticCount === this.limits.maxDiagnostics && this.lastFinding) {
|
|
138
|
+
const { severity, kind } = this.lastFinding;
|
|
139
|
+
this.result[severity].pop();
|
|
140
|
+
if (kind !== "other") this.result.score[kind]--;
|
|
141
|
+
this.result.score.total -= FINDING_WEIGHTS[kind];
|
|
142
|
+
}
|
|
143
|
+
this.result.errors.push(abbreviated(message));
|
|
144
|
+
this.result.complete = false;
|
|
145
|
+
if (limit) this.result.limit = limit;
|
|
146
|
+
return this.result;
|
|
147
|
+
}
|
|
46
148
|
}
|
|
47
149
|
|
|
48
150
|
/** Quote an optional attribute consistently in diagnostic messages. */
|
|
49
151
|
function repr(s: string | null): string {
|
|
50
|
-
return s === null ? "None" : `'${s}'`;
|
|
152
|
+
return s === null ? "None" : `'${abbreviated(s, 200)}'`;
|
|
51
153
|
}
|
|
52
154
|
|
|
53
155
|
function overlap(a: Rect, b: Rect): boolean {
|
|
@@ -79,7 +181,7 @@ function pointInRect(point: Point, box: Rect, epsilon = 1e-6): boolean {
|
|
|
79
181
|
return x + epsilon < point[0] && point[0] < x + w - epsilon && y + epsilon < point[1] && point[1] < y + h - epsilon;
|
|
80
182
|
}
|
|
81
183
|
|
|
82
|
-
function routeHitsRect(points: Point[], box: Rect): boolean {
|
|
184
|
+
function routeHitsRect(points: Point[], box: Rect, report: ValidationReport): boolean {
|
|
83
185
|
const [x, y, w, h] = box;
|
|
84
186
|
const corners: Point[] = [
|
|
85
187
|
[x, y],
|
|
@@ -89,6 +191,7 @@ function routeHitsRect(points: Point[], box: Rect): boolean {
|
|
|
89
191
|
];
|
|
90
192
|
const borders: [Point, Point][] = corners.map((corner, index) => [corner, corners[(index + 1) % 4]]);
|
|
91
193
|
for (let i = 0; i < points.length - 1; i++) {
|
|
194
|
+
report.spend("route segment and box comparisons");
|
|
92
195
|
const start = points[i];
|
|
93
196
|
const end = points[i + 1];
|
|
94
197
|
if (pointInRect(start, box) || pointInRect(end, box)) return true;
|
|
@@ -97,10 +200,13 @@ function routeHitsRect(points: Point[], box: Rect): boolean {
|
|
|
97
200
|
return false;
|
|
98
201
|
}
|
|
99
202
|
|
|
100
|
-
function routesCross(a: Point[], b: Point[]): boolean {
|
|
101
|
-
for (let i = 0; i < a.length - 1; i++)
|
|
102
|
-
for (let j = 0; j < b.length - 1; j++)
|
|
203
|
+
function routesCross(a: Point[], b: Point[], report: ValidationReport): boolean {
|
|
204
|
+
for (let i = 0; i < a.length - 1; i++) {
|
|
205
|
+
for (let j = 0; j < b.length - 1; j++) {
|
|
206
|
+
report.spend("route segment pair comparisons");
|
|
103
207
|
if (segmentsCross(a[i], a[i + 1], b[j], b[j + 1])) return true;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
104
210
|
return false;
|
|
105
211
|
}
|
|
106
212
|
|
|
@@ -137,28 +243,23 @@ function collectLeafBoxes(cells: DomEl[], ids: ById, parents: Set<string | null>
|
|
|
137
243
|
return leaves;
|
|
138
244
|
}
|
|
139
245
|
|
|
140
|
-
function
|
|
141
|
-
const warnings: string[] = [];
|
|
246
|
+
function checkRoutes(routed: RoutedEdge[], leaves: LeafBox[], report: ValidationReport, find: Finding): void {
|
|
142
247
|
for (const [edgeId, points, ends] of routed) {
|
|
143
248
|
for (const [vertexId, box] of leaves) {
|
|
144
|
-
|
|
145
|
-
|
|
249
|
+
report.spend("route and vertex comparisons");
|
|
250
|
+
if (!ends.has(vertexId) && routeHitsRect(points, box, report)) {
|
|
251
|
+
find("warnings", () => `edge ${repr(edgeId)} routes through vertex ${repr(vertexId)}`, "through");
|
|
146
252
|
}
|
|
147
253
|
}
|
|
148
254
|
}
|
|
149
|
-
return warnings;
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
function routeCrossWarnings(routed: RoutedEdge[]): string[] {
|
|
153
|
-
const warnings: string[] = [];
|
|
154
255
|
for (let i = 0; i < routed.length; i++) {
|
|
155
256
|
for (let j = i + 1; j < routed.length; j++) {
|
|
156
|
-
|
|
157
|
-
|
|
257
|
+
report.spend("route pair comparisons");
|
|
258
|
+
if (routesCross(routed[i][1], routed[j][1], report)) {
|
|
259
|
+
find("warnings", () => `edges ${repr(routed[i][0])} and ${repr(routed[j][0])} cross`, "crossings");
|
|
158
260
|
}
|
|
159
261
|
}
|
|
160
262
|
}
|
|
161
|
-
return warnings;
|
|
162
263
|
}
|
|
163
264
|
|
|
164
265
|
type Side = "top" | "bottom" | "left" | "right";
|
|
@@ -235,17 +336,17 @@ function anchorDirectionWarning(
|
|
|
235
336
|
}
|
|
236
337
|
|
|
237
338
|
/** Warn when a pinned border anchor faces away from its adjacent waypoint, or its peer when auto-routed. */
|
|
238
|
-
function
|
|
239
|
-
if (cell.getAttribute("edge") !== "1" || !isVisible(cell, ids)) return
|
|
339
|
+
function checkEdgeAnchorFacing(cell: DomEl, ids: ById, find: Finding): void {
|
|
340
|
+
if (cell.getAttribute("edge") !== "1" || !isVisible(cell, ids)) return;
|
|
240
341
|
const sourceId = attr(cell, "source");
|
|
241
342
|
const targetId = attr(cell, "target");
|
|
242
|
-
if (!sourceId || !targetId) return
|
|
343
|
+
if (!sourceId || !targetId) return;
|
|
243
344
|
const source = ids.get(sourceId);
|
|
244
345
|
const target = ids.get(targetId);
|
|
245
|
-
if (!source || !target || geometryIsRelative(source) || geometryIsRelative(target)) return
|
|
346
|
+
if (!source || !target || geometryIsRelative(source) || geometryIsRelative(target)) return;
|
|
246
347
|
const sourceBox = absRect(source, ids);
|
|
247
348
|
const targetBox = absRect(target, ids);
|
|
248
|
-
if (!sourceBox || !targetBox) return
|
|
349
|
+
if (!sourceBox || !targetBox) return;
|
|
249
350
|
|
|
250
351
|
const sourceCenter = rectCenter(sourceBox);
|
|
251
352
|
const targetCenter = rectCenter(targetBox);
|
|
@@ -266,13 +367,10 @@ function edgeAnchorFacingWarnings(cell: DomEl, ids: ById): string[] {
|
|
|
266
367
|
];
|
|
267
368
|
const tolerance = Math.max(sourceBox[2], sourceBox[3], targetBox[2], targetBox[3]) * 0.15;
|
|
268
369
|
const style = attr(cell, "style") ?? "";
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
function anchorFacingWarnings(cells: DomEl[], ids: ById): string[] {
|
|
275
|
-
return cells.flatMap((cell) => edgeAnchorFacingWarnings(cell, ids));
|
|
370
|
+
for (const direction of directions) {
|
|
371
|
+
const warning = anchorDirectionWarning(cell, style, tolerance, direction);
|
|
372
|
+
if (warning) find("warnings", warning, "anchors");
|
|
373
|
+
}
|
|
276
374
|
}
|
|
277
375
|
|
|
278
376
|
/** A segment that enters and exits a rectangle rather than merely touching its boundary. */
|
|
@@ -291,13 +389,14 @@ function segmentPiercesRect(start: Point, end: Point, box: Rect): boolean {
|
|
|
291
389
|
return crossings === 1 && (pointInRect(start, box) || pointInRect(end, box));
|
|
292
390
|
}
|
|
293
391
|
|
|
294
|
-
function isDescendantOf(cell: DomEl, ancestorId: string
|
|
295
|
-
|
|
392
|
+
function isDescendantOf(cell: DomEl, ancestorId: string, ids: ById, report: ValidationReport): boolean {
|
|
393
|
+
// Only called after containment has been checked for cycles.
|
|
296
394
|
let parent = attr(cell, "parent");
|
|
297
|
-
while (parent
|
|
395
|
+
while (parent) {
|
|
396
|
+
report.spend("predicted route ancestor walks");
|
|
298
397
|
if (parent === ancestorId) return true;
|
|
299
|
-
|
|
300
|
-
parent = attr(
|
|
398
|
+
const next = ids.get(parent);
|
|
399
|
+
parent = next ? attr(next, "parent") : null;
|
|
301
400
|
}
|
|
302
401
|
return false;
|
|
303
402
|
}
|
|
@@ -328,132 +427,132 @@ function autoRouteContext(cell: DomEl, ids: ById): AutoRouteContext | null {
|
|
|
328
427
|
return { edgeId: attr(cell, "id"), sourceId, targetId, sourcePoint, targetPoint };
|
|
329
428
|
}
|
|
330
429
|
|
|
331
|
-
function
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
/**
|
|
350
|
-
* Identify auto-routed edges whose direct connection line pierces an unrelated
|
|
351
|
-
* leaf vertex. This is only a preview-review hint because draw.io may route the
|
|
352
|
-
* actual orthogonal connector around the shape.
|
|
353
|
-
*/
|
|
354
|
-
function predictedRouteThroughObservations(cells: DomEl[], ids: ById, leaves: LeafBox[]): string[] {
|
|
355
|
-
return cells.flatMap((cell) => edgeRouteThroughObservations(cell, ids, leaves));
|
|
356
|
-
}
|
|
357
|
-
|
|
358
|
-
function geometryWarnings(cells: DomEl[], ids: ById, parents: Set<string | null>): string[] {
|
|
359
|
-
const routed = collectRoutedEdges(cells, ids);
|
|
360
|
-
const leaves = collectLeafBoxes(cells, ids, parents);
|
|
361
|
-
return [...routeThroughWarnings(routed, leaves), ...routeCrossWarnings(routed), ...anchorFacingWarnings(cells, ids)];
|
|
430
|
+
function checkPredictedRoutes(
|
|
431
|
+
cells: DomEl[], ids: ById, leaves: LeafBox[], report: ValidationReport, find: Finding,
|
|
432
|
+
): void {
|
|
433
|
+
// Preview guidance only: a renderer may route around the pierced leaf box.
|
|
434
|
+
const annotations = new Set(cells.filter(isTextAnnotation));
|
|
435
|
+
for (const cell of cells) {
|
|
436
|
+
const context = autoRouteContext(cell, ids);
|
|
437
|
+
if (!context) continue;
|
|
438
|
+
for (const [vertexId, box] of leaves) {
|
|
439
|
+
report.spend("predicted route and vertex comparisons");
|
|
440
|
+
if (vertexId === null || vertexId === context.sourceId || vertexId === context.targetId) continue;
|
|
441
|
+
if (!segmentPiercesRect(context.sourcePoint, context.targetPoint, box)) continue;
|
|
442
|
+
const vertex = ids.get(vertexId);
|
|
443
|
+
if (!vertex || annotations.has(vertex)) continue;
|
|
444
|
+
if (isDescendantOf(vertex, context.sourceId, ids, report) || isDescendantOf(vertex, context.targetId, ids, report)) continue;
|
|
445
|
+
find("observations", () => `edge ${repr(context.edgeId)} may pass over vertex ${repr(vertexId)} (predicted from the direct line; verify in the preview, then add waypoints or move the shape if needed)`);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
362
448
|
}
|
|
363
449
|
|
|
364
450
|
/** Edges the route checks above cannot see: no explicit waypoints, so the renderer routes them blindly. */
|
|
365
451
|
function autoRoutedEdgeWarning(cells: DomEl[], ids: ById): string | null {
|
|
366
452
|
const unrouted: string[] = [];
|
|
453
|
+
let count = 0;
|
|
454
|
+
let room = 750; // Leave room for the rest of the diagnostic and its recovery advice.
|
|
367
455
|
for (const cell of cells) {
|
|
368
456
|
if (cell.getAttribute("edge") === "1" && isVisible(cell, ids) && edgeRoute(cell, ids) === null) {
|
|
369
|
-
|
|
457
|
+
if (room > 0) {
|
|
458
|
+
const id = repr(attr(cell, "id"));
|
|
459
|
+
room -= id.length + 2;
|
|
460
|
+
if (room >= 0) unrouted.push(id);
|
|
461
|
+
}
|
|
462
|
+
count++;
|
|
370
463
|
}
|
|
371
464
|
}
|
|
372
|
-
if (
|
|
465
|
+
if (count === 0) return null;
|
|
373
466
|
return (
|
|
374
|
-
`${
|
|
467
|
+
`${count} auto-routed edge(s) cannot be route-checked (no explicit waypoints): ${unrouted.join(", ")}${count > unrouted.length ? ", …" : ""}; ` +
|
|
375
468
|
"add waypoints and pinned anchors, or verify their routing visually"
|
|
376
469
|
);
|
|
377
470
|
}
|
|
378
471
|
|
|
379
472
|
/** Map every cell by id (blank key for id-less cells); report duplicate ids as errors. */
|
|
380
|
-
function buildIds(cells: DomEl[],
|
|
473
|
+
function buildIds(cells: DomEl[], report: ValidationReport, find: Finding): ById {
|
|
381
474
|
const ids: ById = new Map();
|
|
382
475
|
for (const cell of cells) {
|
|
476
|
+
report.spend("cell ID indexing");
|
|
383
477
|
const id = attr(cell, "id");
|
|
384
|
-
if (id !== null && ids.has(id)) errors
|
|
478
|
+
if (id !== null && ids.has(id)) find("errors", () => `duplicate id ${repr(id)}`);
|
|
385
479
|
ids.set(id ?? "", cell);
|
|
386
480
|
}
|
|
387
481
|
return ids;
|
|
388
482
|
}
|
|
389
483
|
|
|
390
484
|
/** Geometry checks for a single non-edge-label, non-relative vertex. */
|
|
391
|
-
function checkVertexGeometry(cell: DomEl, id: string | null,
|
|
485
|
+
function checkVertexGeometry(cell: DomEl, id: string | null, find: Finding): void {
|
|
392
486
|
const box = rect(cell);
|
|
393
487
|
if (box === null || hasInvalidNumber(box)) {
|
|
394
|
-
errors
|
|
488
|
+
find("errors", () => `vertex ${repr(id)} has missing/invalid geometry`);
|
|
395
489
|
return;
|
|
396
490
|
}
|
|
397
491
|
const [x, y, width, height] = box;
|
|
398
|
-
if (width <= 0 || height <= 0) warnings
|
|
399
|
-
if (x < 0 || y < 0) warnings
|
|
492
|
+
if (width <= 0 || height <= 0) find("warnings", () => `vertex ${repr(id)} non-positive size ${width}x${height}`);
|
|
493
|
+
if (x < 0 || y < 0) find("warnings", () => `vertex ${repr(id)} negative position (${x},${y})`);
|
|
400
494
|
}
|
|
401
495
|
|
|
402
|
-
function checkEdgeGeometry(cell: DomEl, id: string | null,
|
|
496
|
+
function checkEdgeGeometry(cell: DomEl, id: string | null, find: Finding): void {
|
|
403
497
|
const geometry = firstByTag(cell, "mxGeometry");
|
|
404
498
|
if (!geometry) {
|
|
405
|
-
errors
|
|
499
|
+
find("errors", () => `edge ${repr(id)} has missing geometry`);
|
|
406
500
|
return;
|
|
407
501
|
}
|
|
408
502
|
if (attr(geometry, "relative") !== "1" || attr(geometry, "as") !== "geometry") {
|
|
409
|
-
errors
|
|
503
|
+
find("errors", () => `edge ${repr(id)} geometry must have relative='1' and as='geometry'`);
|
|
410
504
|
}
|
|
411
505
|
}
|
|
412
506
|
|
|
413
|
-
function checkCellReferences(cell: DomEl, id: string | null, ids: ById,
|
|
507
|
+
function checkCellReferences(cell: DomEl, id: string | null, ids: ById, find: Finding): void {
|
|
414
508
|
const parent = attr(cell, "parent");
|
|
415
|
-
if (parent !== null && !ids.has(parent)) errors
|
|
509
|
+
if (parent !== null && !ids.has(parent)) find("errors", () => `cell ${repr(id)} parent ${repr(parent)} does not exist`);
|
|
416
510
|
for (const end of ["source", "target"] as const) {
|
|
417
511
|
const reference = attr(cell, end);
|
|
418
|
-
if (reference && !ids.has(reference)) errors
|
|
512
|
+
if (reference && !ids.has(reference)) find("errors", () => `edge ${repr(id)} ${end} ${repr(reference)} does not exist`);
|
|
419
513
|
}
|
|
420
514
|
}
|
|
421
515
|
|
|
422
516
|
/** Per-cell reference and geometry checks. */
|
|
423
|
-
function checkCell(cell: DomEl, ids: ById,
|
|
517
|
+
function checkCell(cell: DomEl, ids: ById, find: Finding): void {
|
|
424
518
|
const id = attr(cell, "id");
|
|
425
519
|
const isVertex = cell.getAttribute("vertex") === "1";
|
|
426
520
|
const isEdge = cell.getAttribute("edge") === "1";
|
|
427
|
-
checkCellReferences(cell, id, ids,
|
|
428
|
-
if ((isVertex || isEdge) && id !== null && RESERVED.has(id)) errors
|
|
429
|
-
if (isVertex && !isEdgeLabel(cell) && !geometryIsRelative(cell)) checkVertexGeometry(cell, id,
|
|
430
|
-
if (isEdge) checkEdgeGeometry(cell, id,
|
|
521
|
+
checkCellReferences(cell, id, ids, find);
|
|
522
|
+
if ((isVertex || isEdge) && id !== null && RESERVED.has(id)) find("errors", () => `cell ${repr(id)} reuses reserved id 0/1`);
|
|
523
|
+
if (isVertex && !isEdgeLabel(cell) && !geometryIsRelative(cell)) checkVertexGeometry(cell, id, find);
|
|
524
|
+
if (isEdge) checkEdgeGeometry(cell, id, find);
|
|
431
525
|
}
|
|
432
526
|
|
|
433
527
|
/** Sibling overlap: visible leaf vertices only (containers legitimately wrap children). */
|
|
434
|
-
function
|
|
435
|
-
|
|
528
|
+
function checkSiblingOverlap(
|
|
529
|
+
cells: DomEl[], ids: ById, parents: Set<string | null>, origins: Map<DomEl, number>,
|
|
530
|
+
report: ValidationReport, find: Finding,
|
|
531
|
+
): void {
|
|
532
|
+
const groups = new Map<string | null, LeafBox[]>();
|
|
436
533
|
for (const cell of cells) {
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
)
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
534
|
+
report.spend("sibling box collection");
|
|
535
|
+
const id = attr(cell, "id");
|
|
536
|
+
if (cell.getAttribute("vertex") !== "1" || parents.has(id) || isEdgeLabel(cell) || geometryIsRelative(cell)) continue;
|
|
537
|
+
report.spend("ancestor walks", origins.get(cell) ?? 1);
|
|
538
|
+
if (!isVisible(cell, ids)) continue;
|
|
539
|
+
const box = rect(cell);
|
|
540
|
+
if (!box || hasInvalidNumber(box)) continue;
|
|
541
|
+
const parent = attr(cell, "parent");
|
|
542
|
+
const siblings = groups.get(parent);
|
|
543
|
+
if (siblings) siblings.push([id, box]);
|
|
544
|
+
else groups.set(parent, [[id, box]]);
|
|
447
545
|
}
|
|
448
|
-
const
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
546
|
+
for (const siblings of groups.values()) {
|
|
547
|
+
for (let i = 0; i < siblings.length; i++) {
|
|
548
|
+
for (let j = i + 1; j < siblings.length; j++) {
|
|
549
|
+
report.spend("sibling overlap comparisons");
|
|
550
|
+
const [aId, a] = siblings[i];
|
|
551
|
+
const [bId, b] = siblings[j];
|
|
552
|
+
if (overlap(a, b)) find("warnings", () => `vertices ${repr(aId)} and ${repr(bId)} overlap`, "overlaps");
|
|
553
|
+
}
|
|
454
554
|
}
|
|
455
555
|
}
|
|
456
|
-
return warnings;
|
|
457
556
|
}
|
|
458
557
|
|
|
459
558
|
function isContainmentCandidate(cell: DomEl, ids: ById): boolean {
|
|
@@ -489,12 +588,6 @@ function containmentWarning(cell: DomEl, ids: ById): string | null {
|
|
|
489
588
|
return `vertex ${repr(attr(cell, "id"))} extends beyond parent ${repr(parentId)} (${sides.join(", ")})`;
|
|
490
589
|
}
|
|
491
590
|
|
|
492
|
-
function containmentWarnings(cells: DomEl[], ids: ById): string[] {
|
|
493
|
-
return cells
|
|
494
|
-
.map((cell) => containmentWarning(cell, ids))
|
|
495
|
-
.filter((warning): warning is string => warning !== null);
|
|
496
|
-
}
|
|
497
|
-
|
|
498
591
|
interface PageSettings {
|
|
499
592
|
enabled: boolean;
|
|
500
593
|
width?: number;
|
|
@@ -502,24 +595,24 @@ interface PageSettings {
|
|
|
502
595
|
scale: number;
|
|
503
596
|
}
|
|
504
597
|
|
|
505
|
-
function pageSettings(model: DomEl,
|
|
598
|
+
function pageSettings(model: DomEl, find: Finding): PageSettings {
|
|
506
599
|
const enabled = attr(model, "page") !== "0";
|
|
507
600
|
if (!enabled) {
|
|
508
|
-
|
|
601
|
+
find("observations", "page canvas is disabled (infinite canvas); boundary, margin, and empty-space checks skipped");
|
|
509
602
|
return { enabled, scale: 1 };
|
|
510
603
|
}
|
|
511
604
|
|
|
512
605
|
const rawScale = attr(model, "pageScale");
|
|
513
606
|
const parsedScale = rawScale === null ? 1 : pyFloat(rawScale);
|
|
514
607
|
const scale = parsedScale && Number.isFinite(parsedScale) && parsedScale > 0 ? parsedScale : 1;
|
|
515
|
-
if (rawScale !== null && scale !== parsedScale) warnings
|
|
608
|
+
if (rawScale !== null && scale !== parsedScale) find("warnings", () => `invalid pageScale ${repr(rawScale)}; using 1`);
|
|
516
609
|
|
|
517
610
|
const parseDimension = (name: "pageWidth" | "pageHeight"): number | undefined => {
|
|
518
611
|
const raw = attr(model, name);
|
|
519
612
|
if (raw === null) return undefined;
|
|
520
613
|
const value = pyFloat(raw);
|
|
521
614
|
if (value === undefined || !Number.isFinite(value) || value <= 0) {
|
|
522
|
-
warnings
|
|
615
|
+
find("warnings", () => `invalid ${name} ${repr(raw)}; page-boundary checks skipped`);
|
|
523
616
|
return undefined;
|
|
524
617
|
}
|
|
525
618
|
return value * scale;
|
|
@@ -527,7 +620,7 @@ function pageSettings(model: DomEl, warnings: string[], observations: string[]):
|
|
|
527
620
|
const width = parseDimension("pageWidth");
|
|
528
621
|
const height = parseDimension("pageHeight");
|
|
529
622
|
if (width === undefined || height === undefined) {
|
|
530
|
-
observations
|
|
623
|
+
find("observations",
|
|
531
624
|
"page dimensions are omitted or invalid; boundary, outer-margin, and empty-space checks require both pageWidth and pageHeight",
|
|
532
625
|
);
|
|
533
626
|
}
|
|
@@ -648,50 +741,48 @@ function labelFraction(edge: DomEl): number {
|
|
|
648
741
|
return along !== undefined && Number.isFinite(along) ? Math.min(1, Math.max(0, (along + 1) / 2)) : 0.5;
|
|
649
742
|
}
|
|
650
743
|
|
|
651
|
-
/** Estimated box
|
|
652
|
-
function
|
|
653
|
-
const
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
/** Estimated label box for an edge along a given route. */
|
|
658
|
-
function labelBox(edge: DomEl, route: Point[]): Rect {
|
|
659
|
-
const label = labelText(edge);
|
|
660
|
-
const [centerX, centerY] = routePointAt(route, labelFraction(edge));
|
|
661
|
-
const [offsetX, offsetY] = labelOffset(edge) ?? [0, 0];
|
|
744
|
+
/** Estimated label box at the displaced label point on the edge. */
|
|
745
|
+
function labelBox(edge: DomEl, route: Point[], label: string): Rect | null {
|
|
746
|
+
const center = routeLabelPoint(edge, route);
|
|
747
|
+
if (!center) return null;
|
|
748
|
+
const [centerX, centerY] = center;
|
|
662
749
|
const fontSize = styleNum(attr(edge, "style"), "fontSize") ?? DEFAULT_FONT_SIZE;
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
750
|
+
let lines = 1;
|
|
751
|
+
let longest = 0;
|
|
752
|
+
let lineStart = 0;
|
|
753
|
+
for (let i = label.indexOf("\n"); i !== -1; i = label.indexOf("\n", lineStart)) {
|
|
754
|
+
longest = Math.max(longest, i - lineStart);
|
|
755
|
+
lineStart = i + 1;
|
|
756
|
+
lines++;
|
|
757
|
+
}
|
|
758
|
+
const width = Math.max(longest, label.length - lineStart) * fontSize * CHAR_WIDTH_FACTOR;
|
|
759
|
+
const height = lines * fontSize * LINE_HEIGHT_FACTOR;
|
|
760
|
+
return [centerX - width / 2, centerY - height / 2, width, height];
|
|
667
761
|
}
|
|
668
762
|
|
|
669
|
-
function edgeLabelBox(cell: DomEl, ids: ById
|
|
763
|
+
function edgeLabelBox(cell: DomEl, ids: ById, routes: Map<DomEl, Point[]>): Rect | null {
|
|
670
764
|
if (cell.getAttribute("edge") === "1") {
|
|
671
|
-
const
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
const box = explicitEdgeLabelRect(cell, ids);
|
|
676
|
-
return box ? [attr(cell, "id"), box] : null;
|
|
765
|
+
const label = labelText(cell);
|
|
766
|
+
if (!label) return null;
|
|
767
|
+
const route = routes.get(cell) ?? edgeRoute(cell, ids);
|
|
768
|
+
return route ? labelBox(cell, route, label) : null;
|
|
677
769
|
}
|
|
678
|
-
return null;
|
|
770
|
+
return isEdgeLabel(cell) && labelText(cell) ? explicitEdgeLabelRect(cell, ids) : null;
|
|
679
771
|
}
|
|
680
772
|
|
|
681
773
|
/** Edge-label text lying on top of a shape; sizes are estimated, so phrased as "likely". */
|
|
682
|
-
function
|
|
683
|
-
|
|
684
|
-
|
|
774
|
+
function checkLabelOverlap(
|
|
775
|
+
cells: DomEl[], ids: ById, leaves: LeafBox[], routes: Map<DomEl, Point[]>, report: ValidationReport, find: Finding,
|
|
776
|
+
): void {
|
|
685
777
|
for (const cell of cells) {
|
|
686
778
|
if (!isVisible(cell, ids)) continue;
|
|
687
|
-
const
|
|
688
|
-
if (!
|
|
689
|
-
const [id, box] = labeled;
|
|
779
|
+
const box = edgeLabelBox(cell, ids, routes);
|
|
780
|
+
if (!box || hasInvalidNumber(box)) continue;
|
|
690
781
|
for (const [vertexId, vertexBox] of leaves) {
|
|
691
|
-
|
|
782
|
+
report.spend("edge label and vertex comparisons");
|
|
783
|
+
if (overlap(box, vertexBox)) find("warnings", () => `edge label ${repr(attr(cell, "id"))} likely overlaps vertex ${repr(vertexId)}`);
|
|
692
784
|
}
|
|
693
785
|
}
|
|
694
|
-
return warnings;
|
|
695
786
|
}
|
|
696
787
|
|
|
697
788
|
/** Drop waypoints on a straight run and sub-2px jogs (not real bends), keeping the route's shape. */
|
|
@@ -763,11 +854,14 @@ function orthogonalRoute(edge: DomEl, route: Point[]): Point[] | null {
|
|
|
763
854
|
function anchorSegment(points: Point[], fraction: number): number {
|
|
764
855
|
const lengths = points.slice(1).map((point, i) => Math.hypot(point[0] - points[i][0], point[1] - points[i][1]));
|
|
765
856
|
let remaining = lengths.reduce((sum, length) => sum + length, 0) * fraction;
|
|
857
|
+
let last = 0;
|
|
766
858
|
for (let i = 0; i < lengths.length; i++) {
|
|
767
|
-
if (
|
|
859
|
+
if (lengths[i] === 0) continue;
|
|
860
|
+
if (remaining < lengths[i]) return i;
|
|
768
861
|
remaining -= lengths[i];
|
|
862
|
+
last = i;
|
|
769
863
|
}
|
|
770
|
-
return
|
|
864
|
+
return last;
|
|
771
865
|
}
|
|
772
866
|
|
|
773
867
|
/**
|
|
@@ -776,57 +870,53 @@ function anchorSegment(points: Point[], fraction: number): number {
|
|
|
776
870
|
* another explicitly routed connector. A background color cannot fix these:
|
|
777
871
|
* the line visibly runs into the text.
|
|
778
872
|
*/
|
|
779
|
-
function
|
|
780
|
-
const
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
const warnings: string[] = [];
|
|
786
|
-
for (const cell of cells) {
|
|
787
|
-
const route = labelText(cell) ? visibleEdgeRoute(cell, ids) : null;
|
|
788
|
-
if (!route) continue;
|
|
789
|
-
const box = labelBox(cell, route);
|
|
790
|
-
if (hasInvalidNumber(box)) continue;
|
|
873
|
+
function checkLabelRoutes(routes: Map<DomEl, Point[]>, report: ValidationReport, find: Finding): void {
|
|
874
|
+
for (const [cell, route] of routes) {
|
|
875
|
+
const label = labelText(cell);
|
|
876
|
+
if (!label) continue;
|
|
877
|
+
const box = labelBox(cell, route, label);
|
|
878
|
+
if (!box || hasInvalidNumber(box)) continue;
|
|
791
879
|
const id = attr(cell, "id");
|
|
792
|
-
|
|
880
|
+
const anchor = anchorSegment(route, labelFraction(cell));
|
|
881
|
+
for (let i = 0; i < route.length - 1; i++) {
|
|
882
|
+
if (i !== anchor && routeHitsRect([route[i], route[i + 1]], box, report)) {
|
|
883
|
+
find("warnings", () => `edge label ${repr(id)} likely sits on a bend or another segment of its own connector; move it along the edge (geometry x) or change its offset so the text clears every segment`);
|
|
884
|
+
break;
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
for (const [other, otherRoute] of routes) {
|
|
888
|
+
report.spend("edge label and route comparisons");
|
|
889
|
+
if (other !== cell && routeHitsRect(otherRoute, box, report)) {
|
|
890
|
+
find("warnings", () => `edge label ${repr(id)} likely overlaps edge ${repr(attr(other, "id"))}`);
|
|
891
|
+
}
|
|
892
|
+
}
|
|
793
893
|
}
|
|
794
|
-
return warnings;
|
|
795
|
-
}
|
|
796
|
-
|
|
797
|
-
function visibleEdgeRoute(cell: DomEl, ids: ById): Point[] | null {
|
|
798
|
-
if (cell.getAttribute("edge") !== "1" || !isVisible(cell, ids)) return null;
|
|
799
|
-
const explicit = edgeRoute(cell, ids);
|
|
800
|
-
return explicit ? orthogonalRoute(cell, straightenRoute(explicit)) : null;
|
|
801
894
|
}
|
|
802
895
|
|
|
803
|
-
function
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
)
|
|
810
|
-
const warnings: string[] = [];
|
|
811
|
-
const anchor = anchorSegment(route, fraction);
|
|
812
|
-
const hitsOwnRoute = route.slice(1).some((point, i) => i !== anchor && routeHitsRect([route[i], point], box));
|
|
813
|
-
if (hitsOwnRoute) {
|
|
814
|
-
warnings.push(
|
|
815
|
-
`edge label ${repr(id)} likely sits on a bend or another segment of its own connector; move it along the edge (geometry x) or change its offset so the text clears every segment`,
|
|
816
|
-
);
|
|
896
|
+
function visibleEdgeRoutes(cells: DomEl[], ids: ById): Map<DomEl, Point[]> {
|
|
897
|
+
const routes = new Map<DomEl, Point[]>();
|
|
898
|
+
for (const cell of cells) {
|
|
899
|
+
if (cell.getAttribute("edge") !== "1" || !isVisible(cell, ids)) continue;
|
|
900
|
+
const explicit = edgeRoute(cell, ids);
|
|
901
|
+
const route = explicit ? orthogonalRoute(cell, straightenRoute(explicit)) : null;
|
|
902
|
+
if (route) routes.set(cell, route);
|
|
817
903
|
}
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
904
|
+
return routes;
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
function labelOnLineWarning(cell: DomEl, label: string, route: Point[] | undefined, report: ValidationReport): string | null {
|
|
908
|
+
if (cell.getAttribute("edge") !== "1" || (attr(cell, "style") ?? "").includes("labelBackgroundColor=")) return null;
|
|
909
|
+
if (route) {
|
|
910
|
+
const box = labelBox(cell, route, label);
|
|
911
|
+
if (!box || hasInvalidNumber(box)) return null;
|
|
912
|
+
const anchor = anchorSegment(route, labelFraction(cell));
|
|
913
|
+
if (!routeHitsRect([route[anchor], route[anchor + 1]], box, report)) return null;
|
|
914
|
+
} else {
|
|
915
|
+
// With no known route, only an undisplaced label is definitely on its line.
|
|
916
|
+
const geometry = firstByTag(cell, "mxGeometry");
|
|
917
|
+
const normal = geometry ? pyFloat(attr(geometry, "y") ?? "0") : 0;
|
|
918
|
+
if (normal !== 0 || labelOffset(cell)?.some((coordinate) => coordinate !== 0)) return null;
|
|
822
919
|
}
|
|
823
|
-
return warnings;
|
|
824
|
-
}
|
|
825
|
-
|
|
826
|
-
function labelOnLineWarning(cell: DomEl): string | null {
|
|
827
|
-
if (cell.getAttribute("edge") !== "1" || !labelText(cell)) return null;
|
|
828
|
-
if ((attr(cell, "style") ?? "").includes("labelBackgroundColor=")) return null;
|
|
829
|
-
if (labelOffset(cell)) return null;
|
|
830
920
|
return `edge ${repr(attr(cell, "id"))} label sits directly on its line; add an offset or labelBackgroundColor`;
|
|
831
921
|
}
|
|
832
922
|
|
|
@@ -873,127 +963,431 @@ function longLabelWarning(cell: DomEl, label: string, box: Rect | null): string
|
|
|
873
963
|
return `vertex ${repr(attr(cell, "id"))} has a long label in narrow geometry without whiteSpace=wrap`;
|
|
874
964
|
}
|
|
875
965
|
|
|
876
|
-
|
|
966
|
+
/** Conservative static checks only; uncertain typography remains a visual concern. */
|
|
967
|
+
function checkReadability(cell: DomEl, route: Point[] | undefined, report: ValidationReport, find: Finding): void {
|
|
877
968
|
const label = labelText(cell);
|
|
878
|
-
if (!label) return
|
|
969
|
+
if (!label) return;
|
|
879
970
|
const box = rect(cell);
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
);
|
|
971
|
+
const font = smallFontWarning(cell, box);
|
|
972
|
+
if (font) find("warnings", font);
|
|
973
|
+
const wrapping = longLabelWarning(cell, label, box);
|
|
974
|
+
if (wrapping) find("warnings", wrapping);
|
|
975
|
+
const onLine = labelOnLineWarning(cell, label, route, report);
|
|
976
|
+
if (onLine) find("warnings", onLine);
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
/** Walk a page without recursion or first materializing its node list. */
|
|
980
|
+
function admitDom(page: DomEl, report: ValidationReport): void {
|
|
981
|
+
const stack = [{ node: page, next: 0 }];
|
|
982
|
+
report.spend("DOM traversal");
|
|
983
|
+
while (stack.length > 0) {
|
|
984
|
+
const frame = stack.at(-1)!;
|
|
985
|
+
if (frame.next === frame.node.childNodes.length) {
|
|
986
|
+
stack.pop();
|
|
987
|
+
continue;
|
|
988
|
+
}
|
|
989
|
+
// Depth also costs work: bound the active stack even for a cell-free tree.
|
|
990
|
+
report.spend("DOM traversal", 1 + Math.floor(stack.length / 16));
|
|
991
|
+
const child = frame.node.childNodes[frame.next++];
|
|
992
|
+
if (child.nodeType === ELEMENT_NODE) stack.push({ node: child, next: 0 });
|
|
993
|
+
}
|
|
883
994
|
}
|
|
884
995
|
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
996
|
+
function admitCells(root: DomEl, report: ValidationReport): void {
|
|
997
|
+
let count = 0;
|
|
998
|
+
for (let i = 0; i < root.childNodes.length; i++) {
|
|
999
|
+
report.spend("cell admission");
|
|
1000
|
+
const child = root.childNodes[i];
|
|
1001
|
+
if (child.tagName !== "mxCell") {
|
|
1002
|
+
if (child.tagName !== "UserObject" && child.tagName !== "object") continue;
|
|
1003
|
+
report.spend("cell admission", child.childNodes.length);
|
|
1004
|
+
if (!firstByTag(child, "mxCell")) continue;
|
|
1005
|
+
}
|
|
1006
|
+
if (++count > report.limits.maxCellsPerPage) {
|
|
1007
|
+
throw new ValidationStop("cells", `page exceeds the ${report.limits.maxCellsPerPage}-cell limit`);
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
888
1010
|
}
|
|
889
1011
|
|
|
890
|
-
|
|
891
|
-
|
|
1012
|
+
/** Approximate repeated scans in chunks; one small geometry or text token costs one unit. */
|
|
1013
|
+
function textUnits(value: string | null): number {
|
|
1014
|
+
return Math.ceil((value?.length ?? 0) / 128);
|
|
892
1015
|
}
|
|
893
1016
|
|
|
894
|
-
function
|
|
895
|
-
const
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
1017
|
+
function localGeometryUnits(cell: DomEl, report: ValidationReport): number {
|
|
1018
|
+
const children = Math.ceil(cell.childNodes.length / 8);
|
|
1019
|
+
report.spend("cell geometry admission", children);
|
|
1020
|
+
const geometry = firstByTag(cell, "mxGeometry");
|
|
1021
|
+
let size = children + Math.ceil((geometry?.childNodes.length ?? 0) / 8);
|
|
1022
|
+
if (geometry) {
|
|
1023
|
+
for (const key of ["x", "y", "width", "height"]) size += textUnits(attr(geometry, key));
|
|
900
1024
|
}
|
|
901
|
-
|
|
1025
|
+
return Math.max(1, Math.ceil(size / 8));
|
|
1026
|
+
}
|
|
902
1027
|
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
const
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
)
|
|
1028
|
+
/** Detect each cycle once and memoize weighted ancestor-chain lengths in linear time. */
|
|
1029
|
+
function checkHierarchy(
|
|
1030
|
+
cells: DomEl[], ids: ById, local: Map<DomEl, number>, report: ValidationReport, find: Finding,
|
|
1031
|
+
): Map<DomEl, number> | null {
|
|
1032
|
+
const origins = new Map<DomEl, number>();
|
|
1033
|
+
let cyclic = false;
|
|
1034
|
+
for (const cell of cells) {
|
|
1035
|
+
if (origins.has(cell)) continue;
|
|
1036
|
+
const path: DomEl[] = [];
|
|
1037
|
+
const positions = new Map<DomEl, number>();
|
|
1038
|
+
let next: DomEl | undefined = cell;
|
|
1039
|
+
while (next && !origins.has(next)) {
|
|
1040
|
+
report.spend("containment hierarchy");
|
|
1041
|
+
const earlier = positions.get(next);
|
|
1042
|
+
if (earlier !== undefined) {
|
|
1043
|
+
cyclic = true;
|
|
1044
|
+
find("errors", () => {
|
|
1045
|
+
const members = path.slice(earlier, earlier + 4).map((member) => repr(attr(member, "id")));
|
|
1046
|
+
const more = path.length - earlier > members.length ? ", …" : "";
|
|
1047
|
+
return `parent cycle involving cell(s) ${members.join(", ")}${more}`;
|
|
1048
|
+
});
|
|
1049
|
+
break;
|
|
1050
|
+
}
|
|
1051
|
+
positions.set(next, path.length);
|
|
1052
|
+
path.push(next);
|
|
1053
|
+
const parent: string | null = attr(next, "parent");
|
|
1054
|
+
next = parent ? ids.get(parent) : undefined;
|
|
1055
|
+
}
|
|
1056
|
+
let cost = next ? origins.get(next) ?? 0 : 0;
|
|
1057
|
+
while (path.length > 0) {
|
|
1058
|
+
const member = path.pop()!;
|
|
1059
|
+
cost += local.get(member) ?? 1;
|
|
1060
|
+
origins.set(member, cost);
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
return cyclic ? null : origins;
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
function pointUnits(geometry: DomEl | null, report: ValidationReport): number {
|
|
1067
|
+
if (!geometry) return 0;
|
|
1068
|
+
const array = firstByTag(geometry, "Array");
|
|
1069
|
+
const containers = array ? [geometry, array] : [geometry];
|
|
1070
|
+
let cost = 0;
|
|
1071
|
+
for (const container of containers) {
|
|
1072
|
+
for (let i = 0; i < container.childNodes.length; i++) {
|
|
1073
|
+
report.spend("waypoint admission");
|
|
1074
|
+
const point = container.childNodes[i];
|
|
1075
|
+
cost++;
|
|
1076
|
+
if (point.tagName === "mxPoint") cost += textUnits(attr(point, "x")) + textUnits(attr(point, "y"));
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
return Math.ceil(cost / 8);
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
/** Prepay repeated scans in shared geometry helpers; nested comparisons are charged in their own loops. */
|
|
1083
|
+
function admitGeometry(cells: DomEl[], ids: ById, origins: Map<DomEl, number>, report: ValidationReport): void {
|
|
1084
|
+
const walk = (cell: DomEl | undefined) => cell ? origins.get(cell) ?? 1 : 0;
|
|
1085
|
+
const referenced = (cell: DomEl, key: string) => {
|
|
1086
|
+
const id = attr(cell, key);
|
|
1087
|
+
return id ? ids.get(id) : undefined;
|
|
1088
|
+
};
|
|
1089
|
+
const edgeCosts = new Map<DomEl, number>();
|
|
1090
|
+
const edgeCost = (edge: DomEl) => {
|
|
1091
|
+
const known = edgeCosts.get(edge);
|
|
1092
|
+
if (known !== undefined) return known;
|
|
1093
|
+
const terminals = walk(referenced(edge, "source")) + walk(referenced(edge, "target"));
|
|
1094
|
+
const waypoints = pointUnits(firstByTag(edge, "mxGeometry"), report);
|
|
1095
|
+
const cost = walk(edge) + terminals + waypoints + textUnits(attr(edge, "style"));
|
|
1096
|
+
edgeCosts.set(edge, cost);
|
|
1097
|
+
return cost;
|
|
1098
|
+
};
|
|
1099
|
+
for (const cell of cells) {
|
|
1100
|
+
// Visibility checks, absolute rectangles, and containment inspect these chains repeatedly.
|
|
1101
|
+
report.spend("ancestor walks", 5 * walk(cell) + 2 * walk(referenced(cell, "parent")));
|
|
1102
|
+
report.spend("style and label analysis", 1 + 8 * textUnits(attr(cell, "style")) + 6 * textUnits(attr(cell, "value")));
|
|
1103
|
+
if (attr(cell, "edge") === "1") report.spend("edge and waypoint analysis", 8 * edgeCost(cell));
|
|
1104
|
+
else if (isEdgeLabel(cell)) {
|
|
1105
|
+
const edge = referenced(cell, "parent");
|
|
1106
|
+
if (edge && attr(edge, "edge") === "1") report.spend("edge label geometry", 3 * edgeCost(edge));
|
|
1107
|
+
report.spend("edge label geometry", 3 * pointUnits(firstByTag(cell, "mxGeometry"), report));
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
function jsonObject(value: unknown): Record<string, unknown> | undefined {
|
|
1113
|
+
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
1114
|
+
? value as Record<string, unknown>
|
|
1115
|
+
: undefined;
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
/** Admission only: analyzers remain the authority for malformed JSON and effect semantics. */
|
|
1119
|
+
function timelineSteps(raw: string | null, envelope: string, stage: string, report: ValidationReport): unknown[] {
|
|
1120
|
+
if (raw === null) return [];
|
|
1121
|
+
report.spend(stage, 1 + textUnits(raw));
|
|
1122
|
+
try {
|
|
1123
|
+
const parsed: unknown = JSON.parse(raw);
|
|
1124
|
+
const obj = jsonObject(parsed);
|
|
1125
|
+
const timeline = jsonObject(obj?.[envelope]) ?? obj;
|
|
1126
|
+
return Array.isArray(timeline?.steps) ? timeline.steps : [];
|
|
1127
|
+
} catch {
|
|
1128
|
+
return [];
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
/** Budget the same root-cell candidates as the native analyzer, including a wrapped cell. */
|
|
1133
|
+
function nativeTimeline(root: DomEl): string | null {
|
|
1134
|
+
for (let i = 0; i < root.childNodes.length; i++) {
|
|
1135
|
+
const cell = root.childNodes[i];
|
|
1136
|
+
if (cell.nodeType !== ELEMENT_NODE || attr(cell, "id") !== "0") continue;
|
|
1137
|
+
const direct = attr(cell, "animation");
|
|
1138
|
+
if (direct !== null) return direct;
|
|
1139
|
+
const inner = firstByTag(cell, "mxCell");
|
|
1140
|
+
const nested = inner ? attr(inner, "animation") : null;
|
|
1141
|
+
if (nested !== null) return nested;
|
|
1142
|
+
}
|
|
1143
|
+
return null;
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
function admitNativeAnimation(root: DomEl, cells: DomEl[], report: ValidationReport): void {
|
|
1147
|
+
const stage = "native animation analysis";
|
|
1148
|
+
let animatable = 0;
|
|
1149
|
+
for (const cell of cells) {
|
|
1150
|
+
// Flow-style checks can emit several findings per cell.
|
|
1151
|
+
const style = attr(cell, "style");
|
|
1152
|
+
report.spend(stage, 1 + textUnits(style) + (style?.includes("flowAnimation") ? 4 : 0));
|
|
1153
|
+
if (attr(cell, "vertex") === "1" || attr(cell, "edge") === "1") animatable++;
|
|
1154
|
+
}
|
|
1155
|
+
const steps = timelineSteps(nativeTimeline(root), "animation", stage, report);
|
|
1156
|
+
report.spend(stage, 3 * steps.length);
|
|
1157
|
+
for (const step of steps) {
|
|
1158
|
+
const obj = jsonObject(step);
|
|
1159
|
+
if (!obj) continue;
|
|
1160
|
+
for (const action in obj) {
|
|
1161
|
+
if (!Object.hasOwn(obj, action) || action === "immediate") continue;
|
|
1162
|
+
report.spend(stage, 5); // Action-level validation, including possible diagnostic creation.
|
|
1163
|
+
const params = jsonObject(obj[action]);
|
|
1164
|
+
if (Array.isArray(params?.excludeCells)) report.spend(stage, params.excludeCells.length);
|
|
1165
|
+
if (!Array.isArray(params?.cells)) continue;
|
|
1166
|
+
// Selector setup copies the page's candidate set; each wildcard visits it again.
|
|
1167
|
+
report.spend(stage, animatable + params.cells.length);
|
|
1168
|
+
for (const reference of params.cells) if (reference === "*") report.spend(stage, animatable);
|
|
918
1169
|
}
|
|
919
|
-
|
|
920
|
-
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
function admitStoredMotion(raw: string, ids: ById, origins: Map<DomEl, number>, report: ValidationReport): void {
|
|
1174
|
+
const stage = "stored motion analysis";
|
|
1175
|
+
const steps = timelineSteps(raw, "motion", stage, report);
|
|
1176
|
+
if (steps.length === 0) return; // Cannot reach motion cell construction without steps.
|
|
1177
|
+
report.spend(stage, 8 * steps.length);
|
|
1178
|
+
const visits = new Map<string, number>();
|
|
1179
|
+
for (const raw of steps) {
|
|
1180
|
+
const step = jsonObject(raw);
|
|
1181
|
+
if (!Array.isArray(step?.cells)) continue;
|
|
1182
|
+
report.spend(stage, 3 * step.cells.length);
|
|
1183
|
+
for (const id of step.cells) {
|
|
1184
|
+
if (typeof id !== "string") continue;
|
|
1185
|
+
const cell = ids.get(id);
|
|
1186
|
+
if (!cell) continue;
|
|
1187
|
+
const seen = visits.get(id) ?? 0;
|
|
1188
|
+
// Track updates scan preceding keypoints. Account for growing tracks, repeated IDs/styles,
|
|
1189
|
+
// and the ancestor traversals needed to validate effective visibility.
|
|
1190
|
+
report.spend(stage, 1 + Math.ceil(seen / 4) + (origins.get(cell) ?? 1) + textUnits(id) + textUnits(attr(cell, "style")));
|
|
1191
|
+
visits.set(id, seen + 1);
|
|
921
1192
|
}
|
|
922
1193
|
}
|
|
1194
|
+
// The compiler snapshots tracked cells for each visual batch.
|
|
1195
|
+
report.spend(stage, steps.length * visits.size);
|
|
1196
|
+
// The analyzer builds a map and walks authored visibility for every vertex and edge,
|
|
1197
|
+
// not just ones named by the timeline. Use the already-computed chain costs.
|
|
1198
|
+
report.spend("stored motion cell ancestry", ids.size);
|
|
1199
|
+
for (const cell of ids.values()) {
|
|
1200
|
+
if (attr(cell, "vertex") === "1" || attr(cell, "edge") === "1") {
|
|
1201
|
+
report.spend("stored motion cell ancestry", origins.get(cell) ?? 1);
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
type AnalysisFinding = (severity: Severity, render: () => string) => void;
|
|
1207
|
+
|
|
1208
|
+
function analyzeWithFindings<T extends Partial<Record<Severity, string[]>> | null>(
|
|
1209
|
+
analyze: (input: DomEl, emit: AnalysisFinding) => T, input: DomEl, report: ValidationReport, find: Finding,
|
|
1210
|
+
): T {
|
|
1211
|
+
const analysis = analyze(input, (severity, render) => {
|
|
1212
|
+
find(severity, render);
|
|
1213
|
+
report.stopDiagnosticsAtCap();
|
|
1214
|
+
});
|
|
1215
|
+
// Streamed findings are not returned again in the analysis result.
|
|
1216
|
+
for (const severity of ["errors", "warnings", "observations"] as const) {
|
|
1217
|
+
for (const message of analysis?.[severity] ?? []) find(severity, message);
|
|
1218
|
+
}
|
|
1219
|
+
return analysis;
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
function checkAnimations(
|
|
1223
|
+
diagram: DomEl, model: DomEl, root: DomEl, cells: DomEl[], ids: ById, origins: Map<DomEl, number>,
|
|
1224
|
+
report: ValidationReport, find: Finding,
|
|
1225
|
+
): void {
|
|
1226
|
+
// Preflight delegate work (including possible diagnostics) before calling either analyzer.
|
|
1227
|
+
admitNativeAnimation(root, cells, report);
|
|
1228
|
+
const animation = analyzeWithFindings(analyzeAnimationPage, diagram, report, find);
|
|
1229
|
+
const rawMotion = readStoredMotion(model);
|
|
1230
|
+
if (rawMotion === null) return;
|
|
1231
|
+
admitStoredMotion(rawMotion, ids, origins, report);
|
|
1232
|
+
const motion = analyzeWithFindings(analyzeStoredMotion, model, report, find);
|
|
1233
|
+
if (!motion) return;
|
|
1234
|
+
if (motion.compiled) {
|
|
1235
|
+
find("observations", () =>
|
|
1236
|
+
`stored motion has ${motion.spec!.steps.length} step(s) lasting ${Math.round(motion.compiled!.sequenceMs)}ms; export it with drawio_animate`);
|
|
1237
|
+
}
|
|
1238
|
+
if (animation.sequence?.enabled) {
|
|
1239
|
+
find("errors", "page has both stored motion and an enabled native page animation; keep only one timeline");
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
function checkPage(diagram: DomEl, report: ValidationReport): void {
|
|
1244
|
+
const prefix = `page ${repr(attr(diagram, "name") ?? "?")}: `;
|
|
1245
|
+
const find: Finding = (severity, message, kind) => report.add(severity, message, kind, prefix);
|
|
1246
|
+
report.spend("page model lookup", 1 + diagram.childNodes.length);
|
|
1247
|
+
const model = graphModel(diagram);
|
|
1248
|
+
if (!model) {
|
|
1249
|
+
if (directText(diagram).trim()) {
|
|
1250
|
+
report.result.complete = false;
|
|
1251
|
+
find("warnings", "compressed, skipped (cannot lint)");
|
|
1252
|
+
} else find("errors", "no <mxGraphModel>");
|
|
1253
|
+
return;
|
|
1254
|
+
}
|
|
1255
|
+
if (model !== diagram) report.spend("page model lookup", model.childNodes.length);
|
|
1256
|
+
const root = firstByTag(model, "root");
|
|
1257
|
+
if (!root) {
|
|
1258
|
+
find("errors", "<mxGraphModel> is missing its <root> element");
|
|
1259
|
+
return;
|
|
1260
|
+
}
|
|
1261
|
+
admitCells(root, report);
|
|
1262
|
+
admitDom(diagram, report);
|
|
1263
|
+
const cells = collectCells(root);
|
|
1264
|
+
const ids = buildIds(cells, report, find);
|
|
923
1265
|
const parents = new Set<string | null>();
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
);
|
|
935
|
-
|
|
1266
|
+
const local = new Map<DomEl, number>();
|
|
1267
|
+
for (const cell of cells) {
|
|
1268
|
+
const work = localGeometryUnits(cell, report);
|
|
1269
|
+
report.spend("cell structure and geometry", work + textUnits(attr(cell, "style")));
|
|
1270
|
+
local.set(cell, work);
|
|
1271
|
+
parents.add(attr(cell, "parent"));
|
|
1272
|
+
checkCell(cell, ids, find);
|
|
1273
|
+
}
|
|
1274
|
+
const origins = checkHierarchy(cells, ids, local, report, find);
|
|
1275
|
+
if (!origins) return; // Spatial and motion analysis cannot trust a cyclic containment hierarchy.
|
|
1276
|
+
checkAnimations(diagram, model, root, cells, ids, origins, report, find);
|
|
1277
|
+
checkSiblingOverlap(cells, ids, parents, origins, report, find);
|
|
1278
|
+
admitGeometry(cells, ids, origins, report);
|
|
1279
|
+
const leaves = collectLeafBoxes(cells, ids, parents);
|
|
1280
|
+
checkRoutes(collectRoutedEdges(cells, ids), leaves, report, find);
|
|
1281
|
+
for (const cell of cells) checkEdgeAnchorFacing(cell, ids, find);
|
|
1282
|
+
const routes = visibleEdgeRoutes(cells, ids);
|
|
1283
|
+
checkLabelOverlap(cells, ids, leaves, routes, report, find);
|
|
1284
|
+
checkLabelRoutes(routes, report, find);
|
|
1285
|
+
for (const cell of cells) {
|
|
1286
|
+
const containment = containmentWarning(cell, ids);
|
|
1287
|
+
if (containment) find("warnings", containment);
|
|
1288
|
+
}
|
|
1289
|
+
for (const cell of cells) checkReadability(cell, routes.get(cell), report, find);
|
|
1290
|
+
checkPredictedRoutes(cells, ids, leaves, report, find);
|
|
936
1291
|
const autoRouted = autoRoutedEdgeWarning(cells, ids);
|
|
937
|
-
if (autoRouted) warnings
|
|
938
|
-
const settings = pageSettings(model,
|
|
939
|
-
|
|
940
|
-
|
|
1292
|
+
if (autoRouted) find("warnings", autoRouted);
|
|
1293
|
+
const settings = pageSettings(model, find);
|
|
1294
|
+
if (settings.enabled && settings.width !== undefined && settings.height !== undefined) {
|
|
1295
|
+
for (const warning of canvasWarnings(contentBounds(cells, ids), settings)) find("warnings", warning);
|
|
1296
|
+
}
|
|
941
1297
|
}
|
|
942
1298
|
|
|
943
|
-
/**
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
1299
|
+
/** Avoid building a huge DOM from dense markup within the byte ceiling. */
|
|
1300
|
+
function admitMarkup(xml: string, report: ValidationReport): void {
|
|
1301
|
+
let candidates = 0;
|
|
1302
|
+
let cursor = 0;
|
|
1303
|
+
for (;;) {
|
|
1304
|
+
const open = xml.indexOf("<", cursor);
|
|
1305
|
+
if (open === -1) return;
|
|
1306
|
+
cursor = open + 1;
|
|
1307
|
+
if (xml[cursor] === "/") continue;
|
|
1308
|
+
// This is a conservative admission check, not an XML parser. Charge actual DOM nodes
|
|
1309
|
+
// when visiting them; don't count tag-like text inside XML comments, CDATA or PIs here.
|
|
1310
|
+
report.checkWork("XML markup admission", ++candidates);
|
|
1311
|
+
const endMarker = xml.startsWith("<!--", open) ? "-->"
|
|
1312
|
+
: xml.startsWith("<![CDATA[", open) ? "]]>"
|
|
1313
|
+
: xml[cursor] === "?" ? "?>" : undefined;
|
|
1314
|
+
if (endMarker) {
|
|
1315
|
+
const end = xml.indexOf(endMarker, open + (endMarker === "-->" ? 4 : endMarker === "]]>" ? 9 : 2));
|
|
1316
|
+
if (end === -1) return; // Let xmldom diagnose the unterminated section.
|
|
1317
|
+
cursor = end + endMarker.length;
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
950
1321
|
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
}
|
|
1322
|
+
function parseDiagram(xml: string, report: ValidationReport): DomEl {
|
|
1323
|
+
let parserStop: ValidationStop | undefined;
|
|
1324
|
+
try {
|
|
1325
|
+
const doc = new DOMParser({
|
|
1326
|
+
onError(level, message) {
|
|
1327
|
+
if (level === "fatalError") return; // xmldom already throws a distinct parse failure.
|
|
1328
|
+
try {
|
|
1329
|
+
report.add("errors", () => `malformed XML: ${abbreviated(message, MAX_MESSAGE_LENGTH - 15)}`);
|
|
1330
|
+
report.stopDiagnosticsAtCap(); // Stop recovery now, even if the remaining XML has a fatal tail.
|
|
1331
|
+
} catch (error) {
|
|
1332
|
+
if (error instanceof ValidationStop) parserStop = error;
|
|
1333
|
+
throw error;
|
|
1334
|
+
}
|
|
1335
|
+
},
|
|
1336
|
+
}).parseFromString(xml, "text/xml");
|
|
1337
|
+
const root = doc.documentElement as unknown as DomEl | null;
|
|
1338
|
+
if (!root) throw new Error("no root element (malformed XML)");
|
|
1339
|
+
return root;
|
|
1340
|
+
} catch (error) {
|
|
1341
|
+
// xmldom wraps exceptions thrown from onError in ParseError.
|
|
1342
|
+
throw parserStop ?? error;
|
|
1343
|
+
}
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1346
|
+
function validate(xml: string, report: ValidationReport): ValidateResult {
|
|
1347
|
+
try {
|
|
1348
|
+
const maxBytes = report.limits.maxBytes;
|
|
1349
|
+
if (xml.length > maxBytes || Buffer.byteLength(xml) > maxBytes) throw new DiagramLimitError(maxBytes);
|
|
1350
|
+
admitMarkup(xml, report);
|
|
1351
|
+
const root = parseDiagram(xml, report);
|
|
1352
|
+
let pages = 0;
|
|
1353
|
+
if (root.tagName !== "diagram" && root.tagName !== "mxGraphModel") {
|
|
1354
|
+
for (let i = 0; i < root.childNodes.length; i++) {
|
|
1355
|
+
report.spend("page traversal");
|
|
1356
|
+
const page = root.childNodes[i];
|
|
1357
|
+
if (page.tagName !== "diagram") continue;
|
|
1358
|
+
if (++pages > report.limits.maxPages) {
|
|
1359
|
+
throw new ValidationStop("pages", `document exceeds the ${report.limits.maxPages}-page limit`);
|
|
1360
|
+
}
|
|
1361
|
+
checkPage(page, report);
|
|
1362
|
+
}
|
|
1363
|
+
}
|
|
1364
|
+
if (pages === 0) checkPage(root, report);
|
|
1365
|
+
return report.result;
|
|
1366
|
+
} catch (error) {
|
|
1367
|
+
if (error instanceof DiagramLimitError) return report.incomplete(`Validation incomplete: ${error.message}`, error.reason);
|
|
1368
|
+
if (error instanceof ValidationStop) return report.incomplete(`Validation incomplete: ${error.message}`, error.limit);
|
|
1369
|
+
throw error;
|
|
1370
|
+
}
|
|
970
1371
|
}
|
|
971
1372
|
|
|
972
|
-
|
|
973
|
-
|
|
1373
|
+
/** Lint a `.drawio` XML string. Throws on an unrecoverable parse failure. */
|
|
1374
|
+
export function validateXml(xml: string, limits?: Partial<ValidationLimits>): ValidateResult {
|
|
1375
|
+
return validate(xml, new ValidationReport(validationLimits(limits)));
|
|
974
1376
|
}
|
|
975
1377
|
|
|
976
|
-
/** Read and lint a `.drawio` file. Read/parse failures are returned as errors
|
|
977
|
-
export async function validateFile(path: string): Promise<ValidateResult> {
|
|
1378
|
+
/** Read and lint a `.drawio` file. Read/parse failures are returned as errors. */
|
|
1379
|
+
export async function validateFile(path: string, limits?: Partial<ValidationLimits>): Promise<ValidateResult> {
|
|
1380
|
+
const report = new ValidationReport(validationLimits(limits));
|
|
978
1381
|
let xml: string;
|
|
979
1382
|
try {
|
|
980
|
-
xml = await
|
|
1383
|
+
xml = await readDiagramXml(path, report.limits.maxBytes);
|
|
981
1384
|
} catch (error) {
|
|
982
|
-
return {
|
|
983
|
-
|
|
984
|
-
warnings: [],
|
|
985
|
-
observations: [],
|
|
986
|
-
score: emptyScore(),
|
|
987
|
-
};
|
|
1385
|
+
if (error instanceof DiagramLimitError) return report.incomplete(`Validation incomplete: ${error.message}`, error.reason);
|
|
1386
|
+
return report.incomplete(`cannot read ${repr(path)}: ${(error as Error).message}`);
|
|
988
1387
|
}
|
|
989
1388
|
try {
|
|
990
|
-
return
|
|
1389
|
+
return validate(xml, report);
|
|
991
1390
|
} catch (error) {
|
|
992
|
-
return {
|
|
993
|
-
errors: [`cannot parse ${path}: ${(error as Error).message}`],
|
|
994
|
-
warnings: [],
|
|
995
|
-
observations: [],
|
|
996
|
-
score: emptyScore(),
|
|
997
|
-
};
|
|
1391
|
+
return report.incomplete(`cannot parse ${repr(path)}: ${(error as Error).message}`);
|
|
998
1392
|
}
|
|
999
1393
|
}
|