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