🎥 Make videos programmatically with React
`@remotion/studio-protocol`: Stabilize Element install contract (#9832)
Igor Samokhovets7100b341c837
diff --git a/packages/studio-protocol/README.md b/packages/studio-protocol/README.mdindex bbb8f5d24b..6b9f61edf5 100644--- a/packages/studio-protocol/README.md+++ b/packages/studio-protocol/README.md@@ -1,6 +1,6 @@# @remotion/studio-protocol-Construct and parse drag-and-drop payloads for Remotion+Create Element payloads and request installation into Remotion Studio.[](https://npmcharts.com/compare/@remotion/studio-protocol?minimal=true)@@ -10,9 +10,8 @@ Construct and parse drag-and-drop payloads for Remotionnpm install @remotion/studio-protocol --save-exact```-When installing a Remotion package, make sure to align the version of all `remotion` and `@remotion/*` packages to the same version.-Remove the `^` character from the version number to use the exact version.+When installing a Remotion package, align the version of all `remotion` and `@remotion/*` packages. Remove the `^` character to use the exact version.## Usage-See the [documentation](https://www.remotion.dev/docs/studio-protocol) for more information.+See the [Remotion Studio Protocol documentation](https://www.remotion.dev/docs/studio-protocol).diff --git a/packages/studio-protocol/package.json b/packages/studio-protocol/package.jsonindex 400c4b5481..08df1d2685 100644--- a/packages/studio-protocol/package.json+++ b/packages/studio-protocol/package.json@@ -1,7 +1,7 @@{"name": "@remotion/studio-protocol","version": "4.0.501",- "description": "Construct and parse drag-and-drop payloads for Remotion",+ "description": "Create Element payloads and request installation into Remotion Studio","main": "dist/index.cjs","types": "dist/index.d.ts","module": "dist/esm/index.mjs",@@ -39,6 +39,9 @@},"keywords": ["remotion",+ "studio",+ "protocol",+ "elements","drag-and-drop"],"publishConfig": {diff --git a/packages/studio-protocol/src/drag-transport.ts b/packages/studio-protocol/src/drag-transport.tsnew file mode 100644index 0000000000..19cd0fa5f5--- /dev/null+++ b/packages/studio-protocol/src/drag-transport.ts@@ -0,0 +1,19 @@+import {makeDragData} from './drag-data';+import type {StudioElementPayload} from './element-payload';++export const setStudioDragData = ({+ dataTransfer,+ payload,+}: {+ readonly dataTransfer: DataTransfer;+ readonly payload: StudioElementPayload;+}): void => {+ const dragData = makeDragData({+ type: 'element',+ ...payload.element,+ durationInFrames: payload.durationInFrames,+ });++ dataTransfer.effectAllowed = 'copy';+ dataTransfer.setData(dragData.mimeType, dragData.payload);+};diff --git a/packages/studio-protocol/src/element-payload.ts b/packages/studio-protocol/src/element-payload.tsnew file mode 100644index 0000000000..3d73164dd6--- /dev/null+++ b/packages/studio-protocol/src/element-payload.ts@@ -0,0 +1,145 @@+import type {ComponentDimensions} from './component-drag-data';+import {makeDragData} from './drag-data';+import type {makeElementDragData} from './element-drag-data';+import {+ getElementComponentNameFromSourceCode,+ makeElementFileNameFromSlug,+ parseElementDragData,+} from './element-drag-data';+import {isRecord, isValidPackageName} from './validation';++const MAX_PAYLOAD_SIZE = 250_000;+const MAX_SOURCE_CODE_SIZE = 200_000;+const MAX_DEPENDENCIES = 100;++export type CreateElementPayloadInput = {+ readonly displayName: string;+ readonly slug: string;+ readonly sourceCode: string;+ readonly dependencies: readonly string[];+ readonly dimensions: ComponentDimensions | null;+ readonly durationInFrames: number;+};++export type StudioElementPayload = ReturnType<typeof makeElementDragData> & {+ readonly durationInFrames: number;+};++const assertCreateElementPayloadInput = (+ input: CreateElementPayloadInput,+): void => {+ if (typeof input.displayName !== 'string' || input.displayName.length === 0) {+ throw new TypeError('displayName must be a non-empty string');+ }++ if (input.displayName.length >= 120) {+ throw new TypeError('displayName must be shorter than 120 characters');+ }++ if (makeElementFileNameFromSlug(input.slug) === null) {+ throw new TypeError('slug must be a safe lowercase Element slug');+ }++ if (+ typeof input.sourceCode !== 'string' ||+ input.sourceCode.trim().length === 0+ ) {+ throw new TypeError('sourceCode must be a non-empty string');+ }++ if (input.sourceCode.length >= MAX_SOURCE_CODE_SIZE) {+ throw new TypeError(+ `sourceCode must be shorter than ${MAX_SOURCE_CODE_SIZE} characters`,+ );+ }++ if (getElementComponentNameFromSourceCode(input.sourceCode) === null) {+ throw new TypeError(+ 'sourceCode must contain exactly one exported named React component',+ );+ }++ if (!Array.isArray(input.dependencies)) {+ throw new TypeError('dependencies must be an array');+ }++ if (input.dependencies.length > MAX_DEPENDENCIES) {+ throw new TypeError(+ `dependencies must contain at most ${MAX_DEPENDENCIES} packages`,+ );+ }++ for (const dependency of input.dependencies) {+ if (typeof dependency !== 'string' || !isValidPackageName(dependency)) {+ throw new TypeError(+ `Invalid dependency package name: ${String(dependency)}`,+ );+ }+ }+};++export const createElementPayload = (+ input: CreateElementPayloadInput,+): StudioElementPayload => {+ assertCreateElementPayloadInput(input);++ const constructed = makeDragData({+ type: 'element',+ ...input,+ dependencies: input.dependencies.slice(),+ });+ const payload: StudioElementPayload = {+ ...constructed.data,+ durationInFrames: input.durationInFrames,+ };++ if (JSON.stringify(payload).length > MAX_PAYLOAD_SIZE) {+ throw new TypeError(+ `The Element payload must be smaller than ${MAX_PAYLOAD_SIZE} characters`,+ );+ }++ return payload;+};++export const parseStudioElementPayload = (+ value: unknown,+): StudioElementPayload | null => {+ if (+ !isRecord(value) ||+ value.type !== 'remotion-element' ||+ value.version !== 1 ||+ typeof value.durationInFrames !== 'number' ||+ !Number.isInteger(value.durationInFrames) ||+ !isRecord(value.element)+ ) {+ return null;+ }++ const parsed = parseElementDragData(+ JSON.stringify({+ type: value.type,+ version: value.version,+ element: value.element,+ }),+ );+ if (parsed === null) {+ return null;+ }++ try {+ makeDragData({+ type: 'element',+ ...parsed.element,+ durationInFrames: value.durationInFrames,+ });+ } catch {+ return null;+ }++ const payload: StudioElementPayload = {+ ...parsed,+ durationInFrames: value.durationInFrames,+ };+ return JSON.stringify(payload).length <= MAX_PAYLOAD_SIZE ? payload : null;+};diff --git a/packages/studio-protocol/src/index.ts b/packages/studio-protocol/src/index.tsindex 73ab29679e..c10c3db649 100644--- a/packages/studio-protocol/src/index.ts+++ b/packages/studio-protocol/src/index.ts@@ -9,7 +9,8 @@ import {getElementComponentNameFromSourceCode,makeElementFileNameFromSlug,} from './element-drag-data';-import {installInStudio} from './install-in-studio';+import {parseStudioElementPayload} from './element-payload';+import {installInStudioWithDependencies} from './install-in-studio';export type {AssetDragData} from './asset-drag-data';export type {@@ -45,9 +46,18 @@ export type {export type {EffectDragData} from './effect-drag-data';export type {ElementDragData} from './element-drag-data';export type {SfxDragData} from './sfx-drag-data';-export type {- InstallInStudioResult,- StudioInstallTarget,+export {setStudioDragData} from './drag-transport';+export {+ createElementPayload,+ type CreateElementPayloadInput,+ type StudioElementPayload,+} from './element-payload';+export {+ installInStudio,+ type InstallInStudioErrorCode,+ type InstallInStudioResult,+ type StudioProtocolDescriptor,+ type StudioProtocolInstallTarget,} from './install-in-studio';export const StudioProtocolInternals = {@@ -56,8 +66,9 @@ export const StudioProtocolInternals = {getElementComponentNameFromSourceCode,isComponentIdentifier,isComponentImportPath,- installInStudio,+ installInStudioWithDependencies,makeDragData,makeElementFileNameFromSlug,parseDragData,+ parseStudioElementPayload,};diff --git a/packages/studio-protocol/src/install-in-studio.ts b/packages/studio-protocol/src/install-in-studio.tsindex 56379b6ed3..dee7afa2a7 100644--- a/packages/studio-protocol/src/install-in-studio.ts+++ b/packages/studio-protocol/src/install-in-studio.ts@@ -1,188 +1,408 @@-import type {SerializedDragData} from './drag-data';+import type {StudioElementPayload} from './element-payload';import {isRecord} from './validation';-export type StudioInstallTarget = {- readonly type: 'remotion-studio';+export type StudioProtocolInstallTarget = {+ readonly id: string;+ readonly expiresAt: number;+ readonly compositionId: string;+ readonly lastFocusedAt: number;+};++export type StudioProtocolDescriptor = {+ readonly protocol: 'remotion-studio-protocol';+ readonly protocolVersion: 1;+ readonly studioVersion: string;+ readonly capabilities: {+ readonly install: readonly {+ readonly payloadType: 'remotion-element';+ readonly payloadVersions: readonly number[];+ }[];+ };readonly projectName: string | null;- readonly port: number | null;- readonly lastFocusedAt: number | null;- readonly canInstall: boolean;- readonly activeCompositionId: string | null;- readonly readOnly: boolean;- readonly origin: string;+ readonly installTarget: StudioProtocolInstallTarget | null;};+export type InstallInStudioErrorCode =+ | 'unsupported-origin'+ | 'no-compatible-studio'+ | 'studio-upgrade-required'+ | 'no-installable-target'+ | 'unsupported-protocol'+ | 'invalid-response'+ | 'target-expired'+ | 'request-rejected'+ | 'request-timed-out'+ | 'network-error';+export type InstallInStudioResult =| {readonly success: true;- readonly target: StudioInstallTarget;+ readonly status: 'awaiting-confirmation';+ readonly target: {+ readonly projectName: string | null;+ readonly compositionId: string;+ readonly studioOrigin: string;+ readonly studioVersion: string;+ };}| {readonly success: false;- readonly reason: string;+ readonly code: InstallInStudioErrorCode;+ readonly message: string;};-const probePorts = [3000, 3001, 3002, 3003, 3004, 3005, 3006, 3007, 3008, 3009];-const focusedStudioMaxAge = 5 * 60 * 1000;+type Fetcher = (+ input: string | URL | Request,+ options?: RequestInit,+) => Promise<Response>;-type InstallInStudioDependencies = {+export type InstallInStudioDependencies = {readonly fetchFn: Fetcher;readonly now: () => number;readonly ports: readonly number[];+ readonly pageOrigin: string | null;};-type Fetcher = (- input: string | URL | Request,- options?: RequestInit,-) => Promise<Response>;+const probePorts = [3000, 3001, 3002, 3003, 3004, 3005, 3006, 3007, 3008, 3009];+const focusedStudioMaxAge = 5 * 60 * 1000;+const requestTimeout = 2_000;++const failure = (+ code: InstallInStudioErrorCode,+ message: string,+): InstallInStudioResult => ({success: false, code, message});const fetchWithTimeout = async ({fetchFn,- options = {},+ options,url,}: {readonly fetchFn: Fetcher;- readonly options?: RequestInit;+ readonly options: RequestInit | null;readonly url: string;}) => {const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(), 700);+ const timeout = setTimeout(() => controller.abort(), requestTimeout);try {- return await fetchFn(url, {...options, signal: controller.signal});+ return await fetchFn(url, {+ ...(options ?? {}),+ signal: controller.signal,+ });} finally {clearTimeout(timeout);}};-const isNullableString = (value: unknown): value is string | null => {- return value === null || typeof value === 'string';-};+const isNullableString = (value: unknown): value is string | null =>+ value === null || typeof value === 'string';-const isStudioInstallTarget = (+const isInstallTarget = (value: unknown,-): value is Omit<StudioInstallTarget, 'origin'> => {- if (!isRecord(value)) {+): value is StudioProtocolInstallTarget => {+ return (+ isRecord(value) &&+ typeof value.id === 'string' &&+ value.id.length > 0 &&+ typeof value.expiresAt === 'number' &&+ Number.isFinite(value.expiresAt) &&+ typeof value.compositionId === 'string' &&+ value.compositionId.length > 0 &&+ typeof value.lastFocusedAt === 'number' &&+ Number.isFinite(value.lastFocusedAt)+ );+};++const isDescriptor = (value: unknown): value is StudioProtocolDescriptor => {+ if (+ !isRecord(value) ||+ value.protocol !== 'remotion-studio-protocol' ||+ value.protocolVersion !== 1 ||+ typeof value.studioVersion !== 'string' ||+ !isNullableString(value.projectName) ||+ !isRecord(value.capabilities) ||+ !Array.isArray(value.capabilities.install) ||+ value.capabilities.install.length !== 1+ ) {return false;}+ const [capability] = value.capabilities.install;return (- value.type === 'remotion-studio' &&- isNullableString(value.projectName) &&- (value.port === null ||- (typeof value.port === 'number' && Number.isFinite(value.port))) &&- (value.lastFocusedAt === null ||- (typeof value.lastFocusedAt === 'number' &&- Number.isFinite(value.lastFocusedAt))) &&- typeof value.canInstall === 'boolean' &&- isNullableString(value.activeCompositionId) &&- typeof value.readOnly === 'boolean'+ isRecord(capability) &&+ capability.payloadType === 'remotion-element' &&+ Array.isArray(capability.payloadVersions) &&+ capability.payloadVersions.every(+ (version) => typeof version === 'number',+ ) &&+ (value.installTarget === null || isInstallTarget(value.installTarget)));};-const findBestStudioInstallTarget = async ({- fetchFn,- now,- ports,-}: InstallInStudioDependencies): Promise<StudioInstallTarget | null> => {- const targets = await Promise.all(- ports.map(async (port): Promise<StudioInstallTarget | null> => {+const hasSupportedElementCapability = (+ descriptor: StudioProtocolDescriptor,+): boolean => descriptor.capabilities.install[0]!.payloadVersions.includes(1);++const isAllowedOrigin = (origin: string | null): boolean => {+ if (origin === null) {+ return false;+ }++ try {+ const parsed = new URL(origin);+ return (+ (parsed.protocol === 'https:' &&+ (parsed.hostname === 'remotion.dev' ||+ parsed.hostname === 'www.remotion.dev')) ||+ (parsed.protocol === 'http:' &&+ (parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1'))+ );+ } catch {+ return false;+ }+};++type DiscoveredStudio = {+ readonly descriptor: StudioProtocolDescriptor;+ readonly discoveredAt: number;+ readonly origin: string;+};++const discoverStudios = async (+ dependencies: InstallInStudioDependencies,+): Promise<{+ readonly studios: DiscoveredStudio[];+ readonly foundUnsupportedProtocol: boolean;+ readonly foundInvalidResponse: boolean;+}> => {+ let foundUnsupportedProtocol = false;+ let foundInvalidResponse = false;+ const studios = await Promise.all(+ dependencies.ports.map(async (port): Promise<DiscoveredStudio | null> => {const origin = `http://localhost:${port}`;try {const response = await fetchWithTimeout({- fetchFn,- url: `${origin}/api/element-install-target`,+ fetchFn: dependencies.fetchFn,+ options: {cache: 'no-store'},+ url: `${origin}/api/studio-protocol`,});if (!response.ok) {return null;}- const target: unknown = await response.json();- if (!isStudioInstallTarget(target)) {+ const value: unknown = await response.json();+ if (+ isRecord(value) &&+ value.protocol === 'remotion-studio-protocol' &&+ value.protocolVersion !== 1+ ) {+ foundUnsupportedProtocol = true;return null;}- return {...target, origin};+ if (!isDescriptor(value)) {+ foundInvalidResponse = true;+ return null;+ }++ return {+ descriptor: value,+ discoveredAt: dependencies.now(),+ origin,+ };} catch {return null;}}),);- const currentTime = now();- const installableTargets = targets.filter(- (target): target is StudioInstallTarget =>- target !== null &&- target.canInstall &&- target.lastFocusedAt !== null &&- currentTime - target.lastFocusedAt < focusedStudioMaxAge,- );+ return {+ studios: studios.filter(+ (studio): studio is DiscoveredStudio => studio !== null,+ ),+ foundUnsupportedProtocol,+ foundInvalidResponse,+ };+};- return (- installableTargets.sort((a, b) => b.lastFocusedAt! - a.lastFocusedAt!)[0] ??- null+const hasLegacyStudio = async (+ dependencies: InstallInStudioDependencies,+): Promise<boolean> => {+ const results = await Promise.all(+ dependencies.ports.map(async (port) => {+ try {+ const response = await fetchWithTimeout({+ fetchFn: dependencies.fetchFn,+ options: {cache: 'no-store'},+ url: `http://localhost:${port}/api/element-install-target`,+ });+ if (!response.ok) {+ return false;+ }++ const value: unknown = await response.json();+ return isRecord(value) && value.type === 'remotion-studio';+ } catch {+ return false;+ }+ }),);+ return results.some(Boolean);};+const isAbortError = (error: unknown): boolean =>+ error instanceof Error && error.name === 'AbortError';+export const installInStudioWithDependencies = async (- dragData: SerializedDragData,+ payload: StudioElementPayload,dependencies: InstallInStudioDependencies,): Promise<InstallInStudioResult> => {- const target = await findBestStudioInstallTarget(dependencies);- if (target === null) {- return {- success: false,- reason:- 'Focus the Remotion Studio you want to install into, then click again.',- };+ if (!isAllowedOrigin(dependencies.pageOrigin)) {+ return failure(+ 'unsupported-origin',+ 'Install in Studio is only supported on remotion.dev and local development origins.',+ );+ }++ const discovery = await discoverStudios(dependencies);+ if (discovery.studios.length === 0) {+ if (discovery.foundUnsupportedProtocol) {+ return failure(+ 'unsupported-protocol',+ 'The running Remotion Studio uses an unsupported Studio Protocol version.',+ );+ }++ if (await hasLegacyStudio(dependencies)) {+ return failure(+ 'studio-upgrade-required',+ 'This Remotion Studio does not support the Remotion Studio Protocol. Upgrade Remotion to 4.0.502 or newer.',+ );+ }++ if (discovery.foundInvalidResponse) {+ return failure(+ 'invalid-response',+ 'Remotion Studio returned an invalid Studio Protocol response.',+ );+ }++ return failure(+ 'no-compatible-studio',+ 'Start Remotion Studio and open a composition, then try again.',+ );+ }++ const supportedStudios = discovery.studios.filter(({descriptor}) =>+ hasSupportedElementCapability(descriptor),+ );+ if (supportedStudios.length === 0) {+ return failure(+ 'unsupported-protocol',+ 'The running Remotion Studio cannot install this Element payload version.',+ );+ }++ const now = dependencies.now();+ const installable = supportedStudios+ .filter(({descriptor}) => {+ const target = descriptor.installTarget;+ return (+ target !== null &&+ target.expiresAt > now &&+ now - target.lastFocusedAt < focusedStudioMaxAge+ );+ })+ .sort((a, b) => {+ const focusDifference =+ b.descriptor.installTarget!.lastFocusedAt -+ a.descriptor.installTarget!.lastFocusedAt;+ return focusDifference === 0+ ? b.discoveredAt - a.discoveredAt+ : focusDifference;+ });+ const selected = installable[0];+ if (!selected || selected.descriptor.installTarget === null) {+ return failure(+ 'no-installable-target',+ 'Focus a writable composition in Remotion Studio, then try again.',+ );}try {const response = await fetchWithTimeout({fetchFn: dependencies.fetchFn,- url: `${target.origin}/api/request-element-install`,+ url: `${selected.origin}/api/studio-protocol/install`,options: {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify({- mimeType: dragData.mimeType,- payload: dragData.payload,+ protocol: 'remotion-studio-protocol',+ protocolVersion: 1,+ targetId: selected.descriptor.installTarget.id,+ payload,}),},});const result: unknown = await response.json();-if (- !response.ok ||- !isRecord(result) ||- result.success !== true ||- result.status !== 'sent'+ response.ok &&+ isRecord(result) &&+ result.protocol === 'remotion-studio-protocol' &&+ result.protocolVersion === 1 &&+ result.status === 'awaiting-confirmation') {return {- success: false,- reason:- isRecord(result) &&- result.success === false &&- typeof result.reason === 'string'- ? result.reason- : 'Could not send payload to Remotion Studio.',+ success: true,+ status: 'awaiting-confirmation',+ target: {+ projectName: selected.descriptor.projectName,+ compositionId: selected.descriptor.installTarget.compositionId,+ studioOrigin: selected.origin,+ studioVersion: selected.descriptor.studioVersion,+ },};}- return {success: true, target};+ if (+ isRecord(result) &&+ result.status === 'error' &&+ isRecord(result.error) &&+ typeof result.error.code === 'string' &&+ typeof result.error.message === 'string'+ ) {+ const {code} = result.error;+ return failure(+ code === 'target-expired' ? 'target-expired' : 'request-rejected',+ result.error.message,+ );+ }++ return failure(+ 'invalid-response',+ 'Remotion Studio returned an invalid installation response.',+ );} catch (error) {- return {- success: false,- reason: error instanceof Error ? error.message : String(error),- };+ return failure(+ isAbortError(error) ? 'request-timed-out' : 'network-error',+ isAbortError(error)+ ? 'The request to Remotion Studio timed out.'+ : 'Could not connect to Remotion Studio.',+ );}};-export const installInStudio = (- dragData: SerializedDragData,-): Promise<InstallInStudioResult> => {- return installInStudioWithDependencies(dragData, {+export const installInStudio = ({+ payload,+}: {+ readonly payload: StudioElementPayload;+}): Promise<InstallInStudioResult> => {+ return installInStudioWithDependencies(payload, {fetchFn: fetch,now: Date.now,+ pageOrigin:+ typeof globalThis.location === 'undefined'+ ? null+ : globalThis.location.origin,ports: probePorts,});};diff --git a/packages/studio-protocol/src/test/element-payload.test.ts b/packages/studio-protocol/src/test/element-payload.test.tsnew file mode 100644index 0000000000..edb9095853--- /dev/null+++ b/packages/studio-protocol/src/test/element-payload.test.ts@@ -0,0 +1,86 @@+import {expect, test} from 'bun:test';+import {parseDragData} from '../drag-data';+import {setStudioDragData} from '../drag-transport';+import {createElementPayload} from '../element-payload';++const validInput = {+ dependencies: ['remotion', 'remotion'],+ dimensions: {width: 800, height: 200},+ displayName: 'Lower Third',+ durationInFrames: 90,+ slug: 'lower-third',+ sourceCode: 'export const LowerThird = () => null;',+};++test('creates one canonical Element payload for HTTP and drag transports', () => {+ const payload = createElementPayload(validInput);+ expect(payload).toEqual({+ type: 'remotion-element',+ version: 1,+ durationInFrames: 90,+ element: {+ dependencies: ['remotion'],+ dimensions: {width: 800, height: 200},+ displayName: 'Lower Third',+ slug: 'lower-third',+ sourceCode: 'export const LowerThird = () => null;',+ },+ });++ const data = new Map<string, string>();+ const dataTransfer = {+ effectAllowed: 'none',+ setData: (type: string, value: string) => data.set(type, value),+ } as unknown as DataTransfer;+ setStudioDragData({dataTransfer, payload});++ expect(dataTransfer.effectAllowed).toBe('copy');+ const [mimeType] = data.keys();+ expect(mimeType).toBe(+ 'application/vnd.remotion.drag+json;v=1;type=element;width=800;height=200;duration=90',+ );+ expect(+ parseDragData({mimeType: mimeType!, payload: data.get(mimeType!)!}),+ ).toMatchObject({+ type: 'element',+ data: {element: {displayName: 'Lower Third'}},+ preview: {width: 800, height: 200, durationInFrames: 90},+ });+});++test('rejects invalid Element authoring input with actionable errors', () => {+ const cases: Array<{+ input: typeof validInput;+ message: string;+ }> = [+ {+ input: {...validInput, slug: '../unsafe'},+ message: 'slug must be a safe lowercase Element slug',+ },+ {+ input: {+ ...validInput,+ sourceCode:+ 'export const First = () => null; export const Second = () => null;',+ },+ message:+ 'sourceCode must contain exactly one exported named React component',+ },+ {+ input: {...validInput, dependencies: ['FS']},+ message: 'Invalid dependency package name: FS',+ },+ {+ input: {...validInput, dimensions: {width: 0, height: 200}},+ message: 'width and height must be numbers between 0 and 100000',+ },+ {+ input: {...validInput, durationInFrames: 0},+ message: 'durationInFrames must be an integer between 1 and 100000000',+ },+ ];++ for (const {input, message} of cases) {+ expect(() => createElementPayload(input)).toThrow(message);+ }+});diff --git a/packages/studio-protocol/src/test/install-in-studio.test.ts b/packages/studio-protocol/src/test/install-in-studio.test.tsindex 4d028a46eb..237e5d165e 100644--- a/packages/studio-protocol/src/test/install-in-studio.test.ts+++ b/packages/studio-protocol/src/test/install-in-studio.test.ts@@ -1,129 +1,258 @@import {expect, test} from 'bun:test';+import {createElementPayload} from '../element-payload';import {installInStudioWithDependencies} from '../install-in-studio';-const dragData = {- mimeType: 'application/vnd.remotion.drag+json;v=1;type=element;duration=90',- payload: '{"type":"remotion-element"}',- data: {type: 'not-sent'},-};+const elementPayload = createElementPayload({+ dependencies: ['remotion'],+ dimensions: {width: 800, height: 200},+ displayName: 'Lower Third',+ durationInFrames: 90,+ slug: 'lower-third',+ sourceCode: 'export const LowerThird = () => null;',+});-const target = ({+const descriptor = ({+ compositionId,lastFocusedAt,projectName,+ targetId,}: {- lastFocusedAt: number;- projectName: string;+ readonly compositionId: string;+ readonly lastFocusedAt: number;+ readonly projectName: string;+ readonly targetId: string;}) => ({- type: 'remotion-studio' as const,+ protocol: 'remotion-studio-protocol',+ protocolVersion: 1,+ studioVersion: '4.0.502',+ capabilities: {+ install: [{payloadType: 'remotion-element', payloadVersions: [1]}],+ },projectName,- port: 3000,- lastFocusedAt,- canInstall: true,- activeCompositionId: 'Main',- readOnly: false,+ installTarget: {+ id: targetId,+ expiresAt: 1_010_000,+ compositionId,+ lastFocusedAt,+ },});-const jsonResponse = (value: unknown, status = 200) => {- return new Response(JSON.stringify(value), {+const jsonResponse = (value: unknown, status = 200) =>+ new Response(JSON.stringify(value), {headers: {'Content-Type': 'application/json'},status,});++const dependencies = {+ now: () => 1_000_000,+ pageOrigin: 'http://localhost:4000',+ ports: [3000, 3001],};-test('installs into the most recently focused Studio', async () => {+test('delivers the payload to the exact most recently focused Studio target', async () => {const requests: Array<{url: string; options?: RequestInit}> = [];const fetchFn = (input: string | URL | Request, options?: RequestInit) => {const url = String(input);requests.push({url, options});-- if (url === 'http://localhost:3000/api/element-install-target') {+ if (url === 'http://localhost:3000/api/studio-protocol') {return Promise.resolve(jsonResponse(- target({lastFocusedAt: 900_000, projectName: 'Older project'}),+ descriptor({+ compositionId: 'Older',+ lastFocusedAt: 900_000,+ projectName: 'Older project',+ targetId: 'older-target',+ }),),);}- if (url === 'http://localhost:3001/api/element-install-target') {+ if (url === 'http://localhost:3001/api/studio-protocol') {return Promise.resolve(jsonResponse(- target({lastFocusedAt: 950_000, projectName: 'Newest project'}),+ descriptor({+ compositionId: 'Main',+ lastFocusedAt: 950_000,+ projectName: 'Newest project',+ targetId: 'newest-target',+ }),),);}- if (url === 'http://localhost:3001/api/request-element-install') {- return Promise.resolve(jsonResponse({success: true, status: 'sent'}));+ if (url === 'http://localhost:3001/api/studio-protocol/install') {+ return Promise.resolve(+ jsonResponse({+ protocol: 'remotion-studio-protocol',+ protocolVersion: 1,+ status: 'awaiting-confirmation',+ }),+ );}return Promise.resolve(new Response(null, {status: 404}));};- const result = await installInStudioWithDependencies(dragData, {+ const result = await installInStudioWithDependencies(elementPayload, {+ ...dependencies,fetchFn,- now: () => 1_000_000,- ports: [3000, 3001],});expect(result).toEqual({success: true,+ status: 'awaiting-confirmation',target: {- ...target({lastFocusedAt: 950_000, projectName: 'Newest project'}),- origin: 'http://localhost:3001',+ projectName: 'Newest project',+ compositionId: 'Main',+ studioOrigin: 'http://localhost:3001',+ studioVersion: '4.0.502',},});- expect(requests.at(-1)).toEqual({- url: 'http://localhost:3001/api/request-element-install',- options: {- method: 'POST',- headers: {'Content-Type': 'application/json'},- body: JSON.stringify({- mimeType: dragData.mimeType,- payload: dragData.payload,- }),- signal: expect.any(AbortSignal),- },+ const installRequest = requests.at(-1);+ expect(installRequest?.url).toBe(+ 'http://localhost:3001/api/studio-protocol/install',+ );+ expect(JSON.parse(String(installRequest?.options?.body))).toEqual({+ protocol: 'remotion-studio-protocol',+ protocolVersion: 1,+ targetId: 'newest-target',+ payload: elementPayload,});});-test('returns an actionable error if no focused Studio is available', async () => {- const fetchFn = () => Promise.resolve(new Response(null, {status: 404}));+test('distinguishes a compatible Studio without an installable target', async () => {+ const fetchFn = (input: string | URL | Request) => {+ const url = String(input);+ if (url === 'http://localhost:3000/api/studio-protocol') {+ return Promise.resolve(+ jsonResponse({+ ...descriptor({+ compositionId: 'Main',+ lastFocusedAt: 950_000,+ projectName: 'Project',+ targetId: 'target',+ }),+ installTarget: null,+ }),+ );+ }++ return Promise.resolve(new Response(null, {status: 404}));+ };- const result = await installInStudioWithDependencies(dragData, {- fetchFn,- now: () => 1_000_000,- ports: [3000],+ expect(+ await installInStudioWithDependencies(elementPayload, {+ ...dependencies,+ fetchFn,+ }),+ ).toEqual({+ success: false,+ code: 'no-installable-target',+ message: 'Focus a writable composition in Remotion Studio, then try again.',+ });+});++test('returns an actionable result when no Studio is running', async () => {+ const result = await installInStudioWithDependencies(elementPayload, {+ ...dependencies,+ fetchFn: () => Promise.resolve(new Response(null, {status: 404})),});expect(result).toEqual({success: false,- reason:- 'Focus the Remotion Studio you want to install into, then click again.',+ code: 'no-compatible-studio',+ message: 'Start Remotion Studio and open a composition, then try again.',});});-test('returns the error from Studio if installation is rejected', async () => {+test('reports a legacy Studio as requiring an upgrade without sending a payload', async () => {+ const requests: string[] = [];const fetchFn = (input: string | URL | Request) => {const url = String(input);- if (url.endsWith('/api/element-install-target')) {+ requests.push(url);+ if (url === 'http://localhost:3000/api/element-install-target') {+ return Promise.resolve(+ jsonResponse({type: 'remotion-studio', canInstall: true}),+ );+ }++ return Promise.resolve(new Response(null, {status: 404}));+ };++ expect(+ await installInStudioWithDependencies(elementPayload, {+ ...dependencies,+ fetchFn,+ }),+ ).toEqual({+ success: false,+ code: 'studio-upgrade-required',+ message:+ 'This Remotion Studio does not support the Remotion Studio Protocol. Upgrade Remotion to 4.0.502 or newer.',+ });+ expect(+ requests.some((url) => url.endsWith('/api/request-element-install')),+ ).toBe(false);+});++test('returns a structured error when the selected target expired', async () => {+ const fetchFn = (input: string | URL | Request) => {+ const url = String(input);+ if (url.endsWith('/api/studio-protocol')) {return Promise.resolve(- jsonResponse(target({lastFocusedAt: 950_000, projectName: 'Project'})),+ jsonResponse(+ descriptor({+ compositionId: 'Main',+ lastFocusedAt: 950_000,+ projectName: 'Project',+ targetId: 'expired-target',+ }),+ ),);}return Promise.resolve(- jsonResponse({success: false, reason: 'No active composition'}, 409),+ jsonResponse(+ {+ protocol: 'remotion-studio-protocol',+ protocolVersion: 1,+ status: 'error',+ error: {code: 'target-expired', message: 'Target expired'},+ },+ 409,+ ),);};- const result = await installInStudioWithDependencies(dragData, {- fetchFn,- now: () => 1_000_000,- ports: [3000],+ expect(+ await installInStudioWithDependencies(elementPayload, {+ ...dependencies,+ ports: [3000],+ fetchFn,+ }),+ ).toEqual({+ success: false,+ code: 'target-expired',+ message: 'Target expired',+ });+});++test('does not probe Studio from an unsupported origin', async () => {+ let requests = 0;+ const result = await installInStudioWithDependencies(elementPayload, {+ ...dependencies,+ fetchFn: () => {+ requests++;+ return Promise.resolve(new Response(null, {status: 404}));+ },+ pageOrigin: 'https://example.com',});expect(result).toEqual({success: false,- reason: 'No active composition',+ code: 'unsupported-origin',+ message:+ 'Install in Studio is only supported on remotion.dev and local development origins.',});+ expect(requests).toBe(0);});diff --git a/packages/studio-shared/src/package-info.ts b/packages/studio-shared/src/package-info.tsindex 569099fc29..8d1ca477b1 100644--- a/packages/studio-shared/src/package-info.ts+++ b/packages/studio-shared/src/package-info.ts@@ -249,7 +249,8 @@ export const descriptions: {[key in Pkgs]: string | null} = {'remotion-media': null,'web-renderer': 'Render videos in the browser',design: 'Design system',- 'studio-protocol': 'Construct and parse drag-and-drop payloads for Remotion',+ 'studio-protocol':+ 'Create Element payloads and request installation into Remotion Studio','light-leaks': 'Light leak effects for Remotion','rough-notation': 'Rough annotation primitives for Remotion','player-a11y': 'Internal accessibility wrapper around @remotion/player',