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

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