@webpacked-timeline/core 1.0.0-beta.1

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.
Files changed (77) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/LICENSE +21 -0
  3. package/README.md +162 -0
  4. package/dist/chunk-27XCNVPR.js +5969 -0
  5. package/dist/chunk-6PDBJDHM.js +2263 -0
  6. package/dist/chunk-BWPS6NQT.js +7465 -0
  7. package/dist/chunk-FBOYSUYV.js +1280 -0
  8. package/dist/chunk-FR632TZX.js +1870 -0
  9. package/dist/chunk-HW4Z7YLJ.js +1242 -0
  10. package/dist/chunk-HWW62IFH.js +5424 -0
  11. package/dist/chunk-I2GZXRH4.js +4790 -0
  12. package/dist/chunk-JQZE3OK4.js +1255 -0
  13. package/dist/chunk-KF7JNK2F.js +1864 -0
  14. package/dist/chunk-KR3P2DYK.js +5655 -0
  15. package/dist/chunk-MO5DSFSW.js +2214 -0
  16. package/dist/chunk-MQAW33RJ.js +5530 -0
  17. package/dist/chunk-N4WUWZZX.js +2833 -0
  18. package/dist/chunk-NRJV7I4C.js +1331 -0
  19. package/dist/chunk-NXG52532.js +2230 -0
  20. package/dist/chunk-PVXF67CN.js +1278 -0
  21. package/dist/chunk-QSB6DHIF.js +5429 -0
  22. package/dist/chunk-QYWJT7HR.js +5837 -0
  23. package/dist/chunk-SWBRCMW7.js +7466 -0
  24. package/dist/chunk-TAT3ULSV.js +2214 -0
  25. package/dist/chunk-TTDP5JUM.js +2228 -0
  26. package/dist/chunk-UAGP4VPG.js +1739 -0
  27. package/dist/chunk-WIG6SY7A.js +1183 -0
  28. package/dist/chunk-YJ2K5N2R.js +6187 -0
  29. package/dist/index-3Lr_vKBd.d.cts +2810 -0
  30. package/dist/index-3Lr_vKBd.d.ts +2810 -0
  31. package/dist/index-7IPJn1yM.d.cts +1146 -0
  32. package/dist/index-7IPJn1yM.d.ts +1146 -0
  33. package/dist/index-B0xOv0V0.d.cts +3259 -0
  34. package/dist/index-B0xOv0V0.d.ts +3259 -0
  35. package/dist/index-B2m3zwg7.d.cts +1381 -0
  36. package/dist/index-B2m3zwg7.d.ts +1381 -0
  37. package/dist/index-B3sUrU_X.d.cts +1249 -0
  38. package/dist/index-B3sUrU_X.d.ts +1249 -0
  39. package/dist/index-B6wla7ZJ.d.cts +2751 -0
  40. package/dist/index-B6wla7ZJ.d.ts +2751 -0
  41. package/dist/index-BIv8RWWT.d.cts +1574 -0
  42. package/dist/index-BIv8RWWT.d.ts +1574 -0
  43. package/dist/index-BJv6hDHL.d.cts +3255 -0
  44. package/dist/index-BJv6hDHL.d.ts +3255 -0
  45. package/dist/index-BUCimS2e.d.cts +1393 -0
  46. package/dist/index-BUCimS2e.d.ts +1393 -0
  47. package/dist/index-Bw_nvNcG.d.cts +1275 -0
  48. package/dist/index-Bw_nvNcG.d.ts +1275 -0
  49. package/dist/index-ByG0gOtd.d.cts +1167 -0
  50. package/dist/index-ByG0gOtd.d.ts +1167 -0
  51. package/dist/index-CDGd2XXv.d.cts +2492 -0
  52. package/dist/index-CDGd2XXv.d.ts +2492 -0
  53. package/dist/index-CznAVeJ6.d.cts +1145 -0
  54. package/dist/index-CznAVeJ6.d.ts +1145 -0
  55. package/dist/index-DQD9IMh7.d.cts +2534 -0
  56. package/dist/index-DQD9IMh7.d.ts +2534 -0
  57. package/dist/index-Dl3qtJEI.d.cts +2178 -0
  58. package/dist/index-Dl3qtJEI.d.ts +2178 -0
  59. package/dist/index-DnE2A-Nz.d.cts +2603 -0
  60. package/dist/index-DnE2A-Nz.d.ts +2603 -0
  61. package/dist/index-DrOA6QmW.d.cts +2492 -0
  62. package/dist/index-DrOA6QmW.d.ts +2492 -0
  63. package/dist/index-Vpa3rPEM.d.cts +1402 -0
  64. package/dist/index-Vpa3rPEM.d.ts +1402 -0
  65. package/dist/index-jP6BomSd.d.cts +2640 -0
  66. package/dist/index-jP6BomSd.d.ts +2640 -0
  67. package/dist/index-wiGRwVyY.d.cts +3259 -0
  68. package/dist/index-wiGRwVyY.d.ts +3259 -0
  69. package/dist/index.cjs +7386 -0
  70. package/dist/index.d.cts +1 -0
  71. package/dist/index.d.ts +1 -0
  72. package/dist/index.js +263 -0
  73. package/dist/internal.cjs +7721 -0
  74. package/dist/internal.d.cts +704 -0
  75. package/dist/internal.d.ts +704 -0
  76. package/dist/internal.js +405 -0
  77. package/package.json +58 -0
@@ -0,0 +1,2214 @@
1
+ // src/types/timeline.ts
2
+ var DEFAULT_SEQUENCE_SETTINGS = {
3
+ pixelAspectRatio: 1,
4
+ fieldOrder: "progressive",
5
+ colorSpace: "sRGB",
6
+ audioSampleRate: 48e3,
7
+ audioChannelCount: 2
8
+ };
9
+ function createTimeline(params) {
10
+ return {
11
+ id: params.id,
12
+ name: params.name,
13
+ fps: params.fps,
14
+ duration: params.duration,
15
+ startTimecode: params.startTimecode ?? "00:00:00:00",
16
+ tracks: params.tracks ?? [],
17
+ sequenceSettings: { ...DEFAULT_SEQUENCE_SETTINGS, ...params.sequenceSettings },
18
+ version: 0
19
+ };
20
+ }
21
+
22
+ // src/types/track.ts
23
+ function createTrack(params) {
24
+ return {
25
+ id: params.id,
26
+ name: params.name,
27
+ type: params.type,
28
+ clips: params.clips ?? [],
29
+ locked: params.locked ?? false,
30
+ muted: params.muted ?? false,
31
+ solo: params.solo ?? false,
32
+ height: params.height ?? 56
33
+ };
34
+ }
35
+ function sortTrackClips(track) {
36
+ return {
37
+ ...track,
38
+ clips: [...track.clips].sort((a, b) => a.timelineStart - b.timelineStart)
39
+ };
40
+ }
41
+
42
+ // src/types/clip.ts
43
+ function createClip(params) {
44
+ return {
45
+ id: params.id,
46
+ assetId: params.assetId,
47
+ trackId: params.trackId,
48
+ timelineStart: params.timelineStart,
49
+ timelineEnd: params.timelineEnd,
50
+ mediaIn: params.mediaIn,
51
+ mediaOut: params.mediaOut,
52
+ speed: params.speed ?? 1,
53
+ enabled: params.enabled ?? true,
54
+ reversed: params.reversed ?? false,
55
+ name: params.name ?? null,
56
+ color: params.color ?? null,
57
+ metadata: params.metadata ?? {}
58
+ };
59
+ }
60
+ function getClipDuration(clip) {
61
+ return clip.timelineEnd - clip.timelineStart;
62
+ }
63
+ function getClipMediaDuration(clip) {
64
+ return clip.mediaOut - clip.mediaIn;
65
+ }
66
+ function clipContainsFrame(clip, f) {
67
+ return f >= clip.timelineStart && f < clip.timelineEnd;
68
+ }
69
+ function clipsOverlap(a, b) {
70
+ return a.timelineStart < b.timelineEnd && b.timelineStart < a.timelineEnd;
71
+ }
72
+
73
+ // src/types/asset.ts
74
+ var toAssetId = (s) => s;
75
+ function createAsset(params) {
76
+ return {
77
+ id: params.id,
78
+ name: params.name,
79
+ mediaType: params.mediaType,
80
+ filePath: params.filePath,
81
+ intrinsicDuration: params.intrinsicDuration,
82
+ nativeFps: params.nativeFps,
83
+ sourceTimecodeOffset: params.sourceTimecodeOffset,
84
+ status: params.status ?? "online"
85
+ };
86
+ }
87
+
88
+ // src/types/state.ts
89
+ function createTimelineState(params) {
90
+ const registry = params.assetRegistry ?? (params.assets ? params.assets : /* @__PURE__ */ new Map());
91
+ return {
92
+ timeline: params.timeline,
93
+ assetRegistry: registry
94
+ };
95
+ }
96
+
97
+ // src/types/frame.ts
98
+ var toFrame = (n) => n;
99
+ function frame(value) {
100
+ const rounded = Math.round(value);
101
+ if (rounded < 0) {
102
+ throw new Error(`TimelineFrame must be non-negative, got: ${value}`);
103
+ }
104
+ return rounded;
105
+ }
106
+ var FrameRates = {
107
+ CINEMA: 24,
108
+ PAL: 25,
109
+ NTSC_DF: 29.97,
110
+ NTSC: 30,
111
+ PAL_HFR: 50,
112
+ NTSC_HFR: 59.94,
113
+ HFR: 60
114
+ };
115
+ function frameRate(value) {
116
+ const valid = [23.976, 24, 25, 29.97, 30, 50, 59.94, 60];
117
+ if (!valid.includes(value)) {
118
+ throw new Error(
119
+ `FrameRate must be one of ${valid.join(", ")}, got: ${value}`
120
+ );
121
+ }
122
+ return value;
123
+ }
124
+ var toTimecode = (s) => s;
125
+ function isValidFrame(value) {
126
+ return Number.isInteger(value) && value >= 0;
127
+ }
128
+ function isDropFrame(fps) {
129
+ return fps === 29.97 || fps === 59.94;
130
+ }
131
+
132
+ // src/utils/frame.ts
133
+ function framesToSeconds(frames, fps) {
134
+ return frames / fps;
135
+ }
136
+ function secondsToFrames(seconds, fps) {
137
+ return toFrame(seconds * fps);
138
+ }
139
+ function framesToTimecode(frames, fps) {
140
+ const totalFrames = frames;
141
+ const framesPart = totalFrames % fps;
142
+ const totalSeconds = Math.floor(totalFrames / fps);
143
+ const secondsPart = totalSeconds % 60;
144
+ const totalMinutes = Math.floor(totalSeconds / 60);
145
+ const minutesPart = totalMinutes % 60;
146
+ const hoursPart = Math.floor(totalMinutes / 60);
147
+ return `${pad(hoursPart)}:${pad(minutesPart)}:${pad(secondsPart)}:${pad(framesPart)}`;
148
+ }
149
+ function framesToMinutesSeconds(frames, fps) {
150
+ const totalSeconds = Math.floor(frames / fps);
151
+ const minutes = Math.floor(totalSeconds / 60);
152
+ const seconds = totalSeconds % 60;
153
+ return `${minutes}:${pad(seconds)}`;
154
+ }
155
+ function clampFrame(value, min, max) {
156
+ return toFrame(Math.max(min, Math.min(max, value)));
157
+ }
158
+ function addFrames(a, b) {
159
+ return toFrame(a + b);
160
+ }
161
+ function subtractFrames(a, b) {
162
+ return toFrame(Math.max(0, a - b));
163
+ }
164
+ function frameDuration(start, end) {
165
+ return toFrame(end - start);
166
+ }
167
+ function pad(num, width = 2) {
168
+ return num.toString().padStart(width, "0");
169
+ }
170
+
171
+ // src/engine/history.ts
172
+ function createHistory(initialState, limit = 50) {
173
+ return {
174
+ past: [],
175
+ present: initialState,
176
+ future: [],
177
+ limit
178
+ };
179
+ }
180
+ function pushHistory(history, newState) {
181
+ const newPast = [...history.past, history.present];
182
+ if (newPast.length > history.limit) {
183
+ newPast.shift();
184
+ }
185
+ return {
186
+ ...history,
187
+ past: newPast,
188
+ present: newState,
189
+ future: []
190
+ // Clear future on new action
191
+ };
192
+ }
193
+ function undo(history) {
194
+ if (history.past.length === 0) {
195
+ return history;
196
+ }
197
+ const newPast = [...history.past];
198
+ const previous = newPast.pop();
199
+ return {
200
+ ...history,
201
+ past: newPast,
202
+ present: previous,
203
+ future: [history.present, ...history.future]
204
+ };
205
+ }
206
+ function redo(history) {
207
+ if (history.future.length === 0) {
208
+ return history;
209
+ }
210
+ const newFuture = [...history.future];
211
+ const next = newFuture.shift();
212
+ return {
213
+ ...history,
214
+ past: [...history.past, history.present],
215
+ present: next,
216
+ future: newFuture
217
+ };
218
+ }
219
+ function canUndo(history) {
220
+ return history.past.length > 0;
221
+ }
222
+ function canRedo(history) {
223
+ return history.future.length > 0;
224
+ }
225
+ function getCurrentState(history) {
226
+ return history.present;
227
+ }
228
+
229
+ // src/systems/queries.ts
230
+ function findClipById(state, clipId) {
231
+ for (const track of state.timeline.tracks) {
232
+ const clip = track.clips.find((c) => c.id === clipId);
233
+ if (clip) {
234
+ return clip;
235
+ }
236
+ }
237
+ return void 0;
238
+ }
239
+ function findTrackById(state, trackId) {
240
+ return state.timeline.tracks.find((t) => t.id === trackId);
241
+ }
242
+ function getClipsOnTrack(state, trackId) {
243
+ const track = findTrackById(state, trackId);
244
+ return track ? Array.from(track.clips) : [];
245
+ }
246
+ function getClipsAtFrame(state, frame2) {
247
+ const clips = [];
248
+ for (const track of state.timeline.tracks) {
249
+ for (const clip of track.clips) {
250
+ if (clipContainsFrame(clip, frame2)) {
251
+ clips.push(clip);
252
+ }
253
+ }
254
+ }
255
+ return clips;
256
+ }
257
+ function getClipsInRange(state, start, end) {
258
+ const clips = [];
259
+ for (const track of state.timeline.tracks) {
260
+ for (const clip of track.clips) {
261
+ if (clip.timelineStart < end && clip.timelineEnd > start) {
262
+ clips.push(clip);
263
+ }
264
+ }
265
+ }
266
+ return clips;
267
+ }
268
+ function getAllClips(state) {
269
+ const clips = [];
270
+ for (const track of state.timeline.tracks) {
271
+ clips.push(...track.clips);
272
+ }
273
+ return clips;
274
+ }
275
+ function getAllTracks(state) {
276
+ return state.timeline.tracks;
277
+ }
278
+ function findTrackIndex(state, trackId) {
279
+ return state.timeline.tracks.findIndex((t) => t.id === trackId);
280
+ }
281
+
282
+ // src/types/validation.ts
283
+ function validResult() {
284
+ return {
285
+ valid: true,
286
+ errors: []
287
+ };
288
+ }
289
+ function invalidResult(code, message, context) {
290
+ const error = { code, message };
291
+ if (context !== void 0) {
292
+ error.context = context;
293
+ }
294
+ return {
295
+ valid: false,
296
+ errors: [error]
297
+ };
298
+ }
299
+ function invalidResults(errors) {
300
+ return {
301
+ valid: false,
302
+ errors
303
+ };
304
+ }
305
+ function combineResults(...results) {
306
+ const allErrors = [];
307
+ for (const result of results) {
308
+ if (!result.valid) {
309
+ allErrors.push(...result.errors);
310
+ }
311
+ }
312
+ if (allErrors.length > 0) {
313
+ return invalidResults(allErrors);
314
+ }
315
+ return validResult();
316
+ }
317
+
318
+ // src/systems/asset-registry.ts
319
+ function registerAsset(state, asset) {
320
+ const next = new Map(state.assetRegistry);
321
+ next.set(asset.id, asset);
322
+ return { ...state, assetRegistry: next };
323
+ }
324
+ function getAsset(state, assetId) {
325
+ return state.assetRegistry.get(toAssetId(assetId));
326
+ }
327
+ function hasAsset(state, assetId) {
328
+ return state.assetRegistry.has(toAssetId(assetId));
329
+ }
330
+ function getAllAssets(state) {
331
+ return Array.from(state.assetRegistry.values());
332
+ }
333
+ function unregisterAsset(state, assetId) {
334
+ const next = new Map(state.assetRegistry);
335
+ next.delete(toAssetId(assetId));
336
+ return { ...state, assetRegistry: next };
337
+ }
338
+
339
+ // src/systems/validation.ts
340
+ function validateClip(state, clip) {
341
+ const errors = [];
342
+ const asset = getAsset(state, clip.assetId);
343
+ if (!asset) {
344
+ errors.push(invalidResult(
345
+ "ASSET_NOT_FOUND",
346
+ `Asset '${clip.assetId}' not found in registry`,
347
+ { clipId: clip.id, assetId: clip.assetId }
348
+ ));
349
+ return combineResults(...errors);
350
+ }
351
+ if (clip.timelineEnd <= clip.timelineStart) {
352
+ errors.push(invalidResult(
353
+ "INVALID_TIMELINE_BOUNDS",
354
+ `Clip timeline end (${clip.timelineEnd}) must be greater than start (${clip.timelineStart})`,
355
+ { clipId: clip.id, timelineStart: clip.timelineStart, timelineEnd: clip.timelineEnd }
356
+ ));
357
+ }
358
+ if (clip.mediaIn < 0) {
359
+ errors.push(invalidResult(
360
+ "INVALID_MEDIA_IN",
361
+ `Clip media in (${clip.mediaIn}) must be >= 0`,
362
+ { clipId: clip.id, mediaIn: clip.mediaIn }
363
+ ));
364
+ }
365
+ if (clip.mediaOut <= clip.mediaIn) {
366
+ errors.push(invalidResult(
367
+ "INVALID_MEDIA_BOUNDS",
368
+ `Clip media out (${clip.mediaOut}) must be greater than media in (${clip.mediaIn})`,
369
+ { clipId: clip.id, mediaIn: clip.mediaIn, mediaOut: clip.mediaOut }
370
+ ));
371
+ }
372
+ if (clip.mediaOut > asset.intrinsicDuration) {
373
+ errors.push(invalidResult(
374
+ "MEDIA_EXCEEDS_ASSET",
375
+ `Clip media out (${clip.mediaOut}) exceeds asset duration (${asset.intrinsicDuration})`,
376
+ { clipId: clip.id, mediaOut: clip.mediaOut, assetDuration: asset.intrinsicDuration }
377
+ ));
378
+ }
379
+ const timelineDuration = getClipDuration(clip);
380
+ const mediaDuration = getClipMediaDuration(clip);
381
+ if (timelineDuration !== mediaDuration) {
382
+ errors.push(invalidResult(
383
+ "DURATION_MISMATCH",
384
+ `Clip timeline duration (${timelineDuration}) must match media duration (${mediaDuration}) in Phase 1`,
385
+ { clipId: clip.id, timelineDuration, mediaDuration }
386
+ ));
387
+ }
388
+ return combineResults(...errors);
389
+ }
390
+ function validateTrack(state, track) {
391
+ const errors = [];
392
+ for (const clip of track.clips) {
393
+ const clipResult = validateClip(state, clip);
394
+ if (!clipResult.valid) {
395
+ errors.push(clipResult);
396
+ }
397
+ }
398
+ for (let i = 0; i < track.clips.length; i++) {
399
+ for (let j = i + 1; j < track.clips.length; j++) {
400
+ const clip1 = track.clips[i];
401
+ const clip2 = track.clips[j];
402
+ if (!clip1 || !clip2) {
403
+ continue;
404
+ }
405
+ if (clipsOverlap(clip1, clip2)) {
406
+ errors.push(invalidResult(
407
+ "CLIPS_OVERLAP",
408
+ `Clips '${clip1.id}' and '${clip2.id}' overlap on track '${track.id}'`,
409
+ {
410
+ trackId: track.id,
411
+ clip1Id: clip1.id,
412
+ clip2Id: clip2.id,
413
+ clip1Start: clip1.timelineStart,
414
+ clip1End: clip1.timelineEnd,
415
+ clip2Start: clip2.timelineStart,
416
+ clip2End: clip2.timelineEnd
417
+ }
418
+ ));
419
+ }
420
+ }
421
+ }
422
+ return combineResults(...errors);
423
+ }
424
+ function validateTimeline(state) {
425
+ const errors = [];
426
+ if (state.timeline.fps <= 0) {
427
+ errors.push(invalidResult(
428
+ "INVALID_FPS",
429
+ `Timeline FPS must be positive, got ${state.timeline.fps}`,
430
+ { fps: state.timeline.fps }
431
+ ));
432
+ }
433
+ if (state.timeline.duration <= 0) {
434
+ errors.push(invalidResult(
435
+ "INVALID_DURATION",
436
+ `Timeline duration must be positive, got ${state.timeline.duration}`,
437
+ { duration: state.timeline.duration }
438
+ ));
439
+ }
440
+ for (const track of state.timeline.tracks) {
441
+ const trackResult = validateTrack(state, track);
442
+ if (!trackResult.valid) {
443
+ errors.push(trackResult);
444
+ }
445
+ }
446
+ return combineResults(...errors);
447
+ }
448
+ function validateNoOverlap(track, clip) {
449
+ for (const existingClip of track.clips) {
450
+ if (existingClip.id === clip.id) {
451
+ continue;
452
+ }
453
+ if (clipsOverlap(existingClip, clip)) {
454
+ return invalidResult(
455
+ "CLIPS_OVERLAP",
456
+ `Clip '${clip.id}' would overlap with existing clip '${existingClip.id}' on track '${track.id}'`,
457
+ {
458
+ trackId: track.id,
459
+ newClipId: clip.id,
460
+ existingClipId: existingClip.id,
461
+ newClipStart: clip.timelineStart,
462
+ newClipEnd: clip.timelineEnd,
463
+ existingClipStart: existingClip.timelineStart,
464
+ existingClipEnd: existingClip.timelineEnd
465
+ }
466
+ );
467
+ }
468
+ }
469
+ return validResult();
470
+ }
471
+ function validateTrackTypeMatch(state, clip, targetTrack) {
472
+ const asset = getAsset(state, clip.assetId);
473
+ if (!asset) {
474
+ return invalidResult(
475
+ "ASSET_NOT_FOUND",
476
+ `Asset '${clip.assetId}' not found in registry`,
477
+ { clipId: clip.id, assetId: clip.assetId }
478
+ );
479
+ }
480
+ if (asset.mediaType === "video" && targetTrack.type !== "video") {
481
+ return invalidResult(
482
+ "TRACK_TYPE_MISMATCH",
483
+ `Cannot place video clip '${clip.id}' on ${targetTrack.type} track '${targetTrack.id}'`,
484
+ {
485
+ clipId: clip.id,
486
+ assetType: asset.mediaType,
487
+ trackType: targetTrack.type,
488
+ trackId: targetTrack.id
489
+ }
490
+ );
491
+ }
492
+ if (asset.mediaType === "audio" && targetTrack.type !== "audio") {
493
+ return invalidResult(
494
+ "TRACK_TYPE_MISMATCH",
495
+ `Cannot place audio clip '${clip.id}' on ${targetTrack.type} track '${targetTrack.id}'`,
496
+ {
497
+ clipId: clip.id,
498
+ assetType: asset.mediaType,
499
+ trackType: targetTrack.type,
500
+ trackId: targetTrack.id
501
+ }
502
+ );
503
+ }
504
+ return validResult();
505
+ }
506
+
507
+ // src/operations/clip-operations.ts
508
+ function addClip(state, trackId, clip) {
509
+ const trackIndex = state.timeline.tracks.findIndex((t) => t.id === trackId);
510
+ if (trackIndex === -1) {
511
+ return state;
512
+ }
513
+ const track = state.timeline.tracks[trackIndex];
514
+ if (!track) {
515
+ return state;
516
+ }
517
+ const newTrack = sortTrackClips({
518
+ ...track,
519
+ clips: [...track.clips, clip]
520
+ });
521
+ const newTracks = [...state.timeline.tracks];
522
+ newTracks[trackIndex] = newTrack;
523
+ return {
524
+ ...state,
525
+ timeline: {
526
+ ...state.timeline,
527
+ tracks: newTracks
528
+ }
529
+ };
530
+ }
531
+ function removeClip(state, clipId) {
532
+ const newTracks = state.timeline.tracks.map((track) => ({
533
+ ...track,
534
+ clips: track.clips.filter((c) => c.id !== clipId)
535
+ }));
536
+ return {
537
+ ...state,
538
+ timeline: {
539
+ ...state.timeline,
540
+ tracks: newTracks
541
+ }
542
+ };
543
+ }
544
+ function moveClip(state, clipId, newStart) {
545
+ const clip = findClipById(state, clipId);
546
+ if (!clip) {
547
+ return state;
548
+ }
549
+ const duration = clip.timelineEnd - clip.timelineStart;
550
+ const newEnd = newStart + duration;
551
+ return updateClip(state, clipId, {
552
+ timelineStart: newStart,
553
+ timelineEnd: newEnd
554
+ });
555
+ }
556
+ function resizeClip(state, clipId, newStart, newEnd) {
557
+ const clip = findClipById(state, clipId);
558
+ if (!clip) {
559
+ return state;
560
+ }
561
+ const startDelta = newStart - clip.timelineStart;
562
+ const endDelta = newEnd - clip.timelineEnd;
563
+ let newMediaIn = clip.mediaIn;
564
+ let newMediaOut = clip.mediaOut;
565
+ if (startDelta !== 0) {
566
+ newMediaIn = clip.mediaIn + startDelta;
567
+ }
568
+ if (endDelta !== 0) {
569
+ newMediaOut = clip.mediaOut + endDelta;
570
+ }
571
+ return updateClip(state, clipId, {
572
+ timelineStart: newStart,
573
+ timelineEnd: newEnd,
574
+ mediaIn: newMediaIn,
575
+ mediaOut: newMediaOut
576
+ });
577
+ }
578
+ function trimClip(state, clipId, newMediaIn, newMediaOut) {
579
+ return updateClip(state, clipId, {
580
+ mediaIn: newMediaIn,
581
+ mediaOut: newMediaOut
582
+ });
583
+ }
584
+ function updateClip(state, clipId, updates) {
585
+ const newTracks = state.timeline.tracks.map((track) => {
586
+ const clipIndex = track.clips.findIndex((c) => c.id === clipId);
587
+ if (clipIndex === -1) {
588
+ return track;
589
+ }
590
+ const newClips = [...track.clips];
591
+ const existingClip = newClips[clipIndex];
592
+ if (!existingClip) {
593
+ return track;
594
+ }
595
+ newClips[clipIndex] = {
596
+ ...existingClip,
597
+ ...updates
598
+ };
599
+ return sortTrackClips({
600
+ ...track,
601
+ clips: newClips
602
+ });
603
+ });
604
+ return {
605
+ ...state,
606
+ timeline: {
607
+ ...state.timeline,
608
+ tracks: newTracks
609
+ }
610
+ };
611
+ }
612
+ function moveClipToTrack(state, clipId, targetTrackId) {
613
+ const clip = findClipById(state, clipId);
614
+ if (!clip) {
615
+ return state;
616
+ }
617
+ const targetTrack = findTrackById(state, targetTrackId);
618
+ if (!targetTrack) {
619
+ return state;
620
+ }
621
+ const validationResult = validateTrackTypeMatch(state, clip, targetTrack);
622
+ if (!validationResult.valid) {
623
+ return state;
624
+ }
625
+ if (clip.trackId === targetTrackId) {
626
+ return state;
627
+ }
628
+ let newState = removeClip(state, clipId);
629
+ const updatedClip = { ...clip, trackId: targetTrackId };
630
+ newState = addClip(newState, targetTrackId, updatedClip);
631
+ return newState;
632
+ }
633
+
634
+ // src/operations/track-operations.ts
635
+ function addTrack(state, track) {
636
+ return {
637
+ ...state,
638
+ timeline: {
639
+ ...state.timeline,
640
+ tracks: [...state.timeline.tracks, track]
641
+ }
642
+ };
643
+ }
644
+ function removeTrack(state, trackId) {
645
+ return {
646
+ ...state,
647
+ timeline: {
648
+ ...state.timeline,
649
+ tracks: state.timeline.tracks.filter((t) => t.id !== trackId)
650
+ }
651
+ };
652
+ }
653
+ function moveTrack(state, trackId, newIndex) {
654
+ const currentIndex = findTrackIndex(state, trackId);
655
+ if (currentIndex === -1) {
656
+ return state;
657
+ }
658
+ const newTracks = [...state.timeline.tracks];
659
+ const [track] = newTracks.splice(currentIndex, 1);
660
+ if (!track) {
661
+ return state;
662
+ }
663
+ newTracks.splice(newIndex, 0, track);
664
+ return {
665
+ ...state,
666
+ timeline: {
667
+ ...state.timeline,
668
+ tracks: newTracks
669
+ }
670
+ };
671
+ }
672
+ function updateTrack(state, trackId, updates) {
673
+ const trackIndex = findTrackIndex(state, trackId);
674
+ if (trackIndex === -1) {
675
+ return state;
676
+ }
677
+ const newTracks = [...state.timeline.tracks];
678
+ const existingTrack = newTracks[trackIndex];
679
+ if (!existingTrack) {
680
+ return state;
681
+ }
682
+ newTracks[trackIndex] = {
683
+ ...existingTrack,
684
+ ...updates
685
+ };
686
+ return {
687
+ ...state,
688
+ timeline: {
689
+ ...state.timeline,
690
+ tracks: newTracks
691
+ }
692
+ };
693
+ }
694
+ function toggleTrackMute(state, trackId) {
695
+ const trackIndex = findTrackIndex(state, trackId);
696
+ if (trackIndex === -1) {
697
+ return state;
698
+ }
699
+ const track = state.timeline.tracks[trackIndex];
700
+ if (!track) {
701
+ return state;
702
+ }
703
+ return updateTrack(state, trackId, { muted: !track.muted });
704
+ }
705
+ function toggleTrackLock(state, trackId) {
706
+ const trackIndex = findTrackIndex(state, trackId);
707
+ if (trackIndex === -1) {
708
+ return state;
709
+ }
710
+ const track = state.timeline.tracks[trackIndex];
711
+ if (!track) {
712
+ return state;
713
+ }
714
+ return updateTrack(state, trackId, { locked: !track.locked });
715
+ }
716
+ function toggleTrackSolo(state, trackId) {
717
+ const trackIndex = findTrackIndex(state, trackId);
718
+ if (trackIndex === -1) {
719
+ return state;
720
+ }
721
+ const track = state.timeline.tracks[trackIndex];
722
+ if (!track) {
723
+ return state;
724
+ }
725
+ return updateTrack(state, trackId, { solo: !track.solo });
726
+ }
727
+ function setTrackHeight(state, trackId, height) {
728
+ return updateTrack(state, trackId, { height: Math.max(40, Math.min(200, height)) });
729
+ }
730
+
731
+ // src/operations/timeline-operations.ts
732
+ function setTimelineDuration(state, duration) {
733
+ return {
734
+ ...state,
735
+ timeline: {
736
+ ...state.timeline,
737
+ duration
738
+ }
739
+ };
740
+ }
741
+ function setTimelineName(state, name) {
742
+ return {
743
+ ...state,
744
+ timeline: {
745
+ ...state.timeline,
746
+ name
747
+ }
748
+ };
749
+ }
750
+
751
+ // src/engine/transactions.ts
752
+ function beginTransaction(state) {
753
+ return {
754
+ initialState: state,
755
+ currentState: state,
756
+ operations: [],
757
+ finalized: false
758
+ };
759
+ }
760
+ function applyOperation(tx, operation) {
761
+ if (tx.finalized) {
762
+ throw new Error("Cannot apply operation to finalized transaction");
763
+ }
764
+ const newState = operation(tx.currentState);
765
+ return {
766
+ ...tx,
767
+ currentState: newState,
768
+ operations: [...tx.operations, operation]
769
+ };
770
+ }
771
+ function commitTransaction(tx) {
772
+ if (tx.finalized) {
773
+ throw new Error("Transaction already finalized");
774
+ }
775
+ tx.finalized = true;
776
+ return tx.currentState;
777
+ }
778
+
779
+ // src/operations/ripple.ts
780
+ function rippleDelete(state, clipId) {
781
+ const clip = findClipById(state, clipId);
782
+ if (!clip) {
783
+ throw new Error(`Clip not found: ${clipId}`);
784
+ }
785
+ const track = findTrackById(state, clip.trackId);
786
+ if (!track) {
787
+ throw new Error(`Track not found: ${clip.trackId}`);
788
+ }
789
+ const clipDuration = getClipDuration(clip);
790
+ const deleteEnd = clip.timelineEnd;
791
+ const clipsToShift = track.clips.filter(
792
+ (c) => c.id !== clipId && c.timelineStart >= deleteEnd
793
+ );
794
+ let tx = beginTransaction(state);
795
+ tx = applyOperation(tx, (s) => removeClip(s, clipId));
796
+ for (const clipToShift of clipsToShift) {
797
+ const newStart = clipToShift.timelineStart - clipDuration;
798
+ tx = applyOperation(tx, (s) => moveClip(s, clipToShift.id, newStart));
799
+ }
800
+ return commitTransaction(tx);
801
+ }
802
+ function rippleTrim(state, clipId, newEnd) {
803
+ const clip = findClipById(state, clipId);
804
+ if (!clip) {
805
+ throw new Error(`Clip not found: ${clipId}`);
806
+ }
807
+ const track = findTrackById(state, clip.trackId);
808
+ if (!track) {
809
+ throw new Error(`Track not found: ${clip.trackId}`);
810
+ }
811
+ if (newEnd <= clip.timelineStart) {
812
+ throw new Error("New end must be after clip start");
813
+ }
814
+ const delta = newEnd - clip.timelineEnd;
815
+ const clipsToShift = track.clips.filter(
816
+ (c) => c.id !== clipId && c.timelineStart >= clip.timelineEnd
817
+ );
818
+ let tx = beginTransaction(state);
819
+ tx = applyOperation(tx, (s) => resizeClip(s, clipId, clip.timelineStart, newEnd));
820
+ for (const clipToShift of clipsToShift) {
821
+ const newStart = clipToShift.timelineStart + delta;
822
+ tx = applyOperation(tx, (s) => moveClip(s, clipToShift.id, newStart));
823
+ }
824
+ return commitTransaction(tx);
825
+ }
826
+ function insertEdit(state, trackId, clip, atFrame) {
827
+ const track = findTrackById(state, trackId);
828
+ if (!track) {
829
+ throw new Error(`Track not found: ${trackId}`);
830
+ }
831
+ const clipDuration = getClipDuration(clip);
832
+ const clipsToShift = track.clips.filter((c) => c.timelineStart >= atFrame);
833
+ const adjustedClip = {
834
+ ...clip,
835
+ timelineStart: atFrame,
836
+ timelineEnd: atFrame + clipDuration
837
+ };
838
+ let tx = beginTransaction(state);
839
+ for (const clipToShift of clipsToShift) {
840
+ const newStart = clipToShift.timelineStart + clipDuration;
841
+ tx = applyOperation(tx, (s) => moveClip(s, clipToShift.id, newStart));
842
+ }
843
+ tx = applyOperation(tx, (s) => addClip(s, trackId, adjustedClip));
844
+ return commitTransaction(tx);
845
+ }
846
+ function rippleMove(state, clipId, newStart) {
847
+ const clip = findClipById(state, clipId);
848
+ if (!clip) {
849
+ throw new Error(`Clip not found: ${clipId}`);
850
+ }
851
+ const track = findTrackById(state, clip.trackId);
852
+ if (!track) {
853
+ throw new Error(`Track not found: ${clip.trackId}`);
854
+ }
855
+ const clipDuration = getClipDuration(clip);
856
+ const newEnd = newStart + clipDuration;
857
+ if (newStart < 0) {
858
+ throw new Error("Cannot move clip before timeline start (frame 0)");
859
+ }
860
+ if (newEnd > state.timeline.duration) {
861
+ throw new Error(`Cannot move clip beyond timeline duration (${state.timeline.duration} frames)`);
862
+ }
863
+ const originalStart = clip.timelineStart;
864
+ const originalEnd = clip.timelineEnd;
865
+ if (newStart === originalStart) {
866
+ return state;
867
+ }
868
+ let tx = beginTransaction(state);
869
+ if (newStart > originalStart) {
870
+ const afterSource = track.clips.filter((c) => c.id !== clipId && c.timelineStart >= originalEnd).sort((a, b) => a.timelineStart - b.timelineStart);
871
+ for (const other of afterSource) {
872
+ const s = other.timelineStart - clipDuration;
873
+ tx = applyOperation(tx, (st) => moveClip(st, other.id, s));
874
+ }
875
+ const anyClipBetween = afterSource.some((c) => c.timelineStart < newStart);
876
+ const collapsedDest = anyClipBetween ? newStart - clipDuration : newStart;
877
+ const currentTrack = tx.currentState.timeline.tracks.find((t) => t.id === track.id);
878
+ const atDest = currentTrack.clips.filter((c) => c.id !== clipId && c.timelineStart >= collapsedDest).sort((a, b) => b.timelineStart - a.timelineStart);
879
+ for (const other of atDest) {
880
+ const s = other.timelineStart + clipDuration;
881
+ tx = applyOperation(tx, (st) => moveClip(st, other.id, s));
882
+ }
883
+ tx = applyOperation(tx, (st) => moveClip(st, clipId, collapsedDest));
884
+ } else {
885
+ const afterSource = track.clips.filter((c) => c.id !== clipId && c.timelineStart >= originalEnd).sort((a, b) => a.timelineStart - b.timelineStart);
886
+ for (const other of afterSource) {
887
+ const s = other.timelineStart - clipDuration;
888
+ tx = applyOperation(tx, (st) => moveClip(st, other.id, s));
889
+ }
890
+ tx = applyOperation(tx, (st) => moveClip(st, clipId, newStart));
891
+ }
892
+ return commitTransaction(tx);
893
+ }
894
+ function insertMove(state, clipId, newStart) {
895
+ const clip = findClipById(state, clipId);
896
+ if (!clip) {
897
+ throw new Error(`Clip not found: ${clipId}`);
898
+ }
899
+ const track = findTrackById(state, clip.trackId);
900
+ if (!track) {
901
+ throw new Error(`Track not found: ${clip.trackId}`);
902
+ }
903
+ const clipDuration = getClipDuration(clip);
904
+ const newEnd = newStart + clipDuration;
905
+ if (newStart < 0) {
906
+ throw new Error("Cannot move clip before timeline start (frame 0)");
907
+ }
908
+ if (newEnd > state.timeline.duration) {
909
+ throw new Error(`Cannot move clip beyond timeline duration (${state.timeline.duration} frames)`);
910
+ }
911
+ if (newStart === clip.timelineStart) {
912
+ return state;
913
+ }
914
+ let tx = beginTransaction(state);
915
+ const clipsToShift = track.clips.filter(
916
+ (c) => c.id !== clipId && c.timelineStart >= newStart
917
+ );
918
+ for (const clipToShift of clipsToShift) {
919
+ const shiftedStart = clipToShift.timelineStart + clipDuration;
920
+ tx = applyOperation(tx, (s) => moveClip(s, clipToShift.id, shiftedStart));
921
+ }
922
+ tx = applyOperation(tx, (s) => moveClip(s, clipId, newStart));
923
+ return commitTransaction(tx);
924
+ }
925
+
926
+ // src/engine/timeline-engine.ts
927
+ function legacyDispatch(history, operation) {
928
+ const currentState = getCurrentState(history);
929
+ let newState;
930
+ try {
931
+ newState = operation(currentState);
932
+ } catch (err) {
933
+ return { accepted: false, errors: [{ code: "OPERATION_ERROR", message: String(err) }] };
934
+ }
935
+ const newHistory = pushHistory(history, newState);
936
+ return { accepted: true, history: newHistory };
937
+ }
938
+ var TimelineEngine = class {
939
+ history;
940
+ listeners = /* @__PURE__ */ new Set();
941
+ /**
942
+ * Create a new timeline engine
943
+ *
944
+ * @param initialState - Initial timeline state
945
+ * @param historyLimit - Maximum number of undo steps (default: 50)
946
+ */
947
+ constructor(initialState, historyLimit = 50) {
948
+ this.history = createHistory(initialState, historyLimit);
949
+ }
950
+ // ===== SUBSCRIPTION =====
951
+ /**
952
+ * Subscribe to state changes
953
+ *
954
+ * The listener will be called whenever the timeline state changes,
955
+ * with the new state passed as an argument.
956
+ * This is used by framework adapters (e.g., React) to trigger re-renders.
957
+ *
958
+ * @param listener - Function to call on state changes, receives new state
959
+ * @returns Unsubscribe function
960
+ *
961
+ * @example
962
+ * ```typescript
963
+ * const unsubscribe = engine.subscribe((state) => {
964
+ * console.log('State changed:', state);
965
+ * });
966
+ *
967
+ * // Later...
968
+ * unsubscribe();
969
+ * ```
970
+ */
971
+ subscribe(listener) {
972
+ this.listeners.add(listener);
973
+ return () => {
974
+ this.listeners.delete(listener);
975
+ };
976
+ }
977
+ /**
978
+ * Notify all subscribers of a state change
979
+ *
980
+ * This is called internally after any operation that modifies state.
981
+ * Framework adapters use this to trigger re-renders.
982
+ */
983
+ notify() {
984
+ const state = this.getState();
985
+ this.listeners.forEach((listener) => listener(state));
986
+ }
987
+ // ===== STATE ACCESS =====
988
+ /**
989
+ * Get the current timeline state
990
+ *
991
+ * @returns Current timeline state
992
+ */
993
+ getState() {
994
+ return getCurrentState(this.history);
995
+ }
996
+ // ===== ASSET OPERATIONS =====
997
+ /**
998
+ * Register an asset
999
+ *
1000
+ * @param asset - Asset to register
1001
+ * @returns Dispatch result
1002
+ */
1003
+ registerAsset(asset) {
1004
+ const result = legacyDispatch(
1005
+ this.history,
1006
+ (state) => registerAsset(state, asset)
1007
+ );
1008
+ if (result.accepted && result.history) {
1009
+ this.history = result.history;
1010
+ this.notify();
1011
+ }
1012
+ return result;
1013
+ }
1014
+ /**
1015
+ * Get an asset by ID
1016
+ *
1017
+ * @param assetId - Asset ID
1018
+ * @returns The asset, or undefined if not found
1019
+ */
1020
+ getAsset(assetId) {
1021
+ return getAsset(this.getState(), assetId);
1022
+ }
1023
+ // ===== CLIP OPERATIONS =====
1024
+ /**
1025
+ * Add a clip to a track
1026
+ *
1027
+ * @param trackId - ID of the track to add to
1028
+ * @param clip - Clip to add
1029
+ * @returns Dispatch result
1030
+ */
1031
+ addClip(trackId, clip) {
1032
+ const result = legacyDispatch(
1033
+ this.history,
1034
+ (state) => addClip(state, trackId, clip)
1035
+ );
1036
+ if (result.accepted && result.history) {
1037
+ this.history = result.history;
1038
+ this.notify();
1039
+ }
1040
+ return result;
1041
+ }
1042
+ /**
1043
+ * Remove a clip
1044
+ *
1045
+ * @param clipId - ID of the clip to remove
1046
+ * @returns Dispatch result
1047
+ */
1048
+ removeClip(clipId) {
1049
+ const result = legacyDispatch(
1050
+ this.history,
1051
+ (state) => removeClip(state, clipId)
1052
+ );
1053
+ if (result.accepted && result.history) {
1054
+ this.history = result.history;
1055
+ this.notify();
1056
+ }
1057
+ return result;
1058
+ }
1059
+ /**
1060
+ * Move a clip to a new timeline position
1061
+ *
1062
+ * @param clipId - ID of the clip to move
1063
+ * @param newStart - New timeline start frame
1064
+ * @returns Dispatch result
1065
+ */
1066
+ moveClip(clipId, newStart) {
1067
+ const result = legacyDispatch(
1068
+ this.history,
1069
+ (state) => moveClip(state, clipId, newStart)
1070
+ );
1071
+ if (result.accepted && result.history) {
1072
+ this.history = result.history;
1073
+ this.notify();
1074
+ }
1075
+ return result;
1076
+ }
1077
+ /**
1078
+ * Resize a clip
1079
+ *
1080
+ * @param clipId - ID of the clip to resize
1081
+ * @param newStart - New timeline start frame
1082
+ * @param newEnd - New timeline end frame
1083
+ * @returns Dispatch result
1084
+ */
1085
+ resizeClip(clipId, newStart, newEnd) {
1086
+ const result = legacyDispatch(
1087
+ this.history,
1088
+ (state) => resizeClip(state, clipId, newStart, newEnd)
1089
+ );
1090
+ if (result.accepted && result.history) {
1091
+ this.history = result.history;
1092
+ this.notify();
1093
+ }
1094
+ return result;
1095
+ }
1096
+ /**
1097
+ * Trim a clip (change media bounds)
1098
+ *
1099
+ * @param clipId - ID of the clip to trim
1100
+ * @param newMediaIn - New media in frame
1101
+ * @param newMediaOut - New media out frame
1102
+ * @returns Dispatch result
1103
+ */
1104
+ trimClip(clipId, newMediaIn, newMediaOut) {
1105
+ const result = legacyDispatch(
1106
+ this.history,
1107
+ (state) => trimClip(state, clipId, newMediaIn, newMediaOut)
1108
+ );
1109
+ if (result.accepted && result.history) {
1110
+ this.history = result.history;
1111
+ this.notify();
1112
+ }
1113
+ return result;
1114
+ }
1115
+ /**
1116
+ * Move a clip to a different track
1117
+ *
1118
+ * @param clipId - ID of the clip to move
1119
+ * @param targetTrackId - ID of the target track
1120
+ * @returns Dispatch result
1121
+ */
1122
+ moveClipToTrack(clipId, targetTrackId) {
1123
+ const result = legacyDispatch(
1124
+ this.history,
1125
+ (state) => moveClipToTrack(state, clipId, targetTrackId)
1126
+ );
1127
+ if (result.accepted && result.history) {
1128
+ this.history = result.history;
1129
+ this.notify();
1130
+ }
1131
+ return result;
1132
+ }
1133
+ // ===== TRACK OPERATIONS =====
1134
+ /**
1135
+ * Add a track
1136
+ *
1137
+ * @param track - Track to add
1138
+ * @returns Dispatch result
1139
+ */
1140
+ addTrack(track) {
1141
+ const result = legacyDispatch(
1142
+ this.history,
1143
+ (state) => addTrack(state, track)
1144
+ );
1145
+ if (result.accepted && result.history) {
1146
+ this.history = result.history;
1147
+ this.notify();
1148
+ }
1149
+ return result;
1150
+ }
1151
+ /**
1152
+ * Remove a track
1153
+ *
1154
+ * @param trackId - ID of the track to remove
1155
+ * @returns Dispatch result
1156
+ */
1157
+ removeTrack(trackId) {
1158
+ const result = legacyDispatch(
1159
+ this.history,
1160
+ (state) => removeTrack(state, trackId)
1161
+ );
1162
+ if (result.accepted && result.history) {
1163
+ this.history = result.history;
1164
+ this.notify();
1165
+ }
1166
+ return result;
1167
+ }
1168
+ /**
1169
+ * Move a track to a new position
1170
+ *
1171
+ * @param trackId - ID of the track to move
1172
+ * @param newIndex - New index position
1173
+ * @returns Dispatch result
1174
+ */
1175
+ moveTrack(trackId, newIndex) {
1176
+ const result = legacyDispatch(
1177
+ this.history,
1178
+ (state) => moveTrack(state, trackId, newIndex)
1179
+ );
1180
+ if (result.accepted && result.history) {
1181
+ this.history = result.history;
1182
+ this.notify();
1183
+ }
1184
+ return result;
1185
+ }
1186
+ /**
1187
+ * Toggle track mute
1188
+ *
1189
+ * @param trackId - ID of the track
1190
+ * @returns Dispatch result
1191
+ */
1192
+ toggleTrackMute(trackId) {
1193
+ const result = legacyDispatch(
1194
+ this.history,
1195
+ (state) => toggleTrackMute(state, trackId)
1196
+ );
1197
+ if (result.accepted && result.history) {
1198
+ this.history = result.history;
1199
+ this.notify();
1200
+ }
1201
+ return result;
1202
+ }
1203
+ /**
1204
+ * Toggle track lock
1205
+ *
1206
+ * @param trackId - ID of the track
1207
+ * @returns Dispatch result
1208
+ */
1209
+ toggleTrackLock(trackId) {
1210
+ const result = legacyDispatch(
1211
+ this.history,
1212
+ (state) => toggleTrackLock(state, trackId)
1213
+ );
1214
+ if (result.accepted && result.history) {
1215
+ this.history = result.history;
1216
+ this.notify();
1217
+ }
1218
+ return result;
1219
+ }
1220
+ /**
1221
+ * Toggle track solo
1222
+ *
1223
+ * @param trackId - ID of the track
1224
+ * @returns Dispatch result
1225
+ */
1226
+ toggleTrackSolo(trackId) {
1227
+ const result = legacyDispatch(
1228
+ this.history,
1229
+ (state) => toggleTrackSolo(state, trackId)
1230
+ );
1231
+ if (result.accepted && result.history) {
1232
+ this.history = result.history;
1233
+ this.notify();
1234
+ }
1235
+ return result;
1236
+ }
1237
+ /**
1238
+ * Set track height
1239
+ *
1240
+ * @param trackId - ID of the track
1241
+ * @param height - New height in pixels
1242
+ * @returns Dispatch result
1243
+ */
1244
+ setTrackHeight(trackId, height) {
1245
+ const result = legacyDispatch(
1246
+ this.history,
1247
+ (state) => setTrackHeight(state, trackId, height)
1248
+ );
1249
+ if (result.accepted && result.history) {
1250
+ this.history = result.history;
1251
+ this.notify();
1252
+ }
1253
+ return result;
1254
+ }
1255
+ // ===== TIMELINE OPERATIONS =====
1256
+ /**
1257
+ * Set timeline duration
1258
+ *
1259
+ * @param duration - New duration in frames
1260
+ * @returns Dispatch result
1261
+ */
1262
+ setTimelineDuration(duration) {
1263
+ const result = legacyDispatch(
1264
+ this.history,
1265
+ (state) => setTimelineDuration(state, duration)
1266
+ );
1267
+ if (result.accepted && result.history) {
1268
+ this.history = result.history;
1269
+ this.notify();
1270
+ }
1271
+ return result;
1272
+ }
1273
+ /**
1274
+ * Set timeline name
1275
+ *
1276
+ * @param name - New timeline name
1277
+ * @returns Dispatch result
1278
+ */
1279
+ setTimelineName(name) {
1280
+ const result = legacyDispatch(
1281
+ this.history,
1282
+ (state) => setTimelineName(state, name)
1283
+ );
1284
+ if (result.accepted && result.history) {
1285
+ this.history = result.history;
1286
+ this.notify();
1287
+ }
1288
+ return result;
1289
+ }
1290
+ // ===== HISTORY OPERATIONS =====
1291
+ /**
1292
+ * Undo the last action
1293
+ *
1294
+ * @returns true if undo was performed
1295
+ */
1296
+ undo() {
1297
+ if (!this.canUndo()) {
1298
+ return false;
1299
+ }
1300
+ this.history = undo(this.history);
1301
+ this.notify();
1302
+ return true;
1303
+ }
1304
+ /**
1305
+ * Redo the last undone action
1306
+ *
1307
+ * @returns true if redo was performed
1308
+ */
1309
+ redo() {
1310
+ if (!this.canRedo()) {
1311
+ return false;
1312
+ }
1313
+ this.history = redo(this.history);
1314
+ this.notify();
1315
+ return true;
1316
+ }
1317
+ /**
1318
+ * Check if undo is available
1319
+ *
1320
+ * @returns true if undo is available
1321
+ */
1322
+ canUndo() {
1323
+ return canUndo(this.history);
1324
+ }
1325
+ /**
1326
+ * Check if redo is available
1327
+ *
1328
+ * @returns true if redo is available
1329
+ */
1330
+ canRedo() {
1331
+ return canRedo(this.history);
1332
+ }
1333
+ // ===== QUERY OPERATIONS =====
1334
+ /**
1335
+ * Find a clip by ID
1336
+ *
1337
+ * @param clipId - Clip ID
1338
+ * @returns The clip, or undefined if not found
1339
+ */
1340
+ findClipById(clipId) {
1341
+ return findClipById(this.getState(), clipId);
1342
+ }
1343
+ /**
1344
+ * Find a track by ID
1345
+ *
1346
+ * @param trackId - Track ID
1347
+ * @returns The track, or undefined if not found
1348
+ */
1349
+ findTrackById(trackId) {
1350
+ return findTrackById(this.getState(), trackId);
1351
+ }
1352
+ /**
1353
+ * Get all clips on a track
1354
+ *
1355
+ * @param trackId - Track ID
1356
+ * @returns Array of clips on the track
1357
+ */
1358
+ getClipsOnTrack(trackId) {
1359
+ return getClipsOnTrack(this.getState(), trackId);
1360
+ }
1361
+ /**
1362
+ * Get all clips at a specific frame
1363
+ *
1364
+ * @param frame - Frame to check
1365
+ * @returns Array of clips at that frame
1366
+ */
1367
+ getClipsAtFrame(f) {
1368
+ return getClipsAtFrame(this.getState(), f);
1369
+ }
1370
+ /**
1371
+ * Get all clips in a frame range
1372
+ *
1373
+ * @param start - Start frame
1374
+ * @param end - End frame
1375
+ * @returns Array of clips in the range
1376
+ */
1377
+ getClipsInRange(start, end) {
1378
+ return getClipsInRange(this.getState(), start, end);
1379
+ }
1380
+ /**
1381
+ * Get all clips in the timeline
1382
+ *
1383
+ * @returns Array of all clips
1384
+ */
1385
+ getAllClips() {
1386
+ return getAllClips(this.getState());
1387
+ }
1388
+ /**
1389
+ * Get all tracks in the timeline
1390
+ *
1391
+ * @returns Array of all tracks
1392
+ */
1393
+ getAllTracks() {
1394
+ return getAllTracks(this.getState());
1395
+ }
1396
+ // ===== RIPPLE OPERATIONS =====
1397
+ /**
1398
+ * Ripple delete - delete clip and shift subsequent clips left
1399
+ *
1400
+ * @param clipId - ID of the clip to delete
1401
+ * @returns Dispatch result
1402
+ */
1403
+ rippleDelete(clipId) {
1404
+ const result = legacyDispatch(
1405
+ this.history,
1406
+ (state) => rippleDelete(state, clipId)
1407
+ );
1408
+ if (result.accepted && result.history) {
1409
+ this.history = result.history;
1410
+ this.notify();
1411
+ }
1412
+ return result;
1413
+ }
1414
+ /**
1415
+ * Ripple trim - trim clip end and shift subsequent clips
1416
+ *
1417
+ * @param clipId - ID of the clip to trim
1418
+ * @param newEnd - New end frame for the clip
1419
+ * @returns Dispatch result
1420
+ */
1421
+ rippleTrim(clipId, newEnd) {
1422
+ const result = legacyDispatch(
1423
+ this.history,
1424
+ (state) => rippleTrim(state, clipId, newEnd)
1425
+ );
1426
+ if (result.accepted && result.history) {
1427
+ this.history = result.history;
1428
+ this.notify();
1429
+ }
1430
+ return result;
1431
+ }
1432
+ /**
1433
+ * Insert edit - insert clip and shift subsequent clips right
1434
+ *
1435
+ * @param trackId - ID of the track to insert into
1436
+ * @param clip - Clip to insert
1437
+ * @param atFrame - Frame to insert at
1438
+ * @returns Dispatch result
1439
+ */
1440
+ insertEdit(trackId, clip, atFrame) {
1441
+ const result = legacyDispatch(
1442
+ this.history,
1443
+ (state) => insertEdit(state, trackId, clip, atFrame)
1444
+ );
1445
+ if (result.accepted && result.history) {
1446
+ this.history = result.history;
1447
+ this.notify();
1448
+ }
1449
+ return result;
1450
+ }
1451
+ /**
1452
+ * Ripple move - move clip and shift surrounding clips to accommodate
1453
+ *
1454
+ * This moves a clip to a new position while maintaining timeline continuity:
1455
+ * - Closes the gap at the source position
1456
+ * - Makes space at the destination position
1457
+ * - All operations are atomic (single undo entry)
1458
+ *
1459
+ * @param clipId - ID of the clip to move
1460
+ * @param newStart - New start frame for the clip
1461
+ * @returns Dispatch result
1462
+ */
1463
+ rippleMove(clipId, newStart) {
1464
+ const result = legacyDispatch(
1465
+ this.history,
1466
+ (state) => rippleMove(state, clipId, newStart)
1467
+ );
1468
+ if (result.accepted && result.history) {
1469
+ this.history = result.history;
1470
+ this.notify();
1471
+ } else if (!result.accepted && result.errors?.[0]?.code === "OPERATION_ERROR") {
1472
+ throw new Error(result.errors[0].message);
1473
+ }
1474
+ return result;
1475
+ }
1476
+ /**
1477
+ * Insert move - move clip and shift destination clips right
1478
+ *
1479
+ * This moves a clip to a new position without closing the gap at source:
1480
+ * - Leaves gap at the source position
1481
+ * - Pushes all clips at destination right to make space
1482
+ * - All operations are atomic (single undo entry)
1483
+ *
1484
+ * @param clipId - ID of the clip to move
1485
+ * @param newStart - New start frame for the clip
1486
+ * @returns Dispatch result
1487
+ */
1488
+ insertMove(clipId, newStart) {
1489
+ const result = legacyDispatch(
1490
+ this.history,
1491
+ (state) => insertMove(state, clipId, newStart)
1492
+ );
1493
+ if (result.accepted && result.history) {
1494
+ this.history = result.history;
1495
+ this.notify();
1496
+ } else if (!result.accepted && result.errors?.[0]?.code === "OPERATION_ERROR") {
1497
+ throw new Error(result.errors[0].message);
1498
+ }
1499
+ return result;
1500
+ }
1501
+ // Phase 2: Marker and WorkArea operations are gated to Phase 2.
1502
+ // They are intentionally omitted here to keep Phase 0 clean.
1503
+ };
1504
+
1505
+ // src/validation/invariants.ts
1506
+ function checkInvariants(state) {
1507
+ const violations = [];
1508
+ for (const track of state.timeline.tracks) {
1509
+ checkTrack(state, track, violations);
1510
+ }
1511
+ return violations;
1512
+ }
1513
+ function checkTrack(state, track, violations) {
1514
+ const clips = track.clips;
1515
+ for (let i = 1; i < clips.length; i++) {
1516
+ const prev = clips[i - 1];
1517
+ const curr = clips[i];
1518
+ if (prev.timelineStart > curr.timelineStart) {
1519
+ violations.push({
1520
+ type: "TRACK_NOT_SORTED",
1521
+ entityId: track.id,
1522
+ message: `Track '${track.id}': clip '${curr.id}' (start=${curr.timelineStart}) appears after clip '${prev.id}' (start=${prev.timelineStart}) \u2014 not sorted.`
1523
+ });
1524
+ }
1525
+ }
1526
+ for (let i = 0; i < clips.length; i++) {
1527
+ for (let j = i + 1; j < clips.length; j++) {
1528
+ const a = clips[i];
1529
+ const b = clips[j];
1530
+ if (clipsOverlap(a, b)) {
1531
+ violations.push({
1532
+ type: "OVERLAP",
1533
+ entityId: a.id,
1534
+ message: `Track '${track.id}': clips '${a.id}' [${a.timelineStart}-${a.timelineEnd}) and '${b.id}' [${b.timelineStart}-${b.timelineEnd}) overlap.`
1535
+ });
1536
+ }
1537
+ }
1538
+ }
1539
+ for (const clip of clips) {
1540
+ checkClip(state, track, clip, violations);
1541
+ }
1542
+ }
1543
+ function checkClip(state, track, clip, violations) {
1544
+ const asset = state.assetRegistry.get(clip.assetId);
1545
+ if (!asset) {
1546
+ violations.push({
1547
+ type: "ASSET_MISSING",
1548
+ entityId: clip.id,
1549
+ message: `Clip '${clip.id}' references asset '${clip.assetId}' which is not in the registry.`
1550
+ });
1551
+ return;
1552
+ }
1553
+ if (asset.mediaType !== track.type) {
1554
+ violations.push({
1555
+ type: "TRACK_TYPE_MISMATCH",
1556
+ entityId: clip.id,
1557
+ message: `Clip '${clip.id}' has asset mediaType '${asset.mediaType}' but is on a '${track.type}' track '${track.id}'.`
1558
+ });
1559
+ }
1560
+ if (clip.mediaIn < 0) {
1561
+ violations.push({
1562
+ type: "MEDIA_BOUNDS_INVALID",
1563
+ entityId: clip.id,
1564
+ message: `Clip '${clip.id}': mediaIn (${clip.mediaIn}) must be >= 0.`
1565
+ });
1566
+ }
1567
+ if (clip.mediaOut > asset.intrinsicDuration) {
1568
+ violations.push({
1569
+ type: "MEDIA_BOUNDS_INVALID",
1570
+ entityId: clip.id,
1571
+ message: `Clip '${clip.id}': mediaOut (${clip.mediaOut}) exceeds asset intrinsicDuration (${asset.intrinsicDuration}).`
1572
+ });
1573
+ }
1574
+ const mediaDuration = clip.mediaOut - clip.mediaIn;
1575
+ const timelineDuration = clip.timelineEnd - clip.timelineStart;
1576
+ const expectedMediaDuration = timelineDuration / clip.speed;
1577
+ if (Math.abs(mediaDuration - expectedMediaDuration) > 0.5) {
1578
+ violations.push({
1579
+ type: "DURATION_MISMATCH",
1580
+ entityId: clip.id,
1581
+ message: `Clip '${clip.id}': mediaDuration (${mediaDuration}) \u2260 timelineDuration/speed (${expectedMediaDuration.toFixed(2)}).`
1582
+ });
1583
+ }
1584
+ if (clip.timelineEnd > state.timeline.duration) {
1585
+ violations.push({
1586
+ type: "CLIP_BEYOND_TIMELINE",
1587
+ entityId: clip.id,
1588
+ message: `Clip '${clip.id}': timelineEnd (${clip.timelineEnd}) exceeds timeline duration (${state.timeline.duration}).`
1589
+ });
1590
+ }
1591
+ if (clip.speed <= 0) {
1592
+ violations.push({
1593
+ type: "SPEED_INVALID",
1594
+ entityId: clip.id,
1595
+ message: `Clip '${clip.id}': speed (${clip.speed}) must be > 0.`
1596
+ });
1597
+ }
1598
+ }
1599
+
1600
+ // src/engine/apply.ts
1601
+ function applyOperation2(state, op) {
1602
+ switch (op.type) {
1603
+ // — Clip operations ——————————————————————————————————————————————————
1604
+ case "INSERT_CLIP": {
1605
+ return updateTrack2(
1606
+ state,
1607
+ op.trackId,
1608
+ (track) => sortTrackClips({ ...track, clips: [...track.clips, op.clip] })
1609
+ );
1610
+ }
1611
+ case "DELETE_CLIP": {
1612
+ return updateTrackOfClip(state, op.clipId, (track) => ({
1613
+ ...track,
1614
+ clips: track.clips.filter((c) => c.id !== op.clipId)
1615
+ }));
1616
+ }
1617
+ case "MOVE_CLIP": {
1618
+ const targetTrackId = op.targetTrackId;
1619
+ let foundClip;
1620
+ for (const track of state.timeline.tracks) {
1621
+ const c = track.clips.find((c2) => c2.id === op.clipId);
1622
+ if (c) {
1623
+ foundClip = c;
1624
+ break;
1625
+ }
1626
+ }
1627
+ if (!foundClip) return state;
1628
+ const delta = op.newTimelineStart - foundClip.timelineStart;
1629
+ const movedClip = {
1630
+ ...foundClip,
1631
+ trackId: targetTrackId ?? foundClip.trackId,
1632
+ timelineStart: op.newTimelineStart,
1633
+ timelineEnd: foundClip.timelineEnd + delta
1634
+ };
1635
+ const effectiveTargetTrackId = targetTrackId ?? foundClip.trackId;
1636
+ const isCrossTrack = effectiveTargetTrackId !== foundClip.trackId;
1637
+ if (!isCrossTrack) {
1638
+ return updateClip2(state, op.clipId, () => movedClip);
1639
+ }
1640
+ const newTracks = state.timeline.tracks.map((track) => {
1641
+ if (track.id === foundClip.trackId) {
1642
+ return { ...track, clips: track.clips.filter((c) => c.id !== op.clipId) };
1643
+ }
1644
+ if (track.id === effectiveTargetTrackId) {
1645
+ return sortTrackClips({ ...track, clips: [...track.clips, movedClip] });
1646
+ }
1647
+ return track;
1648
+ });
1649
+ return { ...state, timeline: { ...state.timeline, tracks: newTracks } };
1650
+ }
1651
+ case "RESIZE_CLIP": {
1652
+ return updateClip2(state, op.clipId, (clip) => {
1653
+ if (op.edge === "start") {
1654
+ const delta = op.newFrame - clip.timelineStart;
1655
+ return {
1656
+ ...clip,
1657
+ timelineStart: op.newFrame,
1658
+ mediaIn: clip.mediaIn + delta
1659
+ };
1660
+ } else {
1661
+ const delta = op.newFrame - clip.timelineEnd;
1662
+ return {
1663
+ ...clip,
1664
+ timelineEnd: op.newFrame,
1665
+ mediaOut: clip.mediaOut + delta
1666
+ };
1667
+ }
1668
+ });
1669
+ }
1670
+ case "SLICE_CLIP": {
1671
+ return state;
1672
+ }
1673
+ case "SET_MEDIA_BOUNDS": {
1674
+ return updateClip2(state, op.clipId, (clip) => ({
1675
+ ...clip,
1676
+ mediaIn: op.mediaIn,
1677
+ mediaOut: op.mediaOut
1678
+ }));
1679
+ }
1680
+ case "SET_CLIP_ENABLED": {
1681
+ return updateClip2(state, op.clipId, (clip) => ({ ...clip, enabled: op.enabled }));
1682
+ }
1683
+ case "SET_CLIP_REVERSED": {
1684
+ return updateClip2(state, op.clipId, (clip) => ({ ...clip, reversed: op.reversed }));
1685
+ }
1686
+ case "SET_CLIP_SPEED": {
1687
+ return updateClip2(state, op.clipId, (clip) => ({ ...clip, speed: op.speed }));
1688
+ }
1689
+ case "SET_CLIP_COLOR": {
1690
+ return updateClip2(state, op.clipId, (clip) => ({ ...clip, color: op.color }));
1691
+ }
1692
+ case "SET_CLIP_NAME": {
1693
+ return updateClip2(state, op.clipId, (clip) => ({ ...clip, name: op.name }));
1694
+ }
1695
+ // — Track operations ——————————————————————————————————————————————————
1696
+ case "ADD_TRACK": {
1697
+ return {
1698
+ ...state,
1699
+ timeline: {
1700
+ ...state.timeline,
1701
+ tracks: [...state.timeline.tracks, op.track]
1702
+ }
1703
+ };
1704
+ }
1705
+ case "DELETE_TRACK": {
1706
+ return {
1707
+ ...state,
1708
+ timeline: {
1709
+ ...state.timeline,
1710
+ tracks: state.timeline.tracks.filter((t) => t.id !== op.trackId)
1711
+ }
1712
+ };
1713
+ }
1714
+ case "REORDER_TRACK": {
1715
+ const tracks = [...state.timeline.tracks];
1716
+ const idx = tracks.findIndex((t) => t.id === op.trackId);
1717
+ if (idx === -1) return state;
1718
+ const [track] = tracks.splice(idx, 1);
1719
+ if (!track) return state;
1720
+ tracks.splice(op.newIndex, 0, track);
1721
+ return { ...state, timeline: { ...state.timeline, tracks } };
1722
+ }
1723
+ case "SET_TRACK_HEIGHT": {
1724
+ return updateTrack2(state, op.trackId, (t) => ({ ...t, height: op.height }));
1725
+ }
1726
+ case "SET_TRACK_NAME": {
1727
+ return updateTrack2(state, op.trackId, (t) => ({ ...t, name: op.name }));
1728
+ }
1729
+ // — Asset operations ——————————————————————————————————————————————————
1730
+ case "REGISTER_ASSET": {
1731
+ const next = new Map(state.assetRegistry);
1732
+ next.set(op.asset.id, op.asset);
1733
+ return { ...state, assetRegistry: next };
1734
+ }
1735
+ case "UNREGISTER_ASSET": {
1736
+ const next = new Map(state.assetRegistry);
1737
+ next.delete(op.assetId);
1738
+ return { ...state, assetRegistry: next };
1739
+ }
1740
+ case "SET_ASSET_STATUS": {
1741
+ const asset = state.assetRegistry.get(op.assetId);
1742
+ if (!asset) return state;
1743
+ const next = new Map(state.assetRegistry);
1744
+ next.set(op.assetId, { ...asset, status: op.status });
1745
+ return { ...state, assetRegistry: next };
1746
+ }
1747
+ // — Timeline operations ———————————————————————————————————————————————
1748
+ case "RENAME_TIMELINE": {
1749
+ return { ...state, timeline: { ...state.timeline, name: op.name } };
1750
+ }
1751
+ case "SET_TIMELINE_DURATION": {
1752
+ return { ...state, timeline: { ...state.timeline, duration: op.duration } };
1753
+ }
1754
+ case "SET_TIMELINE_START_TC": {
1755
+ return { ...state, timeline: { ...state.timeline, startTimecode: op.startTimecode } };
1756
+ }
1757
+ case "SET_SEQUENCE_SETTINGS": {
1758
+ return {
1759
+ ...state,
1760
+ timeline: {
1761
+ ...state.timeline,
1762
+ sequenceSettings: { ...state.timeline.sequenceSettings, ...op.settings }
1763
+ }
1764
+ };
1765
+ }
1766
+ }
1767
+ }
1768
+ function updateTrack2(state, trackId, fn) {
1769
+ return {
1770
+ ...state,
1771
+ timeline: {
1772
+ ...state.timeline,
1773
+ tracks: state.timeline.tracks.map((t) => t.id === trackId ? fn(t) : t)
1774
+ }
1775
+ };
1776
+ }
1777
+ function updateTrackOfClip(state, clipId, fn) {
1778
+ return {
1779
+ ...state,
1780
+ timeline: {
1781
+ ...state.timeline,
1782
+ tracks: state.timeline.tracks.map(
1783
+ (t) => t.clips.some((c) => c.id === clipId) ? fn(t) : t
1784
+ )
1785
+ }
1786
+ };
1787
+ }
1788
+ function updateClip2(state, clipId, fn) {
1789
+ return {
1790
+ ...state,
1791
+ timeline: {
1792
+ ...state.timeline,
1793
+ tracks: state.timeline.tracks.map((track) => {
1794
+ if (!track.clips.some((c) => c.id === clipId)) return track;
1795
+ const updatedTrack = {
1796
+ ...track,
1797
+ clips: track.clips.map((c) => c.id === clipId ? fn(c) : c)
1798
+ };
1799
+ return sortTrackClips(updatedTrack);
1800
+ })
1801
+ }
1802
+ };
1803
+ }
1804
+
1805
+ // src/validation/validators.ts
1806
+ function validateOperation(state, op) {
1807
+ switch (op.type) {
1808
+ case "MOVE_CLIP":
1809
+ return validateMoveClip(state, op);
1810
+ case "RESIZE_CLIP":
1811
+ return validateResizeClip(state, op);
1812
+ case "SLICE_CLIP":
1813
+ return validateSliceClip(state, op);
1814
+ case "DELETE_CLIP":
1815
+ return validateDeleteClip(state, op);
1816
+ case "INSERT_CLIP":
1817
+ return validateInsertClip(state, op);
1818
+ case "SET_MEDIA_BOUNDS":
1819
+ return validateSetMediaBounds(state, op);
1820
+ case "SET_CLIP_SPEED":
1821
+ return validateSetClipSpeed(state, op);
1822
+ case "ADD_TRACK":
1823
+ return validateAddTrack(state, op);
1824
+ case "DELETE_TRACK":
1825
+ return validateDeleteTrack(state, op);
1826
+ case "UNREGISTER_ASSET":
1827
+ return validateUnregisterAsset(state, op);
1828
+ // All other ops are always valid at the primitive level
1829
+ default:
1830
+ return null;
1831
+ }
1832
+ }
1833
+ function validateMoveClip(state, op) {
1834
+ const clip = findClip(state, op.clipId);
1835
+ if (!clip) return { reason: "ASSET_MISSING", message: `Clip '${op.clipId}' not found.` };
1836
+ const targetTrackId = op.targetTrackId ?? clip.trackId;
1837
+ const track = state.timeline.tracks.find((t) => t.id === targetTrackId);
1838
+ if (!track) return { reason: "OUT_OF_BOUNDS", message: `Track '${targetTrackId}' not found.` };
1839
+ if (track.locked) return { reason: "LOCKED_TRACK", message: `Track '${targetTrackId}' is locked.` };
1840
+ const duration = clip.timelineEnd - clip.timelineStart;
1841
+ const newEnd = op.newTimelineStart + duration;
1842
+ if (op.newTimelineStart < 0 || newEnd > state.timeline.duration) {
1843
+ return { reason: "OUT_OF_BOUNDS", message: `MOVE_CLIP would place clip '${op.clipId}' outside timeline bounds.` };
1844
+ }
1845
+ for (const existing of track.clips) {
1846
+ if (existing.id === op.clipId) continue;
1847
+ const overlaps = op.newTimelineStart < existing.timelineEnd && newEnd > existing.timelineStart;
1848
+ if (overlaps) {
1849
+ return { reason: "OVERLAP", message: `Clip '${op.clipId}' would overlap '${existing.id}' on track '${targetTrackId}'.` };
1850
+ }
1851
+ }
1852
+ return null;
1853
+ }
1854
+ function validateResizeClip(state, op) {
1855
+ const clip = findClip(state, op.clipId);
1856
+ if (!clip) return { reason: "ASSET_MISSING", message: `Clip '${op.clipId}' not found.` };
1857
+ if (op.edge === "start" && op.newFrame >= clip.timelineEnd) {
1858
+ return { reason: "OUT_OF_BOUNDS", message: `RESIZE_CLIP start edge must be < timelineEnd.` };
1859
+ }
1860
+ if (op.edge === "end" && op.newFrame <= clip.timelineStart) {
1861
+ return { reason: "OUT_OF_BOUNDS", message: `RESIZE_CLIP end edge must be > timelineStart.` };
1862
+ }
1863
+ return null;
1864
+ }
1865
+ function validateSliceClip(state, op) {
1866
+ const clip = findClip(state, op.clipId);
1867
+ if (!clip) return { reason: "ASSET_MISSING", message: `Clip '${op.clipId}' not found.` };
1868
+ if (op.atFrame <= clip.timelineStart || op.atFrame >= clip.timelineEnd) {
1869
+ return { reason: "OUT_OF_BOUNDS", message: `SLICE_CLIP atFrame must be strictly inside the clip bounds.` };
1870
+ }
1871
+ return null;
1872
+ }
1873
+ function validateDeleteClip(state, op) {
1874
+ const clip = findClip(state, op.clipId);
1875
+ if (!clip) return { reason: "ASSET_MISSING", message: `Clip '${op.clipId}' not found.` };
1876
+ const track = state.timeline.tracks.find((t) => t.id === clip.trackId);
1877
+ if (track?.locked) return { reason: "LOCKED_TRACK", message: `Track '${clip.trackId}' is locked.` };
1878
+ return null;
1879
+ }
1880
+ function validateInsertClip(state, op) {
1881
+ const track = state.timeline.tracks.find((t) => t.id === op.trackId);
1882
+ if (!track) return { reason: "OUT_OF_BOUNDS", message: `Track '${op.trackId}' not found.` };
1883
+ if (track.locked) return { reason: "LOCKED_TRACK", message: `Track '${op.trackId}' is locked.` };
1884
+ const asset = state.assetRegistry.get(op.clip.assetId);
1885
+ if (!asset) return { reason: "ASSET_MISSING", message: `Asset '${op.clip.assetId}' not in registry.` };
1886
+ if (asset.mediaType !== track.type) return { reason: "TYPE_MISMATCH", message: `Asset mediaType '${asset.mediaType}' \u2260 track type '${track.type}'.` };
1887
+ for (const existing of track.clips) {
1888
+ const overlaps = op.clip.timelineStart < existing.timelineEnd && op.clip.timelineEnd > existing.timelineStart;
1889
+ if (overlaps) {
1890
+ return { reason: "OVERLAP", message: `INSERT_CLIP would overlap '${existing.id}'.` };
1891
+ }
1892
+ }
1893
+ return null;
1894
+ }
1895
+ function validateSetMediaBounds(state, op) {
1896
+ const clip = findClip(state, op.clipId);
1897
+ if (!clip) return { reason: "ASSET_MISSING", message: `Clip '${op.clipId}' not found.` };
1898
+ const asset = state.assetRegistry.get(clip.assetId);
1899
+ if (!asset) return { reason: "ASSET_MISSING", message: `Asset '${clip.assetId}' not found.` };
1900
+ if (op.mediaIn < 0) return { reason: "MEDIA_BOUNDS_INVALID", message: `mediaIn must be >= 0.` };
1901
+ if (op.mediaOut > asset.intrinsicDuration) {
1902
+ return { reason: "MEDIA_BOUNDS_INVALID", message: `mediaOut (${op.mediaOut}) exceeds asset intrinsicDuration (${asset.intrinsicDuration}).` };
1903
+ }
1904
+ return null;
1905
+ }
1906
+ function validateSetClipSpeed(_state, op) {
1907
+ if (op.speed <= 0) return { reason: "SPEED_INVALID", message: `speed must be > 0, got ${op.speed}.` };
1908
+ return null;
1909
+ }
1910
+ function validateAddTrack(state, op) {
1911
+ if (state.timeline.tracks.some((t) => t.id === op.track.id)) {
1912
+ return { reason: "OVERLAP", message: `Track '${op.track.id}' already exists.` };
1913
+ }
1914
+ return null;
1915
+ }
1916
+ function validateDeleteTrack(state, op) {
1917
+ const track = state.timeline.tracks.find((t) => t.id === op.trackId);
1918
+ if (!track) return { reason: "OUT_OF_BOUNDS", message: `Track '${op.trackId}' not found.` };
1919
+ if (track.clips.length > 0) return { reason: "TRACK_NOT_EMPTY", message: `Cannot delete track '${op.trackId}': it has ${track.clips.length} clips. Delete all clips first.` };
1920
+ return null;
1921
+ }
1922
+ function validateUnregisterAsset(state, op) {
1923
+ for (const track of state.timeline.tracks) {
1924
+ for (const clip of track.clips) {
1925
+ if (clip.assetId === op.assetId) {
1926
+ return { reason: "ASSET_IN_USE", message: `Asset '${op.assetId}' is referenced by clip '${clip.id}'.` };
1927
+ }
1928
+ }
1929
+ }
1930
+ return null;
1931
+ }
1932
+ function findClip(state, clipId) {
1933
+ for (const track of state.timeline.tracks) {
1934
+ const clip = track.clips.find((c) => c.id === clipId);
1935
+ if (clip) return clip;
1936
+ }
1937
+ return void 0;
1938
+ }
1939
+
1940
+ // src/engine/dispatcher.ts
1941
+ function dispatch(state, transaction) {
1942
+ for (const op of transaction.operations) {
1943
+ const rejection = validateOperation(state, op);
1944
+ if (rejection) {
1945
+ return {
1946
+ accepted: false,
1947
+ reason: rejection.reason,
1948
+ message: rejection.message
1949
+ };
1950
+ }
1951
+ }
1952
+ let proposedState = state;
1953
+ for (const op of transaction.operations) {
1954
+ proposedState = applyOperation2(proposedState, op);
1955
+ }
1956
+ const violations = checkInvariants(proposedState);
1957
+ if (violations.length > 0) {
1958
+ return {
1959
+ accepted: false,
1960
+ reason: "INVARIANT_VIOLATED",
1961
+ message: violations.map((v) => v.message).join("; ")
1962
+ };
1963
+ }
1964
+ const nextState = {
1965
+ ...proposedState,
1966
+ timeline: {
1967
+ ...proposedState.timeline,
1968
+ version: state.timeline.version + 1
1969
+ }
1970
+ };
1971
+ return { accepted: true, nextState };
1972
+ }
1973
+
1974
+ // src/snap-index.ts
1975
+ var PRIORITIES = {
1976
+ Marker: 100,
1977
+ InPoint: 90,
1978
+ OutPoint: 90,
1979
+ ClipStart: 80,
1980
+ ClipEnd: 80,
1981
+ Playhead: 70,
1982
+ BeatGrid: 50
1983
+ };
1984
+ function buildSnapIndex(state, playheadFrame, enabled = true) {
1985
+ const points = [];
1986
+ for (const track of state.timeline.tracks) {
1987
+ for (const clip of track.clips) {
1988
+ points.push({
1989
+ frame: clip.timelineStart,
1990
+ type: "ClipStart",
1991
+ priority: PRIORITIES.ClipStart,
1992
+ trackId: track.id,
1993
+ sourceId: clip.id
1994
+ });
1995
+ points.push({
1996
+ frame: clip.timelineEnd,
1997
+ type: "ClipEnd",
1998
+ priority: PRIORITIES.ClipEnd,
1999
+ trackId: track.id,
2000
+ sourceId: clip.id
2001
+ });
2002
+ }
2003
+ }
2004
+ points.push({
2005
+ frame: playheadFrame,
2006
+ type: "Playhead",
2007
+ priority: PRIORITIES.Playhead,
2008
+ trackId: null,
2009
+ sourceId: "__playhead__"
2010
+ });
2011
+ points.sort((a, b) => a.frame - b.frame);
2012
+ return { points, builtAt: Date.now(), enabled };
2013
+ }
2014
+ function nearest(index, frame2, radiusFrames, exclude, allowedTypes) {
2015
+ if (!index.enabled) return null;
2016
+ const excludeSet = exclude ? new Set(exclude) : null;
2017
+ let best = null;
2018
+ let bestDist = Infinity;
2019
+ for (const point of index.points) {
2020
+ if (excludeSet && excludeSet.has(point.sourceId)) continue;
2021
+ if (allowedTypes && !allowedTypes.includes(point.type)) continue;
2022
+ const dist = Math.abs(point.frame - frame2);
2023
+ if (dist > radiusFrames) continue;
2024
+ if (dist < bestDist || dist === bestDist && best !== null && point.priority > best.priority) {
2025
+ best = point;
2026
+ bestDist = dist;
2027
+ }
2028
+ }
2029
+ return best;
2030
+ }
2031
+ function toggleSnap(index, enabled) {
2032
+ return { ...index, enabled };
2033
+ }
2034
+
2035
+ // src/tools/types.ts
2036
+ function toToolId(s) {
2037
+ return s;
2038
+ }
2039
+
2040
+ // src/tools/registry.ts
2041
+ function createRegistry(tools, defaultId) {
2042
+ const map = /* @__PURE__ */ new Map();
2043
+ for (const tool of tools) {
2044
+ map.set(tool.id, tool);
2045
+ }
2046
+ if (!map.has(defaultId)) {
2047
+ throw new Error(
2048
+ `createRegistry: defaultId "${defaultId}" not found in tools. Available: [${[...map.keys()].join(", ")}]`
2049
+ );
2050
+ }
2051
+ return { tools: map, activeToolId: defaultId };
2052
+ }
2053
+ function activateTool(registry, id) {
2054
+ getActiveTool(registry).onCancel();
2055
+ if (!registry.tools.has(id)) {
2056
+ throw new Error(
2057
+ `activateTool: unknown toolId "${id}". Registered: [${[...registry.tools.keys()].join(", ")}]`
2058
+ );
2059
+ }
2060
+ return { ...registry, activeToolId: id };
2061
+ }
2062
+ function getActiveTool(registry) {
2063
+ const tool = registry.tools.get(registry.activeToolId);
2064
+ if (!tool) {
2065
+ throw new Error(
2066
+ `getActiveTool: activeToolId "${registry.activeToolId}" is not registered. Registry is corrupt.`
2067
+ );
2068
+ }
2069
+ return tool;
2070
+ }
2071
+ function registerTool(registry, tool) {
2072
+ const next = new Map(registry.tools);
2073
+ next.set(tool.id, tool);
2074
+ return { ...registry, tools: next };
2075
+ }
2076
+ var NoOpTool = {
2077
+ id: toToolId("noop"),
2078
+ shortcutKey: "",
2079
+ getCursor(_ctx) {
2080
+ return "default";
2081
+ },
2082
+ getSnapCandidateTypes() {
2083
+ return [];
2084
+ },
2085
+ onPointerDown(_evt, _ctx) {
2086
+ },
2087
+ onPointerMove(_evt, _ctx) {
2088
+ return null;
2089
+ },
2090
+ onPointerUp(_evt, _ctx) {
2091
+ return null;
2092
+ },
2093
+ onKeyDown(_evt, _ctx) {
2094
+ return null;
2095
+ },
2096
+ onKeyUp(_evt, _ctx) {
2097
+ },
2098
+ onCancel() {
2099
+ }
2100
+ };
2101
+
2102
+ // src/tools/provisional.ts
2103
+ function createProvisionalManager() {
2104
+ return { current: null };
2105
+ }
2106
+ function setProvisional(_manager, state) {
2107
+ return { current: state };
2108
+ }
2109
+ function clearProvisional(_manager) {
2110
+ return { current: null };
2111
+ }
2112
+ function resolveClip(clipId, state, manager) {
2113
+ if (manager.current !== null) {
2114
+ const ghost = manager.current.clips.find((c) => c.id === clipId);
2115
+ if (ghost) return ghost;
2116
+ }
2117
+ for (const track of state.timeline.tracks) {
2118
+ const clip = track.clips.find((c) => c.id === clipId);
2119
+ if (clip) return clip;
2120
+ }
2121
+ return void 0;
2122
+ }
2123
+
2124
+ export {
2125
+ createTimeline,
2126
+ createTrack,
2127
+ sortTrackClips,
2128
+ createClip,
2129
+ getClipDuration,
2130
+ getClipMediaDuration,
2131
+ clipContainsFrame,
2132
+ clipsOverlap,
2133
+ createAsset,
2134
+ createTimelineState,
2135
+ toFrame,
2136
+ frame,
2137
+ FrameRates,
2138
+ frameRate,
2139
+ toTimecode,
2140
+ isValidFrame,
2141
+ isDropFrame,
2142
+ framesToSeconds,
2143
+ secondsToFrames,
2144
+ framesToTimecode,
2145
+ framesToMinutesSeconds,
2146
+ clampFrame,
2147
+ addFrames,
2148
+ subtractFrames,
2149
+ frameDuration,
2150
+ createHistory,
2151
+ pushHistory,
2152
+ undo,
2153
+ redo,
2154
+ canUndo,
2155
+ canRedo,
2156
+ getCurrentState,
2157
+ findClipById,
2158
+ findTrackById,
2159
+ getClipsOnTrack,
2160
+ getClipsAtFrame,
2161
+ getClipsInRange,
2162
+ getAllClips,
2163
+ getAllTracks,
2164
+ findTrackIndex,
2165
+ validResult,
2166
+ invalidResult,
2167
+ invalidResults,
2168
+ combineResults,
2169
+ registerAsset,
2170
+ getAsset,
2171
+ hasAsset,
2172
+ getAllAssets,
2173
+ unregisterAsset,
2174
+ validateClip,
2175
+ validateTrack,
2176
+ validateTimeline,
2177
+ validateNoOverlap,
2178
+ addClip,
2179
+ removeClip,
2180
+ moveClip,
2181
+ resizeClip,
2182
+ trimClip,
2183
+ updateClip,
2184
+ moveClipToTrack,
2185
+ addTrack,
2186
+ removeTrack,
2187
+ moveTrack,
2188
+ updateTrack,
2189
+ toggleTrackMute,
2190
+ toggleTrackLock,
2191
+ setTimelineDuration,
2192
+ setTimelineName,
2193
+ rippleDelete,
2194
+ rippleTrim,
2195
+ insertEdit,
2196
+ rippleMove,
2197
+ insertMove,
2198
+ TimelineEngine,
2199
+ checkInvariants,
2200
+ dispatch,
2201
+ buildSnapIndex,
2202
+ nearest,
2203
+ toggleSnap,
2204
+ toToolId,
2205
+ createRegistry,
2206
+ activateTool,
2207
+ getActiveTool,
2208
+ registerTool,
2209
+ NoOpTool,
2210
+ createProvisionalManager,
2211
+ setProvisional,
2212
+ clearProvisional,
2213
+ resolveClip
2214
+ };