Skip to content

Production-ready animations, transitions, backgrounds, and scenes for Remotion

chore: drop the dead render pipeline, build with a Dockerfile

kapishdimac8f399138257
diff --git a/.dockerignore b/.dockerignore
index 219da599..6fdbedd5 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -5,10 +5,6 @@ node_modules
.omc
.claude
-# Generated inside the Docker build (RUN bun run bundle:remotion) — never copy a
-# local/stale bundle in.
-.remotion-bundle
-
# Local env + misc
.env*
*.tsbuildinfo
diff --git a/.gitignore b/.gitignore
index 0958d105..062f06f5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -43,9 +43,6 @@ next-env.d.ts
# fumadocs generated source
.source/
-# remotion pre-bundle (generated by `bun run bundle:remotion` / Docker build)
-.remotion-bundle/
-
.omc
articles
diff --git a/Dockerfile b/Dockerfile
index a3c5dbe4..14edb936 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,66 +1,37 @@
-# Coolify builds this image. Debian (bookworm) — NOT Alpine — because Remotion's
-# headless Chromium needs glibc. Single stage; the Chrome Headless Shell and the
-# pre-bundled Remotion serveUrl are baked in so renders start fast at boot.
+# Coolify builds this image (Dockerfile build pack). Node 22 runs `next build`
+# and `next start`; bun is the package manager. Every base image comes from
+# Docker Hub and is cached on the server, so a build doesn't depend on GitHub.
FROM node:22-bookworm-slim
-ENV DEBIAN_FRONTEND=noninteractive \
- NODE_ENV=production \
+ENV NEXT_TELEMETRY_DISABLED=1 \
PORT=3000
-# Chromium runtime libraries + base fonts needed by @remotion/renderer.
-RUN apt-get update && apt-get install -y --no-install-recommends \
- ca-certificates \
- fonts-liberation \
- libasound2 \
- libatk-bridge2.0-0 \
- libatk1.0-0 \
- libcups2 \
- libdbus-1-3 \
- libdrm2 \
- libgbm1 \
- libgtk-3-0 \
- libnss3 \
- libpango-1.0-0 \
- libxcomposite1 \
- libxdamage1 \
- libxfixes3 \
- libxkbcommon0 \
- libxrandr2 \
- && rm -rf /var/lib/apt/lists/*
-
-# Bun (the repo's package manager + runtime) — copied from the official image.
-COPY --from=oven/bun:1 /usr/local/bin/bun /usr/local/bin/bun
+COPY --from=oven/bun:1.4.2 /usr/local/bin/bun /usr/local/bin/bun
WORKDIR /app
-# Install deps first for better layer caching. Requires bun.lock to match
-# package.json — run `bun install` locally after dependency changes and commit
-# the updated lockfile before building.
+# Dependencies get their own layer, reused until bun.lock changes. Scripts are
+# skipped because the root postinstall (fumadocs-mdx) needs the sources; it runs
+# after the COPY below.
COPY package.json bun.lock ./
-RUN bun install --frozen-lockfile
+RUN --mount=type=cache,target=/root/.bun/install/cache \
+ bun install --frozen-lockfile --ignore-scripts
-# App source + build.
COPY . .
+RUN bun run postinstall
-# The /showcases pages are prerendered, so the build itself fetches the manager
-# and fails loudly when it can't reach it. Coolify only forwards this to the
-# build when the variable is marked as a *build* variable in its UI — a plain
-# runtime variable is not enough. ENV also carries the value into the running
-# image as a default; a runtime variable of the same name still overrides it.
+# Read while prerendering. Coolify passes these only when they are marked as
+# *build* variables in its UI. /showcases fails the build without
+# SHOWCASES_API_URL; the OpenPanel keys feed the sponsors traffic numbers.
ARG SHOWCASES_API_URL
-ENV SHOWCASES_API_URL=$SHOWCASES_API_URL
-
-RUN bun run build
+ARG NEXT_PUBLIC_OPENPANEL_CLIENT_ID
+ARG NEXT_PUBLIC_OPENPANEL_API_URL
+ARG OPENPANEL_CLIENT_SECRET
+ARG OPENPANEL_PUBLIC_DASHBOARD_URL
-# Bake the Chrome Headless Shell into the image (no slow runtime download).
-# Uses @remotion/renderer's ensureBrowser() — the `remotion` pkg has no CLI bin
-# (that's @remotion/cli, which we don't install), so `bunx remotion ...` fails.
-RUN bun run remotion:browser
-
-# Pre-bundle the Remotion entry → .remotion-bundle/ (serveUrl ready at boot).
-RUN bun run bundle:remotion
+# .next/cache survives between builds, so Next recompiles only what changed.
+RUN --mount=type=cache,target=/app/.next/cache bun run build
+ENV NODE_ENV=production
EXPOSE 3000
-
-# next start (matches `bun run start` in package.json).
CMD ["bun", "run", "start"]
diff --git a/app/api/render/[jobId]/download/route.ts b/app/api/render/[jobId]/download/route.ts
deleted file mode 100644
index bbefc244..00000000
--- a/app/api/render/[jobId]/download/route.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-import { createReadStream } from "node:fs";
-import { stat } from "node:fs/promises";
-import path from "node:path";
-import { Readable } from "node:stream";
-import { deleteJobFile } from "@/lib/server/cleanup";
-import { RENDER_WORK_DIR } from "@/lib/server/paths";
-import { getJob } from "@/lib/server/render-queue";
-
-// Node runtime: streams a file off disk via node:fs.
-export const runtime = "nodejs";
-
-/** Job ids are crypto.randomUUID()s — accept only that exact shape. */
-const JOB_ID_RE =
- /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
-
-/**
- * GET /api/render/[jobId]/download
- *
- * Streams the finished MP4 (Content-Type video/mp4, attachment), then schedules
- * the file for deletion. 404 if the job/file is unknown; 410 if the render isn't
- * done yet or the file has already been swept.
- */
-export async function GET(
- _request: Request,
- { params }: { params: Promise<{ jobId: string }> },
-) {
- const { jobId } = await params;
-
- // Path-traversal guard: build the path from a validated id only.
- if (!JOB_ID_RE.test(jobId)) {
- return jsonError(404, "Unknown render job.", "not_found");
- }
-
- const job = getJob(jobId);
- if (!job) {
- return jsonError(404, "Unknown render job.", "not_found");
- }
- if (job.status !== "done") {
- return jsonError(410, "Render is not ready for download.", "not_ready");
- }
-
- const filePath = path.join(RENDER_WORK_DIR, `${jobId}.mp4`);
- let size: number;
- try {
- size = (await stat(filePath)).size;
- } catch {
- return jsonError(410, "Render file has expired.", "expired");
- }
-
- const nodeStream = createReadStream(filePath);
- // Schedule cleanup once the file has been fully read out.
- nodeStream.on("close", () => {
- void deleteJobFile(jobId);
- });
-
- const webStream = Readable.toWeb(
- nodeStream,
- ) as unknown as ReadableStream<Uint8Array>;
-
- return new Response(webStream, {
- status: 200,
- headers: {
- "Content-Type": "video/mp4",
- "Content-Length": String(size),
- "Content-Disposition": `attachment; filename="${downloadName(job.repo)}"`,
- "Cache-Control": "no-store",
- },
- });
-}
-
-/** Safe, repo-derived filename, e.g. "vercel-next.js-stars.mp4". */
-function downloadName(repo: string): string {
- const slug = repo
- .toLowerCase()
- .replace(/[^a-z0-9._-]+/g, "-")
- .replace(/^-+|-+$/g, "")
- .slice(0, 80);
- return `${slug || "github"}-stars.mp4`;
-}
-
-function jsonError(status: number, error: string, code: string): Response {
- return new Response(JSON.stringify({ error, code }), {
- status,
- headers: { "Content-Type": "application/json" },
- });
-}
diff --git a/app/api/render/[jobId]/route.ts b/app/api/render/[jobId]/route.ts
deleted file mode 100644
index 17538e8f..00000000
--- a/app/api/render/[jobId]/route.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { NextResponse } from "next/server";
-
-import { getJob } from "@/lib/server/render-queue";
-
-// Node runtime: shares the in-memory job registry with the render route.
-export const runtime = "nodejs";
-
-/**
- * GET /api/render/[jobId]
- *
- * Poll a render's progress. Returns:
- * { status, progress, downloadUrl?, error? }
- * where status is "queued" | "rendering" | "done" | "error", progress is in
- * [0, 1], `downloadUrl` is present only when done, and `error` only on failure.
- * 404 `{ error, code }` for an unknown job.
- */
-export async function GET(
- _request: Request,
- { params }: { params: Promise<{ jobId: string }> },
-) {
- const { jobId } = await params;
- const job = getJob(jobId);
-
- if (!job) {
- return NextResponse.json(
- { error: "Unknown render job.", code: "not_found" },
- { status: 404 },
- );
- }
-
- return NextResponse.json({
- status: job.status,
- progress: job.progress,
- ...(job.status === "done"
- ? { downloadUrl: `/api/render/${jobId}/download` }
- : {}),
- ...(job.status === "error" ? { error: job.error } : {}),
- });
-}
diff --git a/app/api/render/__tests__/route.test.ts b/app/api/render/__tests__/route.test.ts
deleted file mode 100644
index f76ffc46..00000000
--- a/app/api/render/__tests__/route.test.ts
+++ /dev/null
@@ -1,509 +0,0 @@
-/**
- * Unit tests for app/api/render/route.ts (POST /api/render)
- * app/api/render/[jobId]/route.ts (GET /api/render/[jobId])
- *
- * Run with: bunx vitest run app/api/render/__tests__/route.test.ts
- *
- * enqueueRender, checkRateLimit, getJob, and ensureCleanupSweep are all mocked
- * so no real renders, rate-buckets, or filesystem ops occur.
- */
-
-import { afterEach, describe, expect, it, mock } from "bun:test";
-import type { JobState } from "@/lib/server/render-queue";
-
-// ---------------------------------------------------------------------------
-// Mocks — must be declared before importing the route handlers.
-// ---------------------------------------------------------------------------
-
-const mockEnqueue = mock();
-const mockGetJob = mock();
-const mockCheckRate = mock();
-
-mock.module("server-only", () => ({}));
-
-class MockQueueFullError extends Error {
- constructor() {
- super("Render queue is full");
- this.name = "QueueFullError";
- }
-}
-
-mock.module("@/lib/server/render-queue", () => ({
- enqueueRender: mockEnqueue,
- getJob: mockGetJob,
- QueueFullError: MockQueueFullError,
-}));
-
-mock.module("@/lib/server/rate-limit", () => ({
- checkRateLimit: mockCheckRate,
-}));
-
-mock.module("@/lib/server/cleanup", () => ({
- ensureCleanupSweep: mock(),
-}));
-
-// validate-input is NOT mocked: we use the real parser so the route's
-// validation path is exercised end-to-end.
-
-// ---------------------------------------------------------------------------
-// Imports (after mocks)
-// ---------------------------------------------------------------------------
-
-const { POST } = await import("@/app/api/render/route");
-const { GET } = await import("@/app/api/render/[jobId]/route");
-
-afterEach(() => {
- mockEnqueue.mockClear();
- mockGetJob.mockClear();
- mockCheckRate.mockClear();
-});
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-/** Build a minimal NextRequest-compatible Request for POST /api/render. */
-function makePostRequest(
- body: unknown,
- ip = "1.2.3.4",
- extraHeaders?: Record<string, string>,
-): Request {
- return new Request("http://localhost/api/render", {
- method: "POST",
- headers: {
- "content-type": "application/json",
- "x-forwarded-for": ip,
- ...extraHeaders,
- },
- body: typeof body === "string" ? body : JSON.stringify(body),
- });
-}
-
-/** A valid render payload that passes parseRenderInput. */
-function validPayload(
- overrides?: Record<string, unknown>,
-): Record<string, unknown> {
- return {
- repo: "vercel/next.js",
- totalStars: 50_000,
- stargazers: [
- {
- login: "bob",
- avatarUrl: "https://avatars.githubusercontent.com/u/2",
- starredAt: "2022-06-15",
- },
- ],
- orientation: "horizontal",
- ...overrides,
- };
-}
-
-/** Build a GET request for /api/render/[jobId]. */
-function makeGetRequest(jobId: string): Request {
- return new Request(`http://localhost/api/render/${jobId}`);
-}
-
-/** Resolve params the same way Next.js does for dynamic routes. */
-function makeGetParams(jobId: string): { params: Promise<{ jobId: string }> } {
- return { params: Promise.resolve({ jobId }) };
-}
-
-// ---------------------------------------------------------------------------
-// POST /api/render — 429 rate limited
-// ---------------------------------------------------------------------------
-
-describe("POST /api/render — 429 rate limited", () => {
- it("returns 429 with code rate_limited when checkRateLimit returns false", async () => {
- mockCheckRate.mockReturnValue(false);
-
- const res = await POST(makePostRequest(validPayload()) as never);
-
- expect(res.status).toBe(429);
- const body = await res.json();
- expect(body.code).toBe("rate_limited");
- expect(mockEnqueue).not.toHaveBeenCalled();
- });
-
- it("does not include any absolute path in a 429 response body", async () => {
- mockCheckRate.mockReturnValue(false);
- const res = await POST(makePostRequest(validPayload()) as never);
- const text = await res.text();
- expect(text).not.toMatch(/\/(Users|home|var|tmp)\//);
- });
-});
-
-// ---------------------------------------------------------------------------
-// POST /api/render — 400 invalid JSON
-// ---------------------------------------------------------------------------
-
-describe("POST /api/render — 400 invalid JSON", () => {
- it("returns 400 with code invalid_json when body is not valid JSON", async () => {
- mockCheckRate.mockReturnValue(true);
-
- const res = await POST(
- new Request("http://localhost/api/render", {
- method: "POST",
- headers: {
- "content-type": "application/json",
- "x-forwarded-for": "1.2.3.4",
- },
- body: "{ not valid json !!!",
- }) as never,
- );
-
- expect(res.status).toBe(400);
- const body = await res.json();
- expect(body.code).toBe("invalid_json");
- expect(mockEnqueue).not.toHaveBeenCalled();
- });
-});
-
-// ---------------------------------------------------------------------------
-// POST /api/render — 400 invalid input
-// ---------------------------------------------------------------------------
-
-describe("POST /api/render — 400 invalid input", () => {
- it("returns 400 with code invalid_input when orientation is wrong", async () => {
- mockCheckRate.mockReturnValue(true);
-
- const res = await POST(
- makePostRequest(validPayload({ orientation: "diagonal" })) as never,
- );
-
- expect(res.status).toBe(400);
- const body = await res.json();
- expect(body.code).toBe("invalid_input");
- expect(mockEnqueue).not.toHaveBeenCalled();
- });
-
- it("returns 400 with code invalid_input when body is a non-object (array)", async () => {
- mockCheckRate.mockReturnValue(true);
-
- const res = await POST(makePostRequest([1, 2, 3]) as never);
-
- expect(res.status).toBe(400);
- const body = await res.json();
- expect(body.code).toBe("invalid_input");
- });
-
- it("returns 400 with code invalid_input when stargazers exceeds 60", async () => {
- mockCheckRate.mockReturnValue(true);
- const many = Array.from({ length: 61 }, (_, i) => ({
- login: `user${i}`,
- avatarUrl: `https://example.com/u/${i}`,
- starredAt: "2021-01-01",
- }));
-
- const res = await POST(
- makePostRequest(validPayload({ stargazers: many })) as never,
- );
-
- expect(res.status).toBe(400);
- const body = await res.json();
- expect(body.code).toBe("invalid_input");
- });
-
- it("returns 400 with code invalid_input when repo is missing", async () => {
- mockCheckRate.mockReturnValue(true);
- const payload = validPayload();
- delete payload.repo;
-
- const res = await POST(makePostRequest(payload) as never);
-
- expect(res.status).toBe(400);
- const body = await res.json();
- expect(body.code).toBe("invalid_input");
- });
-
- it("does not leak absolute paths in invalid_input error message", async () => {
- mockCheckRate.mockReturnValue(true);
- const res = await POST(
- makePostRequest(validPayload({ orientation: "sideways" })) as never,
- );
- const text = await res.text();
- expect(text).not.toMatch(/\/(Users|home|var|tmp)\//);
- });
-});
-
-// ---------------------------------------------------------------------------
-// POST /api/render — 202 success
-// ---------------------------------------------------------------------------
-
-describe("POST /api/render — 202 success", () => {
- it("returns 202 with { jobId } on a valid request", async () => {
- mockCheckRate.mockReturnValue(true);
- mockEnqueue.mockReturnValue("test-job-id-abc");
-
- const res = await POST(makePostRequest(validPayload()) as never);
-
- expect(res.status).toBe(202);
- const body = await res.json();
- expect(body).toEqual({ jobId: "test-job-id-abc" });
- });
-
- it("calls enqueueRender with the parsed input (not raw body)", async () => {
- mockCheckRate.mockReturnValue(true);
- mockEnqueue.mockReturnValue("job-xyz");
-
- await POST(makePostRequest(validPayload({ speed: 10 })) as never); // speed 10 → clamped to 4
-
- expect(mockEnqueue).toHaveBeenCalledOnce();
- const calledWith = mockEnqueue.mock.calls[0][0];
- expect(calledWith.speed).toBe(4); // clamped
- expect(calledWith.accentColor).toBe("#ffbb00"); // default applied
- expect(calledWith.theme).toBe("light"); // default applied
- });
-
- it("extracts IP from x-forwarded-for header and passes it to checkRateLimit", async () => {
- mockCheckRate.mockReturnValue(true);
- mockEnqueue.mockReturnValue("job-ip-test");
-
- await POST(makePostRequest(validPayload(), "203.0.113.1") as never);
-
- expect(mockCheckRate).toHaveBeenCalledWith("203.0.113.1");
- });
-
- it("uses the LAST hop of a spoofed x-forwarded-for, not the client-controlled first hop", async () => {
- mockCheckRate.mockReturnValue(true);
- mockEnqueue.mockReturnValue("job-spoof-test");
-
- await POST(makePostRequest(validPayload(), "1.1.1.1, 9.9.9.9") as never);
-
- expect(mockCheckRate).toHaveBeenCalledWith("9.9.9.9");
- });
-
- it("prefers x-real-ip over x-forwarded-for when both are present", async () => {
- mockCheckRate.mockReturnValue(true);
- mockEnqueue.mockReturnValue("job-real-ip-test");
-
- await POST(
- makePostRequest(validPayload(), "1.1.1.1, 9.9.9.9", {
- "x-real-ip": "2.2.2.2",
- }) as never,
- );
-
- expect(mockCheckRate).toHaveBeenCalledWith("2.2.2.2");
- });
-
- it("returns only { jobId } in the 202 body — no extra fields", async () => {
- mockCheckRate.mockReturnValue(true);
- mockEnqueue.mockReturnValue("clean-job");
-
- const res = await POST(makePostRequest(validPayload()) as never);
- const body = await res.json();
- expect(Object.keys(body)).toEqual(["jobId"]);
- });
-});
-
-// ---------------------------------------------------------------------------
-// POST /api/render — 503 queue full
-// ---------------------------------------------------------------------------
-
-describe("POST /api/render — 503 queue full", () => {
- it("returns 503 with code queue_full when enqueueRender throws QueueFullError", async () => {
- mockCheckRate.mockReturnValue(true);
- mockEnqueue.mockImplementationOnce(() => {
- throw new MockQueueFullError();
- });
-
- const res = await POST(makePostRequest(validPayload()) as never);
-
- expect(res.status).toBe(503);
- const body = await res.json();
- expect(body.code).toBe("queue_full");
- });
-});
-
-// ---------------------------------------------------------------------------
-// GET /api/render/[jobId] — 404 unknown job
-// ---------------------------------------------------------------------------
-
-describe("GET /api/render/[jobId] — 404 not found", () => {
- it("returns 404 with code not_found for an unknown jobId", async () => {
- mockGetJob.mockReturnValue(undefined);
-
- const res = await GET(
- makeGetRequest("unknown-id") as never,
- makeGetParams("unknown-id"),
- );
-
- expect(res.status).toBe(404);
- const body = await res.json();
- expect(body.code).toBe("not_found");
- });
-
- it("does not leak absolute paths in a 404 response", async () => {
- mockGetJob.mockReturnValue(undefined);
- const res = await GET(
- makeGetRequest("ghost") as never,
- makeGetParams("ghost"),
- );
- const text = await res.text();
- expect(text).not.toMatch(/\/(Users|home|var|tmp)\//);
- });
-});
-
-// ---------------------------------------------------------------------------
-// GET /api/render/[jobId] — status responses
-// ---------------------------------------------------------------------------
-
-describe("GET /api/render/[jobId] — status JSON", () => {
- it("returns status=queued and progress=0 for a queued job", async () => {
- const job: JobState = {
- status: "queued",
- progress: 0,
- repo: "owner/repo",
- createdAt: Date.now(),
- };
- mockGetJob.mockReturnValue(job);
-
- const res = await GET(
- makeGetRequest("job1") as never,
- makeGetParams("job1"),
- );
-
- expect(res.status).toBe(200);
- const body = await res.json();
- expect(body.status).toBe("queued");
- expect(body.progress).toBe(0);
- expect(body.downloadUrl).toBeUndefined();
- expect(body.error).toBeUndefined();
- });
-
- it("returns status=rendering and a progress value for a rendering job", async () => {
- const job: JobState = {
- status: "rendering",
- progress: 0.42,
- repo: "owner/repo",
- createdAt: Date.now(),
- };
- mockGetJob.mockReturnValue(job);
-
- const res = await GET(
- makeGetRequest("job2") as never,
- makeGetParams("job2"),
- );
-
- const body = await res.json();
- expect(body.status).toBe("rendering");
- expect(body.progress).toBe(0.42);
- expect(body.downloadUrl).toBeUndefined();
- });
-
- it("returns status=done with downloadUrl for a finished job", async () => {
- const job: JobState = {
- status: "done",
- progress: 1,
- outputPath: "/tmp/remocn-renders/some-uuid.mp4",
- repo: "owner/repo",
- createdAt: Date.now(),
- };
- mockGetJob.mockReturnValue(job);
-
- const res = await GET(
- makeGetRequest("job3") as never,
- makeGetParams("job3"),
- );
-
- const body = await res.json();
- expect(body.status).toBe("done");
- expect(body.progress).toBe(1);
- expect(body.downloadUrl).toContain("job3");
- expect(body.downloadUrl).toContain("/api/render/");
- });
-
- it("does not expose the absolute outputPath in the done response", async () => {
- const job: JobState = {
- status: "done",
- progress: 1,
- outputPath: "/tmp/remocn-renders/secret.mp4",
- repo: "owner/repo",
- createdAt: Date.now(),
- };
- mockGetJob.mockReturnValue(job);
-
- const res = await GET(
- makeGetRequest("job3b") as never,
- makeGetParams("job3b"),
- );
- const text = await res.text();
- expect(text).not.toContain("/tmp/remocn-renders/secret.mp4");
- });
-
- it("returns status=error with an error message for a failed job", async () => {
- const job: JobState = {
- status: "error",
- progress: 0,
- error: "Chromium crashed",
- repo: "owner/repo",
- createdAt: Date.now(),
- };
- mockGetJob.mockReturnValue(job);
-
- const res = await GET(
- makeGetRequest("job4") as never,
- makeGetParams("job4"),
- );
-
- const body = await res.json();
- expect(body.status).toBe("error");
- expect(body.error).toBe("Chromium crashed");
- expect(body.downloadUrl).toBeUndefined();
- });
-
- it("does not include 'error' key in a non-error job response", async () => {
- const job: JobState = {
- status: "queued",
- progress: 0,
- repo: "owner/repo",
- createdAt: Date.now(),
- };
- mockGetJob.mockReturnValue(job);
-
- const res = await GET(
- makeGetRequest("job5") as never,
- makeGetParams("job5"),
- );
- const body = await res.json();
- expect("error" in body).toBe(false);
- });
-});
-
-// ---------------------------------------------------------------------------
-// Security: no secrets / absolute paths in any response
-// ---------------------------------------------------------------------------
-
-describe("POST + GET — no secrets or paths leak", () => {
- it("does not expose RENDER_WORK_DIR in any success response", async () => {
- process.env.RENDER_WORK_DIR = "/secret/render/dir";
- mockCheckRate.mockReturnValue(true);
- mockEnqueue.mockReturnValue("safe-job");
-
- const res = await POST(makePostRequest(validPayload()) as never);
- const text = await res.text();
- expect(text).not.toContain("/secret/render/dir");
-
- delete process.env.RENDER_WORK_DIR;
- });
-
- it("does not expose RENDER_WORK_DIR in a done job response", async () => {
- process.env.RENDER_WORK_DIR = "/secret/render/dir";
- const job: JobState = {
- status: "done",
- progress: 1,
- outputPath: "/secret/render/dir/job-abc.mp4",
- repo: "owner/repo",
- createdAt: Date.now(),
- };
- mockGetJob.mockReturnValue(job);
-
- const res = await GET(
- makeGetRequest("jobS") as never,
- makeGetParams("jobS"),
- );
- const text = await res.text();
- expect(text).not.toContain("/secret/render/dir");
-
- delete process.env.RENDER_WORK_DIR;
- });
-});
diff --git a/app/api/render/route.ts b/app/api/render/route.ts
deleted file mode 100644
index 0096f342..00000000
--- a/app/api/render/route.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-import { type NextRequest, NextResponse } from "next/server";
-import { ensureCleanupSweep } from "@/lib/server/cleanup";
-import { checkRateLimit } from "@/lib/server/rate-limit";
-import { enqueueRender, QueueFullError } from "@/lib/server/render-queue";
-import {
- parseRenderInput,
- type RenderInput,
- RenderInputError,
-} from "@/lib/server/validate-input";
-
-// Node runtime: native Remotion render (Chromium) needs full Node, not edge.
-export const runtime = "nodejs";
-
-/**
- * POST /api/render
- *
- * Body: the render props (see RenderInput) —
- * { repo, totalStars, stargazers[], orientation, accentColor?, speed?, theme? }
- *
- * Rate-limits per IP, validates the payload, enqueues a background render, and
- * returns `{ jobId }` (202) immediately. The render never blocks the request;
- * poll `GET /api/render/[jobId]` for progress. Errors: `{ error, code }`.
- */
-export async function POST(request: NextRequest) {
- // Install the TTL sweep on first request (idempotent).
- ensureCleanupSweep();
-
- const ip = clientIp(request);
- if (!checkRateLimit(ip)) {
- return NextResponse.json(
- {
- error: "Too many render requests. Please wait and retry.",
- code: "rate_limited",
- },
- { status: 429 },
- );
- }
-
- let body: unknown;
- try {
- body = await request.json();
- } catch {
- return NextResponse.json(
- { error: "Request body must be valid JSON.", code: "invalid_json" },
- { status: 400 },
- );
- }
-
- let input: RenderInput;
- try {
- input = parseRenderInput(body);
- } catch (err) {
- if (err instanceof RenderInputError) {
- return NextResponse.json(
- { error: err.message, code: "invalid_input" },
- { status: err.status },
- );
- }
- throw err;
- }
-
- let jobId: string;
- try {
- jobId = enqueueRender(input);
- } catch (err) {
- if (err instanceof QueueFullError) {
- return NextResponse.json(
- {
- error: "Render queue is full. Please retry shortly.",
- code: "queue_full",
- },
- { status: 503 },
- );
- }
- throw err;
- }
-
- return NextResponse.json({ jobId }, { status: 202 });
-}
-
-/**
- * The real client IP, trusting only what Traefik (the one proxy in front of
- * this process) sets: `x-real-ip`, or else the LAST hop of `x-forwarded-for`
- * (Traefik appends the peer; earlier hops are client-controlled and spoofable).
- */
-function clientIp(request: NextRequest): string {
- const realIp = request.headers.get("x-real-ip")?.trim();
- if (realIp) return realIp;
-
- const forwarded = request.headers.get("x-forwarded-for");
- if (forwarded) {
- const parts = forwarded.split(",");
- const last = parts[parts.length - 1]?.trim();
- if (last) return last;
- }
-
- return "unknown";
-}
diff --git a/lib/openapi.test.ts b/lib/openapi.test.ts
index 0114877b..e0d9c49e 100644
--- a/lib/openapi.test.ts
+++ b/lib/openapi.test.ts
@@ -32,7 +32,7 @@ const operations: [string, string, Operation][] = Object.entries(
),
);
-/** `/api/render/{jobId}` -> `app/api/render/[jobId]/route.ts` */
+/** `/r/{file}` -> `app/r/[file]/route.ts` */
function routeFile(path: string): string {
return join(
ROOT,
diff --git a/lib/openapi.ts b/lib/openapi.ts
index c21357f9..737c69ec 100644
--- a/lib/openapi.ts
+++ b/lib/openapi.ts
@@ -16,27 +16,19 @@ const ERROR_RESPONSE = (description: string) => ({
},
});
-const JOB_ID = {
- name: "jobId",
- in: "path",
- required: true,
- description: "Render job id returned by `createRender`.",
- schema: { type: "string", format: "uuid" },
-} as const;
-
export const OPENAPI_SPEC = {
openapi: "3.1.0",
info: {
title: "Remocn API",
version: "1.0.0",
summary:
- "Registry items, docs search and GitHub stars video renders for Remocn, the shadcn registry of Remotion components.",
+ "Registry items, docs search and GitHub stargazers for Remocn, the shadcn registry of Remotion components.",
description: [
"Public, unauthenticated HTTP API behind remocn.dev.",
"",
"- **Install components** with the shadcn CLI (`npx shadcn@latest add @remocn/<name>`); it fetches `getRegistryItem` for you.",
"- **Find components** with `getComponentIndex` (one Markdown table of every component) or `searchDocs`.",
- "- **Render a GitHub stars video**: `getStargazers` → `createRender` → poll `getRenderStatus` → `downloadRender`.",
+ "- **Get a repository's stargazers** with `getStargazers`, e.g. as props for the `github-stars` component.",
"",
`Agents can also use the remote MCP server at ${SITE_URL}/mcp (Streamable HTTP, JSON-RPC, no auth) with the tools \`search_components\`, \`get_component\`, \`plan_video\` and \`preview_component\`.`,
"",
@@ -58,9 +50,8 @@ export const OPENAPI_SPEC = {
{ name: "Registry", description: "shadcn registry items." },
{ name: "Docs", description: "Documentation for people and agents." },
{
- name: "Stars video",
- description:
- "Turn a GitHub repository's stargazers into an MP4 (the /stars page).",
+ name: "GitHub",
+ description: "GitHub data for the `github-stars` component.",
},
],
paths: {
@@ -176,10 +167,10 @@ export const OPENAPI_SPEC = {
"/api/stargazers": {
get: {
operationId: "getStargazers",
- tags: ["Stars video"],
+ tags: ["GitHub"],
summary: "Get a repository's stargazers",
description:
- "Fetches a GitHub repository's stargazers server-side and returns a downsampled list ready to pass to `createRender`.",
+ "Fetches a GitHub repository's stargazers server-side and returns a downsampled list ready to pass to the `github-stars` component.",
parameters: [
{
name: "repo",
@@ -214,99 +205,6 @@ export const OPENAPI_SPEC = {
},
},
},
- "/api/render": {
- post: {
- operationId: "createRender",
- tags: ["Stars video"],
- summary: "Start a stars video render",
- description:
- "Validates the props and queues a background render. Returns a job id immediately; poll `getRenderStatus`. Rate-limited per IP (5 requests per minute by default).",
- requestBody: {
- required: true,
- content: {
- "application/json": {
- schema: { $ref: "#/components/schemas/RenderInput" },
- },
- },
- },
- responses: {
- "202": {
- description: "Render queued.",
- content: {
- "application/json": {
- schema: {
- type: "object",
- required: ["jobId"],
- properties: {
- jobId: {
- type: "string",
- format: "uuid",
- description: "Pass to `getRenderStatus`.",
- },
- },
- },
- },
- },
- },
- "400": ERROR_RESPONSE(
- "Body is not JSON (code `invalid_json`) or breaks a field rule (code `invalid_input`; the message names the field).",
- ),
- "429": ERROR_RESPONSE(
- "Too many renders from this IP (code `rate_limited`). Wait a minute and retry.",
- ),
- "503": ERROR_RESPONSE(
- "Render queue is full (code `queue_full`). Retry shortly.",
- ),
- },
- },
- },
- "/api/render/{jobId}": {
- get: {
- operationId: "getRenderStatus",
- tags: ["Stars video"],
- summary: "Get a render's progress",
- description:
- "Poll until `status` is `done` (then follow `downloadUrl`) or `error`.",
- parameters: [JOB_ID],
- responses: {
- "200": {
- description: "The job's state.",
- content: {
- "application/json": {
- schema: { $ref: "#/components/schemas/RenderStatus" },
- },
- },
- },
- "404": ERROR_RESPONSE(
- "Unknown job (code `not_found`). Jobs live in memory and expire.",
- ),
- },
- },
- },
- "/api/render/{jobId}/download": {
- get: {
- operationId: "downloadRender",
- tags: ["Stars video"],
- summary: "Download a finished render",
- description:
- "Streams the MP4 once, then deletes it from the server. Download it as soon as `getRenderStatus` reports `done`.",
- parameters: [JOB_ID],
- responses: {
- "200": {
- description: "The rendered video.",
- content: {
- "video/mp4": {
- schema: { type: "string", contentMediaType: "video/mp4" },
- },
- },
- },
- "404": ERROR_RESPONSE("Unknown job (code `not_found`)."),
- "410": ERROR_RESPONSE(
- "Not finished yet (code `not_ready`) or already downloaded and swept (code `expired`). Start a new render.",
- ),
- },
- },
- },
},
components: {
schemas: {
@@ -414,67 +312,6 @@ export const OPENAPI_SPEC = {
},
},
},
- RenderInput: {
- type: "object",
- required: ["repo", "totalStars", "stargazers", "orientation"],
- properties: {
- repo: {
- type: "string",
- minLength: 1,
- maxLength: 200,
- description: "Shown in the video, e.g. `Remocn/remocn`.",
- },
- totalStars: {
- type: "integer",
- minimum: 0,
- maximum: 100000000,
- },
- stargazers: {
- type: "array",
- maxItems: 60,
- items: { $ref: "#/components/schemas/Stargazer" },
- },
- orientation: {
- type: "string",
- enum: ["horizontal", "vertical"],
- },
- accentColor: {
- type: "string",
- pattern: "^#[0-9a-fA-F]{3,8}$",
- default: "#ffbb00",
- },
- speed: {
- type: "number",
- minimum: 1,
- maximum: 4,
- default: 1,
- },
- theme: {
- type: "string",
- enum: ["light", "dark"],
- default: "light",
- },
- },
- },
- RenderStatus: {
- type: "object",
- required: ["status", "progress"],
- properties: {
- status: {
- type: "string",
- enum: ["queued", "rendering", "done", "error"],
- },
- progress: { type: "number", minimum: 0, maximum: 1 },
- downloadUrl: {
- type: "string",
- description: "Present when `status` is `done`.",
- },
- error: {
- type: "string",
- description: "Present when `status` is `error`.",
- },
- },
- },
},
},
} as const;
diff --git a/lib/server/__tests__/cleanup.test.ts b/lib/server/__tests__/cleanup.test.ts
deleted file mode 100644
index e3726155..00000000
--- a/lib/server/__tests__/cleanup.test.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import { describe, expect, it, mock, spyOn } from "bun:test";
-import * as fsPromises from "node:fs/promises";
-import type { RenderInput } from "@/lib/server/validate-input";
-
-const mockRender = mock();
-
-mock.module("@/lib/server/render", () => ({
- renderStarsVideo: mockRender,
-}));
-
-spyOn(fsPromises, "mkdir").mockResolvedValue(undefined);
-
-mock.module("server-only", () => ({}));
-
-function makeInput(repo = "owner/repo"): RenderInput {
- return {
- repo,
- totalStars: 100,
- stargazers: [
- {
- login: "alice",
- avatarUrl: "https://avatars.githubusercontent.com/u/1",
- starredAt: "2021-01-01",
- },
- ],
- orientation: "horizontal",
- accentColor: "#ffbb00",
- speed: 1,
- theme: "light",
- };
-}
-
-const tick = () => new Promise<void>((r) => setTimeout(r, 0));
-
-const { enqueueRender, getJob, listJobs } = await import(
- "@/lib/server/render-queue"
-);
-const { sweepOnce } = await import("@/lib/server/cleanup");
-
-async function makeErrorJob(): Promise<string> {
- mockRender.mockRejectedValueOnce(new Error("Chromium crashed"));
- const jobId = enqueueRender(makeInput());
- await tick();
- await tick();
- return jobId;
-}
-
-describe("cleanup — sweepOnce registry eviction", () => {
- it("removes an error-status job older than the TTL", async () => {
- const jobId = await makeErrorJob();
- const job = listJobs().get(jobId);
- if (!job) throw new Error("job not found");
- expect(job.status).toBe("error");
-
- job.createdAt = Date.now() - 700_000;
-
- await sweepOnce();
-
- expect(getJob(jobId)).toBeUndefined();
- });
-
- it("keeps an error-status job younger than the TTL", async () => {
- const jobId = await makeErrorJob();
- expect(listJobs().get(jobId)?.status).toBe("error");
-
- await sweepOnce();
-
- expect(getJob(jobId)).toBeDefined();
- });
-
- it("never evicts a rendering-status entry regardless of age", async () => {
- let releaseRender!: (v: string) => void;
- mockRender.mockImplementationOnce(
- () =>
- new Promise<string>((resolve) => {
- releaseRender = resolve;
- }),
- );
-
- const jobId = enqueueRender(makeInput());
- await tick();
-
- const job = listJobs().get(jobId);
- if (!job) throw new Error("job not found");
- expect(job.status).toBe("rendering");
- job.createdAt = Date.now() - 10_000_000;
-
- await sweepOnce();
-
- expect(getJob(jobId)).toBeDefined();
-
- releaseRender("/tmp/out.mp4");
- await tick();
- });
-});
diff --git a/lib/server/__tests__/rate-limit.test.ts b/lib/server/__tests__/rate-limit.test.ts
deleted file mode 100644
index 8e485a8a..00000000
--- a/lib/server/__tests__/rate-limit.test.ts
+++ /dev/null
@@ -1,195 +0,0 @@
-/**
- * Unit tests for lib/server/rate-limit.ts
- *
- * Run with: bunx vitest run lib/server/__tests__/rate-limit.test.ts
- *
- * The module reads RENDER_RATE_LIMIT (token-bucket capacity) and
- * RENDER_RATE_WINDOW_MS (the window over which a full bucket refills) from env
- * at call-time, so we override those per-test without re-importing. Refill rate
- * is capacity / windowMs per ms, so one token refills in (windowMs / capacity) ms.
- *
- * The in-memory `buckets` Map is a module-level singleton shared across tests in
- * this file, so we use a fresh IP per test to avoid cross-test interference.
- *
- * Clock: checkRateLimit() uses Date.now(); we swap in vi.useFakeTimers() to
- * advance time and exercise refill.
- *
- * --- Seam note ---
- * No exported reset/inject hook exists; (a) unique IPs per test + (b) fake timers
- * are sufficient. A future `_resetBuckets()` export would remove the unique-IP
- * requirement.
- */
-
-import {
- afterEach,
- beforeEach,
- describe,
- expect,
- it,
- mock,
- setSystemTime,
-} from "bun:test";
-
-// Mock server-only so importing the module doesn't blow up outside Next.js.
-mock.module("server-only", () => ({}));
-
-const { checkRateLimit } = await import("@/lib/server/rate-limit");
-
-// ---------------------------------------------------------------------------
-// Reset env and clock between tests
-// ---------------------------------------------------------------------------
-
-let ipCounter = 0;
-/** Each call returns a fresh IP string that no prior test has used. */
-function freshIp(): string {
- return `10.0.0.${++ipCounter}`;
-}
-
-let clock = 0;
-function advanceClock(ms: number): void {
- clock += ms;
- setSystemTime(new Date(clock));
-}
-
-beforeEach(() => {
- clock = Date.UTC(2024, 0, 1);
- setSystemTime(new Date(clock));
- // Defaults mirror the module defaults: capacity 5, full refill over 60 s.
- process.env.RENDER_RATE_LIMIT = "5";
- process.env.RENDER_RATE_WINDOW_MS = "60000";
-});
-
-afterEach(() => {
- setSystemTime();
- delete process.env.RENDER_RATE_LIMIT;
- delete process.env.RENDER_RATE_WINDOW_MS;
-});
-
-// ---------------------------------------------------------------------------
-// Allow up to capacity
-// ---------------------------------------------------------------------------
-
-describe("checkRateLimit — allow up to capacity", () => {
- it("allows the first request for a new IP", () => {
- expect(checkRateLimit(freshIp())).toBe(true);
- });
-
- it("allows exactly RENDER_RATE_LIMIT=3 requests in a row", () => {
- process.env.RENDER_RATE_LIMIT = "3";
- process.env.RENDER_RATE_WINDOW_MS = "60000";
- const ip = freshIp();
- expect(checkRateLimit(ip)).toBe(true);
- expect(checkRateLimit(ip)).toBe(true);
- expect(checkRateLimit(ip)).toBe(true);
- });
-
- it("allows exactly RENDER_RATE_LIMIT=5 requests before blocking", () => {
- process.env.RENDER_RATE_LIMIT = "5";
- process.env.RENDER_RATE_WINDOW_MS = "60000";
- const ip = freshIp();
- for (let i = 0; i < 5; i++) {
- expect(checkRateLimit(ip)).toBe(true);
- }
- });
-});
-
-// ---------------------------------------------------------------------------
-// Block once the bucket is empty
-// ---------------------------------------------------------------------------
-
-describe("checkRateLimit — block over limit", () => {
- it("blocks the (LIMIT+1)th request", () => {
- process.env.RENDER_RATE_LIMIT = "3";
- process.env.RENDER_RATE_WINDOW_MS = "60000";
- const ip = freshIp();
- checkRateLimit(ip); // 1
- checkRateLimit(ip); // 2
- checkRateLimit(ip); // 3 — exhausted
- expect(checkRateLimit(ip)).toBe(false); // 4 — blocked
- });
-
- it("continues to block on repeated requests while bucket is empty", () => {
- process.env.RENDER_RATE_LIMIT = "1";
- process.env.RENDER_RATE_WINDOW_MS = "60000";
- const ip = freshIp();
- checkRateLimit(ip); // consume the single token
- expect(checkRateLimit(ip)).toBe(false);
- expect(checkRateLimit(ip)).toBe(false);
- });
-
- it("does not affect a different IP's bucket", () => {
- process.env.RENDER_RATE_LIMIT = "1";
- process.env.RENDER_RATE_WINDOW_MS = "60000";
- const ipA = freshIp();
- const ipB = freshIp();
- checkRateLimit(ipA); // exhaust A
- expect(checkRateLimit(ipA)).toBe(false); // A blocked
- expect(checkRateLimit(ipB)).toBe(true); // B unaffected
- });
-});
-
-// ---------------------------------------------------------------------------
-// Token refill over time (refill rate = capacity / windowMs per ms)
-// ---------------------------------------------------------------------------
-
-describe("checkRateLimit — token refill", () => {
- it("refills a token after a full window/capacity period", () => {
- process.env.RENDER_RATE_LIMIT = "1";
- process.env.RENDER_RATE_WINDOW_MS = "60000"; // 1 token refills in 60 000 ms
-
- const ip = freshIp();
- checkRateLimit(ip); // consume the single token
- expect(checkRateLimit(ip)).toBe(false); // blocked
-
- advanceClock(60_000); // one full refill period
- expect(checkRateLimit(ip)).toBe(true); // refilled
- });
-
- it("does not refill beyond capacity", () => {
- process.env.RENDER_RATE_LIMIT = "2";
- process.env.RENDER_RATE_WINDOW_MS = "60000";
-
- const ip = freshIp();
- checkRateLimit(ip);
- checkRateLimit(ip);
- expect(checkRateLimit(ip)).toBe(false);
-
- // Advance far past the window — tokens must cap at capacity (2).
- advanceClock(10 * 60_000);
- expect(checkRateLimit(ip)).toBe(true);
- expect(checkRateLimit(ip)).toBe(true);
- expect(checkRateLimit(ip)).toBe(false); // 3rd blocked
- });
-
- it("partial refill restores one token after windowMs/capacity elapses", () => {
- process.env.RENDER_RATE_LIMIT = "1";
- process.env.RENDER_RATE_WINDOW_MS = "30000"; // 1 token refills in 30 000 ms
-
- const ip = freshIp();
- checkRateLimit(ip); // consume
- expect(checkRateLimit(ip)).toBe(false);
-
- advanceClock(30_000); // exactly one token back
- expect(checkRateLimit(ip)).toBe(true);
- expect(checkRateLimit(ip)).toBe(false); // consumed again
- });
-});
-
-// ---------------------------------------------------------------------------
-// Edge cases
-// ---------------------------------------------------------------------------
-
-describe("checkRateLimit — edge cases", () => {
- it("treats different IP strings as independent buckets", () => {
- process.env.RENDER_RATE_LIMIT = "1";
- const ips = [freshIp(), freshIp(), freshIp()];
- for (const ip of ips) {
- expect(checkRateLimit(ip)).toBe(true);
- }
- });
-
- it("uses the 'unknown' fallback IP without throwing", () => {
- // The route falls back to "unknown" when no IP header is present.
- expect(() => checkRateLimit("unknown")).not.toThrow();
- });
-});
diff --git a/lib/server/__tests__/render-queue.test.ts b/lib/server/__tests__/render-queue.test.ts
deleted file mode 100644
index e74c6653..00000000
--- a/lib/server/__tests__/render-queue.test.ts
+++ /dev/null
@@ -1,330 +0,0 @@
-/**
- * Unit tests for lib/server/render-queue.ts
- *
- * Run with: bunx vitest run lib/server/__tests__/render-queue.test.ts
- *
- * renderStarsVideo (real Chromium) is mocked via vi.mock so nothing real runs.
- * node:fs/promises (mkdir) is also mocked — no real filesystem side-effects.
- *
- * --- Seam note ---
- * render-queue.ts imports renderStarsVideo from "./render" at module load time,
- * then calls it inside runRender(). vi.mock("@/lib/server/render") replaces that
- * module before the queue module is imported, so the mock is in effect for all
- * enqueueRender() calls below. The module-level `limit` and `jobs` singletons
- * are reset between tests by re-importing the module inside a vi.isolateModules
- * block — see the "resetQueue" helper. If the queue ever needs a cleaner
- * injection point (e.g. an exported `_setRenderFn` for testing), that would
- * remove the need for vi.isolateModules, but the current mock approach is
- * sufficient.
- */
-
-import {
- afterEach,
- beforeEach,
- describe,
- expect,
- it,
- mock,
- spyOn,
-} from "bun:test";
-import * as fsPromises from "node:fs/promises";
-import type { RenderInput } from "@/lib/server/validate-input";
-
-// ---------------------------------------------------------------------------
-// Mock the render module (real Chromium → deferred promise under test control)
-// ---------------------------------------------------------------------------
-
-const mockRender = mock();
-
-mock.module("@/lib/server/render", () => ({
- renderStarsVideo: mockRender,
-}));
-
-spyOn(fsPromises, "mkdir").mockResolvedValue(undefined);
-
-// Mock server-only so it doesn't blow up outside Next.js.
-mock.module("server-only", () => ({}));
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-/** A valid RenderInput that exercises no interesting code paths in validate. */
-function makeInput(repo = "owner/repo"): RenderInput {
- return {
- repo,
- totalStars: 100,
- stargazers: [
- {
- login: "alice",
- avatarUrl: "https://avatars.githubusercontent.com/u/1",
- starredAt: "2021-01-01",
- },
- ],
- orientation: "horizontal",
- accentColor: "#ffbb00",
- speed: 1,
- theme: "light",
- };
-}
-
-/**
- * Returns a { resolve, reject, promise } triple: the promise stays pending
- * until resolve/reject is called, simulating a long-running render.
- */
-function deferred<T = string>() {
- let resolve!: (v: T) => void;
- let reject!: (e: unknown) => void;
- const promise = new Promise<T>((res, rej) => {
- resolve = res;
- reject = rej;
- });
- return { resolve, reject, promise };
-}
-
-/** Wait one microtask turn so queued promises can settle. */
-const tick = () => new Promise<void>((r) => setTimeout(r, 0));
-
-// ---------------------------------------------------------------------------
-// Import queue + mock render fn after all vi.mock() calls are hoisted.
-// ---------------------------------------------------------------------------
-
-const { enqueueRender, getJob, QueueFullError } = await import(
- "@/lib/server/render-queue"
-);
-
-// ---------------------------------------------------------------------------
-// Reset mock state between tests (the module singleton is shared across the
-// file because bun re-uses the same module instance within a test file).
-// ---------------------------------------------------------------------------
-
-beforeEach(() => {
- mockRender.mockReset();
-});
-
-afterEach(() => {
- mockRender.mockReset();
-});
-
-// ---------------------------------------------------------------------------
-// Status transitions: queued → rendering → done
-// ---------------------------------------------------------------------------
-
-describe("render-queue — status transitions", () => {
- it("newly enqueued job starts as 'queued'", () => {
- const d = deferred();
- mockRender.mockReturnValueOnce(d.promise);
-
- const jobId = enqueueRender(makeInput());
- const job = getJob(jobId);
-
- // Synchronously the job is registered.
- expect(job).toBeDefined();
- expect(job?.status).toBe("queued");
- expect(job?.progress).toBe(0);
-
- // Clean up: let it resolve so the limiter slot is freed.
- d.resolve("/tmp/out.mp4");
- });
-
- it("transitions to 'rendering' once the slot is acquired", async () => {
- const d = deferred();
- mockRender.mockReturnValueOnce(d.promise);
-
- const jobId = enqueueRender(makeInput());
-
- // Allow the microtask queue to run so the limiter picks up the task.
- await tick();
-
- const job = getJob(jobId);
- expect(job?.status).toBe("rendering");
-
- d.resolve("/tmp/out.mp4");
- await tick();
- });
-
- it("transitions to 'done' with progress=1 after renderStarsVideo resolves", async () => {
- const d = deferred();
- mockRender.mockReturnValueOnce(d.promise);
-
- const jobId = enqueueRender(makeInput());
- await tick();
-
- d.resolve("/tmp/out.mp4");
- await tick();
-
- const job = getJob(jobId);
- expect(job?.status).toBe("done");
- expect(job?.progress).toBe(1);
- expect(job?.outputPath).toBeDefined();
- });
-
- it("stores the correct repo on the job", () => {
- mockRender.mockResolvedValueOnce("/tmp/x.mp4");
- const jobId = enqueueRender(makeInput("my-org/my-repo"));
- expect(getJob(jobId)?.repo).toBe("my-org/my-repo");
- });
-
- it("returns a string jobId that differs between two calls", () => {
- mockRender.mockResolvedValue("/tmp/x.mp4");
- const id1 = enqueueRender(makeInput());
- const id2 = enqueueRender(makeInput());
- expect(typeof id1).toBe("string");
- expect(id1).not.toBe(id2);
- });
-});
-
-// ---------------------------------------------------------------------------
-// Error path: renderStarsVideo rejects → job.status = "error"
-// ---------------------------------------------------------------------------
-
-describe("render-queue — error path", () => {
- it("sets status to 'error' when renderStarsVideo rejects", async () => {
- mockRender.mockRejectedValueOnce(new Error("Chromium crashed"));
-
- const jobId = enqueueRender(makeInput());
- await tick();
- await tick(); // extra tick for rejection propagation
-
- const job = getJob(jobId);
- expect(job?.status).toBe("error");
- expect(job?.error).toContain("Chromium crashed");
- });
-
- it("captures a generic (non-Error) rejection as a fallback string", async () => {
- mockRender.mockRejectedValueOnce("raw string failure");
-
- const jobId = enqueueRender(makeInput());
- await tick();
- await tick();
-
- const job = getJob(jobId);
- expect(job?.status).toBe("error");
- expect(typeof job?.error).toBe("string");
- });
-});
-
-// ---------------------------------------------------------------------------
-// Concurrency cap — at most RENDER_MAX_CONCURRENT renders in flight at once
-// ---------------------------------------------------------------------------
-
-describe("render-queue — concurrency semaphore", () => {
- it("runs at most RENDER_MAX_CONCURRENT renders simultaneously (default 2)", async () => {
- // Each deferred keeps its render slot occupied until resolved.
- const deferreds = Array.from({ length: 4 }, () => deferred());
- let callCount = 0;
-
- mockRender.mockImplementation(() => {
- callCount++;
- return deferreds[callCount - 1].promise;
- });
-
- // Enqueue 4 jobs.
- const ids = Array.from({ length: 4 }, () => enqueueRender(makeInput()));
-
- // Let the event loop run so the limiter can dispatch.
- await tick();
- await tick();
-
- // Only 2 should be rendering (default RENDER_MAX_CONCURRENT = 2).
- const statuses = ids.map((id) => getJob(id)?.status);
- const renderingCount = statuses.filter((s) => s === "rendering").length;
- const queuedCount = statuses.filter((s) => s === "queued").length;
-
- expect(renderingCount).toBe(2);
- expect(queuedCount).toBe(2);
-
- // Resolve the first two; the next two should start.
- deferreds[0].resolve("/tmp/a.mp4");
- deferreds[1].resolve("/tmp/b.mp4");
- await tick();
- await tick();
-
- const newStatuses = ids.map((id) => getJob(id)?.status);
- // ids[0] and ids[1] should now be done.
- expect(newStatuses[0]).toBe("done");
- expect(newStatuses[1]).toBe("done");
- // ids[2] or ids[3] should have started rendering.
- const nowRendering = newStatuses.filter((s) => s === "rendering").length;
- expect(nowRendering).toBeGreaterThanOrEqual(1);
-
- // Clean up remaining.
- deferreds[2].resolve("/tmp/c.mp4");
- deferreds[3].resolve("/tmp/d.mp4");
- await tick();
- });
-});
-
-// ---------------------------------------------------------------------------
-// Timeout path — AbortController fires → job.status = "error" with "timed out"
-// ---------------------------------------------------------------------------
-
-describe("render-queue — render timeout", () => {
- it("sets status to 'error' containing 'timed out' when RENDER_TIMEOUT_MS elapses", async () => {
- // Set a very short timeout via env so we don't wait 120 s.
- process.env.RENDER_TIMEOUT_MS = "1000";
-
- // renderStarsVideo never resolves — simulates a stuck Chromium.
- // The real runRender() uses an AbortController; when the timeout fires it
- // calls controller.abort(). renderStarsVideo must honor the signal and
- // throw. We simulate that by rejecting once the abort callback fires.
- let abortCallback: (() => void) | undefined;
- mockRender.mockImplementation(({ signal }: { signal?: AbortSignal }) => {
- return new Promise<string>((_, reject) => {
- if (signal) {
- signal.addEventListener("abort", () => {
- abortCallback = () => reject(new Error("Render aborted"));
- abortCallback();
- });
- }
- });
- });
-
- const jobId = enqueueRender(makeInput());
- await tick();
-
- // Wait past the timeout so the AbortController fires.
- await new Promise((r) => setTimeout(r, 1100));
- await tick();
- await tick();
-
- const job = getJob(jobId);
- expect(job?.status).toBe("error");
- // The queue sets job.error to "Render timed out" when signal.aborted is true.
- expect(job?.error).toMatch(/timed out/i);
-
- delete process.env.RENDER_TIMEOUT_MS;
- });
-});
-
-// ---------------------------------------------------------------------------
-// Queue depth cap — RENDER_MAX_QUEUE
-// ---------------------------------------------------------------------------
-
-describe("render-queue — queue depth cap", () => {
- it("throws QueueFullError when RENDER_MAX_QUEUE is reached", async () => {
- process.env.RENDER_MAX_QUEUE = "1";
-
- const d = deferred();
- mockRender.mockReturnValueOnce(d.promise);
-
- enqueueRender(makeInput());
- await tick();
-
- expect(() => enqueueRender(makeInput())).toThrow(QueueFullError);
-
- d.resolve("/tmp/out.mp4");
- await tick();
- delete process.env.RENDER_MAX_QUEUE;
- });
-});
-
-// ---------------------------------------------------------------------------
-// getJob — unknown id returns undefined
-// ---------------------------------------------------------------------------
-
-describe("render-queue — getJob", () => {
- it("returns undefined for an unknown jobId", () => {
- expect(getJob("00000000-0000-0000-0000-000000000000")).toBeUndefined();
- });
-});
diff --git a/lib/server/__tests__/validate-input.test.ts b/lib/server/__tests__/validate-input.test.ts
deleted file mode 100644
index b362ca95..00000000
--- a/lib/server/__tests__/validate-input.test.ts
+++ /dev/null
@@ -1,527 +0,0 @@
-/**
- * Unit tests for lib/server/validate-input.ts
- *
- * Run with: bunx vitest run lib/server/__tests__/validate-input.test.ts
- *
- * Pure function — no mocks needed; all logic is deterministic.
- */
-
-import { describe, expect, it, mock } from "bun:test";
-
-mock.module("server-only", () => ({}));
-
-const { parseRenderInput, RenderInputError } = await import(
- "@/lib/server/validate-input"
-);
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-/** A minimal valid body that passes every rule. */
-function validBody(
- overrides?: Record<string, unknown>,
-): Record<string, unknown> {
- return {
- repo: "vercel/next.js",
- totalStars: 120_000,
- stargazers: [
- {
- login: "alice",
- avatarUrl: "https://avatars.githubusercontent.com/u/1",
- starredAt: "2021-01-01",
- },
- ],
- orientation: "horizontal",
- ...overrides,
- };
-}
-
-function stargazer(overrides?: Record<string, unknown>) {
- return {
- login: "alice",
- avatarUrl: "https://avatars.githubusercontent.com/u/1",
- starredAt: "2021-01-01",
- ...overrides,
- };
-}
-
-// ---------------------------------------------------------------------------
-// Happy path — accepts a valid payload and applies defaults
-// ---------------------------------------------------------------------------
-
-describe("parseRenderInput — valid payload", () => {
- it("accepts a minimal valid body and returns the parsed input", () => {
- const result = parseRenderInput(validBody());
- expect(result.repo).toBe("vercel/next.js");
- expect(result.totalStars).toBe(120_000);
- expect(result.orientation).toBe("horizontal");
- expect(result.stargazers).toHaveLength(1);
- });
-
- it("applies default accentColor #ffbb00 when omitted", () => {
- const result = parseRenderInput(validBody());
- expect(result.accentColor).toBe("#ffbb00");
- });
-
- it("applies default speed 1 when omitted", () => {
- const result = parseRenderInput(validBody());
- expect(result.speed).toBe(1);
- });
-
- it("applies default theme 'light' when omitted", () => {
- const result = parseRenderInput(validBody());
- expect(result.theme).toBe("light");
- });
-
- it("accepts orientation 'vertical'", () => {
- const result = parseRenderInput(validBody({ orientation: "vertical" }));
- expect(result.orientation).toBe("vertical");
- });
-
- it("accepts theme 'dark'", () => {
- const result = parseRenderInput(validBody({ theme: "dark" }));
- expect(result.theme).toBe("dark");
- });
-
- it("accepts a valid 3-char hex accentColor", () => {
- const result = parseRenderInput(validBody({ accentColor: "#abc" }));
- expect(result.accentColor).toBe("#abc");
- });
-
- it("accepts a valid 6-char hex accentColor", () => {
- const result = parseRenderInput(validBody({ accentColor: "#ff0000" }));
- expect(result.accentColor).toBe("#ff0000");
- });
-
- it("accepts an 8-char hex accentColor (with alpha)", () => {
- const result = parseRenderInput(validBody({ accentColor: "#ff0000ff" }));
- expect(result.accentColor).toBe("#ff0000ff");
- });
-
- it("accepts stargazers array of exactly 60 items", () => {
- const many = Array.from({ length: 60 }, (_, i) =>
- stargazer({
- login: `user${i}`,
- avatarUrl: `https://avatars.githubusercontent.com/u/${i}`,
- }),
- );
- const result = parseRenderInput(validBody({ stargazers: many }));
- expect(result.stargazers).toHaveLength(60);
- });
-
- it("returns floored totalStars when given a float", () => {
- const result = parseRenderInput(validBody({ totalStars: 99.9 }));
- expect(result.totalStars).toBe(99);
- });
-});
-
-// ---------------------------------------------------------------------------
-// Clamps — numbers clamped, not rejected
-// ---------------------------------------------------------------------------
-
-describe("parseRenderInput — clamping", () => {
- it("clamps totalStars below 0 to 0", () => {
- const result = parseRenderInput(validBody({ totalStars: -100 }));
- expect(result.totalStars).toBe(0);
- });
-
- it("clamps totalStars above 1e8 to 1e8", () => {
- const result = parseRenderInput(validBody({ totalStars: 999_000_000 }));
- expect(result.totalStars).toBe(100_000_000);
- });
-
- it("clamps speed below 1 to 1", () => {
- const result = parseRenderInput(validBody({ speed: 0 }));
- expect(result.speed).toBe(1);
- });
-
- it("clamps speed above 4 to 4", () => {
- const result = parseRenderInput(validBody({ speed: 100 }));
- expect(result.speed).toBe(4);
- });
-
- it("accepts speed exactly at min bound (1)", () => {
- const result = parseRenderInput(validBody({ speed: 1 }));
- expect(result.speed).toBe(1);
- });
-
- it("accepts speed exactly at max bound (4)", () => {
- const result = parseRenderInput(validBody({ speed: 4 }));
- expect(result.speed).toBe(4);
- });
-});
-
-// ---------------------------------------------------------------------------
-// Non-object body
-// ---------------------------------------------------------------------------
-
-describe("parseRenderInput — non-object body throws", () => {
- it("throws RenderInputError on null", () => {
- expect(() => parseRenderInput(null)).toThrow(RenderInputError);
- });
-
- it("throws RenderInputError on a string", () => {
- expect(() => parseRenderInput("hello")).toThrow(RenderInputError);
- });
-
- it("throws RenderInputError on an array", () => {
- expect(() => parseRenderInput([])).toThrow(RenderInputError);
- });
-
- it("throws RenderInputError on a number", () => {
- expect(() => parseRenderInput(42)).toThrow(RenderInputError);
- });
-
- it("carries status 400", () => {
- try {
- parseRenderInput(null);
- expect.fail("should have thrown");
- } catch (err) {
- expect(err).toBeInstanceOf(RenderInputError);
- expect((err as RenderInputError).status).toBe(400);
- }
- });
-});
-
-// ---------------------------------------------------------------------------
-// orientation validation
-// ---------------------------------------------------------------------------
-
-describe("parseRenderInput — orientation", () => {
- it("throws on unknown orientation", () => {
- expect(() =>
- parseRenderInput(validBody({ orientation: "diagonal" })),
- ).toThrow(RenderInputError);
- });
-
- it("throws when orientation is missing", () => {
- const body = validBody();
- delete body.orientation;
- expect(() => parseRenderInput(body)).toThrow(RenderInputError);
- });
-
- it("throws when orientation is null", () => {
- expect(() => parseRenderInput(validBody({ orientation: null }))).toThrow(
- RenderInputError,
- );
- });
-});
-
-// ---------------------------------------------------------------------------
-// stargazers array validation
-// ---------------------------------------------------------------------------
-
-describe("parseRenderInput — stargazers length cap", () => {
- it("throws when stargazers has 61 items", () => {
- const many = Array.from({ length: 61 }, (_, i) =>
- stargazer({ login: `user${i}`, avatarUrl: `https://example.com/u/${i}` }),
- );
- expect(() => parseRenderInput(validBody({ stargazers: many }))).toThrow(
- RenderInputError,
- );
- });
-
- it("throws when stargazers is not an array", () => {
- expect(() => parseRenderInput(validBody({ stargazers: "nope" }))).toThrow(
- RenderInputError,
- );
- });
-
- it("throws when stargazers is null", () => {
- expect(() => parseRenderInput(validBody({ stargazers: null }))).toThrow(
- RenderInputError,
- );
- });
-});
-
-// ---------------------------------------------------------------------------
-// stargazer item shape validation
-// ---------------------------------------------------------------------------
-
-describe("parseRenderInput — stargazer item shapes", () => {
- it("throws when a stargazer item is not an object", () => {
- expect(() =>
- parseRenderInput(validBody({ stargazers: ["not-an-object"] })),
- ).toThrow(RenderInputError);
- });
-
- it("throws when login is missing", () => {
- expect(() =>
- parseRenderInput(
- validBody({ stargazers: [stargazer({ login: undefined })] }),
- ),
- ).toThrow(RenderInputError);
- });
-
- it("throws when login is empty string", () => {
- expect(() =>
- parseRenderInput(validBody({ stargazers: [stargazer({ login: "" })] })),
- ).toThrow(RenderInputError);
- });
-
- it("throws when login exceeds 100 chars", () => {
- expect(() =>
- parseRenderInput(
- validBody({ stargazers: [stargazer({ login: "a".repeat(101) })] }),
- ),
- ).toThrow(RenderInputError);
- });
-
- it("throws when avatarUrl is missing", () => {
- expect(() =>
- parseRenderInput(
- validBody({ stargazers: [stargazer({ avatarUrl: undefined })] }),
- ),
- ).toThrow(RenderInputError);
- });
-
- it("throws when avatarUrl exceeds 512 chars", () => {
- const longUrl = `https://example.com/${"a".repeat(494)}`;
- expect(() =>
- parseRenderInput(
- validBody({ stargazers: [stargazer({ avatarUrl: longUrl })] }),
- ),
- ).toThrow(RenderInputError);
- });
-
- it("throws when starredAt is missing", () => {
- expect(() =>
- parseRenderInput(
- validBody({ stargazers: [stargazer({ starredAt: undefined })] }),
- ),
- ).toThrow(RenderInputError);
- });
-
- it("throws when starredAt exceeds 40 chars", () => {
- expect(() =>
- parseRenderInput(
- validBody({ stargazers: [stargazer({ starredAt: "x".repeat(41) })] }),
- ),
- ).toThrow(RenderInputError);
- });
-});
-
-// ---------------------------------------------------------------------------
-// avatarUrl — GitHub avatar host allowlist (closes the SSRF window)
-// ---------------------------------------------------------------------------
-
-describe("parseRenderInput — avatarUrl must be a GitHub avatar URL", () => {
- it("throws on a file:// avatarUrl", () => {
- expect(() =>
- parseRenderInput(
- validBody({
- stargazers: [stargazer({ avatarUrl: "file:///etc/passwd" })],
- }),
- ),
- ).toThrow(RenderInputError);
- });
-
- it("throws on a javascript: avatarUrl", () => {
- expect(() =>
- parseRenderInput(
- validBody({
- stargazers: [stargazer({ avatarUrl: "javascript:alert(1)" })],
- }),
- ),
- ).toThrow(RenderInputError);
- });
-
- it("throws on a relative avatarUrl", () => {
- expect(() =>
- parseRenderInput(
- validBody({ stargazers: [stargazer({ avatarUrl: "/relative/path" })] }),
- ),
- ).toThrow(RenderInputError);
- });
-
- it("accepts an https:// avatarUrl on the GitHub avatar host", () => {
- const result = parseRenderInput(
- validBody({
- stargazers: [
- stargazer({
- avatarUrl: "https://avatars.githubusercontent.com/u/99",
- }),
- ],
- }),
- );
- expect(result.stargazers[0].avatarUrl).toBe(
- "https://avatars.githubusercontent.com/u/99",
- );
- });
-
- it("accepts a GitHub avatar URL with a query string", () => {
- const result = parseRenderInput(
- validBody({
- stargazers: [
- stargazer({
- avatarUrl: "https://avatars.githubusercontent.com/u/1?v=4",
- }),
- ],
- }),
- );
- expect(result.stargazers[0].avatarUrl).toBe(
- "https://avatars.githubusercontent.com/u/1?v=4",
- );
- });
-
- it("rejects an http:// downgrade of the GitHub avatar host", () => {
- expect(() =>
- parseRenderInput(
- validBody({
- stargazers: [
- stargazer({
- avatarUrl: "http://avatars.githubusercontent.com/u/1",
- }),
- ],
- }),
- ),
- ).toThrow(RenderInputError);
- });
-
- it("rejects a non-GitHub https host", () => {
- expect(() =>
- parseRenderInput(
- validBody({
- stargazers: [
- stargazer({ avatarUrl: "https://evil.example.com/a.png" }),
- ],
- }),
- ),
- ).toThrow(RenderInputError);
- });
-
- it("rejects a loopback IP avatarUrl", () => {
- expect(() =>
- parseRenderInput(
- validBody({
- stargazers: [stargazer({ avatarUrl: "http://127.0.0.1:8080/x" })],
- }),
- ),
- ).toThrow(RenderInputError);
- });
-
- it("rejects the cloud metadata IP avatarUrl", () => {
- expect(() =>
- parseRenderInput(
- validBody({
- stargazers: [
- stargazer({ avatarUrl: "http://169.254.169.254/latest/meta-data" }),
- ],
- }),
- ),
- ).toThrow(RenderInputError);
- });
-
- it("rejects an IPv6 loopback avatarUrl", () => {
- expect(() =>
- parseRenderInput(
- validBody({
- stargazers: [stargazer({ avatarUrl: "https://[::1]/x" })],
- }),
- ),
- ).toThrow(RenderInputError);
- });
-
- it("throws a 400 RenderInputError on an unparseable URL", () => {
- expect(() =>
- parseRenderInput(
- validBody({ stargazers: [stargazer({ avatarUrl: "not a url" })] }),
- ),
- ).toThrow(RenderInputError);
- });
-
- it("throws a 400 RenderInputError on a scheme-only URL", () => {
- expect(() =>
- parseRenderInput(
- validBody({ stargazers: [stargazer({ avatarUrl: "https://" })] }),
- ),
- ).toThrow(RenderInputError);
- });
-
- it("rejects a hostname that merely starts with the allowed host (subdomain spoof)", () => {
- expect(() =>
- parseRenderInput(
- validBody({
- stargazers: [
- stargazer({
- avatarUrl: "https://avatars.githubusercontent.com.evil.com/x",
- }),
- ],
- }),
- ),
- ).toThrow(RenderInputError);
- });
-});
-
-// ---------------------------------------------------------------------------
-// accentColor validation
-// ---------------------------------------------------------------------------
-
-describe("parseRenderInput — accentColor", () => {
- it("throws when accentColor is not a hex color", () => {
- expect(() => parseRenderInput(validBody({ accentColor: "red" }))).toThrow(
- RenderInputError,
- );
- });
-
- it("throws when accentColor lacks the leading #", () => {
- expect(() =>
- parseRenderInput(validBody({ accentColor: "ffbb00" })),
- ).toThrow(RenderInputError);
- });
-
- it("throws when accentColor has 2 hex digits (too short)", () => {
- expect(() => parseRenderInput(validBody({ accentColor: "#ff" }))).toThrow(
- RenderInputError,
- );
- });
-});
-
-// ---------------------------------------------------------------------------
-// repo validation
-// ---------------------------------------------------------------------------
-
-describe("parseRenderInput — repo", () => {
- it("throws when repo is missing", () => {
- const body = validBody();
- delete body.repo;
- expect(() => parseRenderInput(body)).toThrow(RenderInputError);
- });
-
- it("throws when repo is empty string", () => {
- expect(() => parseRenderInput(validBody({ repo: "" }))).toThrow(
- RenderInputError,
- );
- });
-
- it("throws when repo exceeds 200 chars", () => {
- expect(() =>
- parseRenderInput(validBody({ repo: "a".repeat(201) })),
- ).toThrow(RenderInputError);
- });
-});
-
-// ---------------------------------------------------------------------------
-// totalStars validation
-// ---------------------------------------------------------------------------
-
-describe("parseRenderInput — totalStars", () => {
- it("throws when totalStars is not a number", () => {
- expect(() =>
- parseRenderInput(validBody({ totalStars: "not-a-number" })),
- ).toThrow(RenderInputError);
- });
-
- it("throws when totalStars is Infinity", () => {
- expect(() => parseRenderInput(validBody({ totalStars: Infinity }))).toThrow(
- RenderInputError,
- );
- });
-
- it("throws when totalStars is NaN", () => {
- expect(() => parseRenderInput(validBody({ totalStars: NaN }))).toThrow(
- RenderInputError,
- );
- });
-});
diff --git a/lib/server/bundle.ts b/lib/server/bundle.ts
deleted file mode 100644
index 4b4c8b01..00000000
--- a/lib/server/bundle.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import "server-only";
-import { existsSync } from "node:fs";
-import path from "node:path";
-import { bundle } from "@remotion/bundler";
-
-/**
- * Resolves the Remotion `serveUrl` that `selectComposition`/`renderMedia` need.
- *
- * Bundling is expensive, so it happens at most once per process: if the deploy
- * baked a pre-bundle into `.remotion-bundle/` (see scripts/bundle-remotion.mts),
- * that path is returned directly; otherwise we lazily `bundle()` the entry once
- * and cache the in-flight promise so concurrent first renders share it.
- */
-
-const PREBUNDLED_DIR = path.join(process.cwd(), ".remotion-bundle");
-const ENTRY_POINT = path.join(process.cwd(), "src", "remotion", "index.ts");
-
-let serveUrlPromise: Promise<string> | null = null;
-
-export function getServeUrl(): Promise<string> {
- if (serveUrlPromise) return serveUrlPromise;
-
- serveUrlPromise = (async () => {
- if (existsSync(PREBUNDLED_DIR)) {
- return PREBUNDLED_DIR;
- }
- try {
- return await bundle({
- entryPoint: ENTRY_POINT,
- // Webpack doesn't read tsconfig `paths`; teach it the `@/* → root` alias
- // (must match scripts/bundle-remotion.mts) so `@/registry/...` resolves.
- webpackOverride: (config) => ({
- ...config,
- resolve: {
- ...config.resolve,
- alias: {
- ...(config.resolve?.alias ?? {}),
- "@": process.cwd(),
- },
- },
- }),
- });
- } catch (err) {
- // Don't poison the cache on failure — let the next render retry the bundle.
- serveUrlPromise = null;
- throw err;
- }
- })();
-
- return serveUrlPromise;
-}
diff --git a/lib/server/cleanup.ts b/lib/server/cleanup.ts
deleted file mode 100644
index 33ddb6e7..00000000
--- a/lib/server/cleanup.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-import "server-only";
-import * as fsPromises from "node:fs/promises";
-import path from "node:path";
-import { RENDER_WORK_DIR } from "./paths";
-import { deleteJob, listJobs } from "./render-queue";
-
-/**
- * Disk hygiene for the render work dir. Two mechanisms:
- * - `deleteJobFile` removes a single MP4 right after it's been downloaded.
- * - a guarded `setInterval` TTL sweep deletes any leftover files older than
- * the TTL (downloads that never happened, crashed renders) so the disk can't
- * fill up.
- */
-
-/** How long a finished file may sit before the sweep reclaims it. */
-function ttlMs(): number {
- const parsed = Number(process.env.RENDER_FILE_TTL_MS);
- return Number.isFinite(parsed) && parsed >= 1000
- ? Math.floor(parsed)
- : 600_000;
-}
-
-/** How often the sweep runs — derived from the TTL (at least once a minute). */
-function sweepIntervalMs(): number {
- return Math.max(60_000, ttlMs());
-}
-
-/** Delete a single job's MP4 (best-effort) and drop it from the registry. */
-export async function deleteJobFile(jobId: string): Promise<void> {
- const filePath = path.join(RENDER_WORK_DIR, `${jobId}.mp4`);
- try {
- await fsPromises.rm(filePath, { force: true });
- } finally {
- deleteJob(jobId);
- }
-}
-
-/** Remove every `.mp4` in the work dir older than the TTL. */
-export async function sweepOnce(): Promise<void> {
- const ttl = ttlMs();
- const now = Date.now();
-
- let entries: string[];
- try {
- entries = await fsPromises.readdir(RENDER_WORK_DIR);
- } catch {
- entries = [];
- }
-
- await Promise.all(
- entries
- .filter((name) => name.endsWith(".mp4"))
- .map(async (name) => {
- const filePath = path.join(RENDER_WORK_DIR, name);
- try {
- const info = await fsPromises.stat(filePath);
- if (now - info.mtimeMs > ttl) {
- await fsPromises.rm(filePath, { force: true });
- deleteJob(path.basename(name, ".mp4"));
- }
- } catch {
- // File vanished between readdir and stat — ignore.
- }
- }),
- );
-
- for (const [jobId, job] of listJobs()) {
- if (now - job.createdAt <= ttl) continue;
- if (job.status === "error" || job.status === "done") deleteJob(jobId);
- }
-}
-
-// Module-level guard: ensure the sweep timer is installed exactly once per
-// process, even if multiple routes import this module.
-let sweepStarted = false;
-
-/** Start the periodic TTL sweep (idempotent). */
-export function ensureCleanupSweep(): void {
- if (sweepStarted) return;
- sweepStarted = true;
-
- const timer = setInterval(() => {
- void sweepOnce();
- }, sweepIntervalMs());
- // Don't keep the process alive just for the sweep.
- timer.unref?.();
-}
diff --git a/lib/server/paths.ts b/lib/server/paths.ts
deleted file mode 100644
index 848a1786..00000000
--- a/lib/server/paths.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import "server-only";
-import os from "node:os";
-import path from "node:path";
-
-/**
- * Shared filesystem location for rendered MP4s. A single dir owned by the Node
- * process; the queue writes `${jobId}.mp4` here, the download route streams from
- * it, and the cleanup sweep prunes it. Overridable via `RENDER_WORK_DIR` (e.g.
- * a tmpfs/volume on the box); defaults to the OS temp dir.
- */
-export const RENDER_WORK_DIR =
- process.env.RENDER_WORK_DIR?.trim() ||
- path.join(os.tmpdir(), "remocn-renders");
diff --git a/lib/server/rate-limit.ts b/lib/server/rate-limit.ts
deleted file mode 100644
index c326d926..00000000
--- a/lib/server/rate-limit.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import "server-only";
-
-/**
- * Per-IP rate limiter, in-memory. Renders cost real CPU, so this caps how often
- * a single client can kick one off: at most `RENDER_RATE_LIMIT` requests per
- * `RENDER_RATE_WINDOW_MS` window. Implemented as a token bucket (capacity =
- * limit, refilled smoothly across the window) so bursts are bounded without a
- * hard fixed-window edge. Cheap and good enough for a single-process box — not a
- * distributed limiter.
- */
-
-interface Bucket {
- /** Fractional tokens currently available. */
- tokens: number;
- /** Last time (ms) the bucket was refilled. */
- updatedAt: number;
-}
-
-/** Max requests per window before throttling (bucket capacity). */
-function limit(): number {
- const parsed = Number(process.env.RENDER_RATE_LIMIT);
- return Number.isFinite(parsed) && parsed >= 1 ? Math.floor(parsed) : 5;
-}
-
-/** Window over which a full bucket refills. */
-function windowMs(): number {
- const parsed = Number(process.env.RENDER_RATE_WINDOW_MS);
- return Number.isFinite(parsed) && parsed >= 1 ? Math.floor(parsed) : 60_000;
-}
-
-const buckets = new Map<string, Bucket>();
-
-// Evict idle buckets so the map can't grow unbounded from one-off IPs.
-const IDLE_EVICT_MS = 60 * 60 * 1000;
-
-/**
- * Consume one token for `ip`. Returns true if allowed, false if the bucket is
- * empty (caller should respond 429).
- */
-export function checkRateLimit(ip: string): boolean {
- const cap = limit();
- // Tokens refilled per ms so a full window restores the whole capacity.
- const ratePerMs = cap / windowMs();
- const now = Date.now();
-
- let bucket = buckets.get(ip);
- if (!bucket) {
- bucket = { tokens: cap, updatedAt: now };
- buckets.set(ip, bucket);
- } else {
- const elapsed = now - bucket.updatedAt;
- bucket.tokens = Math.min(cap, bucket.tokens + elapsed * ratePerMs);
- bucket.updatedAt = now;
- }
-
- if (bucket.tokens < 1) {
- return false;
- }
-
- bucket.tokens -= 1;
-
- // Opportunistic eviction of long-idle buckets (kept tiny — only on access).
- if (buckets.size > 1000) {
- for (const [key, b] of buckets) {
- if (now - b.updatedAt > IDLE_EVICT_MS) buckets.delete(key);
- }
- }
-
- return true;
-}
diff --git a/lib/server/render-queue.ts b/lib/server/render-queue.ts
deleted file mode 100644
index 6dcdac8d..00000000
--- a/lib/server/render-queue.ts
+++ /dev/null
@@ -1,158 +0,0 @@
-import "server-only";
-import { randomUUID } from "node:crypto";
-import { mkdir } from "node:fs/promises";
-import path from "node:path";
-import pLimit from "p-limit";
-import { RENDER_WORK_DIR } from "./paths";
-import { renderStarsVideo } from "./render";
-import type { RenderInput } from "./validate-input";
-
-/**
- * In-process render orchestration: a global concurrency semaphore plus a job
- * registry so the API can return a `jobId` immediately (202) and let the client
- * poll for progress. Renders are CPU-heavy (native Chromium), so at most
- * `RENDER_MAX_CONCURRENT` run at once; the rest wait in the limiter's queue.
- *
- * State is intentionally in-memory: a single long-lived Node process owns the
- * work dir, and a job only matters until its MP4 is downloaded (then swept).
- * Restarting the process drops in-flight jobs by design — clients re-POST.
- */
-
-export type JobStatus = "queued" | "rendering" | "done" | "error";
-
-export interface JobState {
- status: JobStatus;
- /** Render progress in [0, 1]. */
- progress: number;
- /** Absolute path to the finished MP4 (only once status === "done"). */
- outputPath?: string;
- /** Human-readable failure reason (only once status === "error"). */
- error?: string;
- /** Original repo slug, used to name the downloaded file. */
- repo: string;
- createdAt: number;
-}
-
-/** Max simultaneous renders; the rest queue. Sized for the 8-vCPU box. */
-function maxConcurrent(): number {
- const parsed = Number(process.env.RENDER_MAX_CONCURRENT);
- return Number.isFinite(parsed) && parsed >= 1 ? Math.floor(parsed) : 2;
-}
-
-/** Hard ceiling on a single render before it's aborted as stuck. */
-function renderTimeoutMs(): number {
- const parsed = Number(process.env.RENDER_TIMEOUT_MS);
- return Number.isFinite(parsed) && parsed >= 1000
- ? Math.floor(parsed)
- : 120_000;
-}
-
-/** Max jobs allowed in flight or waiting before new ones are rejected. */
-function maxQueueDepth(): number {
- const parsed = Number(process.env.RENDER_MAX_QUEUE);
- return Number.isFinite(parsed) && parsed >= 1 ? Math.floor(parsed) : 10;
-}
-
-const limit = pLimit(maxConcurrent());
-const jobs = new Map<string, JobState>();
-
-/** Thrown by enqueueRender when the queue is already at maxQueueDepth(). */
-export class QueueFullError extends Error {
- constructor() {
- super("Render queue is full");
- this.name = "QueueFullError";
- }
-}
-
-/**
- * Register a render and kick it off through the concurrency limiter. Returns the
- * `jobId` synchronously — the actual render runs in the background and updates
- * the registry. Never await the returned render work in the request handler.
- */
-export function enqueueRender(input: RenderInput): string {
- if (limit.activeCount + limit.pendingCount >= maxQueueDepth()) {
- throw new QueueFullError();
- }
-
- const jobId = randomUUID();
- const outputPath = path.join(RENDER_WORK_DIR, `${jobId}.mp4`);
-
- const job: JobState = {
- status: "queued",
- progress: 0,
- repo: input.repo,
- createdAt: Date.now(),
- };
- jobs.set(jobId, job);
-
- // Fire-and-forget: the limiter serializes execution, errors are captured into
- // the job state, and we swallow the promise so it never becomes unhandled.
- void limit(() => runRender(jobId, input, outputPath)).catch((err) => {
- const current = jobs.get(jobId);
- if (current && current.status !== "done") {
- current.status = "error";
- current.error = err instanceof Error ? err.message : "Render failed";
- }
- });
-
- return jobId;
-}
-
-/** Snapshot of a job's state, or undefined if the id is unknown. */
-export function getJob(jobId: string): JobState | undefined {
- return jobs.get(jobId);
-}
-
-/** Drop a job from the registry (called after its file is cleaned up). */
-export function deleteJob(jobId: string): void {
- jobs.delete(jobId);
-}
-
-/** Read-only view of the registry for the TTL sweep. */
-export function listJobs(): ReadonlyMap<string, JobState> {
- return jobs;
-}
-
-async function runRender(
- jobId: string,
- input: RenderInput,
- outputPath: string,
-): Promise<void> {
- const job = jobs.get(jobId);
- if (!job) return; // deleted before it got a slot
-
- job.status = "rendering";
-
- await mkdir(RENDER_WORK_DIR, { recursive: true });
-
- // Per-render timeout: abort stuck Chromium so a wedged render can't hold a
- // semaphore slot forever.
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), renderTimeoutMs());
-
- try {
- await renderStarsVideo({
- inputProps: input,
- orientation: input.orientation,
- outputPath,
- signal: controller.signal,
- onProgress: (progress) => {
- const current = jobs.get(jobId);
- if (current) current.progress = progress;
- },
- });
-
- job.status = "done";
- job.progress = 1;
- job.outputPath = outputPath;
- } catch (err) {
- job.status = "error";
- job.error = controller.signal.aborted
- ? "Render timed out"
- : err instanceof Error
- ? err.message
- : "Render failed";
- } finally {
- clearTimeout(timeout);
- }
-}
diff --git a/lib/server/render.ts b/lib/server/render.ts
deleted file mode 100644
index 458df858..00000000
--- a/lib/server/render.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-import "server-only";
-import {
- makeCancelSignal,
- renderMedia,
- selectComposition,
-} from "@remotion/renderer";
-import { getServeUrl } from "./bundle";
-import type { Orientation, RenderInput } from "./validate-input";
-
-/**
- * Server-side MP4 render of the `github-stars` composition. Runs full native
- * quality (this is the 8-core box, not a weak client): horizontal 1280×720,
- * vertical 720×1280, 30fps — no downscale. Width/height are overridden per
- * orientation on the selected composition so a single bundle entry serves both.
- */
-
-const COMPOSITION_ID = "github-stars";
-
-/** Native render dimensions per orientation (no client downscale). */
-function dimsFor(orientation: Orientation): { width: number; height: number } {
- return orientation === "vertical"
- ? { width: 720, height: 1280 }
- : { width: 1280, height: 720 };
-}
-
-/** Concurrency (Chromium tabs) for a single render; env-tunable, default 4. */
-function remotionConcurrency(): number {
- const parsed = Number(process.env.REMOTION_CONCURRENCY);
- return Number.isFinite(parsed) && parsed >= 1 ? Math.floor(parsed) : 4;
-}
-
-export interface RenderStarsVideoOptions {
- /** Validated, render-ready props (see parseRenderInput). */
- inputProps: RenderInput;
- /** Drives the output dimensions (overrides the composition defaults). */
- orientation: Orientation;
- /** Absolute path the encoded MP4 is written to. */
- outputPath: string;
- /** Render progress in [0, 1]. */
- onProgress?: (progress: number) => void;
- /** Abort the render (e.g. client disconnect / timeout) → cancels Chromium. */
- signal?: AbortSignal;
-}
-
-/**
- * Render the composition to `outputPath` and resolve with that same path.
- * Bridges a standard AbortSignal onto Remotion's CancelSignal so callers can
- * kill a stuck/abandoned render.
- */
-export async function renderStarsVideo({
- inputProps,
- orientation,
- outputPath,
- onProgress,
- signal,
-}: RenderStarsVideoOptions): Promise<string> {
- if (signal?.aborted) {
- throw new Error("Render aborted before it started");
- }
-
- const serveUrl = await getServeUrl();
- const { width, height } = dimsFor(orientation);
-
- const composition = await selectComposition({
- serveUrl,
- id: COMPOSITION_ID,
- inputProps,
- });
-
- // Bridge AbortSignal → Remotion CancelSignal.
- const { cancelSignal, cancel } = makeCancelSignal();
- const onAbort = () => cancel();
- signal?.addEventListener("abort", onAbort, { once: true });
-
- try {
- await renderMedia({
- composition: { ...composition, width, height },
- serveUrl,
- codec: "h264",
- inputProps,
- outputLocation: outputPath,
- concurrency: remotionConcurrency(),
- cancelSignal,
- onProgress: onProgress
- ? ({ progress }) => onProgress(progress)
- : undefined,
- });
- } finally {
- signal?.removeEventListener("abort", onAbort);
- }
-
- return outputPath;
-}
diff --git a/lib/server/validate-input.ts b/lib/server/validate-input.ts
deleted file mode 100644
index ffd1467e..00000000
--- a/lib/server/validate-input.ts
+++ /dev/null
@@ -1,203 +0,0 @@
-import "server-only";
-
-/**
- * Strict server-side validation of the render payload. Renders cost real CPU on
- * the box, so this is the gate that stops a crafted/oversized request from
- * blowing up Chromium: caps the stargazer count + string sizes, enums the
- * orientation/theme, clamps the numbers, and only lets avatar URLs through
- * whose host is on the GitHub avatar allowlist (avatars are fetched by the
- * headless browser → pinning the host closes the SSRF window instead of just
- * narrowing it). Throws a typed 400 error on anything outside the rules.
- */
-
-export type Orientation = "horizontal" | "vertical";
-export type Theme = "light" | "dark";
-
-export type RenderStargazer = {
- login: string;
- avatarUrl: string;
- /** ISO date string, e.g. "2021-03-04" */
- starredAt: string;
-};
-
-export type RenderInput = {
- repo: string;
- totalStars: number;
- stargazers: RenderStargazer[];
- orientation: Orientation;
- accentColor: string;
- speed: number;
- theme: Theme;
-};
-
-/** Thrown on invalid input; carries the HTTP status the API route should map to. */
-export class RenderInputError extends Error {
- readonly status = 400 as const;
- constructor(message: string) {
- super(message);
- this.name = "RenderInputError";
- }
-}
-
-// --- Limits ----------------------------------------------------------------
-const MAX_STARGAZERS = 60; // matches the composition's own downsample cap
-const MAX_REPO_LEN = 200;
-const MAX_LOGIN_LEN = 100;
-const MAX_AVATAR_URL_LEN = 512;
-const MAX_STARRED_AT_LEN = 40;
-const MAX_TOTAL_STARS = 100_000_000;
-const MIN_SPEED = 1;
-const MAX_SPEED = 4;
-
-const HEX_COLOR = /^#[0-9a-fA-F]{3,8}$/;
-const ALLOWED_AVATAR_HOSTS = new Set(["avatars.githubusercontent.com"]);
-
-const DEFAULT_ACCENT = "#ffbb00";
-const DEFAULT_SPEED = 1;
-const DEFAULT_THEME: Theme = "light";
-
-// --- Field helpers (pure) --------------------------------------------------
-
-function isPlainObject(v: unknown): v is Record<string, unknown> {
- return typeof v === "object" && v !== null && !Array.isArray(v);
-}
-
-function requireString(value: unknown, field: string, maxLen: number): string {
- if (typeof value !== "string") {
- throw new RenderInputError(`"${field}" must be a string`);
- }
- if (value.length === 0) {
- throw new RenderInputError(`"${field}" must not be empty`);
- }
- if (value.length > maxLen) {
- throw new RenderInputError(`"${field}" exceeds ${maxLen} characters`);
- }
- return value;
-}
-
-function requireFiniteNumber(value: unknown, field: string): number {
- const n = typeof value === "string" ? Number(value) : value;
- if (typeof n !== "number" || !Number.isFinite(n)) {
- throw new RenderInputError(`"${field}" must be a finite number`);
- }
- return n;
-}
-
-function clamp(n: number, min: number, max: number): number {
- return Math.min(max, Math.max(min, n));
-}
-
-function parseStargazer(value: unknown, index: number): RenderStargazer {
- if (!isPlainObject(value)) {
- throw new RenderInputError(`stargazers[${index}] must be an object`);
- }
- const login = requireString(
- value.login,
- `stargazers[${index}].login`,
- MAX_LOGIN_LEN,
- );
- const avatarUrl = requireString(
- value.avatarUrl,
- `stargazers[${index}].avatarUrl`,
- MAX_AVATAR_URL_LEN,
- );
- let parsedAvatarUrl: URL;
- try {
- parsedAvatarUrl = new URL(avatarUrl);
- } catch {
- throw new RenderInputError(
- `stargazers[${index}].avatarUrl must be a valid URL`,
- );
- }
- if (
- parsedAvatarUrl.protocol !== "https:" ||
- !ALLOWED_AVATAR_HOSTS.has(parsedAvatarUrl.hostname)
- ) {
- throw new RenderInputError(
- `stargazers[${index}].avatarUrl must be a GitHub avatar URL`,
- );
- }
- const starredAt = requireString(
- value.starredAt,
- `stargazers[${index}].starredAt`,
- MAX_STARRED_AT_LEN,
- );
- return { login, avatarUrl, starredAt };
-}
-
-// --- Public entrypoint -----------------------------------------------------
-
-/**
- * Validate + normalize an untrusted request body into render-ready props.
- * Cosmetic fields (accentColor, speed, theme) default when omitted; data fields
- * (repo, totalStars, stargazers, orientation) are required.
- */
-export function parseRenderInput(body: unknown): RenderInput {
- if (!isPlainObject(body)) {
- throw new RenderInputError("request body must be a JSON object");
- }
-
- const repo = requireString(body.repo, "repo", MAX_REPO_LEN);
-
- const totalStars = Math.floor(
- clamp(
- requireFiniteNumber(body.totalStars, "totalStars"),
- 0,
- MAX_TOTAL_STARS,
- ),
- );
-
- if (!Array.isArray(body.stargazers)) {
- throw new RenderInputError(`"stargazers" must be an array`);
- }
- if (body.stargazers.length > MAX_STARGAZERS) {
- throw new RenderInputError(
- `"stargazers" exceeds the ${MAX_STARGAZERS}-item limit`,
- );
- }
- const stargazers = body.stargazers.map(parseStargazer);
-
- if (body.orientation !== "horizontal" && body.orientation !== "vertical") {
- throw new RenderInputError(
- `"orientation" must be "horizontal" or "vertical"`,
- );
- }
- const orientation: Orientation = body.orientation;
-
- let accentColor = DEFAULT_ACCENT;
- if (body.accentColor !== undefined) {
- accentColor = requireString(body.accentColor, "accentColor", 32);
- if (!HEX_COLOR.test(accentColor)) {
- throw new RenderInputError(
- `"accentColor" must be a hex color (e.g. #ffbb00)`,
- );
- }
- }
-
- let speed = DEFAULT_SPEED;
- if (body.speed !== undefined) {
- speed = clamp(
- requireFiniteNumber(body.speed, "speed"),
- MIN_SPEED,
- MAX_SPEED,
- );
- }
-
- let theme: Theme = DEFAULT_THEME;
- if (body.theme !== undefined) {
- if (body.theme !== "light" && body.theme !== "dark") {
- throw new RenderInputError(`"theme" must be "light" or "dark"`);
- }
- theme = body.theme;
- }
-
- return {
- repo,
- totalStars,
- stargazers,
- orientation,
- accentColor,
- speed,
- theme,
- };
-}
diff --git a/next.config.ts b/next.config.ts
index 649a9b8f..eb67df46 100644
--- a/next.config.ts
+++ b/next.config.ts
@@ -36,17 +36,8 @@ const nextConfig: NextConfig = {
experimental: {
optimizePackageImports: ["motion"],
},
- // Remotion's server packages are Node-only and ship native binaries (esbuild +
- // the platform-specific @remotion/compositor-*). They must NOT be bundled by
- // Turbopack/webpack — keep them external so they're require()'d at runtime in
- // the /api/render route. Without this the build fails resolving the compositor
- // binaries + reading the esbuild binary as source.
- serverExternalPackages: [
- "@remotion/renderer",
- "@remotion/bundler",
- "esbuild",
- "@takumi-rs/core",
- ],
+ // takumi's OG renderer is a native binding: keep it out of the server bundle.
+ serverExternalPackages: ["@takumi-rs/core"],
// The /mcp route reads the remocn skill's archetype recipes from disk at
// runtime (lib/mcp/archetype-files.ts). Docker copies the whole tree, but
// trace them explicitly so standalone/traced output keeps them too.
diff --git a/nixpacks.toml b/nixpacks.toml
deleted file mode 100644
index c812709b..00000000
--- a/nixpacks.toml
+++ /dev/null
@@ -1,31 +0,0 @@
-# Nixpacks build config for Coolify (default build pack — used unless you switch
-# the resource to the Dockerfile build pack).
-#
-# Nixpacks does NOT install Chromium's system libraries by default, so
-# @remotion/renderer can't launch headless Chrome. The aptPkgs below add exactly
-# the runtime libs + fonts Remotion needs.
-#
-# IMPORTANT: the libs alone aren't enough. The Coolify BUILD command must also
-# bake in the browser + the Remotion bundle, e.g.:
-#
-# bun install && bun run build && bun run remotion:browser && bun run bundle:remotion
-#
-# (`remotion:browser` downloads the Chrome Headless Shell via @remotion/renderer's
-# ensureBrowser() — NOT `bunx remotion ...`, the `remotion` pkg has no CLI binary;
-# `bundle:remotion` pre-builds .remotion-bundle/ so the serveUrl is ready at boot.)
-# Start command (Coolify UI): bun run start
-#
-# NOTE: the Nixpacks base image is Ubuntu Noble (24.04), where the time_t (t64)
-# transition RENAMED several libs — libasound2 → libasound2t64, libatk1.0-0 →
-# libatk1.0-0t64, libatk-bridge2.0-0 → libatk-bridge2.0-0t64, libcups2 →
-# libcups2t64, libgtk-3-0 → libgtk-3-0t64. The t64 names below are required on
-# Noble. (The Dockerfile build pack uses Debian Bookworm, where the OLD names
-# apply — that's why the two lists differ.)
-
-[phases.setup]
-aptPkgs = [
- "ca-certificates","fonts-liberation","libasound2t64","libatk-bridge2.0-0t64",
- "libatk1.0-0t64","libcups2t64","libdbus-1-3","libdrm2","libgbm1","libgtk-3-0t64",
- "libnss3","libpango-1.0-0","libxcomposite1","libxdamage1","libxfixes3",
- "libxkbcommon0","libxrandr2"
-]
diff --git a/package.json b/package.json
index 181e8d8e..6c9406f4 100644
--- a/package.json
+++ b/package.json
@@ -35,8 +35,6 @@
"studio": "remotion studio",
"studio:motion-pack": "remotion studio src/remotion/motion-pack-root.tsx",
"studio:design-audit": "remotion studio src/remotion/design-audit-root.tsx",
- "remotion:browser": "bun scripts/ensure-browser.mts",
- "bundle:remotion": "bun scripts/bundle-remotion.mts",
"render:demos": "bun scripts/render-demos.mts",
"spike:canvas": "bun scripts/canvas-determinism.mts",
"render:not-found": "bun scripts/render-not-found.mts",
diff --git a/remotion.config.ts b/remotion.config.ts
index f2dc3bd7..1d81b1da 100644
--- a/remotion.config.ts
+++ b/remotion.config.ts
@@ -1,9 +1,8 @@
import path from "node:path";
import { Config } from "@remotion/cli/config";
-// The Remotion bundler (webpack) doesn't read tsconfig `paths` — mirror the
-// alias override from scripts/bundle-remotion.mts so `@/registry/...` resolves
-// in Studio too.
+// The Remotion bundler (webpack) doesn't read tsconfig `paths`, so teach it the
+// `@/* → project root` alias that `@/registry/...` imports rely on.
Config.overrideWebpackConfig((config) => ({
...config,
resolve: {
diff --git a/scripts/bundle-remotion.mts b/scripts/bundle-remotion.mts
deleted file mode 100644
index e56d184a..00000000
--- a/scripts/bundle-remotion.mts
+++ /dev/null
@@ -1,49 +0,0 @@
-import path from "node:path";
-import { fileURLToPath } from "node:url";
-import { bundle } from "@remotion/bundler";
-
-/**
- * Pre-bundle the Remotion entry into `.remotion-bundle/` so the server has a
- * ready serveUrl at boot (no slow bundle-on-first-render). Baked into the Docker
- * image during build (see Dockerfile) — `lib/server/bundle.ts` returns this dir
- * when present, otherwise it lazily bundles at runtime.
- *
- * Run: `bun run bundle:remotion`
- */
-
-const here = path.dirname(fileURLToPath(import.meta.url));
-const root = path.resolve(here, "..");
-
-async function main() {
- const entryPoint = path.join(root, "src", "remotion", "index.ts");
- const outDir = path.join(root, ".remotion-bundle");
-
- console.log(`Bundling Remotion entry: ${entryPoint}`);
- const serveUrl = await bundle({
- entryPoint,
- outDir,
- // The Remotion bundler (webpack) doesn't read tsconfig `paths`, so teach it
- // the `@/* → project root` alias that src/remotion/Root.tsx + the registry
- // component's config rely on. Without this `@/registry/...` fails to resolve.
- webpackOverride: (config) => ({
- ...config,
- resolve: {
- ...config.resolve,
- alias: {
- ...(config.resolve?.alias ?? {}),
- "@/components/remocn/number-wheel$": path.join(
- root,
- "registry/remocn/number-wheel/index.tsx",
- ),
- "@": root,
- },
- },
- }),
- });
- console.log(`Remotion bundle ready at: ${serveUrl}`);
-}
-
-main().catch((err) => {
- console.error("Remotion bundle failed:", err);
- process.exit(1);
-});
diff --git a/scripts/ensure-browser.mts b/scripts/ensure-browser.mts
deleted file mode 100644
index 86b9603e..00000000
--- a/scripts/ensure-browser.mts
+++ /dev/null
@@ -1,12 +0,0 @@
-/**
- * Download Remotion's Chrome Headless Shell ahead of time so the first render
- * doesn't pay for it at runtime. Uses @remotion/renderer's `ensureBrowser()`
- * directly — the `remotion` package has NO CLI binary (that's `@remotion/cli`,
- * which we don't install), so `bunx remotion browser ensure` does not work here.
- *
- * Run: `bun run remotion:browser` (baked into the Docker / Coolify build).
- */
-import { ensureBrowser } from "@remotion/renderer";
-
-await ensureBrowser();
-console.log("Remotion browser (Chrome Headless Shell) ensured.");