Skip to content

🎥 Make videos programmatically with React

@remotion/browser-bundler: Extract reusable browser compiler

Jonny Burger7d51ced6ee82
diff --git a/bun.lock b/bun.lock
index 37551eff4d..2ca99d71fc 100644
--- a/bun.lock
+++ b/bun.lock
@@ -149,10 +149,35 @@
"zod": "catalog:",
},
},
+ "packages/browser-bundler": {
+ "name": "@remotion/browser-bundler",
+ "version": "4.0.525",
+ "dependencies": {
+ "@rspack/browser": "2.1.1",
+ "remotion": "workspace:*",
+ },
+ "devDependencies": {
+ "@happy-dom/global-registrator": "14.5.1",
+ "@remotion/eslint-config-internal": "workspace:*",
+ "@remotion/player": "workspace:*",
+ "@testing-library/react": "16.1.0",
+ "@types/react": "catalog:",
+ "@types/react-dom": "catalog:",
+ "@typescript/native-preview": "catalog:",
+ "eslint": "catalog:",
+ "react": "catalog:",
+ "react-dom": "catalog:",
+ },
+ "peerDependencies": {
+ "react": ">=18.0.0",
+ "react-dom": ">=18.0.0",
+ },
+ },
"packages/browser-studio": {
"name": "@remotion/browser-studio",
"version": "4.0.525",
"dependencies": {
+ "@remotion/browser-bundler": "workspace:*",
"@remotion/studio-codemods": "workspace:*",
"@remotion/studio-protocol": "workspace:*",
"@remotion/studio-shared": "workspace:*",
@@ -536,6 +561,7 @@
"@remotion/animation-utils": "workspace:*",
"@remotion/babel-loader": "workspace:*",
"@remotion/brand": "workspace:*",
+ "@remotion/browser-bundler": "workspace:*",
"@remotion/browser-studio": "workspace:*",
"@remotion/bundler": "workspace:*",
"@remotion/captions": "workspace:*",
@@ -1444,6 +1470,7 @@
"name": "@remotion/player-example",
"version": "4.0.525",
"dependencies": {
+ "@remotion/browser-bundler": "workspace:*",
"@remotion/bundler": "workspace:*",
"@remotion/canvas": "workspace:*",
"@remotion/eslint-config-flat": "workspace:*",
@@ -1458,6 +1485,7 @@
"remotion": "workspace:*",
},
"devDependencies": {
+ "@playwright/test": "1.55.1",
"@types/node": "catalog:",
"eslint": "catalog:",
"prettier": "catalog:",
@@ -4533,6 +4561,8 @@
"@remotion/brand": ["@remotion/brand@workspace:packages/brand"],
+ "@remotion/browser-bundler": ["@remotion/browser-bundler@workspace:packages/browser-bundler"],
+
"@remotion/browser-studio": ["@remotion/browser-studio@workspace:packages/browser-studio"],
"@remotion/bundler": ["@remotion/bundler@workspace:packages/bundler"],
@@ -4847,7 +4877,7 @@
"@rspack/core": ["@rspack/[email protected]", "", { "dependencies": { "@module-federation/runtime-tools": "0.22.0", "@rspack/binding": "1.7.11", "@rspack/lite-tapable": "1.1.0" }, "peerDependencies": { "@swc/helpers": ">=0.5.1" }, "optionalPeers": ["@swc/helpers"] }, "sha512-rsD9b+Khmot5DwCMiB3cqTQo53ioPG3M/A7BySu8+0+RS7GCxKm+Z+mtsjtG/vsu4Tn2tcqCdZtA3pgLoJB+ew=="],
- "@rspack/lite-tapable": ["@rspack/[email protected]", "", {}, "sha512-E2B0JhYFmVAwdDiG14+DW0Di4Ze4Jg10Pc4/lILUrd5DRCaklduz2OvJ5HYQ6G+hd+WTzqQb3QnDNfK4yvAFYw=="],
+ "@rspack/lite-tapable": ["@rspack/[email protected]", "", {}, "sha512-1OnyWChLGE46YzWyjlmYJssOu/Y0STAnnr2ueKPqDCYTf63GJMs0mxNnCul4dNiVqHYPKv3/fxrTY3IpqoVwZQ=="],
"@rspack/plugin-react-refresh": ["@rspack/[email protected]", "", { "dependencies": { "error-stack-parser": "^2.1.4", "html-entities": "^2.6.0" }, "peerDependencies": { "react-refresh": ">=0.10.0 <1.0.0", "webpack-hot-middleware": "2.x" }, "optionalPeers": ["webpack-hot-middleware"] }, "sha512-eqqW5645VG3CzGzFgNg5HqNdHVXY+567PGjtDhhrM8t67caxmsSzRmT5qfoEIfBcGgFkH9vEg7kzXwmCYQdQDw=="],
@@ -10669,6 +10699,10 @@
"@remotion/brand/react-dom": ["[email protected]", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.3" } }, "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg=="],
+ "@remotion/browser-bundler/react": ["[email protected]", "", {}, "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA=="],
+
+ "@remotion/browser-bundler/react-dom": ["[email protected]", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.3" } }, "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg=="],
+
"@remotion/browser-studio/react": ["[email protected]", "", {}, "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA=="],
"@remotion/browser-studio/react-dom": ["[email protected]", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.3" } }, "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg=="],
@@ -10883,12 +10917,12 @@
"@rspack/binding-wasm32-wasi/@napi-rs/wasm-runtime": ["@napi-rs/[email protected]", "", { "dependencies": { "@emnapi/core": "^1.5.0", "@emnapi/runtime": "^1.5.0", "@tybys/wasm-util": "^0.10.1" } }, "sha512-SeDnOO0Tk7Okiq6DbXmmBODgOAb9dp9gjlphokTUxmt8U3liIP1ZsozBahH69j/RJv+Rfs6IwUKHTgQYJ/HBAw=="],
- "@rspack/browser/@rspack/lite-tapable": ["@rspack/[email protected]", "", {}, "sha512-1OnyWChLGE46YzWyjlmYJssOu/Y0STAnnr2ueKPqDCYTf63GJMs0mxNnCul4dNiVqHYPKv3/fxrTY3IpqoVwZQ=="],
-
"@rspack/browser/memfs": ["[email protected]", "", { "dependencies": { "@jsonjoy.com/fs-core": "4.57.7", "@jsonjoy.com/fs-fsa": "4.57.7", "@jsonjoy.com/fs-node": "4.57.7", "@jsonjoy.com/fs-node-builtins": "4.57.7", "@jsonjoy.com/fs-node-to-fsa": "4.57.7", "@jsonjoy.com/fs-node-utils": "4.57.7", "@jsonjoy.com/fs-print": "4.57.7", "@jsonjoy.com/fs-snapshot": "4.57.7", "@jsonjoy.com/json-pack": "^1.11.0", "@jsonjoy.com/util": "^1.9.0", "glob-to-regex.js": "^1.0.1", "thingies": "^2.5.0", "tree-dump": "^1.0.3", "tslib": "^2.0.0" } }, "sha512-YZPphUQZSRGk6ddPlsNuMbztrLwsbUATFNZcqKscSbSJZ4g0+Y3vSZLJ/rfnGZaB1FFhC7SrywZXev6i8lnHgg=="],
"@rspack/browser/webpack-sources": ["[email protected]", "", {}, "sha512-HPuy+uuoTCaaoEoI1LQ3JN9+vrPBvEesnnX1jADHy728cHSMlq4wUc4afYqahq2B1mhQVZxCXOkNTnXltr+2vQ=="],
+ "@rspack/core/@rspack/lite-tapable": ["@rspack/[email protected]", "", {}, "sha512-E2B0JhYFmVAwdDiG14+DW0Di4Ze4Jg10Pc4/lILUrd5DRCaklduz2OvJ5HYQ6G+hd+WTzqQb3QnDNfK4yvAFYw=="],
+
"@shikijs/primitive/@shikijs/types": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-qzbeRooUTPnLE+sHD/Z8DStmaDgnbbc/pMrU203950aRqjX/6AFHeDYT+j00y2lPdz0ywJKx7o/7qnqTivtlXg=="],
"@shopify/react-native-skia/react": ["[email protected]", "", {}, "sha512-V8AVnmPIICiWpGfm6GLzCR/W5FXLchHop40W4nXBmdlEceh16rCN8O8LNWm5bh5XUX91fh7KpA+W0TgMKmgTpQ=="],
diff --git a/package.json b/package.json
index 6375551224..8da8c6a8fe 100644
--- a/package.json
+++ b/package.json
@@ -18,6 +18,7 @@
"testwebcodecs": "turbo run testwebcodecs --no-update-notifier",
"testwebrenderer": "turbo run testwebrenderer --concurrency=1 --no-update-notifier",
"testbrowserstudio": "turbo run testbrowserstudio --concurrency=1 --no-update-notifier",
+ "testbrowserbundler": "turbo run testbrowserbundler --concurrency=1 --no-update-notifier",
"testlayoututils": "turbo run testlayoututils --concurrency=1 --no-update-notifier",
"testeffectsvisual": "turbo run testeffectsvisual --concurrency=1 --no-update-notifier",
"testlambda": "turbo run testlambda --concurrency=1 --no-update-notifier",
diff --git a/packages/browser-bundler/.npmignore b/packages/browser-bundler/.npmignore
new file mode 100644
index 0000000000..8ac36fc493
--- /dev/null
+++ b/packages/browser-bundler/.npmignore
@@ -0,0 +1,11 @@
+dist/test/**
+src
+eslint.config.mjs
+tsconfig.tsbuildinfo
+*.tgz
+.turbo
+tsconfig.json
+.prettierrc.js
+bundle.ts
+bunfig.toml
+dist/cjs/test
diff --git a/packages/browser-bundler/README.md b/packages/browser-bundler/README.md
new file mode 100644
index 0000000000..eab42aa8c4
--- /dev/null
+++ b/packages/browser-bundler/README.md
@@ -0,0 +1,11 @@
+# @remotion/browser-bundler
+
+Experimental browser-side bundling for virtual Remotion projects. Compile source snapshots, then use `@remotion/browser-bundler/runtime` to select a registered composition for your own UI, such as a Remotion Player.
+
+```sh
+npm install @remotion/browser-bundler
+```
+
+Requires a cross-origin-isolated browser page and worker/WebAssembly asset support in your app's bundler. The runtime executes trusted code with host-page privileges; it is not a sandbox.
+
+[Documentation](https://www.remotion.dev/docs/browser-bundler)
diff --git a/packages/browser-bundler/bundle.ts b/packages/browser-bundler/bundle.ts
new file mode 100644
index 0000000000..daea4b48c7
--- /dev/null
+++ b/packages/browser-bundler/bundle.ts
@@ -0,0 +1,68 @@
+import path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {build} from 'bun';
+import rootPackage from '../../package.json';
+import remotionPackage from '../core/package.json';
+
+if (process.env.NODE_ENV !== 'production') {
+ throw new Error('This script must be run using NODE_ENV=production');
+}
+
+const define = {
+ __BROWSER_BUNDLER_DEPENDENCY_VERSIONS__: JSON.stringify({
+ react: rootPackage.workspaces.catalog.react,
+ 'react-dom': rootPackage.workspaces.catalog['react-dom'],
+ remotion: remotionPackage.version,
+ }),
+};
+
+const output = await build({
+ entrypoints: [
+ 'src/index.ts',
+ 'src/runtime.ts',
+ 'src/compiler.ts',
+ ],
+ naming: '[name].js',
+ outdir: 'dist',
+ target: 'browser',
+ define,
+ external: [
+ '@rspack/browser',
+ 'react',
+ 'react-dom',
+ 'react-dom/client',
+ 'react/jsx-runtime',
+ 'react/jsx-dev-runtime',
+ 'remotion',
+ 'remotion/no-react',
+ 'remotion/version',
+ ],
+});
+
+if (!output.success) {
+ throw new Error(output.logs.join('\n'));
+}
+
+// Ship Rspack's runtime as part of the worker. Consumers should not have to
+// rebundle its generated module loader or know its internal dependency graph.
+const workerOutput = await build({
+ entrypoints: ['src/browser-bundler-worker.ts'],
+ naming: '[name].js',
+ outdir: 'dist',
+ target: 'browser',
+ minify: true,
+ define,
+});
+if (!workerOutput.success) {
+ throw new Error(workerOutput.logs.join('\n'));
+}
+
+const rspackDir = path.dirname(fileURLToPath(import.meta.resolve('@rspack/browser')));
+for (const asset of [
+ 'rspack.wasm32-wasi.wasm',
+ 'wasi-worker-browser.mjs',
+ 'wasi-worker-browser.mjs.LICENSE.txt',
+ 'index.js.LICENSE.txt',
+]) {
+ await Bun.write(path.join('dist', asset), Bun.file(path.join(rspackDir, asset)));
+}
diff --git a/packages/browser-bundler/bunfig.toml b/packages/browser-bundler/bunfig.toml
new file mode 100644
index 0000000000..297a01eead
--- /dev/null
+++ b/packages/browser-bundler/bunfig.toml
@@ -0,0 +1,2 @@
+[test]
+preload = "./src/test/runtime-dom.ts"
diff --git a/packages/browser-bundler/eslint.config.mjs b/packages/browser-bundler/eslint.config.mjs
new file mode 100644
index 0000000000..ab29acaba0
--- /dev/null
+++ b/packages/browser-bundler/eslint.config.mjs
@@ -0,0 +1,7 @@
+import {remotionFlatConfig} from '@remotion/eslint-config-internal';
+
+const config = remotionFlatConfig({react: true});
+
+export default {
+ ...config,
+};
diff --git a/packages/browser-bundler/package.json b/packages/browser-bundler/package.json
new file mode 100644
index 0000000000..ee0d137870
--- /dev/null
+++ b/packages/browser-bundler/package.json
@@ -0,0 +1,69 @@
+{
+ "name": "@remotion/browser-bundler",
+ "version": "4.0.525",
+ "description": "Compile virtual Remotion projects in the browser",
+ "main": "dist/index.js",
+ "types": "dist/index.d.ts",
+ "module": "dist/index.js",
+ "type": "module",
+ "repository": {
+ "url": "https://github.com/remotion-dev/remotion/tree/main/packages/browser-bundler"
+ },
+ "scripts": {
+ "test": "bun test src/test",
+ "formatting": "oxfmt src --check",
+ "format": "oxfmt src",
+ "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": {
+ "@rspack/browser": "2.1.1",
+ "remotion": "workspace:*"
+ },
+ "peerDependencies": {
+ "react": ">=18.0.0",
+ "react-dom": ">=18.0.0"
+ },
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.ts",
+ "import": "./dist/index.js",
+ "module": "./dist/index.js"
+ },
+ "./runtime": {
+ "types": "./dist/runtime.d.ts",
+ "import": "./dist/runtime.js",
+ "module": "./dist/runtime.js"
+ },
+ "./compiler": {
+ "types": "./dist/compiler.d.ts",
+ "import": "./dist/compiler.js",
+ "module": "./dist/compiler.js"
+ },
+ "./package.json": "./package.json"
+ },
+ "devDependencies": {
+ "@happy-dom/global-registrator": "14.5.1",
+ "@remotion/eslint-config-internal": "workspace:*",
+ "@remotion/player": "workspace:*",
+ "@testing-library/react": "16.1.0",
+ "@types/react": "catalog:",
+ "@types/react-dom": "catalog:",
+ "@typescript/native-preview": "catalog:",
+ "eslint": "catalog:",
+ "react": "catalog:",
+ "react-dom": "catalog:"
+ },
+ "keywords": ["remotion", "browser", "bundler", "rspack"],
+ "publishConfig": {
+ "access": "public"
+ },
+ "homepage": "https://www.remotion.dev/docs/browser-bundler"
+}
diff --git a/packages/browser-bundler/src/browser-bundler-worker.ts b/packages/browser-bundler/src/browser-bundler-worker.ts
new file mode 100644
index 0000000000..d222e79db5
--- /dev/null
+++ b/packages/browser-bundler/src/browser-bundler-worker.ts
@@ -0,0 +1,151 @@
+import {
+ createBrowserCompiler,
+ type BrowserCompiler,
+} from './create-browser-compiler';
+import {createBrowserDependencyPlugin} from './dependency-resolution';
+import {BrowserBundlerError, serializeCompilerError} from './errors';
+import {makeBrowserHttpClient} from './http-client';
+import type {
+ BrowserBundlerWorkerRequest,
+ BrowserBundlerWorkerResponse,
+ VirtualProject,
+} from './types';
+import {normalizeVirtualPath} from './virtual-project';
+
+declare const __BROWSER_BUNDLER_DEPENDENCY_VERSIONS__: Record<string, string>;
+
+const sharedModules = [
+ 'react',
+ 'react-dom',
+ 'react-dom/client',
+ 'react/jsx-runtime',
+ 'react/jsx-dev-runtime',
+ 'remotion',
+ 'remotion/no-react',
+ 'remotion/version',
+];
+
+let compiler: BrowserCompiler | null = null;
+let previousProject: VirtualProject | null = null;
+let queue: Promise<void> = Promise.resolve();
+
+const postResponse = (response: BrowserBundlerWorkerResponse) => {
+ self.postMessage(response);
+};
+
+self.addEventListener(
+ 'message',
+ (event: MessageEvent<BrowserBundlerWorkerRequest>) => {
+ const request = event.data;
+ queue = queue.then(async () => {
+ try {
+ const {project} = request;
+ if (
+ compiler &&
+ (previousProject?.rootDir !== project.rootDir ||
+ previousProject?.entryPoint !== project.entryPoint)
+ ) {
+ await compiler.dispose();
+ compiler = null;
+ }
+
+ compiler ??= await createBrowserCompiler({
+ project,
+ virtualFiles: {},
+ onProgress: (progress) =>
+ postResponse({type: 'progress', ...progress}),
+ configure: (rspack) => ({
+ context: normalizeVirtualPath(project.rootDir),
+ mode: 'development',
+ devtool: 'inline-cheap-module-source-map',
+ entry: {
+ bundle: {
+ asyncChunks: false,
+ import: [normalizeVirtualPath(project.entryPoint)],
+ },
+ },
+ experiments: {
+ buildHttp: {
+ allowedUris: ['https://esm.sh/', `${self.location.origin}/`],
+ cacheLocation: false,
+ httpClient: makeBrowserHttpClient({fetchImplementation: fetch}),
+ },
+ },
+ externals: Object.fromEntries(
+ sharedModules.map((name) => [name, `commonjs ${name}`]),
+ ),
+ module: {
+ rules: [
+ {parser: {worker: false}, test: /\.[cm]?[jt]sx?$/},
+ {
+ test: /\.[jt]sx?$/,
+ use: [
+ {
+ loader: 'builtin:swc-loader',
+ options: {
+ env: {targets: 'Chrome >= 111'},
+ jsc: {
+ parser: {syntax: 'typescript', tsx: true},
+ transform: {
+ react: {
+ // jsxDEV is unavailable in production React.
+ development: false,
+ runtime: 'automatic',
+ },
+ },
+ },
+ },
+ },
+ ],
+ },
+ ],
+ },
+ optimization: {runtimeChunk: false, splitChunks: false},
+ output: {
+ filename: 'bundle.js',
+ path: '/dist',
+ publicPath: '',
+ hashFunction: 'xxhash64',
+ uniqueName: 'remotion-browser-bundler',
+ },
+ plugins: [
+ createBrowserDependencyPlugin({
+ rspack,
+ development: false,
+ external: ['react', 'react-dom', 'remotion'],
+ resolvedUrls: {},
+ resolvedVersions: {
+ ...__BROWSER_BUNDLER_DEPENDENCY_VERSIONS__,
+ ...request.dependencyVersions,
+ },
+ resolvePackage: null,
+ }),
+ new rspack.optimize.LimitChunkCountPlugin({maxChunks: 1}),
+ ],
+ resolve: {extensions: ['.tsx', '.ts', '.jsx', '.js', '.json']},
+ }),
+ });
+ previousProject = project;
+ const result = await compiler.compile(project);
+ if (result.bundle === null) {
+ throw new BrowserBundlerError(
+ 'Rspack compilation failed',
+ result.errors,
+ );
+ }
+
+ postResponse({
+ type: 'bundle',
+ id: request.id,
+ bundle: {code: result.bundle, warnings: result.warnings},
+ });
+ } catch (error) {
+ postResponse({
+ type: 'error',
+ id: request.id,
+ error: serializeCompilerError(error),
+ });
+ }
+ });
+ },
+);
diff --git a/packages/browser-bundler/src/compiler.ts b/packages/browser-bundler/src/compiler.ts
new file mode 100644
index 0000000000..f9f79831db
--- /dev/null
+++ b/packages/browser-bundler/src/compiler.ts
@@ -0,0 +1,12 @@
+export {
+ createBrowserCompiler,
+ type BrowserCompiler,
+ type BrowserCompilerResult,
+} from './create-browser-compiler';
+export {createBrowserDependencyPlugin} from './dependency-resolution';
+export {makeBrowserHttpClient} from './http-client';
+export {
+ getVirtualProjectChanges,
+ getVirtualProjectFiles,
+ normalizeVirtualPath,
+} from './virtual-project';
diff --git a/packages/browser-bundler/src/create-browser-bundler.ts b/packages/browser-bundler/src/create-browser-bundler.ts
new file mode 100644
index 0000000000..dca18101c5
--- /dev/null
+++ b/packages/browser-bundler/src/create-browser-bundler.ts
@@ -0,0 +1,111 @@
+import {BrowserBundlerError} from './errors';
+import type {
+ BrowserBundle,
+ BrowserBundler,
+ BrowserBundlerOptions,
+ BrowserBundlerWorkerRequest,
+ BrowserBundlerWorkerResponse,
+} from './types';
+
+export const createBrowserBundler = (
+ options: BrowserBundlerOptions = {},
+): BrowserBundler => {
+ if (typeof Worker === 'undefined') {
+ throw new Error('createBrowserBundler() must be called in a browser.');
+ }
+
+ if (!globalThis.crossOriginIsolated) {
+ throw new Error(
+ 'The browser bundler requires cross-origin isolation. Serve the page with Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp.',
+ );
+ }
+
+ const worker = options.workerUrl
+ ? new Worker(options.workerUrl, {type: 'module'})
+ : new Worker(new URL('./browser-bundler-worker.js', import.meta.url), {
+ type: 'module',
+ });
+ const dependencyVersions = {...options.dependencyVersions};
+ const pending = new Map<
+ number,
+ {
+ resolve: (bundle: BrowserBundle) => void;
+ reject: (error: Error) => void;
+ }
+ >();
+ let nextId = 0;
+ let terminalError: Error | null = null;
+
+ const stop = (error: Error) => {
+ terminalError = error;
+ worker.terminate();
+ for (const request of pending.values()) {
+ request.reject(error);
+ }
+
+ pending.clear();
+ };
+
+ worker.onmessage = (event: MessageEvent<BrowserBundlerWorkerResponse>) => {
+ const response = event.data;
+ if (response.type === 'progress') {
+ options.onProgress?.(response);
+ return;
+ }
+
+ const request = pending.get(response.id);
+ if (!request) {
+ return;
+ }
+
+ pending.delete(response.id);
+ if (response.type === 'error') {
+ const error = new BrowserBundlerError(
+ response.error.message,
+ response.error.diagnostics,
+ );
+ if (response.error.stack) {
+ error.stack = response.error.stack;
+ }
+
+ request.reject(error);
+ return;
+ }
+
+ request.resolve(response.bundle);
+ };
+
+ worker.onerror = (event) => {
+ stop(new Error(event.message || 'The browser compiler worker failed.'));
+ };
+
+ worker.onmessageerror = () => {
+ stop(new Error('Could not read the browser compiler worker response.'));
+ };
+
+ return {
+ bundle: ({project}) => {
+ if (terminalError) {
+ return Promise.reject(terminalError);
+ }
+
+ const id = nextId++;
+ return new Promise<BrowserBundle>((resolve, reject) => {
+ pending.set(id, {resolve, reject});
+ try {
+ worker.postMessage({
+ id,
+ project,
+ dependencyVersions,
+ } satisfies BrowserBundlerWorkerRequest);
+ } catch (error) {
+ pending.delete(id);
+ reject(error);
+ }
+ });
+ },
+ dispose: () => {
+ stop(new Error('The browser bundler has been disposed.'));
+ },
+ };
+};
diff --git a/packages/browser-bundler/src/create-browser-compiler.ts b/packages/browser-bundler/src/create-browser-compiler.ts
new file mode 100644
index 0000000000..3138d31cb0
--- /dev/null
+++ b/packages/browser-bundler/src/create-browser-compiler.ts
@@ -0,0 +1,193 @@
+import type * as RspackBrowser from '@rspack/browser';
+import {loadRspackBrowser} from './load-rspack';
+import type {BrowserBundlerProgress, VirtualProject} from './types';
+import {
+ getVirtualProjectChanges,
+ getVirtualProjectFiles,
+ normalizeVirtualPath,
+} from './virtual-project';
+
+export type BrowserCompilerResult = {
+ bundle: string | null;
+ assets: {name: string; content: string}[];
+ errors: string[];
+ warnings: string[];
+ hash: string | undefined;
+ modules: Record<string, string>;
+ time: number | undefined;
+};
+
+export type BrowserCompiler = {
+ compile: (project: VirtualProject) => Promise<BrowserCompilerResult>;
+ dispose: () => Promise<void>;
+};
+
+const problemToString = (problem: unknown): string => {
+ if (
+ typeof problem === 'object' &&
+ problem !== null &&
+ 'message' in problem &&
+ typeof problem.message === 'string'
+ ) {
+ return problem.message;
+ }
+
+ return String(problem);
+};
+
+// Rspack's WASM filesystem is global to a worker. Keep one compiler per worker.
+export const createBrowserCompiler = async ({
+ project,
+ virtualFiles,
+ configure,
+ onProgress,
+}: {
+ project: VirtualProject;
+ virtualFiles: Record<string, string>;
+ configure: (rspack: typeof RspackBrowser) => RspackBrowser.Configuration;
+ onProgress: ((progress: BrowserBundlerProgress) => void) | null;
+}): Promise<BrowserCompiler> => {
+ const rspack = await loadRspackBrowser(onProgress);
+ const {volume} = rspack.builtinMemFs;
+ let currentFiles = getVirtualProjectFiles(project);
+ const rootDir = normalizeVirtualPath(project.rootDir);
+ const entryPoint = normalizeVirtualPath(project.entryPoint);
+ volume.reset();
+ volume.fromJSON({...virtualFiles, ...currentFiles});
+
+ const compiler = rspack.rspack(configure(rspack));
+ const outputPath = compiler.options.output.path;
+ let queue: Promise<void> = Promise.resolve();
+ let disposed = false;
+ let disposal: Promise<void> | null = null;
+ let initial = true;
+
+ return {
+ compile: (nextProject) => {
+ if (disposed) {
+ return Promise.reject(new Error('The browser compiler was disposed.'));
+ }
+
+ const nextFiles = getVirtualProjectFiles(nextProject);
+ const run = queue.then(() => {
+ if (
+ normalizeVirtualPath(nextProject.rootDir) !== rootDir ||
+ normalizeVirtualPath(nextProject.entryPoint) !== entryPoint
+ ) {
+ throw new Error(
+ 'Create a new compiler when changing rootDir or entryPoint.',
+ );
+ }
+
+ if (!Object.hasOwn(nextFiles, entryPoint)) {
+ throw new Error(
+ `The virtual entry point does not exist: ${entryPoint}`,
+ );
+ }
+
+ const {modified, removed} = getVirtualProjectChanges({
+ previous: currentFiles,
+ next: nextFiles,
+ });
+ for (const path of modified) {
+ volume.mkdirSync(path.slice(0, path.lastIndexOf('/')) || '/', {
+ recursive: true,
+ });
+ volume.writeFileSync(path, nextFiles[path]);
+ }
+
+ for (const path of removed) {
+ volume.unlinkSync(path);
+ }
+
+ currentFiles = nextFiles;
+ const modifiedFiles = initial ? undefined : new Set(modified);
+ const removedFiles = initial ? undefined : new Set(removed);
+ initial = false;
+
+ return new Promise<BrowserCompilerResult>((resolve, reject) => {
+ compiler.run(
+ (error, stats) => {
+ if (error) {
+ reject(error);
+ return;
+ }
+
+ if (!stats) {
+ reject(new Error('Rspack returned no compilation stats'));
+ return;
+ }
+
+ try {
+ const json = stats.toJson({
+ all: false,
+ assets: true,
+ errors: true,
+ hash: true,
+ modules: true,
+ timings: true,
+ warnings: true,
+ });
+ const errors = (json.errors ?? []).map(problemToString);
+ resolve({
+ bundle:
+ errors.length === 0
+ ? String(
+ volume.readFileSync(
+ `${outputPath}/bundle.js`,
+ 'utf8',
+ ),
+ )
+ : null,
+ assets: stats.compilation
+ .getAssets()
+ .map(({name, source}) => ({
+ name,
+ content: String(source.source()),
+ })),
+ errors,
+ warnings: (json.warnings ?? []).map(problemToString),
+ hash: json.hash,
+ modules: Object.fromEntries(
+ (json.modules ?? []).map((module, index) => [
+ String(module.id ?? index),
+ module.name ?? module.identifier ?? '',
+ ]),
+ ),
+ time: json.time,
+ });
+ } catch (readError) {
+ reject(readError);
+ }
+ },
+ {modifiedFiles, removedFiles},
+ );
+ });
+ });
+ // A failed build must not poison subsequent edits. Its caller still
+ // receives the rejection, while the serialization queue can continue.
+ queue = run.then(
+ () => undefined,
+ () => undefined,
+ );
+ return run;
+ },
+ dispose: () => {
+ disposed = true;
+ disposal ??= queue.then(
+ () =>
+ new Promise<void>((resolve, reject) => {
+ compiler.close((error) => {
+ if (error) {
+ reject(error);
+ return;
+ }
+
+ resolve();
+ });
+ }),
+ );
+ return disposal;
+ },
+ };
+};
diff --git a/packages/browser-bundler/src/dependency-resolution.ts b/packages/browser-bundler/src/dependency-resolution.ts
new file mode 100644
index 0000000000..e952af2d63
--- /dev/null
+++ b/packages/browser-bundler/src/dependency-resolution.ts
@@ -0,0 +1,65 @@
+import type * as RspackBrowser from '@rspack/browser';
+
+export const createBrowserDependencyPlugin = ({
+ rspack,
+ resolvedUrls,
+ resolvedVersions,
+ resolvePackage,
+ external,
+ development,
+}: {
+ rspack: typeof RspackBrowser;
+ resolvedUrls: Record<string, string>;
+ resolvedVersions: Record<string, string>;
+ resolvePackage: ((request: string) => string | null) | null;
+ external: string[];
+ development: boolean;
+}) => {
+ const postprocess = (url: URL) => {
+ if (development) {
+ url.searchParams.set('dev', '');
+ }
+
+ url.searchParams.set('external', external.join(','));
+ };
+
+ return new rspack.BrowserHttpImportEsmPlugin({
+ dependencyUrl: ({request}) => {
+ if (
+ request.startsWith('.') ||
+ request.startsWith('/') ||
+ request.startsWith('http://') ||
+ request.startsWith('https://') ||
+ request.includes('!')
+ ) {
+ return undefined;
+ }
+
+ const packageName = request.startsWith('@')
+ ? request.split('/').slice(0, 2).join('/')
+ : request.split('/')[0];
+ const resolvedUrl =
+ resolvedUrls[packageName] ?? resolvePackage?.(request);
+ if (resolvedUrl) {
+ return resolvedUrl;
+ }
+
+ const version =
+ resolvedVersions[packageName] ??
+ (packageName.startsWith('@remotion/')
+ ? resolvedVersions.remotion
+ : null) ??
+ 'latest';
+ const subpath = request.slice(packageName.length);
+ const url = new URL(
+ `${packageName}@${version}${subpath}`,
+ 'https://esm.sh/',
+ );
+ postprocess(url);
+ return url.href;
+ },
+ dependencyVersions: resolvedVersions,
+ domain: 'https://esm.sh',
+ postprocess: ({url}) => postprocess(url),
+ });
+};
diff --git a/packages/browser-bundler/src/errors.ts b/packages/browser-bundler/src/errors.ts
new file mode 100644
index 0000000000..8a87e1c859
--- /dev/null
+++ b/packages/browser-bundler/src/errors.ts
@@ -0,0 +1,19 @@
+import type {SerializedCompilerError} from './types';
+
+export class BrowserBundlerError extends Error {
+ readonly diagnostics: string[];
+
+ constructor(message: string, diagnostics: string[]) {
+ super(message);
+ this.name = 'BrowserBundlerError';
+ this.diagnostics = diagnostics;
+ }
+}
+
+export const serializeCompilerError = (
+ error: unknown,
+): SerializedCompilerError => ({
+ message: error instanceof Error ? error.message : String(error),
+ stack: error instanceof Error ? (error.stack ?? null) : null,
+ diagnostics: error instanceof BrowserBundlerError ? error.diagnostics : [],
+});
diff --git a/packages/browser-bundler/src/get-browser-composition.tsx b/packages/browser-bundler/src/get-browser-composition.tsx
new file mode 100644
index 0000000000..4fd741d404
--- /dev/null
+++ b/packages/browser-bundler/src/get-browser-composition.tsx
@@ -0,0 +1,206 @@
+import React, {Suspense, useEffect} from 'react';
+import type {Root} from 'react-dom/client';
+import {createRoot} from 'react-dom/client';
+import type {AnyComposition, VideoConfig} from 'remotion';
+import {Internals} from 'remotion';
+
+export type BrowserComposition = VideoConfig & {
+ component: AnyComposition['component'];
+};
+
+class RegistrationErrorBoundary extends React.Component<
+ {
+ readonly children: React.ReactNode;
+ readonly onError: (error: unknown) => void;
+ },
+ {failed: boolean}
+> {
+ state = {failed: false};
+
+ static getDerivedStateFromError() {
+ return {failed: true};
+ }
+
+ componentDidCatch(error: Error) {
+ this.props.onError(error);
+ }
+
+ render() {
+ return this.state.failed ? null : this.props.children;
+ }
+}
+
+const RegistrationComplete: React.FC<{
+ readonly onComplete: () => void;
+}> = ({onComplete}) => {
+ useEffect(onComplete, [onComplete]);
+ return null;
+};
+
+/**
+ * Mounts a registered Root to select a Composition and resolve its metadata.
+ * Input props override default props. Root providers are used for registration
+ * only; they are not included around the component returned for the Player.
+ * Pass an AbortSignal to cancel pending lazy roots or calculateMetadata().
+ */
+export const getBrowserComposition = async ({
+ root: RegisteredRoot,
+ compositionId,
+ inputProps,
+ signal,
+}: {
+ root: React.FC;
+ compositionId: string;
+ inputProps: Record<string, unknown>;
+ signal?: AbortSignal;
+}): Promise<BrowserComposition> => {
+ if (signal?.aborted) {
+ throw signal.reason;
+ }
+
+ if (typeof document === 'undefined' || !document.body) {
+ throw new Error('getBrowserComposition() must be called in a browser.');
+ }
+
+ const container = document.createElement('div');
+ container.hidden = true;
+ document.body.appendChild(container);
+
+ const controller = new AbortController();
+ const abort = () => controller.abort(signal?.reason);
+ signal?.addEventListener('abort', abort, {once: true});
+
+ const compositions = new Map<string, AnyComposition>();
+ let reactRoot: Root | null = null;
+ let finished = false;
+ let resolving = false;
+
+ try {
+ return await new Promise<BrowserComposition>((resolve, reject) => {
+ const onError = (error: unknown) => {
+ if (finished) {
+ return;
+ }
+
+ finished = true;
+ reject(error instanceof Error ? error : new Error(String(error)));
+ };
+
+ controller.signal.addEventListener(
+ 'abort',
+ () => {
+ if (finished) {
+ return;
+ }
+
+ finished = true;
+ reject(controller.signal.reason);
+ },
+ {once: true},
+ );
+
+ const onComplete = () => {
+ // Wait until all passive effects (including Strict Mode remounts
+ // and registration errors) have finished before taking the snapshot.
+ queueMicrotask(() => {
+ if (finished || resolving) {
+ return;
+ }
+
+ resolving = true;
+ try {
+ const composition = compositions.get(compositionId);
+ if (!composition) {
+ throw new Error(
+ `No composition with ID "${compositionId}" was registered. Available IDs: ${
+ [...compositions.keys()].join(', ') || '(none)'
+ }.`,
+ );
+ }
+
+ const defaultProps = composition.defaultProps ?? {};
+ const config = Internals.resolveVideoConfig({
+ compositionId,
+ compositionWidth: composition.width ?? null,
+ compositionHeight: composition.height ?? null,
+ compositionFps: composition.fps ?? null,
+ compositionDurationInFrames: composition.durationInFrames ?? null,
+ calculateMetadata: composition.calculateMetadata,
+ defaultProps,
+ inputProps: {...defaultProps, ...inputProps},
+ signal: controller.signal,
+ });
+
+ Promise.resolve(config).then((videoConfig) => {
+ if (finished) {
+ return;
+ }
+
+ finished = true;
+ resolve({...videoConfig, component: composition.component});
+ }, onError);
+ } catch (error) {
+ onError(error);
+ }
+ });
+ };
+
+ const setters: React.ContextType<typeof Internals.CompositionSetters> = {
+ registerComposition: (composition) => {
+ if (compositions.has(composition.id)) {
+ throw new Error(
+ `A composition with ID "${composition.id}" was registered more than once.`,
+ );
+ }
+
+ compositions.set(composition.id, composition as AnyComposition);
+ },
+ unregisterComposition: (id) => {
+ compositions.delete(id);
+ },
+ registerFolder: () => undefined,
+ unregisterFolder: () => undefined,
+ setCanvasContent: () => undefined,
+ setCurrentAssetMetadata: () => undefined,
+ onlyRenderComposition: null,
+ };
+
+ reactRoot = createRoot(container, {
+ onCaughtError: onError,
+ onUncaughtError: onError,
+ });
+ reactRoot.render(
+ <RegistrationErrorBoundary onError={onError}>
+ <Internals.RemotionEnvironmentContext.Provider
+ value={{
+ isClientSideRendering: false,
+ isPlayer: false,
+ isReadOnlyStudio: false,
+ isRendering: false,
+ isStudio: false,
+ }}
+ >
+ <Internals.CompositionSetters.Provider value={setters}>
+ <Suspense fallback={null}>
+ <RegisteredRoot />
+ <RegistrationComplete onComplete={onComplete} />
+ </Suspense>
+ </Internals.CompositionSetters.Provider>
+ </Internals.RemotionEnvironmentContext.Provider>
+ </RegistrationErrorBoundary>,
+ );
+ });
+ } finally {
+ finished = true;
+ signal?.removeEventListener('abort', abort);
+ controller.abort();
+ try {
+ // Promise continuations run outside React's commit, so unmounting
+ // here also works when registration finishes in an effect.
+ (reactRoot as Root | null)?.unmount();
+ } finally {
+ compositions.clear();
+ container.remove();
+ }
+ }
+};
diff --git a/packages/browser-studio/src/browser-studio-http-client.ts b/packages/browser-bundler/src/http-client.ts
similarity index 87%
rename from packages/browser-studio/src/browser-studio-http-client.ts
rename to packages/browser-bundler/src/http-client.ts
index 94e1b5a502..eecfdc1f40 100644
--- a/packages/browser-studio/src/browser-studio-http-client.ts
+++ b/packages/browser-bundler/src/http-client.ts
@@ -1,10 +1,10 @@
-type BrowserStudioHttpResponse = {
+type BrowserHttpResponse = {
body: Buffer;
headers: Record<string, string>;
status: number;
};
-export const makeBrowserStudioHttpClient = ({
+export const makeBrowserHttpClient = ({
fetchImplementation,
}: {
fetchImplementation: (
@@ -12,7 +12,7 @@ export const makeBrowserStudioHttpClient = ({
init?: RequestInit,
) => Promise<Response>;
}) => {
- const responseCache = new Map<string, Promise<BrowserStudioHttpResponse>>();
+ const responseCache = new Map<string, Promise<BrowserHttpResponse>>();
return (url: string, headers: Record<string, string>) => {
const cacheKey = JSON.stringify([
diff --git a/packages/browser-bundler/src/index.ts b/packages/browser-bundler/src/index.ts
new file mode 100644
index 0000000000..1cb8ff05c2
--- /dev/null
+++ b/packages/browser-bundler/src/index.ts
@@ -0,0 +1,10 @@
+export {createBrowserBundler} from './create-browser-bundler';
+export {BrowserBundlerError} from './errors';
+export type {
+ BrowserBundle,
+ BrowserBundler,
+ BrowserBundlerOptions,
+ BrowserBundlerProgress,
+ VirtualFileSystem,
+ VirtualProject,
+} from './types';
diff --git a/packages/browser-bundler/src/load-browser-bundle.ts b/packages/browser-bundler/src/load-browser-bundle.ts
new file mode 100644
index 0000000000..94bbe60823
--- /dev/null
+++ b/packages/browser-bundler/src/load-browser-bundle.ts
@@ -0,0 +1,81 @@
+import * as React from 'react';
+import * as ReactDOM from 'react-dom';
+import * as ReactDOMClient from 'react-dom/client';
+import * as JSXDevRuntime from 'react/jsx-dev-runtime';
+import * as JSXRuntime from 'react/jsx-runtime';
+import * as Remotion from 'remotion';
+import * as RemotionNoReact from 'remotion/no-react';
+import * as RemotionVersion from 'remotion/version';
+import type {BrowserBundle} from './types.js';
+
+/**
+ * Executes a browser bundle and returns its registerRoot() component.
+ * Only execute code you trust: this uses Function(), not a sandbox, and the
+ * bundle has access to the page. React and Remotion are shared with the host.
+ */
+export const loadBrowserBundle = ({
+ bundle,
+}: {
+ bundle: BrowserBundle;
+}): React.FC => {
+ let root: React.FC | null = null;
+ const registerRoot = (component: React.FC) => {
+ if (
+ !component ||
+ React.isValidElement(component) ||
+ (typeof component !== 'function' &&
+ (typeof component !== 'object' || !('$$typeof' in component)))
+ ) {
+ throw new Error('registerRoot() must receive a React component.');
+ }
+
+ if (root !== null) {
+ throw new Error('registerRoot() was called more than once.');
+ }
+
+ root = component;
+ };
+
+ const sharedModules = new Map<string, unknown>([
+ ['react', React],
+ ['react-dom', ReactDOM],
+ ['react-dom/client', ReactDOMClient],
+ ['react/jsx-runtime', JSXRuntime],
+ ['react/jsx-dev-runtime', JSXDevRuntime],
+ ['remotion', {...Remotion, registerRoot}],
+ ['remotion/no-react', RemotionNoReact],
+ ['remotion/version', RemotionVersion],
+ ]);
+
+ try {
+ // eslint-disable-next-line no-new-func
+ const evaluate = new Function(
+ 'require',
+ `${bundle.code}\n//# sourceURL=remotion-browser-bundle.js`,
+ );
+ evaluate((id: string) => {
+ if (!sharedModules.has(id)) {
+ throw new Error(
+ `The browser bundle requested an unavailable shared module: "${id}".`,
+ );
+ }
+
+ return sharedModules.get(id);
+ });
+ } catch (error) {
+ throw new Error(
+ `Could not evaluate the browser bundle: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ {cause: error},
+ );
+ }
+
+ if (root === null) {
+ throw new Error(
+ 'The browser bundle did not call registerRoot(). Use a normal Remotion project entry point.',
+ );
+ }
+
+ return root;
+};
diff --git a/packages/browser-bundler/src/load-rspack.ts b/packages/browser-bundler/src/load-rspack.ts
new file mode 100644
index 0000000000..9c07c75bff
--- /dev/null
+++ b/packages/browser-bundler/src/load-rspack.ts
@@ -0,0 +1,100 @@
+import type * as RspackBrowser from '@rspack/browser';
+import type {BrowserBundlerProgress} from './types';
+
+let rspackBrowserPromise: Promise<typeof RspackBrowser> | null = null;
+
+export const loadRspackBrowser = (
+ onProgress: ((progress: BrowserBundlerProgress) => void) | null,
+) => {
+ const workerGlobal = globalThis as Record<string, unknown>;
+ workerGlobal.window ??= globalThis;
+ if (rspackBrowserPromise) {
+ return rspackBrowserPromise;
+ }
+
+ const originalFetch = globalThis.fetch.bind(globalThis);
+ workerGlobal.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
+ const response = await originalFetch(input, init);
+ const inputUrl =
+ typeof input === 'string'
+ ? input
+ : input instanceof URL
+ ? input.href
+ : input.url;
+ if (!inputUrl.split(/[?#]/)[0].endsWith('.wasm')) {
+ return response;
+ }
+
+ if (!response.ok) {
+ throw new Error(`Failed to load Rspack WASM: ${response.status}`);
+ }
+
+ const contentLength = Number(response.headers.get('content-length'));
+ const totalBytes =
+ Number.isFinite(contentLength) && contentLength > 0
+ ? contentLength
+ : null;
+ onProgress?.({
+ asset: 'rspack-wasm',
+ loadedBytes: 0,
+ totalBytes,
+ });
+ if (!response.body) {
+ onProgress?.({
+ asset: 'rspack-wasm',
+ loadedBytes: totalBytes ?? 0,
+ totalBytes,
+ });
+ return response;
+ }
+
+ const reader = response.body.getReader();
+ let loadedBytes = 0;
+ let lastProgressUpdate = 0;
+ const body = new ReadableStream<Uint8Array>({
+ async pull(controller) {
+ try {
+ const result = await reader.read();
+ if (result.done) {
+ onProgress?.({
+ asset: 'rspack-wasm',
+ loadedBytes,
+ totalBytes: totalBytes ?? loadedBytes,
+ });
+ controller.close();
+ return;
+ }
+
+ loadedBytes += result.value.byteLength;
+ const now = performance.now();
+ if (now - lastProgressUpdate >= 50) {
+ lastProgressUpdate = now;
+ onProgress?.({
+ asset: 'rspack-wasm',
+ loadedBytes,
+ totalBytes,
+ });
+ }
+
+ controller.enqueue(result.value);
+ } catch (error) {
+ controller.error(error);
+ }
+ },
+ cancel(reason) {
+ return reader.cancel(reason);
+ },
+ });
+
+ return new Response(body, {
+ headers: response.headers,
+ status: response.status,
+ statusText: response.statusText,
+ });
+ };
+
+ rspackBrowserPromise = import('@rspack/browser').finally(() => {
+ workerGlobal.fetch = originalFetch;
+ });
+ return rspackBrowserPromise;
+};
diff --git a/packages/browser-bundler/src/runtime.ts b/packages/browser-bundler/src/runtime.ts
new file mode 100644
index 0000000000..44b159bbe8
--- /dev/null
+++ b/packages/browser-bundler/src/runtime.ts
@@ -0,0 +1,3 @@
+export {getBrowserComposition} from './get-browser-composition.js';
+export type {BrowserComposition} from './get-browser-composition.js';
+export {loadBrowserBundle} from './load-browser-bundle.js';
diff --git a/packages/browser-studio/src/test/browser-studio-http-client.test.ts b/packages/browser-bundler/src/test/http-client.test.ts
similarity index 82%
rename from packages/browser-studio/src/test/browser-studio-http-client.test.ts
rename to packages/browser-bundler/src/test/http-client.test.ts
index c5679a4698..877e4bbe60 100644
--- a/packages/browser-studio/src/test/browser-studio-http-client.test.ts
+++ b/packages/browser-bundler/src/test/http-client.test.ts
@@ -1,9 +1,9 @@
import {expect, test} from 'bun:test';
-import {makeBrowserStudioHttpClient} from '../browser-studio-http-client';
+import {makeBrowserHttpClient} from '../http-client';
test('coalesces concurrent requests with equivalent headers', async () => {
let requests = 0;
- const httpClient = makeBrowserStudioHttpClient({
+ const httpClient = makeBrowserHttpClient({
fetchImplementation: async () => {
requests++;
await Promise.resolve();
@@ -25,7 +25,10 @@ test('coalesces concurrent requests with equivalent headers', async () => {
expect(first).toBe(second);
const response = await second;
- expect({...response, body: new TextDecoder().decode(response.body)}).toEqual({
+ expect({
+ ...response,
+ body: new TextDecoder().decode(response.body),
+ }).toMatchObject({
body: 'module',
headers: {'x-test': 'value'},
status: 200,
@@ -35,7 +38,7 @@ test('coalesces concurrent requests with equivalent headers', async () => {
test('allows a failed request to be retried', async () => {
let requests = 0;
- const httpClient = makeBrowserStudioHttpClient({
+ const httpClient = makeBrowserHttpClient({
fetchImplementation: () => {
requests++;
if (requests === 1) {
diff --git a/packages/browser-bundler/src/test/runtime-dom.ts b/packages/browser-bundler/src/test/runtime-dom.ts
new file mode 100644
index 0000000000..cb117e7957
--- /dev/null
+++ b/packages/browser-bundler/src/test/runtime-dom.ts
@@ -0,0 +1,5 @@
+import {GlobalRegistrator} from '@happy-dom/global-registrator';
+
+if (typeof document === 'undefined') {
+ GlobalRegistrator.register({url: 'http://localhost:3000'});
+}
diff --git a/packages/browser-bundler/src/test/runtime.test.tsx b/packages/browser-bundler/src/test/runtime.test.tsx
new file mode 100644
index 0000000000..df6399b3e7
--- /dev/null
+++ b/packages/browser-bundler/src/test/runtime.test.tsx
@@ -0,0 +1,367 @@
+// organize-imports-ignore
+// React DOM and Testing Library inspect the DOM when they are imported.
+import './runtime-dom.js';
+import {afterEach, expect, test} from 'bun:test';
+import {Player, type PlayerRef} from '@remotion/player';
+import {act, cleanup, render, screen} from '@testing-library/react';
+import React, {createRef, useEffect} from 'react';
+import {Composition, Internals} from 'remotion';
+import {
+ getBrowserComposition,
+ loadBrowserBundle,
+ type BrowserComposition,
+} from '../runtime.js';
+
+afterEach(() => {
+ cleanup();
+});
+
+const bundle = {
+ warnings: [],
+ code: `
+const React = require('react');
+const {jsx, jsxs} = require('react/jsx-runtime');
+const {Composition, Folder, registerRoot, useCurrentFrame, useVideoConfig} = require('remotion');
+require('react-dom');
+require('react-dom/client');
+require('react/jsx-dev-runtime');
+require('remotion/no-react');
+require('remotion/version');
+
+const Video = ({title, suffix}) => {
+ const frame = useCurrentFrame();
+ const {width, height, durationInFrames} = useVideoConfig();
+ return jsx('p', {children: title + ' / ' + suffix + ' / frame ' + frame + ' / ' + width + 'x' + height + ' / ' + durationInFrames});
+};
+const Root = () => {
+ const [enabled] = React.useState(true);
+ return jsx(React.StrictMode, {children: jsx(Folder, {
+ name: 'Nested',
+ children: jsxs(React.Fragment, {children: [
+ jsx(Composition, {
+ id: 'Other', component: () => null,
+ width: 320, height: 180, fps: 30, durationInFrames: 90,
+ }),
+ enabled ? jsx(Composition, {
+ id: 'BrowserDemo',
+ lazyComponent: () => Promise.resolve({default: Video}),
+ width: 320, height: 180, fps: 30, durationInFrames: 90,
+ defaultProps: {title: 'Default', suffix: 'from defaults'},
+ calculateMetadata: async ({props}) => ({
+ width: 960, height: 540, fps: 24, durationInFrames: 48,
+ props: {...props, title: props.title + '!'},
+ }),
+ }) : null,
+ ]}),
+ })});
+};
+registerRoot(React.lazy(() => Promise.resolve({default: Root})));
+`,
+};
+
+test('isolated registerRoot bundles resolve real compositions and play their calculated props and frames', async () => {
+ const hostRoot = Internals.getRoot();
+ const hostCompositions = Internals.compositionsRef.current;
+ const seenIds = window.remotion_seenCompositionIds;
+ const roots = [loadBrowserBundle({bundle}), loadBrowserBundle({bundle})];
+ expect(roots[0]).not.toBe(roots[1]);
+ expect(Internals.getRoot()).toBe(hostRoot);
+ expect(window.remotion_seenCompositionIds).toBe(seenIds);
+
+ render(<p>Host application</p>);
+ const hostContainers = document.body.childElementCount;
+ let pending: Promise<BrowserComposition>[] = [];
+ await act(async () => {
+ pending = roots.map((root, index) =>
+ getBrowserComposition({
+ root,
+ compositionId: 'BrowserDemo',
+ inputProps: {title: index === 0 ? 'First' : 'Recompiled'},
+ }),
+ );
+ await Promise.resolve();
+ });
+ const [first, second] = await Promise.all(pending);
+
+ expect(first.defaultProps).toEqual({
+ title: 'Default',
+ suffix: 'from defaults',
+ });
+ expect(first.props).toEqual({
+ title: 'First!',
+ suffix: 'from defaults',
+ });
+ expect(first.fps).toBe(24);
+ expect(Internals.getRoot()).toBe(hostRoot);
+ expect(Internals.compositionsRef.current).toBe(hostCompositions);
+ expect(document.body.childElementCount).toBe(hostContainers);
+ expect(screen.getByText('Host application')).toBeTruthy();
+
+ const playerRef = createRef<PlayerRef>();
+ const player = render(
+ <Player
+ ref={playerRef}
+ component={first.component}
+ inputProps={first.props}
+ compositionWidth={first.width}
+ compositionHeight={first.height}
+ durationInFrames={first.durationInFrames}
+ fps={first.fps}
+ initialFrame={7}
+ numberOfSharedAudioTags={0}
+ acknowledgeRemotionLicense
+ />,
+ );
+ await screen.findByText('First! / from defaults / frame 7 / 960x540 / 48');
+ act(() => {
+ playerRef.current?.seekTo(12);
+ });
+ await screen.findByText('First! / from defaults / frame 12 / 960x540 / 48');
+
+ player.rerender(
+ <Player
+ key="recompiled"
+ component={second.component}
+ inputProps={second.props}
+ compositionWidth={second.width}
+ compositionHeight={second.height}
+ durationInFrames={second.durationInFrames}
+ fps={second.fps}
+ initialFrame={3}
+ numberOfSharedAudioTags={0}
+ acknowledgeRemotionLicense
+ />,
+ );
+ await screen.findByText(
+ 'Recompiled! / from defaults / frame 3 / 960x540 / 48',
+ );
+});
+
+test.each([
+ {
+ name: 'missing registration',
+ code: 'const Component = () => null;',
+ error: 'did not call registerRoot()',
+ },
+ {
+ name: 'duplicate registration',
+ code: `const {registerRoot} = require('remotion');
+registerRoot(() => null);
+registerRoot(() => null);`,
+ error: 'called more than once',
+ },
+ {
+ name: 'an unavailable shared module',
+ code: "require('unknown-shared-module');",
+ error: 'unavailable shared module: "unknown-shared-module"',
+ },
+ {
+ name: 'an invalid root',
+ code: "require('remotion').registerRoot(null);",
+ error: 'must receive a React component',
+ },
+ {
+ name: 'a runtime error',
+ code: "throw new Error('entry failed');",
+ error: 'Could not evaluate the browser bundle: entry failed',
+ },
+ {
+ name: 'invalid JavaScript',
+ code: 'const = ;',
+ error: 'Could not evaluate the browser bundle:',
+ },
+])('rejects $name without registering a global root', ({code, error}) => {
+ const hostRoot = Internals.getRoot();
+ expect(() => loadBrowserBundle({bundle: {code, warnings: []}})).toThrow(
+ error,
+ );
+ expect(Internals.getRoot()).toBe(hostRoot);
+});
+
+const compositionProps = {
+ id: 'Demo',
+ component: () => null,
+ width: 320,
+ height: 180,
+ fps: 30,
+ durationInFrames: 90,
+};
+
+const EffectErrorRoot = () => {
+ useEffect(() => {
+ throw new Error('Root effect failed');
+ }, []);
+ return <Composition {...compositionProps} />;
+};
+
+test.each([
+ {
+ name: 'missing composition IDs',
+ root: () => <Composition {...compositionProps} id="Other" />,
+ error: 'No composition with ID "Demo" was registered. Available IDs: Other',
+ },
+ {
+ name: 'duplicate composition IDs',
+ root: () => (
+ <>
+ <Composition {...compositionProps} />
+ <Composition {...compositionProps} />
+ </>
+ ),
+ error: 'ID "Demo" was registered more than once',
+ },
+ {
+ name: 'registration validation failures',
+ root: () => <Composition {...compositionProps} id="not/valid" />,
+ error: 'Composition id can only contain',
+ },
+ {
+ name: 'Root render errors',
+ root: () => {
+ throw new Error('Root render failed');
+ },
+ error: 'Root render failed',
+ },
+ {
+ name: 'Root effect errors',
+ root: EffectErrorRoot,
+ error: 'Root effect failed',
+ },
+ {
+ name: 'rejected lazy roots',
+ root: React.lazy(() => Promise.reject(new Error('Lazy Root failed'))),
+ error: 'Lazy Root failed',
+ },
+ {
+ name: 'invalid calculated metadata',
+ root: () => (
+ <Composition {...compositionProps} calculateMetadata={() => ({fps: 0})} />
+ ),
+ error: 'fps',
+ },
+ {
+ name: 'rejected calculateMetadata',
+ root: () => (
+ <Composition
+ {...compositionProps}
+ calculateMetadata={() => Promise.reject(new Error('Metadata failed'))}
+ />
+ ),
+ error: 'Metadata failed',
+ },
+])('rejects $name and removes its React root', async ({root, error}) => {
+ const hostContainers = document.body.childElementCount;
+ let result: Promise<unknown> = Promise.resolve();
+ await act(async () => {
+ result = getBrowserComposition({
+ root,
+ compositionId: 'Demo',
+ inputProps: {},
+ }).catch((reason: unknown) => reason);
+ await Promise.resolve();
+ });
+ const caught = await result;
+ expect(caught).toBeInstanceOf(Error);
+ expect((caught as Error).message).toContain(error);
+ expect(document.body.childElementCount).toBe(hostContainers);
+});
+
+test('aborting suspended roots and pending metadata cleans up and permits another selection', async () => {
+ const hostContainers = document.body.childElementCount;
+ const alreadyAborted = new AbortController();
+ alreadyAborted.abort();
+ await expect(
+ getBrowserComposition({
+ root: () => null,
+ compositionId: 'Demo',
+ inputProps: {},
+ signal: alreadyAborted.signal,
+ }),
+ ).rejects.toMatchObject({name: 'AbortError'});
+
+ const lazyController = new AbortController();
+ let lazyResult: Promise<unknown> = Promise.resolve();
+ await act(async () => {
+ lazyResult = getBrowserComposition({
+ root: React.lazy(() => new Promise(() => undefined)),
+ compositionId: 'Demo',
+ inputProps: {},
+ signal: lazyController.signal,
+ }).catch((error: unknown) => error);
+ await Promise.resolve();
+ });
+ await act(async () => {
+ lazyController.abort();
+ await lazyResult;
+ });
+ expect(await lazyResult).toMatchObject({name: 'AbortError'});
+ expect(document.body.childElementCount).toBe(hostContainers);
+
+ let unmounts = 0;
+ let metadataSignal: AbortSignal | null = null;
+ let finishMetadata: () => void = () => undefined;
+ const metadataGate = new Promise<void>((resolve) => {
+ finishMetadata = resolve;
+ });
+ const MetadataRoot = () => {
+ useEffect(
+ () => () => {
+ unmounts++;
+ },
+ [],
+ );
+
+ return (
+ <Composition
+ {...compositionProps}
+ calculateMetadata={async ({abortSignal}) => {
+ metadataSignal = abortSignal;
+ await metadataGate;
+ return {width: 640};
+ }}
+ />
+ );
+ };
+
+ const metadataController = new AbortController();
+ let metadataResult: Promise<unknown> = Promise.resolve();
+
+ await act(async () => {
+ metadataResult = getBrowserComposition({
+ root: MetadataRoot,
+ compositionId: 'Demo',
+ inputProps: {},
+ signal: metadataController.signal,
+ }).catch((error: unknown) => error);
+ await Promise.resolve();
+ });
+ expect(metadataSignal).not.toBeNull();
+ await act(async () => {
+ metadataController.abort();
+ await metadataResult;
+ });
+ expect(await metadataResult).toMatchObject({name: 'AbortError'});
+ expect((metadataSignal as AbortSignal | null)?.aborted).toBe(true);
+ expect(unmounts).toBe(1);
+ expect(document.body.childElementCount).toBe(hostContainers);
+
+ await act(async () => {
+ finishMetadata();
+ await metadataGate;
+ });
+ let recovery: Promise<BrowserComposition> | null = null;
+ await act(async () => {
+ recovery = getBrowserComposition({
+ root: () => <Composition {...compositionProps} />,
+ compositionId: 'Demo',
+ inputProps: {title: 'Recovered'},
+ });
+ await Promise.resolve();
+ });
+ expect(await recovery).toMatchObject({
+ id: 'Demo',
+ width: 320,
+ props: {title: 'Recovered'},
+ });
+ expect(document.body.childElementCount).toBe(hostContainers);
+});
diff --git a/packages/browser-bundler/src/test/virtual-project.test.ts b/packages/browser-bundler/src/test/virtual-project.test.ts
new file mode 100644
index 0000000000..22319321f8
--- /dev/null
+++ b/packages/browser-bundler/src/test/virtual-project.test.ts
@@ -0,0 +1,35 @@
+import {expect, test} from 'bun:test';
+import {
+ getVirtualProjectChanges,
+ getVirtualProjectFiles,
+} from '../virtual-project';
+
+test('source snapshots distinguish added, edited, removed and unchanged virtual files', () => {
+ const project = {
+ rootDir: '/project',
+ entryPoint: '/project/index.ts',
+ files: {
+ 'project/index.ts': "import './Video';",
+ '/project/Video.tsx': 'export const Video = () => null;',
+ '/project/removed.ts': 'export const unused = true;',
+ },
+ };
+ const previous = getVirtualProjectFiles(project);
+ const next = getVirtualProjectFiles({
+ ...project,
+ files: {
+ '/project/index.ts': "import './Video';",
+ 'project/Video.tsx': 'export const Video = () => <div />;',
+ '/project/added.ts': 'export const title = "New";',
+ },
+ });
+ expect(getVirtualProjectChanges({previous, next})).toEqual({
+ modified: ['/project/Video.tsx', '/project/added.ts'],
+ removed: ['/project/removed.ts'],
+ });
+ expect(getVirtualProjectChanges({previous: next, next})).toEqual({
+ modified: [],
+ removed: [],
+ });
+ expect(project.files['project/index.ts']).toBe("import './Video';");
+});
diff --git a/packages/browser-bundler/src/types.ts b/packages/browser-bundler/src/types.ts
new file mode 100644
index 0000000000..0b337fcbdf
--- /dev/null
+++ b/packages/browser-bundler/src/types.ts
@@ -0,0 +1,59 @@
+export type VirtualProject = {
+ rootDir: string;
+ entryPoint: string;
+ files: Record<string, string>;
+};
+
+export type VirtualFileSystem = {
+ readFile: (path: string) => Promise<string> | string;
+ writeFile: (path: string, contents: string) => Promise<void> | void;
+ exists: (path: string) => Promise<boolean> | boolean;
+ listFiles: () => Promise<string[]> | string[];
+};
+
+export type BrowserBundle = {
+ code: string;
+ warnings: string[];
+};
+
+export type BrowserBundlerProgress = {
+ asset: 'rspack-wasm';
+ loadedBytes: number;
+ totalBytes: number | null;
+};
+
+export type BrowserBundlerOptions = {
+ dependencyVersions?: Record<string, string>;
+ onProgress?: (progress: BrowserBundlerProgress) => void;
+ workerUrl?: string | URL;
+};
+
+export type BrowserBundler = {
+ bundle: (options: {project: VirtualProject}) => Promise<BrowserBundle>;
+ dispose: () => void;
+};
+
+export type BrowserBundlerWorkerRequest = {
+ id: number;
+ project: VirtualProject;
+ dependencyVersions: Record<string, string>;
+};
+
+export type SerializedCompilerError = {
+ message: string;
+ stack: string | null;
+ diagnostics: string[];
+};
+
+export type BrowserBundlerWorkerResponse =
+ | {
+ type: 'bundle';
+ id: number;
+ bundle: BrowserBundle;
+ }
+ | {
+ type: 'error';
+ id: number;
+ error: SerializedCompilerError;
+ }
+ | ({type: 'progress'} & BrowserBundlerProgress);
diff --git a/packages/browser-bundler/src/virtual-project.ts b/packages/browser-bundler/src/virtual-project.ts
new file mode 100644
index 0000000000..8614090b35
--- /dev/null
+++ b/packages/browser-bundler/src/virtual-project.ts
@@ -0,0 +1,23 @@
+import type {VirtualProject} from './types';
+
+export const normalizeVirtualPath = (path: string) =>
+ path.startsWith('/') ? path : `/${path}`;
+
+export const getVirtualProjectFiles = (project: VirtualProject) =>
+ Object.fromEntries(
+ Object.entries(project.files).map(([path, contents]) => [
+ normalizeVirtualPath(path),
+ contents,
+ ]),
+ );
+
+export const getVirtualProjectChanges = ({
+ previous,
+ next,
+}: {
+ previous: Record<string, string>;
+ next: Record<string, string>;
+}) => ({
+ modified: Object.keys(next).filter((path) => previous[path] !== next[path]),
+ removed: Object.keys(previous).filter((path) => !Object.hasOwn(next, path)),
+});
diff --git a/packages/browser-bundler/tsconfig.json b/packages/browser-bundler/tsconfig.json
new file mode 100644
index 0000000000..00f904424c
--- /dev/null
+++ b/packages/browser-bundler/tsconfig.json
@@ -0,0 +1,16 @@
+{
+ "extends": "../tsconfig.settings.json",
+ "compilerOptions": {
+ "rootDir": "src",
+ "outDir": "dist",
+ "jsx": "react-jsx",
+ "skipLibCheck": true,
+ "target": "ES2022",
+ "module": "es2020",
+ "moduleResolution": "bundler",
+ "declaration": true,
+ "emitDeclarationOnly": true
+ },
+ "include": ["src"],
+ "references": [{"path": "../core"}, {"path": "../player"}]
+}
diff --git a/packages/browser-studio/package.json b/packages/browser-studio/package.json
index e381feb930..9d72ebc0ff 100644
--- a/packages/browser-studio/package.json
+++ b/packages/browser-studio/package.json
@@ -27,6 +27,7 @@
"url": "https://github.com/remotion-dev/remotion/issues"
},
"dependencies": {
+ "@remotion/browser-bundler": "workspace:*",
"@remotion/studio-codemods": "workspace:*",
"@remotion/studio-protocol": "workspace:*",
"@remotion/studio-shared": "workspace:*",
diff --git a/packages/browser-studio/src/browser-studio-worker.ts b/packages/browser-studio/src/browser-studio-worker.ts
index 58290a10c5..fba7daa031 100644
--- a/packages/browser-studio/src/browser-studio-worker.ts
+++ b/packages/browser-studio/src/browser-studio-worker.ts
@@ -1,14 +1,22 @@
+import {
+ createBrowserCompiler,
+ createBrowserDependencyPlugin,
+ getVirtualProjectChanges,
+ getVirtualProjectFiles,
+ makeBrowserHttpClient,
+ normalizeVirtualPath,
+ type BrowserCompiler,
+ type BrowserCompilerResult,
+} from '@remotion/browser-bundler/compiler';
import type {HotMiddlewareMessage} from '@remotion/studio-shared';
import {getStudioEntryPoints} from '@remotion/studio-shared/studio-entry-points';
import type * as RspackBrowser from '@rspack/browser';
-import {makeBrowserStudioHttpClient} from './browser-studio-http-client';
import {BROWSER_STUDIO_TRANSFORMERS_PACKAGE} from './browser-studio-import-map';
import {browserStudioDependencyVersions} from './dependency-versions';
import {studioRenderEntryExternal} from './dev/studio-render-entry-external';
import type {
BrowserStudioDependencyResolution,
BrowserStudioError,
- BrowserStudioHmrAsset,
BrowserStudioWorkerCompileRequest,
BrowserStudioWorkerCompileResponse,
VirtualProject,
@@ -22,126 +30,22 @@ import {
resolveBrowserStudioRemotionPackage,
} from './workspace-package-exports';
-type BuiltinMemFs = typeof RspackBrowser.builtinMemFs;
-type Compiler = RspackBrowser.Compiler;
-
type CompilerSession = {
- builtinMemFs: BuiltinMemFs;
- compiler: Compiler;
+ compiler: BrowserCompiler;
initialCompiled: boolean;
- modifiedFiles: ReadonlySet<string> | undefined;
project: VirtualProject;
queuedProject: VirtualProject | null;
- removedFiles: ReadonlySet<string> | undefined;
resolvedUrls: Record<string, string>;
resolvedVersions: Record<string, string>;
running: boolean;
};
-let rspackBrowserPromise: Promise<typeof RspackBrowser> | null = null;
let compilerSession: CompilerSession | null = null;
const postResponse = (response: BrowserStudioWorkerCompileResponse) => {
self.postMessage(response);
};
-const loadRspackBrowser = () => {
- const workerGlobal = globalThis as Record<string, unknown>;
- workerGlobal.window ??= globalThis;
- if (!rspackBrowserPromise) {
- const originalFetch = globalThis.fetch.bind(globalThis);
- workerGlobal.fetch = async (
- input: RequestInfo | URL,
- init?: RequestInit,
- ) => {
- const response = await originalFetch(input, init);
- const inputUrl =
- typeof input === 'string'
- ? input
- : input instanceof URL
- ? input.href
- : input.url;
- // Asset filenames may be hashed by the consumer's bundler.
- if (!inputUrl.split(/[?#]/)[0].endsWith('.wasm')) {
- return response;
- }
-
- const contentLength = Number(response.headers.get('content-length'));
- const totalBytes =
- Number.isFinite(contentLength) && contentLength > 0
- ? contentLength
- : null;
- postResponse({
- asset: 'rspack-wasm',
- loadedBytes: 0,
- totalBytes,
- type: 'load-progress',
- });
- if (!response.body) {
- postResponse({
- asset: 'rspack-wasm',
- loadedBytes: totalBytes ?? 0,
- totalBytes,
- type: 'load-progress',
- });
- return response;
- }
-
- const reader = response.body.getReader();
- let loadedBytes = 0;
- let lastProgressUpdate = 0;
- const body = new ReadableStream<Uint8Array>({
- async pull(controller) {
- try {
- const result = await reader.read();
- if (result.done) {
- postResponse({
- asset: 'rspack-wasm',
- loadedBytes,
- totalBytes: totalBytes ?? loadedBytes,
- type: 'load-progress',
- });
- controller.close();
- return;
- }
-
- loadedBytes += result.value.byteLength;
- const now = performance.now();
- if (now - lastProgressUpdate >= 50) {
- lastProgressUpdate = now;
- postResponse({
- asset: 'rspack-wasm',
- loadedBytes,
- totalBytes,
- type: 'load-progress',
- });
- }
-
- controller.enqueue(result.value);
- } catch (error) {
- controller.error(error);
- }
- },
- cancel(reason) {
- return reader.cancel(reason);
- },
- });
-
- return new Response(body, {
- headers: response.headers,
- status: response.status,
- statusText: response.statusText,
- });
- };
-
- rspackBrowserPromise = import('@rspack/browser').finally(() => {
- workerGlobal.fetch = originalFetch;
- });
- }
-
- return rspackBrowserPromise;
-};
-
const browserStudioVendorExternals = {
react: 'globalThis.remotion_browserStudioVendor.react',
'react-dom': 'globalThis.remotion_browserStudioVendor.reactDom',
@@ -158,9 +62,6 @@ const browserStudioVendorExternals = {
'remotion/version': 'globalThis.remotion_browserStudioVendor.remotionVersion',
};
-const normalizePath = (path: string) =>
- path.startsWith('/') ? path : `/${path}`;
-
const makeBrowserStudioError = (
error: unknown,
diagnostics?: string[],
@@ -176,23 +77,6 @@ const makeBrowserStudioError = (
return {diagnostics, message: String(error)};
};
-const problemToString = (problem: unknown): string => {
- if (typeof problem === 'string') {
- return problem;
- }
-
- if (
- typeof problem === 'object' &&
- problem !== null &&
- 'message' in problem &&
- typeof problem.message === 'string'
- ) {
- return problem.message;
- }
-
- return String(problem);
-};
-
const applyDependencyResolution = ({
name,
resolution,
@@ -224,56 +108,6 @@ const applyDependencyResolution = ({
}
};
-const isBarePackageImport = (request: string) =>
- !request.startsWith('.') &&
- !request.startsWith('/') &&
- !request.startsWith('http://') &&
- !request.startsWith('https://') &&
- !request.includes('!');
-
-const getPackageName = (request: string) =>
- request.startsWith('@')
- ? request.split('/').slice(0, 2).join('/')
- : request.split('/')[0];
-
-const getVersionedPackageRequest = (request: string, version: string) => {
- if (!request.startsWith('@')) {
- const slashIndex = request.indexOf('/');
- return slashIndex === -1
- ? `${request}@${version}`
- : `${request.slice(0, slashIndex)}@${version}${request.slice(slashIndex)}`;
- }
-
- const secondSlashIndex = request.indexOf('/', request.indexOf('/') + 1);
- return secondSlashIndex === -1
- ? `${request}@${version}`
- : `${request.slice(0, secondSlashIndex)}@${version}${request.slice(secondSlashIndex)}`;
-};
-
-const externalizeSharedDependencies = (url: URL) => {
- url.searchParams.set('dev', '');
- url.searchParams.set('external', studioRenderEntryExternal.join(','));
-};
-
-const writeInitialFiles = ({
- builtinMemFs,
- project,
-}: {
- builtinMemFs: BuiltinMemFs;
- project: VirtualProject;
-}) => {
- builtinMemFs.volume.reset();
- builtinMemFs.volume.fromJSON({
- ...getBrowserStudioVirtualFiles(),
- ...Object.fromEntries(
- Object.entries(project.files).map(([path, contents]) => [
- normalizePath(path),
- contents,
- ]),
- ),
- });
-};
-
const getReactRefreshPlugin = (
rspackBrowser: typeof RspackBrowser,
): RspackBrowser.RspackPluginInstance => ({
@@ -354,10 +188,6 @@ const createCompiler = async ({
remotionPackageSource,
useVendorBundle,
}: Extract<BrowserStudioWorkerCompileRequest, {type: 'init'}>) => {
- const rspackBrowser = await loadRspackBrowser();
- const {BrowserHttpImportEsmPlugin, builtinMemFs, rspack} = rspackBrowser;
- writeInitialFiles({builtinMemFs, project});
-
const resolvedVersions = {...browserStudioDependencyVersions};
if (remotionPackageSource?.type === 'release') {
for (const name of Object.keys(resolvedVersions)) {
@@ -387,7 +217,7 @@ const createCompiler = async ({
studioRenderEntry: useVendorBundle
? browserStudioVirtualFilePaths.studioPreviewEntry
: '@remotion/studio/previewEntry',
- userDefinedComponent: normalizePath(project.entryPoint),
+ userDefinedComponent: normalizeVirtualPath(project.entryPoint),
});
entryPoints.splice(
entryPoints.length - 1,
@@ -395,358 +225,255 @@ const createCompiler = async ({
browserStudioVirtualFilePaths.browserRequireShim,
);
- const compiler = rspack({
- context: normalizePath(project.rootDir),
- devtool: 'eval-cheap-module-source-map',
- entry: {bundle: {asyncChunks: false, import: entryPoints}},
- experiments: {
- buildHttp: {
- allowedUris: [
- 'https://esm.sh/',
- `${self.location.origin}/`,
- ...(remotionPackageSource ? [remotionPackageSource.baseUrl] : []),
- ],
- cacheLocation: false,
- httpClient: makeBrowserStudioHttpClient({
- fetchImplementation: fetch,
- }),
+ const compiler = await createBrowserCompiler({
+ project,
+ virtualFiles: getBrowserStudioVirtualFiles(),
+ onProgress: (progress) =>
+ postResponse({type: 'load-progress', ...progress}),
+ configure: (rspackBrowser) => ({
+ context: normalizeVirtualPath(project.rootDir),
+ devtool: 'eval-cheap-module-source-map',
+ entry: {bundle: {asyncChunks: false, import: entryPoints}},
+ experiments: {
+ buildHttp: {
+ allowedUris: [
+ 'https://esm.sh/',
+ `${self.location.origin}/`,
+ ...(remotionPackageSource ? [remotionPackageSource.baseUrl] : []),
+ ],
+ cacheLocation: false,
+ httpClient: makeBrowserHttpClient({
+ fetchImplementation: fetch,
+ }),
+ },
},
- },
- externals: [
- ...(useVendorBundle ? [browserStudioVendorExternals] : []),
- ({request}, callback) => {
- if (request === BROWSER_STUDIO_TRANSFORMERS_PACKAGE) {
- callback(undefined, request, 'import');
- return;
- }
+ externals: [
+ ...(useVendorBundle ? [browserStudioVendorExternals] : []),
+ ({request}, callback) => {
+ if (request === BROWSER_STUDIO_TRANSFORMERS_PACKAGE) {
+ callback(undefined, request, 'import');
+ return;
+ }
- callback();
- },
- ],
- externalsType: useVendorBundle ? 'var' : undefined,
- mode: 'development',
- module: {
- rules: [
- {parser: {worker: false}, test: /\.[cm]?[jt]sx?$/},
- {
- exclude: [/node_modules/, /__remotion_browser_studio__/],
- test: /\.[jt]sx?$/,
- use: [{loader: 'builtin:react-refresh-loader'}],
+ callback();
},
- {
- test: /\.tsx?$/,
- use: [
- {
- loader: 'builtin:swc-loader',
- options: {
- env: {targets: 'Chrome >= 111'},
- jsc: {
- parser: {syntax: 'typescript', tsx: true},
- transform: {
- react: {
- development: true,
- refresh: true,
- importSource:
- browserStudioVirtualFilePaths.jsxImportSource,
- runtime: 'automatic',
+ ],
+ externalsType: useVendorBundle ? 'var' : undefined,
+ mode: 'development',
+ module: {
+ rules: [
+ {parser: {worker: false}, test: /\.[cm]?[jt]sx?$/},
+ {
+ exclude: [/node_modules/, /__remotion_browser_studio__/],
+ test: /\.[jt]sx?$/,
+ use: [{loader: 'builtin:react-refresh-loader'}],
+ },
+ {
+ test: /\.tsx?$/,
+ use: [
+ {
+ loader: 'builtin:swc-loader',
+ options: {
+ env: {targets: 'Chrome >= 111'},
+ jsc: {
+ parser: {syntax: 'typescript', tsx: true},
+ transform: {
+ react: {
+ development: true,
+ refresh: true,
+ importSource:
+ browserStudioVirtualFilePaths.jsxImportSource,
+ runtime: 'automatic',
+ },
},
},
},
},
- },
- ],
- },
- {
- exclude: /node_modules/,
- test: /\.jsx?$/,
- use: [
- {
- loader: 'builtin:swc-loader',
- options: {
- env: {targets: 'Chrome >= 111'},
- jsc: {
- parser: {jsx: true, syntax: 'ecmascript'},
- transform: {
- react: {
- development: true,
- refresh: true,
- importSource:
- browserStudioVirtualFilePaths.jsxImportSource,
- runtime: 'automatic',
+ ],
+ },
+ {
+ exclude: /node_modules/,
+ test: /\.jsx?$/,
+ use: [
+ {
+ loader: 'builtin:swc-loader',
+ options: {
+ env: {targets: 'Chrome >= 111'},
+ jsc: {
+ parser: {jsx: true, syntax: 'ecmascript'},
+ transform: {
+ react: {
+ development: true,
+ refresh: true,
+ importSource:
+ browserStudioVirtualFilePaths.jsxImportSource,
+ runtime: 'automatic',
+ },
},
},
},
},
- },
- ],
- },
+ ],
+ },
+ ],
+ },
+ optimization: {runtimeChunk: false, splitChunks: false},
+ output: {
+ chunkFilename: '[name].js',
+ chunkFormat: 'array-push',
+ chunkLoading: 'jsonp',
+ filename: 'bundle.js',
+ hashFunction: 'xxhash64',
+ path: '/dist',
+ publicPath: '/__remotion_browser_studio_hmr__/',
+ },
+ plugins: [
+ getReactRefreshPlugin(rspackBrowser),
+ createBrowserDependencyPlugin({
+ rspack: rspackBrowser,
+ development: true,
+ external: studioRenderEntryExternal,
+ resolvedUrls,
+ resolvedVersions,
+ resolvePackage: (request) =>
+ resolveBrowserStudioRemotionPackage({
+ packages: workspacePackageExports,
+ request,
+ source: remotionPackageSource,
+ }),
+ }),
+ new rspackBrowser.HotModuleReplacementPlugin(),
+ getBrowserStudioHmrRuntimePlugin(rspackBrowser),
+ new rspackBrowser.optimize.LimitChunkCountPlugin({maxChunks: 1}),
],
- },
- optimization: {runtimeChunk: false, splitChunks: false},
- output: {
- chunkFilename: '[name].js',
- chunkFormat: 'array-push',
- chunkLoading: 'jsonp',
- filename: 'bundle.js',
- hashFunction: 'xxhash64',
- path: '/dist',
- publicPath: '/__remotion_browser_studio_hmr__/',
- },
- plugins: [
- getReactRefreshPlugin(rspackBrowser),
- new BrowserHttpImportEsmPlugin({
- dependencyUrl: ({request}) => {
- if (!isBarePackageImport(request)) {
- return undefined;
- }
-
- const packageName = getPackageName(request);
- const resolvedUrl = resolvedUrls[packageName];
- if (resolvedUrl) {
- return resolvedUrl;
- }
-
- const remotionPackageUrl = resolveBrowserStudioRemotionPackage({
- packages: workspacePackageExports,
- request,
- source: remotionPackageSource,
- });
- if (remotionPackageUrl) {
- return remotionPackageUrl;
- }
-
- const version = resolvedVersions[packageName] ?? 'latest';
- const url = new URL(
- getVersionedPackageRequest(request, version),
- 'https://esm.sh/',
- );
- externalizeSharedDependencies(url);
- return url.href;
- },
- dependencyVersions: resolvedVersions,
- domain: 'https://esm.sh',
- postprocess: ({url}) => externalizeSharedDependencies(url),
- }),
- new rspackBrowser.HotModuleReplacementPlugin(),
- getBrowserStudioHmrRuntimePlugin(rspackBrowser),
- new rspack.optimize.LimitChunkCountPlugin({maxChunks: 1}),
- ],
- resolve: {extensions: ['.tsx', '.ts', '.jsx', '.js', '.json']},
+ resolve: {extensions: ['.tsx', '.ts', '.jsx', '.js', '.json']},
+ }),
});
return {
- builtinMemFs,
compiler,
resolvedUrls,
resolvedVersions,
- rspackBrowser,
};
};
-const makeHmrEvent = ({
- errors,
- statsJson,
- warnings,
-}: {
- errors: string[];
- statsJson: RspackBrowser.StatsCompilation;
- warnings: string[];
-}): HotMiddlewareMessage => ({
+const makeHmrEvent = (result: BrowserCompilerResult): HotMiddlewareMessage => ({
action: 'built',
- errors,
- hash: statsJson.hash,
- modules: Object.fromEntries(
- (statsJson.modules ?? []).map((module, index) => [
- String(module.id ?? index),
- module.name ?? module.identifier ?? '',
- ]),
- ),
+ errors: result.errors,
+ hash: result.hash,
+ modules: result.modules,
name: '',
- time: statsJson.time,
- warnings,
+ time: result.time,
+ warnings: result.warnings,
});
-const getHmrAssets = ({
- assetNames,
- builtinMemFs,
-}: {
- assetNames: string[];
- builtinMemFs: BuiltinMemFs;
-}): BrowserStudioHmrAsset[] =>
- assetNames
- .filter((name) => name.includes('.hot-update.'))
- .map((name) => ({
- content: String(
- builtinMemFs.volume.readFileSync(`/dist/${name}`, 'utf8'),
- ),
- name,
- }));
-
const applyProjectUpdate = (
session: CompilerSession,
project: VirtualProject,
) => {
- const previousFiles = Object.fromEntries(
- Object.entries(session.project.files).map(([path, contents]) => [
- normalizePath(path),
- contents,
- ]),
- );
- const nextFiles = Object.fromEntries(
- Object.entries(project.files).map(([path, contents]) => [
- normalizePath(path),
- contents,
- ]),
- );
- const changed = Object.keys(nextFiles).filter(
- (path) => previousFiles[path] !== nextFiles[path],
- );
- const removed = Object.keys(previousFiles).filter(
- (path) => !(path in nextFiles),
- );
+ const {modified, removed} = getVirtualProjectChanges({
+ previous: getVirtualProjectFiles(session.project),
+ next: getVirtualProjectFiles(project),
+ });
session.project = project;
- if (changed.length === 0 && removed.length === 0) {
- return false;
- }
-
- for (const path of changed) {
- session.builtinMemFs.volume.mkdirSync(
- path.slice(0, path.lastIndexOf('/')) || '/',
- {recursive: true},
- );
- session.builtinMemFs.volume.writeFileSync(path, nextFiles[path]);
- }
-
- for (const path of removed) {
- session.builtinMemFs.volume.unlinkSync(path);
- }
-
- session.modifiedFiles = new Set(changed);
- session.removedFiles = new Set(removed);
- return true;
+ return modified.length > 0 || removed.length > 0;
};
-const runCompilation = (session: CompilerSession) => {
+const runCompilation = async (session: CompilerSession) => {
if (session.running) {
return;
}
session.running = true;
- const {modifiedFiles, removedFiles} = session;
- session.modifiedFiles = undefined;
- session.removedFiles = undefined;
- session.compiler.run(
- (error, stats) => {
- session.running = false;
- const {queuedProject} = session;
- session.queuedProject = null;
- const runQueuedProject = () => {
- if (!queuedProject || !applyProjectUpdate(session, queuedProject)) {
- return false;
- }
+ const outcome = await session.compiler.compile(session.project).then(
+ (compilation) => ({type: 'success' as const, result: compilation}),
+ (error: unknown) => ({
+ type: 'error' as const,
+ error: makeBrowserStudioError(error),
+ }),
+ );
+ if (compilerSession !== session) {
+ return;
+ }
- if (session.initialCompiled) {
- postResponse({type: 'building'});
- }
+ session.running = false;
+ const {queuedProject} = session;
+ session.queuedProject = null;
+ const runQueuedProject = () => {
+ if (!queuedProject || !applyProjectUpdate(session, queuedProject)) {
+ return false;
+ }
- runCompilation(session);
- return true;
- };
+ if (session.initialCompiled) {
+ postResponse({type: 'building'});
+ }
- if (error) {
- if (runQueuedProject()) {
- return;
- }
+ runCompilation(session);
+ return true;
+ };
- postResponse({error: makeBrowserStudioError(error), type: 'error'});
- return;
- }
+ if (outcome.type === 'error') {
+ if (!runQueuedProject()) {
+ postResponse({error: outcome.error, type: 'error'});
+ }
- if (!stats) {
- if (runQueuedProject()) {
- return;
- }
+ return;
+ }
+ const {result} = outcome;
+ if (!session.initialCompiled) {
+ if (result.bundle === null) {
+ if (!runQueuedProject()) {
postResponse({
- error: makeBrowserStudioError('Rspack returned no compilation stats'),
+ error: makeBrowserStudioError(
+ 'Rspack compilation failed',
+ result.errors,
+ ),
type: 'error',
});
- return;
}
- const statsJson = stats.toJson({
- all: false,
- assets: true,
- errors: true,
- hash: true,
- modules: true,
- timings: true,
- warnings: true,
- });
- const errors = (statsJson.errors ?? []).map(problemToString);
- const warnings = (statsJson.warnings ?? []).map(problemToString);
-
- if (!session.initialCompiled) {
- if (errors.length > 0) {
- if (runQueuedProject()) {
- return;
- }
-
- postResponse({
- error: makeBrowserStudioError('Rspack compilation failed', errors),
- type: 'error',
- });
- return;
- }
+ return;
+ }
- session.initialCompiled = true;
- postResponse({
- bundle: String(
- session.builtinMemFs.volume.readFileSync('/dist/bundle.js', 'utf8'),
- ),
- type: 'initial-compiled',
- warnings,
- });
- runQueuedProject();
- return;
- }
+ session.initialCompiled = true;
+ postResponse({
+ bundle: result.bundle,
+ type: 'initial-compiled',
+ warnings: result.warnings,
+ });
+ runQueuedProject();
+ return;
+ }
- postResponse({
- assets: getHmrAssets({
- assetNames: (statsJson.assets ?? [])
- .map((asset) => asset.name)
- .filter((name): name is string => Boolean(name)),
- builtinMemFs: session.builtinMemFs,
- }),
- hmrEvent: makeHmrEvent({errors, statsJson, warnings}),
- type: 'hmr-update',
- warnings,
- });
- runQueuedProject();
- },
- {modifiedFiles, removedFiles},
- );
+ postResponse({
+ assets: result.assets.filter((asset) =>
+ asset.name.includes('.hot-update.'),
+ ),
+ hmrEvent: makeHmrEvent(result),
+ type: 'hmr-update',
+ warnings: result.warnings,
+ });
+ runQueuedProject();
};
const startCompiler = async (
request: Extract<BrowserStudioWorkerCompileRequest, {type: 'init'}>,
) => {
if (compilerSession) {
- compilerSession.compiler.close(() => undefined);
+ const previous = compilerSession;
compilerSession = null;
+ await previous.compiler.dispose();
}
- const {builtinMemFs, compiler, resolvedUrls, resolvedVersions} =
+ const {compiler, resolvedUrls, resolvedVersions} =
await createCompiler(request);
const session: CompilerSession = {
- builtinMemFs,
compiler,
initialCompiled: false,
- modifiedFiles: undefined,
project: request.project,
queuedProject: null,
- removedFiles: undefined,
resolvedUrls,
resolvedVersions,
running: false,
@@ -789,19 +516,23 @@ const updateProject = (
runCompilation(compilerSession);
};
+let messages: Promise<void> = Promise.resolve();
+
self.addEventListener(
'message',
- async (event: MessageEvent<BrowserStudioWorkerCompileRequest>) => {
- try {
- if (event.data.type === 'init') {
- await startCompiler(event.data);
- return;
- }
+ (event: MessageEvent<BrowserStudioWorkerCompileRequest>) => {
+ messages = messages.then(async () => {
+ try {
+ if (event.data.type === 'init') {
+ await startCompiler(event.data);
+ return;
+ }
- updateProject(event.data);
- } catch (error) {
- postResponse({error: makeBrowserStudioError(error), type: 'error'});
- }
+ updateProject(event.data);
+ } catch (error) {
+ postResponse({error: makeBrowserStudioError(error), type: 'error'});
+ }
+ });
},
);
diff --git a/packages/browser-studio/src/types.ts b/packages/browser-studio/src/types.ts
index 040dd8b8ef..1c2638dd43 100644
--- a/packages/browser-studio/src/types.ts
+++ b/packages/browser-studio/src/types.ts
@@ -1,10 +1,8 @@
+import type {VirtualProject as SourceProject} from '@remotion/browser-bundler';
import type {StudioElementPayload} from '@remotion/studio-protocol';
import type {HotMiddlewareMessage} from '@remotion/studio-shared';
-export type VirtualProject = {
- rootDir: string;
- entryPoint: string;
- files: Record<string, string>;
+export type VirtualProject = SourceProject & {
publicFiles?: Record<string, VirtualProjectPublicFile>;
publicFileStorage?: BrowserStudioProjectStorage;
};
@@ -26,12 +24,7 @@ export type VirtualProjectPublicFile =
| string
| BrowserStudioStoredPublicFile;
-export type VirtualFileSystem = {
- readFile: (path: string) => Promise<string> | string;
- writeFile: (path: string, contents: string) => Promise<void> | void;
- exists: (path: string) => Promise<boolean> | boolean;
- listFiles: () => Promise<string[]> | string[];
-};
+export type {VirtualFileSystem} from '@remotion/browser-bundler';
export type BrowserStudioDependencyResolution =
| string
diff --git a/packages/browser-studio/tsconfig.json b/packages/browser-studio/tsconfig.json
index 2521f2bc8d..b35fcc1654 100644
--- a/packages/browser-studio/tsconfig.json
+++ b/packages/browser-studio/tsconfig.json
@@ -13,6 +13,7 @@
},
"include": ["src"],
"references": [
+ {"path": "../browser-bundler"},
{"path": "../studio"},
{"path": "../studio-codemods"},
{"path": "../studio-shared"}
diff --git a/packages/cli/src/list-of-remotion-packages.ts b/packages/cli/src/list-of-remotion-packages.ts
index b3de971a35..04365d4903 100644
--- a/packages/cli/src/list-of-remotion-packages.ts
+++ b/packages/cli/src/list-of-remotion-packages.ts
@@ -8,6 +8,7 @@ export const listOfRemotionPackages = [
'@remotion/bugs',
'@remotion/brand',
'@remotion/bundler',
+ '@remotion/browser-bundler',
'@remotion/browser-studio',
'@remotion/canvas',
'@remotion/claude-code-plugin',
diff --git a/packages/create-video/src/list-of-remotion-packages.ts b/packages/create-video/src/list-of-remotion-packages.ts
index b3de971a35..04365d4903 100644
--- a/packages/create-video/src/list-of-remotion-packages.ts
+++ b/packages/create-video/src/list-of-remotion-packages.ts
@@ -8,6 +8,7 @@ export const listOfRemotionPackages = [
'@remotion/bugs',
'@remotion/brand',
'@remotion/bundler',
+ '@remotion/browser-bundler',
'@remotion/browser-studio',
'@remotion/canvas',
'@remotion/claude-code-plugin',
diff --git a/packages/docs/components/TableOfContents/api.tsx b/packages/docs/components/TableOfContents/api.tsx
index 03cfc9adcd..4412d98035 100644
--- a/packages/docs/components/TableOfContents/api.tsx
+++ b/packages/docs/components/TableOfContents/api.tsx
@@ -1,6 +1,7 @@
import React from 'react';
import {TableOfContents as AnimatedEmojiTableOfContents} from '../../docs/animated-emoji/TableOfContents';
import {TableOfContents as AnimationUtilsTableOfContents} from '../../docs/animation-utils/table-of-contents';
+import {TableOfContents as BrowserBundlerTableOfContents} from '../../docs/browser-bundler/table-of-contents';
import {TableOfContents as BundlerTableOfContents} from '../../docs/bundler/table-of-contents';
import {TableOfContents as CaptionsTableOfContents} from '../../docs/captions/TableOfContents';
import {TableOfContents as CloudrunTableOfContents} from '../../docs/cloudrun/table-of-contents';
@@ -77,6 +78,9 @@ export const TableOfContents: React.FC = () => {
<h2>@remotion/animation-utils</h2>
<p>Obtain info about video and audio.</p>
<AnimationUtilsTableOfContents />
+ <h2>@remotion/browser-bundler</h2>
+ <p>Compile virtual Remotion projects in the browser.</p>
+ <BrowserBundlerTableOfContents />
<h2>@remotion/bundler</h2>
<p>Create a Webpack bundle from Node.JS </p>
<BundlerTableOfContents />
diff --git a/packages/docs/docs/browser-bundler/create-browser-bundler.mdx b/packages/docs/docs/browser-bundler/create-browser-bundler.mdx
new file mode 100644
index 0000000000..70a8efbc56
--- /dev/null
+++ b/packages/docs/docs/browser-bundler/create-browser-bundler.mdx
@@ -0,0 +1,168 @@
+---
+image: /generated/articles-docs-browser-bundler-create-browser-bundler.png
+title: createBrowserBundler()
+crumb: '@remotion/browser-bundler'
+---
+
+# createBrowserBundler()<AvailableFrom v="4.0.526" />
+
+Creates a browser-side compiler for virtual Remotion projects. Import it from `@remotion/browser-bundler`.
+
+<ExperimentalBadge>
+<p>This API is experimental. Read the <a href="/docs/browser-bundler#browser-setup">browser setup requirements</a> before using it.</p>
+</ExperimentalBadge>
+
+Given a [`VirtualProject`](#virtualproject) snapshot, such as the [overview example](/docs/browser-bundler#minimal-example):
+
+```ts twoslash title="compile-project.ts"
+// @moduleResolution: bundler
+import type {VirtualProject} from '@remotion/browser-bundler';
+declare const project: VirtualProject;
+// ---cut---
+import {
+ BrowserBundlerError,
+ createBrowserBundler,
+} from '@remotion/browser-bundler';
+
+const bundler = createBrowserBundler({
+ onProgress: ({loadedBytes, totalBytes}) => {
+ console.log({loadedBytes, totalBytes});
+ },
+});
+
+try {
+ const bundle = await bundler.bundle({project});
+ console.log(bundle.warnings);
+} catch (error) {
+ if (error instanceof BrowserBundlerError) {
+ console.error(error.diagnostics);
+ } else {
+ throw error;
+ }
+} finally {
+ bundler.dispose();
+}
+```
+
+## Options
+
+All options are optional. Calling `createBrowserBundler()` uses the defaults.
+
+### dependencyVersions?
+
+A `Record<string, string>` mapping npm package names to versions. These values override the package's built-in dependency versions for HTTP dependency resolution.
+
+The built-in defaults are the versions used to build `@remotion/browser-bundler`. Other packages without a configured version resolve to `latest` on [esm.sh](https://esm.sh). Pin dependencies if you need reproducible resolutions.
+
+React, React DOM, and Remotion imports must match the host app's versions. They are shared with the host at runtime; setting a different version here does not install a separate runtime.
+
+```ts twoslash title="Pinning an additional dependency"
+// @moduleResolution: bundler
+import {createBrowserBundler} from '@remotion/browser-bundler';
+
+const bundler = createBrowserBundler({
+ dependencyVersions: {
+ 'lodash-es': '4.17.21',
+ },
+});
+```
+
+### onProgress?
+
+Called with download progress while loading the compiler's WebAssembly asset. By default, no progress callback is called. This is download progress, not compilation progress.
+
+#### asset
+
+The string `'rspack-wasm'`.
+
+#### loadedBytes
+
+The number of bytes downloaded so far.
+
+#### totalBytes
+
+The total download size in bytes, or `null` if the size is not yet known. Only calculate a percentage when this value is known and greater than zero.
+
+### workerUrl?
+
+A `string` or `URL` pointing to the browser bundler's prebuilt module worker on the same origin as your app. By default, the package resolves its worker relative to its own module URL.
+
+Use this when you serve the packaged worker at a custom location. The URL must point to the browser bundler worker, not to your virtual project's entry point. Host its adjacent WebAssembly and supporting worker assets too, preserving their filenames and relative paths. See [host bundler support](/docs/browser-bundler#host-bundler-support).
+
+## Return value
+
+A `BrowserBundler` with the following methods. Creating it starts a worker; compiler initialization happens when a project is first bundled.
+
+### bundle()
+
+Accepts an object containing a `project` field with a [`VirtualProject`](#virtualproject). Returns a `Promise<BrowserBundle>` that resolves after compilation completes.
+
+Calls on the same instance are serialized. Reusing the instance applies added, edited, and removed source files incrementally. Pass a complete snapshot, not only the changed files; omitted files are removed from the next project snapshot.
+
+A failed compilation rejects its promise without preventing a later compilation on the same instance. Compiling does not execute the bundle or update your UI.
+
+#### project
+
+The complete [`VirtualProject`](#virtualproject) snapshot to compile.
+
+### dispose()
+
+Terminates the worker and releases its compiler resources. Returns `void`.
+
+Pending `bundle()` calls reject, and further calls to `bundle()` on this instance reject. Create a new bundler to compile again. Calling `dispose()` does not unmount a Player or undo side effects from an already executed bundle.
+
+## VirtualProject
+
+An object describing source files in memory. Import the `VirtualProject` type from `@remotion/browser-bundler`.
+
+### rootDir
+
+The virtual project's root directory, for example `'/project'`. Use forward-slash paths.
+
+### entryPoint
+
+The virtual entry file, for example `'/project/src/index.ts'`. It must be included in `files`.
+
+Use an ordinary Remotion entry point that calls [`registerRoot()`](/docs/register-root) if you will execute the result with [`loadBrowserBundle()`](/docs/browser-bundler/load-browser-bundle).
+
+Keep `rootDir` and `entryPoint` unchanged across source edits to reuse the compiler. Changing either starts a new compiler for the new project.
+
+### files
+
+A `Record<string, string>` mapping virtual file paths to their source text. Use complete paths such as `'/project/src/Root.tsx'`, not paths relative to `rootDir`.
+
+This is a source snapshot, not a persistent filesystem. Do not include binary media or expect files under `public/` to be served as assets.
+
+## BrowserBundle
+
+The object returned by `bundle()`. Import the `BrowserBundle` type from `@remotion/browser-bundler`.
+
+### code
+
+The compiled JavaScript as a `string`. Pass the complete `BrowserBundle` to [`loadBrowserBundle()`](/docs/browser-bundler/load-browser-bundle) to execute it.
+
+### warnings
+
+An array of compiler warning strings. An empty array means no compiler warnings were reported.
+
+## Errors
+
+Compilation failures reject with `BrowserBundlerError`, exported from `@remotion/browser-bundler`. Display its `message` and diagnostics in your own error UI.
+
+### diagnostics
+
+An array of compiler diagnostic strings on `BrowserBundlerError`. It may be empty when no detailed diagnostics are available.
+
+Browser setup failures can throw synchronously from `createBrowserBundler()`. Worker failures and disposal can reject `bundle()` with other errors, so handle more than `BrowserBundlerError`.
+
+## Compatibility
+
+<CompatibilityTable chrome firefox="Not tested" safari="Not tested" nodejs="" bun="" serverlessFunctions="" clientSideRendering="" serverSideRendering={false} player studio="" hideServers />
+
+The experimental workflow has only been tested in Chrome. Run it in the host web app with [cross-origin isolation](/docs/browser-bundler#browser-setup), not during server rendering or a video frame render.
+
+## See also
+
+- [Overview and complete Player example](/docs/browser-bundler)
+- [`loadBrowserBundle()`](/docs/browser-bundler/load-browser-bundle)
+- [`getBrowserComposition()`](/docs/browser-bundler/get-browser-composition)
diff --git a/packages/docs/docs/browser-bundler/get-browser-composition.mdx b/packages/docs/docs/browser-bundler/get-browser-composition.mdx
new file mode 100644
index 0000000000..493c300a13
--- /dev/null
+++ b/packages/docs/docs/browser-bundler/get-browser-composition.mdx
@@ -0,0 +1,182 @@
+---
+image: /generated/articles-docs-browser-bundler-get-browser-composition.png
+title: getBrowserComposition()
+crumb: '@remotion/browser-bundler'
+---
+
+# getBrowserComposition()<AvailableFrom v="4.0.526" />
+
+Selects a registered composition by ID and resolves its video configuration and props. Import it from `@remotion/browser-bundler/runtime`.
+
+<ExperimentalBadge>
+<p>This API is experimental. It runs trusted project code in the host page.</p>
+</ExperimentalBadge>
+
+Use a root returned by [`loadBrowserBundle()`](/docs/browser-bundler/load-browser-bundle):
+
+```tsx twoslash title="resolve-composition.tsx"
+// @moduleResolution: bundler
+import type {FC} from 'react';
+declare const root: FC;
+// ---cut---
+import {getBrowserComposition} from '@remotion/browser-bundler/runtime';
+import {Player} from '@remotion/player';
+
+const composition = await getBrowserComposition({
+ root,
+ compositionId: 'HelloWorld',
+ inputProps: {message: 'Hello from the browser!'},
+});
+
+export const Preview = () => (
+ <Player
+ component={composition.component}
+ inputProps={composition.props}
+ durationInFrames={composition.durationInFrames}
+ fps={composition.fps}
+ compositionWidth={composition.width}
+ compositionHeight={composition.height}
+ controls
+ />
+);
+```
+
+Call this in browser-side initialization or an event handler. For a React example with loading, errors, and cleanup, see the [overview](/docs/browser-bundler#minimal-example).
+
+## Options
+
+### root
+
+The `React.FC` returned by [`loadBrowserBundle()`](/docs/browser-bundler/load-browser-bundle). Its registered [`<Composition>`](/docs/composition) elements are used to find the requested ID.
+
+### compositionId
+
+The exact `id` of the registered [`<Composition>`](/docs/composition) to select. The promise rejects if no composition with that ID is registered.
+
+### inputProps
+
+A `Record<string, unknown>` of [input props](/docs/terminology/input-props). This field is required; pass `{}` to use the composition's defaults.
+
+Input props are shallowly merged over [`defaultProps`](/docs/composition#defaultprops). If the composition supplies [`calculateMetadata()`](/docs/calculate-metadata), it receives the merged props and may return new props or video metadata.
+
+### signal?
+
+An `AbortSignal` that cancels pending composition resolution, including waiting for registration and [`calculateMetadata()`](/docs/calculate-metadata). By default, there is no caller-provided cancellation signal.
+
+The metadata function receives an `abortSignal` for cancelling its own asynchronous work. Cancellation rejects the returned promise. It does not stop arbitrary synchronous project code, cancel compilation, or unmount an existing Player.
+
+```ts twoslash title="Cancelling composition resolution"
+// @moduleResolution: bundler
+import type {FC} from 'react';
+declare const root: FC;
+// ---cut---
+import {getBrowserComposition} from '@remotion/browser-bundler/runtime';
+
+const controller = new AbortController();
+const pending = getBrowserComposition({
+ root,
+ compositionId: 'HelloWorld',
+ inputProps: {},
+ signal: controller.signal,
+});
+
+controller.abort();
+
+try {
+ await pending;
+} catch (error) {
+ if (!controller.signal.aborted) {
+ throw error;
+ }
+}
+```
+
+## Return value
+
+A `Promise<BrowserComposition>`. Import the `BrowserComposition` type from `@remotion/browser-bundler/runtime`.
+
+The result extends `VideoConfig` from `remotion` with a `component` field. It includes the following values for playback:
+
+### component
+
+The selected composition's video component, compatible with [`<Player>`](/docs/player/player). Compositions registered with either `component` or [`lazyComponent`](/docs/composition#lazycomponent) are supported.
+
+Pass this value to the Player's `component` prop, not the registered root or `<Composition>` itself.
+
+Providers wrapped around `<Composition>` in the root are used for registration only. They are not included around the returned video component. Put providers needed for playback inside the video component or in the host UI around your Player.
+
+### id
+
+The selected composition's ID.
+
+### props
+
+The resolved props after merging input and default props and applying any props returned by [`calculateMetadata()`](/docs/calculate-metadata). Pass this value to the Player's `inputProps`.
+
+### defaultProps
+
+The composition's original default props, before applying input props or metadata transformations.
+
+### width
+
+The resolved video width in pixels. Pass it as the Player's `compositionWidth`.
+
+### height
+
+The resolved video height in pixels. Pass it as the Player's `compositionHeight`.
+
+### fps
+
+The resolved frame rate. Pass it as the Player's `fps`.
+
+### durationInFrames
+
+The resolved duration in frames. Pass it as the Player's `durationInFrames`.
+
+### defaultCodec
+
+The default codec returned by [`calculateMetadata()`](/docs/calculate-metadata), or `null`.
+
+### defaultOutName
+
+The default output name returned by [`calculateMetadata()`](/docs/calculate-metadata), or `null`.
+
+### defaultVideoImageFormat
+
+The default intermediate frame format returned by [`calculateMetadata()`](/docs/calculate-metadata), or `null`.
+
+### defaultPixelFormat
+
+The default pixel format returned by [`calculateMetadata()`](/docs/calculate-metadata), or `null`.
+
+### defaultProResProfile
+
+The default ProRes profile returned by [`calculateMetadata()`](/docs/calculate-metadata), or `null`.
+
+### defaultSampleRate
+
+The default audio sample rate returned by [`calculateMetadata()`](/docs/calculate-metadata), or `null`.
+
+These default encoding settings are part of `VideoConfig`. They do not configure Player playback.
+
+## Resolution and errors
+
+The function uses ordinary [`<Composition>`](/docs/composition) registration, supports lazily loaded compositions, and runs [`calculateMetadata()`](/docs/calculate-metadata) when present. It validates the resulting dimensions, frame rate, and duration.
+
+The promise rejects for a missing composition ID, invalid or duplicate registrations, metadata errors, invalid video configuration, or cancellation. Handle these errors separately from compiler diagnostics: a successful compilation does not guarantee valid runtime metadata.
+
+This function runs again on every call. Resolving a new bundle does not automatically update a Player; you decide when to replace its component, props, and configuration.
+
+## Compatibility
+
+<CompatibilityTable chrome firefox="Not tested" safari="Not tested" nodejs="" bun="" serverlessFunctions="" clientSideRendering="" serverSideRendering={false} player studio="" hideServers />
+
+The experimental workflow has only been tested in Chrome. Call this in a browser page with a DOM, not during server rendering or a video frame render.
+
+## See also
+
+- [Overview and complete Player example](/docs/browser-bundler)
+- [`loadBrowserBundle()`](/docs/browser-bundler/load-browser-bundle)
+- [`<Composition>`](/docs/composition)
+- [`calculateMetadata()`](/docs/calculate-metadata)
+- [`<Player>`](/docs/player/player)
diff --git a/packages/docs/docs/browser-bundler/index.mdx b/packages/docs/docs/browser-bundler/index.mdx
new file mode 100644
index 0000000000..5d5377ca05
--- /dev/null
+++ b/packages/docs/docs/browser-bundler/index.mdx
@@ -0,0 +1,262 @@
+---
+image: /generated/articles-docs-browser-bundler-index.png
+sidebar_label: Overview
+title: '@remotion/browser-bundler'
+crumb: '@remotion/browser-bundler'
+---
+
+# @remotion/browser-bundler<AvailableFrom v="4.0.526" />
+
+Compile a virtual Remotion project in the browser and use a registered [composition](/docs/composition) in your own UI, such as a [`<Player>`](/docs/player/player).
+
+<ExperimentalBadge>
+<p>This package is experimental. The initial implementation has only been tested in Chrome.</p>
+</ExperimentalBadge>
+
+The main entry point compiles source snapshots, manages its worker and WebAssembly compiler, applies source edits incrementally, and resolves npm imports over HTTP. The separate `@remotion/browser-bundler/runtime` entry point executes a bundle and resolves a registered composition.
+
+Neither entry point provides an editor or playback UI.
+
+## Installation
+
+<Installation pkg="@remotion/browser-bundler" />
+
+For the example below, also install [`@remotion/player`](/docs/player/installation). Keep all Remotion packages on the same version, and use the same React and React DOM versions in the host app and virtual project.
+
+## Browser setup
+
+Serve your app in a secure context, such as HTTPS or `localhost`, with these response headers:
+
+```text title="HTTP response headers"
+Cross-Origin-Opener-Policy: same-origin
+Cross-Origin-Embedder-Policy: require-corp
+```
+
+`window.crossOriginIsolated` must be `true`. The browser must support module workers, `SharedArrayBuffer`, and WebAssembly with shared memory. Cross-origin scripts, media, and other resources must satisfy the page's cross-origin policy.
+
+The compiler downloads a sizable WebAssembly binary and can use significant memory. The first compilation is slower than subsequent edits. Use [`onProgress`](/docs/browser-bundler/create-browser-bundler#onprogress) to display download progress, and reuse a bundler instance while editing.
+
+### Host bundler support
+
+The package ships a prebuilt compiler worker together with its WebAssembly binary and supporting worker asset. Your app's bundler must handle `new Worker(new URL(..., import.meta.url))` and emit the assets referenced with `new URL(..., import.meta.url)`. Serve those emitted assets alongside your app.
+
+Alternatively, use [`workerUrl`](/docs/browser-bundler/create-browser-bundler#workerurl) to host the packaged worker and its adjacent assets at a custom same-origin location. Preserve the packaged filenames and relative paths. This overrides the main worker URL, not the requirement to deploy its supporting assets.
+
+Other bundlers and deployment configurations are not guaranteed to work without additional setup. Call these APIs on the client, not during server rendering.
+
+### Next.js with webpack
+
+The initial Next.js integration uses webpack for development and production builds, not Turbopack:
+
+```json title="package.json (scripts)"
+{
+ "scripts": {
+ "dev": "next dev --webpack",
+ "build": "next build --webpack"
+ }
+}
+```
+
+Merge these headers and webpack rules into your configuration. This example uses `/browser-bundler` as the page route; replace it with your route.
+
+```js title="next.config.mjs"
+/** @type {import('next').NextConfig} */
+const nextConfig = {
+ async headers() {
+ return ['/browser-bundler', '/_next/:path*'].map((source) => ({
+ source,
+ headers: [
+ {key: 'Cross-Origin-Opener-Policy', value: 'same-origin'},
+ {key: 'Cross-Origin-Embedder-Policy', value: 'require-corp'},
+ ],
+ }));
+ },
+ webpack(config) {
+ config.module.rules.push(
+ {test: /browser-bundler-worker\.js$/, parser: {url: true}},
+ {test: /\.wasm$/, type: 'asset/resource'},
+ {test: /wasi-worker-browser\.mjs$/, type: 'asset/resource'},
+ );
+ return config;
+ },
+};
+
+export default nextConfig;
+```
+
+If other pages are served without these headers, use full-page navigation when entering or leaving this route. Next.js client-side navigation does not change the current document's cross-origin isolation. A normal `<a>` link performs a full-page navigation.
+
+Next.js normally makes asset URLs relative. The supporting worker starts from a `blob:` URL, so its `importScripts()` call needs an absolute script URL. The scoped `parser: {url: true}` rule preserves that behavior for the packaged compiler worker without changing URL handling throughout your app.
+
+This configuration is specific to webpack. Check that the emitted worker and WebAssembly URLs remain accessible in your deployment.
+
+## Trusted code only
+
+[`loadBrowserBundle()`](/docs/browser-bundler/load-browser-bundle) evaluates JavaScript using `Function`. The bundle and its dependencies run with your host page's privileges, including access to its DOM, storage, and network. This is not a sandbox; do not use it to execute untrusted source.
+
+Your Content Security Policy must permit JavaScript code evaluation (`'unsafe-eval'`), workers, and WebAssembly compilation, as well as the asset and dependency requests. Allowing only `'wasm-unsafe-eval'` is insufficient for the runtime's JavaScript evaluation.
+
+## Minimal example
+
+This is a normal Remotion project: its entry point calls [`registerRoot()`](/docs/register-root), and its root registers a [`<Composition>`](/docs/composition). The host selects the hardcoded `HelloWorld` ID after compiling.
+
+```tsx twoslash title="BrowserBundlerPreview.tsx"
+// @moduleResolution: bundler
+'use client';
+
+import {
+ createBrowserBundler,
+ type BrowserBundler,
+ type VirtualProject,
+} from '@remotion/browser-bundler';
+import {
+ getBrowserComposition,
+ loadBrowserBundle,
+ type BrowserComposition,
+} from '@remotion/browser-bundler/runtime';
+import {Player} from '@remotion/player';
+import {useEffect, useState} from 'react';
+
+const project: VirtualProject = {
+ rootDir: '/project',
+ entryPoint: '/project/src/index.ts',
+ files: {
+ '/project/src/index.ts': `
+ import {registerRoot} from 'remotion';
+ import {Root} from './Root';
+ registerRoot(Root);
+ `,
+ '/project/src/Root.tsx': `
+ import {AbsoluteFill, Composition, useCurrentFrame} from 'remotion';
+
+ const Video = ({message}: {message: string}) => {
+ const frame = useCurrentFrame();
+ return (
+ <AbsoluteFill style={{
+ backgroundColor: 'white',
+ color: 'black',
+ justifyContent: 'center',
+ alignItems: 'center',
+ fontSize: 80,
+ opacity: Math.min(frame / 30, 1),
+ }}>
+ {message}
+ </AbsoluteFill>
+ );
+ };
+
+ export const Root = () => (
+ <Composition
+ id="HelloWorld"
+ component={Video}
+ durationInFrames={90}
+ fps={30}
+ width={1280}
+ height={720}
+ defaultProps={{message: 'Hello world'}}
+ />
+ );
+ `,
+ },
+};
+
+export const BrowserBundlerPreview = () => {
+ const [composition, setComposition] = useState<BrowserComposition | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ const controller = new AbortController();
+ let bundler: BrowserBundler | null = null;
+
+ const compile = async () => {
+ try {
+ bundler = createBrowserBundler();
+ const bundle = await bundler.bundle({project});
+ if (controller.signal.aborted) {
+ return;
+ }
+
+ const root = loadBrowserBundle({bundle});
+ const resolved = await getBrowserComposition({
+ root,
+ compositionId: 'HelloWorld',
+ inputProps: {message: 'Hello from the browser!'},
+ signal: controller.signal,
+ });
+ if (!controller.signal.aborted) {
+ setComposition(resolved);
+ }
+ } catch (err) {
+ if (!controller.signal.aborted) {
+ setError(err instanceof Error ? err.message : String(err));
+ }
+ } finally {
+ bundler?.dispose();
+ }
+ };
+
+ void compile();
+ return () => {
+ controller.abort();
+ bundler?.dispose();
+ };
+ }, []);
+
+ if (error) {
+ return <pre>{error}</pre>;
+ }
+
+ if (!composition) {
+ return <p>Compiling...</p>;
+ }
+
+ return (
+ <Player
+ component={composition.component}
+ inputProps={composition.props}
+ durationInFrames={composition.durationInFrames}
+ fps={composition.fps}
+ compositionWidth={composition.width}
+ compositionHeight={composition.height}
+ controls
+ style={{width: '100%'}}
+ />
+ );
+};
+```
+
+Pass the returned `component` to [`<Player>`](/docs/player/player), not the registered root or `<Composition>` itself. Pass `props` and the resolved dimensions, frame rate, and duration alongside it. [`getBrowserComposition()`](/docs/browser-bundler/get-browser-composition) merges default and input props and runs [`calculateMetadata()`](/docs/calculate-metadata) when provided.
+
+This example compiles once and disposes its worker. For editing, keep the bundler alive, submit a new complete snapshot for each compilation, then load and resolve the new bundle before updating your Player.
+
+## Scope and limitations
+
+### Source snapshots
+
+A [`VirtualProject`](/docs/browser-bundler/create-browser-bundler#virtualproject) contains source file paths and text. You own editing, history, saving, and restoring snapshots. The package does not provide filesystem persistence or an installation UI for npm packages.
+
+### Dependencies
+
+Browser-compatible npm imports resolve through [esm.sh](https://esm.sh). Default dependency versions come from the versions used to build the package. Use [`dependencyVersions`](/docs/browser-bundler/create-browser-bundler#dependencyversions) to pin additional dependencies.
+
+React, React DOM, and Remotion imports are shared with the host app when executing the bundle; they are not isolated copies. An override cannot make a different React or Remotion version run alongside the host version.
+
+### Public assets
+
+The virtual project has no `public/` asset mapping or public-file persistence. [`staticFile()`](/docs/staticfile) does not map a virtual source file to a served asset. Use hosted asset URLs that satisfy the page's cross-origin policy.
+
+### Updating the preview
+
+Compiling does not automatically replace an existing Player component. You own recompilation triggers, loading and resolving the new bundle, handling stale results and errors, and updating playback. There is no automatic hot module replacement for the host Player.
+
+This package does not export a video file. See [client-side rendering](/docs/client-side-rendering) for video export APIs and their separate requirements.
+
+## APIs
+
+import {TableOfContents} from './table-of-contents';
+
+<TableOfContents />
+
+## License
+
+[Remotion License](/docs/license)
diff --git a/packages/docs/docs/browser-bundler/load-browser-bundle.mdx b/packages/docs/docs/browser-bundler/load-browser-bundle.mdx
new file mode 100644
index 0000000000..e254fedf1a
--- /dev/null
+++ b/packages/docs/docs/browser-bundler/load-browser-bundle.mdx
@@ -0,0 +1,74 @@
+---
+image: /generated/articles-docs-browser-bundler-load-browser-bundle.png
+title: loadBrowserBundle()
+crumb: '@remotion/browser-bundler'
+---
+
+# loadBrowserBundle()<AvailableFrom v="4.0.526" />
+
+Executes a [`BrowserBundle`](/docs/browser-bundler/create-browser-bundler#browserbundle) and returns the root component it registered with [`registerRoot()`](/docs/register-root). Import it from `@remotion/browser-bundler/runtime`.
+
+<ExperimentalBadge>
+<p>This API is experimental and executes trusted code only. It is not a sandbox.</p>
+</ExperimentalBadge>
+
+After compiling a project with [`createBrowserBundler()`](/docs/browser-bundler/create-browser-bundler):
+
+```ts twoslash title="load-composition.ts"
+// @moduleResolution: bundler
+import type {BrowserBundle} from '@remotion/browser-bundler';
+declare const bundle: BrowserBundle;
+// ---cut---
+import {
+ getBrowserComposition,
+ loadBrowserBundle,
+} from '@remotion/browser-bundler/runtime';
+
+const root = loadBrowserBundle({bundle});
+const composition = await getBrowserComposition({
+ root,
+ compositionId: 'HelloWorld',
+ inputProps: {},
+});
+```
+
+## Options
+
+### bundle
+
+The complete `BrowserBundle` returned by a bundler's `bundle()` method. Its entry point must synchronously call [`registerRoot()`](/docs/register-root) exactly once with a root component. Registering after an awaited operation or in a timer is not supported.
+
+Exporting a video component without registering a root is not sufficient. Use the [normal Remotion project structure](/docs/browser-bundler#minimal-example).
+
+## Return value
+
+The registered root component, typed as `React.FC`.
+
+Registration is captured separately for each bundle. Loading a bundle does not replace the host app's global Remotion root registration. React, React DOM, and Remotion imports are shared with the host app.
+
+The returned root registers compositions; it is not the video component to pass to [`<Player>`](/docs/player/player). Use [`getBrowserComposition()`](/docs/browser-bundler/get-browser-composition) to select a composition by ID and obtain its `component`, `props`, and video configuration.
+
+## Code execution
+
+The function synchronously evaluates `bundle.code` using `Function`. Both source code and imported npm dependencies execute with the host page's privileges. They can access its DOM, storage, and network; do not pass untrusted bundles.
+
+Your Content Security Policy must allow JavaScript code evaluation. The overall workflow also requires workers, WebAssembly, and allowed asset and dependency requests. See [trusted code only](/docs/browser-bundler#trusted-code-only).
+
+Each call executes the bundle again. There is no automatic cleanup of its side effects, and disposing the compiler does not undo them.
+
+## Errors
+
+Throws if evaluation fails, a shared import is unavailable, or the bundle does not register a valid root exactly once. Errors from importing or initializing project code can occur here even if compilation succeeded.
+
+## Compatibility
+
+<CompatibilityTable chrome firefox="Not tested" safari="Not tested" nodejs="" bun="" serverlessFunctions="" clientSideRendering="" serverSideRendering={false} player studio="" hideServers />
+
+The experimental browser workflow has only been tested in Chrome. Load bundles in the host app, not during server rendering.
+
+## See also
+
+- [Overview and complete Player example](/docs/browser-bundler)
+- [`createBrowserBundler()`](/docs/browser-bundler/create-browser-bundler)
+- [`getBrowserComposition()`](/docs/browser-bundler/get-browser-composition)
+- [`registerRoot()`](/docs/register-root)
diff --git a/packages/docs/docs/browser-bundler/table-of-contents.tsx b/packages/docs/docs/browser-bundler/table-of-contents.tsx
new file mode 100644
index 0000000000..551e5ec08d
--- /dev/null
+++ b/packages/docs/docs/browser-bundler/table-of-contents.tsx
@@ -0,0 +1,24 @@
+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/browser-bundler/create-browser-bundler">
+ <strong>createBrowserBundler()</strong>
+ <div>Compile virtual Remotion projects in the browser</div>
+ </TOCItem>
+ <TOCItem link="/docs/browser-bundler/load-browser-bundle">
+ <strong>loadBrowserBundle()</strong>
+ <div>Execute a trusted bundle and capture its registered root</div>
+ </TOCItem>
+ <TOCItem link="/docs/browser-bundler/get-browser-composition">
+ <strong>getBrowserComposition()</strong>
+ <div>Resolve a registered composition for playback</div>
+ </TOCItem>
+ </Grid>
+ </div>
+ );
+};
diff --git a/packages/docs/package.json b/packages/docs/package.json
index 874442091c..c411b5dfab 100644
--- a/packages/docs/package.json
+++ b/packages/docs/package.json
@@ -46,6 +46,7 @@
"@remotion/animation-utils": "workspace:*",
"@remotion/babel-loader": "workspace:*",
"@remotion/brand": "workspace:*",
+ "@remotion/browser-bundler": "workspace:*",
"@remotion/browser-studio": "workspace:*",
"@remotion/bundler": "workspace:*",
"@remotion/captions": "workspace:*",
diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.ts
index 1af7797646..3c6d26e07b 100644
--- a/packages/docs/sidebars.ts
+++ b/packages/docs/sidebars.ts
@@ -214,6 +214,19 @@ const sidebars: SidebarsConfig = {
'animation-utils/interpolate-styles',
],
},
+ {
+ type: 'category',
+ label: '@remotion/browser-bundler',
+ link: {
+ type: 'doc',
+ id: 'browser-bundler/index',
+ },
+ items: [
+ 'browser-bundler/create-browser-bundler',
+ 'browser-bundler/load-browser-bundle',
+ 'browser-bundler/get-browser-composition',
+ ],
+ },
{
type: 'category',
label: '@remotion/bundler',
diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.ts
index 65f089c886..989d41ef7f 100644
--- a/packages/docs/src/data/articles.ts
+++ b/packages/docs/src/data/articles.ts
@@ -521,6 +521,42 @@ export const articles = [
noAi: false,
slug: 'brownfield',
},
+ {
+ id: 'browser-bundler/create-browser-bundler',
+ title: 'createBrowserBundler()',
+ relativePath: 'docs/browser-bundler/create-browser-bundler.mdx',
+ compId: 'articles-docs-browser-bundler-create-browser-bundler',
+ crumb: '@remotion/browser-bundler',
+ noAi: false,
+ slug: 'browser-bundler/create-browser-bundler',
+ },
+ {
+ id: 'browser-bundler/get-browser-composition',
+ title: 'getBrowserComposition()',
+ relativePath: 'docs/browser-bundler/get-browser-composition.mdx',
+ compId: 'articles-docs-browser-bundler-get-browser-composition',
+ crumb: '@remotion/browser-bundler',
+ noAi: false,
+ slug: 'browser-bundler/get-browser-composition',
+ },
+ {
+ id: 'browser-bundler/index',
+ title: '@remotion/browser-bundler',
+ relativePath: 'docs/browser-bundler/index.mdx',
+ compId: 'articles-docs-browser-bundler-index',
+ crumb: '@remotion/browser-bundler',
+ noAi: false,
+ slug: 'browser-bundler/index',
+ },
+ {
+ id: 'browser-bundler/load-browser-bundle',
+ title: 'loadBrowserBundle()',
+ relativePath: 'docs/browser-bundler/load-browser-bundle.mdx',
+ compId: 'articles-docs-browser-bundler-load-browser-bundle',
+ crumb: '@remotion/browser-bundler',
+ noAi: false,
+ slug: 'browser-bundler/load-browser-bundle',
+ },
{
id: 'building-a-timeline',
title: 'Build a timeline-based video editor',
diff --git a/packages/docs/static/generated/articles-docs-browser-bundler-create-browser-bundler.png b/packages/docs/static/generated/articles-docs-browser-bundler-create-browser-bundler.png
new file mode 100644
index 0000000000..b395f19729
Binary files /dev/null and b/packages/docs/static/generated/articles-docs-browser-bundler-create-browser-bundler.png differ
diff --git a/packages/docs/static/generated/articles-docs-browser-bundler-get-browser-composition.png b/packages/docs/static/generated/articles-docs-browser-bundler-get-browser-composition.png
new file mode 100644
index 0000000000..560c38e3d2
Binary files /dev/null and b/packages/docs/static/generated/articles-docs-browser-bundler-get-browser-composition.png differ
diff --git a/packages/docs/static/generated/articles-docs-browser-bundler-index.png b/packages/docs/static/generated/articles-docs-browser-bundler-index.png
new file mode 100644
index 0000000000..022963b8a7
Binary files /dev/null and b/packages/docs/static/generated/articles-docs-browser-bundler-index.png differ
diff --git a/packages/docs/static/generated/articles-docs-browser-bundler-load-browser-bundle.png b/packages/docs/static/generated/articles-docs-browser-bundler-load-browser-bundle.png
new file mode 100644
index 0000000000..4477737108
Binary files /dev/null and b/packages/docs/static/generated/articles-docs-browser-bundler-load-browser-bundle.png differ
diff --git a/packages/player-example/e2e/browser-bundler.test.ts b/packages/player-example/e2e/browser-bundler.test.ts
new file mode 100644
index 0000000000..05171e654f
--- /dev/null
+++ b/packages/player-example/e2e/browser-bundler.test.ts
@@ -0,0 +1,102 @@
+import {expect, test} from '@playwright/test';
+import {VERSION} from 'remotion/version';
+
+test('compiles a virtual root, plays its composition, imports a dependency and recovers from errors', async ({
+ page,
+}) => {
+ const pageErrors: string[] = [];
+ page.on('pageerror', (error) => pageErrors.push(error.message));
+
+ await page.goto('/');
+ await page
+ .getByRole('link', {name: 'Browser-compiled Player', exact: true})
+ .click();
+ const composition = page.getByRole('region', {name: 'Compiled composition'});
+ await expect(
+ composition.getByRole('heading', {
+ name: 'Compiled in the browser',
+ exact: true,
+ }),
+ ).toBeVisible();
+ await expect(
+ composition.getByText('Frame 0 of 138', {exact: true}),
+ ).toBeVisible();
+
+ await composition
+ .getByRole('button', {name: 'Play video', exact: true})
+ .click();
+ await expect(composition.getByText(/^Frame \d+ of 138$/)).not.toHaveText(
+ 'Frame 0 of 138',
+ );
+ await composition
+ .getByRole('button', {name: 'Pause video', exact: true})
+ .click();
+
+ const editor = page.getByRole('textbox', {name: 'Video.tsx source'});
+ const original = await editor.inputValue();
+ const dependencyRequest = page.waitForRequest((request) => {
+ const url = new URL(request.url());
+ return (
+ url.hostname === 'esm.sh' &&
+ url.pathname === `/@remotion/shapes@${VERSION}`
+ );
+ });
+ await editor.fill(
+ `import {Circle} from '@remotion/shapes';\n${original
+ .replace('{title}', '{title.toUpperCase()}')
+ .replace(
+ '<Orb accent={accent} />',
+ '<Circle radius={40} fill="red" role="img" aria-label="Bundled circle" />',
+ )}`,
+ );
+ await page.getByRole('button', {name: 'Compile', exact: true}).click();
+ expect(new URL((await dependencyRequest).url()).searchParams.has('dev')).toBe(
+ false,
+ );
+ await expect(
+ composition.getByRole('heading', {
+ name: 'COMPILED IN THE BROWSER',
+ exact: true,
+ }),
+ ).toBeVisible();
+ await expect(
+ composition.getByRole('img', {name: 'Bundled circle', exact: true}),
+ ).toBeVisible();
+
+ await editor.fill("import {Broken from 'remotion';");
+ await page.getByRole('button', {name: 'Compile', exact: true}).click();
+ const compilationError = page
+ .getByRole('alert')
+ .filter({hasText: 'Rspack compilation failed'});
+ await expect(compilationError).toBeVisible();
+ await expect(compilationError).toContainText('Video.tsx');
+
+ await editor.fill(original);
+ await page.getByRole('button', {name: 'Compile', exact: true}).click();
+ await expect(
+ composition.getByRole('heading', {
+ name: 'Compiled in the browser',
+ exact: true,
+ }),
+ ).toBeVisible();
+ await expect(
+ composition.getByText('Frame 0 of 138', {exact: true}),
+ ).toBeVisible();
+
+ await page
+ .getByRole('link', {name: 'All Player examples', exact: true})
+ .click();
+ await expect(
+ page.getByRole('heading', {name: 'Player examples', exact: true}),
+ ).toBeVisible();
+ await page
+ .getByRole('link', {name: 'Browser-compiled Player', exact: true})
+ .click();
+ await expect(
+ composition.getByRole('heading', {
+ name: 'Compiled in the browser',
+ exact: true,
+ }),
+ ).toBeVisible();
+ expect(pageErrors).toEqual([]);
+});
diff --git a/packages/player-example/next.config.mjs b/packages/player-example/next.config.mjs
new file mode 100644
index 0000000000..9c4fcab1ec
--- /dev/null
+++ b/packages/player-example/next.config.mjs
@@ -0,0 +1,24 @@
+/** @type {import('next').NextConfig} */
+const nextConfig = {
+ agentRules: false,
+ async headers() {
+ return ['/browser-bundler', '/_next/:path*'].map((source) => ({
+ source,
+ headers: [
+ {key: 'Cross-Origin-Opener-Policy', value: 'same-origin'},
+ {key: 'Cross-Origin-Embedder-Policy', value: 'require-corp'},
+ ],
+ }));
+ },
+ webpack(config) {
+ config.module.rules.push(
+ // A blob: WASI worker needs absolute URLs for importScripts().
+ {test: /browser-bundler-worker\.js$/, parser: {url: true}},
+ {test: /\.wasm$/, type: 'asset/resource'},
+ {test: /wasi-worker-browser\.mjs$/, type: 'asset/resource'},
+ );
+ return config;
+ },
+};
+
+export default nextConfig;
diff --git a/packages/player-example/package.json b/packages/player-example/package.json
index b37126b161..fcae7ea82b 100644
--- a/packages/player-example/package.json
+++ b/packages/player-example/package.json
@@ -11,6 +11,7 @@
"Shankhadeep Dey <[email protected]>"
],
"dependencies": {
+ "@remotion/browser-bundler": "workspace:*",
"@remotion/bundler": "workspace:*",
"@remotion/canvas": "workspace:*",
"@remotion/eslint-config-flat": "workspace:*",
@@ -25,15 +26,17 @@
"@remotion/media": "workspace:*"
},
"devDependencies": {
+ "@playwright/test": "1.55.1",
"eslint": "catalog:",
"prettier": "catalog:",
"@types/node": "catalog:"
},
"scripts": {
- "formatting": "prettier src pages --check",
- "lint": "eslint src pages",
- "dev": "next dev",
- "build-site": "next build",
- "testnextjs": "next build"
+ "formatting": "prettier src pages e2e playwright.config.ts next.config.mjs --check",
+ "lint": "eslint src pages e2e playwright.config.ts next.config.mjs",
+ "dev": "next dev --webpack",
+ "build-site": "next build --webpack",
+ "testnextjs": "next build --webpack",
+ "testbrowserbundler": "playwright test"
}
}
diff --git a/packages/player-example/pages/browser-bundler.tsx b/packages/player-example/pages/browser-bundler.tsx
new file mode 100644
index 0000000000..9668384369
--- /dev/null
+++ b/packages/player-example/pages/browser-bundler.tsx
@@ -0,0 +1,14 @@
+import dynamic from 'next/dynamic';
+
+const BrowserBundlerPage = dynamic(
+ () =>
+ import('../src/BrowserBundlerExample').then(
+ (module) => module.BrowserBundlerExample,
+ ),
+ {
+ ssr: false,
+ loading: () => <p role="status">Loading the browser compiler example…</p>,
+ },
+);
+
+export default BrowserBundlerPage;
diff --git a/packages/player-example/pages/index.tsx b/packages/player-example/pages/index.tsx
index cc258a5066..94cdada93e 100644
--- a/packages/player-example/pages/index.tsx
+++ b/packages/player-example/pages/index.tsx
@@ -12,6 +12,12 @@ const examples = [
name: 'Canvas layers',
description: 'A Player with a live list of mounted timeline layers.',
},
+ {
+ href: '/browser-bundler',
+ name: 'Browser-compiled Player',
+ description:
+ 'Compile an editable virtual Remotion project and play a registered composition.',
+ },
{
href: '/audio',
name: 'Audio',
@@ -64,7 +70,20 @@ function Index() {
<ul style={{lineHeight: 1.5, paddingLeft: 24}}>
{examples.map((example) => (
<li key={example.href} style={{marginBottom: 16}}>
- <Link href={example.href}>{example.name}</Link>
+ <Link
+ href={example.href}
+ onNavigate={(event) => {
+ if (example.href !== '/browser-bundler') {
+ return;
+ }
+
+ // COOP/COEP apply to documents, not client-side navigations.
+ event.preventDefault();
+ window.location.assign(example.href);
+ }}
+ >
+ {example.name}
+ </Link>
<div style={{color: '#555'}}>{example.description}</div>
</li>
))}
diff --git a/packages/player-example/playwright.config.ts b/packages/player-example/playwright.config.ts
new file mode 100644
index 0000000000..caf6e0c9a7
--- /dev/null
+++ b/packages/player-example/playwright.config.ts
@@ -0,0 +1,28 @@
+import {defineConfig, devices} from '@playwright/test';
+
+const port = 3137;
+
+export default defineConfig({
+ testDir: './e2e',
+ outputDir: './node_modules/.cache/browser-bundler-test-results',
+ timeout: 120_000,
+ expect: {timeout: 60_000},
+ fullyParallel: false,
+ workers: 1,
+ use: {
+ baseURL: `http://localhost:${port}`,
+ trace: 'retain-on-failure',
+ },
+ projects: [
+ {
+ name: 'chromium',
+ use: {...devices['Desktop Chrome']},
+ },
+ ],
+ webServer: {
+ command: `bun run testnextjs && bunx next start --port ${port}`,
+ url: `http://localhost:${port}`,
+ reuseExistingServer: !process.env.CI,
+ timeout: 180_000,
+ },
+});
diff --git a/packages/player-example/src/BrowserBundlerExample.tsx b/packages/player-example/src/BrowserBundlerExample.tsx
new file mode 100644
index 0000000000..6828a52eba
--- /dev/null
+++ b/packages/player-example/src/BrowserBundlerExample.tsx
@@ -0,0 +1,308 @@
+import {
+ BrowserBundlerError,
+ createBrowserBundler,
+ type VirtualProject,
+} from '@remotion/browser-bundler';
+import {
+ getBrowserComposition,
+ loadBrowserBundle,
+ type BrowserComposition,
+} from '@remotion/browser-bundler/runtime';
+import {Player} from '@remotion/player';
+import Link from 'next/link';
+import React, {useCallback, useEffect, useRef, useState} from 'react';
+
+const initialSource = `import React from 'react';
+import {AbsoluteFill, useCurrentFrame, useVideoConfig} from 'remotion';
+import {Orb} from './Orb';
+
+export const Video: React.FC<{title: string; accent: string}> = ({title, accent}) => {
+ const frame = useCurrentFrame();
+ const {fps, durationInFrames} = useVideoConfig();
+
+ return (
+ <AbsoluteFill style={{
+ backgroundColor: '#0f172a', color: 'white', fontFamily: 'sans-serif',
+ justifyContent: 'center', padding: 80,
+ }}>
+ <Orb accent={accent} />
+ <div style={{position: 'relative', transform: \`translateY(\${Math.sin(frame / fps) * 12}px)\`}}>
+ <h1 style={{fontSize: 76, margin: 0}}>{title}</h1>
+ <p style={{fontSize: 28, color: accent}}>Frame {frame} of {durationInFrames}</p>
+ </div>
+ </AbsoluteFill>
+ );
+};
+`;
+
+const project: VirtualProject = {
+ rootDir: '/browser-demo',
+ entryPoint: '/browser-demo/src/index.ts',
+ files: {
+ '/browser-demo/src/index.ts': `import {registerRoot} from 'remotion';
+import {Root} from './Root';
+registerRoot(Root);
+`,
+ '/browser-demo/src/Root.tsx': `import React from 'react';
+import {Composition, Folder} from 'remotion';
+import {Video} from './Video';
+
+export const Root = () => (
+ <Folder name="Browser">
+ <Composition
+ id="BrowserDemo"
+ component={Video}
+ width={1280}
+ height={720}
+ fps={30}
+ durationInFrames={150}
+ defaultProps={{title: 'Compiled in the browser', accent: '#60a5fa'}}
+ calculateMetadata={({props}) => ({
+ durationInFrames: Math.max(90, props.title.length * 6),
+ props: {...props, title: props.title.trim()},
+ })}
+ />
+ </Folder>
+);
+`,
+ '/browser-demo/src/Video.tsx': initialSource,
+ '/browser-demo/src/Orb.tsx': `import React from 'react';
+import {useCurrentFrame} from 'remotion';
+
+export const Orb: React.FC<{accent: string}> = ({accent}) => {
+ const frame = useCurrentFrame();
+ return <div style={{
+ position: 'absolute', width: 450, height: 450, borderRadius: '50%',
+ right: -80, top: -80, backgroundColor: accent, opacity: 0.3,
+ transform: \`translateY(\${Math.sin(frame / 25) * 100}px)\`,
+ }} />;
+};
+`,
+ },
+};
+
+const getCompilationErrorMessage = (error: unknown): string => {
+ if (error instanceof BrowserBundlerError) {
+ return [error.message, ...error.diagnostics].join('\n\n');
+ }
+
+ return error instanceof Error ? error.message : String(error);
+};
+
+type CompilationState =
+ | {type: 'loading'}
+ | {type: 'error'; message: string}
+ | {
+ type: 'ready';
+ composition: BrowserComposition;
+ revision: number;
+ };
+
+export const BrowserBundlerExample: React.FC = () => {
+ const [source, setSource] = useState(initialSource);
+ const [state, setState] = useState<CompilationState>({type: 'loading'});
+ const [progress, setProgress] = useState<string | null>(null);
+ const [warnings, setWarnings] = useState<string[]>([]);
+ const bundlerRef = useRef<ReturnType<typeof createBrowserBundler> | null>(
+ null,
+ );
+ const requestId = useRef(0);
+ const abortRef = useRef<AbortController | null>(null);
+
+ const compile = useCallback(async (videoSource: string) => {
+ const bundler = bundlerRef.current;
+ if (!bundler) {
+ return;
+ }
+
+ const revision = ++requestId.current;
+ abortRef.current?.abort();
+ const controller = new AbortController();
+ abortRef.current = controller;
+ setState({type: 'loading'});
+ setWarnings([]);
+ setProgress(null);
+
+ try {
+ const bundle = await bundler.bundle({
+ project: {
+ ...project,
+ files: {
+ ...project.files,
+ '/browser-demo/src/Video.tsx': videoSource,
+ },
+ },
+ });
+ if (controller.signal.aborted || revision !== requestId.current) {
+ return;
+ }
+
+ setWarnings(bundle.warnings);
+ const root = loadBrowserBundle({bundle});
+ const composition = await getBrowserComposition({
+ root,
+ compositionId: 'BrowserDemo',
+ inputProps: {},
+ signal: controller.signal,
+ });
+ if (controller.signal.aborted || revision !== requestId.current) {
+ return;
+ }
+
+ setState({type: 'ready', composition, revision});
+ } catch (error) {
+ if (controller.signal.aborted || revision !== requestId.current) {
+ return;
+ }
+
+ setState({
+ type: 'error',
+ message: getCompilationErrorMessage(error),
+ });
+ }
+ }, []);
+
+ useEffect(() => {
+ let disposed = false;
+ try {
+ const bundler = createBrowserBundler({
+ onProgress: ({loadedBytes, totalBytes}) => {
+ if (disposed) {
+ return;
+ }
+
+ setProgress(
+ totalBytes
+ ? `Loading compiler: ${Math.round((loadedBytes / totalBytes) * 100)}%`
+ : `Loading compiler: ${(loadedBytes / 1024 / 1024).toFixed(1)} MB`,
+ );
+ },
+ });
+ bundlerRef.current = bundler;
+ void compile(initialSource);
+
+ return () => {
+ disposed = true;
+ abortRef.current?.abort();
+ bundlerRef.current = null;
+ bundler.dispose();
+ };
+ } catch (error) {
+ setState({
+ type: 'error',
+ message: getCompilationErrorMessage(error),
+ });
+ }
+ }, [compile]);
+
+ return (
+ <main
+ style={{
+ fontFamily: 'sans-serif',
+ margin: '40px auto',
+ maxWidth: 1000,
+ padding: '0 20px',
+ }}
+ >
+ <Link
+ href="/"
+ onNavigate={(event) => {
+ // Leave the isolated document when returning to other examples.
+ event.preventDefault();
+ window.location.assign('/');
+ }}
+ >
+ All Player examples
+ </Link>
+ <h1>Browser-compiled Player</h1>
+ <p>
+ A virtual Remotion project calls <code>registerRoot()</code>. This page
+ selects <code>BrowserDemo</code> and uses its registered component,
+ default props, and calculated metadata in a Player.
+ </p>
+ <p>
+ Edit the source and compile again. Only run code you trust: the compiled
+ code runs in this page, not in a sandbox.
+ </p>
+ <form
+ onSubmit={(event) => {
+ event.preventDefault();
+ void compile(source);
+ }}
+ >
+ <label htmlFor="browser-video-source">
+ <strong>Video.tsx source</strong>
+ </label>
+ <textarea
+ id="browser-video-source"
+ value={source}
+ onChange={(event) => setSource(event.target.value)}
+ rows={17}
+ spellCheck={false}
+ style={{
+ boxSizing: 'border-box',
+ display: 'block',
+ fontFamily: 'monospace',
+ fontSize: 13,
+ lineHeight: 1.5,
+ margin: '8px 0 12px',
+ padding: 12,
+ width: '100%',
+ }}
+ />
+ <button type="submit">Compile</button>
+ </form>
+ <p role="status" aria-live="polite">
+ {state.type === 'loading'
+ ? (progress ?? 'Compiling the virtual project...')
+ : state.type === 'ready'
+ ? 'BrowserDemo compiled successfully.'
+ : 'Compilation failed.'}
+ </p>
+ {warnings.length > 0 ? (
+ <section aria-label="Compiler warnings">
+ <h2>Warnings</h2>
+ <ul>
+ {warnings.map((warning, index) => (
+ <li key={`${index}-${warning}`}>
+ <pre style={{whiteSpace: 'pre-wrap'}}>{warning}</pre>
+ </li>
+ ))}
+ </ul>
+ </section>
+ ) : null}
+ {state.type === 'error' ? (
+ <pre role="alert" style={{color: '#b91c1c', whiteSpace: 'pre-wrap'}}>
+ {state.message}
+ </pre>
+ ) : null}
+ {state.type === 'ready' ? (
+ <section aria-label="Compiled composition">
+ <p>
+ {state.composition.width} x {state.composition.height} /{' '}
+ {state.composition.fps} fps / {state.composition.durationInFrames}{' '}
+ frames
+ </p>
+ <Player
+ key={state.revision}
+ component={state.composition.component}
+ inputProps={state.composition.props}
+ compositionWidth={state.composition.width}
+ compositionHeight={state.composition.height}
+ fps={state.composition.fps}
+ durationInFrames={state.composition.durationInFrames}
+ controls
+ loop
+ acknowledgeRemotionLicense
+ errorFallback={({error}) => (
+ <div role="alert">
+ Could not play the composition: {error.message}
+ </div>
+ )}
+ style={{width: '100%'}}
+ />
+ </section>
+ ) : null}
+ </main>
+ );
+};
diff --git a/packages/player-example/tsconfig.json b/packages/player-example/tsconfig.json
index c64bf17908..30cbbd8c72 100644
--- a/packages/player-example/tsconfig.json
+++ b/packages/player-example/tsconfig.json
@@ -3,7 +3,8 @@
"./src/**/*",
"./pages/index.tsx",
"./pages/player.tsx",
- "./pages/canvas.tsx"
+ "./pages/canvas.tsx",
+ "./pages/browser-bundler.tsx"
],
"compilerOptions": {
"strict": true,
@@ -17,13 +18,16 @@
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
- "moduleResolution": "node",
+ "moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"incremental": true
},
"references": [
+ {
+ "path": "../browser-bundler"
+ },
{
"path": "../canvas"
},
diff --git a/packages/studio-shared/src/package-info.ts b/packages/studio-shared/src/package-info.ts
index b0953ac3e1..b58ee6e2e3 100644
--- a/packages/studio-shared/src/package-info.ts
+++ b/packages/studio-shared/src/package-info.ts
@@ -10,6 +10,7 @@ const allPackages = [
'bugs',
'brand',
'bundler',
+ 'browser-bundler',
'browser-studio',
'canvas',
'claude-code-plugin',
@@ -186,6 +187,7 @@ export const descriptions: {[key in Pkgs]: string | null} = {
core: 'Make videos programmatically',
lambda: 'Render Remotion videos on AWS Lambda',
bundler: 'Bundle Remotion compositions using Webpack',
+ 'browser-bundler': 'Compile virtual Remotion projects in the browser',
'browser-studio': 'Run Remotion Studio in the browser',
canvas: 'Headless primitives for Remotion authoring interfaces',
'studio-codemods': 'Shared codemods for Remotion Studio',
@@ -299,6 +301,7 @@ export const installableMap: {[key in Pkgs]: boolean} = {
bugs: false,
brand: false,
bundler: false,
+ 'browser-bundler': false,
'browser-studio': false,
canvas: false,
cli: false,
@@ -426,6 +429,7 @@ export const apiDocs: {[key in Pkgs]: string | null} = {
core: 'https://www.remotion.dev/docs/remotion',
lambda: 'https://www.remotion.dev/docs/lambda',
bundler: 'https://www.remotion.dev/docs/bundler',
+ 'browser-bundler': 'https://www.remotion.dev/docs/browser-bundler',
'browser-studio': null,
canvas: null,
'studio-codemods': null,
diff --git a/tsconfig.json b/tsconfig.json
index 151c1280dd..3a7a01c3f6 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -24,6 +24,9 @@
{
"path": "./packages/bundler"
},
+ {
+ "path": "./packages/browser-bundler"
+ },
{
"path": "./packages/browser-studio"
},
diff --git a/turbo.json b/turbo.json
index d3cd5a4102..09bf50627c 100644
--- a/turbo.json
+++ b/turbo.json
@@ -67,6 +67,9 @@
"testbrowserstudio": {
"dependsOn": ["@remotion/browser-studio#make"]
},
+ "testbrowserbundler": {
+ "dependsOn": ["^make"]
+ },
"testlayoututils": {
"dependsOn": ["@remotion/layout-utils#make"]
},