@morshoto/framekit 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/README.md +67 -0
  2. package/bin/framekit.mjs +26 -0
  3. package/dist-package/adapters/final-cut/typescript/src/analyzers.js +116 -0
  4. package/dist-package/adapters/final-cut/typescript/src/assets.js +112 -0
  5. package/dist-package/adapters/final-cut/typescript/src/connection.js +379 -0
  6. package/dist-package/adapters/final-cut/typescript/src/disposable-native.js +282 -0
  7. package/dist-package/adapters/final-cut/typescript/src/export.js +382 -0
  8. package/dist-package/adapters/final-cut/typescript/src/fcpxml.js +503 -0
  9. package/dist-package/adapters/final-cut/typescript/src/index.js +11 -0
  10. package/dist-package/adapters/final-cut/typescript/src/live.js +415 -0
  11. package/dist-package/adapters/final-cut/typescript/src/native-operation.js +18 -0
  12. package/dist-package/adapters/final-cut/typescript/src/native.js +3134 -0
  13. package/dist-package/adapters/final-cut/typescript/src/publisher.js +102 -0
  14. package/dist-package/adapters/final-cut/typescript/src/session.js +171 -0
  15. package/dist-package/apps/cli/src/main.js +130 -0
  16. package/dist-package/apps/mcp-server/src/main.js +146 -0
  17. package/dist-package/apps/mcp-server/src/server.js +617 -0
  18. package/dist-package/packages/runtime/src/capabilities.js +24 -0
  19. package/dist-package/packages/runtime/src/context/context-engine.js +142 -0
  20. package/dist-package/packages/runtime/src/diff/diff.js +145 -0
  21. package/dist-package/packages/runtime/src/domain/types.js +1 -0
  22. package/dist-package/packages/runtime/src/editing/intent.js +83 -0
  23. package/dist-package/packages/runtime/src/index.js +8 -0
  24. package/dist-package/packages/runtime/src/runtime.js +890 -0
  25. package/dist-package/packages/runtime/src/snapshot-digest.js +24 -0
  26. package/dist-package/packages/runtime/src/speech/filler-removal.js +87 -0
  27. package/dist-package/packages/runtime/src/verification/verification.js +113 -0
  28. package/dist-package/packages/testkit/src/fixture-analyzers.js +39 -0
  29. package/dist-package/packages/testkit/src/in-memory-editor.js +520 -0
  30. package/dist-package/packages/testkit/src/index.js +2 -0
  31. package/package.json +64 -0
@@ -0,0 +1,382 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { execFile as execFileCallback } from "node:child_process";
3
+ import { access, constants, rename, stat, unlink } from "node:fs/promises";
4
+ import { basename, dirname, extname, join, resolve } from "node:path";
5
+ import { promisify } from "node:util";
6
+ const execFile = promisify(execFileCallback);
7
+ export const FINAL_CUT_EXPORT_PRESETS = {
8
+ master: { menuItem: "Export File" },
9
+ web: { menuItem: "Web Hosting" },
10
+ };
11
+ export async function isFinalCutVideoProbeAvailable() {
12
+ try {
13
+ await execFile("ffprobe", ["-version"], { maxBuffer: 1_000_000 });
14
+ return true;
15
+ }
16
+ catch {
17
+ return false;
18
+ }
19
+ }
20
+ /** Exports the active Final Cut timeline and verifies the resulting media file. */
21
+ export class FinalCutVideoExporter {
22
+ enabled;
23
+ executor;
24
+ preflight;
25
+ probe;
26
+ probeAvailability;
27
+ probeAvailable;
28
+ waitMs;
29
+ pollMs;
30
+ stablePolls;
31
+ now;
32
+ sleep;
33
+ nativeOperationLease;
34
+ suspendLiveConnection;
35
+ resumeLiveConnection;
36
+ constructor(options = {}) {
37
+ this.enabled = options.enabled ?? false;
38
+ this.executor = options.executor ?? runAppleScript;
39
+ this.preflight = options.preflight;
40
+ this.probe = options.probe ?? probeWithFfprobe;
41
+ this.probeAvailability = options.probeAvailability ?? (options.probe ? undefined : isFinalCutVideoProbeAvailable);
42
+ this.probeAvailable = options.probeAvailable ?? true;
43
+ this.waitMs = options.waitMs ?? 120_000;
44
+ this.pollMs = options.pollMs ?? 250;
45
+ this.stablePolls = Math.max(1, Math.floor(options.stablePolls ?? 2));
46
+ this.now = options.now ?? Date.now;
47
+ this.sleep = options.sleep ?? ((milliseconds) => new Promise((resolvePromise) => setTimeout(resolvePromise, milliseconds)));
48
+ this.nativeOperationLease = options.nativeOperationLease;
49
+ this.suspendLiveConnection = options.suspendLiveConnection;
50
+ this.resumeLiveConnection = options.resumeLiveConnection;
51
+ }
52
+ isAvailable() {
53
+ return this.enabled && this.probeAvailable;
54
+ }
55
+ async exportVideo(request) {
56
+ if (!this.enabled) {
57
+ throw new Error("CAPABILITY_UNAVAILABLE: Final Cut video export is disabled; set FRAMEKIT_FINAL_CUT_NATIVE_WRITES=1");
58
+ }
59
+ if (!request.outputPath.trim())
60
+ throw new Error("INVALID_EXPORT: outputPath is required");
61
+ if (!this.isAvailable())
62
+ throw new Error("CAPABILITY_UNAVAILABLE: Final Cut video export metadata probing is unavailable");
63
+ const outputPath = resolve(request.outputPath.trim());
64
+ const preset = FINAL_CUT_EXPORT_PRESETS[request.preset];
65
+ if (!preset)
66
+ throw new Error(`INVALID_EXPORT_PRESET: unsupported Final Cut export preset ${String(request.preset)}`);
67
+ validateExpectation(request.expected);
68
+ if (this.probeAvailability && !(await this.probeAvailability())) {
69
+ throw new Error("FINAL_CUT_EXPORT_METADATA_UNAVAILABLE: ffprobe is required to verify exported video metadata");
70
+ }
71
+ await assertOutputDirectory(outputPath);
72
+ await assertOutputCanBeReplaced(outputPath, request.overwrite ?? false);
73
+ const stagingPath = createStagingPath(outputPath);
74
+ let committed = false;
75
+ try {
76
+ const result = await this.withNativeUi(async () => {
77
+ await this.assertPreflight();
78
+ await this.executor(exportScript(stagingPath, preset.menuItem));
79
+ const output = await this.waitForOutput(stagingPath);
80
+ const probed = await this.probeUntilReady(stagingPath, output.deadline);
81
+ const metadata = {
82
+ outputPath,
83
+ sizeBytes: output.size,
84
+ ...probed,
85
+ };
86
+ verifyMetadata(metadata, request.expected);
87
+ await commitOutput(stagingPath, outputPath, request.overwrite ?? false);
88
+ committed = true;
89
+ return {
90
+ outputPath,
91
+ preset: request.preset,
92
+ completed: true,
93
+ verified: true,
94
+ metadata,
95
+ };
96
+ });
97
+ return result;
98
+ }
99
+ finally {
100
+ if (!committed)
101
+ await removeIfPresent(stagingPath);
102
+ }
103
+ }
104
+ async assertPreflight() {
105
+ if (!this.preflight)
106
+ return;
107
+ const context = await this.preflight();
108
+ if (!context.available) {
109
+ throw new Error(`${context.error?.code ?? "FINAL_CUT_NATIVE_UNAVAILABLE"}: ${context.error?.message ?? "native Final Cut context unavailable"}`);
110
+ }
111
+ if (!context.timelineWindowAvailable) {
112
+ throw new Error("FINAL_CUT_NATIVE_NO_TIMELINE_WINDOW: Final Cut has no accessible timeline window; open a project timeline and retry");
113
+ }
114
+ if (!context.frontmost) {
115
+ throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut is running but is not the frontmost application");
116
+ }
117
+ if (!context.timelineFocused) {
118
+ throw new Error("FINAL_CUT_NATIVE_TIMELINE_FOCUS_REQUIRED: Final Cut's timeline pane could not be focused; click the timeline and retry");
119
+ }
120
+ }
121
+ async waitForOutput(outputPath) {
122
+ const deadline = this.now() + this.waitMs;
123
+ let previous;
124
+ let stableObservations = 0;
125
+ while (true) {
126
+ try {
127
+ const details = await stat(outputPath);
128
+ if (details.isFile() && details.size > 0) {
129
+ const current = { size: details.size, mtimeMs: details.mtimeMs };
130
+ stableObservations = previous
131
+ && previous.size === current.size
132
+ && previous.mtimeMs === current.mtimeMs
133
+ ? stableObservations + 1
134
+ : 1;
135
+ previous = current;
136
+ if (stableObservations >= this.stablePolls)
137
+ return { ...current, deadline };
138
+ }
139
+ else {
140
+ previous = undefined;
141
+ stableObservations = 0;
142
+ }
143
+ }
144
+ catch {
145
+ // The export may still be rendering or writing its output.
146
+ previous = undefined;
147
+ stableObservations = 0;
148
+ }
149
+ if (this.now() >= deadline)
150
+ break;
151
+ await this.sleep(Math.min(this.pollMs, Math.max(0, deadline - this.now())));
152
+ }
153
+ throw new Error(`FINAL_CUT_EXPORT_COMPLETION_TIMEOUT: Final Cut did not produce a non-empty file at ${outputPath}`);
154
+ }
155
+ async probeUntilReady(outputPath, deadline) {
156
+ while (true) {
157
+ try {
158
+ return await this.probe(outputPath);
159
+ }
160
+ catch (error) {
161
+ if (this.now() >= deadline) {
162
+ throw new Error(`FINAL_CUT_EXPORT_METADATA_FAILED: could not inspect ${outputPath} (${String(error)})`);
163
+ }
164
+ await this.sleep(Math.min(this.pollMs, Math.max(0, deadline - this.now())));
165
+ }
166
+ }
167
+ }
168
+ async withNativeUi(operation) {
169
+ if (this.nativeOperationLease)
170
+ this.nativeOperationLease.acquire();
171
+ else
172
+ this.suspendLiveConnection?.();
173
+ try {
174
+ return await operation();
175
+ }
176
+ finally {
177
+ if (this.nativeOperationLease)
178
+ this.nativeOperationLease.release();
179
+ else
180
+ this.resumeLiveConnection?.();
181
+ }
182
+ }
183
+ }
184
+ async function assertOutputDirectory(outputPath) {
185
+ try {
186
+ const parent = await stat(dirname(outputPath));
187
+ if (!parent.isDirectory())
188
+ throw new Error("parent path is not a directory");
189
+ await access(dirname(outputPath), constants.W_OK);
190
+ }
191
+ catch (error) {
192
+ throw new Error(`FINAL_CUT_EXPORT_PATH_UNAVAILABLE: output directory is not writable (${String(error)})`);
193
+ }
194
+ }
195
+ async function assertOutputCanBeReplaced(outputPath, overwrite) {
196
+ try {
197
+ const details = await stat(outputPath);
198
+ if (!details.isFile()) {
199
+ throw new Error(`FINAL_CUT_EXPORT_OUTPUT_EXISTS: output path is not a file: ${outputPath}`);
200
+ }
201
+ if (!overwrite) {
202
+ throw new Error(`FINAL_CUT_EXPORT_OUTPUT_EXISTS: refusing to replace existing output ${outputPath}; set overwrite=true to confirm`);
203
+ }
204
+ }
205
+ catch (error) {
206
+ if (isNodeError(error) && error.code === "ENOENT")
207
+ return;
208
+ if (error instanceof Error && error.message.startsWith("FINAL_CUT_EXPORT_OUTPUT_EXISTS:"))
209
+ throw error;
210
+ throw new Error(`FINAL_CUT_EXPORT_PATH_UNAVAILABLE: could not prepare output path (${String(error)})`);
211
+ }
212
+ }
213
+ function createStagingPath(outputPath) {
214
+ const extension = extname(outputPath);
215
+ const stem = basename(outputPath, extension);
216
+ return join(dirname(outputPath), `.${stem}.framekit-${randomUUID()}${extension}`);
217
+ }
218
+ async function commitOutput(stagingPath, outputPath, overwrite) {
219
+ if (!overwrite) {
220
+ try {
221
+ await stat(outputPath);
222
+ throw new Error(`FINAL_CUT_EXPORT_OUTPUT_EXISTS: output appeared while export was running ${outputPath}`);
223
+ }
224
+ catch (error) {
225
+ if (!(isNodeError(error) && error.code === "ENOENT"))
226
+ throw error;
227
+ }
228
+ }
229
+ try {
230
+ await rename(stagingPath, outputPath);
231
+ }
232
+ catch (error) {
233
+ throw new Error(`FINAL_CUT_EXPORT_COMMIT_FAILED: could not replace ${outputPath} (${String(error)})`);
234
+ }
235
+ }
236
+ async function removeIfPresent(path) {
237
+ try {
238
+ await unlink(path);
239
+ }
240
+ catch (error) {
241
+ if (!(isNodeError(error) && error.code === "ENOENT"))
242
+ throw error;
243
+ }
244
+ }
245
+ function isNodeError(error) {
246
+ return error instanceof Error && "code" in error;
247
+ }
248
+ function validateExpectation(expectation) {
249
+ if (!expectation)
250
+ return;
251
+ for (const [name, value] of Object.entries(expectation)) {
252
+ if (name.endsWith("ToleranceSeconds") || name === "frameRateTolerance")
253
+ continue;
254
+ if (typeof value === "number" && (!Number.isFinite(value) || value <= 0)) {
255
+ throw new Error(`INVALID_EXPORT: expected ${name} must be a positive finite number`);
256
+ }
257
+ }
258
+ if (expectation.durationToleranceSeconds !== undefined
259
+ && (!Number.isFinite(expectation.durationToleranceSeconds) || expectation.durationToleranceSeconds < 0)) {
260
+ throw new Error("INVALID_EXPORT: durationToleranceSeconds must be a non-negative finite number");
261
+ }
262
+ if (expectation.frameRateTolerance !== undefined
263
+ && (!Number.isFinite(expectation.frameRateTolerance) || expectation.frameRateTolerance < 0)) {
264
+ throw new Error("INVALID_EXPORT: frameRateTolerance must be a non-negative finite number");
265
+ }
266
+ }
267
+ function verifyMetadata(metadata, expectation) {
268
+ if (!Number.isFinite(metadata.durationSeconds) || metadata.durationSeconds <= 0) {
269
+ throw new Error("FINAL_CUT_EXPORT_VERIFICATION_FAILED: output duration is missing or invalid");
270
+ }
271
+ if (!Number.isInteger(metadata.width) || metadata.width <= 0 || !Number.isInteger(metadata.height) || metadata.height <= 0) {
272
+ throw new Error("FINAL_CUT_EXPORT_VERIFICATION_FAILED: output resolution is missing or invalid");
273
+ }
274
+ if (!Number.isFinite(metadata.frameRate) || metadata.frameRate <= 0) {
275
+ throw new Error("FINAL_CUT_EXPORT_VERIFICATION_FAILED: output frame rate is missing or invalid");
276
+ }
277
+ if (typeof metadata.hasAudio !== "boolean") {
278
+ throw new Error("FINAL_CUT_EXPORT_VERIFICATION_FAILED: output audio presence is missing or invalid");
279
+ }
280
+ if (!expectation)
281
+ return;
282
+ if (expectation.durationSeconds !== undefined
283
+ && Math.abs(metadata.durationSeconds - expectation.durationSeconds) > (expectation.durationToleranceSeconds ?? 0.05)) {
284
+ throw new Error(`FINAL_CUT_EXPORT_VERIFICATION_FAILED: expected duration ${expectation.durationSeconds}s, observed ${metadata.durationSeconds}s`);
285
+ }
286
+ if (expectation.width !== undefined && metadata.width !== expectation.width) {
287
+ throw new Error(`FINAL_CUT_EXPORT_VERIFICATION_FAILED: expected width ${expectation.width}, observed ${metadata.width}`);
288
+ }
289
+ if (expectation.height !== undefined && metadata.height !== expectation.height) {
290
+ throw new Error(`FINAL_CUT_EXPORT_VERIFICATION_FAILED: expected height ${expectation.height}, observed ${metadata.height}`);
291
+ }
292
+ if (expectation.frameRate !== undefined
293
+ && Math.abs(metadata.frameRate - expectation.frameRate) > (expectation.frameRateTolerance ?? 0.01)) {
294
+ throw new Error(`FINAL_CUT_EXPORT_VERIFICATION_FAILED: expected frame rate ${expectation.frameRate}, observed ${metadata.frameRate}`);
295
+ }
296
+ if (expectation.hasAudio !== undefined && metadata.hasAudio !== expectation.hasAudio) {
297
+ throw new Error(`FINAL_CUT_EXPORT_VERIFICATION_FAILED: expected audio presence ${expectation.hasAudio}, observed ${metadata.hasAudio}`);
298
+ }
299
+ }
300
+ async function probeWithFfprobe(outputPath) {
301
+ let stdout;
302
+ try {
303
+ ({ stdout } = await execFile("ffprobe", [
304
+ "-v", "error",
305
+ "-show_entries", "format=duration:stream=codec_type,width,height,r_frame_rate,avg_frame_rate,codec_name",
306
+ "-of", "json",
307
+ outputPath,
308
+ ], { maxBuffer: 1_000_000 }));
309
+ }
310
+ catch (error) {
311
+ throw new Error(`ffprobe failed: ${String(error)}`);
312
+ }
313
+ const parsed = JSON.parse(stdout);
314
+ const video = parsed.streams?.find((stream) => stream.codec_type === "video");
315
+ if (!video)
316
+ throw new Error("ffprobe returned no video stream");
317
+ const durationSeconds = Number(parsed.format?.duration);
318
+ const width = Number(video.width);
319
+ const height = Number(video.height);
320
+ const frameRate = parseFrameRate(video.avg_frame_rate ?? video.r_frame_rate);
321
+ if (!Number.isFinite(durationSeconds) || !Number.isFinite(width) || !Number.isFinite(height) || !Number.isFinite(frameRate)) {
322
+ throw new Error("ffprobe returned incomplete video metadata");
323
+ }
324
+ const audio = parsed.streams?.find((stream) => stream.codec_type === "audio");
325
+ return {
326
+ durationSeconds,
327
+ width,
328
+ height,
329
+ frameRate,
330
+ hasAudio: Boolean(audio),
331
+ ...(typeof video.codec_name === "string" ? { videoCodec: video.codec_name } : {}),
332
+ ...(typeof audio?.codec_name === "string" ? { audioCodec: audio.codec_name } : {}),
333
+ };
334
+ }
335
+ function parseFrameRate(value) {
336
+ if (typeof value !== "string")
337
+ return Number.NaN;
338
+ const [numerator, denominator] = value.split("/").map(Number);
339
+ if (!Number.isFinite(numerator) || !Number.isFinite(denominator) || denominator <= 0)
340
+ return Number(value);
341
+ return numerator / denominator;
342
+ }
343
+ async function runAppleScript(script) {
344
+ try {
345
+ const result = await execFile("osascript", ["-e", script], { maxBuffer: 1_000_000 });
346
+ return result.stdout.trim();
347
+ }
348
+ catch (error) {
349
+ const detail = error instanceof Error ? error.message : String(error);
350
+ if (detail.includes("not authorized") || detail.includes("-1743") || detail.includes("-25211")) {
351
+ throw new Error(`FINAL_CUT_EXPORT_PERMISSION_REQUIRED: ${detail}`);
352
+ }
353
+ throw new Error(`FINAL_CUT_EXPORT_AUTOMATION_FAILED: ${detail}`);
354
+ }
355
+ }
356
+ function exportScript(outputPath, menuItem) {
357
+ return `
358
+ tell application "Final Cut Pro" to activate
359
+ tell application "System Events"
360
+ tell process "Final Cut Pro"
361
+ if not frontmost then error number -1719
362
+ set shareMenu to menu 1 of menu item "Share" of menu "File" of menu bar 1
363
+ set matchingItems to every menu item of shareMenu whose name starts with "${menuItem}"
364
+ if (count of matchingItems) is 0 then error "FINAL_CUT_EXPORT_PRESET_UNAVAILABLE: ${menuItem}"
365
+ click item 1 of matchingItems
366
+ delay 1
367
+ try
368
+ click button "Next" of front window
369
+ delay 0.5
370
+ end try
371
+ keystroke "g" using {command down}
372
+ delay 0.2
373
+ set value of first text field of front window to ${appleScriptString(outputPath)}
374
+ key code 36
375
+ delay 0.5
376
+ key code 36
377
+ end tell
378
+ end tell`;
379
+ }
380
+ function appleScriptString(value) {
381
+ return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"').replace(/[\r\n]/g, " ")}"`;
382
+ }