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