@morshoto/framekit 0.1.10 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,175 @@
1
+ import { createHash } from "node:crypto";
2
+ import { spawn } from "node:child_process";
3
+ import { readFile } from "node:fs/promises";
4
+ import { timelineIrDigest, validateTimelineIr } from "../../../../packages/runtime/src/index.js";
5
+ const DEFAULT_COMMAND_TIMEOUT_MS = 30_000;
6
+ /**
7
+ * Publishes an immutable FCPXML artifact through an explicit non-UI Final Cut
8
+ * capability. The command owns Final Cut import and target-bound canonical
9
+ * readback; this adapter never activates Final Cut or falls back to UI calls.
10
+ */
11
+ export class FinalCutBackgroundMaterializationPublisher {
12
+ options;
13
+ commandTimeoutMs;
14
+ constructor(options = {}) {
15
+ this.options = options;
16
+ if (options.commandTimeoutMs !== undefined && (!Number.isFinite(options.commandTimeoutMs) || options.commandTimeoutMs <= 0)) {
17
+ throw new Error("FINAL_CUT_BACKGROUND_MATERIALIZATION_TIMEOUT_INVALID: command timeout must be greater than zero");
18
+ }
19
+ this.commandTimeoutMs = options.commandTimeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS;
20
+ }
21
+ isAvailable() {
22
+ return this.options.executor !== undefined || Boolean(this.options.command?.trim());
23
+ }
24
+ async publish(request) {
25
+ validateRequest(request);
26
+ const executor = this.options.executor ?? (this.options.command?.trim()
27
+ ? commandExecutor(this.options.command.trim(), this.commandTimeoutMs)
28
+ : undefined);
29
+ if (!executor) {
30
+ return {
31
+ state: "blocked",
32
+ code: "FINAL_CUT_BACKGROUND_MATERIALIZATION_UNAVAILABLE",
33
+ message: "No explicit non-UI Final Cut materialization capability is configured",
34
+ retryable: true,
35
+ };
36
+ }
37
+ const artifact = await readFile(request.artifactPath, "utf8");
38
+ if (createHash("sha256").update(artifact).digest("hex") !== request.artifactDigest) {
39
+ throw new Error("MATERIALIZATION_ARTIFACT_CHANGED: the staged FCPXML artifact no longer matches its immutable digest");
40
+ }
41
+ if (timelineIrDigest(request.desired) !== request.desiredDigest) {
42
+ throw new Error("MATERIALIZATION_DESIRED_SNAPSHOT_INVALID: the staged desired Timeline IR digest is invalid");
43
+ }
44
+ const result = await executor({ ...request, desired: structuredClone(request.desired) });
45
+ return validateResult(result);
46
+ }
47
+ }
48
+ function validateRequest(request) {
49
+ if (!request.jobId.trim())
50
+ throw new Error("MATERIALIZATION_REQUEST_INVALID: jobId is required");
51
+ if (!request.artifactPath.trim() || !request.artifactDigest.trim()) {
52
+ throw new Error("MATERIALIZATION_REQUEST_INVALID: immutable artifact path and digest are required");
53
+ }
54
+ if (!request.desiredDigest.trim())
55
+ throw new Error("MATERIALIZATION_REQUEST_INVALID: desired digest is required");
56
+ if (request.collisionPolicy !== "create-only")
57
+ throw new Error("MATERIALIZATION_REQUEST_INVALID: publication must be create-only");
58
+ const { target } = request;
59
+ if (target.provider !== "final-cut" || !target.libraryUid.trim() || !target.eventUid.trim() || !target.projectUid.trim() || !target.sequenceUid.trim()) {
60
+ throw new Error("FCPXML_TARGET_BINDING_INVALID: library, event, project, and sequence identities are required");
61
+ }
62
+ if (request.destination.mode !== "versioned") {
63
+ throw new Error("FINAL_CUT_BACKGROUND_MATERIALIZATION_REUSE_FORBIDDEN: background publication cannot overwrite an existing project");
64
+ }
65
+ if (!request.destination.projectUid.trim() || !request.destination.sequenceUid.trim()) {
66
+ throw new Error("MATERIALIZATION_DESTINATION_INVALID: versioned project and sequence identities are required");
67
+ }
68
+ validateTimelineIr(request.desired);
69
+ }
70
+ function validateResult(result) {
71
+ if (!result || (result.state !== "completed" && result.state !== "blocked")) {
72
+ throw new Error("FINAL_CUT_BACKGROUND_MATERIALIZATION_RESPONSE_INVALID: capability returned an invalid result");
73
+ }
74
+ if (result.state === "blocked") {
75
+ if (typeof result.code !== "string" || typeof result.message !== "string" || !result.code.trim() || !result.message.trim()) {
76
+ throw new Error("FINAL_CUT_BACKGROUND_MATERIALIZATION_RESPONSE_INVALID: blocked result is missing code or message");
77
+ }
78
+ return result;
79
+ }
80
+ validateTimelineIr(result.canonicalReadback);
81
+ validateTargetIdentity(result.canonicalTarget);
82
+ if (result.headedNativeVerified !== false) {
83
+ throw new Error("FINAL_CUT_BACKGROUND_MATERIALIZATION_RESPONSE_INVALID: background publisher cannot claim headed-native verification");
84
+ }
85
+ return result;
86
+ }
87
+ function validateTargetIdentity(target) {
88
+ if (!target || !target.libraryUid?.trim() || !target.eventUid?.trim() || !target.projectUid?.trim() || !target.sequenceUid?.trim()) {
89
+ throw new Error("FINAL_CUT_BACKGROUND_MATERIALIZATION_RESPONSE_INVALID: canonical target identity is incomplete");
90
+ }
91
+ }
92
+ function commandExecutor(command, timeoutMs) {
93
+ return async (request) => {
94
+ let output;
95
+ try {
96
+ output = await runCommand(command, request, timeoutMs);
97
+ }
98
+ catch (error) {
99
+ const detail = error instanceof Error ? error.message : String(error);
100
+ const timedOut = detail.startsWith("FINAL_CUT_BACKGROUND_MATERIALIZATION_COMMAND_TIMEOUT");
101
+ return {
102
+ state: "blocked",
103
+ code: timedOut
104
+ ? "FINAL_CUT_BACKGROUND_MATERIALIZATION_COMMAND_TIMEOUT"
105
+ : "FINAL_CUT_BACKGROUND_MATERIALIZATION_COMMAND_UNAVAILABLE",
106
+ message: detail,
107
+ retryable: true,
108
+ };
109
+ }
110
+ let parsed;
111
+ try {
112
+ parsed = JSON.parse(output);
113
+ }
114
+ catch (error) {
115
+ throw new Error(`FINAL_CUT_BACKGROUND_MATERIALIZATION_RESPONSE_INVALID: ${error instanceof Error ? error.message : String(error)}`);
116
+ }
117
+ return validateResult(parsed);
118
+ };
119
+ }
120
+ function runCommand(command, request, timeoutMs) {
121
+ return new Promise((resolve, reject) => {
122
+ const child = spawn(command, [], { stdio: ["pipe", "pipe", "pipe"] });
123
+ let stdout = "";
124
+ let stderr = "";
125
+ let settled = false;
126
+ let closed = false;
127
+ let timeoutHandle;
128
+ let forceKillHandle;
129
+ const cleanup = () => {
130
+ if (timeoutHandle !== undefined)
131
+ clearTimeout(timeoutHandle);
132
+ if (forceKillHandle !== undefined)
133
+ clearTimeout(forceKillHandle);
134
+ };
135
+ const settle = (callback) => {
136
+ if (settled)
137
+ return;
138
+ settled = true;
139
+ cleanup();
140
+ callback();
141
+ };
142
+ child.stdout.setEncoding("utf8");
143
+ child.stderr.setEncoding("utf8");
144
+ child.stdout.on("data", (chunk) => { stdout += chunk; });
145
+ child.stderr.on("data", (chunk) => { stderr += chunk; });
146
+ child.once("error", (error) => settle(() => reject(error)));
147
+ child.once("close", (code) => {
148
+ closed = true;
149
+ if (settled) {
150
+ cleanup();
151
+ return;
152
+ }
153
+ if (code === 0) {
154
+ settle(() => resolve(stdout));
155
+ }
156
+ else {
157
+ settle(() => reject(new Error(`FINAL_CUT_BACKGROUND_MATERIALIZATION_COMMAND_FAILED: command exited ${code}: ${stderr.trim()}`)));
158
+ }
159
+ });
160
+ timeoutHandle = setTimeout(() => {
161
+ if (settled)
162
+ return;
163
+ child.kill("SIGTERM");
164
+ forceKillHandle = setTimeout(() => {
165
+ if (!closed)
166
+ child.kill("SIGKILL");
167
+ }, 1_000);
168
+ settled = true;
169
+ if (timeoutHandle !== undefined)
170
+ clearTimeout(timeoutHandle);
171
+ reject(new Error(`FINAL_CUT_BACKGROUND_MATERIALIZATION_COMMAND_TIMEOUT: command exceeded ${timeoutMs}ms`));
172
+ }, timeoutMs);
173
+ child.stdin.end(`${JSON.stringify(request)}\n`);
174
+ });
175
+ }
@@ -104,13 +104,19 @@ export class FinalCutConnectionManager {
104
104
  try {
105
105
  this.update({ state: "detecting", lastError: undefined });
106
106
  const existing = await this.tryProbe();
107
- if (existing)
108
- return this.ready(existing);
107
+ this.update({ extensionInstalled: await pathExists(this.extensionInstallPath) });
108
+ if (existing.result)
109
+ return this.ready(existing.result);
109
110
  if (this.canonicalProviderRequired) {
110
111
  return this.fail("FINAL_CUT_CANONICAL_PROVIDER_UNAVAILABLE", `Canonical live provider is unavailable at ${this.socketPath}; metadata-only fallback is disabled`, "needs-user-action");
111
112
  }
112
113
  if (this.headless) {
113
- return this.fail("FINAL_CUT_HEADLESS_SOCKET_UNAVAILABLE", `Headless mode only probes the existing Workflow Extension socket at ${this.socketPath}; it does not launch or activate Final Cut Pro`, "unavailable");
114
+ this.update({ state: "waiting-for-socket" });
115
+ const waiting = await this.waitForHeadlessBridge(existing.error);
116
+ if (waiting.result)
117
+ return this.ready(waiting.result);
118
+ const failure = headlessProbeFailure(waiting.error, this.socketPath);
119
+ return this.fail(failure.code, failure.message, "unavailable");
114
120
  }
115
121
  const editorDetected = await this.detectFinalCut();
116
122
  this.update({ editorDetected });
@@ -157,8 +163,8 @@ export class FinalCutConnectionManager {
157
163
  let nextActivationAt = Date.now() + this.activationRetryIntervalMs;
158
164
  while (Date.now() < deadline) {
159
165
  const result = await this.tryProbe();
160
- if (result)
161
- return this.ready(result);
166
+ if (result.result)
167
+ return this.ready(result.result);
162
168
  if (Date.now() >= nextActivationAt) {
163
169
  try {
164
170
  await this.activateWithDeadline(deadline);
@@ -186,11 +192,24 @@ export class FinalCutConnectionManager {
186
192
  }
187
193
  async tryProbe() {
188
194
  try {
189
- return await this.probe();
195
+ return { result: await this.probe() };
190
196
  }
191
- catch {
192
- return undefined;
197
+ catch (error) {
198
+ return { error };
199
+ }
200
+ }
201
+ async waitForHeadlessBridge(initialError) {
202
+ const deadline = Date.now() + this.startupTimeoutMs;
203
+ let attempt = { error: initialError };
204
+ while (Date.now() < deadline) {
205
+ if (isIncompatibleProbeError(attempt.error))
206
+ return attempt;
207
+ await this.sleep(Math.min(this.pollIntervalMs, Math.max(1, deadline - Date.now())));
208
+ attempt = await this.tryProbe();
209
+ if (attempt.result)
210
+ return attempt;
193
211
  }
212
+ return attempt;
194
213
  }
195
214
  ready(result) {
196
215
  const capabilities = withCanonicalTimelineMode(withCapabilityFamilies(result.capabilities, {
@@ -203,7 +222,6 @@ export class FinalCutConnectionManager {
203
222
  this.update({
204
223
  state: "ready",
205
224
  editorDetected: true,
206
- extensionInstalled: true,
207
225
  identity: result.identity,
208
226
  capabilities,
209
227
  lastError: undefined,
@@ -211,7 +229,12 @@ export class FinalCutConnectionManager {
211
229
  return this.getStatus();
212
230
  }
213
231
  fail(code, message, state) {
214
- this.update({ state, lastError: { code, message } });
232
+ this.update({
233
+ state,
234
+ identity: undefined,
235
+ capabilities: undefined,
236
+ lastError: { code, message },
237
+ });
215
238
  return this.getStatus();
216
239
  }
217
240
  update(patch) {
@@ -304,10 +327,7 @@ export class FinalCutConnectionManager {
304
327
  }
305
328
  function defaultProbe(socketPath) {
306
329
  const adapter = createFinalCutLiveAdapter(socketPath);
307
- return async () => ({
308
- identity: await adapter.getIdentity(),
309
- capabilities: await adapter.getCapabilities(),
310
- });
330
+ return () => adapter.inspect();
311
331
  }
312
332
  async function defaultDetectFinalCut(appPath) {
313
333
  try {
@@ -396,3 +416,21 @@ function isActivationTimeout(error) {
396
416
  const message = String(error);
397
417
  return message.includes("-1712") || message.includes("ETIMEDOUT") || message.includes("timed out");
398
418
  }
419
+ function isIncompatibleProbeError(error) {
420
+ return String(error).includes("FINAL_CUT_LIVE_PROTOCOL")
421
+ || String(error).includes("UNSUPPORTED_METHOD")
422
+ || String(error).includes("CAPABILITY_UNAVAILABLE");
423
+ }
424
+ function headlessProbeFailure(error, socketPath) {
425
+ const detail = error instanceof Error ? error.message : String(error ?? "unknown probe failure");
426
+ if (isIncompatibleProbeError(error)) {
427
+ return {
428
+ code: "FINAL_CUT_HEADLESS_PROTOCOL_INCOMPATIBLE",
429
+ message: `The Workflow Extension endpoint at ${socketPath} is incompatible with Framekit's live protocol: ${detail}`,
430
+ };
431
+ }
432
+ return {
433
+ code: "FINAL_CUT_HEADLESS_SOCKET_UNAVAILABLE",
434
+ message: `Headless mode could not connect to the Workflow Extension socket at ${socketPath}: ${detail}. It does not launch or activate Final Cut Pro`,
435
+ };
436
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Classifies evidence collected around the FCPXML programmatic/artifact path.
3
+ * This function never authorizes a write: a headed result is preflight only,
4
+ * and target-bound import readback remains unavailable until independently
5
+ * proven by a native provider.
6
+ */
7
+ export function classifyFinalCutFcpxmlExperiment(observation) {
8
+ validateArtifact(observation.artifact);
9
+ if (!observation.console.source.trim())
10
+ throw new Error("FCPXML_EXPERIMENT_INVALID: console source is required");
11
+ if (!Number.isInteger(observation.log.lineCount) || observation.log.lineCount < 0) {
12
+ throw new Error("FCPXML_EXPERIMENT_INVALID: log lineCount must be a non-negative integer");
13
+ }
14
+ const base = {
15
+ schemaVersion: 1,
16
+ observation: structuredClone(observation),
17
+ capabilities: {
18
+ artifactRead: "verified",
19
+ targetBoundReadback: "unavailable",
20
+ },
21
+ mutationAttempted: false,
22
+ nativeImportVerified: false,
23
+ safeToOverwrite: false,
24
+ };
25
+ if (observation.console.state === "locked") {
26
+ return {
27
+ ...base,
28
+ status: "blocked",
29
+ capabilities: { ...base.capabilities, headedImport: "blocked" },
30
+ blockers: [{
31
+ code: "FINAL_CUT_NATIVE_CONSOLE_LOCKED",
32
+ retryable: observation.console.retryable,
33
+ message: "The macOS console is locked; no headed FCPXML import was attempted",
34
+ }],
35
+ };
36
+ }
37
+ if (observation.console.state === "unknown") {
38
+ return {
39
+ ...base,
40
+ status: "blocked",
41
+ capabilities: { ...base.capabilities, headedImport: "blocked" },
42
+ blockers: [{
43
+ code: "FINAL_CUT_NATIVE_CONSOLE_LOCK_STATE_UNKNOWN",
44
+ retryable: observation.console.retryable,
45
+ message: "macOS did not expose one consistent supported console lock state",
46
+ }],
47
+ };
48
+ }
49
+ if (observation.process !== "running") {
50
+ return artifactOnly(base, "FINAL_CUT_NOT_RUNNING", true, "Final Cut Pro is not running; only the FCPXML artifact was inspected");
51
+ }
52
+ if (observation.frontmost !== "final-cut") {
53
+ return artifactOnly(base, "FINAL_CUT_NOT_FRONTMOST", true, "Final Cut Pro is not frontmost; only the FCPXML artifact was inspected");
54
+ }
55
+ return {
56
+ ...base,
57
+ status: "headed-preflight-ready",
58
+ capabilities: { ...base.capabilities, headedImport: "preflight-only" },
59
+ blockers: [],
60
+ };
61
+ }
62
+ function artifactOnly(base, code, retryable, message) {
63
+ return {
64
+ ...base,
65
+ status: "artifact-only",
66
+ capabilities: { ...base.capabilities, headedImport: "blocked" },
67
+ blockers: [{ code, retryable, message }],
68
+ };
69
+ }
70
+ function validateArtifact(artifact) {
71
+ if (artifact.format !== "fcpxml" || !artifact.valid || artifact.version !== "1.11" || !/^[a-f0-9]{64}$/i.test(artifact.digest)) {
72
+ throw new Error("FCPXML_ARTIFACT_INVALID: experiment requires a valid FCPXML 1.11 artifact and SHA-256 digest");
73
+ }
74
+ }
@@ -11,6 +11,12 @@ export * from "./disposable-native.js";
11
11
  export * from "./publisher.js";
12
12
  export * from "./export.js";
13
13
  export * from "./background-export.js";
14
+ export * from "./background-materialization.js";
14
15
  export * from "./library-inspection.js";
16
+ export * from "./sqlite-inspection.js";
17
+ export * from "./shadow-mutation.js";
15
18
  export * from "./native-operation.js";
16
19
  export * from "./native-session.js";
20
+ export * from "./timeline-ir-fcpxml.js";
21
+ export * from "./fcpxml-console-experiment.js";
22
+ export * from "./unattended-editing.js";
@@ -71,13 +71,20 @@ export class FinalCutLiveAdapter {
71
71
  this.transport = transport;
72
72
  this.socketPath = socketPath;
73
73
  }
74
- async getIdentity() {
74
+ async inspect() {
75
75
  const response = await this.request({ method: "capabilities" });
76
- return response.identity;
76
+ return {
77
+ identity: response.identity,
78
+ capabilities: withCanonicalTimelineMode(withCapabilityFamilies(response.capabilities, {
79
+ backend: response.identity.backend,
80
+ })),
81
+ };
82
+ }
83
+ async getIdentity() {
84
+ return (await this.inspect()).identity;
77
85
  }
78
86
  async getCapabilities() {
79
- const response = await this.request({ method: "capabilities" });
80
- return withCanonicalTimelineMode(withCapabilityFamilies(response.capabilities, { backend: response.identity.backend }));
87
+ return (await this.inspect()).capabilities;
81
88
  }
82
89
  async read() {
83
90
  return this.readProject();
@@ -17,6 +17,10 @@ export class FinalCutSessionAdapter {
17
17
  }
18
18
  if (this.options.snapshot)
19
19
  return this.options.snapshot.getIdentity();
20
+ const liveOnly = this.pureLiveProvider();
21
+ if (liveOnly) {
22
+ return liveOnly.getIdentity();
23
+ }
20
24
  if (this.options.live) {
21
25
  try {
22
26
  return await this.options.live.getIdentity();
@@ -38,7 +42,10 @@ export class FinalCutSessionAdapter {
38
42
  async getCapabilities(options = {}) {
39
43
  const snapshot = await this.options.snapshot?.getCapabilities(options);
40
44
  const mutation = await this.options.mutation?.getCapabilities(options);
41
- const live = await optionalCapabilities(this.options.live, options);
45
+ const liveOnly = this.pureLiveProvider();
46
+ const live = liveOnly
47
+ ? withCanonicalTimelineMode(await liveOnly.getCapabilities(options))
48
+ : await optionalCapabilities(this.options.live, options);
42
49
  const hasExplicitDocumentPair = Boolean(this.options.snapshot && this.options.mutation);
43
50
  const useLiveCanonical = !this.options.snapshot && !this.options.mutation;
44
51
  const liveSnapshot = Boolean(useLiveCanonical
@@ -328,6 +335,17 @@ export class FinalCutSessionAdapter {
328
335
  throw new Error("CAPABILITY_UNAVAILABLE: live Final Cut editor state");
329
336
  return this.options.live.liveChangesSince(revision, waitMs);
330
337
  }
338
+ pureLiveProvider() {
339
+ if (!this.options.live
340
+ || this.options.snapshot
341
+ || this.options.mutation
342
+ || this.options.assets
343
+ || this.options.media
344
+ || this.options.backgroundCatalog) {
345
+ return undefined;
346
+ }
347
+ return this.options.live;
348
+ }
331
349
  async routedTransactionProvider() {
332
350
  if (this.options.snapshot && this.options.mutation)
333
351
  return this.options.mutation;
@@ -0,0 +1,120 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { execFile as execFileCallback } from "node:child_process";
3
+ import { copyFile, cp, mkdir, readdir, realpath, stat } from "node:fs/promises";
4
+ import { basename, isAbsolute, join, relative, resolve, sep } from "node:path";
5
+ import { promisify } from "node:util";
6
+ const execFile = promisify(execFileCallback);
7
+ /**
8
+ * Experimental writer for disposable shadow copies only. It intentionally has
9
+ * no API for timeline payloads, metadata BLOBs, or arbitrary SQL.
10
+ */
11
+ export class FinalCutShadowBundleMutator {
12
+ options;
13
+ sqliteCommand;
14
+ constructor(options) {
15
+ this.options = options;
16
+ this.sqliteCommand = options.sqliteCommand ?? "sqlite3";
17
+ }
18
+ async createShadow(sourceBundlePath) {
19
+ if (!sourceBundlePath.endsWith(".fcpbundle")) {
20
+ throw new Error("FINAL_CUT_SHADOW_SOURCE_INVALID: source must be a .fcpbundle directory");
21
+ }
22
+ const sourceBundle = await realpath(sourceBundlePath);
23
+ await mkdir(this.options.shadowRoot, { recursive: true });
24
+ const shadowRoot = await realpath(this.options.shadowRoot);
25
+ const shadowBundle = join(shadowRoot, `${basename(sourceBundle, ".fcpbundle")}-framekit-shadow-${randomUUID()}.fcpbundle`);
26
+ await cp(sourceBundle, shadowBundle, { recursive: true, force: false, errorOnExist: true, dereference: false });
27
+ const resolvedShadowBundle = await realpath(shadowBundle);
28
+ if (!isWithin(shadowRoot, resolvedShadowBundle)) {
29
+ throw new Error("FINAL_CUT_SHADOW_BUNDLE_PATH_INVALID: shadow bundle escaped the configured shadow root");
30
+ }
31
+ return {
32
+ sourceBundlePath: sourceBundle,
33
+ shadowBundlePath: resolvedShadowBundle,
34
+ sourceDigest: await digestPath(sourceBundle),
35
+ };
36
+ }
37
+ async renameCollection(request) {
38
+ if (!Number.isSafeInteger(request.collectionPrimaryKey) || request.collectionPrimaryKey < 1) {
39
+ throw new Error("FINAL_CUT_SHADOW_COLLECTION_INVALID: collectionPrimaryKey must be a positive integer");
40
+ }
41
+ if (request.name.length === 0 || request.name.includes("\0")) {
42
+ throw new Error("FINAL_CUT_SHADOW_COLLECTION_INVALID: name must be non-empty text");
43
+ }
44
+ const databasePath = await this.resolveShadowDatabase(request.shadow, request.databaseRelativePath);
45
+ await this.assertRenameSchema(databasePath);
46
+ const beforeDigest = await digestPath(databasePath);
47
+ const backupPath = `${databasePath}.framekit-backup-${randomUUID()}`;
48
+ await copyFile(databasePath, backupPath);
49
+ const name = request.name.replaceAll("'", "''");
50
+ const sql = [
51
+ "BEGIN IMMEDIATE;",
52
+ `UPDATE ZCOLLECTION SET ZNAME = '${name}', Z_OPT = Z_OPT + 1 WHERE Z_PK = ${request.collectionPrimaryKey};`,
53
+ "SELECT changes();",
54
+ "COMMIT;",
55
+ ].join(" ");
56
+ const { stdout } = await this.run(databasePath, sql);
57
+ if (stdout.trim().split(/\s+/).at(-1) !== "1") {
58
+ throw new Error("FINAL_CUT_SHADOW_COLLECTION_NOT_FOUND: collection was not updated");
59
+ }
60
+ const integrity = (await this.run(databasePath, "PRAGMA integrity_check;")).stdout.trim();
61
+ if (integrity !== "ok") {
62
+ throw new Error("FINAL_CUT_SHADOW_INTEGRITY_FAILED: SQLite integrity check failed after mutation");
63
+ }
64
+ return { databasePath, backupPath, beforeDigest, afterDigest: await digestPath(databasePath), integrity: "ok" };
65
+ }
66
+ async resolveShadowDatabase(shadow, databaseRelativePath) {
67
+ if (isAbsolute(databaseRelativePath)) {
68
+ throw new Error("FINAL_CUT_SHADOW_DATABASE_PATH_INVALID: database path must be relative to the shadow bundle");
69
+ }
70
+ const bundle = await realpath(shadow.shadowBundlePath);
71
+ const candidate = resolve(bundle, databaseRelativePath);
72
+ if (!isWithin(bundle, candidate)) {
73
+ throw new Error("FINAL_CUT_SHADOW_DATABASE_PATH_INVALID: database path escapes the shadow bundle");
74
+ }
75
+ const database = await realpath(candidate);
76
+ if (!isWithin(bundle, database) || !database.endsWith(".fcpevent")) {
77
+ throw new Error("FINAL_CUT_SHADOW_DATABASE_PATH_INVALID: target must be a CurrentVersion.fcpevent database in the shadow bundle");
78
+ }
79
+ return database;
80
+ }
81
+ async assertRenameSchema(databasePath) {
82
+ try {
83
+ const { stdout } = await this.run(databasePath, "PRAGMA table_info('ZCOLLECTION');");
84
+ const columns = new Set(stdout.split("\n").map((line) => line.split("|")[1]).filter(Boolean));
85
+ for (const required of ["Z_PK", "Z_OPT", "ZNAME"]) {
86
+ if (!columns.has(required))
87
+ throw new Error(`missing ${required}`);
88
+ }
89
+ }
90
+ catch {
91
+ throw new Error("FINAL_CUT_SHADOW_SCHEMA_UNSUPPORTED: expected ZCOLLECTION rename schema is unavailable");
92
+ }
93
+ }
94
+ async run(databasePath, sql) {
95
+ return execFile(this.sqliteCommand, [databasePath, sql], { timeout: 30_000, maxBuffer: 1_000_000 });
96
+ }
97
+ }
98
+ function isWithin(root, path) {
99
+ const pathRelative = relative(root, path);
100
+ return pathRelative !== "" && !pathRelative.startsWith(`..${sep}`) && pathRelative !== ".." && !isAbsolute(pathRelative);
101
+ }
102
+ async function digestPath(path) {
103
+ const pathStat = await stat(path);
104
+ const digest = createHash("sha256");
105
+ if (pathStat.isDirectory()) {
106
+ for (const entry of (await readdir(path)).sort()) {
107
+ digest.update(entry);
108
+ digest.update(await digestPath(join(path, entry)));
109
+ }
110
+ return digest.digest("hex");
111
+ }
112
+ const { createReadStream } = await import("node:fs");
113
+ await new Promise((resolvePromise, reject) => {
114
+ const stream = createReadStream(path);
115
+ stream.on("data", (chunk) => { digest.update(chunk); });
116
+ stream.on("error", reject);
117
+ stream.on("end", resolvePromise);
118
+ });
119
+ return digest.digest("hex");
120
+ }