@mengine/medeo-client 1.4.0 → 1.4.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,6 @@
1
- import { t as __exportAll } from "./chunk-D7D4PA-g.js";
2
- import { A as isEmptyVideoClip, B as bytesToBase64, C as fillMainTrackTimeGaps, D as resolveSpeechOverlapByShiftingVideos, E as resolveAllSpeechOverlaps, F as effectiveVideoClipDurationMs, I as partUnionToDraft, L as recordEntries, M as safeDurationMs, N as DEFAULT_UNIT_TIME_MS, O as syncAggregatedClipsTimePosition, P as VIDEO_DOCUMENT_SCHEMA_VERSION, R as videoDocumentMirrorSchema, S as arrangeMainTrackSeamlessly, T as recalculateTimelineDuration, _ as ensureLaneTrack, a as DocumentMutationGuard, b as solveVideoDocument, c as derivePositionFromAbs, d as VideoDocumentValidationError, f as assertValidVideoDocument, g as LANE_KINDS_IN_STACK_ORDER, h as videoDocumentSchema, i as readVideoDocumentFromDraft, j as partDurationMs, k as TIMELINE_SKELETON_DURATION_MS, l as fromVideoDocument, m as partUnionSchema, n as createMirrorVideoDocument, o as buildInitialVideoDocument, p as validateVideoDocument, r as createMirrorVideoDocumentAdapter, s as buildSpeechHostMap, t as MirrorVideoDocumentAdapter, u as toVideoDocument, v as findLaneTrack, w as reassignSpeechesToVideoClipsByTime, x as cascadeAfterVideoClipChanges, y as laneTrackId, z as base64ToBytes } from "./document-DKPAavs9.js";
3
- import { z } from "zod";
4
- import { LoroDoc, UndoManager, VersionVector } from "loro-crdt";
1
+ import { $ as reassignSpeechesToVideoClipsByTime, A as isJsonObject, B as VideoDocumentValidationError, C as assembleEntityContent, D as selectAudioScriptSegments, E as findComposedAudioScript, F as buildInitialVideoDocument, G as LANE_KINDS_IN_STACK_ORDER, H as validateVideoDocument, I as buildSpeechHostMap, J as laneTrackId, K as ensureLaneTrack, L as derivePositionFromAbs, M as createRelationId, N as hasSequence, O as updateEntityFields, P as isMediaAssetVariantKind, Q as fillMainTrackTimeGaps, R as fromVideoDocument, S as assembleCaptionContent, T as assembleScriptText, U as partUnionSchema, V as assertValidVideoDocument, W as videoDocumentSchema, X as cascadeAfterVideoClipChanges, Y as solveVideoDocument, Z as arrangeMainTrackSeamlessly, _ as EntityProjectionGraph, _t as bytesToBase64, a as applyEntityTimelineProjection, at as isEmptyVideoClip, b as decodeEntityRelationRows, c as writeVideoDocumentToDraft, ct as DEFAULT_UNIT_TIME_MS, d as LoroEntityDocument, dt as effectiveVideoClipDurationMs, et as recalculateTimelineDuration, f as LoroEntityDraft, ft as speedOf, g as projectEntityTimeline, gt as base64ToBytes, h as equalJson, ht as videoDocumentMirrorSchema, i as MirrorVideoDocumentAdapter, it as TIMELINE_SKELETON_DURATION_MS, j as createEntityId, k as variantBaseEntityIds, l as readVideoDocumentFromDraft, lt as ENTITY_TIMELINE_PROJECTION_SCHEMA_VERSION, m as entityOrderGroups, mt as recordEntries, n as createPlainMemoryAdapter, nt as resolveSpeechOverlapByShiftingVideos, o as createMirrorVideoDocument, ot as partDurationMs, p as readEntityDocument, pt as partUnionToDraft, q as findLaneTrack, r as generatePartId, rt as syncAggregatedClipsTimePosition, s as createMirrorVideoDocumentAdapter, st as safeDurationMs, t as PlainMemoryAdapter, tt as resolveAllSpeechOverlaps, u as LORO_ENTITY_SCHEMA, ut as VIDEO_DOCUMENT_SCHEMA_VERSION, v as resolveEntityTimelineLayout, w as assemblePhoneticScriptContent, x as ScriptCompositionError, y as EntityTimelineProjectionError, z as toVideoDocument } from "./document-CF-q_mRy.js";
2
+ import { addSpeechesInputSchema, addVideoClipsInputSchema, adjustBgmVolumeInputSchema, adjustSpeechVolumeInputSchema, adjustVideoClipDurationInputSchema, adjustVideoClipVolumeInputSchema, changeSpeechScriptInputSchema, changeSpeechVoiceInputSchema, deleteBgmInputSchema, deleteSpeechesInputSchema, deleteVideoClipsInputSchema, moveSpeechesInputSchema, moveVideoClipsByAnchorInputSchema, moveVideoClipsInputSchema, replaceVideoClipContentInputSchema, replaceVideoClipSequenceInputSchema, setBgmInputSchema, setCaptionStyleInputSchema, setCaptionVisibilityInputSchema, setVideoClipSpeedShiftInputSchema, t as schemas_exports } from "./schemas.js";
3
+ import { LoroDoc, VersionVector } from "loro-crdt";
5
4
  import { ClientServerSynchronizer, DocManager } from "@mengine/sync";
6
5
  import { DisposableSet, EventBus, Task } from "@mengine/utils";
7
6
  import { BaseDocStorage, DummyConnection } from "@mengine/storage";
@@ -13,7 +12,7 @@ import { BaseDocStorage, DummyConnection } from "@mengine/storage";
13
12
  * namespace (mirrors the cluster's `/oapi/v1` precedent for an independent
14
13
  * subsystem) rather than folding into the shared `/api/v2/*` space.
15
14
  */
16
- const MENGINE_API_PREFIX = "/api/mengine/v1";
15
+ const MENGINE_API_PREFIX$1 = "/api/mengine/v1";
17
16
  var MengineHttpRequestError = class extends Error {
18
17
  status;
19
18
  payload;
@@ -135,12 +134,12 @@ var MengineHttpClient = class {
135
134
  ...init,
136
135
  headers
137
136
  });
138
- const payload = await safeReadJson(response);
137
+ const payload = await safeReadJson$1(response);
139
138
  if (!response.ok) throw new MengineHttpRequestError(response.status, payload);
140
139
  return payload;
141
140
  }
142
141
  endpoint(path) {
143
- return `${this.options.httpOrigin.replace(/\/$/, "")}${MENGINE_API_PREFIX}/docs/${encodeURIComponent(this.options.docId)}/${path}`;
142
+ return `${this.options.httpOrigin.replace(/\/$/, "")}${MENGINE_API_PREFIX$1}/docs/${encodeURIComponent(this.options.docId)}/${path}`;
144
143
  }
145
144
  };
146
145
  /**
@@ -157,7 +156,7 @@ function asPushRejection(error) {
157
156
  if (body.kind !== "rejected" || typeof body.code !== "string") return void 0;
158
157
  return new MenginePushRejectedError(body.code, body.message ?? "", body.server_version, error.status);
159
158
  }
160
- async function safeReadJson(response) {
159
+ async function safeReadJson$1(response) {
161
160
  const text = await response.text();
162
161
  if (text.length === 0) return null;
163
162
  try {
@@ -195,588 +194,2521 @@ async function readMengineEventStream(options) {
195
194
  }
196
195
  }
197
196
  }
198
- function handleSseFrame(frame, onUpdate) {
199
- const event = parseSseFrame(frame);
200
- if (event.event !== "update" || event.data.length === 0) return;
201
- onUpdate(JSON.parse(event.data.join("\n")));
197
+ function handleSseFrame(frame, onUpdate) {
198
+ const event = parseSseFrame(frame);
199
+ if (event.event !== "update" || event.data.length === 0) return;
200
+ onUpdate(JSON.parse(event.data.join("\n")));
201
+ }
202
+ function parseSseFrame(frame) {
203
+ let event = null;
204
+ const data = [];
205
+ for (const line of frame.split(/\r?\n/)) if (line.startsWith("event:")) event = line.slice(6).trim();
206
+ else if (line.startsWith("data:")) data.push(line.slice(5).trimStart());
207
+ return {
208
+ event,
209
+ data
210
+ };
211
+ }
212
+ function findSseFrameBoundary(buffer) {
213
+ const lf = buffer.indexOf("\n\n");
214
+ const crlf = buffer.indexOf("\r\n\r\n");
215
+ if (lf < 0) return crlf;
216
+ if (crlf < 0) return lf;
217
+ return Math.min(lf, crlf);
218
+ }
219
+ //#endregion
220
+ //#region src/entity-crdt/compile-rows.ts
221
+ /** Lower a detached ordinary-object edit against its actual causal Loro baseline. */
222
+ function compileEntityRows(snapshot, rows, validate) {
223
+ const doc = new LoroDoc();
224
+ doc.import(snapshot);
225
+ return applyEntityRows(new LoroEntityDocument(doc, validate), rows);
226
+ }
227
+ /** Compile an edit on an existing peer, retaining its native local undo history. */
228
+ function applyEntityRows(editor, rows) {
229
+ const before = editor.snapshot().rows;
230
+ const oldEntities = new Map(before.entities.map((row) => [row.entityId, row]));
231
+ const newEntities = new Map(rows.entities.map((row) => [row.entityId, row]));
232
+ const oldRelations = new Map(before.relations.map((row) => [row.relationId, row]));
233
+ const newRelations = new Map(rows.relations.map((row) => [row.relationId, row]));
234
+ if (newEntities.size !== rows.entities.length || newRelations.size !== rows.relations.length) throw new Error("Duplicate domain identity");
235
+ return {
236
+ update: editor.transact((draft) => {
237
+ for (const row of before.relations) {
238
+ const next = newRelations.get(row.relationId);
239
+ if (!next) draft.unlink(row.relationId);
240
+ else {
241
+ if (next.relationKind !== row.relationKind || next.endpoint0EntityId !== row.endpoint0EntityId || next.endpoint1EntityId !== row.endpoint1EntityId) throw new Error("Relation identity cannot change kind or endpoint positions");
242
+ if (!equalJson(row.metadata, next.metadata) || !equalJson(row.trace, next.trace)) draft.patchRelation(row.relationId, next.metadata, next.trace);
243
+ }
244
+ }
245
+ for (const row of rows.entities) {
246
+ const previous = oldEntities.get(row.entityId);
247
+ if (!previous) draft.create(row);
248
+ else {
249
+ if (previous.entityKind !== row.entityKind) throw new Error("Entity kind cannot change");
250
+ if (!equalJson(previous.payload, row.payload)) draft.replaceOwned(row.entityId, row.payload);
251
+ }
252
+ }
253
+ for (const row of rows.relations) if (!oldRelations.has(row.relationId)) draft.link(row);
254
+ const beforeOrder = entityOrderGroups(before), afterOrder = entityOrderGroups(rows);
255
+ for (const group of new Set([...beforeOrder.keys(), ...afterOrder.keys()])) {
256
+ const next = afterOrder.get(group) ?? [];
257
+ if (!equalJson(beforeOrder.get(group) ?? [], next)) draft.order(group, next);
258
+ }
259
+ for (const row of before.entities) if (!newEntities.has(row.entityId)) draft.delete(row.entityId);
260
+ }),
261
+ state: editor.snapshot()
262
+ };
263
+ }
264
+ //#endregion
265
+ //#region src/entity-editor/document-audio-script.ts
266
+ /** Read only the attached version and preserve every segment; never aggregate other scripts. */
267
+ function readDocumentAudioScript(state) {
268
+ const id = state.audioScriptEntityId;
269
+ if (id === null) throw new EntityTimelineProjectionError("Document AudioScript is not initialized");
270
+ if (typeof id !== "string" || id.trim() !== id || !id) throw new EntityTimelineProjectionError("Invalid document AudioScript identity");
271
+ const entity = state.rows.entities.find((row) => row.entityId === id);
272
+ if (!entity || entity.entityKind !== "audio-script") throw new EntityTimelineProjectionError(`Document AudioScript ${id} must name the project AudioScript`);
273
+ const content = assembleEntityContent(state.rows, createEntityId(id));
274
+ assembleScriptText(content);
275
+ return {
276
+ entityId: id,
277
+ segments: structuredClone(content.payload.segments)
278
+ };
279
+ }
280
+ //#endregion
281
+ //#region src/entity-editor/editor-resources.ts
282
+ const roleOrder$1 = {
283
+ caption: 0,
284
+ video_clip: 1,
285
+ speech: 2,
286
+ bgm: 3
287
+ };
288
+ /**
289
+ * MEngine editor policy, not a cardinality restriction on the general-purpose DSL.
290
+ *
291
+ * Media variants share one entity identity with their Asset: every
292
+ * Image/Video/Audio/Voice Entity must carry its own external locator, every
293
+ * external asset id has exactly one claimant, and no media variant may be
294
+ * bound through a legacy `physical-asset` Relation. Dual-entity media graphs
295
+ * are rejected, not migrated. Caption composes AudioScript text and may associate with a physical text Asset.
296
+ */
297
+ function assertCanonicalEditorResources(rows) {
298
+ if (rows.entities.filter((row) => row.entityKind === "timeline").length > 1) throw new EntityTimelineProjectionError("Editor requires exactly one Timeline");
299
+ for (const role of Object.keys(roleOrder$1)) if (rows.entities.filter((row) => row.entityKind === "track" && row.payload.role === role).length > 1) throw new EntityTimelineProjectionError(`Editor has multiple ${role} Tracks`);
300
+ const identityByAssetKey = /* @__PURE__ */ new Map();
301
+ const kinds = new Map(rows.entities.map((row) => [String(row.entityId), row.entityKind]));
302
+ for (const entity of rows.entities) {
303
+ if (isMediaAssetVariantKind(entity.entityKind) && memotaLocator(entity.payload.external) === void 0) throw new EntityTimelineProjectionError(`Media Entity ${entity.entityId} must carry its own Asset external identity`);
304
+ if (entity.entityKind !== "asset" && !isMediaAssetVariantKind(entity.entityKind)) continue;
305
+ const external = entity.payload.external;
306
+ if (!isJsonObject(external) || external.system !== "memota" && external.system !== "memota-speech" || typeof external.key !== "string") continue;
307
+ const key = JSON.stringify([external.system, external.key]);
308
+ const previous = identityByAssetKey.get(key);
309
+ if (previous !== void 0 && previous !== entity.entityId) throw new EntityTimelineProjectionError(`Duplicate Asset for ${key}; reuse ${previous}`);
310
+ identityByAssetKey.set(key, entity.entityId);
311
+ }
312
+ for (const relation of rows.relations) {
313
+ if (relation.relationKind !== "physical-asset") continue;
314
+ const mediaEndpoint = [relation.endpoint0EntityId, relation.endpoint1EntityId].find((endpoint) => isMediaAssetVariantKind(kinds.get(String(endpoint)) ?? ""));
315
+ if (mediaEndpoint !== void 0) throw new EntityTimelineProjectionError(`Cannot bind media Entity ${mediaEndpoint} through physical-asset Relation ${relation.relationId}; media owns its Asset identity directly`);
316
+ }
317
+ }
318
+ /**
319
+ * Commit-transition policy shared by the editor, the HTTP commit boundary, the
320
+ * host tool, and the entity stores. It compares the authoritative before and
321
+ * after rows of one CAS commit and enforces the single-identity write rules
322
+ * on the complete after state, with no exemption for historical graphs:
323
+ *
324
+ * 1. every Image/Video/Audio/Voice Entity carries its own Asset `external`
325
+ * identity;
326
+ * 2. no `physical-asset` Relation may bind a media variant;
327
+ * 3. a self-carried media identity is immutable — it cannot be rewritten to
328
+ * another asset id.
329
+ *
330
+ * Dual-entity media graphs are rejected instead of being migrated or merged
331
+ * implicitly. Deleting media is explicit and allowed.
332
+ */
333
+ function assertMediaAssetWritePolicy(before, after) {
334
+ const beforeEntities = new Map(before.entities.map((row) => [String(row.entityId), row]));
335
+ const afterKinds = new Map(after.entities.map((row) => [String(row.entityId), row.entityKind]));
336
+ for (const row of after.entities) {
337
+ if (!isMediaAssetVariantKind(row.entityKind)) continue;
338
+ if (memotaLocator(row.payload.external) === void 0) throw new EntityTimelineProjectionError(`Media Entity ${row.entityId} must carry its own Asset external identity`);
339
+ }
340
+ for (const relation of after.relations) {
341
+ if (relation.relationKind !== "physical-asset") continue;
342
+ const mediaEndpoint = [relation.endpoint0EntityId, relation.endpoint1EntityId].find((endpoint) => isMediaAssetVariantKind(afterKinds.get(String(endpoint)) ?? ""));
343
+ if (mediaEndpoint !== void 0) throw new EntityTimelineProjectionError(`Cannot bind media Entity ${mediaEndpoint} through physical-asset Relation ${relation.relationId}; media owns its Asset identity directly`);
344
+ }
345
+ for (const row of after.entities) {
346
+ if (!isMediaAssetVariantKind(row.entityKind)) continue;
347
+ const priorExternal = memotaLocator(beforeEntities.get(String(row.entityId))?.payload.external);
348
+ if (priorExternal === void 0) continue;
349
+ const nextExternal = memotaLocator(row.payload.external);
350
+ if (nextExternal !== void 0 && (nextExternal.system !== priorExternal.system || nextExternal.key !== priorExternal.key)) throw new EntityTimelineProjectionError(`Media Entity ${row.entityId} cannot rewrite its Asset external identity; create a new Entity instead`);
351
+ }
352
+ }
353
+ function memotaLocator(value) {
354
+ if (!isJsonObject(value) || value.system !== "memota" && value.system !== "memota-speech" || typeof value.key !== "string" || value.key.trim() === "") return;
355
+ return {
356
+ system: value.system,
357
+ key: value.key
358
+ };
359
+ }
360
+ /**
361
+ * Bootstrap an empty script when the foundation has no candidate. Without an
362
+ * explicit project attachment, multiple candidates are ambiguous. Existing
363
+ * content IDs are reused here; Loro editing advances their immutable versions.
364
+ */
365
+ function ensureDocumentAudioScript(entities, idFactory) {
366
+ const scripts = entities.filter((row) => row.entityKind === "audio-script");
367
+ if (scripts.length > 1) throw new EntityTimelineProjectionError("Editor requires exactly one AudioScript");
368
+ const existing = scripts[0];
369
+ if (existing !== void 0) return existing.entityId;
370
+ const id = createEntityId(idFactory("entity"));
371
+ if (entities.some((row) => row.entityId === id)) throw new Error(`Duplicate entity id ${id}`);
372
+ entities.push({
373
+ entityId: id,
374
+ entityKind: "audio-script",
375
+ payload: { segments: [] }
376
+ });
377
+ return id;
378
+ }
379
+ /** Add only missing editor structure; existing identities and owned settings are never replaced. */
380
+ function ensureEditorFoundation(initial, idFactory = (prefix) => `${prefix}_${globalThis.crypto.randomUUID()}`, timelinePayload = {}) {
381
+ const entities = structuredClone([...initial.entities]);
382
+ const relations = structuredClone([...initial.relations]);
383
+ const roots = entities.filter((row) => row.entityKind === "timeline");
384
+ if (roots.length > 1) throw new EntityTimelineProjectionError("Editor requires exactly one Timeline");
385
+ const mintEntity = () => {
386
+ const id = createEntityId(idFactory("entity"));
387
+ if (entities.some((row) => row.entityId === id)) throw new Error(`Duplicate entity id ${id}`);
388
+ return id;
389
+ };
390
+ let timeline = roots[0];
391
+ if (timeline === void 0) {
392
+ timeline = {
393
+ entityId: mintEntity(),
394
+ entityKind: "timeline",
395
+ payload: structuredClone(timelinePayload)
396
+ };
397
+ entities.push(timeline);
398
+ }
399
+ const trackEntityIds = {};
400
+ for (const role of Object.keys(roleOrder$1)) {
401
+ const matches = entities.filter((row) => row.entityKind === "track" && row.payload.role === role);
402
+ if (matches.length > 1) throw new EntityTimelineProjectionError(`Editor has multiple ${role} Tracks`);
403
+ let track = matches[0];
404
+ if (track === void 0) {
405
+ track = {
406
+ entityId: mintEntity(),
407
+ entityKind: "track",
408
+ payload: {
409
+ role,
410
+ order: roleOrder$1[role]
411
+ }
412
+ };
413
+ entities.push(track);
414
+ }
415
+ const bindings = relations.filter((row) => row.relationKind === "timeline-track" && (row.endpoint0EntityId === track.entityId || row.endpoint1EntityId === track.entityId));
416
+ if (bindings.some((row) => row.endpoint0EntityId !== timeline.entityId && row.endpoint1EntityId !== timeline.entityId)) throw new EntityTimelineProjectionError(`Track ${track.entityId} belongs to another Timeline`);
417
+ if (bindings.length === 0) {
418
+ const relationId = createRelationId(idFactory("relation"));
419
+ if (relations.some((row) => row.relationId === relationId)) throw new Error(`Duplicate relation id ${relationId}`);
420
+ relations.push({
421
+ relationId,
422
+ relationKind: "timeline-track",
423
+ endpoint0EntityId: timeline.entityId,
424
+ endpoint1EntityId: track.entityId,
425
+ metadata: {},
426
+ trace: {}
427
+ });
428
+ }
429
+ trackEntityIds[role] = track.entityId;
430
+ }
431
+ const audioScriptEntityId = ensureDocumentAudioScript(entities, idFactory);
432
+ return {
433
+ rows: {
434
+ entities,
435
+ relations
436
+ },
437
+ timelineEntityId: timeline.entityId,
438
+ trackEntityIds,
439
+ audioScriptEntityId
440
+ };
441
+ }
442
+ //#endregion
443
+ //#region src/entity-editor/entity-graph-http-client.ts
444
+ const MENGINE_API_PREFIX = "/api/mengine/v1";
445
+ const numericMarkerValidation$1 = { compareMarkerPoints: (_marker, _range, left, right) => {
446
+ if (typeof left !== "number" || !Number.isFinite(left) || typeof right !== "number" || !Number.isFinite(right)) throw new Error("entity-state requires finite numeric Marker coordinates");
447
+ return left < right ? -1 : left > right ? 1 : 0;
448
+ } };
449
+ /** Browser-safe authenticated Loro client for a document's Entity graph. */
450
+ var EntityGraphHttpClient = class {
451
+ options;
452
+ transport;
453
+ endpoint;
454
+ constructor(options) {
455
+ this.options = options;
456
+ this.transport = new MengineHttpClient(options);
457
+ const origin = options.httpOrigin.replace(/\/$/, "");
458
+ this.endpoint = `${origin}${MENGINE_API_PREFIX}/docs/${encodeURIComponent(options.docId)}/entity-state`;
459
+ }
460
+ async fetchState() {
461
+ return this.request({ method: "GET" });
462
+ }
463
+ /**
464
+ * Compile edits against the original causal snapshot and publish native Loro operations.
465
+ *
466
+ * Deletion intent is derived from baseline IDs omitted from `nextRows`, so a
467
+ * transient create-then-remove never becomes a request to delete unknown
468
+ * persisted data.
469
+ */
470
+ async commit(baseState, nextRows, options = {}) {
471
+ if (options.migrationBaseVv !== void 0) throw new Error("Legacy entity migration is not supported by the Loro contract");
472
+ const next = cloneAndValidateRows(nextRows);
473
+ assertMediaAssetWritePolicy(baseState.rows, next);
474
+ const compiled = compileEntityRows(base64ToBytes(baseState.loroSnapshot), next);
475
+ return this.commitUpdate(bytesToBase64(compiled.update));
476
+ }
477
+ /** Send the same prepared bytes on retry; never recompile an unconfirmed edit. */
478
+ async commitUpdate(update) {
479
+ return this.request({
480
+ method: "POST",
481
+ body: JSON.stringify({ update })
482
+ });
483
+ }
484
+ async request(init) {
485
+ const response = await this.transport.fetch(this.endpoint, {
486
+ ...init,
487
+ headers: this.transport.headers()
488
+ });
489
+ const payload = await safeReadJson(response);
490
+ if (!response.ok) throw new MengineHttpRequestError(response.status, payload);
491
+ return parseWireState(payload, this.options.docId);
492
+ }
493
+ };
494
+ function parseWireState(value, expectedDocId) {
495
+ if (!isRecord(value) || typeof value.doc_id !== "string" || !isNonNegativeSafeInteger(value.revision)) throw new Error("Invalid entity-state response envelope");
496
+ if (value.doc_id !== expectedDocId) throw new Error(`Entity-state response doc_id mismatch: expected "${expectedDocId}"`);
497
+ const rows = parseWireRows(value.rows);
498
+ decodeEntityRelationRows(rows, numericMarkerValidation$1);
499
+ if (typeof value.audio_script_entity_id !== "string") throw new Error("Document AudioScript is not initialized");
500
+ if (typeof value.loro_snapshot !== "string") throw new Error("Missing causal Loro snapshot");
501
+ const state = {
502
+ revision: value.revision,
503
+ loroSnapshot: value.loro_snapshot,
504
+ rows,
505
+ audioScriptEntityId: value.audio_script_entity_id
506
+ };
507
+ readDocumentAudioScript(state);
508
+ return state;
509
+ }
510
+ function parseWireRows(value) {
511
+ if (!isRecord(value) || !Array.isArray(value.entities) || !Array.isArray(value.relations)) throw new Error("Invalid entity-state response rows");
512
+ return {
513
+ entities: value.entities.map(parseWireEntity),
514
+ relations: value.relations.map(parseWireRelation)
515
+ };
516
+ }
517
+ function parseWireEntity(value) {
518
+ if (!isRecord(value) || !isJsonObject(value.payload)) throw new Error("Invalid Entity row in entity-state response");
519
+ return {
520
+ entityId: createEntityId(requiredString(value.entity_id, "entity_id")),
521
+ entityKind: requiredString(value.entity_kind, "entity_kind"),
522
+ payload: structuredClone(value.payload)
523
+ };
524
+ }
525
+ function parseWireRelation(value) {
526
+ if (!isRecord(value) || !isJsonObject(value.metadata) || !isJsonObject(value.trace)) throw new Error("Invalid Relation row in entity-state response");
527
+ return {
528
+ relationId: createRelationId(requiredString(value.relation_id, "relation_id")),
529
+ relationKind: requiredString(value.relation_kind, "relation_kind"),
530
+ endpoint0EntityId: createEntityId(requiredString(value.endpoint_0_entity_id, "endpoint_0_entity_id")),
531
+ endpoint1EntityId: createEntityId(requiredString(value.endpoint_1_entity_id, "endpoint_1_entity_id")),
532
+ metadata: structuredClone(value.metadata),
533
+ trace: structuredClone(value.trace)
534
+ };
535
+ }
536
+ function cloneAndValidateRows(rows) {
537
+ const clone = structuredClone(rows);
538
+ decodeEntityRelationRows(clone, numericMarkerValidation$1);
539
+ return clone;
540
+ }
541
+ function requiredString(value, field) {
542
+ if (typeof value !== "string" || value.length === 0 || value.trim() !== value) throw new Error(`Invalid ${field} in entity-state response`);
543
+ return value;
544
+ }
545
+ function isRecord(value) {
546
+ return value !== null && typeof value === "object" && !Array.isArray(value);
547
+ }
548
+ function isNonNegativeSafeInteger(value) {
549
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
550
+ }
551
+ async function safeReadJson(response) {
552
+ const text = await response.text();
553
+ if (text.length === 0) return null;
554
+ try {
555
+ return JSON.parse(text);
556
+ } catch {
557
+ return text;
558
+ }
559
+ }
560
+ //#endregion
561
+ //#region src/entity-editor/media-asset-import.ts
562
+ const numericCoordinates = { compareMarkerPoints: (_marker, _range, left, right) => {
563
+ if (typeof left !== "number" || typeof right !== "number" || !Number.isFinite(left) || !Number.isFinite(right)) throw new Error("Media editor requires numeric coordinates");
564
+ return left - right;
565
+ } };
566
+ /**
567
+ * Import at the editor boundary, not at asset generation time. Existing
568
+ * provenance is retained.
569
+ *
570
+ * A media variant is a logical facet of its Asset and shares one entity
571
+ * identity: the import mints exactly one entity of the media kind that carries
572
+ * the external locator itself, and deduplicates only against existing variants
573
+ * that already carry the same `(system, key)`. Legacy dual-entity graphs
574
+ * (`asset` row plus a `physical-asset` binding) are not reused and are
575
+ * rejected by the canonical resource policy instead of being migrated.
576
+ */
577
+ function importMediaAsset(initial, fact, idFactory = (prefix) => `${prefix}_${globalThis.crypto.randomUUID()}`) {
578
+ if (!fact.assetId || fact.assetId.trim() !== fact.assetId) throw new Error("Expected an asset id");
579
+ if (![
580
+ "image",
581
+ "video",
582
+ "audio",
583
+ "voice"
584
+ ].includes(fact.kind)) throw new Error("Unsupported media kind");
585
+ if (fact.kind !== "image" && (!Number.isFinite(fact.durationMs) || fact.durationMs <= 0)) throw new Error(`${fact.kind} ${fact.assetId} requires its factual positive duration`);
586
+ if ((fact.kind === "audio" || fact.kind === "voice") && fact.storageKey.trim() === "") throw new Error(`${fact.kind} ${fact.assetId} requires its physical storage key`);
587
+ decodeEntityRelationRows(initial, numericCoordinates);
588
+ assertCanonicalEditorResources(initial);
589
+ const entities = structuredClone([...initial.entities]);
590
+ const relations = structuredClone([...initial.relations]);
591
+ const system = fact.kind === "voice" ? "memota-speech" : "memota";
592
+ const existing = entities.filter((row) => {
593
+ const external = row.payload.external;
594
+ return isMediaAssetVariantKind(row.entityKind) && isJsonObject(external) && external.system === system && external.key === fact.assetId;
595
+ });
596
+ if (existing.length > 1) throw new Error(`Duplicate media identities for ${fact.assetId}; reuse ${existing[0].entityId}`);
597
+ if (existing[0] !== void 0) {
598
+ const variant = requireMatchingVariant(existing[0], fact);
599
+ replaceEntity$1(entities, variant.entityId, variant);
600
+ return {
601
+ rows: {
602
+ entities,
603
+ relations
604
+ },
605
+ contentEntityId: variant.entityId
606
+ };
607
+ }
608
+ const entityId = createEntityId(idFactory("entity"));
609
+ if (entities.some((row) => row.entityId === entityId)) throw new Error(`Duplicate entity id ${entityId}`);
610
+ const variant = {
611
+ entityId,
612
+ entityKind: fact.kind,
613
+ payload: {
614
+ extent: fact.kind === "image" ? {
615
+ kind: "unbounded",
616
+ start: 0
617
+ } : {
618
+ kind: "bounded",
619
+ start: 0,
620
+ end: fact.durationMs
621
+ },
622
+ sampling: fact.kind === "image" ? "constant" : "native",
623
+ coordinateSpace: "milliseconds",
624
+ external: {
625
+ system,
626
+ key: fact.assetId
627
+ },
628
+ ...fact.storageKey === void 0 ? {} : { storageKey: fact.storageKey },
629
+ ...fact.kind === "voice" && fact.voice !== void 0 ? { voice: {
630
+ system: fact.voice.system,
631
+ key: fact.voice.key,
632
+ ...fact.voice.name === void 0 ? {} : { name: fact.voice.name }
633
+ } } : {}
634
+ }
635
+ };
636
+ entities.push(variant);
637
+ const rows = {
638
+ entities,
639
+ relations
640
+ };
641
+ decodeEntityRelationRows(rows, numericCoordinates);
642
+ assertCanonicalEditorResources(rows);
643
+ return {
644
+ rows,
645
+ contentEntityId: entityId
646
+ };
647
+ }
648
+ function requireMatchingVariant(row, fact) {
649
+ const extent = row.payload.extent;
650
+ if (row.entityKind !== fact.kind || fact.kind !== "image" && (!isJsonObject(extent) || extent.start !== 0 || extent.end !== fact.durationMs) || fact.kind === "voice" && !sameVoice(row.payload.voice, fact.voice)) throw new Error(`Media facts conflict with existing identity for ${fact.assetId}`);
651
+ if (fact.storageKey !== void 0 && row.payload.storageKey !== fact.storageKey) {
652
+ if (row.payload.storageKey !== void 0) throw new Error(`Media facts conflict with existing storage key for ${fact.assetId}`);
653
+ return {
654
+ ...row,
655
+ payload: {
656
+ ...row.payload,
657
+ storageKey: fact.storageKey
658
+ }
659
+ };
660
+ }
661
+ return row;
662
+ }
663
+ function replaceEntity$1(entities, entityId, replacement) {
664
+ const index = entities.findIndex((row) => row.entityId === entityId);
665
+ if (index < 0) throw new Error(`Entity id ${entityId} does not exist`);
666
+ entities[index] = replacement;
667
+ }
668
+ function sameVoice(left, right) {
669
+ if (right === void 0) return left === void 0;
670
+ return isJsonObject(left) && left.system === right.system && left.key === right.key && left.name === right.name && Object.keys(left).every((key) => key === "system" || key === "key" || key === "name");
671
+ }
672
+ //#endregion
673
+ //#region src/entity-editor/entity-timeline-editor.ts
674
+ /**
675
+ * Resolve the AudioScript a PhoneticScript composes. The composition is the
676
+ * required text source: a variant without it has no content and fails here.
677
+ */
678
+ function requireComposedAudioScript(rows, phoneticScriptEntityId) {
679
+ return assemblePhoneticScriptContent(rows, phoneticScriptEntityId).audioScript.entityId;
680
+ }
681
+ function captionSelections(selections) {
682
+ return structuredClone(selections);
683
+ }
684
+ function captionBaseIds(ids) {
685
+ if (!Array.isArray(ids) || ids.length === 0) throw new Error("Caption requires non-empty baseEntityIds");
686
+ return ids.map(createEntityId);
687
+ }
688
+ function assertCaptionScript(rows, captionId, scriptId) {
689
+ if (assembleCaptionContent(rows, captionId).audioScript.entityId !== scriptId) throw new Error("Voiceover Caption must compose the same AudioScript as the PhoneticScript");
690
+ }
691
+ const roleOrder = {
692
+ caption: 0,
693
+ video_clip: 1,
694
+ speech: 2,
695
+ bgm: 3
696
+ };
697
+ const defaultIdFactory = (prefix) => `${prefix}_${globalThis.crypto.randomUUID()}`;
698
+ /**
699
+ * Graph-native timeline authoring over authoritative Medeo Entity and Relation rows.
700
+ *
701
+ * Each mutation is applied to a detached graph, validated as a complete DSL set,
702
+ * and committed only after validation succeeds.
703
+ */
704
+ var EntityTimelineEditor = class {
705
+ idFactory;
706
+ state;
707
+ constructor(initialRows, idFactory = defaultIdFactory) {
708
+ this.idFactory = idFactory;
709
+ this.state = cloneRows(initialRows);
710
+ }
711
+ rows() {
712
+ return cloneRows(this.state);
713
+ }
714
+ insertClip(input) {
715
+ const requestedOrder = input.clipPayload?.order;
716
+ const order = typeof requestedOrder === "number" ? requestedOrder : nextSequentialOrder(this.state, createEntityId(input.trackEntityId));
717
+ return this.insertPlacedClip({
718
+ trackEntityId: input.trackEntityId,
719
+ contentEntityId: input.contentEntityId,
720
+ sourceRange: input.sourceRange,
721
+ duration: input.duration,
722
+ placement: input.targetRange === void 0 ? {
723
+ kind: "sequential",
724
+ order
725
+ } : {
726
+ kind: "absolute",
727
+ targetRange: input.targetRange
728
+ },
729
+ clipPayload: input.clipPayload
730
+ });
731
+ }
732
+ insertPlacedClip(input) {
733
+ return this.transact((draft) => this.insertPlacedClipIntoDraft(draft, input));
734
+ }
735
+ updateClipMarker(input) {
736
+ this.transact((draft) => {
737
+ const { marker } = requireClipTopology(draft, input.clipEntityId);
738
+ const payload = { ...cloneJsonObject(marker.payload, "Sequence Marker payload") };
739
+ if (input.sourceRange !== void 0) payload.sourceRange = cloneJsonValue(input.sourceRange, "sourceRange");
740
+ if (input.duration !== void 0) payload.duration = cloneJsonValue(input.duration, "duration");
741
+ if (Object.hasOwn(input, "targetRange")) if (input.targetRange === void 0) {
742
+ delete payload.targetRange;
743
+ if (!hasOutgoingClipAnchor(draft, input.clipEntityId)) {
744
+ const trackId = otherEndpoint(requireOneRelation(draft, createEntityId(input.clipEntityId), "track-clip"), input.clipEntityId);
745
+ const clipPayload = { ...cloneJsonObject(requireEntityKind(draft, input.clipEntityId, "clip").payload, "Clip payload") };
746
+ clipPayload.order ??= nextSequentialOrder(draft, trackId);
747
+ replaceEntity(draft, createEntityId(input.clipEntityId), {
748
+ ...requireEntityKind(draft, input.clipEntityId, "clip"),
749
+ payload: clipPayload
750
+ });
751
+ }
752
+ } else {
753
+ payload.targetRange = cloneJsonValue(input.targetRange, "targetRange");
754
+ const clip = requireEntityKind(draft, input.clipEntityId, "clip");
755
+ const clipPayload = { ...cloneJsonObject(clip.payload, "Clip payload") };
756
+ delete clipPayload.order;
757
+ replaceEntity(draft, clip.entityId, {
758
+ ...clip,
759
+ payload: clipPayload
760
+ });
761
+ }
762
+ if (Object.hasOwn(input, "timeRemapping")) if (input.timeRemapping === void 0) delete payload.timeRemapping;
763
+ else payload.timeRemapping = cloneJsonValue(input.timeRemapping, "timeRemapping");
764
+ replaceEntity(draft, marker.entityId, {
765
+ ...marker,
766
+ payload
767
+ });
768
+ });
769
+ }
770
+ setClipPlacement(input) {
771
+ this.transact((draft) => this.applyClipPlacement(draft, input.clipEntityId, input.placement));
772
+ }
773
+ moveSequentialClips(input) {
774
+ if (input.clipEntityIds.length === 0) throw new Error("At least one Clip is required");
775
+ this.transact((draft) => {
776
+ const original = resolveEntityTimelineLayout(draft);
777
+ this.normalizeMainSequential(draft);
778
+ const before = resolveEntityTimelineLayout(draft);
779
+ const targetIds = new Set(input.clipEntityIds);
780
+ if (targetIds.size !== input.clipEntityIds.length) throw new Error("Clip ids must be unique");
781
+ const placements = input.clipEntityIds.map((id) => before.clips.get(id));
782
+ if (placements.some((placement) => placement === void 0 || placement.mode !== "sequential")) throw new Error("moveSequentialClips accepts only sequential Clips");
783
+ const trackIds = new Set(placements.map((placement) => placement.trackEntityId));
784
+ if (trackIds.size !== 1) throw new Error("Moved Clips must belong to one Track");
785
+ const trackId = [...trackIds][0];
786
+ const track = before.tracks.find((candidate) => candidate.entityId === trackId);
787
+ if (track?.role !== "video_clip") throw new Error("Only the video_clip Track supports sequential block moves");
788
+ const ordered = track.clips.filter((placement) => placement.mode === "sequential").map((placement) => placement.clipEntityId);
789
+ if (input.anchor.position !== "trackStart" && targetIds.has(input.anchor.clipEntityId)) throw new Error("Move anchor cannot be one of the moved Clips");
790
+ const moved = ordered.filter((id) => targetIds.has(id));
791
+ if (moved.length !== targetIds.size) throw new Error("Every moved Clip must exist on the target Track");
792
+ const remaining = ordered.filter((id) => !targetIds.has(id));
793
+ let insertAt = 0;
794
+ if (input.anchor.position !== "trackStart") {
795
+ const anchorIndex = remaining.indexOf(input.anchor.clipEntityId);
796
+ if (anchorIndex < 0) throw new Error("Move anchor Clip does not exist on the target Track");
797
+ insertAt = anchorIndex + (input.anchor.position === "after" ? 1 : 0);
798
+ }
799
+ [
800
+ ...remaining.slice(0, insertAt),
801
+ ...moved,
802
+ ...remaining.slice(insertAt)
803
+ ].forEach((clipId, order) => setClipOrder(draft, clipId, order));
804
+ if (input.onAnchored === "keepAbsolute") {
805
+ const affected = outgoingAnchorChildren(draft, new Set(track.clips.map((clip) => clip.clipEntityId))).filter((childId) => clipRole(draft, childId) === "speech").map((childId) => {
806
+ const placement = original.clips.get(childId);
807
+ if (placement === void 0) throw new Error(`Anchored child Clip "${childId}" is not placed`);
808
+ return {
809
+ childId,
810
+ start: placement.start
811
+ };
812
+ });
813
+ const after = resolveEntityTimelineLayout(draft);
814
+ for (const child of affected) this.reanchorAtAbsolute(draft, child.childId, child.start, after);
815
+ }
816
+ this.resolveOneVoiceoverOverlap(draft);
817
+ });
818
+ }
819
+ moveClipsToStarts(input) {
820
+ if (input.moves.length === 0) throw new Error("At least one Clip move is required");
821
+ this.transact((draft) => {
822
+ const original = resolveEntityTimelineLayout(draft);
823
+ const originalVideo = original.tracks.find((track) => track.role === "video_clip");
824
+ if (originalVideo === void 0) throw new Error("The timeline has no video_clip Track");
825
+ const preservedVoiceovers = outgoingAnchorChildren(draft, new Set(originalVideo.clips.map((clip) => clip.clipEntityId))).filter((clipId) => clipRole(draft, clipId) === "speech").map((clipId) => ({
826
+ clipId,
827
+ start: original.clips.get(clipId).start
828
+ }));
829
+ this.normalizeMainSequential(draft);
830
+ for (const move of input.moves) {
831
+ finiteNonNegative(move.newStartMs, "newStartMs");
832
+ requireClipOnRole(draft, move.clipEntityId, "video_clip");
833
+ const track = resolveEntityTimelineLayout(draft).tracks.find((candidate) => candidate.role === "video_clip");
834
+ const ordered = track.clips.map((clip) => clip.clipEntityId);
835
+ const from = ordered.indexOf(move.clipEntityId);
836
+ if (from < 0) throw new Error(`Clip "${move.clipEntityId}" is not on the video_clip Track`);
837
+ const remaining = track.clips.filter((clip) => clip.clipEntityId !== move.clipEntityId);
838
+ let cursor = 0;
839
+ let target = remaining.length;
840
+ for (const [index, clip] of remaining.entries()) {
841
+ if (move.newStartMs <= cursor + clip.duration / 2) {
842
+ target = index;
843
+ break;
844
+ }
845
+ cursor += clip.duration;
846
+ }
847
+ const next = [...ordered];
848
+ next.splice(from, 1);
849
+ next.splice(target, 0, move.clipEntityId);
850
+ next.forEach((clipId, order) => setClipOrder(draft, clipId, order));
851
+ }
852
+ const after = resolveEntityTimelineLayout(draft);
853
+ for (const voiceover of preservedVoiceovers) this.reanchorAtAbsolute(draft, voiceover.clipId, voiceover.start, after);
854
+ this.resolveOneVoiceoverOverlap(draft);
855
+ });
856
+ }
857
+ moveClip(input) {
858
+ this.transact((draft) => {
859
+ const topology = requireClipTopology(draft, input.clipEntityId);
860
+ const track = requireEntityKind(draft, input.trackEntityId, "track");
861
+ requireTrackTimeline(draft, track.entityId);
862
+ this.relinkRelation(draft, topology.trackRelation, {
863
+ endpoint0EntityId: track.entityId,
864
+ endpoint1EntityId: topology.clip.entityId
865
+ });
866
+ });
867
+ }
868
+ replaceClipContent(input) {
869
+ this.transact((draft) => {
870
+ const topology = requireClipTopology(draft, input.clipEntityId);
871
+ const content = requireSequenceContent(draft, input.contentEntityId);
872
+ const payload = {
873
+ ...cloneJsonObject(topology.marker.payload, "Sequence Marker payload"),
874
+ sourceRange: cloneJsonValue(input.sourceRange, "sourceRange"),
875
+ duration: cloneJsonValue(input.duration, "duration")
876
+ };
877
+ delete payload.targetRange;
878
+ delete payload.timeRemapping;
879
+ if (input.targetRange !== void 0) payload.targetRange = cloneJsonValue(input.targetRange, "targetRange");
880
+ if (input.timeRemapping !== void 0) payload.timeRemapping = cloneJsonValue(input.timeRemapping, "timeRemapping");
881
+ replaceEntity(draft, topology.marker.entityId, {
882
+ ...topology.marker,
883
+ payload
884
+ });
885
+ if (!hasOutgoingClipAnchor(draft, topology.clip.entityId)) {
886
+ const clipPayload = { ...cloneJsonObject(topology.clip.payload, "Clip payload") };
887
+ if (input.targetRange === void 0) clipPayload.order ??= nextSequentialOrder(draft, otherEndpoint(topology.trackRelation, topology.clip.entityId));
888
+ else delete clipPayload.order;
889
+ replaceEntity(draft, topology.clip.entityId, {
890
+ ...topology.clip,
891
+ payload: clipPayload
892
+ });
893
+ }
894
+ this.relinkRelation(draft, topology.markerContentRelation, {
895
+ endpoint0EntityId: topology.marker.entityId,
896
+ endpoint1EntityId: content.entityId
897
+ });
898
+ });
899
+ }
900
+ insertMediaClip(input) {
901
+ return this.transact((draft) => {
902
+ if (input.placement.kind === "sequential") this.normalizeMainSequential(draft);
903
+ const imported = importMediaAsset(draft, input.media, this.idFactory);
904
+ replaceRows(draft, imported.rows);
905
+ const track = this.ensureRoleTrack(draft, input.timelineEntityId, "video_clip");
906
+ const sourceRange = requirePositiveRange(input.sourceRange, "sourceRange");
907
+ const clipId = this.insertPlacedClipIntoDraft(draft, {
908
+ trackEntityId: track.entityId,
909
+ contentEntityId: imported.contentEntityId,
910
+ sourceRange,
911
+ duration: {
912
+ mode: "fixed",
913
+ value: sourceRange.end - sourceRange.start
914
+ },
915
+ placement: input.placement,
916
+ ...input.clipEntityId === void 0 ? {} : { clipEntityId: input.clipEntityId },
917
+ ...input.volume === void 0 ? {} : { clipPayload: { volume: requireVolume(input.volume) } }
918
+ });
919
+ if (input.placement.kind === "sequential") this.resolveOneVoiceoverOverlap(draft);
920
+ return clipId;
921
+ });
922
+ }
923
+ insertMediaClips(input) {
924
+ if (input.clips.length === 0) throw new Error("At least one media Clip is required");
925
+ return this.transact((draft) => {
926
+ this.normalizeMainSequential(draft);
927
+ const track = this.ensureRoleTrack(draft, input.timelineEntityId, "video_clip");
928
+ const ordered = resolveEntityTimelineLayout(draft).tracks.find((candidate) => candidate.entityId === track.entityId)?.clips ?? [];
929
+ let insertAt = ordered.length;
930
+ const insertion = input.insertion;
931
+ if (insertion.kind === "before" || insertion.kind === "after") {
932
+ const anchorIndex = ordered.findIndex((clip) => clip.clipEntityId === insertion.clipEntityId);
933
+ if (anchorIndex >= 0) insertAt = anchorIndex + (insertion.kind === "after" ? 1 : 0);
934
+ } else {
935
+ const startMs = finiteNonNegative(insertion.startMs, "firstStart.startMs");
936
+ let cursor = 0;
937
+ for (const [index, clip] of ordered.entries()) {
938
+ if (startMs <= cursor + clip.duration / 2) {
939
+ insertAt = index;
940
+ break;
941
+ }
942
+ cursor += clip.duration;
943
+ }
944
+ }
945
+ const created = [];
946
+ for (const [offset, clip] of input.clips.entries()) {
947
+ const imported = importMediaAsset(draft, clip.media, this.idFactory);
948
+ replaceRows(draft, imported.rows);
949
+ const sourceRange = requirePositiveRange(clip.sourceRange, "sourceRange");
950
+ created.push(this.insertPlacedClipIntoDraft(draft, {
951
+ trackEntityId: track.entityId,
952
+ contentEntityId: imported.contentEntityId,
953
+ sourceRange,
954
+ duration: {
955
+ mode: "fixed",
956
+ value: sourceRange.end - sourceRange.start
957
+ },
958
+ placement: {
959
+ kind: "sequential",
960
+ order: ordered.length + offset
961
+ },
962
+ ...clip.clipEntityId === void 0 ? {} : { clipEntityId: clip.clipEntityId },
963
+ ...clip.volume === void 0 ? {} : { clipPayload: { volume: requireVolume(clip.volume) } }
964
+ }));
965
+ }
966
+ const desired = ordered.map((clip) => clip.clipEntityId);
967
+ desired.splice(insertAt, 0, ...created);
968
+ desired.forEach((clipId, order) => setClipOrder(draft, clipId, order));
969
+ this.resolveOneVoiceoverOverlap(draft);
970
+ return created;
971
+ });
972
+ }
973
+ replaceMediaClip(input) {
974
+ this.transact((draft) => {
975
+ this.normalizeMainSequential(draft);
976
+ const topology = requireClipOnRole(draft, input.clipEntityId, "video_clip");
977
+ const imported = importMediaAsset(draft, input.media, this.idFactory);
978
+ replaceRows(draft, imported.rows);
979
+ const sourceRange = requirePositiveRange(input.sourceRange, "sourceRange");
980
+ const markerPayloadValue = {
981
+ ...cloneJsonObject(topology.marker.payload, "Sequence Marker payload"),
982
+ sourceRange,
983
+ duration: {
984
+ mode: "fixed",
985
+ value: sourceRange.end - sourceRange.start
986
+ }
987
+ };
988
+ delete markerPayloadValue.timeRemapping;
989
+ resizeAbsoluteTarget(markerPayloadValue, sourceRange.end - sourceRange.start);
990
+ replaceEntity(draft, topology.marker.entityId, {
991
+ ...topology.marker,
992
+ payload: markerPayloadValue
993
+ });
994
+ this.relinkRelation(draft, topology.markerContentRelation, {
995
+ endpoint0EntityId: topology.marker.entityId,
996
+ endpoint1EntityId: createEntityId(imported.contentEntityId)
997
+ });
998
+ this.resolveOneVoiceoverOverlap(draft);
999
+ });
1000
+ }
1001
+ setClipVolume(input) {
1002
+ this.transact((draft) => {
1003
+ const topology = requireClipTopology(draft, input.clipEntityId);
1004
+ requireSupportedRole(draft, topology);
1005
+ replaceEntity(draft, topology.clip.entityId, {
1006
+ ...topology.clip,
1007
+ payload: {
1008
+ ...topology.clip.payload,
1009
+ volume: requireVolume(input.volume)
1010
+ }
1011
+ });
1012
+ });
1013
+ }
1014
+ setClipSpeed(input) {
1015
+ this.transact((draft) => {
1016
+ const initialTopology = requireClipOnRole(draft, input.clipEntityId, "video_clip");
1017
+ const content = requireSequenceContent(draft, otherEndpoint(initialTopology.markerContentRelation, initialTopology.marker.entityId));
1018
+ if (content.entityKind !== "video" && content.entityKind !== "image") throw new Error("Clip speed is supported only for Video or Image content");
1019
+ const initialPayload = cloneJsonObject(initialTopology.marker.payload, "Sequence Marker payload");
1020
+ const priorSource = requirePositiveRange(initialPayload.sourceRange, "sourceRange");
1021
+ if (input.timeRemapping === null && initialPayload.timeRemapping === void 0) return;
1022
+ this.normalizeMainSequential(draft);
1023
+ const topology = requireClipTopology(draft, input.clipEntityId);
1024
+ const payload = { ...cloneJsonObject(topology.marker.payload, "Sequence Marker payload") };
1025
+ let sourceRange = priorSource;
1026
+ if (content.entityKind === "image" && initialPayload.timeRemapping === void 0 && input.timeRemapping !== null) sourceRange = {
1027
+ start: 0,
1028
+ end: markerDuration(initialPayload, priorSource)
1029
+ };
1030
+ if (input.timeRemapping === null) {
1031
+ delete payload.timeRemapping;
1032
+ payload.sourceRange = sourceRange;
1033
+ payload.duration = {
1034
+ mode: "fixed",
1035
+ value: sourceRange.end - sourceRange.start
1036
+ };
1037
+ } else {
1038
+ const rate = finitePositive(input.timeRemapping.rate, "linear speed rate");
1039
+ const duration = Math.round((sourceRange.end - sourceRange.start) / rate);
1040
+ if (duration <= 0 || !Number.isSafeInteger(duration)) throw new Error("Linear speed produces an invalid duration");
1041
+ payload.sourceRange = sourceRange;
1042
+ payload.duration = {
1043
+ mode: "fixed",
1044
+ value: duration
1045
+ };
1046
+ payload.timeRemapping = {
1047
+ kind: "linear",
1048
+ rate,
1049
+ ...input.timeRemapping.mode === void 0 ? {} : { mode: input.timeRemapping.mode }
1050
+ };
1051
+ }
1052
+ resizeAbsoluteTarget(payload, markerDuration(payload, sourceRange));
1053
+ replaceEntity(draft, topology.marker.entityId, {
1054
+ ...topology.marker,
1055
+ payload
1056
+ });
1057
+ this.resolveOneVoiceoverOverlap(draft);
1058
+ });
1059
+ }
1060
+ trimClip(input) {
1061
+ this.transact((draft) => {
1062
+ this.normalizeMainSequential(draft);
1063
+ const topology = requireClipOnRole(draft, input.clipEntityId, "video_clip");
1064
+ const content = requireSequenceContent(draft, otherEndpoint(topology.markerContentRelation, topology.marker.entityId));
1065
+ if (content.entityKind !== "video" && content.entityKind !== "image") throw new Error("Clip trimming is supported only for Video or Image content");
1066
+ const sourceRange = requirePositiveRange(input.sourceRange, "sourceRange");
1067
+ const payload = {
1068
+ ...cloneJsonObject(topology.marker.payload, "Sequence Marker payload"),
1069
+ sourceRange
1070
+ };
1071
+ const rate = linearRate(payload.timeRemapping);
1072
+ const duration = Math.round((sourceRange.end - sourceRange.start) / rate);
1073
+ if (duration <= 0 || !Number.isSafeInteger(duration)) throw new Error("Trim produces an invalid duration");
1074
+ payload.duration = {
1075
+ mode: "fixed",
1076
+ value: duration
1077
+ };
1078
+ resizeAbsoluteTarget(payload, duration);
1079
+ replaceEntity(draft, topology.marker.entityId, {
1080
+ ...topology.marker,
1081
+ payload
1082
+ });
1083
+ this.resolveOneVoiceoverOverlap(draft);
1084
+ });
1085
+ }
1086
+ replaceSequentialClips(input) {
1087
+ if (input.oldClipEntityIds.length === 0 || input.newClips.length === 0) throw new Error("Replacement requires at least one old and one new Clip");
1088
+ return this.transact((draft) => {
1089
+ this.normalizeMainSequential(draft);
1090
+ const before = resolveEntityTimelineLayout(draft);
1091
+ const oldIds = new Set(input.oldClipEntityIds);
1092
+ if (oldIds.size !== input.oldClipEntityIds.length) throw new Error("Old Clip ids must be unique");
1093
+ const track = this.ensureRoleTrack(draft, input.timelineEntityId, "video_clip");
1094
+ const ordered = before.tracks.find((candidate) => candidate.entityId === track.entityId)?.clips.filter((clip) => clip.mode === "sequential").map((clip) => clip.clipEntityId);
1095
+ if (ordered === void 0) throw new Error("The video_clip Track is not present in the current layout");
1096
+ const indexes = input.oldClipEntityIds.map((id) => ordered.indexOf(id));
1097
+ if (indexes.some((index) => index < 0)) throw new Error("Every replaced Clip must be sequential on video_clip");
1098
+ const sortedIndexes = [...indexes].sort((left, right) => left - right);
1099
+ if (sortedIndexes.some((index, offset) => index !== sortedIndexes[0] + offset)) throw new Error("Replaced Clips must form one contiguous timeline run");
1100
+ if (input.oldClipEntityIds.some((id, index) => id !== ordered[sortedIndexes[0] + index])) throw new Error("Replaced Clip ids must be listed in timeline order");
1101
+ const insertOrder = sortedIndexes[0];
1102
+ const temporaryOrder = ordered.length;
1103
+ const created = [];
1104
+ for (const [offset, replacement] of input.newClips.entries()) {
1105
+ if (replacement.clipEntityId !== void 0 && oldIds.has(replacement.clipEntityId)) throw new Error("A replacement Clip id cannot reuse an Entity being removed");
1106
+ const imported = importMediaAsset(draft, replacement.media, this.idFactory);
1107
+ replaceRows(draft, imported.rows);
1108
+ const sourceRange = requirePositiveRange(replacement.sourceRange, "sourceRange");
1109
+ created.push(this.insertPlacedClipIntoDraft(draft, {
1110
+ trackEntityId: track.entityId,
1111
+ contentEntityId: imported.contentEntityId,
1112
+ sourceRange,
1113
+ duration: {
1114
+ mode: "fixed",
1115
+ value: sourceRange.end - sourceRange.start
1116
+ },
1117
+ placement: {
1118
+ kind: "sequential",
1119
+ order: temporaryOrder + offset
1120
+ },
1121
+ ...replacement.clipEntityId === void 0 ? {} : { clipEntityId: replacement.clipEntityId },
1122
+ ...replacement.volume === void 0 ? {} : { clipPayload: { volume: requireVolume(replacement.volume) } }
1123
+ }));
1124
+ }
1125
+ for (const [index, oldId] of input.oldClipEntityIds.entries()) {
1126
+ const children = directAnchorChildren(draft, oldId);
1127
+ if (input.onAnchored === "remap" && created[index] !== void 0) for (const childId of children) this.replaceAnchorHost(draft, childId, created[index]);
1128
+ else {
1129
+ const scheduled = /* @__PURE__ */ new Set();
1130
+ for (const childId of children) {
1131
+ scheduled.add(childId);
1132
+ this.removeAnchoredDescendants(draft, childId, scheduled);
1133
+ this.removeClipGraph(draft, childId);
1134
+ }
1135
+ }
1136
+ }
1137
+ for (const oldId of input.oldClipEntityIds) this.removeClipGraph(draft, oldId);
1138
+ [
1139
+ ...ordered.slice(0, insertOrder),
1140
+ ...created,
1141
+ ...ordered.slice(insertOrder + input.oldClipEntityIds.length)
1142
+ ].forEach((clipId, order) => setClipOrder(draft, clipId, order));
1143
+ this.resolveOneVoiceoverOverlap(draft);
1144
+ return created;
1145
+ });
1146
+ }
1147
+ deleteClip(input) {
1148
+ this.transact((draft) => {
1149
+ const topology = requireClipTopology(draft, input.clipEntityId);
1150
+ assertOnlyStructuralIncidents(draft, topology.clip.entityId, new Set(["track-clip", "clip-marker"]));
1151
+ assertOnlyStructuralIncidents(draft, topology.marker.entityId, new Set(["clip-marker", "marker-content"]));
1152
+ const markerIsExclusive = incidentRelations(draft, topology.marker.entityId).filter((relation) => relation.relationKind === "clip-marker").length === 1;
1153
+ const removedRelationIds = new Set([topology.trackRelation.relationId, topology.clipMarkerRelation.relationId]);
1154
+ if (markerIsExclusive) for (const relation of incidentRelations(draft, topology.marker.entityId)) removedRelationIds.add(relation.relationId);
1155
+ draft.relations = draft.relations.filter((relation) => !removedRelationIds.has(relation.relationId));
1156
+ draft.entities = draft.entities.filter((entity) => entity.entityId !== topology.clip.entityId && (!markerIsExclusive || entity.entityId !== topology.marker.entityId));
1157
+ });
1158
+ }
1159
+ deleteClipTree(input) {
1160
+ if (input.clipEntityIds.length === 0) throw new Error("At least one Clip is required");
1161
+ this.transact((draft) => {
1162
+ const targets = new Set(input.clipEntityIds);
1163
+ if (targets.size !== input.clipEntityIds.length) throw new Error("Clip ids must be unique");
1164
+ for (const target of targets) requireEntityKind(draft, target, "clip");
1165
+ const includesVisual = [...targets].some((target) => clipRole(draft, target) === "video_clip");
1166
+ const original = resolveEntityTimelineLayout(draft);
1167
+ if (includesVisual) this.normalizeMainSequential(draft);
1168
+ if (input.onAnchored === "detach") for (const childId of outgoingAnchorChildren(draft, targets)) {
1169
+ if (targets.has(childId)) continue;
1170
+ const placement = original.clips.get(childId);
1171
+ if (placement === void 0) throw new Error(`Anchored child Clip "${childId}" is not placed`);
1172
+ this.applyClipPlacement(draft, childId, {
1173
+ kind: "absolute",
1174
+ targetRange: {
1175
+ start: placement.start,
1176
+ end: placement.start + placement.duration
1177
+ }
1178
+ });
1179
+ }
1180
+ else for (const target of targets) this.removeAnchoredDescendants(draft, target, targets);
1181
+ for (const target of targets) this.removeClipGraph(draft, target);
1182
+ normalizeSequentialOrders(draft);
1183
+ if (includesVisual) this.resolveOneVoiceoverOverlap(draft);
1184
+ });
1185
+ }
1186
+ updateClip(input) {
1187
+ this.transact((draft) => {
1188
+ const clip = requireEntityKind(draft, input.clipEntityId, "clip");
1189
+ const priorOrder = clip.payload.order;
1190
+ replaceEntity(draft, clip.entityId, {
1191
+ ...clip,
1192
+ payload: {
1193
+ ...cloneJsonObject(input.payload, "Clip payload"),
1194
+ ...priorOrder === void 0 || Object.hasOwn(input.payload, "order") ? {} : { order: priorOrder }
1195
+ }
1196
+ });
1197
+ });
1198
+ }
1199
+ upsertVoiceoverTake(input) {
1200
+ return this.transact((draft) => {
1201
+ this.normalizeMainSequential(draft);
1202
+ const placement = input.placement ?? {
1203
+ kind: "anchored",
1204
+ hostClipEntityId: input.hostClipEntityId,
1205
+ anchorOffset: input.anchorOffset
1206
+ };
1207
+ if (input.placement !== void 0 && (input.hostClipEntityId !== void 0 || input.anchorOffset !== void 0)) throw new Error("Specify Voice placement or hostClipEntityId/anchorOffset, not both");
1208
+ requireVolume(input.volume);
1209
+ const imported = importMediaAsset(draft, input.media, this.idFactory);
1210
+ replaceRows(draft, imported.rows);
1211
+ const voice = requireEntityKind(draft, imported.contentEntityId, "voice");
1212
+ const phonetic = this.requireComposedPhoneticScript(draft, input.phoneticScriptEntityId);
1213
+ this.ensurePhoneticRender(draft, voice.entityId, phonetic.entityId);
1214
+ const speechTrack = this.ensureRoleTrack(draft, input.timelineEntityId, "speech");
1215
+ const existing = draft.entities.find((row) => row.entityId === input.voiceoverClipEntityId);
1216
+ let voiceoverClipEntityId;
1217
+ if (existing === void 0) voiceoverClipEntityId = this.insertPlacedClipIntoDraft(draft, {
1218
+ clipEntityId: input.voiceoverClipEntityId,
1219
+ trackEntityId: speechTrack.entityId,
1220
+ contentEntityId: voice.entityId,
1221
+ sourceRange: {
1222
+ start: 0,
1223
+ end: input.media.durationMs
1224
+ },
1225
+ duration: {
1226
+ mode: "fixed",
1227
+ value: input.media.durationMs
1228
+ },
1229
+ placement,
1230
+ clipPayload: { volume: input.volume }
1231
+ });
1232
+ else {
1233
+ const topology = requireClipOnRole(draft, input.voiceoverClipEntityId, "speech");
1234
+ voiceoverClipEntityId = topology.clip.entityId;
1235
+ replaceEntity(draft, topology.clip.entityId, {
1236
+ ...topology.clip,
1237
+ payload: {
1238
+ ...topology.clip.payload,
1239
+ volume: input.volume
1240
+ }
1241
+ });
1242
+ this.relinkRelation(draft, topology.markerContentRelation, {
1243
+ endpoint0EntityId: topology.marker.entityId,
1244
+ endpoint1EntityId: voice.entityId
1245
+ });
1246
+ this.applyClipPlacement(draft, topology.clip.entityId, placement);
1247
+ const placed = requireClipTopology(draft, topology.clip.entityId);
1248
+ replaceEntity(draft, placed.marker.entityId, {
1249
+ ...placed.marker,
1250
+ payload: {
1251
+ ...placed.marker.payload,
1252
+ sourceRange: {
1253
+ start: 0,
1254
+ end: input.media.durationMs
1255
+ },
1256
+ duration: {
1257
+ mode: "fixed",
1258
+ value: input.media.durationMs
1259
+ }
1260
+ }
1261
+ });
1262
+ }
1263
+ this.reconcileVoiceoverCaptions(draft, voiceoverClipEntityId, voice.entityId, phonetic.entityId, input.captions);
1264
+ this.resolveOneVoiceoverOverlap(draft);
1265
+ return {
1266
+ voiceoverClipEntityId,
1267
+ voiceEntityId: voice.entityId,
1268
+ phoneticScriptEntityId: phonetic.entityId,
1269
+ audioScriptEntityId: requireComposedAudioScript(draft, phonetic.entityId),
1270
+ captionClipEntityIds: input.captions.map((caption) => caption.captionClipEntityId)
1271
+ };
1272
+ });
1273
+ }
1274
+ moveVoiceover(input) {
1275
+ this.transact((draft) => {
1276
+ requireClipOnRole(draft, input.voiceoverClipEntityId, "speech");
1277
+ this.normalizeMainSequential(draft);
1278
+ const layout = resolveEntityTimelineLayout(draft);
1279
+ this.reanchorAtAbsolute(draft, input.voiceoverClipEntityId, finiteNonNegative(input.newStartMs, "newStartMs"), layout);
1280
+ this.resolveOneVoiceoverOverlap(draft);
1281
+ });
1282
+ }
1283
+ deleteVoiceover(input) {
1284
+ this.transact((draft) => {
1285
+ this.normalizeMainSequential(draft);
1286
+ const targets = new Set(input.voiceoverClipEntityIds);
1287
+ if (targets.size !== input.voiceoverClipEntityIds.length) throw new Error("Voiceover Clip ids must be unique");
1288
+ for (const clipId of targets) {
1289
+ requireClipOnRole(draft, clipId, "speech");
1290
+ this.removeAnchoredDescendants(draft, clipId, targets);
1291
+ }
1292
+ for (const clipId of targets) this.removeClipGraph(draft, clipId);
1293
+ this.resolveOneVoiceoverOverlap(draft);
1294
+ });
1295
+ }
1296
+ setBgm(input) {
1297
+ return this.transact((draft) => {
1298
+ const imported = importMediaAsset(draft, input.media, this.idFactory);
1299
+ replaceRows(draft, imported.rows);
1300
+ const track = this.ensureRoleTrack(draft, input.timelineEntityId, "bgm");
1301
+ const existing = clipsOnTrack(draft, track.entityId);
1302
+ for (const clip of existing) this.removeClipGraph(draft, clip.entityId);
1303
+ const clipId = this.insertPlacedClipIntoDraft(draft, {
1304
+ clipEntityId: input.bgmClipEntityId,
1305
+ trackEntityId: track.entityId,
1306
+ contentEntityId: imported.contentEntityId,
1307
+ sourceRange: {
1308
+ start: 0,
1309
+ end: input.media.durationMs
1310
+ },
1311
+ duration: { mode: "from-source" },
1312
+ placement: {
1313
+ kind: "sequential",
1314
+ order: 0
1315
+ },
1316
+ clipPayload: { volume: requireVolume(input.volume) }
1317
+ });
1318
+ const topology = requireClipTopology(draft, clipId);
1319
+ replaceEntity(draft, topology.marker.entityId, {
1320
+ ...topology.marker,
1321
+ payload: {
1322
+ ...topology.marker.payload,
1323
+ durationPolicy: "timeline"
1324
+ }
1325
+ });
1326
+ return clipId;
1327
+ });
1328
+ }
1329
+ deleteBgm(input) {
1330
+ this.transact((draft) => {
1331
+ const track = findRoleTrack(draft, input.timelineEntityId, "bgm");
1332
+ if (track === void 0) return;
1333
+ for (const clip of clipsOnTrack(draft, track.entityId)) this.removeClipGraph(draft, clip.entityId);
1334
+ });
1335
+ }
1336
+ setCaptionVisibility(input) {
1337
+ this.transact((draft) => {
1338
+ const track = this.ensureRoleTrack(draft, input.timelineEntityId, "caption");
1339
+ replaceEntity(draft, track.entityId, {
1340
+ ...track,
1341
+ payload: {
1342
+ ...track.payload,
1343
+ hidden: input.hidden
1344
+ }
1345
+ });
1346
+ });
1347
+ }
1348
+ patchCaptionStyle(input) {
1349
+ this.transact((draft) => {
1350
+ const track = findRoleTrack(draft, input.timelineEntityId, "caption");
1351
+ if (track === void 0) return;
1352
+ const patch = cloneJsonObject(input.style, "Caption style");
1353
+ const assembled = new EntityProjectionGraph(draft);
1354
+ for (const clip of clipsOnTrack(draft, track.entityId)) {
1355
+ const topology = requireClipTopology(draft, clip.entityId);
1356
+ const caption = requireEntityKind(draft, otherEndpoint(topology.markerContentRelation, topology.marker.entityId), "caption");
1357
+ const prior = assembled.entity(caption.entityId).payload.style;
1358
+ const style = isJsonObject(prior) ? prior : {};
1359
+ for (const updated of updateEntityFields(draft, caption.entityId, { style: {
1360
+ ...style,
1361
+ ...patch
1362
+ } })) replaceEntity(draft, updated.entityId, updated);
1363
+ }
1364
+ });
1365
+ }
1366
+ /**
1367
+ * Place a Caption as a composed variant of an existing AudioScript: the
1368
+ * entity stores baseEntityIds, selection, optional style, and inherent cue-bounded
1369
+ * Sequence. This helper does not copy base text. The Clip and its display Marker describe this use;
1370
+ * moving or stretching the returned Clip later changes the Clip/Marker,
1371
+ * never the Caption entity or the AudioScript.
1372
+ */
1373
+ insertCaptionClip(input) {
1374
+ return this.transact((draft) => {
1375
+ const durationMs = finitePositive(input.durationMs, "Caption durationMs");
1376
+ const selections = captionSelections(input.selections);
1377
+ const track = this.ensureRoleTrack(draft, input.timelineEntityId, "caption");
1378
+ const content = {
1379
+ entityId: input.captionEntityId === void 0 ? this.mintEntityId(draft) : requireAvailableEntityId(draft, input.captionEntityId),
1380
+ entityKind: "caption",
1381
+ payload: {
1382
+ extent: {
1383
+ kind: "bounded",
1384
+ start: 0,
1385
+ end: durationMs
1386
+ },
1387
+ sampling: "native",
1388
+ coordinateSpace: "milliseconds",
1389
+ baseEntityIds: captionBaseIds(input.baseEntityIds),
1390
+ selections,
1391
+ ...input.style === void 0 ? {} : { style: cloneJsonObject(input.style, "Caption style") }
1392
+ }
1393
+ };
1394
+ draft.entities.push(content);
1395
+ assembleCaptionContent(draft, content.entityId);
1396
+ return this.insertPlacedClipIntoDraft(draft, {
1397
+ trackEntityId: track.entityId,
1398
+ contentEntityId: content.entityId,
1399
+ sourceRange: {
1400
+ start: 0,
1401
+ end: durationMs
1402
+ },
1403
+ duration: {
1404
+ mode: "fixed",
1405
+ value: durationMs
1406
+ },
1407
+ placement: input.placement,
1408
+ ...input.captionClipEntityId === void 0 ? {} : { clipEntityId: input.captionClipEntityId }
1409
+ });
1410
+ });
1411
+ }
1412
+ insertPlacedClipIntoDraft(draft, input) {
1413
+ const track = requireEntityKind(draft, input.trackEntityId, "track");
1414
+ requireTrackTimeline(draft, track.entityId);
1415
+ const content = requireSequenceContent(draft, input.contentEntityId);
1416
+ const clipId = input.clipEntityId === void 0 ? this.mintEntityId(draft) : requireAvailableEntityId(draft, input.clipEntityId);
1417
+ const markerId = this.mintEntityId(draft);
1418
+ const clipPayload = { ...cloneJsonObject(input.clipPayload ?? {}, "Clip payload") };
1419
+ delete clipPayload.order;
1420
+ const markerPlacement = applyPlacementPayload(clipPayload, input.placement);
1421
+ const clip = {
1422
+ entityId: clipId,
1423
+ entityKind: "clip",
1424
+ payload: clipPayload
1425
+ };
1426
+ const marker = {
1427
+ entityId: markerId,
1428
+ entityKind: "sequence-marker",
1429
+ payload: markerPayload({
1430
+ sourceRange: input.sourceRange,
1431
+ duration: input.duration,
1432
+ ...markerPlacement
1433
+ })
1434
+ };
1435
+ draft.entities.push(clip, marker);
1436
+ draft.relations.push(this.createRelation(draft, "track-clip", track.entityId, clipId), this.createRelation(draft, "clip-marker", clipId, markerId), this.createRelation(draft, "marker-content", markerId, content.entityId));
1437
+ if (input.placement.kind === "anchored") {
1438
+ const host = requireEntityKind(draft, input.placement.hostClipEntityId, "clip");
1439
+ if (host.entityId === clipId) throw new Error("A Clip cannot anchor to itself");
1440
+ draft.relations.push(this.createRelation(draft, "clip-anchor", clipId, host.entityId));
1441
+ }
1442
+ return clipId;
1443
+ }
1444
+ ensureRoleTrack(draft, timelineEntityId, role) {
1445
+ const existing = findRoleTrack(draft, timelineEntityId, role);
1446
+ if (existing !== void 0) {
1447
+ if (existing.payload.order === void 0) {
1448
+ const replacement = {
1449
+ ...existing,
1450
+ payload: {
1451
+ ...existing.payload,
1452
+ order: roleOrder[role]
1453
+ }
1454
+ };
1455
+ replaceEntity(draft, existing.entityId, replacement);
1456
+ return replacement;
1457
+ }
1458
+ return existing;
1459
+ }
1460
+ const timeline = requireEntityKind(draft, timelineEntityId, "timeline");
1461
+ const track = {
1462
+ entityId: this.mintEntityId(draft),
1463
+ entityKind: "track",
1464
+ payload: {
1465
+ role,
1466
+ order: roleOrder[role]
1467
+ }
1468
+ };
1469
+ draft.entities.push(track);
1470
+ draft.relations.push(this.createRelation(draft, "timeline-track", timeline.entityId, track.entityId));
1471
+ return track;
1472
+ }
1473
+ /** The existing pronunciation variant a Voice consumes; composition is required. */
1474
+ requireComposedPhoneticScript(draft, phoneticScriptEntityId) {
1475
+ const phonetic = requireEntityKind(draft, phoneticScriptEntityId, "phonetic-script");
1476
+ requireComposedAudioScript(draft, phonetic.entityId);
1477
+ return phonetic;
1478
+ }
1479
+ /** Preserve the factual synthesis input, regardless of persisted endpoint positions. */
1480
+ ensurePhoneticRender(draft, voiceEntityId, phoneticScriptEntityId) {
1481
+ const renders = draft.relations.filter((relation) => relation.relationKind === "phonetic-script-render" && (relation.endpoint0EntityId === voiceEntityId || relation.endpoint1EntityId === voiceEntityId));
1482
+ if (renders.length > 1) throw new Error(`Voice "${voiceEntityId}" has multiple PhoneticScript render relations`);
1483
+ if (renders[0] !== void 0) {
1484
+ if (otherEndpoint(renders[0], voiceEntityId) === phoneticScriptEntityId) return;
1485
+ throw new Error(`Voice "${voiceEntityId}" already has a different PhoneticScript synthesis input`);
1486
+ }
1487
+ draft.relations.push(this.createRelation(draft, "phonetic-script-render", voiceEntityId, phoneticScriptEntityId));
1488
+ }
1489
+ reconcileVoiceoverCaptions(draft, voiceoverClipEntityId, voiceEntityId, phoneticScriptEntityId, captions) {
1490
+ const audioScriptEntityId = requireComposedAudioScript(draft, phoneticScriptEntityId);
1491
+ const requested = new Set(captions.map((caption) => caption.captionClipEntityId));
1492
+ if (requested.size !== captions.length) throw new Error("Caption Clip ids must be unique within a voiceover take");
1493
+ const existing = directAnchorChildren(draft, voiceoverClipEntityId).filter((clipId) => clipRole(draft, clipId) === "caption");
1494
+ for (const clipId of existing) if (!requested.has(clipId)) this.removeCaptionClipGraph(draft, clipId);
1495
+ const captionTrack = captions.length === 0 ? void 0 : this.ensureRoleTrackForClip(draft, voiceoverClipEntityId, "caption");
1496
+ for (const caption of captions) {
1497
+ const startMs = finiteNonNegative(caption.startMs, "Caption startMs");
1498
+ const durationMs = finitePositive(caption.durationMs, "Caption durationMs");
1499
+ const selections = captionSelections(caption.selections);
1500
+ const baseEntityIds = captionBaseIds(caption.baseEntityIds);
1501
+ if (draft.entities.find((entity) => entity.entityId === caption.captionClipEntityId) === void 0) {
1502
+ const content = {
1503
+ entityId: this.mintEntityId(draft),
1504
+ entityKind: "caption",
1505
+ payload: {
1506
+ extent: {
1507
+ kind: "bounded",
1508
+ start: 0,
1509
+ end: durationMs
1510
+ },
1511
+ sampling: "native",
1512
+ coordinateSpace: "milliseconds",
1513
+ baseEntityIds,
1514
+ selections,
1515
+ ...caption.style === void 0 ? {} : { style: cloneJsonObject(caption.style, "Caption style") }
1516
+ }
1517
+ };
1518
+ draft.entities.push(content);
1519
+ assertCaptionScript(draft, content.entityId, audioScriptEntityId);
1520
+ draft.relations.push(this.createRelation(draft, "caption-alignment", content.entityId, voiceEntityId, { alignment: {
1521
+ start: startMs,
1522
+ end: startMs + durationMs
1523
+ } }));
1524
+ this.insertPlacedClipIntoDraft(draft, {
1525
+ clipEntityId: caption.captionClipEntityId,
1526
+ trackEntityId: captionTrack.entityId,
1527
+ contentEntityId: content.entityId,
1528
+ sourceRange: {
1529
+ start: 0,
1530
+ end: durationMs
1531
+ },
1532
+ duration: {
1533
+ mode: "fixed",
1534
+ value: durationMs
1535
+ },
1536
+ placement: {
1537
+ kind: "anchored",
1538
+ hostClipEntityId: voiceoverClipEntityId,
1539
+ anchorOffset: startMs
1540
+ }
1541
+ });
1542
+ continue;
1543
+ }
1544
+ const topology = requireClipOnRole(draft, caption.captionClipEntityId, "caption");
1545
+ const content = requireEntityKind(draft, otherEndpoint(topology.markerContentRelation, topology.marker.entityId), "caption");
1546
+ const priorStyle = isJsonObject(content.payload.style) ? content.payload.style : {};
1547
+ const style = caption.style === void 0 ? priorStyle : {
1548
+ ...priorStyle,
1549
+ ...cloneJsonObject(caption.style, "Caption style")
1550
+ };
1551
+ replaceEntity(draft, content.entityId, {
1552
+ ...content,
1553
+ payload: {
1554
+ ...content.payload,
1555
+ baseEntityIds,
1556
+ selections,
1557
+ ...Object.keys(style).length === 0 ? {} : { style }
1558
+ }
1559
+ });
1560
+ assertCaptionScript(draft, content.entityId, audioScriptEntityId);
1561
+ this.applyClipPlacement(draft, topology.clip.entityId, {
1562
+ kind: "anchored",
1563
+ hostClipEntityId: voiceoverClipEntityId,
1564
+ anchorOffset: startMs
1565
+ });
1566
+ const placed = requireClipTopology(draft, topology.clip.entityId);
1567
+ replaceEntity(draft, placed.marker.entityId, {
1568
+ ...placed.marker,
1569
+ payload: {
1570
+ ...placed.marker.payload,
1571
+ duration: {
1572
+ mode: "fixed",
1573
+ value: durationMs
1574
+ }
1575
+ }
1576
+ });
1577
+ this.replaceCaptionAlignment(draft, content.entityId, voiceEntityId, startMs, durationMs);
1578
+ }
1579
+ }
1580
+ ensureRoleTrackForClip(draft, clipEntityId, role) {
1581
+ const topology = requireClipTopology(draft, clipEntityId);
1582
+ const track = requireEntityKind(draft, otherEndpoint(topology.trackRelation, topology.clip.entityId), "track");
1583
+ const timeline = requireEntityKind(draft, otherEndpoint(requireOneRelation(draft, track.entityId, "timeline-track"), track.entityId), "timeline");
1584
+ return this.ensureRoleTrack(draft, timeline.entityId, role);
1585
+ }
1586
+ replaceCaptionAlignment(draft, captionEntityId, voiceEntityId, startMs, durationMs) {
1587
+ const removed = new Set(incidentRelations(draft, captionEntityId).filter((relation) => relation.relationKind === "caption-alignment").map((relation) => relation.relationId));
1588
+ draft.relations = draft.relations.filter((relation) => !removed.has(relation.relationId));
1589
+ draft.relations.push(this.createRelation(draft, "caption-alignment", captionEntityId, voiceEntityId, { alignment: {
1590
+ start: startMs,
1591
+ end: startMs + durationMs
1592
+ } }));
1593
+ }
1594
+ /**
1595
+ * Remove one placed Caption use. The composed AudioScript outlives the
1596
+ * caption: it may anchor further captions and remains the text owner.
1597
+ */
1598
+ removeCaptionClipGraph(draft, clipEntityId) {
1599
+ const topology = requireClipOnRole(draft, clipEntityId, "caption");
1600
+ const caption = requireEntityKind(draft, otherEndpoint(topology.markerContentRelation, topology.marker.entityId), "caption");
1601
+ const contentRelations = incidentRelations(draft, caption.entityId);
1602
+ const allowed = new Set(["caption-alignment", "marker-content"]);
1603
+ const unsupported = contentRelations.filter((relation) => !allowed.has(relation.relationKind));
1604
+ if (unsupported.length > 0) throw new Error(`Cannot delete Caption with unsupported Relation ${unsupported[0].relationId}`);
1605
+ this.removeClipGraph(draft, clipEntityId);
1606
+ if (incidentRelations(draft, caption.entityId).some((relation) => relation.relationKind === "marker-content")) return;
1607
+ const removed = new Set(incidentRelations(draft, caption.entityId).map((relation) => relation.relationId));
1608
+ draft.relations = draft.relations.filter((relation) => !removed.has(relation.relationId));
1609
+ draft.entities = draft.entities.filter((entity) => entity.entityId !== caption.entityId);
1610
+ }
1611
+ replaceAnchorHost(draft, childClipEntityId, hostClipEntityId) {
1612
+ const anchors = draft.relations.filter((relation) => relation.relationKind === "clip-anchor" && relation.endpoint0EntityId === childClipEntityId);
1613
+ if (anchors.length !== 1) throw new Error(`Clip "${childClipEntityId}" must have exactly one host`);
1614
+ this.relinkRelation(draft, anchors[0], {
1615
+ endpoint0EntityId: createEntityId(childClipEntityId),
1616
+ endpoint1EntityId: createEntityId(hostClipEntityId)
1617
+ });
1618
+ }
1619
+ /** Rebuild the legacy edit baseline from current visual order before a high-level cascade. */
1620
+ normalizeMainSequential(draft) {
1621
+ const videoTrack = resolveEntityTimelineLayout(draft).tracks.find((track) => track.role === "video_clip");
1622
+ if (videoTrack === void 0) return;
1623
+ videoTrack.clips.forEach((clip, order) => {
1624
+ this.applyClipPlacement(draft, clip.clipEntityId, {
1625
+ kind: "sequential",
1626
+ order
1627
+ });
1628
+ });
1629
+ }
1630
+ resolveOneVoiceoverOverlap(draft) {
1631
+ const layout = resolveEntityTimelineLayout(draft);
1632
+ const speechTrack = layout.tracks.find((track) => track.role === "speech");
1633
+ if (speechTrack === void 0) return;
1634
+ const ranges = speechTrack.clips.map((speech) => {
1635
+ const captions = directAnchorChildren(draft, speech.clipEntityId).filter((clipId) => clipRole(draft, clipId) === "caption").map((clipId) => layout.clips.get(clipId)).filter((value) => value !== void 0);
1636
+ return {
1637
+ speech,
1638
+ start: Math.min(speech.start, ...captions.map((caption) => caption.start)),
1639
+ end: Math.max(speech.start + speech.duration, ...captions.map((caption) => caption.start + caption.duration))
1640
+ };
1641
+ }).sort((left, right) => left.start - right.start || left.speech.clipEntityId.localeCompare(right.speech.clipEntityId));
1642
+ for (let index = 1; index < ranges.length; index += 1) {
1643
+ const prior = ranges[index - 1];
1644
+ const current = ranges[index];
1645
+ if (current.start >= prior.end) continue;
1646
+ const hostId = current.speech.anchorClipEntityId;
1647
+ if (hostId === void 0) continue;
1648
+ const videoTrack = layout.tracks.find((track) => track.role === "video_clip");
1649
+ const hostIndex = videoTrack?.clips.findIndex((clip) => clip.clipEntityId === hostId) ?? -1;
1650
+ if (videoTrack === void 0 || hostIndex < 0) continue;
1651
+ const overlapMs = Math.round(prior.end - current.start);
1652
+ for (const [visualIndex, clip] of videoTrack.clips.entries()) this.applyClipPlacement(draft, clip.clipEntityId, {
1653
+ kind: "absolute",
1654
+ targetRange: {
1655
+ start: clip.start + (visualIndex >= hostIndex ? overlapMs : 0),
1656
+ end: clip.start + clip.duration + (visualIndex >= hostIndex ? overlapMs : 0)
1657
+ }
1658
+ });
1659
+ return;
1660
+ }
1661
+ }
1662
+ applyClipPlacement(draft, clipEntityId, placement) {
1663
+ const topology = requireClipTopology(draft, clipEntityId);
1664
+ const clipPayload = { ...cloneJsonObject(topology.clip.payload, "Clip payload") };
1665
+ const markerPayloadValue = { ...cloneJsonObject(topology.marker.payload, "Sequence Marker payload") };
1666
+ delete clipPayload.order;
1667
+ delete markerPayloadValue.targetRange;
1668
+ delete markerPayloadValue.anchorOffset;
1669
+ const outgoingAnchors = draft.relations.filter((relation) => relation.relationKind === "clip-anchor" && relation.endpoint0EntityId === topology.clip.entityId);
1670
+ const removed = new Set(outgoingAnchors.map((relation) => relation.relationId));
1671
+ draft.relations = draft.relations.filter((relation) => !removed.has(relation.relationId));
1672
+ if (placement.kind === "sequential") clipPayload.order = finiteNumber(placement.order, "Clip order");
1673
+ else if (placement.kind === "absolute") markerPayloadValue.targetRange = cloneJsonValue(placement.targetRange, "targetRange");
1674
+ else {
1675
+ const host = requireEntityKind(draft, placement.hostClipEntityId, "clip");
1676
+ if (host.entityId === topology.clip.entityId) throw new Error("A Clip cannot anchor to itself");
1677
+ markerPayloadValue.anchorOffset = finiteNonNegative(placement.anchorOffset, "anchorOffset");
1678
+ draft.relations.push(this.createRelation(draft, "clip-anchor", topology.clip.entityId, host.entityId));
1679
+ }
1680
+ replaceEntity(draft, topology.clip.entityId, {
1681
+ ...topology.clip,
1682
+ payload: clipPayload
1683
+ });
1684
+ replaceEntity(draft, topology.marker.entityId, {
1685
+ ...topology.marker,
1686
+ payload: markerPayloadValue
1687
+ });
1688
+ }
1689
+ reanchorAtAbsolute(draft, childClipEntityId, absoluteStart, layout) {
1690
+ const hosts = layout.tracks.find((track) => track.role === "video_clip")?.clips.filter((clip) => clip.mode === "sequential") ?? [];
1691
+ if (hosts.length === 0) {
1692
+ const child = layout.clips.get(childClipEntityId);
1693
+ if (child === void 0) throw new Error(`Clip "${childClipEntityId}" is not placed`);
1694
+ this.applyClipPlacement(draft, childClipEntityId, {
1695
+ kind: "absolute",
1696
+ targetRange: {
1697
+ start: absoluteStart,
1698
+ end: absoluteStart + child.duration
1699
+ }
1700
+ });
1701
+ return;
1702
+ }
1703
+ const host = hosts.find((candidate) => candidate.start <= absoluteStart && absoluteStart < candidate.start + candidate.duration) ?? (absoluteStart < hosts[0].start ? hosts[0] : hosts.at(-1));
1704
+ this.applyClipPlacement(draft, childClipEntityId, {
1705
+ kind: "anchored",
1706
+ hostClipEntityId: host.clipEntityId,
1707
+ anchorOffset: Math.max(0, Math.round(absoluteStart - host.start))
1708
+ });
1709
+ }
1710
+ removeAnchoredDescendants(draft, hostClipEntityId, scheduled) {
1711
+ const children = draft.relations.filter((relation) => relation.relationKind === "clip-anchor" && relation.endpoint1EntityId === hostClipEntityId).map((relation) => String(relation.endpoint0EntityId));
1712
+ for (const child of children) {
1713
+ if (scheduled.has(child)) continue;
1714
+ const descendants = new Set(scheduled);
1715
+ descendants.add(child);
1716
+ this.removeAnchoredDescendants(draft, child, descendants);
1717
+ if (clipRole(draft, child) === "caption") this.removeCaptionClipGraph(draft, child);
1718
+ else this.removeClipGraph(draft, child);
1719
+ }
1720
+ }
1721
+ removeClipGraph(draft, clipEntityId) {
1722
+ const topology = requireClipTopology(draft, clipEntityId);
1723
+ assertOnlyStructuralIncidents(draft, topology.clip.entityId, new Set([
1724
+ "track-clip",
1725
+ "clip-marker",
1726
+ "clip-anchor"
1727
+ ]));
1728
+ assertOnlyStructuralIncidents(draft, topology.marker.entityId, new Set(["clip-marker", "marker-content"]));
1729
+ const markerIsExclusive = incidentRelations(draft, topology.marker.entityId).filter((relation) => relation.relationKind === "clip-marker").length === 1;
1730
+ const removed = new Set(incidentRelations(draft, topology.clip.entityId).map((relation) => relation.relationId));
1731
+ if (markerIsExclusive) for (const relation of incidentRelations(draft, topology.marker.entityId)) removed.add(relation.relationId);
1732
+ draft.relations = draft.relations.filter((relation) => !removed.has(relation.relationId));
1733
+ draft.entities = draft.entities.filter((entity) => entity.entityId !== topology.clip.entityId && (!markerIsExclusive || entity.entityId !== topology.marker.entityId));
1734
+ }
1735
+ transact(edit) {
1736
+ const draft = cloneRows(this.state);
1737
+ const result = edit(draft);
1738
+ validateFinalRows(draft);
1739
+ assertMediaAssetWritePolicy(this.state, draft);
1740
+ this.state = draft;
1741
+ return result;
1742
+ }
1743
+ mintEntityId(draft) {
1744
+ const entityId = createEntityId(this.idFactory("entity"));
1745
+ if (draft.entities.some((entity) => entity.entityId === entityId)) throw new Error(`Entity id "${entityId}" already exists`);
1746
+ return entityId;
1747
+ }
1748
+ createRelation(draft, relationKind, endpoint0EntityId, endpoint1EntityId, metadata = {}) {
1749
+ return {
1750
+ relationId: this.mintRelationId(draft),
1751
+ relationKind,
1752
+ endpoint0EntityId,
1753
+ endpoint1EntityId,
1754
+ metadata,
1755
+ trace: {}
1756
+ };
1757
+ }
1758
+ relinkRelation(draft, relation, endpoints) {
1759
+ const relationId = this.mintRelationId(draft);
1760
+ const index = draft.relations.findIndex((candidate) => candidate.relationId === relation.relationId);
1761
+ if (index < 0) throw new Error(`Relation id "${relation.relationId}" does not exist`);
1762
+ draft.relations[index] = {
1763
+ ...relation,
1764
+ ...endpoints,
1765
+ relationId
1766
+ };
1767
+ }
1768
+ mintRelationId(draft) {
1769
+ const relationId = createRelationId(this.idFactory("relation"));
1770
+ if (draft.relations.some((relation) => relation.relationId === relationId)) throw new Error(`Relation id "${relationId}" already exists`);
1771
+ return relationId;
1772
+ }
1773
+ };
1774
+ function validateFinalRows(rows) {
1775
+ decodeEntityRelationRows(rows, numericMarkerValidation);
1776
+ assertCanonicalEditorResources(rows);
1777
+ validateTimelineHierarchy(rows);
1778
+ }
1779
+ function validateTimelineHierarchy(rows) {
1780
+ for (const entity of rows.entities) {
1781
+ if (entity.entityKind === "track") requireTrackTimeline(rows, entity.entityId);
1782
+ if (entity.entityKind !== "clip") continue;
1783
+ const trackRelations = incidentRelations(rows, entity.entityId).filter((relation) => relation.relationKind === "track-clip");
1784
+ if (trackRelations.length !== 1) throw new Error(`Clip Entity "${entity.entityId}" must belong to exactly one Track`);
1785
+ requireEntityKind(rows, otherEndpoint(trackRelations[0], entity.entityId), "track");
1786
+ }
1787
+ }
1788
+ function requireTrackTimeline(rows, trackEntityId) {
1789
+ const timelineRelations = incidentRelations(rows, trackEntityId).filter((relation) => relation.relationKind === "timeline-track");
1790
+ if (timelineRelations.filter((relation) => {
1791
+ const otherId = otherEndpoint(relation, trackEntityId);
1792
+ return rows.entities.some((entity) => entity.entityId === otherId && entity.entityKind === "timeline");
1793
+ }).length !== 1 || timelineRelations.length !== 1) throw new Error(`Track Entity "${trackEntityId}" must belong to exactly one Timeline`);
1794
+ }
1795
+ function requireClipTopology(rows, clipEntityId) {
1796
+ const clip = requireEntityKind(rows, clipEntityId, "clip");
1797
+ const trackRelation = requireOneRelation(rows, clip.entityId, "track-clip");
1798
+ requireEntityKind(rows, otherEndpoint(trackRelation, clip.entityId), "track");
1799
+ const clipMarkerRelation = requireOneRelation(rows, clip.entityId, "clip-marker");
1800
+ const marker = requireEntityKind(rows, otherEndpoint(clipMarkerRelation, clip.entityId), "sequence-marker");
1801
+ const markerContentRelation = requireOneRelation(rows, marker.entityId, "marker-content");
1802
+ requireSequenceContent(rows, otherEndpoint(markerContentRelation, marker.entityId));
1803
+ return {
1804
+ clip,
1805
+ marker,
1806
+ trackRelation,
1807
+ clipMarkerRelation,
1808
+ markerContentRelation
1809
+ };
1810
+ }
1811
+ function requireOneRelation(rows, entityId, relationKind) {
1812
+ const matches = incidentRelations(rows, entityId).filter((relation) => relation.relationKind === relationKind);
1813
+ if (matches.length !== 1) throw new Error(`Entity "${entityId}" must have exactly one ${relationKind} Relation`);
1814
+ return matches[0];
1815
+ }
1816
+ function requireEntityKind(rows, entityIdValue, entityKind) {
1817
+ const entityId = createEntityId(entityIdValue);
1818
+ const entity = rows.entities.find((candidate) => candidate.entityId === entityId);
1819
+ if (entity == null) throw new Error(`Entity id "${entityId}" does not exist`);
1820
+ if (entity.entityKind !== entityKind) throw new Error(`Entity "${entityId}" must have kind "${entityKind}", got "${entity.entityKind}"`);
1821
+ return entity;
1822
+ }
1823
+ function requireSequenceContent(rows, entityIdValue) {
1824
+ if (/^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(entityIdValue)) throw new Error("Timeline content must reference an existing Sequence media Entity id; a URL is not allowed");
1825
+ const entityId = createEntityId(entityIdValue);
1826
+ const row = rows.entities.find((candidate) => candidate.entityId === entityId);
1827
+ if (row == null) throw new Error(`Timeline content must reference an existing Sequence media Entity; "${entityId}" was not found`);
1828
+ if (!hasSequence({
1829
+ ...row.payload,
1830
+ entityId: row.entityId,
1831
+ entityKind: row.entityKind
1832
+ })) throw new Error(`Timeline content must reference a Sequence media Entity, but "${entityId}" has kind "${row.entityKind}"`);
1833
+ return row;
1834
+ }
1835
+ function assertOnlyStructuralIncidents(rows, entityId, allowedKinds) {
1836
+ const unsupported = incidentRelations(rows, entityId).filter((relation) => !allowedKinds.has(relation.relationKind));
1837
+ if (unsupported.length === 0) return;
1838
+ throw new Error(`Cannot delete Clip graph: Entity "${entityId}" has unsupported incident Relation id(s): ${unsupported.map((relation) => relation.relationId).sort().join(", ")}`);
1839
+ }
1840
+ function incidentRelations(rows, entityId) {
1841
+ return rows.relations.filter((relation) => relation.endpoint0EntityId === entityId || relation.endpoint1EntityId === entityId);
1842
+ }
1843
+ function hasOutgoingClipAnchor(rows, clipEntityId) {
1844
+ return rows.relations.some((relation) => relation.relationKind === "clip-anchor" && relation.endpoint0EntityId === clipEntityId);
1845
+ }
1846
+ function outgoingAnchorChildren(rows, hostIds) {
1847
+ return rows.relations.filter((relation) => relation.relationKind === "clip-anchor" && hostIds.has(relation.endpoint1EntityId)).map((relation) => String(relation.endpoint0EntityId));
1848
+ }
1849
+ function applyPlacementPayload(clipPayload, placement) {
1850
+ if (placement.kind === "sequential") {
1851
+ clipPayload.order = finiteNumber(placement.order, "Clip order");
1852
+ return {};
1853
+ }
1854
+ if (placement.kind === "absolute") return { targetRange: cloneJsonValue(placement.targetRange, "targetRange") };
1855
+ return { anchorOffset: finiteNonNegative(placement.anchorOffset, "anchorOffset") };
1856
+ }
1857
+ function requireAvailableEntityId(rows, value) {
1858
+ const entityId = createEntityId(value);
1859
+ if (rows.entities.some((entity) => entity.entityId === entityId)) throw new Error(`Entity id "${entityId}" already exists`);
1860
+ return entityId;
1861
+ }
1862
+ function setClipOrder(rows, clipEntityId, order) {
1863
+ const clip = requireEntityKind(rows, clipEntityId, "clip");
1864
+ replaceEntity(rows, clip.entityId, {
1865
+ ...clip,
1866
+ payload: {
1867
+ ...clip.payload,
1868
+ order
1869
+ }
1870
+ });
1871
+ }
1872
+ function normalizeSequentialOrders(rows) {
1873
+ for (const track of rows.entities.filter((entity) => entity.entityKind === "track")) rows.relations.filter((relation) => relation.relationKind === "track-clip" && relation.endpoint0EntityId === track.entityId).map((relation) => rows.entities.find((entity) => entity.entityId === relation.endpoint1EntityId)).filter((entity) => entity?.entityKind === "clip" && typeof entity.payload.order === "number").sort((left, right) => Number(left.payload.order) - Number(right.payload.order)).forEach((clip, order) => setClipOrder(rows, clip.entityId, order));
1874
+ }
1875
+ function findRoleTrack(rows, timelineEntityId, role) {
1876
+ const timeline = requireEntityKind(rows, timelineEntityId, "timeline");
1877
+ const tracks = incidentRelations(rows, timeline.entityId).filter((relation) => relation.relationKind === "timeline-track").map((relation) => requireEntityKind(rows, otherEndpoint(relation, timeline.entityId), "track")).filter((track) => track.payload.role === role);
1878
+ if (tracks.length > 1) throw new Error(`Timeline "${timelineEntityId}" has multiple ${role} Tracks`);
1879
+ return tracks[0];
1880
+ }
1881
+ function clipsOnTrack(rows, trackEntityId) {
1882
+ return incidentRelations(rows, trackEntityId).filter((relation) => relation.relationKind === "track-clip").map((relation) => requireEntityKind(rows, otherEndpoint(relation, trackEntityId), "clip"));
1883
+ }
1884
+ function clipRole(rows, clipEntityId) {
1885
+ const topology = requireClipTopology(rows, clipEntityId);
1886
+ return requireEntityKind(rows, otherEndpoint(topology.trackRelation, topology.clip.entityId), "track").payload.role;
1887
+ }
1888
+ function directAnchorChildren(rows, hostClipEntityId) {
1889
+ return rows.relations.filter((relation) => relation.relationKind === "clip-anchor" && relation.endpoint1EntityId === hostClipEntityId).map((relation) => String(relation.endpoint0EntityId));
1890
+ }
1891
+ function requireSupportedRole(rows, topology) {
1892
+ const role = requireEntityKind(rows, otherEndpoint(topology.trackRelation, topology.clip.entityId), "track").payload.role;
1893
+ if (role !== "video_clip" && role !== "speech" && role !== "caption" && role !== "bgm") throw new Error(`Clip "${topology.clip.entityId}" is not on a supported timeline Track`);
1894
+ return role;
1895
+ }
1896
+ function requireClipOnRole(rows, clipEntityId, role) {
1897
+ const topology = requireClipTopology(rows, clipEntityId);
1898
+ if (requireEntityKind(rows, otherEndpoint(topology.trackRelation, topology.clip.entityId), "track").payload.role !== role) throw new Error(`Clip "${clipEntityId}" must belong to the ${role} Track`);
1899
+ return topology;
1900
+ }
1901
+ function finiteNumber(value, label) {
1902
+ if (!Number.isFinite(value)) throw new Error(`${label} must be finite`);
1903
+ return value;
1904
+ }
1905
+ function finitePositive(value, label) {
1906
+ const result = finiteNumber(value, label);
1907
+ if (result <= 0) throw new Error(`${label} must be positive`);
1908
+ return result;
1909
+ }
1910
+ function requireVolume(value) {
1911
+ const volume = finiteNumber(value, "Clip volume");
1912
+ if (volume < -60 || volume > 20) throw new Error("Clip volume must be between -60 and 20 dB");
1913
+ return volume;
1914
+ }
1915
+ function requirePositiveRange(value, label) {
1916
+ if (!isJsonObject(value)) throw new Error(`${label} must be an object`);
1917
+ const start = finiteNonNegative(value.start, `${label}.start`);
1918
+ const end = finitePositive(value.end, `${label}.end`);
1919
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || end <= start) throw new Error(`${label} must be a positive whole-millisecond range`);
1920
+ return {
1921
+ start,
1922
+ end
1923
+ };
1924
+ }
1925
+ function markerDuration(payload, sourceRange) {
1926
+ const duration = payload.duration;
1927
+ if (!isJsonObject(duration)) throw new Error("Sequence Marker duration must be an object");
1928
+ if (duration.mode === "from-source") return sourceRange.end - sourceRange.start;
1929
+ if (duration.mode !== "fixed") throw new Error("Sequence Marker duration mode is unsupported");
1930
+ return finitePositive(duration.value, "Sequence Marker fixed duration");
1931
+ }
1932
+ function linearRate(value) {
1933
+ if (value === void 0) return 1;
1934
+ if (!isJsonObject(value) || value.kind !== "linear") throw new Error("Only linear Clip time remapping is supported");
1935
+ return finitePositive(value.rate, "linear speed rate");
1936
+ }
1937
+ function resizeAbsoluteTarget(payload, duration) {
1938
+ if (payload.targetRange === void 0) return;
1939
+ const target = requirePositiveRange(payload.targetRange, "targetRange");
1940
+ payload.targetRange = {
1941
+ start: target.start,
1942
+ end: target.start + duration
1943
+ };
1944
+ }
1945
+ function replaceRows(rows, replacement) {
1946
+ rows.entities = structuredClone([...replacement.entities]);
1947
+ rows.relations = structuredClone([...replacement.relations]);
1948
+ }
1949
+ function finiteNonNegative(value, label) {
1950
+ const result = finiteNumber(value, label);
1951
+ if (result < 0) throw new Error(`${label} must be non-negative`);
1952
+ return result;
1953
+ }
1954
+ function nextSequentialOrder(rows, trackEntityId) {
1955
+ const orders = rows.relations.filter((relation) => relation.relationKind === "track-clip" && relation.endpoint0EntityId === trackEntityId).map((relation) => rows.entities.find((entity) => entity.entityId === relation.endpoint1EntityId)?.payload.order).filter((order) => typeof order === "number" && Number.isFinite(order));
1956
+ return orders.length === 0 ? 0 : Math.max(...orders) + 1;
1957
+ }
1958
+ function otherEndpoint(relation, entityId) {
1959
+ if (relation.endpoint0EntityId === entityId) return relation.endpoint1EntityId;
1960
+ if (relation.endpoint1EntityId === entityId) return relation.endpoint0EntityId;
1961
+ throw new Error(`Relation "${relation.relationId}" is not incident to Entity "${entityId}"`);
1962
+ }
1963
+ function replaceEntity(rows, entityId, replacement) {
1964
+ const index = rows.entities.findIndex((entity) => entity.entityId === entityId);
1965
+ if (index < 0) throw new Error(`Entity id "${entityId}" does not exist`);
1966
+ rows.entities[index] = replacement;
1967
+ }
1968
+ function markerPayload(value) {
1969
+ return cloneJsonObject(value, "Sequence Marker payload");
1970
+ }
1971
+ function cloneJsonObject(value, label) {
1972
+ const cloned = structuredClone(value);
1973
+ if (!isJsonObject(cloned)) throw new Error(`${label} must contain only JSON values`);
1974
+ return cloned;
1975
+ }
1976
+ function cloneJsonValue(value, label) {
1977
+ return cloneJsonObject({ value }, label).value;
1978
+ }
1979
+ function cloneRows(rows) {
1980
+ return {
1981
+ entities: rows.entities.map((entity) => structuredClone(entity)),
1982
+ relations: rows.relations.map((relation) => structuredClone(relation))
1983
+ };
1984
+ }
1985
+ const numericMarkerValidation = { compareMarkerPoints: (_marker, _range, left, right) => {
1986
+ if (typeof left !== "number" || !Number.isFinite(left) || typeof right !== "number" || !Number.isFinite(right)) throw new Error("Sequence Marker points must use finite numeric coordinates");
1987
+ return left - right;
1988
+ } };
1989
+ //#endregion
1990
+ //#region src/entity-editor/legacy-entity-migration.ts
1991
+ /** One-time import only. Ordinary editor operations must never reverse-diff a legacy document. */
1992
+ function migrateLegacyTimelineToEntities(legacy, assetFacts, initial = {
1993
+ entities: [],
1994
+ relations: []
1995
+ }, idFactory = (prefix) => `${prefix}_${globalThis.crypto.randomUUID()}`) {
1996
+ assertSupportedLegacy(legacy);
1997
+ if (initial.entities.some((row) => row.entityKind === "timeline")) fail("Timeline already exists; migration is not an editing operation");
1998
+ if (legacy.meta.schema_version === "video-document/entity-projection-v1") fail("An entity projection cannot be migrated as legacy state");
1999
+ const normalizedMainRanges = overlapNormalizedMainRanges(legacy);
2000
+ let entities = structuredClone([...initial.entities]);
2001
+ let relations = structuredClone([...initial.relations]);
2002
+ const documentAudioScriptEntityId = ensureDocumentAudioScript(entities, idFactory);
2003
+ const addEntity = (kind, payload, existingId) => {
2004
+ const entityId = createEntityId(existingId ?? idFactory("entity"));
2005
+ if (entities.some((row) => row.entityId === entityId)) fail(`Migration entity identity collision: ${entityId}`);
2006
+ entities.push({
2007
+ entityId,
2008
+ entityKind: kind,
2009
+ payload
2010
+ });
2011
+ return entityId;
2012
+ };
2013
+ const link = (kind, from, to, metadata = {}) => {
2014
+ const relationId = createRelationId(idFactory("relation"));
2015
+ if (relations.some((row) => row.relationId === relationId)) fail(`Migration relation identity collision: ${relationId}`);
2016
+ relations.push({
2017
+ relationId,
2018
+ relationKind: kind,
2019
+ endpoint0EntityId: createEntityId(from),
2020
+ endpoint1EntityId: createEntityId(to),
2021
+ metadata,
2022
+ trace: {}
2023
+ });
2024
+ };
2025
+ const facts = /* @__PURE__ */ new Map();
2026
+ for (const fact of assetFacts) {
2027
+ if (facts.has(fact.assetId)) fail(`Duplicate asset facts for ${fact.assetId}`);
2028
+ facts.set(fact.assetId, fact);
2029
+ }
2030
+ const contentByPartId = /* @__PURE__ */ new Map();
2031
+ for (const track of legacy.tracks ?? []) for (const item of track.items ?? []) {
2032
+ const part = requirePart(legacy, item.part_id);
2033
+ if (part.video_clip !== void 0) {
2034
+ const assetId = part.video_clip.origin_media_id;
2035
+ const fact = facts.get(assetId);
2036
+ if (fact === void 0) fail(`Missing factual media metadata for ${assetId}`);
2037
+ if (fact.kind !== "image" && fact.kind !== "video") fail(`Legacy video Clip ${item.part_id} requires an image or video fact`);
2038
+ const imported = importMediaAsset({
2039
+ entities,
2040
+ relations
2041
+ }, fact, idFactory);
2042
+ entities = [...imported.rows.entities];
2043
+ relations = [...imported.rows.relations];
2044
+ contentByPartId.set(item.part_id, imported.contentEntityId);
2045
+ } else if (part.speech !== void 0) {
2046
+ const speech = part.speech;
2047
+ const imported = importMediaAsset({
2048
+ entities,
2049
+ relations
2050
+ }, {
2051
+ assetId: speech.origin_speech_id,
2052
+ kind: "voice",
2053
+ durationMs: speech.media_duration_ms,
2054
+ storageKey: speech.audio_storage_key,
2055
+ voice: {
2056
+ system: "voice-library",
2057
+ key: speech.voice.id,
2058
+ ...speech.voice.name === void 0 ? {} : { name: speech.voice.name }
2059
+ }
2060
+ }, idFactory);
2061
+ entities = [...imported.rows.entities];
2062
+ relations = [...imported.rows.relations];
2063
+ contentByPartId.set(item.part_id, imported.contentEntityId);
2064
+ const phonemeScript = speech.phoneme_script;
2065
+ ensureSpeechPhoneticChain(imported.contentEntityId, speech.audio_script, typeof phonemeScript === "string" ? phonemeScript : void 0, entities, relations, addEntity, link, documentAudioScriptEntityId);
2066
+ } else if (part.bgm !== void 0) {
2067
+ const bgm = part.bgm;
2068
+ const fact = facts.get(bgm.origin_media_id);
2069
+ if (fact === void 0) fail(`Missing factual media metadata for ${bgm.origin_media_id}`);
2070
+ if (fact.kind !== "audio") fail(`Legacy BGM ${item.part_id} requires an audio fact`);
2071
+ if (fact.storageKey !== bgm.audio_storage_key) fail(`Factual storage key conflicts with legacy BGM ${item.part_id}`);
2072
+ const imported = importMediaAsset({
2073
+ entities,
2074
+ relations
2075
+ }, fact, idFactory);
2076
+ entities = [...imported.rows.entities];
2077
+ relations = [...imported.rows.relations];
2078
+ contentByPartId.set(item.part_id, imported.contentEntityId);
2079
+ }
2080
+ }
2081
+ const timeline = addEntity("timeline", legacy.timeline?.unit_time_ms === void 0 ? {} : { unit_time_ms: legacy.timeline.unit_time_ms });
2082
+ const trackIds = /* @__PURE__ */ new Map();
2083
+ for (const [order, oldTrack] of (legacy.tracks ?? []).entries()) {
2084
+ const track = addEntity("track", {
2085
+ role: oldTrack.parts_kind,
2086
+ order,
2087
+ ...oldTrack.is_hidden === void 0 ? {} : { hidden: oldTrack.is_hidden }
2088
+ }, oldTrack.id);
2089
+ trackIds.set(oldTrack, track);
2090
+ link("timeline-track", timeline, track);
2091
+ }
2092
+ for (const oldTrack of legacy.tracks ?? []) {
2093
+ const track = trackIds.get(oldTrack);
2094
+ for (const [order, item] of (oldTrack.items ?? []).entries()) {
2095
+ const part = requirePart(legacy, item.part_id);
2096
+ const role = oldTrack.parts_kind;
2097
+ const volume = part.video_clip?.volume ?? part.speech?.volume ?? part.bgm?.volume;
2098
+ const clip = addEntity("clip", {
2099
+ ...volume === void 0 ? {} : { volume },
2100
+ ...item.time_position.mode === "sequential" && !(role === "video_clip" && normalizedMainRanges !== void 0) || role === "bgm" ? { order: role === "bgm" ? 0 : order } : {}
2101
+ }, item.part_id);
2102
+ let content = contentByPartId.get(item.part_id);
2103
+ let duration;
2104
+ let markerPayload;
2105
+ if (part.video_clip !== void 0) {
2106
+ const video = part.video_clip;
2107
+ duration = effectiveVideoClipDurationMs(video);
2108
+ const fact = facts.get(video.origin_media_id);
2109
+ const rate = speedOf(video.speed_shift);
2110
+ markerPayload = {
2111
+ sourceRange: {
2112
+ start: video.play_in,
2113
+ end: video.play_out
2114
+ },
2115
+ duration: {
2116
+ mode: "fixed",
2117
+ value: duration
2118
+ },
2119
+ ...(fact.kind === "image" || fact.kind === "video") && video.speed_shift !== void 0 ? { timeRemapping: {
2120
+ kind: "linear",
2121
+ mode: video.speed_shift?.mode ?? "constant",
2122
+ rate
2123
+ } } : {}
2124
+ };
2125
+ } else if (part.speech !== void 0) {
2126
+ duration = part.speech.media_duration_ms;
2127
+ markerPayload = {
2128
+ sourceRange: {
2129
+ start: 0,
2130
+ end: duration
2131
+ },
2132
+ duration: {
2133
+ mode: "fixed",
2134
+ value: duration
2135
+ }
2136
+ };
2137
+ } else if (part.caption !== void 0) {
2138
+ const caption = part.caption;
2139
+ duration = caption.initial_duration_ms;
2140
+ const voice = contentByPartId.get(caption.speech_part_id);
2141
+ const render = relations.find((relation) => relation.relationKind === "phonetic-script-render" && relation.endpoint0EntityId === voice);
2142
+ const phonetic = entities.find((entity) => entity.entityId === render?.endpoint1EntityId);
2143
+ const script = phonetic === void 0 ? void 0 : composedAudioScript(phonetic, entities);
2144
+ if (script === void 0) fail("Legacy Caption has no composed AudioScript");
2145
+ const sourceText = scriptText(script);
2146
+ const captionText = caption.text;
2147
+ const offset = sourceText.indexOf(captionText);
2148
+ if (!captionText.trim() || offset < 0 || sourceText.indexOf(captionText, offset + 1) >= 0) fail("Legacy Caption needs explicit unambiguous AudioScript selections before cutover");
2149
+ const selections = [{
2150
+ segmentId: "segment-0",
2151
+ ...sourceText === captionText ? {} : { textRange: {
2152
+ start: Array.from(sourceText.slice(0, offset)).length,
2153
+ end: Array.from(sourceText.slice(0, offset + captionText.length)).length
2154
+ } }
2155
+ }];
2156
+ content = addEntity("caption", {
2157
+ extent: {
2158
+ kind: "bounded",
2159
+ start: 0,
2160
+ end: duration
2161
+ },
2162
+ sampling: "native",
2163
+ coordinateSpace: "milliseconds",
2164
+ baseEntityIds: [script.entityId],
2165
+ selections,
2166
+ ...caption.style === void 0 ? {} : { style: toEntityCaptionStyle(caption.style) }
2167
+ });
2168
+ link("caption-alignment", content, voice, { alignment: {
2169
+ start: caption.start_ms,
2170
+ end: caption.start_ms + duration
2171
+ } });
2172
+ markerPayload = {
2173
+ sourceRange: {
2174
+ start: 0,
2175
+ end: duration
2176
+ },
2177
+ duration: {
2178
+ mode: "fixed",
2179
+ value: duration
2180
+ }
2181
+ };
2182
+ } else {
2183
+ const bgm = part.bgm;
2184
+ const fact = facts.get(bgm.origin_media_id);
2185
+ if (fact.kind !== "audio") fail(`Legacy BGM ${item.part_id} requires an audio fact`);
2186
+ duration = fact.durationMs;
2187
+ markerPayload = {
2188
+ sourceRange: {
2189
+ start: 0,
2190
+ end: duration
2191
+ },
2192
+ duration: { mode: "from-source" },
2193
+ durationPolicy: "timeline"
2194
+ };
2195
+ }
2196
+ if (content === void 0) fail(`Migration could not resolve content for ${item.part_id}`);
2197
+ const normalizedMainRange = role === "video_clip" ? normalizedMainRanges?.get(item.part_id) : void 0;
2198
+ if (normalizedMainRange !== void 0) markerPayload = {
2199
+ ...markerPayload,
2200
+ targetRange: normalizedMainRange
2201
+ };
2202
+ else if (item.time_position.mode === "absolute" && role !== "bgm") markerPayload = {
2203
+ ...markerPayload,
2204
+ targetRange: {
2205
+ start: item.time_position.offsetMs,
2206
+ end: item.time_position.offsetMs + duration
2207
+ }
2208
+ };
2209
+ else if (item.time_position.mode === "anchored") markerPayload = {
2210
+ ...markerPayload,
2211
+ anchorOffset: item.time_position.offsetMs
2212
+ };
2213
+ const marker = addEntity("sequence-marker", markerPayload);
2214
+ link("track-clip", track, clip);
2215
+ link("clip-marker", clip, marker);
2216
+ link("marker-content", marker, content);
2217
+ if (item.time_position.mode === "anchored") link("clip-anchor", clip, item.time_position.anchorPartId);
2218
+ }
2219
+ }
2220
+ const rows = {
2221
+ entities,
2222
+ relations
2223
+ };
2224
+ assertEntityProjectionPreservesLegacy(legacy, projectEntityTimeline(rows, legacy.meta), rows);
2225
+ return rows;
2226
+ }
2227
+ /** Server gate: a cutover may change representation, never the existing render facts. */
2228
+ function assertEntityProjectionPreservesLegacy(legacy, projection, rows) {
2229
+ assertSupportedLegacy(legacy);
2230
+ if (projection.meta.schema_version !== "video-document/entity-projection-v1") fail("Expected an entity projection for migration");
2231
+ const normalizedMainRanges = overlapNormalizedMainRanges(legacy);
2232
+ const compatibilityFacts = (document) => {
2233
+ const { version: _version, ...view } = fromVideoDocument(document);
2234
+ for (const part of Object.values(view.part_library ?? {})) {
2235
+ const speech = part.speech;
2236
+ if (speech?.phoneme_script === null) delete speech.phoneme_script;
2237
+ }
2238
+ const { schema_version: _schemaVersion, version: _metaVersion, ...meta } = document.meta;
2239
+ return {
2240
+ meta,
2241
+ view
2242
+ };
2243
+ };
2244
+ if (canonical(compatibilityFacts(legacy)) !== canonical(compatibilityFacts(projection))) fail("Entity migration must preserve all existing timeline facts; edit after cutover");
2245
+ const trackOrders = [];
2246
+ for (const oldTrack of legacy.tracks ?? []) {
2247
+ const candidates = rows.entities.filter((row) => row.entityKind === "track" && (oldTrack.id === void 0 ? row.payload.role === oldTrack.parts_kind : row.entityId === oldTrack.id));
2248
+ if (candidates.length !== 1) fail("Migration must preserve every Track identity");
2249
+ const track = candidates[0];
2250
+ if (track.payload.role !== oldTrack.parts_kind || (track.payload.hidden ?? false) !== (oldTrack.is_hidden ?? false)) fail("Migration must preserve Track role and visibility");
2251
+ if (typeof track.payload.order !== "number" || !Number.isFinite(track.payload.order)) fail("Migration must preserve Track order");
2252
+ trackOrders.push(track.payload.order);
2253
+ const sequentialOrders = [];
2254
+ for (const item of oldTrack.items ?? []) {
2255
+ const clip = rows.entities.find((row) => row.entityId === item.part_id && row.entityKind === "clip");
2256
+ const binding = rows.relations.filter((row) => row.relationKind === "clip-marker" && row.endpoint0EntityId === item.part_id && rows.entities.some((entity) => entity.entityId === row.endpoint1EntityId && entity.entityKind === "sequence-marker"));
2257
+ const marker = rows.entities.find((row) => row.entityId === binding[0]?.endpoint1EntityId && row.entityKind === "sequence-marker");
2258
+ if (clip === void 0 || binding.length !== 1 || marker === void 0) fail("Migration must preserve Clip/Marker placement identity");
2259
+ const anchors = rows.relations.filter((row) => row.relationKind === "clip-anchor" && row.endpoint0EntityId === clip.entityId);
2260
+ const normalizedMainRange = oldTrack.parts_kind === "video_clip" ? normalizedMainRanges?.get(item.part_id) : void 0;
2261
+ if (normalizedMainRange !== void 0) {
2262
+ if (clip.payload.order !== void 0 || !isExactRange(marker.payload.targetRange, normalizedMainRange) || marker.payload.anchorOffset !== void 0 || anchors.length !== 0) fail("Migration must preserve the legacy overlap-normalized main Track");
2263
+ } else if (oldTrack.parts_kind === "bgm") {
2264
+ if (clip.payload.order !== 0 || marker.payload.targetRange !== void 0 || marker.payload.anchorOffset !== void 0 || marker.payload.durationPolicy !== "timeline" || anchors.length !== 0) fail("Migration must preserve timeline-filling BGM semantics");
2265
+ } else if (item.time_position.mode === "sequential") {
2266
+ if (marker.payload.targetRange !== void 0 || marker.payload.anchorOffset !== void 0 || typeof clip.payload.order !== "number" || !Number.isFinite(clip.payload.order) || anchors.length !== 0) fail("Migration must preserve sequential placement semantics");
2267
+ sequentialOrders.push(clip.payload.order);
2268
+ } else if (item.time_position.mode === "absolute") {
2269
+ const target = marker.payload.targetRange;
2270
+ if (clip.payload.order !== void 0 || !isRangeStartingAt(target, item.time_position.offsetMs) || marker.payload.anchorOffset !== void 0 || anchors.length !== 0) fail("Migration must preserve absolute placement semantics");
2271
+ } else if (clip.payload.order !== void 0 || marker.payload.targetRange !== void 0 || marker.payload.anchorOffset !== item.time_position.offsetMs || anchors.length !== 1 || anchors[0].endpoint1EntityId !== item.time_position.anchorPartId) fail("Migration must preserve anchored placement semantics");
2272
+ }
2273
+ if (sequentialOrders.some((order, index) => index > 0 && order <= sequentialOrders[index - 1])) fail("Migration must preserve sequential Clip order");
2274
+ }
2275
+ if (trackOrders.some((order, index) => index > 0 && order <= trackOrders[index - 1])) fail("Migration must preserve Track stacking order");
2276
+ }
2277
+ function assertSupportedLegacy(document) {
2278
+ assertValidVideoDocument(document);
2279
+ const tracks = document.tracks ?? [];
2280
+ assertKnownFields(document.timeline ?? {}, ["unit_time_ms"], "Timeline");
2281
+ if (document.timeline?.unit_time_ms !== void 0 && (typeof document.timeline.unit_time_ms !== "number" || !Number.isFinite(document.timeline.unit_time_ms) || document.timeline.unit_time_ms <= 0)) fail("Migration requires a positive finite unit_time_ms");
2282
+ const seenRoles = /* @__PURE__ */ new Set();
2283
+ const placed = /* @__PURE__ */ new Map();
2284
+ for (const track of tracks) {
2285
+ const role = track.parts_kind;
2286
+ if (role === void 0 || ![
2287
+ "video_clip",
2288
+ "speech",
2289
+ "caption",
2290
+ "bgm"
2291
+ ].includes(role)) fail("Every legacy Track requires a supported role");
2292
+ if (seenRoles.has(role)) fail(`The compatibility editor supports only one ${role} Track`);
2293
+ seenRoles.add(role);
2294
+ if (track.id !== void 0 && (track.id.trim() === "" || track.id.trim() !== track.id)) fail("Migration requires trimmed Track identities");
2295
+ for (const item of track.items ?? []) {
2296
+ if (item.part_id.trim() === "" || item.part_id.trim() !== item.part_id) fail("Migration requires trimmed Clip identities");
2297
+ if (placed.has(item.part_id)) fail(`Legacy part ${item.part_id} is placed more than once`);
2298
+ placed.set(item.part_id, {
2299
+ track,
2300
+ item
2301
+ });
2302
+ assertKnownFields(item.time_position, item.time_position.mode === "sequential" ? ["mode"] : [
2303
+ "mode",
2304
+ "anchorPartId",
2305
+ "offsetMs"
2306
+ ], "placement");
2307
+ if (item.time_position.mode === "absolute") requireMilliseconds(item.time_position.offsetMs, "absolute offset");
2308
+ if (item.time_position.mode === "anchored") {
2309
+ if (item.time_position.anchorPartId.trim() === "" || item.time_position.anchorPartId.trim() !== item.time_position.anchorPartId) fail("Migration requires a trimmed anchor identity");
2310
+ requireMilliseconds(item.time_position.offsetMs, "anchor offset");
2311
+ }
2312
+ if (item.fallback_abs_ms !== void 0) requireMilliseconds(item.fallback_abs_ms, "anchor fallback");
2313
+ assertKnownFields(item, [
2314
+ "part_id",
2315
+ "time_position",
2316
+ "fallback_abs_ms"
2317
+ ], "TrackItem");
2318
+ }
2319
+ assertKnownFields(track, [
2320
+ "id",
2321
+ "parts_kind",
2322
+ "is_hidden",
2323
+ "items"
2324
+ ], "Track");
2325
+ }
2326
+ for (const [id, part] of Object.entries(document.part_library ?? {})) {
2327
+ const placement = placed.get(id);
2328
+ if (placement === void 0) fail(`Cannot discard unplaced legacy part ${id}`);
2329
+ assertPartSupported(id, part, placement.track.parts_kind);
2330
+ }
2331
+ for (const id of placed.keys()) if (document.part_library?.[id] === void 0) fail(`Placed Clip ${id} has no part payload`);
2332
+ assertLegacyRelations(document, placed);
2333
+ }
2334
+ function assertPartSupported(id, part, role) {
2335
+ assertKnownFields(part, [
2336
+ "video_clip",
2337
+ "speech",
2338
+ "caption",
2339
+ "bgm"
2340
+ ], "Part");
2341
+ const present = [
2342
+ "video_clip",
2343
+ "speech",
2344
+ "caption",
2345
+ "bgm"
2346
+ ].filter((kind) => part[kind] !== void 0);
2347
+ if (present.length !== 1 || present[0] !== role) fail(`Legacy part ${id} must match its ${role} Track`);
2348
+ if (part.video_clip !== void 0) {
2349
+ const clip = part.video_clip;
2350
+ if (clip.id !== id || clip.kind !== "video_clip" || !trimmed(clip.origin_media_id) || clip.play_in === void 0 || clip.play_out === void 0) fail("Migration requires complete Clip identity, media and trim facts");
2351
+ requireMilliseconds(clip.play_in, "Clip play_in");
2352
+ requireMilliseconds(clip.play_out, "Clip play_out");
2353
+ if (clip.play_out <= clip.play_in) fail("Migration requires a non-empty Clip trim window");
2354
+ requireFinite(clip.volume, "Clip volume");
2355
+ const speed = clip.speed_shift;
2356
+ if (speed !== void 0 && (speed.category !== "linear" || speed.config?.linear === void 0 || speed.mode !== void 0 && typeof speed.mode !== "string")) fail("Nonlinear speed requires an entity remapping adapter");
2357
+ if (speed !== void 0) {
2358
+ const rate = speed.config?.linear?.speed;
2359
+ if (typeof rate !== "number" || !Number.isFinite(rate) || rate <= 0) fail("Migration requires a positive finite speed");
2360
+ assertKnownFields(speed, [
2361
+ "category",
2362
+ "mode",
2363
+ "config"
2364
+ ], "speed_shift");
2365
+ assertKnownFields(speed.config, ["linear"], "speed config");
2366
+ assertKnownFields(speed.config.linear, ["speed"], "linear speed");
2367
+ }
2368
+ assertKnownFields(clip, [
2369
+ "id",
2370
+ "kind",
2371
+ "origin_media_id",
2372
+ "play_in",
2373
+ "play_out",
2374
+ "volume",
2375
+ "speed_shift"
2376
+ ], "Clip");
2377
+ } else if (part.speech !== void 0) {
2378
+ const speech = part.speech;
2379
+ const phonemeScript = speech.phoneme_script;
2380
+ if (speech.id !== id || speech.kind !== "speech" || !trimmed(speech.origin_speech_id) || !trimmed(speech.audio_storage_key) || typeof speech.audio_script !== "string") fail("Migration requires complete Speech identity and physical take facts");
2381
+ requirePositiveMilliseconds(speech.media_duration_ms, "Speech duration");
2382
+ requireFinite(speech.volume, "Speech volume");
2383
+ if (!trimmed(speech.voice?.id)) fail("Migration requires an explicit voice-library identity");
2384
+ if (speech.voice?.name !== void 0 && typeof speech.voice.name !== "string") fail("Migration requires a string voice name when present");
2385
+ if (!Array.isArray(speech.caption_ids) || speech.caption_ids.some((captionId) => !trimmed(captionId))) fail("Migration requires explicit Speech caption identities");
2386
+ if (new Set(speech.caption_ids).size !== speech.caption_ids.length) fail("Migration requires unique Speech caption identities");
2387
+ if (phonemeScript !== void 0 && phonemeScript !== null && typeof phonemeScript !== "string") fail("Migration requires a string phoneme_script when present");
2388
+ assertKnownFields(speech.voice, ["id", "name"], "voice");
2389
+ assertKnownFields(speech, [
2390
+ "id",
2391
+ "kind",
2392
+ "media_duration_ms",
2393
+ "audio_script",
2394
+ "volume",
2395
+ "audio_storage_key",
2396
+ "origin_speech_id",
2397
+ "voice",
2398
+ "caption_ids",
2399
+ "phoneme_script"
2400
+ ], "Speech");
2401
+ } else if (part.caption !== void 0) {
2402
+ const caption = part.caption;
2403
+ if (caption.id !== id || caption.kind !== "caption" || !trimmed(caption.speech_part_id) || typeof caption.text !== "string") fail("Migration requires complete Caption identity, Speech provenance and text");
2404
+ requireMilliseconds(caption.start_ms, "Caption source offset");
2405
+ requirePositiveMilliseconds(caption.initial_duration_ms, "Caption duration");
2406
+ if (caption.style !== void 0) assertCaptionStyle(caption.style);
2407
+ assertKnownFields(caption, [
2408
+ "id",
2409
+ "kind",
2410
+ "initial_duration_ms",
2411
+ "speech_part_id",
2412
+ "text",
2413
+ "start_ms",
2414
+ "style"
2415
+ ], "Caption");
2416
+ } else if (part.bgm !== void 0) {
2417
+ const bgm = part.bgm;
2418
+ if (bgm.id !== id || bgm.kind !== "bgm" || !trimmed(bgm.origin_media_id) || !trimmed(bgm.audio_storage_key)) fail("Migration requires complete BGM identity and physical media facts");
2419
+ requireFinite(bgm.volume, "BGM volume");
2420
+ assertKnownFields(bgm, [
2421
+ "id",
2422
+ "kind",
2423
+ "audio_storage_key",
2424
+ "volume",
2425
+ "origin_media_id"
2426
+ ], "BGM");
2427
+ }
2428
+ }
2429
+ function assertLegacyRelations(document, placed) {
2430
+ const captionIdsBySpeech = /* @__PURE__ */ new Map();
2431
+ for (const track of document.tracks ?? []) {
2432
+ if (track.parts_kind === "bgm" && (track.items?.length ?? 0) > 1) fail("The compatibility editor supports only one BGM Clip");
2433
+ for (const item of track.items ?? []) {
2434
+ const part = requirePart(document, item.part_id);
2435
+ const position = item.time_position;
2436
+ if (track.parts_kind === "video_clip" && position.mode === "anchored") fail("Anchored video Clips require an overlay adapter");
2437
+ if (track.parts_kind === "bgm") {
2438
+ if (position.mode !== "absolute" || position.offsetMs !== 0) fail("Legacy BGM must start at the Timeline origin");
2439
+ } else if (position.mode === "anchored") {
2440
+ const host = placed.get(position.anchorPartId);
2441
+ if (host === void 0) fail(`Legacy anchor ${position.anchorPartId} is not placed`);
2442
+ if (track.parts_kind === "speech" && host.track.parts_kind !== "video_clip") fail("Speech may only anchor to a video Clip");
2443
+ if (track.parts_kind === "caption") {
2444
+ if (host.track.parts_kind !== "speech") fail("Caption may only anchor to a Speech Clip");
2445
+ const caption = part.caption;
2446
+ if (position.anchorPartId !== caption.speech_part_id || position.offsetMs !== caption.start_ms) fail("Caption placement must agree with its Speech provenance and source offset");
2447
+ }
2448
+ } else if (track.parts_kind === "caption") fail("Caption placement requires an explicit Speech anchor");
2449
+ if (part.caption !== void 0) {
2450
+ const ids = captionIdsBySpeech.get(part.caption.speech_part_id) ?? [];
2451
+ ids.push(item.part_id);
2452
+ captionIdsBySpeech.set(part.caption.speech_part_id, ids);
2453
+ }
2454
+ }
2455
+ }
2456
+ for (const [id, placement] of placed) {
2457
+ const speech = requirePart(document, id).speech;
2458
+ if (speech === void 0) continue;
2459
+ const expected = captionIdsBySpeech.get(id) ?? [];
2460
+ if (canonical(speech.caption_ids) !== canonical(expected)) fail(`Speech ${id} caption_ids must agree with the Caption Track order`);
2461
+ if (placement.item.time_position.mode === "anchored") continue;
2462
+ if (placement.item.time_position.mode !== "absolute") fail("Speech placement must be anchored or absolute");
2463
+ }
2464
+ const intervals = (fromVideoDocument(document).main_track?.items ?? []).map((item) => {
2465
+ const clip = document.part_library?.[item.part_id]?.video_clip;
2466
+ if (clip === void 0) fail("Projection must preserve every video Clip");
2467
+ return {
2468
+ start: item.abs_time_position ?? 0,
2469
+ end: (item.abs_time_position ?? 0) + effectiveVideoClipDurationMs(clip)
2470
+ };
2471
+ }).sort((left, right) => left.start - right.start);
2472
+ if (intervals.some((interval, index) => index > 0 && interval.start < intervals[index - 1].end)) fail("Overlapping video Clips require an overlay adapter");
2473
+ }
2474
+ /**
2475
+ * Legacy reads perform one speech-overlap pass after laying the visual lane out
2476
+ * sequentially. Entity reads deliberately do not run that hidden cascade. When
2477
+ * the pass moved any visual Clip, cutover therefore records the complete solved
2478
+ * visual lane as explicit target ranges. Mixing absolute and sequential Clips
2479
+ * would create two unrelated placement chains and could reorder the lane.
2480
+ */
2481
+ function overlapNormalizedMainRanges(document) {
2482
+ const track = document.tracks?.find((candidate) => candidate.parts_kind === "video_clip");
2483
+ if (track === void 0 || (track.items?.length ?? 0) === 0) return void 0;
2484
+ const solved = fromVideoDocument(document).main_track?.items ?? [];
2485
+ const starts = new Map(solved.map((item) => [item.part_id, requireMilliseconds(item.abs_time_position, `Solved position for ${item.part_id ?? "unknown Clip"}`)]));
2486
+ let cursor = 0;
2487
+ let moved = false;
2488
+ const ranges = /* @__PURE__ */ new Map();
2489
+ for (const item of track.items ?? []) {
2490
+ const part = requirePart(document, item.part_id).video_clip;
2491
+ if (part === void 0) fail(`Projection must preserve video Clip ${item.part_id}`);
2492
+ const duration = effectiveVideoClipDurationMs(part);
2493
+ const start = starts.get(item.part_id);
2494
+ if (start === void 0) fail(`Projection must preserve video Clip ${item.part_id}`);
2495
+ if (start !== cursor) moved = true;
2496
+ const end = start + duration;
2497
+ requireMilliseconds(end, `Solved end for ${item.part_id}`);
2498
+ ranges.set(item.part_id, {
2499
+ start,
2500
+ end
2501
+ });
2502
+ cursor += duration;
2503
+ }
2504
+ return moved ? ranges : void 0;
202
2505
  }
203
- function parseSseFrame(frame) {
204
- let event = null;
205
- const data = [];
206
- for (const line of frame.split(/\r?\n/)) if (line.startsWith("event:")) event = line.slice(6).trim();
207
- else if (line.startsWith("data:")) data.push(line.slice(5).trimStart());
2506
+ function requirePart(document, partId) {
2507
+ const part = document.part_library?.[partId];
2508
+ if (part === void 0) fail(`Placed Clip ${partId} has no part payload`);
2509
+ return part;
2510
+ }
2511
+ function ensureSpeechPhoneticChain(voiceEntityId, audioScriptText, phonemeScript, entities, relations, addEntity, link, documentAudioScriptEntityId) {
2512
+ const renders = relations.filter((relation) => relation.relationKind === "phonetic-script-render" && relation.endpoint0EntityId === voiceEntityId);
2513
+ if (renders.length > 1) fail(`Voice ${voiceEntityId} has ambiguous PhoneticScript provenance`);
2514
+ if (renders.length === 1) {
2515
+ const phonetic = entities.find((entity) => entity.entityId === renders[0].endpoint1EntityId && entity.entityKind === "phonetic-script");
2516
+ if (phonetic === void 0) fail(`Voice ${voiceEntityId} has a dangling PhoneticScript render`);
2517
+ const script = composedAudioScript(phonetic, entities);
2518
+ if (script === void 0 || scriptText(script) !== audioScriptText) fail(`Voice ${voiceEntityId} conflicts with the legacy Speech script`);
2519
+ return phonetic.entityId;
2520
+ }
2521
+ const script = entities.find((entity) => entity.entityId === documentAudioScriptEntityId);
2522
+ if (script === void 0 || script.entityKind !== "audio-script") fail("Migration must carry the fixed document AudioScript");
2523
+ const segments = script.payload.segments;
2524
+ if (Array.isArray(segments) && segments.length > 0) {
2525
+ if (scriptText(script) !== audioScriptText) fail(`Voice ${voiceEntityId} conflicts with the project AudioScript text`);
2526
+ } else {
2527
+ const scriptIndex = entities.findIndex((row) => row.entityId === script.entityId);
2528
+ entities[scriptIndex] = {
2529
+ ...script,
2530
+ payload: { segments: [{
2531
+ segmentId: "segment-0",
2532
+ text: audioScriptText
2533
+ }] }
2534
+ };
2535
+ }
2536
+ const phonetic = addEntity("phonetic-script", {
2537
+ baseEntityIds: [script.entityId],
2538
+ ...phonemeScript === void 0 ? {} : { phonemeScript }
2539
+ });
2540
+ link("phonetic-script-render", voiceEntityId, phonetic);
2541
+ return phonetic;
2542
+ }
2543
+ function composedAudioScript(phonetic, entities) {
2544
+ return findComposedAudioScript({
2545
+ entities,
2546
+ relations: []
2547
+ }, phonetic.entityId, "phonetic-script");
2548
+ }
2549
+ function scriptText(script) {
2550
+ const segments = script.payload.segments;
2551
+ if (!Array.isArray(segments)) fail("AudioScript requires segments");
2552
+ return segments.map((segment) => {
2553
+ if (segment === null || typeof segment !== "object" || Array.isArray(segment) || typeof segment.text !== "string") fail("AudioScript segment requires text");
2554
+ return segment.text;
2555
+ }).join("");
2556
+ }
2557
+ function toEntityCaptionStyle(style) {
208
2558
  return {
209
- event,
210
- data
2559
+ ...style.font_id === void 0 ? {} : { font: {
2560
+ system: "font-library",
2561
+ key: style.font_id
2562
+ } },
2563
+ ...style.font_size === void 0 ? {} : { fontSize: style.font_size },
2564
+ ...style.font_color === void 0 ? {} : { fontColor: style.font_color },
2565
+ ...style.font_weight === void 0 ? {} : { fontWeight: style.font_weight },
2566
+ ...style.entrance_animation === void 0 ? {} : { entranceAnimation: style.entrance_animation },
2567
+ ...style.entrance_animation_duration_ms === void 0 ? {} : { entranceAnimationDurationMs: style.entrance_animation_duration_ms },
2568
+ ...style.stroke_color === void 0 ? {} : { strokeColor: style.stroke_color },
2569
+ ...style.stroke_width === void 0 ? {} : { strokeWidth: style.stroke_width },
2570
+ ...style.position_x === void 0 ? {} : { positionX: style.position_x },
2571
+ ...style.position_y === void 0 ? {} : { positionY: style.position_y }
211
2572
  };
212
2573
  }
213
- function findSseFrameBoundary(buffer) {
214
- const lf = buffer.indexOf("\n\n");
215
- const crlf = buffer.indexOf("\r\n\r\n");
216
- if (lf < 0) return crlf;
217
- if (crlf < 0) return lf;
218
- return Math.min(lf, crlf);
2574
+ function assertCaptionStyle(style) {
2575
+ if (style.font_id !== void 0 && !trimmed(style.font_id)) fail("Caption font_id must be a trimmed identity");
2576
+ for (const value of [
2577
+ style.font_size,
2578
+ style.font_weight,
2579
+ style.entrance_animation_duration_ms,
2580
+ style.stroke_width,
2581
+ style.position_x,
2582
+ style.position_y
2583
+ ]) if (value !== void 0) requireFinite(value, "Caption style number");
2584
+ for (const value of [
2585
+ style.font_color,
2586
+ style.entrance_animation,
2587
+ style.stroke_color
2588
+ ]) if (value !== void 0 && typeof value !== "string") fail("Caption style text must be a string");
2589
+ assertKnownFields(style, [
2590
+ "font_id",
2591
+ "font_size",
2592
+ "font_color",
2593
+ "font_weight",
2594
+ "entrance_animation",
2595
+ "entrance_animation_duration_ms",
2596
+ "stroke_color",
2597
+ "stroke_width",
2598
+ "position_x",
2599
+ "position_y"
2600
+ ], "Caption style");
219
2601
  }
220
- //#endregion
221
- //#region src/editor/id-gen.ts
222
- /**
223
- * Part-id generation, aligned with the online ecosystem.
224
- *
225
- * The authoritative online producers — agent-harness (`@harness/shared`
226
- * `genObjId`) and director.v2 (`common/obj_id.py` `gen_obj_id`) — both mint part
227
- * ids as `` `${prefix}_${ulid()}` ``, and real captured drafts use exactly that
228
- * shape (`clip_…` / `spe_…` / `cap_…` / `bgm_…`, each a 26-char ULID). The engine
229
- * previously emitted `vc_<base36 timestamp><6 random>`, a different prefix AND a
230
- * different encoding — the sole cross-repo id divergence. This module removes it
231
- * by emitting the same `<prefix>_<ULID>` bytes.
232
- *
233
- * The ULID is generated inline (Crockford Base32, 48-bit time + 80-bit random)
234
- * rather than pulling the `ulid` npm package: the randomness class matches the
235
- * old generator (both `Math.random`-based) and it keeps `@mengine/medeo-client`
236
- * dependency-free for a purely mechanical id string. Part ids only need to be
237
- * unique and lexicographically time-sortable, which this satisfies.
238
- */
239
- /** Crockford Base32 alphabet (no I, L, O, U), per the ULID spec. */
240
- const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
241
- const TIME_LEN = 10;
242
- const RANDOM_LEN = 16;
243
- function encodeTime(now) {
244
- let out = "";
245
- let ms = now;
246
- for (let i = TIME_LEN - 1; i >= 0; i--) {
247
- const mod = ms % 32;
248
- out = CROCKFORD[mod] + out;
249
- ms = (ms - mod) / 32;
250
- }
251
- return out;
2602
+ function isRangeStartingAt(value, expectedStart) {
2603
+ return value !== null && typeof value === "object" && !Array.isArray(value) && value.start === expectedStart;
252
2604
  }
253
- function encodeRandom() {
254
- let out = "";
255
- for (let i = 0; i < RANDOM_LEN; i++) out += CROCKFORD[Math.floor(Math.random() * 32)];
256
- return out;
2605
+ function isExactRange(value, expected) {
2606
+ return value !== null && typeof value === "object" && !Array.isArray(value) && value.start === expected.start && value.end === expected.end;
257
2607
  }
258
- /** A 26-char Crockford Base32 ULID (10-char time + 16-char random). */
259
- function ulid() {
260
- return encodeTime(Date.now()) + encodeRandom();
2608
+ function requireFinite(value, label) {
2609
+ if (typeof value !== "number" || !Number.isFinite(value)) fail(`${label} must be finite`);
2610
+ return value;
261
2611
  }
262
- function generatePartId(prefix) {
263
- return `${prefix}_${ulid()}`;
2612
+ function requireMilliseconds(value, label) {
2613
+ const result = requireFinite(value, label);
2614
+ if (!Number.isSafeInteger(result) || result < 0) fail(`${label} must be non-negative whole milliseconds`);
2615
+ return result;
2616
+ }
2617
+ function requirePositiveMilliseconds(value, label) {
2618
+ const result = requireMilliseconds(value, label);
2619
+ if (result <= 0) fail(`${label} must be positive`);
2620
+ return result;
2621
+ }
2622
+ function trimmed(value) {
2623
+ return typeof value === "string" && value.trim() !== "" && value.trim() === value;
2624
+ }
2625
+ function assertKnownFields(value, fields, label) {
2626
+ if (Object.entries(value).some(([key, field]) => field !== void 0 && !fields.includes(key))) fail(`Unknown legacy ${label} fields require an explicit migration adapter`);
2627
+ }
2628
+ function canonical(value) {
2629
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
2630
+ if (value !== null && typeof value === "object") return `{${Object.entries(value).filter(([, field]) => field !== void 0).sort(([left], [right]) => left.localeCompare(right)).map(([key, field]) => `${JSON.stringify(key)}:${canonical(field)}`).join(",")}}`;
2631
+ return JSON.stringify(value) ?? "undefined";
2632
+ }
2633
+ function fail(message) {
2634
+ throw new EntityTimelineProjectionError(message);
264
2635
  }
265
2636
  //#endregion
266
- //#region src/editor/schemas/shared.ts
267
- const clipIdSchema = z.string().min(1).describe("The clip part ID on the timeline");
268
- const clipIdsSchema = z.array(clipIdSchema).min(1).refine((ids) => new Set(ids).size === ids.length, { message: "Duplicate clip IDs are not allowed" }).describe("List of clip part IDs (no duplicates allowed)");
269
- const mediaIdSchema = z.string().min(1).describe("The media asset ID");
270
- const speechIdSchema = z.string().min(1).describe("The speech part ID on the timeline");
271
- const timelineMsSchema = z.number().int().min(0).describe("Time position in milliseconds on the timeline (>= 0)");
272
- const positiveMsSchema = z.number().int().positive().describe("Duration in milliseconds (> 0)");
273
- const volumeSchema = z.number().min(-60).max(20).describe("Volume in decibels (-60.0 to 20.0; 0.0 = original, -60 = mute, +20 = max)");
274
- const speechIdsSchema = z.array(speechIdSchema).min(1).refine((ids) => new Set(ids).size === ids.length, { message: "Duplicate speech IDs are not allowed" }).describe("List of speech part IDs (no duplicates allowed)");
275
- const tangentHandleSchema = z.object({
276
- x: z.number().finite(),
277
- y: z.number().finite()
278
- }).describe("Bezier tangent handle (x, y)");
279
- const speedKeyframeSchema = z.object({
280
- position: z.number().min(0).max(1),
281
- rate: z.number().min(0),
282
- in_tangent: tangentHandleSchema.optional(),
283
- out_tangent: tangentHandleSchema.optional()
284
- }).describe("A speed keyframe: normalized position (0..1), rate, optional tangents");
285
- /**
286
- * A clip's playback-speed fact, the only thing `SetVideoClipSpeedShift` writes.
287
- * Mirrors the IDL `SpeedShift`: `category` is `linear` | `curve`, and `config`
288
- * is a discriminated union — `{ linear: { speed } }` for a constant multiplier
289
- * (the multiplier projection reads at `config.linear.speed`) or `{ curve: {
290
- * keyframes } }` for a Bezier-controlled variable speed (RFC 02 / `reference/16`
291
- * §0). Exactly one of `linear` / `curve` is present.
292
- */
293
- const speedShiftSchema = z.object({
294
- category: z.enum(["linear", "curve"]),
295
- mode: z.string(),
296
- config: z.union([z.object({ linear: z.object({ speed: z.number().finite().positive() }) }), z.object({ curve: z.object({ keyframes: z.array(speedKeyframeSchema).min(2) }) })])
297
- }).describe("Speed shift: linear multiplier or Bezier curve, mirroring the IDL shape");
298
- const voiceSchema = z.object({
299
- id: z.string().min(1),
300
- name: z.string()
301
- }).describe("TTS voice summary attached to a speech");
302
- //#endregion
303
- //#region src/editor/schemas/speech-assets.ts
304
- /**
305
- * The materialized TTS result shared by `AddSpeeches` / `ChangeSpeechScript` /
306
- * `ChangeSpeechVoice` (see `results/phase-4-side-effect-payload-contract.md`
307
- * §1/§2). The side effect (TTS/ASR + billing) runs upstream; the op receives the
308
- * stable speech + caption parts and writes them as authoritative facts. No
309
- * cascade runs on write — the projection derives absolute positions on read.
310
- *
311
- * Each speech carries the anchoring fact directly (RFC 02 §4): the host video
312
- * clip `anchor_part_id` and the `offset_ms` within it. The upstream caller
313
- * already knows which clip a speech attaches to, so the op writes
314
- * `{ mode:'anchored', anchorPartId, offsetMs }` verbatim — no write-time
315
- * host-picking. Captions anchor to their speech via the caption part's
316
- * `start_ms` (offset within the speech).
317
- */
318
- const speechAssetSchema = z.object({
319
- speech_id: speechIdSchema.describe("The speech part ID (= side-effect speech_parts[].id)"),
320
- anchor_part_id: clipIdSchema.describe("Host video clip part ID the speech anchors to (RFC 02 §4)"),
321
- offset_ms: timelineMsSchema.describe("Offset within the host clip (speech.abs = host.abs + offset_ms)"),
322
- audio_storage_key: z.string().min(1),
323
- duration_ms: positiveMsSchema,
324
- audio_script: z.string(),
325
- volume: volumeSchema,
326
- voice: voiceSchema,
327
- origin_speech_id: z.string().min(1),
328
- caption_ids: z.array(z.string().min(1)).describe("Caption part IDs owned by this speech")
329
- });
330
- const captionAssetSchema = z.object({
331
- caption_id: z.string().min(1).describe("The caption part ID (= side-effect created_caption_parts[].id)"),
332
- speech_part_id: speechIdSchema.describe("The owning speech part ID"),
333
- text: z.string(),
334
- start_ms: timelineMsSchema.describe("Offset within the host speech (caption.abs = speech.abs + start_ms)"),
335
- duration_ms: positiveMsSchema
336
- });
337
- /** A materialized speech-subtree write (speeches + their captions). */
338
- const speechAssetsSchema = z.object({
339
- speeches: z.array(speechAssetSchema).min(1).describe("Materialized speech parts to write"),
340
- captions: z.array(captionAssetSchema).describe("Materialized caption parts owned by the speeches")
341
- });
342
- //#endregion
343
- //#region src/editor/schemas/add-speeches.ts
344
- /**
345
- * Add speeches (and their captions). TTS runs upstream; the stable speech /
346
- * caption parts arrive materialized (see `speech-assets.ts`). The op writes the
347
- * parts and each speech's `{ mode:'anchored', anchorPartId, offsetMs }` fact
348
- * verbatim — no write-time host-picking, no cascade (RFC 02 §4). The projection
349
- * derives absolute positions on read.
350
- */
351
- const addSpeechesInputSchema = speechAssetsSchema.describe("Materialized speeches + captions to add");
352
- //#endregion
353
- //#region src/editor/schemas/add-video-clips.ts
354
- /**
355
- * Add video clips to a track. Each clip's duration facts are separated so a
356
- * single number is never overloaded (RFC 02 / `reference/16` §0b):
357
- *
358
- * - `media_duration_ms` is the source media's intrinsic full length (a resource
359
- * fact, written to the part);
360
- * - `play_in` / `play_out` are the optional trim window into that media; when
361
- * omitted the whole media is used (`play_in=0`, `play_out=media_duration_ms`).
362
- *
363
- * The clip's effective timeline duration is derived by the projection from the
364
- * trim window and `speed_shift` — it is never an input here.
365
- */
366
- const addVideoClipsInputSchema = z.object({
367
- clips: z.array(z.object({
368
- media_id: mediaIdSchema.describe("The media asset ID for the video clip"),
369
- start_ms: timelineMsSchema.optional().describe("Absolute start time in milliseconds on the timeline"),
370
- media_duration_ms: positiveMsSchema.describe("The source media's intrinsic full length in ms"),
371
- play_in: timelineMsSchema.optional().describe("Trim window start in the media (default 0)"),
372
- play_out: positiveMsSchema.optional().describe("Trim window end in the media (default media_duration_ms)"),
373
- track_id: z.string().min(1).optional().describe("Target track ID (optional, defaults to main track)")
374
- })).min(1).describe("List of video clips to create"),
375
- before_clip_id: z.string().min(1).optional().describe("Insert new clips before this clip ID"),
376
- after_clip_id: z.string().min(1).optional().describe("Insert new clips after this clip ID")
377
- }).superRefine((data, ctx) => {
378
- if (data.before_clip_id != null && data.after_clip_id != null) {
379
- ctx.addIssue({
380
- code: z.ZodIssueCode.custom,
381
- message: "Cannot provide both before_clip_id and after_clip_id"
382
- });
383
- return;
384
- }
385
- const hasRelative = data.before_clip_id != null || data.after_clip_id != null;
386
- for (let i = 0; i < data.clips.length; i++) {
387
- const clip = data.clips[i];
388
- if (hasRelative && clip.start_ms != null) ctx.addIssue({
389
- code: z.ZodIssueCode.custom,
390
- message: `clips[${i}].start_ms must not be provided when using before_clip_id or after_clip_id`,
391
- path: [
392
- "clips",
393
- i,
394
- "start_ms"
395
- ]
396
- });
397
- if (!hasRelative && clip.start_ms == null) ctx.addIssue({
398
- code: z.ZodIssueCode.custom,
399
- message: `clips[${i}].start_ms is required when not using relative positioning`,
400
- path: [
401
- "clips",
402
- i,
403
- "start_ms"
404
- ]
405
- });
406
- const playIn = clip.play_in ?? 0;
407
- const playOut = clip.play_out ?? clip.media_duration_ms;
408
- if (playOut > clip.media_duration_ms) ctx.addIssue({
409
- code: z.ZodIssueCode.custom,
410
- message: `clips[${i}].play_out ${playOut}ms exceeds media_duration_ms ${clip.media_duration_ms}ms`,
411
- path: [
412
- "clips",
413
- i,
414
- "play_out"
415
- ]
416
- });
417
- if (playIn >= playOut) ctx.addIssue({
418
- code: z.ZodIssueCode.custom,
419
- message: `clips[${i}].play_in ${playIn}ms must be less than play_out ${playOut}ms`,
420
- path: [
421
- "clips",
422
- i,
423
- "play_in"
424
- ]
425
- });
426
- }
427
- });
428
- //#endregion
429
- //#region src/editor/schemas/adjust-bgm-volume.ts
430
- const adjustBgmVolumeInputSchema = z.object({ bgm: z.array(z.object({
431
- bgm_id: clipIdSchema.describe("The bgm part ID to adjust volume for"),
432
- volume: volumeSchema.describe("Volume in decibels (-60.0 to 20.0; 0.0 = original)")
433
- })).min(1).describe("List of bgm parts with their new volume settings") });
434
- //#endregion
435
- //#region src/editor/schemas/adjust-speech-volume.ts
436
- const adjustSpeechVolumeInputSchema = z.object({ speeches: z.array(z.object({
437
- speech_id: speechIdSchema.describe("The speech part ID to adjust volume for"),
438
- volume: volumeSchema.describe("Volume in decibels (-60.0 to 20.0; 0.0 = original)")
439
- })).min(1).describe("List of speeches with their new volume settings") });
440
- //#endregion
441
- //#region src/editor/schemas/adjust-video-clip-duration.ts
442
- /**
443
- * Re-trim existing video clips (the user-facing "adjust duration" gesture is a
444
- * trim of the source window). The new `play_in` / `play_out` are the facts; the
445
- * effective timeline duration is derived from them and the clip's `speed_shift`,
446
- * and the change reflows downstream clips, speeches, and the timeline inside the
447
- * op's transaction (no caller-materialized cascade).
448
- */
449
- const adjustVideoClipDurationInputSchema = z.object({ clips: z.array(z.object({
450
- clip_id: clipIdSchema.describe("The video clip part ID to re-trim"),
451
- play_in: timelineMsSchema.describe("New trim window start in the source media"),
452
- play_out: positiveMsSchema.describe("New trim window end in the source media")
453
- })).min(1).describe("Video clips with their new trim windows") });
454
- //#endregion
455
- //#region src/editor/schemas/adjust-video-clip-volume.ts
456
- const adjustVideoClipVolumeInputSchema = z.object({ clips: z.array(z.object({
457
- clip_id: clipIdSchema.describe("The video clip part ID to adjust volume for"),
458
- volume: volumeSchema.describe("Volume in decibels (-60.0 to 20.0; 0.0 = original)")
459
- })).min(1).describe("List of video clips with their new volume settings") });
460
- //#endregion
461
- //#region src/editor/schemas/change-speech.ts
462
- /**
463
- * Change a speech's script or voice. Both re-run TTS upstream and return the
464
- * regenerated speech / caption parts in the same materialized shape as
465
- * `AddSpeeches` (`speech-assets.ts`); the op upserts them by id (the speech part
466
- * id is preserved across a re-TTS), re-seats at `start_ms`, and reflows. Old
467
- * caption parts no longer owned by the speech are removed via `caption_ids`.
468
- */
469
- const changeSpeechScriptInputSchema = speechAssetsSchema.describe("Regenerated speeches + captions (new script)");
470
- const changeSpeechVoiceInputSchema = speechAssetsSchema.describe("Regenerated speeches + captions (new voice)");
471
- //#endregion
472
- //#region src/editor/schemas/delete-bgm.ts
473
- /**
474
- * Remove the document BGM. Pure document edit: clears the bgm lane and removes
475
- * the bgm part. Takes no input (a document holds at most one bgm); an empty
476
- * object keeps the op signature uniform with the rest.
477
- */
478
- const deleteBgmInputSchema = z.object({}).describe("Remove the document BGM (no parameters)");
479
- //#endregion
480
- //#region src/editor/schemas/delete-speeches.ts
481
- /**
482
- * Delete speeches with their captions. Pure document edit (no side effect): the
483
- * op removes each speech part, cascade-deletes the captions it owns (via
484
- * `caption_ids` / `speech_part_id`), drops their track items, and reflows.
485
- */
486
- const deleteSpeechesInputSchema = z.object({ speech_ids: speechIdsSchema.describe("Speech part IDs to delete (their captions cascade-delete)") });
487
- //#endregion
488
- //#region src/editor/schemas/delete-video-clips.ts
489
- /**
490
- * How a delete handles the anchored subtree (speeches anchored to a deleted clip,
491
- * and their captions) — a delete-op policy, not a data-model field (reference/17
492
- * §6). `cascade` (default) removes the subtree; `detach` keeps the direct
493
- * anchored children, re-pinning them to `absolute` so they stay on the timeline.
494
- */
495
- const anchoredDeletePolicySchema = z.enum(["cascade", "detach"]);
496
- const deleteVideoClipsInputSchema = z.object({
497
- clip_ids: clipIdsSchema.describe("List of video clip part IDs to delete from the main track"),
498
- on_anchored: anchoredDeletePolicySchema.optional().describe("How to treat anchored children (default cascade)")
499
- });
500
- //#endregion
501
- //#region src/editor/schemas/move-speeches.ts
502
- /**
503
- * Move speeches in time. Pure document edit: the op re-seats each speech at its
504
- * new absolute `start_ms`; the cascade reassigns it to the host video clip,
505
- * resolves overlaps, and reflows. Captions follow their speech.
506
- */
507
- const moveSpeechesInputSchema = z.object({ speeches: z.array(z.object({
508
- speech_id: speechIdSchema.describe("The speech part ID to move"),
509
- new_start_ms: timelineMsSchema.describe("New absolute start time on the timeline")
510
- })).min(1).describe("Speeches to move to new positions") });
511
- //#endregion
512
- //#region src/editor/schemas/move-video-clips-by-anchor.ts
513
- /**
514
- * Where the moved block lands on the main track.
515
- *
516
- * A discriminated union rather than two optional `before_clip_id` /
517
- * `after_clip_id` fields (the shape `addVideoClips` had to use, because there the
518
- * two modes share a whole clip description): here the alternatives carry nothing
519
- * in common, so making them mutually exclusive *by type* removes three runtime
520
- * `superRefine` checks that would otherwise have to be written and tested.
521
- *
522
- * `track_start` is an explicit member, not the absence of an anchor. The
523
- * agent-harness mutation this maps from treats "neither anchor given" as
524
- * "move to the front" (`applyBatchMoveVideoClips` falls back to `insertIndex = 0`),
525
- * which is a default buried in a tool description. Requiring the caller to name
526
- * that intent keeps a forgotten field from silently reordering the timeline.
527
- */
528
- const moveAnchorSchema = z.discriminatedUnion("position", [
529
- z.object({
530
- position: z.literal("before"),
531
- clip_id: clipIdSchema.describe("The moved block lands immediately before this clip")
532
- }),
533
- z.object({
534
- position: z.literal("after"),
535
- clip_id: clipIdSchema.describe("The moved block lands immediately after this clip")
536
- }),
537
- z.object({ position: z.literal("track_start") })
538
- ]).describe("Where the moved block lands: before/after a reference clip, or at the head of the track");
539
- /**
540
- * What happens to the speeches anchored to the clips being moved.
541
- *
542
- * - `follow` keeps each speech anchored where it is, so it travels with its clip
543
- * to the new position. In the anchored model this is the *no-op* branch: a
544
- * speech's authoritative fact is `{ anchorPartId, offsetMs }` and its absolute
545
- * time is derived on read from the host's position, so moving the host moves
546
- * the speech with no write to the speech at all.
547
- * - `keep_absolute` preserves each speech's current absolute landing instead, then
548
- * re-anchors it to whichever clip now covers that time (RFC 02 §9.1/§11.1). This
549
- * is the branch that costs an extra pass, and the one the FE timeline uses.
550
- *
551
- * **Required, with no default**, matching `deleteVideoClips` and
552
- * `replaceVideoClipSequence`. The two branches decide which picture the user's
553
- * narration ends up over, which is too consequential to infer from a missing
554
- * field — and neither branch is "safe enough" to be the implicit one.
555
- */
556
- const movedClipAnchoredPolicySchema = z.enum(["follow", "keep_absolute"]);
557
- /**
558
- * Reorder a set of main-track clips relative to a reference clip.
559
- *
560
- * Distinct from `moveVideoClips`, which positions clips by absolute time
561
- * (`new_start_ms`) and is what the FE timeline dispatches after a drag. Main-track
562
- * clips are `sequential`-positioned, so absolute time is not authoritative state
563
- * there (RFC 02 §4/§7): `moveVideoClips` has to *guess* an index back out of the
564
- * time it was handed, whereas an anchor already is the ordinal fact being changed.
565
- * Keeping them separate also isolates blast radius — this method can diverge on
566
- * speech policy without touching the FE path.
567
- *
568
- * `clip_ids` need not be contiguous. They move as one block, keeping their
569
- * relative order, which is the agent-harness `batch_move_video_clips` contract.
570
- */
571
- const moveVideoClipsByAnchorInputSchema = z.object({
572
- clip_ids: clipIdsSchema.describe("Clips to move as one block, keeping their relative order. Need not be contiguous on the track."),
573
- anchor: moveAnchorSchema,
574
- on_anchored: movedClipAnchoredPolicySchema.describe("What happens to speeches anchored to the moved clips (required — see the policy doc)")
575
- });
576
- //#endregion
577
- //#region src/editor/schemas/move-video-clips.ts
578
- const moveVideoClipsInputSchema = z.object({ clips: z.array(z.object({
579
- clip_id: clipIdSchema.describe("The video clip part ID to move"),
580
- new_start_ms: timelineMsSchema.describe("New absolute start time in milliseconds on the timeline"),
581
- new_track_id: z.string().min(1).optional().describe("Target track ID to move the clip to (optional)")
582
- })).min(1).describe("List of video clips to move to new positions") });
583
- //#endregion
584
- //#region src/editor/schemas/replace-video-clip-content.ts
585
- /**
586
- * Replace the media backing existing video clips. The media import runs upstream
587
- * (Director); its stable result — the new media id, intrinsic length, and the
588
- * reset trim window — arrives materialized (see
589
- * `results/phase-4-side-effect-payload-contract.md` §4). Director resets
590
- * `play_in=0` / `play_out=media_duration_ms` and clears `speed_shift` on
591
- * replacement. The clip `part_id`s (hence their track items) are unchanged; the
592
- * editor reflows the main track from the new effective durations.
593
- */
594
- const replaceVideoClipContentInputSchema = z.object({ clips: z.array(z.object({
595
- clip_id: clipIdSchema.describe("Existing video clip part ID to re-point"),
596
- origin_media_id: mediaIdSchema.describe("The new media asset ID"),
597
- media_duration_ms: positiveMsSchema.describe("The new media's intrinsic full length"),
598
- play_in: timelineMsSchema.describe("Trim window start in the new media (usually 0)"),
599
- play_out: positiveMsSchema.describe("Trim window end in the new media (usually = media_duration_ms)"),
600
- volume: volumeSchema
601
- })).min(1).describe("Video clips whose media is being replaced") });
602
- //#endregion
603
- //#region src/editor/schemas/replace-video-clip-sequence.ts
604
- /**
605
- * What happens to the speeches anchored to the clips being replaced.
606
- *
607
- * - `remap` re-anchors each surviving speech to the new clip in the SAME POSITION
608
- * of the sequence, keeping its offset — old[i]'s children become new[i]'s
609
- * children. An old clip with no counterpart (fewer new clips than old) has its
610
- * subtree deleted, because there is nothing left to anchor to.
611
- * - `cascade` deletes every anchored speech (and its captions) outright, like
612
- * `deleteVideoClips`.
613
- *
614
- * **Required, with no default.** The two branches differ in whether the user's
615
- * narration survives, and the agent tool that drives this op makes its
616
- * `preserve_speeches` flag required for that reason. A default here would let a
617
- * caller that forgot the field silently delete speech.
618
- */
619
- const anchoredReplacePolicySchema = z.enum(["remap", "cascade"]);
620
- /**
621
- * Replace a contiguous run of main-track clips with a new run.
622
- *
623
- * A composite of delete + insert that cannot be expressed as the two ops in
624
- * sequence, because the anchored speeches have to survive *across* the swap: with
625
- * `remap` they are re-anchored positionally, which needs both the old and the new
626
- * ids in the same transaction (ADR 0009 — the cascade stays in the editor, callers
627
- * never re-wire anchors themselves).
628
- *
629
- * Duration facts follow `addVideoClips`: `media_duration_ms` is the source's
630
- * intrinsic length and the trim window defaults to the whole media. The effective
631
- * timeline duration is derived by the projection, never an input.
632
- *
633
- * `media_id` is optional: omitting it creates a **deliberate empty placeholder
634
- * clip** (`origin_media_id: ''`) — structure with no picture. This is the only op
635
- * that can produce one, and it is authoritative state, unlike the gap fillers the
636
- * read-side solve mints (which never enter the document).
637
- */
638
- const replaceVideoClipSequenceInputSchema = z.object({
639
- old_clip_ids: clipIdsSchema.describe("The clips being replaced: a contiguous main-track run, listed in timeline order"),
640
- new_clips: z.array(z.object({
641
- media_id: mediaIdSchema.optional().describe("The replacement media asset ID. Omit to create an empty placeholder clip."),
642
- media_duration_ms: positiveMsSchema.describe("The source media's intrinsic full length in ms"),
643
- play_in: timelineMsSchema.optional().describe("Trim window start in the media (default 0)"),
644
- play_out: positiveMsSchema.optional().describe("Trim window end in the media (default media_duration_ms)")
645
- })).min(1).describe("The replacement clips, in the order they take on the track"),
646
- on_anchored: anchoredReplacePolicySchema.describe("What happens to speeches anchored to the replaced clips (required — see the policy doc)")
647
- }).superRefine((data, ctx) => {
648
- for (let i = 0; i < data.new_clips.length; i++) {
649
- const clip = data.new_clips[i];
650
- const playIn = clip.play_in ?? 0;
651
- const playOut = clip.play_out ?? clip.media_duration_ms;
652
- if (playOut > clip.media_duration_ms) ctx.addIssue({
653
- code: z.ZodIssueCode.custom,
654
- message: `new_clips[${i}].play_out ${playOut}ms exceeds media_duration_ms ${clip.media_duration_ms}ms`,
655
- path: [
656
- "new_clips",
657
- i,
658
- "play_out"
659
- ]
660
- });
661
- if (playIn >= playOut) ctx.addIssue({
662
- code: z.ZodIssueCode.custom,
663
- message: `new_clips[${i}].play_in ${playIn}ms must be less than play_out ${playOut}ms`,
664
- path: [
665
- "new_clips",
666
- i,
667
- "play_in"
668
- ]
669
- });
2637
+ //#region src/entity-editor/caption-content.ts
2638
+ /** Author Caption content from semantic intent; callers never reconcile variant bases or assembled fields. */
2639
+ function prepareCaptionContent(rows, input) {
2640
+ const entityId = createEntityId(input.contentEntityId);
2641
+ const scriptId = createEntityId(input.audioScriptEntityId);
2642
+ if (!Number.isFinite(input.durationMs) || input.durationMs <= 0) throw new Error("Caption duration must be positive");
2643
+ const previous = rows.entities.find((row) => row.entityId === entityId);
2644
+ if (previous !== void 0 && previous.entityKind !== "caption") throw new Error("Caption content identity has a different kind");
2645
+ let baseEntityIds = [scriptId];
2646
+ if (previous !== void 0) {
2647
+ const source = assembleCaptionContent(rows, entityId).audioScript.entityId;
2648
+ const bases = variantBaseEntityIds(previous);
2649
+ if (source !== scriptId && !bases.includes(source)) throw new Error("Replacing an indirectly composed AudioScript requires an explicit composition change");
2650
+ baseEntityIds = bases.map((id) => id === source ? scriptId : id);
2651
+ }
2652
+ const candidate = {
2653
+ entityId,
2654
+ entityKind: "caption",
2655
+ payload: {
2656
+ ...previous?.payload,
2657
+ baseEntityIds,
2658
+ extent: previous?.payload.extent ?? {
2659
+ kind: "bounded",
2660
+ start: 0,
2661
+ end: input.durationMs
2662
+ },
2663
+ sampling: previous?.payload.sampling ?? "native",
2664
+ coordinateSpace: previous?.payload.coordinateSpace ?? "milliseconds"
2665
+ }
2666
+ };
2667
+ const graph = {
2668
+ ...rows,
2669
+ entities: [...rows.entities.filter((row) => row.entityId !== entityId), candidate]
2670
+ };
2671
+ const textSource = {
2672
+ ...assembleEntityContent(graph, entityId),
2673
+ entityKind: "audio-script"
2674
+ };
2675
+ const selected = {
2676
+ ...candidate,
2677
+ payload: {
2678
+ ...candidate.payload,
2679
+ selections: structuredClone(input.selections ?? selectCaptionText(textSource, input.text))
2680
+ }
2681
+ };
2682
+ if (assembleCaptionContent({
2683
+ ...graph,
2684
+ entities: graph.entities.map((row) => row.entityId === entityId ? selected : row)
2685
+ }, entityId).text !== input.text) throw new Error("Caption review text differs from its assembled variant content");
2686
+ return selected;
2687
+ }
2688
+ function selectCaptionText(script, text) {
2689
+ if (!text.trim()) throw new Error("Caption text selection must not be blank");
2690
+ const source = script;
2691
+ const fullText = assembleScriptText(source);
2692
+ const segments = source.payload.segments;
2693
+ if (text === fullText) return segments.map((segment) => ({ segmentId: segment.segmentId }));
2694
+ const matches = [];
2695
+ for (const segment of segments) {
2696
+ let offset = segment.text.indexOf(text);
2697
+ while (offset !== -1) {
2698
+ const start = Array.from(segment.text.slice(0, offset)).length;
2699
+ matches.push({
2700
+ segmentId: segment.segmentId,
2701
+ textRange: {
2702
+ start,
2703
+ end: start + Array.from(text).length
2704
+ }
2705
+ });
2706
+ offset = segment.text.indexOf(text, offset + 1);
2707
+ }
670
2708
  }
671
- });
672
- //#endregion
673
- //#region src/editor/schemas/set-bgm.ts
674
- /**
675
- * Set the document BGM. The media's stable result (storage key) arrives
676
- * materialized from upstream (see
677
- * `results/phase-4-side-effect-payload-contract.md` §3). The op upserts the bgm
678
- * part and seats it on the bgm lane; its effective length is always the whole
679
- * timeline, derived by the projection on read — so there is no `duration_ms`
680
- * input or fact (RFC 02 / `reference/16` §0b). A `bgm_id` lets the op replace an
681
- * existing bgm part by id.
682
- */
683
- const setBgmInputSchema = z.object({
684
- bgm_id: z.string().min(1).describe("The bgm part ID to write"),
685
- audio_storage_key: z.string().min(1),
686
- origin_media_id: mediaIdSchema,
687
- volume: volumeSchema
688
- });
689
- //#endregion
690
- //#region src/editor/schemas/set-caption-style.ts
691
- /**
692
- * Set the caption visual style. GLOBAL by design: the style applies to every
693
- * caption part in the document — it carries NO `caption_id`. This mirrors the FE,
694
- * whose caption-style store (`caption-style.ts:persistCaptionStylePatch`) iterates
695
- * ALL captions and writes the same normalized style to each; the product has a
696
- * single document-wide caption style, not per-caption styling.
697
- *
698
- * Every field is optional and maps to a `CaptionStyle` attribute (snake_case
699
- * IDL). A field present in the input is written to every caption; a field ABSENT
700
- * from the input is left untouched on each caption (the editor merges the patch
701
- * onto each caption's existing style — this is a value edit, not a full-style
702
- * replace, so a partial patch such as "recolor only" does not wipe font size).
703
- *
704
- * Pure document edit, no cascade — captions keep their positions; only the style
705
- * sub-map of each caption part changes.
706
- */
707
- const setCaptionStyleInputSchema = z.object({
708
- font_id: z.string().min(1).optional().describe("Font ID referencing a font from the font library"),
709
- font_size: z.number().positive().optional().describe("Font size in points"),
710
- font_color: z.string().min(1).optional().describe("Font color as hex string, e.g. \"#FFFFFF\""),
711
- font_weight: z.number().int().optional().describe("Numeric font weight, e.g. 400 or 700"),
712
- entrance_animation: z.string().optional().describe("Entrance animation preset ID, e.g. \"fade\" or \"none\""),
713
- entrance_animation_duration_ms: z.number().min(0).optional().describe("Entrance animation duration in ms"),
714
- stroke_color: z.string().min(1).optional().describe("Outline/stroke color as hex string, e.g. \"#000000\""),
715
- stroke_width: z.number().min(0).optional().describe("Outline/stroke width in pixels"),
716
- position_x: z.number().optional().describe("Caption center X as a fraction (0.0 to 1.0)"),
717
- position_y: z.number().optional().describe("Caption center Y as a fraction (0.0 to 1.0)")
718
- }).describe("Document-wide caption style patch (no caption_id; applies to every caption)");
719
- //#endregion
720
- //#region src/editor/schemas/set-caption-visibility.ts
721
- /**
722
- * Toggle caption visibility (the caption track's `is_hidden` flag). Pure
723
- * document edit, no cascade — captions keep their positions; only the lane's
724
- * hidden flag changes.
725
- */
726
- const setCaptionVisibilityInputSchema = z.object({ is_hidden: z.boolean().describe("Whether the caption track is hidden") });
727
- //#endregion
728
- //#region src/editor/schemas/set-video-clip-speed-shift.ts
729
- /**
730
- * Set the playback speed of existing video clips. Per the speed-shift decision
731
- * (`reference/16` §0): the op writes only the `speed_shift` fact — it does NOT
732
- * store an effective `duration_ms` (projection derives it from the trim window /
733
- * speed) and does NOT scale anchored speeches' relative offsets (offsets stay
734
- * put; the cascade reflows absolute positions). A `null` speed_shift clears the
735
- * speed back to original (1×).
736
- */
737
- const setVideoClipSpeedShiftInputSchema = z.object({ clips: z.array(z.object({
738
- clip_id: clipIdSchema.describe("The video clip part ID to set speed for"),
739
- speed_shift: speedShiftSchema.nullable().describe("The new speed setting, or null to reset to 1×")
740
- })).min(1).describe("Video clips with their new speed settings") });
741
- //#endregion
742
- //#region src/editor/schemas/index.ts
743
- var schemas_exports = /* @__PURE__ */ __exportAll({
744
- addSpeechesInputSchema: () => addSpeechesInputSchema,
745
- addVideoClipsInputSchema: () => addVideoClipsInputSchema,
746
- adjustBgmVolumeInputSchema: () => adjustBgmVolumeInputSchema,
747
- adjustSpeechVolumeInputSchema: () => adjustSpeechVolumeInputSchema,
748
- adjustVideoClipDurationInputSchema: () => adjustVideoClipDurationInputSchema,
749
- adjustVideoClipVolumeInputSchema: () => adjustVideoClipVolumeInputSchema,
750
- anchoredDeletePolicySchema: () => anchoredDeletePolicySchema,
751
- anchoredReplacePolicySchema: () => anchoredReplacePolicySchema,
752
- changeSpeechScriptInputSchema: () => changeSpeechScriptInputSchema,
753
- changeSpeechVoiceInputSchema: () => changeSpeechVoiceInputSchema,
754
- clipIdSchema: () => clipIdSchema,
755
- clipIdsSchema: () => clipIdsSchema,
756
- deleteBgmInputSchema: () => deleteBgmInputSchema,
757
- deleteSpeechesInputSchema: () => deleteSpeechesInputSchema,
758
- deleteVideoClipsInputSchema: () => deleteVideoClipsInputSchema,
759
- mediaIdSchema: () => mediaIdSchema,
760
- moveAnchorSchema: () => moveAnchorSchema,
761
- moveSpeechesInputSchema: () => moveSpeechesInputSchema,
762
- moveVideoClipsByAnchorInputSchema: () => moveVideoClipsByAnchorInputSchema,
763
- moveVideoClipsInputSchema: () => moveVideoClipsInputSchema,
764
- movedClipAnchoredPolicySchema: () => movedClipAnchoredPolicySchema,
765
- positiveMsSchema: () => positiveMsSchema,
766
- replaceVideoClipContentInputSchema: () => replaceVideoClipContentInputSchema,
767
- replaceVideoClipSequenceInputSchema: () => replaceVideoClipSequenceInputSchema,
768
- setBgmInputSchema: () => setBgmInputSchema,
769
- setCaptionStyleInputSchema: () => setCaptionStyleInputSchema,
770
- setCaptionVisibilityInputSchema: () => setCaptionVisibilityInputSchema,
771
- setVideoClipSpeedShiftInputSchema: () => setVideoClipSpeedShiftInputSchema,
772
- speechAssetsSchema: () => speechAssetsSchema,
773
- speechIdSchema: () => speechIdSchema,
774
- speechIdsSchema: () => speechIdsSchema,
775
- speedShiftSchema: () => speedShiftSchema,
776
- timelineMsSchema: () => timelineMsSchema,
777
- voiceSchema: () => voiceSchema,
778
- volumeSchema: () => volumeSchema
779
- });
2709
+ if (matches.length !== 1) throw new Error("Caption text must select a unique AudioScript range; provide explicit selections");
2710
+ return matches;
2711
+ }
780
2712
  //#endregion
781
2713
  //#region src/editor/snapshot-utils.ts
782
2714
  function isMap(value) {
@@ -1126,9 +3058,11 @@ function readPartLibrary(draft) {
1126
3058
  var SemanticEditor = class {
1127
3059
  doc;
1128
3060
  validator;
1129
- constructor(doc, validator = new SchemaValidator()) {
3061
+ idFactory;
3062
+ constructor(doc, validator = new SchemaValidator(), idFactory = generatePartId) {
1130
3063
  this.doc = doc;
1131
3064
  this.validator = validator;
3065
+ this.idFactory = idFactory;
1132
3066
  }
1133
3067
  async moveVideoClips(input, options) {
1134
3068
  this.validator.validateMoveVideoClips(input, this.doc);
@@ -1208,7 +3142,7 @@ var SemanticEditor = class {
1208
3142
  track.items ??= [];
1209
3143
  let at = insertIndex;
1210
3144
  for (const clip of input.clips) {
1211
- const partId = generatePartId("clip");
3145
+ const partId = this.idFactory("clip");
1212
3146
  setPart(draft, partId, { video_clip: {
1213
3147
  id: partId,
1214
3148
  kind: "video_clip",
@@ -1255,7 +3189,7 @@ var SemanticEditor = class {
1255
3189
  const newItems = [];
1256
3190
  const newClipIds = [];
1257
3191
  for (const clip of input.new_clips) {
1258
- const partId = generatePartId("clip");
3192
+ const partId = this.idFactory("clip");
1259
3193
  setPart(draft, partId, { video_clip: {
1260
3194
  id: partId,
1261
3195
  kind: "video_clip",
@@ -1713,7 +3647,7 @@ function writeSpeechAssets(draft, assets) {
1713
3647
  if (caption == null) continue;
1714
3648
  const priorCaption = draft.part_library?.[captionId]?.caption;
1715
3649
  setPart(draft, captionId, { caption: {
1716
- ...priorCaption ?? { style: {} },
3650
+ ...priorCaption,
1717
3651
  id: captionId,
1718
3652
  kind: "caption",
1719
3653
  initial_duration_ms: caption.duration_ms,
@@ -1875,6 +3809,111 @@ function deleteAnchoredSubtree(draft, clipId) {
1875
3809
  for (const speechId of anchored) deleteSpeechSubtree(draft, speechId);
1876
3810
  }
1877
3811
  //#endregion
3812
+ //#region src/editor/journal.ts
3813
+ /**
3814
+ * Wire a plain-memory adapter + editor that share a recording id factory, so
3815
+ * every mutating transact lands in `journal` with ordered `generated_ids`.
3816
+ */
3817
+ function createEditSandbox(document, options) {
3818
+ const adapter = createPlainMemoryAdapter(document, options);
3819
+ return {
3820
+ adapter,
3821
+ editor: new SemanticEditor(adapter, new SchemaValidator(), adapter.idFactory),
3822
+ journal: adapter.journal
3823
+ };
3824
+ }
3825
+ /**
3826
+ * Re-drive `doc` from a recorded journal, forcing each entry's `generated_ids`
3827
+ * through a queue-backed id factory. Never mints fresh ids: an empty queue on
3828
+ * demand throws `unrecorded id`; leftover ids after an entry throws
3829
+ * `unconsumed ids`. Legacy entries without `generated_ids` are treated as `[]`.
3830
+ */
3831
+ async function replayJournal(doc, journal) {
3832
+ const queue = [];
3833
+ const idFactory = (_prefix) => {
3834
+ const id = queue.shift();
3835
+ if (id == null) throw new Error("unrecorded id");
3836
+ return id;
3837
+ };
3838
+ const editor = new SemanticEditor(doc, new SchemaValidator(), idFactory);
3839
+ for (const entry of journal) {
3840
+ queue.push(...entry.generated_ids ?? []);
3841
+ await dispatchEntry(editor, entry);
3842
+ if (queue.length > 0) throw new Error("unconsumed ids");
3843
+ }
3844
+ }
3845
+ /** Dispatch one journal entry to the matching editor method; payload is passed through. */
3846
+ async function dispatchEntry(editor, entry) {
3847
+ const payload = entry.payload;
3848
+ const options = entry.intent != null ? { intent: entry.intent } : void 0;
3849
+ switch (entry.kind) {
3850
+ case "MoveVideoClips":
3851
+ await editor.moveVideoClips(payload, options);
3852
+ return;
3853
+ case "MoveVideoClipsByAnchor":
3854
+ await editor.moveVideoClipsByAnchor(payload, options);
3855
+ return;
3856
+ case "DeleteVideoClips":
3857
+ await editor.deleteVideoClips(payload, options);
3858
+ return;
3859
+ case "AddVideoClips":
3860
+ await editor.addVideoClips(payload, options);
3861
+ return;
3862
+ case "AdjustVideoClipVolume":
3863
+ await editor.adjustVideoClipVolume(payload, options);
3864
+ return;
3865
+ case "SetVideoClipSpeedShift":
3866
+ await editor.setVideoClipSpeedShift(payload, options);
3867
+ return;
3868
+ case "ReplaceVideoClipContent":
3869
+ await editor.replaceVideoClipContent(payload, options);
3870
+ return;
3871
+ case "ReplaceVideoClipSequence":
3872
+ await editor.replaceVideoClipSequence(payload, options);
3873
+ return;
3874
+ case "AdjustVideoClipDuration":
3875
+ await editor.adjustVideoClipDuration(payload, options);
3876
+ return;
3877
+ case "AddSpeeches":
3878
+ await editor.addSpeeches(payload, options);
3879
+ return;
3880
+ case "DeleteSpeeches":
3881
+ await editor.deleteSpeeches(payload, options);
3882
+ return;
3883
+ case "MoveSpeeches":
3884
+ await editor.moveSpeeches(payload, options);
3885
+ return;
3886
+ case "ChangeSpeechScript":
3887
+ await editor.changeSpeechScript(payload, options);
3888
+ return;
3889
+ case "ChangeSpeechVoice":
3890
+ await editor.changeSpeechVoice(payload, options);
3891
+ return;
3892
+ case "AdjustSpeechVolume":
3893
+ await editor.adjustSpeechVolume(payload, options);
3894
+ return;
3895
+ case "SetCaptionVisibility":
3896
+ await editor.setCaptionVisibility(payload, options);
3897
+ return;
3898
+ case "SetCaptionStyle":
3899
+ await editor.setCaptionStyle(payload, options);
3900
+ return;
3901
+ case "SetBgm":
3902
+ await editor.setBgm(payload, options);
3903
+ return;
3904
+ case "DeleteBgm":
3905
+ await editor.deleteBgm(payload, options);
3906
+ return;
3907
+ case "AdjustBgmVolume":
3908
+ await editor.adjustBgmVolume(payload, options);
3909
+ return;
3910
+ default: {
3911
+ const _exhaustive = entry.kind;
3912
+ throw new Error(`replayJournal: unsupported kind ${String(_exhaustive)}`);
3913
+ }
3914
+ }
3915
+ }
3916
+ //#endregion
1878
3917
  //#region src/editor/types.ts
1879
3918
  /** Runtime list of the frozen, implemented kinds (for guards / introspection). */
1880
3919
  const IMPLEMENTED_SEMANTIC_OP_KINDS = [
@@ -2069,6 +4108,18 @@ var ManualSyncDoc = class ManualSyncDoc {
2069
4108
  return fromVideoDocument(this.adapter.snapshot());
2070
4109
  }
2071
4110
  /**
4111
+ * Replay a deterministic sandbox journal into this document.
4112
+ *
4113
+ * The adapter stays private so callers cannot bypass the manual-sync
4114
+ * lifecycle; journal replay is the one host-side operation that needs the
4115
+ * adapter's transaction boundary and recorded id queue. Durability is still
4116
+ * explicit: call {@link push} after replay and report success only from its
4117
+ * verdict.
4118
+ */
4119
+ async replayJournal(journal) {
4120
+ await replayJournal(this.adapter, journal);
4121
+ }
4122
+ /**
2072
4123
  * Mark the document state the caller has just observed, for a later
2073
4124
  * {@link hasChangedSince}.
2074
4125
  *
@@ -2160,7 +4211,6 @@ var ManualSyncDoc = class ManualSyncDoc {
2160
4211
  if (serverVV != null) this.watermark = serverVV;
2161
4212
  return {
2162
4213
  kind: response.kind,
2163
- mengineUpdateSeq: response.version?.update_seq ?? response.update_seq ?? void 0,
2164
4214
  updateSeq: response.update_seq ?? void 0,
2165
4215
  collaborated: serverVV != null && !covers(localVersion, serverVV)
2166
4216
  };
@@ -2279,7 +4329,6 @@ var SseConnection = class {
2279
4329
  for (const update of event.updates) this.onUpdate(update);
2280
4330
  }
2281
4331
  });
2282
- if (!signal.aborted) this.setStatus("connecting", /* @__PURE__ */ new Error("SSE stream closed"));
2283
4332
  } catch (error) {
2284
4333
  if (signal.aborted) break;
2285
4334
  this.setStatus("connecting", error instanceof Error ? error : new Error(String(error)));
@@ -2332,7 +4381,6 @@ var MedeoHttpDocStorage = class {
2332
4381
  async getDoc(docId) {
2333
4382
  this.assertDocId(docId);
2334
4383
  const snapshot = await this.client.fetchSnapshot();
2335
- this.reportServerVersion(snapshot.version?.server_vv);
2336
4384
  const now = /* @__PURE__ */ new Date();
2337
4385
  return {
2338
4386
  docId,
@@ -2344,7 +4392,6 @@ var MedeoHttpDocStorage = class {
2344
4392
  async getDocDiff(docId, knownVersion) {
2345
4393
  this.assertDocId(docId);
2346
4394
  const response = await this.client.sync(knownVersion);
2347
- this.reportServerVersion(response.server_vv);
2348
4395
  return {
2349
4396
  docId,
2350
4397
  missing: base64ToBytes(response.update),
@@ -2375,7 +4422,7 @@ var MedeoHttpDocStorage = class {
2375
4422
  if (update.data.byteLength === 0) return {};
2376
4423
  try {
2377
4424
  const response = await this.client.pushUpdate(update.data);
2378
- const serverVV = this.reportServerVersion(response.version?.server_vv);
4425
+ const serverVV = decodeServerVV(response.version?.server_vv);
2379
4426
  this.events.emit("pushOutcome", {
2380
4427
  kind: response.kind,
2381
4428
  updateSeq: response.update_seq ?? void 0,
@@ -2403,15 +4450,6 @@ var MedeoHttpDocStorage = class {
2403
4450
  subscribePushOutcome(callback) {
2404
4451
  return this.events.on("pushOutcome", callback);
2405
4452
  }
2406
- /** Authoritative HTTP reads and accepted pushes, never inferred from SSE bytes. */
2407
- subscribeServerVersion(callback) {
2408
- return this.events.on("serverVersion", callback);
2409
- }
2410
- reportServerVersion(encoded) {
2411
- const version = decodeServerVV(encoded);
2412
- if (version != null) this.events.emit("serverVersion", version);
2413
- return version;
2414
- }
2415
4453
  async deleteDoc(_docId) {
2416
4454
  throw new Error("MedeoHttpDocStorage does not support deleteDoc");
2417
4455
  }
@@ -2528,118 +4566,6 @@ var MemoryDocStorage = class extends BaseDocStorage {
2528
4566
  }
2529
4567
  };
2530
4568
  //#endregion
2531
- //#region src/session/document-undo-manager.ts
2532
- /**
2533
- * Tracks the shared LoroDoc independently of semantic editing. Undo/redo use
2534
- * the same mutation guard as the adapter and publish settled availability.
2535
- */
2536
- var DocumentUndoManager = class {
2537
- doc;
2538
- mutationGuard;
2539
- onChange;
2540
- manager;
2541
- unsubscribe;
2542
- disposed = false;
2543
- notificationQueued = false;
2544
- published = {
2545
- canUndo: false,
2546
- canRedo: false
2547
- };
2548
- activeSource = null;
2549
- constructor(doc, mutationGuard, onChange) {
2550
- this.doc = doc;
2551
- this.mutationGuard = mutationGuard;
2552
- this.onChange = onChange;
2553
- const peer = doc.peerIdStr;
2554
- this.manager = new UndoManager(doc, {
2555
- mergeInterval: 0,
2556
- maxUndoSteps: 100,
2557
- excludeOriginPrefixes: ["mengine.bootstrap", "mengine.initialize"],
2558
- onPush: (_isUndo, range) => {
2559
- this.scheduleNotification();
2560
- return {
2561
- value: this.activeSource ?? {
2562
- peer,
2563
- counter: range.start
2564
- },
2565
- cursors: []
2566
- };
2567
- },
2568
- onPop: () => this.scheduleNotification()
2569
- });
2570
- this.unsubscribe = doc.subscribe(() => this.scheduleNotification());
2571
- }
2572
- getState() {
2573
- this.assertActive();
2574
- return {
2575
- canUndo: this.manager.canUndo(),
2576
- canRedo: this.manager.canRedo()
2577
- };
2578
- }
2579
- undo(options) {
2580
- return this.applyUndoRedo("Undo", options);
2581
- }
2582
- redo(options) {
2583
- return this.applyUndoRedo("Redo", options);
2584
- }
2585
- beginGroup() {
2586
- this.assertActive();
2587
- this.mutationGuard.run(() => this.manager.groupStart());
2588
- }
2589
- endGroup() {
2590
- this.assertActive();
2591
- this.mutationGuard.run(() => this.manager.groupEnd());
2592
- this.scheduleNotification();
2593
- }
2594
- applyUndoRedo(kind, options) {
2595
- this.assertActive();
2596
- return this.mutationGuard.run(() => {
2597
- if (kind === "Undo" ? !this.manager.canUndo() : !this.manager.canRedo()) return false;
2598
- this.activeSource = kind === "Undo" ? this.manager.topUndoValue() : this.manager.topRedoValue();
2599
- try {
2600
- this.doc.setNextCommitOptions({ message: JSON.stringify({
2601
- semantic_op: kind,
2602
- payload: { source: this.activeSource },
2603
- intent: options?.intent ?? null,
2604
- actor: options?.actor ?? null
2605
- }) });
2606
- const before = this.doc.oplogFrontiers();
2607
- return (kind === "Undo" ? this.manager.undo() : this.manager.redo()) && this.doc.cmpWithFrontiers(before) !== 0;
2608
- } finally {
2609
- this.doc.clearNextCommitOptions();
2610
- this.activeSource = null;
2611
- this.scheduleNotification();
2612
- }
2613
- });
2614
- }
2615
- dispose() {
2616
- if (this.disposed) return;
2617
- this.disposed = true;
2618
- this.unsubscribe();
2619
- this.manager.setOnPush(void 0);
2620
- this.manager.setOnPop(void 0);
2621
- this.manager.free();
2622
- }
2623
- scheduleNotification() {
2624
- if (this.notificationQueued || this.disposed) return;
2625
- this.notificationQueued = true;
2626
- queueMicrotask(() => {
2627
- this.notificationQueued = false;
2628
- if (!this.disposed) this.publish();
2629
- });
2630
- }
2631
- publish() {
2632
- if (this.disposed) return;
2633
- const state = this.getState();
2634
- if (state.canUndo === this.published.canUndo && state.canRedo === this.published.canRedo) return;
2635
- this.published = state;
2636
- this.onChange();
2637
- }
2638
- assertActive() {
2639
- if (this.disposed) throw new Error("mengine doc undo manager is disposed");
2640
- }
2641
- };
2642
- //#endregion
2643
4569
  //#region src/session/mengine-doc-session.ts
2644
4570
  /**
2645
4571
  * Raised by {@link MengineDocSession.waitForServerAck} when the local edits it
@@ -2675,9 +4601,13 @@ var MengineAckFailedError = class extends Error {
2675
4601
  * A live editing session for one Medeo document — the single entry point clients
2676
4602
  * (FE draft driver, Agent, embeds) use to open, edit, and observe a document.
2677
4603
  *
2678
- * SemanticEditor writes through MirrorVideoDocumentAdapter directly, while
2679
- * DocumentUndoManager observes the same LoroDoc independently. Both mutation
2680
- * paths use the session's DocumentMutationGuard, closed before teardown.
4604
+ * It assembles the engine sync stack around one Medeo document:
4605
+ *
4606
+ * local DocStorage ─┐
4607
+ * ├─ ClientServerSynchronizer ── DocManager ── LoroDoc
4608
+ * MedeoHttpDocStorage┘ │
4609
+ * (remote = Rust mengine-server) ▼
4610
+ * MirrorVideoDocumentAdapter + SemanticEditor
2681
4611
  *
2682
4612
  * `DocManager` owns the `LoroDoc`: local edits committed on the adapter are
2683
4613
  * picked up via `subscribeLocalUpdates`, saved to local storage, then pushed to
@@ -2698,19 +4628,11 @@ var MengineDocSession = class {
2698
4628
  manager;
2699
4629
  events = new EventBus();
2700
4630
  disposables = new DisposableSet();
2701
- mutationGuard = new DocumentMutationGuard();
2702
4631
  adapterValue = null;
2703
4632
  editorValue = null;
2704
- undoManagerValue = null;
2705
4633
  started = false;
2706
- destroyed = false;
2707
- lifetime = null;
2708
- hasConnected = false;
2709
- initialVersionValue = null;
2710
- localVersionValue = null;
2711
- pushErrorValue = null;
2712
4634
  /**
2713
- * Latest server oplog version seen on an authoritative HTTP response. Lets `waitForServerAck`
4635
+ * Latest server oplog version seen on a push outcome. Lets `waitForServerAck`
2714
4636
  * return without waiting when the server is already known to cover the local
2715
4637
  * doc (e.g. nothing was edited since the last confirmed push).
2716
4638
  */
@@ -2722,7 +4644,8 @@ var MengineDocSession = class {
2722
4644
  this.server = new MedeoHttpDocStorage({
2723
4645
  docId: options.docId,
2724
4646
  client: options.client,
2725
- sseReconnectDelayMs: options.sseReconnectDelayMs
4647
+ sseReconnectDelayMs: options.sseReconnectDelayMs,
4648
+ readonlyMode: options.readonlyMode
2726
4649
  });
2727
4650
  this.synchronizer = new ClientServerSynchronizer(this.local, this.server);
2728
4651
  this.manager = new DocManager(this.local, this.synchronizer);
@@ -2738,14 +4661,14 @@ var MengineDocSession = class {
2738
4661
  return this.server.subscribePushOutcome(callback);
2739
4662
  }
2740
4663
  /**
2741
- * Resolve once the server has durably accepted the local commits as of
4664
+ * Resolve once the server has durably accepted the local document state as of
2742
4665
  * *now* — the capability an Agent tool needs to answer "did my edit land?"
2743
4666
  * before reporting success.
2744
4667
  *
2745
4668
  * Call it right after the editor ops whose durability matters. It snapshots the
2746
- * latest local commit's version (or the loaded baseline before any edit) and
2747
- * resolves when an authoritative server version covers it. Remote-only
2748
- * imports do not extend this target, matching the displayed confirmation state.
4669
+ * local doc's current version and resolves on the first push outcome whose
4670
+ * `serverVV` covers that version, i.e. the server log is at least as advanced as
4671
+ * the local doc was when this was called.
2749
4672
  *
2750
4673
  * Version coverage, not byte identity, is the acceptance test — for two reasons:
2751
4674
  * the ops may reach the server inside a merged blob rather than as the exact
@@ -2760,39 +4683,31 @@ var MengineDocSession = class {
2760
4683
  * @throws {MengineAckFailedError} on timeout, rejection, or transport failure.
2761
4684
  */
2762
4685
  async waitForServerAck(options = {}) {
2763
- if (this.adapterValue == null || this.lifetime == null) throw new Error("mengine doc session is not started");
4686
+ if (this.adapterValue == null) throw new Error("mengine doc session is not started");
2764
4687
  const timeoutMs = options.timeoutMs ?? 15e3;
2765
- const target = this.confirmationTarget() ?? this.manager.connectDoc(this.docId).version();
2766
- const signal = this.lifetime.signal;
4688
+ const target = this.manager.connectDoc(this.docId).version();
2767
4689
  if (this.serverVVValue != null && serverCovers(this.serverVVValue, target)) return;
2768
4690
  await new Promise((resolve, reject) => {
2769
- const cleanup = [];
4691
+ let off = () => {};
2770
4692
  let done = false;
2771
4693
  const settle = (error) => {
2772
4694
  if (done) return;
2773
4695
  done = true;
2774
4696
  clearTimeout(timer);
2775
- cleanup.forEach((off) => off());
4697
+ off();
2776
4698
  if (error == null) resolve();
2777
4699
  else reject(error);
2778
4700
  };
2779
4701
  const timer = setTimeout(() => {
2780
4702
  settle(new MengineAckFailedError("timeout", void 0, void 0, `mengine did not acknowledge the update within ${timeoutMs}ms`));
2781
4703
  }, timeoutMs);
2782
- const onAbort = () => settle(new MengineAckFailedError("failed", void 0, void 0, "mengine doc session destroyed"));
2783
- signal.addEventListener("abort", onAbort, { once: true });
2784
- cleanup.push(() => signal.removeEventListener("abort", onAbort));
2785
- cleanup.push(this.events.on("syncState", () => {
2786
- if (this.serverVVValue != null && serverCovers(this.serverVVValue, target)) settle(void 0);
2787
- }));
2788
- cleanup.push(this.server.subscribePushOutcome((outcome) => {
4704
+ off = this.server.subscribePushOutcome((outcome) => {
2789
4705
  if (outcome.kind === "rejected" || outcome.kind === "failed") {
2790
4706
  settle(new MengineAckFailedError(outcome.kind, outcome.code, outcome.error, outcome.error?.message ?? `mengine push ${outcome.kind}`));
2791
4707
  return;
2792
4708
  }
2793
- }));
2794
- if (signal.aborted) onAbort();
2795
- else this.synchronizer.requestSync(this.docId);
4709
+ if (outcome.serverVV != null && serverCovers(outcome.serverVV, target)) settle(void 0);
4710
+ });
2796
4711
  });
2797
4712
  }
2798
4713
  /**
@@ -2805,63 +4720,28 @@ var MengineDocSession = class {
2805
4720
  if (this.editorValue == null) throw new Error("mengine doc session is not started");
2806
4721
  return this.editorValue;
2807
4722
  }
2808
- /** Current document snapshot (read model). */
2809
- snapshot() {
2810
- if (this.adapterValue == null) throw new Error("mengine doc session is not started");
2811
- return this.adapterValue.snapshot();
2812
- }
2813
- /** Current-session undo/redo availability. Loading and closed sessions report false. */
2814
- getUndoState() {
2815
- return this.undoManagerValue?.getState() ?? {
2816
- canUndo: false,
2817
- canRedo: false
2818
- };
2819
- }
2820
- /**
2821
- * Supplies current availability immediately, then coalesces stack changes in a
2822
- * microtask. Session teardown publishes empty availability synchronously.
2823
- */
2824
- subscribeUndoState(cb) {
2825
- const notify = () => cb(this.getUndoState());
2826
- const off = this.destroyed ? () => {} : this.events.on("undoState", notify);
2827
- notify();
2828
- return off;
2829
- }
2830
- /**
2831
- * Undo a local edit immediately; server confirmation remains asynchronous.
2832
- * On a shared LWW field this writes its prior value, potentially overwriting a
2833
- * later remote edit to that same field. Returns false if no update is produced.
2834
- */
2835
- undo(options) {
2836
- if (this.undoManagerValue == null) throw new Error("mengine doc undo manager is not ready");
2837
- return this.undoManagerValue.undo(options);
2838
- }
2839
4723
  /**
2840
- * Restore the state visible before undo without rerunning external side effects.
2841
- * Returns false if no update is produced; durable confirmation is separate.
4724
+ * Opaque version token of the local oplog (base64 `VersionVector.encode`).
4725
+ * Equality-comparable only: equal means no observed change (local or
4726
+ * remote-arrived) since the token was taken. Throws when not started.
2842
4727
  */
2843
- redo(options) {
2844
- if (this.undoManagerValue == null) throw new Error("mengine doc undo manager is not ready");
2845
- return this.undoManagerValue.redo(options);
4728
+ version() {
4729
+ if (this.adapterValue == null) throw new Error("mengine doc session is not started");
4730
+ return bytesToBase64(this.adapterValue.doc.oplogVersion().encode());
2846
4731
  }
2847
4732
  /**
2848
- * Combine existing semantic operations (e.g. trim a clip and adjust its volume)
2849
- * or repeated commits during one drag gesture into a single undo step. A gesture
2850
- * that only previews locally and commits once on release needs no group.
2851
- * Each commit is immediately visible locally and enters sync independently;
2852
- * a later failure does not roll it back.
2853
- * Always pair with endUndoGroup in a finally block. Conflicting remote imports
2854
- * can end/split the group early, and unrelated local edits would join it.
2855
- * Complete asynchronous asset preparation before opening the group.
4733
+ * The live document adapter, exposed for journal replay (commit channel).
4734
+ * Replaying through it still goes SemanticEditor → Loro → mengine-server —
4735
+ * no write bypass. Typed by the narrow interface on purpose.
2856
4736
  */
2857
- beginUndoGroup() {
2858
- if (this.undoManagerValue == null) throw new Error("mengine doc undo manager is not ready");
2859
- this.undoManagerValue.beginGroup();
4737
+ get documentAdapter() {
4738
+ if (this.adapterValue == null) throw new Error("mengine doc session is not started");
4739
+ return this.adapterValue;
2860
4740
  }
2861
- /** End a gesture, including one already split by a conflicting remote import. */
2862
- endUndoGroup() {
2863
- if (this.undoManagerValue == null) throw new Error("mengine doc undo manager is not ready");
2864
- this.undoManagerValue.endGroup();
4741
+ /** Current document snapshot (read model). */
4742
+ snapshot() {
4743
+ if (this.adapterValue == null) throw new Error("mengine doc session is not started");
4744
+ return this.adapterValue.snapshot();
2865
4745
  }
2866
4746
  /**
2867
4747
  * Start the sync stack and connect the document.
@@ -2871,23 +4751,8 @@ var MengineDocSession = class {
2871
4751
  * surfaces through `subscribe`.
2872
4752
  */
2873
4753
  async start() {
2874
- if (this.destroyed) throw new Error("mengine doc session destroyed");
2875
4754
  if (this.started) return this.snapshot();
2876
4755
  this.started = true;
2877
- this.lifetime = new AbortController();
2878
- this.disposables.add(this.server.subscribeServerVersion((version) => {
2879
- this.serverVVValue = version;
2880
- if (this.getSyncState().confirmation === "confirmed") this.pushErrorValue = null;
2881
- this.emitSyncState();
2882
- }));
2883
- this.disposables.add(this.server.subscribePushOutcome((outcome) => {
2884
- this.pushErrorValue = outcome.kind === "failed" || outcome.kind === "rejected" ? outcome.error ?? /* @__PURE__ */ new Error(`mengine push ${outcome.kind}`) : null;
2885
- this.emitSyncState();
2886
- }));
2887
- this.disposables.add(this.server.connection.onStatusChanged((status) => {
2888
- if (status === "connected") this.hasConnected = true;
2889
- this.emitSyncState();
2890
- }));
2891
4756
  this.local.connection.connect();
2892
4757
  this.server.connection.connect();
2893
4758
  this.disposables.add(() => this.local.connection.disconnect());
@@ -2898,53 +4763,24 @@ var MengineDocSession = class {
2898
4763
  this.disposables.add(() => this.manager.stop());
2899
4764
  const doc = this.manager.connectDoc(this.docId);
2900
4765
  if (this.options.peerId != null) doc.setPeerId(this.options.peerId);
2901
- this.adapterValue = new MirrorVideoDocumentAdapter(doc, this.mutationGuard);
4766
+ this.adapterValue = new MirrorVideoDocumentAdapter(doc);
4767
+ this.editorValue = new SemanticEditor(this.adapterValue);
2902
4768
  this.disposables.add(() => this.manager.disconnectDoc(this.docId));
2903
4769
  const unsubscribe = doc.subscribe((event) => {
2904
4770
  if (this.adapterValue == null) return;
2905
- if (this.initialVersionValue == null && this.hasContent()) this.initialVersionValue = doc.version();
2906
- if (event.by === "local") this.localVersionValue = doc.version();
2907
- this.emitSyncState();
2908
4771
  this.events.emit("update", {
2909
4772
  source: event.by === "local" ? "local" : "remote",
2910
4773
  snapshot: this.adapterValue.snapshot()
2911
4774
  });
2912
4775
  });
2913
4776
  this.disposables.add(unsubscribe);
2914
- this.disposables.add(this.manager.onDocStateChange(this.docId, (state) => {
2915
- this.events.emit("state", state);
2916
- this.emitSyncState();
4777
+ this.disposables.add(this.manager.onDocStateChange(this.docId, (state) => this.events.emit("state", state)));
4778
+ this.disposables.add(this.server.subscribePushOutcome((outcome) => {
4779
+ if (outcome.serverVV != null) this.serverVVValue = outcome.serverVV;
2917
4780
  }));
2918
4781
  await this.waitForContent();
2919
- if (this.destroyed) throw new Error("mengine doc session destroyed");
2920
- this.undoManagerValue = new DocumentUndoManager(doc, this.mutationGuard, () => this.events.emit("undoState"));
2921
- this.editorValue = new SemanticEditor(this.adapterValue);
2922
- this.initialVersionValue ??= doc.version();
2923
- this.emitSyncState();
2924
4782
  return this.snapshot();
2925
4783
  }
2926
- getSyncState() {
2927
- const state = this.getState();
2928
- const target = this.confirmationTarget();
2929
- const confirmation = this.serverVVValue == null || target == null ? this.localVersionValue == null ? "unknown" : "pending" : serverCovers(this.serverVVValue, target) ? "confirmed" : "pending";
2930
- const connection = !this.started ? "disconnected" : this.server.connection.status === "connected" ? "connected" : this.hasConnected || this.server.connection.error != null ? "disconnected" : "connecting";
2931
- return {
2932
- confirmation,
2933
- phase: connection === "disconnected" ? "offline" : this.pushErrorValue != null || state.error != null ? "failed" : connection === "connecting" ? "connecting" : state.syncing ? "syncing" : "idle"
2934
- };
2935
- }
2936
- confirmationTarget() {
2937
- return this.localVersionValue ?? this.initialVersionValue;
2938
- }
2939
- /** Immediately supplies current state; unsubscribe when the host changes docs. */
2940
- subscribeSyncState(cb) {
2941
- const off = this.events.on("syncState", cb);
2942
- cb(this.getSyncState());
2943
- return off;
2944
- }
2945
- emitSyncState() {
2946
- this.events.emit("syncState", this.getSyncState());
2947
- }
2948
4784
  subscribe(cb) {
2949
4785
  return this.events.on("update", cb);
2950
4786
  }
@@ -2955,18 +4791,8 @@ var MengineDocSession = class {
2955
4791
  return this.manager.getDocState(this.docId);
2956
4792
  }
2957
4793
  destroy() {
2958
- if (this.destroyed) return;
2959
- this.destroyed = true;
2960
- this.mutationGuard.close();
2961
- this.started = false;
2962
- this.lifetime?.abort();
2963
- this.undoManagerValue?.dispose();
2964
- this.undoManagerValue = null;
2965
- this.events.emit("undoState");
2966
4794
  this.disposables.dispose();
2967
- this.emitSyncState();
2968
4795
  this.events.clearAll();
2969
- this.adapterValue?.dispose();
2970
4796
  this.adapterValue = null;
2971
4797
  this.editorValue = null;
2972
4798
  this.started = false;
@@ -2982,21 +4808,13 @@ var MengineDocSession = class {
2982
4808
  */
2983
4809
  async waitForContent() {
2984
4810
  if (this.hasContent()) return;
2985
- const signal = this.lifetime.signal;
2986
- await new Promise((resolve, reject) => {
2987
- const onAbort = () => {
2988
- off();
2989
- reject(/* @__PURE__ */ new Error("mengine doc session destroyed"));
2990
- };
4811
+ await new Promise((resolve) => {
2991
4812
  const off = this.events.on("update", () => {
2992
4813
  if (this.hasContent()) {
2993
4814
  off();
2994
- signal.removeEventListener("abort", onAbort);
2995
4815
  resolve();
2996
4816
  }
2997
4817
  });
2998
- signal.addEventListener("abort", onAbort, { once: true });
2999
- if (signal.aborted) onAbort();
3000
4818
  });
3001
4819
  }
3002
4820
  hasContent() {
@@ -3030,4 +4848,4 @@ function serverCovers(serverVV, target) {
3030
4848
  return covers(server, target);
3031
4849
  }
3032
4850
  //#endregion
3033
- export { DEFAULT_UNIT_TIME_MS, IMPLEMENTED_SEMANTIC_OP_KINDS, LANE_KINDS_IN_STACK_ORDER, ManualSyncDoc, MedeoHttpDocStorage, MemoryDocStorage, MengineAckFailedError, MengineDocSession, MengineHttpClient, MengineHttpRequestError, MenginePushRejectedError, MirrorVideoDocumentAdapter, SchemaValidator, SemanticEditor, TIMELINE_SKELETON_DURATION_MS, VIDEO_DOCUMENT_SCHEMA_VERSION, ValidationError, VideoDocumentValidationError, arrangeMainTrackSeamlessly, assertValidVideoDocument, base64ToBytes, buildInitialVideoDocument, buildSpeechHostMap, bytesToBase64, cascadeAfterVideoClipChanges, createMirrorVideoDocument, createMirrorVideoDocumentAdapter, decodeDocVersionMark, derivePositionFromAbs, encodeDocVersionMark, ensureLaneTrack, fillMainTrackTimeGaps, findLaneTrack, fromVideoDocument, generatePartId, getAt, hostForAbsMs, isEmptyVideoClip, isImplementedSemanticOpKind, isMap, laneTrackId, mainTrackRanges, partDurationMs, partUnionSchema, readMainTrackItems, readMengineEventStream, readPart, readPartDurationMs, readVideoDocumentFromDraft, reassignSpeechesToVideoClipsByTime, recalculateTimelineDuration, relativePositionForAbs, resolveAllSpeechOverlaps, resolveSpeechOverlapByShiftingVideos, safeDurationMs, schemas_exports as schemas, snapshotToPlain, solveVideoDocument, syncAggregatedClipsTimePosition, toVideoDocument, validateVideoDocument, videoDocumentMirrorSchema, videoDocumentSchema };
4851
+ export { DEFAULT_UNIT_TIME_MS, ENTITY_TIMELINE_PROJECTION_SCHEMA_VERSION, EntityGraphHttpClient, EntityTimelineEditor, EntityTimelineProjectionError, IMPLEMENTED_SEMANTIC_OP_KINDS, LANE_KINDS_IN_STACK_ORDER, LORO_ENTITY_SCHEMA, LoroEntityDocument, LoroEntityDraft, ManualSyncDoc, MedeoHttpDocStorage, MemoryDocStorage, MengineAckFailedError, MengineDocSession, MengineHttpClient, MengineHttpRequestError, MenginePushRejectedError, MirrorVideoDocumentAdapter, PlainMemoryAdapter, SchemaValidator, ScriptCompositionError, SemanticEditor, TIMELINE_SKELETON_DURATION_MS, VIDEO_DOCUMENT_SCHEMA_VERSION, ValidationError, VideoDocumentValidationError, applyEntityRows, applyEntityTimelineProjection, arrangeMainTrackSeamlessly, assembleCaptionContent, assembleEntityContent, assemblePhoneticScriptContent, assembleScriptText, assertCanonicalEditorResources, assertEntityProjectionPreservesLegacy, assertMediaAssetWritePolicy, assertValidVideoDocument, base64ToBytes, buildInitialVideoDocument, buildSpeechHostMap, bytesToBase64, cascadeAfterVideoClipChanges, compileEntityRows, createEditSandbox, createMirrorVideoDocument, createMirrorVideoDocumentAdapter, createPlainMemoryAdapter, decodeDocVersionMark, derivePositionFromAbs, effectiveVideoClipDurationMs, encodeDocVersionMark, ensureEditorFoundation, ensureLaneTrack, fillMainTrackTimeGaps, findComposedAudioScript, findLaneTrack, fromVideoDocument, generatePartId, getAt, hostForAbsMs, importMediaAsset, isEmptyVideoClip, isImplementedSemanticOpKind, isMap, laneTrackId, mainTrackRanges, migrateLegacyTimelineToEntities, partDurationMs, partUnionSchema, prepareCaptionContent, projectEntityTimeline, readDocumentAudioScript, readEntityDocument, readMainTrackItems, readMengineEventStream, readPart, readPartDurationMs, readVideoDocumentFromDraft, reassignSpeechesToVideoClipsByTime, recalculateTimelineDuration, relativePositionForAbs, replayJournal, resolveAllSpeechOverlaps, resolveEntityTimelineLayout, resolveSpeechOverlapByShiftingVideos, safeDurationMs, schemas_exports as schemas, selectAudioScriptSegments, snapshotToPlain, solveVideoDocument, speedOf, syncAggregatedClipsTimePosition, toVideoDocument, validateVideoDocument, videoDocumentMirrorSchema, videoDocumentSchema, writeVideoDocumentToDraft };