Open source CapCut alternative.
TypeScript
// Copy a project between backends: read the source doc, create the target
// project, move every media file's bytes across (in doc order — the fresh
// target dedupes only against names this copy already claimed), remap asset
// fileNames, save the doc, and carry the chat history. A failure deletes the
// half-made copy. Shared by the projects home's "Duplicate to cloud/Mac" and
// the editor's move.
import type { CutBackend } from "./backend/types";
import { fetchCloudThreads, putCloudThread } from "./chatCloud";
import { loadProjectThreads, mergeThreads, readProjectThreads, writeProjectThreads } from "./chatThreads";
import { ensureLinkedOnCloud, linkedIdsIn } from "./linkedLibrary";
import { uploadProjectMediaTo } from "./media";
import { localMediaFile } from "./mediaSync";
import type { ProjectDoc, StoredAsset } from "./types";
import { compatCoverOf } from "./proxyNames";
import { UserError } from "./userError";
/** Move a project's conversations onto the copy.
*
* Chat-created media belongs to a thread: it rides the doc like any other
* asset, but only its thread shows it, and only deleting that thread deletes
* it. A copy that took the media and left the conversations behind would hold
* media nobody can see, delete, or account for — while it still counts against
* the account's storage. So the threads travel with it. */
async function copyChatThreads(
src: CutBackend,
dst: CutBackend,
srcProjectId: string,
dstProjectId: string
): Promise<void> {
await loadProjectThreads(srcProjectId);
const threads = mergeThreads(
await fetchCloudThreads(src, srcProjectId),
readProjectThreads(srcProjectId)
);
if (threads.length === 0) return;
writeProjectThreads(dstProjectId, threads);
for (const thread of threads) {
await putCloudThread(dst, dstProjectId, thread);
}
}
export async function copyProjectAcross(
src: CutBackend,
dst: CutBackend,
projectId: string,
opts: {
/** Target name from the source doc's name; defaults to keeping it. */
rename?: (docName: string) => string;
/** Called per media file as its bytes land on the target. */
onProgress?: (done: number, total: number) => void;
} = {}
): Promise<string> {
let created: string | null = null;
try {
const docRes = await src.fetch(`/api/cut/projects/${projectId}`);
if (!docRes.ok) throw new UserError("project_read_failed", "Could not read the project.");
const doc = (await docRes.json()) as ProjectDoc;
const name = opts.rename ? opts.rename(doc.name ?? "") : (doc.name ?? "");
const createRes = await dst.fetch("/api/cut/projects", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name }),
});
const summary = (await createRes.json()) as { id?: string };
if (!createRes.ok || !summary.id) throw new UserError("project_creation_failed", "Could not create the project.");
created = summary.id;
const assets = Array.isArray(doc.assets) ? doc.assets : [];
const names = new Map<string, string>();
// A preview proxy travels with its master to a Mac or a browser. The
// cloud writes proxies only through its worker — they are the one
// quota-exempt media there — so a copy landing in the cloud leaves the
// proxy behind and asks the worker for a new one once the doc is saved.
const carryProxies = dst.kind !== "cloud";
const files = assets.flatMap((a) => [
{ fileName: a.fileName, name: a.name },
...(carryProxies && a.proxy ? [{ fileName: a.proxy.fileName, name: a.name }] : []),
]);
const unique = new Set(files.map((f) => f.fileName)).size;
for (const f of files) {
if (names.has(f.fileName)) continue;
// A cloud project's media may exist only in this browser's store so far
// (an import the lazy upload hasn't drained — a full account's, say).
// The local copy is the same write-once bytes, and for the undrained
// file it is the only copy, so it is read first; the network serves the
// rest.
const local = src.kind === "cloud" ? await localMediaFile(projectId, f.fileName) : null;
let blob: Blob;
if (local) {
blob = local;
} else {
const bytes = await src.fetch(
`/api/cut/projects/${projectId}/media/${encodeURIComponent(f.fileName)}`
);
if (!bytes.ok) throw new UserError("media_read_failed", `Could not read “${f.name}”.`, { name: f.name });
blob = await bytes.blob();
}
names.set(f.fileName, await uploadProjectMediaTo(dst, summary.id, blob, f.fileName));
opts.onProgress?.(names.size, unique);
}
// A project moving to the cloud takes what it links to with it: a render
// job reads the cloud shelf alone, so a title set in a font that lives only
// on this Mac would come out in the fallback face once it renders there.
// Linked ids are the bytes, so nothing in the document changes.
if (dst.kind === "cloud") await ensureLinkedOnCloud(linkedIdsIn(doc));
const copied: ProjectDoc = {
...doc,
// The copy is a new project; the target backend stamps its own id.
id: undefined,
name,
folderId: null,
assets: assets.map((a) => {
const { proxy, ...rest } = a;
const copied: StoredAsset = { ...rest, fileName: names.get(a.fileName) ?? a.fileName };
if (proxy && carryProxies) {
copied.proxy = { ...proxy, fileName: names.get(proxy.fileName) ?? proxy.fileName };
}
return copied;
}),
};
const putRes = await dst.fetch(`/api/cut/projects/${summary.id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(copied),
});
if (!putRes.ok) throw new UserError("project_doc_save_failed", "Could not save the project.");
await copyChatThreads(src, dst, projectId, summary.id);
if (!carryProxies) {
// The worker builds the proxies the copy left behind; the editor writes
// each onto its asset when the project is next opened.
for (const a of assets) {
if (!a.proxy) continue;
// A compat proxy is asked for as the cover it was.
const compat = compatCoverOf(a.proxy.fileName);
void dst
.fetch(`/api/cut/projects/${summary.id}/proxy`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ file: names.get(a.fileName) ?? a.fileName, ...(compat ? { compat } : {}) }),
})
.catch(() => {});
}
}
return summary.id;
} catch (e) {
if (created) {
void dst.fetch(`/api/cut/projects/${created}`, { method: "DELETE" }).catch(() => {});
}
throw e;
}
}