@mengine/medeo-client 1.3.1-alpha.5 → 1.3.1-alpha.6

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.
@@ -1,1590 +0,0 @@
1
- import { Mirror, schema, validateSchema } from "loro-mirror";
2
- import { z } from "zod";
3
- import { LoroDoc } from "loro-crdt";
4
- //#region src/client/base64.ts
5
- function bytesToBase64(bytes) {
6
- let binary = "";
7
- for (const byte of bytes) binary += String.fromCharCode(byte);
8
- return btoa(binary);
9
- }
10
- function base64ToBytes(base64) {
11
- const binary = atob(base64);
12
- const bytes = new Uint8Array(binary.length);
13
- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
14
- return bytes;
15
- }
16
- //#endregion
17
- //#region src/document/mirror-schema.ts
18
- /**
19
- * Declarative `loro-mirror` schema for `VideoDocument` — the canonical structural
20
- * SSOT and live storage wire (replaces the hand-rolled `@mengine/schema`
21
- * definition + adapter, see ADR 0008).
22
- *
23
- * Mirror gives an in-memory immutable state synced to the Loro doc by declarative
24
- * diff, so the storage layer no longer hand-writes per-region reconcile or a
25
- * transaction state machine. The shapes here store only authoritative facts
26
- * (RFC 02 §6): per-item absolute time, `part_aggregations`, and total duration
27
- * are projection-derived (cascade-solved at read time), so they are absent here.
28
- *
29
- * - tracks live in a single `tracks` `LoroMovableList` keyed by track id
30
- * (reference/17 §4). Lane is expressed by each track's `parts_kind`, not by
31
- * which container it lives in; order is the movable-list order itself. There is
32
- * no `lane` / `lane_order` field, so two peers inserting tracks never collide
33
- * on an order integer — list moves are conflict-free (RFC 03 §4). The legacy
34
- * keyed-map (`LoroMapRecord` + an integer `lane_order`) and the prior three
35
- * named containers are gone; the `main` / `above` / `below` three-pane view is
36
- * rebuilt by the projection from `parts_kind`.
37
- * - each track's `items` is a `LoroMovableList` keyed by `part_id`: a part is
38
- * placed at most once per lane, so `part_id` is the stable placement identity.
39
- * Reorder diffs to a real Loro `move`, preserving per-item CRDT identity on
40
- * every lane (main and secondary alike).
41
- * - `time_position` is the authoritative positioning fact (RFC 02 §4,
42
- * reference/17 §3), carried as an opaque JSON blob string (a whole tagged-union
43
- * value, last-writer-wins). The derived `fallback_abs_ms` snapshot sits beside
44
- * it as its own number field — a separate LWW unit so a projection refresh
45
- * never clobbers a `time_position` edit.
46
- * - `part_library` values are nested `LoroMap`s: the value is a `LoroMap` with
47
- * four mutually-exclusive optional part sub-maps (`video_clip` / `speech` /
48
- * `caption` / `bgm`), each a `LoroMap` whose fields are stored as real Loro
49
- * sub-keys. This makes each field its own CRDT unit, so two peers editing
50
- * different fields of the same part (e.g. one volume, one play_out) merge
51
- * field-by-field instead of one whole-value overwrite. Field `required` mirrors
52
- * the Smithy `@required` contract (see `video_draft_comp.smithy`). `kind` is not
53
- * stored (the present sub-key names the kind); `duration_ms` is not stored (it
54
- * is derived, reference/17 §5). Nested values that the engine does not edit
55
- * field-by-field — `speed_shift` (a tagged union), `voice`, `caption_ids` — stay
56
- * as opaque JSON-blob sub-keys via `transform`. The four sub-keys are optional,
57
- * so the "exactly one part kind" union invariant is not enforced by the schema
58
- * type; it is rebuilt by `draftToPartUnion` on read and gated by zod on write.
59
- * - a caption's `style` is the one lazily-created optional child container, so
60
- * `captionPart` sets `mergeableMapChildContainers: true` — two peers can
61
- * concurrently first-create the same caption's `style` (one attribute each), and
62
- * only a mergeable child converges instead of last-writer-wins dropping one. All
63
- * other nested maps are keyed by a unique id (`part_library`) or created
64
- * atomically with their parent (`partValue`'s part sub-map), so they never hit
65
- * that concurrent-first-create fork and stay on plain `setContainer`. See the
66
- * note on `captionPart` below.
67
- */
68
- /**
69
- * JSON-blob transform for an opaque, last-writer-wins value carried in a Loro
70
- * string. The field must be declared `required: false`: an absent field decodes
71
- * to `undefined` (mirror never calls `decode`/`encode` for null/undefined),
72
- * which is how we represent "no value" instead of encoding a `null` sentinel.
73
- */
74
- function jsonTransform() {
75
- return {
76
- decode: (value) => JSON.parse(value),
77
- encode: (value) => JSON.stringify(value),
78
- isEqual: "encoded-value-equality"
79
- };
80
- }
81
- const trackItem = schema.LoroMap({
82
- part_id: schema.String(),
83
- time_position: schema.String().transform(jsonTransform()),
84
- fallback_abs_ms: schema.Number({ required: false })
85
- });
86
- const track = schema.LoroMap({
87
- id: schema.String(),
88
- parts_kind: schema.String({ required: false }),
89
- is_hidden: schema.Boolean({ required: false }),
90
- items: schema.LoroMovableList(trackItem, (item) => item.part_id)
91
- });
92
- const videoClipPart = schema.LoroMap({
93
- id: schema.String(),
94
- play_in: schema.Number(),
95
- play_out: schema.Number(),
96
- volume: schema.Number(),
97
- origin_media_id: schema.String(),
98
- speed_shift: schema.String({ required: false }).transform(jsonTransform())
99
- }, { required: false });
100
- const speechPart = schema.LoroMap({
101
- id: schema.String(),
102
- media_duration_ms: schema.Number(),
103
- audio_script: schema.String(),
104
- volume: schema.Number(),
105
- audio_storage_key: schema.String(),
106
- origin_speech_id: schema.String(),
107
- voice: schema.String().transform(jsonTransform()),
108
- caption_ids: schema.String().transform(jsonTransform())
109
- }, { required: false });
110
- const captionStyle = schema.LoroMap({
111
- font_id: schema.String({ required: false }),
112
- font_size: schema.Number({ required: false }),
113
- font_color: schema.String({ required: false }),
114
- font_weight: schema.Number({ required: false }),
115
- entrance_animation: schema.String({ required: false }),
116
- entrance_animation_duration_ms: schema.Number({ required: false }),
117
- stroke_color: schema.String({ required: false }),
118
- stroke_width: schema.Number({ required: false }),
119
- position_x: schema.Number({ required: false }),
120
- position_y: schema.Number({ required: false })
121
- }, { required: false });
122
- const captionPart = schema.LoroMap({
123
- id: schema.String(),
124
- initial_duration_ms: schema.Number(),
125
- speech_part_id: schema.String(),
126
- text: schema.String(),
127
- start_ms: schema.Number(),
128
- style: captionStyle
129
- }, {
130
- required: false,
131
- mergeableMapChildContainers: true
132
- });
133
- const bgmPart = schema.LoroMap({
134
- id: schema.String(),
135
- audio_storage_key: schema.String(),
136
- volume: schema.Number(),
137
- origin_media_id: schema.String()
138
- }, { required: false });
139
- const partValue = schema.LoroMap({
140
- video_clip: videoClipPart,
141
- speech: speechPart,
142
- caption: captionPart,
143
- bgm: bgmPart
144
- });
145
- const videoDocumentMirrorSchema = schema({
146
- timeline: schema.LoroMap({ unit_time_ms: schema.Number({ required: false }) }),
147
- tracks: schema.LoroMovableList(track, (t) => t.id),
148
- part_library: schema.LoroMapRecord(partValue)
149
- });
150
- /** Project a discriminated `PartUnion` into the draft's four-optional shape. */
151
- function partUnionToDraft(part) {
152
- if (part.video_clip != null) return { video_clip: omitKind(part.video_clip) };
153
- if (part.speech != null) return { speech: omitKind(part.speech) };
154
- if (part.caption != null) return { caption: omitKind(part.caption) };
155
- return { bgm: omitKind(part.bgm) };
156
- }
157
- /**
158
- * Rebuild a discriminated `PartUnion` from a draft part value: pick the one
159
- * present sub-key, restore its `kind`, and drop the `$cid`. Returns `undefined`
160
- * when no part sub-key is present (an empty/placeholder value).
161
- */
162
- function draftToPartUnion(value) {
163
- if (value == null) return void 0;
164
- const v = value;
165
- if (v.video_clip != null) return { video_clip: withKind(v.video_clip, "video_clip") };
166
- if (v.speech != null) return { speech: withKind(v.speech, "speech") };
167
- if (v.caption != null) return { caption: withKind(v.caption, "caption") };
168
- if (v.bgm != null) return { bgm: withKind(v.bgm, "bgm") };
169
- }
170
- /** Drop `kind` (not stored) and `$cid` from a part payload for the draft. */
171
- function omitKind(part) {
172
- const { kind: _kind, $cid: _cid, ...rest } = part;
173
- return rest;
174
- }
175
- /** Restore `kind` (and drop `$cid`) on a part sub-map read from the draft. */
176
- function withKind(part, kind) {
177
- const { $cid: _cid, ...rest } = part;
178
- return {
179
- ...rest,
180
- kind
181
- };
182
- }
183
- /** Entries of a draft record (e.g. `tracks`) with `$cid` stripped. */
184
- function recordEntries(record) {
185
- if (record == null) return [];
186
- const out = [];
187
- for (const [key, value] of Object.entries(record)) {
188
- if (key === "$cid") continue;
189
- out.push([key, value]);
190
- }
191
- return out;
192
- }
193
- //#endregion
194
- //#region src/document/types.ts
195
- /** The linear speed multiplier of a `speed_shift`, defaulting to 1 (original). */
196
- function speedOf(speedShift) {
197
- const speed = speedShift?.config?.linear?.speed;
198
- return typeof speed === "number" && Number.isFinite(speed) && speed > 0 ? speed : 1;
199
- }
200
- /**
201
- * A video clip's effective timeline duration, derived from authoritative facts
202
- * (RFC 02, `reference/16` §4, reference/17 §5): the trim window
203
- * `play_out - play_in` divided by the speed multiplier, rounded to integer ms.
204
- * `play_in` / `play_out` are optional in the IDL but every write path sets them
205
- * (defaulting to the whole media), and the legacy-ingest projection backfills the
206
- * window from a legacy `duration_ms` — so an authoritative clip always carries a
207
- * trim window and there is no stored `duration_ms` to fall back to. A clip with
208
- * neither bound yields 0. Speeds the clip up (>1× → shorter) or down (<1×).
209
- */
210
- function effectiveVideoClipDurationMs(clip) {
211
- const speed = speedOf(clip.speed_shift);
212
- const sourceMs = (clip.play_out ?? 0) - (clip.play_in ?? 0);
213
- const effective = Math.round(sourceMs / speed);
214
- return Number.isFinite(effective) && effective > 0 ? effective : 0;
215
- }
216
- /**
217
- * The `timeline.unit_time_ms` the read-view states when the document states none.
218
- *
219
- * One frame at 30fps. A document legitimately has no such fact (display
220
- * granularity is the editor's, not the timeline's), but the read-view IDL marks
221
- * the field `@required`, so the projection has to name a value. This one is a
222
- * usable granularity; `0` — which a downstream consumer had been defaulting to —
223
- * is not, and passes any `>= 0` guard on its way to an editor that cannot use it.
224
- */
225
- const DEFAULT_UNIT_TIME_MS = 33.333;
226
- //#endregion
227
- //#region src/timeline-core/types.ts
228
- /** Total document duration when there is no real content (matches FE bgm fallback). */
229
- const TIMELINE_SKELETON_DURATION_MS = 2e4;
230
- /** Empty placeholder clip marker: a video_clip part with no backing media. */
231
- function isEmptyVideoClip(part) {
232
- const clip = part?.video_clip;
233
- if (clip == null) return false;
234
- return clip.origin_media_id == null || clip.origin_media_id === "";
235
- }
236
- /** Clamp a duration to a non-negative integer (NaN/Infinity/negative → 0). */
237
- function safeDurationMs(value) {
238
- const n = Number(value);
239
- if (!Number.isFinite(n) || n <= 0) return 0;
240
- return Math.round(n);
241
- }
242
- function partDurationMs(doc, partId) {
243
- const part = doc.part_library[partId];
244
- if (part?.video_clip != null) return safeDurationMs(effectiveVideoClipDurationMs(part.video_clip));
245
- if (part?.bgm != null) return doc.timeline.duration_ms > 0 ? doc.timeline.duration_ms : TIMELINE_SKELETON_DURATION_MS;
246
- if (part?.speech != null) return safeDurationMs(part.speech.media_duration_ms);
247
- if (part?.caption != null) return safeDurationMs(part.caption.initial_duration_ms);
248
- return 0;
249
- }
250
- //#endregion
251
- //#region src/timeline-core/cascade.ts
252
- /**
253
- * Canonical timeline cascade primitives (ADR 0009).
254
- *
255
- * Single source of truth for "how an edit's connected regions move": main-track
256
- * seamless layout, aggregation position sync + reassignment, total-duration
257
- * recompute, speech-overlap resolution, gap filling. Reconciled per ADR 0009 §4:
258
- *
259
- * - product behavior follows the FE current implementation;
260
- * - all times are integer ms — positions/durations are rounded, never floated;
261
- * - function decomposition follows agent-harness (the Python-derived structure).
262
- *
263
- * Every function mutates the `TimelineDoc` in place (the editor runs them inside
264
- * one immer `transact`, so in-place edits diff correctly).
265
- */
266
- /**
267
- * Lay the main track out head-to-tail from 0, rewriting each item's
268
- * `abs_time_position`. Items whose part is missing from the library are dropped.
269
- */
270
- function arrangeMainTrackSeamlessly(doc) {
271
- const kept = [];
272
- let cursor = 0;
273
- for (const item of doc.main_track) {
274
- if (doc.part_library[item.part_id] == null) continue;
275
- item.abs_time_position = cursor;
276
- cursor += partDurationMs(doc, item.part_id);
277
- kept.push(item);
278
- }
279
- doc.main_track = kept;
280
- }
281
- /**
282
- * Sync attached parts' absolute positions from their host:
283
- * speech.abs = host_video.abs + relative_time_position
284
- * caption.abs = speech.abs + caption.start_ms
285
- */
286
- function syncAggregatedClipsTimePosition(doc) {
287
- const videoByPart = indexByPart(doc.main_track);
288
- const speechByPart = indexByPart(doc.speech_track);
289
- for (const aggregation of doc.aggregations) {
290
- const videoItem = videoByPart.get(aggregation.body_part_id);
291
- if (videoItem == null) continue;
292
- for (const attachment of aggregation.attachments) {
293
- const speechItem = speechByPart.get(attachment.part_id);
294
- if (speechItem == null) continue;
295
- speechItem.abs_time_position = videoItem.abs_time_position + attachment.relative_time_position;
296
- }
297
- }
298
- for (const captionItem of doc.caption_track) {
299
- const captionPart = doc.part_library[captionItem.part_id]?.caption;
300
- if (captionPart == null) continue;
301
- const speechItem = captionPart.speech_part_id == null ? void 0 : speechByPart.get(captionPart.speech_part_id);
302
- if (speechItem == null) continue;
303
- captionItem.abs_time_position = speechItem.abs_time_position + safeDurationMs(captionPart.start_ms);
304
- }
305
- }
306
- /**
307
- * Reassign each speech to the video clip whose time range contains its start,
308
- * rebuilding `aggregations`. A speech before the first clip or after the last
309
- * falls back to the first / last clip respectively (FE: see §4 note — FE falls
310
- * back to last only; we keep the harness two-sided fallback because a speech
311
- * dragged before clip 0 belonging to the last clip is clearly wrong, and the FE
312
- * single-sided rule is an acknowledged rough edge). `relative_time_position` is
313
- * clamped to a non-negative integer.
314
- */
315
- function reassignSpeechesToVideoClipsByTime(doc) {
316
- const ranges = doc.main_track.filter((item) => doc.part_library[item.part_id] != null).map((item) => ({
317
- part_id: item.part_id,
318
- start: item.abs_time_position,
319
- end: item.abs_time_position + partDurationMs(doc, item.part_id)
320
- }));
321
- if (ranges.length === 0) {
322
- doc.aggregations = [];
323
- return;
324
- }
325
- const rebuilt = /* @__PURE__ */ new Map();
326
- for (const speechItem of doc.speech_track) {
327
- const start = speechItem.abs_time_position;
328
- const targetRange = ranges.find((r) => r.start <= start && start < r.end) ?? (start < ranges[0].start ? ranges[0] : ranges[ranges.length - 1]);
329
- const relative = Math.max(0, Math.round(start - targetRange.start));
330
- const targetId = targetRange.part_id;
331
- let aggregation = rebuilt.get(targetId);
332
- if (aggregation == null) {
333
- aggregation = {
334
- body_part_id: targetId,
335
- attachments: []
336
- };
337
- rebuilt.set(targetId, aggregation);
338
- }
339
- aggregation.attachments.push({
340
- part_id: speechItem.part_id,
341
- relative_time_position: relative
342
- });
343
- }
344
- doc.aggregations = ranges.map((r) => rebuilt.get(r.part_id)).filter((a) => a != null);
345
- }
346
- /**
347
- * Recompute `timeline.duration_ms` as the max end (abs + duration) across main,
348
- * speech, and caption lanes (BGM does not extend the timeline).
349
- *
350
- * BGM has no authoritative duration (RFC 02 / `reference/16` §0b): its effective
351
- * length is always the timeline total, so it is not written back here — the
352
- * projection derives it from `timeline.duration_ms` on read (`partDurationMs`
353
- * returns the timeline total for a bgm part). The empty-document 20s skeleton is
354
- * applied at that read step, not stored.
355
- */
356
- function recalculateTimelineDuration(doc) {
357
- const max = Math.max(laneEndMs(doc, doc.main_track), laneEndMs(doc, doc.speech_track), laneEndMs(doc, doc.caption_track));
358
- doc.timeline.duration_ms = max;
359
- }
360
- /**
361
- * Resolve one speech overlap by shifting the overlapping speech's host video
362
- * (and every clip after it) right. Returns true when one overlap was resolved;
363
- * callers loop until it returns false. The compared range is the speech merged
364
- * with its captions: start = min(speech.start, captions.start) (FE behavior),
365
- * end = max(speech.end, captions.end).
366
- */
367
- function resolveSpeechOverlapByShiftingVideos(doc) {
368
- const speeches = doc.speech_track;
369
- for (let i = 1; i < speeches.length; i++) {
370
- const prev = speechWithCaptionsRange(doc, speeches[i - 1]);
371
- const curr = speechWithCaptionsRange(doc, speeches[i]);
372
- if (prev == null || curr == null) continue;
373
- if (curr.start >= prev.end) continue;
374
- const overlapMs = Math.round(prev.end - curr.start);
375
- const hostId = hostVideoOf(doc, speeches[i].part_id);
376
- if (hostId == null) continue;
377
- const fromIndex = doc.main_track.findIndex((item) => item.part_id === hostId);
378
- if (fromIndex < 0) continue;
379
- for (let idx = fromIndex; idx < doc.main_track.length; idx++) doc.main_track[idx].abs_time_position += overlapMs;
380
- syncAggregatedClipsTimePosition(doc);
381
- return true;
382
- }
383
- return false;
384
- }
385
- /**
386
- * Resolve speech overlaps for one cascade pass. Mirrors the authoritative FE
387
- * `ensureNoOverlappingClips`, which is documented to resolve AT MOST ONE overlap
388
- * per cascade and is invoked exactly once at every FE call site — the supported
389
- * ops each produce at most one new overlap. It is NOT a fixpoint loop: shifting a
390
- * host right also moves every speech anchored to it, so two speeches sharing a
391
- * host can never be separated by shifting. Looping to a "fixed point" there does
392
- * not converge — it accumulates the same overlap every iteration and pushes the
393
- * clip arbitrarily far right (e.g. a sped-up clip landing at ~287k ms instead of
394
- * its seamless slot). A single pass matches FE product behavior and terminates.
395
- */
396
- function resolveAllSpeechOverlaps(doc) {
397
- resolveSpeechOverlapByShiftingVideos(doc);
398
- }
399
- /**
400
- * Make the main track gapless by adjusting/merging empty placeholder clips or
401
- * inserting new ones between real clips. Mirrors the harness four-case rule, but
402
- * the merge of two adjacent empty clips keeps the earlier clip (harness Case 4).
403
- * Requires `makeEmptyPart` to mint a placeholder part (the editor supplies an
404
- * id generator).
405
- */
406
- function fillMainTrackTimeGaps(doc, makeEmptyPart) {
407
- const items = doc.main_track;
408
- let i = 0;
409
- while (i < items.length) {
410
- const current = items[i];
411
- const currentPart = doc.part_library[current.part_id];
412
- if (currentPart == null) {
413
- i += 1;
414
- continue;
415
- }
416
- const currentEnd = current.abs_time_position + partDurationMs(doc, current.part_id);
417
- if (i + 1 >= items.length) break;
418
- const next = items[i + 1];
419
- const nextPart = doc.part_library[next.part_id];
420
- if (nextPart == null) {
421
- i += 1;
422
- continue;
423
- }
424
- const gap = next.abs_time_position - currentEnd;
425
- if (gap > 0) {
426
- if (isEmptyVideoClip(currentPart)) {
427
- extendEmptyClip(currentPart.video_clip, gap);
428
- continue;
429
- }
430
- if (isEmptyVideoClip(nextPart)) {
431
- next.abs_time_position -= gap;
432
- extendEmptyClip(nextPart.video_clip, gap);
433
- i += 1;
434
- continue;
435
- }
436
- const { partId } = makeEmptyPart(gap);
437
- doc.part_library[partId] = { video_clip: {
438
- id: partId,
439
- kind: "video_clip",
440
- play_in: 0,
441
- play_out: gap,
442
- volume: 0,
443
- origin_media_id: ""
444
- } };
445
- items.splice(i + 1, 0, {
446
- part_id: partId,
447
- time_position: { mode: "sequential" },
448
- abs_time_position: currentEnd
449
- });
450
- i += 1;
451
- continue;
452
- }
453
- if (gap === 0 && isEmptyVideoClip(currentPart) && isEmptyVideoClip(nextPart)) {
454
- extendEmptyClip(currentPart.video_clip, partDurationMs(doc, next.part_id));
455
- items.splice(i + 1, 1);
456
- delete doc.part_library[next.part_id];
457
- continue;
458
- }
459
- i += 1;
460
- }
461
- }
462
- function indexByPart(items) {
463
- const map = /* @__PURE__ */ new Map();
464
- for (const item of items) map.set(item.part_id, item);
465
- return map;
466
- }
467
- function laneEndMs(doc, items) {
468
- let max = 0;
469
- for (const item of items) {
470
- if (doc.part_library[item.part_id] == null) continue;
471
- const end = item.abs_time_position + partDurationMs(doc, item.part_id);
472
- if (end > max) max = end;
473
- }
474
- return max;
475
- }
476
- function extendEmptyClip(clip, byMs) {
477
- clip.play_out = safeDurationMs(clip.play_out) + byMs;
478
- }
479
- /** speech merged with its captions: start = min, end = max. */
480
- function speechWithCaptionsRange(doc, speechItem) {
481
- const speech = doc.part_library[speechItem.part_id]?.speech;
482
- if (speech == null) return null;
483
- let start = speechItem.abs_time_position;
484
- let end = speechItem.abs_time_position + safeDurationMs(speech.media_duration_ms);
485
- for (const captionId of captionIdsOf(speech)) {
486
- const captionItem = doc.caption_track.find((item) => item.part_id === captionId);
487
- const captionPart = doc.part_library[captionId]?.caption;
488
- if (captionItem == null || captionPart == null) continue;
489
- const cStart = captionItem.abs_time_position;
490
- const cEnd = captionItem.abs_time_position + safeDurationMs(captionPart.initial_duration_ms);
491
- if (cStart < start) start = cStart;
492
- if (cEnd > end) end = cEnd;
493
- }
494
- return {
495
- start,
496
- end
497
- };
498
- }
499
- function captionIdsOf(speech) {
500
- return (speech.caption_ids ?? []).filter((id) => id != null);
501
- }
502
- function hostVideoOf(doc, speechPartId) {
503
- for (const aggregation of doc.aggregations) if (aggregation.attachments.some((att) => att.part_id === speechPartId)) return aggregation.body_part_id;
504
- return null;
505
- }
506
- //#endregion
507
- //#region src/timeline-core/entrypoints.ts
508
- /**
509
- * The full solve pipeline: arrange → sync → reassign → resolve-overlap →
510
- * fill-gaps → recalc. The single cascade the read-side projection runs; ops
511
- * never call it (they write only facts — RFC 02 §7/§10).
512
- */
513
- function cascadeAfterVideoClipChanges(doc, makeEmptyPart) {
514
- arrangeMainTrackSeamlessly(doc);
515
- syncAggregatedClipsTimePosition(doc);
516
- reassignSpeechesToVideoClipsByTime(doc);
517
- resolveAllSpeechOverlaps(doc);
518
- fillMainTrackTimeGaps(doc, makeEmptyPart);
519
- recalculateTimelineDuration(doc);
520
- }
521
- //#endregion
522
- //#region src/timeline-core/bridge.ts
523
- /**
524
- * Solve a `VideoDocument` (authoritative, position-only) into its derived
525
- * read-view: absolute time per item, `part_aggregations`, and total duration.
526
- * This is the read side of the single-directional flow — never written back.
527
- */
528
- function solveVideoDocument(document) {
529
- const doc = videoDocumentToTimelineDoc(document);
530
- let counter = 0;
531
- const derivedFillerPartIds = /* @__PURE__ */ new Set();
532
- cascadeAfterVideoClipChanges(doc, () => {
533
- const partId = `empty_${counter++}`;
534
- derivedFillerPartIds.add(partId);
535
- return { partId };
536
- });
537
- const absByPartId = /* @__PURE__ */ new Map();
538
- for (const item of doc.main_track) absByPartId.set(item.part_id, item.abs_time_position);
539
- for (const item of doc.speech_track) absByPartId.set(item.part_id, item.abs_time_position);
540
- for (const item of doc.caption_track) absByPartId.set(item.part_id, item.abs_time_position);
541
- for (const item of doc.bgm_track) absByPartId.set(item.part_id, item.abs_time_position);
542
- return {
543
- absByPartId,
544
- aggregations: doc.aggregations.map((aggregation) => ({
545
- body_part_id: aggregation.body_part_id,
546
- attachments: aggregation.attachments.map((a) => ({
547
- part_id: a.part_id,
548
- relative_time_position: a.relative_time_position
549
- }))
550
- })),
551
- durationMs: doc.timeline.duration_ms,
552
- partLibrary: doc.part_library,
553
- derivedFillerPartIds
554
- };
555
- }
556
- function videoDocumentToTimelineDoc(document) {
557
- const partLibrary = {};
558
- for (const [partId, part] of Object.entries(document.part_library ?? {})) partLibrary[partId] = part;
559
- const laneItems = (track) => (track?.items ?? []).map((item) => ({
560
- part_id: item.part_id,
561
- time_position: item.time_position,
562
- abs_time_position: seedAbs(item.time_position, item.fallback_abs_ms),
563
- fallback_abs_ms: item.fallback_abs_ms
564
- }));
565
- const tracks = document.tracks ?? [];
566
- let mainItems = [];
567
- let speechItems = [];
568
- let bgmItems = [];
569
- let captionItems = [];
570
- for (const t of tracks) switch (t.parts_kind) {
571
- case "video_clip":
572
- mainItems = mainItems.concat(laneItems(t));
573
- break;
574
- case "speech":
575
- speechItems = speechItems.concat(laneItems(t));
576
- break;
577
- case "bgm":
578
- bgmItems = bgmItems.concat(laneItems(t));
579
- break;
580
- case "caption":
581
- captionItems = captionItems.concat(laneItems(t));
582
- break;
583
- }
584
- return {
585
- main_track: mainItems,
586
- speech_track: speechItems,
587
- caption_track: captionItems,
588
- bgm_track: bgmItems,
589
- part_library: partLibrary,
590
- aggregations: seedAggregations(mainItems, speechItems),
591
- timeline: {
592
- duration_ms: 0,
593
- unit_time_ms: document.timeline?.unit_time_ms ?? 0
594
- }
595
- };
596
- }
597
- /**
598
- * Seed an item's solve-variable `abs_time_position` from its `time_position` (and
599
- * the `fallback_abs_ms` snapshot carried beside it): `absolute` → `offsetMs`;
600
- * `anchored` → `fallbackAbsMs` (last solved position, also the orphan-recovery
601
- * anchor when the host is gone); `sequential` → 0 (the cascade lays the main
602
- * track out head-to-tail). The cascade then resolves anchored items against their
603
- * host, so this seed only needs to put each item somewhere plausible for the
604
- * first reassign/overlap pass.
605
- */
606
- function seedAbs(position, fallbackAbsMs) {
607
- switch (position.mode) {
608
- case "absolute": return Math.round(position.offsetMs);
609
- case "anchored": return Math.round(fallbackAbsMs ?? 0);
610
- case "sequential": return 0;
611
- }
612
- }
613
- /**
614
- * Build the cascade `aggregations` parent-map from anchored items: an anchored
615
- * item's `anchorPartId` is the host's `part_id` (= `body_part_id`), `offsetMs`
616
- * is `relative_time_position`. Only main-track (video) hosts form aggregations;
617
- * caption→speech relations are recomputed by the cascade from `caption.start_ms`.
618
- */
619
- function seedAggregations(mainItems, speechItems) {
620
- const mainPartIds = new Set(mainItems.map((item) => item.part_id));
621
- const byHost = /* @__PURE__ */ new Map();
622
- const order = [];
623
- for (const speech of speechItems) {
624
- if (speech.time_position.mode !== "anchored") continue;
625
- const host = speech.time_position.anchorPartId;
626
- if (!mainPartIds.has(host)) continue;
627
- let aggregation = byHost.get(host);
628
- if (aggregation == null) {
629
- aggregation = {
630
- body_part_id: host,
631
- attachments: []
632
- };
633
- byHost.set(host, aggregation);
634
- order.push(host);
635
- }
636
- aggregation.attachments.push({
637
- part_id: speech.part_id,
638
- relative_time_position: speech.time_position.offsetMs
639
- });
640
- }
641
- return order.map((host) => byHost.get(host));
642
- }
643
- /**
644
- * The four lanes in top-to-bottom stack order — the order a `tracks` list holds
645
- * them in (see {@link laneRank}).
646
- *
647
- * Exported so a document can be seeded with all four lanes up front. That seed is
648
- * not cosmetic: {@link ensureLaneTrack} is find-then-mint over a `LoroMovableList`,
649
- * so two concurrent writers that each mint the same absent lane both keep their
650
- * row, and the merged document holds two tracks for one lane. For the main lane
651
- * that is fatal — `videoDocumentSchema` allows at most one `video_clip` track, so
652
- * the merged document stops being projectable at all, symmetrically on both
653
- * replicas. Pre-seeding every lane makes `ensureLaneTrack` always take its find
654
- * branch, which removes the race by construction rather than by detection.
655
- *
656
- * What closes the race is that a track with the lane's `parts_kind` EXISTS — the
657
- * lookup is by kind, not by id. So a seed is only safe if it covers every lane:
658
- * a partial seed leaves the uncovered lanes exactly as exposed as before.
659
- */
660
- const LANE_KINDS_IN_STACK_ORDER = [
661
- "caption",
662
- "video_clip",
663
- "speech",
664
- "bgm"
665
- ];
666
- /**
667
- * The conventional track id for a lane (`main_track`, `<kind>_track`). Shared by
668
- * the up-front seed and {@link ensureLaneTrack}'s lazy mint so a document's lane
669
- * ids do not depend on which of the two created the track.
670
- *
671
- * Ids are cosmetic to the merge itself — lane lookup goes by `parts_kind`, so
672
- * drifting them apart would not reopen the concurrent-mint race. They matter to
673
- * readers that address a lane by id (the FE editor's panes, fixtures), which is
674
- * why there is one convention rather than two.
675
- */
676
- function laneTrackId(kind) {
677
- return kind === "video_clip" ? "main_track" : `${kind}_track`;
678
- }
679
- /**
680
- * Lane-stacking rank for the single `tracks` list (reference/17 §4): caption
681
- * (above) sits before the video_clip main track, which sits before speech / bgm
682
- * (below). The `tracks` array is kept in this top-to-bottom order so a freshly
683
- * minted track lands in the right place and the projection's three-pane rebuild
684
- * stays deterministic.
685
- */
686
- function laneRank(kind) {
687
- switch (kind) {
688
- case "caption": return 0;
689
- case "video_clip": return 1;
690
- case "speech":
691
- case "bgm": return 2;
692
- default: return 3;
693
- }
694
- }
695
- /**
696
- * Insert a freshly-minted track into `tracks` at the position that keeps the
697
- * lane-stacking order (caption → main → speech/bgm). Inserts before the first
698
- * track whose rank is strictly greater, so same-rank tracks keep insertion order.
699
- */
700
- function insertTrackByLaneOrder(tracks, track) {
701
- const rank = laneRank(track.parts_kind);
702
- const at = tracks.findIndex((t) => laneRank(t?.parts_kind) > rank);
703
- if (at < 0) tracks.push(track);
704
- else tracks.splice(at, 0, track);
705
- }
706
- /**
707
- * Locate a lane's track row in the single `tracks` list by kind, minting an empty
708
- * row in lane-stacking order if absent (reference/17 §4: lane = `parts_kind`).
709
- * Ops use this to write authoritative items onto the right lane. The track id
710
- * comes from {@link laneTrackId}, shared with the up-front seed.
711
- *
712
- * The mint branch is a concurrency hazard, not a convenience: see
713
- * {@link LANE_KINDS_IN_STACK_ORDER}. A document seeded with all four lanes never
714
- * reaches it.
715
- */
716
- function ensureLaneTrack(draft, kind) {
717
- draft.tracks ??= [];
718
- let track = draft.tracks.find((t) => t?.parts_kind === kind);
719
- if (track == null) {
720
- track = {
721
- id: laneTrackId(kind),
722
- parts_kind: kind,
723
- is_hidden: void 0,
724
- items: []
725
- };
726
- insertTrackByLaneOrder(draft.tracks, track);
727
- }
728
- track.items ??= [];
729
- return track;
730
- }
731
- /** Find a secondary lane's track row without minting it. */
732
- function findLaneTrack(draft, kind) {
733
- return (draft.tracks ?? []).find((t) => t?.parts_kind === kind);
734
- }
735
- //#endregion
736
- //#region src/document/zod-schema.ts
737
- const partKindSchema = z.enum([
738
- "video_clip",
739
- "speech",
740
- "caption",
741
- "bgm"
742
- ]);
743
- const finiteNumber = z.number().finite();
744
- const trackItemTimePositionSchema = z.discriminatedUnion("mode", [
745
- z.object({ mode: z.literal("sequential") }).passthrough(),
746
- z.object({
747
- mode: z.literal("anchored"),
748
- anchorPartId: z.string(),
749
- offsetMs: finiteNumber
750
- }).passthrough(),
751
- z.object({
752
- mode: z.literal("absolute"),
753
- offsetMs: finiteNumber
754
- }).passthrough()
755
- ]);
756
- const trackItemSchema = z.object({
757
- part_id: z.string(),
758
- time_position: trackItemTimePositionSchema,
759
- fallback_abs_ms: finiteNumber.optional()
760
- }).passthrough();
761
- const trackSchema = z.object({
762
- id: z.string().optional(),
763
- parts_kind: partKindSchema.optional(),
764
- is_hidden: z.boolean().optional(),
765
- items: z.array(trackItemSchema).optional()
766
- }).passthrough();
767
- const speedShiftSchema = z.object({
768
- category: z.string().optional(),
769
- mode: z.string().optional(),
770
- config: z.object({ linear: z.object({ speed: finiteNumber.optional() }).passthrough().optional() }).passthrough().optional()
771
- }).passthrough();
772
- const videoClipPartSchema = z.object({
773
- id: z.string().optional(),
774
- kind: z.literal("video_clip"),
775
- duration_ms: finiteNumber.optional(),
776
- play_in: finiteNumber,
777
- play_out: finiteNumber,
778
- volume: finiteNumber,
779
- origin_media_id: z.string(),
780
- speed_shift: speedShiftSchema.optional()
781
- }).passthrough();
782
- const speechPartSchema = z.object({
783
- id: z.string().optional(),
784
- kind: z.literal("speech"),
785
- media_duration_ms: finiteNumber,
786
- duration_ms: finiteNumber.optional(),
787
- audio_script: z.string(),
788
- volume: finiteNumber,
789
- audio_storage_key: z.string(),
790
- origin_speech_id: z.string(),
791
- voice: z.unknown(),
792
- caption_ids: z.array(z.string())
793
- }).passthrough();
794
- const captionPartSchema = z.object({
795
- id: z.string().optional(),
796
- kind: z.literal("caption"),
797
- initial_duration_ms: finiteNumber,
798
- speech_part_id: z.string(),
799
- text: z.string(),
800
- start_ms: finiteNumber,
801
- style: z.object({
802
- font_id: z.string().optional(),
803
- font_size: finiteNumber.optional(),
804
- font_color: z.string().optional(),
805
- font_weight: finiteNumber.optional(),
806
- entrance_animation: z.string().optional(),
807
- entrance_animation_duration_ms: finiteNumber.optional(),
808
- stroke_color: z.string().optional(),
809
- stroke_width: finiteNumber.optional(),
810
- position_x: finiteNumber.optional(),
811
- position_y: finiteNumber.optional()
812
- }).passthrough().optional()
813
- }).passthrough();
814
- const bgmPartSchema = z.object({
815
- id: z.string().optional(),
816
- kind: z.literal("bgm"),
817
- audio_storage_key: z.string(),
818
- volume: finiteNumber,
819
- origin_media_id: z.string()
820
- }).passthrough();
821
- const partUnionSchema = z.union([
822
- z.object({ video_clip: videoClipPartSchema }).passthrough(),
823
- z.object({ speech: speechPartSchema }).passthrough(),
824
- z.object({ caption: captionPartSchema }).passthrough(),
825
- z.object({ bgm: bgmPartSchema }).passthrough()
826
- ]).refine((part) => {
827
- const p = part;
828
- return [
829
- "video_clip",
830
- "speech",
831
- "caption",
832
- "bgm"
833
- ].filter((k) => p[k] != null).length === 1;
834
- }, { message: "A part_library value must have exactly one of video_clip / speech / caption / bgm" });
835
- const videoDocumentSchema = z.object({
836
- timeline: z.object({ unit_time_ms: finiteNumber.optional() }).passthrough().optional(),
837
- tracks: z.array(trackSchema).optional(),
838
- part_library: z.record(z.string(), partUnionSchema).optional()
839
- }).passthrough().refine((doc) => (doc.tracks ?? []).filter((t) => t.parts_kind === "video_clip").length <= 1, {
840
- message: "A VideoDocument may have at most one video_clip (main) track",
841
- path: ["tracks"]
842
- });
843
- //#endregion
844
- //#region src/document/validation.ts
845
- /**
846
- * Business-level schema guard for `VideoDocument` (RFC 03 §9). It is the gate
847
- * that decides whether an arbitrary value is a *legal* `VideoDocument` before it
848
- * is written into Loro — distinct from two neighbours:
849
- *
850
- * - `zod-schema.ts` (`videoDocumentSchema`) checks structure/shape only; this
851
- * file layers the business rules on top (part-kind match, reference integrity,
852
- * `position.anchorPartId` targets, value ranges, identity uniqueness).
853
- * - loro-mirror's own `validateSchema` (run on every `setState`) only checks the
854
- * storage structure, never these business invariants.
855
- *
856
- * Projection (`projection.ts`) calls `assertValidVideoDocument` before solving a
857
- * document into the legacy `VideoDraft`.
858
- */
859
- var VideoDocumentValidationError = class extends Error {
860
- issues;
861
- constructor(issues) {
862
- super(`Invalid VideoDocument: ${issues.map((issue) => issue.message).join("; ")}`);
863
- this.issues = issues;
864
- this.name = "VideoDocumentValidationError";
865
- }
866
- };
867
- /**
868
- * Assert the document is legal enough to project. Only `error`-severity issues
869
- * hard-reject; `recoverable` ones (dangling anchor / orphan, RFC 02 §11.1) are
870
- * left for the projection to heal on read and do NOT throw. Use
871
- * `validateVideoDocument` directly to inspect recoverable issues too.
872
- */
873
- function assertValidVideoDocument(document) {
874
- const blocking = validateVideoDocument(document).filter((issue) => (issue.severity ?? "error") === "error");
875
- if (blocking.length > 0) throw new VideoDocumentValidationError(blocking);
876
- }
877
- function validateVideoDocument(document) {
878
- const parsed = videoDocumentSchema.safeParse(document);
879
- if (!parsed.success) return parsed.error.issues.map((issue) => ({
880
- code: "invalid_schema",
881
- path: zodPath(issue.path),
882
- message: issue.message
883
- }));
884
- const doc = parsed.data;
885
- const issues = [];
886
- const partLibrary = doc.part_library ?? {};
887
- for (const [partId, part] of Object.entries(partLibrary)) {
888
- if (!partUnionSchema.safeParse(part).success) {
889
- issues.push({
890
- code: "unknown_part_kind",
891
- path: `/part_library/${partId}`,
892
- message: `Part "${partId}" is not a supported part union`
893
- });
894
- continue;
895
- }
896
- const wrapperKind = getPartUnionKind(part);
897
- const innerKind = getPartKind(part);
898
- if (wrapperKind != null && innerKind != null && wrapperKind !== innerKind) issues.push({
899
- code: "part_kind_mismatch",
900
- path: `/part_library/${partId}`,
901
- message: `Part "${partId}" wrapper kind "${wrapperKind}" does not match inner kind "${innerKind}"`
902
- });
903
- validatePartValues(partId, part, issues);
904
- }
905
- for (const [idx, track] of (doc.tracks ?? []).entries()) validateTrack(track, `tracks/${idx}`, partLibrary, issues, track.parts_kind === "video_clip");
906
- validateLaneTrackUniqueness(doc, issues);
907
- validateSpeechCaptionReferences(partLibrary, issues);
908
- validatePositionReferences(doc, partLibrary, issues);
909
- return issues;
910
- }
911
- /**
912
- * Report a duplicated lane: two tracks sharing the same `id`, or two secondary
913
- * tracks of the same `parts_kind`.
914
- *
915
- * Found by the Phase 6 M0/S2 concurrency probe. `ensureLaneTrack` locates a lane
916
- * by `parts_kind` and mints `<kind>_track` when absent, so two replicas that both
917
- * start without (say) a caption track each create one; `tracks` is a
918
- * `LoroMovableList`, so the merge keeps BOTH. The lane is then split across two
919
- * same-id tracks, and the projection's `find`-by-kind returns only one of them —
920
- * so an item can be authoritative yet invisible in the pane a reader looks at.
921
- *
922
- * Flagged **recoverable**, not `error`, for two reasons. It is a reachable
923
- * outcome of ordinary concurrent editing, and hard-rejecting would make an
924
- * unavoidable merge result un-projectable — the same argument §11.1 makes for
925
- * orphans. And the projection already tolerates it: `solveVideoDocument`
926
- * concatenates every track of a kind, so the cascade sees all items regardless.
927
- * The defect is a *reader-visible* split, so the right response is to surface it
928
- * (loudly, in a channel someone reads), not to block the document.
929
- *
930
- * The main track is exempt from the kind check: `parts_kind === 'video_clip'` may
931
- * legitimately appear on several tracks (the projection treats only the first as
932
- * the main pane), so only its `id` collision is reported.
933
- */
934
- function validateLaneTrackUniqueness(doc, issues) {
935
- const tracks = doc.tracks ?? [];
936
- const seenIds = /* @__PURE__ */ new Set();
937
- const seenSecondaryKinds = /* @__PURE__ */ new Set();
938
- for (const [idx, track] of tracks.entries()) {
939
- const id = track?.id;
940
- if (id != null && id !== "") if (seenIds.has(id)) issues.push({
941
- code: "duplicate_lane_track",
942
- path: `/tracks/${idx}/id`,
943
- message: `Track "tracks/${idx}" reuses track id "${id}"`,
944
- severity: "recoverable"
945
- });
946
- else seenIds.add(id);
947
- const kind = track?.parts_kind;
948
- if (kind == null || kind === "video_clip") continue;
949
- if (seenSecondaryKinds.has(kind)) issues.push({
950
- code: "duplicate_lane_track",
951
- path: `/tracks/${idx}/parts_kind`,
952
- message: `Lane "${kind}" is split across more than one track (at "tracks/${idx}")`,
953
- severity: "recoverable"
954
- });
955
- else seenSecondaryKinds.add(kind);
956
- }
957
- }
958
- /**
959
- * An `anchored` item whose `anchorPartId` no longer exists in the library is the
960
- * orphan condition (RFC 02 §4/§11.1) — e.g. a speech whose host video, or a
961
- * caption whose host speech, was concurrently deleted while this item was being
962
- * reparented in. This is flagged as a **recoverable** issue, NOT a hard error:
963
- * the projection heals it on read (the item's `fallback_abs_ms` snapshot seeds
964
- * its absolute position, then the cascade reassigns it to the nearest available
965
- * host, or it stays put as an absolute item). Reporting it here keeps the orphan
966
- * observable without blocking projection — the opposite of a hard reject, which
967
- * would make an inevitable concurrent-delete outcome un-projectable (§11.1).
968
- */
969
- function validatePositionReferences(doc, partLibrary, issues) {
970
- const tracks = (doc.tracks ?? []).map((track, idx) => ({
971
- track,
972
- path: `tracks/${idx}`
973
- }));
974
- for (const { track, path } of tracks) for (const [idx, item] of (track?.items ?? []).entries()) {
975
- if (item.time_position.mode !== "anchored") continue;
976
- if (partLibrary[item.time_position.anchorPartId] == null) issues.push({
977
- code: "invalid_position_anchor",
978
- path: `/${path}/items/${idx}/time_position/anchorPartId`,
979
- message: `Track item "${path}/${idx}" anchors to missing part "${item.time_position.anchorPartId}"`,
980
- severity: "recoverable"
981
- });
982
- }
983
- }
984
- function validatePartValues(partId, part, issues) {
985
- const payload = part.video_clip ?? part.speech ?? part.caption ?? part.bgm ?? void 0;
986
- if (payload == null) return;
987
- if ("duration_ms" in payload && payload.duration_ms != null && payload.duration_ms < 0) issues.push({
988
- code: "invalid_part_value",
989
- path: `/part_library/${partId}/duration_ms`,
990
- message: `Part "${partId}" has negative duration_ms`
991
- });
992
- if ("volume" in payload && payload.volume != null && !Number.isFinite(payload.volume)) issues.push({
993
- code: "invalid_part_value",
994
- path: `/part_library/${partId}/volume`,
995
- message: `Part "${partId}" has non-finite volume`
996
- });
997
- if (part.video_clip != null) {
998
- const { play_in, play_out } = part.video_clip;
999
- if (play_in != null && play_in < 0) issues.push({
1000
- code: "invalid_part_value",
1001
- path: `/part_library/${partId}/play_in`,
1002
- message: `Video clip "${partId}" has negative play_in`
1003
- });
1004
- if (play_out != null && play_in != null && play_out < play_in) issues.push({
1005
- code: "invalid_part_value",
1006
- path: `/part_library/${partId}/play_out`,
1007
- message: `Video clip "${partId}" has play_out before play_in`
1008
- });
1009
- }
1010
- }
1011
- function validateTrack(track, path, partLibrary, issues, isMainTrack) {
1012
- if (track == null) return;
1013
- const seenPartIds = /* @__PURE__ */ new Set();
1014
- for (const [idx, item] of (track.items ?? []).entries()) {
1015
- const partId = item.part_id;
1016
- if (partId != null && partId !== "") if (seenPartIds.has(partId)) issues.push({
1017
- code: "duplicate_track_item_identity",
1018
- path: `/${path}/items/${idx}/part_id`,
1019
- message: `Track item "${path}/${idx}" reuses part_id "${partId}"`
1020
- });
1021
- else seenPartIds.add(partId);
1022
- if (partId == null || partId === "") {
1023
- issues.push({
1024
- code: "missing_part_reference",
1025
- path: `/${path}/items/${idx}/part_id`,
1026
- message: `Track item "${path}/${idx}" has no part_id`
1027
- });
1028
- continue;
1029
- }
1030
- const part = partLibrary[partId];
1031
- if (part == null) {
1032
- issues.push({
1033
- code: "missing_part_reference",
1034
- path: `/${path}/items/${idx}/part_id`,
1035
- message: `Track item "${path}/${idx}" references missing part "${partId}"`
1036
- });
1037
- continue;
1038
- }
1039
- const partKind = getPartKind(part);
1040
- if (isMainTrack && partKind !== "video_clip") issues.push({
1041
- code: "main_track_non_video_clip",
1042
- path: `/${path}/items/${idx}/part_id`,
1043
- message: `Main track item "${path}/${idx}" references non-video part "${partId}"`
1044
- });
1045
- if (track.parts_kind != null && partKind != null && track.parts_kind !== partKind) issues.push({
1046
- code: "track_kind_mismatch",
1047
- path: `/${path}/items/${idx}/part_id`,
1048
- message: `Track "${path}" expects "${track.parts_kind}" but part "${partId}" is "${partKind}"`
1049
- });
1050
- }
1051
- }
1052
- /**
1053
- * Check speech↔caption references. A reference to a *missing* part (speech's
1054
- * caption_ids → deleted caption, or caption's speech_part_id → deleted speech)
1055
- * is the orphan condition (RFC 02 §11.1): reported as **recoverable** so the
1056
- * projection can heal it on read, not block. A *back-pointer mismatch* (caption
1057
- * exists but does not point back) is data corruption, kept as a hard error.
1058
- */
1059
- function validateSpeechCaptionReferences(partLibrary, issues) {
1060
- for (const [partId, part] of Object.entries(partLibrary)) {
1061
- if (part.speech != null) for (const captionId of part.speech.caption_ids ?? []) {
1062
- const caption = partLibrary[captionId]?.caption;
1063
- if (caption == null) {
1064
- issues.push({
1065
- code: "invalid_speech_caption_reference",
1066
- path: `/part_library/${partId}/speech/caption_ids`,
1067
- message: `Speech "${partId}" references missing caption "${captionId}"`,
1068
- severity: "recoverable"
1069
- });
1070
- continue;
1071
- }
1072
- if (caption.speech_part_id !== partId) issues.push({
1073
- code: "invalid_speech_caption_reference",
1074
- path: `/part_library/${captionId}/caption/speech_part_id`,
1075
- message: `Caption "${captionId}" does not point back to speech "${partId}"`
1076
- });
1077
- }
1078
- if (part.caption != null) {
1079
- const speechId = part.caption.speech_part_id;
1080
- if (speechId != null && partLibrary[speechId]?.speech == null) issues.push({
1081
- code: "invalid_speech_caption_reference",
1082
- path: `/part_library/${partId}/caption/speech_part_id`,
1083
- message: `Caption "${partId}" references missing speech "${speechId}"`,
1084
- severity: "recoverable"
1085
- });
1086
- }
1087
- }
1088
- }
1089
- function getPartUnionKind(part) {
1090
- if (part.video_clip != null) return "video_clip";
1091
- if (part.speech != null) return "speech";
1092
- if (part.caption != null) return "caption";
1093
- if (part.bgm != null) return "bgm";
1094
- }
1095
- function getPartKind(part) {
1096
- return part.video_clip?.kind ?? part.speech?.kind ?? part.caption?.kind ?? part.bgm?.kind;
1097
- }
1098
- function zodPath(path) {
1099
- if (path.length === 0) return "/";
1100
- return `/${path.map(String).join("/")}`;
1101
- }
1102
- //#endregion
1103
- //#region src/document/projection.ts
1104
- /**
1105
- * Projection between authoritative `VideoDocument` and compatible content
1106
- * layouts (RFC 02 §5/§7). Both directions live here:
1107
- *
1108
- * - `toVideoDocument` ingests a `VideoDraft`, deriving each item's `position`
1109
- * from the legacy absolute layout + aggregations; derived values (abs time,
1110
- * `part_aggregations`, total duration) are dropped.
1111
- * - `fromVideoDocument` solves a `VideoDocument` into `VideoDraftContent` via the
1112
- * timeline-core cascade, re-deriving exactly those values.
1113
- *
1114
- * Business validation lives in `validation.ts`; `fromVideoDocument` asserts a
1115
- * valid document before solving.
1116
- */
1117
- /**
1118
- * Ingest the legacy `VideoDraft` into the authoritative `VideoDocument`,
1119
- * deriving each item's `time_position` from the legacy absolute layout +
1120
- * aggregations (RFC 02 §4/§5). Absolute time, `part_aggregations`, and total
1121
- * duration are dropped — they are re-derived by the projection.
1122
- */
1123
- function toVideoDocument(draft) {
1124
- const speechHost = buildSpeechHostMap(draft.part_aggregations);
1125
- const partLibrary = draft.part_library ?? {};
1126
- const toTrack = (track, isMain) => {
1127
- if (track == null) return void 0;
1128
- return {
1129
- id: track.id,
1130
- parts_kind: track.parts_kind,
1131
- is_hidden: track.is_hidden,
1132
- items: (track.items ?? []).map((item) => deriveItem(item, isMain, speechHost, partLibrary))
1133
- };
1134
- };
1135
- const mainTrack = toTrack(draft.main_track, true);
1136
- const tracks = [
1137
- ...(draft.above_main_tracks ?? []).map((t) => toTrack(t, false)),
1138
- ...mainTrack == null ? [] : [mainTrack],
1139
- ...(draft.below_main_tracks ?? []).map((t) => toTrack(t, false))
1140
- ];
1141
- return {
1142
- timeline: draft.timeline == null ? void 0 : { unit_time_ms: draft.timeline.unit_time_ms },
1143
- tracks,
1144
- part_library: toAuthoritativePartLibrary(draft.part_library)
1145
- };
1146
- }
1147
- /**
1148
- * Map the legacy `VideoDraft` part library into the authoritative shape
1149
- * (reference/17 §5): the authoritative parts store no derived part-level
1150
- * duration, so the read-view `duration_ms` is dropped from video / speech / bgm.
1151
- * For a caption the legacy `duration_ms` is the generation-time length, stored
1152
- * authoritatively as `initial_duration_ms`.
1153
- */
1154
- function toAuthoritativePartLibrary(partLibrary) {
1155
- if (partLibrary == null) return void 0;
1156
- const out = {};
1157
- for (const [partId, part] of Object.entries(partLibrary)) {
1158
- if (typeof part !== "object" || part == null) continue;
1159
- if (part.video_clip != null) out[partId] = { video_clip: withTrimWindowFromDuration(part.video_clip) };
1160
- else if (part.speech != null) {
1161
- const { duration_ms, rest } = splitDurationMs(part.speech);
1162
- out[partId] = { speech: {
1163
- ...rest,
1164
- media_duration_ms: rest.media_duration_ms ?? duration_ms
1165
- } };
1166
- } else if (part.caption != null) {
1167
- const { duration_ms, rest } = splitDurationMs(part.caption);
1168
- out[partId] = { caption: {
1169
- ...rest,
1170
- initial_duration_ms: rest.initial_duration_ms ?? duration_ms
1171
- } };
1172
- } else if (part.bgm != null) out[partId] = { bgm: omitDurationMs(part.bgm) };
1173
- }
1174
- return out;
1175
- }
1176
- /**
1177
- * Build a speech-host map from a part_aggregations list. Used by
1178
- * `toVideoDocument` (legacy VideoDraft → VideoDocument) to recover each speech's
1179
- * host video clip and relative offset. Aggregation items with null ids are
1180
- * skipped (malformed input tolerance).
1181
- */
1182
- function buildSpeechHostMap(aggregations) {
1183
- const map = /* @__PURE__ */ new Map();
1184
- for (const aggregation of aggregations ?? []) {
1185
- const host = aggregation.body_part_id;
1186
- if (host == null) continue;
1187
- for (const attachment of aggregation.attachments ?? []) {
1188
- if (attachment.part_id == null) continue;
1189
- map.set(attachment.part_id, {
1190
- hostPartId: host,
1191
- offsetMs: Math.round(attachment.relative_time_position ?? 0)
1192
- });
1193
- }
1194
- }
1195
- return map;
1196
- }
1197
- /**
1198
- * Derive `time_position` (and `fallbackAbsMs` for anchored items) from a legacy
1199
- * absolute time + pre-built speech-host map + part library. The three-branch
1200
- * rule (RFC 02 §4/§5, reference/17 §3):
1201
- *
1202
- * 1. main-track → `sequential`
1203
- * 2. speech/attachment (part_id in speechHost) → `anchored(host, offsetMs)`
1204
- * 3. caption (part has `speech_part_id`) → `anchored(speech, start_ms)`
1205
- * 4. everything else → `absolute(abs)`
1206
- *
1207
- * `partLibrary` values may be `PartUnion | string | undefined` (draft raw
1208
- * form); only object-typed entries are inspected for `caption`.
1209
- */
1210
- function derivePositionFromAbs(partId, abs, isMain, speechHost, partLibrary) {
1211
- if (isMain) return { timePosition: { mode: "sequential" } };
1212
- const host = speechHost.get(partId);
1213
- if (host != null) return {
1214
- timePosition: {
1215
- mode: "anchored",
1216
- anchorPartId: host.hostPartId,
1217
- offsetMs: host.offsetMs
1218
- },
1219
- fallbackAbsMs: abs
1220
- };
1221
- const part = partLibrary[partId];
1222
- const captionPart = typeof part === "object" && part != null ? part.caption : void 0;
1223
- const speechId = captionPart?.speech_part_id ?? void 0;
1224
- if (speechId != null) return {
1225
- timePosition: {
1226
- mode: "anchored",
1227
- anchorPartId: speechId,
1228
- offsetMs: Math.round(captionPart?.start_ms ?? 0)
1229
- },
1230
- fallbackAbsMs: abs
1231
- };
1232
- return { timePosition: {
1233
- mode: "absolute",
1234
- offsetMs: abs
1235
- } };
1236
- }
1237
- /** Derive one item's authoritative `time_position` from its legacy abs + aggregation. */
1238
- function deriveItem(item, isMain, speechHost, partLibrary) {
1239
- const partId = item.part_id ?? "";
1240
- const { timePosition, fallbackAbsMs } = derivePositionFromAbs(partId, Math.round(item.abs_time_position ?? 0), isMain, speechHost, partLibrary);
1241
- return fallbackAbsMs == null ? {
1242
- part_id: partId,
1243
- time_position: timePosition
1244
- } : {
1245
- part_id: partId,
1246
- time_position: timePosition,
1247
- fallback_abs_ms: fallbackAbsMs
1248
- };
1249
- }
1250
- /**
1251
- * Project `VideoDocument` into `VideoDraftContent`, solving each item's
1252
- * absolute position, the `part_aggregations`, and
1253
- * the total duration via the timeline-core cascade.
1254
- *
1255
- * The read-view is a compatibility contract, and the IDL declares
1256
- * `Timeline.unit_time_ms` and `Track.is_hidden` `@required`
1257
- * (`video_draft_comp.smithy`) — so a projection that omitted them handed every
1258
- * consumer a payload that violated the shape it claims to satisfy, leaving each
1259
- * one to invent its own default. Two already had, and they disagreed: the agent
1260
- * harness used `unit_time_ms: 0`, director used a frame at 30fps. Defaulting here
1261
- * makes the contract true at the one place that produces it.
1262
- *
1263
- * These two are defaultable because the projection knows their values on its own:
1264
- * absent `unit_time_ms` means "no display granularity was ever stated" and absent
1265
- * `is_hidden` means "this track was never hidden". `version` is NOT defaultable
1266
- * here — it belongs to Director assembly using the server envelope update_seq.
1267
- * Neither business metadata nor a revision counter belongs in content projection.
1268
- */
1269
- function fromVideoDocument(document) {
1270
- assertValidVideoDocument(document);
1271
- const view = solveVideoDocument(document);
1272
- const tracks = document.tracks ?? [];
1273
- const mainTrack = tracks.find((t) => t.parts_kind === "video_clip");
1274
- const aboveTracks = tracks.filter((t) => t.parts_kind === "caption");
1275
- const belowTracks = tracks.filter((t) => t.parts_kind === "speech" || t.parts_kind === "bgm");
1276
- return {
1277
- timeline: {
1278
- duration_ms: view.durationMs,
1279
- unit_time_ms: document.timeline?.unit_time_ms ?? 33.333
1280
- },
1281
- main_track: draftTrack(mainTrack, view.absByPartId),
1282
- above_main_tracks: aboveTracks.map((t) => draftTrack(t, view.absByPartId)),
1283
- below_main_tracks: belowTracks.map((t) => draftTrack(t, view.absByPartId)),
1284
- part_aggregations: view.aggregations,
1285
- part_library: toReadViewPartLibrary(view.partLibrary, view.durationMs, view.derivedFillerPartIds)
1286
- };
1287
- }
1288
- /**
1289
- * Map the authoritative part library into the `VideoDraft` read-view shape,
1290
- * re-injecting the derived effective `duration_ms` downstream expects
1291
- * (reference/17 §5/§7) — the authoritative parts store no part-level duration:
1292
- *
1293
- * - video clip → `(play_out - play_in) / speed` (`effectiveVideoClipDurationMs`)
1294
- * - speech → its intrinsic `media_duration_ms` (no trim/speed)
1295
- * - caption → its generation-time `initial_duration_ms`
1296
- * - bgm → the timeline total (`durationMs`)
1297
- *
1298
- * Parts are deep-cloned; the engine extensions (`media_duration_ms`,
1299
- * `initial_duration_ms`) are kept alongside the injected `duration_ms`.
1300
- *
1301
- * `derivedFillerPartIds` are skipped: the solve minted them to lay the track out
1302
- * and they are not part of the document (see `fromVideoDocument`). An empty clip a
1303
- * writer placed deliberately is NOT in that set and is projected normally.
1304
- */
1305
- function toReadViewPartLibrary(partLibrary, durationMs, derivedFillerPartIds) {
1306
- const out = {};
1307
- for (const [partId, part] of Object.entries(partLibrary)) {
1308
- if (derivedFillerPartIds.has(partId)) continue;
1309
- if (part.video_clip != null) {
1310
- const clip = clone(part.video_clip);
1311
- out[partId] = { video_clip: {
1312
- ...clip,
1313
- duration_ms: effectiveVideoClipDurationMs(clip)
1314
- } };
1315
- } else if (part.speech != null) {
1316
- const speech = clone(part.speech);
1317
- out[partId] = { speech: {
1318
- ...speech,
1319
- duration_ms: speech.media_duration_ms
1320
- } };
1321
- } else if (part.caption != null) {
1322
- const caption = clone(part.caption);
1323
- out[partId] = { caption: {
1324
- ...caption,
1325
- duration_ms: caption.initial_duration_ms
1326
- } };
1327
- } else if (part.bgm != null) out[partId] = { bgm: {
1328
- ...clone(part.bgm),
1329
- duration_ms: durationMs
1330
- } };
1331
- }
1332
- return out;
1333
- }
1334
- /** Deep-clone a part payload, dropping the derived read-view `duration_ms`. */
1335
- function omitDurationMs(part) {
1336
- const { duration_ms: _drop, ...rest } = clone(part);
1337
- return rest;
1338
- }
1339
- /**
1340
- * Migrate a legacy video clip into the authoritative trim-window-only shape: the
1341
- * authoritative part stores no `duration_ms`, so it is dropped — but a legacy
1342
- * clip with no explicit trim window (`play_in` / `play_out` absent) would then
1343
- * compute an effective length of 0 and vanish from the layout. When that clip
1344
- * carried a legacy `duration_ms`, backfill it as the trim window (`play_in` 0,
1345
- * `play_out = duration_ms`, no speed) so the effective length is preserved, then
1346
- * drop `duration_ms`. A clip that already has a trim window keeps it verbatim.
1347
- */
1348
- function withTrimWindowFromDuration(clip) {
1349
- const stripped = omitDurationMs(clip);
1350
- if (clip.play_in != null || clip.play_out != null) return stripped;
1351
- const legacyDuration = clip.duration_ms;
1352
- if (legacyDuration == null || !Number.isFinite(legacyDuration)) return stripped;
1353
- return {
1354
- ...stripped,
1355
- play_in: 0,
1356
- play_out: legacyDuration
1357
- };
1358
- }
1359
- /** Deep-clone a part payload, returning its `duration_ms` separately from the rest. */
1360
- function splitDurationMs(part) {
1361
- const { duration_ms, ...rest } = clone(part);
1362
- return {
1363
- duration_ms,
1364
- rest
1365
- };
1366
- }
1367
- function draftTrack(track, absByPartId) {
1368
- if (track == null) return void 0;
1369
- return {
1370
- id: track.id,
1371
- parts_kind: track.parts_kind,
1372
- is_hidden: track.is_hidden ?? false,
1373
- items: (track.items ?? []).map((item) => ({
1374
- part_id: item.part_id,
1375
- abs_time_position: absByPartId.get(item.part_id) ?? 0
1376
- }))
1377
- };
1378
- }
1379
- function clone(value) {
1380
- if (Array.isArray(value)) return value.map((item) => clone(item));
1381
- if (value != null && typeof value === "object") {
1382
- const result = {};
1383
- for (const [key, child] of Object.entries(value)) result[key] = clone(child);
1384
- return result;
1385
- }
1386
- return value;
1387
- }
1388
- //#endregion
1389
- //#region src/document/initial-document.ts
1390
- /**
1391
- * Build the `VideoDocument` a newly created project starts from: the caller's
1392
- * no parts and one empty track per lane. Business facts remain in Director.
1393
- *
1394
- * The empty lane tracks are the reason this function exists rather than callers
1395
- * assembling a document inline. Lane tracks are otherwise minted lazily by the
1396
- * first op that needs one (`ensureLaneTrack`), which is find-then-mint over a
1397
- * CRDT list — so if the Agent's first generation and a user edit race on an
1398
- * empty document, each mints its own copy of the same lane and the merge keeps
1399
- * both. Two video_clip tracks violate the at-most-one-main-track rule, and the
1400
- * merged document becomes unprojectable for *every* reader (editor, render,
1401
- * share) with no winning replica to fall back on. Seeding all four lanes up
1402
- * front means `ensureLaneTrack` only ever finds, never mints, so the race cannot
1403
- * happen on a document created here.
1404
- *
1405
- * All four, not just the main lane: the secondary lanes fail less loudly (a
1406
- * duplicate pane rather than an unreadable document), but they fail by the same
1407
- * mechanism, and covering only the fatal one would leave three live races.
1408
- *
1409
- * `timeline` is left absent: `unit_time_ms` is a display concern the editor
1410
- * supplies, and total duration is derived on read (RFC 02 §6), so a new document
1411
- * has no timeline fact to state.
1412
- */
1413
- function buildInitialVideoDocument() {
1414
- return {
1415
- timeline: void 0,
1416
- tracks: emptyLaneTracks(),
1417
- part_library: {}
1418
- };
1419
- }
1420
- /** One empty track per lane, in lane-stacking order, with the conventional ids. */
1421
- function emptyLaneTracks() {
1422
- return LANE_KINDS_IN_STACK_ORDER.map((kind) => ({
1423
- id: laneTrackId(kind),
1424
- parts_kind: kind,
1425
- is_hidden: void 0,
1426
- items: []
1427
- }));
1428
- }
1429
- //#endregion
1430
- //#region src/document/mirror-read.ts
1431
- /**
1432
- * Project the mirror state (`VideoDocumentDraft`) into the authoritative
1433
- * `VideoDocument`. The storage shape is isomorphic to the domain shape (RFC 03
1434
- * §4, reference/17 §4: timeline + a single `tracks` list + part_library), so this
1435
- * is a near-identity — it reads `time_position` / `fallback_abs_ms` JSON blobs
1436
- * back into structured values and selects content fields. Legacy meta is ignored.
1437
- *
1438
- * It maps only authoritative facts (RFC 02 §6): `part_id` + `time_position`. The
1439
- * projection-derived `VideoDraft` read-view (absolute time, `part_aggregations`,
1440
- * total duration) is solved separately by the cascade, not here.
1441
- *
1442
- * It reads in-memory mirror state (O(n) over the document), not a Loro
1443
- * `toJSON()` FFI rebuild — the cost the prior schema adapter paid on every
1444
- * `snapshot()`.
1445
- */
1446
- function readVideoDocumentFromDraft(draft) {
1447
- const partLibrary = {};
1448
- for (const [partId, payload] of recordEntries(draft.part_library)) {
1449
- const part = draftToPartUnion(payload);
1450
- if (part != null) partLibrary[partId] = part;
1451
- }
1452
- const timeline = draft.timeline;
1453
- return {
1454
- timeline: timeline?.unit_time_ms != null ? { unit_time_ms: timeline.unit_time_ms } : void 0,
1455
- tracks: rowsToTracks(draft.tracks),
1456
- part_library: partLibrary
1457
- };
1458
- }
1459
- /** Map a movable-list of track rows (`$cid`-bearing) into domain tracks, dropping empty-id placeholders. */
1460
- function rowsToTracks(rows) {
1461
- return (rows ?? []).filter((row) => row.id != null && row.id !== "").map(rowToTrack);
1462
- }
1463
- function rowToTrack(row) {
1464
- return {
1465
- id: row.id,
1466
- parts_kind: row.parts_kind ?? void 0,
1467
- is_hidden: row.is_hidden ?? void 0,
1468
- items: (row.items ?? []).map((item) => {
1469
- const result = {
1470
- part_id: item.part_id ?? "",
1471
- time_position: item.time_position
1472
- };
1473
- if (item.fallback_abs_ms != null) result.fallback_abs_ms = item.fallback_abs_ms;
1474
- return result;
1475
- })
1476
- };
1477
- }
1478
- //#endregion
1479
- //#region src/document/mirror-adapter.ts
1480
- /**
1481
- * Storage-layer adapter that backs a `VideoDocument` with `loro-mirror` (ADR
1482
- * 0008). The mirror holds an in-memory immutable state synced to the `LoroDoc`
1483
- * by declarative diff, replacing the hand-rolled `@mengine/schema` adapter:
1484
- *
1485
- * - `snapshot()` projects the mirror's in-memory state to the read model — no
1486
- * per-call `toJSON()` FFI rebuild.
1487
- * - `transact(edit, audit)` runs the whole op in one `mirror.setState` callback:
1488
- * one diff, one `doc.commit` carrying the audit message. The callback edits an
1489
- * immer draft, so a throw inside it discards the draft and never touches Loro
1490
- * (natural rollback) — no `guard` / `rollback` / `openTransaction` machinery.
1491
- * - mirror's `idSelector` (track items keyed by `part_id`) diffs reorders to
1492
- * real Loro `move` ops on every lane, so per-item CRDT identity survives on
1493
- * main and secondary tracks alike.
1494
- */
1495
- var MirrorVideoDocumentAdapter = class {
1496
- doc;
1497
- mirror;
1498
- constructor(doc) {
1499
- this.doc = doc;
1500
- this.mirror = new Mirror({
1501
- doc,
1502
- schema: videoDocumentMirrorSchema,
1503
- validateUpdates: false
1504
- });
1505
- }
1506
- snapshot() {
1507
- return readVideoDocumentFromDraft(this.mirror.getState());
1508
- }
1509
- /**
1510
- * Release mirror subscriptions; do not reuse this adapter afterwards.
1511
- * The caller still owns the borrowed LoroDoc.
1512
- */
1513
- dispose() {
1514
- this.mirror.dispose();
1515
- }
1516
- /**
1517
- * Apply one op as a single transaction. `edit` mutates the immer draft; mirror
1518
- * diffs the result and commits once with the audit `message`. A throw in `edit`
1519
- * discards the draft (Loro untouched). When `edit` produces no change, mirror
1520
- * skips the commit — matching the prior "empty op leaves no audit" behavior.
1521
- */
1522
- transact(edit, audit) {
1523
- this.mirror.setState((draft) => {
1524
- edit(draft);
1525
- const result = validateSchema(videoDocumentMirrorSchema, {
1526
- timeline: draft.timeline,
1527
- tracks: draft.tracks,
1528
- part_library: draft.part_library
1529
- });
1530
- if (!result.valid) throw new Error(`Invalid content update: ${result.errors?.join("; ")}`);
1531
- }, {
1532
- origin: "mengine.semantic_editor",
1533
- message: JSON.stringify({
1534
- semantic_op: audit.kind,
1535
- payload: audit.payload,
1536
- intent: audit.intent ?? null,
1537
- actor: audit.actor ?? null
1538
- })
1539
- });
1540
- }
1541
- };
1542
- /** Build a fresh Loro doc seeded with `document` through the mirror. */
1543
- function createMirrorVideoDocument(document, options = {}) {
1544
- assertValidVideoDocument(document);
1545
- const doc = new LoroDoc();
1546
- try {
1547
- if (options.peerId != null) doc.setPeerId(options.peerId);
1548
- const mirror = new Mirror({
1549
- doc,
1550
- schema: videoDocumentMirrorSchema
1551
- });
1552
- try {
1553
- mirror.setState((draft) => {
1554
- seedDraft(draft, document);
1555
- }, { origin: options.origin ?? "mengine.bootstrap" });
1556
- return doc;
1557
- } finally {
1558
- mirror.dispose();
1559
- }
1560
- } catch (error) {
1561
- doc.free();
1562
- throw error;
1563
- }
1564
- }
1565
- /** Build a `MirrorVideoDocumentAdapter` over a fresh doc seeded with `document`. */
1566
- function createMirrorVideoDocumentAdapter(document, options) {
1567
- return new MirrorVideoDocumentAdapter(createMirrorVideoDocument(document, options));
1568
- }
1569
- /** Write a whole `VideoDocument` into the mirror draft (used to seed a fresh doc). */
1570
- function seedDraft(draft, document) {
1571
- draft.timeline = { unit_time_ms: document.timeline?.unit_time_ms ?? void 0 };
1572
- draft.tracks = (document.tracks ?? []).map(toTrackRow);
1573
- draft.part_library = {};
1574
- for (const [partId, part] of Object.entries(document.part_library ?? {})) draft.part_library[partId] = partUnionToDraft(part);
1575
- }
1576
- /** Map a domain `Track` to a draft track row (no lane/lane_order — see schema). */
1577
- function toTrackRow(track) {
1578
- return {
1579
- id: track.id ?? "",
1580
- parts_kind: track.parts_kind ?? void 0,
1581
- is_hidden: track.is_hidden ?? void 0,
1582
- items: (track.items ?? []).map((item) => ({
1583
- part_id: item.part_id,
1584
- time_position: item.time_position,
1585
- fallback_abs_ms: item.fallback_abs_ms
1586
- }))
1587
- };
1588
- }
1589
- //#endregion
1590
- export { partDurationMs as A, reassignSpeechesToVideoClipsByTime as C, syncAggregatedClipsTimePosition as D, resolveSpeechOverlapByShiftingVideos as E, recordEntries as F, videoDocumentMirrorSchema as I, base64ToBytes as L, DEFAULT_UNIT_TIME_MS as M, effectiveVideoClipDurationMs as N, TIMELINE_SKELETON_DURATION_MS as O, partUnionToDraft as P, bytesToBase64 as R, fillMainTrackTimeGaps as S, resolveAllSpeechOverlaps as T, findLaneTrack as _, buildInitialVideoDocument as a, cascadeAfterVideoClipChanges as b, fromVideoDocument as c, assertValidVideoDocument as d, validateVideoDocument as f, ensureLaneTrack as g, LANE_KINDS_IN_STACK_ORDER as h, readVideoDocumentFromDraft as i, safeDurationMs as j, isEmptyVideoClip as k, toVideoDocument as l, videoDocumentSchema as m, createMirrorVideoDocument as n, buildSpeechHostMap as o, partUnionSchema as p, createMirrorVideoDocumentAdapter as r, derivePositionFromAbs as s, MirrorVideoDocumentAdapter as t, VideoDocumentValidationError as u, laneTrackId as v, recalculateTimelineDuration as w, arrangeMainTrackSeamlessly as x, solveVideoDocument as y };