@tapedock/mcp 0.0.0-stage → 0.1.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.
@@ -0,0 +1,74 @@
1
+ import type { SessionExportFile, VcrApiClient } from "../api/client.js";
2
+ export type DownloadCategory = "bundle" | "audio" | "video" | "screen";
3
+ export declare const ALL_DOWNLOAD_CATEGORIES: DownloadCategory[];
4
+ export interface DownloadFileState {
5
+ name: string;
6
+ category: DownloadCategory;
7
+ byteSize: number;
8
+ downloadedBytes: number;
9
+ status: "pending" | "downloading" | "completed" | "skipped" | "failed";
10
+ localPath: string;
11
+ error?: string;
12
+ }
13
+ export interface DownloadJobSnapshot {
14
+ downloadId: string;
15
+ sessionId: string;
16
+ sessionTitle: string;
17
+ mode: "foreground" | "background" | "dry_run";
18
+ status: "running" | "completed" | "failed" | "dry_run";
19
+ targetDir: string;
20
+ totalBytes: number;
21
+ remainingBytes: number;
22
+ downloadedBytes: number;
23
+ startedAtMs: number;
24
+ completedAtMs: number | null;
25
+ files: DownloadFileState[];
26
+ /** Local-path DaVinci Resolve timeline, written once the job completes and session.otio is on disk. */
27
+ resolveOtioPath?: string;
28
+ error?: string;
29
+ }
30
+ export interface DownloadSessionInput {
31
+ sessionId: string;
32
+ destinationDir?: string;
33
+ createSubfolder?: boolean;
34
+ categories?: DownloadCategory[];
35
+ overwrite?: boolean;
36
+ dryRun?: boolean;
37
+ mode?: "auto" | "foreground" | "background";
38
+ }
39
+ export interface DownloadProgressCallback {
40
+ (update: {
41
+ downloadedBytes: number;
42
+ totalBytes: number;
43
+ message: string;
44
+ }): Promise<void> | void;
45
+ }
46
+ export declare function resolveDefaultDownloadDir(): string;
47
+ export declare function assertSafeExportPath(targetDir: string, filename: string): string;
48
+ export declare class DownloadManager {
49
+ private readonly api;
50
+ private readonly fetchImpl;
51
+ private readonly autoForegroundBytes;
52
+ private readonly urlRefreshMs;
53
+ private readonly concurrency;
54
+ private readonly jobs;
55
+ private readonly retryBaseDelayMs;
56
+ constructor(opts: {
57
+ api: VcrApiClient;
58
+ fetchImpl?: typeof fetch;
59
+ autoForegroundBytes?: number;
60
+ urlRefreshMs?: number;
61
+ concurrency?: number;
62
+ retryBaseDelayMs?: number;
63
+ });
64
+ private pruneOldJobs;
65
+ getJob(downloadId: string): DownloadJobSnapshot | null;
66
+ listJobs(): DownloadJobSnapshot[];
67
+ startDownload(input: DownloadSessionInput, runtimeOpts?: {
68
+ signal?: AbortSignal;
69
+ onProgress?: DownloadProgressCallback;
70
+ }): Promise<DownloadJobSnapshot>;
71
+ private executeJob;
72
+ private downloadSingleFile;
73
+ }
74
+ export type { SessionExportFile };
@@ -0,0 +1,509 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { createWriteStream } from "node:fs";
3
+ import * as fs from "node:fs/promises";
4
+ import * as os from "node:os";
5
+ import * as path from "node:path";
6
+ import { Readable, Transform } from "node:stream";
7
+ import { pipeline } from "node:stream/promises";
8
+ import { buildSessionFolderName, formatBytes } from "../lib/format.js";
9
+ import { buildLocalResolveOtio } from "./resolve-otio.js";
10
+ export const ALL_DOWNLOAD_CATEGORIES = ["bundle", "audio", "video", "screen"];
11
+ const SAFE_EXPORT_FILENAME_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
12
+ const DEFAULT_AUTO_FOREGROUND_BYTES = 100 * 1024 * 1024; // 100 MB
13
+ const DEFAULT_URL_REFRESH_MS = 45 * 60 * 1000; // 45 minutes (presigned TTL is 60 min)
14
+ const DEFAULT_CONCURRENCY = 2;
15
+ const MAX_FILE_RETRIES = 3;
16
+ const PROGRESS_THROTTLE_MS = 1500;
17
+ const MAX_STORED_JOBS = 50;
18
+ const SESSION_OTIO_FILENAME = "session.otio";
19
+ const RESOLVE_OTIO_FILENAME = "session.resolve.otio";
20
+ export function resolveDefaultDownloadDir() {
21
+ const fromEnv = process.env.TAPEDOCK_DOWNLOAD_DIR?.trim() || process.env.VCR_DOWNLOAD_DIR?.trim();
22
+ if (fromEnv)
23
+ return path.resolve(fromEnv);
24
+ return path.join(os.homedir(), "Downloads", "tapedock");
25
+ }
26
+ export function assertSafeExportPath(targetDir, filename) {
27
+ if (!filename ||
28
+ filename.includes("/") ||
29
+ filename.includes("\\") ||
30
+ filename.includes("..") ||
31
+ !SAFE_EXPORT_FILENAME_RE.test(filename)) {
32
+ throw new Error(`Unsafe export filename rejected: "${filename}"`);
33
+ }
34
+ const resolvedDir = path.resolve(targetDir);
35
+ const resolvedFile = path.resolve(resolvedDir, filename);
36
+ if (!resolvedFile.startsWith(resolvedDir + path.sep)) {
37
+ throw new Error(`Path traversal rejected for "${filename}"`);
38
+ }
39
+ return resolvedFile;
40
+ }
41
+ function parseContentRange(header) {
42
+ if (!header)
43
+ return null;
44
+ const match = header.trim().match(/^bytes\s+(\d+)-(\d+)\/(\d+|\*)$/i);
45
+ if (!match)
46
+ return null;
47
+ const start = Number(match[1]);
48
+ const end = Number(match[2]);
49
+ const total = match[3] === "*" ? -1 : Number(match[3]);
50
+ if (!Number.isFinite(start) || !Number.isFinite(end))
51
+ return null;
52
+ return { start, end, total };
53
+ }
54
+ async function abortableSleep(ms, signal) {
55
+ if (signal?.aborted)
56
+ throw new Error("Download cancelled by client.");
57
+ await new Promise((resolve, reject) => {
58
+ const onAbort = () => {
59
+ clearTimeout(timer);
60
+ reject(new Error("Download cancelled by client."));
61
+ };
62
+ const timer = setTimeout(() => {
63
+ signal?.removeEventListener("abort", onAbort);
64
+ resolve();
65
+ }, ms);
66
+ signal?.addEventListener("abort", onAbort, { once: true });
67
+ });
68
+ }
69
+ /**
70
+ * Best-effort: a missing or malformed session.otio must never fail a download that
71
+ * already landed every Track, so any error here just means no Resolve timeline.
72
+ */
73
+ async function writeLocalResolveOtio(targetDir) {
74
+ const resolvePath = path.join(targetDir, RESOLVE_OTIO_FILENAME);
75
+ const tmpPath = `${resolvePath}.${randomBytes(4).toString("hex")}.tmp`;
76
+ try {
77
+ const otioJson = await fs.readFile(path.join(targetDir, SESSION_OTIO_FILENAME), "utf8");
78
+ await fs.writeFile(tmpPath, buildLocalResolveOtio(otioJson, targetDir), { mode: 0o644 });
79
+ await fs.rename(tmpPath, resolvePath);
80
+ return resolvePath;
81
+ }
82
+ catch {
83
+ await fs.unlink(tmpPath).catch(() => { });
84
+ return undefined;
85
+ }
86
+ }
87
+ class PresignedUrlExpiredError extends Error {
88
+ failedUrl;
89
+ constructor(failedUrl) {
90
+ super("Presigned download URL expired (403)");
91
+ this.failedUrl = failedUrl;
92
+ this.name = "PresignedUrlExpiredError";
93
+ }
94
+ }
95
+ class RangeRestartError extends Error {
96
+ constructor(message) {
97
+ super(message);
98
+ this.name = "RangeRestartError";
99
+ }
100
+ }
101
+ export class DownloadManager {
102
+ api;
103
+ fetchImpl;
104
+ autoForegroundBytes;
105
+ urlRefreshMs;
106
+ concurrency;
107
+ jobs = new Map();
108
+ retryBaseDelayMs;
109
+ constructor(opts) {
110
+ this.api = opts.api;
111
+ this.fetchImpl = opts.fetchImpl ?? fetch;
112
+ this.autoForegroundBytes = opts.autoForegroundBytes ?? DEFAULT_AUTO_FOREGROUND_BYTES;
113
+ this.urlRefreshMs = opts.urlRefreshMs ?? DEFAULT_URL_REFRESH_MS;
114
+ this.concurrency = opts.concurrency ?? DEFAULT_CONCURRENCY;
115
+ this.retryBaseDelayMs = opts.retryBaseDelayMs ?? 500;
116
+ }
117
+ pruneOldJobs() {
118
+ if (this.jobs.size <= MAX_STORED_JOBS)
119
+ return;
120
+ const completed = [...this.jobs.values()]
121
+ .filter((j) => j.status !== "running")
122
+ .sort((a, b) => a.startedAtMs - b.startedAtMs);
123
+ for (const old of completed) {
124
+ if (this.jobs.size <= MAX_STORED_JOBS)
125
+ break;
126
+ this.jobs.delete(old.downloadId);
127
+ }
128
+ }
129
+ getJob(downloadId) {
130
+ const job = this.jobs.get(downloadId);
131
+ return job ? structuredClone(job) : null;
132
+ }
133
+ listJobs() {
134
+ return [...this.jobs.values()]
135
+ .sort((a, b) => b.startedAtMs - a.startedAtMs)
136
+ .map((j) => structuredClone(j));
137
+ }
138
+ async startDownload(input, runtimeOpts) {
139
+ const detail = await this.api.getSession(input.sessionId, runtimeOpts?.signal);
140
+ const { session } = detail;
141
+ if (session.mediaDeletedAt) {
142
+ throw new Error(`Media for Session "${session.title}" (${session.id}) has been permanently deleted.`);
143
+ }
144
+ if (session.status !== "ready" && session.status !== "ready_partial") {
145
+ throw new Error(`Session "${session.title}" (${session.id}) is currently "${session.status}" and exports are not ready yet.`);
146
+ }
147
+ const wantedCategories = new Set(input.categories && input.categories.length > 0 ? input.categories : ALL_DOWNLOAD_CATEGORIES);
148
+ const matchingFiles = detail.files.filter((f) => wantedCategories.has(f.category));
149
+ if (matchingFiles.length === 0) {
150
+ throw new Error(`No export files matched categories [${[...wantedCategories].join(", ")}] for Session ${session.id}.`);
151
+ }
152
+ const baseDir = input.destinationDir?.trim()
153
+ ? path.resolve(input.destinationDir.trim())
154
+ : resolveDefaultDownloadDir();
155
+ const createSubfolder = input.createSubfolder !== false;
156
+ const targetDir = createSubfolder
157
+ ? path.join(baseDir, buildSessionFolderName(session))
158
+ : baseDir;
159
+ const overwrite = Boolean(input.overwrite);
160
+ const fileStates = [];
161
+ const urlByName = new Map();
162
+ let totalBytes = 0;
163
+ let remainingBytes = 0;
164
+ for (const file of matchingFiles) {
165
+ const localPath = assertSafeExportPath(targetDir, file.name);
166
+ urlByName.set(file.name, file.downloadUrl);
167
+ totalBytes += file.byteSize;
168
+ let alreadyComplete = false;
169
+ if (!overwrite) {
170
+ try {
171
+ const stat = await fs.stat(localPath);
172
+ if (stat.isFile() && stat.size === file.byteSize) {
173
+ alreadyComplete = true;
174
+ }
175
+ }
176
+ catch {
177
+ // file does not exist
178
+ }
179
+ }
180
+ if (alreadyComplete) {
181
+ fileStates.push({
182
+ name: file.name,
183
+ category: file.category,
184
+ byteSize: file.byteSize,
185
+ downloadedBytes: file.byteSize,
186
+ status: "skipped",
187
+ localPath,
188
+ });
189
+ }
190
+ else {
191
+ remainingBytes += file.byteSize;
192
+ fileStates.push({
193
+ name: file.name,
194
+ category: file.category,
195
+ byteSize: file.byteSize,
196
+ downloadedBytes: 0,
197
+ status: "pending",
198
+ localPath,
199
+ });
200
+ }
201
+ }
202
+ const downloadId = `dl_${randomBytes(6).toString("hex")}`;
203
+ const now = Date.now();
204
+ if (input.dryRun) {
205
+ return {
206
+ downloadId,
207
+ sessionId: session.id,
208
+ sessionTitle: session.title,
209
+ mode: "dry_run",
210
+ status: "dry_run",
211
+ targetDir,
212
+ totalBytes,
213
+ remainingBytes,
214
+ downloadedBytes: totalBytes - remainingBytes,
215
+ startedAtMs: now,
216
+ completedAtMs: now,
217
+ files: fileStates,
218
+ };
219
+ }
220
+ const requestedMode = input.mode ?? "auto";
221
+ const resolvedMode = requestedMode === "foreground"
222
+ ? "foreground"
223
+ : requestedMode === "background"
224
+ ? "background"
225
+ : remainingBytes <= this.autoForegroundBytes
226
+ ? "foreground"
227
+ : "background";
228
+ const job = {
229
+ downloadId,
230
+ sessionId: session.id,
231
+ sessionTitle: session.title,
232
+ mode: resolvedMode,
233
+ status: "running",
234
+ targetDir,
235
+ totalBytes,
236
+ remainingBytes,
237
+ downloadedBytes: totalBytes - remainingBytes,
238
+ startedAtMs: now,
239
+ completedAtMs: null,
240
+ files: fileStates,
241
+ };
242
+ this.jobs.set(downloadId, job);
243
+ this.pruneOldJobs();
244
+ const runPromise = this.executeJob(job, {
245
+ urlByName,
246
+ urlsFetchedAtMs: now,
247
+ overwrite,
248
+ signal: resolvedMode === "foreground" ? runtimeOpts?.signal : undefined,
249
+ onProgress: resolvedMode === "foreground" ? runtimeOpts?.onProgress : undefined,
250
+ });
251
+ if (resolvedMode === "background") {
252
+ void runPromise.catch(() => { });
253
+ return structuredClone(job);
254
+ }
255
+ await runPromise;
256
+ return structuredClone(job);
257
+ }
258
+ async executeJob(job, ctx) {
259
+ const jobController = new AbortController();
260
+ const onParentAbort = () => jobController.abort();
261
+ if (ctx.signal) {
262
+ if (ctx.signal.aborted) {
263
+ jobController.abort();
264
+ }
265
+ else {
266
+ ctx.signal.addEventListener("abort", onParentAbort, { once: true });
267
+ }
268
+ }
269
+ let finished = false;
270
+ try {
271
+ await fs.mkdir(job.targetDir, { recursive: true });
272
+ const pending = job.files.filter((f) => f.status === "pending");
273
+ let nextIdx = 0;
274
+ let lastProgressAt = 0;
275
+ let lastProgressBytes = -1;
276
+ let refreshPromise = null;
277
+ const emitProgress = async (currentFile, force = false) => {
278
+ const bytes = job.files.reduce((sum, f) => sum + f.downloadedBytes, 0);
279
+ // Always keep top-level downloadedBytes current (including background jobs!)
280
+ job.downloadedBytes = bytes;
281
+ if (!ctx.onProgress || finished || jobController.signal.aborted)
282
+ return;
283
+ const now = Date.now();
284
+ if (!force && now - lastProgressAt < PROGRESS_THROTTLE_MS)
285
+ return;
286
+ // MCP progress values MUST strictly increase on every notification
287
+ if (bytes <= lastProgressBytes && lastProgressBytes >= 0)
288
+ return;
289
+ lastProgressAt = now;
290
+ lastProgressBytes = bytes;
291
+ await ctx.onProgress({
292
+ downloadedBytes: bytes,
293
+ totalBytes: Math.max(job.totalBytes, 1),
294
+ message: `Downloading ${currentFile} (${formatBytes(bytes)} / ${formatBytes(job.totalBytes)})`,
295
+ });
296
+ };
297
+ const refreshPresignedUrls = async () => {
298
+ if (!refreshPromise) {
299
+ refreshPromise = (async () => {
300
+ const refreshed = await this.api.getSession(job.sessionId, jobController.signal);
301
+ for (const f of refreshed.files) {
302
+ ctx.urlByName.set(f.name, f.downloadUrl);
303
+ }
304
+ ctx.urlsFetchedAtMs = Date.now();
305
+ })().finally(() => {
306
+ refreshPromise = null;
307
+ });
308
+ }
309
+ return refreshPromise;
310
+ };
311
+ let firstError = null;
312
+ const worker = async () => {
313
+ while (!jobController.signal.aborted) {
314
+ const idx = nextIdx++;
315
+ if (idx >= pending.length)
316
+ return;
317
+ const file = pending[idx];
318
+ file.status = "downloading";
319
+ try {
320
+ await this.downloadSingleFile(file, {
321
+ getUrl: async (failedUrl) => {
322
+ const currentUrl = ctx.urlByName.get(file.name);
323
+ const needsRefresh = (failedUrl !== undefined && currentUrl === failedUrl) ||
324
+ Date.now() - ctx.urlsFetchedAtMs >= this.urlRefreshMs;
325
+ if (needsRefresh) {
326
+ await refreshPresignedUrls();
327
+ }
328
+ const url = ctx.urlByName.get(file.name);
329
+ if (!url)
330
+ throw new Error(`Missing download URL for ${file.name}`);
331
+ return url;
332
+ },
333
+ overwrite: ctx.overwrite,
334
+ signal: jobController.signal,
335
+ onChunk: async () => {
336
+ await emitProgress(file.name, false);
337
+ },
338
+ });
339
+ file.status = "completed";
340
+ file.downloadedBytes = file.byteSize;
341
+ await emitProgress(file.name, false);
342
+ }
343
+ catch (err) {
344
+ file.status = "failed";
345
+ file.error = err instanceof Error ? err.message : String(err);
346
+ if (!firstError) {
347
+ firstError = err;
348
+ }
349
+ jobController.abort();
350
+ return;
351
+ }
352
+ }
353
+ };
354
+ const workerCount = Math.min(this.concurrency, Math.max(1, pending.length));
355
+ await Promise.allSettled(Array.from({ length: workerCount }, () => worker()));
356
+ if (firstError) {
357
+ throw firstError;
358
+ }
359
+ if (jobController.signal.aborted) {
360
+ throw new Error("Download cancelled by client.");
361
+ }
362
+ job.downloadedBytes = job.files.reduce((sum, f) => sum + f.downloadedBytes, 0);
363
+ await emitProgress("Complete", true);
364
+ finished = true;
365
+ const resolveOtioPath = await writeLocalResolveOtio(job.targetDir);
366
+ if (resolveOtioPath)
367
+ job.resolveOtioPath = resolveOtioPath;
368
+ job.status = "completed";
369
+ job.completedAtMs = Date.now();
370
+ }
371
+ catch (err) {
372
+ finished = true;
373
+ jobController.abort();
374
+ job.status = "failed";
375
+ job.completedAtMs = Date.now();
376
+ job.error = err instanceof Error ? err.message : String(err);
377
+ if (job.mode === "foreground") {
378
+ throw err;
379
+ }
380
+ }
381
+ finally {
382
+ ctx.signal?.removeEventListener("abort", onParentAbort);
383
+ }
384
+ }
385
+ async downloadSingleFile(file, opts) {
386
+ const partPath = `${file.localPath}.part`;
387
+ let lastExpiredUrl;
388
+ let lastError;
389
+ for (let attempt = 0; attempt <= MAX_FILE_RETRIES; attempt++) {
390
+ if (opts.signal.aborted) {
391
+ throw new Error("Download cancelled by client.");
392
+ }
393
+ try {
394
+ let resumeOffset = 0;
395
+ if (opts.overwrite && attempt === 0) {
396
+ await fs.unlink(partPath).catch(() => { });
397
+ }
398
+ else {
399
+ try {
400
+ const st = await fs.stat(partPath);
401
+ if (st.isFile() && st.size > 0 && st.size < file.byteSize) {
402
+ resumeOffset = st.size;
403
+ }
404
+ else if (st.isFile() && st.size >= file.byteSize) {
405
+ await fs.unlink(partPath).catch(() => { });
406
+ }
407
+ }
408
+ catch {
409
+ resumeOffset = 0;
410
+ }
411
+ }
412
+ const url = await opts.getUrl(lastExpiredUrl);
413
+ lastExpiredUrl = undefined;
414
+ const headers = {};
415
+ if (resumeOffset > 0) {
416
+ headers.Range = `bytes=${resumeOffset}-`;
417
+ }
418
+ const resp = await this.fetchImpl(url, { headers, signal: opts.signal });
419
+ if (resp.status === 403) {
420
+ await resp.body?.cancel().catch(() => { });
421
+ throw new PresignedUrlExpiredError(url);
422
+ }
423
+ if (resp.status === 416 && resumeOffset > 0) {
424
+ await resp.body?.cancel().catch(() => { });
425
+ await fs.unlink(partPath).catch(() => { });
426
+ throw new RangeRestartError(`HTTP 416 Range not satisfiable for ${file.name}; restarting from byte 0`);
427
+ }
428
+ if (!resp.ok) {
429
+ await resp.body?.cancel().catch(() => { });
430
+ throw new Error(`HTTP ${resp.status} downloading ${file.name}`);
431
+ }
432
+ let appendMode = false;
433
+ if (resumeOffset > 0) {
434
+ if (resp.status === 206) {
435
+ const cr = parseContentRange(resp.headers.get("content-range"));
436
+ if (cr && cr.start === resumeOffset && (cr.total === -1 || cr.total === file.byteSize)) {
437
+ appendMode = true;
438
+ }
439
+ else {
440
+ await resp.body?.cancel().catch(() => { });
441
+ await fs.unlink(partPath).catch(() => { });
442
+ throw new RangeRestartError(`Mismatched Content-Range for ${file.name}; restarting from byte 0`);
443
+ }
444
+ }
445
+ else if (resp.status === 200) {
446
+ resumeOffset = 0;
447
+ appendMode = false;
448
+ }
449
+ }
450
+ file.downloadedBytes = resumeOffset;
451
+ if (!resp.body) {
452
+ if (file.byteSize === 0) {
453
+ await fs.writeFile(partPath, Buffer.alloc(0), { mode: 0o644 });
454
+ }
455
+ else {
456
+ throw new Error(`Empty response body downloading ${file.name}`);
457
+ }
458
+ }
459
+ else {
460
+ const ws = createWriteStream(partPath, {
461
+ flags: appendMode ? "a" : "w",
462
+ mode: 0o644,
463
+ });
464
+ const nodeReadable = Readable.fromWeb(resp.body);
465
+ const progressTransform = new Transform({
466
+ transform(chunk, _encoding, callback) {
467
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
468
+ file.downloadedBytes += buf.byteLength;
469
+ Promise.resolve(opts.onChunk())
470
+ .then(() => callback(null, buf))
471
+ .catch((e) => callback(e instanceof Error ? e : new Error(String(e))));
472
+ },
473
+ });
474
+ await pipeline(nodeReadable, progressTransform, ws, { signal: opts.signal });
475
+ }
476
+ const finalStat = await fs.stat(partPath);
477
+ if (finalStat.size !== file.byteSize) {
478
+ throw new Error(`Incomplete download for ${file.name}: expected ${file.byteSize} bytes, got ${finalStat.size}`);
479
+ }
480
+ // Flush to disk before atomic rename into final Resolve-ready location
481
+ const fh = await fs.open(partPath, "r+");
482
+ try {
483
+ await fh.sync();
484
+ }
485
+ finally {
486
+ await fh.close();
487
+ }
488
+ await fs.rename(partPath, file.localPath);
489
+ return;
490
+ }
491
+ catch (err) {
492
+ lastError = err;
493
+ if (opts.signal.aborted)
494
+ throw err;
495
+ if (err instanceof PresignedUrlExpiredError) {
496
+ lastExpiredUrl = err.failedUrl;
497
+ }
498
+ if (attempt >= MAX_FILE_RETRIES) {
499
+ throw err;
500
+ }
501
+ const delayMs = err instanceof PresignedUrlExpiredError || err instanceof RangeRestartError
502
+ ? 50
503
+ : this.retryBaseDelayMs * 2 ** attempt;
504
+ await abortableSleep(delayMs, opts.signal);
505
+ }
506
+ }
507
+ throw lastError ?? new Error(`Failed downloading ${file.name} after retries.`);
508
+ }
509
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Turn a downloaded `session.otio` into a DaVinci Resolve 21 timeline whose media
3
+ * references point at absolute paths inside `targetDir`, so File → Import → Timeline
4
+ * links every Track without a relink pass. Throws on malformed JSON, a non-Timeline
5
+ * root, or any `target_url` that resolves outside `targetDir`.
6
+ */
7
+ export declare function buildLocalResolveOtio(otioJson: string, targetDir: string): string;
@@ -0,0 +1,68 @@
1
+ import * as path from "node:path";
2
+ const URL_SCHEME_RE = /^[a-z][a-z0-9+.-]*:\/\//i;
3
+ const ITEM_SCHEMAS = new Set(["Stack", "Track", "Clip", "Gap"]);
4
+ function isObject(value) {
5
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6
+ }
7
+ function schemaName(node) {
8
+ const schema = node.OTIO_SCHEMA;
9
+ return typeof schema === "string" ? (schema.split(".")[0] ?? null) : null;
10
+ }
11
+ function localizeTargetUrl(targetUrl, resolvedDir) {
12
+ if (URL_SCHEME_RE.test(targetUrl)) {
13
+ throw new Error(`Non-local target_url rejected: "${targetUrl}"`);
14
+ }
15
+ const resolved = path.resolve(resolvedDir, targetUrl);
16
+ if (!resolved.startsWith(resolvedDir + path.sep)) {
17
+ throw new Error(`Path traversal rejected for target_url "${targetUrl}"`);
18
+ }
19
+ return resolved;
20
+ }
21
+ function normalize(value, resolvedDir) {
22
+ if (Array.isArray(value)) {
23
+ for (const item of value)
24
+ normalize(item, resolvedDir);
25
+ return;
26
+ }
27
+ if (!isObject(value))
28
+ return;
29
+ const schema = schemaName(value);
30
+ if (schema === "Clip") {
31
+ // Legacy Clip.2 carried a single `media_reference`; Resolve 21 only reads the keyed map.
32
+ if ("media_reference" in value && !("media_references" in value)) {
33
+ value.media_references = { DEFAULT_MEDIA: value.media_reference };
34
+ delete value.media_reference;
35
+ }
36
+ if ("media_references" in value) {
37
+ value.active_media_reference_key ??= "DEFAULT_MEDIA";
38
+ }
39
+ }
40
+ if (schema !== null && ITEM_SCHEMAS.has(schema)) {
41
+ value.metadata ??= {};
42
+ value.effects ??= [];
43
+ value.markers ??= [];
44
+ value.enabled ??= true;
45
+ }
46
+ if (schema === "Timeline" || schema === "ExternalReference") {
47
+ value.metadata ??= {};
48
+ }
49
+ if (schema === "ExternalReference" && typeof value.target_url === "string") {
50
+ value.target_url = localizeTargetUrl(value.target_url, resolvedDir);
51
+ }
52
+ for (const child of Object.values(value))
53
+ normalize(child, resolvedDir);
54
+ }
55
+ /**
56
+ * Turn a downloaded `session.otio` into a DaVinci Resolve 21 timeline whose media
57
+ * references point at absolute paths inside `targetDir`, so File → Import → Timeline
58
+ * links every Track without a relink pass. Throws on malformed JSON, a non-Timeline
59
+ * root, or any `target_url` that resolves outside `targetDir`.
60
+ */
61
+ export function buildLocalResolveOtio(otioJson, targetDir) {
62
+ const timeline = JSON.parse(otioJson);
63
+ if (!isObject(timeline) || schemaName(timeline) !== "Timeline") {
64
+ throw new Error("session.otio root is not an OTIO Timeline.");
65
+ }
66
+ normalize(timeline, path.resolve(targetDir));
67
+ return JSON.stringify(timeline, null, 2) + "\n";
68
+ }
@@ -0,0 +1,31 @@
1
+ export declare function normalizeOrigin(raw?: string | null): string;
2
+ export declare function parseIsoToMs(iso: string, fieldName?: string): number;
3
+ /**
4
+ * Parse a Marker timecode ("HH:MM:SS", "HH:MM:SS.mmm", "MM:SS", or raw seconds like "95.5") into milliseconds.
5
+ */
6
+ export declare function parseTimecodeToMs(raw: string): number;
7
+ export declare function formatBytes(bytes: number): string;
8
+ export declare function sanitizeFolderSegment(raw: string): string;
9
+ export declare function buildSessionFolderName(session: {
10
+ id: string;
11
+ title: string;
12
+ startedAtMs?: number | null;
13
+ createdAt?: number | null;
14
+ }): string;
15
+ export declare function formatScheduledTimeUtc(ms: number): string;
16
+ export declare function buildInviteBlurb(input: {
17
+ sessionTitle: string;
18
+ hostName: string;
19
+ guestName?: string | null;
20
+ scheduledStartAtMs?: number | null;
21
+ inviteUrl: string;
22
+ }): string;
23
+ export declare function buildSessionIcs(input: {
24
+ sessionId: string;
25
+ sessionTitle: string;
26
+ hostName: string;
27
+ roomName: string;
28
+ scheduledStartAtMs: number;
29
+ inviteUrl: string;
30
+ durationMinutes?: number;
31
+ }): string;