Skip to content

🎥 Make videos programmatically with React

Validate Studio Protocol data with Zod Mini (#10983)

Igor Samokhovetsc9147ae3df54
diff --git a/bun.lock b/bun.lock
index 260aa42654..74d8cdd310 100644
--- a/bun.lock
+++ b/bun.lock
@@ -1856,6 +1856,9 @@
"packages/studio-protocol": {
"name": "@remotion/studio-protocol",
"version": "4.0.519",
+ "dependencies": {
+ "zod": "catalog:",
+ },
"devDependencies": {
"@remotion/eslint-config-internal": "workspace:*",
"@typescript/native-preview": "catalog:",
diff --git a/packages/studio-protocol/package.json b/packages/studio-protocol/package.json
index 0d194d7b4c..d793ff0a16 100644
--- a/packages/studio-protocol/package.json
+++ b/packages/studio-protocol/package.json
@@ -32,6 +32,9 @@
},
"./package.json": "./package.json"
},
+ "dependencies": {
+ "zod": "catalog:"
+ },
"devDependencies": {
"@remotion/eslint-config-internal": "workspace:*",
"eslint": "catalog:",
diff --git a/packages/studio-protocol/src/add-element-library-to-studio.ts b/packages/studio-protocol/src/add-element-library-to-studio.ts
index 81527fabf5..7f8b3a4184 100644
--- a/packages/studio-protocol/src/add-element-library-to-studio.ts
+++ b/packages/studio-protocol/src/add-element-library-to-studio.ts
@@ -1,3 +1,4 @@
+import * as z from 'zod/mini';
import {isAllowedStudioProtocolPageOrigin} from './install-in-studio';
import type {StudioProtocolFetcher} from './studio-discovery';
import {
@@ -9,7 +10,10 @@ import {
isAbortError,
studioProtocolProbePorts,
} from './studio-discovery';
-import {isRecord} from './validation';
+import {
+ isAwaitingConfirmationResponse,
+ parseStudioProtocolError,
+} from './studio-response';
export type AddElementLibraryToStudioInput = {
readonly url: string;
@@ -63,6 +67,25 @@ export type StudioProtocolAddElementLibraryRequest = {
readonly displayName: string | null;
};
+const studioProtocolAddElementLibraryRequestSchema = z.object({
+ operation: z.literal('add-element-library'),
+ protocol: z.literal('remotion-studio-protocol'),
+ protocolVersion: z.literal(1),
+ targetId: z.string().check(z.minLength(1)),
+ url: z.string(),
+ displayName: z.nullable(z.string()),
+});
+
+export const parseStudioProtocolAddElementLibraryRequest = (
+ value: unknown,
+): StudioProtocolAddElementLibraryRequest | null => {
+ const parsed = z.safeParse(
+ studioProtocolAddElementLibraryRequestSchema,
+ value,
+ );
+ return parsed.success ? parsed.data : null;
+};
+
const failure = (
code: AddElementLibraryToStudioErrorCode,
message: string,
@@ -227,13 +250,7 @@ export const addElementLibraryToStudioWithDependencies = async (
);
}
- if (
- response.ok &&
- isRecord(result) &&
- result.protocol === 'remotion-studio-protocol' &&
- result.protocolVersion === 1 &&
- result.status === 'awaiting-confirmation'
- ) {
+ if (response.ok && isAwaitingConfirmationResponse(result)) {
return {
success: true,
status: 'awaiting-confirmation',
@@ -245,21 +262,15 @@ export const addElementLibraryToStudioWithDependencies = async (
};
}
- if (
- isRecord(result) &&
- result.status === 'error' &&
- isRecord(result.error) &&
- typeof result.error.code === 'string' &&
- typeof result.error.message === 'string'
- ) {
- const {code, message} = result.error;
+ const protocolError = parseStudioProtocolError(result);
+ if (protocolError !== null) {
return failure(
- code === 'target-expired'
+ protocolError.code === 'target-expired'
? 'target-expired'
- : code === 'no-config-file'
+ : protocolError.code === 'no-config-file'
? 'no-config-file'
: 'request-rejected',
- message,
+ protocolError.message,
);
}
diff --git a/packages/studio-protocol/src/asset-drag-data.ts b/packages/studio-protocol/src/asset-drag-data.ts
index 81076329dd..3c197c3965 100644
--- a/packages/studio-protocol/src/asset-drag-data.ts
+++ b/packages/studio-protocol/src/asset-drag-data.ts
@@ -1,4 +1,4 @@
-import {isRecord} from './validation';
+import * as z from 'zod/mini';
export type AssetDragData = {
type: 'remotion-asset';
@@ -6,6 +6,12 @@ export type AssetDragData = {
assetPath: string;
};
+const assetDragDataSchema = z.object({
+ type: z.literal('remotion-asset'),
+ version: z.literal(1),
+ assetPath: z.string().check(z.minLength(1)),
+});
+
export const makeAssetDragData = (assetPath: string): AssetDragData => {
return {
type: 'remotion-asset',
@@ -16,18 +22,8 @@ export const makeAssetDragData = (assetPath: string): AssetDragData => {
export const parseAssetDragData = (value: string): AssetDragData | null => {
try {
- const parsed: unknown = JSON.parse(value);
- if (
- !isRecord(parsed) ||
- parsed.type !== 'remotion-asset' ||
- parsed.version !== 1 ||
- typeof parsed.assetPath !== 'string' ||
- parsed.assetPath.length === 0
- ) {
- return null;
- }
-
- return makeAssetDragData(parsed.assetPath);
+ const parsed = z.safeParse(assetDragDataSchema, JSON.parse(value));
+ return parsed.success ? makeAssetDragData(parsed.data.assetPath) : null;
} catch {
return null;
}
diff --git a/packages/studio-protocol/src/browser-studio-link.ts b/packages/studio-protocol/src/browser-studio-link.ts
index 66663d4bc1..7d3121ca9a 100644
--- a/packages/studio-protocol/src/browser-studio-link.ts
+++ b/packages/studio-protocol/src/browser-studio-link.ts
@@ -1,11 +1,16 @@
+import * as z from 'zod/mini';
import type {StudioElementPayload} from './element-payload';
import {parseStudioElementPayload} from './element-payload';
-import {isRecord} from './validation';
const browserStudioHashKey = 'remotion-browser-studio';
const defaultBrowserStudioEndpoint =
'https://www.remotion.dev/experimental_new';
const maxEncodedPayloadLength = 1_100_000;
+const browserStudioEnvelopeSchema = z.object({
+ type: z.literal('remotion-browser-studio'),
+ version: z.literal(1),
+ payload: z.unknown(),
+});
const toBase64Url = (value: string) => {
const bytes = new TextEncoder().encode(value);
@@ -97,16 +102,13 @@ export const parseBrowserStudioHash = (
}
try {
- const envelope: unknown = JSON.parse(decoded);
- if (
- !isRecord(envelope) ||
- envelope.type !== 'remotion-browser-studio' ||
- envelope.version !== 1
- ) {
- return null;
- }
-
- return parseStudioElementPayload(envelope.payload);
+ const envelope = z.safeParse(
+ browserStudioEnvelopeSchema,
+ JSON.parse(decoded),
+ );
+ return envelope.success
+ ? parseStudioElementPayload(envelope.data.payload)
+ : null;
} catch {
return null;
}
diff --git a/packages/studio-protocol/src/component-drag-data.ts b/packages/studio-protocol/src/component-drag-data.ts
index e68dcf129d..2739d47ab1 100644
--- a/packages/studio-protocol/src/component-drag-data.ts
+++ b/packages/studio-protocol/src/component-drag-data.ts
@@ -1,4 +1,4 @@
-import {isRecord} from './validation';
+import * as z from 'zod/mini';
export type ComponentProp = {
name: string;
@@ -22,75 +22,69 @@ export type ComponentDragData = {
};
};
-export const isComponentIdentifier = (value: unknown): value is string => {
- return typeof value === 'string' && /^[A-Z_$][A-Za-z0-9_$]*$/.test(value);
-};
-
-export const isComponentImportPath = (value: unknown): value is string => {
- return (
- typeof value === 'string' &&
- value.length > 0 &&
- value.length < 200 &&
- !value.includes('\\') &&
- !value.includes('\0') &&
- !value.startsWith('/') &&
- /^[A-Za-z0-9@._/-]+$/.test(value)
- );
-};
-
-export const isComponentPropName = (value: unknown): value is string => {
- return (
- typeof value === 'string' &&
- value !== 'style' &&
- /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(value)
+const componentIdentifierSchema = z
+ .string()
+ .check(z.regex(/^[A-Z_$][A-Za-z0-9_$]*$/));
+const componentImportPathSchema = z
+ .string()
+ .check(
+ z.refine(
+ (value) =>
+ value.length > 0 &&
+ value.length < 200 &&
+ !value.includes('\\') &&
+ !value.includes('\0') &&
+ !value.startsWith('/') &&
+ /^[A-Za-z0-9@._/-]+$/.test(value),
+ ),
);
-};
-
-export const isComponentProp = (value: unknown): value is ComponentProp => {
- if (!isRecord(value) || !isComponentPropName(value.name)) {
- return false;
- }
-
- return (
- typeof value.value === 'string' ||
- typeof value.value === 'boolean' ||
- (typeof value.value === 'number' && Number.isFinite(value.value))
- );
-};
-
-export const areComponentProps = (value: unknown): value is ComponentProp[] => {
- if (!Array.isArray(value)) {
- return false;
- }
-
- const seen = new Set<string>();
- for (const prop of value) {
- if (!isComponentProp(prop) || seen.has(prop.name)) {
- return false;
- }
-
- seen.add(prop.name);
- }
-
- return true;
-};
-
-const isComponentDimensions = (
- value: unknown,
-): value is ComponentDimensions => {
- if (!isRecord(value)) {
- return false;
- }
-
- return (
- typeof value.width === 'number' &&
- Number.isFinite(value.width) &&
- value.width >= 0 &&
- typeof value.height === 'number' &&
- Number.isFinite(value.height) &&
- value.height >= 0
+const componentPropNameSchema = z
+ .string()
+ .check(
+ z.refine(
+ (value) => value !== 'style' && /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(value),
+ ),
);
-};
+const componentPropSchema = z.object({
+ name: componentPropNameSchema,
+ value: z.union([z.string(), z.number(), z.boolean()]),
+});
+const componentPropsSchema = z.array(componentPropSchema).check(
+ z.refine((props) => {
+ const names = props.map((prop) => prop.name);
+ return new Set(names).size === names.length;
+ }),
+);
+const componentDimensionsSchema = z.object({
+ width: z.number().check(z.nonnegative()),
+ height: z.number().check(z.nonnegative()),
+});
+const componentDragDataSchema = z.object({
+ type: z.literal('remotion-component'),
+ version: z.literal(1),
+ component: z.object({
+ componentName: componentIdentifierSchema,
+ dimensions: z.optional(componentDimensionsSchema),
+ importName: componentIdentifierSchema,
+ importPath: componentImportPathSchema,
+ props: componentPropsSchema,
+ }),
+});
+
+export const isComponentIdentifier = (value: unknown): value is string =>
+ z.safeParse(componentIdentifierSchema, value).success;
+
+export const isComponentImportPath = (value: unknown): value is string =>
+ z.safeParse(componentImportPathSchema, value).success;
+
+export const isComponentPropName = (value: unknown): value is string =>
+ z.safeParse(componentPropNameSchema, value).success;
+
+export const isComponentProp = (value: unknown): value is ComponentProp =>
+ z.safeParse(componentPropSchema, value).success;
+
+export const areComponentProps = (value: unknown): value is ComponentProp[] =>
+ z.safeParse(componentPropsSchema, value).success;
export const makeComponentDragData = ({
componentName,
@@ -122,34 +116,17 @@ export const parseComponentDragData = (
value: string,
): ComponentDragData | null => {
try {
- const parsed: unknown = JSON.parse(value);
- if (
- !isRecord(parsed) ||
- parsed.type !== 'remotion-component' ||
- parsed.version !== 1 ||
- !isRecord(parsed.component)
- ) {
- return null;
- }
-
- const {componentName, dimensions, importName, importPath, props} =
- parsed.component;
- if (
- !isComponentIdentifier(componentName) ||
- !isComponentIdentifier(importName) ||
- !isComponentImportPath(importPath) ||
- !areComponentProps(props) ||
- (typeof dimensions !== 'undefined' && !isComponentDimensions(dimensions))
- ) {
+ const parsed = z.safeParse(componentDragDataSchema, JSON.parse(value));
+ if (!parsed.success) {
return null;
}
return makeComponentDragData({
- componentName,
- dimensions: dimensions ?? null,
- importName,
- importPath,
- props,
+ componentName: parsed.data.component.componentName,
+ dimensions: parsed.data.component.dimensions ?? null,
+ importName: parsed.data.component.importName,
+ importPath: parsed.data.component.importPath,
+ props: parsed.data.component.props,
});
} catch {
return null;
diff --git a/packages/studio-protocol/src/effect-drag-data.ts b/packages/studio-protocol/src/effect-drag-data.ts
index 910e89178c..a0afc08f6a 100644
--- a/packages/studio-protocol/src/effect-drag-data.ts
+++ b/packages/studio-protocol/src/effect-drag-data.ts
@@ -1,4 +1,16 @@
-import {isRecord} from './validation';
+import * as z from 'zod/mini';
+
+export type EffectConfigValue =
+ | string
+ | number
+ | boolean
+ | null
+ | EffectConfig
+ | readonly EffectConfigValue[];
+
+export type EffectConfig = {
+ readonly [key: string]: EffectConfigValue;
+};
export type EffectDragData = {
type: 'remotion-effect';
@@ -6,13 +18,28 @@ export type EffectDragData = {
effect: {
name: string;
importPath: string;
- config: Record<string, unknown>;
+ config: EffectConfig;
};
};
+const effectConfigSchema = z.record(z.string(), z.json());
+const effectDragDataSchema = z.object({
+ type: z.literal('remotion-effect'),
+ version: z.literal(1),
+ effect: z.object({
+ name: z.string(),
+ importPath: z.string(),
+ config: effectConfigSchema,
+ }),
+});
+
export const makeEffectDragData = (
effect: EffectDragData['effect'],
): EffectDragData => {
+ if (!z.safeParse(effectConfigSchema, effect.config).success) {
+ throw new TypeError('Effect config must contain only finite JSON values');
+ }
+
return {
type: 'remotion-effect',
version: 1,
@@ -22,26 +49,16 @@ export const makeEffectDragData = (
export const parseEffectDragData = (value: string): EffectDragData | null => {
try {
- const parsed: unknown = JSON.parse(value);
- if (
- !isRecord(parsed) ||
- parsed.type !== 'remotion-effect' ||
- parsed.version !== 1 ||
- !isRecord(parsed.effect)
- ) {
- return null;
- }
-
- const {name, importPath, config} = parsed.effect;
- if (
- typeof name !== 'string' ||
- typeof importPath !== 'string' ||
- !isRecord(config)
- ) {
+ const parsed = z.safeParse(effectDragDataSchema, JSON.parse(value));
+ if (!parsed.success) {
return null;
}
- return makeEffectDragData({name, importPath, config});
+ return makeEffectDragData({
+ name: parsed.data.effect.name,
+ importPath: parsed.data.effect.importPath,
+ config: parsed.data.effect.config,
+ });
} catch {
return null;
}
diff --git a/packages/studio-protocol/src/element-drag-data.ts b/packages/studio-protocol/src/element-drag-data.ts
index 51efda6ba3..4e43df0f4f 100644
--- a/packages/studio-protocol/src/element-drag-data.ts
+++ b/packages/studio-protocol/src/element-drag-data.ts
@@ -1,8 +1,9 @@
+import * as z from 'zod/mini';
import {
isComponentIdentifier,
type ComponentDimensions,
} from './component-drag-data';
-import {isRecord, isValidPackageName} from './validation';
+import {isValidPackageName} from './validation';
export type ElementInstallationMode = 'wrapped' | 'component-owned-sequence';
@@ -30,31 +31,40 @@ export type ElementDragData = {
};
};
-export const isLowercaseElementFileName = (value: unknown): value is string => {
- return (
- typeof value === 'string' &&
- value.length > 0 &&
- value.length < 120 &&
- value === value.toLowerCase() &&
- value.endsWith('.tsx') &&
- !value.includes('/') &&
- !value.includes('\\') &&
- !value.includes('\0') &&
- !value.includes('..') &&
- /^[a-z0-9][a-z0-9.-]*\.tsx$/.test(value)
+const lowercaseElementFileNameSchema = z
+ .string()
+ .check(
+ z.refine(
+ (value) =>
+ value.length > 0 &&
+ value.length < 120 &&
+ value === value.toLowerCase() &&
+ value.endsWith('.tsx') &&
+ !value.includes('/') &&
+ !value.includes('\\') &&
+ !value.includes('\0') &&
+ !value.includes('..') &&
+ /^[a-z0-9][a-z0-9.-]*\.tsx$/.test(value),
+ ),
);
-};
-
-const isSlug = (value: unknown): value is string => {
- return (
- typeof value === 'string' &&
- value.length > 0 &&
- value.length < 120 &&
- /^[a-z0-9][a-z0-9/-]*$/.test(value) &&
- !value.includes('..') &&
- !value.includes('//')
+const slugSchema = z
+ .string()
+ .check(
+ z.refine(
+ (value) =>
+ value.length > 0 &&
+ value.length < 120 &&
+ /^[a-z0-9][a-z0-9/-]*$/.test(value) &&
+ !value.includes('..') &&
+ !value.includes('//'),
+ ),
);
-};
+
+export const isLowercaseElementFileName = (value: unknown): value is string =>
+ z.safeParse(lowercaseElementFileNameSchema, value).success;
+
+const isSlug = (value: unknown): value is string =>
+ z.safeParse(slugSchema, value).success;
export const makeElementFileNameFromSlug = (slug: string) => {
if (!isSlug(slug)) return null;
@@ -83,36 +93,43 @@ const packagesProvidedByRemotionProjects = new Set([
'remotion',
]);
-const isExactVersion = (value: unknown): value is string =>
- typeof value === 'string' &&
- /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.test(
- value,
+const exactVersionSchema = z
+ .string()
+ .check(
+ z.regex(
+ /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,
+ ),
);
+const elementDependencyEnvelopeSchema = z.looseObject({
+ name: z.string().check(z.refine(isValidPackageName)),
+ version: z.unknown(),
+});
const getElementDependencyError = (value: unknown): string | null => {
- if (
- !isRecord(value) ||
- typeof value.name !== 'string' ||
- !isValidPackageName(value.name)
- ) {
+ const parsed = z.safeParse(elementDependencyEnvelopeSchema, value);
+ if (!parsed.success) {
return `Invalid Element dependency: ${JSON.stringify(value)}`;
}
- if (packagesProvidedByRemotionProjects.has(value.name)) {
- return `${JSON.stringify(value.name)} is provided by Remotion projects and must not be declared as an Element dependency.`;
+ if (packagesProvidedByRemotionProjects.has(parsed.data.name)) {
+ return `${JSON.stringify(parsed.data.name)} is provided by Remotion projects and must not be declared as an Element dependency.`;
}
- if (value.name.startsWith('@remotion/')) {
- return value.version === null
+ if (parsed.data.name.startsWith('@remotion/')) {
+ return parsed.data.version === null
? null
- : `Remotion Element dependency ${JSON.stringify(value.name)} must use version: null.`;
+ : `Remotion Element dependency ${JSON.stringify(parsed.data.name)} must use version: null.`;
}
- return isExactVersion(value.version)
+ return z.safeParse(exactVersionSchema, parsed.data.version).success
? null
- : `Non-Remotion Element dependency ${JSON.stringify(value.name)} must declare an exact version.`;
+ : `Non-Remotion Element dependency ${JSON.stringify(parsed.data.name)} must declare an exact version.`;
};
+const elementDependencySchema = elementDependencyEnvelopeSchema.check(
+ z.refine((value) => getElementDependencyError(value) === null),
+);
+
export function assertElementDependency(
value: unknown,
): asserts value is ElementDependency {
@@ -124,7 +141,8 @@ export function assertElementDependency(
export const isElementDependency = (
value: unknown,
-): value is ElementDependency => getElementDependencyError(value) === null;
+): value is ElementDependency =>
+ z.safeParse(elementDependencySchema, value).success;
export const makeElementDragData = ({
dependencies,
@@ -162,77 +180,67 @@ export const makeElementDragData = ({
};
};
-const isDimensions = (value: unknown): value is ComponentDimensions =>
- isRecord(value) &&
- typeof value.width === 'number' &&
- Number.isFinite(value.width) &&
- value.width > 0 &&
- typeof value.height === 'number' &&
- Number.isFinite(value.height) &&
- value.height > 0;
-
-const isElementInstallationMode = (
- value: unknown,
-): value is ElementInstallationMode =>
- value === 'wrapped' || value === 'component-owned-sequence';
-
-const isDuration = (value: unknown): value is number =>
- typeof value === 'number' &&
- Number.isInteger(value) &&
- value > 0 &&
- value <= 100_000_000;
+const dimensionsSchema = z.object({
+ width: z.number().check(z.positive()),
+ height: z.number().check(z.positive()),
+});
+const elementInstallationModeSchema = z.union([
+ z.literal('wrapped'),
+ z.literal('component-owned-sequence'),
+]);
+const durationSchema = z
+ .number()
+ .check(z.int(), z.positive(), z.lte(100_000_000));
+const elementDragDataSchema = z.object({
+ type: z.literal('remotion-element'),
+ version: z.literal(1),
+ element: z.object({
+ dependencies: z.array(z.unknown()).check(z.maxLength(100)),
+ durationInFrames: z.optional(durationSchema),
+ installationMode: z.optional(elementInstallationModeSchema),
+ slug: slugSchema,
+ displayName: z.string().check(z.minLength(1), z.maxLength(119)),
+ sourceCode: z
+ .string()
+ .check(
+ z.refine(
+ (value) =>
+ value.trim().length > 0 &&
+ value.length < 200_000 &&
+ getElementComponentNameFromSourceCode(value) !== null,
+ ),
+ ),
+ dimensions: z.optional(z.nullable(dimensionsSchema)),
+ }),
+});
export const parseElementDragData = (value: string): ElementDragData | null => {
try {
- const parsed: unknown = JSON.parse(value);
+ const parsed = z.safeParse(elementDragDataSchema, JSON.parse(value));
if (
- !isRecord(parsed) ||
- parsed.type !== 'remotion-element' ||
- parsed.version !== 1 ||
- !isRecord(parsed.element)
- )
- return null;
- const {
- dependencies,
- dimensions,
- displayName,
- durationInFrames,
- slug,
- sourceCode,
- installationMode,
- } = parsed.element;
- const validDependencies =
- Array.isArray(dependencies) && dependencies.length <= 100
- ? dependencies
- : null;
- if (
- !isSlug(slug) ||
- typeof displayName !== 'string' ||
- displayName.length === 0 ||
- displayName.length >= 120 ||
- typeof sourceCode !== 'string' ||
- sourceCode.trim().length === 0 ||
- sourceCode.length >= 200000 ||
- getElementComponentNameFromSourceCode(sourceCode) === null ||
- makeElementFileNameFromSlug(slug) === null ||
- validDependencies === null ||
- !validDependencies.every(isElementDependency) ||
- (durationInFrames !== undefined && !isDuration(durationInFrames)) ||
- (installationMode !== undefined &&
- !isElementInstallationMode(installationMode)) ||
- (dimensions !== undefined &&
- dimensions !== null &&
- !isDimensions(dimensions))
- )
+ !parsed.success ||
+ makeElementFileNameFromSlug(parsed.data.element.slug) === null
+ ) {
return null;
+ }
+
+ const dependencies: ElementDependency[] = [];
+ for (const dependency of parsed.data.element.dependencies) {
+ if (!isElementDependency(dependency)) {
+ return null;
+ }
+
+ dependencies.push(dependency);
+ }
+
return makeElementDragData({
- dependencies: validDependencies,
- dimensions: dimensions ?? null,
- displayName,
- durationInFrames,
- slug,
- sourceCode,
- installationMode,
+ dependencies,
+ dimensions: parsed.data.element.dimensions ?? null,
+ displayName: parsed.data.element.displayName,
+ durationInFrames: parsed.data.element.durationInFrames,
+ slug: parsed.data.element.slug,
+ sourceCode: parsed.data.element.sourceCode,
+ installationMode: parsed.data.element.installationMode,
});
} catch {
return null;
diff --git a/packages/studio-protocol/src/element-payload.ts b/packages/studio-protocol/src/element-payload.ts
index 2c6c4561d7..38d75f302e 100644
--- a/packages/studio-protocol/src/element-payload.ts
+++ b/packages/studio-protocol/src/element-payload.ts
@@ -1,3 +1,4 @@
+import * as z from 'zod/mini';
import type {ComponentDimensions} from './component-drag-data';
import {makeDragData} from './drag-data';
import {
@@ -9,7 +10,6 @@ import {
type ElementDragData,
type ElementInstallationMode,
} from './element-drag-data';
-import {isRecord} from './validation';
const MAX_PAYLOAD_SIZE = 250_000;
const MAX_SOURCE_CODE_SIZE = 200_000;
@@ -29,11 +29,16 @@ export type StudioElementPayload = ElementDragData & {
readonly durationInFrames: number;
};
+const durationSchema = z.int().check(z.positive(), z.lte(100_000_000));
+const studioElementPayloadEnvelopeSchema = z.object({
+ type: z.literal('remotion-element'),
+ version: z.literal(1),
+ durationInFrames: durationSchema,
+ element: z.unknown(),
+});
+
const isDuration = (value: unknown): value is number =>
- typeof value === 'number' &&
- Number.isInteger(value) &&
- value >= 1 &&
- value <= 100_000_000;
+ z.safeParse(durationSchema, value).success;
const assertCreateElementPayloadInput = (
input: CreateElementPayloadInput,
@@ -112,19 +117,16 @@ export const createElementPayload = (
export const parseStudioElementPayload = (
value: unknown,
): StudioElementPayload | null => {
- if (
- !isRecord(value) ||
- value.type !== 'remotion-element' ||
- value.version !== 1 ||
- !isDuration(value.durationInFrames) ||
- !isRecord(value.element)
- )
+ const parsed = z.safeParse(studioElementPayloadEnvelopeSchema, value);
+ if (!parsed.success) {
return null;
+ }
+
const element = parseElementDragData(
JSON.stringify({
- type: value.type,
- version: value.version,
- element: value.element,
+ type: parsed.data.type,
+ version: parsed.data.version,
+ element: parsed.data.element,
}),
);
if (element === null) return null;
@@ -132,9 +134,9 @@ export const parseStudioElementPayload = (
...element,
element: {
...element.element,
- durationInFrames: value.durationInFrames,
+ durationInFrames: parsed.data.durationInFrames,
},
- durationInFrames: value.durationInFrames,
+ durationInFrames: parsed.data.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.ts
index 72b508f90f..d34d60832d 100644
--- a/packages/studio-protocol/src/index.ts
+++ b/packages/studio-protocol/src/index.ts
@@ -1,4 +1,7 @@
-import {addElementLibraryToStudioWithDependencies} from './add-element-library-to-studio';
+import {
+ addElementLibraryToStudioWithDependencies,
+ parseStudioProtocolAddElementLibraryRequest,
+} from './add-element-library-to-studio';
import {
makeBrowserStudioUrl,
openInBrowserStudio,
@@ -16,9 +19,16 @@ import {
makeElementFileNameFromSlug,
} from './element-drag-data';
import {parseStudioElementPayload} from './element-payload';
-import {installInStudioWithDependencies} from './install-in-studio';
+import {
+ installInStudioWithDependencies,
+ parseStudioProtocolInstallRequest,
+} from './install-in-studio';
import {isValidPublicLicenseKey} from './license-key';
-import {setLicenseKeyInStudio} from './set-license-key-in-studio';
+import {
+ parseStudioProtocolSetLicenseKeyRequest,
+ setLicenseKeyInStudio,
+} from './set-license-key-in-studio';
+import {parseStudioProtocolDescriptor} from './studio-discovery';
export {
addElementLibraryToStudio,
@@ -57,7 +67,11 @@ export type {
SfxDragPreviewMetadata,
} from './drag-preview-metadata';
export {setStudioDragData} from './drag-transport';
-export type {EffectDragData} from './effect-drag-data';
+export type {
+ EffectConfig,
+ EffectConfigValue,
+ EffectDragData,
+} from './effect-drag-data';
export type {
ElementDependency,
ElementDragData,
@@ -97,5 +111,9 @@ export const StudioProtocolInternals = {
parseBrowserStudioHash,
parseDragData,
parseStudioElementPayload,
+ parseStudioProtocolAddElementLibraryRequest,
+ parseStudioProtocolDescriptor,
+ parseStudioProtocolInstallRequest,
+ parseStudioProtocolSetLicenseKeyRequest,
setLicenseKeyInStudio,
};
diff --git a/packages/studio-protocol/src/install-in-studio.ts b/packages/studio-protocol/src/install-in-studio.ts
index eb223bf561..1a63de5d0b 100644
--- a/packages/studio-protocol/src/install-in-studio.ts
+++ b/packages/studio-protocol/src/install-in-studio.ts
@@ -1,4 +1,8 @@
-import type {StudioElementPayload} from './element-payload';
+import * as z from 'zod/mini';
+import {
+ parseStudioElementPayload,
+ type StudioElementPayload,
+} from './element-payload';
import type {StudioProtocolFetcher} from './studio-discovery';
import {
discoverStudios,
@@ -9,7 +13,10 @@ import {
isAbortError,
studioProtocolProbePorts,
} from './studio-discovery';
-import {isRecord} from './validation';
+import {
+ isAwaitingConfirmationResponse,
+ parseStudioProtocolError,
+} from './studio-response';
export type InstallInStudioErrorCode =
| 'unsupported-origin'
@@ -55,6 +62,44 @@ export type StudioProtocolInstallRequest = {
readonly payload: StudioElementPayload;
};
+const studioProtocolInstallRequestEnvelopeSchema = z.object({
+ operation: z.literal('install-element'),
+ protocol: z.literal('remotion-studio-protocol'),
+ protocolVersion: z.literal(1),
+ targetId: z.string(),
+ payload: z.unknown(),
+});
+
+export const parseStudioProtocolInstallRequest = (
+ value: unknown,
+):
+ | {readonly status: 'valid'; readonly request: StudioProtocolInstallRequest}
+ | {readonly status: 'invalid-request' | 'invalid-payload'} => {
+ const envelope = z.safeParse(
+ studioProtocolInstallRequestEnvelopeSchema,
+ value,
+ );
+ if (!envelope.success) {
+ return {status: 'invalid-request'};
+ }
+
+ const payload = parseStudioElementPayload(envelope.data.payload);
+ if (payload === null) {
+ return {status: 'invalid-payload'};
+ }
+
+ return {
+ status: 'valid',
+ request: {
+ operation: envelope.data.operation,
+ protocol: envelope.data.protocol,
+ protocolVersion: envelope.data.protocolVersion,
+ targetId: envelope.data.targetId,
+ payload,
+ },
+ };
+};
+
const failure = (
code: InstallInStudioErrorCode,
message: string,
@@ -195,13 +240,7 @@ export const installInStudioWithDependencies = async (
);
}
- if (
- response.ok &&
- isRecord(result) &&
- result.protocol === 'remotion-studio-protocol' &&
- result.protocolVersion === 1 &&
- result.status === 'awaiting-confirmation'
- ) {
+ if (response.ok && isAwaitingConfirmationResponse(result)) {
return {
success: true,
status: 'awaiting-confirmation',
@@ -214,17 +253,13 @@ export const installInStudioWithDependencies = async (
};
}
- if (
- isRecord(result) &&
- result.status === 'error' &&
- isRecord(result.error) &&
- typeof result.error.code === 'string' &&
- typeof result.error.message === 'string'
- ) {
- const {code} = result.error;
+ const protocolError = parseStudioProtocolError(result);
+ if (protocolError !== null) {
return failure(
- code === 'target-expired' ? 'target-expired' : 'request-rejected',
- result.error.message,
+ protocolError.code === 'target-expired'
+ ? 'target-expired'
+ : 'request-rejected',
+ protocolError.message,
);
}
diff --git a/packages/studio-protocol/src/render-output-drag-data.ts b/packages/studio-protocol/src/render-output-drag-data.ts
index 43864e1a9d..f4513ee390 100644
--- a/packages/studio-protocol/src/render-output-drag-data.ts
+++ b/packages/studio-protocol/src/render-output-drag-data.ts
@@ -1,4 +1,4 @@
-import {isRecord} from './validation';
+import * as z from 'zod/mini';
export type RenderOutputDragData = {
type: 'remotion-render-output';
@@ -7,6 +7,20 @@ export type RenderOutputDragData = {
fileName: string;
};
+const renderOutputDragDataSchema = z.object({
+ type: z.literal('remotion-render-output'),
+ version: z.literal(1),
+ outputPath: z.string().check(z.minLength(1)),
+ fileName: z
+ .string()
+ .check(
+ z.refine(
+ (value) =>
+ value.length > 0 && !value.includes('/') && !value.includes('\\'),
+ ),
+ ),
+});
+
export const makeRenderOutputDragData = ({
outputPath,
fileName,
@@ -26,25 +40,13 @@ export const parseRenderOutputDragData = (
value: string,
): RenderOutputDragData | null => {
try {
- const parsed: unknown = JSON.parse(value);
- if (
- !isRecord(parsed) ||
- parsed.type !== 'remotion-render-output' ||
- parsed.version !== 1 ||
- typeof parsed.outputPath !== 'string' ||
- parsed.outputPath.length === 0 ||
- typeof parsed.fileName !== 'string' ||
- parsed.fileName.length === 0 ||
- parsed.fileName.includes('/') ||
- parsed.fileName.includes('\\')
- ) {
- return null;
- }
-
- return makeRenderOutputDragData({
- outputPath: parsed.outputPath,
- fileName: parsed.fileName,
- });
+ const parsed = z.safeParse(renderOutputDragDataSchema, JSON.parse(value));
+ return parsed.success
+ ? makeRenderOutputDragData({
+ outputPath: parsed.data.outputPath,
+ fileName: parsed.data.fileName,
+ })
+ : null;
} catch {
return null;
}
diff --git a/packages/studio-protocol/src/set-license-key-in-studio.ts b/packages/studio-protocol/src/set-license-key-in-studio.ts
index b17e4079c7..54afb06053 100644
--- a/packages/studio-protocol/src/set-license-key-in-studio.ts
+++ b/packages/studio-protocol/src/set-license-key-in-studio.ts
@@ -1,3 +1,4 @@
+import * as z from 'zod/mini';
import {isValidPublicLicenseKey} from './license-key';
import type {StudioProtocolFetcher} from './studio-discovery';
import {
@@ -9,7 +10,10 @@ import {
isAbortError,
studioProtocolProbePorts,
} from './studio-discovery';
-import {isRecord} from './validation';
+import {
+ isAwaitingConfirmationResponse,
+ parseStudioProtocolError,
+} from './studio-response';
export type SetLicenseKeyInStudioErrorCode =
| 'invalid-license-key'
@@ -54,6 +58,21 @@ export type StudioProtocolSetLicenseKeyRequest = {
readonly licenseKey: string;
};
+const studioProtocolSetLicenseKeyRequestSchema = z.object({
+ operation: z.literal('set-license-key'),
+ protocol: z.literal('remotion-studio-protocol'),
+ protocolVersion: z.literal(1),
+ targetId: z.string().check(z.minLength(1)),
+ licenseKey: z.string(),
+});
+
+export const parseStudioProtocolSetLicenseKeyRequest = (
+ value: unknown,
+): StudioProtocolSetLicenseKeyRequest | null => {
+ const parsed = z.safeParse(studioProtocolSetLicenseKeyRequestSchema, value);
+ return parsed.success ? parsed.data : null;
+};
+
export const setLicenseKeyInStudioWithDependencies = async (
licenseKey: string,
dependencies: SetLicenseKeyInStudioDependencies,
@@ -182,13 +201,7 @@ export const setLicenseKeyInStudioWithDependencies = async (
};
}
- if (
- response.ok &&
- isRecord(result) &&
- result.protocol === 'remotion-studio-protocol' &&
- result.protocolVersion === 1 &&
- result.status === 'awaiting-confirmation'
- ) {
+ if (response.ok && isAwaitingConfirmationResponse(result)) {
return {
success: true,
status: 'awaiting-confirmation',
@@ -200,23 +213,17 @@ export const setLicenseKeyInStudioWithDependencies = async (
};
}
- if (
- isRecord(result) &&
- result.status === 'error' &&
- isRecord(result.error) &&
- typeof result.error.code === 'string' &&
- typeof result.error.message === 'string'
- ) {
- const {code, message} = result.error;
+ const protocolError = parseStudioProtocolError(result);
+ if (protocolError !== null) {
return {
success: false,
code:
- code === 'target-expired'
+ protocolError.code === 'target-expired'
? 'target-expired'
- : code === 'no-config-file'
+ : protocolError.code === 'no-config-file'
? 'no-config-file'
: 'request-rejected',
- message,
+ message: protocolError.message,
};
}
diff --git a/packages/studio-protocol/src/sfx-drag-data.ts b/packages/studio-protocol/src/sfx-drag-data.ts
index c5ed8aeffc..01b5848cfe 100644
--- a/packages/studio-protocol/src/sfx-drag-data.ts
+++ b/packages/studio-protocol/src/sfx-drag-data.ts
@@ -1,4 +1,5 @@
-import {isRecord, isUrl} from './validation';
+import * as z from 'zod/mini';
+import {isUrl} from './validation';
export type SfxDragData = {
type: 'remotion-sfx';
@@ -9,6 +10,15 @@ export type SfxDragData = {
};
};
+const sfxDragDataSchema = z.object({
+ type: z.literal('remotion-sfx'),
+ version: z.literal(1),
+ sfx: z.object({
+ name: z.string().check(z.minLength(1)),
+ url: z.string().check(z.refine(isUrl)),
+ }),
+});
+
export const makeSfxDragData = ({
name,
url,
@@ -22,27 +32,13 @@ export const makeSfxDragData = ({
export const parseSfxDragData = (value: string): SfxDragData | null => {
try {
- const parsed: unknown = JSON.parse(value);
- if (
- !isRecord(parsed) ||
- parsed.type !== 'remotion-sfx' ||
- parsed.version !== 1 ||
- !isRecord(parsed.sfx)
- ) {
- return null;
- }
-
- const {name, url} = parsed.sfx;
- if (
- typeof name !== 'string' ||
- name.length === 0 ||
- typeof url !== 'string' ||
- !isUrl(url)
- ) {
- return null;
- }
-
- return makeSfxDragData({name, url});
+ const parsed = z.safeParse(sfxDragDataSchema, JSON.parse(value));
+ return parsed.success
+ ? makeSfxDragData({
+ name: parsed.data.sfx.name,
+ url: parsed.data.sfx.url,
+ })
+ : null;
} catch {
return null;
}
diff --git a/packages/studio-protocol/src/studio-discovery.ts b/packages/studio-protocol/src/studio-discovery.ts
index e1fc3b30ff..a0f2cb372d 100644
--- a/packages/studio-protocol/src/studio-discovery.ts
+++ b/packages/studio-protocol/src/studio-discovery.ts
@@ -1,4 +1,4 @@
-import {isRecord} from './validation';
+import * as z from 'zod/mini';
export type StudioProtocolTarget = {
readonly id: string;
@@ -57,6 +57,67 @@ export const studioProtocolProbePorts = [
export const focusedStudioMaxAge = 5 * 60 * 1000;
const requestTimeout = 2_000;
+const targetSchema = z.looseObject({
+ id: z.string().check(z.minLength(1)),
+ expiresAt: z.number(),
+ lastFocusedAt: z.number(),
+});
+const installTargetSchema = z.looseObject({
+ id: z.string().check(z.minLength(1)),
+ expiresAt: z.number(),
+ lastFocusedAt: z.number(),
+ compositionId: z.string().check(z.minLength(1)),
+});
+const installCapabilitySchema = z.looseObject({
+ type: z.literal('install-element'),
+ payloadType: z.literal('remotion-element'),
+ payloadVersions: z.array(z.number()),
+ target: z.nullable(installTargetSchema),
+});
+const setLicenseKeyCapabilitySchema = z.looseObject({
+ type: z.literal('set-license-key'),
+ target: z.nullable(targetSchema),
+});
+const addElementLibraryCapabilitySchema = z.looseObject({
+ type: z.literal('add-element-library'),
+ target: z.nullable(targetSchema),
+});
+const capabilitySchema = z.union([
+ installCapabilitySchema,
+ setLicenseKeyCapabilitySchema,
+ addElementLibraryCapabilitySchema,
+]);
+const descriptorEnvelopeSchema = z.looseObject({
+ protocol: z.literal('remotion-studio-protocol'),
+ protocolVersion: z.literal(1),
+ studioVersion: z.string(),
+ projectName: z.nullable(z.string()),
+ capabilities: z.array(z.unknown()),
+});
+const descriptorSchema = z
+ .looseObject({
+ protocol: z.literal('remotion-studio-protocol'),
+ protocolVersion: z.literal(1),
+ studioVersion: z.string(),
+ projectName: z.nullable(z.string()),
+ capabilities: z.array(capabilitySchema),
+ })
+ .check(
+ z.refine((descriptor) => {
+ const capabilityTypes = descriptor.capabilities.map(
+ (capability) => capability.type,
+ );
+ return new Set(capabilityTypes).size === capabilityTypes.length;
+ }),
+ );
+const protocolVersionEnvelopeSchema = z.looseObject({
+ protocol: z.literal('remotion-studio-protocol'),
+ protocolVersion: z.unknown(),
+});
+const legacyStudioSchema = z.looseObject({
+ type: z.literal('remotion-studio'),
+});
+
export const fetchWithTimeout = async ({
fetchFn,
options,
@@ -78,90 +139,32 @@ export const fetchWithTimeout = async ({
}
};
-const isNullableString = (value: unknown): value is string | null =>
- value === null || typeof value === 'string';
-
-const isTarget = (value: unknown): value is StudioProtocolTarget =>
- isRecord(value) &&
- typeof value.id === 'string' &&
- value.id.length > 0 &&
- typeof value.expiresAt === 'number' &&
- Number.isFinite(value.expiresAt) &&
- typeof value.lastFocusedAt === 'number' &&
- Number.isFinite(value.lastFocusedAt);
-
-const isInstallTarget = (
- value: unknown,
-): value is StudioProtocolInstallTarget => {
- if (!isRecord(value)) {
- return false;
- }
-
- const {compositionId} = value;
- return (
- isTarget(value) &&
- typeof compositionId === 'string' &&
- compositionId.length > 0
- );
-};
-
-const isCapability = (value: unknown): value is StudioProtocolCapability => {
- if (!isRecord(value)) {
- return false;
- }
-
- if (value.type === 'install-element') {
- return (
- value.payloadType === 'remotion-element' &&
- Array.isArray(value.payloadVersions) &&
- value.payloadVersions.every((version) => typeof version === 'number') &&
- (value.target === null || isInstallTarget(value.target))
- );
- }
-
- if (value.type === 'set-license-key') {
- return value.target === null || isTarget(value.target);
- }
-
- return (
- value.type === 'add-element-library' &&
- (value.target === null || isTarget(value.target))
- );
-};
-
export const isStudioProtocolDescriptor = (
value: unknown,
-): value is StudioProtocolDescriptor => {
- if (
- !isRecord(value) ||
- value.protocol !== 'remotion-studio-protocol' ||
- value.protocolVersion !== 1 ||
- typeof value.studioVersion !== 'string' ||
- !isNullableString(value.projectName) ||
- !Array.isArray(value.capabilities) ||
- !value.capabilities.every(isCapability)
- ) {
- return false;
- }
+): value is StudioProtocolDescriptor =>
+ z.safeParse(descriptorSchema, value).success;
- const capabilityTypes = value.capabilities.map(
- (capability) => capability.type,
- );
- return new Set(capabilityTypes).size === capabilityTypes.length;
-};
-
-const parseStudioProtocolDescriptor = (
+export const parseStudioProtocolDescriptor = (
value: unknown,
): StudioProtocolDescriptor | null => {
- if (!isRecord(value) || !Array.isArray(value.capabilities)) {
+ const envelope = z.safeParse(descriptorEnvelopeSchema, value);
+ if (!envelope.success) {
return null;
}
- const descriptor = {
- ...value,
- capabilities: value.capabilities.filter(isCapability),
- };
- return isStudioProtocolDescriptor(descriptor) ? descriptor : null;
+ const capabilities: StudioProtocolCapability[] = [];
+ for (const capability of envelope.data.capabilities) {
+ const parsedCapability = z.safeParse(capabilitySchema, capability);
+ if (parsedCapability.success) {
+ capabilities.push(parsedCapability.data);
+ }
+ }
+
+ const descriptor = z.safeParse(descriptorSchema, {
+ ...envelope.data,
+ capabilities,
+ });
+ return descriptor.success ? descriptor.data : null;
};
export const getInstallCapability = (
@@ -229,10 +232,13 @@ export const discoverStudios = async (
return null;
}
+ const protocolVersionEnvelope = z.safeParse(
+ protocolVersionEnvelopeSchema,
+ value,
+ );
if (
- isRecord(value) &&
- value.protocol === 'remotion-studio-protocol' &&
- value.protocolVersion !== 1
+ protocolVersionEnvelope.success &&
+ protocolVersionEnvelope.data.protocolVersion !== 1
) {
foundUnsupportedProtocol = true;
return null;
@@ -276,8 +282,7 @@ export const hasLegacyStudio = async (
return false;
}
- const value: unknown = await response.json();
- return isRecord(value) && value.type === 'remotion-studio';
+ return z.safeParse(legacyStudioSchema, await response.json()).success;
} catch {
return false;
}
diff --git a/packages/studio-protocol/src/studio-response.ts b/packages/studio-protocol/src/studio-response.ts
new file mode 100644
index 0000000000..05f0cc516c
--- /dev/null
+++ b/packages/studio-protocol/src/studio-response.ts
@@ -0,0 +1,26 @@
+import * as z from 'zod/mini';
+
+const awaitingConfirmationResponseSchema = z.object({
+ protocol: z.literal('remotion-studio-protocol'),
+ protocolVersion: z.literal(1),
+ status: z.literal('awaiting-confirmation'),
+});
+const studioProtocolErrorSchema = z.object({
+ status: z.literal('error'),
+ error: z.object({
+ code: z.string(),
+ message: z.string(),
+ }),
+});
+
+export const isAwaitingConfirmationResponse = (value: unknown): boolean =>
+ z.safeParse(awaitingConfirmationResponseSchema, value).success;
+
+export const parseStudioProtocolError = (
+ value: unknown,
+): {readonly code: string; readonly message: string} | null => {
+ const parsed = z.safeParse(studioProtocolErrorSchema, value);
+ return parsed.success
+ ? {code: parsed.data.error.code, message: parsed.data.error.message}
+ : null;
+};
diff --git a/packages/studio-protocol/src/test/drag-data.test.ts b/packages/studio-protocol/src/test/drag-data.test.ts
index 3595aa22dd..346f6e719c 100644
--- a/packages/studio-protocol/src/test/drag-data.test.ts
+++ b/packages/studio-protocol/src/test/drag-data.test.ts
@@ -26,7 +26,11 @@ const inputs: MakeDragDataInput[] = [
type: 'effect',
name: 'brightness',
importPath: '@remotion/effects/brightness',
- config: {brightness: 1.2},
+ config: {
+ brightness: 1.2,
+ channels: ['red', 'green', 'blue'],
+ settings: {enabled: true, fallback: null},
+ },
},
{
type: 'element',
@@ -55,6 +59,7 @@ test('constructs and parses all drag data families', () => {
const parsed = StudioProtocolInternals.parseDragData(constructed);
expect(parsed?.type).toBe(input.type);
+ expect(parsed?.data).toEqual(constructed.data);
expect(constructed.mimeType).toStartWith(
'application/vnd.remotion.drag+json;v=1;type=',
);
@@ -151,6 +156,22 @@ test('requires a duration for element drags', () => {
});
test('rejects malformed and mismatched drag data', () => {
+ expect(() =>
+ StudioProtocolInternals.makeDragData({
+ type: 'effect',
+ name: 'brightness',
+ importPath: '@remotion/effects/brightness',
+ config: {brightness: Number.POSITIVE_INFINITY},
+ }),
+ ).toThrow('Effect config must contain only finite JSON values');
+ expect(
+ StudioProtocolInternals.parseDragData({
+ mimeType: 'application/vnd.remotion.drag+json;v=1;type=effect',
+ payload:
+ '{"type":"remotion-effect","version":1,"effect":{"name":"brightness","importPath":"@remotion/effects/brightness","config":{"brightness":1e400}}}',
+ }),
+ ).toBe(null);
+
const renderOutput = StudioProtocolInternals.makeDragData({
type: 'render-output',
outputPath: 'out/video.mp4',
diff --git a/packages/studio-protocol/src/test/studio-discovery.test.ts b/packages/studio-protocol/src/test/studio-discovery.test.ts
new file mode 100644
index 0000000000..9b3fa9379e
--- /dev/null
+++ b/packages/studio-protocol/src/test/studio-discovery.test.ts
@@ -0,0 +1,40 @@
+import {expect, test} from 'bun:test';
+import {StudioProtocolInternals} from '../index';
+
+const installCapability = {
+ type: 'install-element' as const,
+ payloadType: 'remotion-element' as const,
+ payloadVersions: [1],
+ target: {
+ id: 'target',
+ expiresAt: 2_000,
+ lastFocusedAt: 1_000,
+ compositionId: 'Main',
+ },
+ futureCapabilityMetadata: true,
+};
+
+const descriptor = {
+ protocol: 'remotion-studio-protocol' as const,
+ protocolVersion: 1 as const,
+ studioVersion: '4.0.519',
+ projectName: 'Project',
+ capabilities: [installCapability, {type: 'future-capability'}],
+ futureDescriptorMetadata: true,
+};
+
+test('filters future capabilities, preserves extensions, and rejects duplicates', () => {
+ const parsed =
+ StudioProtocolInternals.parseStudioProtocolDescriptor(descriptor);
+ expect(parsed).toEqual({
+ ...descriptor,
+ capabilities: [installCapability],
+ });
+
+ expect(
+ StudioProtocolInternals.parseStudioProtocolDescriptor({
+ ...descriptor,
+ capabilities: [installCapability, installCapability],
+ }),
+ ).toBe(null);
+});
diff --git a/packages/studio-protocol/src/validation.ts b/packages/studio-protocol/src/validation.ts
index a7ddf29885..cc5c990785 100644
--- a/packages/studio-protocol/src/validation.ts
+++ b/packages/studio-protocol/src/validation.ts
@@ -1,7 +1,3 @@
-export const isRecord = (value: unknown): value is Record<string, unknown> => {
- return typeof value === 'object' && value !== null && !Array.isArray(value);
-};
-
export const isUrl = (value: string): boolean => {
try {
const parsed = new URL(value);
diff --git a/packages/studio-server/src/preview-server/studio-protocol/handle-element-library.ts b/packages/studio-server/src/preview-server/studio-protocol/handle-element-library.ts
index 9e541137b4..f91ea272d5 100644
--- a/packages/studio-server/src/preview-server/studio-protocol/handle-element-library.ts
+++ b/packages/studio-server/src/preview-server/studio-protocol/handle-element-library.ts
@@ -1,5 +1,5 @@
import type {IncomingMessage, ServerResponse} from 'node:http';
-import {z} from 'zod';
+import {StudioProtocolInternals} from '@remotion/studio-protocol';
import {consumeStudioProtocolTarget} from '../element-install-state';
import type {LiveEventsServer} from '../live-events';
import {parseRequestBody, RequestBodyTooLargeError} from '../parse-body';
@@ -11,15 +11,6 @@ import {writeStudioProtocolError} from './protocol-response';
type FocusStudioTab = (studioUrl: string) => void;
-const studioProtocolElementLibraryRequestSchema = z.object({
- operation: z.literal('add-element-library'),
- protocol: z.literal('remotion-studio-protocol'),
- protocolVersion: z.literal(1),
- targetId: z.string().min(1),
- url: z.string(),
- displayName: z.string().nullable(),
-});
-
const MAX_STUDIO_PROTOCOL_ELEMENT_LIBRARY_BODY_SIZE = 16 * 1024;
export const handleStudioProtocolElementLibrary = async ({
@@ -83,8 +74,8 @@ export const handleStudioProtocolElementLibrary = async ({
}
const parsedRequest =
- studioProtocolElementLibraryRequestSchema.safeParse(body);
- if (!parsedRequest.success) {
+ StudioProtocolInternals.parseStudioProtocolAddElementLibraryRequest(body);
+ if (parsedRequest === null) {
writeStudioProtocolError({
code: 'unsupported-protocol',
message: 'Invalid Remotion Studio Protocol request.',
@@ -96,7 +87,7 @@ export const handleStudioProtocolElementLibrary = async ({
let normalizedUrl: string;
try {
- const parsedUrl = new URL(parsedRequest.data.url);
+ const parsedUrl = new URL(parsedRequest.url);
if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
throw new Error('Unsupported protocol');
}
@@ -112,7 +103,7 @@ export const handleStudioProtocolElementLibrary = async ({
return;
}
- const displayName = parsedRequest.data.displayName?.trim() ?? null;
+ const displayName = parsedRequest.displayName?.trim() ?? null;
if (displayName === '') {
writeStudioProtocolError({
code: 'invalid-display-name',
@@ -127,7 +118,7 @@ export const handleStudioProtocolElementLibrary = async ({
now: Date.now(),
origin: requestOrigin,
purpose: 'add-element-library',
- targetId: parsedRequest.data.targetId,
+ targetId: parsedRequest.targetId,
});
if (target === null) {
writeStudioProtocolError({
diff --git a/packages/studio-server/src/preview-server/studio-protocol/handle-install.ts b/packages/studio-server/src/preview-server/studio-protocol/handle-install.ts
index 4c613f0608..c786510aa0 100644
--- a/packages/studio-server/src/preview-server/studio-protocol/handle-install.ts
+++ b/packages/studio-server/src/preview-server/studio-protocol/handle-install.ts
@@ -1,7 +1,6 @@
import type {IncomingMessage, ServerResponse} from 'node:http';
import {StudioProtocolInternals} from '@remotion/studio-protocol';
import type {ElementInstallRequest} from '@remotion/studio-shared';
-import {z} from 'zod';
import type {getElementInstallTarget} from '../element-install-state';
import {consumeStudioProtocolTarget} from '../element-install-state';
import type {LiveEventsServer} from '../live-events';
@@ -14,14 +13,6 @@ import {writeStudioProtocolError} from './protocol-response';
type FocusStudioTab = (studioUrl: string) => void;
-const studioProtocolInstallRequestSchema = z.object({
- operation: z.literal('install-element'),
- protocol: z.literal('remotion-studio-protocol'),
- protocolVersion: z.literal(1),
- targetId: z.string(),
- payload: z.unknown(),
-});
-
// A valid payload may contain 250,000 JSON characters. Allow room for its
// UTF-8 representation and the protocol envelope while keeping memory bounded.
const MAX_STUDIO_PROTOCOL_INSTALL_BODY_SIZE = 1_000_000;
@@ -127,24 +118,18 @@ export const handleStudioProtocolInstall = async ({
return;
}
- const parsedRequest = studioProtocolInstallRequestSchema.safeParse(body);
- if (!parsedRequest.success) {
- writeStudioProtocolError({
- code: 'unsupported-protocol',
- message: 'Invalid Remotion Studio Protocol request.',
- response,
- status: 400,
- });
- return;
- }
-
- const payload = StudioProtocolInternals.parseStudioElementPayload(
- parsedRequest.data.payload,
- );
- if (payload === null) {
+ const parsedRequest =
+ StudioProtocolInternals.parseStudioProtocolInstallRequest(body);
+ if (parsedRequest.status !== 'valid') {
writeStudioProtocolError({
- code: 'invalid-payload',
- message: 'Invalid Element payload.',
+ code:
+ parsedRequest.status === 'invalid-payload'
+ ? 'invalid-payload'
+ : 'unsupported-protocol',
+ message:
+ parsedRequest.status === 'invalid-payload'
+ ? 'Invalid Element payload.'
+ : 'Invalid Remotion Studio Protocol request.',
response,
status: 400,
});
@@ -155,7 +140,7 @@ export const handleStudioProtocolInstall = async ({
now: Date.now(),
origin: requestOrigin,
purpose: 'install-element',
- targetId: parsedRequest.data.targetId,
+ targetId: parsedRequest.request.targetId,
});
if (target === null) {
writeStudioProtocolError({
@@ -169,7 +154,7 @@ export const handleStudioProtocolInstall = async ({
if (
!deliverElementInstall({
- element: payload.element,
+ element: parsedRequest.request.payload.element,
focusStudioTab,
liveEventsServer,
origin: requestOrigin,
diff --git a/packages/studio-server/src/preview-server/studio-protocol/handle-license-key.ts b/packages/studio-server/src/preview-server/studio-protocol/handle-license-key.ts
index 5f602e4e7e..5e1b8d813c 100644
--- a/packages/studio-server/src/preview-server/studio-protocol/handle-license-key.ts
+++ b/packages/studio-server/src/preview-server/studio-protocol/handle-license-key.ts
@@ -1,6 +1,5 @@
import type {IncomingMessage, ServerResponse} from 'node:http';
import {StudioProtocolInternals} from '@remotion/studio-protocol';
-import {z} from 'zod';
import {consumeStudioProtocolTarget} from '../element-install-state';
import type {LiveEventsServer} from '../live-events';
import {parseRequestBody, RequestBodyTooLargeError} from '../parse-body';
@@ -12,14 +11,6 @@ import {writeStudioProtocolError} from './protocol-response';
type FocusStudioTab = (studioUrl: string) => void;
-const studioProtocolLicenseKeyRequestSchema = z.object({
- operation: z.literal('set-license-key'),
- protocol: z.literal('remotion-studio-protocol'),
- protocolVersion: z.literal(1),
- targetId: z.string().min(1),
- licenseKey: z.string(),
-});
-
const MAX_STUDIO_PROTOCOL_LICENSE_KEY_BODY_SIZE = 4096;
export const handleStudioProtocolLicenseKey = async ({
@@ -82,8 +73,9 @@ export const handleStudioProtocolLicenseKey = async ({
return;
}
- const parsedRequest = studioProtocolLicenseKeyRequestSchema.safeParse(body);
- if (!parsedRequest.success) {
+ const parsedRequest =
+ StudioProtocolInternals.parseStudioProtocolSetLicenseKeyRequest(body);
+ if (parsedRequest === null) {
writeStudioProtocolError({
code: 'unsupported-protocol',
message: 'Invalid Remotion Studio Protocol request.',
@@ -94,9 +86,7 @@ export const handleStudioProtocolLicenseKey = async ({
}
if (
- !StudioProtocolInternals.isValidPublicLicenseKey(
- parsedRequest.data.licenseKey,
- )
+ !StudioProtocolInternals.isValidPublicLicenseKey(parsedRequest.licenseKey)
) {
writeStudioProtocolError({
code: 'invalid-license-key',
@@ -111,7 +101,7 @@ export const handleStudioProtocolLicenseKey = async ({
now: Date.now(),
origin: requestOrigin,
purpose: 'set-license-key',
- targetId: parsedRequest.data.targetId,
+ targetId: parsedRequest.targetId,
});
if (target === null) {
writeStudioProtocolError({
@@ -135,7 +125,7 @@ export const handleStudioProtocolLicenseKey = async ({
const delivered = liveEventsServer.sendEventToClientId(target.clientId, {
type: 'license-key-install-request',
- licenseKey: parsedRequest.data.licenseKey,
+ licenseKey: parsedRequest.licenseKey,
});
if (!delivered) {
writeStudioProtocolError({