@senad-d/drawme 0.1.11 → 0.3.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/src/animation.ts CHANGED
@@ -5,8 +5,10 @@
5
5
  */
6
6
  import { readFile, writeFile } from "node:fs/promises";
7
7
  import { DOMParser, XMLSerializer } from "@xmldom/xmldom";
8
- import { type DomEl, attr, childrenByTag, elemChildren, firstByTag } from "./dom";
8
+ import { readDiagramXml } from "./diagram-files";
9
+ import { type DomEl, attr, childrenByTag, elemChildren, firstByTag, graphModel } from "./dom";
9
10
  import { collectCells } from "./geometry";
11
+ import { cssString, walkElements } from "./svg-helpers";
10
12
 
11
13
  const PORTABLE_ACTIONS = new Set(["opacity", "show", "hide", "toggle", "fadeIn", "fadeOut", "fadeTo"]);
12
14
  const DRAWIO_ONLY_ACTIONS = new Set([
@@ -31,6 +33,8 @@ const DEFAULT_FADE_DURATION_MS = 1000;
31
33
  const INSTANT_EPSILON_MS = 0.01;
32
34
 
33
35
  type JsonObject = Record<string, unknown>;
36
+ type AnimationSeverity = "errors" | "warnings" | "observations";
37
+ type AnimationFinding = (severity: AnimationSeverity, render: () => string) => void;
34
38
 
35
39
  export interface NativeAnimationSequence {
36
40
  enabled: boolean;
@@ -66,7 +70,7 @@ interface OpacityPoint {
66
70
  interface CompiledTimeline {
67
71
  css: string;
68
72
  durationMs: number;
69
- animatedCellIds: string[];
73
+ requiredCellIds: string[];
70
74
  }
71
75
 
72
76
  function isObject(value: unknown): value is JsonObject {
@@ -86,22 +90,6 @@ function finiteNumber(value: unknown): number | null {
86
90
  return typeof value === "number" && Number.isFinite(value) ? value : null;
87
91
  }
88
92
 
89
- /** Quote an arbitrary draw.io cell id as a CSS attribute-selector string. */
90
- function cssString(value: string): string {
91
- let escaped = '"';
92
- for (const char of value) {
93
- const code = char.codePointAt(0)!;
94
- if (char === '"' || char === "\\") escaped += `\\${char}`;
95
- else if (code <= 0x1f || code === 0x7f) escaped += `\\${code.toString(16)} `;
96
- else escaped += char;
97
- }
98
- return `${escaped}"`;
99
- }
100
-
101
- function pageModel(diagram: DomEl): DomEl | null {
102
- return firstByTag(diagram, "mxGraphModel");
103
- }
104
-
105
93
  function animationAttribute(model: DomEl): string | null {
106
94
  const root = firstByTag(model, "root");
107
95
  if (!root) return null;
@@ -116,10 +104,10 @@ function animationAttribute(model: DomEl): string | null {
116
104
  return null;
117
105
  }
118
106
 
119
- function parseSequence(raw: string | null, errors: string[], warnings: string[]): NativeAnimationSequence | null {
107
+ function parseSequence(raw: string | null, find: AnimationFinding): NativeAnimationSequence | null {
120
108
  if (raw === null || raw.trim() === "") return null;
121
109
  if (!raw.trimStart().startsWith("{")) {
122
- warnings.push("legacy text page animations cannot be compiled to standalone animated SVG; save the animation as JSON");
110
+ find("warnings", () => "legacy text page animations cannot be compiled to standalone animated SVG; save the animation as JSON");
123
111
  return null;
124
112
  }
125
113
 
@@ -127,27 +115,27 @@ function parseSequence(raw: string | null, errors: string[], warnings: string[])
127
115
  try {
128
116
  parsed = JSON.parse(raw);
129
117
  } catch (error) {
130
- errors.push(`page animation contains malformed JSON: ${(error as Error).message}`);
118
+ find("errors", () => `page animation contains malformed JSON: ${(error as Error).message}`);
131
119
  return null;
132
120
  }
133
121
 
134
122
  if (!isObject(parsed)) {
135
- errors.push("page animation JSON must be an object");
123
+ find("errors", () => "page animation JSON must be an object");
136
124
  return null;
137
125
  }
138
126
  const value = isObject(parsed.animation) ? parsed.animation : parsed;
139
127
  if (!Array.isArray(value.steps)) {
140
- errors.push("page animation JSON must contain a steps array");
128
+ find("errors", () => "page animation JSON must contain a steps array");
141
129
  return null;
142
130
  }
143
131
  if (value.enabled !== undefined && typeof value.enabled !== "boolean") {
144
- errors.push("page animation enabled must be a boolean");
132
+ find("errors", () => "page animation enabled must be a boolean");
145
133
  }
146
134
  if (value.loop !== undefined && typeof value.loop !== "boolean") {
147
- errors.push("page animation loop must be a boolean");
135
+ find("errors", () => "page animation loop must be a boolean");
148
136
  }
149
137
 
150
- const steps = parseSequenceSteps(value.steps, errors);
138
+ const steps = parseSequenceSteps(value.steps, find);
151
139
  return {
152
140
  enabled: value.enabled === undefined ? true : value.enabled === true,
153
141
  loop: value.loop === undefined ? true : value.loop === true,
@@ -155,10 +143,10 @@ function parseSequence(raw: string | null, errors: string[], warnings: string[])
155
143
  };
156
144
  }
157
145
 
158
- function parseSequenceSteps(raw: unknown[], errors: string[]): JsonObject[] {
146
+ function parseSequenceSteps(raw: unknown[], find: AnimationFinding): JsonObject[] {
159
147
  const steps: JsonObject[] = [];
160
148
  raw.forEach((step, index) => {
161
- if (!isObject(step)) errors.push(`page animation step ${index + 1} must be an object`);
149
+ if (!isObject(step)) find("errors", () => `page animation step ${index + 1} must be an object`);
162
150
  else steps.push(step);
163
151
  });
164
152
  return steps;
@@ -176,38 +164,38 @@ function collectCellData(cells: DomEl[]): { byId: Map<string, DomEl>; animatable
176
164
  return { byId, animatable };
177
165
  }
178
166
 
179
- function validateFlowAnimations(cells: DomEl[], errors: string[], flowEdgeIds: string[]): void {
167
+ function validateFlowAnimations(cells: DomEl[], find: AnimationFinding, flowEdgeIds: string[]): void {
180
168
  for (const cell of cells) {
181
169
  const style = styleMap(attr(cell, "style"));
182
170
  const flow = style.get("flowAnimation");
183
171
  const id = attr(cell, "id") ?? "?";
184
172
  if (flow !== undefined && flow !== "0" && flow !== "1") {
185
- errors.push(`cell '${id}' has invalid flowAnimation '${flow}' (expected 0 or 1)`);
173
+ find("errors", () => `cell '${id}' has invalid flowAnimation '${flow}' (expected 0 or 1)`);
186
174
  continue;
187
175
  }
188
176
  if (flow !== "1") continue;
189
177
  if (cell.getAttribute("edge") !== "1") {
190
- errors.push(`cell '${id}' uses flowAnimation=1 but is not an edge`);
178
+ find("errors", () => `cell '${id}' uses flowAnimation=1 but is not an edge`);
191
179
  continue;
192
180
  }
193
181
  flowEdgeIds.push(id);
194
182
 
195
- validateFlowStyle(style, id, errors);
183
+ validateFlowStyle(style, id, find);
196
184
  }
197
185
  }
198
186
 
199
- function validateFlowStyle(style: Map<string, string>, id: string, errors: string[]): void {
187
+ function validateFlowStyle(style: Map<string, string>, id: string, find: AnimationFinding): void {
200
188
  const duration = style.get("flowAnimationDuration");
201
189
  if (duration !== undefined && (Number(duration) <= 0 || !Number.isFinite(Number(duration)))) {
202
- errors.push(`edge '${id}' has invalid flowAnimationDuration '${duration}' (expected a positive millisecond value)`);
190
+ find("errors", () => `edge '${id}' has invalid flowAnimationDuration '${duration}' (expected a positive millisecond value)`);
203
191
  }
204
192
  const direction = style.get("flowAnimationDirection");
205
193
  if (direction !== undefined && !FLOW_DIRECTIONS.has(direction)) {
206
- errors.push(`edge '${id}' has invalid flowAnimationDirection '${direction}'`);
194
+ find("errors", () => `edge '${id}' has invalid flowAnimationDirection '${direction}'`);
207
195
  }
208
196
  const timing = style.get("flowAnimationTimingFunction");
209
197
  if (timing !== undefined && !FLOW_TIMINGS.has(timing)) {
210
- errors.push(`edge '${id}' has invalid flowAnimationTimingFunction '${timing}'`);
198
+ find("errors", () => `edge '${id}' has invalid flowAnimationTimingFunction '${timing}'`);
211
199
  }
212
200
  }
213
201
 
@@ -217,16 +205,15 @@ function selectorIds(
217
205
  action: string,
218
206
  cells: Map<string, DomEl>,
219
207
  animatable: string[],
220
- errors: string[],
221
- warnings: string[],
208
+ find: AnimationFinding,
222
209
  ): string[] {
223
210
  if (params.layers !== undefined || params.tags !== undefined) {
224
- warnings.push(
211
+ find("warnings", () =>
225
212
  `page animation step ${stepNumber} action '${action}' uses layer/tag selectors, which standalone animated SVG does not support`,
226
213
  );
227
214
  }
228
215
  if (!Array.isArray(params.cells)) {
229
- errors.push(`page animation step ${stepNumber} action '${action}' must provide a cells array`);
216
+ find("errors", () => `page animation step ${stepNumber} action '${action}' must provide a cells array`);
230
217
  return [];
231
218
  }
232
219
 
@@ -234,28 +221,28 @@ function selectorIds(
234
221
  const animatableIds = new Set(animatable);
235
222
  for (const cellId of params.cells) {
236
223
  if (typeof cellId !== "string") {
237
- errors.push(`page animation step ${stepNumber} action '${action}' has a non-string cell id`);
224
+ find("errors", () => `page animation step ${stepNumber} action '${action}' has a non-string cell id`);
238
225
  continue;
239
226
  }
240
227
  if (cellId === "*") {
241
228
  for (const id of animatable) requested.add(id);
242
229
  } else if (!cells.has(cellId)) {
243
- errors.push(`page animation step ${stepNumber} action '${action}' references missing cell '${cellId}'`);
230
+ find("errors", () => `page animation step ${stepNumber} action '${action}' references missing cell '${cellId}'`);
244
231
  } else if (!animatableIds.has(cellId)) {
245
- errors.push(`page animation step ${stepNumber} action '${action}' references non-animatable cell '${cellId}'`);
232
+ find("errors", () => `page animation step ${stepNumber} action '${action}' references non-animatable cell '${cellId}'`);
246
233
  } else {
247
234
  requested.add(cellId);
248
235
  }
249
236
  }
250
237
 
251
- excludeSelectorIds(params.excludeCells, requested, stepNumber, action, errors);
238
+ excludeSelectorIds(params.excludeCells, requested, stepNumber, action, find);
252
239
  return [...requested];
253
240
  }
254
241
 
255
- function excludeSelectorIds(raw: unknown, requested: Set<string>, stepNumber: number, action: string, errors: string[]): void {
242
+ function excludeSelectorIds(raw: unknown, requested: Set<string>, stepNumber: number, action: string, find: AnimationFinding): void {
256
243
  if (raw === undefined) return;
257
244
  if (!Array.isArray(raw) || raw.some((id) => typeof id !== "string")) {
258
- errors.push(`page animation step ${stepNumber} action '${action}' has an invalid excludeCells array`);
245
+ find("errors", () => `page animation step ${stepNumber} action '${action}' has an invalid excludeCells array`);
259
246
  return;
260
247
  }
261
248
  for (const id of raw as string[]) {
@@ -264,17 +251,17 @@ function excludeSelectorIds(raw: unknown, requested: Set<string>, stepNumber: nu
264
251
  }
265
252
  }
266
253
 
267
- function validateActionParameters(action: string, params: JsonObject, stepNumber: number, errors: string[]): void {
254
+ function validateActionParameters(action: string, params: JsonObject, stepNumber: number, find: AnimationFinding): void {
268
255
  if (action === "opacity" || action === "fadeTo") {
269
256
  const value = finiteNumber(params.value);
270
257
  if (value === null || value < 0 || value > 1) {
271
- errors.push(`page animation step ${stepNumber} action '${action}' needs value between 0 and 1`);
258
+ find("errors", () => `page animation step ${stepNumber} action '${action}' needs value between 0 and 1`);
272
259
  }
273
260
  }
274
261
  if (action.startsWith("fade") && params.delay !== undefined) {
275
262
  const delay = finiteNumber(params.delay);
276
263
  if (delay === null || delay < 0) {
277
- errors.push(`page animation step ${stepNumber} action '${action}' has an invalid delay`);
264
+ find("errors", () => `page animation step ${stepNumber} action '${action}' has an invalid delay`);
278
265
  }
279
266
  }
280
267
  }
@@ -283,90 +270,86 @@ function validateSequence(
283
270
  sequence: NativeAnimationSequence,
284
271
  cells: Map<string, DomEl>,
285
272
  animatable: string[],
286
- errors: string[],
287
- warnings: string[],
273
+ find: AnimationFinding,
288
274
  ): void {
289
- if (sequence.enabled && sequence.steps.length === 0) errors.push("enabled page animation must contain at least one step");
275
+ if (sequence.enabled && sequence.steps.length === 0) find("errors", () => "enabled page animation must contain at least one step");
290
276
  let hasPortableVisualAction = false;
291
277
  for (let index = 0; index < sequence.steps.length; index++) {
292
278
  const step = sequence.steps[index];
293
279
  const stepNumber = index + 1;
294
280
  if (step.immediate !== undefined && typeof step.immediate !== "boolean") {
295
- errors.push(`page animation step ${stepNumber} immediate must be a boolean`);
281
+ find("errors", () => `page animation step ${stepNumber} immediate must be a boolean`);
296
282
  }
297
283
 
298
284
  const actions = Object.keys(step).filter((key) => key !== "immediate");
299
- if (actions.length === 0) errors.push(`page animation step ${stepNumber} has no action`);
285
+ if (actions.length === 0) find("errors", () => `page animation step ${stepNumber} has no action`);
300
286
  for (const action of actions) {
301
- const portable = validateSequenceAction(action, step[action], stepNumber, cells, animatable, errors, warnings);
287
+ const portable = validateSequenceAction(action, step[action], stepNumber, cells, animatable, find);
302
288
  hasPortableVisualAction ||= portable;
303
289
  }
304
290
  }
305
291
  if (sequence.enabled && sequence.steps.length > 0 && !hasPortableVisualAction) {
306
- errors.push("enabled page animation must contain at least one portable visual action");
292
+ find("errors", () => "enabled page animation must contain at least one portable visual action");
307
293
  }
308
294
  }
309
295
 
310
296
  function validateSequenceAction(
311
297
  action: string, raw: unknown, stepNumber: number, cells: Map<string, DomEl>,
312
- animatable: string[], errors: string[], warnings: string[],
298
+ animatable: string[], find: AnimationFinding,
313
299
  ): boolean {
314
300
  if (action === "wait") {
315
301
  const delay = finiteNumber(raw);
316
- if (delay === null || delay < 0) errors.push(`page animation step ${stepNumber} wait must be a non-negative number`);
302
+ if (delay === null || delay < 0) find("errors", () => `page animation step ${stepNumber} wait must be a non-negative number`);
317
303
  return false;
318
304
  }
319
305
  if (DRAWIO_ONLY_ACTIONS.has(action) || !PORTABLE_ACTIONS.has(action)) {
320
- warnings.push(`page animation step ${stepNumber} action '${action}' is not supported in standalone animated SVG`);
306
+ find("warnings", () => `page animation step ${stepNumber} action '${action}' is not supported in standalone animated SVG`);
321
307
  return false;
322
308
  }
323
309
  if (!isObject(raw)) {
324
- errors.push(`page animation step ${stepNumber} action '${action}' must be an object`);
310
+ find("errors", () => `page animation step ${stepNumber} action '${action}' must be an object`);
325
311
  return true;
326
312
  }
327
- selectorIds(raw, stepNumber, action, cells, animatable, errors, warnings);
328
- validateActionParameters(action, raw, stepNumber, errors);
313
+ selectorIds(raw, stepNumber, action, cells, animatable, find);
314
+ validateActionParameters(action, raw, stepNumber, find);
329
315
  return true;
330
316
  }
331
317
 
332
- export function analyzeAnimationPage(diagram: DomEl): PageAnimationAnalysis {
318
+ /** A supplied sink receives lazy findings synchronously, instead of accumulating them in the result. */
319
+ export function analyzeAnimationPage(diagram: DomEl, emit?: AnimationFinding): PageAnimationAnalysis {
333
320
  const pageName = attr(diagram, "name") ?? "?";
334
- const errors: string[] = [];
335
- const warnings: string[] = [];
336
- const observations: string[] = [];
337
- const model = pageModel(diagram);
321
+ const findings: Record<AnimationSeverity, string[]> = { errors: [], warnings: [], observations: [] };
322
+ const find: AnimationFinding = emit ?? ((severity, render) => { findings[severity].push(render()); });
323
+ const model = graphModel(diagram);
338
324
  if (!model) {
339
- errors.push("compressed or missing page model cannot be inspected for animation");
325
+ find("errors", () => "compressed or missing page model cannot be inspected for animation");
340
326
  return {
341
327
  pageName,
342
328
  flowEdgeIds: [],
343
329
  sequence: null,
344
330
  cells: new Map(),
345
331
  animatableCellIds: [],
346
- errors,
347
- warnings,
348
- observations,
332
+ ...findings,
349
333
  };
350
334
  }
351
335
 
352
336
  const cells = collectCells(firstByTag(model, "root"));
353
337
  const { byId, animatable } = collectCellData(cells);
354
338
  const flowEdgeIds: string[] = [];
355
- validateFlowAnimations(cells, errors, flowEdgeIds);
356
- const sequence = parseSequence(animationAttribute(model), errors, warnings);
357
- if (sequence) validateSequence(sequence, byId, animatable, errors, warnings);
339
+ validateFlowAnimations(cells, find, flowEdgeIds);
340
+ const sequence = parseSequence(animationAttribute(model), find);
341
+ if (sequence) validateSequence(sequence, byId, animatable, find);
358
342
 
359
343
  if (flowEdgeIds.length > 0) {
360
- const connectorIds = flowEdgeIds.map((id) => "'" + id + "'").join(", ");
361
- observations.push(
362
- `${flowEdgeIds.length} connector(s) use persistent flow animation; SVG preserves it, static formats do not: ${connectorIds}`,
363
- );
344
+ find("observations", () => {
345
+ const connectorIds = flowEdgeIds.map((id) => "'" + id + "'").join(", ");
346
+ return `${flowEdgeIds.length} connector(s) use persistent flow animation; SVG preserves it, static formats do not: ${connectorIds}`;
347
+ });
364
348
  }
365
349
  if (sequence) {
366
- observations.push(
367
- sequence.enabled
368
- ? `page animation contains ${sequence.steps.length} step(s); standalone animated SVG supports visibility, opacity, fade, and wait actions`
369
- : `page animation contains ${sequence.steps.length} step(s) but autoplay is disabled`,
350
+ find("observations", () => sequence.enabled
351
+ ? `page animation contains ${sequence.steps.length} step(s); standalone animated SVG supports visibility, opacity, fade, and wait actions`
352
+ : `page animation contains ${sequence.steps.length} step(s) but autoplay is disabled`,
370
353
  );
371
354
  }
372
355
 
@@ -376,13 +359,11 @@ export function analyzeAnimationPage(diagram: DomEl): PageAnimationAnalysis {
376
359
  sequence,
377
360
  cells: byId,
378
361
  animatableCellIds: animatable,
379
- errors,
380
- warnings,
381
- observations,
362
+ ...findings,
382
363
  };
383
364
  }
384
365
 
385
- export function analyzeDrawioAnimation(xml: string, pageIndex = 1): PageAnimationAnalysis {
366
+ function selectAnimationPage(xml: string, pageIndex: number): DomEl {
386
367
  if (!Number.isInteger(pageIndex) || pageIndex < 1) throw new Error("pageIndex must be a positive 1-based integer");
387
368
  const doc = new DOMParser().parseFromString(xml, "text/xml");
388
369
  const root = doc.documentElement as unknown as DomEl | null;
@@ -391,7 +372,11 @@ export function analyzeDrawioAnimation(xml: string, pageIndex = 1): PageAnimatio
391
372
  const pages = pageList.length > 0 ? pageList : [root];
392
373
  const page = pages[pageIndex - 1];
393
374
  if (!page) throw new Error(`pageIndex ${pageIndex} is out of range (diagram has ${pages.length} page(s))`);
394
- return analyzeAnimationPage(page);
375
+ return page;
376
+ }
377
+
378
+ export function analyzeDrawioAnimation(xml: string, pageIndex = 1): PageAnimationAnalysis {
379
+ return analyzeAnimationPage(selectAnimationPage(xml, pageIndex));
395
380
  }
396
381
 
397
382
  function actionDuration(action: string, value: unknown): number {
@@ -434,13 +419,10 @@ function compileOpacityTimeline(analysis: PageAnimationAnalysis): CompiledTimeli
434
419
  const sequence = analysis.sequence;
435
420
  if (!sequence?.enabled || sequence.steps.length === 0) return null;
436
421
 
437
- const states = new Map<string, number>();
422
+ const authoredOpacity = new Map(analysis.animatableCellIds.map((id) => [id, baseOpacity(analysis.cells.get(id)!)]));
423
+ const states = new Map(authoredOpacity);
438
424
  const tracks = new Map<string, OpacityPoint[]>();
439
- for (const id of analysis.animatableCellIds) {
440
- const value = baseOpacity(analysis.cells.get(id)!);
441
- states.set(id, value);
442
- tracks.set(id, [{ time: 0, value }]);
443
- }
425
+ for (const [id, value] of authoredOpacity) tracks.set(id, [{ time: 0, value }]);
444
426
 
445
427
  let time = 0;
446
428
  for (let index = 0; index < sequence.steps.length; ) {
@@ -451,10 +433,20 @@ function compileOpacityTimeline(analysis: PageAnimationAnalysis): CompiledTimeli
451
433
  }
452
434
 
453
435
  const durationMs = Math.max(1, time);
454
- const animated = [...tracks.entries()].filter(([, points]) => {
455
- const values = new Set(points.map((point) => point.value));
456
- return values.size > 1;
457
- });
436
+ const animated: [string, OpacityPoint[]][] = [];
437
+ const initialRules: string[] = [];
438
+ const requiredCellIds: string[] = [];
439
+ for (const [id, points] of tracks) {
440
+ const initial = points[0].value;
441
+ if (points.some((point) => point.value !== initial)) {
442
+ animated.push([id, points]);
443
+ requiredCellIds.push(id);
444
+ } else if (initial !== authoredOpacity.get(id)) {
445
+ initialRules.push(` g[data-cell-id=${cssString(id)}] { opacity: ${initial} !important; }`);
446
+ // A group omitted by draw.io is already hidden, but cannot be shown.
447
+ if (initial > 0) requiredCellIds.push(id);
448
+ }
449
+ }
458
450
  if (animated.length === 0) throw new Error("page animation has no visible opacity change to compile");
459
451
 
460
452
  const reducedMotionRules: string[] = [];
@@ -466,7 +458,7 @@ function compileOpacityTimeline(analysis: PageAnimationAnalysis): CompiledTimeli
466
458
  const name = `drawme-opacity-${index + 1}`;
467
459
  const selector = `g[data-cell-id=${cssString(id)}]`;
468
460
  reducedMotionRules.push(
469
- ` ${selector} { animation: none !important; opacity: ${baseOpacity(analysis.cells.get(id)!)} !important; }`,
461
+ ` ${selector} { animation: none !important; opacity: ${authoredOpacity.get(id)} !important; }`,
470
462
  );
471
463
  const keyframes = points
472
464
  .map((point) => ` ${((point.time / durationMs) * 100).toFixed(9)}% { opacity: ${point.value}; }`)
@@ -476,10 +468,13 @@ function compileOpacityTimeline(analysis: PageAnimationAnalysis): CompiledTimeli
476
468
  `${selector} { animation: ${name} ${durationMs}ms ease-in-out 0ms ${sequence.loop ? "infinite" : "1"} normal forwards; }`,
477
469
  );
478
470
  }
471
+ // Initial overrides last throughout playback, but leave the rendered static
472
+ // appearance untouched under reduced motion (including inline opacity).
473
+ if (initialRules.length > 0) rules.push(`@media not all and (prefers-reduced-motion: reduce) {\n${initialRules.join("\n")}\n}`);
479
474
  rules.push(
480
475
  `@media (prefers-reduced-motion: reduce) {\n${reducedMotionRules.join("\n")}\n g[data-cell-id] * { animation: none !important; }\n}`,
481
476
  );
482
- return { css: rules.join("\n"), durationMs, animatedCellIds: animated.map(([id]) => id) };
477
+ return { css: rules.join("\n"), durationMs, requiredCellIds };
483
478
  }
484
479
 
485
480
  function opacityEndpoints(action: string, params: JsonObject, current: number): [number, number] {
@@ -537,12 +532,6 @@ function compileOpacityBatch(
537
532
  return duration;
538
533
  }
539
534
 
540
- function walkElements(root: DomEl): DomEl[] {
541
- const elements: DomEl[] = [root];
542
- for (const child of elemChildren(root)) elements.push(...walkElements(child));
543
- return elements;
544
- }
545
-
546
535
  function hasAnimatedPath(root: DomEl): boolean {
547
536
  return walkElements(root).some((element) => {
548
537
  if (element.tagName !== "path") return false;
@@ -551,7 +540,7 @@ function hasAnimatedPath(root: DomEl): boolean {
551
540
  });
552
541
  }
553
542
 
554
- function verifyFlowGroups(ids: string[], groups: Map<string, DomEl>): void {
543
+ export function verifyFlowGroups(ids: string[], groups: Map<string, DomEl>): void {
555
544
  const missing = ids.filter((id) => !groups.has(id));
556
545
  if (missing.length > 0) {
557
546
  throw new Error(`SVG is missing animated connector group(s): ${missing.join(", ")}`);
@@ -564,7 +553,7 @@ function verifyFlowGroups(ids: string[], groups: Map<string, DomEl>): void {
564
553
 
565
554
  function verifyTimelineGroups(timeline: CompiledTimeline | null, groups: Map<string, DomEl>): void {
566
555
  if (!timeline) return;
567
- const missing = timeline.animatedCellIds.filter((id) => !groups.has(id));
556
+ const missing = timeline.requiredCellIds.filter((id) => !groups.has(id));
568
557
  if (missing.length > 0) {
569
558
  throw new Error(
570
559
  `SVG is missing page-animation cell group(s): ${missing.join(", ")}; do not use visible=0 for cells revealed by an animation`,
@@ -577,8 +566,8 @@ export async function enhanceAnimatedSvg(
577
566
  output: string,
578
567
  pageIndex = 1,
579
568
  ): Promise<AnimatedSvgSummary> {
580
- const source = await readFile(input, "utf8");
581
- const analysis = analyzeDrawioAnimation(source, pageIndex);
569
+ const page = selectAnimationPage(await readDiagramXml(input), pageIndex);
570
+ const analysis = analyzeAnimationPage(page);
582
571
  const blockers = [
583
572
  ...analysis.errors,
584
573
  ...(analysis.sequence?.enabled === false ? [] : analysis.warnings),
@@ -586,6 +575,13 @@ export async function enhanceAnimatedSvg(
586
575
  if (blockers.length > 0) throw new Error(blockers.join("; "));
587
576
  const activeSequence = analysis.sequence?.enabled === true && analysis.sequence.steps.length > 0;
588
577
  if (analysis.flowEdgeIds.length === 0 && !activeSequence) {
578
+ // Stored motion uses the native flow verifier, so defer access to its
579
+ // storage reader to the error path instead of creating a static cycle.
580
+ const { readStoredMotion } = await import("./motion");
581
+ const model = graphModel(page);
582
+ if (model && readStoredMotion(model)?.trim()) {
583
+ throw new Error("the selected page has stored DrawMe motion, not an enabled native sequence or flow; use drawio_animate with input and omit steps to reuse it");
584
+ }
589
585
  throw new Error("the selected page has no enabled page sequence or connector with flowAnimation=1");
590
586
  }
591
587
 
@@ -0,0 +1,159 @@
1
+ import { addAbortListener } from "node:events";
2
+ import { constants, type Stats } from "node:fs";
3
+ import { lstat, open, readlink, realpath, stat } from "node:fs/promises";
4
+ import { basename, dirname, isAbsolute, join, sep } from "node:path";
5
+ import { StringDecoder } from "node:string_decoder";
6
+
7
+ export const DEFAULT_XML_BYTES = 8 * 1024 * 1024;
8
+
9
+ export class DiagramLimitError extends Error {
10
+ readonly reason = "bytes";
11
+
12
+ constructor(maxBytes: number) {
13
+ super(`diagram XML exceeds the ${maxBytes}-byte limit`);
14
+ this.name = "DiagramLimitError";
15
+ }
16
+ }
17
+
18
+ function appendPath(directory: string, name: string): string {
19
+ const terminated = directory.endsWith(sep) || (sep === "\\" && directory.endsWith("/"));
20
+ return `${directory}${terminated ? "" : sep}${name}`;
21
+ }
22
+
23
+ /** Anchor without normalizing: symlink/.. must be interpreted by the filesystem. */
24
+ export function sessionPath(cwd: string, operand: string): string {
25
+ return isAbsolute(operand) ? operand : appendPath(cwd, operand);
26
+ }
27
+
28
+ /** Replace the filename without changing how its parent directory is reached. */
29
+ export function siblingPath(input: string, name: string): string {
30
+ const parent = dirname(input);
31
+ return parent === "." ? name : appendPath(parent, name);
32
+ }
33
+
34
+ function checkXmlFile(info: Stats, path: string, maxBytes: number): void {
35
+ if (!info.isFile()) throw new Error(`diagram is not a regular file: ${path}`);
36
+ if (info.size > maxBytes) throw new DiagramLimitError(maxBytes);
37
+ }
38
+
39
+ /** Check the path before opening it, then read at most maxBytes + 1 from the checked descriptor. */
40
+ export async function readDiagramXml(path: string, maxBytes = DEFAULT_XML_BYTES): Promise<string> {
41
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 0 || maxBytes === Number.MAX_SAFE_INTEGER) {
42
+ throw new RangeError("invalid diagram XML byte limit");
43
+ }
44
+ checkXmlFile(await stat(path), path, maxBytes);
45
+ // Nonblocking open covers a FIFO swapped in between the path check and open.
46
+ const handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
47
+ try {
48
+ checkXmlFile(await handle.stat(), path, maxBytes);
49
+ const buffer = Buffer.allocUnsafe(Math.min(64 * 1024, maxBytes + 1));
50
+ const decoder = new StringDecoder("utf8");
51
+ let xml = "";
52
+ let total = 0;
53
+ for (;;) {
54
+ const { bytesRead } = await handle.read(buffer, 0, Math.min(buffer.length, maxBytes + 1 - total), null);
55
+ if (bytesRead === 0) return xml + decoder.end();
56
+ total += bytesRead;
57
+ if (total > maxBytes) throw new DiagramLimitError(maxBytes);
58
+ xml += decoder.write(buffer.subarray(0, bytesRead));
59
+ }
60
+ } finally {
61
+ await handle.close();
62
+ }
63
+ }
64
+
65
+ async function fileKeys(path: string): Promise<string[]> {
66
+ const seen = new Set<string>();
67
+ for (;;) {
68
+ const parent = await realpath(dirname(path));
69
+ const entry = join(parent, basename(path));
70
+ // Use the physical directory entry even when it does not yet have an inode.
71
+ const entryKey = `entry:${sep === "\\" ? entry.toLowerCase() : entry}`;
72
+ let file;
73
+ try {
74
+ file = await lstat(entry, { bigint: true });
75
+ } catch (error) {
76
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [entryKey];
77
+ throw error;
78
+ }
79
+ if (!file.isSymbolicLink()) {
80
+ return file.ino === 0n ? [entryKey] : [entryKey, `inode:${file.dev}:${file.ino}`];
81
+ }
82
+ // A dangling destination link still reserves its target entry.
83
+ if (seen.has(entryKey)) throw new Error(`diagram path has a symlink loop: ${path}`);
84
+ seen.add(entryKey);
85
+ path = sessionPath(parent, await readlink(entry));
86
+ }
87
+ }
88
+
89
+ interface Waiter {
90
+ keys: ReadonlySet<string>;
91
+ enter: () => void;
92
+ }
93
+
94
+ const held = new Set<string>();
95
+ const waiting = new Set<Waiter>();
96
+
97
+ function admitWaiters(): void {
98
+ const claimed = new Set(held);
99
+ for (const waiter of waiting) {
100
+ if ([...waiter.keys].every((key) => !claimed.has(key))) {
101
+ for (const key of waiter.keys) held.add(key);
102
+ waiting.delete(waiter);
103
+ waiter.enter();
104
+ }
105
+ // An earlier waiter keeps its place for overlapping requests, but doesn't block disjoint ones.
106
+ for (const key of waiter.keys) claimed.add(key);
107
+ }
108
+ }
109
+
110
+ function reserve(keys: ReadonlySet<string>, signal: AbortSignal | undefined): Promise<void> {
111
+ signal?.throwIfAborted();
112
+ return new Promise<void>((resolve, reject) => {
113
+ let abort: Disposable | undefined;
114
+ const waiter: Waiter = {
115
+ keys,
116
+ enter: () => {
117
+ abort?.[Symbol.dispose]();
118
+ resolve();
119
+ },
120
+ };
121
+ waiting.add(waiter);
122
+ admitWaiters();
123
+ if (signal && waiting.has(waiter)) {
124
+ abort = addAbortListener(signal, () => {
125
+ waiting.delete(waiter);
126
+ reject(signal.reason);
127
+ admitWaiters();
128
+ });
129
+ }
130
+ });
131
+ }
132
+
133
+ async function keysFor(paths: readonly string[]): Promise<Set<string>> {
134
+ return new Set((await Promise.all(paths.map(fileKeys))).flat());
135
+ }
136
+
137
+ /** Process-local transaction. Actions must not re-enter for any of the files they reserve. */
138
+ export async function withDiagramFiles<T>(
139
+ paths: readonly string[], signal: AbortSignal | undefined, action: () => Promise<T>,
140
+ ): Promise<T> {
141
+ signal?.throwIfAborted();
142
+ const uniquePaths = [...new Set(paths)];
143
+ let keys = await keysFor(uniquePaths);
144
+ for (;;) {
145
+ await reserve(keys, signal);
146
+ let current: Set<string>;
147
+ try {
148
+ signal?.throwIfAborted();
149
+ // Waiting behind a replacement can invalidate an inode or a symlink target snapshot.
150
+ current = await keysFor(uniquePaths);
151
+ signal?.throwIfAborted();
152
+ if (current.size === keys.size && [...current].every((key) => keys.has(key))) return await action();
153
+ } finally {
154
+ for (const key of keys) held.delete(key);
155
+ admitWaiters();
156
+ }
157
+ keys = current;
158
+ }
159
+ }