@mengine/medeo-client 2.0.1-alpha.9 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4662 +0,0 @@
1
- import { u as volumeSchema } from "./shared-iWnU2osE.js";
2
- import { Mirror, schema, validateSchema } from "loro-mirror";
3
- import { z } from "zod";
4
- import { LoroDoc, LoroMap, LoroMovableList, LoroText, UndoManager } from "loro-crdt";
5
- import { sha256 } from "@noble/hashes/sha2.js";
6
- import { bytesToHex } from "@noble/hashes/utils.js";
7
- import { produce } from "immer";
8
- //#region src/client/base64.ts
9
- function bytesToBase64(bytes) {
10
- const native = bytes.toBase64;
11
- if (typeof native === "function") return native.call(bytes);
12
- const chunks = [];
13
- for (let offset = 0; offset < bytes.length; offset += 8192) chunks.push(String.fromCharCode(...bytes.subarray(offset, offset + 8192)));
14
- return btoa(chunks.join(""));
15
- }
16
- function base64ToBytes(base64) {
17
- const binary = atob(base64);
18
- const bytes = new Uint8Array(binary.length);
19
- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
20
- return bytes;
21
- }
22
- //#endregion
23
- //#region src/document/mirror-schema.ts
24
- /**
25
- * Declarative `loro-mirror` schema for `VideoDocument` — the canonical structural
26
- * SSOT and live storage wire (replaces the hand-rolled `@mengine/schema`
27
- * definition + adapter, see ADR 0008).
28
- *
29
- * Mirror gives an in-memory immutable state synced to the Loro doc by declarative
30
- * diff, so the storage layer no longer hand-writes per-region reconcile or a
31
- * transaction state machine. The shapes here store only authoritative facts
32
- * (RFC 02 §6): per-item absolute time, `part_aggregations`, and total duration
33
- * are projection-derived (cascade-solved at read time), so they are absent here.
34
- *
35
- * - tracks live in a single `tracks` `LoroMovableList` keyed by track id
36
- * (reference/17 §4). Lane is expressed by each track's `parts_kind`, not by
37
- * which container it lives in; order is the movable-list order itself. There is
38
- * no `lane` / `lane_order` field, so two peers inserting tracks never collide
39
- * on an order integer — list moves are conflict-free (RFC 03 §4). The legacy
40
- * keyed-map (`LoroMapRecord` + an integer `lane_order`) and the prior three
41
- * named containers are gone; the `main` / `above` / `below` three-pane view is
42
- * rebuilt by the projection from `parts_kind`.
43
- * - each track's `items` is a `LoroMovableList` keyed by `part_id`: a part is
44
- * placed at most once per lane, so `part_id` is the stable placement identity.
45
- * Reorder diffs to a real Loro `move`, preserving per-item CRDT identity on
46
- * every lane (main and secondary alike).
47
- * - `time_position` is the authoritative positioning fact (RFC 02 §4,
48
- * reference/17 §3), carried as an opaque JSON blob string (a whole tagged-union
49
- * value, last-writer-wins). The derived `fallback_abs_ms` snapshot sits beside
50
- * it as its own number field — a separate LWW unit so a projection refresh
51
- * never clobbers a `time_position` edit.
52
- * - `part_library` values are nested `LoroMap`s: the value is a `LoroMap` with
53
- * four mutually-exclusive optional part sub-maps (`video_clip` / `speech` /
54
- * `caption` / `bgm`), each a `LoroMap` whose fields are stored as real Loro
55
- * sub-keys. This makes each field its own CRDT unit, so two peers editing
56
- * different fields of the same part (e.g. one volume, one play_out) merge
57
- * field-by-field instead of one whole-value overwrite. Field `required` mirrors
58
- * the Smithy `@required` contract (see `video_draft_comp.smithy`). `kind` is not
59
- * stored (the present sub-key names the kind); `duration_ms` is not stored (it
60
- * is derived, reference/17 §5). Nested values that the engine does not edit
61
- * field-by-field — `speed_shift` (a tagged union), `voice`, `caption_ids` — stay
62
- * as opaque JSON-blob sub-keys via `transform`. The four sub-keys are optional,
63
- * so the "exactly one part kind" union invariant is not enforced by the schema
64
- * type; it is rebuilt by `draftToPartUnion` on read and gated by zod on write.
65
- * - a caption's `style` is a mergeable child map for independent style fields.
66
- * Creation paths materialize it with the caption, even when empty, so undoing
67
- * a later style edit never removes the parent reference. Other nested maps
68
- * keep their regular container identities from creation.
69
- */
70
- /**
71
- * JSON-blob transform for an opaque, last-writer-wins value carried in a Loro
72
- * string. The field must be declared `required: false`: an absent field decodes
73
- * to `undefined` (mirror never calls `decode`/`encode` for null/undefined),
74
- * which is how we represent "no value" instead of encoding a `null` sentinel.
75
- */
76
- function jsonTransform() {
77
- return {
78
- decode: (value) => JSON.parse(value),
79
- encode: (value) => JSON.stringify(value),
80
- isEqual: "encoded-value-equality"
81
- };
82
- }
83
- const trackItem = schema.LoroMap({
84
- part_id: schema.String(),
85
- time_position: schema.String().transform(jsonTransform()),
86
- fallback_abs_ms: schema.Number({ required: false })
87
- });
88
- const track = schema.LoroMap({
89
- id: schema.String(),
90
- parts_kind: schema.String({ required: false }),
91
- is_hidden: schema.Boolean({ required: false }),
92
- items: schema.LoroMovableList(trackItem, (item) => item.part_id)
93
- });
94
- const videoClipPart = schema.LoroMap({
95
- id: schema.String(),
96
- play_in: schema.Number(),
97
- play_out: schema.Number(),
98
- volume: schema.Number(),
99
- origin_media_id: schema.String(),
100
- speed_shift: schema.String({ required: false }).transform(jsonTransform())
101
- }, { required: false });
102
- const speechPart = schema.LoroMap({
103
- id: schema.String(),
104
- media_duration_ms: schema.Number(),
105
- audio_script: schema.String(),
106
- volume: schema.Number(),
107
- audio_storage_key: schema.String(),
108
- origin_speech_id: schema.String(),
109
- voice: schema.String().transform(jsonTransform()),
110
- caption_ids: schema.String().transform(jsonTransform())
111
- }, { required: false });
112
- const captionStyle$1 = schema.LoroMap({
113
- font_id: schema.String({ required: false }),
114
- font_size: schema.Number({ required: false }),
115
- font_color: schema.String({ required: false }),
116
- font_weight: schema.Number({ required: false }),
117
- entrance_animation: schema.String({ required: false }),
118
- entrance_animation_duration_ms: schema.Number({ required: false }),
119
- stroke_color: schema.String({ required: false }),
120
- stroke_width: schema.Number({ required: false }),
121
- position_x: schema.Number({ required: false }),
122
- position_y: schema.Number({ required: false })
123
- }, { required: false });
124
- const captionPart = schema.LoroMap({
125
- display_cues: schema.String({ required: false }).transform(jsonTransform()),
126
- id: schema.String(),
127
- initial_duration_ms: schema.Number(),
128
- speech_part_id: schema.String({ required: false }),
129
- text: schema.String(),
130
- start_ms: schema.Number(),
131
- style: captionStyle$1
132
- }, {
133
- required: false,
134
- mergeableMapChildContainers: true
135
- });
136
- const bgmPart = schema.LoroMap({
137
- id: schema.String(),
138
- audio_storage_key: schema.String(),
139
- volume: schema.Number(),
140
- origin_media_id: schema.String()
141
- }, { required: false });
142
- const partValue = schema.LoroMap({
143
- video_clip: videoClipPart,
144
- speech: speechPart,
145
- caption: captionPart,
146
- bgm: bgmPart
147
- });
148
- const videoDocumentMirrorSchema = schema({
149
- timeline: schema.LoroMap({ unit_time_ms: schema.Number({ required: false }) }),
150
- tracks: schema.LoroMovableList(track, (t) => t.id),
151
- part_library: schema.LoroMapRecord(partValue)
152
- });
153
- /** Project a discriminated `PartUnion` into the draft's four-optional shape. */
154
- function partUnionToDraft(part) {
155
- if (part.video_clip != null) return { video_clip: omitKind(part.video_clip) };
156
- if (part.speech != null) return { speech: omitKind(part.speech) };
157
- if (part.caption != null) return { caption: omitKind(part.caption) };
158
- return { bgm: omitKind(part.bgm) };
159
- }
160
- /**
161
- * Rebuild a discriminated `PartUnion` from a draft part value: pick the one
162
- * present sub-key, restore its `kind`, and drop the `$cid`. Returns `undefined`
163
- * when no part sub-key is present (an empty/placeholder value).
164
- */
165
- function draftToPartUnion(value) {
166
- if (value == null) return void 0;
167
- const v = value;
168
- if (v.video_clip != null) return { video_clip: withKind(v.video_clip, "video_clip") };
169
- if (v.speech != null) return { speech: withKind(v.speech, "speech") };
170
- if (v.caption != null) return { caption: withKind(v.caption, "caption") };
171
- if (v.bgm != null) return { bgm: withKind(v.bgm, "bgm") };
172
- }
173
- /** Drop `kind` (not stored) and `$cid` from a part payload for the draft. */
174
- function omitKind(part) {
175
- const { kind: _kind, $cid: _cid, ...rest } = part;
176
- return rest;
177
- }
178
- /** Restore `kind` (and drop `$cid`) on a part sub-map read from the draft. */
179
- function withKind(part, kind) {
180
- const { $cid: _cid, ...rest } = part;
181
- return {
182
- ...rest,
183
- kind
184
- };
185
- }
186
- /** Entries of a draft record (e.g. `tracks`) with `$cid` stripped. */
187
- function recordEntries(record) {
188
- if (record == null) return [];
189
- const out = [];
190
- for (const [key, value] of Object.entries(record)) {
191
- if (key === "$cid") continue;
192
- out.push([key, value]);
193
- }
194
- return out;
195
- }
196
- //#endregion
197
- //#region src/document/types.ts
198
- /** The linear speed multiplier of a `speed_shift`, defaulting to 1 (original). */
199
- function speedOf(speedShift) {
200
- const speed = speedShift?.config?.linear?.speed;
201
- return typeof speed === "number" && Number.isFinite(speed) && speed > 0 ? speed : 1;
202
- }
203
- /**
204
- * A video clip's effective timeline duration, derived from authoritative facts
205
- * (RFC 02, `reference/16` §4, reference/17 §5): the trim window
206
- * `play_out - play_in` divided by the speed multiplier, rounded to integer ms.
207
- * `play_in` / `play_out` are optional in the IDL but every write path sets them
208
- * (defaulting to the whole media), and the legacy-ingest projection backfills the
209
- * window from a legacy `duration_ms` — so an authoritative clip always carries a
210
- * trim window and there is no stored `duration_ms` to fall back to. A clip with
211
- * neither bound yields 0. Speeds the clip up (>1× → shorter) or down (<1×).
212
- */
213
- function effectiveVideoClipDurationMs(clip) {
214
- const speed = speedOf(clip.speed_shift);
215
- const sourceMs = (clip.play_out ?? 0) - (clip.play_in ?? 0);
216
- const effective = Math.round(sourceMs / speed);
217
- return Number.isFinite(effective) && effective > 0 ? effective : 0;
218
- }
219
- /**
220
- * The `timeline.unit_time_ms` the read-view states when the document states none.
221
- *
222
- * One frame at 30fps. A document legitimately has no such fact (display
223
- * granularity is the editor's, not the timeline's), but the read-view IDL marks
224
- * the field `@required`, so the projection has to name a value. This one is a
225
- * usable granularity; `0` — which a downstream consumer had been defaulting to —
226
- * is not, and passes any `>= 0` guard on its way to an editor that cannot use it.
227
- */
228
- const DEFAULT_UNIT_TIME_MS = 33.333;
229
- //#endregion
230
- //#region src/timeline-core/types.ts
231
- /** Total document duration when there is no real content (matches FE bgm fallback). */
232
- const TIMELINE_SKELETON_DURATION_MS = 2e4;
233
- /** Empty placeholder clip marker: a video_clip part with no backing media. */
234
- function isEmptyVideoClip(part) {
235
- const clip = part?.video_clip;
236
- if (clip == null) return false;
237
- return clip.origin_media_id == null || clip.origin_media_id === "";
238
- }
239
- /** Clamp a duration to a non-negative integer (NaN/Infinity/negative → 0). */
240
- function safeDurationMs(value) {
241
- const n = Number(value);
242
- if (!Number.isFinite(n) || n <= 0) return 0;
243
- return Math.round(n);
244
- }
245
- function partDurationMs(doc, partId) {
246
- const part = doc.part_library[partId];
247
- if (part?.video_clip != null) return safeDurationMs(effectiveVideoClipDurationMs(part.video_clip));
248
- if (part?.bgm != null) return doc.timeline.duration_ms > 0 ? doc.timeline.duration_ms : TIMELINE_SKELETON_DURATION_MS;
249
- if (part?.speech != null) return safeDurationMs(part.speech.media_duration_ms);
250
- if (part?.caption != null) return safeDurationMs(part.caption.initial_duration_ms);
251
- return 0;
252
- }
253
- //#endregion
254
- //#region src/timeline-core/cascade.ts
255
- /**
256
- * Canonical timeline cascade primitives (ADR 0009).
257
- *
258
- * Single source of truth for "how an edit's connected regions move": main-track
259
- * seamless layout, aggregation position sync + reassignment, total-duration
260
- * recompute, speech-overlap resolution, gap filling. Reconciled per ADR 0009 §4:
261
- *
262
- * - product behavior follows the FE current implementation;
263
- * - all times are integer ms — positions/durations are rounded, never floated;
264
- * - function decomposition follows agent-harness (the Python-derived structure).
265
- *
266
- * Every function mutates the `TimelineDoc` in place (the editor runs them inside
267
- * one immer `transact`, so in-place edits diff correctly).
268
- */
269
- /**
270
- * Lay the main track out head-to-tail from 0, rewriting each item's
271
- * `abs_time_position`. Items whose part is missing from the library are dropped.
272
- */
273
- function arrangeMainTrackSeamlessly(doc) {
274
- const kept = [];
275
- let cursor = 0;
276
- for (const item of doc.main_track) {
277
- if (doc.part_library[item.part_id] == null) continue;
278
- item.abs_time_position = cursor;
279
- cursor += partDurationMs(doc, item.part_id);
280
- kept.push(item);
281
- }
282
- doc.main_track = kept;
283
- }
284
- /**
285
- * Sync attached parts' absolute positions from their host:
286
- * speech.abs = host_video.abs + relative_time_position
287
- * caption.abs = speech.abs + caption.start_ms
288
- */
289
- function syncAggregatedClipsTimePosition(doc) {
290
- const videoByPart = indexByPart(doc.main_track);
291
- const speechByPart = indexByPart(doc.speech_track);
292
- for (const aggregation of doc.aggregations) {
293
- const videoItem = videoByPart.get(aggregation.body_part_id);
294
- if (videoItem == null) continue;
295
- for (const attachment of aggregation.attachments) {
296
- const speechItem = speechByPart.get(attachment.part_id);
297
- if (speechItem == null) continue;
298
- speechItem.abs_time_position = videoItem.abs_time_position + attachment.relative_time_position;
299
- }
300
- }
301
- for (const captionItem of doc.caption_track) {
302
- const captionPart = doc.part_library[captionItem.part_id]?.caption;
303
- if (captionPart == null) continue;
304
- const speechItem = captionPart.speech_part_id == null ? void 0 : speechByPart.get(captionPart.speech_part_id);
305
- if (speechItem == null) continue;
306
- captionItem.abs_time_position = speechItem.abs_time_position + safeDurationMs(captionPart.start_ms);
307
- }
308
- }
309
- /**
310
- * Reassign each speech to the video clip whose time range contains its start,
311
- * rebuilding `aggregations`. A speech before the first clip or after the last
312
- * falls back to the first / last clip respectively (FE: see §4 note — FE falls
313
- * back to last only; we keep the harness two-sided fallback because a speech
314
- * dragged before clip 0 belonging to the last clip is clearly wrong, and the FE
315
- * single-sided rule is an acknowledged rough edge). `relative_time_position` is
316
- * clamped to a non-negative integer.
317
- */
318
- function reassignSpeechesToVideoClipsByTime(doc) {
319
- const ranges = doc.main_track.filter((item) => doc.part_library[item.part_id] != null).map((item) => ({
320
- part_id: item.part_id,
321
- start: item.abs_time_position,
322
- end: item.abs_time_position + partDurationMs(doc, item.part_id)
323
- }));
324
- if (ranges.length === 0) {
325
- doc.aggregations = [];
326
- return;
327
- }
328
- const rebuilt = /* @__PURE__ */ new Map();
329
- for (const speechItem of doc.speech_track) {
330
- const start = speechItem.abs_time_position;
331
- const targetRange = ranges.find((r) => r.start <= start && start < r.end) ?? (start < ranges[0].start ? ranges[0] : ranges[ranges.length - 1]);
332
- const relative = Math.max(0, Math.round(start - targetRange.start));
333
- const targetId = targetRange.part_id;
334
- let aggregation = rebuilt.get(targetId);
335
- if (aggregation == null) {
336
- aggregation = {
337
- body_part_id: targetId,
338
- attachments: []
339
- };
340
- rebuilt.set(targetId, aggregation);
341
- }
342
- aggregation.attachments.push({
343
- part_id: speechItem.part_id,
344
- relative_time_position: relative
345
- });
346
- }
347
- doc.aggregations = ranges.map((r) => rebuilt.get(r.part_id)).filter((a) => a != null);
348
- }
349
- /**
350
- * Recompute `timeline.duration_ms` as the max end (abs + duration) across main,
351
- * speech, and caption lanes (BGM does not extend the timeline).
352
- *
353
- * BGM has no authoritative duration (RFC 02 / `reference/16` §0b): its effective
354
- * length is always the timeline total, so it is not written back here — the
355
- * projection derives it from `timeline.duration_ms` on read (`partDurationMs`
356
- * returns the timeline total for a bgm part). The empty-document 20s skeleton is
357
- * applied at that read step, not stored.
358
- */
359
- function recalculateTimelineDuration(doc) {
360
- const max = Math.max(laneEndMs(doc, doc.main_track), laneEndMs(doc, doc.speech_track), laneEndMs(doc, doc.caption_track));
361
- doc.timeline.duration_ms = max;
362
- }
363
- /**
364
- * Resolve one speech overlap by shifting the overlapping speech's host video
365
- * (and every clip after it) right. Returns true when one overlap was resolved;
366
- * callers loop until it returns false. The compared range is the speech merged
367
- * with its captions: start = min(speech.start, captions.start) (FE behavior),
368
- * end = max(speech.end, captions.end).
369
- */
370
- function resolveSpeechOverlapByShiftingVideos(doc) {
371
- const speeches = doc.speech_track;
372
- for (let i = 1; i < speeches.length; i++) {
373
- const prev = speechWithCaptionsRange(doc, speeches[i - 1]);
374
- const curr = speechWithCaptionsRange(doc, speeches[i]);
375
- if (prev == null || curr == null) continue;
376
- if (curr.start >= prev.end) continue;
377
- const overlapMs = Math.round(prev.end - curr.start);
378
- const hostId = hostVideoOf(doc, speeches[i].part_id);
379
- if (hostId == null) continue;
380
- const fromIndex = doc.main_track.findIndex((item) => item.part_id === hostId);
381
- if (fromIndex < 0) continue;
382
- for (let idx = fromIndex; idx < doc.main_track.length; idx++) doc.main_track[idx].abs_time_position += overlapMs;
383
- syncAggregatedClipsTimePosition(doc);
384
- return true;
385
- }
386
- return false;
387
- }
388
- /**
389
- * Resolve speech overlaps for one cascade pass. Mirrors the authoritative FE
390
- * `ensureNoOverlappingClips`, which is documented to resolve AT MOST ONE overlap
391
- * per cascade and is invoked exactly once at every FE call site — the supported
392
- * ops each produce at most one new overlap. It is NOT a fixpoint loop: shifting a
393
- * host right also moves every speech anchored to it, so two speeches sharing a
394
- * host can never be separated by shifting. Looping to a "fixed point" there does
395
- * not converge — it accumulates the same overlap every iteration and pushes the
396
- * clip arbitrarily far right (e.g. a sped-up clip landing at ~287k ms instead of
397
- * its seamless slot). A single pass matches FE product behavior and terminates.
398
- */
399
- function resolveAllSpeechOverlaps(doc) {
400
- resolveSpeechOverlapByShiftingVideos(doc);
401
- }
402
- /**
403
- * Make the main track gapless by adjusting/merging empty placeholder clips or
404
- * inserting new ones between real clips. Mirrors the harness four-case rule, but
405
- * the merge of two adjacent empty clips keeps the earlier clip (harness Case 4).
406
- * Requires `makeEmptyPart` to mint a placeholder part (the editor supplies an
407
- * id generator).
408
- */
409
- function fillMainTrackTimeGaps(doc, makeEmptyPart) {
410
- const items = doc.main_track;
411
- let i = 0;
412
- while (i < items.length) {
413
- const current = items[i];
414
- const currentPart = doc.part_library[current.part_id];
415
- if (currentPart == null) {
416
- i += 1;
417
- continue;
418
- }
419
- const currentEnd = current.abs_time_position + partDurationMs(doc, current.part_id);
420
- if (i + 1 >= items.length) break;
421
- const next = items[i + 1];
422
- const nextPart = doc.part_library[next.part_id];
423
- if (nextPart == null) {
424
- i += 1;
425
- continue;
426
- }
427
- const gap = next.abs_time_position - currentEnd;
428
- if (gap > 0) {
429
- if (isEmptyVideoClip(currentPart)) {
430
- extendEmptyClip(currentPart.video_clip, gap);
431
- continue;
432
- }
433
- if (isEmptyVideoClip(nextPart)) {
434
- next.abs_time_position -= gap;
435
- extendEmptyClip(nextPart.video_clip, gap);
436
- i += 1;
437
- continue;
438
- }
439
- const { partId } = makeEmptyPart(gap);
440
- doc.part_library[partId] = { video_clip: {
441
- id: partId,
442
- kind: "video_clip",
443
- play_in: 0,
444
- play_out: gap,
445
- volume: 0,
446
- origin_media_id: ""
447
- } };
448
- items.splice(i + 1, 0, {
449
- part_id: partId,
450
- time_position: { mode: "sequential" },
451
- abs_time_position: currentEnd
452
- });
453
- i += 1;
454
- continue;
455
- }
456
- if (gap === 0 && isEmptyVideoClip(currentPart) && isEmptyVideoClip(nextPart)) {
457
- extendEmptyClip(currentPart.video_clip, partDurationMs(doc, next.part_id));
458
- items.splice(i + 1, 1);
459
- delete doc.part_library[next.part_id];
460
- continue;
461
- }
462
- i += 1;
463
- }
464
- }
465
- function indexByPart(items) {
466
- const map = /* @__PURE__ */ new Map();
467
- for (const item of items) map.set(item.part_id, item);
468
- return map;
469
- }
470
- function laneEndMs(doc, items) {
471
- let max = 0;
472
- for (const item of items) {
473
- if (doc.part_library[item.part_id] == null) continue;
474
- const end = item.abs_time_position + partDurationMs(doc, item.part_id);
475
- if (end > max) max = end;
476
- }
477
- return max;
478
- }
479
- function extendEmptyClip(clip, byMs) {
480
- clip.play_out = safeDurationMs(clip.play_out) + byMs;
481
- }
482
- /** speech merged with its captions: start = min, end = max. */
483
- function speechWithCaptionsRange(doc, speechItem) {
484
- const speech = doc.part_library[speechItem.part_id]?.speech;
485
- if (speech == null) return null;
486
- let start = speechItem.abs_time_position;
487
- let end = speechItem.abs_time_position + safeDurationMs(speech.media_duration_ms);
488
- for (const captionId of captionIdsOf(speech)) {
489
- const captionItem = doc.caption_track.find((item) => item.part_id === captionId);
490
- const captionPart = doc.part_library[captionId]?.caption;
491
- if (captionItem == null || captionPart == null) continue;
492
- const cStart = captionItem.abs_time_position;
493
- const cEnd = captionItem.abs_time_position + safeDurationMs(captionPart.initial_duration_ms);
494
- if (cStart < start) start = cStart;
495
- if (cEnd > end) end = cEnd;
496
- }
497
- return {
498
- start,
499
- end
500
- };
501
- }
502
- function captionIdsOf(speech) {
503
- return (speech.caption_ids ?? []).filter((id) => id != null);
504
- }
505
- function hostVideoOf(doc, speechPartId) {
506
- for (const aggregation of doc.aggregations) if (aggregation.attachments.some((att) => att.part_id === speechPartId)) return aggregation.body_part_id;
507
- return null;
508
- }
509
- //#endregion
510
- //#region src/timeline-core/entrypoints.ts
511
- /**
512
- * The full solve pipeline: arrange → sync → reassign → resolve-overlap →
513
- * fill-gaps → recalc. The single cascade the read-side projection runs; ops
514
- * never call it (they write only facts — RFC 02 §7/§10).
515
- */
516
- function cascadeAfterVideoClipChanges(doc, makeEmptyPart) {
517
- arrangeMainTrackSeamlessly(doc);
518
- syncAggregatedClipsTimePosition(doc);
519
- reassignSpeechesToVideoClipsByTime(doc);
520
- resolveAllSpeechOverlaps(doc);
521
- fillMainTrackTimeGaps(doc, makeEmptyPart);
522
- recalculateTimelineDuration(doc);
523
- }
524
- //#endregion
525
- //#region src/timeline-core/bridge.ts
526
- /**
527
- * Solve a `VideoDocument` (authoritative, position-only) into its derived
528
- * read-view: absolute time per item, `part_aggregations`, and total duration.
529
- * This is the read side of the single-directional flow — never written back.
530
- */
531
- function solveVideoDocument(document, options = {}) {
532
- const doc = videoDocumentToTimelineDoc(document);
533
- let counter = 0;
534
- const derivedFillerPartIds = /* @__PURE__ */ new Set();
535
- if (options.placementResolved === true) {
536
- assertResolvedPlacement(document);
537
- recalculateTimelineDuration(doc);
538
- } else cascadeAfterVideoClipChanges(doc, () => {
539
- const partId = `empty_${counter++}`;
540
- derivedFillerPartIds.add(partId);
541
- return { partId };
542
- });
543
- const absByPartId = /* @__PURE__ */ new Map();
544
- for (const item of doc.main_track) absByPartId.set(item.part_id, item.abs_time_position);
545
- for (const item of doc.speech_track) absByPartId.set(item.part_id, item.abs_time_position);
546
- for (const item of doc.caption_track) absByPartId.set(item.part_id, item.abs_time_position);
547
- for (const item of doc.bgm_track) absByPartId.set(item.part_id, item.abs_time_position);
548
- return {
549
- absByPartId,
550
- aggregations: doc.aggregations.map((aggregation) => ({
551
- body_part_id: aggregation.body_part_id,
552
- attachments: aggregation.attachments.map((a) => ({
553
- part_id: a.part_id,
554
- relative_time_position: a.relative_time_position
555
- }))
556
- })),
557
- durationMs: doc.timeline.duration_ms,
558
- partLibrary: doc.part_library,
559
- derivedFillerPartIds
560
- };
561
- }
562
- function videoDocumentToTimelineDoc(document) {
563
- const partLibrary = {};
564
- for (const [partId, part] of Object.entries(document.part_library ?? {})) partLibrary[partId] = part;
565
- const laneItems = (track) => (track?.items ?? []).map((item) => ({
566
- part_id: item.part_id,
567
- time_position: item.time_position,
568
- abs_time_position: seedAbs(item.time_position, item.fallback_abs_ms),
569
- fallback_abs_ms: item.fallback_abs_ms
570
- }));
571
- const tracks = document.tracks ?? [];
572
- let mainItems = [];
573
- let speechItems = [];
574
- let bgmItems = [];
575
- let captionItems = [];
576
- for (const t of tracks) switch (t.parts_kind) {
577
- case "video_clip":
578
- mainItems = mainItems.concat(laneItems(t));
579
- break;
580
- case "speech":
581
- speechItems = speechItems.concat(laneItems(t));
582
- break;
583
- case "bgm":
584
- bgmItems = bgmItems.concat(laneItems(t));
585
- break;
586
- case "caption":
587
- captionItems = captionItems.concat(laneItems(t));
588
- break;
589
- }
590
- return {
591
- main_track: mainItems,
592
- speech_track: speechItems,
593
- caption_track: captionItems,
594
- bgm_track: bgmItems,
595
- part_library: partLibrary,
596
- aggregations: seedAggregations(mainItems, speechItems),
597
- timeline: {
598
- duration_ms: 0,
599
- unit_time_ms: document.timeline?.unit_time_ms ?? 0
600
- }
601
- };
602
- }
603
- /**
604
- * Seed an item's solve-variable `abs_time_position` from its `time_position` (and
605
- * the `fallback_abs_ms` snapshot carried beside it): `absolute` → `offsetMs`;
606
- * `anchored` → `fallbackAbsMs` (last solved position, also the orphan-recovery
607
- * anchor when the host is gone); `sequential` → 0 (the cascade lays the main
608
- * track out head-to-tail). The cascade then resolves anchored items against their
609
- * host, so this seed only needs to put each item somewhere plausible for the
610
- * first reassign/overlap pass.
611
- */
612
- function seedAbs(position, fallbackAbsMs) {
613
- switch (position.mode) {
614
- case "absolute": return Math.round(position.offsetMs);
615
- case "anchored": return Math.round(fallbackAbsMs ?? 0);
616
- case "sequential": return 0;
617
- }
618
- }
619
- /**
620
- * Build the cascade `aggregations` parent-map from anchored items: an anchored
621
- * item's `anchorPartId` is the host's `part_id` (= `body_part_id`), `offsetMs`
622
- * is `relative_time_position`. Only main-track (video) hosts form aggregations;
623
- * caption→speech relations are recomputed by the cascade from `caption.start_ms`.
624
- */
625
- function seedAggregations(mainItems, speechItems) {
626
- const mainPartIds = new Set(mainItems.map((item) => item.part_id));
627
- const byHost = /* @__PURE__ */ new Map();
628
- const order = [];
629
- for (const speech of speechItems) {
630
- if (speech.time_position.mode !== "anchored") continue;
631
- const host = speech.time_position.anchorPartId;
632
- if (!mainPartIds.has(host)) continue;
633
- let aggregation = byHost.get(host);
634
- if (aggregation == null) {
635
- aggregation = {
636
- body_part_id: host,
637
- attachments: []
638
- };
639
- byHost.set(host, aggregation);
640
- order.push(host);
641
- }
642
- aggregation.attachments.push({
643
- part_id: speech.part_id,
644
- relative_time_position: speech.time_position.offsetMs
645
- });
646
- }
647
- return order.map((host) => byHost.get(host));
648
- }
649
- /**
650
- * The four lanes in top-to-bottom stack order — the order a `tracks` list holds
651
- * them in (see {@link laneRank}).
652
- *
653
- * Exported so a document can be seeded with all four lanes up front. That seed is
654
- * not cosmetic: {@link ensureLaneTrack} is find-then-mint over a `LoroMovableList`,
655
- * so two concurrent writers that each mint the same absent lane both keep their
656
- * row, and the merged document holds two tracks for one lane. For the main lane
657
- * that is fatal — `videoDocumentSchema` allows at most one `video_clip` track, so
658
- * the merged document stops being projectable at all, symmetrically on both
659
- * replicas. Pre-seeding every lane makes `ensureLaneTrack` always take its find
660
- * branch, which removes the race by construction rather than by detection.
661
- *
662
- * What closes the race is that a track with the lane's `parts_kind` EXISTS — the
663
- * lookup is by kind, not by id. So a seed is only safe if it covers every lane:
664
- * a partial seed leaves the uncovered lanes exactly as exposed as before.
665
- */
666
- const LANE_KINDS_IN_STACK_ORDER = [
667
- "caption",
668
- "video_clip",
669
- "speech",
670
- "bgm"
671
- ];
672
- /**
673
- * The conventional track id for a lane (`main_track`, `<kind>_track`). Shared by
674
- * the up-front seed and {@link ensureLaneTrack}'s lazy mint so a document's lane
675
- * ids do not depend on which of the two created the track.
676
- *
677
- * Ids are cosmetic to the merge itself — lane lookup goes by `parts_kind`, so
678
- * drifting them apart would not reopen the concurrent-mint race. They matter to
679
- * readers that address a lane by id (the FE editor's panes, fixtures), which is
680
- * why there is one convention rather than two.
681
- */
682
- function laneTrackId(kind) {
683
- return kind === "video_clip" ? "main_track" : `${kind}_track`;
684
- }
685
- /**
686
- * Lane-stacking rank for the single `tracks` list (reference/17 §4): caption
687
- * (above) sits before the video_clip main track, which sits before speech / bgm
688
- * (below). The `tracks` array is kept in this top-to-bottom order so a freshly
689
- * minted track lands in the right place and the projection's three-pane rebuild
690
- * stays deterministic.
691
- */
692
- function laneRank(kind) {
693
- switch (kind) {
694
- case "caption": return 0;
695
- case "video_clip": return 1;
696
- case "speech":
697
- case "bgm": return 2;
698
- default: return 3;
699
- }
700
- }
701
- /**
702
- * Insert a freshly-minted track into `tracks` at the position that keeps the
703
- * lane-stacking order (caption → main → speech/bgm). Inserts before the first
704
- * track whose rank is strictly greater, so same-rank tracks keep insertion order.
705
- */
706
- function insertTrackByLaneOrder(tracks, track) {
707
- const rank = laneRank(track.parts_kind);
708
- const at = tracks.findIndex((t) => laneRank(t?.parts_kind) > rank);
709
- if (at < 0) tracks.push(track);
710
- else tracks.splice(at, 0, track);
711
- }
712
- /**
713
- * Locate a lane's track row in the single `tracks` list by kind, minting an empty
714
- * row in lane-stacking order if absent (reference/17 §4: lane = `parts_kind`).
715
- * Ops use this to write authoritative items onto the right lane. The track id
716
- * comes from {@link laneTrackId}, shared with the up-front seed.
717
- *
718
- * The mint branch is a concurrency hazard, not a convenience: see
719
- * {@link LANE_KINDS_IN_STACK_ORDER}. A document seeded with all four lanes never
720
- * reaches it.
721
- */
722
- function ensureLaneTrack(draft, kind) {
723
- draft.tracks ??= [];
724
- let track = draft.tracks.find((t) => t?.parts_kind === kind);
725
- if (track == null) {
726
- track = {
727
- id: laneTrackId(kind),
728
- parts_kind: kind,
729
- is_hidden: void 0,
730
- items: []
731
- };
732
- insertTrackByLaneOrder(draft.tracks, track);
733
- }
734
- track.items ??= [];
735
- return track;
736
- }
737
- /** Find a secondary lane's track row without minting it. */
738
- function findLaneTrack(draft, kind) {
739
- return (draft.tracks ?? []).find((t) => t?.parts_kind === kind);
740
- }
741
- /**
742
- * Whether every item already states a position that can be read without running
743
- * the cascade: nothing `sequential`, and every `anchored` item carrying the
744
- * absolute landing its writer stamped. This is a verification predicate, not a
745
- * provenance test — see `SolveVideoDocumentOptions.placementResolved`.
746
- */
747
- function hasResolvedPlacement(document) {
748
- return (document.tracks ?? []).every((track) => (track.items ?? []).every((item) => item.time_position.mode !== "sequential" && (item.time_position.mode !== "anchored" || Number.isSafeInteger(item.fallback_abs_ms))));
749
- }
750
- /** A producer that claims resolved placement must actually have resolved it. */
751
- function assertResolvedPlacement(document) {
752
- if (!hasResolvedPlacement(document)) throw new Error("An entity timeline projection must contain resolved placement facts");
753
- }
754
- //#endregion
755
- //#region src/document/zod-schema.ts
756
- const partKindSchema = z.enum([
757
- "video_clip",
758
- "speech",
759
- "caption",
760
- "bgm"
761
- ]);
762
- const finiteNumber = z.number().finite();
763
- const trackItemTimePositionSchema = z.discriminatedUnion("mode", [
764
- z.object({ mode: z.literal("sequential") }).passthrough(),
765
- z.object({
766
- mode: z.literal("anchored"),
767
- anchorPartId: z.string(),
768
- offsetMs: finiteNumber
769
- }).passthrough(),
770
- z.object({
771
- mode: z.literal("absolute"),
772
- offsetMs: finiteNumber
773
- }).passthrough()
774
- ]);
775
- const trackItemSchema = z.object({
776
- part_id: z.string(),
777
- time_position: trackItemTimePositionSchema,
778
- fallback_abs_ms: finiteNumber.optional()
779
- }).passthrough();
780
- const trackSchema = z.object({
781
- id: z.string().optional(),
782
- parts_kind: partKindSchema.optional(),
783
- is_hidden: z.boolean().optional(),
784
- items: z.array(trackItemSchema).optional()
785
- }).passthrough();
786
- const speedShiftSchema = z.object({
787
- category: z.string().optional(),
788
- mode: z.string().optional(),
789
- config: z.object({ linear: z.object({ speed: finiteNumber.optional() }).passthrough().optional() }).passthrough().optional()
790
- }).passthrough();
791
- const videoClipPartSchema = z.object({
792
- id: z.string().optional(),
793
- kind: z.literal("video_clip"),
794
- duration_ms: finiteNumber.optional(),
795
- play_in: finiteNumber,
796
- play_out: finiteNumber,
797
- volume: finiteNumber,
798
- origin_media_id: z.string(),
799
- speed_shift: speedShiftSchema.optional()
800
- }).passthrough();
801
- const speechPartSchema = z.object({
802
- id: z.string().optional(),
803
- kind: z.literal("speech"),
804
- media_duration_ms: finiteNumber,
805
- duration_ms: finiteNumber.optional(),
806
- audio_script: z.string(),
807
- volume: finiteNumber,
808
- audio_storage_key: z.string(),
809
- origin_speech_id: z.string(),
810
- voice: z.unknown(),
811
- caption_ids: z.array(z.string())
812
- }).passthrough();
813
- const captionPartSchema = z.object({
814
- id: z.string().optional(),
815
- kind: z.literal("caption"),
816
- initial_duration_ms: finiteNumber,
817
- speech_part_id: z.string().optional(),
818
- text: z.string(),
819
- start_ms: finiteNumber,
820
- style: z.object({
821
- font_id: z.string().optional(),
822
- font_size: finiteNumber.optional(),
823
- font_color: z.string().optional(),
824
- font_weight: finiteNumber.optional(),
825
- entrance_animation: z.string().optional(),
826
- entrance_animation_duration_ms: finiteNumber.optional(),
827
- stroke_color: z.string().optional(),
828
- stroke_width: finiteNumber.optional(),
829
- position_x: finiteNumber.optional(),
830
- position_y: finiteNumber.optional()
831
- }).passthrough().optional()
832
- }).passthrough();
833
- const bgmPartSchema = z.object({
834
- id: z.string().optional(),
835
- kind: z.literal("bgm"),
836
- audio_storage_key: z.string(),
837
- volume: finiteNumber,
838
- origin_media_id: z.string()
839
- }).passthrough();
840
- const partUnionSchema = z.union([
841
- z.object({ video_clip: videoClipPartSchema }).passthrough(),
842
- z.object({ speech: speechPartSchema }).passthrough(),
843
- z.object({ caption: captionPartSchema }).passthrough(),
844
- z.object({ bgm: bgmPartSchema }).passthrough()
845
- ]).refine((part) => {
846
- const p = part;
847
- return [
848
- "video_clip",
849
- "speech",
850
- "caption",
851
- "bgm"
852
- ].filter((k) => p[k] != null).length === 1;
853
- }, { message: "A part_library value must have exactly one of video_clip / speech / caption / bgm" });
854
- const videoDocumentSchema = z.object({
855
- timeline: z.object({ unit_time_ms: finiteNumber.optional() }).passthrough().optional(),
856
- tracks: z.array(trackSchema).optional(),
857
- part_library: z.record(z.string(), partUnionSchema).optional()
858
- }).passthrough().refine((doc) => (doc.tracks ?? []).filter((t) => t.parts_kind === "video_clip").length <= 1, {
859
- message: "A VideoDocument may have at most one video_clip (main) track",
860
- path: ["tracks"]
861
- });
862
- //#endregion
863
- //#region src/document/validation.ts
864
- /**
865
- * Business-level schema guard for `VideoDocument` (RFC 03 §9). It is the gate
866
- * that decides whether an arbitrary value is a *legal* `VideoDocument` before it
867
- * is written into Loro — distinct from two neighbours:
868
- *
869
- * - `zod-schema.ts` (`videoDocumentSchema`) checks structure/shape only; this
870
- * file layers the business rules on top (part-kind match, reference integrity,
871
- * `position.anchorPartId` targets, value ranges, identity uniqueness).
872
- * - loro-mirror's own `validateSchema` (run on every `setState`) only checks the
873
- * storage structure, never these business invariants.
874
- *
875
- * Projection (`projection.ts`) calls `assertValidVideoDocument` before solving a
876
- * document into the legacy `VideoDraft`.
877
- */
878
- var VideoDocumentValidationError = class extends Error {
879
- issues;
880
- constructor(issues) {
881
- super(`Invalid VideoDocument: ${issues.map((issue) => issue.message).join("; ")}`);
882
- this.issues = issues;
883
- this.name = "VideoDocumentValidationError";
884
- }
885
- };
886
- /**
887
- * Assert the document is legal enough to project. Only `error`-severity issues
888
- * hard-reject; `recoverable` ones (dangling anchor / orphan, RFC 02 §11.1) are
889
- * left for the projection to heal on read and do NOT throw. Use
890
- * `validateVideoDocument` directly to inspect recoverable issues too.
891
- */
892
- function assertValidVideoDocument(document) {
893
- const blocking = validateVideoDocument(document).filter((issue) => (issue.severity ?? "error") === "error");
894
- if (blocking.length > 0) throw new VideoDocumentValidationError(blocking);
895
- }
896
- function validateVideoDocument(document) {
897
- const parsed = videoDocumentSchema.safeParse(document);
898
- if (!parsed.success) return parsed.error.issues.map((issue) => ({
899
- code: "invalid_schema",
900
- path: zodPath(issue.path),
901
- message: issue.message
902
- }));
903
- const doc = parsed.data;
904
- const issues = [];
905
- const partLibrary = doc.part_library ?? {};
906
- for (const [partId, part] of Object.entries(partLibrary)) {
907
- if (!partUnionSchema.safeParse(part).success) {
908
- issues.push({
909
- code: "unknown_part_kind",
910
- path: `/part_library/${partId}`,
911
- message: `Part "${partId}" is not a supported part union`
912
- });
913
- continue;
914
- }
915
- const wrapperKind = getPartUnionKind(part);
916
- const innerKind = getPartKind(part);
917
- if (wrapperKind != null && innerKind != null && wrapperKind !== innerKind) issues.push({
918
- code: "part_kind_mismatch",
919
- path: `/part_library/${partId}`,
920
- message: `Part "${partId}" wrapper kind "${wrapperKind}" does not match inner kind "${innerKind}"`
921
- });
922
- validatePartValues(partId, part, issues);
923
- }
924
- for (const [idx, track] of (doc.tracks ?? []).entries()) validateTrack(track, `tracks/${idx}`, partLibrary, issues, track.parts_kind === "video_clip");
925
- validateLaneTrackUniqueness(doc, issues);
926
- validateSpeechCaptionReferences(partLibrary, issues);
927
- validatePositionReferences(doc, partLibrary, issues);
928
- return issues;
929
- }
930
- /**
931
- * Report a duplicated lane: two tracks sharing the same `id`, or two secondary
932
- * tracks of the same `parts_kind`.
933
- *
934
- * Found by the Phase 6 M0/S2 concurrency probe. `ensureLaneTrack` locates a lane
935
- * by `parts_kind` and mints `<kind>_track` when absent, so two replicas that both
936
- * start without (say) a caption track each create one; `tracks` is a
937
- * `LoroMovableList`, so the merge keeps BOTH. The lane is then split across two
938
- * same-id tracks, and the projection's `find`-by-kind returns only one of them —
939
- * so an item can be authoritative yet invisible in the pane a reader looks at.
940
- *
941
- * Flagged **recoverable**, not `error`, for two reasons. It is a reachable
942
- * outcome of ordinary concurrent editing, and hard-rejecting would make an
943
- * unavoidable merge result un-projectable — the same argument §11.1 makes for
944
- * orphans. And the projection already tolerates it: `solveVideoDocument`
945
- * concatenates every track of a kind, so the cascade sees all items regardless.
946
- * The defect is a *reader-visible* split, so the right response is to surface it
947
- * (loudly, in a channel someone reads), not to block the document.
948
- *
949
- * The main track is exempt from the kind check: `parts_kind === 'video_clip'` may
950
- * legitimately appear on several tracks (the projection treats only the first as
951
- * the main pane), so only its `id` collision is reported.
952
- */
953
- function validateLaneTrackUniqueness(doc, issues) {
954
- const tracks = doc.tracks ?? [];
955
- const seenIds = /* @__PURE__ */ new Set();
956
- const seenSecondaryKinds = /* @__PURE__ */ new Set();
957
- for (const [idx, track] of tracks.entries()) {
958
- const id = track?.id;
959
- if (id != null && id !== "") if (seenIds.has(id)) issues.push({
960
- code: "duplicate_lane_track",
961
- path: `/tracks/${idx}/id`,
962
- message: `Track "tracks/${idx}" reuses track id "${id}"`,
963
- severity: "recoverable"
964
- });
965
- else seenIds.add(id);
966
- const kind = track?.parts_kind;
967
- if (kind == null || kind === "video_clip") continue;
968
- if (seenSecondaryKinds.has(kind)) issues.push({
969
- code: "duplicate_lane_track",
970
- path: `/tracks/${idx}/parts_kind`,
971
- message: `Lane "${kind}" is split across more than one track (at "tracks/${idx}")`,
972
- severity: "recoverable"
973
- });
974
- else seenSecondaryKinds.add(kind);
975
- }
976
- }
977
- /**
978
- * An `anchored` item whose `anchorPartId` no longer exists in the library is the
979
- * orphan condition (RFC 02 §4/§11.1) — e.g. a speech whose host video, or a
980
- * caption whose host speech, was concurrently deleted while this item was being
981
- * reparented in. This is flagged as a **recoverable** issue, NOT a hard error:
982
- * the projection heals it on read (the item's `fallback_abs_ms` snapshot seeds
983
- * its absolute position, then the cascade reassigns it to the nearest available
984
- * host, or it stays put as an absolute item). Reporting it here keeps the orphan
985
- * observable without blocking projection — the opposite of a hard reject, which
986
- * would make an inevitable concurrent-delete outcome un-projectable (§11.1).
987
- */
988
- function validatePositionReferences(doc, partLibrary, issues) {
989
- const tracks = (doc.tracks ?? []).map((track, idx) => ({
990
- track,
991
- path: `tracks/${idx}`
992
- }));
993
- for (const { track, path } of tracks) for (const [idx, item] of (track?.items ?? []).entries()) {
994
- if (item.time_position.mode !== "anchored") continue;
995
- if (partLibrary[item.time_position.anchorPartId] == null) issues.push({
996
- code: "invalid_position_anchor",
997
- path: `/${path}/items/${idx}/time_position/anchorPartId`,
998
- message: `Track item "${path}/${idx}" anchors to missing part "${item.time_position.anchorPartId}"`,
999
- severity: "recoverable"
1000
- });
1001
- }
1002
- }
1003
- function validatePartValues(partId, part, issues) {
1004
- const payload = part.video_clip ?? part.speech ?? part.caption ?? part.bgm ?? void 0;
1005
- if (payload == null) return;
1006
- if ("duration_ms" in payload && payload.duration_ms != null && payload.duration_ms < 0) issues.push({
1007
- code: "invalid_part_value",
1008
- path: `/part_library/${partId}/duration_ms`,
1009
- message: `Part "${partId}" has negative duration_ms`
1010
- });
1011
- if ("volume" in payload && payload.volume != null && !Number.isFinite(payload.volume)) issues.push({
1012
- code: "invalid_part_value",
1013
- path: `/part_library/${partId}/volume`,
1014
- message: `Part "${partId}" has non-finite volume`
1015
- });
1016
- if (part.video_clip != null) {
1017
- const { play_in, play_out } = part.video_clip;
1018
- if (play_in != null && play_in < 0) issues.push({
1019
- code: "invalid_part_value",
1020
- path: `/part_library/${partId}/play_in`,
1021
- message: `Video clip "${partId}" has negative play_in`
1022
- });
1023
- if (play_out != null && play_in != null && play_out < play_in) issues.push({
1024
- code: "invalid_part_value",
1025
- path: `/part_library/${partId}/play_out`,
1026
- message: `Video clip "${partId}" has play_out before play_in`
1027
- });
1028
- }
1029
- }
1030
- function validateTrack(track, path, partLibrary, issues, isMainTrack) {
1031
- if (track == null) return;
1032
- const seenPartIds = /* @__PURE__ */ new Set();
1033
- for (const [idx, item] of (track.items ?? []).entries()) {
1034
- const partId = item.part_id;
1035
- if (partId != null && partId !== "") if (seenPartIds.has(partId)) issues.push({
1036
- code: "duplicate_track_item_identity",
1037
- path: `/${path}/items/${idx}/part_id`,
1038
- message: `Track item "${path}/${idx}" reuses part_id "${partId}"`
1039
- });
1040
- else seenPartIds.add(partId);
1041
- if (partId == null || partId === "") {
1042
- issues.push({
1043
- code: "missing_part_reference",
1044
- path: `/${path}/items/${idx}/part_id`,
1045
- message: `Track item "${path}/${idx}" has no part_id`
1046
- });
1047
- continue;
1048
- }
1049
- const part = partLibrary[partId];
1050
- if (part == null) {
1051
- issues.push({
1052
- code: "missing_part_reference",
1053
- path: `/${path}/items/${idx}/part_id`,
1054
- message: `Track item "${path}/${idx}" references missing part "${partId}"`
1055
- });
1056
- continue;
1057
- }
1058
- const partKind = getPartKind(part);
1059
- if (isMainTrack && partKind !== "video_clip") issues.push({
1060
- code: "main_track_non_video_clip",
1061
- path: `/${path}/items/${idx}/part_id`,
1062
- message: `Main track item "${path}/${idx}" references non-video part "${partId}"`
1063
- });
1064
- if (track.parts_kind != null && partKind != null && track.parts_kind !== partKind) issues.push({
1065
- code: "track_kind_mismatch",
1066
- path: `/${path}/items/${idx}/part_id`,
1067
- message: `Track "${path}" expects "${track.parts_kind}" but part "${partId}" is "${partKind}"`
1068
- });
1069
- }
1070
- }
1071
- /**
1072
- * Check speech↔caption references. A reference to a *missing* part (speech's
1073
- * caption_ids → deleted caption, or caption's speech_part_id → deleted speech)
1074
- * is the orphan condition (RFC 02 §11.1): reported as **recoverable** so the
1075
- * projection can heal it on read, not block. A *back-pointer mismatch* (caption
1076
- * exists but does not point back) is data corruption, kept as a hard error.
1077
- */
1078
- function validateSpeechCaptionReferences(partLibrary, issues) {
1079
- for (const [partId, part] of Object.entries(partLibrary)) {
1080
- if (part.speech != null) for (const captionId of part.speech.caption_ids ?? []) {
1081
- const caption = partLibrary[captionId]?.caption;
1082
- if (caption == null) {
1083
- issues.push({
1084
- code: "invalid_speech_caption_reference",
1085
- path: `/part_library/${partId}/speech/caption_ids`,
1086
- message: `Speech "${partId}" references missing caption "${captionId}"`,
1087
- severity: "recoverable"
1088
- });
1089
- continue;
1090
- }
1091
- if (caption.speech_part_id !== partId) issues.push({
1092
- code: "invalid_speech_caption_reference",
1093
- path: `/part_library/${captionId}/caption/speech_part_id`,
1094
- message: `Caption "${captionId}" does not point back to speech "${partId}"`
1095
- });
1096
- }
1097
- if (part.caption != null) {
1098
- const speechId = part.caption.speech_part_id;
1099
- if (speechId != null && partLibrary[speechId]?.speech == null) issues.push({
1100
- code: "invalid_speech_caption_reference",
1101
- path: `/part_library/${partId}/caption/speech_part_id`,
1102
- message: `Caption "${partId}" references missing speech "${speechId}"`,
1103
- severity: "recoverable"
1104
- });
1105
- }
1106
- }
1107
- }
1108
- function getPartUnionKind(part) {
1109
- if (part.video_clip != null) return "video_clip";
1110
- if (part.speech != null) return "speech";
1111
- if (part.caption != null) return "caption";
1112
- if (part.bgm != null) return "bgm";
1113
- }
1114
- function getPartKind(part) {
1115
- return part.video_clip?.kind ?? part.speech?.kind ?? part.caption?.kind ?? part.bgm?.kind;
1116
- }
1117
- function zodPath(path) {
1118
- if (path.length === 0) return "/";
1119
- return `/${path.map(String).join("/")}`;
1120
- }
1121
- //#endregion
1122
- //#region src/document/projection.ts
1123
- /**
1124
- * Projection between authoritative `VideoDocument` and compatible content
1125
- * layouts (RFC 02 §5/§7). Both directions live here:
1126
- *
1127
- * - `toVideoDocument` ingests a `VideoDraft`, deriving each item's `position`
1128
- * from the legacy absolute layout + aggregations; derived values (abs time,
1129
- * `part_aggregations`, total duration) are dropped.
1130
- * - `fromVideoDocument` solves a `VideoDocument` into `VideoDraftContent` via the
1131
- * timeline-core cascade, re-deriving exactly those values.
1132
- *
1133
- * Business validation lives in `validation.ts`; `fromVideoDocument` asserts a
1134
- * valid document before solving.
1135
- */
1136
- /**
1137
- * Ingest the legacy `VideoDraft` into the authoritative `VideoDocument`,
1138
- * deriving each item's `time_position` from the legacy absolute layout +
1139
- * aggregations (RFC 02 §4/§5). Absolute time, `part_aggregations`, and total
1140
- * duration are dropped — they are re-derived by the projection.
1141
- */
1142
- function toVideoDocument(draft) {
1143
- const speechHost = buildSpeechHostMap(draft.part_aggregations);
1144
- const partLibrary = draft.part_library ?? {};
1145
- const toTrack = (track, isMain) => {
1146
- if (track == null) return void 0;
1147
- return {
1148
- id: track.id,
1149
- parts_kind: track.parts_kind,
1150
- is_hidden: track.is_hidden,
1151
- items: (track.items ?? []).map((item) => deriveItem(item, isMain, speechHost, partLibrary))
1152
- };
1153
- };
1154
- const mainTrack = toTrack(draft.main_track, true);
1155
- const tracks = [
1156
- ...(draft.above_main_tracks ?? []).map((t) => toTrack(t, false)),
1157
- ...mainTrack == null ? [] : [mainTrack],
1158
- ...(draft.below_main_tracks ?? []).map((t) => toTrack(t, false))
1159
- ];
1160
- return {
1161
- timeline: draft.timeline == null ? void 0 : { unit_time_ms: draft.timeline.unit_time_ms },
1162
- tracks,
1163
- part_library: toAuthoritativePartLibrary(draft.part_library)
1164
- };
1165
- }
1166
- /**
1167
- * Map the legacy `VideoDraft` part library into the authoritative shape
1168
- * (reference/17 §5): the authoritative parts store no derived part-level
1169
- * duration, so the read-view `duration_ms` is dropped from video / speech / bgm.
1170
- * For a caption the legacy `duration_ms` is the generation-time length, stored
1171
- * authoritatively as `initial_duration_ms`.
1172
- */
1173
- function toAuthoritativePartLibrary(partLibrary) {
1174
- if (partLibrary == null) return void 0;
1175
- const out = {};
1176
- for (const [partId, part] of Object.entries(partLibrary)) {
1177
- if (typeof part !== "object" || part == null) continue;
1178
- if (part.video_clip != null) out[partId] = { video_clip: withTrimWindowFromDuration(part.video_clip) };
1179
- else if (part.speech != null) {
1180
- const { duration_ms, rest } = splitDurationMs(part.speech);
1181
- out[partId] = { speech: {
1182
- ...rest,
1183
- media_duration_ms: rest.media_duration_ms ?? duration_ms
1184
- } };
1185
- } else if (part.caption != null) {
1186
- const { duration_ms, rest } = splitDurationMs(part.caption);
1187
- out[partId] = { caption: {
1188
- ...rest,
1189
- initial_duration_ms: rest.initial_duration_ms ?? duration_ms
1190
- } };
1191
- } else if (part.bgm != null) out[partId] = { bgm: omitDurationMs(part.bgm) };
1192
- }
1193
- return out;
1194
- }
1195
- /**
1196
- * Build a speech-host map from a part_aggregations list. Used by
1197
- * `toVideoDocument` (legacy VideoDraft → VideoDocument) to recover each speech's
1198
- * host video clip and relative offset. Aggregation items with null ids are
1199
- * skipped (malformed input tolerance).
1200
- */
1201
- function buildSpeechHostMap(aggregations) {
1202
- const map = /* @__PURE__ */ new Map();
1203
- for (const aggregation of aggregations ?? []) {
1204
- const host = aggregation.body_part_id;
1205
- if (host == null) continue;
1206
- for (const attachment of aggregation.attachments ?? []) {
1207
- if (attachment.part_id == null) continue;
1208
- map.set(attachment.part_id, {
1209
- hostPartId: host,
1210
- offsetMs: Math.round(attachment.relative_time_position ?? 0)
1211
- });
1212
- }
1213
- }
1214
- return map;
1215
- }
1216
- /**
1217
- * Derive `time_position` (and `fallbackAbsMs` for anchored items) from a legacy
1218
- * absolute time + pre-built speech-host map + part library. The three-branch
1219
- * rule (RFC 02 §4/§5, reference/17 §3):
1220
- *
1221
- * 1. main-track → `sequential`
1222
- * 2. speech/attachment (part_id in speechHost) → `anchored(host, offsetMs)`
1223
- * 3. caption (part has `speech_part_id`) → `anchored(speech, start_ms)`
1224
- * 4. everything else → `absolute(abs)`
1225
- *
1226
- * `partLibrary` values may be `PartUnion | string | undefined` (draft raw
1227
- * form); only object-typed entries are inspected for `caption`.
1228
- */
1229
- function derivePositionFromAbs(partId, abs, isMain, speechHost, partLibrary) {
1230
- if (isMain) return { timePosition: { mode: "sequential" } };
1231
- const host = speechHost.get(partId);
1232
- if (host != null) return {
1233
- timePosition: {
1234
- mode: "anchored",
1235
- anchorPartId: host.hostPartId,
1236
- offsetMs: host.offsetMs
1237
- },
1238
- fallbackAbsMs: abs
1239
- };
1240
- const part = partLibrary[partId];
1241
- const captionPart = typeof part === "object" && part != null ? part.caption : void 0;
1242
- const speechId = captionPart?.speech_part_id ?? void 0;
1243
- if (speechId != null) return {
1244
- timePosition: {
1245
- mode: "anchored",
1246
- anchorPartId: speechId,
1247
- offsetMs: Math.round(captionPart?.start_ms ?? 0)
1248
- },
1249
- fallbackAbsMs: abs
1250
- };
1251
- return { timePosition: {
1252
- mode: "absolute",
1253
- offsetMs: abs
1254
- } };
1255
- }
1256
- /** Derive one item's authoritative `time_position` from its legacy abs + aggregation. */
1257
- function deriveItem(item, isMain, speechHost, partLibrary) {
1258
- const partId = item.part_id ?? "";
1259
- const { timePosition, fallbackAbsMs } = derivePositionFromAbs(partId, Math.round(item.abs_time_position ?? 0), isMain, speechHost, partLibrary);
1260
- return fallbackAbsMs == null ? {
1261
- part_id: partId,
1262
- time_position: timePosition
1263
- } : {
1264
- part_id: partId,
1265
- time_position: timePosition,
1266
- fallback_abs_ms: fallbackAbsMs
1267
- };
1268
- }
1269
- /**
1270
- * Project `VideoDocument` into `VideoDraftContent`, solving each item's
1271
- * absolute position, the `part_aggregations`, and
1272
- * the total duration via the timeline-core cascade.
1273
- *
1274
- * The read-view is a compatibility contract, and the IDL declares
1275
- * `Timeline.unit_time_ms` and `Track.is_hidden` `@required`
1276
- * (`video_draft_comp.smithy`) — so a projection that omitted them handed every
1277
- * consumer a payload that violated the shape it claims to satisfy, leaving each
1278
- * one to invent its own default. Two already had, and they disagreed: the agent
1279
- * harness used `unit_time_ms: 0`, director used a frame at 30fps. Defaulting here
1280
- * makes the contract true at the one place that produces it.
1281
- *
1282
- * These two are defaultable because the projection knows their values on its own:
1283
- * absent `unit_time_ms` means "no display granularity was ever stated" and absent
1284
- * `is_hidden` means "this track was never hidden". `version` is NOT defaultable
1285
- * here — it belongs to Director assembly using the server envelope update_seq.
1286
- * Neither business metadata nor a revision counter belongs in content projection.
1287
- */
1288
- function fromVideoDocument(document, options = {}) {
1289
- assertValidVideoDocument(document);
1290
- const view = solveVideoDocument(document, options);
1291
- const tracks = document.tracks ?? [];
1292
- const mainTrack = tracks.find((t) => t.parts_kind === "video_clip");
1293
- const aboveTracks = tracks.filter((t) => t.parts_kind === "caption");
1294
- const belowTracks = tracks.filter((t) => t.parts_kind === "speech" || t.parts_kind === "bgm");
1295
- return {
1296
- timeline: {
1297
- duration_ms: view.durationMs,
1298
- unit_time_ms: document.timeline?.unit_time_ms ?? 33.333
1299
- },
1300
- main_track: draftTrack(mainTrack, view.absByPartId),
1301
- above_main_tracks: aboveTracks.map((t) => draftTrack(t, view.absByPartId)),
1302
- below_main_tracks: belowTracks.map((t) => draftTrack(t, view.absByPartId)),
1303
- part_aggregations: view.aggregations,
1304
- part_library: toReadViewPartLibrary(view.partLibrary, view.durationMs, view.derivedFillerPartIds)
1305
- };
1306
- }
1307
- /**
1308
- * Map the authoritative part library into the `VideoDraft` read-view shape,
1309
- * re-injecting the derived effective `duration_ms` downstream expects
1310
- * (reference/17 §5/§7) — the authoritative parts store no part-level duration:
1311
- *
1312
- * - video clip → `(play_out - play_in) / speed` (`effectiveVideoClipDurationMs`)
1313
- * - speech → its intrinsic `media_duration_ms` (no trim/speed)
1314
- * - caption → its generation-time `initial_duration_ms`
1315
- * - bgm → the timeline total (`durationMs`)
1316
- *
1317
- * Parts are deep-cloned; the engine extensions (`media_duration_ms`,
1318
- * `initial_duration_ms`) are kept alongside the injected `duration_ms`.
1319
- *
1320
- * `derivedFillerPartIds` are skipped: the solve minted them to lay the track out
1321
- * and they are not part of the document (see `fromVideoDocument`). An empty clip a
1322
- * writer placed deliberately is NOT in that set and is projected normally.
1323
- */
1324
- function toReadViewPartLibrary(partLibrary, durationMs, derivedFillerPartIds) {
1325
- const out = {};
1326
- for (const [partId, part] of Object.entries(partLibrary)) {
1327
- if (derivedFillerPartIds.has(partId)) continue;
1328
- if (part.video_clip != null) {
1329
- const clip = clone$1(part.video_clip);
1330
- out[partId] = { video_clip: {
1331
- ...clip,
1332
- duration_ms: effectiveVideoClipDurationMs(clip)
1333
- } };
1334
- } else if (part.speech != null) {
1335
- const speech = clone$1(part.speech);
1336
- out[partId] = { speech: {
1337
- ...speech,
1338
- duration_ms: speech.media_duration_ms
1339
- } };
1340
- } else if (part.caption != null) {
1341
- const caption = clone$1(part.caption);
1342
- out[partId] = { caption: {
1343
- ...caption,
1344
- duration_ms: caption.initial_duration_ms
1345
- } };
1346
- } else if (part.bgm != null) out[partId] = { bgm: {
1347
- ...clone$1(part.bgm),
1348
- duration_ms: durationMs
1349
- } };
1350
- }
1351
- return out;
1352
- }
1353
- /** Deep-clone a part payload, dropping the derived read-view `duration_ms`. */
1354
- function omitDurationMs(part) {
1355
- const { duration_ms: _drop, ...rest } = clone$1(part);
1356
- return rest;
1357
- }
1358
- /**
1359
- * Migrate a legacy video clip into the authoritative trim-window-only shape: the
1360
- * authoritative part stores no `duration_ms`, so it is dropped — but a legacy
1361
- * clip with no explicit trim window (`play_in` / `play_out` absent) would then
1362
- * compute an effective length of 0 and vanish from the layout. When that clip
1363
- * carried a legacy `duration_ms`, backfill it as the trim window (`play_in` 0,
1364
- * `play_out = duration_ms`, no speed) so the effective length is preserved, then
1365
- * drop `duration_ms`. A clip that already has a trim window keeps it verbatim.
1366
- */
1367
- function withTrimWindowFromDuration(clip) {
1368
- const stripped = omitDurationMs(clip);
1369
- if (clip.play_in != null || clip.play_out != null) return stripped;
1370
- const legacyDuration = clip.duration_ms;
1371
- if (legacyDuration == null || !Number.isFinite(legacyDuration)) return stripped;
1372
- return {
1373
- ...stripped,
1374
- play_in: 0,
1375
- play_out: legacyDuration
1376
- };
1377
- }
1378
- /** Deep-clone a part payload, returning its `duration_ms` separately from the rest. */
1379
- function splitDurationMs(part) {
1380
- const { duration_ms, ...rest } = clone$1(part);
1381
- return {
1382
- duration_ms,
1383
- rest
1384
- };
1385
- }
1386
- function draftTrack(track, absByPartId) {
1387
- if (track == null) return void 0;
1388
- return {
1389
- id: track.id,
1390
- parts_kind: track.parts_kind,
1391
- is_hidden: track.is_hidden ?? false,
1392
- items: (track.items ?? []).map((item) => ({
1393
- part_id: item.part_id,
1394
- abs_time_position: absByPartId.get(item.part_id) ?? 0
1395
- }))
1396
- };
1397
- }
1398
- function clone$1(value) {
1399
- if (Array.isArray(value)) return value.map((item) => clone$1(item));
1400
- if (value != null && typeof value === "object") {
1401
- const result = {};
1402
- for (const [key, child] of Object.entries(value)) result[key] = clone$1(child);
1403
- return result;
1404
- }
1405
- return value;
1406
- }
1407
- //#endregion
1408
- //#region src/document/initial-document.ts
1409
- /**
1410
- * Build the `VideoDocument` a newly created project starts from: the caller's
1411
- * no parts and one empty track per lane. Business facts remain in Director.
1412
- *
1413
- * The empty lane tracks are the reason this function exists rather than callers
1414
- * assembling a document inline. Lane tracks are otherwise minted lazily by the
1415
- * first op that needs one (`ensureLaneTrack`), which is find-then-mint over a
1416
- * CRDT list — so if the Agent's first generation and a user edit race on an
1417
- * empty document, each mints its own copy of the same lane and the merge keeps
1418
- * both. Two video_clip tracks violate the at-most-one-main-track rule, and the
1419
- * merged document becomes unprojectable for *every* reader (editor, render,
1420
- * share) with no winning replica to fall back on. Seeding all four lanes up
1421
- * front means `ensureLaneTrack` only ever finds, never mints, so the race cannot
1422
- * happen on a document created here.
1423
- *
1424
- * All four, not just the main lane: the secondary lanes fail less loudly (a
1425
- * duplicate pane rather than an unreadable document), but they fail by the same
1426
- * mechanism, and covering only the fatal one would leave three live races.
1427
- *
1428
- * `timeline` is left absent: `unit_time_ms` is a display concern the editor
1429
- * supplies, and total duration is derived on read (RFC 02 §6), so a new document
1430
- * has no timeline fact to state.
1431
- */
1432
- function buildInitialVideoDocument() {
1433
- return {
1434
- timeline: void 0,
1435
- tracks: emptyLaneTracks(),
1436
- part_library: {}
1437
- };
1438
- }
1439
- /** One empty track per lane, in lane-stacking order, with the conventional ids. */
1440
- function emptyLaneTracks() {
1441
- return LANE_KINDS_IN_STACK_ORDER.map((kind) => ({
1442
- id: laneTrackId(kind),
1443
- parts_kind: kind,
1444
- is_hidden: void 0,
1445
- items: []
1446
- }));
1447
- }
1448
- //#endregion
1449
- //#region ../medeo-dsl/src/entities.ts
1450
- /**
1451
- * What every known entity kind declares.
1452
- *
1453
- * `kinds` is a multi-declaration: every entry holds at the same time, the first
1454
- * naming the object and the rest the properties it shares with others. The
1455
- * order carries no priority, endpoint role, or edit sequence — an operation
1456
- * asks whether the entity declares the kind it needs, never what its "main
1457
- * type" is.
1458
- *
1459
- * `Caption` declares `Sequence` on purpose: it owns the display timing of the
1460
- * one AudioScript segment it shows, which is what admits it into a Clip.
1461
- * `Voice` declares neither `MediaFile` nor `Sequence` — it is a timbre
1462
- * identity, not playable content; a rendered voiceover is an `audio` entity.
1463
- */
1464
- const ENTITY_KINDS = Object.freeze({
1465
- axvideo: Object.freeze([
1466
- "AXVideo",
1467
- "Container",
1468
- "Sequence",
1469
- "Visual",
1470
- "Audible"
1471
- ]),
1472
- timeline: Object.freeze(["Timeline", "Container"]),
1473
- track: Object.freeze([
1474
- "Track",
1475
- "Container",
1476
- "Sequence"
1477
- ]),
1478
- clip: Object.freeze(["Clip", "Container"]),
1479
- asset: Object.freeze(["Asset"]),
1480
- video: Object.freeze([
1481
- "Video",
1482
- "MediaFile",
1483
- "Sequence",
1484
- "Visual",
1485
- "Audible"
1486
- ]),
1487
- audio: Object.freeze([
1488
- "Audio",
1489
- "MediaFile",
1490
- "Sequence",
1491
- "Audible"
1492
- ]),
1493
- image: Object.freeze([
1494
- "Image",
1495
- "MediaFile",
1496
- "Sequence",
1497
- "Visual"
1498
- ]),
1499
- voice: Object.freeze([
1500
- "Voice",
1501
- "Container",
1502
- "IPBound"
1503
- ]),
1504
- "sequence-marker": Object.freeze(["SequenceMarker"]),
1505
- viewport: Object.freeze(["Viewport"]),
1506
- "audio-script": Object.freeze(["AudioScript", "SegmentText"]),
1507
- "phonetic-script": Object.freeze(["PhoneticScript", "SegmentText"]),
1508
- caption: Object.freeze([
1509
- "Caption",
1510
- "SegmentText",
1511
- "Sequence"
1512
- ])
1513
- });
1514
- /** What a known kind declares; extension kinds declare nothing through this table. */
1515
- function kindsOf(entityKind) {
1516
- return isKnownEntityKind(entityKind) ? ENTITY_KINDS[entityKind] : [];
1517
- }
1518
- function declaresKind(entityKind, kind) {
1519
- return kindsOf(entityKind).includes(kind);
1520
- }
1521
- /**
1522
- * Sequence admission asks `kinds` first, so an entity that does not declare
1523
- * `Sequence` can never buy its way in by carrying the fields. Extension kinds
1524
- * declare nothing and stay structurally detected.
1525
- */
1526
- function hasSequence(entity) {
1527
- if (isReservedEntityKind(entity.entityKind)) return false;
1528
- if (isKnownEntityKind(entity.entityKind) && !declaresKind(entity.entityKind, "Sequence")) return false;
1529
- return isSequenceFields(entity);
1530
- }
1531
- function isSequenceFields(value) {
1532
- if (!isRecord$1(value)) return false;
1533
- const extent = value.extent;
1534
- if (!isRecord$1(extent) || !("start" in extent) || extent.start === void 0) return false;
1535
- if (extent.kind === "bounded" && (!("end" in extent) || extent.end === void 0)) return false;
1536
- if (extent.kind === "unbounded" && "end" in extent) return false;
1537
- if (extent.kind !== "bounded" && extent.kind !== "unbounded") return false;
1538
- if (value.sampling !== "native" && value.sampling !== "constant" && value.sampling !== "derived") return false;
1539
- return "coordinateSpace" in value && value.coordinateSpace !== void 0;
1540
- }
1541
- function isMediaAssetVariantKind(kind) {
1542
- return kind === "video" || kind === "image" || kind === "audio";
1543
- }
1544
- function isKnownEntityKind(kind) {
1545
- return Object.hasOwn(ENTITY_KINDS, kind);
1546
- }
1547
- function isReservedEntityKind(kind) {
1548
- const normalized = kind.toLowerCase().replaceAll("-", "").replaceAll("_", "");
1549
- return normalized === "speech" || normalized === "videodocument";
1550
- }
1551
- function isRecord$1(value) {
1552
- return typeof value === "object" && value != null && !Array.isArray(value);
1553
- }
1554
- //#endregion
1555
- //#region ../medeo-dsl/src/ids.ts
1556
- function createEntityId(value) {
1557
- return createId(value, "EntityId");
1558
- }
1559
- function createRelationId(value) {
1560
- return createId(value, "RelationId");
1561
- }
1562
- function createId(value, label) {
1563
- if (value.length === 0 || value.trim() !== value) throw new Error(`${label} must be a non-empty trimmed string`);
1564
- return value;
1565
- }
1566
- //#endregion
1567
- //#region ../medeo-dsl/src/json-values.ts
1568
- const nativeObjectConstructorSource = Function.prototype.toString.call(Object);
1569
- function isJsonObject(value) {
1570
- return typeof value === "object" && value !== null && !Array.isArray(value) && isJsonValue(value, /* @__PURE__ */ new Set());
1571
- }
1572
- function isJsonValue(value, ancestors) {
1573
- if (value === null || typeof value === "string" || typeof value === "boolean") return true;
1574
- if (typeof value === "number") return Number.isFinite(value);
1575
- if (typeof value !== "object") return false;
1576
- if (!Array.isArray(value) && !isPlainObject(value)) return false;
1577
- if (ancestors.has(value)) return false;
1578
- ancestors.add(value);
1579
- const valid = Array.isArray(value) ? value.every((item) => isJsonValue(item, ancestors)) : Object.values(value).every((item) => isJsonValue(item, ancestors));
1580
- ancestors.delete(value);
1581
- return valid;
1582
- }
1583
- /** Recognize an ordinary object from any VM realm without admitting class instances. */
1584
- function isPlainObject(value) {
1585
- try {
1586
- const prototype = Object.getPrototypeOf(value);
1587
- if (prototype === null) return true;
1588
- if (Object.getPrototypeOf(prototype) !== null) return false;
1589
- const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
1590
- return typeof constructor === "function" && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === nativeObjectConstructorSource;
1591
- } catch {
1592
- return false;
1593
- }
1594
- }
1595
- //#endregion
1596
- //#region ../medeo-dsl/src/composition.ts
1597
- /** Assembly fails explicitly when declared bases cannot provide valid, unambiguous content. */
1598
- var ScriptCompositionError = class extends Error {
1599
- code;
1600
- entityId;
1601
- constructor(code, entityId, message) {
1602
- super(message);
1603
- this.code = code;
1604
- this.entityId = entityId;
1605
- this.name = "ScriptCompositionError";
1606
- }
1607
- };
1608
- /** Direct base IDs are structural fields, never ordinary Relation endpoints. */
1609
- function variantBaseEntityIds(entity) {
1610
- if (!Object.hasOwn(entity.payload, "baseEntityIds")) return [];
1611
- const ids = entity.payload.baseEntityIds;
1612
- if (!Array.isArray(ids) || ids.length === 0 || !ids.every((id) => typeof id === "string" && id.trim() === id && id.length > 0) || new Set(ids).size !== ids.length) throw new ScriptCompositionError("invalid_bases", entity.entityId, `Entity "${entity.entityId}" requires non-empty, unique baseEntityIds`);
1613
- return ids.map(createEntityId);
1614
- }
1615
- /** Validate all base providers before applying explicit own fields; ordering cannot resolve ambiguity. */
1616
- function assembleEntityContent(rows, entityId) {
1617
- const byId = /* @__PURE__ */ new Map();
1618
- for (const row of rows.entities) {
1619
- if (byId.has(row.entityId)) throw new ScriptCompositionError("composition_ambiguous", row.entityId, `duplicate entity id "${row.entityId}"`);
1620
- byId.set(row.entityId, row);
1621
- }
1622
- const active = /* @__PURE__ */ new Set();
1623
- const cache = /* @__PURE__ */ new Map();
1624
- const visit = (id) => {
1625
- const cached = cache.get(id);
1626
- if (cached !== void 0) return cached;
1627
- if (active.has(id)) throw new ScriptCompositionError("composition_cycle", id, `Cyclic baseEntityIds at "${id}"`);
1628
- const row = byId.get(id);
1629
- if (row === void 0) throw new ScriptCompositionError("composition_dangling", id, `Missing base entity "${id}" in this document`);
1630
- if (!isJsonObject(row.payload) || Object.hasOwn(row.payload, "entityId") || Object.hasOwn(row.payload, "entityKind")) throw new ScriptCompositionError("invalid_bases", id, `Entity "${id}" requires JSON own fields without reserved identity fields`);
1631
- active.add(id);
1632
- const inherited = {};
1633
- const providers = /* @__PURE__ */ new Map();
1634
- for (const baseId of variantBaseEntityIds(row)) {
1635
- const base = visit(baseId);
1636
- for (const [field, value] of Object.entries(base.payload)) {
1637
- if (field === "baseEntityIds") continue;
1638
- const previous = providers.get(field);
1639
- if (previous !== void 0) throw new ScriptCompositionError("field_conflict", id, `Entity "${id}" field "${field}" conflicts between bases "${previous}" and "${baseId}"; own fields cannot resolve base ambiguity`);
1640
- providers.set(field, baseId);
1641
- Object.defineProperty(inherited, field, {
1642
- value,
1643
- enumerable: true,
1644
- configurable: true,
1645
- writable: true
1646
- });
1647
- }
1648
- }
1649
- const assembled = {
1650
- ...row,
1651
- payload: JSON.parse(JSON.stringify({
1652
- ...inherited,
1653
- ...row.payload
1654
- }))
1655
- };
1656
- active.delete(id);
1657
- cache.set(id, assembled);
1658
- return assembled;
1659
- };
1660
- return visit(entityId);
1661
- }
1662
- /** Resolve a field's declaring entity after validating the entire composition. */
1663
- function resolveEntityFieldOwner(rows, entityId, field) {
1664
- assembleEntityContent(rows, entityId);
1665
- const byId = new Map(rows.entities.map((row) => [row.entityId, row]));
1666
- const find = (id) => {
1667
- const row = byId.get(id);
1668
- if (Object.hasOwn(row.payload, field)) return id;
1669
- if (field === "baseEntityIds") return void 0;
1670
- for (const baseId of variantBaseEntityIds(row)) {
1671
- const owner = find(baseId);
1672
- if (owner !== void 0) return owner;
1673
- }
1674
- };
1675
- return find(entityId) ?? entityId;
1676
- }
1677
- /** Patch assembled fields without copying inherited fields into the variant's stored payload. */
1678
- function updateEntityFields(rows, entityId, fields) {
1679
- assembleEntityContent(rows, entityId);
1680
- if (!isJsonObject(fields) || Object.hasOwn(fields, "entityId") || Object.hasOwn(fields, "entityKind")) throw new ScriptCompositionError("invalid_bases", entityId, "Field updates require JSON without reserved identity fields");
1681
- const updates = /* @__PURE__ */ new Map();
1682
- for (const [field, value] of Object.entries(fields)) {
1683
- const ownerId = resolveEntityFieldOwner(rows, entityId, field);
1684
- const owner = updates.get(ownerId) ?? rows.entities.find((row) => row.entityId === ownerId);
1685
- updates.set(ownerId, {
1686
- ...owner,
1687
- payload: {
1688
- ...owner.payload,
1689
- [field]: value
1690
- }
1691
- });
1692
- }
1693
- return [...updates.values()].map((row) => JSON.parse(JSON.stringify(row)));
1694
- }
1695
- /** Find the actual AudioScript text owner through direct variant bases. */
1696
- function findComposedAudioScript(rows, variantEntityId, variantKind) {
1697
- const variant = requireEntityKind(rows, variantEntityId, variantKind);
1698
- assembleEntityContent(rows, variantEntityId);
1699
- const sources = /* @__PURE__ */ new Map();
1700
- const seen = /* @__PURE__ */ new Set();
1701
- const visit = (row) => {
1702
- for (const id of variantBaseEntityIds(row)) {
1703
- if (seen.has(id)) continue;
1704
- seen.add(id);
1705
- const base = rows.entities.find((candidate) => candidate.entityId === id);
1706
- if (base.entityKind === "audio-script") sources.set(id, assembleEntityContent(rows, id));
1707
- else visit(base);
1708
- }
1709
- };
1710
- visit(variant);
1711
- if (sources.size !== 1) throw new ScriptCompositionError(sources.size === 0 ? "composition_missing" : "composition_ambiguous", variantEntityId, `${variantKind} "${variantEntityId}" baseEntityIds must resolve one AudioScript text owner, got ${sources.size}`);
1712
- return [...sources.values()][0];
1713
- }
1714
- /** Join the whole AudioScript text in segment order. */
1715
- function assembleScriptText(script) {
1716
- return scriptSegments(script).map((segment) => segment.text).join("");
1717
- }
1718
- function scriptSegments(script) {
1719
- const segments = script.payload.segments;
1720
- if (!Array.isArray(segments)) throw new ScriptCompositionError("composition_dangling", script.entityId, `AudioScript "${script.entityId}" requires segments`);
1721
- if (!segments.every(isScriptSegment) || new Set(segments.map((s) => s.segmentId)).size !== segments.length) throw new ScriptCompositionError("invalid_script", script.entityId, "AudioScript requires valid segments with unique local segmentId and text");
1722
- return segments;
1723
- }
1724
- function isScriptSegment(value) {
1725
- if (typeof value !== "object" || value == null || Array.isArray(value)) return false;
1726
- const segment = value;
1727
- return typeof segment.segmentId === "string" && segment.segmentId.trim() !== "" && typeof segment.text === "string" && (segment.language === void 0 || typeof segment.language === "string");
1728
- }
1729
- /** Assemble selected text after base-field validation and explicit variant overrides. */
1730
- function assembleCaptionContent(rows, captionEntityId) {
1731
- requireEntityKind(rows, captionEntityId, "caption");
1732
- const caption = assembleEntityContent(rows, captionEntityId);
1733
- const script = findComposedAudioScript(rows, captionEntityId, "caption");
1734
- const selection = captionSelection(caption);
1735
- const composed = {
1736
- ...script,
1737
- payload: caption.payload
1738
- };
1739
- const segment = selectAudioScriptSegment(composed, selection);
1740
- return {
1741
- caption,
1742
- audioScript: script,
1743
- segments: [segment],
1744
- segmentIndex: scriptSegments(composed).findIndex((entry) => entry.segmentId === selection.segmentId),
1745
- text: segment.text
1746
- };
1747
- }
1748
- /**
1749
- * Assemble the complete Phonetic Script content for TTS: the composed
1750
- * AudioScript's base text plus the variant's own phoneme and prosody fields.
1751
- */
1752
- function assemblePhoneticScriptContent(rows, phoneticScriptEntityId) {
1753
- requireEntityKind(rows, phoneticScriptEntityId, "phonetic-script");
1754
- const phoneticScript = assembleEntityContent(rows, phoneticScriptEntityId);
1755
- const audioScript = findComposedAudioScript(rows, phoneticScriptEntityId, "phonetic-script");
1756
- const segments = scriptSegments({
1757
- ...audioScript,
1758
- payload: phoneticScript.payload
1759
- });
1760
- return {
1761
- phoneticScript,
1762
- audioScript,
1763
- segments,
1764
- text: segments.map((segment) => segment.text).join("")
1765
- };
1766
- }
1767
- function captionSelection(caption) {
1768
- if (Object.hasOwn(caption.payload, "selections") || !isSegmentSelection(caption.payload.selection)) throw new ScriptCompositionError("invalid_selection", caption.entityId, "Caption requires one selection object with segmentId and optional textRange; selections arrays are forbidden");
1769
- return caption.payload.selection;
1770
- }
1771
- function isSegmentSelection(value) {
1772
- return typeof value === "object" && value != null && !Array.isArray(value) && typeof value.segmentId === "string" && value.segmentId.trim() !== "" && Object.keys(value).every((key) => key === "segmentId" || key === "textRange");
1773
- }
1774
- /** Select source text without creating another authoritative text field. */
1775
- function selectAudioScriptSegment(script, selection) {
1776
- if (!isSegmentSelection(selection)) throw new ScriptCompositionError("invalid_selection", script.entityId, "Caption requires one selection object with segmentId and optional textRange");
1777
- const bySegmentId = new Map(scriptSegments(script).map((segment) => [segment.segmentId, segment]));
1778
- const selected = (() => {
1779
- const segment = bySegmentId.get(selection.segmentId);
1780
- if (segment === void 0) throw new ScriptCompositionError("unknown_segment", script.entityId, `Caption selection "${selection.segmentId}" does not name a segment of AudioScript "${script.entityId}"`);
1781
- if (selection.textRange === void 0) return segment;
1782
- const range = selection.textRange;
1783
- const points = Array.from(segment.text);
1784
- if (typeof range !== "object" || range === null || !Number.isSafeInteger(range.start) || !Number.isSafeInteger(range.end) || range.start < 0 || range.end <= range.start || range.end > points.length || Object.keys(range).some((key) => key !== "start" && key !== "end")) throw new ScriptCompositionError("invalid_selection", script.entityId, "Caption textRange must be a non-empty half-open Unicode code-point range within its source segment");
1785
- return {
1786
- ...segment,
1787
- text: points.slice(range.start, range.end).join("")
1788
- };
1789
- })();
1790
- if (!selected.text.trim()) throw new ScriptCompositionError("empty_selection", script.entityId, "Caption selection must contain visible source text");
1791
- return selected;
1792
- }
1793
- function requireEntityKind(rows, entityIdValue, entityKind) {
1794
- const entity = rows.entities.find((candidate) => candidate.entityId === entityIdValue);
1795
- if (entity === void 0) throw new ScriptCompositionError("composition_dangling", entityIdValue, `Entity "${entityIdValue}" does not exist`);
1796
- if (entity.entityKind !== entityKind) throw new ScriptCompositionError("composition_dangling", entityIdValue, `Entity "${entityIdValue}" must have kind "${entityKind}", got "${entity.entityKind}"`);
1797
- return entity;
1798
- }
1799
- //#endregion
1800
- //#region ../medeo-dsl/src/rows.ts
1801
- function entityToRow(entity) {
1802
- const { entityId, entityKind, ...payload } = entity;
1803
- if (!isJsonObject(payload)) throw new Error(`Entity "${entityId}" payload must contain only JSON values`);
1804
- return {
1805
- entityId,
1806
- entityKind,
1807
- payload
1808
- };
1809
- }
1810
- //#endregion
1811
- //#region ../medeo-dsl/src/invariants.ts
1812
- /**
1813
- * Media variants own their Asset identity directly: a `physical-asset`
1814
- * Relation may not bind them. Caption may associate with a physical text Asset
1815
- * independently of its AudioScript composition.
1816
- */
1817
- function validateMediaAssetIdentity(entity, index) {
1818
- return [...index.relationsOf(entity)].filter((relation) => relation.kind === "physical-asset").map(() => ({
1819
- code: "media_physical_asset_forbidden",
1820
- entityId: entity.entityId,
1821
- message: `Media entity "${entity.entityId}" owns its Asset identity; remove its physical-asset Relation`
1822
- }));
1823
- }
1824
- /** Validates one complete set of entities and its authoritative Relation rows. */
1825
- function validateEntityRelationSet(entityRefs, index, options) {
1826
- const { entities, issues } = collectRelatedEntities(entityRefs, index);
1827
- const entityIds = new Set(entities.map((entity) => entity.entityId));
1828
- const rows = {
1829
- entities: entities.map((entity) => entityToRow(entity.current())),
1830
- relations: []
1831
- };
1832
- for (const entity of entities) try {
1833
- assembleEntityContent(rows, entity.entityId);
1834
- } catch (error) {
1835
- issues.push({
1836
- code: "invalid_variant_composition",
1837
- entityId: entity.entityId,
1838
- message: error instanceof Error ? error.message : "Invalid variant composition"
1839
- });
1840
- }
1841
- for (const entity of entities) {
1842
- const current = entity.current();
1843
- const entityIssues = validateEntity(entity, entityIds);
1844
- issues.push(...entityIssues);
1845
- if (isMediaAssetVariantKind(current.entityKind)) issues.push(...validateMediaAssetIdentity(entity, index));
1846
- if (entityIssues.some((issue) => issue.code === "invalid_entity_payload")) continue;
1847
- if (current.entityKind === "sequence-marker") {
1848
- const marker = entity;
1849
- issues.push(...validateMarkerUse(entity, index));
1850
- issues.push(...validateMarkerRanges(marker, {
1851
- source: (left, right) => options.compareMarkerPoints(marker, "source", left, right),
1852
- target: (left, right) => options.compareMarkerPoints(marker, "target", left, right)
1853
- }));
1854
- issues.push(...validateMarkerSourceBounds(marker, index, (left, right) => options.compareMarkerPoints(marker, "source", left, right)));
1855
- }
1856
- if (current.entityKind === "clip") {
1857
- issues.push(...validateClipAdmission(entity, index));
1858
- issues.push(...validateClipPlacement(entity, index));
1859
- }
1860
- if (current.entityKind === "axvideo") issues.push(...validateAXVideoAdmission(entity, index));
1861
- if (current.entityKind === "caption") issues.push(...validateCaptionComposition(entity, index, entities));
1862
- if (current.entityKind === "phonetic-script") issues.push(...validatePhoneticComposition(entity, index, entities));
1863
- issues.push(...validateSequenceComposition(entity));
1864
- }
1865
- issues.push(...validateClipAnchorCycles(entities, index));
1866
- return issues;
1867
- }
1868
- function validateMarkerUse(marker, index) {
1869
- const relations = [...index.relationsOf(marker)];
1870
- const clipEdges = ofKind(relations, "clip-marker");
1871
- const axVideoEdges = ofKind(relations, "axvideo-marker");
1872
- const contentEdges = ofKind(relations, "marker-content");
1873
- const timelineEdges = ofKind(relations, "marker-timeline");
1874
- const scriptEdges = ofKind(relations, "audio-script-marker");
1875
- const issues = [];
1876
- if (scriptEdges.length > 0) {
1877
- if (clipEdges.length + axVideoEdges.length + contentEdges.length + timelineEdges.length > 0) issues.push({
1878
- code: "marker_container_xor",
1879
- entityId: marker.entityId,
1880
- message: "An AudioScript annotation Marker must not carry Clip, AXVideo, content, or Timeline relations"
1881
- });
1882
- const ranges = marker.current().segmentRanges;
1883
- if (!ranges?.length) issues.push({
1884
- code: "invalid_entity_payload",
1885
- entityId: marker.entityId,
1886
- message: "An AudioScript annotation Marker requires segmentRanges"
1887
- });
1888
- for (const relation of scriptEdges) {
1889
- const script = relation.other(marker)?.deref()?.current();
1890
- if (script?.entityKind !== "audio-script") continue;
1891
- const segments = script.segments;
1892
- if (!Array.isArray(segments)) continue;
1893
- const segmentIds = new Set(segments.map((segment) => segment.segmentId));
1894
- if (ranges?.some((range) => !segmentIds.has(range.segmentId))) issues.push({
1895
- code: "invalid_entity_payload",
1896
- entityId: marker.entityId,
1897
- message: "Annotation segmentRanges must name segments of the related AudioScript"
1898
- });
1899
- }
1900
- return issues;
1901
- }
1902
- if (marker.current().segmentRanges !== void 0) issues.push({
1903
- code: "invalid_entity_payload",
1904
- entityId: marker.entityId,
1905
- message: "segmentRanges belongs to an AudioScript annotation Marker, not a display Marker"
1906
- });
1907
- if (clipEdges.length + axVideoEdges.length !== 1) issues.push({
1908
- code: "marker_container_xor",
1909
- entityId: marker.entityId,
1910
- message: "Sequence Marker must have exactly one Clip XOR AXVideo container relation"
1911
- });
1912
- if (contentEdges.length + timelineEdges.length !== 1) issues.push({
1913
- code: "marker_content_xor",
1914
- entityId: marker.entityId,
1915
- message: "Sequence Marker must have exactly one Sequence content XOR Timeline relation"
1916
- });
1917
- if (clipEdges.length === 1 && timelineEdges.length === 1 || axVideoEdges.length === 1 && contentEdges.length === 1) issues.push({
1918
- code: "marker_pair_mismatch",
1919
- entityId: marker.entityId,
1920
- message: "Only Clip+Content or AXVideo+Timeline Marker relation pairs are valid"
1921
- });
1922
- return issues;
1923
- }
1924
- function validateClipAdmission(clip, index) {
1925
- const markerEdges = ofKind([...index.relationsOf(clip)], "clip-marker");
1926
- if (markerEdges.length !== 1) return [{
1927
- code: "clip_marker_cardinality",
1928
- entityId: clip.entityId,
1929
- message: "Clip must have exactly one authoritative Clip-Marker Relation"
1930
- }];
1931
- const marker = markerEdges[0]?.other(clip)?.deref();
1932
- if (marker == null) return [{
1933
- code: "clip_content_cardinality",
1934
- entityId: clip.entityId,
1935
- message: "Clip must resolve one live Sequence Marker and one content Relation"
1936
- }];
1937
- const contentEdges = ofKind([...index.relationsOf(marker)], "marker-content");
1938
- if (contentEdges.length !== 1) return [{
1939
- code: "clip_content_cardinality",
1940
- entityId: clip.entityId,
1941
- message: "Clip Marker must resolve exactly one content Relation"
1942
- }];
1943
- const content = contentEdges[0]?.other(marker)?.deref()?.current();
1944
- if (content == null) return [{
1945
- code: "clip_content_cardinality",
1946
- entityId: clip.entityId,
1947
- message: "Clip Marker content Relation must resolve one live entity"
1948
- }];
1949
- if (!hasSequence(content)) return [{
1950
- code: "clip_content_not_sequence",
1951
- entityId: clip.entityId,
1952
- message: `Clip Marker resolves to non-Sequence entity "${content.entityId}"`
1953
- }];
1954
- return [];
1955
- }
1956
- function validateAXVideoAdmission(axVideo, index) {
1957
- const markerEdges = ofKind([...index.relationsOf(axVideo)], "axvideo-marker");
1958
- if (markerEdges.length === 1 && markerEdges[0]?.other(axVideo)?.deref() != null) return [];
1959
- return [{
1960
- code: "axvideo_marker_cardinality",
1961
- entityId: axVideo.entityId,
1962
- message: "AXVideo must have exactly one live AXVideo-Marker Relation"
1963
- }];
1964
- }
1965
- /** Validate a Caption against the complete entity set, including its directly held bases. */
1966
- function validateCaptionComposition(caption, index, entities = []) {
1967
- return validateVariantComposition(caption, index, entities, "caption");
1968
- }
1969
- function validatePhoneticComposition(phonetic, index, entities = []) {
1970
- return validateVariantComposition(phonetic, index, entities, "phonetic-script");
1971
- }
1972
- function validateVariantComposition(variant, index, entities, kind) {
1973
- const issues = [];
1974
- const rows = {
1975
- entities: collectRelatedEntities([...entities, variant], index).entities.map((ref) => entityToRow(ref.current())),
1976
- relations: []
1977
- };
1978
- try {
1979
- if (kind === "caption") assembleCaptionContent(rows, variant.entityId);
1980
- else assemblePhoneticScriptContent(rows, variant.entityId);
1981
- } catch (error) {
1982
- issues.push({
1983
- code: kind === "caption" ? "caption_composition_required" : "phonetic_script_composition_required",
1984
- entityId: variant.entityId,
1985
- message: error instanceof Error ? error.message : "Invalid variant composition"
1986
- });
1987
- }
1988
- return issues;
1989
- }
1990
- function validateClipPlacement(clip, index) {
1991
- const marker = ofKind([...index.relationsOf(clip)], "clip-marker")[0]?.other(clip)?.deref();
1992
- if (marker?.current().entityKind !== "sequence-marker") return [];
1993
- const markerValue = marker.current();
1994
- const anchors = ofKind([...index.relationsOf(clip)], "clip-anchor").filter((relation) => relation.endpoints[0].deref() === clip);
1995
- const hasOrder = clip.current().order !== void 0;
1996
- const hasTarget = markerValue.targetRange !== void 0;
1997
- const hasAnchorOffset = markerValue.anchorOffset !== void 0;
1998
- const issues = [];
1999
- if (anchors.length > 1) issues.push({
2000
- code: "clip_anchor_cardinality",
2001
- entityId: clip.entityId,
2002
- message: "A Clip may follow at most one host Clip"
2003
- });
2004
- const hasAnchor = anchors.length === 1;
2005
- if (hasAnchor && (!hasAnchorOffset || hasOrder || hasTarget) || !hasAnchor && (hasAnchorOffset || Number(hasOrder) + Number(hasTarget) !== 1)) issues.push({
2006
- code: "clip_placement_invalid",
2007
- entityId: clip.entityId,
2008
- message: "Clip placement must be exactly one of Clip.order, Marker.targetRange, or clip-anchor with Marker.anchorOffset"
2009
- });
2010
- if (markerValue.durationPolicy === "timeline") {
2011
- const content = ofKind([...index.relationsOf(marker)], "marker-content")[0]?.other(marker)?.deref()?.current();
2012
- const track = ofKind([...index.relationsOf(clip)], "track-clip")[0]?.other(clip)?.deref()?.current();
2013
- const trackRole = track?.entityKind === "track" ? track.role : void 0;
2014
- if (content?.entityKind !== "audio" || trackRole !== "bgm" || !hasOrder && !hasTarget) issues.push({
2015
- code: "timeline_duration_policy_invalid",
2016
- entityId: marker.entityId,
2017
- message: "Marker durationPolicy \"timeline\" is only valid for ordered or absolutely placed Audio Clips on the bgm Track"
2018
- });
2019
- }
2020
- return issues;
2021
- }
2022
- function validateClipAnchorCycles(entities, index) {
2023
- const hostByChild = /* @__PURE__ */ new Map();
2024
- for (const entity of entities) {
2025
- if (entity.current().entityKind !== "clip") continue;
2026
- for (const relation of ofKind([...index.relationsOf(entity)], "clip-anchor")) {
2027
- if (relation.endpoints[0].deref() !== entity) continue;
2028
- const host = relation.endpoints[1].deref();
2029
- if (host != null) hostByChild.set(entity.entityId, host.entityId);
2030
- }
2031
- }
2032
- const issues = [];
2033
- for (const child of hostByChild.keys()) {
2034
- const seen = /* @__PURE__ */ new Set();
2035
- let current = child;
2036
- while (current !== void 0 && !seen.has(current)) {
2037
- seen.add(current);
2038
- current = hostByChild.get(current);
2039
- }
2040
- if (current === void 0) continue;
2041
- issues.push({
2042
- code: "clip_anchor_cycle",
2043
- entityId: child,
2044
- message: "clip-anchor Relations must form an acyclic dependency graph"
2045
- });
2046
- }
2047
- return issues;
2048
- }
2049
- function validateMarkerRanges(marker, compare) {
2050
- const current = marker.current();
2051
- const issues = [];
2052
- if (!(compare.source(current.sourceRange.start, current.sourceRange.end) < 0)) issues.push({
2053
- code: "marker_source_range_empty",
2054
- entityId: marker.entityId,
2055
- message: "Sequence Marker sourceRange must be a non-empty half-open interval"
2056
- });
2057
- if (current.targetRange != null && !(compare.target(current.targetRange.start, current.targetRange.end) < 0)) issues.push({
2058
- code: "marker_target_range_empty",
2059
- entityId: marker.entityId,
2060
- message: "Sequence Marker targetRange must be a non-empty half-open interval"
2061
- });
2062
- return issues;
2063
- }
2064
- function validateMarkerSourceBounds(marker, index, compare) {
2065
- const contentEdges = ofKind([...index.relationsOf(marker)], "marker-content");
2066
- if (contentEdges.length !== 1) return [];
2067
- const content = contentEdges[0]?.other(marker)?.deref()?.current();
2068
- if (content == null || !hasSequence(content)) return [];
2069
- const sourceRange = marker.current().sourceRange;
2070
- const startVsExtent = compare(sourceRange.start, content.extent.start);
2071
- const endVsExtent = content.extent.kind === "bounded" ? compare(sourceRange.end, content.extent.end) : void 0;
2072
- if (!Number.isNaN(startVsExtent) && startVsExtent >= 0 && (endVsExtent == null || !Number.isNaN(endVsExtent) && endVsExtent <= 0)) return [];
2073
- return [{
2074
- code: "marker_source_out_of_bounds",
2075
- entityId: marker.entityId,
2076
- message: `Sequence Marker sourceRange must stay within content "${content.entityId}" extent`
2077
- }];
2078
- }
2079
- function validateSequenceComposition(entity) {
2080
- const current = entity.current();
2081
- const expected = expectedSequenceShape(current.entityKind);
2082
- if (expected == null) return [];
2083
- if (hasSequence(current) && current.extent.kind === expected.extent && current.sampling === expected.sampling) return [];
2084
- return [{
2085
- code: "invalid_sequence_composition",
2086
- entityId: current.entityId,
2087
- message: `${current.entityKind} must compose ${expected.extent} / ${expected.sampling} Sequence semantics`
2088
- }];
2089
- }
2090
- function validateEntity(entity, entityIds = /* @__PURE__ */ new Set()) {
2091
- const current = entity.current();
2092
- const issues = [];
2093
- if (isReservedEntityKind(current.entityKind)) issues.push({
2094
- code: "forbidden_entity_kind",
2095
- entityId: current.entityId,
2096
- message: `Entity kind "${current.entityKind}" is explicitly outside the Medeo DSL`
2097
- });
2098
- for (const problem of validateKnownEntityPayload(current)) issues.push({
2099
- code: "invalid_entity_payload",
2100
- entityId: current.entityId,
2101
- message: `Entity "${current.entityKind}" ${problem}`
2102
- });
2103
- const peerIdPaths = [...collectPeerEntityIdPaths(current, current.entityKind), ...collectPeerEntityValuePaths(current, current.entityKind, current.entityId, entityIds)];
2104
- const uniquePeerIdPaths = [...new Set(peerIdPaths)].sort();
2105
- if (uniquePeerIdPaths.length > 0) issues.push({
2106
- code: "peer_entity_id_field",
2107
- entityId: current.entityId,
2108
- message: `Entity embeds forbidden peer-ID field/value path(s): ${uniquePeerIdPaths.join(", ")}`
2109
- });
2110
- return issues;
2111
- }
2112
- function validateKnownEntityPayload(entity) {
2113
- const value = entity;
2114
- const problems = [];
2115
- if (value.lifecycle !== void 0 && !isRecord(value.lifecycle)) problems.push("lifecycle must be an object when present");
2116
- if (entity.entityKind === "audio-script" || entity.entityKind === "phonetic-script") {
2117
- for (const key of [
2118
- "extent",
2119
- "sampling",
2120
- "coordinateSpace",
2121
- "sourceRange",
2122
- "targetRange",
2123
- "duration",
2124
- "startMs",
2125
- "endMs"
2126
- ]) if (Object.hasOwn(value, key)) problems.push(`${key} is not intrinsic script data; assign an external annotation Marker`);
2127
- }
2128
- switch (entity.entityKind) {
2129
- case "track":
2130
- validateOptionalField(value, "hidden", "boolean", problems);
2131
- validateOptionalField(value, "role", "string", problems);
2132
- validateOptionalFiniteNumber(value, "order", problems);
2133
- break;
2134
- case "video":
2135
- case "audio":
2136
- validateSequencePayload(value, "bounded", "native", problems);
2137
- validateMediaAssetFields(value, problems);
2138
- break;
2139
- case "caption":
2140
- validateSequencePayload(value, "bounded", "native", problems);
2141
- validateCaptionPayload(value, problems);
2142
- break;
2143
- case "voice":
2144
- validateVoicePayload(value, problems);
2145
- break;
2146
- case "image":
2147
- validateSequencePayload(value, "unbounded", "constant", problems);
2148
- validateMediaAssetFields(value, problems);
2149
- break;
2150
- case "axvideo":
2151
- validateSequencePayload(value, "bounded", "derived", problems);
2152
- break;
2153
- case "sequence-marker":
2154
- validateMarkerPayload(value, problems);
2155
- break;
2156
- case "audio-script":
2157
- validateScriptPayload(value, problems);
2158
- break;
2159
- case "phonetic-script":
2160
- validatePhoneticScriptPayload(value, problems);
2161
- break;
2162
- case "timeline":
2163
- case "viewport": break;
2164
- case "clip":
2165
- validateOptionalFiniteNumber(value, "order", problems);
2166
- validateOptionalFiniteNumber(value, "volume", problems);
2167
- if (typeof value.volume === "number" && (value.volume < -60 || value.volume > 20)) problems.push("volume must be decibels between -60 and 20");
2168
- break;
2169
- case "asset":
2170
- validateAssetPayload(value, problems);
2171
- break;
2172
- default: break;
2173
- }
2174
- return problems;
2175
- }
2176
- function validateSequencePayload(value, expectedExtent, expectedSampling, problems) {
2177
- const extent = value.extent;
2178
- if (!isRecord(extent)) problems.push("extent must be an object");
2179
- else {
2180
- if (extent.kind !== expectedExtent) problems.push(`extent.kind must be "${expectedExtent}"`);
2181
- if (!Object.hasOwn(extent, "start") || extent.start === void 0) problems.push("extent.start is required");
2182
- if (expectedExtent === "bounded" && (!Object.hasOwn(extent, "end") || extent.end === void 0)) problems.push("extent.end is required for bounded sequences");
2183
- if (expectedExtent === "unbounded" && Object.hasOwn(extent, "end")) problems.push("extent.end is forbidden for unbounded sequences");
2184
- }
2185
- if (value.sampling !== expectedSampling) problems.push(`sampling must be "${expectedSampling}"`);
2186
- if (!Object.hasOwn(value, "coordinateSpace") || value.coordinateSpace === void 0) problems.push("coordinateSpace is required");
2187
- }
2188
- function validateMarkerPayload(value, problems) {
2189
- validateRange(value.sourceRange, "sourceRange", true, problems);
2190
- if (Object.hasOwn(value, "targetRange") && value.targetRange !== void 0) validateRange(value.targetRange, "targetRange", true, problems);
2191
- const duration = value.duration;
2192
- if (!isRecord(duration)) problems.push("duration must be an object");
2193
- else if (duration.mode === "fixed") {
2194
- if (!Object.hasOwn(duration, "value") || duration.value === void 0) problems.push("duration.value is required when duration.mode is \"fixed\"");
2195
- } else if (duration.mode !== "from-source") problems.push("duration.mode must be \"from-source\" or \"fixed\"");
2196
- if (value.anchorOffset === void 0 && Object.hasOwn(value, "anchorOffset")) problems.push("anchorOffset cannot be undefined when present");
2197
- if (value.durationPolicy !== void 0 && value.durationPolicy !== "timeline") problems.push("durationPolicy must be \"timeline\" when present");
2198
- if (value.segmentRanges !== void 0) validateSegmentRanges(value.segmentRanges, problems);
2199
- }
2200
- /** Annotation Marker time values are directly assigned facts; no cross-references are allowed. */
2201
- function validateSegmentRanges(value, problems) {
2202
- if (!Array.isArray(value)) {
2203
- problems.push("segmentRanges must be an array when present");
2204
- return;
2205
- }
2206
- const seen = /* @__PURE__ */ new Set();
2207
- for (const [index, entry] of value.entries()) {
2208
- if (!isRecord(entry)) {
2209
- problems.push(`segmentRanges[${index}] must be an object`);
2210
- continue;
2211
- }
2212
- if (typeof entry.segmentId !== "string") problems.push(`segmentRanges[${index}].segmentId must be a string`);
2213
- else if (seen.has(entry.segmentId)) problems.push(`segmentRanges[${index}].segmentId must be unique within the Marker`);
2214
- else seen.add(entry.segmentId);
2215
- for (const key of ["startMs", "endMs"]) {
2216
- const point = entry[key];
2217
- if (typeof point !== "number" || !Number.isFinite(point)) problems.push(`segmentRanges[${index}].${key} must be a finite number`);
2218
- }
2219
- if (typeof entry.startMs === "number" && Number.isFinite(entry.startMs) && typeof entry.endMs === "number" && Number.isFinite(entry.endMs) && entry.startMs > entry.endMs) problems.push(`segmentRanges[${index}].startMs must not exceed segmentRanges[${index}].endMs`);
2220
- }
2221
- }
2222
- function validateAssetPayload(value, problems) {
2223
- validateExternalLocator(value, problems);
2224
- validateStorageKey(value, problems);
2225
- if (value.inline !== void 0) problems.push("inline is not a physical location; text is domain content owned by its AudioScript");
2226
- }
2227
- /**
2228
- * Media variants own their Asset locator directly: `external` is required and
2229
- * textual domain content is owned by AudioScript; the physical-location
2230
- * vocabularies cannot mix.
2231
- */
2232
- function validateMediaAssetFields(value, problems) {
2233
- if (value.external === void 0) problems.push("external is required; media variants own their Asset identity");
2234
- else validateExternalLocator(value, problems);
2235
- validateStorageKey(value, problems);
2236
- if (value.inline !== void 0) problems.push("media variants use external locators, not inline domain text");
2237
- }
2238
- function validateExternalLocator(value, problems) {
2239
- const external = value.external;
2240
- if (external === void 0) return;
2241
- if (!isRecord(external)) {
2242
- problems.push("external must be an object when present");
2243
- return;
2244
- }
2245
- if (external.system !== "memota" && external.system !== "memota-speech") problems.push("external.system must be \"memota\" or \"memota-speech\"");
2246
- if (typeof external.key !== "string" || external.key.trim() === "") problems.push("external.key must be a non-empty string");
2247
- }
2248
- function validateStorageKey(value, problems) {
2249
- if (value.storageKey !== void 0 && (typeof value.storageKey !== "string" || value.storageKey.trim() === "")) problems.push("storageKey must be a non-empty string when present");
2250
- }
2251
- /**
2252
- * Voice is a timbre identity, not playable content: it owns the voice-library
2253
- * descriptor and nothing that would make it look like media or a Sequence. The
2254
- * rendered voiceover is an `audio` entity bound by a `voice-timbre` Relation.
2255
- */
2256
- function validateVoicePayload(value, problems) {
2257
- for (const key of [
2258
- "extent",
2259
- "sampling",
2260
- "coordinateSpace",
2261
- "external",
2262
- "storageKey"
2263
- ]) if (Object.hasOwn(value, key)) problems.push(`${key} belongs to the rendered Audio, not to the Voice identity`);
2264
- const voice = value.voice;
2265
- if (voice === void 0) {
2266
- problems.push("voice is required; a Voice entity is its voice-library identity");
2267
- return;
2268
- }
2269
- if (!isRecord(voice)) {
2270
- problems.push("voice must be an object");
2271
- return;
2272
- }
2273
- if (voice.system !== "voice-library") problems.push("voice.system must be \"voice-library\"");
2274
- if (typeof voice.key !== "string" || voice.key.trim() === "") problems.push("voice.key must be a non-empty string");
2275
- if (voice.name !== void 0 && typeof voice.name !== "string") problems.push("voice.name must be a string when present");
2276
- }
2277
- function validateCaptionPayload(value, problems) {
2278
- validateExternalLocator(value, problems);
2279
- if (value.segmentRanges !== void 0) validateSegmentRanges(value.segmentRanges, problems);
2280
- if (Object.hasOwn(value, "selections")) problems.push("selections is forbidden; Caption requires one selection object");
2281
- const selection = value.selection;
2282
- if (!isRecord(selection)) problems.push("selection must be one AudioScript segment selection object, not an array");
2283
- else {
2284
- if (typeof selection.segmentId !== "string" || !selection.segmentId.trim()) problems.push("selection.segmentId must be a non-empty string");
2285
- if (Object.keys(selection).some((key) => key !== "segmentId" && key !== "textRange")) problems.push("selection may only contain segmentId and textRange");
2286
- const range = selection.textRange;
2287
- if (range !== void 0 && (!isRecord(range) || !Number.isSafeInteger(range.start) || !Number.isSafeInteger(range.end) || range.start < 0 || range.end <= range.start || Object.keys(range).some((key) => key !== "start" && key !== "end"))) problems.push("selection.textRange must be a non-empty half-open code-point range");
2288
- if (Array.isArray(value.segmentRanges) && (value.segmentRanges.length !== 1 || !isRecord(value.segmentRanges[0]) || value.segmentRanges[0].segmentId !== selection.segmentId)) problems.push("Caption segmentRanges must contain only the selected segment timing");
2289
- }
2290
- const style = value.style;
2291
- if (style === void 0) return;
2292
- if (!isRecord(style)) {
2293
- problems.push("style must be an object when present");
2294
- return;
2295
- }
2296
- const font = style.font;
2297
- if (font !== void 0) if (!isRecord(font)) problems.push("style.font must be an object when present");
2298
- else {
2299
- if (font.system !== "font-library") problems.push("style.font.system must be \"font-library\"");
2300
- if (typeof font.key !== "string" || font.key.trim() === "") problems.push("style.font.key must be a non-empty string");
2301
- }
2302
- for (const key of [
2303
- "fontSize",
2304
- "fontWeight",
2305
- "entranceAnimationDurationMs",
2306
- "strokeWidth",
2307
- "positionX",
2308
- "positionY"
2309
- ]) validateOptionalFiniteNumber(style, key, problems, `style.${key}`);
2310
- for (const key of [
2311
- "fontColor",
2312
- "entranceAnimation",
2313
- "strokeColor"
2314
- ]) if (style[key] !== void 0 && typeof style[key] !== "string") problems.push(`style.${key} must be a string`);
2315
- }
2316
- function validateRange(value, path, required, problems) {
2317
- if (!isRecord(value)) {
2318
- if (required) problems.push(`${path} must be an object`);
2319
- return;
2320
- }
2321
- if (!Object.hasOwn(value, "start") || value.start === void 0) problems.push(`${path}.start is required`);
2322
- if (!Object.hasOwn(value, "end") || value.end === void 0) problems.push(`${path}.end is required`);
2323
- }
2324
- /** Phonetic variants store pronunciation fields only; base text stays in the AudioScript. */
2325
- function validatePhoneticScriptPayload(value, problems) {
2326
- if (value.segments !== void 0) validateScriptPayload(value, problems);
2327
- if (value.phonemeScript !== void 0 && (typeof value.phonemeScript !== "string" || value.phonemeScript.trim() === "")) problems.push("phonemeScript must be a non-empty string when present");
2328
- if (value.prosody !== void 0 && !isRecord(value.prosody)) problems.push("prosody must be an object when present");
2329
- }
2330
- function validateScriptPayload(value, problems) {
2331
- if (!Array.isArray(value.segments)) {
2332
- problems.push("segments must be an array");
2333
- return;
2334
- }
2335
- for (const [index, segment] of value.segments.entries()) {
2336
- if (!isRecord(segment)) {
2337
- problems.push(`segments[${index}] must be an object`);
2338
- continue;
2339
- }
2340
- for (const key of [
2341
- "startMs",
2342
- "endMs",
2343
- "start_ms",
2344
- "end_ms",
2345
- "sourceRange",
2346
- "targetRange",
2347
- "duration"
2348
- ]) if (Object.hasOwn(segment, key)) problems.push(`segments[${index}].${key} is timing; attach an AudioScript annotation Marker instead`);
2349
- if (typeof segment.segmentId !== "string") problems.push(`segments[${index}].segmentId must be a string`);
2350
- if (typeof segment.text !== "string") problems.push(`segments[${index}].text must be a string`);
2351
- if (segment.language !== void 0 && typeof segment.language !== "string") problems.push(`segments[${index}].language must be a string when present`);
2352
- }
2353
- }
2354
- function validateOptionalField(value, key, expectedType, problems) {
2355
- if (value[key] !== void 0 && typeof value[key] !== expectedType) problems.push(`${key} must be a ${expectedType} when present`);
2356
- }
2357
- function validateOptionalFiniteNumber(value, key, problems, label = key) {
2358
- if (value[key] !== void 0 && (typeof value[key] !== "number" || !Number.isFinite(value[key]))) problems.push(`${label} must be a finite number when present`);
2359
- }
2360
- function collectPeerEntityIdPaths(value, entityKind) {
2361
- const paths = [];
2362
- visitPeerEntityIdPaths(value, entityKind, "", /* @__PURE__ */ new Set(), paths);
2363
- return paths;
2364
- }
2365
- function visitPeerEntityIdPaths(value, entityKind, parentPath, ancestors, paths) {
2366
- if (typeof value !== "object" || value == null) return;
2367
- if (ancestors.has(value)) return;
2368
- ancestors.add(value);
2369
- if (Array.isArray(value)) for (const [index, item] of value.entries()) visitPeerEntityIdPaths(item, entityKind, `${parentPath}[${index}]`, ancestors, paths);
2370
- else for (const [key, child] of Object.entries(value)) {
2371
- const path = parentPath.length === 0 ? key : `${parentPath}.${key}`;
2372
- if (parentPath.length === 0 && key === "baseEntityIds") continue;
2373
- if (!(parentPath.length === 0 && key === "entityId") && !isOwnedLocalIdPath(entityKind, path) && isEntityIdFieldName(key)) paths.push(path);
2374
- visitPeerEntityIdPaths(child, entityKind, path, ancestors, paths);
2375
- }
2376
- ancestors.delete(value);
2377
- }
2378
- function collectPeerEntityValuePaths(value, entityKind, ownEntityId, entityIds) {
2379
- const paths = [];
2380
- visitPeerEntityValues(value, entityKind, ownEntityId, entityIds, "", /* @__PURE__ */ new Set(), paths);
2381
- return paths;
2382
- }
2383
- function visitPeerEntityValues(value, entityKind, ownEntityId, entityIds, path, ancestors, paths) {
2384
- if (typeof value === "string") {
2385
- if (value !== ownEntityId && entityIds.has(value) && !isOwnedLocalEntityValuePath(entityKind, path)) paths.push(path);
2386
- return;
2387
- }
2388
- if (typeof value !== "object" || value == null || ancestors.has(value)) return;
2389
- ancestors.add(value);
2390
- if (Array.isArray(value)) for (const [index, item] of value.entries()) visitPeerEntityValues(item, entityKind, ownEntityId, entityIds, `${path}[${index}]`, ancestors, paths);
2391
- else for (const [key, child] of Object.entries(value)) {
2392
- if (path.length === 0 && (key === "entityId" || key === "entityKind" || key === "baseEntityIds")) continue;
2393
- visitPeerEntityValues(child, entityKind, ownEntityId, entityIds, path.length === 0 ? key : `${path}.${key}`, ancestors, paths);
2394
- }
2395
- ancestors.delete(value);
2396
- }
2397
- function isOwnedLocalEntityValuePath(entityKind, path) {
2398
- if (entityKind === "track" && path === "role") return true;
2399
- if ([
2400
- "video",
2401
- "audio",
2402
- "image",
2403
- "caption",
2404
- "axvideo"
2405
- ].includes(entityKind) && /^(?:sampling|coordinateSpace|coordinateSpace\.unit|extent\.kind)$/.test(path)) return true;
2406
- if (entityKind === "sequence-marker" && /^(?:durationPolicy|duration\.mode|timeRemapping\.(?:kind|mode))$/.test(path)) return true;
2407
- if ((entityKind === "sequence-marker" || entityKind === "caption") && /^segmentRanges\[\d+\]\.segmentId$/.test(path)) return true;
2408
- if (entityKind === "asset" && /^(?:external\.(?:system|key)|storageKey)$/.test(path)) return true;
2409
- if (isMediaAssetVariantKind(entityKind) && /^(?:external\.(?:system|key)|storageKey)$/.test(path)) return true;
2410
- if (entityKind === "voice" && /^voice\.(?:system|key|name)$/.test(path)) return true;
2411
- if (entityKind === "caption" && (path.startsWith("style.") || path === "selection.segmentId")) return true;
2412
- if ([
2413
- "audio-script",
2414
- "caption",
2415
- "phonetic-script"
2416
- ].includes(entityKind) && /^segments\[\d+\]\.(?:segmentId|text|language)$/.test(path)) return true;
2417
- return false;
2418
- }
2419
- function isOwnedLocalIdPath(entityKind, path) {
2420
- if (path === "lifecycle.actorId") return true;
2421
- if ([
2422
- "audio-script",
2423
- "caption",
2424
- "phonetic-script"
2425
- ].includes(entityKind) && /^segments\[\d+\]\.segmentId$/.test(path)) return true;
2426
- if (entityKind === "caption" && path === "selection.segmentId") return true;
2427
- if ((entityKind === "sequence-marker" || entityKind === "caption") && /^segmentRanges\[\d+\]\.segmentId$/.test(path)) return true;
2428
- if (entityKind === "asset" && /^(?:tracks\[\d+\]\.trackId|renditions\[\d+\]\.renditionId)$/.test(path)) return true;
2429
- return false;
2430
- }
2431
- function isEntityIdFieldName(key) {
2432
- return key.endsWith("Id") || key.endsWith("Ids") || key.endsWith("ID") || key.endsWith("IDs") || /_ids?$/i.test(key);
2433
- }
2434
- function isRecord(value) {
2435
- return typeof value === "object" && value != null && !Array.isArray(value);
2436
- }
2437
- function collectRelatedEntities(entityRefs, index) {
2438
- const byId = /* @__PURE__ */ new Map();
2439
- const queue = [...entityRefs];
2440
- const issues = [];
2441
- while (queue.length > 0) {
2442
- const entity = queue.shift();
2443
- if (entity == null) continue;
2444
- const existing = byId.get(entity.entityId);
2445
- if (existing != null) {
2446
- if (existing !== entity) issues.push({
2447
- code: "duplicate_entity_id",
2448
- entityId: entity.entityId,
2449
- message: `Entity id "${entity.entityId}" has more than one live EntityRef`
2450
- });
2451
- continue;
2452
- }
2453
- byId.set(entity.entityId, entity);
2454
- for (const relation of index.relationsOf(entity)) for (const endpoint of relation.endpoints) {
2455
- const ref = endpoint.deref();
2456
- if (ref != null && !byId.has(ref.entityId)) queue.push(ref);
2457
- }
2458
- }
2459
- return {
2460
- entities: [...byId.values()],
2461
- issues
2462
- };
2463
- }
2464
- function expectedSequenceShape(kind) {
2465
- if (kind === "video" || kind === "audio" || kind === "caption") return {
2466
- extent: "bounded",
2467
- sampling: "native"
2468
- };
2469
- if (kind === "image") return {
2470
- extent: "unbounded",
2471
- sampling: "constant"
2472
- };
2473
- if (kind === "axvideo") return {
2474
- extent: "bounded",
2475
- sampling: "derived"
2476
- };
2477
- }
2478
- function ofKind(relations, kind) {
2479
- return relations.filter((relation) => relation.kind === kind);
2480
- }
2481
- //#endregion
2482
- //#region ../medeo-dsl/src/relation-specs.ts
2483
- const timelineTrackRelationSpec = emptySpec("timeline-track", "timeline", "track");
2484
- const trackClipRelationSpec = emptySpec("track-clip", "track", "clip");
2485
- const clipMarkerRelationSpec = emptySpec("clip-marker", "clip", "sequence-marker");
2486
- const axVideoMarkerRelationSpec = emptySpec("axvideo-marker", "axvideo", "sequence-marker");
2487
- const markerTimelineRelationSpec = emptySpec("marker-timeline", "sequence-marker", "timeline");
2488
- const markerContentRelationSpec = Object.freeze({
2489
- kind: "marker-content",
2490
- validateEndpoints: (endpoints) => hasMarkerAndSequence(endpoints),
2491
- validateMetadata: isEmptyMetadata
2492
- });
2493
- const physicalAssetRelationSpec = Object.freeze({
2494
- kind: "physical-asset",
2495
- validateEndpoints: (endpoints) => hasAssetAndSequence(endpoints),
2496
- validateMetadata: isAssetBinding
2497
- });
2498
- /** `generated(output, input)` means endpoint 0 was generated from endpoint 1. */
2499
- const generatedRelationSpec = Object.freeze({
2500
- kind: "generated",
2501
- validateEndpoints: (endpoints) => endpoints.every((endpoint) => isGeneratedMedia(endpoint.current())),
2502
- validateMetadata: isEmptyMetadata
2503
- });
2504
- const captionAlignmentRelationSpec = Object.freeze({
2505
- kind: "caption-alignment",
2506
- validateEndpoints: (endpoints) => hasKinds(endpoints, new Set(["caption"]), new Set(["audio"])),
2507
- validateMetadata: isCaptionAlignmentMetadata
2508
- });
2509
- /** `clip-anchor(child, host)` means endpoint 0 follows endpoint 1. */
2510
- const clipAnchorRelationSpec = Object.freeze({
2511
- kind: "clip-anchor",
2512
- validateEndpoints: (endpoints) => endpoints[0].current().entityKind === "clip" && endpoints[1].current().entityKind === "clip",
2513
- validateMetadata: isEmptyMetadata
2514
- });
2515
- /**
2516
- * The rendered voiceover Audio and the PhoneticScript it was synthesized from;
2517
- * kinds determine roles regardless of endpoint positions.
2518
- */
2519
- const phoneticScriptRenderRelationSpec = Object.freeze({
2520
- kind: "phonetic-script-render",
2521
- validateEndpoints: (endpoints) => hasKinds(endpoints, new Set(["audio"]), new Set(["phonetic-script"])),
2522
- validateMetadata: isEmptyMetadata
2523
- });
2524
- /**
2525
- * The timbre identity a rendered voiceover Audio was synthesized with. Voice
2526
- * stays an identity: it never carries the audio itself, so the link between the
2527
- * two is a Relation rather than one shared entity.
2528
- */
2529
- const voiceTimbreRelationSpec = Object.freeze({
2530
- kind: "voice-timbre",
2531
- validateEndpoints: (endpoints) => hasKinds(endpoints, new Set(["audio"]), new Set(["voice"])),
2532
- validateMetadata: isEmptyMetadata
2533
- });
2534
- /** AudioScript was transcribed from Audio, Video, or recorded Voice; kinds determine roles. */
2535
- const audioScriptSourceRelationSpec = Object.freeze({
2536
- kind: "audio-script-source",
2537
- validateEndpoints: (endpoints) => hasKinds(endpoints, new Set(["audio-script"]), new Set(["audio", "video"])),
2538
- validateMetadata: isEmptyMetadata
2539
- });
2540
- /**
2541
- * `audio-script-marker(script, marker)` attaches an annotation Sequence Marker
2542
- * whose `segmentRanges` hold directly assigned per-Segment time values. The
2543
- * script keeps no Sequence and no Clip admission; annotation Markers cannot
2544
- * enter Clip/AXVideo use chains (enforced by the marker-use invariant).
2545
- */
2546
- const audioScriptMarkerRelationSpec = Object.freeze({
2547
- kind: "audio-script-marker",
2548
- validateEndpoints: (endpoints) => hasKinds(endpoints, new Set(["audio-script"]), new Set(["sequence-marker"])),
2549
- validateMetadata: isEmptyMetadata
2550
- });
2551
- /** Built-in kinds are reserved; callers may add specs only under new names. */
2552
- const builtInRelationSpecs = Object.freeze([
2553
- timelineTrackRelationSpec,
2554
- trackClipRelationSpec,
2555
- clipMarkerRelationSpec,
2556
- markerContentRelationSpec,
2557
- axVideoMarkerRelationSpec,
2558
- markerTimelineRelationSpec,
2559
- physicalAssetRelationSpec,
2560
- generatedRelationSpec,
2561
- captionAlignmentRelationSpec,
2562
- clipAnchorRelationSpec,
2563
- phoneticScriptRenderRelationSpec,
2564
- voiceTimbreRelationSpec,
2565
- audioScriptSourceRelationSpec,
2566
- audioScriptMarkerRelationSpec
2567
- ]);
2568
- function emptySpec(kind, a, b) {
2569
- return metadataSpec(kind, a, b, isEmptyMetadata);
2570
- }
2571
- function metadataSpec(kind, a, b, validateMetadata) {
2572
- return Object.freeze({
2573
- kind,
2574
- validateEndpoints: (endpoints) => hasKinds(endpoints, new Set([a]), new Set([b])),
2575
- validateMetadata
2576
- });
2577
- }
2578
- function hasKinds(endpoints, aKinds, bKinds) {
2579
- const first = endpoints[0].current().entityKind;
2580
- const second = endpoints[1].current().entityKind;
2581
- return aKinds.has(first) && bKinds.has(second) || aKinds.has(second) && bKinds.has(first);
2582
- }
2583
- function hasMarkerAndSequence(endpoints) {
2584
- const first = endpoints[0].current();
2585
- const second = endpoints[1].current();
2586
- return first.entityKind === "sequence-marker" && hasSequence(second) || second.entityKind === "sequence-marker" && hasSequence(first);
2587
- }
2588
- function hasAssetAndSequence(endpoints) {
2589
- const first = endpoints[0].current();
2590
- const second = endpoints[1].current();
2591
- return first.entityKind === "asset" && hasSequence(second) || second.entityKind === "asset" && hasSequence(first);
2592
- }
2593
- function isGeneratedMedia(entity) {
2594
- return entity.entityKind === "video" || entity.entityKind === "image" || entity.entityKind === "audio";
2595
- }
2596
- function isEmptyMetadata(value) {
2597
- return isJsonObject(value) && Object.keys(value).length === 0;
2598
- }
2599
- function isAssetBinding(value) {
2600
- if (!isJsonObject(value)) return false;
2601
- const orderingKey = /(order|ordinal|position|rank|index|z[_-]?index)/i;
2602
- return Object.keys(value).every((key) => !orderingKey.test(key));
2603
- }
2604
- function isCaptionAlignmentMetadata(value) {
2605
- return isJsonObject(value) && Object.hasOwn(value, "alignment");
2606
- }
2607
- //#endregion
2608
- //#region ../medeo-dsl/src/relations.ts
2609
- function createEntityRef(entity) {
2610
- return {
2611
- entityId: entity.entityId,
2612
- current: () => entity
2613
- };
2614
- }
2615
- //#endregion
2616
- //#region ../medeo-dsl/src/relation-index.ts
2617
- var RelationEdge = class {
2618
- relationId;
2619
- kind;
2620
- metadata;
2621
- trace;
2622
- endpoints;
2623
- constructor(relationId, kind, endpoints, metadata, trace) {
2624
- this.relationId = relationId;
2625
- this.kind = kind;
2626
- this.metadata = metadata;
2627
- this.trace = trace;
2628
- this.endpoints = [new WeakRef(endpoints[0]), new WeakRef(endpoints[1])];
2629
- }
2630
- other(entity) {
2631
- const first = this.endpoints[0].deref();
2632
- const second = this.endpoints[1].deref();
2633
- if (first === entity) return this.endpoints[1];
2634
- if (second === entity) return this.endpoints[0];
2635
- }
2636
- toRow() {
2637
- const first = this.endpoints[0].deref();
2638
- const second = this.endpoints[1].deref();
2639
- if (first == null || second == null) return void 0;
2640
- return {
2641
- relationId: this.relationId,
2642
- endpoint0EntityId: first.entityId,
2643
- endpoint1EntityId: second.entityId,
2644
- relationKind: this.kind,
2645
- metadata: this.metadata,
2646
- trace: this.trace
2647
- };
2648
- }
2649
- isStale() {
2650
- return this.endpoints[0].deref() == null || this.endpoints[1].deref() == null;
2651
- }
2652
- };
2653
- /** Endpoint-agnostic secondary index. Relation rows remain the persistence authority. */
2654
- var BiRelationIndex = class {
2655
- byEntity = /* @__PURE__ */ new WeakMap();
2656
- canonicalRefs = /* @__PURE__ */ new Map();
2657
- byRelationId = /* @__PURE__ */ new Map();
2658
- link(input) {
2659
- if (input.spec.kind === "generated") throw new Error("Author generated Relations with linkGenerated({ output, input })");
2660
- if (input.spec.kind === "clip-anchor" || input.spec.kind === "phonetic-script-render" || input.spec.kind === "audio-script-source") throw new Error(`Author ordered ${input.spec.kind} Relations with the dedicated role-named method`);
2661
- return this.linkValidated(input);
2662
- }
2663
- /** Author `generated(output, input)` without exposing positional arguments. */
2664
- linkGenerated(input) {
2665
- return this.linkValidated({
2666
- relationId: input.relationId,
2667
- spec: generatedRelationSpec,
2668
- endpoints: [input.output, input.input],
2669
- metadata: {},
2670
- trace: input.trace
2671
- });
2672
- }
2673
- /** Author `clip-anchor(child, host)` without exposing positional arguments. */
2674
- linkClipAnchor(input) {
2675
- return this.linkValidated({
2676
- relationId: input.relationId,
2677
- spec: clipAnchorRelationSpec,
2678
- endpoints: [input.child, input.host],
2679
- metadata: {},
2680
- trace: input.trace
2681
- });
2682
- }
2683
- /** Author `phonetic-script-render(output, phoneticScript)` without exposing positional arguments. */
2684
- linkPhoneticScriptRender(input) {
2685
- return this.linkValidated({
2686
- relationId: input.relationId,
2687
- spec: phoneticScriptRenderRelationSpec,
2688
- endpoints: [input.output, input.phoneticScript],
2689
- metadata: {},
2690
- trace: input.trace
2691
- });
2692
- }
2693
- /** Author `audio-script-source(script, source)` without exposing positional arguments. */
2694
- linkAudioScriptSource(input) {
2695
- return this.linkValidated({
2696
- relationId: input.relationId,
2697
- spec: audioScriptSourceRelationSpec,
2698
- endpoints: [input.script, input.source],
2699
- metadata: {},
2700
- trace: input.trace
2701
- });
2702
- }
2703
- /**
2704
- * Rehydrate a persisted row after resolving its spec and endpoint refs.
2705
- *
2706
- * This is a storage-boundary escape hatch, not an authoring API: persisted
2707
- * positions already are the semantic assertion made by their relation kind.
2708
- */
2709
- linkRuntime(input) {
2710
- return this.linkValidated(input);
2711
- }
2712
- linkValidated(input) {
2713
- const [first, second] = input.endpoints;
2714
- if (first.entityId === second.entityId) throw new Error("A Relation cannot connect an entity to itself");
2715
- this.assertRelationIdAvailable(input.relationId);
2716
- const builtInSpec = builtInSpecByKind.get(input.spec.kind);
2717
- if (builtInSpec != null && builtInSpec !== input.spec) throw new Error(`Relation kind "${input.spec.kind}" must use its built-in specification`);
2718
- if (isForbiddenAuthoritativeRelation(input.spec.kind, input.endpoints)) throw new Error("A direct Clip-Content Relation is derived-only and cannot be authoritative");
2719
- if (!input.spec.validateEndpoints(input.endpoints)) throw new Error(`Relation "${input.spec.kind}" received invalid endpoints`);
2720
- if (!input.spec.validateMetadata(input.metadata)) throw new Error(`Relation "${input.spec.kind}" received invalid metadata`);
2721
- this.assertCanonicalRefAvailable(first);
2722
- this.assertCanonicalRefAvailable(second);
2723
- const relation = new RelationEdge(input.relationId, input.spec.kind, input.endpoints, input.metadata, input.trace ?? {});
2724
- this.rememberCanonicalRef(first);
2725
- this.rememberCanonicalRef(second);
2726
- this.add(first, relation);
2727
- this.add(second, relation);
2728
- this.byRelationId.set(input.relationId, new WeakRef(relation));
2729
- return relation;
2730
- }
2731
- relationsOf(entity) {
2732
- this.registerCanonicalRef(entity);
2733
- const relations = this.byEntity.get(entity);
2734
- if (relations == null) return /* @__PURE__ */ new Set();
2735
- for (const relation of relations) if (relation instanceof RelationEdge && relation.isStale()) this.unlink(relation);
2736
- return new Set(relations);
2737
- }
2738
- unlink(relation) {
2739
- for (const endpoint of relation.endpoints) {
2740
- const ref = endpoint.deref();
2741
- if (ref != null) this.byEntity.get(ref)?.delete(relation);
2742
- }
2743
- if (this.byRelationId.get(relation.relationId)?.deref() === relation) this.byRelationId.delete(relation.relationId);
2744
- }
2745
- add(entity, relation) {
2746
- const relations = this.byEntity.get(entity) ?? /* @__PURE__ */ new Set();
2747
- relations.add(relation);
2748
- this.byEntity.set(entity, relations);
2749
- }
2750
- registerCanonicalRef(entity) {
2751
- this.assertCanonicalRefAvailable(entity);
2752
- this.rememberCanonicalRef(entity);
2753
- }
2754
- assertCanonicalRefAvailable(entity) {
2755
- const existing = this.canonicalRefs.get(entity.entityId)?.deref();
2756
- if (existing != null && existing !== entity) throw new Error(`Entity "${entity.entityId}" already has a live canonical EntityRef`);
2757
- }
2758
- rememberCanonicalRef(entity) {
2759
- this.canonicalRefs.set(entity.entityId, new WeakRef(entity));
2760
- }
2761
- assertRelationIdAvailable(relationId) {
2762
- if (this.byRelationId.get(relationId)?.deref() != null) throw new Error(`Relation id "${relationId}" already exists`);
2763
- this.byRelationId.delete(relationId);
2764
- }
2765
- };
2766
- const builtInSpecByKind = new Map(builtInRelationSpecs.map((spec) => [spec.kind, spec]));
2767
- function isForbiddenAuthoritativeRelation(kind, endpoints) {
2768
- if (kind === "clip-content") return true;
2769
- const first = endpoints[0].current();
2770
- const second = endpoints[1].current();
2771
- return first.entityKind === "clip" && hasSequence(second) || second.entityKind === "clip" && hasSequence(first);
2772
- }
2773
- //#endregion
2774
- //#region ../medeo-dsl/src/entity-relation-rows.ts
2775
- var InvalidEntityRelationRowsError = class extends Error {
2776
- issues;
2777
- constructor(issues) {
2778
- super(`Invalid Medeo entity/relation rows:\n- ${issues.join("\n- ")}`);
2779
- this.issues = issues;
2780
- this.name = "InvalidEntityRelationRowsError";
2781
- }
2782
- };
2783
- /** Decodes database rows into flat entities and validates the complete relation set. */
2784
- function decodeEntityRelationRows(rows, options) {
2785
- const issues = [];
2786
- const entitiesById = /* @__PURE__ */ new Map();
2787
- const extensionEntityKinds = new Set(options.entityKinds ?? []);
2788
- for (const row of rows.entities) {
2789
- let entity = decodeEntityRow(row, extensionEntityKinds, issues);
2790
- if (entity != null) try {
2791
- entity = decodeEntityRow(assembleEntityContent(rows, row.entityId), extensionEntityKinds, issues);
2792
- } catch (error) {
2793
- issues.push(errorMessage(error));
2794
- continue;
2795
- }
2796
- if (entity == null) continue;
2797
- const ref = createEntityRef(entity);
2798
- if (entitiesById.has(ref.entityId)) {
2799
- issues.push(`duplicate entity id "${ref.entityId}"`);
2800
- continue;
2801
- }
2802
- entitiesById.set(ref.entityId, ref);
2803
- }
2804
- const specsByKind = collectRelationSpecs(options.relationSpecs ?? [], issues);
2805
- const relationIndex = new BiRelationIndex();
2806
- const relations = [];
2807
- const relationIds = /* @__PURE__ */ new Set();
2808
- for (const row of rows.relations) {
2809
- let relationId;
2810
- try {
2811
- relationId = createRelationId(row.relationId);
2812
- } catch (error) {
2813
- issues.push(errorMessage(error));
2814
- continue;
2815
- }
2816
- if (relationIds.has(relationId)) {
2817
- issues.push(`duplicate relation id "${relationId}"`);
2818
- continue;
2819
- }
2820
- relationIds.add(relationId);
2821
- if (!isTrimmedNonEmpty(row.relationKind)) {
2822
- issues.push(`relation "${relationId}" has an empty or untrimmed kind`);
2823
- continue;
2824
- }
2825
- const spec = specsByKind.get(row.relationKind);
2826
- if (spec == null) {
2827
- issues.push(`relation "${relationId}" has no registered spec for kind "${row.relationKind}"`);
2828
- continue;
2829
- }
2830
- let endpoint0EntityId;
2831
- let endpoint1EntityId;
2832
- try {
2833
- endpoint0EntityId = createEntityId(row.endpoint0EntityId);
2834
- endpoint1EntityId = createEntityId(row.endpoint1EntityId);
2835
- } catch (error) {
2836
- issues.push(errorMessage(error));
2837
- continue;
2838
- }
2839
- const endpoint0 = entitiesById.get(endpoint0EntityId);
2840
- const endpoint1 = entitiesById.get(endpoint1EntityId);
2841
- if (endpoint0 == null || endpoint1 == null) {
2842
- const missing = [endpoint0 == null ? endpoint0EntityId : void 0, endpoint1 == null ? endpoint1EntityId : void 0].filter((value) => value != null).join(", ");
2843
- issues.push(`relation "${relationId}" references missing entity id(s): ${missing}`);
2844
- continue;
2845
- }
2846
- if (!isJsonObject(row.metadata) || !isJsonObject(row.trace)) {
2847
- issues.push(`relation "${relationId}" metadata and trace must contain only JSON values`);
2848
- continue;
2849
- }
2850
- try {
2851
- relations.push(relationIndex.linkRuntime({
2852
- relationId,
2853
- spec,
2854
- endpoints: [endpoint0, endpoint1],
2855
- metadata: row.metadata,
2856
- trace: row.trace
2857
- }));
2858
- } catch (error) {
2859
- issues.push(errorMessage(error));
2860
- }
2861
- }
2862
- if (issues.length === 0) for (const issue of validateEntityRelationSet([...entitiesById.values()], relationIndex, options)) issues.push(`${issue.code}: ${issue.message}`);
2863
- if (issues.length > 0) throw new InvalidEntityRelationRowsError(issues);
2864
- return {
2865
- entitiesById,
2866
- relationIndex,
2867
- relations
2868
- };
2869
- }
2870
- function decodeEntityRow(row, extensionEntityKinds, issues) {
2871
- let entityId;
2872
- try {
2873
- entityId = createEntityId(row.entityId);
2874
- } catch (error) {
2875
- issues.push(errorMessage(error));
2876
- return;
2877
- }
2878
- if (!isTrimmedNonEmpty(row.entityKind)) {
2879
- issues.push(`entity "${entityId}" has an empty or untrimmed kind`);
2880
- return;
2881
- }
2882
- if (isReservedEntityKind(row.entityKind)) {
2883
- issues.push(`entity "${entityId}" uses reserved kind "${row.entityKind}"`);
2884
- return;
2885
- }
2886
- if (!isKnownEntityKind(row.entityKind) && !extensionEntityKinds.has(row.entityKind)) {
2887
- issues.push(`entity "${entityId}" has unregistered extension kind "${row.entityKind}"`);
2888
- return;
2889
- }
2890
- if (!isJsonObject(row.payload)) {
2891
- issues.push(`entity "${entityId}" payload must contain only JSON values`);
2892
- return;
2893
- }
2894
- const reserved = ["entityId", "entityKind"].filter((key) => Object.hasOwn(row.payload, key));
2895
- if (reserved.length > 0) {
2896
- issues.push(`entity "${entityId}" payload contains reserved field(s): ${reserved.join(", ")}`);
2897
- return;
2898
- }
2899
- return {
2900
- ...row.payload,
2901
- entityId,
2902
- entityKind: row.entityKind
2903
- };
2904
- }
2905
- function collectRelationSpecs(extensionSpecs, issues) {
2906
- const specs = /* @__PURE__ */ new Map();
2907
- for (const spec of builtInRelationSpecs) specs.set(spec.kind, spec);
2908
- for (const spec of extensionSpecs) {
2909
- if (!isTrimmedNonEmpty(spec.kind)) {
2910
- issues.push("extension relation spec has an empty or untrimmed kind");
2911
- continue;
2912
- }
2913
- if (specs.has(spec.kind)) {
2914
- issues.push(`relation spec kind "${spec.kind}" is already registered`);
2915
- continue;
2916
- }
2917
- specs.set(spec.kind, spec);
2918
- }
2919
- return specs;
2920
- }
2921
- function isTrimmedNonEmpty(value) {
2922
- return value.length > 0 && value.trim() === value;
2923
- }
2924
- function errorMessage(error) {
2925
- return error instanceof Error ? error.message : String(error);
2926
- }
2927
- //#endregion
2928
- //#region src/document/entity-projection-values.ts
2929
- /** A graph cannot be represented faithfully by the compatibility reader. */
2930
- var EntityTimelineProjectionError = class extends Error {
2931
- constructor(message) {
2932
- super(message);
2933
- this.name = "EntityTimelineProjectionError";
2934
- }
2935
- };
2936
- function fail(message) {
2937
- throw new EntityTimelineProjectionError(message);
2938
- }
2939
- function object(value) {
2940
- return value !== void 0 && value !== null && typeof value === "object" && !Array.isArray(value);
2941
- }
2942
- function finite(value, label) {
2943
- if (typeof value !== "number" || !Number.isFinite(value)) fail(`${label} must be finite`);
2944
- return value;
2945
- }
2946
- function positive(value, label) {
2947
- const result = finite(value, label);
2948
- if (result <= 0) fail(`${label} must be positive`);
2949
- return result;
2950
- }
2951
- function milliseconds(value, label) {
2952
- const result = finite(value, label);
2953
- if (!Number.isSafeInteger(result) || result < 0) fail(`${label} must be non-negative whole milliseconds`);
2954
- return result;
2955
- }
2956
- function range(value, label) {
2957
- if (!object(value)) fail(`${label} must be a numeric range`);
2958
- const start = finite(value.start, `${label}.start`);
2959
- const end = finite(value.end, `${label}.end`);
2960
- if (start >= end) fail(`${label} must be non-empty`);
2961
- return {
2962
- start,
2963
- end
2964
- };
2965
- }
2966
- //#endregion
2967
- //#region src/document/entity-timeline-layout.ts
2968
- /** Validated graph lookup shared by the compatibility layout and projection. */
2969
- var EntityProjectionGraph = class {
2970
- rows;
2971
- entities;
2972
- timeline;
2973
- constructor(rows) {
2974
- this.rows = rows;
2975
- const decoded = decodeEntityRelationRows(rows, { compareMarkerPoints: (_marker, _range, left, right) => finite(left, "range point") - finite(right, "range point") });
2976
- this.entities = new Map([...decoded.entitiesById.values()].map((ref) => [String(ref.entityId), entityToRow(ref.current())]));
2977
- const roots = [...this.entities.values()].filter((row) => row.entityKind === "timeline");
2978
- if (roots.length !== 1) fail("compatibility projection requires exactly one Timeline");
2979
- this.timeline = roots[0];
2980
- }
2981
- entity(id, kind) {
2982
- const row = this.entities.get(id);
2983
- if (row === void 0 || kind !== void 0 && row.entityKind !== kind) fail(`Expected ${kind ?? "Entity"} ${id}`);
2984
- return row;
2985
- }
2986
- adjacent(id, kind) {
2987
- return [...new Set(this.rows.relations.filter((row) => row.relationKind === kind && (row.endpoint0EntityId === id || row.endpoint1EntityId === id)).map((row) => row.endpoint0EntityId === id ? row.endpoint1EntityId : row.endpoint0EntityId))].map((entityId) => this.entity(entityId));
2988
- }
2989
- one(id, relation, kind) {
2990
- const values = this.adjacent(id, relation);
2991
- if (values.length !== 1 || kind !== void 0 && values[0]?.entityKind !== kind) fail(`entity ${id} requires exactly one ${relation}${kind === void 0 ? "" : ` to ${kind}`}`);
2992
- return values[0];
2993
- }
2994
- };
2995
- const roleOrder = {
2996
- caption: 0,
2997
- video_clip: 1,
2998
- speech: 2,
2999
- bgm: 3
3000
- };
3001
- /**
3002
- * Resolve only entity-owned placement facts. This does not choose new anchors,
3003
- * manufacture clips, or mutate a graph while reading. Write-side operations
3004
- * must express any detach/reparent/overlap decision in their entity plan.
3005
- */
3006
- function resolveEntityTimelineLayout(rows) {
3007
- return resolveGraphLayout(new EntityProjectionGraph(rows));
3008
- }
3009
- function resolveGraphLayout(graph) {
3010
- const facts = /* @__PURE__ */ new Map();
3011
- const seenRoles = /* @__PURE__ */ new Set();
3012
- const tracks = graph.adjacent(graph.timeline.entityId, "timeline-track").map((track) => {
3013
- const role = track.payload.role;
3014
- if (track.entityKind !== "track" || typeof role !== "string" || !Object.hasOwn(roleOrder, role)) fail(`unsupported compatibility Track role on ${track.entityId}`);
3015
- if (seenRoles.has(role)) fail(`The compatibility editor supports only one ${role} Track`);
3016
- seenRoles.add(role);
3017
- const typedRole = role;
3018
- if (track.payload.hidden !== void 0 && typeof track.payload.hidden !== "boolean") fail("Track hidden must be boolean");
3019
- const order = track.payload.order === void 0 ? roleOrder[typedRole] : finite(track.payload.order, "Track order");
3020
- const trackFacts = graph.adjacent(track.entityId, "track-clip").map((clip) => {
3021
- if (clip.entityKind !== "clip" || graph.adjacent(clip.entityId, "track-clip").length !== 1) fail(`Clip ${clip.entityId} must belong to exactly one Track`);
3022
- const marker = graph.one(clip.entityId, "clip-marker", "sequence-marker");
3023
- const content = graph.one(marker.entityId, "marker-content");
3024
- if (!(typedRole === "video_clip" ? ["image", "video"] : typedRole === "speech" ? ["audio"] : typedRole === "caption" ? ["caption"] : ["audio"]).includes(content.entityKind)) fail(`unsupported compatibility content kind ${content.entityKind} on ${typedRole} Track`);
3025
- const space = content.payload.coordinateSpace;
3026
- if (space !== "ms" && space !== "milliseconds" && (!object(space) || space.unit !== "ms" && space.unit !== "milliseconds")) fail(`media ${content.entityId} must state millisecond coordinates for this reader`);
3027
- const source = range(marker.payload.sourceRange, "sourceRange");
3028
- const durationFact = marker.payload.duration;
3029
- if (!object(durationFact)) fail(`Marker ${marker.entityId} requires duration`);
3030
- const duration = positive(durationFact.mode === "from-source" ? source.end - source.start : durationFact.value, "duration");
3031
- if (!Number.isSafeInteger(duration)) fail("Compatibility duration must be whole milliseconds");
3032
- const fillTimeline = marker.payload.durationPolicy === "timeline";
3033
- if (marker.payload.durationPolicy !== void 0 && (!fillTimeline || typedRole !== "bgm")) fail("durationPolicy is only supported for timeline-filling background Audio");
3034
- const anchors = graph.rows.relations.filter((row) => row.relationKind === "clip-anchor" && row.endpoint0EntityId === clip.entityId);
3035
- if (anchors.length > 1) fail(`Clip ${clip.entityId} has multiple anchors`);
3036
- const target = marker.payload.targetRange === void 0 ? void 0 : range(marker.payload.targetRange, "targetRange");
3037
- const anchorId = anchors[0]?.endpoint1EntityId;
3038
- let mode;
3039
- let absoluteStart;
3040
- let anchorOffset;
3041
- let clipOrder;
3042
- if (anchorId !== void 0) {
3043
- if (target !== void 0) fail(`Anchored Marker ${marker.entityId} cannot also have targetRange`);
3044
- mode = "anchored";
3045
- anchorOffset = milliseconds(marker.payload.anchorOffset, "anchorOffset");
3046
- } else {
3047
- if (marker.payload.anchorOffset !== void 0) fail(`Marker ${marker.entityId} has anchorOffset without a clip-anchor Relation`);
3048
- if (target !== void 0) {
3049
- mode = "absolute";
3050
- absoluteStart = milliseconds(target.start, "target start");
3051
- milliseconds(target.end, "target end");
3052
- if (Math.abs(target.end - target.start - duration) > 1e-6) fail(`Marker ${marker.entityId} targetRange must match its effective duration`);
3053
- } else {
3054
- mode = "sequential";
3055
- if (clip.payload.order === void 0) fail(`Clip ${clip.entityId} has no placement: targetRange or explicit order is required`);
3056
- clipOrder = finite(clip.payload.order, "Clip order");
3057
- }
3058
- }
3059
- const fact = {
3060
- clip,
3061
- marker,
3062
- content,
3063
- trackId: track.entityId,
3064
- role: typedRole,
3065
- duration,
3066
- mode,
3067
- order: clipOrder,
3068
- absoluteStart,
3069
- anchorId,
3070
- anchorOffset,
3071
- fillTimeline
3072
- };
3073
- facts.set(clip.entityId, fact);
3074
- return fact;
3075
- });
3076
- if (typedRole === "bgm" && trackFacts.length > 1) fail("The compatibility editor supports only one background Audio Clip");
3077
- const sequential = trackFacts.filter((fact) => fact.mode === "sequential").sort((left, right) => left.order - right.order);
3078
- if (new Set(sequential.map((fact) => fact.order)).size !== sequential.length) fail("sequential Clips must have distinct order values");
3079
- sequential.forEach((fact, index) => {
3080
- fact.predecessor = sequential[index - 1]?.clip.entityId;
3081
- });
3082
- return {
3083
- entityId: String(track.entityId),
3084
- role: typedRole,
3085
- order,
3086
- hidden: track.payload.hidden === true,
3087
- trackFacts
3088
- };
3089
- });
3090
- tracks.sort((left, right) => left.order - right.order || left.entityId.localeCompare(right.entityId));
3091
- const resolved = /* @__PURE__ */ new Map();
3092
- const visiting = /* @__PURE__ */ new Set();
3093
- const resolve = (id) => {
3094
- const cached = resolved.get(id);
3095
- if (cached !== void 0) return cached;
3096
- if (visiting.has(id)) fail(`Cyclic Clip placement dependency at ${id}`);
3097
- visiting.add(id);
3098
- const fact = facts.get(id);
3099
- if (fact === void 0) fail(`Placement refers to unplaced Clip ${id}`);
3100
- let start = fact.absoluteStart ?? 0;
3101
- if (fact.mode === "anchored") {
3102
- const host = resolve(fact.anchorId);
3103
- if (fact.role === "speech" && !["video_clip", "bgm"].includes(facts.get(host.clipEntityId).role)) fail("An anchored voiceover must use a visual or BGM Clip as its host");
3104
- start = host.start + fact.anchorOffset;
3105
- } else if (fact.predecessor !== void 0) {
3106
- const prior = resolve(fact.predecessor);
3107
- start = prior.start + prior.duration;
3108
- }
3109
- milliseconds(start + fact.duration, "Clip end");
3110
- const result = {
3111
- clipEntityId: id,
3112
- markerEntityId: fact.marker.entityId,
3113
- contentEntityId: fact.content.entityId,
3114
- trackEntityId: fact.trackId,
3115
- start: milliseconds(start, "Clip start"),
3116
- duration: fact.duration,
3117
- mode: fact.mode,
3118
- ...fact.anchorId === void 0 ? {} : {
3119
- anchorClipEntityId: fact.anchorId,
3120
- anchorOffset: fact.anchorOffset
3121
- }
3122
- };
3123
- visiting.delete(id);
3124
- resolved.set(id, result);
3125
- return result;
3126
- };
3127
- for (const id of facts.keys()) resolve(id);
3128
- const durationMs = Math.max(0, ...[...resolved.values()].filter((clip) => facts.get(clip.clipEntityId).role !== "bgm").map((clip) => clip.start + clip.duration));
3129
- for (const [id, fact] of facts) if (fact.fillTimeline) {
3130
- const clip = resolved.get(id);
3131
- resolved.set(id, {
3132
- ...clip,
3133
- duration: durationMs
3134
- });
3135
- }
3136
- return {
3137
- durationMs,
3138
- clips: resolved,
3139
- tracks: tracks.map(({ trackFacts, ...track }) => ({
3140
- ...track,
3141
- clips: trackFacts.map((fact) => resolved.get(fact.clip.entityId)).sort((left, right) => left.start - right.start || left.clipEntityId.localeCompare(right.clipEntityId))
3142
- }))
3143
- };
3144
- }
3145
- //#endregion
3146
- //#region src/document/entity-projection.ts
3147
- /**
3148
- * One-way compatibility view over the Entity graph. A legacy part is never
3149
- * consulted as an editing fact. Peer IDs appear only in this derived read
3150
- * contract, reconstructed from relations; they are not stored in payloads.
3151
- */
3152
- function projectEntityTimeline(rows) {
3153
- const graph = new EntityProjectionGraph(rows);
3154
- const layout = resolveGraphLayout(graph);
3155
- for (const track of layout.tracks) {
3156
- if (track.role !== "video_clip") continue;
3157
- for (let index = 1; index < track.clips.length; index += 1) {
3158
- const previous = track.clips[index - 1];
3159
- if (track.clips[index].start < previous.start + previous.duration) fail("Overlapping visual Clips require an explicit overlay adapter; the current editor supports one visual lane");
3160
- }
3161
- }
3162
- const parts = {};
3163
- for (const track of layout.tracks) for (const placement of track.clips) {
3164
- const clip = graph.entity(placement.clipEntityId, "clip");
3165
- const marker = graph.entity(placement.markerEntityId, "sequence-marker");
3166
- const content = graph.entity(placement.contentEntityId);
3167
- const volume = volumeSchema.safeParse(clip.payload.volume ?? 0);
3168
- if (!volume.success) fail("Clip volume must be decibels between -60 and 20");
3169
- if (track.role === "video_clip") {
3170
- const asset = mediaAssetFacts(graph, content);
3171
- const source = range(marker.payload.sourceRange, "sourceRange");
3172
- const external = externalLocator(asset, "memota");
3173
- const speed = videoSpeed(content, marker, placement);
3174
- parts[clip.entityId] = { video_clip: {
3175
- id: clip.entityId,
3176
- kind: "video_clip",
3177
- origin_media_id: external.key,
3178
- play_in: content.entityKind === "image" && speed === void 0 ? 0 : source.start,
3179
- play_out: content.entityKind === "image" && speed === void 0 ? placement.duration : source.end,
3180
- volume: volume.data,
3181
- ...speed === void 0 ? {} : { speed_shift: speed }
3182
- } };
3183
- } else if (track.role === "speech") {
3184
- const asset = mediaAssetFacts(graph, content);
3185
- requireUntrimmedAudio(content, marker, placement);
3186
- const external = externalLocator(asset, "memota-speech");
3187
- const renderEdges = graph.adjacent(content.entityId, "phonetic-script-render");
3188
- const timbreEdges = graph.adjacent(content.entityId, "voice-timbre");
3189
- const assembled = renderEdges.length > 0 || timbreEdges.length > 0 ? assemblePhoneticScriptContent(rows, graph.one(content.entityId, "phonetic-script-render", "phonetic-script").entityId) : void 0;
3190
- if (timbreEdges.length > 1) fail("A voiceover resolves at most one Voice identity");
3191
- const voice = timbreEdges.length === 0 ? void 0 : graph.one(content.entityId, "voice-timbre", "voice").payload.voice;
3192
- if (voice !== void 0 && (!object(voice) || voice.system !== "voice-library" || typeof voice.key !== "string")) fail("Voice must use an explicit voice-library locator");
3193
- const captionIds = layout.tracks.flatMap((candidate) => candidate.role === "caption" ? candidate.clips.filter((caption) => caption.anchorClipEntityId === clip.entityId).map((caption) => caption.clipEntityId) : []);
3194
- parts[clip.entityId] = { speech: {
3195
- id: clip.entityId,
3196
- kind: "speech",
3197
- media_duration_ms: placement.duration,
3198
- audio_storage_key: storageKey(asset),
3199
- origin_speech_id: external.key,
3200
- audio_script: assembled?.text ?? (graph.adjacent(content.entityId, "audio-script-source").length > 0 ? assembleScriptText(graph.one(content.entityId, "audio-script-source", "audio-script")) : ""),
3201
- volume: volume.data,
3202
- voice: object(voice) ? {
3203
- id: typeof voice.key === "string" ? voice.key : void 0,
3204
- name: typeof voice.name === "string" ? voice.name : void 0
3205
- } : void 0,
3206
- caption_ids: captionIds
3207
- } };
3208
- } else if (track.role === "caption") {
3209
- const assembled = assembleCaptionContent(rows, content.entityId);
3210
- const text = assembled.text;
3211
- const cues = captionDisplayCues(assembled, marker, placement.duration);
3212
- if (marker.payload.timeRemapping !== void 0) fail("Caption timeRemapping is not supported by this reader");
3213
- const style = captionStyle(content.payload.style);
3214
- const anchor = placement.anchorClipEntityId === void 0 ? void 0 : layout.clips.get(placement.anchorClipEntityId);
3215
- const anchoredToSpeech = anchor !== void 0 && trackRoleOf(layout, anchor.trackEntityId) === "speech";
3216
- parts[clip.entityId] = { caption: {
3217
- id: clip.entityId,
3218
- kind: "caption",
3219
- text,
3220
- ...cues === void 0 ? {} : { display_cues: cues },
3221
- speech_part_id: anchoredToSpeech ? placement.anchorClipEntityId : void 0,
3222
- start_ms: anchoredToSpeech ? placement.anchorOffset : 0,
3223
- initial_duration_ms: placement.duration,
3224
- ...style === void 0 ? {} : { style }
3225
- } };
3226
- } else {
3227
- const asset = mediaAssetFacts(graph, content);
3228
- const external = externalLocator(asset, "memota");
3229
- if (marker.payload.durationPolicy !== "timeline") fail("Background Audio requires an explicit timeline-fill durationPolicy");
3230
- if (marker.payload.timeRemapping !== void 0) fail("BGM timeRemapping is not supported by this reader");
3231
- const source = range(marker.payload.sourceRange, "sourceRange");
3232
- const extent = content.payload.extent;
3233
- if (!object(extent) || extent.start !== source.start || extent.end !== source.end) fail("Background Audio compatibility requires the complete source");
3234
- parts[clip.entityId] = { bgm: {
3235
- id: clip.entityId,
3236
- kind: "bgm",
3237
- audio_storage_key: storageKey(asset),
3238
- origin_media_id: external.key,
3239
- volume: volume.data
3240
- } };
3241
- }
3242
- }
3243
- const document = {
3244
- timeline: graph.timeline.payload.unit_time_ms === void 0 ? void 0 : { unit_time_ms: positive(graph.timeline.payload.unit_time_ms, "unit_time_ms") },
3245
- tracks: layout.tracks.map((track) => ({
3246
- id: track.entityId,
3247
- parts_kind: track.role,
3248
- is_hidden: track.hidden,
3249
- items: track.clips.map((clip) => clip.mode === "anchored" ? {
3250
- part_id: clip.clipEntityId,
3251
- time_position: {
3252
- mode: "anchored",
3253
- anchorPartId: clip.anchorClipEntityId,
3254
- offsetMs: clip.anchorOffset
3255
- },
3256
- fallback_abs_ms: clip.start
3257
- } : {
3258
- part_id: clip.clipEntityId,
3259
- time_position: {
3260
- mode: "absolute",
3261
- offsetMs: clip.start
3262
- }
3263
- })
3264
- })),
3265
- part_library: parts
3266
- };
3267
- assertValidVideoDocument(document);
3268
- return document;
3269
- }
3270
- function trackRoleOf(layout, trackEntityId) {
3271
- return layout.tracks.find((track) => track.entityId === trackEntityId)?.role;
3272
- }
3273
- /**
3274
- * Media facts are read from the variant itself: a media variant owns its
3275
- * Asset identity and carries `external`/`storageKey` directly. Dual-entity
3276
- * media graphs are rejected instead of being resolved through a legacy
3277
- * `physical-asset` binding.
3278
- */
3279
- function mediaAssetFacts(graph, content) {
3280
- if (graph.adjacent(content.entityId, "physical-asset").length > 0) fail("Media " + content.entityId + " owns its Asset identity; remove its physical-asset Relation");
3281
- if (!object(content.payload.external)) fail("Media " + content.entityId + " must carry its own Asset external identity");
3282
- return {
3283
- entityId: String(content.entityId),
3284
- payload: content.payload
3285
- };
3286
- }
3287
- function externalLocator(asset, system) {
3288
- const value = asset.payload.external;
3289
- if (!object(value) || value.system !== system || typeof value.key !== "string" || value.key.trim() === "") fail("Asset " + asset.entityId + " requires an explicit " + system + " external key");
3290
- return { key: value.key };
3291
- }
3292
- function storageKey(asset) {
3293
- if (typeof asset.payload.storageKey !== "string" || asset.payload.storageKey.trim() === "") fail("Asset " + asset.entityId + " requires its factual storageKey");
3294
- return asset.payload.storageKey;
3295
- }
3296
- function captionStyle(value) {
3297
- if (value === void 0) return void 0;
3298
- if (!object(value)) fail("Caption style must be an object");
3299
- const { font, ...owned } = structuredClone(value);
3300
- const fields = {
3301
- fontSize: "font_size",
3302
- fontColor: "font_color",
3303
- fontWeight: "font_weight",
3304
- entranceAnimation: "entrance_animation",
3305
- entranceAnimationDurationMs: "entrance_animation_duration_ms",
3306
- strokeColor: "stroke_color",
3307
- strokeWidth: "stroke_width",
3308
- positionX: "position_x",
3309
- positionY: "position_y"
3310
- };
3311
- const style = {};
3312
- for (const [key, field] of Object.entries(owned)) {
3313
- if (!Object.hasOwn(fields, key)) fail("Unsupported Caption style field " + key);
3314
- style[fields[key]] = field;
3315
- }
3316
- if (font !== void 0) {
3317
- if (!object(font) || font.system !== "font-library" || typeof font.key !== "string") fail("Caption font requires a font-library locator");
3318
- return {
3319
- ...style,
3320
- font_id: font.key
3321
- };
3322
- }
3323
- return style;
3324
- }
3325
- function requireUntrimmedAudio(content, marker, placement) {
3326
- const source = range(marker.payload.sourceRange, "sourceRange");
3327
- const extent = content.payload.extent;
3328
- if (!object(extent) || extent.start !== source.start || extent.end !== source.end || placement.duration !== source.end - source.start || marker.payload.timeRemapping !== void 0) fail("Voice compatibility requires the complete, unremapped take");
3329
- }
3330
- function videoSpeed(content, marker, placement) {
3331
- const remapping = marker.payload.timeRemapping;
3332
- if (content.entityKind === "image" && remapping === void 0) return void 0;
3333
- const source = range(marker.payload.sourceRange, "sourceRange");
3334
- if (remapping !== void 0) {
3335
- if (!object(remapping) || remapping.kind !== "linear") fail("unsupported timeRemapping on " + marker.entityId);
3336
- if (Object.keys(remapping).some((key) => key !== "kind" && key !== "rate" && key !== "mode")) fail("Unsupported linear timeRemapping fields");
3337
- const rate = positive(remapping.rate, "linear remapping rate");
3338
- if (Math.round((source.end - source.start) / rate) !== placement.duration) fail("timeRemapping on " + marker.entityId + " must agree with Marker duration");
3339
- if (remapping.mode !== void 0 && typeof remapping.mode !== "string") fail("Linear remapping mode must be a string");
3340
- return {
3341
- category: "linear",
3342
- mode: typeof remapping.mode === "string" ? remapping.mode : "constant",
3343
- config: { linear: { speed: rate } }
3344
- };
3345
- }
3346
- const rate = (source.end - source.start) / placement.duration;
3347
- return rate === 1 ? void 0 : {
3348
- category: "linear",
3349
- mode: "constant",
3350
- config: { linear: { speed: rate } }
3351
- };
3352
- }
3353
- /** Preserve selected text intervals without minting synthetic editable Clip identities. */
3354
- function captionDisplayCues(assembled, marker, duration) {
3355
- const ranges = assembled.caption.payload.segmentRanges;
3356
- if (!Array.isArray(ranges)) return void 0;
3357
- const source = range(marker.payload.sourceRange, "Caption sourceRange");
3358
- const scale = duration / (source.end - source.start);
3359
- return assembled.segments.flatMap((segment) => {
3360
- const timing = ranges.find((entry) => object(entry) && entry.segmentId === segment.segmentId);
3361
- if (!object(timing)) fail(`Caption timing is missing for selected segment ${segment.segmentId}`);
3362
- const intrinsic = range({
3363
- start: timing.startMs,
3364
- end: timing.endMs
3365
- }, "Caption segmentRange");
3366
- const start = Math.max(source.start, intrinsic.start);
3367
- const end = Math.min(source.end, intrinsic.end);
3368
- if (end <= start) return [];
3369
- const startMs = Math.round((start - source.start) * scale);
3370
- const endMs = Math.round((end - source.start) * scale);
3371
- return endMs > startMs ? [{
3372
- segmentId: segment.segmentId,
3373
- text: segment.text,
3374
- startMs,
3375
- durationMs: endMs - startMs
3376
- }] : [];
3377
- });
3378
- }
3379
- //#endregion
3380
- //#region src/entity-crdt/field-changes.ts
3381
- const atomicFields = new Set([
3382
- "sequence",
3383
- "sourceRange",
3384
- "targetRange",
3385
- "duration",
3386
- "extent",
3387
- "timeRemapping",
3388
- "textRange",
3389
- "selection",
3390
- "external",
3391
- "coordinateSpace"
3392
- ]);
3393
- const textFields = new Set(["text", "phonemeScript"]);
3394
- const orderedFields = new Set([
3395
- "segments",
3396
- "segmentRanges",
3397
- "baseEntityIds"
3398
- ]);
3399
- const unsafeKeys = new Set([
3400
- "__proto__",
3401
- "prototype",
3402
- "constructor"
3403
- ]);
3404
- function listElementId(value) {
3405
- const id = typeof value === "string" ? value : isJsonObject(value) ? value.segmentId : void 0;
3406
- if (typeof id !== "string" || !id.trim()) throw new Error("List elements require a nonempty segmentId or string identity");
3407
- return id;
3408
- }
3409
- function assertFieldChanges(changes) {
3410
- if (!Array.isArray(changes) || changes.length === 0) throw new Error("changes must be a nonempty array");
3411
- for (const change of changes) {
3412
- if (!isJsonObject(change) || ![
3413
- "set",
3414
- "unset",
3415
- "text.splice",
3416
- "list.insert",
3417
- "list.move",
3418
- "list.remove"
3419
- ].includes(change.op)) throw new Error("Unknown field operation");
3420
- if (!Array.isArray(change.path) || !change.path.length || typeof change.path[0] !== "string") throw new Error("Field paths must start with a field name");
3421
- for (const part of change.path) if (typeof part === "string") {
3422
- if (!part || unsafeKeys.has(part)) throw new Error("Invalid field name");
3423
- } else if (!isJsonObject(part) || Object.keys(part).length !== 1 || typeof part.elementId !== "string" || !part.elementId.trim()) throw new Error("List paths require { elementId }; numeric indices are not supported");
3424
- }
3425
- }
3426
- /** Resolve against the sequential causal view; the numeric path never crosses the API boundary. */
3427
- function resolveFieldPath(payload, path) {
3428
- let value = payload;
3429
- const resolved = [];
3430
- for (const [index, part] of path.entries()) if (typeof part === "string") {
3431
- if (!isJsonObject(value)) throw new Error(`Field path does not reach a map: ${part}`);
3432
- if (index < path.length - 1 && atomicFields.has(part)) throw new Error(`Atomic field ${part} must be changed as one value`);
3433
- resolved.push(part);
3434
- value = value[part];
3435
- } else {
3436
- if (!Array.isArray(value)) throw new Error("Element selector requires a list");
3437
- const matches = value.flatMap((item, i) => listElementId(item) === part.elementId ? [i] : []);
3438
- if (matches.length !== 1) throw new Error(`Missing or ambiguous list element ${part.elementId}`);
3439
- resolved.push(matches[0]);
3440
- value = value[matches[0]];
3441
- }
3442
- return resolved;
3443
- }
3444
- /** Detached plan evaluation. Native compilation replays the original operations, not this snapshot. */
3445
- function applyFieldChanges(payload, changes) {
3446
- assertFieldChanges(changes);
3447
- const result = structuredClone(payload);
3448
- for (const change of changes) {
3449
- const path = resolveFieldPath(result, change.path);
3450
- const key = path.at(-1);
3451
- if (typeof key !== "string") throw new Error("Change fields inside a list element or use list operations");
3452
- let parent = result;
3453
- for (const part of path.slice(0, -1)) parent = parent[part];
3454
- if (!isJsonObject(parent)) throw new Error("Field parent is not a map");
3455
- const mutable = parent;
3456
- const value = mutable[key];
3457
- if ([
3458
- "entityId",
3459
- "entityKind",
3460
- "entity_id",
3461
- "entity_kind",
3462
- "segmentId"
3463
- ].includes(key)) throw new Error(`Identity field ${key} cannot be edited`);
3464
- switch (change.op) {
3465
- case "set":
3466
- if (textFields.has(key) || orderedFields.has(key) || !atomicFields.has(key) && (isJsonObject(value) || isJsonObject(change.value) || Array.isArray(value) || Array.isArray(change.value))) throw new Error(`Field ${key} requires a text, list, or leaf operation; snapshot replacement is not allowed`);
3467
- if (change.value === void 0 || !isJsonObject({ value: change.value })) throw new Error("set requires a JSON value");
3468
- if (value !== void 0 && value !== null && change.value !== null && typeof value !== typeof change.value) throw new Error(`Field ${key} cannot change type`);
3469
- mutable[key] = structuredClone(change.value);
3470
- break;
3471
- case "unset":
3472
- if (!Object.hasOwn(parent, key)) throw new Error(`Field ${key} is absent`);
3473
- delete mutable[key];
3474
- break;
3475
- case "text.splice": {
3476
- if (!textFields.has(key) || typeof value !== "string") throw new Error(`Field ${key} is not collaborative text`);
3477
- const chars = Array.from(value);
3478
- if (!Number.isSafeInteger(change.index) || !Number.isSafeInteger(change.deleteCount) || change.index < 0 || change.deleteCount < 0 || change.index + change.deleteCount > chars.length || typeof change.text !== "string") throw new Error("Invalid text splice range");
3479
- chars.splice(change.index, change.deleteCount, ...Array.from(change.text));
3480
- mutable[key] = chars.join("");
3481
- break;
3482
- }
3483
- default: {
3484
- if (!orderedFields.has(key) || !Array.isArray(value)) throw new Error(`Field ${key} is not a collaborative list`);
3485
- const ids = value.map(listElementId);
3486
- if (new Set(ids).size !== ids.length) throw new Error("Duplicate collaborative list identity");
3487
- const requireIndex = (id) => {
3488
- const index = ids.indexOf(id);
3489
- if (index < 0) throw new Error(`Unknown list element ${id}`);
3490
- return index;
3491
- };
3492
- if (change.op === "list.remove") value.splice(requireIndex(change.elementId), 1);
3493
- else {
3494
- if (change.beforeElementId !== null && typeof change.beforeElementId !== "string") throw new Error("beforeElementId must be an identity or null");
3495
- const before = change.beforeElementId === null ? value.length : requireIndex(change.beforeElementId);
3496
- if (change.op === "list.insert") {
3497
- const id = listElementId(change.value);
3498
- if (ids.includes(id)) throw new Error(`Duplicate list element ${id}`);
3499
- value.splice(before, 0, structuredClone(change.value));
3500
- } else {
3501
- if (change.elementId === change.beforeElementId) throw new Error("Cannot move a list element before itself");
3502
- const from = requireIndex(change.elementId);
3503
- const [item] = value.splice(from, 1);
3504
- value.splice(before > from ? before - 1 : before, 0, item);
3505
- }
3506
- }
3507
- }
3508
- }
3509
- }
3510
- return result;
3511
- }
3512
- //#endregion
3513
- //#region src/entity-crdt/json-containers.ts
3514
- function equalJson(a, b) {
3515
- return canonicalJson(a) === canonicalJson(b);
3516
- }
3517
- function canonicalJson(value) {
3518
- if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
3519
- if (value !== null && typeof value === "object") return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(",")}}`;
3520
- return JSON.stringify(value);
3521
- }
3522
- /** Compile only the changed fields; untouched containers retain their operation identity. */
3523
- function writeObject(map, before, after) {
3524
- for (const key of Object.keys(before)) if (!Object.hasOwn(after, key)) map.delete(key);
3525
- for (const [key, value] of Object.entries(after)) {
3526
- if (equalJson(before[key], value)) continue;
3527
- if (atomicFields.has(key)) map.set(key, value);
3528
- else if (typeof value === "string" && textFields.has(key)) map.ensureMergeableText(key).update(value);
3529
- else if (Array.isArray(value) && orderedFields.has(key)) writeList(map.ensureMergeableMovableList(key), value);
3530
- else if (isJsonObject(value)) writeObject(map.ensureMergeableMap(key), isJsonObject(before[key]) ? before[key] : {}, value);
3531
- else map.set(key, value);
3532
- }
3533
- }
3534
- function readItem(list, index) {
3535
- const value = list.get(index);
3536
- return value instanceof LoroMap ? value.toJSON() : value;
3537
- }
3538
- function writeList(list, values) {
3539
- const wanted = values.map(listElementId);
3540
- if (new Set(wanted).size !== wanted.length) throw new Error("Duplicate collaborative list identity");
3541
- for (let index = list.length - 1; index >= 0; index--) if (!wanted.includes(listElementId(readItem(list, index)))) list.delete(index, 1);
3542
- for (let index = 0; index < values.length; index++) {
3543
- const value = values[index];
3544
- const key = wanted[index];
3545
- let found = -1;
3546
- for (let cursor = index; cursor < list.length; cursor++) if (listElementId(readItem(list, cursor)) === key) {
3547
- found = cursor;
3548
- break;
3549
- }
3550
- if (found === -1) if (isJsonObject(value)) writeObject(list.insertContainer(index, new LoroMap()), {}, value);
3551
- else list.insert(index, value);
3552
- else {
3553
- if (found !== index) list.move(found, index);
3554
- const current = list.get(index);
3555
- if (isJsonObject(value)) {
3556
- if (!(current instanceof LoroMap)) throw new Error("Collaborative list item changed type");
3557
- writeObject(current, current.toJSON(), value);
3558
- }
3559
- }
3560
- }
3561
- }
3562
- function requireText(map, path) {
3563
- let value = map;
3564
- for (const part of path) if (value instanceof LoroMap && typeof part === "string") value = value.get(part);
3565
- else if (value instanceof LoroMovableList && typeof part === "number") value = value.get(part);
3566
- else throw new Error("Invalid collaborative text path");
3567
- if (!(value instanceof LoroText)) throw new Error("Field is not collaborative text");
3568
- return value;
3569
- }
3570
- /** Apply the authored operation directly, preserving text positions and moved item identity. */
3571
- function applyNativeFieldChange(map, path, change) {
3572
- let parent = map;
3573
- for (const part of path.slice(0, -1)) if (parent instanceof LoroMap && typeof part === "string") parent = parent.get(part);
3574
- else if (parent instanceof LoroMovableList && typeof part === "number") parent = parent.get(part);
3575
- else throw new Error("Invalid native field path");
3576
- const key = path.at(-1);
3577
- if (!(parent instanceof LoroMap) || typeof key !== "string") throw new Error("Invalid native field parent");
3578
- if (change.op === "set") {
3579
- parent.set(key, change.value);
3580
- return;
3581
- }
3582
- if (change.op === "unset") {
3583
- parent.delete(key);
3584
- return;
3585
- }
3586
- const value = parent.get(key);
3587
- if (change.op === "text.splice") {
3588
- if (!(value instanceof LoroText)) throw new Error("Field is not collaborative text");
3589
- const start = value.convertPos(change.index, "unicode", "utf16");
3590
- const end = value.convertPos(change.index + change.deleteCount, "unicode", "utf16");
3591
- value.splice(start, end - start, change.text);
3592
- return;
3593
- }
3594
- if (!(value instanceof LoroMovableList)) throw new Error("Field is not a collaborative list");
3595
- applyNativeListChange(value, change);
3596
- }
3597
- function applyNativeListChange(list, change) {
3598
- const ids = Array.from({ length: list.length }, (_, i) => listElementId(readItem(list, i)));
3599
- const index = (id) => {
3600
- const found = ids.indexOf(id);
3601
- if (found < 0) throw new Error(`Unknown list element ${id}`);
3602
- return found;
3603
- };
3604
- if (change.op === "list.remove") {
3605
- list.delete(index(change.elementId), 1);
3606
- return;
3607
- }
3608
- const before = change.beforeElementId === null ? list.length : index(change.beforeElementId);
3609
- if (change.op === "list.insert") if (isJsonObject(change.value)) writeObject(list.insertContainer(before, new LoroMap()), {}, change.value);
3610
- else list.insert(before, change.value);
3611
- else {
3612
- const from = index(change.elementId);
3613
- const to = before > from ? before - 1 : before;
3614
- if (from !== to) list.move(from, to);
3615
- }
3616
- }
3617
- //#endregion
3618
- //#region src/entity-crdt/audio-script-assets.ts
3619
- /** A resource is a snapshot of text; the native Loro text remains the editing authority. */
3620
- function audioScriptAssetContent(payload) {
3621
- assembleScriptText({
3622
- entityId: createEntityId("script-validation"),
3623
- entityKind: "audio-script",
3624
- payload
3625
- });
3626
- return { segments: structuredClone(payload.segments) };
3627
- }
3628
- function audioScriptAssetHash(payload) {
3629
- return bytesToHex(sha256(new TextEncoder().encode(canonicalJson(audioScriptAssetContent(payload)))));
3630
- }
3631
- function hasAudioScriptAsset(payload) {
3632
- return isJsonObject(payload.external) && payload.external.system === "memota" && typeof payload.external.key === "string";
3633
- }
3634
- /** Internal fingerprint prevents a resource from silently describing an older text revision. */
3635
- function audioScriptAssetFields(payload, assetId) {
3636
- if (!assetId.trim()) throw new Error("AudioScript resource writer returned an empty asset ID");
3637
- return {
3638
- external: {
3639
- system: "memota",
3640
- key: assetId
3641
- },
3642
- assetContentHash: audioScriptAssetHash(payload)
3643
- };
3644
- }
3645
- //#endregion
3646
- //#region src/entity-crdt/ordering.ts
3647
- /** Domain order is scoped by membership; relation storage has no global order. */
3648
- function entityOrderGroups(rows) {
3649
- const entities = new Map(rows.entities.map((row) => [String(row.entityId), row]));
3650
- const groups = /* @__PURE__ */ new Map();
3651
- for (const relation of rows.relations) {
3652
- const childKind = relation.relationKind === "timeline-track" ? "track" : relation.relationKind === "track-clip" ? "clip" : null;
3653
- if (!childKind) continue;
3654
- const endpoints = [relation.endpoint0EntityId, relation.endpoint1EntityId];
3655
- const childId = endpoints.find((id) => entities.get(id)?.entityKind === childKind);
3656
- if (!childId) continue;
3657
- const child = entities.get(childId);
3658
- if (typeof child.payload.order !== "number") continue;
3659
- const parent = endpoints.find((id) => id !== childId);
3660
- const values = groups.get(parent) ?? [];
3661
- values.push({
3662
- id: childId,
3663
- order: child.payload.order
3664
- });
3665
- groups.set(parent, values);
3666
- }
3667
- return new Map([...groups].map(([parent, values]) => [parent, values.sort((a, b) => a.order - b.order || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)).map((item) => item.id)]));
3668
- }
3669
- function ordering(doc) {
3670
- const map = doc.getMap("medeo").get("ordering");
3671
- if (!(map instanceof LoroMap)) throw new Error("Missing native entity ordering");
3672
- return map;
3673
- }
3674
- /** Returns a derived ordinal while the stable element retains its native move identity. */
3675
- function entityOrdinal(doc, root) {
3676
- let found;
3677
- for (const key of ordering(doc).keys()) {
3678
- const list = ordering(doc).get(key);
3679
- if (!(list instanceof LoroMovableList)) throw new Error("Invalid entity order container");
3680
- const index = list.toArray().indexOf(root);
3681
- if (index < 0) continue;
3682
- if (found !== void 0) throw new Error("Entity belongs to multiple ordered groups");
3683
- found = index;
3684
- }
3685
- return found;
3686
- }
3687
- /** Move existing elements, insert new identities and delete removed members on the causal list. */
3688
- function writeEntityOrder(doc, group, roots, token) {
3689
- if (new Set(roots).size !== roots.length) throw new Error("Duplicate ordered entity identity");
3690
- const list = ordering(doc).ensureMergeableMovableList(group);
3691
- const before = list.toArray();
3692
- for (let index = list.length - 1; index >= 0; index--) if (!roots.includes(String(list.get(index)))) list.delete(index, 1);
3693
- roots.forEach((root, index) => {
3694
- const current = list.toArray().indexOf(root);
3695
- if (current < 0) list.insert(index, root);
3696
- else if (current !== index) list.move(current, index);
3697
- });
3698
- if (token) {
3699
- const editing = doc.getMap("medeo").get("editing");
3700
- for (const root of new Set([...before, ...roots])) {
3701
- if (before.indexOf(root) < 0 || before.indexOf(root) === roots.indexOf(root)) continue;
3702
- editing.get(root).get("changes").set(token, true);
3703
- }
3704
- }
3705
- }
3706
- //#endregion
3707
- //#region src/entity-crdt/entity-document.ts
3708
- const LORO_ENTITY_SCHEMA = "medeo.entities.loro.v1";
3709
- const MATERIALIZE_ORIGIN = "medeo.materialize";
3710
- function hash(value) {
3711
- return bytesToHex(sha256(new TextEncoder().encode(canonicalJson(value))));
3712
- }
3713
- function clone(value) {
3714
- return structuredClone(value);
3715
- }
3716
- function root(doc) {
3717
- return doc.getMap("medeo");
3718
- }
3719
- function requireMap(parent, key) {
3720
- const value = parent.get(key);
3721
- if (!(value instanceof LoroMap)) throw new Error(`Missing Loro map ${key}`);
3722
- return value;
3723
- }
3724
- function section(doc, key) {
3725
- return requireMap(root(doc), key);
3726
- }
3727
- function workspace(doc, id) {
3728
- const value = section(doc, "editing").get(id);
3729
- if (!(value instanceof LoroMap)) throw new Error(`Unknown entity editing identity ${id}`);
3730
- return value;
3731
- }
3732
- function content(map) {
3733
- return requireMap(map, "content").toJSON();
3734
- }
3735
- function entityContent(doc, key) {
3736
- const payload = content(workspace(doc, key));
3737
- const order = entityOrdinal(doc, key);
3738
- return order === void 0 ? payload : {
3739
- ...payload,
3740
- order
3741
- };
3742
- }
3743
- function bases(map) {
3744
- const links = requireMap(map, "bases");
3745
- return links.keys().sort((a, b) => a < b ? -1 : a > b ? 1 : 0).map((key) => String(links.get(key)));
3746
- }
3747
- function owned(payload) {
3748
- const { baseEntityIds: _bases, ...fields } = payload;
3749
- return fields;
3750
- }
3751
- function baseIds(payload) {
3752
- const ids = payload.baseEntityIds ?? [];
3753
- if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string") || new Set(ids).size !== ids.length) throw new Error("baseEntityIds must contain unique entity IDs");
3754
- return ids;
3755
- }
3756
- function family(doc, id) {
3757
- const value = section(doc, "origins").get(id);
3758
- if (typeof value === "string") return value;
3759
- for (const [key, value] of currentIds(doc)) if (value === id) return key;
3760
- throw new Error(`Unknown entity ${id}`);
3761
- }
3762
- function currentIds(doc) {
3763
- const result = /* @__PURE__ */ new Map();
3764
- for (const key of section(doc, "editing").keys().sort((a, b) => a < b ? -1 : a > b ? 1 : 0)) {
3765
- const map = workspace(doc, key);
3766
- if (map.get("deleted") === true) continue;
3767
- const tokens = requireMap(map, "changes").keys().sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
3768
- const initial = section(doc, "entities").get(key);
3769
- const { id: _id, kind: _kind, ...initialPayload } = isJsonObject(initial) ? initial : {};
3770
- const payload = entityContent(doc, key);
3771
- const changed = tokens.length > 0 || initial !== void 0 && !equalJson(owned(initialPayload), payload);
3772
- result.set(key, changed ? `entity_${hash([
3773
- key,
3774
- tokens,
3775
- payload
3776
- ])}` : key);
3777
- }
3778
- return result;
3779
- }
3780
- function currentId(doc, id, ids = currentIds(doc)) {
3781
- const resolved = ids.get(family(doc, id));
3782
- if (resolved === void 0) throw new Error(`Referenced entity ${id} was deleted`);
3783
- return resolved;
3784
- }
3785
- /** Plain domain objects assembled from native Loro state, never a second writable authority. */
3786
- function readEntityDocument(doc, allowSelectionConflicts = false) {
3787
- if (root(doc).get("schema") !== "medeo.entities.loro.v1") throw new Error("Document has no Loro entity state");
3788
- const ids = currentIds(doc);
3789
- const entities = [...ids].map(([key, entityId]) => {
3790
- const map = workspace(doc, key);
3791
- const baseEntityIds = bases(map).map((id) => currentId(doc, id, ids));
3792
- return {
3793
- entityId: createEntityId(entityId),
3794
- entityKind: map.get("kind"),
3795
- payload: {
3796
- ...entityContent(doc, key),
3797
- ...baseEntityIds.length ? { baseEntityIds } : {}
3798
- }
3799
- };
3800
- });
3801
- const relations = [];
3802
- for (const key of section(doc, "relations").keys().sort((a, b) => a < b ? -1 : a > b ? 1 : 0)) {
3803
- const map = section(doc, "relations").get(key);
3804
- if (!(map instanceof LoroMap) || map.get("deleted") === true) continue;
3805
- const original = map.get("identity");
3806
- if (original.endpoints.some((id) => !ids.has(family(doc, id)))) continue;
3807
- const endpoints = original.endpoints.map((id) => currentId(doc, id, ids));
3808
- const relationId = equalJson(endpoints, original.endpoints) ? key : `relation_${hash([key, endpoints])}`;
3809
- relations.push({
3810
- relationId: createRelationId(relationId),
3811
- relationKind: original.kind,
3812
- endpoint0EntityId: createEntityId(endpoints[0]),
3813
- endpoint1EntityId: createEntityId(endpoints[1]),
3814
- metadata: requireMap(map, "metadata").toJSON(),
3815
- trace: requireMap(map, "trace").toJSON()
3816
- });
3817
- }
3818
- const project = {};
3819
- for (const [key, value] of Object.entries(section(doc, "attachments").toJSON())) {
3820
- if (typeof value !== "string") throw new Error(`Invalid project attachment ${key}`);
3821
- project[key] = currentId(doc, value, ids);
3822
- }
3823
- const state = {
3824
- rows: {
3825
- entities,
3826
- relations
3827
- },
3828
- project
3829
- };
3830
- if (!allowSelectionConflicts) for (const [key, id] of ids) {
3831
- const fingerprint = selectionFingerprint(state.rows, id);
3832
- if (fingerprint !== void 0 && workspace(doc, key).get("selectionBaseline") !== fingerprint) throw new Error(`Caption text selection conflict at ${id}: source text changed; revise its text ranges explicitly`);
3833
- }
3834
- return state;
3835
- }
3836
- /** Native editing containers survive domain version changes and merge independently. */
3837
- var LoroEntityDocument = class LoroEntityDocument {
3838
- doc;
3839
- validate;
3840
- undoManager;
3841
- constructor(doc, validate) {
3842
- this.doc = doc;
3843
- this.validate = validate;
3844
- this.undoManager = new UndoManager(doc, {
3845
- mergeInterval: 0,
3846
- excludeOriginPrefixes: [MATERIALIZE_ORIGIN]
3847
- });
3848
- }
3849
- /** Open a causal snapshot using the same Loro runtime as the compiler. */
3850
- static fromSnapshot(snapshot, validate) {
3851
- const doc = new LoroDoc();
3852
- doc.import(snapshot);
3853
- readEntityDocument(doc);
3854
- return new LoroEntityDocument(doc, validate);
3855
- }
3856
- static create(rows, project = {}, peerId) {
3857
- const doc = new LoroDoc();
3858
- if (peerId !== void 0) doc.setPeerId(peerId);
3859
- root(doc).set("schema", LORO_ENTITY_SCHEMA);
3860
- for (const name of [
3861
- "editing",
3862
- "entities",
3863
- "origins",
3864
- "relations",
3865
- "project",
3866
- "attachments",
3867
- "ordering"
3868
- ]) root(doc).ensureMergeableMap(name);
3869
- for (const row of rows.entities) apply(doc, {
3870
- type: "create",
3871
- row
3872
- });
3873
- for (const row of rows.relations) apply(doc, {
3874
- type: "relation",
3875
- row
3876
- });
3877
- for (const [slot, entityId] of Object.entries(project)) apply(doc, {
3878
- type: "attach",
3879
- slot,
3880
- entityId
3881
- });
3882
- for (const [group, ids] of entityOrderGroups(rows)) writeEntityOrder(doc, group, ids);
3883
- const initialState = readEntityDocument(doc, true);
3884
- for (const row of initialState.rows.entities) {
3885
- const fingerprint = selectionFingerprint(initialState.rows, row.entityId);
3886
- if (fingerprint !== void 0) workspace(doc, row.entityId).set("selectionBaseline", fingerprint);
3887
- }
3888
- assertState(readEntityDocument(doc));
3889
- materialize(doc);
3890
- doc.commit({ origin: MATERIALIZE_ORIGIN });
3891
- return new LoroEntityDocument(doc);
3892
- }
3893
- snapshot() {
3894
- return readEntityDocument(this.doc);
3895
- }
3896
- relationsOf(entityId) {
3897
- const id = currentIds(this.doc).get(family(this.doc, entityId));
3898
- if (id === void 0) return [];
3899
- return this.snapshot().rows.relations.filter((row) => row.endpoint0EntityId === id || row.endpoint1EntityId === id);
3900
- }
3901
- /** Resolve a queued edit target through its native identity without changing history. */
3902
- resolveCurrentEntityId(id) {
3903
- return currentId(this.doc, id);
3904
- }
3905
- getVersion(id) {
3906
- const entity = section(this.doc, "entities").get(id);
3907
- if (!isJsonObject(entity)) return void 0;
3908
- const { id: entityId, kind, ...payload } = entity;
3909
- if (typeof entityId !== "string") throw new Error("Invalid stored entity ID");
3910
- return {
3911
- entityId: createEntityId(entityId),
3912
- entityKind: kind,
3913
- payload
3914
- };
3915
- }
3916
- /** The callback and every domain validation execute on a causally complete fork first. */
3917
- transact(edit) {
3918
- const probe = this.doc.fork();
3919
- const draft = new LoroEntityDraft(probe);
3920
- edit(draft);
3921
- draft.captureSelectionBaselines();
3922
- const state = readEntityDocument(probe);
3923
- assertState(state);
3924
- this.validate?.(state);
3925
- materialize(probe);
3926
- const from = this.doc.oplogVersion();
3927
- for (const command of draft.commands) apply(this.doc, command);
3928
- this.doc.commit({ origin: "medeo.edit" });
3929
- materialize(this.doc);
3930
- this.doc.commit({ origin: MATERIALIZE_ORIGIN });
3931
- return this.doc.export({
3932
- mode: "update",
3933
- from
3934
- });
3935
- }
3936
- /** Import preserves native operation identities; projection errors never discard remote operations. */
3937
- import(update) {
3938
- this.doc.import(update);
3939
- const state = this.snapshot();
3940
- assertState(state);
3941
- this.validate?.(state);
3942
- materialize(this.doc);
3943
- this.doc.commit({ origin: MATERIALIZE_ORIGIN });
3944
- }
3945
- /** Bind a saved snapshot without rewriting text operations or resolving selection conflicts. */
3946
- bindAudioScriptAsset(entityId, assetId, expectedContentHash) {
3947
- const key = family(this.doc, entityId);
3948
- const map = workspace(this.doc, key);
3949
- if (map.get("kind") !== "audio-script" || map.get("deleted") === true) throw new Error("Resource binding requires an active AudioScript");
3950
- const payload = entityContent(this.doc, key);
3951
- if (audioScriptAssetHash(payload) !== expectedContentHash) throw new Error("AudioScript changed while saving its resource");
3952
- const from = this.doc.oplogVersion();
3953
- writeObject(requireMap(map, "content"), payload, {
3954
- ...payload,
3955
- ...audioScriptAssetFields(payload, assetId)
3956
- });
3957
- this.doc.commit({ origin: "medeo.asset-sync" });
3958
- materialize(this.doc, true);
3959
- this.doc.commit({ origin: MATERIALIZE_ORIGIN });
3960
- return this.doc.export({
3961
- mode: "update",
3962
- from
3963
- });
3964
- }
3965
- canUndo() {
3966
- return this.undoManager.canUndo();
3967
- }
3968
- canRedo() {
3969
- return this.undoManager.canRedo();
3970
- }
3971
- undo() {
3972
- return this.historyEdit(() => this.undoManager.undo());
3973
- }
3974
- redo() {
3975
- return this.historyEdit(() => this.undoManager.redo());
3976
- }
3977
- historyEdit(run) {
3978
- const before = new Map(this.snapshot().rows.entities.map((row) => [family(this.doc, row.entityId), row]));
3979
- if (!run()) return false;
3980
- const after = this.snapshot();
3981
- for (const row of after.rows.entities) {
3982
- const id = family(this.doc, row.entityId);
3983
- const previous = before.get(id);
3984
- if (previous && !equalJson(owned(previous.payload), owned(row.payload))) workspace(this.doc, id).ensureMergeableMap("changes").set(globalThis.crypto.randomUUID(), true);
3985
- }
3986
- materialize(this.doc);
3987
- this.doc.commit({ origin: MATERIALIZE_ORIGIN });
3988
- return true;
3989
- }
3990
- };
3991
- var LoroEntityDraft = class {
3992
- doc;
3993
- commands = [];
3994
- selectedRoots = /* @__PURE__ */ new Set();
3995
- relationAliases = /* @__PURE__ */ new Map();
3996
- constructor(doc) {
3997
- this.doc = doc;
3998
- for (const row of this.snapshot().rows.relations) this.relationAliases.set(row.relationId, this.relationRoot(row.relationId));
3999
- }
4000
- snapshot() {
4001
- return readEntityDocument(this.doc, true);
4002
- }
4003
- order(groupId, entityIds) {
4004
- this.record({
4005
- type: "order",
4006
- group: family(this.doc, groupId),
4007
- roots: entityIds.map((id) => family(this.doc, id)),
4008
- token: globalThis.crypto.randomUUID()
4009
- });
4010
- }
4011
- /** Project the final scalar placement intents onto the existing native ordering containers. */
4012
- reconcileOrder(rows) {
4013
- const before = new Map([...entityOrderGroups(this.snapshot().rows)].map(([id, ids]) => [family(this.doc, id), ids.map((id) => family(this.doc, id))]));
4014
- const after = new Map([...entityOrderGroups(rows)].map(([id, ids]) => [family(this.doc, id), ids.map((id) => family(this.doc, id))]));
4015
- for (const group of new Set([...before.keys(), ...after.keys()])) {
4016
- const next = after.get(group) ?? [];
4017
- if (!equalJson(before.get(group) ?? [], next)) this.order(group, next);
4018
- }
4019
- }
4020
- create(row) {
4021
- this.record({
4022
- type: "create",
4023
- row: clone(row)
4024
- });
4025
- }
4026
- delete(entityId) {
4027
- this.record({
4028
- type: "delete",
4029
- root: family(this.doc, entityId)
4030
- });
4031
- }
4032
- attach(slot, entityId) {
4033
- this.record({
4034
- type: "attach",
4035
- slot,
4036
- entityId
4037
- });
4038
- }
4039
- link(row) {
4040
- this.record({
4041
- type: "relation",
4042
- row: clone(row)
4043
- });
4044
- }
4045
- patchRelation(relationId, metadata, trace) {
4046
- this.record({
4047
- type: "relation-fields",
4048
- root: this.relationRoot(relationId),
4049
- metadata: clone(metadata),
4050
- trace: clone(trace)
4051
- });
4052
- }
4053
- unlink(relationId) {
4054
- this.record({
4055
- type: "unlink",
4056
- root: this.relationRoot(relationId)
4057
- });
4058
- }
4059
- relationRoot(relationId) {
4060
- const alias = this.relationAliases.get(relationId);
4061
- if (alias !== void 0) return alias;
4062
- const ids = currentIds(this.doc);
4063
- for (const key of section(this.doc, "relations").keys()) {
4064
- const map = section(this.doc, "relations").get(key);
4065
- if (!(map instanceof LoroMap) || map.get("deleted") === true) continue;
4066
- const identity = map.get("identity");
4067
- if (identity.endpoints.some((id) => !ids.has(family(this.doc, id)))) continue;
4068
- const endpoints = identity.endpoints.map((id) => currentId(this.doc, id, ids));
4069
- if ((equalJson(endpoints, identity.endpoints) ? key : `relation_${hash([key, endpoints])}`) === relationId || key === relationId) return key;
4070
- }
4071
- throw new Error(`Unknown relation ${relationId}`);
4072
- }
4073
- update(entityId, fields) {
4074
- const state = this.snapshot();
4075
- const id = createEntityId(currentId(this.doc, entityId));
4076
- const updates = /* @__PURE__ */ new Map();
4077
- for (const [field, value] of Object.entries(fields)) {
4078
- const owner = resolveEntityFieldOwner(state.rows, id, field);
4079
- const payload = updates.get(owner) ?? clone(state.rows.entities.find((row) => row.entityId === owner).payload);
4080
- updates.set(owner, {
4081
- ...payload,
4082
- [field]: clone(value)
4083
- });
4084
- }
4085
- for (const [owner, payload] of updates) this.replaceOwned(owner, payload);
4086
- }
4087
- declare(entityId, fields) {
4088
- const row = this.snapshot().rows.entities.find((row) => row.entityId === currentId(this.doc, entityId));
4089
- if (!row) throw new Error(`Unknown entity ${entityId}`);
4090
- this.replaceOwned(entityId, {
4091
- ...row.payload,
4092
- ...fields
4093
- });
4094
- }
4095
- replaceOwned(entityId, payload) {
4096
- this.record({
4097
- type: "write",
4098
- root: family(this.doc, entityId),
4099
- payload: clone(payload),
4100
- token: globalThis.crypto.randomUUID()
4101
- });
4102
- }
4103
- editText(entityId, path, start, deleteCount, text) {
4104
- if (typeof path[0] !== "string") throw new Error("Text path must start with a field");
4105
- const owner = resolveEntityFieldOwner(this.snapshot().rows, createEntityId(currentId(this.doc, entityId)), path[0]);
4106
- this.record({
4107
- type: "text",
4108
- root: family(this.doc, owner),
4109
- path: [...path],
4110
- start,
4111
- deleteCount,
4112
- text,
4113
- token: globalThis.crypto.randomUUID()
4114
- });
4115
- }
4116
- /** Generic assembled-field edit compiled at the author's causal position. */
4117
- change(entityId, changes) {
4118
- assertFieldChanges(changes);
4119
- for (const raw of changes) {
4120
- const change = clone(raw);
4121
- if (change.path[0] === "baseEntityIds") {
4122
- if (change.op === "list.insert" && typeof change.value === "string") change.value = currentId(this.doc, change.value);
4123
- if (change.op === "list.remove" || change.op === "list.move") change.elementId = currentId(this.doc, change.elementId);
4124
- if ((change.op === "list.insert" || change.op === "list.move") && change.beforeElementId !== null) change.beforeElementId = currentId(this.doc, change.beforeElementId);
4125
- }
4126
- const state = this.snapshot();
4127
- const id = createEntityId(currentId(this.doc, entityId));
4128
- const owner = resolveEntityFieldOwner(state.rows, id, change.path[0]);
4129
- const row = state.rows.entities.find((row) => row.entityId === owner);
4130
- if (equalJson(row.payload, applyFieldChanges(row.payload, [change]))) continue;
4131
- this.record({
4132
- type: "field",
4133
- root: family(this.doc, owner),
4134
- path: resolveFieldPath(row.payload, change.path),
4135
- change: clone(change),
4136
- token: globalThis.crypto.randomUUID()
4137
- });
4138
- }
4139
- }
4140
- changeRelation(relationId, changes) {
4141
- assertFieldChanges(changes);
4142
- const key = this.relationRoot(relationId);
4143
- const map = section(this.doc, "relations").get(key);
4144
- if (!(map instanceof LoroMap) || map.get("deleted") === true) throw new Error("Unknown relation");
4145
- for (const change of changes) {
4146
- if (!["metadata", "trace"].includes(change.path[0]) || change.path.length < 2) throw new Error("Relation changes may only edit metadata or trace fields");
4147
- const payload = {
4148
- metadata: requireMap(map, "metadata").toJSON(),
4149
- trace: requireMap(map, "trace").toJSON()
4150
- };
4151
- applyFieldChanges(payload, [change]);
4152
- this.record({
4153
- type: "relation-field",
4154
- root: key,
4155
- path: resolveFieldPath(payload, change.path),
4156
- change: clone(change)
4157
- });
4158
- }
4159
- }
4160
- captureSelectionBaselines() {
4161
- const state = this.snapshot();
4162
- for (const key of this.selectedRoots) {
4163
- const id = currentIds(this.doc).get(key);
4164
- if (id === void 0) continue;
4165
- const fingerprint = selectionFingerprint(state.rows, id);
4166
- if (fingerprint !== void 0) this.record({
4167
- type: "selection-baseline",
4168
- root: key,
4169
- fingerprint
4170
- });
4171
- }
4172
- }
4173
- record(command) {
4174
- if (command.type === "create") this.selectedRoots.add(command.row.entityId);
4175
- if (command.type === "write" && !equalJson(content(workspace(this.doc, command.root)).selection, command.payload.selection)) this.selectedRoots.add(command.root);
4176
- if (command.type === "field" && command.path[0] === "selection") this.selectedRoots.add(command.root);
4177
- apply(this.doc, command);
4178
- this.commands.push(command);
4179
- }
4180
- };
4181
- function apply(doc, command) {
4182
- switch (command.type) {
4183
- case "selection-baseline":
4184
- workspace(doc, command.root).set("selectionBaseline", command.fingerprint);
4185
- break;
4186
- case "order":
4187
- writeEntityOrder(doc, command.group, command.roots, command.token);
4188
- break;
4189
- case "create": {
4190
- const row = command.row;
4191
- if (section(doc, "origins").get(row.entityId) !== void 0) throw new Error(`Duplicate entity ${row.entityId}`);
4192
- const map = section(doc, "editing").ensureMergeableMap(row.entityId);
4193
- map.set("kind", row.entityKind);
4194
- map.ensureMergeableMap("changes");
4195
- section(doc, "origins").set(row.entityId, row.entityId);
4196
- writeObject(map.ensureMergeableMap("content"), {}, owned(row.payload));
4197
- writeBases(doc, map, baseIds(row.payload));
4198
- break;
4199
- }
4200
- case "write": {
4201
- const map = workspace(doc, command.root);
4202
- const before = content(map);
4203
- const after = owned(command.payload);
4204
- if (!equalJson(before, after)) {
4205
- writeObject(map.ensureMergeableMap("content"), before, after);
4206
- map.ensureMergeableMap("changes").set(command.token, true);
4207
- }
4208
- writeBases(doc, map, baseIds(command.payload));
4209
- break;
4210
- }
4211
- case "text": {
4212
- const map = workspace(doc, command.root);
4213
- const text = requireText(map.ensureMergeableMap("content"), command.path);
4214
- if (!Number.isSafeInteger(command.start) || !Number.isSafeInteger(command.deleteCount) || command.start < 0 || command.deleteCount < 0 || command.start + command.deleteCount > Array.from(text.toString()).length) throw new Error("Invalid text edit range");
4215
- const start = text.convertPos(command.start, "unicode", "utf16");
4216
- const end = text.convertPos(command.start + command.deleteCount, "unicode", "utf16");
4217
- text.splice(start, end - start, command.text);
4218
- map.ensureMergeableMap("changes").set(command.token, true);
4219
- break;
4220
- }
4221
- case "field": {
4222
- const map = workspace(doc, command.root);
4223
- if (command.path[0] === "baseEntityIds") {
4224
- const before = { baseEntityIds: bases(map).map((id) => currentId(doc, id)) };
4225
- if (command.change.op === "list.move") throw new Error("Composition bases are unordered; list.move is not applicable");
4226
- writeBases(doc, map, baseIds(applyFieldChanges(before, [command.change])));
4227
- } else {
4228
- applyNativeFieldChange(requireMap(map, "content"), command.path, command.change);
4229
- map.ensureMergeableMap("changes").set(command.token, true);
4230
- }
4231
- break;
4232
- }
4233
- case "relation-field": {
4234
- const map = section(doc, "relations").get(command.root);
4235
- if (!(map instanceof LoroMap) || map.get("deleted") === true) throw new Error("Unknown relation");
4236
- applyNativeFieldChange(map, command.path, command.change);
4237
- break;
4238
- }
4239
- case "delete":
4240
- workspace(doc, command.root).set("deleted", true);
4241
- break;
4242
- case "relation": {
4243
- const row = command.row;
4244
- const map = section(doc, "relations").ensureMergeableMap(row.relationId);
4245
- const identity = {
4246
- kind: row.relationKind,
4247
- endpoints: [row.endpoint0EntityId, row.endpoint1EntityId]
4248
- };
4249
- const previous = map.get("identity");
4250
- if (previous !== void 0 && !equalJson(previous, identity)) throw new Error("Relation identity cannot change kind or endpoint positions");
4251
- if (previous === void 0) map.set("identity", identity);
4252
- if (map.get("deleted") === true) throw new Error("Deleted relation IDs cannot be reused");
4253
- const metadata = map.ensureMergeableMap("metadata");
4254
- const trace = map.ensureMergeableMap("trace");
4255
- writeObject(metadata, metadata.toJSON(), row.metadata);
4256
- writeObject(trace, trace.toJSON(), row.trace);
4257
- break;
4258
- }
4259
- case "unlink": {
4260
- const map = section(doc, "relations").get(command.root);
4261
- if (!(map instanceof LoroMap)) throw new Error("Unknown relation");
4262
- map.set("deleted", true);
4263
- break;
4264
- }
4265
- case "relation-fields": {
4266
- const map = section(doc, "relations").get(command.root);
4267
- if (!(map instanceof LoroMap)) throw new Error("Unknown relation");
4268
- const metadata = map.ensureMergeableMap("metadata");
4269
- const trace = map.ensureMergeableMap("trace");
4270
- writeObject(metadata, metadata.toJSON(), command.metadata);
4271
- writeObject(trace, trace.toJSON(), command.trace);
4272
- break;
4273
- }
4274
- case "attach":
4275
- section(doc, "attachments").set(command.slot, command.entityId);
4276
- break;
4277
- }
4278
- }
4279
- function writeBases(doc, map, ids) {
4280
- const links = map.ensureMergeableMap("bases");
4281
- const wanted = new Map(ids.map((id) => {
4282
- const origin = section(doc, "origins").get(id);
4283
- return [typeof origin === "string" ? origin : [...currentIds(doc)].find(([, current]) => current === id)?.[0] ?? id, id];
4284
- }));
4285
- if (wanted.size !== ids.length) throw new Error("Duplicate base entity family");
4286
- for (const key of links.keys()) if (!wanted.has(key)) links.delete(key);
4287
- for (const [key, id] of wanted) if (links.get(key) === void 0) links.set(key, id);
4288
- }
4289
- /** Numeric sub-spans must not silently quote different text after a collaborative edit. */
4290
- function selectionFingerprint(rows, id) {
4291
- const row = rows.entities.find((row) => row.entityId === id);
4292
- if (row?.entityKind !== "caption" || !isJsonObject(row.payload.selection)) return void 0;
4293
- const selection = row.payload.selection;
4294
- if (selection.textRange === void 0) return void 0;
4295
- const segments = assembleEntityContent(rows, row.entityId).payload.segments;
4296
- if (!Array.isArray(segments)) throw new Error("Caption text selection has no source segments");
4297
- const source = segments.find((segment) => isJsonObject(segment) && segment.segmentId === selection.segmentId);
4298
- if (!isJsonObject(source) || typeof source.text !== "string") throw new Error("Caption text selection source is missing");
4299
- return hash([selection, source.text]);
4300
- }
4301
- function assertState(state) {
4302
- for (const row of state.rows.entities) assembleEntityContent(state.rows, row.entityId);
4303
- const ids = new Set(state.rows.entities.map((row) => String(row.entityId)));
4304
- for (const row of state.rows.relations) if (!ids.has(row.endpoint0EntityId) || !ids.has(row.endpoint1EntityId)) throw new Error("Relation has a missing endpoint");
4305
- }
4306
- function materialize(doc, allowSelectionConflicts = false) {
4307
- const state = readEntityDocument(doc, allowSelectionConflicts);
4308
- const byId = section(doc, "entities");
4309
- const ids = currentIds(doc);
4310
- for (const [source, id] of ids) {
4311
- const origins = section(doc, "origins");
4312
- if (origins.get(id) !== source) origins.set(id, source);
4313
- }
4314
- for (const row of state.rows.entities) {
4315
- const next = {
4316
- id: row.entityId,
4317
- kind: row.entityKind,
4318
- ...row.payload
4319
- };
4320
- const previous = byId.get(row.entityId);
4321
- if (isJsonObject(previous) && !equalJson(owned(previous), owned(next))) throw new Error("Immutable entity version collision");
4322
- if (!equalJson(previous, next)) byId.set(row.entityId, next);
4323
- }
4324
- const project = section(doc, "project");
4325
- for (const [slot, id] of Object.entries(state.project)) if (project.get(slot) !== id) project.set(slot, id);
4326
- }
4327
- //#endregion
4328
- //#region src/document/document-mutation-guard.ts
4329
- /**
4330
- * @internal
4331
- * Shared by synchronous mutation entry points for one document. The session
4332
- * closes it before teardown callbacks can attempt another write.
4333
- */
4334
- var DocumentMutationGuard = class {
4335
- running = false;
4336
- closed = false;
4337
- run(mutation) {
4338
- if (this.closed) throw new Error("mengine document is disposed");
4339
- if (this.running) throw new Error("mengine document mutation is already running");
4340
- this.running = true;
4341
- try {
4342
- return mutation();
4343
- } finally {
4344
- this.running = false;
4345
- }
4346
- }
4347
- close() {
4348
- this.closed = true;
4349
- }
4350
- };
4351
- //#endregion
4352
- //#region src/document/mirror-read.ts
4353
- /**
4354
- * Project the mirror state (`VideoDocumentDraft`) into the authoritative
4355
- * `VideoDocument`. The storage shape is isomorphic to the domain shape (RFC 03
4356
- * §4, reference/17 §4: timeline + a single `tracks` list + part_library), so this
4357
- * is a near-identity — it reads `time_position` / `fallback_abs_ms` JSON blobs
4358
- * back into structured values and selects content fields. Legacy meta is ignored.
4359
- *
4360
- * It maps only authoritative facts (RFC 02 §6): `part_id` + `time_position`. The
4361
- * projection-derived `VideoDraft` read-view (absolute time, `part_aggregations`,
4362
- * total duration) is solved separately by the cascade, not here.
4363
- *
4364
- * It reads in-memory mirror state (O(n) over the document), not a Loro
4365
- * `toJSON()` FFI rebuild — the cost the prior schema adapter paid on every
4366
- * `snapshot()`.
4367
- */
4368
- function readVideoDocumentFromDraft(draft) {
4369
- const partLibrary = {};
4370
- for (const [partId, payload] of recordEntries(draft.part_library)) {
4371
- const part = draftToPartUnion(payload);
4372
- if (part != null) partLibrary[partId] = part;
4373
- }
4374
- const timeline = draft.timeline;
4375
- return {
4376
- timeline: timeline?.unit_time_ms != null ? { unit_time_ms: timeline.unit_time_ms } : void 0,
4377
- tracks: rowsToTracks(draft.tracks),
4378
- part_library: partLibrary
4379
- };
4380
- }
4381
- /** Map a movable-list of track rows (`$cid`-bearing) into domain tracks, dropping empty-id placeholders. */
4382
- function rowsToTracks(rows) {
4383
- return (rows ?? []).filter((row) => row.id != null && row.id !== "").map(rowToTrack);
4384
- }
4385
- function rowToTrack(row) {
4386
- return {
4387
- id: row.id,
4388
- parts_kind: row.parts_kind ?? void 0,
4389
- is_hidden: row.is_hidden ?? void 0,
4390
- items: (row.items ?? []).map((item) => {
4391
- const result = {
4392
- part_id: item.part_id ?? "",
4393
- time_position: item.time_position
4394
- };
4395
- if (item.fallback_abs_ms != null) result.fallback_abs_ms = item.fallback_abs_ms;
4396
- return result;
4397
- })
4398
- };
4399
- }
4400
- //#endregion
4401
- //#region src/document/mirror-adapter.ts
4402
- /**
4403
- * Storage-layer adapter that backs a `VideoDocument` with `loro-mirror` (ADR
4404
- * 0008). The mirror holds an in-memory immutable state synced to the `LoroDoc`
4405
- * by declarative diff, replacing the hand-rolled `@mengine/schema` adapter:
4406
- *
4407
- * - `snapshot()` projects the mirror's in-memory state to the read model — no
4408
- * per-call `toJSON()` FFI rebuild.
4409
- * - `transact(edit, audit)` runs the whole op in one `mirror.setState` callback:
4410
- * one diff, one `doc.commit` carrying the audit message. The callback edits an
4411
- * immer draft, so a throw inside it discards the draft and never touches Loro
4412
- * (natural rollback) without a document checkout or compensating commit.
4413
- * - mirror's `idSelector` (track items keyed by `part_id`) diffs reorders to
4414
- * real Loro `move` ops on every lane, so per-item CRDT identity survives on
4415
- * main and secondary tracks alike.
4416
- */
4417
- var MirrorVideoDocumentAdapter = class {
4418
- doc;
4419
- mutationGuard;
4420
- mirror;
4421
- disposed = false;
4422
- constructor(doc, mutationGuard = new DocumentMutationGuard()) {
4423
- this.doc = doc;
4424
- this.mutationGuard = mutationGuard;
4425
- this.mirror = new Mirror({
4426
- doc,
4427
- schema: videoDocumentMirrorSchema,
4428
- validateUpdates: false
4429
- });
4430
- }
4431
- snapshot() {
4432
- this.assertActive();
4433
- if (this.isEntityDocument()) return projectEntityTimeline(readEntityDocument(this.doc).rows);
4434
- return readVideoDocumentFromDraft(this.mirror.getState());
4435
- }
4436
- /**
4437
- * Native Entity authority: placement is already solved by the Entity graph.
4438
- *
4439
- * The root check goes through `getShallowValue` first because `getMap` creates
4440
- * the container on access — probing a legacy document for `medeo` would
4441
- * otherwise mutate it, which a read must never do.
4442
- */
4443
- isEntityDocument() {
4444
- const roots = this.doc.getShallowValue();
4445
- if (!Object.hasOwn(roots, "medeo")) return false;
4446
- return this.doc.getMap("medeo").get("schema") === LORO_ENTITY_SCHEMA;
4447
- }
4448
- /**
4449
- * Release mirror subscriptions; do not reuse this adapter afterwards.
4450
- * The caller still owns the borrowed LoroDoc.
4451
- */
4452
- dispose() {
4453
- if (this.disposed) return;
4454
- this.disposed = true;
4455
- this.mirror.dispose();
4456
- }
4457
- /**
4458
- * Apply one op as a single transaction. `edit` mutates the immer draft; mirror
4459
- * diffs the result and commits once with the audit `message`. A throw in `edit`
4460
- * discards the draft (Loro untouched). When `edit` produces no change, mirror
4461
- * skips the commit — matching the prior "empty op leaves no audit" behavior.
4462
- */
4463
- transact(edit, audit) {
4464
- this.assertActive();
4465
- if (this.isEntityDocument()) throw new Error("Entity documents are read-only through this adapter; edit the Medeo entities instead");
4466
- this.mutationGuard.run(() => {
4467
- this.mirror.setState((draft) => {
4468
- edit(draft);
4469
- const result = validateSchema(videoDocumentMirrorSchema, {
4470
- timeline: draft.timeline,
4471
- tracks: draft.tracks,
4472
- part_library: draft.part_library
4473
- });
4474
- if (!result.valid) throw new Error(`Invalid content update: ${result.errors?.join("; ")}`);
4475
- }, {
4476
- origin: "mengine.semantic_editor",
4477
- message: JSON.stringify({
4478
- semantic_op: audit.kind,
4479
- payload: audit.payload,
4480
- intent: audit.intent ?? null,
4481
- actor: audit.actor ?? null
4482
- })
4483
- });
4484
- });
4485
- }
4486
- assertActive() {
4487
- if (this.disposed) throw new Error("mengine document adapter is disposed");
4488
- }
4489
- };
4490
- /** Build a fresh Loro doc seeded with `document` through the mirror. */
4491
- function createMirrorVideoDocument(document, options = {}) {
4492
- assertValidVideoDocument(document);
4493
- const doc = new LoroDoc();
4494
- try {
4495
- if (options.peerId != null) doc.setPeerId(options.peerId);
4496
- const mirror = new Mirror({
4497
- doc,
4498
- schema: videoDocumentMirrorSchema
4499
- });
4500
- try {
4501
- mirror.setState((draft) => {
4502
- seedDraft(draft, document);
4503
- }, { origin: options.origin ?? "mengine.bootstrap" });
4504
- return doc;
4505
- } finally {
4506
- mirror.dispose();
4507
- }
4508
- } catch (error) {
4509
- doc.free();
4510
- throw error;
4511
- }
4512
- }
4513
- /** Build a `MirrorVideoDocumentAdapter` over a fresh doc seeded with `document`. */
4514
- function createMirrorVideoDocumentAdapter(document, options) {
4515
- return new MirrorVideoDocumentAdapter(createMirrorVideoDocument(document, options));
4516
- }
4517
- /** Write a whole `VideoDocument` into the mirror draft (seed a fresh doc / plain-memory state). */
4518
- function seedDraft(draft, document) {
4519
- draft.timeline = { unit_time_ms: document.timeline?.unit_time_ms ?? void 0 };
4520
- draft.tracks = (document.tracks ?? []).map(toTrackRow);
4521
- draft.part_library = {};
4522
- for (const [partId, part] of Object.entries(document.part_library ?? {})) {
4523
- const createdPart = part.caption != null ? { caption: {
4524
- ...part.caption,
4525
- style: part.caption.style ?? {}
4526
- } } : part;
4527
- draft.part_library[partId] = partUnionToDraft(createdPart);
4528
- }
4529
- }
4530
- /** Map a domain `Track` to a draft track row (no lane/lane_order — see schema). */
4531
- function toTrackRow(track) {
4532
- return {
4533
- id: track.id ?? "",
4534
- parts_kind: track.parts_kind ?? void 0,
4535
- is_hidden: track.is_hidden ?? void 0,
4536
- items: (track.items ?? []).map((item) => ({
4537
- part_id: item.part_id,
4538
- time_position: item.time_position,
4539
- fallback_abs_ms: item.fallback_abs_ms
4540
- }))
4541
- };
4542
- }
4543
- //#endregion
4544
- //#region src/editor/id-gen.ts
4545
- /**
4546
- * Part-id generation, aligned with the online ecosystem.
4547
- *
4548
- * The authoritative online producers — agent-harness (`@harness/shared`
4549
- * `genObjId`) and director.v2 (`common/obj_id.py` `gen_obj_id`) — both mint part
4550
- * ids as `` `${prefix}_${ulid()}` ``, and real captured drafts use exactly that
4551
- * shape (`clip_…` / `spe_…` / `cap_…` / `bgm_…`, each a 26-char ULID). The engine
4552
- * previously emitted `vc_<base36 timestamp><6 random>`, a different prefix AND a
4553
- * different encoding — the sole cross-repo id divergence. This module removes it
4554
- * by emitting the same `<prefix>_<ULID>` bytes.
4555
- *
4556
- * The ULID is generated inline (Crockford Base32, 48-bit time + 80-bit random)
4557
- * rather than pulling the `ulid` npm package: the randomness class matches the
4558
- * old generator (both `Math.random`-based) and it keeps `@mengine/medeo-client`
4559
- * dependency-free for a purely mechanical id string. Part ids only need to be
4560
- * unique and lexicographically time-sortable, which this satisfies.
4561
- */
4562
- /** Crockford Base32 alphabet (no I, L, O, U), per the ULID spec. */
4563
- const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
4564
- const TIME_LEN = 10;
4565
- const RANDOM_LEN = 16;
4566
- function encodeTime(now) {
4567
- let out = "";
4568
- let ms = now;
4569
- for (let i = TIME_LEN - 1; i >= 0; i--) {
4570
- const mod = ms % 32;
4571
- out = CROCKFORD[mod] + out;
4572
- ms = (ms - mod) / 32;
4573
- }
4574
- return out;
4575
- }
4576
- function encodeRandom() {
4577
- let out = "";
4578
- for (let i = 0; i < RANDOM_LEN; i++) out += CROCKFORD[Math.floor(Math.random() * 32)];
4579
- return out;
4580
- }
4581
- /** A 26-char Crockford Base32 ULID (10-char time + 16-char random). */
4582
- function ulid() {
4583
- return encodeTime(Date.now()) + encodeRandom();
4584
- }
4585
- function generatePartId(prefix) {
4586
- return `${prefix}_${ulid()}`;
4587
- }
4588
- //#endregion
4589
- //#region src/document/plain-memory-adapter.ts
4590
- /**
4591
- * Pure in-memory `SemanticDocumentAdapter` — no Loro/WASM. Holds a
4592
- * `VideoDocumentDraft` object and applies each `transact` via immer `produce`,
4593
- * journaling every audit that actually mutated state (plus any ids minted
4594
- * during that transact).
4595
- *
4596
- * Known benign difference vs `MirrorVideoDocumentAdapter`: the editor's
4597
- * `setPart` assigns a fresh part object on every call, so a same-value rewrite
4598
- * produces a new immer state and IS journaled here, while the mirror's deep
4599
- * diff emits no commit. Terminal `snapshot()` stays equal; replay is idempotent.
4600
- */
4601
- var PlainMemoryAdapter = class {
4602
- state;
4603
- _journal = [];
4604
- baseIdFactory;
4605
- /** Non-null only while a `transact` edit callback is running. */
4606
- pendingIds = null;
4607
- /**
4608
- * Recording wrapper around the underlying factory. Callers (sandbox editor)
4609
- * use this so every minted id is appended to the current transact's list.
4610
- */
4611
- idFactory;
4612
- readOnly;
4613
- constructor(document, options) {
4614
- assertValidVideoDocument(document);
4615
- this.readOnly = options?.readOnly === true;
4616
- const draft = {};
4617
- seedDraft(draft, document);
4618
- this.state = draft;
4619
- this.baseIdFactory = options?.idFactory ?? generatePartId;
4620
- this.idFactory = (prefix) => {
4621
- const id = this.baseIdFactory(prefix);
4622
- if (this.pendingIds != null) this.pendingIds.push(id);
4623
- return id;
4624
- };
4625
- }
4626
- get journal() {
4627
- return this._journal;
4628
- }
4629
- hasContent() {
4630
- return this.state.tracks !== void 0 || this.state.timeline !== void 0;
4631
- }
4632
- snapshot() {
4633
- return readVideoDocumentFromDraft(this.state);
4634
- }
4635
- /**
4636
- * Apply one op via immer. A throw in `edit` discards the draft (state and
4637
- * journal unchanged). When `produce` returns the same reference, there was
4638
- * no structural change — skip journal, matching mirror "no change, no commit".
4639
- */
4640
- transact(edit, audit) {
4641
- if (this.readOnly) throw new Error("Entity documents are read-only here; edit the Medeo entities instead");
4642
- this.pendingIds = [];
4643
- try {
4644
- const next = produce(this.state, edit);
4645
- if (next !== this.state) {
4646
- this.state = next;
4647
- this._journal.push({
4648
- ...audit,
4649
- generated_ids: this.pendingIds
4650
- });
4651
- }
4652
- } finally {
4653
- this.pendingIds = null;
4654
- }
4655
- }
4656
- };
4657
- /** Build a `PlainMemoryAdapter` seeded with `document`. */
4658
- function createPlainMemoryAdapter(document, options) {
4659
- return new PlainMemoryAdapter(document, options);
4660
- }
4661
- //#endregion
4662
- export { findLaneTrack as $, assemblePhoneticScriptContent as A, isMediaAssetVariantKind as B, EntityProjectionGraph as C, ScriptCompositionError as D, decodeEntityRelationRows as E, variantBaseEntityIds as F, toVideoDocument as G, buildSpeechHostMap as H, isJsonObject as I, validateVideoDocument as J, VideoDocumentValidationError as K, createEntityId as L, findComposedAudioScript as M, selectAudioScriptSegment as N, assembleCaptionContent as O, updateEntityFields as P, ensureLaneTrack as Q, createRelationId as R, projectEntityTimeline as S, bytesToBase64 as St, EntityTimelineProjectionError as T, derivePositionFromAbs as U, buildInitialVideoDocument as V, fromVideoDocument as W, videoDocumentSchema as X, partUnionSchema as Y, LANE_KINDS_IN_STACK_ORDER as Z, hasAudioScriptAsset as _, speedOf as _t, createMirrorVideoDocument as a, fillMainTrackTimeGaps as at, assertFieldChanges as b, videoDocumentMirrorSchema as bt, DocumentMutationGuard as c, resolveAllSpeechOverlaps as ct, LoroEntityDraft as d, TIMELINE_SKELETON_DURATION_MS as dt, hasResolvedPlacement as et, readEntityDocument as f, isEmptyVideoClip as ft, audioScriptAssetHash as g, effectiveVideoClipDurationMs as gt, audioScriptAssetFields as h, DEFAULT_UNIT_TIME_MS as ht, MirrorVideoDocumentAdapter as i, arrangeMainTrackSeamlessly as it, assembleScriptText as j, assembleEntityContent as k, LORO_ENTITY_SCHEMA as l, resolveSpeechOverlapByShiftingVideos as lt, audioScriptAssetContent as m, safeDurationMs as mt, createPlainMemoryAdapter as n, solveVideoDocument as nt, createMirrorVideoDocumentAdapter as o, reassignSpeechesToVideoClipsByTime as ot, entityOrderGroups as p, partDurationMs as pt, assertValidVideoDocument as q, generatePartId as r, cascadeAfterVideoClipChanges as rt, readVideoDocumentFromDraft as s, recalculateTimelineDuration as st, PlainMemoryAdapter as t, laneTrackId as tt, LoroEntityDocument as u, syncAggregatedClipsTimePosition as ut, equalJson as v, partUnionToDraft as vt, resolveEntityTimelineLayout as w, resolveFieldPath as x, base64ToBytes as xt, applyFieldChanges as y, recordEntries as yt, hasSequence as z };