@mengine/medeo-client 2.0.1-alpha.3 → 2.0.1-alpha.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
- import { $ as VideoDraft, A as assertValidVideoDocument, B as CaptionPart, C as index_d_exports, D as VideoDocumentMirrorSchema, E as VideoDocumentDraft, F as buildSpeechHostMap, G as Timeline, H as PartKind, I as derivePositionFromAbs, J as TrackItemTimePosition, K as Track, L as fromVideoDocument, M as buildInitialVideoDocument, N as DerivedItemPosition, O as videoDocumentMirrorSchema, P as SpeechHostMap, Q as VideoDocumentValidationIssueCode, R as toVideoDocument, S as ValidationError, T as TrackItemDraft, U as PartUnion, V as DEFAULT_UNIT_TIME_MS, W as SpeechPart, X as VideoDocument, Y as VideoClipPart, Z as VideoDocumentValidationIssue, _ as PlannedSemanticOpKind, a as MirrorVideoDocumentOptions, at as PartAggregation, b as SchemaValidator, c as CommitOptions, ct as Track$1, d as SemanticEditor, et as VideoDraftContent, f as SemanticOpInput, g as ImplementedSemanticOpKind, h as IMPLEMENTED_SEMANTIC_OP_KINDS, i as MirrorVideoDocumentAdapter, it as CaptionStyle, j as validateVideoDocument, k as VideoDocumentValidationError, l as OpActor, lt as TrackItem$1, m as TransactAudit, n as videoDocumentSchema, nt as Attachment, o as createMirrorVideoDocument, ot as SpeedShift, p as SemanticOpName, q as TrackItem, r as readVideoDocumentFromDraft, rt as CaptionPart$1, s as createMirrorVideoDocumentAdapter, st as Timeline$1, t as partUnionSchema, tt as VideoDraftPartUnion, u as SemanticDocumentAdapter, v as SemanticOpKind, w as TrackDraft, x as SnapshotReadable, y as isImplementedSemanticOpKind, z as BgmPart } from "./index-CnZ9l3rb.js";
1
+ import { t as index_d_exports } from "./index-CMa6ZCtX.js";
2
+ import { $ as derivePositionFromAbs, A as assertValidVideoDocument, At as VideoDraftContent, B as EntityRow, Bt as Track$1, C as isImplementedSemanticOpKind, Ct as TrackItem, D as PartIdFactory, Dt as VideoDocumentValidationIssue, E as ValidationError, Et as VideoDocument, F as ResolvedEntityTrack, Ft as CaptionPart$1, G as VoiceDescriptor, H as CaptionSegmentSelection, I as resolveEntityTimelineLayout, It as CaptionStyle, J as EntityId, K as JsonObject, L as projectEntityTimeline, Lt as PartAggregation, M as EntityTimelineTrackRole, Mt as effectiveVideoClipDurationMs, N as ResolvedEntityClipPlacement, Nt as speedOf, O as generatePartId, Ot as VideoDocumentValidationIssueCode, P as ResolvedEntityTimelineLayout, Pt as Attachment, Q as buildSpeechHostMap, R as EntityTimelineProjectionError, Rt as SpeedShift, S as SemanticOpKind, St as Track, T as SnapshotReadable, Tt as VideoClipPart, U as CaptionStyleFields, V as RelationRow, Vt as TrackItem$1, W as ScriptTextSegment, X as DerivedItemPosition, Y as buildInitialVideoDocument, Z as SpeechHostMap, _ as SemanticOpName, _t as DEFAULT_UNIT_TIME_MS, a as PlainMemoryAdapter, at as ensureLaneTrack, b as ImplementedSemanticOpKind, bt as SpeechPart, c as MirrorVideoDocumentAdapter, ct as solveVideoDocument, d as createMirrorVideoDocumentAdapter, dt as VideoDocumentDraft, et as fromVideoDocument, f as CommitOptions, ft as VideoDocumentMirrorSchema, g as SemanticOpInput, gt as CaptionPart, h as SemanticEditor, ht as CaptionDisplayCue, i as JournalEntry, it as SolvedVideoDocument, j as validateVideoDocument, jt as VideoDraftPartUnion, k as VideoDocumentValidationError, kt as VideoDraft, l as MirrorVideoDocumentOptions, lt as TrackDraft, m as SemanticDocumentAdapter, mt as BgmPart, n as videoDocumentSchema, nt as LANE_KINDS_IN_STACK_ORDER, o as PlainMemoryAdapterOptions, ot as findLaneTrack, p as OpActor, pt as videoDocumentMirrorSchema, q as JsonValue, r as readVideoDocumentFromDraft, rt as LaneKind, s as createPlainMemoryAdapter, st as laneTrackId, t as partUnionSchema, tt as toVideoDocument, u as createMirrorVideoDocument, ut as TrackItemDraft, v as TransactAudit, vt as PartKind, w as SchemaValidator, wt as TrackItemTimePosition, x as PlannedSemanticOpKind, xt as Timeline, y as IMPLEMENTED_SEMANTIC_OP_KINDS, yt as PartUnion, z as EntityRelationRows, zt as Timeline$1 } from "./index-DaabF2vA.js";
2
3
  import { LoroDoc, PeerID } from "loro-crdt";
3
- import { DocState, LocalSaveState } from "@mengine/sync";
4
+ import { DocState } from "@mengine/sync";
4
5
  import { BaseDocStorage, Connection, DocDiff, DocPushReceipt, DocSnapshotRecord, DocStorage, DocStorageOptions, DocUpdate, DocUpdateRecord } from "@mengine/storage";
5
6
 
6
7
  //#region src/client/base64.d.ts
@@ -178,33 +179,840 @@ interface MengineEventStreamOptions {
178
179
  }
179
180
  declare function readMengineEventStream(options: MengineEventStreamOptions): Promise<void>;
180
181
  //#endregion
181
- //#region src/editor/id-gen.d.ts
182
+ //#region ../medeo-dsl/src/composition.d.ts
183
+ type ScriptCompositionIssueCode = 'field_conflict' | 'composition_cycle' | 'invalid_bases' | 'composition_missing' | 'composition_ambiguous' | 'composition_dangling' | 'unknown_segment' | 'empty_selection' | 'invalid_script' | 'invalid_selection';
184
+ /** Assembly fails explicitly when declared bases cannot provide valid, unambiguous content. */
185
+ declare class ScriptCompositionError extends Error {
186
+ readonly code: ScriptCompositionIssueCode;
187
+ readonly entityId: EntityId;
188
+ constructor(code: ScriptCompositionIssueCode, entityId: EntityId, message: string);
189
+ }
190
+ interface AssembledCaptionContent {
191
+ readonly caption: EntityRow<'caption'>;
192
+ readonly audioScript: EntityRow<'audio-script'>;
193
+ /** Selected AudioScript segments in Caption selection order. */
194
+ readonly segments: readonly ScriptTextSegment[];
195
+ /**
196
+ * Where the selected segment sits in the AudioScript's ordered segments.
197
+ *
198
+ * A Caption locates its text as AudioScript plus index. The selection is
199
+ * stored as the segment's own stable id rather than this ordinal, so a
200
+ * concurrent insert or re-segmentation cannot silently slide a Caption onto
201
+ * different text; the ordinal is derived here for readers that want the
202
+ * position.
203
+ */
204
+ readonly segmentIndex: number;
205
+ /** Complete display text: the selected segments' text joined in order. */
206
+ readonly text: string;
207
+ }
208
+ interface AssembledPhoneticScriptContent {
209
+ readonly phoneticScript: EntityRow<'phonetic-script'>;
210
+ readonly audioScript: EntityRow<'audio-script'>;
211
+ /** All AudioScript segments in script order; the pronunciation variant never reorders text. */
212
+ readonly segments: readonly ScriptTextSegment[];
213
+ /** Complete base text owned by the AudioScript. */
214
+ readonly text: string;
215
+ }
216
+ /** Validate all base providers before applying explicit own fields; ordering cannot resolve ambiguity. */
217
+ declare function assembleEntityContent(rows: EntityRelationRows, entityId: EntityId): EntityRow;
218
+ /** Find the actual AudioScript text owner through direct variant bases. */
219
+ declare function findComposedAudioScript(rows: EntityRelationRows, variantEntityId: EntityId, variantKind: 'caption' | 'phonetic-script'): EntityRow<'audio-script'>;
220
+ /** Join the whole AudioScript text in segment order. */
221
+ declare function assembleScriptText(script: EntityRow<'audio-script'>): string;
222
+ /** Assemble selected text after base-field validation and explicit variant overrides. */
223
+ declare function assembleCaptionContent(rows: EntityRelationRows, captionEntityId: EntityId): AssembledCaptionContent;
182
224
  /**
183
- * Part-id generation, aligned with the online ecosystem.
225
+ * Assemble the complete Phonetic Script content for TTS: the composed
226
+ * AudioScript's base text plus the variant's own phoneme and prosody fields.
227
+ */
228
+ declare function assemblePhoneticScriptContent(rows: EntityRelationRows, phoneticScriptEntityId: EntityId): AssembledPhoneticScriptContent;
229
+ /** Select source text without creating another authoritative text field. */
230
+ declare function selectAudioScriptSegment(script: EntityRow<'audio-script'>, selection: CaptionSegmentSelection): ScriptTextSegment;
231
+ //#endregion
232
+ //#region src/entity-editor/entity-graph-http-client.d.ts
233
+ /** One authenticated revision of the authoritative Medeo Entity graph. */
234
+ interface EntityGraphState {
235
+ /** Current AudioScript attached to the project, or null until one is written. */
236
+ readonly audioScriptEntityId: string | null;
237
+ readonly revision: number;
238
+ readonly loroSnapshot: string;
239
+ readonly rows: EntityRelationRows;
240
+ }
241
+ interface EntityGraphCommitOptions {
242
+ /** Server version vector proving the explicit legacy-to-Entity migration baseline. */
243
+ readonly migrationBaseVv?: string;
244
+ }
245
+ interface EntityGraphRevisionConflictPayload {
246
+ readonly error: {
247
+ readonly code: 'revision_conflict';
248
+ readonly message: string;
249
+ readonly expected_revision: number;
250
+ readonly current_revision: number;
251
+ };
252
+ }
253
+ declare class EntityGraphRevisionConflictError extends MengineHttpRequestError {
254
+ readonly expectedRevision: number;
255
+ readonly currentRevision: number;
256
+ constructor(expectedRevision: number, currentRevision: number, payload: EntityGraphRevisionConflictPayload);
257
+ }
258
+ /** Browser-safe authenticated Loro client for a document's Entity graph. */
259
+ declare class EntityGraphHttpClient {
260
+ private readonly options;
261
+ private readonly transport;
262
+ private readonly endpoint;
263
+ constructor(options: MengineHttpClientOptions);
264
+ fetchState(): Promise<EntityGraphState>;
265
+ /**
266
+ * Compile edits against the original causal snapshot and publish native Loro operations.
267
+ * The base revision is sent as an optimistic precondition, so a stale adoption
268
+ * fails loudly instead of letting Loro choose between concurrent selections.
269
+ *
270
+ * Deletion intent is derived from baseline IDs omitted from `nextRows`, so a
271
+ * transient create-then-remove never becomes a request to delete unknown
272
+ * persisted data.
273
+ */
274
+ commit(baseState: Pick<EntityGraphState, 'revision' | 'rows' | 'loroSnapshot'>, nextRows: EntityRelationRows, options?: EntityGraphCommitOptions): Promise<EntityGraphState>;
275
+ /** Send prepared bytes directly; omit `expectedRevision` for immutable fact publication. */
276
+ commitUpdate(update: string, expectedRevision?: number): Promise<EntityGraphState>;
277
+ private request;
278
+ }
279
+ //#endregion
280
+ //#region src/entity-editor/types.d.ts
281
+ /** Injectable domain-id mint shared by Entity and Relation authoring surfaces. */
282
+ type EntityTimelineIdFactory = (prefix: 'entity' | 'relation') => string;
283
+ interface ImageMediaAssetFact {
284
+ readonly assetId: string;
285
+ readonly kind: 'image';
286
+ readonly storageKey?: string;
287
+ }
288
+ interface VideoMediaAssetFact {
289
+ readonly assetId: string;
290
+ readonly kind: 'video';
291
+ readonly durationMs: number;
292
+ readonly storageKey?: string;
293
+ }
294
+ interface AudioMediaAssetFact {
295
+ readonly assetId: string;
296
+ readonly kind: 'audio';
297
+ readonly durationMs: number;
298
+ readonly storageKey: string;
299
+ }
300
+ /** A synthesized speech result. Uploaded recordings remain raw `audio`. */
301
+ interface VoiceoverMediaAssetFact {
302
+ /** Stable external speech result id, independent of the placed Clip id. */
303
+ readonly assetId: string;
304
+ readonly kind: 'voiceover-recording';
305
+ readonly durationMs: number;
306
+ readonly storageKey: string;
307
+ /**
308
+ * The PhoneticScript this take was spoken from, when the caller minting it
309
+ * knows. A migration that rebuilds the whole chain relates it itself; either
310
+ * way a take that never names one is refused when a plan is built.
311
+ */
312
+ readonly phoneticScriptEntityId?: string;
313
+ /** Timbre identity used for synthesis, when the caller has it. */
314
+ readonly voice?: VoiceDescriptor;
315
+ }
316
+ /** Facts resolved from media storage. A trim window never substitutes for intrinsic duration. */
317
+ type MediaAssetFact = ImageMediaAssetFact | VideoMediaAssetFact | AudioMediaAssetFact | VoiceoverMediaAssetFact;
318
+ /** Where a Clip starts: in flow by order, or at a stated start on its Track or inside its host. */
319
+ type ClipPlacement = {
320
+ readonly kind: 'sequential';
321
+ readonly order: number;
322
+ } | {
323
+ readonly kind: 'absolute';
324
+ readonly startMs: number;
325
+ } | {
326
+ readonly kind: 'anchored';
327
+ readonly hostClipEntityId: string;
328
+ readonly startMs: number;
329
+ };
330
+ interface InsertPlacedClipInput {
331
+ readonly trackEntityId: string;
332
+ readonly contentEntityId: string;
333
+ readonly inMs: number;
334
+ readonly outMs: number;
335
+ readonly placement: ClipPlacement;
336
+ readonly clipPayload?: JsonObject;
337
+ /** Stable caller-owned placement identity, when one already exists outside the graph. */
338
+ readonly clipEntityId?: string;
339
+ }
340
+ interface SetClipPlacementInput {
341
+ readonly clipEntityId: string;
342
+ readonly placement: ClipPlacement;
343
+ }
344
+ type SequentialClipAnchor = {
345
+ readonly position: 'before' | 'after';
346
+ readonly clipEntityId: string;
347
+ } | {
348
+ readonly position: 'trackStart';
349
+ };
350
+ interface MoveSequentialClipsInput {
351
+ readonly clipEntityIds: readonly string[];
352
+ readonly anchor: SequentialClipAnchor;
353
+ readonly onAnchored: 'follow' | 'keepAbsolute';
354
+ }
355
+ interface MoveClipsToStartsInput {
356
+ readonly moves: readonly {
357
+ readonly clipEntityId: string;
358
+ readonly newStartMs: number;
359
+ }[];
360
+ /** Absolute-time drags preserve every voiceover's current visible landing. */
361
+ readonly onAnchored: 'keepAbsolute';
362
+ }
363
+ interface DeleteClipTreeInput {
364
+ readonly clipEntityIds: readonly string[];
365
+ readonly onAnchored: 'cascade' | 'detach';
366
+ }
367
+ interface VoiceoverCaptionFact {
368
+ /** Stable placed caption identity supplied by the materialized side effect. */
369
+ readonly captionClipEntityId: string;
370
+ /** Directly held bases; includes the AudioScript the voiceover was rendered from. */
371
+ readonly baseEntityIds: readonly string[];
372
+ /** Ordered selection of AudioScript segments; caption text is never passed inline. */
373
+ readonly selection: CaptionSegmentSelection;
374
+ readonly startMs: number;
375
+ readonly durationMs: number;
376
+ readonly style?: CaptionStyleFields;
377
+ }
378
+ type VoiceoverTakeInput = {
379
+ readonly timelineEntityId: string; /** Stable placed speech identity, distinct from media.assetId. */
380
+ readonly voiceoverClipEntityId: string;
381
+ readonly media: VoiceoverMediaAssetFact; /** Existing pronunciation variant; its composed AudioScript stays the text owner. */
382
+ readonly phoneticScriptEntityId: string;
383
+ readonly volume: number;
384
+ readonly captions: readonly VoiceoverCaptionFact[];
385
+ } & ({
386
+ readonly placement: ClipPlacement;
387
+ readonly hostClipEntityId?: never;
388
+ readonly startMs?: never;
389
+ } | {
390
+ readonly placement?: never;
391
+ readonly hostClipEntityId: string;
392
+ readonly startMs: number;
393
+ });
394
+ type VisualMediaAssetFact = ImageMediaAssetFact | VideoMediaAssetFact;
395
+ interface InsertMediaClipInput {
396
+ readonly timelineEntityId: string;
397
+ readonly clipEntityId?: string;
398
+ readonly media: VisualMediaAssetFact;
399
+ /** Window on the source, whole milliseconds. An Image uses it as its finite display span. */
400
+ readonly inMs: number;
401
+ readonly outMs: number;
402
+ readonly placement: ClipPlacement;
403
+ readonly volume?: number;
404
+ }
405
+ interface ReplaceMediaClipInput {
406
+ readonly clipEntityId: string;
407
+ readonly media: VisualMediaAssetFact;
408
+ readonly inMs: number;
409
+ readonly outMs: number;
410
+ }
411
+ interface ReplacementMediaClipInput {
412
+ readonly clipEntityId?: string;
413
+ readonly media: VisualMediaAssetFact;
414
+ readonly inMs: number;
415
+ readonly outMs: number;
416
+ readonly volume?: number;
417
+ }
418
+ type MediaClipInsertion = {
419
+ readonly kind: 'before';
420
+ readonly clipEntityId: string;
421
+ } | {
422
+ readonly kind: 'after';
423
+ readonly clipEntityId: string;
424
+ } | {
425
+ readonly kind: 'firstStart';
426
+ readonly startMs: number;
427
+ };
428
+ interface InsertMediaClipsInput {
429
+ readonly timelineEntityId: string;
430
+ readonly clips: readonly ReplacementMediaClipInput[];
431
+ /** One placement decision for the whole input-ordered block. */
432
+ readonly insertion: MediaClipInsertion;
433
+ }
434
+ interface ReplaceSequentialClipsInput {
435
+ readonly timelineEntityId: string;
436
+ readonly oldClipEntityIds: readonly string[];
437
+ readonly newClips: readonly ReplacementMediaClipInput[];
438
+ readonly onAnchored: 'remap' | 'cascade';
439
+ }
440
+ interface SetClipVolumeInput {
441
+ readonly clipEntityId: string;
442
+ /** Playback gain in decibels. */
443
+ readonly volume: number;
444
+ }
445
+ interface LinearClipSpeed {
446
+ readonly kind: 'linear';
447
+ readonly rate: number;
448
+ readonly mode?: string;
449
+ }
450
+ interface SetClipSpeedInput {
451
+ readonly clipEntityId: string;
452
+ /** Linear speed; null restores the source's own pace. */
453
+ readonly rate: number | null;
454
+ }
455
+ interface TrimClipInput {
456
+ readonly clipEntityId: string;
457
+ readonly inMs: number;
458
+ readonly outMs: number;
459
+ }
460
+ interface VoiceoverTakeResult {
461
+ readonly voiceoverClipEntityId: string;
462
+ /** The rendered voiceover Audio entity. */
463
+ readonly voiceoverAudioEntityId: string;
464
+ /** The timbre identity it was synthesized with, when the take declared one. */
465
+ readonly voiceEntityId?: string;
466
+ /** The pronunciation variant the voiceover was rendered from. */
467
+ readonly phoneticScriptEntityId: string;
468
+ /** The base-text owner resolved from the PhoneticScript baseEntityIds. */
469
+ readonly audioScriptEntityId: string;
470
+ readonly captionClipEntityIds: readonly string[];
471
+ }
472
+ interface MoveVoiceoverInput {
473
+ readonly voiceoverClipEntityId: string;
474
+ /** Absolute requested timeline start; MEngine resolves and persists the host relation. */
475
+ readonly newStartMs: number;
476
+ }
477
+ interface DeleteVoiceoverInput {
478
+ readonly voiceoverClipEntityIds: readonly string[];
479
+ }
480
+ interface SetBgmInput {
481
+ readonly timelineEntityId: string;
482
+ readonly bgmClipEntityId: string;
483
+ readonly media: AudioMediaAssetFact;
484
+ readonly volume: number;
485
+ }
486
+ interface DeleteBgmInput {
487
+ readonly timelineEntityId: string;
488
+ }
489
+ interface SetCaptionVisibilityInput {
490
+ readonly timelineEntityId: string;
491
+ readonly hidden: boolean;
492
+ }
493
+ interface PatchCaptionStyleInput {
494
+ readonly timelineEntityId: string;
495
+ readonly style: CaptionStyleFields;
496
+ }
497
+ interface InsertCaptionClipInput {
498
+ readonly timelineEntityId: string;
499
+ /** Existing generation identity for newly materialized Caption content, distinct from its Clip. */
500
+ readonly captionEntityId?: string;
501
+ /** Stable placed caption identity, distinct from the Caption content identity. */
502
+ readonly captionClipEntityId?: string;
503
+ /** Existing bases composed by this variant; includes an AudioScript text owner. */
504
+ readonly baseEntityIds: readonly string[];
505
+ /** Ordered selection of the AudioScript segments this Caption displays. */
506
+ readonly selection: CaptionSegmentSelection;
507
+ /** Intrinsic cue length of the Caption entity itself; display comes from the placement. */
508
+ readonly durationMs: number;
509
+ readonly style?: CaptionStyleFields;
510
+ readonly placement: ClipPlacement;
511
+ }
512
+ interface InsertClipInput {
513
+ readonly trackEntityId: string;
514
+ /** Existing Sequence media Entity id. Asset ids and URLs are not content ids. */
515
+ readonly contentEntityId: string;
516
+ readonly inMs: number;
517
+ readonly outMs: number;
518
+ readonly startMs?: number;
519
+ /** Where among its Track's Clips it lands; appended when omitted. */
520
+ readonly order?: number;
521
+ readonly clipPayload?: JsonObject;
522
+ }
523
+ interface UpdateClipMarkerInput {
524
+ readonly clipEntityId: string;
525
+ readonly inMs?: number;
526
+ readonly outMs?: number;
527
+ /** Passing `undefined` explicitly removes the optional start. */
528
+ readonly startMs?: number | undefined;
529
+ /** Passing `undefined` explicitly removes the optional rate. */
530
+ readonly rate?: number | undefined;
531
+ }
532
+ interface MoveClipInput {
533
+ readonly clipEntityId: string;
534
+ readonly trackEntityId: string;
535
+ }
536
+ interface ReplaceClipContentInput {
537
+ readonly clipEntityId: string;
538
+ /** Existing Sequence media Entity id. Asset ids and URLs are not content ids. */
539
+ readonly contentEntityId: string;
540
+ readonly inMs: number;
541
+ readonly outMs: number;
542
+ readonly startMs?: number;
543
+ readonly rate?: number;
544
+ }
545
+ interface DeleteClipInput {
546
+ readonly clipEntityId: string;
547
+ }
548
+ interface UpdateClipInput {
549
+ readonly clipEntityId: string;
550
+ /** Complete replacement for the Clip-owned payload. */
551
+ readonly payload: JsonObject;
552
+ }
553
+ type ClipEntityId = EntityId;
554
+ //#endregion
555
+ //#region src/entity-editor/entity-timeline-editor.d.ts
556
+ /**
557
+ * Graph-native timeline authoring over authoritative Medeo Entity and Relation rows.
184
558
  *
185
- * The authoritative online producers — agent-harness (`@harness/shared`
186
- * `genObjId`) and director.v2 (`common/obj_id.py` `gen_obj_id`) — both mint part
187
- * ids as `` `${prefix}_${ulid()}` ``, and real captured drafts use exactly that
188
- * shape (`clip_…` / `spe_…` / `cap_…` / `bgm_…`, each a 26-char ULID). The engine
189
- * previously emitted `vc_<base36 timestamp><6 random>`, a different prefix AND a
190
- * different encoding — the sole cross-repo id divergence. This module removes it
191
- * by emitting the same `<prefix>_<ULID>` bytes.
559
+ * Each mutation is applied to a detached graph, validated as a complete DSL set,
560
+ * and committed only after validation succeeds.
561
+ */
562
+ declare class EntityTimelineEditor {
563
+ private readonly idFactory;
564
+ private state;
565
+ constructor(initialRows: EntityRelationRows, idFactory?: EntityTimelineIdFactory);
566
+ rows(): EntityRelationRows;
567
+ insertClip(input: InsertClipInput): ClipEntityId;
568
+ insertPlacedClip(input: InsertPlacedClipInput): ClipEntityId;
569
+ updateClipMarker(input: UpdateClipMarkerInput): void;
570
+ setClipPlacement(input: SetClipPlacementInput): void;
571
+ moveSequentialClips(input: MoveSequentialClipsInput): void;
572
+ moveClipsToStarts(input: MoveClipsToStartsInput): void;
573
+ moveClip(input: MoveClipInput): void;
574
+ replaceClipContent(input: ReplaceClipContentInput): void;
575
+ insertMediaClip(input: InsertMediaClipInput): ClipEntityId;
576
+ insertMediaClips(input: InsertMediaClipsInput): readonly ClipEntityId[];
577
+ replaceMediaClip(input: ReplaceMediaClipInput): void;
578
+ setClipVolume(input: SetClipVolumeInput): void;
579
+ setClipSpeed(input: SetClipSpeedInput): void;
580
+ trimClip(input: TrimClipInput): void;
581
+ replaceSequentialClips(input: ReplaceSequentialClipsInput): readonly ClipEntityId[];
582
+ deleteClip(input: DeleteClipInput): void;
583
+ deleteClipTree(input: DeleteClipTreeInput): void;
584
+ updateClip(input: UpdateClipInput): void;
585
+ upsertVoiceoverTake(input: VoiceoverTakeInput): VoiceoverTakeResult;
586
+ moveVoiceover(input: MoveVoiceoverInput): void;
587
+ deleteVoiceover(input: DeleteVoiceoverInput): void;
588
+ setBgm(input: SetBgmInput): ClipEntityId;
589
+ deleteBgm(input: DeleteBgmInput): void;
590
+ setCaptionVisibility(input: SetCaptionVisibilityInput): void;
591
+ patchCaptionStyle(input: PatchCaptionStyleInput): void;
592
+ /**
593
+ * Place a Caption as a composed variant of an existing AudioScript: the
594
+ * entity stores baseEntityIds, selection, optional style, and inherent cue-bounded
595
+ * Sequence. This helper does not copy base text. The Clip and its display Marker describe this use;
596
+ * moving or stretching the returned Clip later changes the Clip/Marker,
597
+ * never the Caption entity or the AudioScript.
598
+ */
599
+ insertCaptionClip(input: InsertCaptionClipInput): ClipEntityId;
600
+ private insertPlacedClipIntoDraft;
601
+ private ensureRoleTrack;
602
+ /** The existing pronunciation variant a voiceover consumes; composition is required. */
603
+ private requireComposedPhoneticScript;
604
+ /** Preserve the factual synthesis input as `[rendered Audio, PhoneticScript]`. */
605
+ private ensurePhoneticRender;
606
+ private reconcileVoiceoverCaptions;
607
+ private ensureRoleTrackForClip;
608
+ /**
609
+ * Remove one placed Caption use. The composed AudioScript outlives the
610
+ * caption: it may anchor further captions and remains the text owner.
611
+ */
612
+ private removeCaptionClipGraph;
613
+ private replaceAnchorHost;
614
+ /** Rebuild the legacy edit baseline from current visual order before a high-level cascade. */
615
+ private normalizeMainSequential;
616
+ private resolveOneVoiceoverOverlap;
617
+ private applyClipPlacement;
618
+ private reanchorAtAbsolute;
619
+ private removeAnchoredDescendants;
620
+ private removeClipGraph;
621
+ private transact;
622
+ private mintEntityId;
623
+ private createRelation;
624
+ private relinkRelation;
625
+ private mintRelationId;
626
+ }
627
+ //#endregion
628
+ //#region src/entity-editor/visual-assets-effect.d.ts
629
+ type MediaFact = MediaAssetFact;
630
+ interface VisualAssetsEffectInput {
631
+ /** Stable command identity. A retried command must reuse it; a new placement must use a new one. */
632
+ effect_id: string;
633
+ clips: ReadonlyArray<{
634
+ media_id: string;
635
+ media_kind: 'image' | 'video';
636
+ media_duration_ms: number;
637
+ storage_key?: string;
638
+ start_ms?: number;
639
+ play_in?: number;
640
+ play_out?: number;
641
+ volume?: number;
642
+ lineage?: {
643
+ generation_job_id: string;
644
+ sources: ReadonlyArray<MediaFact>;
645
+ script?: {
646
+ entity_id: string;
647
+ segments: ReadonlyArray<{
648
+ segment_id: string;
649
+ text: string;
650
+ language?: string;
651
+ }>;
652
+ content_hash: string;
653
+ };
654
+ };
655
+ }>;
656
+ before_clip_id?: string;
657
+ after_clip_id?: string;
658
+ }
659
+ /** Read the authoritative timeline receipt, not a media-id heuristic. */
660
+ declare function hasVisualAssetsEffect(rows: EntityRelationRows, effectId: string): boolean;
661
+ /**
662
+ * Materialize a host-resolved visual command into native Entity/Relation rows.
663
+ * The result is suitable for one revision-checked `EntityGraphHttpClient.commit`.
664
+ * This does not fetch Assets or write remotely; callers must supply factual media
665
+ * and lineage inputs after their own ownership checks.
666
+ */
667
+ declare function applyVisualAssetsEffect(rows: EntityRelationRows, input: VisualAssetsEffectInput): EntityRelationRows;
668
+ //#endregion
669
+ //#region src/entity-editor/revise-audio-script.d.ts
670
+ interface ReviseAudioScriptInput {
671
+ readonly editId: string;
672
+ readonly sourceAudioScriptEntityId: string;
673
+ readonly edits: readonly {
674
+ readonly segmentId: string;
675
+ readonly text: string;
676
+ }[];
677
+ readonly captionUsages?: readonly {
678
+ readonly clipEntityId: string;
679
+ readonly captionEntityId: string;
680
+ readonly markerEntityId: string;
681
+ readonly selection?: CaptionSegmentSelection;
682
+ }[];
683
+ }
684
+ interface ReviseAudioScriptResult {
685
+ readonly rows: EntityRelationRows;
686
+ readonly audioScriptEntityId: string;
687
+ readonly captionUsages: readonly {
688
+ readonly clipEntityId: string;
689
+ readonly previousCaptionEntityId: string;
690
+ readonly captionEntityId: string;
691
+ readonly markerEntityId: string;
692
+ }[];
693
+ readonly changed: boolean;
694
+ }
695
+ /** Revise text as an independent authored document, never as a version-family mutation. */
696
+ declare function reviseAudioScript(rows: EntityRelationRows, input: ReviseAudioScriptInput): ReviseAudioScriptResult;
697
+ //#endregion
698
+ //#region src/entity-editor/editor-resources.d.ts
699
+ declare const roleOrder: {
700
+ readonly caption: 0;
701
+ readonly video_clip: 1;
702
+ readonly speech: 2;
703
+ readonly bgm: 3;
704
+ };
705
+ type EditorTrackRole = keyof typeof roleOrder;
706
+ interface EditorFoundation {
707
+ readonly rows: EntityRelationRows;
708
+ readonly timelineEntityId: string;
709
+ readonly trackEntityIds: Readonly<Record<EditorTrackRole, string>>;
710
+ /** Initial or current AudioScript content ID selected by the foundation. */
711
+ readonly audioScriptEntityId: string | null;
712
+ }
713
+ /**
714
+ * MEngine editor policy, not a cardinality restriction on the general-purpose DSL.
192
715
  *
193
- * The ULID is generated inline (Crockford Base32, 48-bit time + 80-bit random)
194
- * rather than pulling the `ulid` npm package: the randomness class matches the
195
- * old generator (both `Math.random`-based) and it keeps `@mengine/medeo-client`
196
- * dependency-free for a purely mechanical id string. Part ids only need to be
197
- * unique and lexicographically time-sortable, which this satisfies.
716
+ * Resources live on Asset entities and are reached through `from-asset`: no
717
+ * other entity carries a locator, one Asset claims each `(system, key)` pair,
718
+ * and media reaches at most one Asset. Media whose bytes are not named through
719
+ * that Relation is rejected rather than guessed at.
198
720
  */
721
+ declare function assertCanonicalEditorResources(rows: EntityRelationRows): void;
199
722
  /**
200
- * Online part-id semantic prefixes. `clip` (video clip) is the only value the
201
- * engine currently mints (see `addVideoClips`); the rest are declared so the
202
- * type documents the shared vocabulary and guards against reintroducing the old
203
- * `vc`/`sp`/`cp`/`bg` names. Speech/caption/bgm ids arrive pre-minted in op
204
- * payloads, so the engine never generates them itself.
723
+ * Commit-transition policy shared by the editor, the HTTP commit boundary, the
724
+ * host tool, and the entity stores. It compares the authoritative before and
725
+ * after rows of one CAS commit and enforces the resource rules on the complete
726
+ * after state, with no exemption for historical graphs:
727
+ *
728
+ * 1. every media Entity reaches exactly one Asset through `from-asset`;
729
+ * 2. no entity other than an Asset carries a locator;
730
+ * 3. an Asset's locator is immutable — pointing it at other bytes would
731
+ * silently rewrite every entity already made from it.
732
+ *
733
+ * Deleting media is explicit and allowed.
734
+ */
735
+ declare function assertMediaAssetWritePolicy(before: EntityRelationRows, after: EntityRelationRows): void;
736
+ /** Add only missing editor structure; existing identities and owned settings are never replaced. */
737
+ declare function ensureEditorFoundation(initial: EntityRelationRows, idFactory?: EntityTimelineIdFactory, timelinePayload?: EntityRow['payload'], selectedAudioScriptEntityId?: string | null): EditorFoundation;
738
+ //#endregion
739
+ //#region src/entity-editor/media-asset-import.d.ts
740
+ interface ImportedMediaAsset {
741
+ readonly rows: EntityRelationRows;
742
+ /** The media entity for this asset id. */
743
+ readonly contentEntityId: string;
744
+ /** The Asset the media was made from; shared by every entity naming the same bytes. */
745
+ readonly assetEntityId: string;
746
+ /** The timbre identity of a synthesized voiceover; absent for recorded media. */
747
+ readonly voiceEntityId?: string;
748
+ }
749
+ /**
750
+ * Import at the editor boundary, not at asset generation time. Existing
751
+ * provenance is retained.
752
+ *
753
+ * The bytes are named once, on an Asset entity, and the media entity reaches
754
+ * them through a `from-asset` Relation. Re-importing the same `(system, key)`
755
+ * reuses that Asset and the media already made from it, so one stored resource
756
+ * is never copied into several rows.
205
757
  */
206
- type PartIdPrefix = 'clip' | 'spe' | 'cap' | 'bgm' | 'ti';
207
- declare function generatePartId(prefix: PartIdPrefix): string;
758
+ declare function importMediaAsset(initial: EntityRelationRows, fact: MediaAssetFact, idFactory?: EntityTimelineIdFactory): ImportedMediaAsset;
759
+ //#endregion
760
+ //#region src/entity-editor/legacy-entity-migration.d.ts
761
+ /** One-time import only. Ordinary editor operations must never reverse-diff a legacy document. */
762
+ declare function migrateLegacyTimelineToEntities(legacy: VideoDocument, assetFacts: readonly MediaAssetFact[], initial?: EntityRelationRows, idFactory?: EntityTimelineIdFactory): EntityRelationRows;
763
+ /** Server gate: a cutover may change representation, never the existing render facts. */
764
+ declare function assertEntityProjectionPreservesLegacy(legacy: VideoDocument, projection: VideoDocument, rows: EntityRelationRows): void;
765
+ //#endregion
766
+ //#region src/entity-editor/caption-content.d.ts
767
+ interface CaptionContentInput {
768
+ readonly contentEntityId: string;
769
+ readonly audioScriptEntityId: string;
770
+ readonly text: string;
771
+ readonly selection?: CaptionSegmentSelection;
772
+ readonly durationMs: number;
773
+ }
774
+ /** Author Caption content from semantic intent; callers never reconcile variant bases or assembled fields. */
775
+ declare function prepareCaptionContent(rows: EntityRelationRows, input: CaptionContentInput): EntityRow<'caption'>;
776
+ //#endregion
777
+ //#region src/entity-editor/document-audio-script.d.ts
778
+ interface DocumentAudioScript {
779
+ readonly entityId: string;
780
+ readonly segments: readonly (ScriptTextSegment & Readonly<Record<string, unknown>>)[];
781
+ }
782
+ /** State exposing the current AudioScript content version attached to the project. */
783
+ interface DocumentAudioScriptState {
784
+ readonly rows: EntityRelationRows;
785
+ /** Current attachment, or null until a script is transcribed or written. */
786
+ readonly audioScriptEntityId: string | null;
787
+ }
788
+ /** Read only the attached version and preserve every segment; never aggregate other scripts. */
789
+ declare function readDocumentAudioScript(state: DocumentAudioScriptState): DocumentAudioScript;
790
+ //#endregion
791
+ //#region src/entity-crdt/field-changes.d.ts
792
+ /** List members are addressed by identity, never a transient array offset. */
793
+ type FieldPath = readonly (string | {
794
+ elementId: string;
795
+ })[];
796
+ type FieldChange = {
797
+ op: 'set';
798
+ path: FieldPath;
799
+ value: JsonValue;
800
+ } | {
801
+ op: 'unset';
802
+ path: FieldPath;
803
+ } | {
804
+ op: 'text.splice';
805
+ path: FieldPath;
806
+ index: number;
807
+ deleteCount: number;
808
+ text: string;
809
+ } | {
810
+ op: 'list.insert';
811
+ path: FieldPath;
812
+ value: JsonValue;
813
+ beforeElementId: string | null;
814
+ } | {
815
+ op: 'list.move';
816
+ path: FieldPath;
817
+ elementId: string;
818
+ beforeElementId: string | null;
819
+ } | {
820
+ op: 'list.remove';
821
+ path: FieldPath;
822
+ elementId: string;
823
+ };
824
+ declare function assertFieldChanges(changes: readonly FieldChange[]): void;
825
+ /** Resolve against the sequential causal view; the numeric path never crosses the API boundary. */
826
+ declare function resolveFieldPath(payload: JsonObject, path: FieldPath): (string | number)[];
827
+ /** Detached plan evaluation. Native compilation replays the original operations, not this snapshot. */
828
+ declare function applyFieldChanges(payload: JsonObject, changes: readonly FieldChange[]): JsonObject;
829
+ //#endregion
830
+ //#region src/entity-crdt/entity-document.d.ts
831
+ declare const LORO_ENTITY_SCHEMA = "medeo.entities.loro.v1";
832
+ interface EntityDocumentState {
833
+ readonly rows: EntityRelationRows;
834
+ readonly project: Readonly<Record<string, string>>;
835
+ readonly phoneticScriptSelections?: Readonly<Record<string, string>>;
836
+ }
837
+ /** One stable native relation root, including records tombstoned from the active projection. */
838
+ interface EntityRelationRecord extends RelationRow {
839
+ readonly deleted: boolean;
840
+ }
841
+ /** Read persisted relation roots before current entity versions are projected. */
842
+ declare function readEntityRelationRecords(doc: LoroDoc): readonly EntityRelationRecord[];
843
+ type Command = {
844
+ type: 'create';
845
+ row: EntityRow;
846
+ } | {
847
+ type: 'selection-baseline';
848
+ root: string;
849
+ fingerprint: string;
850
+ } | {
851
+ type: 'order';
852
+ group: string;
853
+ roots: string[];
854
+ token: string;
855
+ } | {
856
+ type: 'write';
857
+ root: string;
858
+ payload: JsonObject;
859
+ token: string;
860
+ } | {
861
+ type: 'text';
862
+ root: string;
863
+ path: readonly (string | number)[];
864
+ start: number;
865
+ deleteCount: number;
866
+ text: string;
867
+ token: string;
868
+ } | {
869
+ type: 'field';
870
+ root: string;
871
+ path: (string | number)[];
872
+ change: FieldChange;
873
+ token: string;
874
+ } | {
875
+ type: 'relation-field';
876
+ root: string;
877
+ path: (string | number)[];
878
+ change: FieldChange;
879
+ } | {
880
+ type: 'delete';
881
+ root: string;
882
+ } | {
883
+ type: 'relation';
884
+ row: RelationRow;
885
+ } | {
886
+ type: 'relation-fields';
887
+ root: string;
888
+ metadata: JsonObject;
889
+ trace: JsonObject;
890
+ } | {
891
+ type: 'unlink';
892
+ root: string;
893
+ } | {
894
+ type: 'select-clip-content';
895
+ clipRoot: string;
896
+ relationRoot: string;
897
+ } | {
898
+ type: 'select-phonetic-script';
899
+ clipRoot: string;
900
+ phoneticScriptRoot: string;
901
+ } | {
902
+ type: 'attach';
903
+ slot: string;
904
+ entityId: string;
905
+ };
906
+ /** Plain domain objects assembled from native Loro state, never a second writable authority. */
907
+ declare function readEntityDocument(doc: LoroDoc, allowSelectionConflicts?: boolean): EntityDocumentState;
908
+ /** Native editing containers survive domain version changes and merge independently. */
909
+ declare class LoroEntityDocument {
910
+ readonly doc: LoroDoc;
911
+ private readonly validate?;
912
+ private readonly undoManager;
913
+ constructor(doc: LoroDoc, validate?: ((state: EntityDocumentState) => void) | undefined);
914
+ /** Open a causal snapshot using the same Loro runtime as the compiler. */
915
+ static fromSnapshot(snapshot: Uint8Array, validate?: (state: EntityDocumentState) => void): LoroEntityDocument;
916
+ static create(rows: EntityRelationRows, project?: Readonly<Record<string, string>>, peerId?: PeerID): LoroEntityDocument;
917
+ snapshot(): EntityDocumentState;
918
+ relationsOf(entityId: string): readonly RelationRow[];
919
+ /** Resolve a queued edit target through its native identity without changing history. */
920
+ resolveCurrentEntityId(id: string): string;
921
+ getVersion(id: string): EntityRow | undefined;
922
+ /** The callback and every domain validation execute on a causally complete fork first. */
923
+ transact(edit: (draft: LoroEntityDraft) => void): Uint8Array;
924
+ /** Validate remote operations on a fork before importing their native identities. */
925
+ import(update: Uint8Array): void;
926
+ /**
927
+ * Bind a saved snapshot without rewriting text operations or resolving
928
+ * selection conflicts. The script names the bytes the same way everything
929
+ * else does — an Asset entity plus a Relation — and keeps only the
930
+ * fingerprint that tells a stale snapshot from a current one. The Relation is
931
+ * `to-asset`: these bytes are the script's own content written out, not a
932
+ * source it was made from.
933
+ */
934
+ bindAudioScriptAsset(entityId: string, assetId: string, expectedContentHash: string): Uint8Array;
935
+ canUndo(): boolean;
936
+ canRedo(): boolean;
937
+ undo(): boolean;
938
+ redo(): boolean;
939
+ private historyEdit;
940
+ }
941
+ declare class LoroEntityDraft {
942
+ private readonly doc;
943
+ readonly commands: Command[];
944
+ private readonly selectedRoots;
945
+ private readonly relationAliases;
946
+ constructor(doc: LoroDoc);
947
+ snapshot(): EntityDocumentState;
948
+ order(groupId: string, entityIds: readonly string[]): void;
949
+ /** Project the final scalar placement intents onto the existing native ordering containers. */
950
+ reconcileOrder(rows: EntityRelationRows): void;
951
+ create(row: EntityRow): void;
952
+ delete(entityId: string): void;
953
+ attach(slot: string, entityId: string): void;
954
+ link(row: RelationRow): void;
955
+ patchRelationTrace(relationId: string, trace: JsonObject): void;
956
+ unlink(relationId: string): void;
957
+ /** Select the one content membership projected for this stable Clip identity. */
958
+ selectClipContent(relationId: string): void;
959
+ /** Select the pending immutable pronunciation variant for one stable Speech Clip. */
960
+ selectPhoneticScript(clipEntityId: string, phoneticScriptEntityId: string): void;
961
+ private relationRoot;
962
+ update(entityId: string, fields: JsonObject): void;
963
+ declare(entityId: string, fields: JsonObject): void;
964
+ replaceOwned(entityId: string, payload: JsonObject): void;
965
+ editText(entityId: string, path: readonly (string | number)[], start: number, deleteCount: number, text: string): void;
966
+ /** Generic assembled-field edit compiled at the author's causal position. */
967
+ change(entityId: string, changes: readonly FieldChange[]): void;
968
+ private assertGenericMutationAllowed;
969
+ changeRelation(relationId: string, changes: readonly FieldChange[]): void;
970
+ captureSelectionBaselines(): void;
971
+ private record;
972
+ }
973
+ //#endregion
974
+ //#region src/entity-crdt/compile-rows.d.ts
975
+ interface ApplyEntityRowsOptions {
976
+ readonly projectAttachments?: Readonly<Record<string, string>>;
977
+ readonly phoneticScriptSelections?: Readonly<Record<string, string>>;
978
+ }
979
+ /** Lower a detached ordinary-object edit against its actual causal Loro baseline. */
980
+ declare function compileEntityRows(snapshot: Uint8Array, rows: EntityRelationRows, validate?: (state: EntityDocumentState) => void, options?: ApplyEntityRowsOptions): {
981
+ update: Uint8Array;
982
+ state: EntityDocumentState;
983
+ };
984
+ /** Publish final rows as imported causal operations, outside the caller's local undo history. */
985
+ declare function publishEntityRows(editor: LoroEntityDocument, rows: EntityRelationRows, options?: ApplyEntityRowsOptions): {
986
+ update: Uint8Array;
987
+ state: EntityDocumentState;
988
+ };
989
+ /** Compile an edit on an existing peer, retaining its native local undo history. */
990
+ declare function applyEntityRows(editor: LoroEntityDocument, rows: EntityRelationRows, options?: ApplyEntityRowsOptions): {
991
+ update: Uint8Array;
992
+ state: EntityDocumentState;
993
+ };
994
+ //#endregion
995
+ //#region src/entity-crdt/legacy-schema-migration.d.ts
996
+ /** Replace only the four positionally equivalent alpha23 relation kinds. */
997
+ declare function migrateAlpha23EntityDocument(doc: LoroDoc): Uint8Array | undefined;
998
+ //#endregion
999
+ //#region src/editor/journal.d.ts
1000
+ /**
1001
+ * Wire a plain-memory adapter + editor that share a recording id factory, so
1002
+ * every mutating transact lands in `journal` with ordered `generated_ids`.
1003
+ */
1004
+ declare function createEditSandbox(document: VideoDocument, options?: PlainMemoryAdapterOptions): {
1005
+ adapter: PlainMemoryAdapter;
1006
+ editor: SemanticEditor;
1007
+ journal: readonly JournalEntry[];
1008
+ };
1009
+ /**
1010
+ * Re-drive `doc` from a recorded journal, forcing each entry's `generated_ids`
1011
+ * through a queue-backed id factory. Never mints fresh ids: an empty queue on
1012
+ * demand throws `unrecorded id`; leftover ids after an entry throws
1013
+ * `unconsumed ids`. Legacy entries without `generated_ids` are treated as `[]`.
1014
+ */
1015
+ declare function replayJournal(doc: SemanticDocumentAdapter, journal: readonly JournalEntry[]): Promise<void>;
208
1016
  //#endregion
209
1017
  //#region src/editor/snapshot-utils.d.ts
210
1018
  /** Main-track item identity read from a raw snapshot (only `part_id` is needed). */
@@ -393,6 +1201,8 @@ declare class ManualSyncDoc {
393
1201
  private readonly client;
394
1202
  private readonly doc;
395
1203
  private readonly adapter;
1204
+ /** Whether this document's timeline is owned by the Entity graph. */
1205
+ isEntityDocument(): boolean;
396
1206
  readonly editor: SemanticEditor;
397
1207
  /**
398
1208
  * The version the server is known to hold. Starts empty (nothing confirmed)
@@ -424,6 +1234,16 @@ declare class ManualSyncDoc {
424
1234
  editorPeerId(): PeerID;
425
1235
  /** Current content projected into the compatible track and part read shape. */
426
1236
  content(): VideoDraftContent;
1237
+ /**
1238
+ * Replay a deterministic sandbox journal into this document.
1239
+ *
1240
+ * The adapter stays private so callers cannot bypass the manual-sync
1241
+ * lifecycle; journal replay is the one host-side operation that needs the
1242
+ * adapter's transaction boundary and recorded id queue. Durability is still
1243
+ * explicit: call {@link push} after replay and report success only from its
1244
+ * verdict.
1245
+ */
1246
+ replayJournal(journal: readonly JournalEntry[]): Promise<void>;
427
1247
  /**
428
1248
  * Mark the document state the caller has just observed, for a later
429
1249
  * {@link hasChangedSince}.
@@ -632,18 +1452,13 @@ declare class MengineAckFailedError extends Error {
632
1452
  readonly cause: Error | undefined;
633
1453
  constructor(reason: 'timeout' | 'rejected' | 'failed', code: string | undefined, cause: Error | undefined, message: string);
634
1454
  }
635
- type MengineLocalSaveState = LocalSaveState;
636
- interface WaitForLocalSaveOptions {
637
- /** Only limits waiting, never cancels persistence. */
638
- timeoutMs?: number;
639
- }
640
1455
  interface WaitForServerAckOptions {
641
1456
  /** Deadline in ms. Rejects with reason `timeout` when it elapses. */
642
1457
  timeoutMs?: number;
643
1458
  }
644
1459
  /** Document-level confirmation is independent of local operation completion. */
645
1460
  interface MengineDocSyncState {
646
- /** Server-originated imports do not create a new local confirmation obligation. */
1461
+ /** Remote-only imports do not create a new local confirmation obligation. */
647
1462
  readonly confirmation: 'unknown' | 'pending' | 'confirmed';
648
1463
  /** Transport/activity phase. Idle does not imply confirmation; failure details
649
1464
  * remain available through push outcomes and confirmation wait errors. */
@@ -658,10 +1473,12 @@ interface MengineDocSessionOptions {
658
1473
  * Browsers should pass an `IndexedDBDocStorage` for refresh/cross-tab support.
659
1474
  */
660
1475
  localStorage?: DocStorageLike;
661
- /** A freshly fetched remote snapshot to merge into storage before loading.
662
- * Existing local changes are retained; the host owns any online startup gate. */
663
- initialSnapshot?: Uint8Array;
664
1476
  sseReconnectDelayMs?: number;
1477
+ /**
1478
+ * Keep remote synchronization read-only: pull snapshot/diffs and subscribe to
1479
+ * SSE updates, but never POST local Loro updates to the server.
1480
+ */
1481
+ readonlyMode?: boolean;
665
1482
  }
666
1483
  /**
667
1484
  * A live editing session for one Medeo document — the single entry point clients
@@ -697,7 +1514,6 @@ declare class MengineDocSession {
697
1514
  private started;
698
1515
  private startTask;
699
1516
  private destroyed;
700
- private closeTask;
701
1517
  private lifetime;
702
1518
  private hasConnected;
703
1519
  private initialVersionValue;
@@ -748,6 +1564,18 @@ declare class MengineDocSession {
748
1564
  * step. The committed change drives DocManager's local-update push.
749
1565
  */
750
1566
  get editor(): SemanticEditor;
1567
+ /**
1568
+ * Opaque version token of the local oplog (base64 `VersionVector.encode`).
1569
+ * Equality-comparable only: equal means no observed change (local or
1570
+ * remote-arrived) since the token was taken. Throws when not started.
1571
+ */
1572
+ version(): string;
1573
+ /**
1574
+ * The live document adapter, exposed for journal replay (commit channel).
1575
+ * Replaying through it still goes SemanticEditor → Loro → mengine-server —
1576
+ * no write bypass. Typed by the narrow interface on purpose.
1577
+ */
1578
+ get documentAdapter(): SemanticDocumentAdapter;
751
1579
  /** Current document snapshot (read model). */
752
1580
  snapshot(): VideoDocument;
753
1581
  /** Current-session undo/redo availability. Loading and closed sessions report false. */
@@ -791,17 +1619,7 @@ declare class MengineDocSession {
791
1619
  */
792
1620
  start(): Promise<VideoDocument>;
793
1621
  private open;
794
- getLocalSaveState(): MengineLocalSaveState;
795
- /** Immediately reports local transaction state; independent of server confirmation. */
796
- subscribeLocalSaveState(cb: (state: MengineLocalSaveState) => void): () => void;
797
- /** Waits for commits present now to reach local storage. Does not wait for the network. */
798
- waitForLocalSave(options?: WaitForLocalSaveOptions): Promise<void>;
799
- /** Stop accepting edits and drain local persistence before releasing resources.
800
- * A failed local write keeps retrying, even after the host has unmounted.
801
- * Hosts should use this for normal teardown; destroy() is immediate cancellation. */
802
- close(): Promise<void>;
803
1622
  getSyncState(): MengineDocSyncState;
804
- private trackLocalVersion;
805
1623
  private confirmationTarget;
806
1624
  /** Immediately supplies current state; unsubscribe when the host changes docs. */
807
1625
  subscribeSyncState(cb: (state: MengineDocSyncState) => void): () => void;
@@ -998,103 +1816,6 @@ type MakeEmptyPart = (durationMs: number) => {
998
1816
  */
999
1817
  declare function cascadeAfterVideoClipChanges(doc: TimelineDoc, makeEmptyPart: MakeEmptyPart): void;
1000
1818
  //#endregion
1001
- //#region src/timeline-core/bridge.d.ts
1002
- /**
1003
- * Bridge between the authoritative `VideoDocument` (position-only facts) and the
1004
- * flat `TimelineDoc` the cascade primitives solve over.
1005
- *
1006
- * The data flow is single-directional (RFC 02 §7/§10): ops write only facts
1007
- * (`time_position`, parts) to `VideoDocument`; absolute time, `part_aggregations`,
1008
- * total duration, and gap fillers are NOT stored — the projection derives them
1009
- * on read by running the cascade. There is no write-back of solved positions.
1010
- *
1011
- * - `solveVideoDocument` seeds a `TimelineDoc` from each item's `time_position`,
1012
- * runs the full cascade, and returns the derived read-view (abs / aggregations
1013
- * / duration). It is the single solve shared by the legacy `VideoDraft`
1014
- * projection.
1015
- * - `ensureLaneTrack` / `findLaneTrack` locate (or mint) a secondary lane's
1016
- * track row in the draft, so ops can write authoritative facts onto the right
1017
- * named container (lane = container).
1018
- */
1019
- /** The projection-derived read-view of a `VideoDocument` (RFC 02 §7). */
1020
- interface SolvedVideoDocument {
1021
- absByPartId: Map<string, number>;
1022
- aggregations: PartAggregation[];
1023
- durationMs: number;
1024
- partLibrary: Record<string, PartUnion>;
1025
- /**
1026
- * Part ids of the gap fillers this solve minted.
1027
- *
1028
- * They exist only inside the solve: gap filling needs them so the clips after a
1029
- * gap land at the right absolute time, but they are not authoritative state and
1030
- * the read view does not carry them (see `fromVideoDocument`).
1031
- *
1032
- * Reported as ids rather than left for the caller to detect, because the caller
1033
- * *cannot* detect them. The obvious predicate — `origin_media_id === ''` — also
1034
- * matches an empty clip a writer placed on purpose (`batch_replace_video_clip_sequence`
1035
- * documents "Omit to create an empty clip placeholder"), and those are
1036
- * authoritative parts that must survive the projection. The mint callback is the
1037
- * only place that knows the difference.
1038
- *
1039
- * Note this deliberately excludes the fillers that gap filling *extended* rather
1040
- * than minted (`fillMainTrackTimeGaps` cases 1 and 2): those are authoritative
1041
- * empty clips already in `part_library`, and only their length is derived.
1042
- */
1043
- derivedFillerPartIds: Set<string>;
1044
- }
1045
- /**
1046
- * Solve a `VideoDocument` (authoritative, position-only) into its derived
1047
- * read-view: absolute time per item, `part_aggregations`, and total duration.
1048
- * This is the read side of the single-directional flow — never written back.
1049
- */
1050
- declare function solveVideoDocument(document: VideoDocument): SolvedVideoDocument;
1051
- /** The named container a secondary lane lives in. */
1052
- type SecondaryLane = 'speech' | 'caption' | 'bgm';
1053
- /** A lane's track kind: the `video_clip` main lane plus the three secondary lanes. */
1054
- type LaneKind = SecondaryLane | 'video_clip';
1055
- /**
1056
- * The four lanes in top-to-bottom stack order — the order a `tracks` list holds
1057
- * them in (see {@link laneRank}).
1058
- *
1059
- * Exported so a document can be seeded with all four lanes up front. That seed is
1060
- * not cosmetic: {@link ensureLaneTrack} is find-then-mint over a `LoroMovableList`,
1061
- * so two concurrent writers that each mint the same absent lane both keep their
1062
- * row, and the merged document holds two tracks for one lane. For the main lane
1063
- * that is fatal — `videoDocumentSchema` allows at most one `video_clip` track, so
1064
- * the merged document stops being projectable at all, symmetrically on both
1065
- * replicas. Pre-seeding every lane makes `ensureLaneTrack` always take its find
1066
- * branch, which removes the race by construction rather than by detection.
1067
- *
1068
- * What closes the race is that a track with the lane's `parts_kind` EXISTS — the
1069
- * lookup is by kind, not by id. So a seed is only safe if it covers every lane:
1070
- * a partial seed leaves the uncovered lanes exactly as exposed as before.
1071
- */
1072
- declare const LANE_KINDS_IN_STACK_ORDER: readonly LaneKind[];
1073
- /**
1074
- * The conventional track id for a lane (`main_track`, `<kind>_track`). Shared by
1075
- * the up-front seed and {@link ensureLaneTrack}'s lazy mint so a document's lane
1076
- * ids do not depend on which of the two created the track.
1077
- *
1078
- * Ids are cosmetic to the merge itself — lane lookup goes by `parts_kind`, so
1079
- * drifting them apart would not reopen the concurrent-mint race. They matter to
1080
- * readers that address a lane by id (the FE editor's panes, fixtures), which is
1081
- * why there is one convention rather than two.
1082
- */
1083
- declare function laneTrackId(kind: LaneKind): string;
1084
- /**
1085
- * Locate a lane's track row in the single `tracks` list by kind, minting an empty
1086
- * row in lane-stacking order if absent (reference/17 §4: lane = `parts_kind`).
1087
- * Ops use this to write authoritative items onto the right lane. The track id
1088
- * comes from {@link laneTrackId}, shared with the up-front seed.
1089
- *
1090
- * The mint branch is a concurrency hazard, not a convenience: see
1091
- * {@link LANE_KINDS_IN_STACK_ORDER}. A document seeded with all four lanes never
1092
- * reaches it.
1093
- */
1094
- declare function ensureLaneTrack(draft: VideoDocumentDraft, kind: LaneKind): TrackDraft;
1095
- /** Find a secondary lane's track row without minting it. */
1096
- declare function findLaneTrack(draft: VideoDocumentDraft, kind: SecondaryLane): TrackDraft | undefined;
1097
- //#endregion
1098
1819
  //#region src/timeline-core/locate.d.ts
1099
1820
  /**
1100
1821
  * Forward positioning for write-time ops (RFC 02 §9.1) — NOT a cascade.
@@ -1138,4 +1859,37 @@ declare function hostForAbsMs(ranges: MainClipRange[], absMs: number): MainClipR
1138
1859
  */
1139
1860
  declare function relativePositionForAbs(ranges: MainClipRange[], absMs: number): TrackItemTimePosition;
1140
1861
  //#endregion
1141
- export { type Aggregation, type Attachment, type BgmPart, type CaptionPart, type CaptionStyle, type CommitOptions, DEFAULT_UNIT_TIME_MS, type DerivedItemPosition, type DocStorageLike, type DocVersionMark, IMPLEMENTED_SEMANTIC_OP_KINDS, type ImplementedSemanticOpKind, LANE_KINDS_IN_STACK_ORDER, type LaneKind, type MainClipRange, type MakeEmptyPart, ManualSyncDoc, type ManualSyncDocOptions, MedeoHttpDocStorage, type MedeoHttpDocStorageOptions, MemoryDocStorage, MengineAckFailedError, type MengineAuditEntry, type MengineAuditResponse, MengineDocSession, type MengineDocSessionOptions, type MengineDocSessionUpdateEvent, type MengineDocSyncState, type MengineDocumentVersion, type MengineEventStreamOptions, MengineHttpClient, type MengineHttpClientOptions, MengineHttpRequestError, type MengineLocalSaveState, MenginePushRejectedError, type MenginePushResponse, type MenginePushUpdateResponse, type MengineRejectedResponse, type MengineSnapshotResponse, type MengineSseUpdateEvent, type MengineSyncResponse, type MengineUndoState, type MengineUpdateMeta, MirrorVideoDocumentAdapter, type MirrorVideoDocumentOptions, type OpActor, type PartAggregation, type PartKind, type PartUnion, type PlannedSemanticOpKind, type PullFailureReason, type PullResult, type PushOutcome, type PushOutcomeKind, type PushResult, type PushResultKind, SchemaValidator, type SemanticDocumentAdapter, SemanticEditor, type SemanticOpInput, type SemanticOpKind, type SemanticOpName, type SnapshotReadable, type SolvedVideoDocument, type SpeechHostMap, type SpeechPart, type SpeedShift, TIMELINE_SKELETON_DURATION_MS, type Timeline, type TimelineDoc, type TimelineItem, type Track, type TrackDraft, type TrackItem, type TrackItemDraft, type TrackItemTimePosition, type TransactAudit, ValidationError, type VideoClipPart, type VideoDocument, type VideoDocumentDraft, type VideoDocumentMirrorSchema, VideoDocumentValidationError, type VideoDocumentValidationIssue, type VideoDocumentValidationIssueCode, type VideoDraft, type CaptionPart$1 as VideoDraftCaptionPart, type VideoDraftContent, type VideoDraftPartUnion, type Timeline$1 as VideoDraftTimeline, type Track$1 as VideoDraftTrack, type TrackItem$1 as VideoDraftTrackItem, type WaitForLocalSaveOptions, type WaitForServerAckOptions, 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, index_d_exports as schemas, snapshotToPlain, solveVideoDocument, syncAggregatedClipsTimePosition, toVideoDocument, validateVideoDocument, videoDocumentMirrorSchema, videoDocumentSchema };
1862
+ //#region src/entity-crdt/audio-script-assets.d.ts
1863
+ /** A resource is a snapshot of text; the native Loro text remains the editing authority. */
1864
+ declare function audioScriptAssetContent(payload: JsonObject): JsonObject;
1865
+ declare function audioScriptAssetHash(payload: JsonObject): string;
1866
+ /**
1867
+ * The Asset a script was written out to. It is a snapshot the script owns, so
1868
+ * it is reached by `to-asset` — not `from-asset`, which would say the script
1869
+ * was produced from bytes it cannot change.
1870
+ */
1871
+ declare function audioScriptAssetOf(rows: EntityRelationRows, entityId: string): EntityRow | undefined;
1872
+ /**
1873
+ * The Asset a script was made from — a transcript it does not own. A script
1874
+ * that has one never writes a snapshot of its own: the bytes it would describe
1875
+ * are already named, and rewriting them would contradict their source.
1876
+ */
1877
+ declare function scriptSourceAssetOf(rows: EntityRelationRows, entityId: string): EntityRow | undefined;
1878
+ /** Internal fingerprint prevents a resource from silently describing an older text revision. */
1879
+ declare function audioScriptAssetFields(payload: JsonObject): JsonObject;
1880
+ /**
1881
+ * What a PhoneticScript hands to synthesis: the base AudioScript's text as the
1882
+ * variant pronounces it, plus the variant's own phoneme and prosody control.
1883
+ *
1884
+ * The variant's content is written by a model — deciding how words are said is
1885
+ * text work, not a mechanical copy — but the bytes a synthesizer reads have to
1886
+ * leave the entity graph to reach it, because synthesis does not handle
1887
+ * entities. Writing this resource down is that crossing, and it is why speech
1888
+ * can only come from a PhoneticScript.
1889
+ */
1890
+ declare function phoneticScriptAssetContent(rows: EntityRelationRows, entityId: string): JsonObject;
1891
+ declare function phoneticScriptAssetHash(rows: EntityRelationRows, entityId: string): string;
1892
+ /** The Asset a PhoneticScript was written out to, read from the graph. */
1893
+ declare function phoneticScriptAssetOf(rows: EntityRelationRows, entityId: string): EntityRow | undefined;
1894
+ //#endregion
1895
+ export { type Aggregation, ApplyEntityRowsOptions, type AssembledCaptionContent, type AssembledPhoneticScriptContent, type Attachment, type AudioMediaAssetFact, type BgmPart, type CaptionContentInput, type CaptionDisplayCue, type CaptionPart, type CaptionSegmentSelection, type CaptionStyle, type ClipEntityId, type ClipPlacement, type CommitOptions, DEFAULT_UNIT_TIME_MS, type DeleteBgmInput, type DeleteClipInput, type DeleteClipTreeInput, type DeleteVoiceoverInput, type DerivedItemPosition, type DocStorageLike, type DocVersionMark, type DocumentAudioScript, type DocumentAudioScriptState, type EditorFoundation, EntityDocumentState, type EntityGraphCommitOptions, EntityGraphHttpClient, EntityGraphRevisionConflictError, type EntityGraphRevisionConflictPayload, type EntityGraphState, EntityRelationRecord, EntityTimelineEditor, type EntityTimelineIdFactory, EntityTimelineProjectionError, type EntityTimelineTrackRole, type FieldChange, type FieldPath, IMPLEMENTED_SEMANTIC_OP_KINDS, type ImageMediaAssetFact, type ImplementedSemanticOpKind, type ImportedMediaAsset, type InsertCaptionClipInput, type InsertClipInput, type InsertMediaClipInput, type InsertMediaClipsInput, type InsertPlacedClipInput, type JournalEntry, LANE_KINDS_IN_STACK_ORDER, LORO_ENTITY_SCHEMA, type LaneKind, type LinearClipSpeed, LoroEntityDocument, LoroEntityDraft, type MainClipRange, type MakeEmptyPart, ManualSyncDoc, type ManualSyncDocOptions, MedeoHttpDocStorage, type MedeoHttpDocStorageOptions, type MediaAssetFact, type MediaClipInsertion, MemoryDocStorage, MengineAckFailedError, type MengineAuditEntry, type MengineAuditResponse, MengineDocSession, type MengineDocSessionOptions, type MengineDocSessionUpdateEvent, type MengineDocSyncState, type MengineDocumentVersion, type MengineEventStreamOptions, MengineHttpClient, type MengineHttpClientOptions, MengineHttpRequestError, MenginePushRejectedError, type MenginePushResponse, type MenginePushUpdateResponse, type MengineRejectedResponse, type MengineSnapshotResponse, type MengineSseUpdateEvent, type MengineSyncResponse, type MengineUndoState, type MengineUpdateMeta, MirrorVideoDocumentAdapter, type MirrorVideoDocumentOptions, type MoveClipInput, type MoveClipsToStartsInput, type MoveSequentialClipsInput, type MoveVoiceoverInput, type OpActor, type PartAggregation, type PartIdFactory, type PartKind, type PartUnion, type PatchCaptionStyleInput, PlainMemoryAdapter, type PlainMemoryAdapterOptions, type PlannedSemanticOpKind, type PullFailureReason, type PullResult, type PushOutcome, type PushOutcomeKind, type PushResult, type PushResultKind, type ReplaceClipContentInput, type ReplaceMediaClipInput, type ReplaceSequentialClipsInput, type ReplacementMediaClipInput, type ResolvedEntityClipPlacement, type ResolvedEntityTimelineLayout, type ResolvedEntityTrack, type ReviseAudioScriptInput, type ReviseAudioScriptResult, SchemaValidator, ScriptCompositionError, type SemanticDocumentAdapter, SemanticEditor, type SemanticOpInput, type SemanticOpKind, type SemanticOpName, type SequentialClipAnchor, type SetBgmInput, type SetCaptionVisibilityInput, type SetClipPlacementInput, type SetClipSpeedInput, type SetClipVolumeInput, type SnapshotReadable, type SolvedVideoDocument, type SpeechHostMap, type SpeechPart, type SpeedShift, TIMELINE_SKELETON_DURATION_MS, type Timeline, type TimelineDoc, type TimelineItem, type Track, type TrackDraft, type TrackItem, type TrackItemDraft, type TrackItemTimePosition, type TransactAudit, type TrimClipInput, type UpdateClipInput, type UpdateClipMarkerInput, ValidationError, type VideoClipPart, type VideoDocument, type VideoDocumentDraft, type VideoDocumentMirrorSchema, VideoDocumentValidationError, type VideoDocumentValidationIssue, type VideoDocumentValidationIssueCode, type VideoDraft, type CaptionPart$1 as VideoDraftCaptionPart, type VideoDraftContent, type VideoDraftPartUnion, type Timeline$1 as VideoDraftTimeline, type Track$1 as VideoDraftTrack, type TrackItem$1 as VideoDraftTrackItem, type VideoMediaAssetFact, type VisualAssetsEffectInput, type VisualMediaAssetFact, type VoiceoverCaptionFact, type VoiceoverMediaAssetFact, type VoiceoverTakeInput, type VoiceoverTakeResult, type WaitForServerAckOptions, applyEntityRows, applyFieldChanges, applyVisualAssetsEffect, 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, hasVisualAssetsEffect, hostForAbsMs, importMediaAsset, isEmptyVideoClip, isImplementedSemanticOpKind, isMap, laneTrackId, mainTrackRanges, migrateAlpha23EntityDocument, migrateLegacyTimelineToEntities, partDurationMs, partUnionSchema, phoneticScriptAssetContent, phoneticScriptAssetHash, phoneticScriptAssetOf, prepareCaptionContent, projectEntityTimeline, publishEntityRows, readDocumentAudioScript, readEntityDocument, readEntityRelationRecords, readMainTrackItems, readMengineEventStream, readPart, readPartDurationMs, readVideoDocumentFromDraft, reassignSpeechesToVideoClipsByTime, recalculateTimelineDuration, relativePositionForAbs, replayJournal, resolveAllSpeechOverlaps, resolveEntityTimelineLayout, resolveFieldPath, resolveSpeechOverlapByShiftingVideos, reviseAudioScript, safeDurationMs, index_d_exports as schemas, scriptSourceAssetOf, selectAudioScriptSegment, snapshotToPlain, solveVideoDocument, speedOf, syncAggregatedClipsTimePosition, toVideoDocument, validateVideoDocument, videoDocumentMirrorSchema, videoDocumentSchema };