Skip to content

Open source CapCut alternative.

TypeScript
28.6 KB
Raw Blame
// The browser shelf's library: reusable media outside any project, held in
// this page's own storage. Handlers answer the engine's `/api/cut/library`
// routes (`server/http/library.ts`) with the same JSON, so a call site can't
// tell which shelf it reached.
//
// The whole shelf is one index file next to a media folder. Templates keep
// private copies of their media here, the way the engine's do, so a template
// stays whole after the project it came from is gone.
//
// Not owned here: `import-url`, `presign` and `complete`. A page can't fetch a
// video off a link, so that import runs on the cloud worker and the bytes are
// adopted afterwards (`lib/library.ts`); those paths fall through to the
// hosted twin.
import { resolveParent, settleParents, subtreeOf } from "../../folderTree";
import { libraryTypeOf } from "../../libraryFileType";
import { itemName } from "../../itemName";
import type {
  AssetType,
  LibraryTemplate,
  TemplateAudio,
  TemplateLayer,
  TemplateMedia,
} from "../../types";
import * as store from "./opfs";
import { registerBlobFile, registeredUrl, revokeRegistered } from "./registry";
import { caught, err, json, serveFile } from "./respond";
import { UserError } from "../../userError";

const INDEX_FILE = "library.json";

export const libraryMediaApiPath = (fileName: string) =>
  `/api/cut/library/media/${encodeURIComponent(fileName)}`;

const projectMediaApiPath = (id: string, fileName: string) =>
  `/api/cut/projects/${id}/media/${encodeURIComponent(fileName)}`;

/** Where a URL-imported asset came from, kept as notes on the asset. */
type LibrarySource = {
  url: string;
  title?: string;
  uploader?: string;
  uploadDate?: string;
};

type StoredAsset = {
  id: string;
  fileName: string;
  name: string;
  type: AssetType;
  duration: number;
  width?: number;
  height?: number;
  addedAt: number;
  folderId?: string | null;
  source?: LibrarySource;
  /** The source's cover image, stored beside the media and served by the same
   * route — an import from a site that publishes one carries it. */
  posterFile?: string;
  /** The playable copy of a master this browser cannot decode (a ProRes
   * file), built beside it; what the shelf's cards and viewer play. */
  proxyFile?: string;
  /** A linked item's identity, computed by the page before the file was
   * shelved; a LUT's row also says what kind of table it holds. */
  contentKey?: string;
  lut?: { kind: "1d" | "3d" | "shaper+3d"; size: number };
};

type StoredFolder = {
  id: string;
  name: string;
  /** The folder this one is filed in; null (or absent, from before nesting)
   * is the top level. */
  parentId?: string | null;
  createdAt: number;
};

type LibraryIndex = {
  version: 1;
  assets: StoredAsset[];
  folders: StoredFolder[];
  templates: LibraryTemplate[];
};

const EMPTY: LibraryIndex = {
  version: 1,
  assets: [],
  folders: [],
  templates: [],
};

async function readIndex(): Promise<LibraryIndex> {
  const idx = await store.readJson<LibraryIndex>(
    await store.libraryDir(),
    INDEX_FILE,
  );
  if (!idx) return EMPTY;
  return {
    version: 1,
    assets: Array.isArray(idx.assets) ? idx.assets : [],
    folders: Array.isArray(idx.folders) ? idx.folders : [],
    templates: Array.isArray(idx.templates) ? idx.templates : [],
  };
}

/** Read-modify-write the shelf under the store lock, so two tabs filing items
 * at once can't clobber each other's index. */
async function mutateIndex<T>(fn: (idx: LibraryIndex) => T): Promise<T> {
  return store.withStoreLock("library", async () => {
    const dir = await store.libraryDir(true);
    if (!dir) throw new UserError("browser_storage_unavailable", "Browser storage is unavailable.");
    const idx = await readIndex();
    const result = fn(idx);
    await store.writeFileAt(dir, INDEX_FILE, JSON.stringify(idx));
    return result;
  });
}

function parseField<T>(value: FormDataEntryValue | null): T | null {
  if (typeof value !== "string" || !value) return null;
  try {
    return JSON.parse(value) as T;
  } catch {
    return null;
  }
}

/** Mint the blob URL for a library file so `backend.url()` answers for it
 * without awaiting. */
async function register(fileName: string, file?: File | null): Promise<void> {
  const path = libraryMediaApiPath(fileName);
  if (registeredUrl(path)) return;
  const bytes =
    file ?? (await store.readFileAt(await store.libraryMediaDir(), fileName));
  if (bytes) registerBlobFile(path, bytes);
}

/** The whole shelf, with every file it holds registered so cards, players and
 * download links resolve synchronously. */
async function list(): Promise<Response> {
  const idx = await readIndex();
  for (const name of new Set([
    ...idx.assets.map((a) => a.fileName),
    ...idx.assets.flatMap((a) => (a.posterFile ? [a.posterFile] : [])),
    ...idx.assets.flatMap((a) => (a.proxyFile ? [a.proxyFile] : [])),
    ...idx.templates.flatMap((t) => t.media.map((m) => m.fileName)),
  ])) {
    await register(name);
  }
  return json({
    assets: [...idx.assets].sort((a, b) => b.addedAt - a.addedAt),
    folders: settleParents(idx.folders).sort((a, b) => a.createdAt - b.createdAt),
    templates: [...idx.templates].sort((a, b) => b.addedAt - a.addedAt),
  });
}

/** What the page sends alongside a file it has already measured or checked. */
type UploadMeta = {
  type?: AssetType;
  duration?: number;
  width?: number;
  height?: number;
  contentKey?: string;
  lut?: StoredAsset["lut"];
};

/** Write the row for a file already stored in the library. */
async function addAsset(
  fileName: string,
  name: string,
  meta: UploadMeta | null,
  source?: LibrarySource | null,
  posterFile?: string,
): Promise<StoredAsset> {
  const type = meta?.type ?? libraryTypeOf(fileName);
  if (!type) throw new UserError("file_type_unsupported", "Unsupported file type.");
  const asset: StoredAsset = {
    id: crypto.randomUUID().slice(0, 8),
    fileName,
    name,
    type,
    duration: meta?.duration ?? 0,
    ...(meta?.width && meta?.height
      ? { width: meta.width, height: meta.height }
      : {}),
    addedAt: Date.now(),
    folderId: null,
    ...(source ? { source } : {}),
    ...(posterFile ? { posterFile } : {}),
    ...(typeof meta?.contentKey === "string" ? { contentKey: meta.contentKey } : {}),
    ...(meta?.lut ? { lut: meta.lut } : {}),
  };
  await mutateIndex((idx) => {
    idx.assets.push(asset);
  });
  return asset;
}

/**
 * Upload straight onto the shelf. The page probes the file before sending it
 * (`meta`), because nothing here can read a duration out of stored bytes the
 * way the engine's ffprobe can.
 */
async function upload(req: Request): Promise<Response> {
  try {
    const form = await req.formData();
    const file = form.get("file");
    if (!(file instanceof File)) return err("No file in upload.", 400);
    const nameField = form.get("name");
    const name =
      typeof nameField === "string" && nameField.trim()
        ? nameField.trim()
        : file.name;
    const meta = parseField<UploadMeta>(form.get("meta"));
    const source = parseField<LibrarySource>(form.get("source"));
    if (!(meta?.type ?? libraryTypeOf(file.name)))
      return err(new UserError("file_type_unsupported", "Unsupported file type."), 400);
    const fileName = await store.saveLibraryMedia(file, file.name);
    await register(fileName, file);
    // An import carries the source's cover alongside the media; it is stored
    // like any other library file and named after the media it belongs to.
    const posterField = form.get("poster");
    let posterFile: string | undefined;
    if (posterField instanceof File) {
      const ext = posterField.name.match(/\.[a-z0-9]+$/i)?.[0] ?? ".jpg";
      posterFile = await store.saveLibraryMedia(
        posterField,
        `${fileName}.poster${ext}`,
      );
      await register(posterFile, posterField);
    }
    return json(await addAsset(fileName, name, meta, source, posterFile));
  } catch (e) {
    return caught(e, new UserError("upload_failed", "Upload failed."));
  }
}

async function serveMedia(
  fileName: string,
  download: boolean,
): Promise<Response> {
  const file = await store.readFileAt(await store.libraryMediaDir(), fileName);
  if (!file) return err(new UserError("media_file_not_found", "Media file not found."), 404);
  await register(fileName, file);
  return serveFile(file, fileName, download);
}

/** Take the assets in `ids` out of the index, handing back the files they
 * own — the source and its poster — for the caller to drop once the index
 * is written. */
function takeAssets(idx: LibraryIndex, ids: ReadonlySet<string>): string[] {
  const files: string[] = [];
  idx.assets = idx.assets.filter((a) => {
    if (!ids.has(a.id)) return true;
    files.push(a.fileName);
    if (a.posterFile) files.push(a.posterFile);
    if (a.proxyFile) files.push(a.proxyFile);
    return false;
  });
  return files;
}

/** Take the templates in `ids` out of the index, handing back their media
 * copies, which are private to them. */
function takeTemplates(idx: LibraryIndex, ids: ReadonlySet<string>): string[] {
  const files: string[] = [];
  idx.templates = idx.templates.filter((t) => {
    if (!ids.has(t.id)) return true;
    for (const m of t.media ?? []) files.push(m.fileName);
    return false;
  });
  return files;
}

/** Drop files the index no longer names, with the blob URLs minted for them. */
async function dropFiles(files: string[]): Promise<void> {
  for (const f of files) {
    await store.deleteLibraryMedia(f);
    revokeRegistered(libraryMediaApiPath(f));
  }
}

async function removeAsset(id: string): Promise<Response> {
  try {
    const files = await mutateIndex((idx) => {
      if (!idx.assets.some((a) => a.id === id)) throw new UserError("library_asset_not_found", "Library asset not found.");
      return takeAssets(idx, new Set([id]));
    });
    await dropFiles(files);
    return json({ ok: true });
  } catch (e) {
    return caught(e, new UserError("library_delete_failed", "Could not delete."));
  }
}

/**
 * Build the playable copy of a video this browser cannot decode (a ProRes
 * master) beside it, and name it on the asset: in this page when it has a
 * 10-bit encoder, else on the Mac's engine when the app is there. With
 * neither, the ask fails and says so.
 */
async function makeProxy(req: Request, id: string): Promise<Response> {
  try {
    const { maxHeight, crf, compat: asked } = (await req.json()) as { maxHeight?: number; crf?: number; compat?: unknown };
    if (!Number.isFinite(maxHeight) || !Number.isFinite(crf)) return err("maxHeight and crf are required.", 400);
    const { compatCoverIn, compatCovers, compatProxyNameFor } = await import("../../proxyNames");
    const compat = compatCoverIn(asked);
    const asset = (await readIndex()).assets.find((a) => a.id === id);
    if (!asset) return err(new UserError("library_asset_not_found", "Library asset not found."), 404);
    if (asset.type !== "video") return err(new UserError("playable_copy_video_only", "Only a video takes a playable copy."), 400);
    const dir = await store.libraryMediaDir(true);
    if (!dir) return err(new UserError("browser_storage_unavailable", "Browser storage is unavailable."), 500);
    const held = asset.proxyFile;
    const answers = !!held && (!compat || compatCovers(held, compat));
    if (held && answers && (await store.readFileAt(dir, held))) return json(asset);
    const master = await store.readFileAt(dir, asset.fileName);
    if (!master) return err(new UserError("media_file_not_found", "Media file not found."), 404);

    // Loaded on the ask: the encoder pulls in the decoders and the muxer.
    const { encodeProxyInPage, proxyNameFor, proxyOnTheMac } = await import("../../proxyEncode");
    const { probeMediaColor } = await import("../../mediaRead");
    const { code } = await probeMediaColor(master);
    const from = { matrix: code.matrix, fullRange: code.fullRange };
    let fileName: string | undefined;
    if (compat) {
      // A picture this browser cannot decode has nothing to encode from in
      // the page; the worker builds the compat copy by way of the cloud shelf.
      const { compatInTheCloud } = await import("../../cloudLibraryUpload");
      const blob = await compatInTheCloud(new File([master], asset.fileName), compat);
      fileName = await store.saveLibraryMedia(blob, compatProxyNameFor(asset.fileName, compat, false));
    } else {
      fileName = (await encodeProxyInPage(master, from, dir, asset.fileName, maxHeight!, () => {}))?.fileName;
    }
    if (!fileName) {
      const blob = await proxyOnTheMac(async () => master, asset.fileName, maxHeight!, crf!);
      if (!blob) return err(new UserError("playable_copy_needs_app", "This browser can't make a playable copy of this video. Open the Donkey app to make one."), 422);
      fileName = await store.saveLibraryMedia(blob, proxyNameFor(asset.fileName));
    }
    const landed = fileName;
    try {
      // The asset may have been deleted while the copy was built.
      const updated = await mutateIndex((idx) => {
        const live = idx.assets.find((a) => a.id === id);
        if (!live) throw new UserError("library_asset_not_found", "Library asset not found.");
        live.proxyFile = landed;
        return live;
      });
      await register(landed);
      // The copy this browser could not play leaves with its name.
      if (held && held !== landed) await dropFiles([held]);
      return json(updated);
    } catch (e) {
      await dropFiles([landed]);
      throw e;
    }
  } catch (e) {
    return caught(e, new UserError("playable_copy_make_failed", "Could not make the playable copy."));
  }
}

async function move(req: Request): Promise<Response> {
  try {
    const { id, folderId } = (await req.json()) as {
      id: string;
      folderId: string | null;
    };
    await mutateIndex((idx) => {
      const item =
        idx.assets.find((a) => a.id === id) ??
        idx.templates.find((t) => t.id === id);
      if (!item) throw new UserError("library_item_not_found", "Library item not found.");
      if (folderId && !idx.folders.some((f) => f.id === folderId)) {
        throw new UserError("folder_not_found", "Folder not found.");
      }
      item.folderId = folderId ?? null;
    });
    return json({ ok: true });
  } catch (e) {
    return caught(e, new UserError("library_item_move_failed", "Could not move item."));
  }
}

async function createFolder(req: Request): Promise<Response> {
  try {
    const { name, parentId } = (await req.json()) as {
      name?: string;
      parentId?: string | null;
    };
    const trimmed = (name ?? "").trim();
    if (!trimmed) return err(new UserError("folder_name_required", "Folder name required."), 500);
    const id = crypto.randomUUID().slice(0, 8);
    return json(
      await mutateIndex((idx) => {
        const folder: StoredFolder = {
          id,
          name: trimmed.slice(0, 80),
          parentId: resolveParent(idx.folders, id, parentId),
          createdAt: Date.now(),
        };
        idx.folders.push(folder);
        return folder;
      }),
    );
  } catch (e) {
    return caught(e, new UserError("folder_create_failed", "Could not create folder."));
  }
}

/** Rename a folder, file it under another (null for the top level), or
 * both; a key left out keeps what the folder has. */
async function updateFolder(req: Request, id: string): Promise<Response> {
  try {
    const { name, parentId } = (await req.json()) as {
      name?: string;
      parentId?: string | null;
    };
    const trimmed = name?.trim();
    if (name !== undefined && !trimmed) return err(new UserError("folder_name_required", "Folder name required."), 500);
    return json(
      await mutateIndex((idx) => {
        const folder = idx.folders.find((f) => f.id === id);
        if (!folder) throw new UserError("folder_not_found", "Folder not found.");
        if (trimmed) folder.name = trimmed.slice(0, 80);
        if (parentId !== undefined) {
          folder.parentId = resolveParent(idx.folders, id, parentId);
        }
        return folder;
      }),
    );
  } catch (e) {
    return caught(e, new UserError("folder_update_failed", "Could not update folder."));
  }
}

/** Delete a folder and everything in it: the folders filed under it, however
 * deep, and every asset and template they hold, in one write of the index. */
async function deleteFolder(id: string): Promise<Response> {
  try {
    const files = await mutateIndex((idx) => {
      if (!idx.folders.some((f) => f.id === id)) return [];
      const tree = new Set(subtreeOf(idx.folders, id));
      const filed = (x: { folderId?: string | null }) => !!x.folderId && tree.has(x.folderId);
      const assets = new Set(idx.assets.filter(filed).map((a) => a.id));
      const templates = new Set(idx.templates.filter(filed).map((t) => t.id));
      idx.folders = idx.folders.filter((f) => !tree.has(f.id));
      return [...takeAssets(idx, assets), ...takeTemplates(idx, templates)];
    });
    await dropFiles(files);
    return json({ ok: true });
  } catch (e) {
    return caught(e, new UserError("folder_delete_failed", "Could not delete folder."));
  }
}

/** Copy a library file into a project's media folder. */
async function copyIntoProject(
  projectId: string,
  fileName: string,
): Promise<string> {
  const file = await store.readFileAt(await store.libraryMediaDir(), fileName);
  if (!file) throw new UserError("library_file_not_found", "Library file not found.");
  const stored = await store.saveMedia(projectId, file, fileName);
  registerBlobFile(projectMediaApiPath(projectId, stored), file);
  return stored;
}

/** Copy a project's media file onto the shelf. */
async function copyFromProject(
  projectId: string,
  fileName: string,
): Promise<string> {
  const file = await store.readFileAt(
    await store.mediaDir(projectId),
    fileName,
  );
  if (!file) throw new UserError("project_media_not_found", "Media file not found in project.");
  const stored = await store.saveLibraryMedia(file, fileName);
  await register(stored, file);
  return stored;
}

async function addToProject(req: Request): Promise<Response> {
  try {
    const { assetId, projectId } = (await req.json()) as {
      assetId: string;
      projectId: string;
    };
    const asset = (await readIndex()).assets.find((a) => a.id === assetId);
    if (!asset) return err(new UserError("library_asset_not_found", "Library asset not found."), 404);
    if (!(await store.readDoc(projectId)))
      return err(new UserError("project_not_found", "Project not found."), 404);
    return json({ fileName: await copyIntoProject(projectId, asset.fileName) });
  } catch (e) {
    return caught(e, new UserError("library_add_failed", "Could not add from library."));
  }
}

/**
 * Save a project's media file onto the shelf. The doc is right here, so the
 * asset's own row supplies the dimensions and duration the page would
 * otherwise have to re-probe.
 */
async function saveFromProject(req: Request): Promise<Response> {
  try {
    const { projectId, fileName, name } = (await req.json()) as {
      projectId: string;
      fileName: string;
      name?: string;
    };
    const doc = await store.readDoc(projectId);
    if (!doc) return err(new UserError("project_not_found", "Project not found."), 404);
    const known = doc.assets.find((a) => a.fileName === fileName);
    const stored = await copyFromProject(projectId, fileName);
    return json(
      await addAsset(stored, name || fileName, {
        type: known?.type as AssetType | undefined,
        duration: known?.duration,
        width: known?.width,
        height: known?.height,
      }),
    );
  } catch (e) {
    return caught(e, new UserError("library_save_failed", "Could not save to library."));
  }
}

// --- templates: selections saved by reference, media copied in privately ---

type TemplateInput = {
  name: string;
  duration: number;
  media: TemplateMedia[];
  layers: TemplateLayer[];
  audio: TemplateAudio[];
  texts: LibraryTemplate["texts"];
  cues: LibraryTemplate["cues"];
  sound?: LibraryTemplate["sound"];
  grade?: LibraryTemplate["grade"];
};

/** A template with nothing on it saves nothing; a sound preset or a saved
 * grade is a template carrying only its treatment. */
const templateEmpty = (input: TemplateInput) =>
  !input.media?.length && !input.texts?.length && !input.cues?.length && !input.sound && !input.grade;

async function saveTemplate(req: Request): Promise<Response> {
  try {
    const { projectId, ...input } = (await req.json()) as {
      projectId: string;
    } & TemplateInput;
    if (!(await store.readDoc(projectId)))
      return err(new UserError("project_not_found", "Project not found."), 404);
    if (templateEmpty(input)) return err(new UserError("template_nothing_to_save", "Nothing to save."), 500);
    const media: TemplateMedia[] = [];
    for (const m of input.media ?? []) {
      media.push({
        ...m,
        fileName: await copyFromProject(projectId, m.fileName),
      });
    }
    const template: LibraryTemplate = {
      id: crypto.randomUUID().slice(0, 8),
      name: (input.name || "Template").trim().slice(0, 80),
      addedAt: Date.now(),
      duration: input.duration,
      media,
      layers: input.layers ?? [],
      audio: input.audio ?? [],
      texts: input.texts ?? [],
      cues: input.cues ?? [],
      ...(input.sound ? { sound: input.sound } : {}),
      ...(input.grade ? { grade: input.grade } : {}),
    };
    await mutateIndex((idx) => {
      idx.templates.push(template);
    });
    return json(template);
  } catch (e) {
    return caught(e, new UserError("template_save_failed", "Could not save the template."));
  }
}

/** Take in a template carried off another shelf: its doc, and its media as
 * files in the doc's order — `layers` and `audio` point at `media` by index, so
 * only the file names change. */
async function importTemplate(req: Request): Promise<Response> {
  try {
    const form = await req.formData();
    const input = parseField<TemplateInput & { folderId?: string | null }>(
      form.get("doc"),
    );
    if (!input) return err("No template in the request.", 400);
    const files = form
      .getAll("file")
      .filter((f): f is File => f instanceof File);
    const media: TemplateMedia[] = [];
    for (const [i, m] of (input.media ?? []).entries()) {
      const file = files[i];
      if (!file) return err(new UserError("template_media_missing", "Template media missing."), 400);
      const fileName = await store.saveLibraryMedia(
        file,
        m.fileName || file.name,
      );
      await register(fileName, file);
      media.push({ ...m, fileName });
    }
    const template: LibraryTemplate = {
      id: crypto.randomUUID().slice(0, 8),
      name: (input.name || "Template").trim().slice(0, 80),
      addedAt: Date.now(),
      duration: input.duration,
      media,
      layers: input.layers ?? [],
      audio: input.audio ?? [],
      texts: input.texts ?? [],
      cues: input.cues ?? [],
      ...(input.sound ? { sound: input.sound } : {}),
      ...(input.grade ? { grade: input.grade } : {}),
      folderId: input.folderId ?? null,
    };
    await mutateIndex((idx) => {
      idx.templates.push(template);
    });
    return json(template);
  } catch (e) {
    return caught(e, new UserError("template_add_failed", "Could not add the template."));
  }
}

async function materializeTemplate(
  req: Request,
  id: string,
): Promise<Response> {
  try {
    const { projectId } = (await req.json()) as { projectId: string };
    if (!(await store.readDoc(projectId)))
      return err(new UserError("project_not_found", "Project not found."), 404);
    const template = (await readIndex()).templates.find((t) => t.id === id);
    if (!template) return err(new UserError("template_not_found", "Template not found."), 404);
    const media: TemplateMedia[] = [];
    for (const m of template.media) {
      media.push({
        ...m,
        fileName: await copyIntoProject(projectId, m.fileName),
      });
    }
    return json({ template, media });
  } catch (e) {
    return caught(e, new UserError("template_add_failed", "Could not add the template."));
  }
}

async function addToTemplate(req: Request, id: string): Promise<Response> {
  try {
    const { projectId, media, layer, audio, extend } = (await req.json()) as {
      projectId: string;
      media: TemplateMedia;
      layer?: Omit<TemplateLayer, "media" | "start">;
      audio?: Omit<TemplateAudio, "media" | "start">;
      extend: number;
    };
    const stored = await copyFromProject(projectId, media.fileName);
    try {
      return json(
        await mutateIndex((idx) => {
          const t = idx.templates.find((x) => x.id === id);
          if (!t) throw new UserError("template_not_found", "Template not found.");
          const mi = t.media.length;
          t.media = [...t.media, { ...media, fileName: stored }];
          if (audio)
            t.audio = [...t.audio, { ...audio, media: mi, start: t.duration }];
          else if (layer)
            t.layers = [
              ...t.layers,
              { ...layer, media: mi, start: t.duration },
            ];
          t.duration += extend;
          return t;
        }),
      );
    } catch (e) {
      await store.deleteLibraryMedia(stored);
      throw e;
    }
  } catch (e) {
    return caught(e, new UserError("template_append_failed", "Could not add to the template."));
  }
}

async function renameTemplate(req: Request, id: string): Promise<Response> {
  try {
    const { name } = (await req.json()) as { name?: string };
    const next = itemName(name);
    return json(
      await mutateIndex((idx) => {
        const template = idx.templates.find((t) => t.id === id);
        if (!template) throw new UserError("template_not_found", "Template not found.");
        template.name = next;
        return template;
      }),
    );
  } catch (e) {
    return caught(e, new UserError("template_rename_failed", "Could not rename the template."));
  }
}

async function renameAsset(req: Request, id: string): Promise<Response> {
  try {
    const { name } = (await req.json()) as { name?: string };
    const next = itemName(name);
    return json(
      await mutateIndex((idx) => {
        const asset = idx.assets.find((a) => a.id === id);
        if (!asset) throw new UserError("library_asset_not_found", "Library asset not found.");
        asset.name = next;
        return asset;
      }),
    );
  } catch (e) {
    return caught(e, new UserError("file_rename_failed", "Could not rename the file."));
  }
}

async function deleteTemplate(id: string): Promise<Response> {
  try {
    const files = await mutateIndex((idx) => takeTemplates(idx, new Set([id])));
    await dropFiles(files);
    return json({ ok: true });
  } catch (e) {
    return caught(e, new UserError("template_delete_failed", "Could not delete the template."));
  }
}

/**
 * Serve one `/api/cut/library/...` request against this browser's shelf.
 * `rest` is the path past `library`. Returns null for the paths the shelf
 * doesn't own, which the driver proxies to the hosted twin.
 */
export async function dispatchLibraryRoute(
  rest: string[],
  method: string,
  req: () => Request,
  download: boolean,
): Promise<Response | null> {
  // /library
  if (rest.length === 0) {
    if (method === "GET") return list();
    if (method === "POST") return upload(req());
    return err("Method not allowed.", 405);
  }

  // /library/media/:file
  if (rest[0] === "media" && rest.length === 2) {
    if (method === "GET") return serveMedia(rest[1], download);
    return err("Method not allowed.", 405);
  }

  if (rest[0] === "folders") {
    if (rest.length === 1 && method === "POST") return createFolder(req());
    if (rest.length === 2 && method === "PUT")
      return updateFolder(req(), rest[1]);
    if (rest.length === 2 && method === "DELETE") return deleteFolder(rest[1]);
    return err("Not found.", 404);
  }

  if (rest[0] === "templates") {
    if (rest.length === 1 && method === "POST") return saveTemplate(req());
    if (rest.length === 2 && rest[1] === "import" && method === "POST")
      return importTemplate(req());
    if (rest.length === 2 && method === "PUT")
      return renameTemplate(req(), rest[1]);
    if (rest.length === 2 && method === "DELETE")
      return deleteTemplate(rest[1]);
    if (rest.length === 3 && method === "POST") {
      if (rest[2] === "use") return materializeTemplate(req(), rest[1]);
      if (rest[2] === "add") return addToTemplate(req(), rest[1]);
    }
    return err("Not found.", 404);
  }

  if (rest.length === 1 && method === "POST") {
    if (rest[0] === "move") return move(req());
    if (rest[0] === "use") return addToProject(req());
    if (rest[0] === "save") return saveFromProject(req());
    // import-url, presign, complete: the cloud's, not this shelf's.
    return null;
  }

  // /library/:id/proxy
  if (rest.length === 2 && rest[1] === "proxy" && method === "POST") return makeProxy(req(), rest[0]);

  // /library/:id
  if (rest.length === 1 && method === "DELETE") return removeAsset(rest[0]);
  if (rest.length === 1 && method === "PUT") return renameAsset(req(), rest[0]);
  return null;
}