🎥 Make videos programmatically with React
move files around
Jonny Burgere973415d33a6
diff --git a/packages/template-vercel/src/app/api/render/add-bundle-to-sandbox.ts b/packages/template-vercel/src/app/api/render/add-bundle-to-sandbox.tsdeleted file mode 100644index 15dd56e700..0000000000--- a/packages/template-vercel/src/app/api/render/add-bundle-to-sandbox.ts+++ /dev/null@@ -1,30 +0,0 @@-import path from "path";-import { ensureLocalBundle, getRemotionBundleFiles } from "./helpers";-import { BUILD_DIR } from "../../../../build-dir.mjs";-import { Sandbox } from "@vercel/sandbox";--export const addBundleToSandbox = async (- sandbox: Sandbox & AsyncDisposable,-) => {- await ensureLocalBundle();- const bundleFiles = await getRemotionBundleFiles();-- const dirs = new Set<string>();- for (const file of bundleFiles) {- const dir = path.dirname(file.path);- if (dir && dir !== ".") {- dirs.add(dir);- }- }-- for (const dir of Array.from(dirs).sort()) {- await sandbox.mkDir(BUILD_DIR + "/" + dir);- }-- await sandbox.writeFiles(- bundleFiles.map((file) => ({- path: BUILD_DIR + "/" + file.path,- content: file.content,- })),- );-};diff --git a/packages/template-vercel/src/app/api/render/create-sandbox.ts b/packages/template-vercel/src/app/api/render/create-sandbox.tsdeleted file mode 100644index a1c5751a38..0000000000--- a/packages/template-vercel/src/app/api/render/create-sandbox.ts+++ /dev/null@@ -1,169 +0,0 @@-import { Sandbox } from "@vercel/sandbox";-import { VERSION } from "remotion/version";-import {- createDisposableSandbox,- getEnsureBrowserScript,- OnProgressFn,-} from "./helpers";-import { addBundleToSandbox } from "./add-bundle-to-sandbox";--export async function createSandbox({- onProgress,-}: {- onProgress: OnProgressFn;-}): Promise<Sandbox & AsyncDisposable> {- const sandbox = await createDisposableSandbox({- runtime: "node24",- timeout: 5 * 60 * 1000,- });-- const preparingPhase = "Preparing machine...";- const preparingSubtitle = process.env.VERCEL- ? "This only needs to be done once."- : "This is only needed during development.";-- // Preparation has 3 stages with weights:- // - System dependencies: 60%- // - Copying bundle: 20%- // - Downloading browser: 20%- const WEIGHT_SYS_DEPS = 0.6;- const WEIGHT_BUNDLE = 0.2;- const WEIGHT_BROWSER = 0.2;-- await onProgress({- type: "phase",- phase: preparingPhase,- subtitle: preparingSubtitle,- progress: 0,- });-- // Stage 1: Install system dependencies (60%)- const sysInstallCmd = await sandbox.runCommand({- cmd: "sudo",- args: [- "dnf",- "install",- "-y",- "nss",- "atk",- "at-spi2-atk",- "cups-libs",- "libdrm",- "libXcomposite",- "libXdamage",- "libXrandr",- "mesa-libgbm",- "alsa-lib",- "pango",- "gtk3",- ],- detached: true,- });-- // We empirically tested how many lines are printed to stdout when installing the system dependencies:- const EXPECTED_SYS_INSTALL_LINES = 272;- let sysInstallLineCount = 0;- // eslint-disable-next-line @typescript-eslint/no-unused-vars- for await (const _log of sysInstallCmd.logs()) {- sysInstallLineCount++;- const stageProgress = Math.min(- sysInstallLineCount / EXPECTED_SYS_INSTALL_LINES,- 1,- );- await onProgress({- type: "phase",- phase: preparingPhase,- subtitle: preparingSubtitle,- progress: stageProgress * WEIGHT_SYS_DEPS,- });- }-- const sysInstallResult = await sysInstallCmd.wait();- if (sysInstallResult.exitCode !== 0) {- throw new Error(- `System dependencies install failed: ${await sysInstallResult.stderr()}`,- );- }-- await onProgress({- type: "phase",- phase: "Adding Remotion video to Sandbox...",- progress: 0,- subtitle: preparingSubtitle,- });-- await addBundleToSandbox(sandbox);-- await onProgress({- type: "phase",- phase: preparingPhase,- subtitle: preparingSubtitle,- progress: WEIGHT_SYS_DEPS + WEIGHT_BUNDLE,- });-- // Install renderer and blob SDK (part of bundle stage, no separate progress)- const installCmd = await sandbox.runCommand({- cmd: "pnpm",- args: [`i`, `@remotion/renderer@${VERSION}`, `@vercel/blob`],- detached: true,- });-- // eslint-disable-next-line @typescript-eslint/no-unused-vars- for await (const _log of installCmd.logs()) {- // Consume logs without displaying- }-- const installResult = await installCmd.wait();- if (installResult.exitCode !== 0) {- throw new Error(`pnpm install failed: ${await installResult.stderr()}`);- }-- // Stage 3: Download browser (20%)- const ensureBrowserScript = await getEnsureBrowserScript();- await sandbox.writeFiles([- {- path: "ensure-browser.ts",- content: ensureBrowserScript,- },- ]);-- const ensureBrowserCmd = await sandbox.runCommand({- cmd: "node",- args: ["--strip-types", "ensure-browser.ts"],- detached: true,- });-- for await (const log of ensureBrowserCmd.logs()) {- // Parse browser download progress from JSON output- if (log.stream === "stdout") {- try {- const message = JSON.parse(log.data);- if (message.type === "browser-progress") {- const browserProgress = message.percent ?? 0;- await onProgress({- type: "phase",- phase: preparingPhase,- subtitle: preparingSubtitle,- progress:- WEIGHT_SYS_DEPS +- WEIGHT_BUNDLE +- browserProgress * WEIGHT_BROWSER,- });- continue;- }- } catch {- // Not JSON, ignore- }- }- // Ignore other logs during preparation- }-- const ensureBrowserResult = await ensureBrowserCmd.wait();- if (ensureBrowserResult.exitCode !== 0) {- throw new Error(- `ensure-browser failed: ${await ensureBrowserResult.stderr()} ${await ensureBrowserResult.stdout()}`,- );- }-- return sandbox;-}diff --git a/packages/template-vercel/src/app/api/render/helpers.ts b/packages/template-vercel/src/app/api/render/helpers.tsindex 0d0db56277..0b758b0173 100644--- a/packages/template-vercel/src/app/api/render/helpers.ts+++ b/packages/template-vercel/src/app/api/render/helpers.ts@@ -1,9 +1,6 @@import { Sandbox } from "@vercel/sandbox";-import { execSync } from "child_process";-import { existsSync } from "fs";-import { readdir, readFile } from "fs/promises";+import { readFile } from "fs/promises";import path from "path";-import { BUILD_DIR } from "../../../../build-dir.mjs";export const createDisposableSandbox = async (options: Parameters<typeof Sandbox.create>[0],@@ -26,33 +23,6 @@ export const createDisposableWriter = (});};-export async function getRemotionBundleFiles(): Promise<- { path: string; content: Buffer }[]-> {- const bundleDir = path.join(process.cwd(), BUILD_DIR);-- const remotionDir = bundleDir;-- const files: { path: string; content: Buffer }[] = [];-- async function readDirRecursive(dir: string, basePath: string = "") {- const entries = await readdir(dir, { withFileTypes: true });- for (const entry of entries) {- const fullPath = path.join(dir, entry.name);- const relativePath = path.join(basePath, entry.name);- if (entry.isDirectory()) {- await readDirRecursive(fullPath, relativePath);- } else {- const content = await readFile(fullPath);- files.push({ path: relativePath, content });- }- }- }-- await readDirRecursive(remotionDir);- return files;-}-export type RenderProgress =| { type: "phase"; phase: string; progress: number; subtitle?: string }| { type: "done"; url: string; size: number }@@ -64,31 +34,7 @@ export function formatSSE(message: RenderProgress): string {return `data: ${JSON.stringify(message)}\n\n`;}-export async function ensureLocalBundle(): Promise<void> {- if (process.env.VERCEL) {- return;- }-- const bundleDir = path.join(process.cwd(), BUILD_DIR);- if (!existsSync(bundleDir)) {- try {- execSync(`node_modules/.bin/remotion bundle --out-dir ./${BUILD_DIR}`, {- cwd: process.cwd(),- stdio: "pipe",- });- } catch (e) {- const stderr = (e as { stderr?: Buffer }).stderr?.toString() ?? "";- throw new Error(`Remotion bundle failed: ${stderr}`);- }- }-}-export async function getRenderScript(): Promise<Buffer> {const renderScriptPath = path.join(process.cwd(), "render.ts");return readFile(renderScriptPath);}--export async function getEnsureBrowserScript(): Promise<Buffer> {- const scriptPath = path.join(process.cwd(), "ensure-browser.ts");- return readFile(scriptPath);-}diff --git a/packages/template-vercel/src/app/api/render/run-render-in-sandbox.ts b/packages/template-vercel/src/app/api/render/render.tssimilarity index 80%rename from packages/template-vercel/src/app/api/render/run-render-in-sandbox.tsrename to packages/template-vercel/src/app/api/render/render.tsindex ed9e44e601..8f1cfc8a48 100644--- a/packages/template-vercel/src/app/api/render/run-render-in-sandbox.ts+++ b/packages/template-vercel/src/app/api/render/render.ts@@ -1,21 +1,23 @@import { Sandbox } from "@vercel/sandbox";import { COMP_NAME } from "../../../../types/constants";-import { getRenderScript, OnProgressFn } from "./helpers";+import { getRenderScript } from "./helpers";import { BUILD_DIR } from "../../../../build-dir.mjs";import type { RenderConfig } from "../../../../render";-export async function runRenderInSandbox({+export type RenderInSandboxProgress =+ | { type: "render-progress"; progress: number }+ | { type: "uploading" }+ | { type: "done"; url: string; size: number };++export async function renderInSandbox({sandbox,inputProps,onProgress,}: {sandbox: Sandbox & AsyncDisposable;inputProps: Record<string, unknown>;- onProgress: OnProgressFn;+ onProgress: (progress: RenderInSandboxProgress) => Promise<void>;}): Promise<void> {- const renderingPhase = "Rendering video...";- await onProgress({ type: "phase", phase: renderingPhase, progress: 0 });-// Use the local bundle copied to the sandboxconst serveUrl = `/vercel/sandbox/${BUILD_DIR}`;@@ -57,16 +59,11 @@ export async function runRenderInSandbox({const message = JSON.parse(log.data);if (message.type === "progress") {await onProgress({- type: "phase",- phase: renderingPhase,+ type: "render-progress",progress: message.progress,});} else if (message.type === "uploading") {- await onProgress({- type: "phase",- phase: "Uploading video...",- progress: 1,- });+ await onProgress({ type: "uploading" });} else if (message.type === "done") {doneUrl = message.url;doneSize = message.size;@@ -88,9 +85,5 @@ export async function runRenderInSandbox({throw new Error("Render script did not return upload result");}- await onProgress({- type: "done",- url: doneUrl,- size: doneSize,- });+ await onProgress({ type: "done", url: doneUrl, size: doneSize });}diff --git a/packages/template-vercel/src/app/api/render/route.ts b/packages/template-vercel/src/app/api/render/route.tsindex b7203a52cc..c110520dae 100644--- a/packages/template-vercel/src/app/api/render/route.ts+++ b/packages/template-vercel/src/app/api/render/route.ts@@ -5,8 +5,8 @@ import {formatSSE,type RenderProgress,} from "./helpers";-import { getOrCreateSandbox } from "./get-or-create-sandbox";-import { runRenderInSandbox } from "./run-render-in-sandbox";+import { reuseOrCreateSandbox } from "./sandbox/reuse-or-create-sandbox";+import { renderInSandbox } from "./render";export async function POST(req: Request) {const encoder = new TextEncoder();@@ -25,11 +25,21 @@ export async function POST(req: Request) {const payload = await req.json();const body = RenderRequest.parse(payload);- await using sandbox = await getOrCreateSandbox(send);- await runRenderInSandbox({+ await using sandbox = await reuseOrCreateSandbox(send);+ const renderingPhase = "Rendering video...";+ await send({ type: "phase", phase: renderingPhase, progress: 0 });+ await renderInSandbox({sandbox,inputProps: body.inputProps,- onProgress: send,+ onProgress: async (update) => {+ if (update.type === "render-progress") {+ await send({ type: "phase", phase: renderingPhase, progress: update.progress });+ } else if (update.type === "uploading") {+ await send({ type: "phase", phase: "Uploading video...", progress: 1 });+ } else if (update.type === "done") {+ await send({ type: "done", url: update.url, size: update.size });+ }+ },});} catch (err) {console.log(err);diff --git a/packages/template-vercel/src/app/api/render/sandbox/add-bundle.ts b/packages/template-vercel/src/app/api/render/sandbox/add-bundle.tsnew file mode 100644index 0000000000..81ae1138e9--- /dev/null+++ b/packages/template-vercel/src/app/api/render/sandbox/add-bundle.ts@@ -0,0 +1,78 @@+import path from "path";+import { BUILD_DIR } from "../../../../../build-dir.mjs";+import { Sandbox } from "@vercel/sandbox";+import { readdir, readFile } from "fs/promises";+import { existsSync } from "fs";+import { execSync } from "child_process";++export const addBundleToSandbox = async (+ sandbox: Sandbox & AsyncDisposable,+) => {+ await ensureLocalBundle();+ const bundleFiles = await getRemotionBundleFiles();++ const dirs = new Set<string>();+ for (const file of bundleFiles) {+ const dir = path.dirname(file.path);+ if (dir && dir !== ".") {+ dirs.add(dir);+ }+ }++ for (const dir of Array.from(dirs).sort()) {+ await sandbox.mkDir(BUILD_DIR + "/" + dir);+ }++ await sandbox.writeFiles(+ bundleFiles.map((file) => ({+ path: BUILD_DIR + "/" + file.path,+ content: file.content,+ })),+ );+};++async function getRemotionBundleFiles(): Promise<+ { path: string; content: Buffer }[]+> {+ const bundleDir = path.join(process.cwd(), BUILD_DIR);++ const remotionDir = bundleDir;++ const files: { path: string; content: Buffer }[] = [];++ async function readDirRecursive(dir: string, basePath: string = "") {+ const entries = await readdir(dir, { withFileTypes: true });+ for (const entry of entries) {+ const fullPath = path.join(dir, entry.name);+ const relativePath = path.join(basePath, entry.name);+ if (entry.isDirectory()) {+ await readDirRecursive(fullPath, relativePath);+ } else {+ const content = await readFile(fullPath);+ files.push({ path: relativePath, content });+ }+ }+ }++ await readDirRecursive(remotionDir);+ return files;+}++async function ensureLocalBundle(): Promise<void> {+ if (process.env.VERCEL) {+ return;+ }++ const bundleDir = path.join(process.cwd(), BUILD_DIR);+ if (!existsSync(bundleDir)) {+ try {+ execSync(`node_modules/.bin/remotion bundle --out-dir ./${BUILD_DIR}`, {+ cwd: process.cwd(),+ stdio: "pipe",+ });+ } catch (e) {+ const stderr = (e as { stderr?: Buffer }).stderr?.toString() ?? "";+ throw new Error(`Remotion bundle failed: ${stderr}`);+ }+ }+}diff --git a/packages/template-vercel/src/app/api/render/sandbox/create-sandbox.ts b/packages/template-vercel/src/app/api/render/sandbox/create-sandbox.tsnew file mode 100644index 0000000000..5ea4477ad4--- /dev/null+++ b/packages/template-vercel/src/app/api/render/sandbox/create-sandbox.ts@@ -0,0 +1,86 @@+import { Sandbox } from "@vercel/sandbox";+import { createDisposableSandbox, OnProgressFn } from "../helpers";+import { addBundleToSandbox } from "./add-bundle";+import { installSystemDependencies } from "./install-system-dependencies";+import { installJsDependencies } from "./install-js-dependencies";+import { installBrowser } from "./install-browser";++export async function createSandbox({+ onProgress,+}: {+ onProgress: OnProgressFn;+}): Promise<Sandbox & AsyncDisposable> {+ const sandbox = await createDisposableSandbox({+ runtime: "node24",+ timeout: 5 * 60 * 1000,+ });++ const preparingPhase = "Preparing machine...";+ const preparingSubtitle = process.env.VERCEL+ ? "This only needs to be done once."+ : "This is only needed during development.";++ // Preparation has 3 stages with weights:+ // - System dependencies: 60%+ // - Copying bundle: 20%+ // - Downloading browser: 20%+ const WEIGHT_SYS_DEPS = 0.6;+ const WEIGHT_BUNDLE = 0.2;+ const WEIGHT_BROWSER = 0.2;++ await onProgress({+ type: "phase",+ phase: preparingPhase,+ subtitle: preparingSubtitle,+ progress: 0,+ });++ // Stage 1: Install system dependencies (60%)+ await installSystemDependencies({+ sandbox,+ onProgress: async (stageProgress: number) => {+ await onProgress({+ type: "phase",+ phase: preparingPhase,+ subtitle: preparingSubtitle,+ progress: stageProgress * WEIGHT_SYS_DEPS,+ });+ },+ });++ await onProgress({+ type: "phase",+ phase: "Adding Remotion video to Sandbox...",+ progress: 0,+ subtitle: preparingSubtitle,+ });++ // Stage 2: Copy Remotion bundle (20%)+ await addBundleToSandbox(sandbox);++ await onProgress({+ type: "phase",+ phase: preparingPhase,+ subtitle: preparingSubtitle,+ progress: WEIGHT_SYS_DEPS + WEIGHT_BUNDLE,+ });++ // Install renderer and blob SDK+ await installJsDependencies({ sandbox });++ // Stage 3: Download browser (20%)+ await installBrowser({+ sandbox,+ onProgress: async (browserProgress: number) => {+ await onProgress({+ type: "phase",+ phase: preparingPhase,+ subtitle: preparingSubtitle,+ progress:+ WEIGHT_SYS_DEPS + WEIGHT_BUNDLE + browserProgress * WEIGHT_BROWSER,+ });+ },+ });++ return sandbox;+}diff --git a/packages/template-vercel/src/app/api/render/sandbox/install-browser.ts b/packages/template-vercel/src/app/api/render/sandbox/install-browser.tsnew file mode 100644index 0000000000..015fd5928d--- /dev/null+++ b/packages/template-vercel/src/app/api/render/sandbox/install-browser.ts@@ -0,0 +1,51 @@+import { Sandbox } from "@vercel/sandbox";+import path from "path";+import { readFile } from "fs/promises";++async function getEnsureBrowserScript(): Promise<Buffer> {+ const scriptPath = path.join(process.cwd(), "ensure-browser.ts");+ return readFile(scriptPath);+}++export async function installBrowser({+ sandbox,+ onProgress,+}: {+ sandbox: Sandbox;+ onProgress: (progress: number) => Promise<void>;+}): Promise<void> {+ const ensureBrowserScript = await getEnsureBrowserScript();+ await sandbox.writeFiles([+ {+ path: "ensure-browser.ts",+ content: ensureBrowserScript,+ },+ ]);++ const ensureBrowserCmd = await sandbox.runCommand({+ cmd: "node",+ args: ["--strip-types", "ensure-browser.ts"],+ detached: true,+ });++ for await (const log of ensureBrowserCmd.logs()) {+ if (log.stream === "stdout") {+ try {+ const message = JSON.parse(log.data);+ if (message.type === "browser-progress") {+ await onProgress(message.percent ?? 0);+ continue;+ }+ } catch {+ // Not JSON, ignore+ }+ }+ }++ const ensureBrowserResult = await ensureBrowserCmd.wait();+ if (ensureBrowserResult.exitCode !== 0) {+ throw new Error(+ `ensure-browser failed: ${await ensureBrowserResult.stderr()} ${await ensureBrowserResult.stdout()}`,+ );+ }+}diff --git a/packages/template-vercel/src/app/api/render/sandbox/install-js-dependencies.ts b/packages/template-vercel/src/app/api/render/sandbox/install-js-dependencies.tsnew file mode 100644index 0000000000..c5f2803a44--- /dev/null+++ b/packages/template-vercel/src/app/api/render/sandbox/install-js-dependencies.ts@@ -0,0 +1,24 @@+import { Sandbox } from "@vercel/sandbox";+import { VERSION } from "remotion/version";++export async function installJsDependencies({+ sandbox,+}: {+ sandbox: Sandbox;+}): Promise<void> {+ const installCmd = await sandbox.runCommand({+ cmd: "pnpm",+ args: [`i`, `@remotion/renderer@${VERSION}`, `@vercel/blob`],+ detached: true,+ });++ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ for await (const _log of installCmd.logs()) {+ // Consume logs without displaying+ }++ const installResult = await installCmd.wait();+ if (installResult.exitCode !== 0) {+ throw new Error(`pnpm install failed: ${await installResult.stderr()}`);+ }+}diff --git a/packages/template-vercel/src/app/api/render/sandbox/install-system-dependencies.ts b/packages/template-vercel/src/app/api/render/sandbox/install-system-dependencies.tsnew file mode 100644index 0000000000..c865a02440--- /dev/null+++ b/packages/template-vercel/src/app/api/render/sandbox/install-system-dependencies.ts@@ -0,0 +1,51 @@+import { Sandbox } from "@vercel/sandbox";++export async function installSystemDependencies({+ sandbox,+ onProgress,+}: {+ sandbox: Sandbox;+ onProgress: (progress: number) => Promise<void>;+}): Promise<void> {+ const sysInstallCmd = await sandbox.runCommand({+ cmd: "sudo",+ args: [+ "dnf",+ "install",+ "-y",+ "nss",+ "atk",+ "at-spi2-atk",+ "cups-libs",+ "libdrm",+ "libXcomposite",+ "libXdamage",+ "libXrandr",+ "mesa-libgbm",+ "alsa-lib",+ "pango",+ "gtk3",+ ],+ detached: true,+ });++ // We empirically tested how many lines are printed to stdout when installing the system dependencies:+ const EXPECTED_SYS_INSTALL_LINES = 272;+ let sysInstallLineCount = 0;+ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ for await (const _log of sysInstallCmd.logs()) {+ sysInstallLineCount++;+ const stageProgress = Math.min(+ sysInstallLineCount / EXPECTED_SYS_INSTALL_LINES,+ 1,+ );+ await onProgress(stageProgress);+ }++ const sysInstallResult = await sysInstallCmd.wait();+ if (sysInstallResult.exitCode !== 0) {+ throw new Error(+ `System dependencies install failed: ${await sysInstallResult.stderr()}`,+ );+ }+}diff --git a/packages/template-vercel/src/app/api/render/get-or-create-sandbox.ts b/packages/template-vercel/src/app/api/render/sandbox/reuse-or-create-sandbox.tssimilarity index 93%rename from packages/template-vercel/src/app/api/render/get-or-create-sandbox.tsrename to packages/template-vercel/src/app/api/render/sandbox/reuse-or-create-sandbox.tsindex 5f39056082..91bf18f316 100644--- a/packages/template-vercel/src/app/api/render/get-or-create-sandbox.ts+++ b/packages/template-vercel/src/app/api/render/sandbox/reuse-or-create-sandbox.ts@@ -1,11 +1,11 @@import { Sandbox } from "@vercel/sandbox";-import { createDisposableSandbox, OnProgressFn } from "./helpers";+import { createDisposableSandbox, OnProgressFn } from "../helpers";import { createSandbox } from "./create-sandbox";import { getCachedSnapshot, saveSnapshotCache } from "./snapshots";const TIMEOUT = 5 * 60 * 1000;-export async function getOrCreateSandbox(+export async function reuseOrCreateSandbox(onProgress: OnProgressFn,): Promise<Sandbox & AsyncDisposable> {// Check for a cached snapshot (production only)diff --git a/packages/template-vercel/src/app/api/render/snapshots.ts b/packages/template-vercel/src/app/api/render/sandbox/snapshots.tssimilarity index 100%rename from packages/template-vercel/src/app/api/render/snapshots.tsrename to packages/template-vercel/src/app/api/render/sandbox/snapshots.ts