Skip to content

🎥 Make videos programmatically with React

`@remotion/browser-studio`: Enable HMR (#9851)

Jonny Burgerd2698c7467b3
diff --git a/bun.lock b/bun.lock
index f5974e4f8a..f75f8aaee1 100644
--- a/bun.lock
+++ b/bun.lock
@@ -140,10 +140,12 @@
"@remotion/studio-shared": "workspace:*",
"@rspack/browser": "2.1.1",
"fflate": "0.8.2",
+ "react-refresh": "0.18.0",
},
"devDependencies": {
"@remotion/eslint-config-internal": "workspace:*",
"@remotion/studio": "workspace:*",
+ "@rspack/plugin-react-refresh": "1.6.1",
"@types/react": "catalog:",
"@types/react-dom": "catalog:",
"@typescript/native-preview": "catalog:",
diff --git a/packages/browser-studio/bundle.ts b/packages/browser-studio/bundle.ts
index 906c9a6300..48fee4834a 100644
--- a/packages/browser-studio/bundle.ts
+++ b/packages/browser-studio/bundle.ts
@@ -1,6 +1,7 @@
import path from 'path';
import {build} from 'bun';
import {getBrowserStudioDependencyVersionsForBuild} from './src/dev/get-dependency-versions-for-build';
+import {getBrowserStudioReactRefreshFilesForBuild} from './src/dev/get-react-refresh-files-for-build';
import {getBrowserStudioSetupEnvironmentForBuild} from './src/dev/get-setup-environment-for-build';
import {studioRenderEntryExternal} from './src/dev/studio-render-entry-external';
@@ -10,16 +11,18 @@ if (process.env.NODE_ENV !== 'production') {
console.time('Generated.');
const dependencyVersions = getBrowserStudioDependencyVersionsForBuild();
+const reactRefreshFiles = getBrowserStudioReactRefreshFilesForBuild();
const setupEnvironment = getBrowserStudioSetupEnvironmentForBuild();
const output = await build({
entrypoints: [
'src/index.tsx',
'src/browser-studio-worker.ts',
- 'src/browser-studio-render-entry.ts',
+ 'src/browser-studio-preview-entry.ts',
],
naming: '[name].mjs',
define: {
__BROWSER_STUDIO_DEPENDENCY_VERSIONS__: JSON.stringify(dependencyVersions),
+ __BROWSER_STUDIO_REACT_REFRESH_FILES__: JSON.stringify(reactRefreshFiles),
__BROWSER_STUDIO_SETUP_ENVIRONMENT__: JSON.stringify(setupEnvironment),
},
external: [
@@ -41,11 +44,11 @@ const externalStudioSharedImport =
for (const file of output.outputs) {
const str = await file.text();
if (
- path.basename(file.path) === 'browser-studio-render-entry.mjs' &&
+ path.basename(file.path) === 'browser-studio-preview-entry.mjs' &&
externalStudioSharedImport.test(str)
) {
throw new Error(
- 'Browser Studio must bundle @remotion/studio-shared into its render entry so it cannot link against an incompatible published version.',
+ 'Browser Studio must bundle @remotion/studio-shared into its preview entry so it cannot link against an incompatible published version.',
);
}
diff --git a/packages/browser-studio/package.json b/packages/browser-studio/package.json
index a7f771efd5..7473e95223 100644
--- a/packages/browser-studio/package.json
+++ b/packages/browser-studio/package.json
@@ -29,7 +29,8 @@
"@remotion/studio-codemods": "workspace:*",
"@remotion/studio-shared": "workspace:*",
"@rspack/browser": "2.1.1",
- "fflate": "0.8.2"
+ "fflate": "0.8.2",
+ "react-refresh": "0.18.0"
},
"exports": {
".": {
@@ -45,6 +46,7 @@
"./package.json": "./package.json"
},
"devDependencies": {
+ "@rspack/plugin-react-refresh": "1.6.1",
"@remotion/studio": "workspace:*",
"@remotion/eslint-config-internal": "workspace:*",
"@types/react": "catalog:",
diff --git a/packages/browser-studio/src/BrowserStudio.tsx b/packages/browser-studio/src/BrowserStudio.tsx
index 2028e03075..59e7418182 100644
--- a/packages/browser-studio/src/BrowserStudio.tsx
+++ b/packages/browser-studio/src/BrowserStudio.tsx
@@ -1,5 +1,9 @@
import {studioHtml} from '@remotion/studio-shared/studio-html';
import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
+import {
+ createBrowserStudioHmrAssetManager,
+ type BrowserStudioHmrBridge,
+} from './browser-studio-hmr-assets';
import {createBrowserStudioOperations} from './browser-studio-operations';
import {
areBrowserStudioProjectsEqual,
@@ -23,11 +27,15 @@ const makeInitialState = (): CompileState => ({
const BROWSER_STUDIO_OPERATIONS_READY_EVENT =
'remotion-browser-studio-operations-ready';
-const localStudioRenderEntry = new URL(
- './browser-studio-render-entry.mjs',
+const localStudioPreviewEntry = new URL(
+ './browser-studio-preview-entry.mjs',
import.meta.url,
).href;
+type BrowserStudioContentWindow = Window & {
+ remotion_browserStudioHmr: BrowserStudioHmrBridge;
+};
+
const containerStyle: React.CSSProperties = {
backgroundColor: '#111111',
color: '#ffffff',
@@ -80,6 +88,13 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({
const [iframeHtml, setIframeHtml] = useState<string | null>(null);
const [iframeLoaded, setIframeLoaded] = useState(false);
const iframeRef = useRef<HTMLIFrameElement | null>(null);
+ const lastWrittenDocumentRef = useRef<Document | null>(null);
+ const lastWrittenHtmlRef = useRef<string | null>(null);
+ const workerRef = useRef<Worker | null>(null);
+ const lastSentProjectRef = useRef<BrowserStudioProps['project'] | null>(null);
+ const bundleUrlRef = useRef<string | null>(null);
+ const onCompileStateChangeRef = useRef(onCompileStateChange);
+ onCompileStateChangeRef.current = onCompileStateChange;
const publicFileManager = useMemo(
() =>
createBrowserStudioPublicFileManager({
@@ -92,6 +107,17 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({
useEffect(() => {
return () => publicFileManager.dispose();
}, [publicFileManager]);
+ const hmrAssetManager = useMemo(
+ () =>
+ createBrowserStudioHmrAssetManager({
+ createObjectUrl: URL.createObjectURL,
+ revokeObjectUrl: URL.revokeObjectURL,
+ }),
+ [],
+ );
+ useEffect(() => {
+ return () => hmrAssetManager.dispose();
+ }, [hmrAssetManager]);
const [editedProject, setEditedProject] = useState<{
project: BrowserStudioProps['project'];
@@ -158,10 +184,11 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({
useEffect(() => {
setIframeLoaded(false);
+ lastWrittenDocumentRef.current = null;
+ lastWrittenHtmlRef.current = null;
}, [iframeSrc]);
useEffect(() => {
- let cleanupBundle: string | null = null;
let didCancel = false;
const setCompileState = (nextState: CompileState) => {
@@ -170,15 +197,18 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({
}
setState(nextState);
- onCompileStateChange?.(nextState);
+ onCompileStateChangeRef.current?.(nextState);
};
+ setIframeHtml(null);
setCompileState({status: 'compiling'});
const worker = new Worker(
new URL('./browser-studio-worker.mjs', import.meta.url),
{type: 'module'},
);
+ workerRef.current = worker;
+ lastSentProjectRef.current = activeProjectRef.current;
worker.onmessage = (
event: MessageEvent<BrowserStudioWorkerCompileResponse>,
@@ -194,18 +224,38 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({
return;
}
- cleanupBundle = URL.createObjectURL(
+ if (response.type === 'building') {
+ setCompileState({status: 'compiling'});
+ return;
+ }
+
+ if (response.type === 'hmr-update') {
+ hmrAssetManager.updateAssets(response.assets);
+ browserStudioOperations.emitEvent({
+ hmrEvent: response.hmrEvent,
+ type: 'hmr',
+ });
+ setCompileState({status: 'compiled', warnings: response.warnings});
+ return;
+ }
+
+ if (bundleUrlRef.current) {
+ URL.revokeObjectURL(bundleUrlRef.current);
+ }
+
+ bundleUrlRef.current = URL.createObjectURL(
new Blob([response.bundle], {type: 'text/javascript'}),
);
+ const currentProject = activeProjectRef.current;
const html = studioHtml({
audioLatencyHint: 'playback',
- bundleScriptUrl: cleanupBundle,
+ bundleScriptUrl: bundleUrlRef.current,
completedClientRenders: [],
editorName: null,
envVariables: {NODE_ENV: 'development'},
gitSource: null,
- includeFavicon: false,
+ includeFavicon: true,
inputProps: {},
installedDependencies: null,
logLevel: 'info',
@@ -215,13 +265,13 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({
projectName: 'template-blank',
publicFiles: publicFileManager.getStaticFiles({
lastModifiedByPath: null,
- project: activeProject,
+ project: currentProject,
}),
publicFolderExists: null,
fileSystemPlatform: null,
publicPath: '',
readOnlyStudio: readOnly,
- remotionRoot: activeProject.rootDir,
+ remotionRoot: currentProject.rootDir,
renderDefaults: undefined,
renderQueue: [],
sampleRate: null,
@@ -251,7 +301,7 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({
};
const request: BrowserStudioWorkerCompileRequest = {
- type: 'compile',
+ type: 'init',
dependencyResolutions: Object.fromEntries(
Object.entries(browserStudioDependencyVersions).map(
([name, version]) => {
@@ -261,35 +311,72 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({
}
if (name === '@remotion/studio') {
- return [name, {url: localStudioRenderEntry}];
+ return [name, {url: localStudioPreviewEntry}];
}
return [name, null];
},
),
),
- project: activeProject,
+ project: activeProjectRef.current,
};
worker.postMessage(request);
return () => {
didCancel = true;
+ workerRef.current = null;
+ lastSentProjectRef.current = null;
worker.terminate();
-
- if (cleanupBundle) {
- URL.revokeObjectURL(cleanupBundle);
- }
};
}, [
+ browserStudioOperations,
dependencyResolver,
- iframeSrc,
- onCompileStateChange,
- activeProject,
+ hmrAssetManager,
publicFileManager,
readOnly,
+ activeProject.entryPoint,
+ activeProject.rootDir,
]);
+ useEffect(() => {
+ const worker = workerRef.current;
+ const lastSentProject = lastSentProjectRef.current;
+ if (
+ !worker ||
+ !lastSentProject ||
+ areBrowserStudioProjectsEqual(lastSentProject, activeProject)
+ ) {
+ return;
+ }
+
+ lastSentProjectRef.current = activeProject;
+ worker.postMessage({
+ project: activeProject,
+ type: 'update-project',
+ } satisfies BrowserStudioWorkerCompileRequest);
+ }, [activeProject]);
+
+ useEffect(() => {
+ browserStudioOperations.emitEvent({
+ files: publicFileManager.getStaticFiles({
+ lastModifiedByPath: null,
+ project: activeProject,
+ }),
+ folderExists: '/public',
+ type: 'new-public-folder',
+ });
+ }, [activeProject, browserStudioOperations, publicFileManager]);
+
+ useEffect(() => {
+ return () => {
+ if (bundleUrlRef.current) {
+ URL.revokeObjectURL(bundleUrlRef.current);
+ bundleUrlRef.current = null;
+ }
+ };
+ }, []);
+
useEffect(() => {
if (!iframeHtml) {
return;
@@ -306,19 +393,40 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({
return;
}
+ if (
+ lastWrittenDocumentRef.current === contentDocument &&
+ lastWrittenHtmlRef.current === iframeHtml
+ ) {
+ return;
+ }
+
+ lastWrittenDocumentRef.current = contentDocument;
+ lastWrittenHtmlRef.current = iframeHtml;
+
contentDocument.open();
- contentDocument.write(iframeHtml);
+ (contentWindow as BrowserStudioContentWindow).remotion_browserStudioHmr =
+ hmrAssetManager.bridge;
contentWindow.remotion_browserStudio = browserStudioOperations;
+ contentDocument.write(iframeHtml);
contentDocument.close();
const activeContentWindow = iframe.contentWindow;
if (activeContentWindow) {
+ (
+ activeContentWindow as BrowserStudioContentWindow
+ ).remotion_browserStudioHmr = hmrAssetManager.bridge;
activeContentWindow.remotion_browserStudio = browserStudioOperations;
activeContentWindow.dispatchEvent(
new Event(BROWSER_STUDIO_OPERATIONS_READY_EVENT),
);
}
- }, [browserStudioOperations, iframeHtml, iframeLoaded, iframeSrc]);
+ }, [
+ browserStudioOperations,
+ hmrAssetManager,
+ iframeHtml,
+ iframeLoaded,
+ iframeSrc,
+ ]);
return (
<div style={containerStyle}>
diff --git a/packages/browser-studio/src/browser-studio-hmr-assets.ts b/packages/browser-studio/src/browser-studio-hmr-assets.ts
new file mode 100644
index 0000000000..d6d547677f
--- /dev/null
+++ b/packages/browser-studio/src/browser-studio-hmr-assets.ts
@@ -0,0 +1,88 @@
+import type {BrowserStudioHmrAsset} from './types';
+
+export type BrowserStudioHmrBridge = {
+ getManifest: (name: string) => Promise<object | undefined>;
+ resolveScriptUrl: (name: string) => string;
+};
+
+const getAssetName = (nameOrUrl: string) => {
+ const url = new URL(nameOrUrl, 'https://remotion.invalid');
+ return url.pathname.split('/').at(-1) ?? '';
+};
+
+export const createBrowserStudioHmrAssetManager = ({
+ createObjectUrl,
+ revokeObjectUrl,
+}: {
+ createObjectUrl: (blob: Blob) => string;
+ revokeObjectUrl: (url: string) => void;
+}) => {
+ const assets = new Map<string, {content: string; objectUrl: string | null}>();
+
+ const updateAssets = (newAssets: BrowserStudioHmrAsset[]) => {
+ const nextAssetNames = new Set(
+ newAssets.map((asset) => getAssetName(asset.name)),
+ );
+ for (const [name, asset] of assets) {
+ if (nextAssetNames.has(name)) {
+ continue;
+ }
+
+ if (asset.objectUrl) {
+ revokeObjectUrl(asset.objectUrl);
+ }
+
+ assets.delete(name);
+ }
+
+ for (const asset of newAssets) {
+ const name = getAssetName(asset.name);
+ const previous = assets.get(name);
+ if (previous?.objectUrl) {
+ revokeObjectUrl(previous.objectUrl);
+ }
+
+ assets.set(name, {content: asset.content, objectUrl: null});
+ }
+ };
+
+ const bridge: BrowserStudioHmrBridge = {
+ getManifest: (name) => {
+ const asset = assets.get(getAssetName(name));
+ if (!asset) {
+ return Promise.resolve(undefined);
+ }
+
+ return Promise.resolve(JSON.parse(asset.content) as object);
+ },
+ resolveScriptUrl: (name) => {
+ const assetName = getAssetName(name);
+ const asset = assets.get(assetName);
+ if (!asset) {
+ throw new Error(`Missing Browser Studio HMR asset: ${assetName}`);
+ }
+
+ if (!asset.objectUrl) {
+ asset.objectUrl = createObjectUrl(
+ new Blob([asset.content], {type: 'text/javascript'}),
+ );
+ }
+
+ return asset.objectUrl;
+ },
+ };
+
+ return {
+ bridge,
+ dispose: () => {
+ for (const asset of assets.values()) {
+ if (asset.objectUrl) {
+ revokeObjectUrl(asset.objectUrl);
+ }
+ }
+
+ assets.clear();
+ },
+ updateAssets,
+ };
+};
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.ts
index e6f5a54708..78f3396a50 100644
--- a/packages/browser-studio/src/browser-studio-operations.ts
+++ b/packages/browser-studio/src/browser-studio-operations.ts
@@ -5,6 +5,7 @@ import {
} from '@remotion/studio-codemods';
import type {
BrowserStudioOperations,
+ EventSourceEvent,
InsertJsxElementResponse,
} from '@remotion/studio-shared';
import {createBrowserStudioProjectController} from './browser-studio-project-controller';
@@ -14,6 +15,7 @@ import type {VirtualProject} from './types';
export {insertSolidIntoProject} from '@remotion/studio-codemods';
export type BrowserStudioOperationsController = BrowserStudioOperations & {
+ emitEvent: (event: EventSourceEvent) => void;
resetHistory: () => void;
};
@@ -45,6 +47,7 @@ export const createBrowserStudioOperations = ({
project: getProject(),
}),
),
+ emitEvent: controller.emitEvent,
findInFile: controller.findInFile,
getFileSource: controller.getFileSource,
getCompositionFile: (compositionId) =>
diff --git a/packages/browser-studio/src/browser-studio-preview-entry.ts b/packages/browser-studio/src/browser-studio-preview-entry.ts
new file mode 100644
index 0000000000..97cd66a1fd
--- /dev/null
+++ b/packages/browser-studio/src/browser-studio-preview-entry.ts
@@ -0,0 +1 @@
+import '@remotion/studio/previewEntry';
diff --git a/packages/browser-studio/src/browser-studio-project-controller.ts b/packages/browser-studio/src/browser-studio-project-controller.ts
index a77d9f0367..6db154cfa8 100644
--- a/packages/browser-studio/src/browser-studio-project-controller.ts
+++ b/packages/browser-studio/src/browser-studio-project-controller.ts
@@ -273,6 +273,7 @@ const getFileSource = ({
export type BrowserStudioProjectController = {
applyMutation: (mutation: ProjectMutation) => VirtualProject;
deleteStaticFile: BrowserStudioOperations['deleteStaticFile'];
+ emitEvent: (event: EventSourceEvent) => void;
findInFile: BrowserStudioOperations['findInFile'];
getFileSource: BrowserStudioOperations['getFileSource'];
redo: BrowserStudioOperations['redo'];
@@ -310,6 +311,7 @@ export const createBrowserStudioProjectController = ({
const redoStack: HistoryEntry[] = [];
const listeners = new Set<(event: EventSourceEvent) => void>();
const lastModifiedByPath = new Map<string, number>();
+ let latestHmrEvent: Extract<EventSourceEvent, {type: 'hmr'}> | null = null;
let publicFileRevision = 0;
const getUndoRedoEvent = (): EventSourceEvent => ({
@@ -328,6 +330,10 @@ export const createBrowserStudioProjectController = ({
});
const emit = (event: EventSourceEvent) => {
+ if (event.type === 'hmr' && listeners.size === 0) {
+ latestHmrEvent = event;
+ }
+
for (const listener of listeners) {
listener(event);
}
@@ -438,6 +444,7 @@ export const createBrowserStudioProjectController = ({
return Promise.reject(error);
}
},
+ emitEvent: emit,
findInFile: (request) => {
const contents = getFileSource({
fileName: request.fileName,
@@ -497,6 +504,10 @@ export const createBrowserStudioProjectController = ({
redoFile: redoStack.at(-1)?.fileName ?? null,
});
listener(getPublicFilesEvent());
+ if (latestHmrEvent) {
+ listener(latestHmrEvent);
+ latestHmrEvent = null;
+ }
return () => {
listeners.delete(listener);
diff --git a/packages/browser-studio/src/browser-studio-render-entry.ts b/packages/browser-studio/src/browser-studio-render-entry.ts
deleted file mode 100644
index 5f23ac7089..0000000000
--- a/packages/browser-studio/src/browser-studio-render-entry.ts
+++ /dev/null
@@ -1 +0,0 @@
-import '@remotion/studio/renderEntry';
diff --git a/packages/browser-studio/src/browser-studio-worker.ts b/packages/browser-studio/src/browser-studio-worker.ts
index 8c1c942d42..2385bd5fe2 100644
--- a/packages/browser-studio/src/browser-studio-worker.ts
+++ b/packages/browser-studio/src/browser-studio-worker.ts
@@ -1,3 +1,4 @@
+import type {HotMiddlewareMessage} from '@remotion/studio-shared';
import {getStudioEntryPoints} from '@remotion/studio-shared/studio-entry-points';
import type * as RspackBrowser from '@rspack/browser';
import {browserStudioDependencyVersions} from './dependency-versions';
@@ -5,6 +6,7 @@ import {studioRenderEntryExternal} from './dev/studio-render-entry-external';
import type {
BrowserStudioDependencyResolution,
BrowserStudioError,
+ BrowserStudioHmrAsset,
BrowserStudioWorkerCompileRequest,
BrowserStudioWorkerCompileResponse,
VirtualProject,
@@ -14,75 +16,68 @@ import {
getBrowserStudioVirtualFiles,
} from './virtual-files';
-type RspackStats = {
- hasErrors: () => boolean;
- toJson: (options: unknown) => {
- assets?: {name?: string}[];
- errors?: {message?: string}[];
- warnings?: {message?: string}[];
- };
-};
-
type BuiltinMemFs = typeof RspackBrowser.builtinMemFs;
+type Compiler = RspackBrowser.Compiler;
+
+type CompilerSession = {
+ builtinMemFs: BuiltinMemFs;
+ compiler: Compiler;
+ initialCompiled: boolean;
+ modifiedFiles: ReadonlySet<string> | undefined;
+ project: VirtualProject;
+ queuedProject: VirtualProject | null;
+ removedFiles: ReadonlySet<string> | undefined;
+ running: boolean;
+};
let rspackBrowserPromise: Promise<typeof RspackBrowser> | null = null;
+let compilerSession: CompilerSession | null = null;
const loadRspackBrowser = () => {
const workerGlobal = globalThis as Record<string, unknown>;
-
workerGlobal.window ??= globalThis;
rspackBrowserPromise ??= import('@rspack/browser');
return rspackBrowserPromise;
};
+const normalizePath = (path: string) =>
+ path.startsWith('/') ? path : `/${path}`;
+
const makeBrowserStudioError = (
error: unknown,
diagnostics?: string[],
): BrowserStudioError => {
if (error instanceof Error) {
return {
+ diagnostics,
message: error.message,
stack: error.stack,
- diagnostics,
};
}
- return {
- message: String(error),
- diagnostics,
- };
+ return {diagnostics, message: String(error)};
};
-const normalizePath = (path: string) => {
- if (path.startsWith('/')) {
- return path;
+const problemToString = (problem: unknown): string => {
+ if (typeof problem === 'string') {
+ return problem;
}
- return `/${path}`;
-};
-
-const writeFilesToMemFs = (project: VirtualProject, memFs: BuiltinMemFs) => {
- const files = {
- ...getBrowserStudioVirtualFiles(),
- ...Object.fromEntries(
- Object.entries(project.files).map(([path, contents]) => [
- normalizePath(path),
- contents,
- ]),
- ),
- };
+ if (
+ typeof problem === 'object' &&
+ problem !== null &&
+ 'message' in problem &&
+ typeof problem.message === 'string'
+ ) {
+ return problem.message;
+ }
- memFs.volume.reset();
- memFs.volume.fromJSON(files);
+ return String(problem);
};
-const compilerWarnings = (statsJson: {
- warnings?: {message?: string}[];
-}): string[] =>
- (statsJson.warnings ?? []).map((warning) => warning.message ?? '');
-
-const compilerErrors = (statsJson: {errors?: {message?: string}[]}): string[] =>
- (statsJson.errors ?? []).map((error) => error.message ?? '');
+const postResponse = (response: BrowserStudioWorkerCompileResponse) => {
+ self.postMessage(response);
+};
const applyDependencyResolution = ({
name,
@@ -115,40 +110,30 @@ const applyDependencyResolution = ({
}
};
-const isBarePackageImport = (request: string) => {
- return (
- !request.startsWith('.') &&
- !request.startsWith('/') &&
- !request.startsWith('http://') &&
- !request.startsWith('https://') &&
- !request.includes('!')
- );
-};
+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('/');
- if (slashIndex === -1) {
- return `${request}@${version}`;
- }
-
- return `${request.slice(0, slashIndex)}@${version}${request.slice(slashIndex)}`;
+ return slashIndex === -1
+ ? `${request}@${version}`
+ : `${request.slice(0, slashIndex)}@${version}${request.slice(slashIndex)}`;
}
const secondSlashIndex = request.indexOf('/', request.indexOf('/') + 1);
- if (secondSlashIndex === -1) {
- return `${request}@${version}`;
- }
-
- return `${request.slice(0, secondSlashIndex)}@${version}${request.slice(secondSlashIndex)}`;
-};
-
-const getPackageName = (request: string) => {
- if (request.startsWith('@')) {
- return request.split('/').slice(0, 2).join('/');
- }
-
- return request.split('/')[0];
+ return secondSlashIndex === -1
+ ? `${request}@${version}`
+ : `${request.slice(0, secondSlashIndex)}@${version}${request.slice(secondSlashIndex)}`;
};
const externalizeSharedDependencies = (url: URL) => {
@@ -156,214 +141,488 @@ const externalizeSharedDependencies = (url: URL) => {
url.searchParams.set('external', studioRenderEntryExternal.join(','));
};
-const compileProject = async ({
+const writeInitialFiles = ({
+ builtinMemFs,
project,
- dependencyResolutions,
-}: BrowserStudioWorkerCompileRequest): Promise<BrowserStudioWorkerCompileResponse> => {
- try {
- const {BrowserHttpImportEsmPlugin, builtinMemFs, rspack} =
- await loadRspackBrowser();
- writeFilesToMemFs(project, builtinMemFs);
-
- const resolvedVersions = {...browserStudioDependencyVersions};
- const resolvedUrls: Record<string, string> = {};
- for (const [name, resolution] of Object.entries(dependencyResolutions)) {
- applyDependencyResolution({
- name,
- resolution,
- resolvedUrls,
- resolvedVersions,
- });
+}: {
+ 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 => ({
+ name: 'browser-studio-react-refresh',
+ apply: (compiler) => {
+ new rspackBrowser.ProvidePlugin({
+ $ReactRefreshRuntime$: browserStudioVirtualFilePaths.reactRefreshRuntime,
+ __react_refresh_utils__: browserStudioVirtualFilePaths.reactRefreshUtils,
+ }).apply(compiler);
+ new rspackBrowser.DefinePlugin({
+ __react_refresh_error_overlay__: false,
+ __react_refresh_library__: JSON.stringify('browser-studio'),
+ __react_refresh_socket__: false,
+ __reload_on_runtime_errors__: false,
+ }).apply(compiler);
+
+ compiler.hooks.compilation.tap(
+ 'browser-studio-react-refresh',
+ (compilation) => {
+ compilation.hooks.additionalTreeRuntimeRequirements.tap(
+ 'browser-studio-react-refresh',
+ (_chunk, runtimeRequirements) => {
+ runtimeRequirements.add(rspackBrowser.RuntimeGlobals.moduleCache);
+ },
+ );
+ },
+ );
+ },
+});
+
+const getBrowserStudioHmrRuntimePlugin = (
+ rspackBrowser: typeof RspackBrowser,
+): RspackBrowser.RspackPluginInstance => {
+ class BrowserStudioManifestRuntimeModule extends rspackBrowser.RuntimeModule {
+ constructor() {
+ super(
+ 'browser studio hmr manifest',
+ rspackBrowser.RuntimeModule.STAGE_TRIGGER,
+ );
}
- const entryPoints = getStudioEntryPoints({
- fastRefreshRuntime: null,
- environmentSetup: browserStudioVirtualFilePaths.setupEnvironment,
- sequenceStackTraces:
- browserStudioVirtualFilePaths.setupSequenceStackTraces,
- userDefinedComponent: normalizePath(project.entryPoint),
- reactShim: browserStudioVirtualFilePaths.reactShim,
- studioRenderEntry: '@remotion/studio/renderEntry',
- });
+ generate() {
+ return `${rspackBrowser.RuntimeGlobals.hmrDownloadManifest} = function() {
+ return window.remotion_browserStudioHmr.getManifest(${rspackBrowser.RuntimeGlobals.getUpdateManifestFilename}());
+};`;
+ }
+ }
- const compiler = rspack({
- context: normalizePath(project.rootDir),
- devtool: 'eval-cheap-module-source-map',
- entry: {
- bundle: {
- asyncChunks: false,
- import: entryPoints,
+ return {
+ name: 'browser-studio-hmr-runtime',
+ apply: (compiler) => {
+ compiler.hooks.compilation.tap(
+ 'browser-studio-hmr-runtime',
+ (compilation) => {
+ compilation.hooks.runtimeRequirementInTree
+ .for(rspackBrowser.RuntimeGlobals.hmrDownloadManifest)
+ .tap('browser-studio-hmr-runtime', (chunk) => {
+ compilation.addRuntimeModule(
+ chunk,
+ new BrowserStudioManifestRuntimeModule(),
+ );
+ });
+
+ rspackBrowser.RuntimePlugin.getCompilationHooks(
+ compilation,
+ ).createScript.tap('browser-studio-hmr-runtime', (code) => {
+ return `${code}\nscript.src = window.remotion_browserStudioHmr.resolveScriptUrl(script.src);`;
+ });
},
+ );
+ },
+ };
+};
+
+const createCompiler = async ({
+ dependencyResolutions,
+ project,
+}: Extract<BrowserStudioWorkerCompileRequest, {type: 'init'}>) => {
+ const rspackBrowser = await loadRspackBrowser();
+ const {BrowserHttpImportEsmPlugin, builtinMemFs, rspack} = rspackBrowser;
+ writeInitialFiles({builtinMemFs, project});
+
+ const resolvedVersions = {...browserStudioDependencyVersions};
+ const resolvedUrls: Record<string, string> = {};
+ for (const [name, resolution] of Object.entries(dependencyResolutions)) {
+ applyDependencyResolution({
+ name,
+ resolution,
+ resolvedUrls,
+ resolvedVersions,
+ });
+ }
+
+ const entryPoints = getStudioEntryPoints({
+ environmentSetup: browserStudioVirtualFilePaths.setupEnvironment,
+ fastRefreshRuntime: browserStudioVirtualFilePaths.reactRefreshEntry,
+ reactShim: browserStudioVirtualFilePaths.reactShim,
+ sequenceStackTraces: browserStudioVirtualFilePaths.setupSequenceStackTraces,
+ studioRenderEntry: '@remotion/studio/previewEntry',
+ userDefinedComponent: normalizePath(project.entryPoint),
+ });
+ entryPoints.splice(
+ entryPoints.length - 1,
+ 0,
+ 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}/`],
+ cacheLocation: false,
},
- experiments: {
- buildHttp: {
- allowedUris: ['https://esm.sh/', `${self.location.origin}/`],
- cacheLocation: false,
+ },
+ 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'}],
},
- },
- mode: 'development',
- module: {
- rules: [
- {
- parser: {
- worker: false,
- },
- test: /\.[cm]?[jt]sx?$/,
- },
- {
- test: /\.tsx?$/,
- use: [
- {
- loader: 'builtin:swc-loader',
- options: {
- jsc: {
- parser: {syntax: 'typescript', tsx: true},
- transform: {
- react: {
- runtime: 'automatic',
- development: true,
- refresh: false,
- },
+ {
+ test: /\.tsx?$/,
+ use: [
+ {
+ loader: 'builtin:swc-loader',
+ options: {
+ env: {targets: 'Chrome >= 111'},
+ jsc: {
+ parser: {syntax: 'typescript', tsx: true},
+ transform: {
+ react: {
+ development: true,
+ refresh: true,
+ runtime: 'automatic',
},
},
- env: {targets: 'Chrome >= 111'},
},
},
- ],
- },
- {
- test: /\.jsx?$/,
- exclude: /node_modules/,
- use: [
- {
- loader: 'builtin:swc-loader',
- options: {
- jsc: {
- parser: {syntax: 'ecmascript', jsx: true},
- transform: {
- react: {
- runtime: 'automatic',
- development: true,
- refresh: false,
- },
+ },
+ ],
+ },
+ {
+ 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,
+ runtime: 'automatic',
},
},
- env: {targets: 'Chrome >= 111'},
},
},
- ],
- },
- ],
- },
- optimization: {
- runtimeChunk: false,
- splitChunks: false,
- },
- output: {
- chunkFilename: '[name].js',
- filename: 'bundle.js',
- hashFunction: 'xxhash64',
- path: '/dist',
- publicPath: '',
- },
- plugins: [
- new BrowserHttpImportEsmPlugin({
- dependencyUrl: ({request}) => {
- if (!isBarePackageImport(request)) {
- return undefined;
- }
-
- const packageName = getPackageName(request);
- const resolvedUrl = resolvedUrls[packageName];
- if (resolvedUrl) {
- return resolvedUrl;
- }
-
- 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 rspack.optimize.LimitChunkCountPlugin({maxChunks: 1}),
+ },
+ ],
+ },
],
- resolve: {
- extensions: ['.tsx', '.ts', '.jsx', '.js', '.json'],
- },
- });
+ },
+ 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 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']},
+ });
+
+ return {builtinMemFs, compiler, rspackBrowser};
+};
- const stats = await new Promise<RspackStats>((resolve, reject) => {
- compiler.run((error: Error | null, compilationStats: unknown) => {
- if (error) {
- reject(error);
- return;
+const makeHmrEvent = ({
+ errors,
+ statsJson,
+ warnings,
+}: {
+ errors: string[];
+ statsJson: RspackBrowser.StatsCompilation;
+ warnings: string[];
+}): HotMiddlewareMessage => ({
+ action: 'built',
+ errors,
+ hash: statsJson.hash,
+ modules: Object.fromEntries(
+ (statsJson.modules ?? []).map((module, index) => [
+ String(module.id ?? index),
+ module.name ?? module.identifier ?? '',
+ ]),
+ ),
+ name: '',
+ time: statsJson.time,
+ 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),
+ );
+ 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;
+};
+
+const runCompilation = (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;
}
- resolve(compilationStats as RspackStats);
- });
- });
+ if (session.initialCompiled) {
+ postResponse({type: 'building'});
+ }
- const statsJson = stats.toJson({
- all: false,
- assets: true,
- errors: true,
- warnings: true,
- });
- const errors = compilerErrors(statsJson);
-
- if (stats.hasErrors()) {
- return {
- type: 'error',
- error: makeBrowserStudioError(
- new Error(errors.join('\n') || 'Rspack compilation failed'),
- errors,
- ),
+ runCompilation(session);
+ return true;
};
- }
- const jsAssets = (statsJson.assets ?? [])
- .map((asset) => asset.name)
- .filter((name): name is string => Boolean(name?.endsWith('.js')));
+ if (error) {
+ if (runQueuedProject()) {
+ return;
+ }
- if (jsAssets.length !== 1) {
- throw new Error(
- `Expected Rspack to emit one JavaScript asset, got ${jsAssets.length}: ${jsAssets.join(
- ', ',
- )}`,
- );
- }
+ postResponse({error: makeBrowserStudioError(error), type: 'error'});
+ return;
+ }
- const bundle = builtinMemFs.volume.readFileSync(
- `/dist/${jsAssets[0]}`,
- 'utf-8',
- );
+ if (!stats) {
+ if (runQueuedProject()) {
+ return;
+ }
- return {
- type: 'compiled',
- bundle: String(bundle),
- warnings: compilerWarnings(statsJson),
- };
- } catch (error) {
- return {
- type: 'error',
- error: makeBrowserStudioError(error),
- };
+ postResponse({
+ error: makeBrowserStudioError('Rspack returned no compilation stats'),
+ 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;
+ }
+
+ session.initialCompiled = true;
+ postResponse({
+ bundle: String(
+ session.builtinMemFs.volume.readFileSync('/dist/bundle.js', 'utf8'),
+ ),
+ type: 'initial-compiled',
+ 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},
+ );
+};
+
+const startCompiler = async (
+ request: Extract<BrowserStudioWorkerCompileRequest, {type: 'init'}>,
+) => {
+ if (compilerSession) {
+ compilerSession.compiler.close(() => undefined);
+ compilerSession = null;
}
+
+ const {builtinMemFs, compiler} = await createCompiler(request);
+ const session: CompilerSession = {
+ builtinMemFs,
+ compiler,
+ initialCompiled: false,
+ modifiedFiles: undefined,
+ project: request.project,
+ queuedProject: null,
+ removedFiles: undefined,
+ running: false,
+ };
+ compilerSession = session;
+ runCompilation(session);
};
-self.onmessage = async (
- event: MessageEvent<BrowserStudioWorkerCompileRequest>,
+const updateProject = (
+ request: Extract<BrowserStudioWorkerCompileRequest, {type: 'update-project'}>,
) => {
- const response = await compileProject(event.data);
- self.postMessage(response);
+ if (!compilerSession) {
+ throw new Error('Cannot update Browser Studio before initializing it');
+ }
+
+ if (compilerSession.running) {
+ compilerSession.queuedProject = request.project;
+ return;
+ }
+
+ if (!applyProjectUpdate(compilerSession, request.project)) {
+ return;
+ }
+
+ if (compilerSession.initialCompiled) {
+ postResponse({type: 'building'});
+ }
+
+ runCompilation(compilerSession);
};
+self.addEventListener(
+ 'message',
+ async (event: MessageEvent<BrowserStudioWorkerCompileRequest>) => {
+ try {
+ if (event.data.type === 'init') {
+ await startCompiler(event.data);
+ return;
+ }
+
+ updateProject(event.data);
+ } catch (error) {
+ postResponse({error: makeBrowserStudioError(error), type: 'error'});
+ }
+ },
+);
+
export type {BrowserStudioWorkerCompileResponse};
diff --git a/packages/browser-studio/src/dev/get-dependency-versions-for-build.ts b/packages/browser-studio/src/dev/get-dependency-versions-for-build.ts
index 60cb5b0b56..b4023ce993 100644
--- a/packages/browser-studio/src/dev/get-dependency-versions-for-build.ts
+++ b/packages/browser-studio/src/dev/get-dependency-versions-for-build.ts
@@ -77,6 +77,9 @@ export const getBrowserStudioDependencyVersionsForBuild = (): Record<
const studioPackageJson = readPackageJson(
join(repoDir, 'packages', 'studio', 'package.json'),
);
+ const browserStudioPackageJson = readPackageJson(
+ join(repoDir, 'packages', 'browser-studio', 'package.json'),
+ );
const catalog = rootPackageJson.workspaces?.catalog;
if (!catalog) {
@@ -91,6 +94,8 @@ export const getBrowserStudioDependencyVersionsForBuild = (): Record<
[studioPackageJson.name]: studioPackageJson.version,
react: 'catalog:',
'react-dom': 'catalog:',
+ 'react-refresh':
+ browserStudioPackageJson.dependencies?.['react-refresh'] ?? '0.18.0',
};
for (const [name, spec] of Object.entries(
diff --git a/packages/browser-studio/src/dev/get-react-refresh-files-for-build.ts b/packages/browser-studio/src/dev/get-react-refresh-files-for-build.ts
new file mode 100644
index 0000000000..0bb609be1c
--- /dev/null
+++ b/packages/browser-studio/src/dev/get-react-refresh-files-for-build.ts
@@ -0,0 +1,19 @@
+import {readFileSync} from 'node:fs';
+import {dirname, join} from 'node:path';
+import {fileURLToPath} from 'node:url';
+
+export const getBrowserStudioReactRefreshFilesForBuild = () => {
+ const entry = fileURLToPath(
+ import.meta.resolve('@rspack/plugin-react-refresh/react-refresh-entry'),
+ );
+ const runtime = fileURLToPath(
+ import.meta.resolve('@rspack/plugin-react-refresh/react-refresh'),
+ );
+ const refreshUtils = join(dirname(runtime), 'refreshUtils.js');
+
+ return {
+ entry: readFileSync(entry, 'utf-8'),
+ runtime: readFileSync(runtime, 'utf-8'),
+ utils: readFileSync(refreshUtils, 'utf-8'),
+ };
+};
diff --git a/packages/browser-studio/src/dev/index.tsx b/packages/browser-studio/src/dev/index.tsx
index 3c01e9e0a4..62d37af4ee 100644
--- a/packages/browser-studio/src/dev/index.tsx
+++ b/packages/browser-studio/src/dev/index.tsx
@@ -12,6 +12,6 @@ createRoot(root).render(
<BrowserStudio
iframeSrc="/frame.html"
project={createBlankTemplateProject()}
- readOnly
+ readOnly={false}
/>,
);
diff --git a/packages/browser-studio/src/dev/server.ts b/packages/browser-studio/src/dev/server.ts
index 90f9861f4b..19614bc11e 100644
--- a/packages/browser-studio/src/dev/server.ts
+++ b/packages/browser-studio/src/dev/server.ts
@@ -2,6 +2,7 @@ import path from 'path';
import {fileURLToPath} from 'url';
import {build} from 'bun';
import {getBrowserStudioDependencyVersionsForBuild} from './get-dependency-versions-for-build';
+import {getBrowserStudioReactRefreshFilesForBuild} from './get-react-refresh-files-for-build';
import {getBrowserStudioSetupEnvironmentForBuild} from './get-setup-environment-for-build';
import {studioRenderEntryExternal} from './studio-render-entry-external';
@@ -65,12 +66,14 @@ const frameHtml = `<!DOCTYPE html>
const buildDevAssets = async () => {
const dependencyVersions = getBrowserStudioDependencyVersionsForBuild();
+ const reactRefreshFiles = getBrowserStudioReactRefreshFilesForBuild();
const setupEnvironment = getBrowserStudioSetupEnvironmentForBuild();
const output = await build({
entrypoints: ['src/dev/index.tsx', 'src/browser-studio-worker.ts'],
define: {
__BROWSER_STUDIO_DEPENDENCY_VERSIONS__:
JSON.stringify(dependencyVersions),
+ __BROWSER_STUDIO_REACT_REFRESH_FILES__: JSON.stringify(reactRefreshFiles),
__BROWSER_STUDIO_SETUP_ENVIRONMENT__: JSON.stringify(setupEnvironment),
},
format: 'esm',
@@ -85,8 +88,8 @@ const buildDevAssets = async () => {
process.exit(1);
}
- const studioRenderEntryOutput = await build({
- entrypoints: ['src/browser-studio-render-entry.ts'],
+ const studioPreviewEntryOutput = await build({
+ entrypoints: ['src/browser-studio-preview-entry.ts'],
external: studioRenderEntryExternal,
format: 'esm',
naming: '[name].mjs',
@@ -95,8 +98,8 @@ const buildDevAssets = async () => {
target: 'browser',
});
- if (!studioRenderEntryOutput.success) {
- process.stderr.write(`${studioRenderEntryOutput.logs.join('\n')}\n`);
+ if (!studioPreviewEntryOutput.success) {
+ process.stderr.write(`${studioPreviewEntryOutput.logs.join('\n')}\n`);
process.exit(1);
}
diff --git a/packages/browser-studio/src/test/browser-studio-hmr-assets.test.ts b/packages/browser-studio/src/test/browser-studio-hmr-assets.test.ts
new file mode 100644
index 0000000000..7af5317ffa
--- /dev/null
+++ b/packages/browser-studio/src/test/browser-studio-hmr-assets.test.ts
@@ -0,0 +1,65 @@
+import {expect, test} from 'bun:test';
+import {createBrowserStudioHmrAssetManager} from '../browser-studio-hmr-assets';
+
+test('serves HMR manifests and script blobs from browser memory', async () => {
+ const created: Blob[] = [];
+ const revoked: string[] = [];
+ const manager = createBrowserStudioHmrAssetManager({
+ createObjectUrl: (blob) => {
+ created.push(blob);
+ return `blob:hmr-${created.length}`;
+ },
+ revokeObjectUrl: (url) => revoked.push(url),
+ });
+
+ manager.updateAssets([
+ {
+ content: '{"c":["bundle"],"r":[],"m":["changed"]}',
+ name: 'bundle.old.hot-update.json',
+ },
+ {
+ content: 'self.rspackHotUpdate("bundle", {changed: true});',
+ name: 'bundle.old.hot-update.js',
+ },
+ ]);
+
+ expect(
+ await manager.bridge.getManifest(
+ '/__remotion_browser_studio_hmr__/bundle.old.hot-update.json',
+ ),
+ ).toEqual({c: ['bundle'], r: [], m: ['changed']});
+ expect(
+ manager.bridge.resolveScriptUrl(
+ 'https://example.test/bundle.old.hot-update.js',
+ ),
+ ).toBe('blob:hmr-1');
+ expect(manager.bridge.resolveScriptUrl('bundle.old.hot-update.js')).toBe(
+ 'blob:hmr-1',
+ );
+ expect(await created[0].text()).toContain('rspackHotUpdate');
+
+ manager.updateAssets([
+ {
+ content: 'self.rspackHotUpdate("bundle", {changed: false});',
+ name: 'bundle.old.hot-update.js',
+ },
+ ]);
+ expect(revoked).toEqual(['blob:hmr-1']);
+ expect(manager.bridge.resolveScriptUrl('bundle.old.hot-update.js')).toBe(
+ 'blob:hmr-2',
+ );
+
+ manager.dispose();
+ expect(revoked).toEqual(['blob:hmr-1', 'blob:hmr-2']);
+});
+
+test('fails clearly when Rspack asks for a missing HMR script', () => {
+ const manager = createBrowserStudioHmrAssetManager({
+ createObjectUrl: () => 'blob:unused',
+ revokeObjectUrl: () => undefined,
+ });
+
+ expect(() =>
+ manager.bridge.resolveScriptUrl('missing.hot-update.js'),
+ ).toThrow('Missing Browser Studio HMR asset: missing.hot-update.js');
+});
diff --git a/packages/browser-studio/src/test/browser-studio-project-operations.test.ts b/packages/browser-studio/src/test/browser-studio-project-operations.test.ts
index 1e0d3411a5..a048c646c3 100644
--- a/packages/browser-studio/src/test/browser-studio-project-operations.test.ts
+++ b/packages/browser-studio/src/test/browser-studio-project-operations.test.ts
@@ -135,6 +135,34 @@ test('mutates virtual files, emits events, and preserves undo and redo history',
expect(revokedUrls).toContain('blob:virtual-2');
});
+test('replays an HMR event emitted before the Studio subscribes', () => {
+ const project = createBlankTemplateProject();
+ const operations = createBrowserStudioOperations({
+ dependencyVersions: {},
+ getStaticFiles: null,
+ getProject: () => project,
+ onProjectChange: () => undefined,
+ });
+ const hmrEvent = {
+ type: 'hmr',
+ hmrEvent: {
+ action: 'built',
+ errors: [],
+ hash: 'new-hash',
+ modules: {'/project/src/Composition.tsx': 'Composition.tsx'},
+ name: '',
+ time: 12,
+ warnings: [],
+ },
+ } satisfies EventSourceEvent;
+
+ operations.emitEvent(hmrEvent);
+ const events: EventSourceEvent[] = [];
+ operations.subscribeToEvent((event) => events.push(event));
+
+ expect(events.at(-1)).toEqual(hmrEvent);
+});
+
test('rejects unsafe public paths and conflicting renames', async () => {
let project: VirtualProject = {
...createBlankTemplateProject(),
diff --git a/packages/browser-studio/src/types.ts b/packages/browser-studio/src/types.ts
index 15a66148dd..03633a292a 100644
--- a/packages/browser-studio/src/types.ts
+++ b/packages/browser-studio/src/types.ts
@@ -1,3 +1,5 @@
+import type {HotMiddlewareMessage} from '@remotion/studio-shared';
+
export type VirtualProject = {
rootDir: string;
entryPoint: string;
@@ -49,25 +51,44 @@ export type CompileState =
export type BrowserStudioProps = {
project: VirtualProject;
- readOnly: true;
+ readOnly: boolean;
iframeSrc?: string;
dependencyResolver?: BrowserStudioDependencyResolver;
onCompileStateChange?: (state: CompileState) => void;
onProjectChange?: (project: VirtualProject) => void;
};
-export type BrowserStudioWorkerCompileRequest = {
- type: 'compile';
- project: VirtualProject;
- dependencyResolutions: Record<string, BrowserStudioDependencyResolution>;
+export type BrowserStudioWorkerCompileRequest =
+ | {
+ type: 'init';
+ project: VirtualProject;
+ dependencyResolutions: Record<string, BrowserStudioDependencyResolution>;
+ }
+ | {
+ type: 'update-project';
+ project: VirtualProject;
+ };
+
+export type BrowserStudioHmrAsset = {
+ content: string;
+ name: string;
};
export type BrowserStudioWorkerCompileResponse =
| {
- type: 'compiled';
+ type: 'initial-compiled';
bundle: string;
warnings: string[];
}
+ | {
+ type: 'building';
+ }
+ | {
+ type: 'hmr-update';
+ assets: BrowserStudioHmrAsset[];
+ hmrEvent: HotMiddlewareMessage;
+ warnings: string[];
+ }
| {
type: 'error';
error: BrowserStudioError;
diff --git a/packages/browser-studio/src/virtual-files.ts b/packages/browser-studio/src/virtual-files.ts
index d723e3a9f9..e3456aaa07 100644
--- a/packages/browser-studio/src/virtual-files.ts
+++ b/packages/browser-studio/src/virtual-files.ts
@@ -1,4 +1,8 @@
export const browserStudioVirtualFilePaths = {
+ browserRequireShim: '/__remotion_browser_studio__/browser-require-shim.js',
+ reactRefreshEntry: '/__remotion_browser_studio__/react-refresh-entry.js',
+ reactRefreshRuntime: '/__remotion_browser_studio__/reactRefresh.js',
+ reactRefreshUtils: '/__remotion_browser_studio__/refreshUtils.js',
setupEnvironment: '/__remotion_browser_studio__/setup-environment.ts',
setupSequenceStackTraces:
'/__remotion_browser_studio__/setup-sequence-stack-traces.ts',
@@ -6,6 +10,13 @@ export const browserStudioVirtualFilePaths = {
};
declare const __BROWSER_STUDIO_SETUP_ENVIRONMENT__: string | undefined;
+declare const __BROWSER_STUDIO_REACT_REFRESH_FILES__:
+ | {
+ entry: string;
+ runtime: string;
+ utils: string;
+ }
+ | undefined;
const getInjectedSetupEnvironment = () => {
if (typeof __BROWSER_STUDIO_SETUP_ENVIRONMENT__ === 'undefined') {
@@ -15,6 +26,14 @@ const getInjectedSetupEnvironment = () => {
return __BROWSER_STUDIO_SETUP_ENVIRONMENT__;
};
+const getInjectedReactRefreshFiles = () => {
+ if (typeof __BROWSER_STUDIO_REACT_REFRESH_FILES__ === 'undefined') {
+ throw new Error('Browser Studio React Refresh files were not injected');
+ }
+
+ return __BROWSER_STUDIO_REACT_REFRESH_FILES__;
+};
+
const setupSequenceStackTraces = `import React from 'react';
import JsxRuntimeDev from 'react/jsx-dev-runtime';
import JsxRuntime from 'react/jsx-runtime';
@@ -69,10 +88,37 @@ if (typeof globalThis === 'undefined') {
}
`;
-export const getBrowserStudioVirtualFiles = (): Record<string, string> => ({
- [browserStudioVirtualFilePaths.setupEnvironment]:
- getInjectedSetupEnvironment(),
- [browserStudioVirtualFilePaths.setupSequenceStackTraces]:
- setupSequenceStackTraces,
- [browserStudioVirtualFilePaths.reactShim]: reactShim,
-});
+const browserRequireShim = `import * as Remotion from 'remotion';
+import * as RemotionNoReact from 'remotion/no-react';
+
+const modules = {
+ remotion: Remotion,
+ 'remotion/no-react': RemotionNoReact,
+};
+
+globalThis.require = (id) => {
+ const module = modules[id];
+ if (!module) {
+ throw new Error('Unsupported Browser Studio require: ' + id);
+ }
+
+ return module;
+};
+`;
+
+export const getBrowserStudioVirtualFiles = (): Record<string, string> => {
+ const reactRefreshFiles = getInjectedReactRefreshFiles();
+
+ return {
+ [browserStudioVirtualFilePaths.browserRequireShim]: browserRequireShim,
+ [browserStudioVirtualFilePaths.reactRefreshEntry]: reactRefreshFiles.entry,
+ [browserStudioVirtualFilePaths.reactRefreshRuntime]:
+ reactRefreshFiles.runtime,
+ [browserStudioVirtualFilePaths.reactRefreshUtils]: reactRefreshFiles.utils,
+ [browserStudioVirtualFilePaths.setupEnvironment]:
+ getInjectedSetupEnvironment(),
+ [browserStudioVirtualFilePaths.setupSequenceStackTraces]:
+ setupSequenceStackTraces,
+ [browserStudioVirtualFilePaths.reactShim]: reactShim,
+ };
+};
diff --git a/packages/docs/src/pages/experimental_new/index.tsx b/packages/docs/src/pages/experimental_new/index.tsx
index b90c0fcccb..efe906d965 100644
--- a/packages/docs/src/pages/experimental_new/index.tsx
+++ b/packages/docs/src/pages/experimental_new/index.tsx
@@ -55,7 +55,7 @@ const NewRemotionProject = () => {
<BrowserStudio
iframeSrc="/experimental_new/frame.html"
project={createBlankTemplateProject()}
- readOnly
+ readOnly={false}
/>
)}
</BrowserOnly>
diff --git a/packages/studio/src/Studio.tsx b/packages/studio/src/Studio.tsx
index e2260bf0a1..bbaf7c4dae 100644
--- a/packages/studio/src/Studio.tsx
+++ b/packages/studio/src/Studio.tsx
@@ -35,7 +35,7 @@ const StudioInner: React.FC<{
>
<StaticFilesProvider>
<ResolveCompositionConfigInStudio>
- <EditorContexts readOnlyStudio={readOnly}>
+ <EditorContexts>
<Editor readOnlyStudio={readOnly} Root={rootComponent} />
{readOnly
? null
diff --git a/packages/studio/src/components/EditorContexts.tsx b/packages/studio/src/components/EditorContexts.tsx
index 7c2971837b..74846805a2 100644
--- a/packages/studio/src/components/EditorContexts.tsx
+++ b/packages/studio/src/components/EditorContexts.tsx
@@ -24,12 +24,11 @@ import {ZoomGesturesProvider} from './ZoomGesturesProvider';
export const EditorContexts: React.FC<{
readonly children: React.ReactNode;
- readonly readOnlyStudio: boolean;
-}> = ({children, readOnlyStudio}) => {
+}> = ({children}) => {
return (
<ZodProvider>
<VisualControlsProvider>
- <PreviewServerConnection readOnlyStudio={readOnlyStudio}>
+ <PreviewServerConnection>
<VisualControlsUndoSync />
<RenderQueueContextProvider>
<ClientRenderQueueProcessor />
diff --git a/packages/studio/src/helpers/browser-studio-operations.ts b/packages/studio/src/helpers/browser-studio-operations.ts
index 0965b663ff..5d4e04a428 100644
--- a/packages/studio/src/helpers/browser-studio-operations.ts
+++ b/packages/studio/src/helpers/browser-studio-operations.ts
@@ -1,5 +1,10 @@
import type {BrowserStudioOperations} from '@remotion/studio-shared';
+// Browser Studio may be hosted by a different studio-shared version, so this
+// handshake intentionally has no shared runtime import.
+export const BROWSER_STUDIO_OPERATIONS_READY_EVENT =
+ 'remotion-browser-studio-operations-ready';
+
export const getBrowserStudioOperations =
(): BrowserStudioOperations | null => {
if (typeof window === 'undefined') {
diff --git a/packages/studio/src/helpers/client-id.tsx b/packages/studio/src/helpers/client-id.tsx
index 6430bebcfc..026c0616c3 100644
--- a/packages/studio/src/helpers/client-id.tsx
+++ b/packages/studio/src/helpers/client-id.tsx
@@ -5,7 +5,6 @@ import {Internals} from 'remotion';
import {showNotification} from '../components/Notifications/NotificationCenter';
import playBeepSound from '../components/PlayBeepSound';
import {renderJobsRef} from '../components/RenderQueue/context';
-import {getBrowserStudioOperations} from './browser-studio-operations';
import {
subscribeToPreviewServerConnectionState,
subscribeToPreviewServerEvents,
@@ -21,11 +20,6 @@ type Context = {
) => () => void;
};
-// Browser Studio may be hosted by a different studio-shared version, so this
-// handshake intentionally has no shared runtime import.
-const BROWSER_STUDIO_OPERATIONS_READY_EVENT =
- 'remotion-browser-studio-operations-ready';
-
export const StudioServerConnectionCtx = React.createContext<Context>({
previewServerState: {
type: 'init',
@@ -42,8 +36,7 @@ type Listeners = {
export const PreviewServerConnection: React.FC<{
readonly children: React.ReactNode;
- readonly readOnlyStudio: boolean;
-}> = ({children, readOnlyStudio}) => {
+}> = ({children}) => {
const listeners = useRef<Listeners>([]);
const latestUndoRedoEvent = useRef<
Extract<EventSourceEvent, {type: 'undo-redo-stack-changed'}> | undefined
@@ -138,46 +131,6 @@ export const PreviewServerConnection: React.FC<{
});
};
- let unsubscribeFromBrowserStudio: (() => void) | null = null;
- const connectToBrowserStudio = () => {
- if (unsubscribeFromBrowserStudio) {
- return true;
- }
-
- const browserStudioOperations = getBrowserStudioOperations();
- if (!browserStudioOperations) {
- return false;
- }
-
- setState({type: 'connected', clientId: 'browser-studio'});
- unsubscribeFromBrowserStudio =
- browserStudioOperations.subscribeToEvent(handleEvent);
- return true;
- };
-
- if (connectToBrowserStudio()) {
- return () => unsubscribeFromBrowserStudio?.();
- }
-
- if (readOnlyStudio) {
- window.addEventListener(
- BROWSER_STUDIO_OPERATIONS_READY_EVENT,
- connectToBrowserStudio,
- );
- const animationFrame = window.requestAnimationFrame(() => {
- connectToBrowserStudio();
- });
-
- return () => {
- window.cancelAnimationFrame(animationFrame);
- window.removeEventListener(
- BROWSER_STUDIO_OPERATIONS_READY_EVENT,
- connectToBrowserStudio,
- );
- unsubscribeFromBrowserStudio?.();
- };
- }
-
const unsubscribeFromEvents = subscribeToPreviewServerEvents(handleEvent);
const unsubscribeFromConnectionState =
subscribeToPreviewServerConnectionState(setState);
@@ -186,7 +139,7 @@ export const PreviewServerConnection: React.FC<{
unsubscribeFromEvents();
unsubscribeFromConnectionState();
};
- }, [readOnlyStudio]);
+ }, []);
const context: Context = useMemo(() => {
return {
diff --git a/packages/studio/src/helpers/preview-server-events.ts b/packages/studio/src/helpers/preview-server-events.ts
index 73afd3d1c5..09a423d271 100644
--- a/packages/studio/src/helpers/preview-server-events.ts
+++ b/packages/studio/src/helpers/preview-server-events.ts
@@ -2,6 +2,10 @@
/// <reference lib="dom.iterable" />
import type {EventSourceEvent} from '@remotion/studio-shared';
+import {
+ BROWSER_STUDIO_OPERATIONS_READY_EVENT,
+ getBrowserStudioOperations,
+} from './browser-studio-operations';
export type PreviewServerConnectionState =
| {
@@ -19,8 +23,11 @@ type MessageListener = (event: EventSourceEvent) => void;
type ConnectionStateListener = (state: PreviewServerConnectionState) => void;
let source: EventSource | null = null;
+let unsubscribeFromBrowserStudio: (() => void) | null = null;
+let browserStudioReadyListenerInstalled = false;
let connectionState: PreviewServerConnectionState = {type: 'init'};
let lastInitEvent: Extract<EventSourceEvent, {type: 'init'}> | null = null;
+let pendingHmrEvent: Extract<EventSourceEvent, {type: 'hmr'}> | null = null;
const messageListeners = new Set<MessageListener>();
const connectionStateListeners = new Set<ConnectionStateListener>();
@@ -31,11 +38,44 @@ const notifyConnectionState = () => {
};
const dispatch = (event: EventSourceEvent) => {
+ if (event.type === 'init') {
+ lastInitEvent = event;
+ connectionState = {
+ type: 'connected',
+ clientId: event.clientId,
+ };
+ notifyConnectionState();
+ }
+
+ if (event.type === 'hmr' && messageListeners.size === 0) {
+ pendingHmrEvent = event;
+ }
+
for (const listener of messageListeners) {
listener(event);
}
};
+const connectToBrowserStudio = () => {
+ if (unsubscribeFromBrowserStudio) {
+ return true;
+ }
+
+ const browserStudioOperations = getBrowserStudioOperations();
+ if (!browserStudioOperations) {
+ return false;
+ }
+
+ if (source) {
+ source.close();
+ source = null;
+ }
+
+ unsubscribeFromBrowserStudio =
+ browserStudioOperations.subscribeToEvent(dispatch);
+ return true;
+};
+
const openEventSource = () => {
if (source) {
return;
@@ -46,15 +86,6 @@ const openEventSource = () => {
source.addEventListener('message', (event) => {
try {
const newEvent = JSON.parse(event.data) as EventSourceEvent;
- if (newEvent.type === 'init') {
- lastInitEvent = newEvent;
- connectionState = {
- type: 'connected',
- clientId: newEvent.clientId,
- };
- notifyConnectionState();
- }
-
dispatch(newEvent);
} catch {
// Ignore parse errors
@@ -80,7 +111,23 @@ const openEventSource = () => {
};
export const ensurePreviewServerEventSource = () => {
- if (typeof window === 'undefined' || typeof EventSource === 'undefined') {
+ if (typeof window === 'undefined') {
+ return;
+ }
+
+ if (!browserStudioReadyListenerInstalled) {
+ browserStudioReadyListenerInstalled = true;
+ window.addEventListener(
+ BROWSER_STUDIO_OPERATIONS_READY_EVENT,
+ connectToBrowserStudio,
+ );
+ }
+
+ if (connectToBrowserStudio()) {
+ return;
+ }
+
+ if (typeof EventSource === 'undefined') {
return;
}
@@ -97,6 +144,11 @@ export const subscribeToPreviewServerEvents = (
listener(lastInitEvent);
}
+ if (pendingHmrEvent) {
+ listener(pendingHmrEvent);
+ pendingHmrEvent = null;
+ }
+
return () => {
messageListeners.delete(listener);
};
diff --git a/packages/studio/src/hot-middleware-client/client.ts b/packages/studio/src/hot-middleware-client/client.ts
index ee981b2495..1b7cea2045 100644
--- a/packages/studio/src/hot-middleware-client/client.ts
+++ b/packages/studio/src/hot-middleware-client/client.ts
@@ -142,9 +142,9 @@ export const enableHotMiddleware = () => {
processMessage(hmrEvent);
};
- // Connect to /events immediately so HMR works before React mounts.
- // PreviewServerConnection reuses the same EventSource via preview-server-events.
- if (typeof window !== 'undefined' && typeof EventSource !== 'undefined') {
+ // Connect immediately so HMR works before React mounts. Browser Studio and
+ // the preview server share the same transport-neutral event subscription.
+ if (typeof window !== 'undefined') {
if (!unsubscribeFromPreviewServerEvents) {
unsubscribeFromPreviewServerEvents = subscribeToPreviewServerEvents(
(event) => {
diff --git a/packages/studio/src/previewEntry.tsx b/packages/studio/src/previewEntry.tsx
index d28aecf020..5641d4e096 100644
--- a/packages/studio/src/previewEntry.tsx
+++ b/packages/studio/src/previewEntry.tsx
@@ -62,5 +62,10 @@ const renderToDOM = (content: React.ReactElement) => {
renderToDOM(<NoRegisterRoot />);
Internals.waitForRoot((NewRoot) => {
- renderToDOM(<Studio readOnly={false} rootComponent={NewRoot} />);
+ renderToDOM(
+ <Studio
+ readOnly={window.remotion_isReadOnlyStudio}
+ rootComponent={NewRoot}
+ />,
+ );
});