@mengine/medeo-client 1.0.0 → 1.0.1-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,23 +1,8 @@
1
- import { t as __exportAll } from "./chunk-D7D4PA-g.js";
2
- import { Mirror, schema } from "loro-mirror";
3
- import { z } from "zod";
4
- import { LoroDoc } from "loro-crdt";
1
+ import { A as isEmptyVideoClip, B as bytesToBase64, C as fillMainTrackTimeGaps, D as resolveSpeechOverlapByShiftingVideos, E as resolveAllSpeechOverlaps, F as speedOf, I as partUnionToDraft, L as recordEntries, M as safeDurationMs, N as VIDEO_DOCUMENT_SCHEMA_VERSION, O as syncAggregatedClipsTimePosition, P as effectiveVideoClipDurationMs, R as videoDocumentMirrorSchema, S as arrangeMainTrackSeamlessly, T as recalculateTimelineDuration, _ as videoDocumentSchema, a as createMirrorVideoDocument, b as solveVideoDocument, c as readVideoDocumentFromDraft, d as fromVideoDocument, f as toVideoDocument, g as partUnionSchema, h as validateVideoDocument, i as MirrorVideoDocumentAdapter, j as partDurationMs, k as TIMELINE_SKELETON_DURATION_MS, l as buildSpeechHostMap, m as assertValidVideoDocument, n as createPlainMemoryAdapter, o as createMirrorVideoDocumentAdapter, p as VideoDocumentValidationError, r as generatePartId, s as writeVideoDocumentToDraft, t as PlainMemoryAdapter, u as derivePositionFromAbs, v as ensureLaneTrack, w as reassignSpeechesToVideoClipsByTime, x as cascadeAfterVideoClipChanges, y as findLaneTrack, z as base64ToBytes } from "./document-DgffKwRw.js";
2
+ import { addSpeechesInputSchema, addVideoClipsInputSchema, adjustBgmVolumeInputSchema, adjustSpeechVolumeInputSchema, adjustVideoClipDurationInputSchema, adjustVideoClipVolumeInputSchema, changeSpeechScriptInputSchema, changeSpeechVoiceInputSchema, deleteBgmInputSchema, deleteSpeechesInputSchema, deleteVideoClipsInputSchema, moveSpeechesInputSchema, moveVideoClipsInputSchema, replaceVideoClipContentInputSchema, setBgmInputSchema, setCaptionStyleInputSchema, setCaptionVisibilityInputSchema, setVideoClipSpeedShiftInputSchema, t as schemas_exports } from "./schemas.js";
5
3
  import { ClientServerSynchronizer, DocManager } from "@mengine/sync";
6
4
  import { DisposableSet, EventBus, Task } from "@mengine/utils";
7
5
  import { BaseDocStorage, DummyConnection } from "@mengine/storage";
8
- //#region src/client/base64.ts
9
- function bytesToBase64(bytes) {
10
- let binary = "";
11
- for (const byte of bytes) binary += String.fromCharCode(byte);
12
- return btoa(binary);
13
- }
14
- function base64ToBytes(base64) {
15
- const binary = atob(base64);
16
- const bytes = new Uint8Array(binary.length);
17
- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
18
- return bytes;
19
- }
20
- //#endregion
21
6
  //#region src/client/http-client.ts
22
7
  /**
23
8
  * Public route prefix of the mengine doc-collaboration API. Must stay in lockstep
@@ -171,1886 +156,6 @@ function findSseFrameBoundary(buffer) {
171
156
  return Math.min(lf, crlf);
172
157
  }
173
158
  //#endregion
174
- //#region src/document/mirror-schema.ts
175
- /**
176
- * Declarative `loro-mirror` schema for `VideoDocument` — the canonical structural
177
- * SSOT and live storage wire (replaces the hand-rolled `@mengine/schema`
178
- * definition + adapter, see ADR 0008).
179
- *
180
- * Mirror gives an in-memory immutable state synced to the Loro doc by declarative
181
- * diff, so the storage layer no longer hand-writes per-region reconcile or a
182
- * transaction state machine. The shapes here store only authoritative facts
183
- * (RFC 02 §6): per-item absolute time, `part_aggregations`, and total duration
184
- * are projection-derived (cascade-solved at read time), so they are absent here.
185
- *
186
- * - tracks live in a single `tracks` `LoroMovableList` keyed by track id
187
- * (reference/17 §4). Lane is expressed by each track's `parts_kind`, not by
188
- * which container it lives in; order is the movable-list order itself. There is
189
- * no `lane` / `lane_order` field, so two peers inserting tracks never collide
190
- * on an order integer — list moves are conflict-free (RFC 03 §4). The legacy
191
- * keyed-map (`LoroMapRecord` + an integer `lane_order`) and the prior three
192
- * named containers are gone; the `main` / `above` / `below` three-pane view is
193
- * rebuilt by the projection from `parts_kind`.
194
- * - each track's `items` is a `LoroMovableList` keyed by `part_id`: a part is
195
- * placed at most once per lane, so `part_id` is the stable placement identity.
196
- * Reorder diffs to a real Loro `move`, preserving per-item CRDT identity on
197
- * every lane (main and secondary alike).
198
- * - `time_position` is the authoritative positioning fact (RFC 02 §4,
199
- * reference/17 §3), carried as an opaque JSON blob string (a whole tagged-union
200
- * value, last-writer-wins). The derived `fallback_abs_ms` snapshot sits beside
201
- * it as its own number field — a separate LWW unit so a projection refresh
202
- * never clobbers a `time_position` edit.
203
- * - meta lives in a `meta` LoroMap: the mirror root only accepts container
204
- * schemas, so meta scalars can't sit at the root as bare values. The domain
205
- * `VideoDocument` keeps the same `meta` wrapper, so the shapes are isomorphic
206
- * and the read/seed mapping is a near-identity.
207
- * - `part_library` values are nested `LoroMap`s: the value is a `LoroMap` with
208
- * four mutually-exclusive optional part sub-maps (`video_clip` / `speech` /
209
- * `caption` / `bgm`), each a `LoroMap` whose fields are stored as real Loro
210
- * sub-keys. This makes each field its own CRDT unit, so two peers editing
211
- * different fields of the same part (e.g. one volume, one play_out) merge
212
- * field-by-field instead of one whole-value overwrite. Field `required` mirrors
213
- * the Smithy `@required` contract (see `video_draft_comp.smithy`). `kind` is not
214
- * stored (the present sub-key names the kind); `duration_ms` is not stored (it
215
- * is derived, reference/17 §5). Nested values that the engine does not edit
216
- * field-by-field — `speed_shift` (a tagged union), `voice`, `caption_ids` — stay
217
- * as opaque JSON-blob sub-keys via `transform`. The four sub-keys are optional,
218
- * so the "exactly one part kind" union invariant is not enforced by the schema
219
- * type; it is rebuilt by `draftToPartUnion` on read and gated by zod on write.
220
- * - a caption's `style` is the one lazily-created optional child container, so
221
- * `captionPart` sets `mergeableMapChildContainers: true` — two peers can
222
- * concurrently first-create the same caption's `style` (one attribute each), and
223
- * only a mergeable child converges instead of last-writer-wins dropping one. All
224
- * other nested maps are keyed by a unique id (`part_library`) or created
225
- * atomically with their parent (`partValue`'s part sub-map), so they never hit
226
- * that concurrent-first-create fork and stay on plain `setContainer`. See the
227
- * note on `captionPart` below.
228
- * - `video_creation_settings` is an opaque JSON blob carried in a string via
229
- * `transform`: a whole value, last-writer-wins (no field-level concurrent edits).
230
- */
231
- /**
232
- * JSON-blob transform for an opaque, last-writer-wins value carried in a Loro
233
- * string. The field must be declared `required: false`: an absent field decodes
234
- * to `undefined` (mirror never calls `decode`/`encode` for null/undefined),
235
- * which is how we represent "no value" instead of encoding a `null` sentinel.
236
- */
237
- function jsonTransform() {
238
- return {
239
- decode: (value) => JSON.parse(value),
240
- encode: (value) => JSON.stringify(value),
241
- isEqual: "encoded-value-equality"
242
- };
243
- }
244
- const trackItem = schema.LoroMap({
245
- part_id: schema.String(),
246
- time_position: schema.String().transform(jsonTransform()),
247
- fallback_abs_ms: schema.Number({ required: false })
248
- });
249
- const track = schema.LoroMap({
250
- id: schema.String(),
251
- parts_kind: schema.String({ required: false }),
252
- is_hidden: schema.Boolean({ required: false }),
253
- items: schema.LoroMovableList(trackItem, (item) => item.part_id)
254
- });
255
- const videoClipPart = schema.LoroMap({
256
- id: schema.String(),
257
- play_in: schema.Number(),
258
- play_out: schema.Number(),
259
- volume: schema.Number(),
260
- origin_media_id: schema.String(),
261
- speed_shift: schema.String({ required: false }).transform(jsonTransform())
262
- }, { required: false });
263
- const speechPart = schema.LoroMap({
264
- id: schema.String(),
265
- media_duration_ms: schema.Number(),
266
- audio_script: schema.String(),
267
- volume: schema.Number(),
268
- audio_storage_key: schema.String(),
269
- origin_speech_id: schema.String(),
270
- voice: schema.String().transform(jsonTransform()),
271
- caption_ids: schema.String().transform(jsonTransform())
272
- }, { required: false });
273
- const captionStyle = schema.LoroMap({
274
- font_id: schema.String({ required: false }),
275
- font_size: schema.Number({ required: false }),
276
- font_color: schema.String({ required: false }),
277
- font_weight: schema.Number({ required: false }),
278
- entrance_animation: schema.String({ required: false }),
279
- entrance_animation_duration_ms: schema.Number({ required: false }),
280
- stroke_color: schema.String({ required: false }),
281
- stroke_width: schema.Number({ required: false }),
282
- position_x: schema.Number({ required: false }),
283
- position_y: schema.Number({ required: false })
284
- }, { required: false });
285
- const captionPart = schema.LoroMap({
286
- id: schema.String(),
287
- initial_duration_ms: schema.Number(),
288
- speech_part_id: schema.String(),
289
- text: schema.String(),
290
- start_ms: schema.Number(),
291
- style: captionStyle
292
- }, {
293
- required: false,
294
- mergeableMapChildContainers: true
295
- });
296
- const bgmPart = schema.LoroMap({
297
- id: schema.String(),
298
- audio_storage_key: schema.String(),
299
- volume: schema.Number(),
300
- origin_media_id: schema.String()
301
- }, { required: false });
302
- const partValue = schema.LoroMap({
303
- video_clip: videoClipPart,
304
- speech: speechPart,
305
- caption: captionPart,
306
- bgm: bgmPart
307
- });
308
- const videoDocumentMirrorSchema = schema({
309
- meta: schema.LoroMap({
310
- schema_version: schema.String({ required: false }),
311
- draft_id: schema.String({ required: false }),
312
- project_id: schema.String({ required: false }),
313
- owner_id: schema.String({ required: false }),
314
- thumbnail_storage_key: schema.String({ required: false }),
315
- chat_session_id: schema.String({ required: false }),
316
- video_creation_settings: schema.String({ required: false }).transform(jsonTransform()),
317
- version: schema.Number({ required: false })
318
- }),
319
- timeline: schema.LoroMap({ unit_time_ms: schema.Number({ required: false }) }),
320
- tracks: schema.LoroMovableList(track, (t) => t.id),
321
- part_library: schema.LoroMapRecord(partValue)
322
- });
323
- /** Project a discriminated `PartUnion` into the draft's four-optional shape. */
324
- function partUnionToDraft(part) {
325
- if (part.video_clip != null) return { video_clip: omitKind(part.video_clip) };
326
- if (part.speech != null) return { speech: omitKind(part.speech) };
327
- if (part.caption != null) return { caption: omitKind(part.caption) };
328
- return { bgm: omitKind(part.bgm) };
329
- }
330
- /**
331
- * Rebuild a discriminated `PartUnion` from a draft part value: pick the one
332
- * present sub-key, restore its `kind`, and drop the `$cid`. Returns `undefined`
333
- * when no part sub-key is present (an empty/placeholder value).
334
- */
335
- function draftToPartUnion(value) {
336
- if (value == null) return void 0;
337
- const v = value;
338
- if (v.video_clip != null) return { video_clip: withKind(v.video_clip, "video_clip") };
339
- if (v.speech != null) return { speech: withKind(v.speech, "speech") };
340
- if (v.caption != null) return { caption: withKind(v.caption, "caption") };
341
- if (v.bgm != null) return { bgm: withKind(v.bgm, "bgm") };
342
- }
343
- /** Drop `kind` (not stored) and `$cid` from a part payload for the draft. */
344
- function omitKind(part) {
345
- const { kind: _kind, $cid: _cid, ...rest } = part;
346
- return rest;
347
- }
348
- /** Restore `kind` (and drop `$cid`) on a part sub-map read from the draft. */
349
- function withKind(part, kind) {
350
- const { $cid: _cid, ...rest } = part;
351
- return {
352
- ...rest,
353
- kind
354
- };
355
- }
356
- /** Entries of a draft record (e.g. `tracks`) with `$cid` stripped. */
357
- function recordEntries(record) {
358
- if (record == null) return [];
359
- const out = [];
360
- for (const [key, value] of Object.entries(record)) {
361
- if (key === "$cid") continue;
362
- out.push([key, value]);
363
- }
364
- return out;
365
- }
366
- //#endregion
367
- //#region src/document/types.ts
368
- const VIDEO_DOCUMENT_SCHEMA_VERSION = "video-document/v0";
369
- /** The linear speed multiplier of a `speed_shift`, defaulting to 1 (original). */
370
- function speedOf(speedShift) {
371
- const speed = speedShift?.config?.linear?.speed;
372
- return typeof speed === "number" && Number.isFinite(speed) && speed > 0 ? speed : 1;
373
- }
374
- /**
375
- * A video clip's effective timeline duration, derived from authoritative facts
376
- * (RFC 02, `reference/16` §4, reference/17 §5): the trim window
377
- * `play_out - play_in` divided by the speed multiplier, rounded to integer ms.
378
- * `play_in` / `play_out` are optional in the IDL but every write path sets them
379
- * (defaulting to the whole media), and the legacy-ingest projection backfills the
380
- * window from a legacy `duration_ms` — so an authoritative clip always carries a
381
- * trim window and there is no stored `duration_ms` to fall back to. A clip with
382
- * neither bound yields 0. Speeds the clip up (>1× → shorter) or down (<1×).
383
- */
384
- function effectiveVideoClipDurationMs(clip) {
385
- const speed = speedOf(clip.speed_shift);
386
- const sourceMs = (clip.play_out ?? 0) - (clip.play_in ?? 0);
387
- const effective = Math.round(sourceMs / speed);
388
- return Number.isFinite(effective) && effective > 0 ? effective : 0;
389
- }
390
- //#endregion
391
- //#region src/timeline-core/types.ts
392
- /** Total document duration when there is no real content (matches FE bgm fallback). */
393
- const TIMELINE_SKELETON_DURATION_MS = 2e4;
394
- /** Empty placeholder clip marker: a video_clip part with no backing media. */
395
- function isEmptyVideoClip(part) {
396
- const clip = part?.video_clip;
397
- if (clip == null) return false;
398
- return clip.origin_media_id == null || clip.origin_media_id === "";
399
- }
400
- /** Clamp a duration to a non-negative integer (NaN/Infinity/negative → 0). */
401
- function safeDurationMs(value) {
402
- const n = Number(value);
403
- if (!Number.isFinite(n) || n <= 0) return 0;
404
- return Math.round(n);
405
- }
406
- function partDurationMs(doc, partId) {
407
- const part = doc.part_library[partId];
408
- if (part?.video_clip != null) return safeDurationMs(effectiveVideoClipDurationMs(part.video_clip));
409
- if (part?.bgm != null) return doc.timeline.duration_ms > 0 ? doc.timeline.duration_ms : TIMELINE_SKELETON_DURATION_MS;
410
- if (part?.speech != null) return safeDurationMs(part.speech.media_duration_ms);
411
- if (part?.caption != null) return safeDurationMs(part.caption.initial_duration_ms);
412
- return 0;
413
- }
414
- //#endregion
415
- //#region src/timeline-core/cascade.ts
416
- /**
417
- * Canonical timeline cascade primitives (ADR 0009).
418
- *
419
- * Single source of truth for "how an edit's connected regions move": main-track
420
- * seamless layout, aggregation position sync + reassignment, total-duration
421
- * recompute, speech-overlap resolution, gap filling. Reconciled per ADR 0009 §4:
422
- *
423
- * - product behavior follows the FE current implementation;
424
- * - all times are integer ms — positions/durations are rounded, never floated;
425
- * - function decomposition follows agent-harness (the Python-derived structure).
426
- *
427
- * Every function mutates the `TimelineDoc` in place (the editor runs them inside
428
- * one immer `transact`, so in-place edits diff correctly).
429
- */
430
- /**
431
- * Lay the main track out head-to-tail from 0, rewriting each item's
432
- * `abs_time_position`. Items whose part is missing from the library are dropped.
433
- */
434
- function arrangeMainTrackSeamlessly(doc) {
435
- const kept = [];
436
- let cursor = 0;
437
- for (const item of doc.main_track) {
438
- if (doc.part_library[item.part_id] == null) continue;
439
- item.abs_time_position = cursor;
440
- cursor += partDurationMs(doc, item.part_id);
441
- kept.push(item);
442
- }
443
- doc.main_track = kept;
444
- }
445
- /**
446
- * Sync attached parts' absolute positions from their host:
447
- * speech.abs = host_video.abs + relative_time_position
448
- * caption.abs = speech.abs + caption.start_ms
449
- */
450
- function syncAggregatedClipsTimePosition(doc) {
451
- const videoByPart = indexByPart(doc.main_track);
452
- const speechByPart = indexByPart(doc.speech_track);
453
- for (const aggregation of doc.aggregations) {
454
- const videoItem = videoByPart.get(aggregation.body_part_id);
455
- if (videoItem == null) continue;
456
- for (const attachment of aggregation.attachments) {
457
- const speechItem = speechByPart.get(attachment.part_id);
458
- if (speechItem == null) continue;
459
- speechItem.abs_time_position = videoItem.abs_time_position + attachment.relative_time_position;
460
- }
461
- }
462
- for (const captionItem of doc.caption_track) {
463
- const captionPart = doc.part_library[captionItem.part_id]?.caption;
464
- if (captionPart == null) continue;
465
- const speechItem = captionPart.speech_part_id == null ? void 0 : speechByPart.get(captionPart.speech_part_id);
466
- if (speechItem == null) continue;
467
- captionItem.abs_time_position = speechItem.abs_time_position + safeDurationMs(captionPart.start_ms);
468
- }
469
- }
470
- /**
471
- * Reassign each speech to the video clip whose time range contains its start,
472
- * rebuilding `aggregations`. A speech before the first clip or after the last
473
- * falls back to the first / last clip respectively (FE: see §4 note — FE falls
474
- * back to last only; we keep the harness two-sided fallback because a speech
475
- * dragged before clip 0 belonging to the last clip is clearly wrong, and the FE
476
- * single-sided rule is an acknowledged rough edge). `relative_time_position` is
477
- * clamped to a non-negative integer.
478
- */
479
- function reassignSpeechesToVideoClipsByTime(doc) {
480
- const ranges = doc.main_track.filter((item) => doc.part_library[item.part_id] != null).map((item) => ({
481
- part_id: item.part_id,
482
- start: item.abs_time_position,
483
- end: item.abs_time_position + partDurationMs(doc, item.part_id)
484
- }));
485
- if (ranges.length === 0) {
486
- doc.aggregations = [];
487
- return;
488
- }
489
- const rebuilt = /* @__PURE__ */ new Map();
490
- for (const speechItem of doc.speech_track) {
491
- const start = speechItem.abs_time_position;
492
- const targetRange = ranges.find((r) => r.start <= start && start < r.end) ?? (start < ranges[0].start ? ranges[0] : ranges[ranges.length - 1]);
493
- const relative = Math.max(0, Math.round(start - targetRange.start));
494
- const targetId = targetRange.part_id;
495
- let aggregation = rebuilt.get(targetId);
496
- if (aggregation == null) {
497
- aggregation = {
498
- body_part_id: targetId,
499
- attachments: []
500
- };
501
- rebuilt.set(targetId, aggregation);
502
- }
503
- aggregation.attachments.push({
504
- part_id: speechItem.part_id,
505
- relative_time_position: relative
506
- });
507
- }
508
- doc.aggregations = ranges.map((r) => rebuilt.get(r.part_id)).filter((a) => a != null);
509
- }
510
- /**
511
- * Recompute `timeline.duration_ms` as the max end (abs + duration) across main,
512
- * speech, and caption lanes (BGM does not extend the timeline).
513
- *
514
- * BGM has no authoritative duration (RFC 02 / `reference/16` §0b): its effective
515
- * length is always the timeline total, so it is not written back here — the
516
- * projection derives it from `timeline.duration_ms` on read (`partDurationMs`
517
- * returns the timeline total for a bgm part). The empty-document 20s skeleton is
518
- * applied at that read step, not stored.
519
- */
520
- function recalculateTimelineDuration(doc) {
521
- const max = Math.max(laneEndMs(doc, doc.main_track), laneEndMs(doc, doc.speech_track), laneEndMs(doc, doc.caption_track));
522
- doc.timeline.duration_ms = max;
523
- }
524
- /**
525
- * Resolve one speech overlap by shifting the overlapping speech's host video
526
- * (and every clip after it) right. Returns true when one overlap was resolved;
527
- * callers loop until it returns false. The compared range is the speech merged
528
- * with its captions: start = min(speech.start, captions.start) (FE behavior),
529
- * end = max(speech.end, captions.end).
530
- */
531
- function resolveSpeechOverlapByShiftingVideos(doc) {
532
- const speeches = doc.speech_track;
533
- for (let i = 1; i < speeches.length; i++) {
534
- const prev = speechWithCaptionsRange(doc, speeches[i - 1]);
535
- const curr = speechWithCaptionsRange(doc, speeches[i]);
536
- if (prev == null || curr == null) continue;
537
- if (curr.start >= prev.end) continue;
538
- const overlapMs = Math.round(prev.end - curr.start);
539
- const hostId = hostVideoOf(doc, speeches[i].part_id);
540
- if (hostId == null) continue;
541
- const fromIndex = doc.main_track.findIndex((item) => item.part_id === hostId);
542
- if (fromIndex < 0) continue;
543
- for (let idx = fromIndex; idx < doc.main_track.length; idx++) doc.main_track[idx].abs_time_position += overlapMs;
544
- syncAggregatedClipsTimePosition(doc);
545
- return true;
546
- }
547
- return false;
548
- }
549
- /**
550
- * Resolve speech overlaps for one cascade pass. Mirrors the authoritative FE
551
- * `ensureNoOverlappingClips`, which is documented to resolve AT MOST ONE overlap
552
- * per cascade and is invoked exactly once at every FE call site — the supported
553
- * ops each produce at most one new overlap. It is NOT a fixpoint loop: shifting a
554
- * host right also moves every speech anchored to it, so two speeches sharing a
555
- * host can never be separated by shifting. Looping to a "fixed point" there does
556
- * not converge — it accumulates the same overlap every iteration and pushes the
557
- * clip arbitrarily far right (e.g. a sped-up clip landing at ~287k ms instead of
558
- * its seamless slot). A single pass matches FE product behavior and terminates.
559
- */
560
- function resolveAllSpeechOverlaps(doc) {
561
- resolveSpeechOverlapByShiftingVideos(doc);
562
- }
563
- /**
564
- * Make the main track gapless by adjusting/merging empty placeholder clips or
565
- * inserting new ones between real clips. Mirrors the harness four-case rule, but
566
- * the merge of two adjacent empty clips keeps the earlier clip (harness Case 4).
567
- * Requires `makeEmptyPart` to mint a placeholder part (the editor supplies an
568
- * id generator).
569
- */
570
- function fillMainTrackTimeGaps(doc, makeEmptyPart) {
571
- const items = doc.main_track;
572
- let i = 0;
573
- while (i < items.length) {
574
- const current = items[i];
575
- const currentPart = doc.part_library[current.part_id];
576
- if (currentPart == null) {
577
- i += 1;
578
- continue;
579
- }
580
- const currentEnd = current.abs_time_position + partDurationMs(doc, current.part_id);
581
- if (i + 1 >= items.length) break;
582
- const next = items[i + 1];
583
- const nextPart = doc.part_library[next.part_id];
584
- if (nextPart == null) {
585
- i += 1;
586
- continue;
587
- }
588
- const gap = next.abs_time_position - currentEnd;
589
- if (gap > 0) {
590
- if (isEmptyVideoClip(currentPart)) {
591
- extendEmptyClip(currentPart.video_clip, gap);
592
- continue;
593
- }
594
- if (isEmptyVideoClip(nextPart)) {
595
- next.abs_time_position -= gap;
596
- extendEmptyClip(nextPart.video_clip, gap);
597
- i += 1;
598
- continue;
599
- }
600
- const { partId } = makeEmptyPart(gap);
601
- doc.part_library[partId] = { video_clip: {
602
- id: partId,
603
- kind: "video_clip",
604
- play_in: 0,
605
- play_out: gap,
606
- volume: 0,
607
- origin_media_id: ""
608
- } };
609
- items.splice(i + 1, 0, {
610
- part_id: partId,
611
- time_position: { mode: "sequential" },
612
- abs_time_position: currentEnd
613
- });
614
- i += 1;
615
- continue;
616
- }
617
- if (gap === 0 && isEmptyVideoClip(currentPart) && isEmptyVideoClip(nextPart)) {
618
- extendEmptyClip(currentPart.video_clip, partDurationMs(doc, next.part_id));
619
- items.splice(i + 1, 1);
620
- delete doc.part_library[next.part_id];
621
- continue;
622
- }
623
- i += 1;
624
- }
625
- }
626
- function indexByPart(items) {
627
- const map = /* @__PURE__ */ new Map();
628
- for (const item of items) map.set(item.part_id, item);
629
- return map;
630
- }
631
- function laneEndMs(doc, items) {
632
- let max = 0;
633
- for (const item of items) {
634
- if (doc.part_library[item.part_id] == null) continue;
635
- const end = item.abs_time_position + partDurationMs(doc, item.part_id);
636
- if (end > max) max = end;
637
- }
638
- return max;
639
- }
640
- function extendEmptyClip(clip, byMs) {
641
- clip.play_out = safeDurationMs(clip.play_out) + byMs;
642
- }
643
- /** speech merged with its captions: start = min, end = max. */
644
- function speechWithCaptionsRange(doc, speechItem) {
645
- const speech = doc.part_library[speechItem.part_id]?.speech;
646
- if (speech == null) return null;
647
- let start = speechItem.abs_time_position;
648
- let end = speechItem.abs_time_position + safeDurationMs(speech.media_duration_ms);
649
- for (const captionId of captionIdsOf(speech)) {
650
- const captionItem = doc.caption_track.find((item) => item.part_id === captionId);
651
- const captionPart = doc.part_library[captionId]?.caption;
652
- if (captionItem == null || captionPart == null) continue;
653
- const cStart = captionItem.abs_time_position;
654
- const cEnd = captionItem.abs_time_position + safeDurationMs(captionPart.initial_duration_ms);
655
- if (cStart < start) start = cStart;
656
- if (cEnd > end) end = cEnd;
657
- }
658
- return {
659
- start,
660
- end
661
- };
662
- }
663
- function captionIdsOf(speech) {
664
- return (speech.caption_ids ?? []).filter((id) => id != null);
665
- }
666
- function hostVideoOf(doc, speechPartId) {
667
- for (const aggregation of doc.aggregations) if (aggregation.attachments.some((att) => att.part_id === speechPartId)) return aggregation.body_part_id;
668
- return null;
669
- }
670
- //#endregion
671
- //#region src/timeline-core/entrypoints.ts
672
- /**
673
- * The full solve pipeline: arrange → sync → reassign → resolve-overlap →
674
- * fill-gaps → recalc. The single cascade the read-side projection runs; ops
675
- * never call it (they write only facts — RFC 02 §7/§10).
676
- */
677
- function cascadeAfterVideoClipChanges(doc, makeEmptyPart) {
678
- arrangeMainTrackSeamlessly(doc);
679
- syncAggregatedClipsTimePosition(doc);
680
- reassignSpeechesToVideoClipsByTime(doc);
681
- resolveAllSpeechOverlaps(doc);
682
- fillMainTrackTimeGaps(doc, makeEmptyPart);
683
- recalculateTimelineDuration(doc);
684
- }
685
- //#endregion
686
- //#region src/timeline-core/bridge.ts
687
- /**
688
- * Solve a `VideoDocument` (authoritative, position-only) into its derived
689
- * read-view: absolute time per item, `part_aggregations`, and total duration.
690
- * This is the read side of the single-directional flow — never written back.
691
- */
692
- function solveVideoDocument(document) {
693
- const doc = videoDocumentToTimelineDoc(document);
694
- let counter = 0;
695
- cascadeAfterVideoClipChanges(doc, () => ({ partId: `empty_${counter++}` }));
696
- const absByPartId = /* @__PURE__ */ new Map();
697
- for (const item of doc.main_track) absByPartId.set(item.part_id, item.abs_time_position);
698
- for (const item of doc.speech_track) absByPartId.set(item.part_id, item.abs_time_position);
699
- for (const item of doc.caption_track) absByPartId.set(item.part_id, item.abs_time_position);
700
- for (const item of doc.bgm_track) absByPartId.set(item.part_id, item.abs_time_position);
701
- return {
702
- absByPartId,
703
- aggregations: doc.aggregations.map((aggregation) => ({
704
- body_part_id: aggregation.body_part_id,
705
- attachments: aggregation.attachments.map((a) => ({
706
- part_id: a.part_id,
707
- relative_time_position: a.relative_time_position
708
- }))
709
- })),
710
- durationMs: doc.timeline.duration_ms,
711
- partLibrary: doc.part_library
712
- };
713
- }
714
- function videoDocumentToTimelineDoc(document) {
715
- const partLibrary = {};
716
- for (const [partId, part] of Object.entries(document.part_library ?? {})) partLibrary[partId] = part;
717
- const laneItems = (track) => (track?.items ?? []).map((item) => ({
718
- part_id: item.part_id,
719
- time_position: item.time_position,
720
- abs_time_position: seedAbs(item.time_position, item.fallback_abs_ms),
721
- fallback_abs_ms: item.fallback_abs_ms
722
- }));
723
- const tracks = document.tracks ?? [];
724
- let mainItems = [];
725
- let speechItems = [];
726
- let bgmItems = [];
727
- let captionItems = [];
728
- for (const t of tracks) switch (t.parts_kind) {
729
- case "video_clip":
730
- mainItems = mainItems.concat(laneItems(t));
731
- break;
732
- case "speech":
733
- speechItems = speechItems.concat(laneItems(t));
734
- break;
735
- case "bgm":
736
- bgmItems = bgmItems.concat(laneItems(t));
737
- break;
738
- case "caption":
739
- captionItems = captionItems.concat(laneItems(t));
740
- break;
741
- }
742
- return {
743
- main_track: mainItems,
744
- speech_track: speechItems,
745
- caption_track: captionItems,
746
- bgm_track: bgmItems,
747
- part_library: partLibrary,
748
- aggregations: seedAggregations(mainItems, speechItems),
749
- timeline: {
750
- duration_ms: 0,
751
- unit_time_ms: document.timeline?.unit_time_ms ?? 0
752
- }
753
- };
754
- }
755
- /**
756
- * Seed an item's solve-variable `abs_time_position` from its `time_position` (and
757
- * the `fallback_abs_ms` snapshot carried beside it): `absolute` → `offsetMs`;
758
- * `anchored` → `fallbackAbsMs` (last solved position, also the orphan-recovery
759
- * anchor when the host is gone); `sequential` → 0 (the cascade lays the main
760
- * track out head-to-tail). The cascade then resolves anchored items against their
761
- * host, so this seed only needs to put each item somewhere plausible for the
762
- * first reassign/overlap pass.
763
- */
764
- function seedAbs(position, fallbackAbsMs) {
765
- switch (position.mode) {
766
- case "absolute": return Math.round(position.offsetMs);
767
- case "anchored": return Math.round(fallbackAbsMs ?? 0);
768
- case "sequential": return 0;
769
- }
770
- }
771
- /**
772
- * Build the cascade `aggregations` parent-map from anchored items: an anchored
773
- * item's `anchorPartId` is the host's `part_id` (= `body_part_id`), `offsetMs`
774
- * is `relative_time_position`. Only main-track (video) hosts form aggregations;
775
- * caption→speech relations are recomputed by the cascade from `caption.start_ms`.
776
- */
777
- function seedAggregations(mainItems, speechItems) {
778
- const mainPartIds = new Set(mainItems.map((item) => item.part_id));
779
- const byHost = /* @__PURE__ */ new Map();
780
- const order = [];
781
- for (const speech of speechItems) {
782
- if (speech.time_position.mode !== "anchored") continue;
783
- const host = speech.time_position.anchorPartId;
784
- if (!mainPartIds.has(host)) continue;
785
- let aggregation = byHost.get(host);
786
- if (aggregation == null) {
787
- aggregation = {
788
- body_part_id: host,
789
- attachments: []
790
- };
791
- byHost.set(host, aggregation);
792
- order.push(host);
793
- }
794
- aggregation.attachments.push({
795
- part_id: speech.part_id,
796
- relative_time_position: speech.time_position.offsetMs
797
- });
798
- }
799
- return order.map((host) => byHost.get(host));
800
- }
801
- /**
802
- * Lane-stacking rank for the single `tracks` list (reference/17 §4): caption
803
- * (above) sits before the video_clip main track, which sits before speech / bgm
804
- * (below). The `tracks` array is kept in this top-to-bottom order so a freshly
805
- * minted track lands in the right place and the projection's three-pane rebuild
806
- * stays deterministic.
807
- */
808
- function laneRank(kind) {
809
- switch (kind) {
810
- case "caption": return 0;
811
- case "video_clip": return 1;
812
- case "speech":
813
- case "bgm": return 2;
814
- default: return 3;
815
- }
816
- }
817
- /**
818
- * Insert a freshly-minted track into `tracks` at the position that keeps the
819
- * lane-stacking order (caption → main → speech/bgm). Inserts before the first
820
- * track whose rank is strictly greater, so same-rank tracks keep insertion order.
821
- */
822
- function insertTrackByLaneOrder(tracks, track) {
823
- const rank = laneRank(track.parts_kind);
824
- const at = tracks.findIndex((t) => laneRank(t?.parts_kind) > rank);
825
- if (at < 0) tracks.push(track);
826
- else tracks.splice(at, 0, track);
827
- }
828
- /**
829
- * Locate a lane's track row in the single `tracks` list by kind, minting an empty
830
- * row in lane-stacking order if absent (reference/17 §4: lane = `parts_kind`).
831
- * Ops use this to write authoritative items onto the right lane. The track id
832
- * mirrors the seed convention (`<kind>_track`).
833
- */
834
- function ensureLaneTrack(draft, kind) {
835
- draft.tracks ??= [];
836
- let track = draft.tracks.find((t) => t?.parts_kind === kind);
837
- if (track == null) {
838
- track = {
839
- id: kind === "video_clip" ? "main_track" : `${kind}_track`,
840
- parts_kind: kind,
841
- is_hidden: void 0,
842
- items: []
843
- };
844
- insertTrackByLaneOrder(draft.tracks, track);
845
- }
846
- track.items ??= [];
847
- return track;
848
- }
849
- /** Find a secondary lane's track row without minting it. */
850
- function findLaneTrack(draft, kind) {
851
- return (draft.tracks ?? []).find((t) => t?.parts_kind === kind);
852
- }
853
- //#endregion
854
- //#region src/document/zod-schema.ts
855
- const partKindSchema = z.enum([
856
- "video_clip",
857
- "speech",
858
- "caption",
859
- "bgm"
860
- ]);
861
- const finiteNumber = z.number().finite();
862
- const trackItemTimePositionSchema = z.discriminatedUnion("mode", [
863
- z.object({ mode: z.literal("sequential") }).passthrough(),
864
- z.object({
865
- mode: z.literal("anchored"),
866
- anchorPartId: z.string(),
867
- offsetMs: finiteNumber
868
- }).passthrough(),
869
- z.object({
870
- mode: z.literal("absolute"),
871
- offsetMs: finiteNumber
872
- }).passthrough()
873
- ]);
874
- const trackItemSchema = z.object({
875
- part_id: z.string(),
876
- time_position: trackItemTimePositionSchema,
877
- fallback_abs_ms: finiteNumber.optional()
878
- }).passthrough();
879
- const trackSchema = z.object({
880
- id: z.string().optional(),
881
- parts_kind: partKindSchema.optional(),
882
- is_hidden: z.boolean().optional(),
883
- items: z.array(trackItemSchema).optional()
884
- }).passthrough();
885
- const speedShiftSchema$1 = z.object({
886
- category: z.string().optional(),
887
- mode: z.string().optional(),
888
- config: z.object({ linear: z.object({ speed: finiteNumber.optional() }).passthrough().optional() }).passthrough().optional()
889
- }).passthrough();
890
- const videoClipPartSchema = z.object({
891
- id: z.string().optional(),
892
- kind: z.literal("video_clip"),
893
- duration_ms: finiteNumber.optional(),
894
- play_in: finiteNumber,
895
- play_out: finiteNumber,
896
- volume: finiteNumber,
897
- origin_media_id: z.string(),
898
- speed_shift: speedShiftSchema$1.optional()
899
- }).passthrough();
900
- const speechPartSchema = z.object({
901
- id: z.string().optional(),
902
- kind: z.literal("speech"),
903
- media_duration_ms: finiteNumber,
904
- duration_ms: finiteNumber.optional(),
905
- audio_script: z.string(),
906
- volume: finiteNumber,
907
- audio_storage_key: z.string(),
908
- origin_speech_id: z.string(),
909
- voice: z.unknown(),
910
- caption_ids: z.array(z.string())
911
- }).passthrough();
912
- const captionPartSchema = z.object({
913
- id: z.string().optional(),
914
- kind: z.literal("caption"),
915
- initial_duration_ms: finiteNumber,
916
- speech_part_id: z.string(),
917
- text: z.string(),
918
- start_ms: finiteNumber,
919
- style: z.object({
920
- font_id: z.string().optional(),
921
- font_size: finiteNumber.optional(),
922
- font_color: z.string().optional(),
923
- font_weight: finiteNumber.optional(),
924
- entrance_animation: z.string().optional(),
925
- entrance_animation_duration_ms: finiteNumber.optional(),
926
- stroke_color: z.string().optional(),
927
- stroke_width: finiteNumber.optional(),
928
- position_x: finiteNumber.optional(),
929
- position_y: finiteNumber.optional()
930
- }).passthrough().optional()
931
- }).passthrough();
932
- const bgmPartSchema = z.object({
933
- id: z.string().optional(),
934
- kind: z.literal("bgm"),
935
- audio_storage_key: z.string(),
936
- volume: finiteNumber,
937
- origin_media_id: z.string()
938
- }).passthrough();
939
- const partUnionSchema = z.union([
940
- z.object({ video_clip: videoClipPartSchema }).passthrough(),
941
- z.object({ speech: speechPartSchema }).passthrough(),
942
- z.object({ caption: captionPartSchema }).passthrough(),
943
- z.object({ bgm: bgmPartSchema }).passthrough()
944
- ]).refine((part) => {
945
- const p = part;
946
- return [
947
- "video_clip",
948
- "speech",
949
- "caption",
950
- "bgm"
951
- ].filter((k) => p[k] != null).length === 1;
952
- }, { message: "A part_library value must have exactly one of video_clip / speech / caption / bgm" });
953
- const videoDocumentMetaSchema = z.object({
954
- schema_version: z.literal(VIDEO_DOCUMENT_SCHEMA_VERSION),
955
- draft_id: z.string().optional(),
956
- project_id: z.string().optional(),
957
- owner_id: z.string().optional(),
958
- thumbnail_storage_key: z.string().optional(),
959
- chat_session_id: z.string().optional(),
960
- video_creation_settings: z.unknown().optional(),
961
- version: finiteNumber.optional()
962
- }).passthrough();
963
- const videoDocumentSchema = z.object({
964
- meta: videoDocumentMetaSchema,
965
- timeline: z.object({ unit_time_ms: finiteNumber.optional() }).passthrough().optional(),
966
- tracks: z.array(trackSchema).optional(),
967
- part_library: z.record(z.string(), partUnionSchema).optional()
968
- }).passthrough().refine((doc) => (doc.tracks ?? []).filter((t) => t.parts_kind === "video_clip").length <= 1, {
969
- message: "A VideoDocument may have at most one video_clip (main) track",
970
- path: ["tracks"]
971
- });
972
- //#endregion
973
- //#region src/document/validation.ts
974
- /**
975
- * Business-level schema guard for `VideoDocument` (RFC 03 §9). It is the gate
976
- * that decides whether an arbitrary value is a *legal* `VideoDocument` before it
977
- * is written into Loro — distinct from two neighbours:
978
- *
979
- * - `zod-schema.ts` (`videoDocumentSchema`) checks structure/shape only; this
980
- * file layers the business rules on top (part-kind match, reference integrity,
981
- * `position.anchorPartId` targets, value ranges, identity uniqueness).
982
- * - loro-mirror's own `validateSchema` (run on every `setState`) only checks the
983
- * storage structure, never these business invariants.
984
- *
985
- * Projection (`projection.ts`) calls `assertValidVideoDocument` before solving a
986
- * document into the legacy `VideoDraft`.
987
- */
988
- var VideoDocumentValidationError = class extends Error {
989
- issues;
990
- constructor(issues) {
991
- super(`Invalid VideoDocument: ${issues.map((issue) => issue.message).join("; ")}`);
992
- this.issues = issues;
993
- this.name = "VideoDocumentValidationError";
994
- }
995
- };
996
- /**
997
- * Assert the document is legal enough to project. Only `error`-severity issues
998
- * hard-reject; `recoverable` ones (dangling anchor / orphan, RFC 02 §11.1) are
999
- * left for the projection to heal on read and do NOT throw. Use
1000
- * `validateVideoDocument` directly to inspect recoverable issues too.
1001
- */
1002
- function assertValidVideoDocument(document) {
1003
- const blocking = validateVideoDocument(document).filter((issue) => (issue.severity ?? "error") === "error");
1004
- if (blocking.length > 0) throw new VideoDocumentValidationError(blocking);
1005
- }
1006
- function validateVideoDocument(document) {
1007
- const parsed = videoDocumentSchema.safeParse(document);
1008
- if (!parsed.success) return parsed.error.issues.map((issue) => ({
1009
- code: "invalid_schema",
1010
- path: zodPath(issue.path),
1011
- message: issue.message
1012
- }));
1013
- const doc = parsed.data;
1014
- const issues = [];
1015
- const partLibrary = doc.part_library ?? {};
1016
- for (const [partId, part] of Object.entries(partLibrary)) {
1017
- if (!partUnionSchema.safeParse(part).success) {
1018
- issues.push({
1019
- code: "unknown_part_kind",
1020
- path: `/part_library/${partId}`,
1021
- message: `Part "${partId}" is not a supported part union`
1022
- });
1023
- continue;
1024
- }
1025
- const wrapperKind = getPartUnionKind(part);
1026
- const innerKind = getPartKind(part);
1027
- if (wrapperKind != null && innerKind != null && wrapperKind !== innerKind) issues.push({
1028
- code: "part_kind_mismatch",
1029
- path: `/part_library/${partId}`,
1030
- message: `Part "${partId}" wrapper kind "${wrapperKind}" does not match inner kind "${innerKind}"`
1031
- });
1032
- validatePartValues(partId, part, issues);
1033
- }
1034
- for (const [idx, track] of (doc.tracks ?? []).entries()) validateTrack(track, `tracks/${idx}`, partLibrary, issues, track.parts_kind === "video_clip");
1035
- validateSpeechCaptionReferences(partLibrary, issues);
1036
- validatePositionReferences(doc, partLibrary, issues);
1037
- return issues;
1038
- }
1039
- /**
1040
- * An `anchored` item whose `anchorPartId` no longer exists in the library is the
1041
- * orphan condition (RFC 02 §4/§11.1) — e.g. a speech whose host video, or a
1042
- * caption whose host speech, was concurrently deleted while this item was being
1043
- * reparented in. This is flagged as a **recoverable** issue, NOT a hard error:
1044
- * the projection heals it on read (the item's `fallback_abs_ms` snapshot seeds
1045
- * its absolute position, then the cascade reassigns it to the nearest available
1046
- * host, or it stays put as an absolute item). Reporting it here keeps the orphan
1047
- * observable without blocking projection — the opposite of a hard reject, which
1048
- * would make an inevitable concurrent-delete outcome un-projectable (§11.1).
1049
- */
1050
- function validatePositionReferences(doc, partLibrary, issues) {
1051
- const tracks = (doc.tracks ?? []).map((track, idx) => ({
1052
- track,
1053
- path: `tracks/${idx}`
1054
- }));
1055
- for (const { track, path } of tracks) for (const [idx, item] of (track?.items ?? []).entries()) {
1056
- if (item.time_position.mode !== "anchored") continue;
1057
- if (partLibrary[item.time_position.anchorPartId] == null) issues.push({
1058
- code: "invalid_position_anchor",
1059
- path: `/${path}/items/${idx}/time_position/anchorPartId`,
1060
- message: `Track item "${path}/${idx}" anchors to missing part "${item.time_position.anchorPartId}"`,
1061
- severity: "recoverable"
1062
- });
1063
- }
1064
- }
1065
- function validatePartValues(partId, part, issues) {
1066
- const payload = part.video_clip ?? part.speech ?? part.caption ?? part.bgm ?? void 0;
1067
- if (payload == null) return;
1068
- if ("duration_ms" in payload && payload.duration_ms != null && payload.duration_ms < 0) issues.push({
1069
- code: "invalid_part_value",
1070
- path: `/part_library/${partId}/duration_ms`,
1071
- message: `Part "${partId}" has negative duration_ms`
1072
- });
1073
- if ("volume" in payload && payload.volume != null && !Number.isFinite(payload.volume)) issues.push({
1074
- code: "invalid_part_value",
1075
- path: `/part_library/${partId}/volume`,
1076
- message: `Part "${partId}" has non-finite volume`
1077
- });
1078
- if (part.video_clip != null) {
1079
- const { play_in, play_out } = part.video_clip;
1080
- if (play_in != null && play_in < 0) issues.push({
1081
- code: "invalid_part_value",
1082
- path: `/part_library/${partId}/play_in`,
1083
- message: `Video clip "${partId}" has negative play_in`
1084
- });
1085
- if (play_out != null && play_in != null && play_out < play_in) issues.push({
1086
- code: "invalid_part_value",
1087
- path: `/part_library/${partId}/play_out`,
1088
- message: `Video clip "${partId}" has play_out before play_in`
1089
- });
1090
- }
1091
- }
1092
- function validateTrack(track, path, partLibrary, issues, isMainTrack) {
1093
- if (track == null) return;
1094
- const seenPartIds = /* @__PURE__ */ new Set();
1095
- for (const [idx, item] of (track.items ?? []).entries()) {
1096
- const partId = item.part_id;
1097
- if (partId != null && partId !== "") if (seenPartIds.has(partId)) issues.push({
1098
- code: "duplicate_track_item_identity",
1099
- path: `/${path}/items/${idx}/part_id`,
1100
- message: `Track item "${path}/${idx}" reuses part_id "${partId}"`
1101
- });
1102
- else seenPartIds.add(partId);
1103
- if (partId == null || partId === "") {
1104
- issues.push({
1105
- code: "missing_part_reference",
1106
- path: `/${path}/items/${idx}/part_id`,
1107
- message: `Track item "${path}/${idx}" has no part_id`
1108
- });
1109
- continue;
1110
- }
1111
- const part = partLibrary[partId];
1112
- if (part == null) {
1113
- issues.push({
1114
- code: "missing_part_reference",
1115
- path: `/${path}/items/${idx}/part_id`,
1116
- message: `Track item "${path}/${idx}" references missing part "${partId}"`
1117
- });
1118
- continue;
1119
- }
1120
- const partKind = getPartKind(part);
1121
- if (isMainTrack && partKind !== "video_clip") issues.push({
1122
- code: "main_track_non_video_clip",
1123
- path: `/${path}/items/${idx}/part_id`,
1124
- message: `Main track item "${path}/${idx}" references non-video part "${partId}"`
1125
- });
1126
- if (track.parts_kind != null && partKind != null && track.parts_kind !== partKind) issues.push({
1127
- code: "track_kind_mismatch",
1128
- path: `/${path}/items/${idx}/part_id`,
1129
- message: `Track "${path}" expects "${track.parts_kind}" but part "${partId}" is "${partKind}"`
1130
- });
1131
- }
1132
- }
1133
- /**
1134
- * Check speech↔caption references. A reference to a *missing* part (speech's
1135
- * caption_ids → deleted caption, or caption's speech_part_id → deleted speech)
1136
- * is the orphan condition (RFC 02 §11.1): reported as **recoverable** so the
1137
- * projection can heal it on read, not block. A *back-pointer mismatch* (caption
1138
- * exists but does not point back) is data corruption, kept as a hard error.
1139
- */
1140
- function validateSpeechCaptionReferences(partLibrary, issues) {
1141
- for (const [partId, part] of Object.entries(partLibrary)) {
1142
- if (part.speech != null) for (const captionId of part.speech.caption_ids ?? []) {
1143
- const caption = partLibrary[captionId]?.caption;
1144
- if (caption == null) {
1145
- issues.push({
1146
- code: "invalid_speech_caption_reference",
1147
- path: `/part_library/${partId}/speech/caption_ids`,
1148
- message: `Speech "${partId}" references missing caption "${captionId}"`,
1149
- severity: "recoverable"
1150
- });
1151
- continue;
1152
- }
1153
- if (caption.speech_part_id !== partId) issues.push({
1154
- code: "invalid_speech_caption_reference",
1155
- path: `/part_library/${captionId}/caption/speech_part_id`,
1156
- message: `Caption "${captionId}" does not point back to speech "${partId}"`
1157
- });
1158
- }
1159
- if (part.caption != null) {
1160
- const speechId = part.caption.speech_part_id;
1161
- if (speechId != null && partLibrary[speechId]?.speech == null) issues.push({
1162
- code: "invalid_speech_caption_reference",
1163
- path: `/part_library/${partId}/caption/speech_part_id`,
1164
- message: `Caption "${partId}" references missing speech "${speechId}"`,
1165
- severity: "recoverable"
1166
- });
1167
- }
1168
- }
1169
- }
1170
- function getPartUnionKind(part) {
1171
- if (part.video_clip != null) return "video_clip";
1172
- if (part.speech != null) return "speech";
1173
- if (part.caption != null) return "caption";
1174
- if (part.bgm != null) return "bgm";
1175
- }
1176
- function getPartKind(part) {
1177
- return part.video_clip?.kind ?? part.speech?.kind ?? part.caption?.kind ?? part.bgm?.kind;
1178
- }
1179
- function zodPath(path) {
1180
- if (path.length === 0) return "/";
1181
- return `/${path.map(String).join("/")}`;
1182
- }
1183
- //#endregion
1184
- //#region src/document/projection.ts
1185
- /**
1186
- * Projection between the authoritative `VideoDocument` and the legacy
1187
- * `VideoDraft` read-view (RFC 02 §5/§7). Both directions live here:
1188
- *
1189
- * - `toVideoDocument` ingests a `VideoDraft`, deriving each item's `position`
1190
- * from the legacy absolute layout + aggregations; derived values (abs time,
1191
- * `part_aggregations`, total duration) are dropped.
1192
- * - `fromVideoDocument` solves a `VideoDocument` back into a `VideoDraft` via the
1193
- * timeline-core cascade, re-deriving exactly those values.
1194
- *
1195
- * Business validation lives in `validation.ts`; `fromVideoDocument` asserts a
1196
- * valid document before solving.
1197
- */
1198
- /**
1199
- * Ingest the legacy `VideoDraft` into the authoritative `VideoDocument`,
1200
- * deriving each item's `time_position` from the legacy absolute layout +
1201
- * aggregations (RFC 02 §4/§5). Absolute time, `part_aggregations`, and total
1202
- * duration are dropped — they are re-derived by the projection.
1203
- */
1204
- function toVideoDocument(draft) {
1205
- const speechHost = buildSpeechHostMap(draft.part_aggregations);
1206
- const partLibrary = draft.part_library ?? {};
1207
- const toTrack = (track, isMain) => {
1208
- if (track == null) return void 0;
1209
- return {
1210
- id: track.id,
1211
- parts_kind: track.parts_kind,
1212
- is_hidden: track.is_hidden,
1213
- items: (track.items ?? []).map((item) => deriveItem(item, isMain, speechHost, partLibrary))
1214
- };
1215
- };
1216
- const mainTrack = toTrack(draft.main_track, true);
1217
- const tracks = [
1218
- ...(draft.above_main_tracks ?? []).map((t) => toTrack(t, false)),
1219
- ...mainTrack == null ? [] : [mainTrack],
1220
- ...(draft.below_main_tracks ?? []).map((t) => toTrack(t, false))
1221
- ];
1222
- return {
1223
- meta: {
1224
- schema_version: VIDEO_DOCUMENT_SCHEMA_VERSION,
1225
- draft_id: draft.id,
1226
- project_id: draft.project_id,
1227
- owner_id: draft.owner_id,
1228
- thumbnail_storage_key: draft.thumbnail_storage_key,
1229
- chat_session_id: draft.chat_session_id,
1230
- video_creation_settings: clone(draft.video_creation_settings),
1231
- version: draft.version
1232
- },
1233
- timeline: draft.timeline == null ? void 0 : { unit_time_ms: draft.timeline.unit_time_ms },
1234
- tracks,
1235
- part_library: toAuthoritativePartLibrary(draft.part_library)
1236
- };
1237
- }
1238
- /**
1239
- * Map the legacy `VideoDraft` part library into the authoritative shape
1240
- * (reference/17 §5): the authoritative parts store no derived part-level
1241
- * duration, so the read-view `duration_ms` is dropped from video / speech / bgm.
1242
- * For a caption the legacy `duration_ms` is the generation-time length, stored
1243
- * authoritatively as `initial_duration_ms`.
1244
- */
1245
- function toAuthoritativePartLibrary(partLibrary) {
1246
- if (partLibrary == null) return void 0;
1247
- const out = {};
1248
- for (const [partId, part] of Object.entries(partLibrary)) {
1249
- if (typeof part !== "object" || part == null) continue;
1250
- if (part.video_clip != null) out[partId] = { video_clip: withTrimWindowFromDuration(part.video_clip) };
1251
- else if (part.speech != null) {
1252
- const { duration_ms, rest } = splitDurationMs(part.speech);
1253
- out[partId] = { speech: {
1254
- ...rest,
1255
- media_duration_ms: rest.media_duration_ms ?? duration_ms
1256
- } };
1257
- } else if (part.caption != null) {
1258
- const { duration_ms, rest } = splitDurationMs(part.caption);
1259
- out[partId] = { caption: {
1260
- ...rest,
1261
- initial_duration_ms: duration_ms
1262
- } };
1263
- } else if (part.bgm != null) out[partId] = { bgm: omitDurationMs(part.bgm) };
1264
- }
1265
- return out;
1266
- }
1267
- /**
1268
- * Build a speech-host map from a part_aggregations list. Used by
1269
- * `toVideoDocument` (legacy VideoDraft → VideoDocument) to recover each speech's
1270
- * host video clip and relative offset. Aggregation items with null ids are
1271
- * skipped (malformed input tolerance).
1272
- */
1273
- function buildSpeechHostMap(aggregations) {
1274
- const map = /* @__PURE__ */ new Map();
1275
- for (const aggregation of aggregations ?? []) {
1276
- const host = aggregation.body_part_id;
1277
- if (host == null) continue;
1278
- for (const attachment of aggregation.attachments ?? []) {
1279
- if (attachment.part_id == null) continue;
1280
- map.set(attachment.part_id, {
1281
- hostPartId: host,
1282
- offsetMs: Math.round(attachment.relative_time_position ?? 0)
1283
- });
1284
- }
1285
- }
1286
- return map;
1287
- }
1288
- /**
1289
- * Derive `time_position` (and `fallbackAbsMs` for anchored items) from a legacy
1290
- * absolute time + pre-built speech-host map + part library. The three-branch
1291
- * rule (RFC 02 §4/§5, reference/17 §3):
1292
- *
1293
- * 1. main-track → `sequential`
1294
- * 2. speech/attachment (part_id in speechHost) → `anchored(host, offsetMs)`
1295
- * 3. caption (part has `speech_part_id`) → `anchored(speech, start_ms)`
1296
- * 4. everything else → `absolute(abs)`
1297
- *
1298
- * `partLibrary` values may be `PartUnion | string | undefined` (draft raw
1299
- * form); only object-typed entries are inspected for `caption`.
1300
- */
1301
- function derivePositionFromAbs(partId, abs, isMain, speechHost, partLibrary) {
1302
- if (isMain) return { timePosition: { mode: "sequential" } };
1303
- const host = speechHost.get(partId);
1304
- if (host != null) return {
1305
- timePosition: {
1306
- mode: "anchored",
1307
- anchorPartId: host.hostPartId,
1308
- offsetMs: host.offsetMs
1309
- },
1310
- fallbackAbsMs: abs
1311
- };
1312
- const part = partLibrary[partId];
1313
- const captionPart = typeof part === "object" && part != null ? part.caption : void 0;
1314
- const speechId = captionPart?.speech_part_id ?? void 0;
1315
- if (speechId != null) return {
1316
- timePosition: {
1317
- mode: "anchored",
1318
- anchorPartId: speechId,
1319
- offsetMs: Math.round(captionPart?.start_ms ?? 0)
1320
- },
1321
- fallbackAbsMs: abs
1322
- };
1323
- return { timePosition: {
1324
- mode: "absolute",
1325
- offsetMs: abs
1326
- } };
1327
- }
1328
- /** Derive one item's authoritative `time_position` from its legacy abs + aggregation. */
1329
- function deriveItem(item, isMain, speechHost, partLibrary) {
1330
- const partId = item.part_id ?? "";
1331
- const { timePosition, fallbackAbsMs } = derivePositionFromAbs(partId, Math.round(item.abs_time_position ?? 0), isMain, speechHost, partLibrary);
1332
- return fallbackAbsMs == null ? {
1333
- part_id: partId,
1334
- time_position: timePosition
1335
- } : {
1336
- part_id: partId,
1337
- time_position: timePosition,
1338
- fallback_abs_ms: fallbackAbsMs
1339
- };
1340
- }
1341
- /**
1342
- * Project the authoritative `VideoDocument` back into the legacy `VideoDraft`
1343
- * read-view, solving each item's absolute position, the `part_aggregations`, and
1344
- * the total duration via the timeline-core cascade.
1345
- */
1346
- function fromVideoDocument(document) {
1347
- assertValidVideoDocument(document);
1348
- const view = solveVideoDocument(document);
1349
- const tracks = document.tracks ?? [];
1350
- const mainTrack = tracks.find((t) => t.parts_kind === "video_clip");
1351
- const aboveTracks = tracks.filter((t) => t.parts_kind === "caption");
1352
- const belowTracks = tracks.filter((t) => t.parts_kind === "speech" || t.parts_kind === "bgm");
1353
- return {
1354
- id: document.meta.draft_id,
1355
- project_id: document.meta.project_id,
1356
- owner_id: document.meta.owner_id,
1357
- thumbnail_storage_key: document.meta.thumbnail_storage_key,
1358
- timeline: {
1359
- duration_ms: view.durationMs,
1360
- unit_time_ms: document.timeline?.unit_time_ms
1361
- },
1362
- video_creation_settings: clone(document.meta.video_creation_settings),
1363
- chat_session_id: document.meta.chat_session_id,
1364
- main_track: draftTrack(mainTrack, view.absByPartId),
1365
- above_main_tracks: aboveTracks.map((t) => draftTrack(t, view.absByPartId)),
1366
- below_main_tracks: belowTracks.map((t) => draftTrack(t, view.absByPartId)),
1367
- part_aggregations: view.aggregations,
1368
- part_library: toReadViewPartLibrary(view.partLibrary, view.durationMs),
1369
- version: document.meta.version
1370
- };
1371
- }
1372
- /**
1373
- * Map the authoritative part library into the `VideoDraft` read-view shape,
1374
- * re-injecting the derived effective `duration_ms` downstream expects
1375
- * (reference/17 §5/§7) — the authoritative parts store no part-level duration:
1376
- *
1377
- * - video clip → `(play_out - play_in) / speed` (`effectiveVideoClipDurationMs`)
1378
- * - speech → its intrinsic `media_duration_ms` (no trim/speed)
1379
- * - caption → its generation-time `initial_duration_ms`
1380
- * - bgm → the timeline total (`durationMs`)
1381
- *
1382
- * Parts are deep-cloned; the engine extensions (`media_duration_ms`,
1383
- * `initial_duration_ms`) are kept alongside the injected `duration_ms`.
1384
- */
1385
- function toReadViewPartLibrary(partLibrary, durationMs) {
1386
- const out = {};
1387
- for (const [partId, part] of Object.entries(partLibrary)) if (part.video_clip != null) {
1388
- const clip = clone(part.video_clip);
1389
- out[partId] = { video_clip: {
1390
- ...clip,
1391
- duration_ms: effectiveVideoClipDurationMs(clip)
1392
- } };
1393
- } else if (part.speech != null) {
1394
- const speech = clone(part.speech);
1395
- out[partId] = { speech: {
1396
- ...speech,
1397
- duration_ms: speech.media_duration_ms
1398
- } };
1399
- } else if (part.caption != null) {
1400
- const caption = clone(part.caption);
1401
- out[partId] = { caption: {
1402
- ...caption,
1403
- duration_ms: caption.initial_duration_ms
1404
- } };
1405
- } else if (part.bgm != null) out[partId] = { bgm: {
1406
- ...clone(part.bgm),
1407
- duration_ms: durationMs
1408
- } };
1409
- return out;
1410
- }
1411
- /** Deep-clone a part payload, dropping the derived read-view `duration_ms`. */
1412
- function omitDurationMs(part) {
1413
- const { duration_ms: _drop, ...rest } = clone(part);
1414
- return rest;
1415
- }
1416
- /**
1417
- * Migrate a legacy video clip into the authoritative trim-window-only shape: the
1418
- * authoritative part stores no `duration_ms`, so it is dropped — but a legacy
1419
- * clip with no explicit trim window (`play_in` / `play_out` absent) would then
1420
- * compute an effective length of 0 and vanish from the layout. When that clip
1421
- * carried a legacy `duration_ms`, backfill it as the trim window (`play_in` 0,
1422
- * `play_out = duration_ms`, no speed) so the effective length is preserved, then
1423
- * drop `duration_ms`. A clip that already has a trim window keeps it verbatim.
1424
- */
1425
- function withTrimWindowFromDuration(clip) {
1426
- const stripped = omitDurationMs(clip);
1427
- if (clip.play_in != null || clip.play_out != null) return stripped;
1428
- const legacyDuration = clip.duration_ms;
1429
- if (legacyDuration == null || !Number.isFinite(legacyDuration)) return stripped;
1430
- return {
1431
- ...stripped,
1432
- play_in: 0,
1433
- play_out: legacyDuration
1434
- };
1435
- }
1436
- /** Deep-clone a part payload, returning its `duration_ms` separately from the rest. */
1437
- function splitDurationMs(part) {
1438
- const { duration_ms, ...rest } = clone(part);
1439
- return {
1440
- duration_ms,
1441
- rest
1442
- };
1443
- }
1444
- function draftTrack(track, absByPartId) {
1445
- if (track == null) return void 0;
1446
- return {
1447
- id: track.id,
1448
- parts_kind: track.parts_kind,
1449
- is_hidden: track.is_hidden,
1450
- items: (track.items ?? []).map((item) => ({
1451
- part_id: item.part_id,
1452
- abs_time_position: absByPartId.get(item.part_id) ?? 0
1453
- }))
1454
- };
1455
- }
1456
- function clone(value) {
1457
- if (Array.isArray(value)) return value.map((item) => clone(item));
1458
- if (value != null && typeof value === "object") {
1459
- const result = {};
1460
- for (const [key, child] of Object.entries(value)) result[key] = clone(child);
1461
- return result;
1462
- }
1463
- return value;
1464
- }
1465
- //#endregion
1466
- //#region src/document/mirror-read.ts
1467
- /**
1468
- * Project the mirror state (`VideoDocumentDraft`) into the authoritative
1469
- * `VideoDocument`. The storage shape is isomorphic to the domain shape (RFC 03
1470
- * §4, reference/17 §4: meta map + a single `tracks` list + part_library), so this
1471
- * is a near-identity — it reads `time_position` / `fallback_abs_ms` JSON blobs
1472
- * back into structured values and trims empty strings, nothing more.
1473
- *
1474
- * It maps only authoritative facts (RFC 02 §6): `part_id` + `time_position`. The
1475
- * projection-derived `VideoDraft` read-view (absolute time, `part_aggregations`,
1476
- * total duration) is solved separately by the cascade, not here.
1477
- *
1478
- * It reads in-memory mirror state (O(n) over the document), not a Loro
1479
- * `toJSON()` FFI rebuild — the cost the prior schema adapter paid on every
1480
- * `snapshot()`.
1481
- */
1482
- function readVideoDocumentFromDraft(draft) {
1483
- const partLibrary = {};
1484
- for (const [partId, payload] of recordEntries(draft.part_library)) {
1485
- const part = draftToPartUnion(payload);
1486
- if (part != null) partLibrary[partId] = part;
1487
- }
1488
- const timeline = draft.timeline;
1489
- const hasTimeline = timeline?.unit_time_ms != null;
1490
- const meta = draft.meta;
1491
- return {
1492
- meta: {
1493
- schema_version: VIDEO_DOCUMENT_SCHEMA_VERSION,
1494
- draft_id: emptyToUndefined(meta?.draft_id),
1495
- project_id: emptyToUndefined(meta?.project_id),
1496
- owner_id: emptyToUndefined(meta?.owner_id),
1497
- thumbnail_storage_key: emptyToUndefined(meta?.thumbnail_storage_key),
1498
- chat_session_id: emptyToUndefined(meta?.chat_session_id),
1499
- video_creation_settings: meta?.video_creation_settings ?? void 0,
1500
- version: meta?.version ?? void 0
1501
- },
1502
- timeline: hasTimeline ? { unit_time_ms: timeline.unit_time_ms } : void 0,
1503
- tracks: rowsToTracks(draft.tracks),
1504
- part_library: partLibrary
1505
- };
1506
- }
1507
- /** Map a movable-list of track rows (`$cid`-bearing) into domain tracks, dropping empty-id placeholders. */
1508
- function rowsToTracks(rows) {
1509
- return (rows ?? []).filter((row) => row.id != null && row.id !== "").map(rowToTrack);
1510
- }
1511
- function rowToTrack(row) {
1512
- return {
1513
- id: row.id,
1514
- parts_kind: row.parts_kind ?? void 0,
1515
- is_hidden: row.is_hidden ?? void 0,
1516
- items: (row.items ?? []).map((item) => {
1517
- const result = {
1518
- part_id: item.part_id ?? "",
1519
- time_position: item.time_position
1520
- };
1521
- if (item.fallback_abs_ms != null) result.fallback_abs_ms = item.fallback_abs_ms;
1522
- return result;
1523
- })
1524
- };
1525
- }
1526
- function emptyToUndefined(value) {
1527
- return value == null || value === "" ? void 0 : value;
1528
- }
1529
- //#endregion
1530
- //#region src/document/mirror-adapter.ts
1531
- /**
1532
- * Storage-layer adapter that backs a `VideoDocument` with `loro-mirror` (ADR
1533
- * 0008). The mirror holds an in-memory immutable state synced to the `LoroDoc`
1534
- * by declarative diff, replacing the hand-rolled `@mengine/schema` adapter:
1535
- *
1536
- * - `snapshot()` projects the mirror's in-memory state to the read model — no
1537
- * per-call `toJSON()` FFI rebuild.
1538
- * - `transact(edit, audit)` runs the whole op in one `mirror.setState` callback:
1539
- * one diff, one `doc.commit` carrying the audit message. The callback edits an
1540
- * immer draft, so a throw inside it discards the draft and never touches Loro
1541
- * (natural rollback) — no `guard` / `rollback` / `openTransaction` machinery.
1542
- * - mirror's `idSelector` (track items keyed by `part_id`) diffs reorders to
1543
- * real Loro `move` ops on every lane, so per-item CRDT identity survives on
1544
- * main and secondary tracks alike.
1545
- */
1546
- var MirrorVideoDocumentAdapter = class {
1547
- doc;
1548
- mirror;
1549
- constructor(doc) {
1550
- this.doc = doc;
1551
- this.mirror = new Mirror({
1552
- doc,
1553
- schema: videoDocumentMirrorSchema
1554
- });
1555
- }
1556
- snapshot() {
1557
- return readVideoDocumentFromDraft(this.mirror.getState());
1558
- }
1559
- /**
1560
- * True once the doc holds real document content. A fresh mirror over an empty
1561
- * doc still reports defaulted root maps, so probe the stored `schema_version`
1562
- * (empty until a snapshot is bootstrapped or synced in).
1563
- */
1564
- hasContent() {
1565
- return (this.mirror.getState().meta?.schema_version ?? "") !== "";
1566
- }
1567
- /**
1568
- * Apply one op as a single transaction. `edit` mutates the immer draft; mirror
1569
- * diffs the result and commits once with the audit `message`. A throw in `edit`
1570
- * discards the draft (Loro untouched). When `edit` produces no change, mirror
1571
- * skips the commit — matching the prior "empty op leaves no audit" behavior.
1572
- */
1573
- transact(edit, audit) {
1574
- this.mirror.setState((draft) => {
1575
- edit(draft);
1576
- }, {
1577
- origin: "mengine.semantic_editor",
1578
- message: JSON.stringify({
1579
- semantic_op: audit.kind,
1580
- payload: audit.payload,
1581
- intent: audit.intent ?? null
1582
- })
1583
- });
1584
- }
1585
- };
1586
- /** Build a fresh Loro doc seeded with `document` through the mirror. */
1587
- function createMirrorVideoDocument(document, options = {}) {
1588
- assertValidVideoDocument(document);
1589
- const doc = new LoroDoc();
1590
- if (options.peerId != null) doc.setPeerId(options.peerId);
1591
- new Mirror({
1592
- doc,
1593
- schema: videoDocumentMirrorSchema
1594
- }).setState((draft) => {
1595
- seedDraft(draft, document);
1596
- }, { origin: options.origin ?? "mengine.bootstrap" });
1597
- return doc;
1598
- }
1599
- /** Build a `MirrorVideoDocumentAdapter` over a fresh doc seeded with `document`. */
1600
- function createMirrorVideoDocumentAdapter(document, options) {
1601
- return new MirrorVideoDocumentAdapter(createMirrorVideoDocument(document, options));
1602
- }
1603
- /** Write a whole `VideoDocument` into the mirror draft (used to seed a fresh doc). */
1604
- function seedDraft(draft, document) {
1605
- draft.meta = {
1606
- schema_version: document.meta.schema_version,
1607
- draft_id: document.meta.draft_id ?? void 0,
1608
- project_id: document.meta.project_id ?? void 0,
1609
- owner_id: document.meta.owner_id ?? void 0,
1610
- thumbnail_storage_key: document.meta.thumbnail_storage_key ?? void 0,
1611
- chat_session_id: document.meta.chat_session_id ?? void 0,
1612
- video_creation_settings: document.meta.video_creation_settings ?? void 0,
1613
- version: document.meta.version ?? void 0
1614
- };
1615
- draft.timeline = { unit_time_ms: document.timeline?.unit_time_ms ?? void 0 };
1616
- draft.tracks = (document.tracks ?? []).map(toTrackRow);
1617
- draft.part_library = {};
1618
- for (const [partId, part] of Object.entries(document.part_library ?? {})) draft.part_library[partId] = partUnionToDraft(part);
1619
- }
1620
- /** Map a domain `Track` to a draft track row (no lane/lane_order — see schema). */
1621
- function toTrackRow(track) {
1622
- return {
1623
- id: track.id ?? "",
1624
- parts_kind: track.parts_kind ?? void 0,
1625
- is_hidden: track.is_hidden ?? void 0,
1626
- items: (track.items ?? []).map((item) => ({
1627
- part_id: item.part_id,
1628
- time_position: item.time_position,
1629
- fallback_abs_ms: item.fallback_abs_ms
1630
- }))
1631
- };
1632
- }
1633
- //#endregion
1634
- //#region src/editor/id-gen.ts
1635
- /**
1636
- * Part-id generation, aligned with the online ecosystem.
1637
- *
1638
- * The authoritative online producers — agent-harness (`@harness/shared`
1639
- * `genObjId`) and director.v2 (`common/obj_id.py` `gen_obj_id`) — both mint part
1640
- * ids as `` `${prefix}_${ulid()}` ``, and real captured drafts use exactly that
1641
- * shape (`clip_…` / `spe_…` / `cap_…` / `bgm_…`, each a 26-char ULID). The engine
1642
- * previously emitted `vc_<base36 timestamp><6 random>`, a different prefix AND a
1643
- * different encoding — the sole cross-repo id divergence. This module removes it
1644
- * by emitting the same `<prefix>_<ULID>` bytes.
1645
- *
1646
- * The ULID is generated inline (Crockford Base32, 48-bit time + 80-bit random)
1647
- * rather than pulling the `ulid` npm package: the randomness class matches the
1648
- * old generator (both `Math.random`-based) and it keeps `@mengine/medeo-client`
1649
- * dependency-free for a purely mechanical id string. Part ids only need to be
1650
- * unique and lexicographically time-sortable, which this satisfies.
1651
- */
1652
- /** Crockford Base32 alphabet (no I, L, O, U), per the ULID spec. */
1653
- const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
1654
- const TIME_LEN = 10;
1655
- const RANDOM_LEN = 16;
1656
- function encodeTime(now) {
1657
- let out = "";
1658
- let ms = now;
1659
- for (let i = TIME_LEN - 1; i >= 0; i--) {
1660
- const mod = ms % 32;
1661
- out = CROCKFORD[mod] + out;
1662
- ms = (ms - mod) / 32;
1663
- }
1664
- return out;
1665
- }
1666
- function encodeRandom() {
1667
- let out = "";
1668
- for (let i = 0; i < RANDOM_LEN; i++) out += CROCKFORD[Math.floor(Math.random() * 32)];
1669
- return out;
1670
- }
1671
- /** A 26-char Crockford Base32 ULID (10-char time + 16-char random). */
1672
- function ulid() {
1673
- return encodeTime(Date.now()) + encodeRandom();
1674
- }
1675
- function generatePartId(prefix) {
1676
- return `${prefix}_${ulid()}`;
1677
- }
1678
- //#endregion
1679
- //#region src/editor/schemas/shared.ts
1680
- const clipIdSchema = z.string().min(1).describe("The clip part ID on the timeline");
1681
- const clipIdsSchema = z.array(clipIdSchema).min(1).refine((ids) => new Set(ids).size === ids.length, { message: "Duplicate clip IDs are not allowed" }).describe("List of clip part IDs (no duplicates allowed)");
1682
- const mediaIdSchema = z.string().min(1).describe("The media asset ID");
1683
- const speechIdSchema = z.string().min(1).describe("The speech part ID on the timeline");
1684
- const timelineMsSchema = z.number().int().min(0).describe("Time position in milliseconds on the timeline (>= 0)");
1685
- const positiveMsSchema = z.number().int().positive().describe("Duration in milliseconds (> 0)");
1686
- const volumeSchema = z.number().min(-60).max(20).describe("Volume in decibels (-60.0 to 20.0; 0.0 = original, -60 = mute, +20 = max)");
1687
- const speechIdsSchema = z.array(speechIdSchema).min(1).refine((ids) => new Set(ids).size === ids.length, { message: "Duplicate speech IDs are not allowed" }).describe("List of speech part IDs (no duplicates allowed)");
1688
- const tangentHandleSchema = z.object({
1689
- x: z.number().finite(),
1690
- y: z.number().finite()
1691
- }).describe("Bezier tangent handle (x, y)");
1692
- const speedKeyframeSchema = z.object({
1693
- position: z.number().min(0).max(1),
1694
- rate: z.number().min(0),
1695
- in_tangent: tangentHandleSchema.optional(),
1696
- out_tangent: tangentHandleSchema.optional()
1697
- }).describe("A speed keyframe: normalized position (0..1), rate, optional tangents");
1698
- /**
1699
- * A clip's playback-speed fact, the only thing `SetVideoClipSpeedShift` writes.
1700
- * Mirrors the IDL `SpeedShift`: `category` is `linear` | `curve`, and `config`
1701
- * is a discriminated union — `{ linear: { speed } }` for a constant multiplier
1702
- * (the multiplier projection reads at `config.linear.speed`) or `{ curve: {
1703
- * keyframes } }` for a Bezier-controlled variable speed (RFC 02 / `reference/16`
1704
- * §0). Exactly one of `linear` / `curve` is present.
1705
- */
1706
- const speedShiftSchema = z.object({
1707
- category: z.enum(["linear", "curve"]),
1708
- mode: z.string(),
1709
- config: z.union([z.object({ linear: z.object({ speed: z.number().finite().positive() }) }), z.object({ curve: z.object({ keyframes: z.array(speedKeyframeSchema).min(2) }) })])
1710
- }).describe("Speed shift: linear multiplier or Bezier curve, mirroring the IDL shape");
1711
- const voiceSchema = z.object({
1712
- id: z.string().min(1),
1713
- name: z.string()
1714
- }).describe("TTS voice summary attached to a speech");
1715
- //#endregion
1716
- //#region src/editor/schemas/speech-assets.ts
1717
- /**
1718
- * The materialized TTS result shared by `AddSpeeches` / `ChangeSpeechScript` /
1719
- * `ChangeSpeechVoice` (see `results/phase-4-side-effect-payload-contract.md`
1720
- * §1/§2). The side effect (TTS/ASR + billing) runs upstream; the op receives the
1721
- * stable speech + caption parts and writes them as authoritative facts. No
1722
- * cascade runs on write — the projection derives absolute positions on read.
1723
- *
1724
- * Each speech carries the anchoring fact directly (RFC 02 §4): the host video
1725
- * clip `anchor_part_id` and the `offset_ms` within it. The upstream caller
1726
- * already knows which clip a speech attaches to, so the op writes
1727
- * `{ mode:'anchored', anchorPartId, offsetMs }` verbatim — no write-time
1728
- * host-picking. Captions anchor to their speech via the caption part's
1729
- * `start_ms` (offset within the speech).
1730
- */
1731
- const speechAssetSchema = z.object({
1732
- speech_id: speechIdSchema.describe("The speech part ID (= side-effect speech_parts[].id)"),
1733
- anchor_part_id: clipIdSchema.describe("Host video clip part ID the speech anchors to (RFC 02 §4)"),
1734
- offset_ms: timelineMsSchema.describe("Offset within the host clip (speech.abs = host.abs + offset_ms)"),
1735
- audio_storage_key: z.string().min(1),
1736
- duration_ms: positiveMsSchema,
1737
- audio_script: z.string(),
1738
- volume: volumeSchema,
1739
- voice: voiceSchema,
1740
- origin_speech_id: z.string().min(1),
1741
- caption_ids: z.array(z.string().min(1)).describe("Caption part IDs owned by this speech")
1742
- });
1743
- const captionAssetSchema = z.object({
1744
- caption_id: z.string().min(1).describe("The caption part ID (= side-effect created_caption_parts[].id)"),
1745
- speech_part_id: speechIdSchema.describe("The owning speech part ID"),
1746
- text: z.string(),
1747
- start_ms: timelineMsSchema.describe("Offset within the host speech (caption.abs = speech.abs + start_ms)"),
1748
- duration_ms: positiveMsSchema
1749
- });
1750
- /** A materialized speech-subtree write (speeches + their captions). */
1751
- const speechAssetsSchema = z.object({
1752
- speeches: z.array(speechAssetSchema).min(1).describe("Materialized speech parts to write"),
1753
- captions: z.array(captionAssetSchema).describe("Materialized caption parts owned by the speeches")
1754
- });
1755
- //#endregion
1756
- //#region src/editor/schemas/add-speeches.ts
1757
- /**
1758
- * Add speeches (and their captions). TTS runs upstream; the stable speech /
1759
- * caption parts arrive materialized (see `speech-assets.ts`). The op writes the
1760
- * parts and each speech's `{ mode:'anchored', anchorPartId, offsetMs }` fact
1761
- * verbatim — no write-time host-picking, no cascade (RFC 02 §4). The projection
1762
- * derives absolute positions on read.
1763
- */
1764
- const addSpeechesInputSchema = speechAssetsSchema.describe("Materialized speeches + captions to add");
1765
- //#endregion
1766
- //#region src/editor/schemas/add-video-clips.ts
1767
- /**
1768
- * Add video clips to a track. Each clip's duration facts are separated so a
1769
- * single number is never overloaded (RFC 02 / `reference/16` §0b):
1770
- *
1771
- * - `media_duration_ms` is the source media's intrinsic full length (a resource
1772
- * fact, written to the part);
1773
- * - `play_in` / `play_out` are the optional trim window into that media; when
1774
- * omitted the whole media is used (`play_in=0`, `play_out=media_duration_ms`).
1775
- *
1776
- * The clip's effective timeline duration is derived by the projection from the
1777
- * trim window and `speed_shift` — it is never an input here.
1778
- */
1779
- const addVideoClipsInputSchema = z.object({
1780
- clips: z.array(z.object({
1781
- media_id: mediaIdSchema.describe("The media asset ID for the video clip"),
1782
- start_ms: timelineMsSchema.optional().describe("Absolute start time in milliseconds on the timeline"),
1783
- media_duration_ms: positiveMsSchema.describe("The source media's intrinsic full length in ms"),
1784
- play_in: timelineMsSchema.optional().describe("Trim window start in the media (default 0)"),
1785
- play_out: positiveMsSchema.optional().describe("Trim window end in the media (default media_duration_ms)"),
1786
- track_id: z.string().min(1).optional().describe("Target track ID (optional, defaults to main track)")
1787
- })).min(1).describe("List of video clips to create"),
1788
- before_clip_id: z.string().min(1).optional().describe("Insert new clips before this clip ID"),
1789
- after_clip_id: z.string().min(1).optional().describe("Insert new clips after this clip ID")
1790
- }).superRefine((data, ctx) => {
1791
- if (data.before_clip_id != null && data.after_clip_id != null) {
1792
- ctx.addIssue({
1793
- code: z.ZodIssueCode.custom,
1794
- message: "Cannot provide both before_clip_id and after_clip_id"
1795
- });
1796
- return;
1797
- }
1798
- const hasRelative = data.before_clip_id != null || data.after_clip_id != null;
1799
- for (let i = 0; i < data.clips.length; i++) {
1800
- const clip = data.clips[i];
1801
- if (hasRelative && clip.start_ms != null) ctx.addIssue({
1802
- code: z.ZodIssueCode.custom,
1803
- message: `clips[${i}].start_ms must not be provided when using before_clip_id or after_clip_id`,
1804
- path: [
1805
- "clips",
1806
- i,
1807
- "start_ms"
1808
- ]
1809
- });
1810
- if (!hasRelative && clip.start_ms == null) ctx.addIssue({
1811
- code: z.ZodIssueCode.custom,
1812
- message: `clips[${i}].start_ms is required when not using relative positioning`,
1813
- path: [
1814
- "clips",
1815
- i,
1816
- "start_ms"
1817
- ]
1818
- });
1819
- const playIn = clip.play_in ?? 0;
1820
- const playOut = clip.play_out ?? clip.media_duration_ms;
1821
- if (playOut > clip.media_duration_ms) ctx.addIssue({
1822
- code: z.ZodIssueCode.custom,
1823
- message: `clips[${i}].play_out ${playOut}ms exceeds media_duration_ms ${clip.media_duration_ms}ms`,
1824
- path: [
1825
- "clips",
1826
- i,
1827
- "play_out"
1828
- ]
1829
- });
1830
- if (playIn >= playOut) ctx.addIssue({
1831
- code: z.ZodIssueCode.custom,
1832
- message: `clips[${i}].play_in ${playIn}ms must be less than play_out ${playOut}ms`,
1833
- path: [
1834
- "clips",
1835
- i,
1836
- "play_in"
1837
- ]
1838
- });
1839
- }
1840
- });
1841
- //#endregion
1842
- //#region src/editor/schemas/adjust-bgm-volume.ts
1843
- const adjustBgmVolumeInputSchema = z.object({ bgm: z.array(z.object({
1844
- bgm_id: clipIdSchema.describe("The bgm part ID to adjust volume for"),
1845
- volume: volumeSchema.describe("Volume in decibels (-60.0 to 20.0; 0.0 = original)")
1846
- })).min(1).describe("List of bgm parts with their new volume settings") });
1847
- //#endregion
1848
- //#region src/editor/schemas/adjust-speech-volume.ts
1849
- const adjustSpeechVolumeInputSchema = z.object({ speeches: z.array(z.object({
1850
- speech_id: speechIdSchema.describe("The speech part ID to adjust volume for"),
1851
- volume: volumeSchema.describe("Volume in decibels (-60.0 to 20.0; 0.0 = original)")
1852
- })).min(1).describe("List of speeches with their new volume settings") });
1853
- //#endregion
1854
- //#region src/editor/schemas/adjust-video-clip-duration.ts
1855
- /**
1856
- * Re-trim existing video clips (the user-facing "adjust duration" gesture is a
1857
- * trim of the source window). The new `play_in` / `play_out` are the facts; the
1858
- * effective timeline duration is derived from them and the clip's `speed_shift`,
1859
- * and the change reflows downstream clips, speeches, and the timeline inside the
1860
- * op's transaction (no caller-materialized cascade).
1861
- */
1862
- const adjustVideoClipDurationInputSchema = z.object({ clips: z.array(z.object({
1863
- clip_id: clipIdSchema.describe("The video clip part ID to re-trim"),
1864
- play_in: timelineMsSchema.describe("New trim window start in the source media"),
1865
- play_out: positiveMsSchema.describe("New trim window end in the source media")
1866
- })).min(1).describe("Video clips with their new trim windows") });
1867
- //#endregion
1868
- //#region src/editor/schemas/adjust-video-clip-volume.ts
1869
- const adjustVideoClipVolumeInputSchema = z.object({ clips: z.array(z.object({
1870
- clip_id: clipIdSchema.describe("The video clip part ID to adjust volume for"),
1871
- volume: volumeSchema.describe("Volume in decibels (-60.0 to 20.0; 0.0 = original)")
1872
- })).min(1).describe("List of video clips with their new volume settings") });
1873
- //#endregion
1874
- //#region src/editor/schemas/change-speech.ts
1875
- /**
1876
- * Change a speech's script or voice. Both re-run TTS upstream and return the
1877
- * regenerated speech / caption parts in the same materialized shape as
1878
- * `AddSpeeches` (`speech-assets.ts`); the op upserts them by id (the speech part
1879
- * id is preserved across a re-TTS), re-seats at `start_ms`, and reflows. Old
1880
- * caption parts no longer owned by the speech are removed via `caption_ids`.
1881
- */
1882
- const changeSpeechScriptInputSchema = speechAssetsSchema.describe("Regenerated speeches + captions (new script)");
1883
- const changeSpeechVoiceInputSchema = speechAssetsSchema.describe("Regenerated speeches + captions (new voice)");
1884
- //#endregion
1885
- //#region src/editor/schemas/delete-bgm.ts
1886
- /**
1887
- * Remove the document BGM. Pure document edit: clears the bgm lane and removes
1888
- * the bgm part. Takes no input (a document holds at most one bgm); an empty
1889
- * object keeps the op signature uniform with the rest.
1890
- */
1891
- const deleteBgmInputSchema = z.object({}).describe("Remove the document BGM (no parameters)");
1892
- //#endregion
1893
- //#region src/editor/schemas/delete-speeches.ts
1894
- /**
1895
- * Delete speeches with their captions. Pure document edit (no side effect): the
1896
- * op removes each speech part, cascade-deletes the captions it owns (via
1897
- * `caption_ids` / `speech_part_id`), drops their track items, and reflows.
1898
- */
1899
- const deleteSpeechesInputSchema = z.object({ speech_ids: speechIdsSchema.describe("Speech part IDs to delete (their captions cascade-delete)") });
1900
- //#endregion
1901
- //#region src/editor/schemas/delete-video-clips.ts
1902
- /**
1903
- * How a delete handles the anchored subtree (speeches anchored to a deleted clip,
1904
- * and their captions) — a delete-op policy, not a data-model field (reference/17
1905
- * §6). `cascade` (default) removes the subtree; `detach` keeps the direct
1906
- * anchored children, re-pinning them to `absolute` so they stay on the timeline.
1907
- */
1908
- const anchoredDeletePolicySchema = z.enum(["cascade", "detach"]);
1909
- const deleteVideoClipsInputSchema = z.object({
1910
- clip_ids: clipIdsSchema.describe("List of video clip part IDs to delete from the main track"),
1911
- on_anchored: anchoredDeletePolicySchema.optional().describe("How to treat anchored children (default cascade)")
1912
- });
1913
- //#endregion
1914
- //#region src/editor/schemas/move-speeches.ts
1915
- /**
1916
- * Move speeches in time. Pure document edit: the op re-seats each speech at its
1917
- * new absolute `start_ms`; the cascade reassigns it to the host video clip,
1918
- * resolves overlaps, and reflows. Captions follow their speech.
1919
- */
1920
- const moveSpeechesInputSchema = z.object({ speeches: z.array(z.object({
1921
- speech_id: speechIdSchema.describe("The speech part ID to move"),
1922
- new_start_ms: timelineMsSchema.describe("New absolute start time on the timeline")
1923
- })).min(1).describe("Speeches to move to new positions") });
1924
- //#endregion
1925
- //#region src/editor/schemas/move-video-clips.ts
1926
- const moveVideoClipsInputSchema = z.object({ clips: z.array(z.object({
1927
- clip_id: clipIdSchema.describe("The video clip part ID to move"),
1928
- new_start_ms: timelineMsSchema.describe("New absolute start time in milliseconds on the timeline"),
1929
- new_track_id: z.string().min(1).optional().describe("Target track ID to move the clip to (optional)")
1930
- })).min(1).describe("List of video clips to move to new positions") });
1931
- //#endregion
1932
- //#region src/editor/schemas/replace-video-clip-content.ts
1933
- /**
1934
- * Replace the media backing existing video clips. The media import runs upstream
1935
- * (Director); its stable result — the new media id, intrinsic length, and the
1936
- * reset trim window — arrives materialized (see
1937
- * `results/phase-4-side-effect-payload-contract.md` §4). Director resets
1938
- * `play_in=0` / `play_out=media_duration_ms` and clears `speed_shift` on
1939
- * replacement. The clip `part_id`s (hence their track items) are unchanged; the
1940
- * editor reflows the main track from the new effective durations.
1941
- */
1942
- const replaceVideoClipContentInputSchema = z.object({ clips: z.array(z.object({
1943
- clip_id: clipIdSchema.describe("Existing video clip part ID to re-point"),
1944
- origin_media_id: mediaIdSchema.describe("The new media asset ID"),
1945
- media_duration_ms: positiveMsSchema.describe("The new media's intrinsic full length"),
1946
- play_in: timelineMsSchema.describe("Trim window start in the new media (usually 0)"),
1947
- play_out: positiveMsSchema.describe("Trim window end in the new media (usually = media_duration_ms)"),
1948
- volume: volumeSchema
1949
- })).min(1).describe("Video clips whose media is being replaced") });
1950
- //#endregion
1951
- //#region src/editor/schemas/set-bgm.ts
1952
- /**
1953
- * Set the document BGM. The media's stable result (storage key) arrives
1954
- * materialized from upstream (see
1955
- * `results/phase-4-side-effect-payload-contract.md` §3). The op upserts the bgm
1956
- * part and seats it on the bgm lane; its effective length is always the whole
1957
- * timeline, derived by the projection on read — so there is no `duration_ms`
1958
- * input or fact (RFC 02 / `reference/16` §0b). A `bgm_id` lets the op replace an
1959
- * existing bgm part by id.
1960
- */
1961
- const setBgmInputSchema = z.object({
1962
- bgm_id: z.string().min(1).describe("The bgm part ID to write"),
1963
- audio_storage_key: z.string().min(1),
1964
- origin_media_id: mediaIdSchema,
1965
- volume: volumeSchema
1966
- });
1967
- //#endregion
1968
- //#region src/editor/schemas/set-caption-style.ts
1969
- /**
1970
- * Set the caption visual style. GLOBAL by design: the style applies to every
1971
- * caption part in the document — it carries NO `caption_id`. This mirrors the FE,
1972
- * whose caption-style store (`caption-style.ts:persistCaptionStylePatch`) iterates
1973
- * ALL captions and writes the same normalized style to each; the product has a
1974
- * single document-wide caption style, not per-caption styling.
1975
- *
1976
- * Every field is optional and maps to a `CaptionStyle` attribute (snake_case
1977
- * IDL). A field present in the input is written to every caption; a field ABSENT
1978
- * from the input is left untouched on each caption (the editor merges the patch
1979
- * onto each caption's existing style — this is a value edit, not a full-style
1980
- * replace, so a partial patch such as "recolor only" does not wipe font size).
1981
- *
1982
- * Pure document edit, no cascade — captions keep their positions; only the style
1983
- * sub-map of each caption part changes.
1984
- */
1985
- const setCaptionStyleInputSchema = z.object({
1986
- font_id: z.string().min(1).optional().describe("Font ID referencing a font from the font library"),
1987
- font_size: z.number().positive().optional().describe("Font size in points"),
1988
- font_color: z.string().min(1).optional().describe("Font color as hex string, e.g. \"#FFFFFF\""),
1989
- font_weight: z.number().int().optional().describe("Numeric font weight, e.g. 400 or 700"),
1990
- entrance_animation: z.string().optional().describe("Entrance animation preset ID, e.g. \"fade\" or \"none\""),
1991
- entrance_animation_duration_ms: z.number().min(0).optional().describe("Entrance animation duration in ms"),
1992
- stroke_color: z.string().min(1).optional().describe("Outline/stroke color as hex string, e.g. \"#000000\""),
1993
- stroke_width: z.number().min(0).optional().describe("Outline/stroke width in pixels"),
1994
- position_x: z.number().optional().describe("Caption center X as a fraction (0.0 to 1.0)"),
1995
- position_y: z.number().optional().describe("Caption center Y as a fraction (0.0 to 1.0)")
1996
- }).describe("Document-wide caption style patch (no caption_id; applies to every caption)");
1997
- //#endregion
1998
- //#region src/editor/schemas/set-caption-visibility.ts
1999
- /**
2000
- * Toggle caption visibility (the caption track's `is_hidden` flag). Pure
2001
- * document edit, no cascade — captions keep their positions; only the lane's
2002
- * hidden flag changes.
2003
- */
2004
- const setCaptionVisibilityInputSchema = z.object({ is_hidden: z.boolean().describe("Whether the caption track is hidden") });
2005
- //#endregion
2006
- //#region src/editor/schemas/set-video-clip-speed-shift.ts
2007
- /**
2008
- * Set the playback speed of existing video clips. Per the speed-shift decision
2009
- * (`reference/16` §0): the op writes only the `speed_shift` fact — it does NOT
2010
- * store an effective `duration_ms` (projection derives it from the trim window /
2011
- * speed) and does NOT scale anchored speeches' relative offsets (offsets stay
2012
- * put; the cascade reflows absolute positions). A `null` speed_shift clears the
2013
- * speed back to original (1×).
2014
- */
2015
- const setVideoClipSpeedShiftInputSchema = z.object({ clips: z.array(z.object({
2016
- clip_id: clipIdSchema.describe("The video clip part ID to set speed for"),
2017
- speed_shift: speedShiftSchema.nullable().describe("The new speed setting, or null to reset to 1×")
2018
- })).min(1).describe("Video clips with their new speed settings") });
2019
- //#endregion
2020
- //#region src/editor/schemas/index.ts
2021
- var schemas_exports = /* @__PURE__ */ __exportAll({
2022
- addSpeechesInputSchema: () => addSpeechesInputSchema,
2023
- addVideoClipsInputSchema: () => addVideoClipsInputSchema,
2024
- adjustBgmVolumeInputSchema: () => adjustBgmVolumeInputSchema,
2025
- adjustSpeechVolumeInputSchema: () => adjustSpeechVolumeInputSchema,
2026
- adjustVideoClipDurationInputSchema: () => adjustVideoClipDurationInputSchema,
2027
- adjustVideoClipVolumeInputSchema: () => adjustVideoClipVolumeInputSchema,
2028
- anchoredDeletePolicySchema: () => anchoredDeletePolicySchema,
2029
- changeSpeechScriptInputSchema: () => changeSpeechScriptInputSchema,
2030
- changeSpeechVoiceInputSchema: () => changeSpeechVoiceInputSchema,
2031
- clipIdSchema: () => clipIdSchema,
2032
- clipIdsSchema: () => clipIdsSchema,
2033
- deleteBgmInputSchema: () => deleteBgmInputSchema,
2034
- deleteSpeechesInputSchema: () => deleteSpeechesInputSchema,
2035
- deleteVideoClipsInputSchema: () => deleteVideoClipsInputSchema,
2036
- mediaIdSchema: () => mediaIdSchema,
2037
- moveSpeechesInputSchema: () => moveSpeechesInputSchema,
2038
- moveVideoClipsInputSchema: () => moveVideoClipsInputSchema,
2039
- positiveMsSchema: () => positiveMsSchema,
2040
- replaceVideoClipContentInputSchema: () => replaceVideoClipContentInputSchema,
2041
- setBgmInputSchema: () => setBgmInputSchema,
2042
- setCaptionStyleInputSchema: () => setCaptionStyleInputSchema,
2043
- setCaptionVisibilityInputSchema: () => setCaptionVisibilityInputSchema,
2044
- setVideoClipSpeedShiftInputSchema: () => setVideoClipSpeedShiftInputSchema,
2045
- speechAssetsSchema: () => speechAssetsSchema,
2046
- speechIdSchema: () => speechIdSchema,
2047
- speechIdsSchema: () => speechIdsSchema,
2048
- speedShiftSchema: () => speedShiftSchema,
2049
- timelineMsSchema: () => timelineMsSchema,
2050
- voiceSchema: () => voiceSchema,
2051
- volumeSchema: () => volumeSchema
2052
- });
2053
- //#endregion
2054
159
  //#region src/editor/snapshot-utils.ts
2055
160
  function isMap(value) {
2056
161
  return value instanceof Map;
@@ -2358,9 +463,11 @@ function readPartLibrary(draft) {
2358
463
  var SemanticEditor = class {
2359
464
  doc;
2360
465
  validator;
2361
- constructor(doc, validator = new SchemaValidator()) {
466
+ idFactory;
467
+ constructor(doc, validator = new SchemaValidator(), idFactory = generatePartId) {
2362
468
  this.doc = doc;
2363
469
  this.validator = validator;
470
+ this.idFactory = idFactory;
2364
471
  }
2365
472
  async moveVideoClips(input, options) {
2366
473
  this.validator.validateMoveVideoClips(input, this.doc);
@@ -2402,7 +509,7 @@ var SemanticEditor = class {
2402
509
  track.items ??= [];
2403
510
  let at = insertIndex;
2404
511
  for (const clip of input.clips) {
2405
- const partId = generatePartId("clip");
512
+ const partId = this.idFactory("clip");
2406
513
  setPart(draft, partId, { video_clip: {
2407
514
  id: partId,
2408
515
  kind: "video_clip",
@@ -2942,6 +1049,105 @@ function deleteAnchoredSubtree(draft, clipId) {
2942
1049
  for (const speechId of anchored) deleteSpeechSubtree(draft, speechId);
2943
1050
  }
2944
1051
  //#endregion
1052
+ //#region src/editor/journal.ts
1053
+ /**
1054
+ * Wire a plain-memory adapter + editor that share a recording id factory, so
1055
+ * every mutating transact lands in `journal` with ordered `generated_ids`.
1056
+ */
1057
+ function createEditSandbox(document, options) {
1058
+ const adapter = createPlainMemoryAdapter(document, options);
1059
+ return {
1060
+ adapter,
1061
+ editor: new SemanticEditor(adapter, new SchemaValidator(), adapter.idFactory),
1062
+ journal: adapter.journal
1063
+ };
1064
+ }
1065
+ /**
1066
+ * Re-drive `doc` from a recorded journal, forcing each entry's `generated_ids`
1067
+ * through a queue-backed id factory. Never mints fresh ids: an empty queue on
1068
+ * demand throws `unrecorded id`; leftover ids after an entry throws
1069
+ * `unconsumed ids`. Legacy entries without `generated_ids` are treated as `[]`.
1070
+ */
1071
+ async function replayJournal(doc, journal) {
1072
+ const queue = [];
1073
+ const idFactory = (_prefix) => {
1074
+ const id = queue.shift();
1075
+ if (id == null) throw new Error("unrecorded id");
1076
+ return id;
1077
+ };
1078
+ const editor = new SemanticEditor(doc, new SchemaValidator(), idFactory);
1079
+ for (const entry of journal) {
1080
+ queue.push(...entry.generated_ids ?? []);
1081
+ await dispatchEntry(editor, entry);
1082
+ if (queue.length > 0) throw new Error("unconsumed ids");
1083
+ }
1084
+ }
1085
+ /** Dispatch one journal entry to the matching editor method; payload is passed through. */
1086
+ async function dispatchEntry(editor, entry) {
1087
+ const payload = entry.payload;
1088
+ const options = entry.intent != null ? { intent: entry.intent } : void 0;
1089
+ switch (entry.kind) {
1090
+ case "MoveVideoClips":
1091
+ await editor.moveVideoClips(payload, options);
1092
+ return;
1093
+ case "DeleteVideoClips":
1094
+ await editor.deleteVideoClips(payload, options);
1095
+ return;
1096
+ case "AddVideoClips":
1097
+ await editor.addVideoClips(payload, options);
1098
+ return;
1099
+ case "AdjustVideoClipVolume":
1100
+ await editor.adjustVideoClipVolume(payload, options);
1101
+ return;
1102
+ case "SetVideoClipSpeedShift":
1103
+ await editor.setVideoClipSpeedShift(payload, options);
1104
+ return;
1105
+ case "ReplaceVideoClipContent":
1106
+ await editor.replaceVideoClipContent(payload, options);
1107
+ return;
1108
+ case "AdjustVideoClipDuration":
1109
+ await editor.adjustVideoClipDuration(payload, options);
1110
+ return;
1111
+ case "AddSpeeches":
1112
+ await editor.addSpeeches(payload, options);
1113
+ return;
1114
+ case "DeleteSpeeches":
1115
+ await editor.deleteSpeeches(payload, options);
1116
+ return;
1117
+ case "MoveSpeeches":
1118
+ await editor.moveSpeeches(payload, options);
1119
+ return;
1120
+ case "ChangeSpeechScript":
1121
+ await editor.changeSpeechScript(payload, options);
1122
+ return;
1123
+ case "ChangeSpeechVoice":
1124
+ await editor.changeSpeechVoice(payload, options);
1125
+ return;
1126
+ case "AdjustSpeechVolume":
1127
+ await editor.adjustSpeechVolume(payload, options);
1128
+ return;
1129
+ case "SetCaptionVisibility":
1130
+ await editor.setCaptionVisibility(payload, options);
1131
+ return;
1132
+ case "SetCaptionStyle":
1133
+ await editor.setCaptionStyle(payload, options);
1134
+ return;
1135
+ case "SetBgm":
1136
+ await editor.setBgm(payload, options);
1137
+ return;
1138
+ case "DeleteBgm":
1139
+ await editor.deleteBgm(payload, options);
1140
+ return;
1141
+ case "AdjustBgmVolume":
1142
+ await editor.adjustBgmVolume(payload, options);
1143
+ return;
1144
+ default: {
1145
+ const _exhaustive = entry.kind;
1146
+ throw new Error(`replayJournal: unsupported kind ${String(_exhaustive)}`);
1147
+ }
1148
+ }
1149
+ }
1150
+ //#endregion
2945
1151
  //#region src/editor/types.ts
2946
1152
  /** Runtime list of the frozen, implemented kinds (for guards / introspection). */
2947
1153
  const IMPLEMENTED_SEMANTIC_OP_KINDS = [
@@ -3294,6 +1500,24 @@ var MengineDocSession = class {
3294
1500
  if (this.editorValue == null) throw new Error("mengine doc session is not started");
3295
1501
  return this.editorValue;
3296
1502
  }
1503
+ /**
1504
+ * Opaque version token of the local oplog (base64 `VersionVector.encode`).
1505
+ * Equality-comparable only: equal means no observed change (local or
1506
+ * remote-arrived) since the token was taken. Throws when not started.
1507
+ */
1508
+ version() {
1509
+ if (this.adapterValue == null) throw new Error("mengine doc session is not started");
1510
+ return bytesToBase64(this.adapterValue.doc.oplogVersion().encode());
1511
+ }
1512
+ /**
1513
+ * The live document adapter, exposed for journal replay (commit channel).
1514
+ * Replaying through it still goes SemanticEditor → Loro → mengine-server —
1515
+ * no write bypass. Typed by the narrow interface on purpose.
1516
+ */
1517
+ get documentAdapter() {
1518
+ if (this.adapterValue == null) throw new Error("mengine doc session is not started");
1519
+ return this.adapterValue;
1520
+ }
3297
1521
  /** Current document snapshot (read model). */
3298
1522
  snapshot() {
3299
1523
  if (this.adapterValue == null) throw new Error("mengine doc session is not started");
@@ -3380,4 +1604,4 @@ var MengineDocSession = class {
3380
1604
  }
3381
1605
  };
3382
1606
  //#endregion
3383
- export { IMPLEMENTED_SEMANTIC_OP_KINDS, MedeoHttpDocStorage, MemoryDocStorage, MengineDocSession, MengineHttpClient, MengineHttpRequestError, MirrorVideoDocumentAdapter, SchemaValidator, SemanticEditor, TIMELINE_SKELETON_DURATION_MS, VIDEO_DOCUMENT_SCHEMA_VERSION, ValidationError, VideoDocumentValidationError, arrangeMainTrackSeamlessly, assertValidVideoDocument, base64ToBytes, buildSpeechHostMap, bytesToBase64, cascadeAfterVideoClipChanges, createMirrorVideoDocument, createMirrorVideoDocumentAdapter, derivePositionFromAbs, ensureLaneTrack, fillMainTrackTimeGaps, findLaneTrack, fromVideoDocument, generatePartId, getAt, hostForAbsMs, isEmptyVideoClip, isImplementedSemanticOpKind, isMap, mainTrackRanges, partDurationMs, partUnionSchema, readMainTrackItems, readMengineEventStream, readPart, readPartDurationMs, readVideoDocumentFromDraft, reassignSpeechesToVideoClipsByTime, recalculateTimelineDuration, relativePositionForAbs, resolveAllSpeechOverlaps, resolveSpeechOverlapByShiftingVideos, safeDurationMs, schemas_exports as schemas, snapshotToPlain, solveVideoDocument, syncAggregatedClipsTimePosition, toVideoDocument, validateVideoDocument, videoDocumentMirrorSchema, videoDocumentSchema };
1607
+ export { IMPLEMENTED_SEMANTIC_OP_KINDS, MedeoHttpDocStorage, MemoryDocStorage, MengineDocSession, MengineHttpClient, MengineHttpRequestError, MirrorVideoDocumentAdapter, PlainMemoryAdapter, SchemaValidator, SemanticEditor, TIMELINE_SKELETON_DURATION_MS, VIDEO_DOCUMENT_SCHEMA_VERSION, ValidationError, VideoDocumentValidationError, arrangeMainTrackSeamlessly, assertValidVideoDocument, base64ToBytes, buildSpeechHostMap, bytesToBase64, cascadeAfterVideoClipChanges, createEditSandbox, createMirrorVideoDocument, createMirrorVideoDocumentAdapter, createPlainMemoryAdapter, derivePositionFromAbs, effectiveVideoClipDurationMs, ensureLaneTrack, fillMainTrackTimeGaps, findLaneTrack, fromVideoDocument, generatePartId, getAt, hostForAbsMs, isEmptyVideoClip, isImplementedSemanticOpKind, isMap, mainTrackRanges, partDurationMs, partUnionSchema, readMainTrackItems, readMengineEventStream, readPart, readPartDurationMs, readVideoDocumentFromDraft, reassignSpeechesToVideoClipsByTime, recalculateTimelineDuration, relativePositionForAbs, replayJournal, resolveAllSpeechOverlaps, resolveSpeechOverlapByShiftingVideos, safeDurationMs, schemas_exports as schemas, snapshotToPlain, solveVideoDocument, speedOf, syncAggregatedClipsTimePosition, toVideoDocument, validateVideoDocument, videoDocumentMirrorSchema, videoDocumentSchema, writeVideoDocumentToDraft };