@mengine/medeo-client 1.2.1-alpha.0 → 1.2.1-alpha.10

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,4 +1,4 @@
1
- import { A as resolveSpeechOverlapByShiftingVideos, B as partUnionToDraft, C as solveVideoDocument, D as reassignSpeechesToVideoClipsByTime, E as fillMainTrackTimeGaps, F as safeDurationMs, H as videoDocumentMirrorSchema, I as DEFAULT_UNIT_TIME_MS, L as VIDEO_DOCUMENT_SCHEMA_VERSION, M as TIMELINE_SKELETON_DURATION_MS, N as isEmptyVideoClip, O as recalculateTimelineDuration, P as partDurationMs, R as effectiveVideoClipDurationMs, S as laneTrackId, T as arrangeMainTrackSeamlessly, U as base64ToBytes, V as recordEntries, W as bytesToBase64, _ as partUnionSchema, a as createMirrorVideoDocument, b as ensureLaneTrack, c as readVideoDocumentFromDraft, d as derivePositionFromAbs, f as fromVideoDocument, g as validateVideoDocument, h as assertValidVideoDocument, i as MirrorVideoDocumentAdapter, j as syncAggregatedClipsTimePosition, k as resolveAllSpeechOverlaps, l as buildInitialVideoDocument, m as VideoDocumentValidationError, n as createPlainMemoryAdapter, o as createMirrorVideoDocumentAdapter, p as toVideoDocument, r as generatePartId, s as writeVideoDocumentToDraft, t as PlainMemoryAdapter, u as buildSpeechHostMap, v as videoDocumentSchema, w as cascadeAfterVideoClipChanges, x as findLaneTrack, y as LANE_KINDS_IN_STACK_ORDER, z as speedOf } from "./document-49OdvviW.js";
1
+ import { $ as videoDocumentMirrorSchema, A as ensureLaneTrack, B as resolveSpeechOverlapByShiftingVideos, C as toVideoDocument, D as partUnionSchema, E as validateVideoDocument, F as arrangeMainTrackSeamlessly, G as safeDurationMs, H as TIMELINE_SKELETON_DURATION_MS, I as fillMainTrackTimeGaps, J as VIDEO_DOCUMENT_SCHEMA_VERSION, K as DEFAULT_UNIT_TIME_MS, L as reassignSpeechesToVideoClipsByTime, M as laneTrackId, N as solveVideoDocument, O as videoDocumentSchema, P as cascadeAfterVideoClipChanges, Q as recordEntries, R as recalculateTimelineDuration, S as fromVideoDocument, T as assertValidVideoDocument, U as isEmptyVideoClip, V as syncAggregatedClipsTimePosition, W as partDurationMs, X as speedOf, Y as effectiveVideoClipDurationMs, Z as partUnionToDraft, _ as hasSequence, a as applyEntityTimelineProjection, b as buildSpeechHostMap, c as writeVideoDocumentToDraft, d as resolveEntityTimelineLayout, et as base64ToBytes, f as EntityTimelineProjectionError, g as createRelationId, h as createEntityId, i as MirrorVideoDocumentAdapter, j as findLaneTrack, k as LANE_KINDS_IN_STACK_ORDER, l as readVideoDocumentFromDraft, m as isJsonObject, n as createPlainMemoryAdapter, o as createMirrorVideoDocument, p as decodeEntityRelationRows, q as ENTITY_TIMELINE_PROJECTION_SCHEMA_VERSION, r as generatePartId, s as createMirrorVideoDocumentAdapter, t as PlainMemoryAdapter, tt as bytesToBase64, u as projectEntityTimeline, v as isMediaAssetVariantKind, w as VideoDocumentValidationError, x as derivePositionFromAbs, y as buildInitialVideoDocument, z as resolveAllSpeechOverlaps } from "./document-CC9M0bf9.js";
2
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
3
  import { LoroDoc, VersionVector } from "loro-crdt";
4
4
  import { ClientServerSynchronizer, DocManager } from "@mengine/sync";
@@ -12,7 +12,7 @@ import { BaseDocStorage, DummyConnection } from "@mengine/storage";
12
12
  * namespace (mirrors the cluster's `/oapi/v1` precedent for an independent
13
13
  * subsystem) rather than folding into the shared `/api/v2/*` space.
14
14
  */
15
- const MENGINE_API_PREFIX = "/api/mengine/v1";
15
+ const MENGINE_API_PREFIX$1 = "/api/mengine/v1";
16
16
  var MengineHttpRequestError = class extends Error {
17
17
  status;
18
18
  payload;
@@ -134,12 +134,12 @@ var MengineHttpClient = class {
134
134
  ...init,
135
135
  headers
136
136
  });
137
- const payload = await safeReadJson(response);
137
+ const payload = await safeReadJson$1(response);
138
138
  if (!response.ok) throw new MengineHttpRequestError(response.status, payload);
139
139
  return payload;
140
140
  }
141
141
  endpoint(path) {
142
- 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}`;
143
143
  }
144
144
  };
145
145
  /**
@@ -156,7 +156,7 @@ function asPushRejection(error) {
156
156
  if (body.kind !== "rejected" || typeof body.code !== "string") return void 0;
157
157
  return new MenginePushRejectedError(body.code, body.message ?? "", body.server_version, error.status);
158
158
  }
159
- async function safeReadJson(response) {
159
+ async function safeReadJson$1(response) {
160
160
  const text = await response.text();
161
161
  if (text.length === 0) return null;
162
162
  try {
@@ -217,6 +217,2307 @@ function findSseFrameBoundary(buffer) {
217
217
  return Math.min(lf, crlf);
218
218
  }
219
219
  //#endregion
220
+ //#region src/entity-editor/editor-resources.ts
221
+ const roleOrder$1 = {
222
+ caption: 0,
223
+ video_clip: 1,
224
+ speech: 2,
225
+ bgm: 3
226
+ };
227
+ /**
228
+ * MEngine editor policy, not a cardinality restriction on the general-purpose DSL.
229
+ *
230
+ * Media variants share one entity identity with their Asset: every
231
+ * Image/Video/Audio/Voice Entity must carry its own external locator, every
232
+ * external asset id has exactly one claimant, and no media variant may be
233
+ * bound through a legacy `physical-asset` Relation. Dual-entity media graphs
234
+ * are rejected, not migrated. Caption inline text keeps its inline Asset and
235
+ * `physical-asset` binding.
236
+ */
237
+ function assertCanonicalEditorResources(rows) {
238
+ if (rows.entities.filter((row) => row.entityKind === "timeline").length > 1) throw new EntityTimelineProjectionError("Editor requires exactly one Timeline");
239
+ 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`);
240
+ const identityByAssetKey = /* @__PURE__ */ new Map();
241
+ const kinds = new Map(rows.entities.map((row) => [String(row.entityId), row.entityKind]));
242
+ for (const entity of rows.entities) {
243
+ if (isMediaAssetVariantKind(entity.entityKind) && memotaLocator(entity.payload.external) === void 0) throw new EntityTimelineProjectionError(`Media Entity ${entity.entityId} must carry its own Asset external identity`);
244
+ if (entity.entityKind !== "asset" && !isMediaAssetVariantKind(entity.entityKind)) continue;
245
+ const external = entity.payload.external;
246
+ if (!isJsonObject(external) || external.system !== "memota" && external.system !== "memota-speech" || typeof external.key !== "string") continue;
247
+ const key = JSON.stringify([external.system, external.key]);
248
+ const previous = identityByAssetKey.get(key);
249
+ if (previous !== void 0 && previous !== entity.entityId) throw new EntityTimelineProjectionError(`Duplicate Asset for ${key}; reuse ${previous}`);
250
+ identityByAssetKey.set(key, entity.entityId);
251
+ }
252
+ for (const relation of rows.relations) {
253
+ if (relation.relationKind !== "physical-asset") continue;
254
+ const mediaEndpoint = [relation.endpoint0EntityId, relation.endpoint1EntityId].find((endpoint) => isMediaAssetVariantKind(kinds.get(String(endpoint)) ?? ""));
255
+ if (mediaEndpoint !== void 0) throw new EntityTimelineProjectionError(`Cannot bind media Entity ${mediaEndpoint} through physical-asset Relation ${relation.relationId}; media owns its Asset identity directly`);
256
+ }
257
+ }
258
+ /**
259
+ * Commit-transition policy shared by the editor, the HTTP commit boundary, the
260
+ * host tool, and the entity stores. It compares the authoritative before and
261
+ * after rows of one CAS commit and enforces the single-identity write rules
262
+ * on the complete after state, with no exemption for historical graphs:
263
+ *
264
+ * 1. every Image/Video/Audio/Voice Entity carries its own Asset `external`
265
+ * identity;
266
+ * 2. no `physical-asset` Relation may bind a media variant (Caption inline
267
+ * text keeps its inline Asset and binding);
268
+ * 3. a self-carried media identity is immutable — it cannot be rewritten to
269
+ * another asset id.
270
+ *
271
+ * Dual-entity media graphs are rejected instead of being migrated or merged
272
+ * implicitly. Deleting media is explicit and allowed.
273
+ */
274
+ function assertMediaAssetWritePolicy(before, after) {
275
+ const beforeEntities = new Map(before.entities.map((row) => [String(row.entityId), row]));
276
+ const afterKinds = new Map(after.entities.map((row) => [String(row.entityId), row.entityKind]));
277
+ for (const row of after.entities) {
278
+ if (!isMediaAssetVariantKind(row.entityKind)) continue;
279
+ if (memotaLocator(row.payload.external) === void 0) throw new EntityTimelineProjectionError(`Media Entity ${row.entityId} must carry its own Asset external identity`);
280
+ }
281
+ for (const relation of after.relations) {
282
+ if (relation.relationKind !== "physical-asset") continue;
283
+ const mediaEndpoint = [relation.endpoint0EntityId, relation.endpoint1EntityId].find((endpoint) => isMediaAssetVariantKind(afterKinds.get(String(endpoint)) ?? ""));
284
+ if (mediaEndpoint !== void 0) throw new EntityTimelineProjectionError(`Cannot bind media Entity ${mediaEndpoint} through physical-asset Relation ${relation.relationId}; media owns its Asset identity directly`);
285
+ }
286
+ for (const row of after.entities) {
287
+ if (!isMediaAssetVariantKind(row.entityKind)) continue;
288
+ const priorExternal = memotaLocator(beforeEntities.get(String(row.entityId))?.payload.external);
289
+ if (priorExternal === void 0) continue;
290
+ const nextExternal = memotaLocator(row.payload.external);
291
+ 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`);
292
+ }
293
+ }
294
+ function memotaLocator(value) {
295
+ if (!isJsonObject(value) || value.system !== "memota" && value.system !== "memota-speech" || typeof value.key !== "string" || value.key.trim() === "") return;
296
+ return {
297
+ system: value.system,
298
+ key: value.key
299
+ };
300
+ }
301
+ /** Add only missing editor structure; existing identities and owned settings are never replaced. */
302
+ function ensureEditorFoundation(initial, idFactory = (prefix) => `${prefix}_${globalThis.crypto.randomUUID()}`, timelinePayload = {}) {
303
+ const entities = structuredClone([...initial.entities]);
304
+ const relations = structuredClone([...initial.relations]);
305
+ const roots = entities.filter((row) => row.entityKind === "timeline");
306
+ if (roots.length > 1) throw new EntityTimelineProjectionError("Editor requires exactly one Timeline");
307
+ const mintEntity = () => {
308
+ const id = createEntityId(idFactory("entity"));
309
+ if (entities.some((row) => row.entityId === id)) throw new Error(`Duplicate entity id ${id}`);
310
+ return id;
311
+ };
312
+ let timeline = roots[0];
313
+ if (timeline === void 0) {
314
+ timeline = {
315
+ entityId: mintEntity(),
316
+ entityKind: "timeline",
317
+ payload: structuredClone(timelinePayload)
318
+ };
319
+ entities.push(timeline);
320
+ }
321
+ const trackEntityIds = {};
322
+ for (const role of Object.keys(roleOrder$1)) {
323
+ const matches = entities.filter((row) => row.entityKind === "track" && row.payload.role === role);
324
+ if (matches.length > 1) throw new EntityTimelineProjectionError(`Editor has multiple ${role} Tracks`);
325
+ let track = matches[0];
326
+ if (track === void 0) {
327
+ track = {
328
+ entityId: mintEntity(),
329
+ entityKind: "track",
330
+ payload: {
331
+ role,
332
+ order: roleOrder$1[role]
333
+ }
334
+ };
335
+ entities.push(track);
336
+ }
337
+ const bindings = relations.filter((row) => row.relationKind === "timeline-track" && (row.endpoint0EntityId === track.entityId || row.endpoint1EntityId === track.entityId));
338
+ if (bindings.some((row) => row.endpoint0EntityId !== timeline.entityId && row.endpoint1EntityId !== timeline.entityId)) throw new EntityTimelineProjectionError(`Track ${track.entityId} belongs to another Timeline`);
339
+ if (bindings.length === 0) {
340
+ const relationId = createRelationId(idFactory("relation"));
341
+ if (relations.some((row) => row.relationId === relationId)) throw new Error(`Duplicate relation id ${relationId}`);
342
+ relations.push({
343
+ relationId,
344
+ relationKind: "timeline-track",
345
+ endpoint0EntityId: timeline.entityId,
346
+ endpoint1EntityId: track.entityId,
347
+ metadata: {},
348
+ trace: {}
349
+ });
350
+ }
351
+ trackEntityIds[role] = track.entityId;
352
+ }
353
+ return {
354
+ rows: {
355
+ entities,
356
+ relations
357
+ },
358
+ timelineEntityId: timeline.entityId,
359
+ trackEntityIds
360
+ };
361
+ }
362
+ //#endregion
363
+ //#region src/entity-editor/entity-graph-http-client.ts
364
+ const MENGINE_API_PREFIX = "/api/mengine/v1";
365
+ const numericMarkerValidation$1 = { compareMarkerPoints: (_marker, _range, left, right) => {
366
+ if (typeof left !== "number" || !Number.isFinite(left) || typeof right !== "number" || !Number.isFinite(right)) throw new Error("entity-state requires finite numeric Marker coordinates");
367
+ return left < right ? -1 : left > right ? 1 : 0;
368
+ } };
369
+ /** Browser-safe authenticated CAS client for a document's Entity graph. */
370
+ var EntityGraphHttpClient = class {
371
+ options;
372
+ transport;
373
+ endpoint;
374
+ constructor(options) {
375
+ this.options = options;
376
+ this.transport = new MengineHttpClient(options);
377
+ const origin = options.httpOrigin.replace(/\/$/, "");
378
+ this.endpoint = `${origin}${MENGINE_API_PREFIX}/docs/${encodeURIComponent(options.docId)}/entity-state`;
379
+ }
380
+ async fetchState() {
381
+ return this.request({ method: "GET" });
382
+ }
383
+ /**
384
+ * Replace the complete Entity graph under the baseline revision.
385
+ *
386
+ * Deletion intent is derived from baseline IDs omitted from `nextRows`, so a
387
+ * transient create-then-remove never becomes a request to delete unknown
388
+ * persisted data.
389
+ */
390
+ async commit(baseState, nextRows, options = {}) {
391
+ if (!isNonNegativeSafeInteger(baseState.revision)) throw new Error("Entity graph revision must be a non-negative safe integer");
392
+ const baseRows = cloneAndValidateRows(baseState.rows);
393
+ const next = cloneAndValidateRows(nextRows);
394
+ assertMediaAssetWritePolicy(baseRows, next);
395
+ const nextEntityIds = new Set(next.entities.map((row) => row.entityId));
396
+ const nextRelationIds = new Set(next.relations.map((row) => row.relationId));
397
+ const deletedEntityIds = baseRows.entities.map((row) => row.entityId).filter((entityId) => !nextEntityIds.has(entityId)).sort();
398
+ const deletedRelationIds = baseRows.relations.map((row) => row.relationId).filter((relationId) => !nextRelationIds.has(relationId)).sort();
399
+ return this.request({
400
+ method: "POST",
401
+ body: JSON.stringify({
402
+ expected_revision: baseState.revision,
403
+ rows: toWireRows(next),
404
+ deleted_entity_ids: deletedEntityIds,
405
+ deleted_relation_ids: deletedRelationIds,
406
+ ...options.migrationBaseVv === void 0 ? {} : { migration_base_vv: options.migrationBaseVv }
407
+ })
408
+ });
409
+ }
410
+ async request(init) {
411
+ const response = await this.transport.fetch(this.endpoint, {
412
+ ...init,
413
+ headers: this.transport.headers()
414
+ });
415
+ const payload = await safeReadJson(response);
416
+ if (!response.ok) throw new MengineHttpRequestError(response.status, payload);
417
+ return parseWireState(payload, this.options.docId);
418
+ }
419
+ };
420
+ function parseWireState(value, expectedDocId) {
421
+ if (!isRecord(value) || typeof value.doc_id !== "string" || !isNonNegativeSafeInteger(value.revision)) throw new Error("Invalid entity-state response envelope");
422
+ if (value.doc_id !== expectedDocId) throw new Error(`Entity-state response doc_id mismatch: expected "${expectedDocId}"`);
423
+ const rows = parseWireRows(value.rows);
424
+ decodeEntityRelationRows(rows, numericMarkerValidation$1);
425
+ return {
426
+ revision: value.revision,
427
+ rows
428
+ };
429
+ }
430
+ function parseWireRows(value) {
431
+ if (!isRecord(value) || !Array.isArray(value.entities) || !Array.isArray(value.relations)) throw new Error("Invalid entity-state response rows");
432
+ return {
433
+ entities: value.entities.map(parseWireEntity),
434
+ relations: value.relations.map(parseWireRelation)
435
+ };
436
+ }
437
+ function parseWireEntity(value) {
438
+ if (!isRecord(value) || !isJsonObject(value.payload)) throw new Error("Invalid Entity row in entity-state response");
439
+ return {
440
+ entityId: createEntityId(requiredString(value.entity_id, "entity_id")),
441
+ entityKind: requiredString(value.entity_kind, "entity_kind"),
442
+ payload: structuredClone(value.payload)
443
+ };
444
+ }
445
+ function parseWireRelation(value) {
446
+ if (!isRecord(value) || !isJsonObject(value.metadata) || !isJsonObject(value.trace)) throw new Error("Invalid Relation row in entity-state response");
447
+ return {
448
+ relationId: createRelationId(requiredString(value.relation_id, "relation_id")),
449
+ relationKind: requiredString(value.relation_kind, "relation_kind"),
450
+ endpoint0EntityId: createEntityId(requiredString(value.endpoint_0_entity_id, "endpoint_0_entity_id")),
451
+ endpoint1EntityId: createEntityId(requiredString(value.endpoint_1_entity_id, "endpoint_1_entity_id")),
452
+ metadata: structuredClone(value.metadata),
453
+ trace: structuredClone(value.trace)
454
+ };
455
+ }
456
+ function cloneAndValidateRows(rows) {
457
+ const clone = structuredClone(rows);
458
+ decodeEntityRelationRows(clone, numericMarkerValidation$1);
459
+ return clone;
460
+ }
461
+ function toWireRows(rows) {
462
+ return {
463
+ entities: rows.entities.map((row) => ({
464
+ entity_id: row.entityId,
465
+ entity_kind: row.entityKind,
466
+ payload: row.payload
467
+ })),
468
+ relations: rows.relations.map((row) => ({
469
+ relation_id: row.relationId,
470
+ relation_kind: row.relationKind,
471
+ endpoint_0_entity_id: row.endpoint0EntityId,
472
+ endpoint_1_entity_id: row.endpoint1EntityId,
473
+ metadata: row.metadata,
474
+ trace: row.trace
475
+ }))
476
+ };
477
+ }
478
+ function requiredString(value, field) {
479
+ if (typeof value !== "string" || value.length === 0 || value.trim() !== value) throw new Error(`Invalid ${field} in entity-state response`);
480
+ return value;
481
+ }
482
+ function isRecord(value) {
483
+ return value !== null && typeof value === "object" && !Array.isArray(value);
484
+ }
485
+ function isNonNegativeSafeInteger(value) {
486
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
487
+ }
488
+ async function safeReadJson(response) {
489
+ const text = await response.text();
490
+ if (text.length === 0) return null;
491
+ try {
492
+ return JSON.parse(text);
493
+ } catch {
494
+ return text;
495
+ }
496
+ }
497
+ //#endregion
498
+ //#region src/entity-editor/media-asset-import.ts
499
+ const numericCoordinates = { compareMarkerPoints: (_marker, _range, left, right) => {
500
+ if (typeof left !== "number" || typeof right !== "number" || !Number.isFinite(left) || !Number.isFinite(right)) throw new Error("Media editor requires numeric coordinates");
501
+ return left - right;
502
+ } };
503
+ /**
504
+ * Import at the editor boundary, not at asset generation time. Existing
505
+ * provenance is retained.
506
+ *
507
+ * A media variant is a logical facet of its Asset and shares one entity
508
+ * identity: the import mints exactly one entity of the media kind that carries
509
+ * the external locator itself, and deduplicates only against existing variants
510
+ * that already carry the same `(system, key)`. Legacy dual-entity graphs
511
+ * (`asset` row plus a `physical-asset` binding) are not reused and are
512
+ * rejected by the canonical resource policy instead of being migrated.
513
+ */
514
+ function importMediaAsset(initial, fact, idFactory = (prefix) => `${prefix}_${globalThis.crypto.randomUUID()}`) {
515
+ if (!fact.assetId || fact.assetId.trim() !== fact.assetId) throw new Error("Expected an asset id");
516
+ if (![
517
+ "image",
518
+ "video",
519
+ "audio",
520
+ "voice"
521
+ ].includes(fact.kind)) throw new Error("Unsupported media kind");
522
+ if (fact.kind !== "image" && (!Number.isFinite(fact.durationMs) || fact.durationMs <= 0)) throw new Error(`${fact.kind} ${fact.assetId} requires its factual positive duration`);
523
+ if ((fact.kind === "audio" || fact.kind === "voice") && fact.storageKey.trim() === "") throw new Error(`${fact.kind} ${fact.assetId} requires its physical storage key`);
524
+ decodeEntityRelationRows(initial, numericCoordinates);
525
+ assertCanonicalEditorResources(initial);
526
+ const entities = structuredClone([...initial.entities]);
527
+ const relations = structuredClone([...initial.relations]);
528
+ const system = fact.kind === "voice" ? "memota-speech" : "memota";
529
+ const existing = entities.filter((row) => {
530
+ const external = row.payload.external;
531
+ return isMediaAssetVariantKind(row.entityKind) && isJsonObject(external) && external.system === system && external.key === fact.assetId;
532
+ });
533
+ if (existing.length > 1) throw new Error(`Duplicate media identities for ${fact.assetId}; reuse ${existing[0].entityId}`);
534
+ if (existing[0] !== void 0) {
535
+ const variant = requireMatchingVariant(existing[0], fact);
536
+ replaceEntity$1(entities, variant.entityId, variant);
537
+ return {
538
+ rows: {
539
+ entities,
540
+ relations
541
+ },
542
+ contentEntityId: variant.entityId
543
+ };
544
+ }
545
+ const entityId = createEntityId(idFactory("entity"));
546
+ if (entities.some((row) => row.entityId === entityId)) throw new Error(`Duplicate entity id ${entityId}`);
547
+ const variant = {
548
+ entityId,
549
+ entityKind: fact.kind,
550
+ payload: {
551
+ extent: fact.kind === "image" ? {
552
+ kind: "unbounded",
553
+ start: 0
554
+ } : {
555
+ kind: "bounded",
556
+ start: 0,
557
+ end: fact.durationMs
558
+ },
559
+ sampling: fact.kind === "image" ? "constant" : "native",
560
+ coordinateSpace: "milliseconds",
561
+ external: {
562
+ system,
563
+ key: fact.assetId
564
+ },
565
+ ...fact.storageKey === void 0 ? {} : { storageKey: fact.storageKey },
566
+ ...fact.kind === "voice" ? { voice: {
567
+ system: fact.voice.system,
568
+ key: fact.voice.key,
569
+ ...fact.voice.name === void 0 ? {} : { name: fact.voice.name }
570
+ } } : {}
571
+ }
572
+ };
573
+ entities.push(variant);
574
+ const rows = {
575
+ entities,
576
+ relations
577
+ };
578
+ decodeEntityRelationRows(rows, numericCoordinates);
579
+ assertCanonicalEditorResources(rows);
580
+ return {
581
+ rows,
582
+ contentEntityId: entityId
583
+ };
584
+ }
585
+ function requireMatchingVariant(row, fact) {
586
+ const extent = row.payload.extent;
587
+ 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}`);
588
+ if (fact.storageKey !== void 0 && row.payload.storageKey !== fact.storageKey) {
589
+ if (row.payload.storageKey !== void 0) throw new Error(`Media facts conflict with existing storage key for ${fact.assetId}`);
590
+ return {
591
+ ...row,
592
+ payload: {
593
+ ...row.payload,
594
+ storageKey: fact.storageKey
595
+ }
596
+ };
597
+ }
598
+ return row;
599
+ }
600
+ function replaceEntity$1(entities, entityId, replacement) {
601
+ const index = entities.findIndex((row) => row.entityId === entityId);
602
+ if (index < 0) throw new Error(`Entity id ${entityId} does not exist`);
603
+ entities[index] = replacement;
604
+ }
605
+ function sameVoice(left, right) {
606
+ 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");
607
+ }
608
+ //#endregion
609
+ //#region src/entity-editor/entity-timeline-editor.ts
610
+ const roleOrder = {
611
+ caption: 0,
612
+ video_clip: 1,
613
+ speech: 2,
614
+ bgm: 3
615
+ };
616
+ const defaultIdFactory = (prefix) => `${prefix}_${globalThis.crypto.randomUUID()}`;
617
+ /**
618
+ * Graph-native timeline authoring over authoritative Medeo Entity and Relation rows.
619
+ *
620
+ * Each mutation is applied to a detached graph, validated as a complete DSL set,
621
+ * and committed only after validation succeeds.
622
+ */
623
+ var EntityTimelineEditor = class {
624
+ idFactory;
625
+ state;
626
+ constructor(initialRows, idFactory = defaultIdFactory) {
627
+ this.idFactory = idFactory;
628
+ this.state = cloneRows(initialRows);
629
+ }
630
+ rows() {
631
+ return cloneRows(this.state);
632
+ }
633
+ insertClip(input) {
634
+ const requestedOrder = input.clipPayload?.order;
635
+ const order = typeof requestedOrder === "number" ? requestedOrder : nextSequentialOrder(this.state, createEntityId(input.trackEntityId));
636
+ return this.insertPlacedClip({
637
+ trackEntityId: input.trackEntityId,
638
+ contentEntityId: input.contentEntityId,
639
+ sourceRange: input.sourceRange,
640
+ duration: input.duration,
641
+ placement: input.targetRange === void 0 ? {
642
+ kind: "sequential",
643
+ order
644
+ } : {
645
+ kind: "absolute",
646
+ targetRange: input.targetRange
647
+ },
648
+ clipPayload: input.clipPayload
649
+ });
650
+ }
651
+ insertPlacedClip(input) {
652
+ return this.transact((draft) => this.insertPlacedClipIntoDraft(draft, input));
653
+ }
654
+ updateClipMarker(input) {
655
+ this.transact((draft) => {
656
+ const { marker } = requireClipTopology(draft, input.clipEntityId);
657
+ const payload = { ...cloneJsonObject(marker.payload, "Sequence Marker payload") };
658
+ if (input.sourceRange !== void 0) payload.sourceRange = cloneJsonValue(input.sourceRange, "sourceRange");
659
+ if (input.duration !== void 0) payload.duration = cloneJsonValue(input.duration, "duration");
660
+ if (Object.hasOwn(input, "targetRange")) if (input.targetRange === void 0) {
661
+ delete payload.targetRange;
662
+ if (!hasOutgoingClipAnchor(draft, input.clipEntityId)) {
663
+ const trackId = otherEndpoint(requireOneRelation(draft, createEntityId(input.clipEntityId), "track-clip"), input.clipEntityId);
664
+ const clipPayload = { ...cloneJsonObject(requireEntityKind(draft, input.clipEntityId, "clip").payload, "Clip payload") };
665
+ clipPayload.order ??= nextSequentialOrder(draft, trackId);
666
+ replaceEntity(draft, createEntityId(input.clipEntityId), {
667
+ ...requireEntityKind(draft, input.clipEntityId, "clip"),
668
+ payload: clipPayload
669
+ });
670
+ }
671
+ } else {
672
+ payload.targetRange = cloneJsonValue(input.targetRange, "targetRange");
673
+ const clip = requireEntityKind(draft, input.clipEntityId, "clip");
674
+ const clipPayload = { ...cloneJsonObject(clip.payload, "Clip payload") };
675
+ delete clipPayload.order;
676
+ replaceEntity(draft, clip.entityId, {
677
+ ...clip,
678
+ payload: clipPayload
679
+ });
680
+ }
681
+ if (Object.hasOwn(input, "timeRemapping")) if (input.timeRemapping === void 0) delete payload.timeRemapping;
682
+ else payload.timeRemapping = cloneJsonValue(input.timeRemapping, "timeRemapping");
683
+ replaceEntity(draft, marker.entityId, {
684
+ ...marker,
685
+ payload
686
+ });
687
+ });
688
+ }
689
+ setClipPlacement(input) {
690
+ this.transact((draft) => this.applyClipPlacement(draft, input.clipEntityId, input.placement));
691
+ }
692
+ moveSequentialClips(input) {
693
+ if (input.clipEntityIds.length === 0) throw new Error("At least one Clip is required");
694
+ this.transact((draft) => {
695
+ const original = resolveEntityTimelineLayout(draft);
696
+ this.normalizeMainSequential(draft);
697
+ const before = resolveEntityTimelineLayout(draft);
698
+ const targetIds = new Set(input.clipEntityIds);
699
+ if (targetIds.size !== input.clipEntityIds.length) throw new Error("Clip ids must be unique");
700
+ const placements = input.clipEntityIds.map((id) => before.clips.get(id));
701
+ if (placements.some((placement) => placement === void 0 || placement.mode !== "sequential")) throw new Error("moveSequentialClips accepts only sequential Clips");
702
+ const trackIds = new Set(placements.map((placement) => placement.trackEntityId));
703
+ if (trackIds.size !== 1) throw new Error("Moved Clips must belong to one Track");
704
+ const trackId = [...trackIds][0];
705
+ const track = before.tracks.find((candidate) => candidate.entityId === trackId);
706
+ if (track?.role !== "video_clip") throw new Error("Only the video_clip Track supports sequential block moves");
707
+ const ordered = track.clips.filter((placement) => placement.mode === "sequential").map((placement) => placement.clipEntityId);
708
+ if (input.anchor.position !== "trackStart" && targetIds.has(input.anchor.clipEntityId)) throw new Error("Move anchor cannot be one of the moved Clips");
709
+ const moved = ordered.filter((id) => targetIds.has(id));
710
+ if (moved.length !== targetIds.size) throw new Error("Every moved Clip must exist on the target Track");
711
+ const remaining = ordered.filter((id) => !targetIds.has(id));
712
+ let insertAt = 0;
713
+ if (input.anchor.position !== "trackStart") {
714
+ const anchorIndex = remaining.indexOf(input.anchor.clipEntityId);
715
+ if (anchorIndex < 0) throw new Error("Move anchor Clip does not exist on the target Track");
716
+ insertAt = anchorIndex + (input.anchor.position === "after" ? 1 : 0);
717
+ }
718
+ [
719
+ ...remaining.slice(0, insertAt),
720
+ ...moved,
721
+ ...remaining.slice(insertAt)
722
+ ].forEach((clipId, order) => setClipOrder(draft, clipId, order));
723
+ if (input.onAnchored === "keepAbsolute") {
724
+ const affected = outgoingAnchorChildren(draft, new Set(track.clips.map((clip) => clip.clipEntityId))).filter((childId) => clipRole(draft, childId) === "speech").map((childId) => {
725
+ const placement = original.clips.get(childId);
726
+ if (placement === void 0) throw new Error(`Anchored child Clip "${childId}" is not placed`);
727
+ return {
728
+ childId,
729
+ start: placement.start
730
+ };
731
+ });
732
+ const after = resolveEntityTimelineLayout(draft);
733
+ for (const child of affected) this.reanchorAtAbsolute(draft, child.childId, child.start, after);
734
+ }
735
+ this.resolveOneVoiceoverOverlap(draft);
736
+ });
737
+ }
738
+ moveClipsToStarts(input) {
739
+ if (input.moves.length === 0) throw new Error("At least one Clip move is required");
740
+ this.transact((draft) => {
741
+ const original = resolveEntityTimelineLayout(draft);
742
+ const originalVideo = original.tracks.find((track) => track.role === "video_clip");
743
+ if (originalVideo === void 0) throw new Error("The timeline has no video_clip Track");
744
+ const preservedVoiceovers = outgoingAnchorChildren(draft, new Set(originalVideo.clips.map((clip) => clip.clipEntityId))).filter((clipId) => clipRole(draft, clipId) === "speech").map((clipId) => ({
745
+ clipId,
746
+ start: original.clips.get(clipId).start
747
+ }));
748
+ this.normalizeMainSequential(draft);
749
+ for (const move of input.moves) {
750
+ finiteNonNegative(move.newStartMs, "newStartMs");
751
+ requireClipOnRole(draft, move.clipEntityId, "video_clip");
752
+ const track = resolveEntityTimelineLayout(draft).tracks.find((candidate) => candidate.role === "video_clip");
753
+ const ordered = track.clips.map((clip) => clip.clipEntityId);
754
+ const from = ordered.indexOf(move.clipEntityId);
755
+ if (from < 0) throw new Error(`Clip "${move.clipEntityId}" is not on the video_clip Track`);
756
+ const remaining = track.clips.filter((clip) => clip.clipEntityId !== move.clipEntityId);
757
+ let cursor = 0;
758
+ let target = remaining.length;
759
+ for (const [index, clip] of remaining.entries()) {
760
+ if (move.newStartMs <= cursor + clip.duration / 2) {
761
+ target = index;
762
+ break;
763
+ }
764
+ cursor += clip.duration;
765
+ }
766
+ const next = [...ordered];
767
+ next.splice(from, 1);
768
+ next.splice(target, 0, move.clipEntityId);
769
+ next.forEach((clipId, order) => setClipOrder(draft, clipId, order));
770
+ }
771
+ const after = resolveEntityTimelineLayout(draft);
772
+ for (const voiceover of preservedVoiceovers) this.reanchorAtAbsolute(draft, voiceover.clipId, voiceover.start, after);
773
+ this.resolveOneVoiceoverOverlap(draft);
774
+ });
775
+ }
776
+ moveClip(input) {
777
+ this.transact((draft) => {
778
+ const topology = requireClipTopology(draft, input.clipEntityId);
779
+ const track = requireEntityKind(draft, input.trackEntityId, "track");
780
+ requireTrackTimeline(draft, track.entityId);
781
+ this.relinkRelation(draft, topology.trackRelation, {
782
+ endpoint0EntityId: track.entityId,
783
+ endpoint1EntityId: topology.clip.entityId
784
+ });
785
+ });
786
+ }
787
+ replaceClipContent(input) {
788
+ this.transact((draft) => {
789
+ const topology = requireClipTopology(draft, input.clipEntityId);
790
+ const content = requireSequenceContent(draft, input.contentEntityId);
791
+ const payload = {
792
+ ...cloneJsonObject(topology.marker.payload, "Sequence Marker payload"),
793
+ sourceRange: cloneJsonValue(input.sourceRange, "sourceRange"),
794
+ duration: cloneJsonValue(input.duration, "duration")
795
+ };
796
+ delete payload.targetRange;
797
+ delete payload.timeRemapping;
798
+ if (input.targetRange !== void 0) payload.targetRange = cloneJsonValue(input.targetRange, "targetRange");
799
+ if (input.timeRemapping !== void 0) payload.timeRemapping = cloneJsonValue(input.timeRemapping, "timeRemapping");
800
+ replaceEntity(draft, topology.marker.entityId, {
801
+ ...topology.marker,
802
+ payload
803
+ });
804
+ if (!hasOutgoingClipAnchor(draft, topology.clip.entityId)) {
805
+ const clipPayload = { ...cloneJsonObject(topology.clip.payload, "Clip payload") };
806
+ if (input.targetRange === void 0) clipPayload.order ??= nextSequentialOrder(draft, otherEndpoint(topology.trackRelation, topology.clip.entityId));
807
+ else delete clipPayload.order;
808
+ replaceEntity(draft, topology.clip.entityId, {
809
+ ...topology.clip,
810
+ payload: clipPayload
811
+ });
812
+ }
813
+ this.relinkRelation(draft, topology.markerContentRelation, {
814
+ endpoint0EntityId: topology.marker.entityId,
815
+ endpoint1EntityId: content.entityId
816
+ });
817
+ });
818
+ }
819
+ insertMediaClip(input) {
820
+ return this.transact((draft) => {
821
+ if (input.placement.kind === "sequential") this.normalizeMainSequential(draft);
822
+ const imported = importMediaAsset(draft, input.media, this.idFactory);
823
+ replaceRows(draft, imported.rows);
824
+ const track = this.ensureRoleTrack(draft, input.timelineEntityId, "video_clip");
825
+ const sourceRange = requirePositiveRange(input.sourceRange, "sourceRange");
826
+ const clipId = this.insertPlacedClipIntoDraft(draft, {
827
+ trackEntityId: track.entityId,
828
+ contentEntityId: imported.contentEntityId,
829
+ sourceRange,
830
+ duration: {
831
+ mode: "fixed",
832
+ value: sourceRange.end - sourceRange.start
833
+ },
834
+ placement: input.placement,
835
+ ...input.clipEntityId === void 0 ? {} : { clipEntityId: input.clipEntityId },
836
+ ...input.volume === void 0 ? {} : { clipPayload: { volume: requireVolume(input.volume) } }
837
+ });
838
+ if (input.placement.kind === "sequential") this.resolveOneVoiceoverOverlap(draft);
839
+ return clipId;
840
+ });
841
+ }
842
+ insertMediaClips(input) {
843
+ if (input.clips.length === 0) throw new Error("At least one media Clip is required");
844
+ return this.transact((draft) => {
845
+ this.normalizeMainSequential(draft);
846
+ const track = this.ensureRoleTrack(draft, input.timelineEntityId, "video_clip");
847
+ const ordered = resolveEntityTimelineLayout(draft).tracks.find((candidate) => candidate.entityId === track.entityId)?.clips ?? [];
848
+ let insertAt = ordered.length;
849
+ const insertion = input.insertion;
850
+ if (insertion.kind === "before" || insertion.kind === "after") {
851
+ const anchorIndex = ordered.findIndex((clip) => clip.clipEntityId === insertion.clipEntityId);
852
+ if (anchorIndex >= 0) insertAt = anchorIndex + (insertion.kind === "after" ? 1 : 0);
853
+ } else {
854
+ const startMs = finiteNonNegative(insertion.startMs, "firstStart.startMs");
855
+ let cursor = 0;
856
+ for (const [index, clip] of ordered.entries()) {
857
+ if (startMs <= cursor + clip.duration / 2) {
858
+ insertAt = index;
859
+ break;
860
+ }
861
+ cursor += clip.duration;
862
+ }
863
+ }
864
+ const created = [];
865
+ for (const [offset, clip] of input.clips.entries()) {
866
+ const imported = importMediaAsset(draft, clip.media, this.idFactory);
867
+ replaceRows(draft, imported.rows);
868
+ const sourceRange = requirePositiveRange(clip.sourceRange, "sourceRange");
869
+ created.push(this.insertPlacedClipIntoDraft(draft, {
870
+ trackEntityId: track.entityId,
871
+ contentEntityId: imported.contentEntityId,
872
+ sourceRange,
873
+ duration: {
874
+ mode: "fixed",
875
+ value: sourceRange.end - sourceRange.start
876
+ },
877
+ placement: {
878
+ kind: "sequential",
879
+ order: ordered.length + offset
880
+ },
881
+ ...clip.clipEntityId === void 0 ? {} : { clipEntityId: clip.clipEntityId },
882
+ ...clip.volume === void 0 ? {} : { clipPayload: { volume: requireVolume(clip.volume) } }
883
+ }));
884
+ }
885
+ const desired = ordered.map((clip) => clip.clipEntityId);
886
+ desired.splice(insertAt, 0, ...created);
887
+ desired.forEach((clipId, order) => setClipOrder(draft, clipId, order));
888
+ this.resolveOneVoiceoverOverlap(draft);
889
+ return created;
890
+ });
891
+ }
892
+ replaceMediaClip(input) {
893
+ this.transact((draft) => {
894
+ this.normalizeMainSequential(draft);
895
+ const topology = requireClipOnRole(draft, input.clipEntityId, "video_clip");
896
+ const imported = importMediaAsset(draft, input.media, this.idFactory);
897
+ replaceRows(draft, imported.rows);
898
+ const sourceRange = requirePositiveRange(input.sourceRange, "sourceRange");
899
+ const markerPayloadValue = {
900
+ ...cloneJsonObject(topology.marker.payload, "Sequence Marker payload"),
901
+ sourceRange,
902
+ duration: {
903
+ mode: "fixed",
904
+ value: sourceRange.end - sourceRange.start
905
+ }
906
+ };
907
+ delete markerPayloadValue.timeRemapping;
908
+ resizeAbsoluteTarget(markerPayloadValue, sourceRange.end - sourceRange.start);
909
+ replaceEntity(draft, topology.marker.entityId, {
910
+ ...topology.marker,
911
+ payload: markerPayloadValue
912
+ });
913
+ this.relinkRelation(draft, topology.markerContentRelation, {
914
+ endpoint0EntityId: topology.marker.entityId,
915
+ endpoint1EntityId: createEntityId(imported.contentEntityId)
916
+ });
917
+ this.resolveOneVoiceoverOverlap(draft);
918
+ });
919
+ }
920
+ setClipVolume(input) {
921
+ this.transact((draft) => {
922
+ const topology = requireClipTopology(draft, input.clipEntityId);
923
+ requireSupportedRole(draft, topology);
924
+ replaceEntity(draft, topology.clip.entityId, {
925
+ ...topology.clip,
926
+ payload: {
927
+ ...topology.clip.payload,
928
+ volume: requireVolume(input.volume)
929
+ }
930
+ });
931
+ });
932
+ }
933
+ setClipSpeed(input) {
934
+ this.transact((draft) => {
935
+ const initialTopology = requireClipOnRole(draft, input.clipEntityId, "video_clip");
936
+ const content = requireSequenceContent(draft, otherEndpoint(initialTopology.markerContentRelation, initialTopology.marker.entityId));
937
+ if (content.entityKind !== "video" && content.entityKind !== "image") throw new Error("Clip speed is supported only for Video or Image content");
938
+ const initialPayload = cloneJsonObject(initialTopology.marker.payload, "Sequence Marker payload");
939
+ const priorSource = requirePositiveRange(initialPayload.sourceRange, "sourceRange");
940
+ if (input.timeRemapping === null && initialPayload.timeRemapping === void 0) return;
941
+ this.normalizeMainSequential(draft);
942
+ const topology = requireClipTopology(draft, input.clipEntityId);
943
+ const payload = { ...cloneJsonObject(topology.marker.payload, "Sequence Marker payload") };
944
+ let sourceRange = priorSource;
945
+ if (content.entityKind === "image" && initialPayload.timeRemapping === void 0 && input.timeRemapping !== null) sourceRange = {
946
+ start: 0,
947
+ end: markerDuration(initialPayload, priorSource)
948
+ };
949
+ if (input.timeRemapping === null) {
950
+ delete payload.timeRemapping;
951
+ payload.sourceRange = sourceRange;
952
+ payload.duration = {
953
+ mode: "fixed",
954
+ value: sourceRange.end - sourceRange.start
955
+ };
956
+ } else {
957
+ const rate = finitePositive(input.timeRemapping.rate, "linear speed rate");
958
+ const duration = Math.round((sourceRange.end - sourceRange.start) / rate);
959
+ if (duration <= 0 || !Number.isSafeInteger(duration)) throw new Error("Linear speed produces an invalid duration");
960
+ payload.sourceRange = sourceRange;
961
+ payload.duration = {
962
+ mode: "fixed",
963
+ value: duration
964
+ };
965
+ payload.timeRemapping = {
966
+ kind: "linear",
967
+ rate,
968
+ ...input.timeRemapping.mode === void 0 ? {} : { mode: input.timeRemapping.mode }
969
+ };
970
+ }
971
+ resizeAbsoluteTarget(payload, markerDuration(payload, sourceRange));
972
+ replaceEntity(draft, topology.marker.entityId, {
973
+ ...topology.marker,
974
+ payload
975
+ });
976
+ this.resolveOneVoiceoverOverlap(draft);
977
+ });
978
+ }
979
+ trimClip(input) {
980
+ this.transact((draft) => {
981
+ this.normalizeMainSequential(draft);
982
+ const topology = requireClipOnRole(draft, input.clipEntityId, "video_clip");
983
+ const content = requireSequenceContent(draft, otherEndpoint(topology.markerContentRelation, topology.marker.entityId));
984
+ if (content.entityKind !== "video" && content.entityKind !== "image") throw new Error("Clip trimming is supported only for Video or Image content");
985
+ const sourceRange = requirePositiveRange(input.sourceRange, "sourceRange");
986
+ const payload = {
987
+ ...cloneJsonObject(topology.marker.payload, "Sequence Marker payload"),
988
+ sourceRange
989
+ };
990
+ const rate = linearRate(payload.timeRemapping);
991
+ const duration = Math.round((sourceRange.end - sourceRange.start) / rate);
992
+ if (duration <= 0 || !Number.isSafeInteger(duration)) throw new Error("Trim produces an invalid duration");
993
+ payload.duration = {
994
+ mode: "fixed",
995
+ value: duration
996
+ };
997
+ resizeAbsoluteTarget(payload, duration);
998
+ replaceEntity(draft, topology.marker.entityId, {
999
+ ...topology.marker,
1000
+ payload
1001
+ });
1002
+ this.resolveOneVoiceoverOverlap(draft);
1003
+ });
1004
+ }
1005
+ replaceSequentialClips(input) {
1006
+ if (input.oldClipEntityIds.length === 0 || input.newClips.length === 0) throw new Error("Replacement requires at least one old and one new Clip");
1007
+ return this.transact((draft) => {
1008
+ this.normalizeMainSequential(draft);
1009
+ const before = resolveEntityTimelineLayout(draft);
1010
+ const oldIds = new Set(input.oldClipEntityIds);
1011
+ if (oldIds.size !== input.oldClipEntityIds.length) throw new Error("Old Clip ids must be unique");
1012
+ const track = this.ensureRoleTrack(draft, input.timelineEntityId, "video_clip");
1013
+ const ordered = before.tracks.find((candidate) => candidate.entityId === track.entityId)?.clips.filter((clip) => clip.mode === "sequential").map((clip) => clip.clipEntityId);
1014
+ if (ordered === void 0) throw new Error("The video_clip Track is not present in the current layout");
1015
+ const indexes = input.oldClipEntityIds.map((id) => ordered.indexOf(id));
1016
+ if (indexes.some((index) => index < 0)) throw new Error("Every replaced Clip must be sequential on video_clip");
1017
+ const sortedIndexes = [...indexes].sort((left, right) => left - right);
1018
+ if (sortedIndexes.some((index, offset) => index !== sortedIndexes[0] + offset)) throw new Error("Replaced Clips must form one contiguous timeline run");
1019
+ if (input.oldClipEntityIds.some((id, index) => id !== ordered[sortedIndexes[0] + index])) throw new Error("Replaced Clip ids must be listed in timeline order");
1020
+ const insertOrder = sortedIndexes[0];
1021
+ const temporaryOrder = ordered.length;
1022
+ const created = [];
1023
+ for (const [offset, replacement] of input.newClips.entries()) {
1024
+ if (replacement.clipEntityId !== void 0 && oldIds.has(replacement.clipEntityId)) throw new Error("A replacement Clip id cannot reuse an Entity being removed");
1025
+ const imported = importMediaAsset(draft, replacement.media, this.idFactory);
1026
+ replaceRows(draft, imported.rows);
1027
+ const sourceRange = requirePositiveRange(replacement.sourceRange, "sourceRange");
1028
+ created.push(this.insertPlacedClipIntoDraft(draft, {
1029
+ trackEntityId: track.entityId,
1030
+ contentEntityId: imported.contentEntityId,
1031
+ sourceRange,
1032
+ duration: {
1033
+ mode: "fixed",
1034
+ value: sourceRange.end - sourceRange.start
1035
+ },
1036
+ placement: {
1037
+ kind: "sequential",
1038
+ order: temporaryOrder + offset
1039
+ },
1040
+ ...replacement.clipEntityId === void 0 ? {} : { clipEntityId: replacement.clipEntityId },
1041
+ ...replacement.volume === void 0 ? {} : { clipPayload: { volume: requireVolume(replacement.volume) } }
1042
+ }));
1043
+ }
1044
+ for (const [index, oldId] of input.oldClipEntityIds.entries()) {
1045
+ const children = directAnchorChildren(draft, oldId);
1046
+ if (input.onAnchored === "remap" && created[index] !== void 0) for (const childId of children) this.replaceAnchorHost(draft, childId, created[index]);
1047
+ else {
1048
+ const scheduled = /* @__PURE__ */ new Set();
1049
+ for (const childId of children) {
1050
+ scheduled.add(childId);
1051
+ this.removeAnchoredDescendants(draft, childId, scheduled);
1052
+ this.removeClipGraph(draft, childId);
1053
+ }
1054
+ }
1055
+ }
1056
+ for (const oldId of input.oldClipEntityIds) this.removeClipGraph(draft, oldId);
1057
+ [
1058
+ ...ordered.slice(0, insertOrder),
1059
+ ...created,
1060
+ ...ordered.slice(insertOrder + input.oldClipEntityIds.length)
1061
+ ].forEach((clipId, order) => setClipOrder(draft, clipId, order));
1062
+ this.resolveOneVoiceoverOverlap(draft);
1063
+ return created;
1064
+ });
1065
+ }
1066
+ deleteClip(input) {
1067
+ this.transact((draft) => {
1068
+ const topology = requireClipTopology(draft, input.clipEntityId);
1069
+ assertOnlyStructuralIncidents(draft, topology.clip.entityId, new Set(["track-clip", "clip-marker"]));
1070
+ assertOnlyStructuralIncidents(draft, topology.marker.entityId, new Set(["clip-marker", "marker-content"]));
1071
+ const markerIsExclusive = incidentRelations(draft, topology.marker.entityId).filter((relation) => relation.relationKind === "clip-marker").length === 1;
1072
+ const removedRelationIds = new Set([topology.trackRelation.relationId, topology.clipMarkerRelation.relationId]);
1073
+ if (markerIsExclusive) for (const relation of incidentRelations(draft, topology.marker.entityId)) removedRelationIds.add(relation.relationId);
1074
+ draft.relations = draft.relations.filter((relation) => !removedRelationIds.has(relation.relationId));
1075
+ draft.entities = draft.entities.filter((entity) => entity.entityId !== topology.clip.entityId && (!markerIsExclusive || entity.entityId !== topology.marker.entityId));
1076
+ });
1077
+ }
1078
+ deleteClipTree(input) {
1079
+ if (input.clipEntityIds.length === 0) throw new Error("At least one Clip is required");
1080
+ this.transact((draft) => {
1081
+ const targets = new Set(input.clipEntityIds);
1082
+ if (targets.size !== input.clipEntityIds.length) throw new Error("Clip ids must be unique");
1083
+ for (const target of targets) requireEntityKind(draft, target, "clip");
1084
+ const includesVisual = [...targets].some((target) => clipRole(draft, target) === "video_clip");
1085
+ const original = resolveEntityTimelineLayout(draft);
1086
+ if (includesVisual) this.normalizeMainSequential(draft);
1087
+ if (input.onAnchored === "detach") for (const childId of outgoingAnchorChildren(draft, targets)) {
1088
+ if (targets.has(childId)) continue;
1089
+ const placement = original.clips.get(childId);
1090
+ if (placement === void 0) throw new Error(`Anchored child Clip "${childId}" is not placed`);
1091
+ this.applyClipPlacement(draft, childId, {
1092
+ kind: "absolute",
1093
+ targetRange: {
1094
+ start: placement.start,
1095
+ end: placement.start + placement.duration
1096
+ }
1097
+ });
1098
+ }
1099
+ else for (const target of targets) this.removeAnchoredDescendants(draft, target, targets);
1100
+ for (const target of targets) this.removeClipGraph(draft, target);
1101
+ normalizeSequentialOrders(draft);
1102
+ if (includesVisual) this.resolveOneVoiceoverOverlap(draft);
1103
+ });
1104
+ }
1105
+ updateClip(input) {
1106
+ this.transact((draft) => {
1107
+ const clip = requireEntityKind(draft, input.clipEntityId, "clip");
1108
+ const priorOrder = clip.payload.order;
1109
+ replaceEntity(draft, clip.entityId, {
1110
+ ...clip,
1111
+ payload: {
1112
+ ...cloneJsonObject(input.payload, "Clip payload"),
1113
+ ...priorOrder === void 0 || Object.hasOwn(input.payload, "order") ? {} : { order: priorOrder }
1114
+ }
1115
+ });
1116
+ });
1117
+ }
1118
+ upsertVoiceoverTake(input) {
1119
+ return this.transact((draft) => {
1120
+ this.normalizeMainSequential(draft);
1121
+ finiteNonNegative(input.anchorOffset, "Voiceover anchorOffset");
1122
+ requireVolume(input.volume);
1123
+ requireClipOnRole(draft, input.hostClipEntityId, "video_clip");
1124
+ const imported = importMediaAsset(draft, input.media, this.idFactory);
1125
+ replaceRows(draft, imported.rows);
1126
+ const voice = requireEntityKind(draft, imported.contentEntityId, "voice");
1127
+ const script = this.ensureAudioScript(draft, voice.entityId, input.scriptText);
1128
+ const speechTrack = this.ensureRoleTrack(draft, input.timelineEntityId, "speech");
1129
+ const existing = draft.entities.find((row) => row.entityId === input.voiceoverClipEntityId);
1130
+ let voiceoverClipEntityId;
1131
+ if (existing === void 0) voiceoverClipEntityId = this.insertPlacedClipIntoDraft(draft, {
1132
+ clipEntityId: input.voiceoverClipEntityId,
1133
+ trackEntityId: speechTrack.entityId,
1134
+ contentEntityId: voice.entityId,
1135
+ sourceRange: {
1136
+ start: 0,
1137
+ end: input.media.durationMs
1138
+ },
1139
+ duration: {
1140
+ mode: "fixed",
1141
+ value: input.media.durationMs
1142
+ },
1143
+ placement: {
1144
+ kind: "anchored",
1145
+ hostClipEntityId: input.hostClipEntityId,
1146
+ anchorOffset: input.anchorOffset
1147
+ },
1148
+ clipPayload: { volume: input.volume }
1149
+ });
1150
+ else {
1151
+ const topology = requireClipOnRole(draft, input.voiceoverClipEntityId, "speech");
1152
+ voiceoverClipEntityId = topology.clip.entityId;
1153
+ replaceEntity(draft, topology.clip.entityId, {
1154
+ ...topology.clip,
1155
+ payload: {
1156
+ ...topology.clip.payload,
1157
+ volume: input.volume
1158
+ }
1159
+ });
1160
+ this.relinkRelation(draft, topology.markerContentRelation, {
1161
+ endpoint0EntityId: topology.marker.entityId,
1162
+ endpoint1EntityId: voice.entityId
1163
+ });
1164
+ this.applyClipPlacement(draft, topology.clip.entityId, {
1165
+ kind: "anchored",
1166
+ hostClipEntityId: input.hostClipEntityId,
1167
+ anchorOffset: input.anchorOffset
1168
+ });
1169
+ const placed = requireClipTopology(draft, topology.clip.entityId);
1170
+ replaceEntity(draft, placed.marker.entityId, {
1171
+ ...placed.marker,
1172
+ payload: {
1173
+ ...placed.marker.payload,
1174
+ sourceRange: {
1175
+ start: 0,
1176
+ end: input.media.durationMs
1177
+ },
1178
+ duration: {
1179
+ mode: "fixed",
1180
+ value: input.media.durationMs
1181
+ }
1182
+ }
1183
+ });
1184
+ }
1185
+ this.reconcileVoiceoverCaptions(draft, voiceoverClipEntityId, voice.entityId, script.entityId, input.captions);
1186
+ this.resolveOneVoiceoverOverlap(draft);
1187
+ return {
1188
+ voiceoverClipEntityId,
1189
+ voiceEntityId: voice.entityId,
1190
+ audioScriptEntityId: script.entityId,
1191
+ captionClipEntityIds: input.captions.map((caption) => caption.captionClipEntityId)
1192
+ };
1193
+ });
1194
+ }
1195
+ moveVoiceover(input) {
1196
+ this.transact((draft) => {
1197
+ requireClipOnRole(draft, input.voiceoverClipEntityId, "speech");
1198
+ this.normalizeMainSequential(draft);
1199
+ const layout = resolveEntityTimelineLayout(draft);
1200
+ this.reanchorAtAbsolute(draft, input.voiceoverClipEntityId, finiteNonNegative(input.newStartMs, "newStartMs"), layout);
1201
+ this.resolveOneVoiceoverOverlap(draft);
1202
+ });
1203
+ }
1204
+ deleteVoiceover(input) {
1205
+ this.transact((draft) => {
1206
+ this.normalizeMainSequential(draft);
1207
+ const targets = new Set(input.voiceoverClipEntityIds);
1208
+ if (targets.size !== input.voiceoverClipEntityIds.length) throw new Error("Voiceover Clip ids must be unique");
1209
+ for (const clipId of targets) {
1210
+ requireClipOnRole(draft, clipId, "speech");
1211
+ this.removeAnchoredDescendants(draft, clipId, targets);
1212
+ }
1213
+ for (const clipId of targets) this.removeClipGraph(draft, clipId);
1214
+ this.resolveOneVoiceoverOverlap(draft);
1215
+ });
1216
+ }
1217
+ setBgm(input) {
1218
+ return this.transact((draft) => {
1219
+ const imported = importMediaAsset(draft, input.media, this.idFactory);
1220
+ replaceRows(draft, imported.rows);
1221
+ const track = this.ensureRoleTrack(draft, input.timelineEntityId, "bgm");
1222
+ const existing = clipsOnTrack(draft, track.entityId);
1223
+ for (const clip of existing) this.removeClipGraph(draft, clip.entityId);
1224
+ const clipId = this.insertPlacedClipIntoDraft(draft, {
1225
+ clipEntityId: input.bgmClipEntityId,
1226
+ trackEntityId: track.entityId,
1227
+ contentEntityId: imported.contentEntityId,
1228
+ sourceRange: {
1229
+ start: 0,
1230
+ end: input.media.durationMs
1231
+ },
1232
+ duration: { mode: "from-source" },
1233
+ placement: {
1234
+ kind: "sequential",
1235
+ order: 0
1236
+ },
1237
+ clipPayload: { volume: requireVolume(input.volume) }
1238
+ });
1239
+ const topology = requireClipTopology(draft, clipId);
1240
+ replaceEntity(draft, topology.marker.entityId, {
1241
+ ...topology.marker,
1242
+ payload: {
1243
+ ...topology.marker.payload,
1244
+ durationPolicy: "timeline"
1245
+ }
1246
+ });
1247
+ return clipId;
1248
+ });
1249
+ }
1250
+ deleteBgm(input) {
1251
+ this.transact((draft) => {
1252
+ const track = findRoleTrack(draft, input.timelineEntityId, "bgm");
1253
+ if (track === void 0) return;
1254
+ for (const clip of clipsOnTrack(draft, track.entityId)) this.removeClipGraph(draft, clip.entityId);
1255
+ });
1256
+ }
1257
+ setCaptionVisibility(input) {
1258
+ this.transact((draft) => {
1259
+ const track = this.ensureRoleTrack(draft, input.timelineEntityId, "caption");
1260
+ replaceEntity(draft, track.entityId, {
1261
+ ...track,
1262
+ payload: {
1263
+ ...track.payload,
1264
+ hidden: input.hidden
1265
+ }
1266
+ });
1267
+ });
1268
+ }
1269
+ patchCaptionStyle(input) {
1270
+ this.transact((draft) => {
1271
+ const track = findRoleTrack(draft, input.timelineEntityId, "caption");
1272
+ if (track === void 0) return;
1273
+ const patch = cloneJsonObject(input.style, "Caption style");
1274
+ for (const clip of clipsOnTrack(draft, track.entityId)) {
1275
+ const topology = requireClipTopology(draft, clip.entityId);
1276
+ const caption = requireEntityKind(draft, otherEndpoint(topology.markerContentRelation, topology.marker.entityId), "caption");
1277
+ const prior = caption.payload.style;
1278
+ const style = isJsonObject(prior) ? prior : {};
1279
+ replaceEntity(draft, caption.entityId, {
1280
+ ...caption,
1281
+ payload: {
1282
+ ...caption.payload,
1283
+ style: {
1284
+ ...style,
1285
+ ...patch
1286
+ }
1287
+ }
1288
+ });
1289
+ }
1290
+ });
1291
+ }
1292
+ insertPlacedClipIntoDraft(draft, input) {
1293
+ const track = requireEntityKind(draft, input.trackEntityId, "track");
1294
+ requireTrackTimeline(draft, track.entityId);
1295
+ const content = requireSequenceContent(draft, input.contentEntityId);
1296
+ const clipId = input.clipEntityId === void 0 ? this.mintEntityId(draft) : requireAvailableEntityId(draft, input.clipEntityId);
1297
+ const markerId = this.mintEntityId(draft);
1298
+ const clipPayload = { ...cloneJsonObject(input.clipPayload ?? {}, "Clip payload") };
1299
+ delete clipPayload.order;
1300
+ const markerPlacement = applyPlacementPayload(clipPayload, input.placement);
1301
+ const clip = {
1302
+ entityId: clipId,
1303
+ entityKind: "clip",
1304
+ payload: clipPayload
1305
+ };
1306
+ const marker = {
1307
+ entityId: markerId,
1308
+ entityKind: "sequence-marker",
1309
+ payload: markerPayload({
1310
+ sourceRange: input.sourceRange,
1311
+ duration: input.duration,
1312
+ ...markerPlacement
1313
+ })
1314
+ };
1315
+ draft.entities.push(clip, marker);
1316
+ 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));
1317
+ if (input.placement.kind === "anchored") {
1318
+ const host = requireEntityKind(draft, input.placement.hostClipEntityId, "clip");
1319
+ if (host.entityId === clipId) throw new Error("A Clip cannot anchor to itself");
1320
+ draft.relations.push(this.createRelation(draft, "clip-anchor", clipId, host.entityId));
1321
+ }
1322
+ return clipId;
1323
+ }
1324
+ ensureRoleTrack(draft, timelineEntityId, role) {
1325
+ const existing = findRoleTrack(draft, timelineEntityId, role);
1326
+ if (existing !== void 0) {
1327
+ if (existing.payload.order === void 0) {
1328
+ const replacement = {
1329
+ ...existing,
1330
+ payload: {
1331
+ ...existing.payload,
1332
+ order: roleOrder[role]
1333
+ }
1334
+ };
1335
+ replaceEntity(draft, existing.entityId, replacement);
1336
+ return replacement;
1337
+ }
1338
+ return existing;
1339
+ }
1340
+ const timeline = requireEntityKind(draft, timelineEntityId, "timeline");
1341
+ const track = {
1342
+ entityId: this.mintEntityId(draft),
1343
+ entityKind: "track",
1344
+ payload: {
1345
+ role,
1346
+ order: roleOrder[role]
1347
+ }
1348
+ };
1349
+ draft.entities.push(track);
1350
+ draft.relations.push(this.createRelation(draft, "timeline-track", timeline.entityId, track.entityId));
1351
+ return track;
1352
+ }
1353
+ ensureAudioScript(draft, voiceEntityId, text) {
1354
+ const renders = draft.relations.filter((relation) => relation.relationKind === "audio-script-render" && relation.endpoint0EntityId === voiceEntityId);
1355
+ if (renders.length > 1) throw new Error(`Voice "${voiceEntityId}" has multiple AudioScript relations`);
1356
+ if (renders[0] !== void 0) {
1357
+ const script = requireEntityKind(draft, renders[0].endpoint1EntityId, "audio-script");
1358
+ const replacement = {
1359
+ ...script,
1360
+ payload: { segments: [{
1361
+ segmentId: "segment-0",
1362
+ text
1363
+ }] }
1364
+ };
1365
+ replaceEntity(draft, script.entityId, replacement);
1366
+ return replacement;
1367
+ }
1368
+ const script = {
1369
+ entityId: this.mintEntityId(draft),
1370
+ entityKind: "audio-script",
1371
+ payload: { segments: [{
1372
+ segmentId: "segment-0",
1373
+ text
1374
+ }] }
1375
+ };
1376
+ draft.entities.push(script);
1377
+ draft.relations.push(this.createRelation(draft, "audio-script-render", voiceEntityId, script.entityId));
1378
+ return script;
1379
+ }
1380
+ reconcileVoiceoverCaptions(draft, voiceoverClipEntityId, voiceEntityId, scriptEntityId, captions) {
1381
+ const requested = new Set(captions.map((caption) => caption.captionClipEntityId));
1382
+ if (requested.size !== captions.length) throw new Error("Caption Clip ids must be unique within a voiceover take");
1383
+ const existing = directAnchorChildren(draft, voiceoverClipEntityId).filter((clipId) => clipRole(draft, clipId) === "caption");
1384
+ for (const clipId of existing) if (!requested.has(clipId)) this.removeCaptionClipGraph(draft, clipId);
1385
+ const captionTrack = captions.length === 0 ? void 0 : this.ensureRoleTrackForClip(draft, voiceoverClipEntityId, "caption");
1386
+ for (const caption of captions) {
1387
+ const startMs = finiteNonNegative(caption.startMs, "Caption startMs");
1388
+ const durationMs = finitePositive(caption.durationMs, "Caption durationMs");
1389
+ if (draft.entities.find((entity) => entity.entityId === caption.captionClipEntityId) === void 0) {
1390
+ const content = {
1391
+ entityId: this.mintEntityId(draft),
1392
+ entityKind: "caption",
1393
+ payload: {
1394
+ extent: {
1395
+ kind: "bounded",
1396
+ start: 0,
1397
+ end: durationMs
1398
+ },
1399
+ sampling: "native",
1400
+ coordinateSpace: "milliseconds",
1401
+ text: caption.text,
1402
+ ...caption.style === void 0 ? {} : { style: cloneJsonObject(caption.style, "Caption style") }
1403
+ }
1404
+ };
1405
+ const asset = {
1406
+ entityId: this.mintEntityId(draft),
1407
+ entityKind: "asset",
1408
+ payload: { inline: {
1409
+ mediaType: "text/plain",
1410
+ text: caption.text
1411
+ } }
1412
+ };
1413
+ draft.entities.push(content, asset);
1414
+ draft.relations.push(this.createRelation(draft, "physical-asset", content.entityId, asset.entityId), this.createRelation(draft, "caption-alignment", content.entityId, voiceEntityId, { alignment: {
1415
+ start: startMs,
1416
+ end: startMs + durationMs
1417
+ } }), this.createRelation(draft, "caption-provenance", content.entityId, scriptEntityId, { segmentAlignment: [] }));
1418
+ this.insertPlacedClipIntoDraft(draft, {
1419
+ clipEntityId: caption.captionClipEntityId,
1420
+ trackEntityId: captionTrack.entityId,
1421
+ contentEntityId: content.entityId,
1422
+ sourceRange: {
1423
+ start: 0,
1424
+ end: durationMs
1425
+ },
1426
+ duration: {
1427
+ mode: "fixed",
1428
+ value: durationMs
1429
+ },
1430
+ placement: {
1431
+ kind: "anchored",
1432
+ hostClipEntityId: voiceoverClipEntityId,
1433
+ anchorOffset: startMs
1434
+ }
1435
+ });
1436
+ continue;
1437
+ }
1438
+ const topology = requireClipOnRole(draft, caption.captionClipEntityId, "caption");
1439
+ const content = requireEntityKind(draft, otherEndpoint(topology.markerContentRelation, topology.marker.entityId), "caption");
1440
+ const priorStyle = isJsonObject(content.payload.style) ? content.payload.style : {};
1441
+ const style = caption.style === void 0 ? priorStyle : {
1442
+ ...priorStyle,
1443
+ ...cloneJsonObject(caption.style, "Caption style")
1444
+ };
1445
+ replaceEntity(draft, content.entityId, {
1446
+ ...content,
1447
+ payload: {
1448
+ ...content.payload,
1449
+ extent: {
1450
+ kind: "bounded",
1451
+ start: 0,
1452
+ end: durationMs
1453
+ },
1454
+ text: caption.text,
1455
+ ...Object.keys(style).length === 0 ? {} : { style }
1456
+ }
1457
+ });
1458
+ const asset = requireEntityKind(draft, otherEndpoint(requireOneRelation(draft, content.entityId, "physical-asset"), content.entityId), "asset");
1459
+ if (asset.payload.inline === void 0) throw new Error(`Caption "${caption.captionClipEntityId}" is not inline`);
1460
+ replaceEntity(draft, asset.entityId, {
1461
+ ...asset,
1462
+ payload: {
1463
+ ...asset.payload,
1464
+ inline: {
1465
+ mediaType: "text/plain",
1466
+ text: caption.text
1467
+ }
1468
+ }
1469
+ });
1470
+ this.applyClipPlacement(draft, topology.clip.entityId, {
1471
+ kind: "anchored",
1472
+ hostClipEntityId: voiceoverClipEntityId,
1473
+ anchorOffset: startMs
1474
+ });
1475
+ const placed = requireClipTopology(draft, topology.clip.entityId);
1476
+ replaceEntity(draft, placed.marker.entityId, {
1477
+ ...placed.marker,
1478
+ payload: {
1479
+ ...placed.marker.payload,
1480
+ sourceRange: {
1481
+ start: 0,
1482
+ end: durationMs
1483
+ },
1484
+ duration: {
1485
+ mode: "fixed",
1486
+ value: durationMs
1487
+ }
1488
+ }
1489
+ });
1490
+ this.replaceCaptionSemanticRelations(draft, content.entityId, voiceEntityId, scriptEntityId, startMs, durationMs);
1491
+ }
1492
+ }
1493
+ ensureRoleTrackForClip(draft, clipEntityId, role) {
1494
+ const topology = requireClipTopology(draft, clipEntityId);
1495
+ const track = requireEntityKind(draft, otherEndpoint(topology.trackRelation, topology.clip.entityId), "track");
1496
+ const timeline = requireEntityKind(draft, otherEndpoint(requireOneRelation(draft, track.entityId, "timeline-track"), track.entityId), "timeline");
1497
+ return this.ensureRoleTrack(draft, timeline.entityId, role);
1498
+ }
1499
+ replaceCaptionSemanticRelations(draft, captionEntityId, voiceEntityId, scriptEntityId, startMs, durationMs) {
1500
+ const removed = new Set(incidentRelations(draft, captionEntityId).filter((relation) => relation.relationKind === "caption-alignment" || relation.relationKind === "caption-provenance").map((relation) => relation.relationId));
1501
+ draft.relations = draft.relations.filter((relation) => !removed.has(relation.relationId));
1502
+ draft.relations.push(this.createRelation(draft, "caption-alignment", captionEntityId, voiceEntityId, { alignment: {
1503
+ start: startMs,
1504
+ end: startMs + durationMs
1505
+ } }), this.createRelation(draft, "caption-provenance", captionEntityId, scriptEntityId, { segmentAlignment: [] }));
1506
+ }
1507
+ removeCaptionClipGraph(draft, clipEntityId) {
1508
+ const topology = requireClipOnRole(draft, clipEntityId, "caption");
1509
+ const caption = requireEntityKind(draft, otherEndpoint(topology.markerContentRelation, topology.marker.entityId), "caption");
1510
+ const asset = requireEntityKind(draft, otherEndpoint(requireOneRelation(draft, caption.entityId, "physical-asset"), caption.entityId), "asset");
1511
+ const contentRelations = incidentRelations(draft, caption.entityId);
1512
+ const allowed = new Set([
1513
+ "physical-asset",
1514
+ "caption-alignment",
1515
+ "caption-provenance",
1516
+ "marker-content"
1517
+ ]);
1518
+ const unsupported = contentRelations.filter((relation) => !allowed.has(relation.relationKind));
1519
+ if (unsupported.length > 0) throw new Error(`Cannot delete Caption with unsupported Relation ${unsupported[0].relationId}`);
1520
+ this.removeClipGraph(draft, clipEntityId);
1521
+ if (incidentRelations(draft, caption.entityId).some((relation) => relation.relationKind === "marker-content")) return;
1522
+ const removed = new Set(incidentRelations(draft, caption.entityId).map((relation) => relation.relationId));
1523
+ const assetIncidents = incidentRelations(draft, asset.entityId);
1524
+ const deleteAsset = asset.payload.inline !== void 0 && assetIncidents.every((relation) => removed.has(relation.relationId));
1525
+ draft.relations = draft.relations.filter((relation) => !removed.has(relation.relationId));
1526
+ draft.entities = draft.entities.filter((entity) => entity.entityId !== caption.entityId && (!deleteAsset || entity.entityId !== asset.entityId));
1527
+ }
1528
+ replaceAnchorHost(draft, childClipEntityId, hostClipEntityId) {
1529
+ const anchors = draft.relations.filter((relation) => relation.relationKind === "clip-anchor" && relation.endpoint0EntityId === childClipEntityId);
1530
+ if (anchors.length !== 1) throw new Error(`Clip "${childClipEntityId}" must have exactly one host`);
1531
+ this.relinkRelation(draft, anchors[0], {
1532
+ endpoint0EntityId: createEntityId(childClipEntityId),
1533
+ endpoint1EntityId: createEntityId(hostClipEntityId)
1534
+ });
1535
+ }
1536
+ /** Rebuild the legacy edit baseline from current visual order before a high-level cascade. */
1537
+ normalizeMainSequential(draft) {
1538
+ const videoTrack = resolveEntityTimelineLayout(draft).tracks.find((track) => track.role === "video_clip");
1539
+ if (videoTrack === void 0) return;
1540
+ videoTrack.clips.forEach((clip, order) => {
1541
+ this.applyClipPlacement(draft, clip.clipEntityId, {
1542
+ kind: "sequential",
1543
+ order
1544
+ });
1545
+ });
1546
+ }
1547
+ resolveOneVoiceoverOverlap(draft) {
1548
+ const layout = resolveEntityTimelineLayout(draft);
1549
+ const speechTrack = layout.tracks.find((track) => track.role === "speech");
1550
+ if (speechTrack === void 0) return;
1551
+ const ranges = speechTrack.clips.map((speech) => {
1552
+ const captions = directAnchorChildren(draft, speech.clipEntityId).filter((clipId) => clipRole(draft, clipId) === "caption").map((clipId) => layout.clips.get(clipId)).filter((value) => value !== void 0);
1553
+ return {
1554
+ speech,
1555
+ start: Math.min(speech.start, ...captions.map((caption) => caption.start)),
1556
+ end: Math.max(speech.start + speech.duration, ...captions.map((caption) => caption.start + caption.duration))
1557
+ };
1558
+ }).sort((left, right) => left.start - right.start || left.speech.clipEntityId.localeCompare(right.speech.clipEntityId));
1559
+ for (let index = 1; index < ranges.length; index += 1) {
1560
+ const prior = ranges[index - 1];
1561
+ const current = ranges[index];
1562
+ if (current.start >= prior.end) continue;
1563
+ const hostId = current.speech.anchorClipEntityId;
1564
+ if (hostId === void 0) continue;
1565
+ const videoTrack = layout.tracks.find((track) => track.role === "video_clip");
1566
+ const hostIndex = videoTrack?.clips.findIndex((clip) => clip.clipEntityId === hostId) ?? -1;
1567
+ if (videoTrack === void 0 || hostIndex < 0) continue;
1568
+ const overlapMs = Math.round(prior.end - current.start);
1569
+ for (const [visualIndex, clip] of videoTrack.clips.entries()) this.applyClipPlacement(draft, clip.clipEntityId, {
1570
+ kind: "absolute",
1571
+ targetRange: {
1572
+ start: clip.start + (visualIndex >= hostIndex ? overlapMs : 0),
1573
+ end: clip.start + clip.duration + (visualIndex >= hostIndex ? overlapMs : 0)
1574
+ }
1575
+ });
1576
+ return;
1577
+ }
1578
+ }
1579
+ applyClipPlacement(draft, clipEntityId, placement) {
1580
+ const topology = requireClipTopology(draft, clipEntityId);
1581
+ const clipPayload = { ...cloneJsonObject(topology.clip.payload, "Clip payload") };
1582
+ const markerPayloadValue = { ...cloneJsonObject(topology.marker.payload, "Sequence Marker payload") };
1583
+ delete clipPayload.order;
1584
+ delete markerPayloadValue.targetRange;
1585
+ delete markerPayloadValue.anchorOffset;
1586
+ const outgoingAnchors = draft.relations.filter((relation) => relation.relationKind === "clip-anchor" && relation.endpoint0EntityId === topology.clip.entityId);
1587
+ const removed = new Set(outgoingAnchors.map((relation) => relation.relationId));
1588
+ draft.relations = draft.relations.filter((relation) => !removed.has(relation.relationId));
1589
+ if (placement.kind === "sequential") clipPayload.order = finiteNumber(placement.order, "Clip order");
1590
+ else if (placement.kind === "absolute") markerPayloadValue.targetRange = cloneJsonValue(placement.targetRange, "targetRange");
1591
+ else {
1592
+ const host = requireEntityKind(draft, placement.hostClipEntityId, "clip");
1593
+ if (host.entityId === topology.clip.entityId) throw new Error("A Clip cannot anchor to itself");
1594
+ markerPayloadValue.anchorOffset = finiteNonNegative(placement.anchorOffset, "anchorOffset");
1595
+ draft.relations.push(this.createRelation(draft, "clip-anchor", topology.clip.entityId, host.entityId));
1596
+ }
1597
+ replaceEntity(draft, topology.clip.entityId, {
1598
+ ...topology.clip,
1599
+ payload: clipPayload
1600
+ });
1601
+ replaceEntity(draft, topology.marker.entityId, {
1602
+ ...topology.marker,
1603
+ payload: markerPayloadValue
1604
+ });
1605
+ }
1606
+ reanchorAtAbsolute(draft, childClipEntityId, absoluteStart, layout) {
1607
+ const hosts = layout.tracks.find((track) => track.role === "video_clip")?.clips.filter((clip) => clip.mode === "sequential") ?? [];
1608
+ if (hosts.length === 0) {
1609
+ const child = layout.clips.get(childClipEntityId);
1610
+ if (child === void 0) throw new Error(`Clip "${childClipEntityId}" is not placed`);
1611
+ this.applyClipPlacement(draft, childClipEntityId, {
1612
+ kind: "absolute",
1613
+ targetRange: {
1614
+ start: absoluteStart,
1615
+ end: absoluteStart + child.duration
1616
+ }
1617
+ });
1618
+ return;
1619
+ }
1620
+ const host = hosts.find((candidate) => candidate.start <= absoluteStart && absoluteStart < candidate.start + candidate.duration) ?? (absoluteStart < hosts[0].start ? hosts[0] : hosts.at(-1));
1621
+ this.applyClipPlacement(draft, childClipEntityId, {
1622
+ kind: "anchored",
1623
+ hostClipEntityId: host.clipEntityId,
1624
+ anchorOffset: Math.max(0, Math.round(absoluteStart - host.start))
1625
+ });
1626
+ }
1627
+ removeAnchoredDescendants(draft, hostClipEntityId, scheduled) {
1628
+ const children = draft.relations.filter((relation) => relation.relationKind === "clip-anchor" && relation.endpoint1EntityId === hostClipEntityId).map((relation) => String(relation.endpoint0EntityId));
1629
+ for (const child of children) {
1630
+ if (scheduled.has(child)) continue;
1631
+ const descendants = new Set(scheduled);
1632
+ descendants.add(child);
1633
+ this.removeAnchoredDescendants(draft, child, descendants);
1634
+ if (clipRole(draft, child) === "caption") this.removeCaptionClipGraph(draft, child);
1635
+ else this.removeClipGraph(draft, child);
1636
+ }
1637
+ }
1638
+ removeClipGraph(draft, clipEntityId) {
1639
+ const topology = requireClipTopology(draft, clipEntityId);
1640
+ assertOnlyStructuralIncidents(draft, topology.clip.entityId, new Set([
1641
+ "track-clip",
1642
+ "clip-marker",
1643
+ "clip-anchor"
1644
+ ]));
1645
+ assertOnlyStructuralIncidents(draft, topology.marker.entityId, new Set(["clip-marker", "marker-content"]));
1646
+ const markerIsExclusive = incidentRelations(draft, topology.marker.entityId).filter((relation) => relation.relationKind === "clip-marker").length === 1;
1647
+ const removed = new Set(incidentRelations(draft, topology.clip.entityId).map((relation) => relation.relationId));
1648
+ if (markerIsExclusive) for (const relation of incidentRelations(draft, topology.marker.entityId)) removed.add(relation.relationId);
1649
+ draft.relations = draft.relations.filter((relation) => !removed.has(relation.relationId));
1650
+ draft.entities = draft.entities.filter((entity) => entity.entityId !== topology.clip.entityId && (!markerIsExclusive || entity.entityId !== topology.marker.entityId));
1651
+ }
1652
+ transact(edit) {
1653
+ const draft = cloneRows(this.state);
1654
+ const result = edit(draft);
1655
+ validateFinalRows(draft);
1656
+ assertMediaAssetWritePolicy(this.state, draft);
1657
+ this.state = draft;
1658
+ return result;
1659
+ }
1660
+ mintEntityId(draft) {
1661
+ const entityId = createEntityId(this.idFactory("entity"));
1662
+ if (draft.entities.some((entity) => entity.entityId === entityId)) throw new Error(`Entity id "${entityId}" already exists`);
1663
+ return entityId;
1664
+ }
1665
+ createRelation(draft, relationKind, endpoint0EntityId, endpoint1EntityId, metadata = {}) {
1666
+ return {
1667
+ relationId: this.mintRelationId(draft),
1668
+ relationKind,
1669
+ endpoint0EntityId,
1670
+ endpoint1EntityId,
1671
+ metadata,
1672
+ trace: {}
1673
+ };
1674
+ }
1675
+ relinkRelation(draft, relation, endpoints) {
1676
+ const relationId = this.mintRelationId(draft);
1677
+ const index = draft.relations.findIndex((candidate) => candidate.relationId === relation.relationId);
1678
+ if (index < 0) throw new Error(`Relation id "${relation.relationId}" does not exist`);
1679
+ draft.relations[index] = {
1680
+ ...relation,
1681
+ ...endpoints,
1682
+ relationId
1683
+ };
1684
+ }
1685
+ mintRelationId(draft) {
1686
+ const relationId = createRelationId(this.idFactory("relation"));
1687
+ if (draft.relations.some((relation) => relation.relationId === relationId)) throw new Error(`Relation id "${relationId}" already exists`);
1688
+ return relationId;
1689
+ }
1690
+ };
1691
+ function validateFinalRows(rows) {
1692
+ decodeEntityRelationRows(rows, numericMarkerValidation);
1693
+ assertCanonicalEditorResources(rows);
1694
+ validateTimelineHierarchy(rows);
1695
+ }
1696
+ function validateTimelineHierarchy(rows) {
1697
+ for (const entity of rows.entities) {
1698
+ if (entity.entityKind === "track") requireTrackTimeline(rows, entity.entityId);
1699
+ if (entity.entityKind !== "clip") continue;
1700
+ const trackRelations = incidentRelations(rows, entity.entityId).filter((relation) => relation.relationKind === "track-clip");
1701
+ if (trackRelations.length !== 1) throw new Error(`Clip Entity "${entity.entityId}" must belong to exactly one Track`);
1702
+ requireEntityKind(rows, otherEndpoint(trackRelations[0], entity.entityId), "track");
1703
+ }
1704
+ }
1705
+ function requireTrackTimeline(rows, trackEntityId) {
1706
+ const timelineRelations = incidentRelations(rows, trackEntityId).filter((relation) => relation.relationKind === "timeline-track");
1707
+ if (timelineRelations.filter((relation) => {
1708
+ const otherId = otherEndpoint(relation, trackEntityId);
1709
+ return rows.entities.some((entity) => entity.entityId === otherId && entity.entityKind === "timeline");
1710
+ }).length !== 1 || timelineRelations.length !== 1) throw new Error(`Track Entity "${trackEntityId}" must belong to exactly one Timeline`);
1711
+ }
1712
+ function requireClipTopology(rows, clipEntityId) {
1713
+ const clip = requireEntityKind(rows, clipEntityId, "clip");
1714
+ const trackRelation = requireOneRelation(rows, clip.entityId, "track-clip");
1715
+ requireEntityKind(rows, otherEndpoint(trackRelation, clip.entityId), "track");
1716
+ const clipMarkerRelation = requireOneRelation(rows, clip.entityId, "clip-marker");
1717
+ const marker = requireEntityKind(rows, otherEndpoint(clipMarkerRelation, clip.entityId), "sequence-marker");
1718
+ const markerContentRelation = requireOneRelation(rows, marker.entityId, "marker-content");
1719
+ requireSequenceContent(rows, otherEndpoint(markerContentRelation, marker.entityId));
1720
+ return {
1721
+ clip,
1722
+ marker,
1723
+ trackRelation,
1724
+ clipMarkerRelation,
1725
+ markerContentRelation
1726
+ };
1727
+ }
1728
+ function requireOneRelation(rows, entityId, relationKind) {
1729
+ const matches = incidentRelations(rows, entityId).filter((relation) => relation.relationKind === relationKind);
1730
+ if (matches.length !== 1) throw new Error(`Entity "${entityId}" must have exactly one ${relationKind} Relation`);
1731
+ return matches[0];
1732
+ }
1733
+ function requireEntityKind(rows, entityIdValue, entityKind) {
1734
+ const entityId = createEntityId(entityIdValue);
1735
+ const entity = rows.entities.find((candidate) => candidate.entityId === entityId);
1736
+ if (entity == null) throw new Error(`Entity id "${entityId}" does not exist`);
1737
+ if (entity.entityKind !== entityKind) throw new Error(`Entity "${entityId}" must have kind "${entityKind}", got "${entity.entityKind}"`);
1738
+ return entity;
1739
+ }
1740
+ function requireSequenceContent(rows, entityIdValue) {
1741
+ 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");
1742
+ const entityId = createEntityId(entityIdValue);
1743
+ const row = rows.entities.find((candidate) => candidate.entityId === entityId);
1744
+ if (row == null) throw new Error(`Timeline content must reference an existing Sequence media Entity; "${entityId}" was not found`);
1745
+ if (!hasSequence({
1746
+ ...row.payload,
1747
+ entityId: row.entityId,
1748
+ entityKind: row.entityKind
1749
+ })) throw new Error(`Timeline content must reference a Sequence media Entity, but "${entityId}" has kind "${row.entityKind}"`);
1750
+ return row;
1751
+ }
1752
+ function assertOnlyStructuralIncidents(rows, entityId, allowedKinds) {
1753
+ const unsupported = incidentRelations(rows, entityId).filter((relation) => !allowedKinds.has(relation.relationKind));
1754
+ if (unsupported.length === 0) return;
1755
+ throw new Error(`Cannot delete Clip graph: Entity "${entityId}" has unsupported incident Relation id(s): ${unsupported.map((relation) => relation.relationId).sort().join(", ")}`);
1756
+ }
1757
+ function incidentRelations(rows, entityId) {
1758
+ return rows.relations.filter((relation) => relation.endpoint0EntityId === entityId || relation.endpoint1EntityId === entityId);
1759
+ }
1760
+ function hasOutgoingClipAnchor(rows, clipEntityId) {
1761
+ return rows.relations.some((relation) => relation.relationKind === "clip-anchor" && relation.endpoint0EntityId === clipEntityId);
1762
+ }
1763
+ function outgoingAnchorChildren(rows, hostIds) {
1764
+ return rows.relations.filter((relation) => relation.relationKind === "clip-anchor" && hostIds.has(relation.endpoint1EntityId)).map((relation) => String(relation.endpoint0EntityId));
1765
+ }
1766
+ function applyPlacementPayload(clipPayload, placement) {
1767
+ if (placement.kind === "sequential") {
1768
+ clipPayload.order = finiteNumber(placement.order, "Clip order");
1769
+ return {};
1770
+ }
1771
+ if (placement.kind === "absolute") return { targetRange: cloneJsonValue(placement.targetRange, "targetRange") };
1772
+ return { anchorOffset: finiteNonNegative(placement.anchorOffset, "anchorOffset") };
1773
+ }
1774
+ function requireAvailableEntityId(rows, value) {
1775
+ const entityId = createEntityId(value);
1776
+ if (rows.entities.some((entity) => entity.entityId === entityId)) throw new Error(`Entity id "${entityId}" already exists`);
1777
+ return entityId;
1778
+ }
1779
+ function setClipOrder(rows, clipEntityId, order) {
1780
+ const clip = requireEntityKind(rows, clipEntityId, "clip");
1781
+ replaceEntity(rows, clip.entityId, {
1782
+ ...clip,
1783
+ payload: {
1784
+ ...clip.payload,
1785
+ order
1786
+ }
1787
+ });
1788
+ }
1789
+ function normalizeSequentialOrders(rows) {
1790
+ 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));
1791
+ }
1792
+ function findRoleTrack(rows, timelineEntityId, role) {
1793
+ const timeline = requireEntityKind(rows, timelineEntityId, "timeline");
1794
+ 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);
1795
+ if (tracks.length > 1) throw new Error(`Timeline "${timelineEntityId}" has multiple ${role} Tracks`);
1796
+ return tracks[0];
1797
+ }
1798
+ function clipsOnTrack(rows, trackEntityId) {
1799
+ return incidentRelations(rows, trackEntityId).filter((relation) => relation.relationKind === "track-clip").map((relation) => requireEntityKind(rows, otherEndpoint(relation, trackEntityId), "clip"));
1800
+ }
1801
+ function clipRole(rows, clipEntityId) {
1802
+ const topology = requireClipTopology(rows, clipEntityId);
1803
+ return requireEntityKind(rows, otherEndpoint(topology.trackRelation, topology.clip.entityId), "track").payload.role;
1804
+ }
1805
+ function directAnchorChildren(rows, hostClipEntityId) {
1806
+ return rows.relations.filter((relation) => relation.relationKind === "clip-anchor" && relation.endpoint1EntityId === hostClipEntityId).map((relation) => String(relation.endpoint0EntityId));
1807
+ }
1808
+ function requireSupportedRole(rows, topology) {
1809
+ const role = requireEntityKind(rows, otherEndpoint(topology.trackRelation, topology.clip.entityId), "track").payload.role;
1810
+ if (role !== "video_clip" && role !== "speech" && role !== "caption" && role !== "bgm") throw new Error(`Clip "${topology.clip.entityId}" is not on a supported timeline Track`);
1811
+ return role;
1812
+ }
1813
+ function requireClipOnRole(rows, clipEntityId, role) {
1814
+ const topology = requireClipTopology(rows, clipEntityId);
1815
+ if (requireEntityKind(rows, otherEndpoint(topology.trackRelation, topology.clip.entityId), "track").payload.role !== role) throw new Error(`Clip "${clipEntityId}" must belong to the ${role} Track`);
1816
+ return topology;
1817
+ }
1818
+ function finiteNumber(value, label) {
1819
+ if (!Number.isFinite(value)) throw new Error(`${label} must be finite`);
1820
+ return value;
1821
+ }
1822
+ function finitePositive(value, label) {
1823
+ const result = finiteNumber(value, label);
1824
+ if (result <= 0) throw new Error(`${label} must be positive`);
1825
+ return result;
1826
+ }
1827
+ function requireVolume(value) {
1828
+ const volume = finiteNumber(value, "Clip volume");
1829
+ if (volume < -60 || volume > 20) throw new Error("Clip volume must be between -60 and 20 dB");
1830
+ return volume;
1831
+ }
1832
+ function requirePositiveRange(value, label) {
1833
+ if (!isJsonObject(value)) throw new Error(`${label} must be an object`);
1834
+ const start = finiteNonNegative(value.start, `${label}.start`);
1835
+ const end = finitePositive(value.end, `${label}.end`);
1836
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || end <= start) throw new Error(`${label} must be a positive whole-millisecond range`);
1837
+ return {
1838
+ start,
1839
+ end
1840
+ };
1841
+ }
1842
+ function markerDuration(payload, sourceRange) {
1843
+ const duration = payload.duration;
1844
+ if (!isJsonObject(duration)) throw new Error("Sequence Marker duration must be an object");
1845
+ if (duration.mode === "from-source") return sourceRange.end - sourceRange.start;
1846
+ if (duration.mode !== "fixed") throw new Error("Sequence Marker duration mode is unsupported");
1847
+ return finitePositive(duration.value, "Sequence Marker fixed duration");
1848
+ }
1849
+ function linearRate(value) {
1850
+ if (value === void 0) return 1;
1851
+ if (!isJsonObject(value) || value.kind !== "linear") throw new Error("Only linear Clip time remapping is supported");
1852
+ return finitePositive(value.rate, "linear speed rate");
1853
+ }
1854
+ function resizeAbsoluteTarget(payload, duration) {
1855
+ if (payload.targetRange === void 0) return;
1856
+ const target = requirePositiveRange(payload.targetRange, "targetRange");
1857
+ payload.targetRange = {
1858
+ start: target.start,
1859
+ end: target.start + duration
1860
+ };
1861
+ }
1862
+ function replaceRows(rows, replacement) {
1863
+ rows.entities = structuredClone([...replacement.entities]);
1864
+ rows.relations = structuredClone([...replacement.relations]);
1865
+ }
1866
+ function finiteNonNegative(value, label) {
1867
+ const result = finiteNumber(value, label);
1868
+ if (result < 0) throw new Error(`${label} must be non-negative`);
1869
+ return result;
1870
+ }
1871
+ function nextSequentialOrder(rows, trackEntityId) {
1872
+ 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));
1873
+ return orders.length === 0 ? 0 : Math.max(...orders) + 1;
1874
+ }
1875
+ function otherEndpoint(relation, entityId) {
1876
+ if (relation.endpoint0EntityId === entityId) return relation.endpoint1EntityId;
1877
+ if (relation.endpoint1EntityId === entityId) return relation.endpoint0EntityId;
1878
+ throw new Error(`Relation "${relation.relationId}" is not incident to Entity "${entityId}"`);
1879
+ }
1880
+ function replaceEntity(rows, entityId, replacement) {
1881
+ const index = rows.entities.findIndex((entity) => entity.entityId === entityId);
1882
+ if (index < 0) throw new Error(`Entity id "${entityId}" does not exist`);
1883
+ rows.entities[index] = replacement;
1884
+ }
1885
+ function markerPayload(value) {
1886
+ return cloneJsonObject(value, "Sequence Marker payload");
1887
+ }
1888
+ function cloneJsonObject(value, label) {
1889
+ const cloned = structuredClone(value);
1890
+ if (!isJsonObject(cloned)) throw new Error(`${label} must contain only JSON values`);
1891
+ return cloned;
1892
+ }
1893
+ function cloneJsonValue(value, label) {
1894
+ return cloneJsonObject({ value }, label).value;
1895
+ }
1896
+ function cloneRows(rows) {
1897
+ return {
1898
+ entities: rows.entities.map((entity) => structuredClone(entity)),
1899
+ relations: rows.relations.map((relation) => structuredClone(relation))
1900
+ };
1901
+ }
1902
+ const numericMarkerValidation = { compareMarkerPoints: (_marker, _range, left, right) => {
1903
+ if (typeof left !== "number" || !Number.isFinite(left) || typeof right !== "number" || !Number.isFinite(right)) throw new Error("Sequence Marker points must use finite numeric coordinates");
1904
+ return left - right;
1905
+ } };
1906
+ //#endregion
1907
+ //#region src/entity-editor/legacy-entity-migration.ts
1908
+ /** One-time import only. Ordinary editor operations must never reverse-diff a legacy document. */
1909
+ function migrateLegacyTimelineToEntities(legacy, assetFacts, initial = {
1910
+ entities: [],
1911
+ relations: []
1912
+ }, idFactory = (prefix) => `${prefix}_${globalThis.crypto.randomUUID()}`) {
1913
+ assertSupportedLegacy(legacy);
1914
+ if (initial.entities.some((row) => row.entityKind === "timeline")) fail("Timeline already exists; migration is not an editing operation");
1915
+ if (legacy.meta.schema_version === "video-document/entity-projection-v1") fail("An entity projection cannot be migrated as legacy state");
1916
+ const normalizedMainRanges = overlapNormalizedMainRanges(legacy);
1917
+ let entities = structuredClone([...initial.entities]);
1918
+ let relations = structuredClone([...initial.relations]);
1919
+ const addEntity = (kind, payload, existingId) => {
1920
+ const entityId = createEntityId(existingId ?? idFactory("entity"));
1921
+ if (entities.some((row) => row.entityId === entityId)) fail(`Migration entity identity collision: ${entityId}`);
1922
+ entities.push({
1923
+ entityId,
1924
+ entityKind: kind,
1925
+ payload
1926
+ });
1927
+ return entityId;
1928
+ };
1929
+ const link = (kind, from, to, metadata = {}) => {
1930
+ const relationId = createRelationId(idFactory("relation"));
1931
+ if (relations.some((row) => row.relationId === relationId)) fail(`Migration relation identity collision: ${relationId}`);
1932
+ relations.push({
1933
+ relationId,
1934
+ relationKind: kind,
1935
+ endpoint0EntityId: createEntityId(from),
1936
+ endpoint1EntityId: createEntityId(to),
1937
+ metadata,
1938
+ trace: {}
1939
+ });
1940
+ };
1941
+ const facts = /* @__PURE__ */ new Map();
1942
+ for (const fact of assetFacts) {
1943
+ if (facts.has(fact.assetId)) fail(`Duplicate asset facts for ${fact.assetId}`);
1944
+ facts.set(fact.assetId, fact);
1945
+ }
1946
+ const contentByPartId = /* @__PURE__ */ new Map();
1947
+ const scriptBySpeechClipId = /* @__PURE__ */ new Map();
1948
+ for (const track of legacy.tracks ?? []) for (const item of track.items ?? []) {
1949
+ const part = requirePart(legacy, item.part_id);
1950
+ if (part.video_clip !== void 0) {
1951
+ const assetId = part.video_clip.origin_media_id;
1952
+ const fact = facts.get(assetId);
1953
+ if (fact === void 0) fail(`Missing factual media metadata for ${assetId}`);
1954
+ if (fact.kind !== "image" && fact.kind !== "video") fail(`Legacy video Clip ${item.part_id} requires an image or video fact`);
1955
+ const imported = importMediaAsset({
1956
+ entities,
1957
+ relations
1958
+ }, fact, idFactory);
1959
+ entities = [...imported.rows.entities];
1960
+ relations = [...imported.rows.relations];
1961
+ contentByPartId.set(item.part_id, imported.contentEntityId);
1962
+ } else if (part.speech !== void 0) {
1963
+ const speech = part.speech;
1964
+ const imported = importMediaAsset({
1965
+ entities,
1966
+ relations
1967
+ }, {
1968
+ assetId: speech.origin_speech_id,
1969
+ kind: "voice",
1970
+ durationMs: speech.media_duration_ms,
1971
+ storageKey: speech.audio_storage_key,
1972
+ voice: {
1973
+ system: "voice-library",
1974
+ key: speech.voice.id,
1975
+ ...speech.voice.name === void 0 ? {} : { name: speech.voice.name }
1976
+ }
1977
+ }, idFactory);
1978
+ entities = [...imported.rows.entities];
1979
+ relations = [...imported.rows.relations];
1980
+ contentByPartId.set(item.part_id, imported.contentEntityId);
1981
+ scriptBySpeechClipId.set(item.part_id, ensureAudioScript(imported.contentEntityId, speech.audio_script, entities, relations, addEntity, link));
1982
+ } else if (part.bgm !== void 0) {
1983
+ const bgm = part.bgm;
1984
+ const fact = facts.get(bgm.origin_media_id);
1985
+ if (fact === void 0) fail(`Missing factual media metadata for ${bgm.origin_media_id}`);
1986
+ if (fact.kind !== "audio") fail(`Legacy BGM ${item.part_id} requires an audio fact`);
1987
+ if (fact.storageKey !== bgm.audio_storage_key) fail(`Factual storage key conflicts with legacy BGM ${item.part_id}`);
1988
+ const imported = importMediaAsset({
1989
+ entities,
1990
+ relations
1991
+ }, fact, idFactory);
1992
+ entities = [...imported.rows.entities];
1993
+ relations = [...imported.rows.relations];
1994
+ contentByPartId.set(item.part_id, imported.contentEntityId);
1995
+ }
1996
+ }
1997
+ const timeline = addEntity("timeline", legacy.timeline?.unit_time_ms === void 0 ? {} : { unit_time_ms: legacy.timeline.unit_time_ms });
1998
+ const trackIds = /* @__PURE__ */ new Map();
1999
+ for (const [order, oldTrack] of (legacy.tracks ?? []).entries()) {
2000
+ const track = addEntity("track", {
2001
+ role: oldTrack.parts_kind,
2002
+ order,
2003
+ ...oldTrack.is_hidden === void 0 ? {} : { hidden: oldTrack.is_hidden }
2004
+ }, oldTrack.id);
2005
+ trackIds.set(oldTrack, track);
2006
+ link("timeline-track", timeline, track);
2007
+ }
2008
+ for (const oldTrack of legacy.tracks ?? []) {
2009
+ const track = trackIds.get(oldTrack);
2010
+ for (const [order, item] of (oldTrack.items ?? []).entries()) {
2011
+ const part = requirePart(legacy, item.part_id);
2012
+ const role = oldTrack.parts_kind;
2013
+ const volume = part.video_clip?.volume ?? part.speech?.volume ?? part.bgm?.volume;
2014
+ const clip = addEntity("clip", {
2015
+ ...volume === void 0 ? {} : { volume },
2016
+ ...item.time_position.mode === "sequential" && !(role === "video_clip" && normalizedMainRanges !== void 0) || role === "bgm" ? { order: role === "bgm" ? 0 : order } : {}
2017
+ }, item.part_id);
2018
+ let content = contentByPartId.get(item.part_id);
2019
+ let duration;
2020
+ let markerPayload;
2021
+ if (part.video_clip !== void 0) {
2022
+ const video = part.video_clip;
2023
+ duration = effectiveVideoClipDurationMs(video);
2024
+ const fact = facts.get(video.origin_media_id);
2025
+ const rate = speedOf(video.speed_shift);
2026
+ markerPayload = {
2027
+ sourceRange: {
2028
+ start: video.play_in,
2029
+ end: video.play_out
2030
+ },
2031
+ duration: {
2032
+ mode: "fixed",
2033
+ value: duration
2034
+ },
2035
+ ...(fact.kind === "image" || fact.kind === "video") && video.speed_shift !== void 0 ? { timeRemapping: {
2036
+ kind: "linear",
2037
+ mode: video.speed_shift?.mode ?? "constant",
2038
+ rate
2039
+ } } : {}
2040
+ };
2041
+ } else if (part.speech !== void 0) {
2042
+ duration = part.speech.media_duration_ms;
2043
+ markerPayload = {
2044
+ sourceRange: {
2045
+ start: 0,
2046
+ end: duration
2047
+ },
2048
+ duration: {
2049
+ mode: "fixed",
2050
+ value: duration
2051
+ }
2052
+ };
2053
+ } else if (part.caption !== void 0) {
2054
+ const caption = part.caption;
2055
+ duration = caption.initial_duration_ms;
2056
+ content = addEntity("caption", {
2057
+ extent: {
2058
+ kind: "bounded",
2059
+ start: 0,
2060
+ end: duration
2061
+ },
2062
+ sampling: "native",
2063
+ coordinateSpace: "milliseconds",
2064
+ text: caption.text,
2065
+ ...caption.style === void 0 ? {} : { style: toEntityCaptionStyle(caption.style) }
2066
+ });
2067
+ const asset = addEntity("asset", { inline: {
2068
+ mediaType: "text/plain",
2069
+ text: caption.text
2070
+ } });
2071
+ link("physical-asset", content, asset);
2072
+ const voice = contentByPartId.get(caption.speech_part_id);
2073
+ const script = scriptBySpeechClipId.get(caption.speech_part_id);
2074
+ link("caption-alignment", content, voice, { alignment: {
2075
+ start: caption.start_ms,
2076
+ end: caption.start_ms + duration
2077
+ } });
2078
+ link("caption-provenance", content, script, { segmentAlignment: [] });
2079
+ markerPayload = {
2080
+ sourceRange: {
2081
+ start: 0,
2082
+ end: duration
2083
+ },
2084
+ duration: {
2085
+ mode: "fixed",
2086
+ value: duration
2087
+ }
2088
+ };
2089
+ } else {
2090
+ const bgm = part.bgm;
2091
+ const fact = facts.get(bgm.origin_media_id);
2092
+ if (fact.kind !== "audio") fail(`Legacy BGM ${item.part_id} requires an audio fact`);
2093
+ duration = fact.durationMs;
2094
+ markerPayload = {
2095
+ sourceRange: {
2096
+ start: 0,
2097
+ end: duration
2098
+ },
2099
+ duration: { mode: "from-source" },
2100
+ durationPolicy: "timeline"
2101
+ };
2102
+ }
2103
+ if (content === void 0) fail(`Migration could not resolve content for ${item.part_id}`);
2104
+ const normalizedMainRange = role === "video_clip" ? normalizedMainRanges?.get(item.part_id) : void 0;
2105
+ if (normalizedMainRange !== void 0) markerPayload = {
2106
+ ...markerPayload,
2107
+ targetRange: normalizedMainRange
2108
+ };
2109
+ else if (item.time_position.mode === "absolute" && role !== "bgm") markerPayload = {
2110
+ ...markerPayload,
2111
+ targetRange: {
2112
+ start: item.time_position.offsetMs,
2113
+ end: item.time_position.offsetMs + duration
2114
+ }
2115
+ };
2116
+ else if (item.time_position.mode === "anchored") markerPayload = {
2117
+ ...markerPayload,
2118
+ anchorOffset: item.time_position.offsetMs
2119
+ };
2120
+ const marker = addEntity("sequence-marker", markerPayload);
2121
+ link("track-clip", track, clip);
2122
+ link("clip-marker", clip, marker);
2123
+ link("marker-content", marker, content);
2124
+ if (item.time_position.mode === "anchored") link("clip-anchor", clip, item.time_position.anchorPartId);
2125
+ }
2126
+ }
2127
+ const rows = {
2128
+ entities,
2129
+ relations
2130
+ };
2131
+ assertEntityProjectionPreservesLegacy(legacy, projectEntityTimeline(rows, legacy.meta), rows);
2132
+ return rows;
2133
+ }
2134
+ /** Server gate: a cutover may change representation, never the existing render facts. */
2135
+ function assertEntityProjectionPreservesLegacy(legacy, projection, rows) {
2136
+ assertSupportedLegacy(legacy);
2137
+ if (projection.meta.schema_version !== "video-document/entity-projection-v1") fail("Expected an entity projection for migration");
2138
+ const normalizedMainRanges = overlapNormalizedMainRanges(legacy);
2139
+ const compatibilityFacts = (document) => {
2140
+ const { version: _version, ...view } = fromVideoDocument(document);
2141
+ for (const part of Object.values(view.part_library ?? {})) {
2142
+ const speech = part.speech;
2143
+ if (speech?.phoneme_script === null) delete speech.phoneme_script;
2144
+ }
2145
+ const { schema_version: _schemaVersion, version: _metaVersion, ...meta } = document.meta;
2146
+ return {
2147
+ meta,
2148
+ view
2149
+ };
2150
+ };
2151
+ if (canonical(compatibilityFacts(legacy)) !== canonical(compatibilityFacts(projection))) fail("Entity migration must preserve all existing timeline facts; edit after cutover");
2152
+ const trackOrders = [];
2153
+ for (const oldTrack of legacy.tracks ?? []) {
2154
+ const candidates = rows.entities.filter((row) => row.entityKind === "track" && (oldTrack.id === void 0 ? row.payload.role === oldTrack.parts_kind : row.entityId === oldTrack.id));
2155
+ if (candidates.length !== 1) fail("Migration must preserve every Track identity");
2156
+ const track = candidates[0];
2157
+ if (track.payload.role !== oldTrack.parts_kind || (track.payload.hidden ?? false) !== (oldTrack.is_hidden ?? false)) fail("Migration must preserve Track role and visibility");
2158
+ if (typeof track.payload.order !== "number" || !Number.isFinite(track.payload.order)) fail("Migration must preserve Track order");
2159
+ trackOrders.push(track.payload.order);
2160
+ const sequentialOrders = [];
2161
+ for (const item of oldTrack.items ?? []) {
2162
+ const clip = rows.entities.find((row) => row.entityId === item.part_id && row.entityKind === "clip");
2163
+ 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"));
2164
+ const marker = rows.entities.find((row) => row.entityId === binding[0]?.endpoint1EntityId && row.entityKind === "sequence-marker");
2165
+ if (clip === void 0 || binding.length !== 1 || marker === void 0) fail("Migration must preserve Clip/Marker placement identity");
2166
+ const anchors = rows.relations.filter((row) => row.relationKind === "clip-anchor" && row.endpoint0EntityId === clip.entityId);
2167
+ const normalizedMainRange = oldTrack.parts_kind === "video_clip" ? normalizedMainRanges?.get(item.part_id) : void 0;
2168
+ if (normalizedMainRange !== void 0) {
2169
+ 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");
2170
+ } else if (oldTrack.parts_kind === "bgm") {
2171
+ 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");
2172
+ } else if (item.time_position.mode === "sequential") {
2173
+ 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");
2174
+ sequentialOrders.push(clip.payload.order);
2175
+ } else if (item.time_position.mode === "absolute") {
2176
+ const target = marker.payload.targetRange;
2177
+ 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");
2178
+ } 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");
2179
+ }
2180
+ if (sequentialOrders.some((order, index) => index > 0 && order <= sequentialOrders[index - 1])) fail("Migration must preserve sequential Clip order");
2181
+ }
2182
+ if (trackOrders.some((order, index) => index > 0 && order <= trackOrders[index - 1])) fail("Migration must preserve Track stacking order");
2183
+ }
2184
+ function assertSupportedLegacy(document) {
2185
+ assertValidVideoDocument(document);
2186
+ const tracks = document.tracks ?? [];
2187
+ assertKnownFields(document.timeline ?? {}, ["unit_time_ms"], "Timeline");
2188
+ 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");
2189
+ const seenRoles = /* @__PURE__ */ new Set();
2190
+ const placed = /* @__PURE__ */ new Map();
2191
+ for (const track of tracks) {
2192
+ const role = track.parts_kind;
2193
+ if (role === void 0 || ![
2194
+ "video_clip",
2195
+ "speech",
2196
+ "caption",
2197
+ "bgm"
2198
+ ].includes(role)) fail("Every legacy Track requires a supported role");
2199
+ if (seenRoles.has(role)) fail(`The compatibility editor supports only one ${role} Track`);
2200
+ seenRoles.add(role);
2201
+ if (track.id !== void 0 && (track.id.trim() === "" || track.id.trim() !== track.id)) fail("Migration requires trimmed Track identities");
2202
+ for (const item of track.items ?? []) {
2203
+ if (item.part_id.trim() === "" || item.part_id.trim() !== item.part_id) fail("Migration requires trimmed Clip identities");
2204
+ if (placed.has(item.part_id)) fail(`Legacy part ${item.part_id} is placed more than once`);
2205
+ placed.set(item.part_id, {
2206
+ track,
2207
+ item
2208
+ });
2209
+ assertKnownFields(item.time_position, item.time_position.mode === "sequential" ? ["mode"] : [
2210
+ "mode",
2211
+ "anchorPartId",
2212
+ "offsetMs"
2213
+ ], "placement");
2214
+ if (item.time_position.mode === "absolute") requireMilliseconds(item.time_position.offsetMs, "absolute offset");
2215
+ if (item.time_position.mode === "anchored") {
2216
+ if (item.time_position.anchorPartId.trim() === "" || item.time_position.anchorPartId.trim() !== item.time_position.anchorPartId) fail("Migration requires a trimmed anchor identity");
2217
+ requireMilliseconds(item.time_position.offsetMs, "anchor offset");
2218
+ }
2219
+ if (item.fallback_abs_ms !== void 0) requireMilliseconds(item.fallback_abs_ms, "anchor fallback");
2220
+ assertKnownFields(item, [
2221
+ "part_id",
2222
+ "time_position",
2223
+ "fallback_abs_ms"
2224
+ ], "TrackItem");
2225
+ }
2226
+ assertKnownFields(track, [
2227
+ "id",
2228
+ "parts_kind",
2229
+ "is_hidden",
2230
+ "items"
2231
+ ], "Track");
2232
+ }
2233
+ for (const [id, part] of Object.entries(document.part_library ?? {})) {
2234
+ const placement = placed.get(id);
2235
+ if (placement === void 0) fail(`Cannot discard unplaced legacy part ${id}`);
2236
+ assertPartSupported(id, part, placement.track.parts_kind);
2237
+ }
2238
+ for (const id of placed.keys()) if (document.part_library?.[id] === void 0) fail(`Placed Clip ${id} has no part payload`);
2239
+ assertLegacyRelations(document, placed);
2240
+ }
2241
+ function assertPartSupported(id, part, role) {
2242
+ assertKnownFields(part, [
2243
+ "video_clip",
2244
+ "speech",
2245
+ "caption",
2246
+ "bgm"
2247
+ ], "Part");
2248
+ const present = [
2249
+ "video_clip",
2250
+ "speech",
2251
+ "caption",
2252
+ "bgm"
2253
+ ].filter((kind) => part[kind] !== void 0);
2254
+ if (present.length !== 1 || present[0] !== role) fail(`Legacy part ${id} must match its ${role} Track`);
2255
+ if (part.video_clip !== void 0) {
2256
+ const clip = part.video_clip;
2257
+ 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");
2258
+ requireMilliseconds(clip.play_in, "Clip play_in");
2259
+ requireMilliseconds(clip.play_out, "Clip play_out");
2260
+ if (clip.play_out <= clip.play_in) fail("Migration requires a non-empty Clip trim window");
2261
+ requireFinite(clip.volume, "Clip volume");
2262
+ const speed = clip.speed_shift;
2263
+ 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");
2264
+ if (speed !== void 0) {
2265
+ const rate = speed.config?.linear?.speed;
2266
+ if (typeof rate !== "number" || !Number.isFinite(rate) || rate <= 0) fail("Migration requires a positive finite speed");
2267
+ assertKnownFields(speed, [
2268
+ "category",
2269
+ "mode",
2270
+ "config"
2271
+ ], "speed_shift");
2272
+ assertKnownFields(speed.config, ["linear"], "speed config");
2273
+ assertKnownFields(speed.config.linear, ["speed"], "linear speed");
2274
+ }
2275
+ assertKnownFields(clip, [
2276
+ "id",
2277
+ "kind",
2278
+ "origin_media_id",
2279
+ "play_in",
2280
+ "play_out",
2281
+ "volume",
2282
+ "speed_shift"
2283
+ ], "Clip");
2284
+ } else if (part.speech !== void 0) {
2285
+ const speech = part.speech;
2286
+ const phonemeScript = speech.phoneme_script;
2287
+ 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");
2288
+ requirePositiveMilliseconds(speech.media_duration_ms, "Speech duration");
2289
+ requireFinite(speech.volume, "Speech volume");
2290
+ if (!trimmed(speech.voice?.id)) fail("Migration requires an explicit voice-library identity");
2291
+ if (speech.voice?.name !== void 0 && typeof speech.voice.name !== "string") fail("Migration requires a string voice name when present");
2292
+ if (!Array.isArray(speech.caption_ids) || speech.caption_ids.some((captionId) => !trimmed(captionId))) fail("Migration requires explicit Speech caption identities");
2293
+ if (new Set(speech.caption_ids).size !== speech.caption_ids.length) fail("Migration requires unique Speech caption identities");
2294
+ if (phonemeScript !== void 0 && phonemeScript !== null) fail("Non-null phoneme_script requires a phonetic-script migration adapter");
2295
+ assertKnownFields(speech.voice, ["id", "name"], "voice");
2296
+ assertKnownFields(speech, [
2297
+ "id",
2298
+ "kind",
2299
+ "media_duration_ms",
2300
+ "audio_script",
2301
+ "volume",
2302
+ "audio_storage_key",
2303
+ "origin_speech_id",
2304
+ "voice",
2305
+ "caption_ids",
2306
+ "phoneme_script"
2307
+ ], "Speech");
2308
+ } else if (part.caption !== void 0) {
2309
+ const caption = part.caption;
2310
+ 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");
2311
+ requireMilliseconds(caption.start_ms, "Caption source offset");
2312
+ requirePositiveMilliseconds(caption.initial_duration_ms, "Caption duration");
2313
+ if (caption.style !== void 0) assertCaptionStyle(caption.style);
2314
+ assertKnownFields(caption, [
2315
+ "id",
2316
+ "kind",
2317
+ "initial_duration_ms",
2318
+ "speech_part_id",
2319
+ "text",
2320
+ "start_ms",
2321
+ "style"
2322
+ ], "Caption");
2323
+ } else if (part.bgm !== void 0) {
2324
+ const bgm = part.bgm;
2325
+ 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");
2326
+ requireFinite(bgm.volume, "BGM volume");
2327
+ assertKnownFields(bgm, [
2328
+ "id",
2329
+ "kind",
2330
+ "audio_storage_key",
2331
+ "volume",
2332
+ "origin_media_id"
2333
+ ], "BGM");
2334
+ }
2335
+ }
2336
+ function assertLegacyRelations(document, placed) {
2337
+ const captionIdsBySpeech = /* @__PURE__ */ new Map();
2338
+ for (const track of document.tracks ?? []) {
2339
+ if (track.parts_kind === "bgm" && (track.items?.length ?? 0) > 1) fail("The compatibility editor supports only one BGM Clip");
2340
+ for (const item of track.items ?? []) {
2341
+ const part = requirePart(document, item.part_id);
2342
+ const position = item.time_position;
2343
+ if (track.parts_kind === "video_clip" && position.mode === "anchored") fail("Anchored video Clips require an overlay adapter");
2344
+ if (track.parts_kind === "bgm") {
2345
+ if (position.mode !== "absolute" || position.offsetMs !== 0) fail("Legacy BGM must start at the Timeline origin");
2346
+ } else if (position.mode === "anchored") {
2347
+ const host = placed.get(position.anchorPartId);
2348
+ if (host === void 0) fail(`Legacy anchor ${position.anchorPartId} is not placed`);
2349
+ if (track.parts_kind === "speech" && host.track.parts_kind !== "video_clip") fail("Speech may only anchor to a video Clip");
2350
+ if (track.parts_kind === "caption") {
2351
+ if (host.track.parts_kind !== "speech") fail("Caption may only anchor to a Speech Clip");
2352
+ const caption = part.caption;
2353
+ if (position.anchorPartId !== caption.speech_part_id || position.offsetMs !== caption.start_ms) fail("Caption placement must agree with its Speech provenance and source offset");
2354
+ }
2355
+ } else if (track.parts_kind === "caption") fail("Caption placement requires an explicit Speech anchor");
2356
+ if (part.caption !== void 0) {
2357
+ const ids = captionIdsBySpeech.get(part.caption.speech_part_id) ?? [];
2358
+ ids.push(item.part_id);
2359
+ captionIdsBySpeech.set(part.caption.speech_part_id, ids);
2360
+ }
2361
+ }
2362
+ }
2363
+ for (const [id, placement] of placed) {
2364
+ const speech = requirePart(document, id).speech;
2365
+ if (speech === void 0) continue;
2366
+ const expected = captionIdsBySpeech.get(id) ?? [];
2367
+ if (canonical(speech.caption_ids) !== canonical(expected)) fail(`Speech ${id} caption_ids must agree with the Caption Track order`);
2368
+ if (placement.item.time_position.mode === "anchored") continue;
2369
+ if (placement.item.time_position.mode !== "absolute") fail("Speech placement must be anchored or absolute");
2370
+ }
2371
+ const intervals = (fromVideoDocument(document).main_track?.items ?? []).map((item) => {
2372
+ const clip = document.part_library?.[item.part_id]?.video_clip;
2373
+ if (clip === void 0) fail("Projection must preserve every video Clip");
2374
+ return {
2375
+ start: item.abs_time_position ?? 0,
2376
+ end: (item.abs_time_position ?? 0) + effectiveVideoClipDurationMs(clip)
2377
+ };
2378
+ }).sort((left, right) => left.start - right.start);
2379
+ if (intervals.some((interval, index) => index > 0 && interval.start < intervals[index - 1].end)) fail("Overlapping video Clips require an overlay adapter");
2380
+ }
2381
+ /**
2382
+ * Legacy reads perform one speech-overlap pass after laying the visual lane out
2383
+ * sequentially. Entity reads deliberately do not run that hidden cascade. When
2384
+ * the pass moved any visual Clip, cutover therefore records the complete solved
2385
+ * visual lane as explicit target ranges. Mixing absolute and sequential Clips
2386
+ * would create two unrelated placement chains and could reorder the lane.
2387
+ */
2388
+ function overlapNormalizedMainRanges(document) {
2389
+ const track = document.tracks?.find((candidate) => candidate.parts_kind === "video_clip");
2390
+ if (track === void 0 || (track.items?.length ?? 0) === 0) return void 0;
2391
+ const solved = fromVideoDocument(document).main_track?.items ?? [];
2392
+ const starts = new Map(solved.map((item) => [item.part_id, requireMilliseconds(item.abs_time_position, `Solved position for ${item.part_id ?? "unknown Clip"}`)]));
2393
+ let cursor = 0;
2394
+ let moved = false;
2395
+ const ranges = /* @__PURE__ */ new Map();
2396
+ for (const item of track.items ?? []) {
2397
+ const part = requirePart(document, item.part_id).video_clip;
2398
+ if (part === void 0) fail(`Projection must preserve video Clip ${item.part_id}`);
2399
+ const duration = effectiveVideoClipDurationMs(part);
2400
+ const start = starts.get(item.part_id);
2401
+ if (start === void 0) fail(`Projection must preserve video Clip ${item.part_id}`);
2402
+ if (start !== cursor) moved = true;
2403
+ const end = start + duration;
2404
+ requireMilliseconds(end, `Solved end for ${item.part_id}`);
2405
+ ranges.set(item.part_id, {
2406
+ start,
2407
+ end
2408
+ });
2409
+ cursor += duration;
2410
+ }
2411
+ return moved ? ranges : void 0;
2412
+ }
2413
+ function requirePart(document, partId) {
2414
+ const part = document.part_library?.[partId];
2415
+ if (part === void 0) fail(`Placed Clip ${partId} has no part payload`);
2416
+ return part;
2417
+ }
2418
+ function ensureAudioScript(voiceEntityId, text, entities, relations, addEntity, link) {
2419
+ const renders = relations.filter((relation) => relation.relationKind === "audio-script-render" && relation.endpoint0EntityId === voiceEntityId);
2420
+ if (renders.length > 1) fail(`Voice ${voiceEntityId} has ambiguous AudioScript provenance`);
2421
+ if (renders.length === 1) {
2422
+ const script = entities.find((entity) => entity.entityId === renders[0].endpoint1EntityId && entity.entityKind === "audio-script");
2423
+ if (script === void 0 || scriptText(script) !== text) fail(`Voice ${voiceEntityId} conflicts with the legacy Speech script`);
2424
+ return script.entityId;
2425
+ }
2426
+ const script = addEntity("audio-script", { segments: [{
2427
+ segmentId: "segment-0",
2428
+ text
2429
+ }] });
2430
+ link("audio-script-render", voiceEntityId, script);
2431
+ return script;
2432
+ }
2433
+ function scriptText(script) {
2434
+ const segments = script.payload.segments;
2435
+ if (!Array.isArray(segments)) fail("AudioScript requires segments");
2436
+ return segments.map((segment) => {
2437
+ if (segment === null || typeof segment !== "object" || Array.isArray(segment) || typeof segment.text !== "string") fail("AudioScript segment requires text");
2438
+ return segment.text;
2439
+ }).join("");
2440
+ }
2441
+ function toEntityCaptionStyle(style) {
2442
+ return {
2443
+ ...style.font_id === void 0 ? {} : { font: {
2444
+ system: "font-library",
2445
+ key: style.font_id
2446
+ } },
2447
+ ...style.font_size === void 0 ? {} : { fontSize: style.font_size },
2448
+ ...style.font_color === void 0 ? {} : { fontColor: style.font_color },
2449
+ ...style.font_weight === void 0 ? {} : { fontWeight: style.font_weight },
2450
+ ...style.entrance_animation === void 0 ? {} : { entranceAnimation: style.entrance_animation },
2451
+ ...style.entrance_animation_duration_ms === void 0 ? {} : { entranceAnimationDurationMs: style.entrance_animation_duration_ms },
2452
+ ...style.stroke_color === void 0 ? {} : { strokeColor: style.stroke_color },
2453
+ ...style.stroke_width === void 0 ? {} : { strokeWidth: style.stroke_width },
2454
+ ...style.position_x === void 0 ? {} : { positionX: style.position_x },
2455
+ ...style.position_y === void 0 ? {} : { positionY: style.position_y }
2456
+ };
2457
+ }
2458
+ function assertCaptionStyle(style) {
2459
+ if (style.font_id !== void 0 && !trimmed(style.font_id)) fail("Caption font_id must be a trimmed identity");
2460
+ for (const value of [
2461
+ style.font_size,
2462
+ style.font_weight,
2463
+ style.entrance_animation_duration_ms,
2464
+ style.stroke_width,
2465
+ style.position_x,
2466
+ style.position_y
2467
+ ]) if (value !== void 0) requireFinite(value, "Caption style number");
2468
+ for (const value of [
2469
+ style.font_color,
2470
+ style.entrance_animation,
2471
+ style.stroke_color
2472
+ ]) if (value !== void 0 && typeof value !== "string") fail("Caption style text must be a string");
2473
+ assertKnownFields(style, [
2474
+ "font_id",
2475
+ "font_size",
2476
+ "font_color",
2477
+ "font_weight",
2478
+ "entrance_animation",
2479
+ "entrance_animation_duration_ms",
2480
+ "stroke_color",
2481
+ "stroke_width",
2482
+ "position_x",
2483
+ "position_y"
2484
+ ], "Caption style");
2485
+ }
2486
+ function isRangeStartingAt(value, expectedStart) {
2487
+ return value !== null && typeof value === "object" && !Array.isArray(value) && value.start === expectedStart;
2488
+ }
2489
+ function isExactRange(value, expected) {
2490
+ return value !== null && typeof value === "object" && !Array.isArray(value) && value.start === expected.start && value.end === expected.end;
2491
+ }
2492
+ function requireFinite(value, label) {
2493
+ if (typeof value !== "number" || !Number.isFinite(value)) fail(`${label} must be finite`);
2494
+ return value;
2495
+ }
2496
+ function requireMilliseconds(value, label) {
2497
+ const result = requireFinite(value, label);
2498
+ if (!Number.isSafeInteger(result) || result < 0) fail(`${label} must be non-negative whole milliseconds`);
2499
+ return result;
2500
+ }
2501
+ function requirePositiveMilliseconds(value, label) {
2502
+ const result = requireMilliseconds(value, label);
2503
+ if (result <= 0) fail(`${label} must be positive`);
2504
+ return result;
2505
+ }
2506
+ function trimmed(value) {
2507
+ return typeof value === "string" && value.trim() !== "" && value.trim() === value;
2508
+ }
2509
+ function assertKnownFields(value, fields, label) {
2510
+ if (Object.entries(value).some(([key, field]) => field !== void 0 && !fields.includes(key))) fail(`Unknown legacy ${label} fields require an explicit migration adapter`);
2511
+ }
2512
+ function canonical(value) {
2513
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
2514
+ 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(",")}}`;
2515
+ return JSON.stringify(value) ?? "undefined";
2516
+ }
2517
+ function fail(message) {
2518
+ throw new EntityTimelineProjectionError(message);
2519
+ }
2520
+ //#endregion
220
2521
  //#region src/editor/snapshot-utils.ts
221
2522
  function isMap(value) {
222
2523
  return value instanceof Map;
@@ -1615,6 +3916,18 @@ var ManualSyncDoc = class ManualSyncDoc {
1615
3916
  return fromVideoDocument(this.adapter.snapshot());
1616
3917
  }
1617
3918
  /**
3919
+ * Replay a deterministic sandbox journal into this document.
3920
+ *
3921
+ * The adapter stays private so callers cannot bypass the manual-sync
3922
+ * lifecycle; journal replay is the one host-side operation that needs the
3923
+ * adapter's transaction boundary and recorded id queue. Durability is still
3924
+ * explicit: call {@link push} after replay and report success only from its
3925
+ * verdict.
3926
+ */
3927
+ async replayJournal(journal) {
3928
+ await replayJournal(this.adapter, journal);
3929
+ }
3930
+ /**
1618
3931
  * Mark the document state the caller has just observed, for a later
1619
3932
  * {@link hasChangedSince}.
1620
3933
  *
@@ -2139,7 +4452,8 @@ var MengineDocSession = class {
2139
4452
  this.server = new MedeoHttpDocStorage({
2140
4453
  docId: options.docId,
2141
4454
  client: options.client,
2142
- sseReconnectDelayMs: options.sseReconnectDelayMs
4455
+ sseReconnectDelayMs: options.sseReconnectDelayMs,
4456
+ readonlyMode: options.readonlyMode
2143
4457
  });
2144
4458
  this.synchronizer = new ClientServerSynchronizer(this.local, this.server);
2145
4459
  this.manager = new DocManager(this.local, this.synchronizer);
@@ -2342,4 +4656,4 @@ function serverCovers(serverVV, target) {
2342
4656
  return covers(server, target);
2343
4657
  }
2344
4658
  //#endregion
2345
- export { DEFAULT_UNIT_TIME_MS, IMPLEMENTED_SEMANTIC_OP_KINDS, LANE_KINDS_IN_STACK_ORDER, ManualSyncDoc, MedeoHttpDocStorage, MemoryDocStorage, MengineAckFailedError, MengineDocSession, MengineHttpClient, MengineHttpRequestError, MenginePushRejectedError, MirrorVideoDocumentAdapter, PlainMemoryAdapter, SchemaValidator, SemanticEditor, TIMELINE_SKELETON_DURATION_MS, VIDEO_DOCUMENT_SCHEMA_VERSION, ValidationError, VideoDocumentValidationError, arrangeMainTrackSeamlessly, assertValidVideoDocument, base64ToBytes, buildInitialVideoDocument, buildSpeechHostMap, bytesToBase64, cascadeAfterVideoClipChanges, createEditSandbox, createMirrorVideoDocument, createMirrorVideoDocumentAdapter, createPlainMemoryAdapter, decodeDocVersionMark, derivePositionFromAbs, effectiveVideoClipDurationMs, encodeDocVersionMark, ensureLaneTrack, fillMainTrackTimeGaps, findLaneTrack, fromVideoDocument, generatePartId, getAt, hostForAbsMs, isEmptyVideoClip, isImplementedSemanticOpKind, isMap, laneTrackId, mainTrackRanges, partDurationMs, partUnionSchema, readMainTrackItems, readMengineEventStream, readPart, readPartDurationMs, readVideoDocumentFromDraft, reassignSpeechesToVideoClipsByTime, recalculateTimelineDuration, relativePositionForAbs, replayJournal, resolveAllSpeechOverlaps, resolveSpeechOverlapByShiftingVideos, safeDurationMs, schemas_exports as schemas, snapshotToPlain, solveVideoDocument, speedOf, syncAggregatedClipsTimePosition, toVideoDocument, validateVideoDocument, videoDocumentMirrorSchema, videoDocumentSchema, writeVideoDocumentToDraft };
4659
+ export { DEFAULT_UNIT_TIME_MS, ENTITY_TIMELINE_PROJECTION_SCHEMA_VERSION, EntityGraphHttpClient, EntityTimelineEditor, EntityTimelineProjectionError, IMPLEMENTED_SEMANTIC_OP_KINDS, LANE_KINDS_IN_STACK_ORDER, ManualSyncDoc, MedeoHttpDocStorage, MemoryDocStorage, MengineAckFailedError, MengineDocSession, MengineHttpClient, MengineHttpRequestError, MenginePushRejectedError, MirrorVideoDocumentAdapter, PlainMemoryAdapter, SchemaValidator, SemanticEditor, TIMELINE_SKELETON_DURATION_MS, VIDEO_DOCUMENT_SCHEMA_VERSION, ValidationError, VideoDocumentValidationError, applyEntityTimelineProjection, arrangeMainTrackSeamlessly, assertCanonicalEditorResources, assertEntityProjectionPreservesLegacy, assertMediaAssetWritePolicy, assertValidVideoDocument, base64ToBytes, buildInitialVideoDocument, buildSpeechHostMap, bytesToBase64, cascadeAfterVideoClipChanges, createEditSandbox, createMirrorVideoDocument, createMirrorVideoDocumentAdapter, createPlainMemoryAdapter, decodeDocVersionMark, derivePositionFromAbs, effectiveVideoClipDurationMs, encodeDocVersionMark, ensureEditorFoundation, ensureLaneTrack, fillMainTrackTimeGaps, findLaneTrack, fromVideoDocument, generatePartId, getAt, hostForAbsMs, importMediaAsset, isEmptyVideoClip, isImplementedSemanticOpKind, isMap, laneTrackId, mainTrackRanges, migrateLegacyTimelineToEntities, partDurationMs, partUnionSchema, projectEntityTimeline, readMainTrackItems, readMengineEventStream, readPart, readPartDurationMs, readVideoDocumentFromDraft, reassignSpeechesToVideoClipsByTime, recalculateTimelineDuration, relativePositionForAbs, replayJournal, resolveAllSpeechOverlaps, resolveEntityTimelineLayout, resolveSpeechOverlapByShiftingVideos, safeDurationMs, schemas_exports as schemas, snapshotToPlain, solveVideoDocument, speedOf, syncAggregatedClipsTimePosition, toVideoDocument, validateVideoDocument, videoDocumentMirrorSchema, videoDocumentSchema, writeVideoDocumentToDraft };