alpha2 0.4.6 → 0.5.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.
Files changed (119) hide show
  1. package/README.md +5 -4
  2. package/THIRD_PARTY_NOTICES.md +4 -0
  3. package/dist/abort.d.ts +12 -0
  4. package/dist/abort.js +48 -0
  5. package/dist/active-clock.d.ts +35 -0
  6. package/dist/active-clock.js +99 -0
  7. package/dist/assets.d.ts +28 -22
  8. package/dist/assets.js +8 -12
  9. package/dist/audio-layout.d.ts +52 -74
  10. package/dist/audio-layout.js +114 -148
  11. package/dist/audio-timeline.d.ts +89 -117
  12. package/dist/audio-timeline.js +102 -118
  13. package/dist/audio-worker.d.ts +12 -21
  14. package/dist/audio-worker.js +8 -13
  15. package/dist/audio-worklet-processor.js +45 -58
  16. package/dist/audio-worklet.d.ts +45 -76
  17. package/dist/audio-worklet.js +44 -79
  18. package/dist/audio.d.ts +15 -23
  19. package/dist/audio.js +9 -13
  20. package/dist/builder.d.ts +45 -63
  21. package/dist/builder.js +49 -45
  22. package/dist/capabilities.d.ts +99 -16
  23. package/dist/capabilities.js +2 -2
  24. package/dist/captions.d.ts +45 -22
  25. package/dist/captions.js +60 -15
  26. package/dist/chroma-siting.d.ts +24 -41
  27. package/dist/chroma-siting.js +38 -71
  28. package/dist/containers.d.ts +41 -30
  29. package/dist/containers.js +59 -27
  30. package/dist/decoder-fallback.d.ts +13 -0
  31. package/dist/decoder-fallback.js +38 -0
  32. package/dist/decoder-order.d.ts +24 -39
  33. package/dist/decoder-order.js +28 -42
  34. package/dist/edit.d.ts +77 -154
  35. package/dist/edit.js +98 -180
  36. package/dist/effects.d.ts +108 -177
  37. package/dist/effects.js +7 -9
  38. package/dist/export-destination.d.ts +25 -41
  39. package/dist/export-destination.js +20 -32
  40. package/dist/export-failure.d.ts +34 -59
  41. package/dist/export-failure.js +54 -48
  42. package/dist/export-metrics.d.ts +116 -0
  43. package/dist/export-metrics.js +74 -0
  44. package/dist/export-retry.d.ts +46 -29
  45. package/dist/export-retry.js +86 -51
  46. package/dist/exporter.d.ts +67 -116
  47. package/dist/exporter.js +133 -133
  48. package/dist/extensions.d.ts +69 -115
  49. package/dist/extensions.js +55 -82
  50. package/dist/frame-intake.d.ts +92 -0
  51. package/dist/frame-intake.js +114 -0
  52. package/dist/frame-supply.d.ts +96 -162
  53. package/dist/frame-supply.js +181 -171
  54. package/dist/generated/project-schema.d.ts +701 -485
  55. package/dist/generated/project-schema.js +55 -2
  56. package/dist/generated/project-shape.js +261 -16
  57. package/dist/geometry.d.ts +28 -34
  58. package/dist/geometry.js +18 -23
  59. package/dist/gpu-recovery.d.ts +92 -0
  60. package/dist/gpu-recovery.js +135 -0
  61. package/dist/hdr-frames.d.ts +82 -67
  62. package/dist/hdr-frames.js +112 -49
  63. package/dist/index.d.ts +4 -0
  64. package/dist/index.js +4 -0
  65. package/dist/json-text.d.ts +13 -23
  66. package/dist/json-text.js +10 -20
  67. package/dist/layout-values.d.ts +14 -22
  68. package/dist/layout-values.js +18 -21
  69. package/dist/layout.d.ts +48 -63
  70. package/dist/layout.js +37 -37
  71. package/dist/loudness.d.ts +27 -32
  72. package/dist/loudness.js +19 -23
  73. package/dist/media.d.ts +85 -237
  74. package/dist/media.js +133 -287
  75. package/dist/mediabunny.d.ts +166 -245
  76. package/dist/mediabunny.js +741 -580
  77. package/dist/physical-frames.d.ts +5 -17
  78. package/dist/physical-frames.js +4 -11
  79. package/dist/player.d.ts +56 -47
  80. package/dist/player.js +155 -40
  81. package/dist/presented-frames.d.ts +2 -7
  82. package/dist/presented-frames.js +3 -8
  83. package/dist/project.d.ts +73 -117
  84. package/dist/project.js +384 -445
  85. package/dist/rate-control.d.ts +9 -23
  86. package/dist/rate-control.js +7 -18
  87. package/dist/renderer-choice.d.ts +41 -0
  88. package/dist/renderer-choice.js +82 -0
  89. package/dist/repacked-bytes.d.ts +0 -2
  90. package/dist/repacked-bytes.js +2 -5
  91. package/dist/robustness.d.ts +25 -37
  92. package/dist/robustness.js +71 -54
  93. package/dist/sha256.d.ts +5 -13
  94. package/dist/sha256.js +9 -24
  95. package/dist/text.d.ts +97 -71
  96. package/dist/text.js +33 -70
  97. package/dist/video-frames.d.ts +7 -25
  98. package/dist/video-frames.js +12 -29
  99. package/dist/waveform.d.ts +5 -11
  100. package/dist/waveform.js +4 -9
  101. package/dist/worker-error.d.ts +5 -20
  102. package/dist/worker-error.js +8 -25
  103. package/dist/worker.d.ts +82 -95
  104. package/dist/worker.js +235 -143
  105. package/package.json +26 -2
  106. package/wasm/alpha2_audio_worklet.wasm +0 -0
  107. package/wasm/alpha2_extensions.d.ts +26 -47
  108. package/wasm/alpha2_extensions.js +26 -47
  109. package/wasm/alpha2_extensions_bg.wasm +0 -0
  110. package/wasm/alpha2_wasm.d.ts +460 -567
  111. package/wasm/alpha2_wasm.js +594 -594
  112. package/wasm/alpha2_wasm_bg.wasm +0 -0
  113. package/wasm/alpha2_wasm_bg.wasm.d.ts +15 -8
  114. package/wasm/rust-crate-licenses.md +2 -2
  115. package/wasm/snippets/{alpha2-wasm-c62e60c964e88a52 → alpha2-wasm-1313375d424845c0}/inline1.js +1 -0
  116. package/wasm/snippets/alpha2-wasm-1313375d424845c0/inline2.js +82 -0
  117. package/wasm/snippets/alpha2-wasm-c62e60c964e88a52/inline2.js +0 -52
  118. /package/wasm/snippets/{alpha2-wasm-c62e60c964e88a52 → alpha2-wasm-1313375d424845c0}/inline0.js +0 -0
  119. /package/wasm/snippets/{alpha2-wasm-c62e60c964e88a52 → alpha2-wasm-1313375d424845c0}/inline3.js +0 -0
package/dist/project.js CHANGED
@@ -1,40 +1,27 @@
1
1
  /**
2
2
  * The alpha2 project document (schema version 1).
3
3
  *
4
- * The engine accepts this document as JSON through `loadProject`. Field names
5
- * are the wire names, so a value of type {@link Project} serializes directly
6
- * with `JSON.stringify`.
4
+ * Field names are the wire names, so a {@link Project} serializes directly with `JSON.stringify`.
5
+ * Types and limits are generated from `schema/project.v1.schema.json`; {@link validateProject}
6
+ * mirrors the model's invariants beyond the schema.
7
7
  *
8
- * The types and limits are generated from the Rust model's JSON Schema
9
- * (`schema/project.v1.schema.json`) into `generated/project-schema.ts`; this
10
- * module adds conversion helpers and {@link validateProject}. The schema fixes
11
- * the shape of a document, and `validateProject` mirrors the invariants the
12
- * model checks beyond it, pinned by the shared validation corpus.
13
- *
14
- * Timeline values are integer ticks at {@link TICKS_PER_SECOND}. Ranges are
15
- * half-open: `[start, end)`.
8
+ * Timeline values are integer ticks at {@link TICKS_PER_SECOND}. Ranges are half-open.
16
9
  */
17
10
  import { parseHex, parseInsets, parseLength, parseOffset, parsePlacement, parseSize, parseTrackList, } from "./layout-values.js";
18
- import { AUDIO_EFFECT_STATE_MARGIN_MS, MAX_CANVAS_DIMENSION, MAX_CANVAS_PIXELS, MAX_TEXT_CONTENT_BYTES, MAX_FONT_FAMILY_BYTES, MAX_COMPOSITIONS, MAX_COMPOSITION_NODES, MAX_COMPOSITION_CONTROLS, MAX_COMPOSITION_DEPTH, MAX_GROUP_INPUTS, MAX_EFFECT_INPUTS, MAX_FRAME_INLINED_NODES, MAX_INLINED_NODES, MAX_MERGE_LAYERS, MAX_CLIP_MASKS, MAX_DASH_ENTRIES, MAX_GRADIENT_STOPS, MAX_PATH_SUBPATHS, MAX_PATH_VERTICES, MAX_POLYSTAR_POINTS, MAX_SHAPE_DEPTH, MAX_SHAPE_ITEMS, MAX_LAYOUT_DEPTH, MAX_LAYOUT_FONT_SIZE, MAX_LAYOUT_ISOLATED, MAX_LAYOUT_NODES, MAX_LAYOUT_TEXTS, MAX_GRID_TRACKS, MIN_POLYSTAR_POINTS, MAX_CLIPS, MAX_CLIPS_PER_TRACK, MAX_AUDIO_DELAY_MS, MAX_AUDIO_EFFECTS, MAX_CAPTION_FONT_SIZE, MAX_TEXT_GENERATOR_FONT_SIZE, MAX_FONT_WEIGHT, MAX_LETTER_SPACING, MAX_LINE_HEIGHT, MAX_TEXT_OUTLINE_WIDTH, MAX_TEXT_PADDING, MAX_CHAIN_EFFECTS, MAX_COMPRESSOR_RATIO, MAX_ENVELOPE_MS, MAX_EQ_BANDS, MAX_LOOKAHEAD_MS, MIN_FONT_WEIGHT, MIN_LETTER_SPACING, MIN_LINE_HEIGHT, MIN_LEVEL_DB, MAX_EQ_FREQUENCY_HZ, MAX_EQ_GAIN_DB, MAX_EQ_Q, MAX_GAIN, MAX_PROJECT_JSON_BYTES, MAX_SAMPLE_RATE, MAX_TRACKS, MAX_TRANSITIONS_PER_TRACK, MIN_EQ_FREQUENCY_HZ, MIN_EQ_Q, MIN_SAMPLE_RATE, MIN_HDR_PEAK_NITS, MAX_HDR_PEAK_NITS, MAX_SEQUENCE_FRAMES, REVERB_DELAY_MS, TICKS_PER_SECOND, } from "./generated/project-schema.js";
11
+ import { AUDIO_EFFECT_STATE_MARGIN_MS, MAX_CANVAS_DIMENSION, MAX_CANVAS_PIXELS, MAX_TEXT_CONTENT_BYTES, MAX_FONT_FAMILY_BYTES, MAX_COMPOSITIONS, MAX_COMPOSITION_NODES, MAX_COMPOSITION_CONTROLS, MAX_COMPOSITION_DEPTH, MAX_GROUP_INPUTS, MAX_EFFECT_INPUTS, MAX_FRAME_INLINED_NODES, MAX_INLINED_NODES, MAX_MERGE_LAYERS, MAX_CLIP_MASKS, MAX_DASH_ENTRIES, MAX_GRADIENT_STOPS, MAX_PATH_SUBPATHS, MAX_PATH_VERTICES, MAX_POLYSTAR_POINTS, MAX_SHAPE_DEPTH, MAX_SHAPE_ITEMS, MAX_LAYOUT_DEPTH, MAX_LAYOUT_FONT_SIZE, MAX_LAYOUT_ISOLATED, MAX_LAYOUT_NODES, MAX_LAYOUT_TEXTS, MAX_GRID_TRACKS, MIN_POLYSTAR_POINTS, MAX_CLIPS, MAX_CLIPS_PER_TRACK, MAX_AUDIO_DELAY_MS, MAX_AUDIO_EFFECTS, MAX_CAPTION_FONT_SIZE, MAX_CAPTION_NAME_BYTES, MAX_CAPTION_STYLES, MAX_TEXT_GENERATOR_FONT_SIZE, MAX_FONT_WEIGHT, MAX_LETTER_SPACING, MAX_LINE_HEIGHT, MAX_TEXT_PADDING, MAX_ANIMATOR_SCALE, MAX_CLASS_NAME_BYTES, MAX_RANGE_INDEX, MAX_RANGE_PERCENT, MAX_RUN_CLASSES, MAX_TEXT_ANIMATORS, MAX_TEXT_RUNS, MIN_RANGE_PERCENT, MAX_TEXT_SHADOW_BLUR, MAX_TEXT_SHADOW_OFFSET, MAX_TEXT_SHADOWS, MAX_TEXT_STROKE_EXTENT, MAX_TEXT_STROKES, MAX_CHAIN_EFFECTS, MAX_COMPRESSOR_RATIO, MAX_ENVELOPE_MS, MAX_EQ_BANDS, MAX_LOOKAHEAD_MS, MIN_FONT_WEIGHT, MIN_LETTER_SPACING, MIN_LINE_HEIGHT, MIN_LEVEL_DB, MAX_EQ_FREQUENCY_HZ, MAX_EQ_GAIN_DB, MAX_EQ_Q, MAX_GAIN, MAX_PROJECT_JSON_BYTES, MAX_SAMPLE_RATE, MAX_TRACKS, MAX_TRANSITIONS_PER_TRACK, MIN_EQ_FREQUENCY_HZ, MIN_EQ_Q, MIN_SAMPLE_RATE, MIN_HDR_PEAK_NITS, MAX_HDR_PEAK_NITS, MAX_SEQUENCE_FRAMES, REVERB_DELAY_MS, TICKS_PER_SECOND, } from "./generated/project-schema.js";
19
12
  import { PROJECT_SHAPE } from "./generated/project-shape.js";
20
13
  import { MAX_JSON_DEPTH, hasLoneSurrogate, readJsonText, } from "./json-text.js";
21
14
  export * from "./generated/project-schema.js";
22
15
  /** The deepest nesting of arrays and objects the engine reads in a project (serde_json's limit). */
23
16
  export { MAX_JSON_DEPTH };
24
17
  /**
25
- * A CSS `cubic-bezier(x1, y1, x2, y2)` timing curve, usable as a transition
26
- * {@link Easing} and as a keyframe {@link Interpolation}. `x1` and `x2` must
27
- * lie in `0..=1`; `y1` and `y2` may overshoot.
18
+ * A CSS `cubic-bezier` curve, usable as an {@link Easing} or {@link Interpolation}. `x1` and `x2`
19
+ * must lie in `0..=1`; `y1` and `y2` may overshoot.
28
20
  */
29
21
  export function cubicBezier(x1, y1, x2, y2) {
30
22
  return { type: "cubic_bezier", x1, y1, x2, y2 };
31
23
  }
32
- /**
33
- * The CSS Easing Functions Level 1 named curves.
34
- *
35
- * The engine knows only `linear` and `cubic_bezier`; these are the standard values of the latter,
36
- * so a curve an editor calls `ease-in-out` means what the web and motion tools mean by it.
37
- */
24
+ /** The CSS Easing Functions Level 1 named curves, as `cubic_bezier` values. */
38
25
  export const EASING_PRESETS = {
39
26
  linear: { type: "linear" },
40
27
  ease: cubicBezier(0.25, 0.1, 0.25, 1),
@@ -44,27 +31,21 @@ export const EASING_PRESETS = {
44
31
  };
45
32
  /** Keeps a keyframe's value until the next keyframe. */
46
33
  export const HOLD = { type: "hold" };
47
- /** Creates a constant animated value. */
48
34
  export function constant(value) {
49
35
  return { mode: "constant", value };
50
36
  }
51
37
  /**
52
- * The tick nearest `seconds`, half a tick away from zero, as the engine reads a time in seconds.
53
- * Seconds rarely hold a tick exactly (1.001 s is just under tick 120120), so rounding is what gives
54
- * a time back its own tick: `secondsToTicks(ticksToSeconds(t)) === t`.
38
+ * The tick nearest `seconds`, ties away from zero, as the engine reads seconds. Rounding guarantees
39
+ * `secondsToTicks(ticksToSeconds(t)) === t`.
55
40
  */
56
41
  export function secondsToTicks(seconds) {
57
42
  const scaled = seconds * TICKS_PER_SECOND;
58
43
  return Math.sign(scaled) * Math.round(Math.abs(scaled));
59
44
  }
60
- /** Converts timeline ticks to seconds. */
61
45
  export function ticksToSeconds(ticks) {
62
46
  return ticks / TICKS_PER_SECOND;
63
47
  }
64
- /**
65
- * The tick at or before project-rate sample `samples`, negative samples included, as the engine's
66
- * `sample_ticks_floor`.
67
- */
48
+ /** The tick at or before sample `samples`, matching the engine's `sample_ticks_floor`. */
68
49
  export function samplesToTicks(samples, sampleRate) {
69
50
  if (sampleRate <= 0)
70
51
  return 0;
@@ -77,44 +58,30 @@ export function ticksToSamples(ticks, sampleRate) {
77
58
  return Math.floor((ticks * sampleRate) / TICKS_PER_SECOND);
78
59
  }
79
60
  /**
80
- * Structural problems found without opening any media.
81
- *
82
- * This mirrors the checks the Rust model makes so an editor can reject a document before a round
83
- * trip through wasm. The engine re-validates on load; this exists to give the UI a message, not to
84
- * replace that check.
85
- *
86
- * It checks in the engine's two layers. First the document's shape against the generated project
87
- * schema: JSON types, required fields, known enum and tag values, and no unknown fields. A document
88
- * of the wrong shape reports only those problems, as the engine's parser stops there. Then the
89
- * model's invariants: value ranges, limits, references, ordering, and transitions. A document over
90
- * a count limit (tracks, clips, sources, compositions and their nodes, transitions, caption cues)
91
- * reports only its counts, as the engine refuses it before reading what they count; a video track
92
- * reports its first overlap no transition covers. Past the counts, the work is linear in the
93
- * document.
61
+ * Structural problems found without opening any media, mirroring the engine's checks so an editor
62
+ * can reject a document before loading it. The engine still re-validates on load.
94
63
  *
95
- * The argument is typed, but documents usually arrive from `JSON.parse`, so a missing or mistyped
96
- * field is reported as a problem rather than thrown. This function never throws, and returns an
97
- * empty array for a valid document.
64
+ * Shape problems (types, required fields, enum values, unknown fields) are reported alone, as the
65
+ * engine's parser stops there. A document over a count limit reports only its counts. Otherwise the
66
+ * model's invariants are checked in time linear in the document.
98
67
  *
99
- * An object cannot show how its JSON was spelled: a repeated key or an integer written `1920.0` is
100
- * invisible here and refused by the engine's parser. Check text with {@link validateProjectJson}.
68
+ * Never throws; returns an empty array for a valid document. JSON spelling (repeated keys, `1920.0`
69
+ * for an integer) is invisible to an object; use {@link validateProjectJson} for text.
101
70
  */
102
71
  export function validateProject(project) {
103
72
  return projectProblems(project, undefined);
104
73
  }
105
74
  function projectProblems(project, spelling) {
106
- // A document from text is read once; an object may share parts with one validated before.
75
+ // Only objects can share parts with a document validated before.
107
76
  const reuse = spelling === undefined;
108
77
  const { problems: shape, read } = shapeProblems(project, spelling, reuse);
109
78
  if (shape.length > 0)
110
79
  return shape;
111
- // Each float field is read as a 32-bit float, as the engine does. Unchanged parts reuse what
112
- // earlier calls found; a problem is still worded by walking the whole document.
80
+ // Float fields are read as 32-bit, as the engine does. Problems are always worded by a full walk.
113
81
  if (reuse && invariantsHold(read))
114
82
  return [];
115
83
  return invariantProblems(read);
116
84
  }
117
- /** The project's model invariants past its shape, worded, in document order. */
118
85
  function invariantProblems(value) {
119
86
  const project = value;
120
87
  if (!isRecord(project))
@@ -133,8 +100,7 @@ function invariantProblems(value) {
133
100
  if (timeline === undefined)
134
101
  problems.push("timeline must be an object");
135
102
  const tracks = list(timeline?.tracks, "timeline.tracks", timeline !== undefined);
136
- // The engine refuses a document over any count before it reads what the counts hold, and so does
137
- // this: every check after this one is linear in a document within them.
103
+ // Like the engine, refuse over-count documents before reading what the counts hold.
138
104
  const counts = countProblems(sourceList, compositionList, tracks);
139
105
  if (counts.length > 0) {
140
106
  for (const problem of counts)
@@ -174,7 +140,6 @@ function invariantProblems(value) {
174
140
  problems.push(problem);
175
141
  return problems;
176
142
  }
177
- /** The project's id, its settings and its master bus. */
178
143
  function headerProblems(project) {
179
144
  const problems = [];
180
145
  if (text(project.id).length === 0)
@@ -219,7 +184,6 @@ function headerProblems(project) {
219
184
  }
220
185
  return problems;
221
186
  }
222
- /** The project's canvas, which its layouts' pixels are pixels of. */
223
187
  function canvasOf(project) {
224
188
  const settings = isRecord(project.settings)
225
189
  ? project.settings
@@ -316,7 +280,6 @@ function catalogOf(sourceList, resourceList, compositionList, canvas) {
316
280
  for (const composition of compositionList)
317
281
  if (isRecord(composition))
318
282
  compositionsById.set(text(composition.id), composition);
319
- // Each target's control names are built once for every group node drawing it.
320
283
  const controlNames = new Map();
321
284
  const controlNamesOf = (target) => {
322
285
  let names = controlNames.get(target);
@@ -337,7 +300,6 @@ function catalogOf(sourceList, resourceList, compositionList, canvas) {
337
300
  !compositions.has(text(source.composition)))
338
301
  problems.push(`source ${sourceId} is not a valid composition source`);
339
302
  const looping = compositionUsingItself(compositionsById, sources);
340
- // The nodes each composition draws once inlined, when they are all within bounds.
341
303
  let inlined;
342
304
  if (looping !== undefined)
343
305
  problems.push(`composition ${looping} uses itself`);
@@ -351,10 +313,9 @@ function catalogOf(sourceList, resourceList, compositionList, canvas) {
351
313
  return { problems, sources, effectResources, compositions, inlined };
352
314
  }
353
315
  /**
354
- * The problems of one track and its clips and transitions that the rest of the project bears on
355
- * only through `catalog`, and a clip id already in `clipIds` (which this adds the track's to).
356
- * With `reuse`, a clip that passed these checks before on a track of the same kind with the same
357
- * catalog is not checked again.
316
+ * Problems of one track that depend on the rest of the project only through `catalog`. Adds the
317
+ * track's clip ids to `clipIds`. With `reuse`, clips that passed before with the same kind and
318
+ * catalog are skipped.
358
319
  */
359
320
  function trackProblems(track, catalog, clipIds, reuse) {
360
321
  const problems = [];
@@ -369,9 +330,9 @@ function trackProblems(track, catalog, clipIds, reuse) {
369
330
  };
370
331
  const clips = list(track.clips, `track ${trackId} clips`);
371
332
  const transitions = list(track.transitions, `track ${trackId} transitions`);
372
- if (!validCaptions(track, clips, transitions)) {
373
- problems.push(`track ${trackId} has invalid captions`);
374
- }
333
+ const captions = captionsProblem(track, clips, transitions, trackId);
334
+ if (captions !== undefined)
335
+ problems.push(captions);
375
336
  const overlap = uncoveredOverlap(trackId, trackKind, clips, transitions);
376
337
  if (overlap !== undefined)
377
338
  problems.push(overlap);
@@ -416,7 +377,6 @@ function trackProblems(track, catalog, clipIds, reuse) {
416
377
  }
417
378
  return problems;
418
379
  }
419
- /** The problems of one clip on a track of `trackKind`, but for its id being another clip's too. */
420
380
  function clipProblems(clip, trackKind, catalog) {
421
381
  const problems = [];
422
382
  const clipId = text(clip.id);
@@ -474,9 +434,6 @@ function clipProblems(clip, trackKind, catalog) {
474
434
  }
475
435
  return problems;
476
436
  }
477
- /**
478
- * Each track's ducking: valid settings, and a sidechain among `trackIds` that leads back to none.
479
- */
480
437
  function duckingProblems(tracks, trackIds) {
481
438
  const problems = [];
482
439
  const cyclic = duckingCycles(tracks);
@@ -500,25 +457,15 @@ function duckingProblems(tracks, trackIds) {
500
457
  }
501
458
  return problems;
502
459
  }
503
- // Caches for the next validation. Deep-frozen plain data cannot change, so an edit that keeps the
504
- // unchanged parts pays only for what it changed. Only passes are cached; problems are always
505
- // rewalked.
506
- /** Deep-frozen plain values, and the values read from them: neither can change. */
460
+ // Validation caches. Deep-frozen plain data cannot change, so an edit pays only for what it
461
+ // changed. Only passes are cached; problems are always rewalked.
507
462
  const immutable = new WeakSet();
508
- /** The value read from an immutable value whose shape matched `node`. */
509
463
  const readShapes = new WeakMap();
510
- /** Immutable clips that passed `clipProblems` on a track of `kind` with `catalog`. */
511
464
  const checkedClips = new WeakMap();
512
- /** The catalog of an immutable source list, with the immutable lists it was made with. */
513
465
  const catalogs = new WeakMap();
514
- /** What {@link invariantsHold} keeps of an immutable track that passed `trackProblems`. */
515
466
  const trackSummaries = new WeakMap();
516
- /**
517
- * Whether `value`, and everything in it, is frozen plain data: arrays of items and objects of
518
- * enumerable fields, of the plain prototypes, whose own properties all hold values (a getter could
519
- * answer differently next time). Such a value reads as a copy of its fields would. What is found
520
- * so is remembered, so each object is looked into once.
521
- */
467
+ // Deep-frozen plain arrays and objects with data properties only (a getter could answer
468
+ // differently next time). Results are memoized in `immutable`.
522
469
  function sealed(value) {
523
470
  if (typeof value !== "object" || value === null)
524
471
  return true;
@@ -547,7 +494,6 @@ function sealed(value) {
547
494
  immutable.add(value);
548
495
  return true;
549
496
  }
550
- /** Remembers that immutable `value` matched `node` and reads as `read`, when both are sealed. */
551
497
  function rememberShape(node, value, read) {
552
498
  if (!sealed(value))
553
499
  return;
@@ -560,7 +506,6 @@ function rememberShape(node, value, read) {
560
506
  }
561
507
  readShapes.set(value, { node, read });
562
508
  }
563
- /** The catalog of the lists, the one made before when they are the same immutable lists. */
564
509
  function catalogFor(sources, resources, compositions, canvas) {
565
510
  const reusable = typeof sources === "object" &&
566
511
  sources !== null &&
@@ -619,11 +564,7 @@ function summaryOf(track, catalog) {
619
564
  trackSummaries.set(track, summary);
620
565
  return summary;
621
566
  }
622
- /**
623
- * Whether the invariants hold for `value`, a project whose shape matched, decided from the parts
624
- * earlier calls found to pass and a check of the rest. Holds exactly when
625
- * {@link invariantProblems} finds none: each of its checks is made here, on the same parts.
626
- */
567
+ // Must agree exactly with `invariantProblems` finding none, reusing cached passes.
627
568
  function invariantsHold(value) {
628
569
  if (!isRecord(value))
629
570
  return false;
@@ -664,13 +605,9 @@ function invariantsHold(value) {
664
605
  audioEffectProblems(project.audio, summaries.map((summary) => summary.audio)).length === 0 &&
665
606
  duckingProblems(tracks, trackIds).length === 0);
666
607
  }
667
- /**
668
- * The last set of tracks found to have no clip id in common, with the track holding each id. A
669
- * later call checks only the ids of the tracks not among them against those still present. One
670
- * set is kept, of the last project checked whole: an editor's projects share most tracks.
671
- */
608
+ // The last set of tracks found to share no clip id, so a later call checks only new tracks.
609
+ // Successive editor projects share most tracks.
672
610
  let distinctTracks;
673
- /** Whether no clip id is on two of the tracks (each track's own are distinct already). */
674
611
  function clipIdsUnique(summaries) {
675
612
  let total = 0;
676
613
  let holding = 0;
@@ -688,9 +625,8 @@ function clipIdsUnique(summaries) {
688
625
  let count = 0;
689
626
  for (const summary of added)
690
627
  count += summary.ids.length;
691
- // Past half the ids, starting over costs no more.
692
628
  if (count * 2 <= total) {
693
- // A track's own ids are distinct: only two or more new tracks can share one.
629
+ // A track's own ids are distinct, so only two or more new tracks can collide.
694
630
  const seen = added.length > 1 ? new Set() : undefined;
695
631
  for (const summary of added)
696
632
  for (const id of summary.ids) {
@@ -716,10 +652,7 @@ function clipIdsUnique(summaries) {
716
652
  distinctTracks = { members: present, owners };
717
653
  return true;
718
654
  }
719
- /**
720
- * Whether every matte holds, as {@link matteProblems} finds them in a project whose clip ids are
721
- * distinct: it names another clip on a video track, which has no matte and is in no transition.
722
- */
655
+ // Must agree with `matteProblems` for a project whose clip ids are distinct.
723
656
  function mattesHold(summaries) {
724
657
  const video = summaries.filter((summary) => summary.kind === "video");
725
658
  for (const summary of video)
@@ -738,12 +671,7 @@ function mattesHold(summaries) {
738
671
  }
739
672
  return true;
740
673
  }
741
- /**
742
- * The counts the engine bounds before it reads what they count: sources, tracks and compositions in
743
- * the project, nodes in each composition, clips, transitions and caption cues on each track, and
744
- * clips in all. The lists past the project's own are read only when those are within their limits,
745
- * so this is one step per track and composition of a document within them.
746
- */
674
+ // Nested lists are counted only when the top-level counts are within limits.
747
675
  function countProblems(sources, compositions, tracks) {
748
676
  const problems = [];
749
677
  if (sources.length > MAX_CLIPS)
@@ -779,18 +707,10 @@ function countProblems(sources, compositions, tracks) {
779
707
  return problems;
780
708
  }
781
709
  /**
782
- * Structural problems in a serialized document, including what only its text
783
- * shows.
784
- *
785
- * {@link validateProject} takes an object and therefore cannot see what the
786
- * engine checks in the text: `loadProject` rejects anything over
787
- * {@link MAX_PROJECT_JSON_BYTES} before it parses, and its parser refuses a
788
- * struct field given twice, an integer field spelled with a fraction or
789
- * exponent (`1920.0`, `1.92e3`, `-0`), and nesting deeper than 127 levels.
790
- * Hosts that hand the engine a string should validate the string, or a
791
- * document this package accepted can still be refused by the engine.
792
- *
793
- * Like {@link validateProject}, this never throws; malformed JSON is reported.
710
+ * Like {@link validateProject}, but also reports what only the text shows: size over
711
+ * {@link MAX_PROJECT_JSON_BYTES}, repeated fields, integers spelled with a fraction or exponent
712
+ * (`1920.0`, `1.92e3`, `-0`), and nesting deeper than 127 levels. Hosts that pass the engine a
713
+ * string should validate the string. Never throws; malformed JSON is reported.
794
714
  */
795
715
  export function validateProjectJson(json) {
796
716
  if (exceedsParseBudget(json)) {
@@ -799,8 +719,7 @@ export function validateProjectJson(json) {
799
719
  `project JSON is ${bytes} bytes, over the ${MAX_PROJECT_JSON_BYTES} byte limit`,
800
720
  ];
801
721
  }
802
- // `JSON.parse` decides whether the text is JSON and why not; `readJsonText` reads only accepted
803
- // text.
722
+ // `JSON.parse` supplies the error message; `readJsonText` assumes valid JSON.
804
723
  try {
805
724
  JSON.parse(json);
806
725
  }
@@ -816,9 +735,8 @@ export function validateProjectJson(json) {
816
735
  return projectProblems(read.value, read.spelling);
817
736
  }
818
737
  /**
819
- * Whether `rate` is a frame rate the engine reads: positive 32-bit integers
820
- * `num` and `den`, and a frame at least one tick long (at most
821
- * {@link TICKS_PER_SECOND} frames per second).
738
+ * Whether `rate` has positive 32-bit `num` and `den` and at most {@link TICKS_PER_SECOND} frames
739
+ * per second.
822
740
  */
823
741
  export function validFrameRate(rate) {
824
742
  return (isRecord(rate) &&
@@ -829,13 +747,8 @@ export function validFrameRate(rate) {
829
747
  rate.num <= TICKS_PER_SECOND * rate.den);
830
748
  }
831
749
  const MAX_U32 = 0xffff_ffff;
832
- /**
833
- * Whether the engine would refuse to parse this document.
834
- *
835
- * The engine measures UTF-8 bytes. Every UTF-16 code unit encodes to at least one UTF-8 byte and at
836
- * most three, so the code-unit count brackets the byte count from both sides and ordinary documents
837
- * are decided without the exact encode, which copies the whole string.
838
- */
750
+ // The engine measures UTF-8 bytes. Each UTF-16 unit encodes to 1 to 3 bytes, so most documents
751
+ // are decided without encoding the whole string.
839
752
  function exceedsParseBudget(json) {
840
753
  if (json.length > MAX_PROJECT_JSON_BYTES)
841
754
  return true;
@@ -845,13 +758,9 @@ function exceedsParseBudget(json) {
845
758
  }
846
759
  const shapeRoot = PROJECT_SHAPE;
847
760
  /**
848
- * Problems with a document's shape, found by walking the generated schema, and the document as the
849
- * engine reads it: a copy with each number the schema marks `format: "float"` rounded to a 32-bit
850
- * float, as the engine's parser stores it.
851
- *
852
- * The walk covers exactly the keywords the generator keeps (it refuses to generate any other), and
853
- * reports at most one problem per value: a tagged union is checked against the variant its tag
854
- * names.
761
+ * Walks the generated schema and returns shape problems plus the document as the engine reads it,
762
+ * with `format: "float"` numbers rounded to 32 bits. Reports at most one problem per value. The
763
+ * walk must cover exactly the keywords the generator emits.
855
764
  */
856
765
  function shapeProblems(value, spelling, reuse) {
857
766
  const problems = [];
@@ -864,13 +773,8 @@ function shapeProblems(value, spelling, reuse) {
864
773
  reusingShapes = false;
865
774
  }
866
775
  }
867
- /** Whether the walk running now reuses, and keeps, what it finds of immutable values. */
868
776
  let reusingShapes = false;
869
- /**
870
- * The shapes with a rule between their fields, which the schema cannot state and the engine's
871
- * parser enforces: a frame rate is at most one frame per tick, and a time range does not end before
872
- * it starts.
873
- */
777
+ // Cross-field rules the schema cannot state but the engine's parser enforces.
874
778
  const FRAME_RATE_SHAPE = shapeRoot.$defs
875
779
  .FrameRate;
876
780
  const TIME_RANGE_SHAPE = shapeRoot.$defs
@@ -886,10 +790,7 @@ function resolveShape(node) {
886
790
  function describeValue(value) {
887
791
  return JSON.stringify(value) ?? String(value);
888
792
  }
889
- /**
890
- * The integers each integer `format` of the schema holds: the Rust type the engine's parser reads
891
- * the field as.
892
- */
793
+ // Ranges of the Rust integer types behind each schema `format`.
893
794
  const INTEGER_FORMATS = {
894
795
  uint16: { min: 0n, max: 2n ** 16n - 1n },
895
796
  uint32: { min: 0n, max: 2n ** 32n - 1n },
@@ -897,10 +798,8 @@ const INTEGER_FORMATS = {
897
798
  int64: { min: -(2n ** 63n), max: 2n ** 63n - 1n },
898
799
  };
899
800
  /**
900
- * Checks `value` against `node` and returns it as the engine reads it (see
901
- * {@link shapeProblems}). `spelling` is how the document's text spelled its
902
- * members, when it came from text; `texts` are the texts of `value` itself
903
- * when it is a number its value does not spell (`JsonSpelling.numbers`).
801
+ * Checks `value` against `node` and returns it as the engine reads it. `texts` are the source
802
+ * spellings of a number its value does not round-trip (`JsonSpelling.numbers`).
904
803
  */
905
804
  function checkShape(node, value, path, problems, spelling, texts) {
906
805
  if (!reusingShapes || typeof value !== "object" || value === null)
@@ -914,23 +813,16 @@ function checkShape(node, value, path, problems, spelling, texts) {
914
813
  rememberShape(node, value, read);
915
814
  return read;
916
815
  }
917
- /**
918
- * The defs whose JSON is a CSS value form or an alternative spelling, read as the engine's parser
919
- * reads them (`alpha2_model::layout_values`): each problem worded as the parser words it, and the
920
- * value given to the model's checks in one form. A color is `{ red, green, blue, alpha }`, a paint
921
- * tagged, a layout length `{ unit, value }`, sides `{ top, right, bottom, left }` of lengths, an
922
- * offset `{ x, y }` of lengths, a track list its parsed components, a grid placement
923
- * `{ start, end }` edges.
924
- */
816
+ // Defs with CSS-style or alternative spellings are normalized to one form, with problems worded
817
+ // as `alpha2_model::layout_values` words them.
925
818
  const SHAPE_DEFS = shapeRoot.$defs;
926
- /** A value read by `parse`, its problem reported at `path` as the parser reports it. */
927
819
  function parsedOr(parsed, path, problems, value) {
928
820
  if (parsed.ok)
929
821
  return parsed.value;
930
822
  problems.push(`${path}: ${parsed.error}`);
931
823
  return value;
932
824
  }
933
- /** A length: a number is a fraction, a string `"<n>px"` or (with `percent`) `"<n>%"`. */
825
+ // A number is a fraction; a string is `"<n>px"` or, with `percent`, `"<n>%"`.
934
826
  function readLayoutLength(percent) {
935
827
  return (value, path, problems) => {
936
828
  if (typeof value === "number")
@@ -941,7 +833,6 @@ function readLayoutLength(percent) {
941
833
  return value;
942
834
  };
943
835
  }
944
- /** Fields of an object form: unknown ones refused, required ones present, each read by `read`. */
945
836
  function readFields(value, path, problems, fields, required, read, spelling) {
946
837
  for (const key of Object.keys(value)) {
947
838
  if (!fields.includes(key))
@@ -968,7 +859,6 @@ const SHAPE_READERS = new Map([
968
859
  (value, path, problems, spelling) => {
969
860
  if (typeof value === "string")
970
861
  return parsedOr(parseHex(value), path, problems, value);
971
- // The object form, or what is wrong with a value of neither form.
972
862
  const object = SHAPE_DEFS.Rgba.anyOf[0];
973
863
  return checkShape(object, value, path, problems, spelling);
974
864
  },
@@ -976,7 +866,7 @@ const SHAPE_READERS = new Map([
976
866
  [
977
867
  SHAPE_DEFS.Paint,
978
868
  (value, path, problems, spelling) => {
979
- // A color, hex or object, paints solid: told apart by its lack of a tag.
869
+ // An untagged color paints solid.
980
870
  if (typeof value === "string" ||
981
871
  (isRecord(value) && !("type" in value))) {
982
872
  const color = checkShape(SHAPE_DEFS.Rgba, value, path, problems, spelling);
@@ -1036,7 +926,7 @@ const SHAPE_READERS = new Map([
1036
926
  },
1037
927
  ],
1038
928
  ]);
1039
- /** The shortest decimal that reads back as the same 32-bit float, as the engine writes one. */
929
+ // The shortest decimal that reads back as the same 32-bit float, as the engine writes it.
1040
930
  function shortestFloat32(value) {
1041
931
  const target = Math.fround(value);
1042
932
  for (let digits = 1; digits < 9; digits++) {
@@ -1046,9 +936,14 @@ function shortestFloat32(value) {
1046
936
  }
1047
937
  return Number(target.toPrecision(9));
1048
938
  }
939
+ /** The whole text of a caption cue or text generator, with runs joined. */
940
+ export function textOf(content) {
941
+ return typeof content === "string"
942
+ ? content
943
+ : content.map((run) => run.text).join("");
944
+ }
1049
945
  /**
1050
- * `color` as the engine writes it: a CSS hex string becomes the components object, each
1051
- * component the 32-bit value the engine reads, spelled shortest.
946
+ * Converts a CSS hex color to the object form, with 32-bit components spelled shortest.
1052
947
  *
1053
948
  * @throws A `TypeError` for a string that is not CSS hex.
1054
949
  */
@@ -1067,8 +962,7 @@ export function canonicalRgba(color) {
1067
962
  };
1068
963
  }
1069
964
  /**
1070
- * `paint` as the engine writes it: a color (hex or object) becomes a solid paint of it, and
1071
- * every color in it the components object.
965
+ * Converts a paint to the tagged form the engine writes; a bare color becomes a solid paint.
1072
966
  *
1073
967
  * @throws A `TypeError` for a color string that is not CSS hex.
1074
968
  */
@@ -1087,21 +981,17 @@ export function canonicalPaint(paint) {
1087
981
  })),
1088
982
  };
1089
983
  }
1090
- /** A length read from a CSS token, written back as the engine writes it. */
1091
984
  function lengthWritten(length) {
1092
985
  const value = shortestFloat32(length.value);
1093
986
  return length.unit === "px" ? `${value}px` : value;
1094
987
  }
1095
- // The walk below reads what it can and leaves the rest as it is, for validation to report. Each
1096
- // step returns its input itself when nothing in it changes, so a document already in canonical
1097
- // form comes back as the same object, and a part that changes shares every part that did not.
1098
- /** `color` as an object; a string that is not hex stays as it is. */
988
+ // The readers below leave unreadable values for validation to report, and return their input
989
+ // itself when nothing changes so unchanged parts are shared.
1099
990
  function rgbaRead(color) {
1100
991
  if (typeof color !== "string")
1101
992
  return color;
1102
993
  return parseHex(color).ok ? canonicalRgba(color) : color;
1103
994
  }
1104
- /** `paint` tagged, its colors objects; what is not a paint stays as it is. */
1105
995
  function paintRead(paint) {
1106
996
  if (typeof paint === "string" || (isRecord(paint) && !("type" in paint))) {
1107
997
  const color = rgbaRead(paint);
@@ -1127,7 +1017,6 @@ function paintRead(paint) {
1127
1017
  : { ...paint, stops: read };
1128
1018
  }
1129
1019
  const SIDE_NAMES = ["top", "right", "bottom", "left"];
1130
- /** Sides as the four-side object; what cannot be read stays as it is. */
1131
1020
  function insetsRead(value) {
1132
1021
  if (typeof value === "number") {
1133
1022
  return { top: value, right: value, bottom: value, left: value };
@@ -1146,7 +1035,6 @@ function insetsRead(value) {
1146
1035
  ...SIDE_NAMES.map((side) => [side, value[side] ?? 0]),
1147
1036
  ]);
1148
1037
  }
1149
- /** An offset as `{ x, y }`; what cannot be read stays as it is. */
1150
1038
  function offsetRead(value) {
1151
1039
  if (typeof value !== "string")
1152
1040
  return value;
@@ -1156,17 +1044,12 @@ function offsetRead(value) {
1156
1044
  : value;
1157
1045
  }
1158
1046
  /**
1159
- * `project` in the forms the engine writes it back ({@link Canonical}): every color the
1160
- * components object, every paint tagged, every padding and margin the four sides, every offset
1161
- * `{ x, y }`. The forms the engine reads but never writes (CSS hex, a color as a paint, the
1162
- * sides shorthand, a `translate` string) are gone, so code that reads the document can take the
1163
- * one form. A value it cannot read (a string that is not hex, say) stays as it is, for
1164
- * {@link validateProject} to report: give it a document that validates to get a document in
1165
- * canonical form.
1047
+ * Returns `project` in the forms the engine writes ({@link Canonical}): object colors, tagged
1048
+ * paints, four-side insets and `{ x, y }` offsets. Unreadable values are left for
1049
+ * {@link validateProject} to report, so pass a valid document to get a fully canonical one.
1166
1050
  *
1167
- * The input is not changed. A part that is already canonical comes back as the same object, so
1168
- * a document in canonical form is returned itself, and a frozen part met before is not walked
1169
- * again: run on a changed copy of a document read before, it costs the parts that changed.
1051
+ * The input is not changed. Already-canonical parts are returned as the same objects, and frozen
1052
+ * parts seen before are not walked again.
1170
1053
  */
1171
1054
  export function canonicalProject(project) {
1172
1055
  const reusing = reusingShapes;
@@ -1178,9 +1061,8 @@ export function canonicalProject(project) {
1178
1061
  reusingShapes = reusing;
1179
1062
  }
1180
1063
  }
1181
- /** The canonical form of frozen values met before, by the node they were read as. */
1182
1064
  const canonicalShapes = new WeakMap();
1183
- /** The defs a value is put in canonical form at, and every def that can hold one of them. */
1065
+ // The defs that are canonicalized, plus every def that can contain one.
1184
1066
  const CANONICAL_DEFS = (() => {
1185
1067
  const holding = new Set([
1186
1068
  "Rgba",
@@ -1200,17 +1082,13 @@ const CANONICAL_DEFS = (() => {
1200
1082
  }
1201
1083
  return holding;
1202
1084
  })();
1203
- /** The defs `node` refers to anywhere in it. */
1204
1085
  function refsIn(node) {
1205
1086
  return [
1206
1087
  ...JSON.stringify(node).matchAll(/"\$ref":"#\/\$defs\/([^"]+)"/g),
1207
1088
  ].map((match) => match[1]);
1208
1089
  }
1209
1090
  const holdingNodes = new WeakMap();
1210
- /**
1211
- * Whether a value read as `node` can hold a color, paint, sides or offset. The walk does not
1212
- * read a field that cannot: it costs nothing, and reads nothing it has no use for.
1213
- */
1091
+ // Fields that cannot hold a canonicalized value are skipped.
1214
1092
  function mayHold(node) {
1215
1093
  let holds = holdingNodes.get(node);
1216
1094
  if (holds === undefined) {
@@ -1232,7 +1110,6 @@ function canonicalAt(node, value) {
1232
1110
  canonicalShapes.set(value, { node, canonical });
1233
1111
  return canonical;
1234
1112
  }
1235
- /** A string or number where a color, paint, sides or offset lies, in its canonical form. */
1236
1113
  function canonicalLeaf(node, value) {
1237
1114
  if (typeof node !== "object" || value === null || value === undefined)
1238
1115
  return value;
@@ -1250,7 +1127,7 @@ function canonicalWalk(node, value) {
1250
1127
  return offsetRead(value);
1251
1128
  const variants = (schema.oneOf ?? schema.anyOf);
1252
1129
  if (variants !== undefined) {
1253
- // The form that fits, as the parser picks it.
1130
+ // Pick the first form that fits, as the parser does.
1254
1131
  const fits = variants.find((variant) => {
1255
1132
  const found = [];
1256
1133
  checkShape(variant, value, "", found, undefined);
@@ -1274,7 +1151,6 @@ function canonicalWalk(node, value) {
1274
1151
  let read;
1275
1152
  for (const key of Object.keys(value)) {
1276
1153
  const field = Object.hasOwn(properties, key) ? properties[key] : extra;
1277
- // A field that cannot hold what is put in canonical form is not read.
1278
1154
  if (typeof field !== "object" || !mayHold(field))
1279
1155
  continue;
1280
1156
  const before = value[key];
@@ -1282,7 +1158,7 @@ function canonicalWalk(node, value) {
1282
1158
  if (canonical !== before)
1283
1159
  (read ??= {})[key] = canonical;
1284
1160
  }
1285
- // A clip's visual is written whole: each field left out is the schema's default, the engine's.
1161
+ // The engine writes a clip's visual whole, filling omitted fields with schema defaults.
1286
1162
  if (schema === SHAPE_DEFS.VisualProperties) {
1287
1163
  for (const [key, field] of Object.entries(properties)) {
1288
1164
  if (value[key] === undefined && field.default !== undefined)
@@ -1291,7 +1167,6 @@ function canonicalWalk(node, value) {
1291
1167
  }
1292
1168
  return read === undefined ? value : { ...value, ...read };
1293
1169
  }
1294
- /** {@link checkShape} of a value not known to match `node`. */
1295
1170
  function walkShape(node, value, path, problems, spelling, texts) {
1296
1171
  const schema = resolveShape(node);
1297
1172
  const reader = SHAPE_READERS.get(schema);
@@ -1386,16 +1261,11 @@ function integerBounds(schema) {
1386
1261
  integerBoundsByShape.set(schema, bounds);
1387
1262
  return bounds;
1388
1263
  }
1389
- /**
1390
- * Reports an integer field the engine does not read as its integer type: `value` from an object, or
1391
- * one of `texts`, the field's texts in a document's text when its value does not spell them. A
1392
- * number with a fraction, an exponent, or `-0` is not an integer to the engine, and one outside the
1393
- * schema's bounds or the range of its `format` is refused, not rounded.
1394
- */
1264
+ // The engine refuses (never rounds) integers spelled with a fraction, exponent or `-0`, and those
1265
+ // outside the schema bounds or `format` range.
1395
1266
  function checkInteger(schema, value, texts, path, problems) {
1396
1267
  const { min, max } = integerBounds(schema);
1397
- // A safe integer is written as its digits, so its value decides; any other is decided by what
1398
- // the engine reads: the document's text, or what `JSON.stringify` writes for it.
1268
+ // A safe integer's value decides; otherwise the spelling the engine would read decides.
1399
1269
  if (texts === undefined && Number.isSafeInteger(value)) {
1400
1270
  if (min !== undefined && value < Number(min)) {
1401
1271
  problems.push(`${path} must be at least ${min}`);
@@ -1442,8 +1312,7 @@ function isType(type, value) {
1442
1312
  }
1443
1313
  }
1444
1314
  function checkVariants(variants, value, path, problems, spelling, texts) {
1445
- // Forms are tried in order and the first that fits is the reading; every form's problems are
1446
- // only worth building when none fits, to report against the one the value meant.
1315
+ // The first fitting form wins. When none fits, report against the form the value meant.
1447
1316
  const tried = [];
1448
1317
  for (const variant of variants) {
1449
1318
  const found = [];
@@ -1458,14 +1327,12 @@ function checkVariants(variants, value, path, problems, spelling, texts) {
1458
1327
  problems.push(`${path} must be one of ${values.join(", ")}`);
1459
1328
  return value;
1460
1329
  }
1461
- // An optional value: report against the one form that is not `null`.
1462
1330
  const present = resolved.flatMap((variant, index) => variant.type === "null" ? [] : [index]);
1463
1331
  if (value !== null && present.length === 1) {
1464
1332
  for (const problem of tried[present[0]])
1465
1333
  problems.push(problem);
1466
1334
  return value;
1467
1335
  }
1468
- // A tagged union: report against the variant the value's tag selects.
1469
1336
  const tag = tagName(resolved);
1470
1337
  if (tag !== undefined && isRecord(value)) {
1471
1338
  const index = resolved.findIndex((variant) => variant.properties[tag].const ===
@@ -1482,7 +1349,6 @@ function checkVariants(variants, value, path, problems, spelling, texts) {
1482
1349
  problems.push(`${path} matches none of its allowed forms`);
1483
1350
  return value;
1484
1351
  }
1485
- /** The property every variant of a tagged union fixes to a constant. */
1486
1352
  function tagName(variants) {
1487
1353
  const first = variants[0]?.properties;
1488
1354
  if (!isRecord(first))
@@ -1519,23 +1385,21 @@ function checkArrayShape(schema, value, path, problems, spelling) {
1519
1385
  }
1520
1386
  function checkObjectShape(schema, value, path, problems, spelling) {
1521
1387
  const properties = (schema.properties ?? {});
1522
- // A struct field may appear once; a map (`additionalProperties`) keeps the last of a repeated
1523
- // key, as `JSON.parse` does.
1388
+ // A map (`additionalProperties`) keeps the last repeated key, as `JSON.parse` does.
1524
1389
  for (const name of spelling?.repeated.get(value) ?? []) {
1525
1390
  if (Object.hasOwn(properties, name)) {
1526
1391
  problems.push(`${path} has duplicate field ${describeValue(name)}`);
1527
1392
  }
1528
1393
  }
1529
1394
  const numbers = spelling?.numbers.get(value);
1530
- // `undefined` is an omitted field: `JSON.stringify` drops it.
1395
+ // `JSON.stringify` drops `undefined`, so it counts as omitted.
1531
1396
  for (const name of (schema.required ?? [])) {
1532
1397
  if (value[name] === undefined)
1533
1398
  problems.push(`${path}.${name} is required`);
1534
1399
  }
1535
1400
  const extra = schema.additionalProperties;
1536
1401
  const read = {};
1537
- // A key named `__proto__` is defined, not assigned: assigning it would replace the copy's
1538
- // prototype and leave the key out of the checks that follow.
1402
+ // Assigning `__proto__` would replace the copy's prototype instead of adding the key.
1539
1403
  const keep = (name, item) => {
1540
1404
  if (name === "__proto__") {
1541
1405
  Object.defineProperty(read, name, {
@@ -1581,11 +1445,9 @@ function checkObjectShape(schema, value, path, problems, spelling) {
1581
1445
  }
1582
1446
  return !changed && reusingShapes && sealed(value) ? value : read;
1583
1447
  }
1584
- /** Narrows an unknown value to a plain object. */
1585
1448
  function isRecord(value) {
1586
1449
  return typeof value === "object" && value !== null && !Array.isArray(value);
1587
1450
  }
1588
- /** Returns a string field, or `""` when it is absent or mistyped. */
1589
1451
  function text(value) {
1590
1452
  return typeof value === "string" ? value : "";
1591
1453
  }
@@ -1595,21 +1457,14 @@ function finiteNumber(value) {
1595
1457
  function safeInteger(value) {
1596
1458
  return typeof value === "number" && Number.isSafeInteger(value);
1597
1459
  }
1598
- /** An optional number: `fallback` when absent or `null`, `undefined` when mistyped. */
1460
+ // `fallback` when absent or `null`, `undefined` when mistyped.
1599
1461
  function optionalFinite(value, fallback) {
1600
1462
  if (value === undefined || value === null)
1601
1463
  return fallback;
1602
1464
  return finiteNumber(value) ? value : undefined;
1603
1465
  }
1604
- /**
1605
- * The first visual overlap no transition covers, in timeline order, as the engine reports it.
1606
- *
1607
- * Two visual clips at one timestamp have no defined composition without a transition. Overlapping
1608
- * audio does: the mixer sums it into the track bus, so audio tracks may overlay freely.
1609
- *
1610
- * Every clip still active when the next one starts overlaps it, so the walk meets at most one
1611
- * covered overlap per transition side before it either ends or stops here.
1612
- */
1466
+ // The first video overlap no transition covers, as the engine reports it. Audio tracks may
1467
+ // overlap freely because the mixer sums them.
1613
1468
  function uncoveredOverlap(trackId, trackKind, clips, transitions) {
1614
1469
  if (trackKind !== "video")
1615
1470
  return undefined;
@@ -1632,7 +1487,7 @@ function uncoveredOverlap(trackId, trackKind, clips, transitions) {
1632
1487
  ordered.sort(byTime);
1633
1488
  const active = [];
1634
1489
  for (const b of ordered) {
1635
- // The clips still active when `b` starts, in place: a track is usually one clip after another.
1490
+ // Keep only clips still active when `b` starts, in place.
1636
1491
  let kept = 0;
1637
1492
  for (const a of active)
1638
1493
  if (a.timeline_range.end > b.timeline_range.start)
@@ -1648,9 +1503,8 @@ function uncoveredOverlap(trackId, trackKind, clips, transitions) {
1648
1503
  }
1649
1504
  }
1650
1505
  active.push(b);
1651
- // As the engine checks: the transitions among clips active at one instant may not lead from
1652
- // clip to clip in a circle. A tournament has no cycle exactly when its clips lead to 0, 1, ...,
1653
- // k - 1 others.
1506
+ // Transitions among simultaneously active clips must not form a cycle. A tournament is
1507
+ // acyclic exactly when its out-degrees are 0, 1, ..., k - 1.
1654
1508
  if (active.length >= 3) {
1655
1509
  const leads = active
1656
1510
  .map((from) => active.filter((to) => directed.has(`${text(from.id)}\u0000${text(to.id)}`)).length)
@@ -1697,11 +1551,8 @@ function audioProblems(clipId, audio) {
1697
1551
  }
1698
1552
  return problems;
1699
1553
  }
1700
- /**
1701
- * Whether a clip's composition time fits a serialized tick until the clip ends, as the engine
1702
- * checks: it grows with the timeline time, so the last instant has the largest, `offset +
1703
- * floor((end - 1 - start) * num / den)`.
1704
- */
1554
+ // Composition time is largest at the clip's last instant: `offset + floor((end - 1 - start) *
1555
+ // num / den)`, which must fit a safe integer.
1705
1556
  function compositionTimeHeld(clip, reference, scale) {
1706
1557
  const range = clip.timeline_range;
1707
1558
  const num = scale === undefined ? 1 : scale.num;
@@ -1712,7 +1563,7 @@ function compositionTimeHeld(clip, reference, scale) {
1712
1563
  !positiveInteger(den) ||
1713
1564
  !Number.isSafeInteger(offset))
1714
1565
  return true;
1715
- // The range is not empty, so the scaled time is not negative and BigInt division rounds it down.
1566
+ // The range is non-empty, so BigInt division here rounds down.
1716
1567
  const elapsed = BigInt(range.end) - 1n - BigInt(range.start);
1717
1568
  const local = BigInt(offset) + (elapsed * BigInt(num)) / BigInt(den);
1718
1569
  return local <= BigInt(Number.MAX_SAFE_INTEGER);
@@ -1726,7 +1577,6 @@ function validRange(range) {
1726
1577
  safeInteger(range.end) &&
1727
1578
  range.end > range.start);
1728
1579
  }
1729
- /** A freeze's instant lies in the clip's half-open source range. */
1730
1580
  function freezesInside(timeMap, sourceRange) {
1731
1581
  if (!isRecord(timeMap) || timeMap.type !== "freeze")
1732
1582
  return true;
@@ -1738,7 +1588,6 @@ function freezesInside(timeMap, sourceRange) {
1738
1588
  instant >= sourceRange.start &&
1739
1589
  instant < sourceRange.end);
1740
1590
  }
1741
- /** Returns a range start for ordering checks; invalid ranges report separately. */
1742
1591
  function rangeStart(range) {
1743
1592
  return isRecord(range) && finiteNumber(range.start) ? range.start : 0;
1744
1593
  }
@@ -1767,10 +1616,7 @@ function animationValues(animation) {
1767
1616
  }
1768
1617
  return values;
1769
1618
  }
1770
- /**
1771
- * Whether an easing or interpolation's parameters are usable: a `cubic_bezier` keeps `x1` and `x2`
1772
- * in `0..=1` so the curve stays a function of time. `y1` and `y2` may overshoot.
1773
- */
1619
+ // `x1` and `x2` must lie in `0..=1` so the curve stays a function of time.
1774
1620
  function validCurve(curve) {
1775
1621
  if (!isRecord(curve))
1776
1622
  return false;
@@ -1797,7 +1643,6 @@ function validVec2Animation(animation) {
1797
1643
  const values = animationValues(animation);
1798
1644
  return values !== undefined && values.every(validVec2);
1799
1645
  }
1800
- /** Each field left out is its default, which is valid. */
1801
1646
  function validVisual(visual) {
1802
1647
  if (visual === undefined)
1803
1648
  return true;
@@ -1837,10 +1682,7 @@ function validEffectValue(value) {
1837
1682
  return false;
1838
1683
  }
1839
1684
  }
1840
- /**
1841
- * A constant or keyframed effect parameter: every value valid on its own, all of one type, and
1842
- * `enum` and `bool` keyframes holding.
1843
- */
1685
+ // All values share one type, and `enum` and `bool` keyframes must hold.
1844
1686
  function validEffectParam(param) {
1845
1687
  const values = animationValues(param);
1846
1688
  if (values === undefined || !values.every(validEffectValue))
@@ -1858,10 +1700,6 @@ function validEffectParam(param) {
1858
1700
  param.keyframes.every((keyframe) => isRecord(keyframe.interpolation) &&
1859
1701
  keyframe.interpolation.type === "hold"));
1860
1702
  }
1861
- /**
1862
- * A parameter, resource, or named input an effect may bind: an ASCII identifier, as the model
1863
- * requires.
1864
- */
1865
1703
  const EFFECT_BINDING_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
1866
1704
  function validClipEffect(effect) {
1867
1705
  if (!isRecord(effect))
@@ -1877,7 +1715,6 @@ function validClipEffect(effect) {
1877
1715
  Object.entries(params ?? {}).every(([name, value]) => EFFECT_BINDING_NAME.test(name) && validEffectParam(value)) &&
1878
1716
  Object.entries(resources ?? {}).every(([name, id]) => EFFECT_BINDING_NAME.test(name) && text(id).length > 0));
1879
1717
  }
1880
- /** An effect node's named inputs: absent, or at most `MAX_EFFECT_INPUTS` well-named ones. */
1881
1718
  function validEffectInputs(inputs) {
1882
1719
  if (inputs === undefined)
1883
1720
  return true;
@@ -1890,10 +1727,7 @@ function validEffectInputs(inputs) {
1890
1727
  function positiveMs(value) {
1891
1728
  return finiteNumber(value) && value > 0 && value <= MAX_ENVELOPE_MS;
1892
1729
  }
1893
- /**
1894
- * Whether `value`, read as the model's 32-bit float, lies in `[min, max]` (the model's limits,
1895
- * already 32-bit).
1896
- */
1730
+ // The model stores these as 32-bit floats; its limits are already 32-bit.
1897
1731
  function f32Within(value, min, max) {
1898
1732
  if (!finiteNumber(value))
1899
1733
  return false;
@@ -1944,26 +1778,19 @@ function validEffects(effects) {
1944
1778
  effects.length <= MAX_CHAIN_EFFECTS &&
1945
1779
  effects.every(validAudioEffect));
1946
1780
  }
1947
- /** Ticks in a millisecond. */
1948
1781
  const TICKS_PER_MS = TICKS_PER_SECOND / 1000;
1949
- /**
1950
- * What an effect counts toward {@link MAX_AUDIO_DELAY_MS}, in ticks, rounded up: a compressor its
1951
- * `lookahead_ms` at the model's 32-bit precision (times 120, exact in a double), a reverb {@link
1952
- * REVERB_DELAY_MS}. Whole ticks add up to the same number in any order, as the model's do.
1953
- */
1782
+ // Delay in whole ticks, rounded up, so sums match the model in any order.
1954
1783
  function effectDelayTicks(effect) {
1955
1784
  if (effect.type === "reverb")
1956
1785
  return REVERB_DELAY_MS * TICKS_PER_MS;
1957
1786
  return effectLookaheadTicks(effect);
1958
1787
  }
1959
- /** How early a mixer reads an effect's input, in ticks, rounded up: a compressor's lookahead. */
1960
1788
  function effectLookaheadTicks(effect) {
1961
1789
  if (effect.type !== "compressor" || !finiteNumber(effect.lookahead_ms))
1962
1790
  return 0;
1963
1791
  const lookahead = Math.fround(effect.lookahead_ms);
1964
1792
  return lookahead > 0 ? Math.ceil(lookahead * TICKS_PER_MS) : 0;
1965
1793
  }
1966
- /** The effects of a chain, its delay, and its lookahead, in ticks. */
1967
1794
  function chainLoad(effects) {
1968
1795
  const load = { count: 0, delay: 0, lookahead: 0 };
1969
1796
  if (!Array.isArray(effects))
@@ -1977,9 +1804,24 @@ function chainLoad(effects) {
1977
1804
  }
1978
1805
  return load;
1979
1806
  }
1980
- /**
1981
- * The load of `track` for {@link audioEffectProblems}; `undefined` for one that is not an object.
1982
- */
1807
+ // Mirrors `Clip::stretches_audio`.
1808
+ function stretchesAudio(clip) {
1809
+ if (!isRecord(clip.audio) || clip.audio.preserve_pitch !== true)
1810
+ return false;
1811
+ const map = clip.time_map;
1812
+ if (map !== undefined &&
1813
+ !(isRecord(map) && (map.type === "forward" || map.type === "reverse")))
1814
+ return false;
1815
+ const timeline = clip.timeline_range;
1816
+ const source = clip.source_range;
1817
+ if (!validRange(timeline) || !validRange(source))
1818
+ return false;
1819
+ const length = (range) => {
1820
+ const { start, end } = range;
1821
+ return end - start;
1822
+ };
1823
+ return length(timeline) !== length(source);
1824
+ }
1983
1825
  function trackAudioLoad(track) {
1984
1826
  if (!isRecord(track))
1985
1827
  return undefined;
@@ -1992,7 +1834,12 @@ function trackAudioLoad(track) {
1992
1834
  continue;
1993
1835
  if (!validRange(clip.timeline_range))
1994
1836
  continue;
1995
- const own = chainLoad(clip.audio.effects);
1837
+ // A stretched read holds state like one effect, without delay.
1838
+ const chain = chainLoad(clip.audio.effects);
1839
+ const own = {
1840
+ ...chain,
1841
+ count: chain.count + Number(stretchesAudio(clip)),
1842
+ };
1996
1843
  if (own.count === 0)
1997
1844
  continue;
1998
1845
  const lead = bus.lookahead + own.lookahead + margin;
@@ -2003,14 +1850,10 @@ function trackAudioLoad(track) {
2003
1850
  return { count: bus.count, delay: bus.delay, edges };
2004
1851
  }
2005
1852
  /**
2006
- * Mirrors the model's bound on the audio effect state a project holds at once
2007
- * (`Project::audio_effect_load`): at most {@link MAX_AUDIO_EFFECTS} effects, holding at most {@link
2008
- * MAX_AUDIO_DELAY_MS} of delay together (a compressor its `lookahead_ms`, a reverb {@link
2009
- * REVERB_DELAY_MS}). The master's and every track's effects hold state throughout; a clip's from
2010
- * {@link AUDIO_EFFECT_STATE_MARGIN_MS} and the lookahead of its track's and its own effects before
2011
- * its start (never before zero) to its end, both included. Each limit reports its peak and the
2012
- * earliest tick it is reached at, in whole ticks, so a document gets the same answer as natively.
2013
- * `tracks` are the {@link trackAudioLoad} of each track.
1853
+ * Mirrors `Project::audio_effect_load`. Master and track effects hold state throughout; a clip's
1854
+ * hold from {@link AUDIO_EFFECT_STATE_MARGIN_MS} plus lookahead before its start to its end.
1855
+ * Each limit reports its peak and the earliest tick it is reached, in whole ticks, to match the
1856
+ * native result.
2014
1857
  */
2015
1858
  function audioEffectProblems(master, tracks) {
2016
1859
  const held = chainLoad(isRecord(master) ? master.effects : undefined);
@@ -2023,8 +1866,7 @@ function audioEffectProblems(master, tracks) {
2023
1866
  delay += track.delay;
2024
1867
  }
2025
1868
  const edges = tracks.flatMap((track) => track?.edges ?? []);
2026
- // At one position, starts come before ends, since a clip ending where another starts holds
2027
- // state with it.
1869
+ // Starts sort before ends at one position: a clip ending where another starts overlaps it.
2028
1870
  edges.sort((a, b) => a.at - b.at || Number(a.ends) - Number(b.ends));
2029
1871
  const peak = { effects, effectsAt: 0, delay, delayAt: 0 };
2030
1872
  for (const edge of edges) {
@@ -2088,7 +1930,7 @@ function transitionProblems(trackId, trackKind, clips, transitions) {
2088
1930
  const problems = [];
2089
1931
  if (transitions.length === 0)
2090
1932
  return problems;
2091
- // The first clip of each id, as the engine's track index finds it.
1933
+ // The engine's track index keeps the first clip of each id.
2092
1934
  const byId = new Map();
2093
1935
  for (const clip of clips)
2094
1936
  if (isRecord(clip) && !byId.has(text(clip.id)))
@@ -2118,7 +1960,7 @@ function transitionProblems(trackId, trackKind, clips, transitions) {
2118
1960
  problems.push(`track ${trackId} has an invalid clip transition`);
2119
1961
  continue;
2120
1962
  }
2121
- // One transition per pair of clips, either way round, as the engine requires.
1963
+ // At most one transition per pair of clips, in either direction.
2122
1964
  const ends = [text(transition.from_clip), text(transition.to_clip)].sort();
2123
1965
  const pair = JSON.stringify(ends);
2124
1966
  if (pairs.has(pair)) {
@@ -2128,68 +1970,252 @@ function transitionProblems(trackId, trackKind, clips, transitions) {
2128
1970
  }
2129
1971
  return problems;
2130
1972
  }
2131
- /**
2132
- * A caption track holds valid captions and no clips or transitions; no other track holds captions.
2133
- */
2134
- function validCaptions(track, clips, transitions) {
1973
+ /** Mirrors `validate_captions`, worded as the engine words it. */
1974
+ function captionsProblem(track, clips, transitions, trackId) {
1975
+ const invalid = `track ${trackId} has invalid captions`;
2135
1976
  if (track.kind !== "caption")
2136
- return track.captions == null;
1977
+ return track.captions == null ? undefined : invalid;
2137
1978
  const captions = track.captions;
2138
1979
  if (!isRecord(captions) || clips.length > 0 || transitions.length > 0) {
2139
- return false;
1980
+ return invalid;
2140
1981
  }
2141
1982
  const cues = captions.cues;
1983
+ const styles = captions.styles ?? {};
1984
+ const encoder = new TextEncoder();
1985
+ const name = (value) => typeof value === "string" &&
1986
+ value.length > 0 &&
1987
+ encoder.encode(value).length <= MAX_CAPTION_NAME_BYTES;
2142
1988
  if (!Array.isArray(cues) ||
2143
- !validTextStyle(captions.style ?? {}, MAX_CAPTION_FONT_SIZE)) {
2144
- return false;
1989
+ !validTextStyle(captions.style ?? {}, MAX_CAPTION_FONT_SIZE) ||
1990
+ !isRecord(styles) ||
1991
+ Object.keys(styles).length > MAX_CAPTION_STYLES ||
1992
+ !Object.keys(styles).every(name)) {
1993
+ return invalid;
2145
1994
  }
2146
- const encoder = new TextEncoder();
2147
1995
  let previousEnd = 0;
2148
- return cues.every((cue) => {
1996
+ const cuesValid = cues.every((cue) => {
2149
1997
  if (!isRecord(cue) || !validRange(cue.timeline_range))
2150
1998
  return false;
2151
1999
  const range = cue.timeline_range;
2152
- const cueText = cue.text;
2153
2000
  const valid = range.start >= previousEnd &&
2154
- typeof cueText === "string" &&
2155
- cueText.length > 0 &&
2156
- encoder.encode(cueText).length <= MAX_TEXT_CONTENT_BYTES;
2001
+ validTextContent(cue.text, encoder) &&
2002
+ (cue.speaker == null || name(cue.speaker)) &&
2003
+ runTimesLieIn(cue.text, range.end - range.start);
2157
2004
  previousEnd = range.end;
2158
2005
  return valid;
2159
2006
  });
2007
+ if (!cuesValid)
2008
+ return invalid;
2009
+ for (const [index, cue] of cues.entries()) {
2010
+ const own = cue.style;
2011
+ if (typeof own === "string" && !Object.hasOwn(styles, own)) {
2012
+ return `cue ${index} of track ${trackId} names style ${JSON.stringify(own)}, which the track does not have`;
2013
+ }
2014
+ const patchName = typeof own === "string"
2015
+ ? own
2016
+ : typeof cue.speaker === "string" && Object.hasOwn(styles, cue.speaker)
2017
+ ? cue.speaker
2018
+ : undefined;
2019
+ if (patchName === undefined)
2020
+ continue;
2021
+ const merged = patchedStyle(captions.style ?? {}, styles[patchName]);
2022
+ if (!validTextStyle(merged, MAX_CAPTION_FONT_SIZE)) {
2023
+ return `cue ${index} of track ${trackId} has a style out of range once its patch is applied`;
2024
+ }
2025
+ }
2026
+ return undefined;
2027
+ }
2028
+ function runTimesLieIn(text, duration) {
2029
+ if (!Array.isArray(text))
2030
+ return true;
2031
+ return text.every((run) => {
2032
+ if (!isRecord(run) || run.time == null)
2033
+ return true;
2034
+ const time = run.time;
2035
+ return (finiteNumber(time.start) &&
2036
+ finiteNumber(time.end) &&
2037
+ time.start >= 0 &&
2038
+ time.end <= duration);
2039
+ });
2040
+ }
2041
+ /** Mirrors `TextStylePatch::apply`; `null` clears a field. */
2042
+ function patchedStyle(base, patch) {
2043
+ const merged = isRecord(base) ? { ...base } : {};
2044
+ if (!isRecord(patch))
2045
+ return merged;
2046
+ for (const [field, value] of Object.entries(patch)) {
2047
+ if (value === undefined)
2048
+ continue;
2049
+ if (value === null)
2050
+ delete merged[field];
2051
+ else
2052
+ merged[field] = value;
2053
+ }
2054
+ return merged;
2160
2055
  }
2161
- /** Mirrors `TextStyle::is_valid`: a caption track's style, or a text generator's. */
2056
+ /** Mirrors `TextStyle::is_valid`. */
2162
2057
  function validTextStyle(style, maxFontSize) {
2163
2058
  if (!isRecord(style))
2164
2059
  return false;
2165
2060
  const within = (value, low, high, open = false) => finiteNumber(value) && (open ? value > low : value >= low) && value <= high;
2166
- const outline = style.outline;
2167
2061
  const background = style.background;
2168
2062
  const family = style.font_family;
2169
- return (
2170
- // `null` is an absent family, as the model reads it.
2171
- (family == null ||
2063
+ return ((family == null ||
2172
2064
  (typeof family === "string" &&
2173
2065
  family.length > 0 &&
2174
2066
  new TextEncoder().encode(family).length <= MAX_FONT_FAMILY_BYTES)) &&
2175
2067
  within(style.font_size ?? 0.05, 0, maxFontSize, true) &&
2176
- (style.color === undefined || validRgba(style.color)) &&
2068
+ (style.fill === undefined || validTextFill(style.fill)) &&
2177
2069
  within(style.line_height ?? 1.2, MIN_LINE_HEIGHT, MAX_LINE_HEIGHT) &&
2178
2070
  within(style.letter_spacing ?? 0, MIN_LETTER_SPACING, MAX_LETTER_SPACING) &&
2179
2071
  validFontWeight(style.font_weight ?? 400) &&
2180
2072
  within(style.max_width ?? 0.9, 0, 1, true) &&
2181
2073
  (style.position === undefined || validVec2(style.position)) &&
2182
2074
  (style.anchor === undefined || validVec2(style.anchor)) &&
2183
- (outline == null ||
2184
- (isRecord(outline) &&
2185
- validRgba(outline.color) &&
2186
- within(outline.width, 0, MAX_TEXT_OUTLINE_WIDTH, true))) &&
2075
+ (style.strokes === undefined || validTextStrokes(style.strokes)) &&
2076
+ (style.shadows === undefined || validTextShadows(style.shadows)) &&
2077
+ (style.animators === undefined ||
2078
+ validTextAnimators(style.animators, false)) &&
2187
2079
  (background == null ||
2188
2080
  (isRecord(background) &&
2189
2081
  validRgba(background.color) &&
2190
2082
  within(background.padding ?? 0, 0, MAX_TEXT_PADDING))));
2191
2083
  }
2192
- /** A weight `FONT_WEIGHT_RANGE` holds: a whole number from 1 to 1000. */
2084
+ /** Mirrors `TextContent::is_valid`. */
2085
+ function validTextContent(text, encoder) {
2086
+ if (typeof text === "string") {
2087
+ return (text.length > 0 && encoder.encode(text).length <= MAX_TEXT_CONTENT_BYTES);
2088
+ }
2089
+ if (!Array.isArray(text) || text.length > MAX_TEXT_RUNS)
2090
+ return false;
2091
+ let bytes = 0;
2092
+ for (const run of text) {
2093
+ if (!isRecord(run) || typeof run.text !== "string" || run.text.length === 0)
2094
+ return false;
2095
+ bytes += encoder.encode(run.text).length;
2096
+ const classes = run.class ?? [];
2097
+ if (!Array.isArray(classes) ||
2098
+ classes.length > MAX_RUN_CLASSES ||
2099
+ !classes.every(validClassName)) {
2100
+ return false;
2101
+ }
2102
+ const time = run.time;
2103
+ if (time != null &&
2104
+ !(isRecord(time) &&
2105
+ safeInteger(time.start) &&
2106
+ safeInteger(time.end) &&
2107
+ time.start >= 0 &&
2108
+ time.start < time.end)) {
2109
+ return false;
2110
+ }
2111
+ }
2112
+ return bytes > 0 && bytes <= MAX_TEXT_CONTENT_BYTES;
2113
+ }
2114
+ /** Mirrors `valid_class_name`. */
2115
+ function validClassName(name) {
2116
+ return (typeof name === "string" &&
2117
+ name.length > 0 &&
2118
+ name.length <= MAX_CLASS_NAME_BYTES &&
2119
+ /^[A-Za-z0-9_-]+$/.test(name));
2120
+ }
2121
+ /** Mirrors `valid_animators`; `rangeOnly` allows only Range selectors (layout nodes). */
2122
+ function validTextAnimators(animators, rangeOnly) {
2123
+ if (!Array.isArray(animators) || animators.length > MAX_TEXT_ANIMATORS)
2124
+ return false;
2125
+ return animators.every((animator) => {
2126
+ if (!isRecord(animator) || !isRecord(animator.selector))
2127
+ return false;
2128
+ const selector = animator.selector;
2129
+ if (rangeOnly && selector.type !== "range")
2130
+ return false;
2131
+ let selected;
2132
+ switch (selector.type) {
2133
+ case "range": {
2134
+ const [low, high] = selector.units === "index"
2135
+ ? [-MAX_RANGE_INDEX, 2 * MAX_RANGE_INDEX]
2136
+ : [MIN_RANGE_PERCENT, MAX_RANGE_PERCENT];
2137
+ selected =
2138
+ [selector.start, selector.end, selector.offset].every((value) => validScalarAnimation(value, low, high)) && validScalarAnimation(selector.amount, 0, 1);
2139
+ break;
2140
+ }
2141
+ case "timing":
2142
+ selected =
2143
+ selector.ramp === undefined ||
2144
+ (safeInteger(selector.ramp) && selector.ramp >= 0);
2145
+ break;
2146
+ case "class":
2147
+ selected = validClassName(selector.class);
2148
+ break;
2149
+ default:
2150
+ selected = false;
2151
+ }
2152
+ return selected && validAnimatorProperties(animator.properties ?? {});
2153
+ });
2154
+ }
2155
+ /** Mirrors `TextAnimatorProperties::is_valid`. */
2156
+ function validAnimatorProperties(properties) {
2157
+ if (!isRecord(properties))
2158
+ return false;
2159
+ const vec2 = (animation, low, high) => {
2160
+ if (animation === undefined)
2161
+ return true;
2162
+ const values = animationValues(animation);
2163
+ return (values !== undefined &&
2164
+ values.every((value) => isRecord(value) &&
2165
+ [value.x, value.y].every((axis) => finiteNumber(axis) && axis >= low && axis <= high)));
2166
+ };
2167
+ const color = (animation) => {
2168
+ if (animation === undefined)
2169
+ return true;
2170
+ const values = animationValues(animation);
2171
+ return values !== undefined && values.every(validRgba);
2172
+ };
2173
+ return (vec2(properties.offset, -Infinity, Infinity) &&
2174
+ vec2(properties.scale, 0, MAX_ANIMATOR_SCALE) &&
2175
+ validScalarAnimation(properties.rotation_degrees) &&
2176
+ validScalarAnimation(properties.opacity, 0, 1) &&
2177
+ color(properties.fill) &&
2178
+ color(properties.stroke) &&
2179
+ validScalarAnimation(properties.tracking, MIN_LETTER_SPACING, MAX_LETTER_SPACING));
2180
+ }
2181
+ function validTextFill(fill) {
2182
+ return isRecord(fill) && "type" in fill ? validPaint(fill) : validRgba(fill);
2183
+ }
2184
+ /** Mirrors `valid_strokes`; widths are summed in `f32` as the model does. */
2185
+ function validTextStrokes(strokes) {
2186
+ if (!Array.isArray(strokes) || strokes.length > MAX_TEXT_STROKES)
2187
+ return false;
2188
+ let extent = 0;
2189
+ for (const stroke of strokes) {
2190
+ if (!isRecord(stroke) ||
2191
+ !validRgba(stroke.color) ||
2192
+ !finiteNumber(stroke.width) ||
2193
+ Math.fround(stroke.width) <= 0) {
2194
+ return false;
2195
+ }
2196
+ extent = Math.fround(extent + Math.fround(stroke.width));
2197
+ }
2198
+ return extent <= Math.fround(MAX_TEXT_STROKE_EXTENT);
2199
+ }
2200
+ /** Mirrors `valid_shadows`. */
2201
+ function validTextShadows(shadows) {
2202
+ if (!Array.isArray(shadows) || shadows.length > MAX_TEXT_SHADOWS)
2203
+ return false;
2204
+ const offset = (value) => finiteNumber(value) && Math.abs(value) <= MAX_TEXT_SHADOW_OFFSET;
2205
+ return shadows.every((shadow) => {
2206
+ if (!isRecord(shadow))
2207
+ return false;
2208
+ const blur = shadow.blur ?? 0;
2209
+ return (validRgba(shadow.color) &&
2210
+ (shadow.offset === undefined ||
2211
+ (isRecord(shadow.offset) &&
2212
+ offset(shadow.offset.x) &&
2213
+ offset(shadow.offset.y))) &&
2214
+ finiteNumber(blur) &&
2215
+ blur >= 0 &&
2216
+ blur <= MAX_TEXT_SHADOW_BLUR);
2217
+ });
2218
+ }
2193
2219
  function validFontWeight(weight) {
2194
2220
  return (Number.isInteger(weight) &&
2195
2221
  weight >= MIN_FONT_WEIGHT &&
@@ -2247,11 +2273,7 @@ function validFingerprint(fingerprint) {
2247
2273
  return (audio == null ||
2248
2274
  (isRecord(audio) && positive(audio.channels) && positive(audio.sample_rate)));
2249
2275
  }
2250
- /**
2251
- * Whether a color's dynamic range says what its transfer does: HDR exactly when the transfer is PQ
2252
- * or HLG, as the engine's `ColorMetadata::is_consistent` requires. The schema checks each field's
2253
- * shape.
2254
- */
2276
+ /** Mirrors `ColorMetadata::is_consistent`: HDR exactly when the transfer is PQ or HLG. */
2255
2277
  function consistentColor(color) {
2256
2278
  if (!isRecord(color))
2257
2279
  return true;
@@ -2261,13 +2283,6 @@ function consistentColor(color) {
2261
2283
  function positive(value) {
2262
2284
  return typeof value === "number" && value > 0;
2263
2285
  }
2264
- /**
2265
- * A fill whose paint is valid: colors in `0..=1`, gradients of two to {@link MAX_GRADIENT_STOPS}
2266
- * ordered stops, a linear gradient's ends distinct, a radial radius positive. Or shapes whose
2267
- * content tree is valid ({@link shapeItemsIssue}). Or text: non-empty, at most
2268
- * {@link MAX_TEXT_CONTENT_BYTES} bytes, in a valid style whose font size is at most
2269
- * {@link MAX_TEXT_GENERATOR_FONT_SIZE}. Or a layout whose tree is valid ({@link layoutIssue}).
2270
- */
2271
2286
  function validGenerator(generator) {
2272
2287
  if (!isRecord(generator))
2273
2288
  return false;
@@ -2278,10 +2293,7 @@ function validGenerator(generator) {
2278
2293
  if (generator.type === "layout")
2279
2294
  return layoutIssue(generator.root) === undefined;
2280
2295
  if (generator.type === "text")
2281
- return (typeof generator.text === "string" &&
2282
- generator.text.length > 0 &&
2283
- new TextEncoder().encode(generator.text).length <=
2284
- MAX_TEXT_CONTENT_BYTES &&
2296
+ return (validTextContent(generator.text, new TextEncoder()) &&
2285
2297
  validTextStyle(generator.style ?? {}, MAX_TEXT_GENERATOR_FONT_SIZE));
2286
2298
  return false;
2287
2299
  }
@@ -2296,13 +2308,11 @@ const SHAPE_PROBLEM = {
2296
2308
  pathKeyframesDiffer: "has path keyframes that differ in structure",
2297
2309
  paintKeyframesDiffer: "has paint keyframes that differ in kind or stops",
2298
2310
  };
2299
- /** A generator's shape problem, if it is a shapes generator with one. */
2300
2311
  function generatorShapeIssue(generator) {
2301
2312
  return isRecord(generator) && generator.type === "shapes"
2302
2313
  ? shapeItemsIssue(generator.items)
2303
2314
  : undefined;
2304
2315
  }
2305
- /** `issue` as a problem of `owner` (`source s`, `clip c`, `node n of composition g`). */
2306
2316
  function shapeProblem(owner, issue) {
2307
2317
  return `${owner} has an invalid shape: ${issue.at} ${issue.problem}`;
2308
2318
  }
@@ -2331,16 +2341,11 @@ const LAYOUT_PROBLEM = {
2331
2341
  paintKeyframesDiffer: "has paint keyframes that differ in kind or stops",
2332
2342
  textKeyframesInterpolate: "has text keyframes that do not hold",
2333
2343
  };
2334
- /**
2335
- * A generator's layout problem, if it is a layout generator with one; pixel font sizes are held
2336
- * to the limit on `canvas` when it is known.
2337
- */
2338
2344
  function generatorLayoutIssue(generator, canvas) {
2339
2345
  return isRecord(generator) && generator.type === "layout"
2340
2346
  ? layoutIssue(generator.root, canvas)
2341
2347
  : undefined;
2342
2348
  }
2343
- /** `issue` as a problem of `owner`, worded as the engine words it. */
2344
2349
  function layoutProblem(owner, issue) {
2345
2350
  return issue.shape === true
2346
2351
  ? shapeProblem(owner, issue)
@@ -2404,27 +2409,21 @@ const LAYOUT_VISUAL_FIELDS = [
2404
2409
  "scale",
2405
2410
  "rotation_degrees",
2406
2411
  ];
2407
- /** Whether an optional field is present: the model reads `null` as absent. */
2412
+ // The model reads `null` as absent.
2408
2413
  function present(value) {
2409
2414
  return value !== undefined && value !== null;
2410
2415
  }
2411
- /** The first of `fields` present on `node`. */
2412
2416
  function firstPresent(node, fields) {
2413
2417
  return fields.find((field) => present(node[field]));
2414
2418
  }
2415
- /** A length as the shape walk reads it ({@link readLayoutLength}). */
2416
2419
  function lengthOf(value) {
2417
2420
  return isRecord(value) && typeof value.unit === "string"
2418
2421
  ? value
2419
2422
  : undefined;
2420
2423
  }
2421
2424
  /**
2422
- * Mirrors `validate_layout`: the first problem of a layout tree in preorder, as the shape walk
2423
- * reads it. Its limits ({@link MAX_LAYOUT_NODES} nodes, {@link MAX_LAYOUT_DEPTH} deep,
2424
- * {@link MAX_LAYOUT_TEXTS} texts, {@link MAX_LAYOUT_ISOLATED} isolated nodes,
2425
- * {@link MAX_SHAPE_ITEMS} shape items over every shape node), its structure, which fields apply
2426
- * where, every value's range, and keyframes alike in kind. With `canvas`, a pixel font size is
2427
- * held to the largest a layout's text may be.
2425
+ * Mirrors `validate_layout`: the first problem of a layout tree in preorder. With `canvas`, pixel
2426
+ * font sizes are checked against the layout text limit.
2428
2427
  */
2429
2428
  function layoutIssue(root, canvas) {
2430
2429
  const node = isRecord(root) ? root : {};
@@ -2515,7 +2514,7 @@ function layoutNodeIssue(value, at, depth, counts, context) {
2515
2514
  }
2516
2515
  return undefined;
2517
2516
  }
2518
- /** An animated value's problem, as `checks::animated` finds it: keyframes, then values. */
2517
+ /** Mirrors `checks::animated`: keyframes first, then values. */
2519
2518
  function layoutAnimatedIssue(animation, at, check) {
2520
2519
  if (!present(animation))
2521
2520
  return undefined;
@@ -2529,7 +2528,6 @@ function layoutAnimatedIssue(animation, at, check) {
2529
2528
  function layoutScalarIssue(animation, at, check) {
2530
2529
  return layoutAnimatedIssue(animation, at, (value) => finiteNumber(value) && check(value));
2531
2530
  }
2532
- /** A size that may not be a percent: each value's number. */
2533
2531
  function layoutSizeIssue(animation, at, check) {
2534
2532
  return layoutAnimatedIssue(animation, at, (value) => {
2535
2533
  const length = lengthOf(value);
@@ -2545,7 +2543,7 @@ function layoutInsetsIssue(animation, at, check) {
2545
2543
  check(length.value));
2546
2544
  }));
2547
2545
  }
2548
- /** A size or inset: its values, then its keyframes one kind (a percent, or a length). */
2546
+ // Checks values, then that keyframes are all percents or all lengths.
2549
2547
  function layoutLengthIssue(animation, at, check) {
2550
2548
  const issue = layoutSizeIssue(animation, at, check);
2551
2549
  if (issue || !present(animation))
@@ -2614,7 +2612,6 @@ function layoutFieldsIssue(node, at) {
2614
2612
  layoutAnimatedIssue(node.scale, field("scale"), validVec2) ??
2615
2613
  layoutScalarIssue(node.rotation_degrees, field("rotation_degrees"), anyValue));
2616
2614
  }
2617
- /** A track size's lengths and `fr` share, as the shape walk reads it. */
2618
2615
  function trackParts(size) {
2619
2616
  const breadths = size.kind === "breadth"
2620
2617
  ? [size.breadth]
@@ -2627,7 +2624,7 @@ function trackParts(size) {
2627
2624
  const last = breadths.at(-1);
2628
2625
  return { lengths, share: last?.kind === "fr" ? last.share : undefined };
2629
2626
  }
2630
- /** Mirrors `TrackSize::is_fixed`: what `auto-fill` and `auto-fit` repeat. */
2627
+ /** Mirrors `TrackSize::is_fixed`. */
2631
2628
  function fixedTrack(size) {
2632
2629
  const fixed = (breadth) => breadth.kind === "length";
2633
2630
  if (size.kind === "breadth")
@@ -2693,7 +2690,7 @@ function layoutGridIssue(node, at) {
2693
2690
  }
2694
2691
  return undefined;
2695
2692
  }
2696
- /** Mirrors `layout::validate_style`: the text style a node writes, where it writes it. */
2693
+ /** Mirrors `layout::validate_style`. */
2697
2694
  function layoutStyleIssue(node, at, shorterSide) {
2698
2695
  const outOfRange = (name) => ({
2699
2696
  at: `${at}.${name}`,
@@ -2712,7 +2709,6 @@ function layoutStyleIssue(node, at, shorterSide) {
2712
2709
  !finiteNumber(length.value) ||
2713
2710
  length.value <= 0)
2714
2711
  return false;
2715
- // Pixels compare with the limit on a known canvas only.
2716
2712
  const fraction = length.unit !== "px"
2717
2713
  ? length.value
2718
2714
  : shorterSide === undefined
@@ -2722,8 +2718,8 @@ function layoutStyleIssue(node, at, shorterSide) {
2722
2718
  });
2723
2719
  if (size)
2724
2720
  return size;
2725
- if (present(node.color) && !validRgba(node.color)) {
2726
- return outOfRange("color");
2721
+ if (present(node.fill) && !validTextFill(node.fill)) {
2722
+ return outOfRange("fill");
2727
2723
  }
2728
2724
  const lineHeight = node.line_height;
2729
2725
  if (present(lineHeight) &&
@@ -2742,18 +2738,19 @@ function layoutStyleIssue(node, at, shorterSide) {
2742
2738
  if (present(node.font_weight) && !validFontWeight(node.font_weight)) {
2743
2739
  return outOfRange("font_weight");
2744
2740
  }
2745
- const outline = node.outline;
2746
- if (present(outline) &&
2747
- !(isRecord(outline) &&
2748
- validRgba(outline.color) &&
2749
- finiteNumber(outline.width) &&
2750
- outline.width > 0 &&
2751
- outline.width <= MAX_TEXT_OUTLINE_WIDTH)) {
2752
- return outOfRange("outline");
2741
+ if (present(node.strokes) && !validTextStrokes(node.strokes)) {
2742
+ return outOfRange("strokes");
2743
+ }
2744
+ if (present(node.shadows) && !validTextShadows(node.shadows)) {
2745
+ return outOfRange("shadows");
2746
+ }
2747
+ if (present(node.text_animators) &&
2748
+ !validTextAnimators(node.text_animators, true)) {
2749
+ return outOfRange("text_animators");
2753
2750
  }
2754
2751
  return undefined;
2755
2752
  }
2756
- /** Mirrors `layout::validate_text`: a node's text content. */
2753
+ /** Mirrors `layout::validate_text`. */
2757
2754
  function layoutTextIssue(content, at) {
2758
2755
  const keyframes = layoutAnimatedIssue(content, at, () => true);
2759
2756
  if (keyframes)
@@ -2768,11 +2765,7 @@ function layoutTextIssue(content, at) {
2768
2765
  return layoutAnimatedIssue(content, at, (value) => typeof value === "string" &&
2769
2766
  new TextEncoder().encode(value).length <= MAX_TEXT_CONTENT_BYTES);
2770
2767
  }
2771
- /**
2772
- * Mirrors `validate_shape_items`: the first problem of a content tree in document order. Its
2773
- * limits ({@link MAX_SHAPE_ITEMS} items over every group, groups {@link MAX_SHAPE_DEPTH}
2774
- * deep), every value's range, and keyframed paths and paints alike in structure.
2775
- */
2768
+ /** Mirrors `validate_shape_items`: the first problem of a content tree in document order. */
2776
2769
  function shapeItemsIssue(items) {
2777
2770
  const counted = { count: 0 };
2778
2771
  return shapeGroupIssue(items, "items", 1, counted);
@@ -2821,10 +2814,7 @@ function shapeItemIssue(item, at, depth, counted) {
2821
2814
  const unitValue = (value) => value >= 0 && value <= 1;
2822
2815
  const nonNegativeValue = (value) => value >= 0;
2823
2816
  const anyValue = () => true;
2824
- /**
2825
- * An animated scalar's problem: keyframes empty, out of order, or with an unusable curve, then any
2826
- * value not finite or failing `check`. A missing value takes its default, which is valid.
2827
- */
2817
+ // Keyframe problems first, then values. A missing value takes its (valid) default.
2828
2818
  function shapeScalarIssue(animation, at, check) {
2829
2819
  if (animation === undefined)
2830
2820
  return undefined;
@@ -2847,7 +2837,7 @@ function shapeVec2Issue(animation, at, check) {
2847
2837
  ? undefined
2848
2838
  : { at, problem: SHAPE_PROBLEM.outOfRange };
2849
2839
  }
2850
- /** Mirrors `valid_point_animation`: keyframes as any animation's, values and tangents finite. */
2840
+ /** Mirrors `valid_point_animation`. */
2851
2841
  function validPointAnimation(animation) {
2852
2842
  return shapePointIssue(animation, "") === undefined;
2853
2843
  }
@@ -2869,7 +2859,7 @@ function shapePointIssue(animation, at) {
2869
2859
  : { at, problem: SHAPE_PROBLEM.outOfRange };
2870
2860
  }
2871
2861
  const nonNegativeSize = (value) => value.x >= 0 && value.y >= 0;
2872
- /** Mirrors `ShapeGeometry::validate`: a mask's outline, or a content tree's geometry item. */
2862
+ /** Mirrors `ShapeGeometry::validate`. */
2873
2863
  function shapeGeometryIssue(geometry, at) {
2874
2864
  switch (geometry.type) {
2875
2865
  case "rectangle":
@@ -2929,13 +2919,12 @@ function strokeIssue(stroke, at) {
2929
2919
  if (entryIssue)
2930
2920
  return entryIssue;
2931
2921
  }
2932
- // Some entry positive at some keyframe: the pattern has a length to repeat over.
2922
+ // The pattern needs some positive entry to have a length to repeat over.
2933
2923
  const positive = pattern.some((entry) => (animationValues(entry) ?? []).some((value) => value > 0));
2934
2924
  if (!positive)
2935
2925
  return { at: patternAt, problem: SHAPE_PROBLEM.invalidDash };
2936
2926
  return shapeScalarIssue(dash.offset, `${at}.dash.offset`, anyValue);
2937
2927
  }
2938
- /** A path's subpaths and vertex counts within the limits, every point and tangent finite. */
2939
2928
  function pathIssue(path, at) {
2940
2929
  const subpaths = isRecord(path) && Array.isArray(path.subpaths)
2941
2930
  ? path.subpaths
@@ -2957,7 +2946,7 @@ function pathIssue(path, at) {
2957
2946
  (vertex.out_tangent === undefined || validVec2(vertex.out_tangent))));
2958
2947
  return finite ? undefined : { at, problem: SHAPE_PROBLEM.outOfRange };
2959
2948
  }
2960
- /** What two path keyframes must share: each subpath's closing and vertex count. */
2949
+ // Path keyframes must share each subpath's closing and vertex count.
2961
2950
  function pathStructure(path) {
2962
2951
  const subpaths = isRecord(path) && Array.isArray(path.subpaths)
2963
2952
  ? path.subpaths
@@ -2988,7 +2977,7 @@ function animatedPathIssue(animation, at) {
2988
2977
  ? undefined
2989
2978
  : { at, problem: SHAPE_PROBLEM.pathKeyframesDiffer };
2990
2979
  }
2991
- /** What two paint keyframes must share: kind, stop count, and a gradient's spread. */
2980
+ // Paint keyframes must share kind, stop count and gradient spread.
2992
2981
  function paintStructure(paint) {
2993
2982
  const record = isRecord(paint) ? paint : {};
2994
2983
  const stops = Array.isArray(record.stops) ? record.stops.length : 1;
@@ -3061,12 +3050,10 @@ function validRgba(color) {
3061
3050
  return (isRecord(color) &&
3062
3051
  [color.red, color.green, color.blue, color.alpha].every((value) => finiteNumber(value) && value >= 0 && value <= 1));
3063
3052
  }
3064
- /** The inputs of a composition node's operation, named as diagnostics show them. */
3065
3053
  function nodeInputs(op) {
3066
3054
  switch (op.type) {
3067
3055
  case "effect": {
3068
- // In name order, as the model's map keeps them; names are ASCII, so the default string
3069
- // order is its byte order.
3056
+ // The model's map sorts by bytes; names are ASCII, so default string order matches.
3070
3057
  const named = isRecord(op.inputs) ? op.inputs : {};
3071
3058
  return [
3072
3059
  ["input", op.input],
@@ -3099,11 +3086,7 @@ function nodeInputs(op) {
3099
3086
  return [];
3100
3087
  }
3101
3088
  }
3102
- /**
3103
- * The compositions each of `composition`'s nodes draws in its place, as the model reads them: a
3104
- * group node's, or a composition source's that a media node reads; one entry per node, `undefined`
3105
- * for a node that draws none or names an absent one.
3106
- */
3089
+ // One entry per node: the composition it draws through a group or composition source, if any.
3107
3090
  function drawnCompositions(composition, compositions, sources) {
3108
3091
  return (Array.isArray(composition.nodes) ? composition.nodes : []).map((node) => {
3109
3092
  let target;
@@ -3121,11 +3104,7 @@ function drawnCompositions(composition, compositions, sources) {
3121
3104
  : undefined;
3122
3105
  });
3123
3106
  }
3124
- /**
3125
- * Mirrors the model's check that no composition uses itself, through group nodes or composition
3126
- * sources: the first found on its own path. The walk keeps its own stack, as the model's does, so a
3127
- * long chain cannot exhaust the call stack.
3128
- */
3107
+ // Mirrors the model's self-use check. An explicit stack keeps long chains off the call stack.
3129
3108
  function compositionUsingItself(compositions, sources) {
3130
3109
  const uses = (id) => {
3131
3110
  const composition = compositions.get(id);
@@ -3160,14 +3139,9 @@ function compositionUsingItself(compositions, sources) {
3160
3139
  }
3161
3140
  return undefined;
3162
3141
  }
3163
- /**
3164
- * Mirrors the model's bound on what compositions draw once inlined: none nests deeper than {@link
3165
- * MAX_COMPOSITION_DEPTH}, and together they draw at most {@link MAX_INLINED_NODES} nodes, each
3166
- * group node or composition-source media node counted as the nodes of the composition it draws. The
3167
- * references must be acyclic. Within the bounds, `nodes` is what each composition draws.
3168
- */
3142
+ // Mirrors the model's inlined depth and node bounds. References must be acyclic. Within bounds,
3143
+ // `nodes` is what each composition draws.
3169
3144
  function compositionExpansion(compositions, sources) {
3170
- // Counted in dependency order without recursion.
3171
3145
  const walked = new Map();
3172
3146
  let total = 0;
3173
3147
  for (const root of compositions.keys()) {
@@ -3189,7 +3163,7 @@ function compositionExpansion(compositions, sources) {
3189
3163
  for (const target of drawn) {
3190
3164
  const inner = target === undefined ? { depth: 0, nodes: 1 } : walked.get(target);
3191
3165
  depth = Math.max(depth, inner.depth + 1);
3192
- // Past the limit the exact count no longer matters, and doubling it could reach Infinity.
3166
+ // Clamp so repeated doubling cannot reach Infinity.
3193
3167
  nodes = Math.min(nodes + inner.nodes, MAX_INLINED_NODES + 1);
3194
3168
  }
3195
3169
  walked.set(id, { depth, nodes });
@@ -3209,10 +3183,6 @@ function compositionExpansion(compositions, sources) {
3209
3183
  nodes: new Map([...walked].map(([id, { nodes }]) => [id, nodes])),
3210
3184
  };
3211
3185
  }
3212
- /**
3213
- * The clips on `track` drawing compositions, each at its start and its end, for {@link
3214
- * frameNodesOver}.
3215
- */
3216
3186
  function frameEdges(track, sources, inlined) {
3217
3187
  const nodes = (id) => typeof id === "string" ? (inlined.get(id) ?? 0) : 0;
3218
3188
  const edges = [];
@@ -3233,17 +3203,11 @@ function frameEdges(track, sources, inlined) {
3233
3203
  }
3234
3204
  return edges;
3235
3205
  }
3236
- /**
3237
- * Mirrors the model's bound on what one frame draws: at no instant do the clips on the timeline
3238
- * draw more than {@link MAX_FRAME_INLINED_NODES} composition nodes together, each clip counting the
3239
- * nodes its composition and its composition source draw once inlined. Reports the first clip, in
3240
- * document order, starting at the first instant over the bound, with the count of all the clips
3241
- * there. `tracks` are the {@link frameEdges} of each track, in document order.
3242
- */
3206
+ // Mirrors the model's per-frame inlined node bound, reporting the first clip at the first instant
3207
+ // over it.
3243
3208
  function frameNodesOver(tracks) {
3244
3209
  const edges = tracks.flat();
3245
- // By instant, the clips ending there before those starting there (ranges are half-open), each in
3246
- // document order: the sort is stable.
3210
+ // Ends sort before starts at one instant (half-open ranges); stable sort keeps document order.
3247
3211
  edges.sort((a, b) => a.time - b.time || Number(a.starts) - Number(b.starts));
3248
3212
  let drawn = 0;
3249
3213
  for (let at = 0; at < edges.length;) {
@@ -3260,9 +3224,6 @@ function frameNodesOver(tracks) {
3260
3224
  }
3261
3225
  return undefined;
3262
3226
  }
3263
- /**
3264
- * A composition's node identities, settings, and connections, as the model checks them.
3265
- */
3266
3227
  function compositionProblems(composition, sources, effectResources, compositions, controlNamesOf, canvas) {
3267
3228
  if (!isRecord(composition))
3268
3229
  return ["each composition must be an object"];
@@ -3424,7 +3385,6 @@ function compositionProblems(composition, sources, effectResources, compositions
3424
3385
  if (output != null && !byId.has(text(output))) {
3425
3386
  problems.push(`composition ${id} outputs unknown node ${text(output)}`);
3426
3387
  }
3427
- // Depth-first: a node reached again while still on the walk's path closes a cycle.
3428
3388
  const state = new Map();
3429
3389
  const visit = (nodeId) => {
3430
3390
  const mark = state.get(nodeId);
@@ -3451,7 +3411,6 @@ function compositionProblems(composition, sources, effectResources, compositions
3451
3411
  }
3452
3412
  return problems;
3453
3413
  }
3454
- /** At most {@link MAX_CLIP_MASKS} masks, and on visual clips only. */
3455
3414
  function validMaskCount(masks, trackKind) {
3456
3415
  if (masks === undefined)
3457
3416
  return true;
@@ -3461,10 +3420,7 @@ function validMaskCount(masks, trackKind) {
3461
3420
  return true;
3462
3421
  return trackKind === "video" && masks.length <= MAX_CLIP_MASKS;
3463
3422
  }
3464
- /**
3465
- * Mirrors `validate_masks`: the first problem among the masks in order, each outline checked as
3466
- * geometry is and each feather non-negative.
3467
- */
3423
+ /** Mirrors `validate_masks`. */
3468
3424
  function masksIssue(masks) {
3469
3425
  if (!Array.isArray(masks))
3470
3426
  return undefined;
@@ -3482,10 +3438,7 @@ function masksIssue(masks) {
3482
3438
  }
3483
3439
  return undefined;
3484
3440
  }
3485
- /**
3486
- * A matte names a visual clip other than its own, which has no matte of its own and is in no
3487
- * transition.
3488
- */
3441
+ // A matte names another visual clip that has no matte and is in no transition.
3489
3442
  function matteProblems(tracks) {
3490
3443
  const visual = new Map();
3491
3444
  const inTransition = new Set();
@@ -3520,15 +3473,9 @@ function matteProblems(tracks) {
3520
3473
  }
3521
3474
  return problems;
3522
3475
  }
3523
- /**
3524
- * The tracks whose ducking sidechain leads back to themselves.
3525
- *
3526
- * Each track names at most one sidechain, so following them from any track ends, or enters the one
3527
- * cycle its path reaches; a track is on a cycle exactly when its own walk returns to it. One walk
3528
- * per track, each step visited once over all of them, as the engine's walk finds the same tracks
3529
- * within a document's track limit. A repeated track id resolves to its first track, as the engine's
3530
- * lookup does.
3531
- */
3476
+ // Tracks whose ducking sidechain leads back to themselves. Each track names at most one sidechain,
3477
+ // so each step is visited once over all walks. Repeated ids resolve to the first track, as in the
3478
+ // engine.
3532
3479
  function duckingCycles(tracks) {
3533
3480
  const sidechains = new Map();
3534
3481
  for (const track of tracks) {
@@ -3539,7 +3486,7 @@ function duckingCycles(tracks) {
3539
3486
  sidechains.set(text(track.id), isRecord(ducking) ? text(ducking.sidechain_track) : undefined);
3540
3487
  }
3541
3488
  const cyclic = new Set();
3542
- // Which walk first reached each track: a walk that meets its own mark has closed a cycle.
3489
+ // A walk that meets its own mark has closed a cycle.
3543
3490
  const walkOf = new Map();
3544
3491
  let walk = 0;
3545
3492
  for (const start of sidechains.keys()) {
@@ -3562,19 +3509,11 @@ function duckingCycles(tracks) {
3562
3509
  return cyclic;
3563
3510
  }
3564
3511
  /**
3565
- * A valid project's non-fatal diagnostics, computed by the engine's own
3566
- * `Project::lint`, in a fixed order: unused sources, then shapes generators
3567
- * (sources', then composition nodes'), then HDR sources, then each track's
3568
- * clips, transitions, and cues, then compositions' nodes, then generated
3569
- * sources' trees. A keyframe is checked in its own time: a clip's in timeline
3570
- * time, a composition node's in the composition time the clips that show it
3571
- * map to, a generated source's in the picture time its clips' time maps reach.
3572
- *
3573
- * Diagnostics never block a load or an export; they flag what is probably a
3574
- * mistake in a project the engine accepts.
3512
+ * A valid project's non-fatal diagnostics from the engine's `Project::lint`, in a fixed order:
3513
+ * unused sources, shapes generators, HDR sources, each track's clips, transitions and cues,
3514
+ * composition nodes, then generated sources' trees. Diagnostics never block a load or export.
3575
3515
  *
3576
- * @throws When the project does not load: the binding's error, as for
3577
- * `loadProject`.
3516
+ * @throws The binding's error when the project does not load, as for `loadProject`.
3578
3517
  */
3579
3518
  export function lintProject(binding, project) {
3580
3519
  return JSON.parse(binding.lintProject(JSON.stringify(project)));