π₯ Make videos programmatically with React
`@remotion/vercel`: Create package for Vercel Sandbox rendering
Jonny Burgerdaf3430fcb09
diff --git a/bun.lock b/bun.lockindex a79121a28d..cb5adf4551 100644--- a/bun.lock+++ b/bun.lock@@ -2174,6 +2174,7 @@"@remotion/player": "workspace:*","@remotion/shapes": "workspace:*","@remotion/tailwind-v4": "workspace:*",+ "@remotion/vercel": "workspace:*","@types/bun": "1.3.3","@vercel/blob": "2.0.1","@vercel/functions": "^3.4.1",@@ -2274,6 +2275,24 @@"react-dom": ">=16.8.0",},},+ "packages/vercel": {+ "name": "@remotion/vercel",+ "version": "4.0.424",+ "dependencies": {+ "remotion": "workspace:*",+ },+ "devDependencies": {+ "@remotion/eslint-config-internal": "workspace:*",+ "@typescript/native-preview": "catalog:",+ "@vercel/blob": "2.0.1",+ "@vercel/sandbox": "1.6.0",+ "eslint": "catalog:",+ },+ "peerDependencies": {+ "@vercel/blob": ">=2.0.0",+ "@vercel/sandbox": ">=1.0.0",+ },+ },"packages/web-renderer": {"name": "@remotion/web-renderer","version": "4.0.424",@@ -3746,6 +3765,8 @@"@remotion/transitions": ["@remotion/transitions@workspace:packages/transitions"],+ "@remotion/vercel": ["@remotion/vercel@workspace:packages/vercel"],+"@remotion/web-renderer": ["@remotion/web-renderer@workspace:packages/web-renderer"],"@remotion/webcodecs": ["@remotion/webcodecs@workspace:packages/webcodecs"],@@ -5864,7 +5885,7 @@"is-boolean-object": ["[email protected]", "", { "dependencies": { "call-bound": "1.0.3", "has-tostringtag": "1.0.2" } }, "sha512-l9qO6eFlUETHtuihLcYOaLKByJ1f+N4kthcU9YjHy3N+B3hWv0y/2Nd0mu/7lTFnRQHTrSdXF50HQ3bl5fEnng=="],- "is-buffer": ["[email protected]", "", {}, "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w=="],+ "is-buffer": ["[email protected]", "", {}, "sha512-i2R6zNFDwgEHJyQUtJEk0XFi1i0dPFn/oqjK3/vPCcDeJvW5NQ83V8QbicfF1SupOaB0h8ntgBC2YiE7dfyctQ=="],"is-bun-module": ["[email protected]", "", { "dependencies": { "semver": "7.6.3" } }, "sha512-AmidtEM6D6NmUiLOvvU7+IePxjEjOzra2h0pSrsfSAcXwl/83zLLXDByafUJy9k/rKK0pvXMLdwKwGHlX2Ke6Q=="],@@ -9382,8 +9403,6 @@"@vanilla-extract/integration/vite": ["[email protected]", "", { "dependencies": { "esbuild": "0.21.5", "postcss": "8.5.1", "rollup": "4.40.1" }, "optionalDependencies": { "fsevents": "2.3.3" }, "peerDependencies": { "@types/node": "20.12.14" }, "optionalPeers": ["@types/node"], "bin": { "vite": "bin/vite.js" } }, "sha512-j3lYzGC3P+B5Yfy/pfKNgVEg4+UtcIJcVRt2cDjIOmhLourAqPqf8P7acgxeiSgUB7E3p2P8/3gNIgDLpwzs4g=="],- "@vercel/blob/is-buffer": ["[email protected]", "", {}, "sha512-i2R6zNFDwgEHJyQUtJEk0XFi1i0dPFn/oqjK3/vPCcDeJvW5NQ83V8QbicfF1SupOaB0h8ntgBC2YiE7dfyctQ=="],-"@vercel/blob/undici": ["[email protected]", "", {}, "sha512-VfQPToRA5FZs/qJxLIinmU59u0r7LXqoJkCzinq3ckNJp3vKEh7jTWN589YQ5+aoAC/TGRLyJLCPKcLQbM8r9g=="],"@vercel/config/zod": ["[email protected]", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],@@ -9858,6 +9877,8 @@"make-dir/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],+ "md5/is-buffer": ["[email protected]", "", {}, "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w=="],+"mdast-util-definitions/@types/unist": ["@types/[email protected]", "", {}, "sha512-dqId9J8K/vGi5Zr7oo212BGii5m3q5Hxlkwy3WpYuKPklmBEvsbMYYyLxAQpSffdLl/gdW0XUpKWFvYmyoWCoQ=="],"mdast-util-directive/@types/unist": ["@types/[email protected]", "", {}, "sha512-dqId9J8K/vGi5Zr7oo212BGii5m3q5Hxlkwy3WpYuKPklmBEvsbMYYyLxAQpSffdLl/gdW0XUpKWFvYmyoWCoQ=="],@@ -11754,8 +11775,6 @@"@mdx-js/mdx/unified/@types/unist": ["@types/[email protected]", "", {}, "sha512-PBjIUxZHOuj0R15/xuwJYjFi+KZdNFrehocChv4g5hu6aFroHue8m0lBP0POdK2nKzbw0cgV1mws8+V/JAcEkQ=="],- "@mdx-js/mdx/unified/is-buffer": ["[email protected]", "", {}, "sha512-i2R6zNFDwgEHJyQUtJEk0XFi1i0dPFn/oqjK3/vPCcDeJvW5NQ83V8QbicfF1SupOaB0h8ntgBC2YiE7dfyctQ=="],-"@mdx-js/mdx/unist-util-visit/@types/unist": ["@types/[email protected]", "", {}, "sha512-PBjIUxZHOuj0R15/xuwJYjFi+KZdNFrehocChv4g5hu6aFroHue8m0lBP0POdK2nKzbw0cgV1mws8+V/JAcEkQ=="],"@mdx-js/mdx/unist-util-visit/unist-util-is": ["[email protected]", "", {}, "sha512-Glt17jWwZeyqrFqOK0pF1Ded5U3yzJnFr8CG1GMjCWTp9zDo2p+cmD6pWbZU8AgM5WU3IzRv6+rBwhzsGh6hBQ=="],@@ -11764,8 +11783,6 @@"@mdx-js/mdx/vfile/@types/unist": ["@types/[email protected]", "", {}, "sha512-PBjIUxZHOuj0R15/xuwJYjFi+KZdNFrehocChv4g5hu6aFroHue8m0lBP0POdK2nKzbw0cgV1mws8+V/JAcEkQ=="],- "@mdx-js/mdx/vfile/is-buffer": ["[email protected]", "", {}, "sha512-i2R6zNFDwgEHJyQUtJEk0XFi1i0dPFn/oqjK3/vPCcDeJvW5NQ83V8QbicfF1SupOaB0h8ntgBC2YiE7dfyctQ=="],-"@mdx-js/mdx/vfile/vfile-message": ["[email protected]", "", { "dependencies": { "@types/unist": "2.0.6", "unist-util-stringify-position": "3.0.3" } }, "sha512-fa0Z6P8HUrQN4BZaX05SIVXic+7kE3b05PWAtPuYP9QLHsLKYR7/AlLW3NtOrpXRLeawpDLMsVkmk5DG0NXgWw=="],"@mdx-js/react/@types/react/csstype": ["[email protected]", "", {}, "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw=="],@@ -13292,8 +13309,6 @@"remark-frontmatter/unified/@types/unist": ["@types/[email protected]", "", {}, "sha512-PBjIUxZHOuj0R15/xuwJYjFi+KZdNFrehocChv4g5hu6aFroHue8m0lBP0POdK2nKzbw0cgV1mws8+V/JAcEkQ=="],- "remark-frontmatter/unified/is-buffer": ["[email protected]", "", {}, "sha512-i2R6zNFDwgEHJyQUtJEk0XFi1i0dPFn/oqjK3/vPCcDeJvW5NQ83V8QbicfF1SupOaB0h8ntgBC2YiE7dfyctQ=="],-"remark-frontmatter/unified/vfile": ["[email protected]", "", { "dependencies": { "@types/unist": "2.0.6", "is-buffer": "2.0.5", "unist-util-stringify-position": "3.0.3", "vfile-message": "3.1.4" } }, "sha512-r7qlzkgErKjobAmyNIkkSpizsFPYiUPuJb5pNW1RB4JcYVZhs4lIbVqk8XPk033CV/1z8ss5pkax8SuhGpcG8g=="],"remark-mdx/mdast-util-mdx/mdast-util-from-markdown": ["[email protected]", "", { "dependencies": { "@types/mdast": "3.0.10", "@types/unist": "2.0.6", "decode-named-character-reference": "1.0.2", "mdast-util-to-string": "3.1.1", "micromark": "3.1.0", "micromark-util-decode-numeric-character-reference": "1.0.0", "micromark-util-decode-string": "1.0.2", "micromark-util-normalize-identifier": "1.0.0", "micromark-util-symbol": "1.0.1", "micromark-util-types": "1.0.2", "unist-util-stringify-position": "3.0.3", "uvu": "0.5.6" } }, "sha512-HN3W1gRIuN/ZW295c7zi7g9lVBllMgZE40RxCX37wrTPWXCWtpvOZdfnuK+1WNpvZje6XuJeI3Wnb4TJEUem+g=="],diff --git a/packages/cli/src/list-of-remotion-packages.ts b/packages/cli/src/list-of-remotion-packages.tsindex 2402bce383..aff614a75a 100644--- a/packages/cli/src/list-of-remotion-packages.ts+++ b/packages/cli/src/list-of-remotion-packages.ts@@ -83,4 +83,5 @@ export const listOfRemotionPackages = ['@remotion/web-renderer','@remotion/design','@remotion/light-leaks',+ '@remotion/vercel',];diff --git a/packages/create-video/src/list-of-remotion-packages.ts b/packages/create-video/src/list-of-remotion-packages.tsindex 2402bce383..aff614a75a 100644--- a/packages/create-video/src/list-of-remotion-packages.ts+++ b/packages/create-video/src/list-of-remotion-packages.ts@@ -83,4 +83,5 @@ export const listOfRemotionPackages = ['@remotion/web-renderer','@remotion/design','@remotion/light-leaks',+ '@remotion/vercel',];diff --git a/packages/docs/components/TableOfContents/api.tsx b/packages/docs/components/TableOfContents/api.tsxindex 872fc0c65d..6590ebc466 100644--- a/packages/docs/components/TableOfContents/api.tsx+++ b/packages/docs/components/TableOfContents/api.tsx@@ -11,8 +11,8 @@ import {TableOfContents as GoogleFontsTableOfContents} from '../../docs/google-fimport {TableOfContents as InstallWhisperCppTableOfContents} from '../../docs/install-whisper-cpp/install-whisper-cpp';import {TableOfContents as LambdaTableOfContents} from '../../docs/lambda/table-of-contents';import {TableOfContents as LayoutUtilsTableOfContents} from '../../docs/layout-utils/table-of-contents';-import {TableOfContents as LightLeaksTableOfContents} from '../../docs/light-leaks/table-of-contents';import {TableOfContents as LicensingTableOfContents} from '../../docs/licensing/TableOfContents';+import {TableOfContents as LightLeaksTableOfContents} from '../../docs/light-leaks/table-of-contents';import {TableOfContents as LottieTableOfContents} from '../../docs/lottie/table-of-contents';import {TableOfContents as MediaParserTableOfContents} from '../../docs/media-parser/TableOfContents';import {TableOfContents as MediaUtilsTableOfContents} from '../../docs/media-utils/table-of-contents';@@ -33,6 +33,7 @@ import {TableOfContents as TailwindV4TableOfContents} from '../../docs/tailwind-import {TableOfContents as TailwindTableOfContents} from '../../docs/tailwind/TableOfContents';import {TableOfContents as ThreeTableOfContents} from '../../docs/three/TableOfContents';import {TableOfContents as TransitionsTableOfContents} from '../../docs/transitions/table-of-contents';+import {TableOfContents as VercelTableOfContents} from '../../docs/vercel/table-of-contents';import {TableOfContents as WebcodecsTableOfContents} from '../../docs/webcodecs/TableOfContents';import {ZodTypesTableOfContents} from '../../docs/zod-types/TableOfContents';import {Grid} from './Grid';@@ -154,6 +155,9 @@ export const TableOfContents: React.FC = () => {<h2>@remotion/light-leaks</h2><p>Light leak effects</p><LightLeaksTableOfContents />+ <h2>@remotion/vercel</h2>+ <p>Render videos on Vercel Sandbox</p>+ <VercelTableOfContents /><h2>@remotion/motion-blur</h2><p>Apply motion blur effects to components</p><MotionBlurTableOfContents />diff --git a/packages/docs/docs/vercel-sandbox.mdx b/packages/docs/docs/vercel-sandbox.mdxindex 7622aa4656..4882292294 100644--- a/packages/docs/docs/vercel-sandbox.mdx+++ b/packages/docs/docs/vercel-sandbox.mdx@@ -52,12 +52,17 @@ For concurrency, the limit is 10 simultaneous renders on Hobby, and 2000 on ProFor more details, see: [Vercel Sandbox pricing](https://vercel.com/docs/vercel-sandbox/pricing)+## `@remotion/vercel` package++The [`@remotion/vercel`](/docs/vercel/api) package provides a programmatic API for rendering Remotion videos on Vercel Sandbox. The template uses this package under the hood.+## Source CodeSee the [template source code](https://github.com/remotion-dev/remotion/tree/main/packages/template-vercel) for implementation details.## See also+- [`@remotion/vercel` API Reference](/docs/vercel/api)- [Deploying Remotion on Vercel](/docs/vercel)- [Server-side rendering](/docs/ssr)- [Lambda](/docs/lambda)diff --git a/packages/docs/docs/vercel/create-sandbox.mdx b/packages/docs/docs/vercel/create-sandbox.mdxnew file mode 100644index 0000000000..08a9fc8e74--- /dev/null+++ b/packages/docs/docs/vercel/create-sandbox.mdx@@ -0,0 +1,56 @@+---+image: /generated/articles-docs-vercel-create-sandbox.png+title: createSandbox()+crumb: '@remotion/vercel'+---++# createSandbox()<AvailableFrom v="4.0.424" />++Creates a new [Vercel Sandbox](https://vercel.com/docs/vercel-sandbox) with all Remotion dependencies installed, including system libraries, the compositor, a browser, and your Remotion bundle.++This is a lower-level API. For most use cases, prefer [`getOrCreateSandbox()`](/docs/vercel/get-or-create-sandbox) which handles dev/prod routing automatically.++## Example++```ts twoslash title="create-snapshot.ts"+// @module: es2022+// @target: es2022+import type {OnProgress, VercelSandbox} from '@remotion/vercel';+const createSandbox: (options: {bundleDir: string; onProgress?: OnProgress}) => Promise<VercelSandbox> = null as unknown as (options: {bundleDir: string; onProgress?: OnProgress}) => Promise<VercelSandbox>;+// ---cut---+const sandbox = await createSandbox({+ bundleDir: '.remotion',+ onProgress: ({progress, message}) => {+ console.log(`${message} (${Math.round(progress * 100)}%)`);+ },+});+```++## Arguments++An object with the following properties:++### `bundleDir`++The path to your Remotion bundle directory, relative to the current working directory. This is the output of [`npx remotion bundle`](/docs/cli/bundle).++### `onProgress?`++A callback that receives progress updates during sandbox creation.++```ts+type OnProgress = (update: {+ progress: number; // 0 to 1+ message: string; // Human-readable phase description+}) => void;+```++## Return value++A `VercelSandbox` object (a `Sandbox` with `AsyncDisposable` support). You can use `await using` to automatically clean up the sandbox when it goes out of scope.++## See also++- [`getOrCreateSandbox()`](/docs/vercel/get-or-create-sandbox)+- [`createSnapshot()`](/docs/vercel/create-snapshot)+- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/vercel/src/create-sandbox.ts)diff --git a/packages/docs/docs/vercel/create-snapshot.mdx b/packages/docs/docs/vercel/create-snapshot.mdxnew file mode 100644index 0000000000..ccb4133b48--- /dev/null+++ b/packages/docs/docs/vercel/create-snapshot.mdx@@ -0,0 +1,46 @@+---+image: /generated/articles-docs-vercel-create-snapshot.png+title: createSnapshot()+crumb: '@remotion/vercel'+---++# createSnapshot()<AvailableFrom v="4.0.424" />++Takes a snapshot of a sandbox. Snapshots allow you to skip the sandbox setup time in production by restoring from a pre-built state.++Typically called during the build step (e.g. in `create-snapshot.ts`) to cache the sandbox for production use.++## Example++```ts twoslash title="create-snapshot.ts"+// @module: es2022+// @target: es2022+import type {VercelSandbox} from '@remotion/vercel';+const createSnapshot: (options: {sandbox: VercelSandbox}) => Promise<{snapshotId: string}> = null as unknown as (options: {sandbox: VercelSandbox}) => Promise<{snapshotId: string}>;+declare const sandbox: VercelSandbox;+// ---cut---+const {snapshotId} = await createSnapshot({sandbox});+console.log(`Snapshot created: ${snapshotId}`);+```++## Arguments++An object with the following properties:++### `sandbox`++A `VercelSandbox` instance, typically obtained from [`createSandbox()`](/docs/vercel/create-sandbox).++## Return value++An object containing:++### `snapshotId`++A `string` identifier for the snapshot. Pass this to [`saveSnapshot()`](/docs/vercel/save-snapshot) to cache it for production use.++## See also++- [`saveSnapshot()`](/docs/vercel/save-snapshot)+- [`createSandbox()`](/docs/vercel/create-sandbox)+- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/vercel/src/create-snapshot.ts)diff --git a/packages/docs/docs/vercel/get-or-create-sandbox.mdx b/packages/docs/docs/vercel/get-or-create-sandbox.mdxnew file mode 100644index 0000000000..66ab91a0b4--- /dev/null+++ b/packages/docs/docs/vercel/get-or-create-sandbox.mdx@@ -0,0 +1,50 @@+---+image: /generated/articles-docs-vercel-get-or-create-sandbox.png+title: getOrCreateSandbox()+crumb: '@remotion/vercel'+---++# getOrCreateSandbox()<AvailableFrom v="4.0.424" />++The primary entry point for getting a sandbox. Automatically handles the dev/prod routing:++- **Development** (no `VERCEL` env var): Creates a fresh sandbox from scratch using [`createSandbox()`](/docs/vercel/create-sandbox).+- **Production** (on Vercel): Restores a sandbox from a cached snapshot. Throws an error if no snapshot is found.++## Example++```ts twoslash title="route.ts"+// @module: es2022+// @target: es2022+import type {OnProgress, VercelSandbox} from '@remotion/vercel';+const getOrCreateSandbox: (options: {bundleDir: string; onProgress?: OnProgress}) => Promise<VercelSandbox> = null as unknown as (options: {bundleDir: string; onProgress?: OnProgress}) => Promise<VercelSandbox>;+// ---cut---+await using sandbox = await getOrCreateSandbox({+ bundleDir: '.remotion',+ onProgress: ({progress, message}) => {+ console.log(`${message} (${Math.round(progress * 100)}%)`);+ },+});+```++## Arguments++An object with the following properties:++### `bundleDir`++The path to your Remotion bundle directory, relative to the current working directory.++### `onProgress?`++A callback that receives progress updates. Only called during development when a fresh sandbox is created.++## Return value++A `VercelSandbox` object.++## See also++- [`createSandbox()`](/docs/vercel/create-sandbox)+- [`getSnapshot()`](/docs/vercel/get-snapshot)+- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/vercel/src/get-or-create-sandbox.ts)diff --git a/packages/docs/docs/vercel/get-snapshot.mdx b/packages/docs/docs/vercel/get-snapshot.mdxnew file mode 100644index 0000000000..604665bffc--- /dev/null+++ b/packages/docs/docs/vercel/get-snapshot.mdx@@ -0,0 +1,38 @@+---+image: /generated/articles-docs-vercel-get-snapshot.png+title: getSnapshot()+crumb: '@remotion/vercel'+---++# getSnapshot()<AvailableFrom v="4.0.424" />++Retrieves a cached snapshot ID from Vercel Blob storage. Returns `null` if no snapshot is found or if not running on Vercel.++Used internally by [`getOrCreateSandbox()`](/docs/vercel/get-or-create-sandbox) to check for a cached sandbox.++## Example++```ts twoslash title="route.ts"+// @module: es2022+// @target: es2022+const getSnapshot: () => Promise<string | null> = null as unknown as () => Promise<string | null>;+// ---cut---+const snapshotId = await getSnapshot();+if (snapshotId) {+ console.log(`Found cached snapshot: ${snapshotId}`);+}+```++## Arguments++None.++## Return value++`string | null` - The cached snapshot ID, or `null` if not found.++## See also++- [`saveSnapshot()`](/docs/vercel/save-snapshot)+- [`getOrCreateSandbox()`](/docs/vercel/get-or-create-sandbox)+- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/vercel/src/get-snapshot.ts)diff --git a/packages/docs/docs/vercel/index.mdx b/packages/docs/docs/vercel/index.mdxnew file mode 100644index 0000000000..db8b708d7d--- /dev/null+++ b/packages/docs/docs/vercel/index.mdx@@ -0,0 +1,28 @@+---+image: /generated/articles-docs-vercel-index.png+id: vercel-api+slug: /vercel/api+title: '@remotion/vercel'+---++import {TableOfContents} from './table-of-contents';++# @remotion/vercel<AvailableFrom v="4.0.424" />++Render Remotion videos on [Vercel Sandbox](https://vercel.com/docs/vercel-sandbox).++<Installation pkg="@remotion/vercel" />++This package requires `@vercel/sandbox` and `@vercel/blob` as peer dependencies:++```bash+npm i @vercel/sandbox @vercel/blob+```++## APIs++<TableOfContents />++## License++[Remotion License](/docs/license)diff --git a/packages/docs/docs/vercel/render-still-on-vercel.mdx b/packages/docs/docs/vercel/render-still-on-vercel.mdxnew file mode 100644index 0000000000..6e9da633c3--- /dev/null+++ b/packages/docs/docs/vercel/render-still-on-vercel.mdx@@ -0,0 +1,75 @@+---+image: /generated/articles-docs-vercel-render-still-on-vercel.png+title: renderStillOnVercel()+crumb: '@remotion/vercel'+---++# renderStillOnVercel()<AvailableFrom v="4.0.424" />++Renders a still image inside a Vercel Sandbox. Writes a render script to the sandbox, executes it, and returns the output file path.++The rendered file stays inside the sandbox. Use [`uploadToBlobStorage()`](/docs/vercel/upload-to-blob-storage) to upload it to Vercel Blob.++## Example++```ts twoslash title="route.ts"+// @module: es2022+// @target: es2022+import type {RenderOnVercelProgress, VercelSandbox} from '@remotion/vercel';+const renderStillOnVercel: (options: {sandbox: VercelSandbox; compositionId: string; inputProps: Record<string, unknown>; imageFormat?: 'png' | 'jpeg' | 'webp'; outputFile?: string; onProgress?: (progress: RenderOnVercelProgress) => void; bundleDir?: string}) => Promise<{file: string}> =+ null as unknown as any;+declare const sandbox: VercelSandbox;+// ---cut---+const {file} = await renderStillOnVercel({+ sandbox,+ compositionId: 'MyComp',+ inputProps: {title: 'Hello World'},+ imageFormat: 'png',+});+```++## Arguments++An object with the following properties:++### `sandbox`++A `VercelSandbox` instance.++### `compositionId`++The ID of the Remotion composition to render.++### `inputProps`++Props to pass to the composition.++### `imageFormat?`++The output image format. Default: `"png"`. Can be `"png"`, `"jpeg"`, or `"webp"`.++### `outputFile?`++The output file path inside the sandbox. Default: `"/tmp/still.png"`.++### `onProgress?`++A callback that receives render progress updates. See [`renderVideoOnVercel()`](/docs/vercel/render-video-on-vercel) for the type definition.++### `bundleDir?`++The bundle directory name in the sandbox. Default: `".remotion"`.++## Return value++An object containing:++### `file`++The path to the rendered still image inside the sandbox.++## See also++- [`renderVideoOnVercel()`](/docs/vercel/render-video-on-vercel)+- [`uploadToBlobStorage()`](/docs/vercel/upload-to-blob-storage)+- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/vercel/src/render-still.ts)diff --git a/packages/docs/docs/vercel/render-video-on-vercel.mdx b/packages/docs/docs/vercel/render-video-on-vercel.mdxnew file mode 100644index 0000000000..52fff41505--- /dev/null+++ b/packages/docs/docs/vercel/render-video-on-vercel.mdx@@ -0,0 +1,82 @@+---+image: /generated/articles-docs-vercel-render-video-on-vercel.png+title: renderVideoOnVercel()+crumb: '@remotion/vercel'+---++# renderVideoOnVercel()<AvailableFrom v="4.0.424" />++Renders a video inside a Vercel Sandbox. Writes a render script to the sandbox, executes it, and returns the output file path.++The rendered file stays inside the sandbox. Use [`uploadToBlobStorage()`](/docs/vercel/upload-to-blob-storage) to upload it to Vercel Blob.++## Example++```ts twoslash title="route.ts"+// @module: es2022+// @target: es2022+import type {RenderOnVercelProgress, VercelSandbox} from '@remotion/vercel';+const renderVideoOnVercel: (options: {sandbox: VercelSandbox; compositionId: string; inputProps: Record<string, unknown>; codec?: string; outputFile?: string; onProgress?: (progress: RenderOnVercelProgress) => void; bundleDir?: string}) => Promise<{file: string}> = null as unknown as any;+declare const sandbox: VercelSandbox;+// ---cut---+const {file} = await renderVideoOnVercel({+ sandbox,+ compositionId: 'MyComp',+ inputProps: {title: 'Hello World'},+ onProgress: (update) => {+ if (update.type === 'render-progress') {+ console.log(`Rendering: ${Math.round(update.progress * 100)}%`);+ }+ },+});+```++## Arguments++An object with the following properties:++### `sandbox`++A `VercelSandbox` instance.++### `compositionId`++The ID of the Remotion composition to render.++### `inputProps`++Props to pass to the composition.++### `codec?`++The video codec to use. Default: `"h264"`.++### `outputFile?`++The output file path inside the sandbox. Default: `"/tmp/video.mp4"`.++### `onProgress?`++A callback that receives render progress updates.++```ts+type RenderOnVercelProgress = {type: 'opening-browser'} | {type: 'selecting-composition'} | {type: 'render-progress'; progress: number} | {type: 'uploading'} | {type: 'done'; url: string; size: number};+```++### `bundleDir?`++The bundle directory name in the sandbox. Default: `".remotion"`.++## Return value++An object containing:++### `file`++The path to the rendered video inside the sandbox.++## See also++- [`renderStillOnVercel()`](/docs/vercel/render-still-on-vercel)+- [`uploadToBlobStorage()`](/docs/vercel/upload-to-blob-storage)+- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/vercel/src/render-video.ts)diff --git a/packages/docs/docs/vercel/save-snapshot.mdx b/packages/docs/docs/vercel/save-snapshot.mdxnew file mode 100644index 0000000000..44822dad5c--- /dev/null+++ b/packages/docs/docs/vercel/save-snapshot.mdx@@ -0,0 +1,37 @@+---+image: /generated/articles-docs-vercel-save-snapshot.png+title: saveSnapshot()+crumb: '@remotion/vercel'+---++# saveSnapshot()<AvailableFrom v="4.0.424" />++Saves a snapshot ID to Vercel Blob storage, keyed by the current `VERCEL_DEPLOYMENT_ID`. This allows [`getOrCreateSandbox()`](/docs/vercel/get-or-create-sandbox) to restore the sandbox in production without re-creating it.++## Example++```ts twoslash title="create-snapshot.ts"+// @module: es2022+// @target: es2022+const saveSnapshot: (options: {snapshotId: string}) => Promise<void> = null as unknown as (options: {snapshotId: string}) => Promise<void>;+// ---cut---+await saveSnapshot({snapshotId: 'snap_abc123'});+```++## Arguments++An object with the following properties:++### `snapshotId`++The snapshot ID returned by [`createSnapshot()`](/docs/vercel/create-snapshot).++## Return value++`void`. Throws if the upload to Vercel Blob fails.++## See also++- [`createSnapshot()`](/docs/vercel/create-snapshot)+- [`getSnapshot()`](/docs/vercel/get-snapshot)+- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/vercel/src/save-snapshot.ts)diff --git a/packages/docs/docs/vercel/table-of-contents.tsx b/packages/docs/docs/vercel/table-of-contents.tsxnew file mode 100644index 0000000000..36f68d85f0--- /dev/null+++ b/packages/docs/docs/vercel/table-of-contents.tsx@@ -0,0 +1,44 @@+import React from 'react';+import {Grid} from '../../components/TableOfContents/Grid';+import {TOCItem} from '../../components/TableOfContents/TOCItem';++export const TableOfContents: React.FC = () => {+ return (+ <div>+ <Grid>+ <TOCItem link="/docs/vercel/create-sandbox">+ <strong>createSandbox()</strong>+ <div>Create a sandbox with Remotion installed</div>+ </TOCItem>+ <TOCItem link="/docs/vercel/get-or-create-sandbox">+ <strong>getOrCreateSandbox()</strong>+ <div>Get a cached sandbox or create a new one</div>+ </TOCItem>+ <TOCItem link="/docs/vercel/create-snapshot">+ <strong>createSnapshot()</strong>+ <div>Take a snapshot of a sandbox</div>+ </TOCItem>+ <TOCItem link="/docs/vercel/save-snapshot">+ <strong>saveSnapshot()</strong>+ <div>Save a snapshot ID to Vercel Blob</div>+ </TOCItem>+ <TOCItem link="/docs/vercel/get-snapshot">+ <strong>getSnapshot()</strong>+ <div>Get a cached snapshot ID from Vercel Blob</div>+ </TOCItem>+ <TOCItem link="/docs/vercel/render-video-on-vercel">+ <strong>renderVideoOnVercel()</strong>+ <div>Render a video in a sandbox</div>+ </TOCItem>+ <TOCItem link="/docs/vercel/render-still-on-vercel">+ <strong>renderStillOnVercel()</strong>+ <div>Render a still image in a sandbox</div>+ </TOCItem>+ <TOCItem link="/docs/vercel/upload-to-blob-storage">+ <strong>uploadToBlobStorage()</strong>+ <div>Upload a file from the sandbox to Vercel Blob</div>+ </TOCItem>+ </Grid>+ </div>+ );+};diff --git a/packages/docs/docs/vercel/upload-to-blob-storage.mdx b/packages/docs/docs/vercel/upload-to-blob-storage.mdxnew file mode 100644index 0000000000..d7e49826bf--- /dev/null+++ b/packages/docs/docs/vercel/upload-to-blob-storage.mdx@@ -0,0 +1,70 @@+---+image: /generated/articles-docs-vercel-upload-to-blob-storage.png+title: uploadToBlobStorage()+crumb: '@remotion/vercel'+---++# uploadToBlobStorage()<AvailableFrom v="4.0.424" />++Uploads a file from the sandbox to [Vercel Blob](https://vercel.com/docs/storage/vercel-blob) storage. Typically used after [`renderVideoOnVercel()`](/docs/vercel/render-video-on-vercel) or [`renderStillOnVercel()`](/docs/vercel/render-still-on-vercel) to make the output publicly accessible.++## Example++```ts twoslash title="route.ts"+// @module: es2022+// @target: es2022+import type {VercelSandbox} from '@remotion/vercel';+const uploadToBlobStorage: (options: {sandbox: VercelSandbox; sandboxFilePath: string; blobPath?: string; contentType: string; blobToken: string}) => Promise<{url: string; size: number}> = null as unknown as any;+declare const sandbox: VercelSandbox;+// ---cut---+const {url, size} = await uploadToBlobStorage({+ sandbox,+ sandboxFilePath: '/tmp/video.mp4',+ contentType: 'video/mp4',+ blobToken: process.env.BLOB_READ_WRITE_TOKEN!,+});++console.log(`Uploaded ${size} bytes to ${url}`);+```++## Arguments++An object with the following properties:++### `sandbox`++A `VercelSandbox` instance.++### `sandboxFilePath`++The path to the file inside the sandbox to upload, e.g. `"/tmp/video.mp4"`.++### `blobPath?`++The destination path in Vercel Blob, e.g. `"renders/abc.mp4"`. If omitted, a random path is generated.++### `contentType`++The MIME type of the file, e.g. `"video/mp4"` or `"image/png"`.++### `blobToken`++Your Vercel Blob read/write token. Typically `process.env.BLOB_READ_WRITE_TOKEN`.++## Return value++An object containing:++### `url`++The public download URL of the uploaded file.++### `size`++The size of the uploaded file in bytes.++## See also++- [`renderVideoOnVercel()`](/docs/vercel/render-video-on-vercel)+- [`renderStillOnVercel()`](/docs/vercel/render-still-on-vercel)+- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/vercel/src/upload-to-blob-storage.ts)diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.tsindex da0ed81765..f4b4ab6600 100644--- a/packages/docs/sidebars.ts+++ b/packages/docs/sidebars.ts@@ -460,6 +460,24 @@ const sidebars: SidebarsConfig = {},items: ['light-leaks/light-leak'],},+ {+ type: 'category',+ label: '@remotion/vercel',+ link: {+ type: 'doc',+ id: 'vercel/vercel-api',+ },+ items: [+ 'vercel/create-sandbox',+ 'vercel/get-or-create-sandbox',+ 'vercel/create-snapshot',+ 'vercel/save-snapshot',+ 'vercel/get-snapshot',+ 'vercel/render-video-on-vercel',+ 'vercel/render-still-on-vercel',+ 'vercel/upload-to-blob-storage',+ ],+ },{type: 'category',label: '@remotion/openai-whisper',diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.tsindex 12cc0c068e..fd193b3b7d 100644--- a/packages/docs/src/data/articles.ts+++ b/packages/docs/src/data/articles.ts@@ -6538,6 +6538,87 @@ export const articles = [noAi: false,slug: 'vercel',},+ {+ id: 'vercel/create-sandbox',+ title: 'createSandbox()',+ relativePath: 'docs/vercel/create-sandbox.mdx',+ compId: 'articles-docs-vercel-create-sandbox',+ crumb: '@remotion/vercel',+ noAi: false,+ slug: 'vercel/create-sandbox',+ },+ {+ id: 'vercel/create-snapshot',+ title: 'createSnapshot()',+ relativePath: 'docs/vercel/create-snapshot.mdx',+ compId: 'articles-docs-vercel-create-snapshot',+ crumb: '@remotion/vercel',+ noAi: false,+ slug: 'vercel/create-snapshot',+ },+ {+ id: 'vercel/get-or-create-sandbox',+ title: 'getOrCreateSandbox()',+ relativePath: 'docs/vercel/get-or-create-sandbox.mdx',+ compId: 'articles-docs-vercel-get-or-create-sandbox',+ crumb: '@remotion/vercel',+ noAi: false,+ slug: 'vercel/get-or-create-sandbox',+ },+ {+ id: 'vercel/get-snapshot',+ title: 'getSnapshot()',+ relativePath: 'docs/vercel/get-snapshot.mdx',+ compId: 'articles-docs-vercel-get-snapshot',+ crumb: '@remotion/vercel',+ noAi: false,+ slug: 'vercel/get-snapshot',+ },+ {+ id: 'vercel-api',+ title: '@remotion/vercel',+ relativePath: 'docs/vercel/index.mdx',+ compId: 'articles-docs-vercel-index',+ crumb: null,+ noAi: false,+ slug: 'vercel/api',+ },+ {+ id: 'vercel/render-still-on-vercel',+ title: 'renderStillOnVercel()',+ relativePath: 'docs/vercel/render-still-on-vercel.mdx',+ compId: 'articles-docs-vercel-render-still-on-vercel',+ crumb: '@remotion/vercel',+ noAi: false,+ slug: 'vercel/render-still-on-vercel',+ },+ {+ id: 'vercel/render-video-on-vercel',+ title: 'renderVideoOnVercel()',+ relativePath: 'docs/vercel/render-video-on-vercel.mdx',+ compId: 'articles-docs-vercel-render-video-on-vercel',+ crumb: '@remotion/vercel',+ noAi: false,+ slug: 'vercel/render-video-on-vercel',+ },+ {+ id: 'vercel/save-snapshot',+ title: 'saveSnapshot()',+ relativePath: 'docs/vercel/save-snapshot.mdx',+ compId: 'articles-docs-vercel-save-snapshot',+ crumb: '@remotion/vercel',+ noAi: false,+ slug: 'vercel/save-snapshot',+ },+ {+ id: 'vercel/upload-to-blob-storage',+ title: 'uploadToBlobStorage()',+ relativePath: 'docs/vercel/upload-to-blob-storage.mdx',+ compId: 'articles-docs-vercel-upload-to-blob-storage',+ crumb: '@remotion/vercel',+ noAi: false,+ slug: 'vercel/upload-to-blob-storage',+ },{id: 'version-mismatch',title: 'Version mismatch',diff --git a/packages/docs/static/generated/articles-docs-vercel-create-sandbox.png b/packages/docs/static/generated/articles-docs-vercel-create-sandbox.pngnew file mode 100644index 0000000000..c9251c8337Binary files /dev/null and b/packages/docs/static/generated/articles-docs-vercel-create-sandbox.png differdiff --git a/packages/docs/static/generated/articles-docs-vercel-create-snapshot.png b/packages/docs/static/generated/articles-docs-vercel-create-snapshot.pngnew file mode 100644index 0000000000..4ae4bb19d2Binary files /dev/null and b/packages/docs/static/generated/articles-docs-vercel-create-snapshot.png differdiff --git a/packages/docs/static/generated/articles-docs-vercel-get-or-create-sandbox.png b/packages/docs/static/generated/articles-docs-vercel-get-or-create-sandbox.pngnew file mode 100644index 0000000000..73155d1c7cBinary files /dev/null and b/packages/docs/static/generated/articles-docs-vercel-get-or-create-sandbox.png differdiff --git a/packages/docs/static/generated/articles-docs-vercel-get-snapshot.png b/packages/docs/static/generated/articles-docs-vercel-get-snapshot.pngnew file mode 100644index 0000000000..359aeea770Binary files /dev/null and b/packages/docs/static/generated/articles-docs-vercel-get-snapshot.png differdiff --git a/packages/docs/static/generated/articles-docs-vercel-index.png b/packages/docs/static/generated/articles-docs-vercel-index.pngnew file mode 100644index 0000000000..cfd1a6af57Binary files /dev/null and b/packages/docs/static/generated/articles-docs-vercel-index.png differdiff --git a/packages/docs/static/generated/articles-docs-vercel-render-still-on-vercel.png b/packages/docs/static/generated/articles-docs-vercel-render-still-on-vercel.pngnew file mode 100644index 0000000000..5ff8c1efd3Binary files /dev/null and b/packages/docs/static/generated/articles-docs-vercel-render-still-on-vercel.png differdiff --git a/packages/docs/static/generated/articles-docs-vercel-render-video-on-vercel.png b/packages/docs/static/generated/articles-docs-vercel-render-video-on-vercel.pngnew file mode 100644index 0000000000..10b2faa0a3Binary files /dev/null and b/packages/docs/static/generated/articles-docs-vercel-render-video-on-vercel.png differdiff --git a/packages/docs/static/generated/articles-docs-vercel-save-snapshot.png b/packages/docs/static/generated/articles-docs-vercel-save-snapshot.pngnew file mode 100644index 0000000000..8c3d82fddeBinary files /dev/null and b/packages/docs/static/generated/articles-docs-vercel-save-snapshot.png differdiff --git a/packages/docs/static/generated/articles-docs-vercel-upload-to-blob-storage.png b/packages/docs/static/generated/articles-docs-vercel-upload-to-blob-storage.pngnew file mode 100644index 0000000000..cf3b5ed4e4Binary files /dev/null and b/packages/docs/static/generated/articles-docs-vercel-upload-to-blob-storage.png differdiff --git a/packages/studio-shared/src/package-info.ts b/packages/studio-shared/src/package-info.tsindex 407bf1bdc1..3ff347633b 100644--- a/packages/studio-shared/src/package-info.ts+++ b/packages/studio-shared/src/package-info.ts@@ -82,6 +82,7 @@ export const packages = ['web-renderer','design','light-leaks',+ 'vercel',] as const;export type Pkgs = (typeof packages)[number];@@ -197,6 +198,7 @@ export const descriptions: {[key in Pkgs]: string | null} = {'web-renderer': 'Render videos in the browser (not yet released)',design: 'Design system','light-leaks': 'Light leak effects for Remotion',+ vercel: 'Render Remotion videos on Vercel Sandbox',};export const installableMap: {[key in Pkgs]: boolean} = {'svg-3d-engine': false,@@ -282,6 +284,7 @@ export const installableMap: {[key in Pkgs]: boolean} = {'web-renderer': false,design: false,'light-leaks': true,+ vercel: true,};export const apiDocs: {[key in Pkgs]: string | null} = {@@ -371,4 +374,5 @@ export const apiDocs: {[key in Pkgs]: string | null} = {'web-renderer': 'https://www.remotion.dev/docs/web-renderer/',design: 'https://www.remotion.dev/design','light-leaks': 'https://www.remotion.dev/docs/light-leaks',+ vercel: 'https://www.remotion.dev/docs/vercel',};diff --git a/packages/template-vercel/create-snapshot.ts b/packages/template-vercel/create-snapshot.tsindex f2ec3396de..908189a2af 100644--- a/packages/template-vercel/create-snapshot.ts+++ b/packages/template-vercel/create-snapshot.ts@@ -1,20 +1,15 @@-import { createSandbox } from "./src/app/api/render/sandbox/create-sandbox";-import { saveSnapshotCache } from "./src/app/api/render/sandbox/snapshots";+import { createSandbox, createSnapshot, saveSnapshot } from "@remotion/vercel";const sandbox = await createSandbox({- onProgress: async (progress) => {- if (progress.type === "phase") {- const pct = Math.round((progress.progress ?? 0) * 100);- console.log(`[create-snapshot] ${progress.phase} (${pct}%)`);- }+ bundleDir: ".remotion",+ onProgress: ({ progress, message }) => {+ const pct = Math.round(progress * 100);+ console.log(`[create-snapshot] ${message} (${pct}%)`);},});console.log("[create-snapshot] Taking snapshot...");-const snapshot = await sandbox.snapshot({ expiration: 0 });+const { snapshotId } = await createSnapshot({ sandbox });+await saveSnapshot({ snapshotId });-await saveSnapshotCache(snapshot.snapshotId);--console.log(- `[create-snapshot] Snapshot saved: ${snapshot.snapshotId} (never expires)`,-);+console.log(`[create-snapshot] Snapshot saved: ${snapshotId} (never expires)`);diff --git a/packages/template-vercel/package.json b/packages/template-vercel/package.jsonindex 8a18e87e9d..00d9c74dd1 100644--- a/packages/template-vercel/package.json+++ b/packages/template-vercel/package.json@@ -19,6 +19,7 @@"@remotion/player": "workspace:*","@remotion/shapes": "workspace:*","@remotion/tailwind-v4": "workspace:*",+ "@remotion/vercel": "workspace:*","@types/bun": "1.3.3","@vercel/blob": "2.0.1","@vercel/functions": "^3.4.1",diff --git a/packages/template-vercel/render.ts b/packages/template-vercel/render.tsdeleted file mode 100644index 6a2f25aae3..0000000000--- a/packages/template-vercel/render.ts+++ /dev/null@@ -1,65 +0,0 @@-// This file is copied into the Vercel sandbox and executed with `node --strip-types`-import {- openBrowser,- renderMedia,- selectComposition,-} from "@remotion/renderer";-import { put } from "@vercel/blob";-import { readFileSync, statSync } from "fs";--export type RenderConfig = {- serveUrl: string;- compositionId: string;- inputProps: Record<string, unknown>;- blobToken: string;- blobPath: string;-};--const config: RenderConfig = JSON.parse(process.argv[2]);--try {- console.log(JSON.stringify({ type: "opening-browser" }));- const browser = await openBrowser("chrome");- console.log(JSON.stringify({ type: "selecting-composition" }));- const composition = await selectComposition({- serveUrl: config.serveUrl,- id: config.compositionId,- inputProps: config.inputProps,- puppeteerInstance: browser,- });-- await renderMedia({- composition,- serveUrl: config.serveUrl,- codec: "h264",- outputLocation: "/tmp/video.mp4",- inputProps: config.inputProps,- onProgress: ({ progress }) => {- console.log(JSON.stringify({ type: "progress", progress }));- },- puppeteerInstance: browser,- });-- console.log(JSON.stringify({ type: "uploading" }));- const closePromise = browser.close({ silent: false });-- const videoBuffer = readFileSync("/tmp/video.mp4");- const blob = await put(config.blobPath, videoBuffer, {- access: "public",- contentType: "video/mp4",- token: config.blobToken,- });-- console.log(- JSON.stringify({- type: "done",- url: blob.downloadUrl,- size: statSync("/tmp/video.mp4").size,- }),- );- await closePromise;-} catch (err) {- // This prints to stderr, not stdout- console.error((err as Error).message);- process.exit(1);-}diff --git a/packages/template-vercel/src/app/api/render/helpers.ts b/packages/template-vercel/src/app/api/render/helpers.tsindex 09f6a1a670..e4a1015423 100644--- a/packages/template-vercel/src/app/api/render/helpers.ts+++ b/packages/template-vercel/src/app/api/render/helpers.ts@@ -1,18 +1,3 @@-import { Sandbox } from "@vercel/sandbox";-import { readFile } from "fs/promises";-import path from "path";--export const createDisposableSandbox = async (- options: Parameters<typeof Sandbox.create>[0],-): Promise<Sandbox & AsyncDisposable> => {- const sandbox = await Sandbox.create(options);- return Object.assign(sandbox, {- [Symbol.asyncDispose]: async () => {- await sandbox.stop().catch(() => {});- },- });-};-export const createDisposableWriter = (writer: WritableStreamDefaultWriter<Uint8Array>,): WritableStreamDefaultWriter<Uint8Array> & AsyncDisposable => {@@ -33,8 +18,3 @@ export type OnProgressFn = (message: RenderProgress) => Promise<void>;export function formatSSE(message: RenderProgress): string {return `data: ${JSON.stringify(message)}\n\n`;}--export async function getRenderScript(): Promise<Buffer> {- const renderScriptPath = path.join(process.cwd(), "render.ts");- return readFile(renderScriptPath);-}diff --git a/packages/template-vercel/src/app/api/render/render.ts b/packages/template-vercel/src/app/api/render/render.tsdeleted file mode 100644index fcabcb1fa3..0000000000--- a/packages/template-vercel/src/app/api/render/render.ts+++ /dev/null@@ -1,86 +0,0 @@-import { Sandbox } from "@vercel/sandbox";-import { BUILD_DIR } from "../../../../build-dir.mjs";-import type { RenderConfig } from "../../../../render";-import { COMP_NAME } from "../../../../types/constants";--export type RenderInSandboxProgress =- | { type: "opening-browser" }- | { type: "selecting-composition" }- | { 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: (progress: RenderInSandboxProgress) => Promise<void>;-}): Promise<void> {- // Use the local bundle copied to the sandbox- const serveUrl = `/vercel/sandbox/${BUILD_DIR}`;-- const renderId = crypto.randomUUID();- const blobToken = process.env.BLOB_READ_WRITE_TOKEN;- if (!blobToken) {- throw new Error("BLOB_READ_WRITE_TOKEN is not set");- }-- const renderConfig: RenderConfig = {- serveUrl,- compositionId: COMP_NAME,- inputProps,- blobToken,- blobPath: `renders/${renderId}.mp4`,- };-- // Run the render script- const renderCmd = await sandbox.runCommand({- cmd: "node",- args: ["--strip-types", "render.ts", JSON.stringify(renderConfig)],- detached: true,- });-- let doneUrl: string | null = null;- let doneSize: number | null = null;-- for await (const log of renderCmd.logs()) {- if (log.stream === "stdout") {- try {- const message = JSON.parse(log.data);- if (message.type === "opening-browser") {- await onProgress({ type: "opening-browser" });- } else if (message.type === "selecting-composition") {- await onProgress({ type: "selecting-composition" });- } else if (message.type === "progress") {- await onProgress({- type: "render-progress",- progress: message.progress,- });- } else if (message.type === "uploading") {- await onProgress({ type: "uploading" });- } else if (message.type === "done") {- doneUrl = message.url;- doneSize = message.size;- }- } catch {- // Not JSON, ignore- }- }- }-- const renderResult = await renderCmd.wait();- if (renderResult.exitCode !== 0) {- const stderr = await renderResult.stderr();- const stdout = await renderResult.stdout();- throw new Error(`Render failed: ${stderr} ${stdout}`);- }-- if (!doneUrl || doneSize === null) {- throw new Error("Render script did not return upload result");- }-- 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 ec4a9f26ad..bc484c5e4b 100644--- a/packages/template-vercel/src/app/api/render/route.ts+++ b/packages/template-vercel/src/app/api/render/route.ts@@ -1,12 +1,16 @@+import {+ getOrCreateSandbox,+ renderVideoOnVercel,+ uploadToBlobStorage,+} from "@remotion/vercel";import { waitUntil } from "@vercel/functions";+import { COMP_NAME } from "../../../../types/constants";import { RenderRequest } from "../../../../types/schema";import {createDisposableWriter,formatSSE,type RenderProgress,} from "./helpers";-import { renderInSandbox } from "./render";-import { reuseOrCreateSandbox } from "./sandbox/reuse-or-create-sandbox";export async function POST(req: Request) {const encoder = new TextEncoder();@@ -26,49 +30,72 @@ export async function POST(req: Request) {const body = RenderRequest.parse(payload);await send({ type: "phase", phase: "Creating sandbox...", progress: 0 });- await using sandbox = await reuseOrCreateSandbox(send);- await renderInSandbox({++ await using sandbox = await getOrCreateSandbox({+ bundleDir: ".remotion",+ onProgress: ({ progress, message }) => {+ send({+ type: "phase",+ phase: message,+ progress,+ subtitle: "This is only needed during development.",+ });+ },+ });++ const { file } = await renderVideoOnVercel({sandbox,+ compositionId: COMP_NAME,inputProps: body.inputProps,- onProgress: async (update) => {+ bundleDir: ".remotion",+ onProgress: (update) => {switch (update.type) {case "opening-browser":- await send({+ send({type: "phase",phase: "Opening browser...",progress: 0,});break;case "selecting-composition":- await send({+ send({type: "phase",phase: "Selecting composition...",progress: 0,});break;case "render-progress":- await send({+ send({type: "phase",phase: "Rendering video...",progress: update.progress,});break;- case "uploading":- await send({- type: "phase",- phase: "Uploading video...",- progress: 1,- });- break;- case "done":- await send({ type: "done", url: update.url, size: update.size });- break;default:- update satisfies never;break;}},});++ await send({+ type: "phase",+ phase: "Uploading video...",+ progress: 1,+ });++ const blobToken = process.env.BLOB_READ_WRITE_TOKEN;+ if (!blobToken) {+ throw new Error("BLOB_READ_WRITE_TOKEN is not set");+ }++ const { url, size } = await uploadToBlobStorage({+ sandbox,+ sandboxFilePath: file,+ contentType: "video/mp4",+ blobToken,+ });++ await send({ type: "done", url, size });} catch (err) {console.log(err);await send({ type: "error", message: (err as Error).message });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.tsdeleted file mode 100644index 963fe1cbe9..0000000000--- a/packages/template-vercel/src/app/api/render/sandbox/add-bundle.ts+++ /dev/null@@ -1,78 +0,0 @@-import { Sandbox } from "@vercel/sandbox";-import { execSync } from "child_process";-import { existsSync } from "fs";-import { readdir, readFile } from "fs/promises";-import path from "path";-import { BUILD_DIR } from "../../../../../build-dir.mjs";--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.tsdeleted file mode 100644index 017eb6b998..0000000000--- a/packages/template-vercel/src/app/api/render/sandbox/create-sandbox.ts+++ /dev/null@@ -1,107 +0,0 @@-import { Sandbox } from "@vercel/sandbox";-import {- createDisposableSandbox,- getRenderScript,- OnProgressFn,-} from "../helpers";-import { addBundleToSandbox } from "./add-bundle";-import { installBrowser } from "./install-browser";-import { installJsDependencies } from "./install-js-dependencies";-import { installSystemDependencies } from "./install-system-dependencies";-import { patchCompositor } from "./patch-compositor";--export const SANDBOX_CREATING_TIMEOUT = 5 * 60 * 1000;--export async function createSandbox({- onProgress,-}: {- onProgress: OnProgressFn;-}): Promise<Sandbox & AsyncDisposable> {- const sandbox = await createDisposableSandbox({- runtime: "node24",- resources: { vcpus: 4 },- timeout: SANDBOX_CREATING_TIMEOUT,- });-- const preparingPhase = "Preparing...";- const preparingSubtitle = "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 });-- // Patch compositor binary for glibc 2.34 compatibility (Amazon Linux 2023)- await patchCompositor({ 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,- });- },- });-- const renderScript = await getRenderScript();- await sandbox.writeFiles([- {- path: "render.ts",- content: renderScript,- },- {- path: "package.json",- content: Buffer.from(JSON.stringify({ type: "module" })),- },- ]);-- 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.tsdeleted file mode 100644index 233a50fccc..0000000000--- a/packages/template-vercel/src/app/api/render/sandbox/install-browser.ts+++ /dev/null@@ -1,51 +0,0 @@-import { Sandbox } from "@vercel/sandbox";-import { readFile } from "fs/promises";-import path from "path";--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.tsdeleted file mode 100644index d7a0d66918..0000000000--- a/packages/template-vercel/src/app/api/render/sandbox/install-js-dependencies.ts+++ /dev/null@@ -1,28 +0,0 @@-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}`,- `@remotion/compositor-linux-x64-gnu@${VERSION}`,- `@vercel/blob`,- ],- detached: true,- });-- for await (const _log of installCmd.logs()) {- console.log(_log.data);- }-- 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.tsdeleted file mode 100644index 06c12a5b88..0000000000--- a/packages/template-vercel/src/app/api/render/sandbox/install-system-dependencies.ts+++ /dev/null@@ -1,54 +0,0 @@-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",- "patchelf",- "zstd",- "binutils",- ],- 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/sandbox/reuse-or-create-sandbox.ts b/packages/template-vercel/src/app/api/render/sandbox/reuse-or-create-sandbox.tsdeleted file mode 100644index adc5a766fc..0000000000--- a/packages/template-vercel/src/app/api/render/sandbox/reuse-or-create-sandbox.ts+++ /dev/null@@ -1,32 +0,0 @@-import { Sandbox } from "@vercel/sandbox";-import { createDisposableSandbox, OnProgressFn } from "../helpers";-import { createSandbox, SANDBOX_CREATING_TIMEOUT } from "./create-sandbox";-import { getCachedSnapshot } from "./snapshots";--export async function reuseOrCreateSandbox(- onProgress: OnProgressFn,-): Promise<Sandbox & AsyncDisposable> {- // During local development, a new sandbox is created from scratch always (no snapshotting)- if (!process.env.VERCEL) {- await onProgress({- type: "phase",- phase: "Creating sandbox...",- progress: 0,- });- return await createSandbox({ onProgress });- }-- // In production, the snapshot is created at build time via `create-snapshot`- const cachedSnapshotId = await getCachedSnapshot();-- if (!cachedSnapshotId) {- throw new Error(- "No sandbox snapshot found. Run `bun run create-snapshot` as part of the build process.",- );- }-- return await createDisposableSandbox({- source: { type: "snapshot", snapshotId: cachedSnapshotId },- timeout: SANDBOX_CREATING_TIMEOUT,- });-}diff --git a/packages/template-vercel/src/app/api/render/sandbox/snapshots.ts b/packages/template-vercel/src/app/api/render/sandbox/snapshots.tsdeleted file mode 100644index 31b9b158e0..0000000000--- a/packages/template-vercel/src/app/api/render/sandbox/snapshots.ts+++ /dev/null@@ -1,35 +0,0 @@-import { head, put } from "@vercel/blob";--type SnapshotCache = {- snapshotId: string;-};--const SNAPSHOT_BLOB_KEY = `snapshot-cache/${process.env.VERCEL_DEPLOYMENT_ID ?? "local"}.json`;--export async function getCachedSnapshot(): Promise<string | null> {- if (!process.env.VERCEL) {- return null;- }-- try {- const metadata = await head(SNAPSHOT_BLOB_KEY);- const response = await fetch(metadata.url);- const cache: SnapshotCache = await response.json();-- return cache.snapshotId;- } catch {- return null;- }-}--export async function saveSnapshotCache(snapshotId: string): Promise<void> {- const cache: SnapshotCache = {- snapshotId,- };-- await put(SNAPSHOT_BLOB_KEY, JSON.stringify(cache), {- access: "public",- contentType: "application/json",- addRandomSuffix: false,- });-}diff --git a/packages/template-vercel/tsconfig.json b/packages/template-vercel/tsconfig.jsonindex 3a1b9112de..e7c84fb1c9 100644--- a/packages/template-vercel/tsconfig.json+++ b/packages/template-vercel/tsconfig.json@@ -26,8 +26,7 @@"**/*.ts","**/*.tsx",".next/types/**/*.ts",- ".next/dev/types/**/*.ts",- "render.ts"+ ".next/dev/types/**/*.ts"],"exclude": ["node_modules", "remotion.config.ts"]}diff --git a/packages/vercel/.npmignore b/packages/vercel/.npmignorenew file mode 100644index 0000000000..eb76a5ae81--- /dev/null+++ b/packages/vercel/.npmignore@@ -0,0 +1,10 @@+dist/test/**+src+eslint.config.mjs+tsconfig.tsbuildinfo+*.tgz+.turbo+tsconfig.json+.prettierrc.js+bundle.ts+dist/cjs/testdiff --git a/packages/vercel/bundle.ts b/packages/vercel/bundle.tsnew file mode 100644index 0000000000..2880da8ae6--- /dev/null+++ b/packages/vercel/bundle.ts@@ -0,0 +1,34 @@+import {build} from 'bun';+import path from 'path';++if (process.env.NODE_ENV !== 'production') {+ throw new Error('This script must be run using NODE_ENV=production');+}++console.time('Generated.');+const output = await build({+ entrypoints: ['src/index.ts'],+ naming: '[name].mjs',+ target: 'node',+ external: [+ 'remotion',+ 'remotion/no-react',+ 'remotion/version',+ '@vercel/sandbox',+ '@vercel/blob',+ ],+});++if (!output.success) {+ console.log(output.logs.join('\n'));+ process.exit(1);+}++for (const file of output.outputs) {+ const str = await file.text();+ const out = path.join('dist', 'esm', file.path);++ await Bun.write(out, str);+}++console.timeEnd('Generated.');diff --git a/packages/vercel/eslint.config.mjs b/packages/vercel/eslint.config.mjsnew file mode 100644index 0000000000..04fd4fac11--- /dev/null+++ b/packages/vercel/eslint.config.mjs@@ -0,0 +1,7 @@+import {remotionFlatConfig} from '@remotion/eslint-config-internal';++const config = remotionFlatConfig({react: false});++export default {+ ...config,+};diff --git a/packages/vercel/package.json b/packages/vercel/package.jsonnew file mode 100644index 0000000000..6fd4262881--- /dev/null+++ b/packages/vercel/package.json@@ -0,0 +1,57 @@+{+ "name": "@remotion/vercel",+ "version": "4.0.424",+ "description": "Render Remotion videos on Vercel Sandbox",+ "main": "dist/index.js",+ "types": "dist/index.d.ts",+ "module": "dist/esm/index.mjs",+ "repository": {+ "url": "https://github.com/remotion-dev/remotion/tree/main/packages/vercel"+ },+ "sideEffects": false,+ "type": "module",+ "scripts": {+ "formatting": "prettier src --check",+ "lint": "eslint src",+ "watch": "tsgo -w",+ "make": "tsgo && bun --env-file=../.env.bundle bundle.ts"+ },+ "author": "Jonny Burger <[email protected]>",+ "contributors": [],+ "license": "Remotion License",+ "bugs": {+ "url": "https://github.com/remotion-dev/remotion/issues"+ },+ "dependencies": {+ "remotion": "workspace:*"+ },+ "peerDependencies": {+ "@vercel/blob": ">=2.0.0",+ "@vercel/sandbox": ">=1.0.0"+ },+ "exports": {+ ".": {+ "types": "./dist/index.d.ts",+ "module": "./dist/esm/index.mjs",+ "import": "./dist/esm/index.mjs"+ },+ "./package.json": "./package.json"+ },+ "devDependencies": {+ "@remotion/eslint-config-internal": "workspace:*",+ "@vercel/blob": "2.0.1",+ "@vercel/sandbox": "1.6.0",+ "eslint": "catalog:",+ "@typescript/native-preview": "catalog:"+ },+ "keywords": [+ "remotion",+ "vercel",+ "sandbox",+ "video"+ ],+ "publishConfig": {+ "access": "public"+ },+ "homepage": "https://www.remotion.dev/docs/vercel"+}diff --git a/packages/vercel/src/create-sandbox.ts b/packages/vercel/src/create-sandbox.tsnew file mode 100644index 0000000000..0afd48b65b--- /dev/null+++ b/packages/vercel/src/create-sandbox.ts@@ -0,0 +1,96 @@+import {addBundleToSandbox} from './internals/add-bundle';+import {createDisposableSandbox} from './internals/disposable';+import {installBrowser} from './internals/install-browser';+import {installJsDependencies} from './internals/install-js-dependencies';+import {installSystemDependencies} from './internals/install-system-dependencies';+import {patchCompositor} from './internals/patch-compositor';+import {getRenderVideoScript} from './internals/render-video-script';+import type {OnProgress, VercelSandbox} from './types';++export const SANDBOX_CREATING_TIMEOUT = 5 * 60 * 1000;++export async function createSandbox({+ bundleDir,+ onProgress,+}: {+ bundleDir: string;+ onProgress?: OnProgress;+}): Promise<VercelSandbox> {+ const report = (progress: number, message: string) => {+ onProgress?.({progress, message});+ };++ const sandbox = await createDisposableSandbox({+ runtime: 'node24',+ resources: {vcpus: 4},+ timeout: SANDBOX_CREATING_TIMEOUT,+ });++ // 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;++ report(0, 'Installing system dependencies...');++ // Stage 1: Install system dependencies (60%)+ await installSystemDependencies({+ sandbox,+ onProgress: (stageProgress: number) => {+ report(+ stageProgress * WEIGHT_SYS_DEPS,+ 'Installing system dependencies...',+ );+ return Promise.resolve();+ },+ });++ report(WEIGHT_SYS_DEPS, 'Adding Remotion bundle to sandbox...');++ // Stage 2: Copy Remotion bundle (20%)+ await addBundleToSandbox({sandbox, bundleDir});++ report(WEIGHT_SYS_DEPS + WEIGHT_BUNDLE, 'Installing JS dependencies...');++ // Install renderer and blob SDK+ await installJsDependencies({sandbox});++ // Patch compositor binary for glibc 2.34 compatibility (Amazon Linux 2023)+ await patchCompositor({sandbox});++ // Stage 3: Download browser (20%)+ report(WEIGHT_SYS_DEPS + WEIGHT_BUNDLE, 'Downloading browser...');+ await installBrowser({+ sandbox,+ onProgress: (browserProgress: number) => {+ report(+ WEIGHT_SYS_DEPS + WEIGHT_BUNDLE + browserProgress * WEIGHT_BROWSER,+ 'Downloading browser...',+ );+ return Promise.resolve();+ },+ });++ // Write a default render script and package.json (module type)+ const renderScript = getRenderVideoScript({+ codec: 'h264',+ outputFile: '/tmp/video.mp4',+ });+ await sandbox.writeFiles([+ {+ path: 'render.ts',+ content: Buffer.from(renderScript),+ },+ {+ path: 'package.json',+ content: Buffer.from(JSON.stringify({type: 'module'})),+ },+ ]);++ report(1, 'Sandbox ready');++ return sandbox;+}diff --git a/packages/vercel/src/create-snapshot.ts b/packages/vercel/src/create-snapshot.tsnew file mode 100644index 0000000000..019110c506--- /dev/null+++ b/packages/vercel/src/create-snapshot.ts@@ -0,0 +1,10 @@+import type {VercelSandbox} from './types';++export async function createSnapshot({+ sandbox,+}: {+ sandbox: VercelSandbox;+}): Promise<{snapshotId: string}> {+ const snapshot = await sandbox.snapshot({expiration: 0});+ return {snapshotId: snapshot.snapshotId};+}diff --git a/packages/vercel/src/get-or-create-sandbox.ts b/packages/vercel/src/get-or-create-sandbox.tsnew file mode 100644index 0000000000..c6b8e8795f--- /dev/null+++ b/packages/vercel/src/get-or-create-sandbox.ts@@ -0,0 +1,32 @@+import {createSandbox, SANDBOX_CREATING_TIMEOUT} from './create-sandbox';+import {getSnapshot} from './get-snapshot';+import {createDisposableSandbox} from './internals/disposable';+import type {OnProgress, VercelSandbox} from './types';++export async function getOrCreateSandbox({+ bundleDir,+ onProgress,+}: {+ bundleDir: string;+ onProgress?: OnProgress;+}): Promise<VercelSandbox> {+ // During local development, a new sandbox is created from scratch always (no snapshotting)+ if (!process.env.VERCEL) {+ onProgress?.({progress: 0, message: 'Creating sandbox...'});+ return createSandbox({bundleDir, onProgress});+ }++ // In production, the snapshot is created at build time via `create-snapshot`+ const cachedSnapshotId = await getSnapshot();++ if (!cachedSnapshotId) {+ throw new Error(+ 'No sandbox snapshot found. Run `bun run create-snapshot` as part of the build process.',+ );+ }++ return createDisposableSandbox({+ source: {type: 'snapshot', snapshotId: cachedSnapshotId},+ timeout: SANDBOX_CREATING_TIMEOUT,+ });+}diff --git a/packages/vercel/src/get-snapshot.ts b/packages/vercel/src/get-snapshot.tsnew file mode 100644index 0000000000..c130369f11--- /dev/null+++ b/packages/vercel/src/get-snapshot.ts@@ -0,0 +1,24 @@+import {head} from '@vercel/blob';++type SnapshotCache = {+ snapshotId: string;+};++const getSnapshotBlobKey = () =>+ `snapshot-cache/${process.env.VERCEL_DEPLOYMENT_ID ?? 'local'}.json`;++export async function getSnapshot(): Promise<string | null> {+ if (!process.env.VERCEL) {+ return null;+ }++ try {+ const metadata = await head(getSnapshotBlobKey());+ const response = await fetch(metadata.url);+ const cache: SnapshotCache = await response.json();++ return cache.snapshotId;+ } catch {+ return null;+ }+}diff --git a/packages/vercel/src/index.ts b/packages/vercel/src/index.tsnew file mode 100644index 0000000000..00b15e0343--- /dev/null+++ b/packages/vercel/src/index.ts@@ -0,0 +1,9 @@+export {createSandbox} from './create-sandbox';+export {createSnapshot} from './create-snapshot';+export {getOrCreateSandbox} from './get-or-create-sandbox';+export {getSnapshot} from './get-snapshot';+export {renderStillOnVercel} from './render-still';+export {renderVideoOnVercel} from './render-video';+export {saveSnapshot} from './save-snapshot';+export type {OnProgress, RenderOnVercelProgress, VercelSandbox} from './types';+export {uploadToBlobStorage} from './upload-to-blob-storage';diff --git a/packages/vercel/src/internals/add-bundle.ts b/packages/vercel/src/internals/add-bundle.tsnew file mode 100644index 0000000000..0c77a182a9--- /dev/null+++ b/packages/vercel/src/internals/add-bundle.ts@@ -0,0 +1,79 @@+import type {Sandbox} from '@vercel/sandbox';+import {execSync} from 'child_process';+import {existsSync} from 'fs';+import {readdir, readFile} from 'fs/promises';+import path from 'path';++function ensureLocalBundle(bundleDir: string): void {+ if (process.env.VERCEL) {+ return;+ }++ const fullBundleDir = path.join(process.cwd(), bundleDir);+ if (!existsSync(fullBundleDir)) {+ try {+ execSync(`node_modules/.bin/remotion bundle --out-dir ./${bundleDir}`, {+ cwd: process.cwd(),+ stdio: 'pipe',+ });+ } catch (e) {+ const stderr = (e as {stderr?: Buffer}).stderr?.toString() ?? '';+ throw new Error(`Remotion bundle failed: ${stderr}`);+ }+ }+}++async function getRemotionBundleFiles(+ bundleDir: string,+): Promise<{path: string; content: Buffer}[]> {+ const fullBundleDir = path.join(process.cwd(), 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(fullBundleDir);+ return files;+}++export const addBundleToSandbox = async ({+ sandbox,+ bundleDir,+}: {+ sandbox: Sandbox & AsyncDisposable;+ bundleDir: string;+}) => {+ ensureLocalBundle(bundleDir);+ const bundleFiles = await getRemotionBundleFiles(bundleDir);++ 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(bundleDir + '/' + dir);+ }++ await sandbox.writeFiles(+ bundleFiles.map((file) => ({+ path: bundleDir + '/' + file.path,+ content: file.content,+ })),+ );+};diff --git a/packages/vercel/src/internals/disposable.ts b/packages/vercel/src/internals/disposable.tsnew file mode 100644index 0000000000..1c1de81fec--- /dev/null+++ b/packages/vercel/src/internals/disposable.ts@@ -0,0 +1,13 @@+import {Sandbox} from '@vercel/sandbox';+import type {VercelSandbox} from '../types';++export const createDisposableSandbox = async (+ options: Parameters<typeof Sandbox.create>[0],+): Promise<VercelSandbox> => {+ const sandbox = await Sandbox.create(options);+ return Object.assign(sandbox, {+ [Symbol.asyncDispose]: async () => {+ await sandbox.stop().catch(() => {});+ },+ });+};diff --git a/packages/template-vercel/ensure-browser.ts b/packages/vercel/src/internals/ensure-browser-script.tssimilarity index 74%rename from packages/template-vercel/ensure-browser.tsrename to packages/vercel/src/internals/ensure-browser-script.tsindex 8e082c3230..9f806b5358 100644--- a/packages/template-vercel/ensure-browser.ts+++ b/packages/vercel/src/internals/ensure-browser-script.ts@@ -1,4 +1,5 @@-// This file is copied into the Vercel sandbox and executed with `node --strip-types`+export const getEnsureBrowserScript = (): string => {+ return `\import { ensureBrowser } from "@remotion/renderer";await ensureBrowser({@@ -11,3 +12,5 @@ await ensureBrowser({};},});+`;+};diff --git a/packages/vercel/src/internals/install-browser.ts b/packages/vercel/src/internals/install-browser.tsnew file mode 100644index 0000000000..cebd7c2241--- /dev/null+++ b/packages/vercel/src/internals/install-browser.ts@@ -0,0 +1,45 @@+import type {Sandbox} from '@vercel/sandbox';+import {getEnsureBrowserScript} from './ensure-browser-script';++export async function installBrowser({+ sandbox,+ onProgress,+}: {+ sandbox: Sandbox;+ onProgress: (progress: number) => Promise<void>;+}): Promise<void> {+ const ensureBrowserScript = getEnsureBrowserScript();+ await sandbox.writeFiles([+ {+ path: 'ensure-browser.ts',+ content: Buffer.from(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/vercel/src/internals/install-js-dependencies.ts b/packages/vercel/src/internals/install-js-dependencies.tsnew file mode 100644index 0000000000..f53b25704a--- /dev/null+++ b/packages/vercel/src/internals/install-js-dependencies.ts@@ -0,0 +1,28 @@+import type {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}`,+ `@remotion/compositor-linux-x64-gnu@${VERSION}`,+ `@vercel/blob`,+ ],+ detached: true,+ });++ for await (const _log of installCmd.logs()) {+ // consume logs+ }++ const installResult = await installCmd.wait();+ if (installResult.exitCode !== 0) {+ throw new Error(`pnpm install failed: ${await installResult.stderr()}`);+ }+}diff --git a/packages/vercel/src/internals/install-system-dependencies.ts b/packages/vercel/src/internals/install-system-dependencies.tsnew file mode 100644index 0000000000..6762644de5--- /dev/null+++ b/packages/vercel/src/internals/install-system-dependencies.ts@@ -0,0 +1,53 @@+import type {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',+ 'patchelf',+ 'zstd',+ 'binutils',+ ],+ 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;+ 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/sandbox/patch-compositor.ts b/packages/vercel/src/internals/patch-compositor.tssimilarity index 79%rename from packages/template-vercel/src/app/api/render/sandbox/patch-compositor.tsrename to packages/vercel/src/internals/patch-compositor.tsindex cc621a25fd..95c81aecf9 100644--- a/packages/template-vercel/src/app/api/render/sandbox/patch-compositor.ts+++ b/packages/vercel/src/internals/patch-compositor.ts@@ -1,8 +1,8 @@-import { Sandbox } from "@vercel/sandbox";+import type {Sandbox} from '@vercel/sandbox';-const GLIBC_DIR = "/tmp/glibc235";+const GLIBC_DIR = '/tmp/glibc235';const LIBC6_DEB_URL =- "https://launchpadlibrarian.net/612471225/libc6_2.35-0ubuntu3.1_amd64.deb";+ 'https://launchpadlibrarian.net/612471225/libc6_2.35-0ubuntu3.1_amd64.deb';/*** Remotion does not officially support glibc 2.34, but it can be patched.@@ -12,14 +12,14 @@ const LIBC6_DEB_URL =* We download Ubuntu 22.04's libc6 package and use patchelf to* point the compositor at the bundled glibc.*- * Only the `remotion` binary needs patching β ffmpeg/ffprobe work fine on glibc 2.34.+ * Only the `remotion` binary needs patching - ffmpeg/ffprobe work fine on glibc 2.34.*/export async function patchCompositor({- sandbox,+ sandbox,}: {- sandbox: Sandbox;+ sandbox: Sandbox;}): Promise<void> {- const script = `+ const script = `set -euo pipefailecho "[patch-compositor] Listing node_modules/@remotion/:"@@ -87,20 +87,20 @@ patchelf \\echo "[patch-compositor] Compositor patched successfully"`;- const cmd = await sandbox.runCommand({- cmd: "bash",- args: ["-c", script],- detached: true,- });-- for await (const _log of cmd.logs()) {- console.log(_log.data);- }-- const result = await cmd.wait();- if (result.exitCode !== 0) {- throw new Error(- `Failed to patch compositor: ${await result.stderr()} ${await result.stdout()}`,- );- }+ const cmd = await sandbox.runCommand({+ cmd: 'bash',+ args: ['-c', script],+ detached: true,+ });++ for await (const _log of cmd.logs()) {+ // consume logs+ }++ const result = await cmd.wait();+ if (result.exitCode !== 0) {+ throw new Error(+ `Failed to patch compositor: ${await result.stderr()} ${await result.stdout()}`,+ );+ }}diff --git a/packages/vercel/src/internals/render-still-script.ts b/packages/vercel/src/internals/render-still-script.tsnew file mode 100644index 0000000000..88f0d8ec19--- /dev/null+++ b/packages/vercel/src/internals/render-still-script.ts@@ -0,0 +1,48 @@+export const getRenderStillScript = ({+ imageFormat,+ outputFile,+}: {+ imageFormat: string;+ outputFile: string;+}): string => {+ return `\+import {+ openBrowser,+ renderStill,+ selectComposition,+} from "@remotion/renderer";+import { statSync } from "fs";++const config = JSON.parse(process.argv[2]);++try {+ console.log(JSON.stringify({ type: "opening-browser" }));+ const browser = await openBrowser("chrome");+ console.log(JSON.stringify({ type: "selecting-composition" }));+ const composition = await selectComposition({+ serveUrl: config.serveUrl,+ id: config.compositionId,+ inputProps: config.inputProps,+ puppeteerInstance: browser,+ });++ await renderStill({+ composition,+ serveUrl: config.serveUrl,+ imageFormat: ${JSON.stringify(imageFormat)},+ output: ${JSON.stringify(outputFile)},+ inputProps: config.inputProps,+ puppeteerInstance: browser,+ });++ console.log(JSON.stringify({ type: "render-complete" }));+ await browser.close({ silent: false });++ const size = statSync(${JSON.stringify(outputFile)}).size;+ console.log(JSON.stringify({ type: "done", size }));+} catch (err) {+ console.error(err.message);+ process.exit(1);+}+`;+};diff --git a/packages/vercel/src/internals/render-video-script.ts b/packages/vercel/src/internals/render-video-script.tsnew file mode 100644index 0000000000..de022dd9a6--- /dev/null+++ b/packages/vercel/src/internals/render-video-script.ts@@ -0,0 +1,51 @@+export const getRenderVideoScript = ({+ codec,+ outputFile,+}: {+ codec: string;+ outputFile: string;+}): string => {+ return `\+import {+ openBrowser,+ renderMedia,+ selectComposition,+} from "@remotion/renderer";+import { readFileSync, statSync } from "fs";++const config = JSON.parse(process.argv[2]);++try {+ console.log(JSON.stringify({ type: "opening-browser" }));+ const browser = await openBrowser("chrome");+ console.log(JSON.stringify({ type: "selecting-composition" }));+ const composition = await selectComposition({+ serveUrl: config.serveUrl,+ id: config.compositionId,+ inputProps: config.inputProps,+ puppeteerInstance: browser,+ });++ await renderMedia({+ composition,+ serveUrl: config.serveUrl,+ codec: ${JSON.stringify(codec)},+ outputLocation: ${JSON.stringify(outputFile)},+ inputProps: config.inputProps,+ onProgress: ({ progress }) => {+ console.log(JSON.stringify({ type: "progress", progress }));+ },+ puppeteerInstance: browser,+ });++ console.log(JSON.stringify({ type: "render-complete" }));+ await browser.close({ silent: false });++ const size = statSync(${JSON.stringify(outputFile)}).size;+ console.log(JSON.stringify({ type: "done", size }));+} catch (err) {+ console.error(err.message);+ process.exit(1);+}+`;+};diff --git a/packages/vercel/src/render-still.ts b/packages/vercel/src/render-still.tsnew file mode 100644index 0000000000..0f3c7b6a95--- /dev/null+++ b/packages/vercel/src/render-still.ts@@ -0,0 +1,67 @@+import {getRenderStillScript} from './internals/render-still-script';+import type {RenderOnVercelProgress, VercelSandbox} from './types';++export async function renderStillOnVercel({+ sandbox,+ compositionId,+ inputProps,+ imageFormat = 'png',+ outputFile = '/tmp/still.png',+ onProgress,+ bundleDir = '.remotion',+}: {+ sandbox: VercelSandbox;+ compositionId: string;+ inputProps: Record<string, unknown>;+ imageFormat?: 'png' | 'jpeg' | 'webp';+ outputFile?: string;+ onProgress?: (progress: RenderOnVercelProgress) => void;+ bundleDir?: string;+}): Promise<{file: string}> {+ const serveUrl = `/vercel/sandbox/${bundleDir}`;++ const renderScript = getRenderStillScript({imageFormat, outputFile});++ await sandbox.writeFiles([+ {+ path: 'render-still.ts',+ content: Buffer.from(renderScript),+ },+ ]);++ const renderConfig = {+ serveUrl,+ compositionId,+ inputProps,+ };++ const renderCmd = await sandbox.runCommand({+ cmd: 'node',+ args: ['--strip-types', 'render-still.ts', JSON.stringify(renderConfig)],+ detached: true,+ });++ for await (const log of renderCmd.logs()) {+ if (log.stream === 'stdout') {+ try {+ const message = JSON.parse(log.data);+ if (message.type === 'opening-browser') {+ onProgress?.({type: 'opening-browser'});+ } else if (message.type === 'selecting-composition') {+ onProgress?.({type: 'selecting-composition'});+ }+ } catch {+ // Not JSON, ignore+ }+ }+ }++ const renderResult = await renderCmd.wait();+ if (renderResult.exitCode !== 0) {+ const stderr = await renderResult.stderr();+ const stdout = await renderResult.stdout();+ throw new Error(`Render still failed: ${stderr} ${stdout}`);+ }++ return {file: outputFile};+}diff --git a/packages/vercel/src/render-video.ts b/packages/vercel/src/render-video.tsnew file mode 100644index 0000000000..9d073b0597--- /dev/null+++ b/packages/vercel/src/render-video.ts@@ -0,0 +1,72 @@+import {getRenderVideoScript} from './internals/render-video-script';+import type {RenderOnVercelProgress, VercelSandbox} from './types';++export async function renderVideoOnVercel({+ sandbox,+ compositionId,+ inputProps,+ codec = 'h264',+ outputFile = '/tmp/video.mp4',+ onProgress,+ bundleDir = '.remotion',+}: {+ sandbox: VercelSandbox;+ compositionId: string;+ inputProps: Record<string, unknown>;+ codec?: string;+ outputFile?: string;+ onProgress?: (progress: RenderOnVercelProgress) => void;+ bundleDir?: string;+}): Promise<{file: string}> {+ const serveUrl = `/vercel/sandbox/${bundleDir}`;++ const renderScript = getRenderVideoScript({codec, outputFile});++ await sandbox.writeFiles([+ {+ path: 'render-video.ts',+ content: Buffer.from(renderScript),+ },+ ]);++ const renderConfig = {+ serveUrl,+ compositionId,+ inputProps,+ };++ const renderCmd = await sandbox.runCommand({+ cmd: 'node',+ args: ['--strip-types', 'render-video.ts', JSON.stringify(renderConfig)],+ detached: true,+ });++ for await (const log of renderCmd.logs()) {+ if (log.stream === 'stdout') {+ try {+ const message = JSON.parse(log.data);+ if (message.type === 'opening-browser') {+ onProgress?.({type: 'opening-browser'});+ } else if (message.type === 'selecting-composition') {+ onProgress?.({type: 'selecting-composition'});+ } else if (message.type === 'progress') {+ onProgress?.({+ type: 'render-progress',+ progress: message.progress,+ });+ }+ } catch {+ // Not JSON, ignore+ }+ }+ }++ const renderResult = await renderCmd.wait();+ if (renderResult.exitCode !== 0) {+ const stderr = await renderResult.stderr();+ const stdout = await renderResult.stdout();+ throw new Error(`Render failed: ${stderr} ${stdout}`);+ }++ return {file: outputFile};+}diff --git a/packages/vercel/src/save-snapshot.ts b/packages/vercel/src/save-snapshot.tsnew file mode 100644index 0000000000..8e932a5b23--- /dev/null+++ b/packages/vercel/src/save-snapshot.ts@@ -0,0 +1,24 @@+import {put} from '@vercel/blob';++type SnapshotCache = {+ snapshotId: string;+};++const getSnapshotBlobKey = () =>+ `snapshot-cache/${process.env.VERCEL_DEPLOYMENT_ID ?? 'local'}.json`;++export async function saveSnapshot({+ snapshotId,+}: {+ snapshotId: string;+}): Promise<void> {+ const cache: SnapshotCache = {+ snapshotId,+ };++ await put(getSnapshotBlobKey(), JSON.stringify(cache), {+ access: 'public',+ contentType: 'application/json',+ addRandomSuffix: false,+ });+}diff --git a/packages/vercel/src/types.ts b/packages/vercel/src/types.tsnew file mode 100644index 0000000000..49095bbf60--- /dev/null+++ b/packages/vercel/src/types.ts@@ -0,0 +1,12 @@+import type {Sandbox} from '@vercel/sandbox';++export type VercelSandbox = Sandbox & AsyncDisposable;++export type OnProgress = (update: {progress: number; message: string}) => void;++export type RenderOnVercelProgress =+ | {type: 'opening-browser'}+ | {type: 'selecting-composition'}+ | {type: 'render-progress'; progress: number}+ | {type: 'uploading'}+ | {type: 'done'; url: string; size: number};diff --git a/packages/vercel/src/upload-to-blob-storage.ts b/packages/vercel/src/upload-to-blob-storage.tsnew file mode 100644index 0000000000..1df1e3ced4--- /dev/null+++ b/packages/vercel/src/upload-to-blob-storage.ts@@ -0,0 +1,112 @@+import type {VercelSandbox} from './types';++function getExtension(filePath: string): string {+ const lastDot = filePath.lastIndexOf('.');+ if (lastDot === -1) {+ return '';+ }++ return filePath.slice(lastDot);+}++function getUploadScript({+ sandboxFilePath,+ blobPath,+ contentType,+ blobToken,+}: {+ sandboxFilePath: string;+ blobPath: string;+ contentType: string;+ blobToken: string;+}): string {+ return `\+import { put } from "@vercel/blob";+import { readFileSync, statSync } from "fs";++try {+ const fileBuffer = readFileSync(${JSON.stringify(sandboxFilePath)});+ const size = statSync(${JSON.stringify(sandboxFilePath)}).size;+ const blob = await put(${JSON.stringify(blobPath)}, fileBuffer, {+ access: "public",+ contentType: ${JSON.stringify(contentType)},+ token: ${JSON.stringify(blobToken)},+ });++ console.log(JSON.stringify({+ type: "done",+ url: blob.downloadUrl,+ size,+ }));+} catch (err) {+ console.error(err.message);+ process.exit(1);+}+`;+}++export async function uploadToBlobStorage({+ sandbox,+ sandboxFilePath,+ blobPath,+ contentType,+ blobToken,+}: {+ sandbox: VercelSandbox;+ sandboxFilePath: string;+ blobPath?: string;+ contentType: string;+ blobToken: string;+}): Promise<{url: string; size: number}> {+ const actualBlobPath =+ blobPath ??+ `renders/${crypto.randomUUID()}${getExtension(sandboxFilePath)}`;++ const uploadScript = getUploadScript({+ sandboxFilePath,+ blobPath: actualBlobPath,+ contentType,+ blobToken,+ });++ await sandbox.writeFiles([+ {+ path: 'upload.ts',+ content: Buffer.from(uploadScript),+ },+ ]);++ const uploadCmd = await sandbox.runCommand({+ cmd: 'node',+ args: ['--strip-types', 'upload.ts'],+ detached: true,+ });++ let result: {url: string; size: number} | null = null;++ for await (const log of uploadCmd.logs()) {+ if (log.stream === 'stdout') {+ try {+ const message = JSON.parse(log.data);+ if (message.type === 'done') {+ result = {url: message.url, size: message.size};+ }+ } catch {+ // Not JSON, ignore+ }+ }+ }++ const uploadResult = await uploadCmd.wait();+ if (uploadResult.exitCode !== 0) {+ const stderr = await uploadResult.stderr();+ const stdout = await uploadResult.stdout();+ throw new Error(`Upload failed: ${stderr} ${stdout}`);+ }++ if (!result) {+ throw new Error('Upload script did not return result');+ }++ return result;+}diff --git a/packages/vercel/tsconfig.json b/packages/vercel/tsconfig.jsonnew file mode 100644index 0000000000..e5c5f5163c--- /dev/null+++ b/packages/vercel/tsconfig.json@@ -0,0 +1,14 @@+{+ "extends": "../tsconfig.settings.json",+ "compilerOptions": {+ "rootDir": "src",+ "outDir": "dist",+ "skipLibCheck": true,+ "target": "ES2022",+ "module": "es2020",+ "moduleResolution": "bundler",+ "declaration": true,+ "emitDeclarationOnly": true+ },+ "include": ["src"]+}diff --git a/tsconfig.json b/tsconfig.jsonindex 5869c92a93..2dbb2a4a2b 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -254,6 +254,9 @@},{"path": "./packages/light-leaks"+ },+ {+ "path": "./packages/vercel"}]}