đ„ Make videos programmatically with React
Elements: Split submission and acceptance workflows (#10137)
Igor Samokhovetsf927a5b789b5
diff --git a/.agents/skills/accept-element/SKILL.md b/.agents/skills/accept-element/SKILL.mdnew file mode 100644index 0000000000..c8be82708f--- /dev/null+++ b/.agents/skills/accept-element/SKILL.md@@ -0,0 +1,91 @@+---+name: accept-element+description: Accept an external Remotion Element contribution by verifying its committed previews, uploading them to R2, removing the temporary assets, and preparing the pull request for review.+---++# Accept a Remotion Element++This is a maintainer-only workflow for contributions that used the external path in the [`submit-element` skill](../submit-element/SKILL.md). Do not use it for a repository writer's direct submission, which already has public preview URLs and no committed preview assets. Read the [Element Guidelines](../../../packages/docs/elements/guidelines.mdx), the [`scaffold-element` skill](../scaffold-element/SKILL.md), and the `submit-element` skill completely before making changes.++Run this workflow on the external contributor's pull request branch. Do not force push. For a pull request from a fork, confirm that âAllow edits from maintainersâ is enabled. If the branch cannot be updated, upload only after approval and ask the contributor to apply the URL and asset cleanup described below.++## 1. Confirm the contribution is reviewable++Identify the single submitted `<category>/<slug>` and confirm that:++- The implementation, page, central definition, and sidebar registration are in the pull request.+- The page frontmatter and central definition use `/elements/<category>-<slug>-preview.png` and `.mp4` review URLs.+- The matching files are committed at `packages/docs/static/elements/<category>-<slug>-preview.png` and `.mp4`.+- The contributor explicitly reviewed the Element in Studio and approved both committed preview assets.+- The pull request has passed code review against the Element Guidelines.++Do not accept an Element whose metadata already points to a missing `https://remotion.media` asset or whose review assets are available only outside the pull request.++## 2. Verify the committed assets against the final code++Run the focused test, then render the Element again from the final pull request source:++```bash+cd packages/docs+bun test src/test/elements.test.ts+bun run render-element-previews --element=<category>/<slug>+cd ../..+```++Give the maintainer these committed asset paths:++- `packages/docs/static/elements/<category>-<slug>-preview.png`+- `packages/docs/static/elements/<category>-<slug>-preview.mp4`++Also give them the fresh render paths:++- `packages/docs/.element-previews/<category>/<slug>/preview.png`+- `packages/docs/.element-previews/<category>/<slug>/preview.mp4`++Ask the maintainer to visually compare the committed assets with the fresh render and confirm that they represent the same poster frame and animation. Stop and wait for explicit approval of the final source and both committed assets before uploading. Do not infer approval from the agent's own inspection. If the maintainer rejects them, return the contribution to the submission workflow.++## 3. Upload the exact approved files++With maintainer R2 credentials available, run:++```bash+cd packages/docs+bun run upload-element-preview \+ --element=<category>/<slug> \+ --source=submission+cd ../..+```++This command uploads the exact files from `packages/docs/static/elements`; it does not rerender or delete them. The explicit submission source validates that the assets are committed and unmodified, then checks the local paths, signatures, combined size, uploaded sizes, public HTTP responses, and content types. Do not continue unless both uploads are verified.++The command prints the public URLs:++- `https://remotion.media/elements/<category>-<slug>-preview.png`+- `https://remotion.media/elements/<category>-<slug>-preview.mp4`++## 4. Convert the contribution to its published state++Only after the upload succeeds:++1. Replace the local `posterUrl` and `videoUrl` in `packages/docs/src/components/Elements/element-definitions.ts` with the printed `https://remotion.media` URLs.+2. Replace the local `image` URL in `packages/docs/elements/<category>/<slug>/index.mdx` with the public poster URL.+3. Delete the two files from `packages/docs/static/elements`.+4. Remove `packages/docs/static/elements` if it is empty.++Do not change the slug or flat asset names between upload and cleanup.++## 5. Validate and update the pull request++```bash+cd packages/docs+bun test src/test/elements.test.ts+cd ../..+bun run build+bun run stylecheck+git diff --check+git status --short+```++The focused test now validates that the metadata contains the exact public URLs and that no matching local review assets remain.++Inspect the final diff. It should contain the Element source, page, definition, gallery registration, and public URLs, but not the PNG or MP4. Commit the acceptance cleanup normally to the same pull request branch and push without force. Then stop and report that the pull request is ready for review.diff --git a/.agents/skills/publish-element/SKILL.md b/.agents/skills/publish-element/SKILL.mddeleted file mode 100644index f1a008d170..0000000000--- a/.agents/skills/publish-element/SKILL.md+++ /dev/null@@ -1,107 +0,0 @@-----name: publish-element-description: Finalize a developed Remotion Element, add it to the docs gallery, render its previews, and run repository checks.------# Publish a Remotion Element--The source of truth for design and quality criteria is the [Element Guidelines](../../../packages/docs/elements/guidelines.mdx). Read them completely before making changes. If this skill and the guidelines diverge on acceptance criteria, follow the guidelines.--This skill owns the technical publication workflow. It starts with an Element scaffold created by the [`scaffold-element` skill](../scaffold-element/SKILL.md) and does not create the initial development scaffold.--## 1. Confirm the Element is ready--Confirm these files and the matching entry in `packages/docs/src/components/Elements/element-definitions.ts` already exist:--- `packages/docs/elements/<category>/<slug>/index.mdx`-- `packages/docs/elements/<category>/<slug>/<slug>.tsx`--Do not launch the Studio from this skill. Before continuing, require the developer to explicitly confirm that they visually reviewed `element-<category>-<slug>` in the docs Remotion Studio and that it looks correct. Do not infer approval from completed tests or from the agent's own inspection. If the developer has not approved it or more visual development is needed, give them these commands and stop the publishing workflow:--```bash-bun run build-cd packages/docs-bun run remotion-```--## 2. Perform the publication review--Review the finished source, MDX page, and central definition against the Element Guidelines and the technical requirements in the [`scaffold-element` skill](../scaffold-element/SKILL.md). Resolve placeholder content and finalize the description, display name, contributors, dimensions, duration, `installationMode`, declared dependencies, preview padding, poster frame, and `preview` object.--Confirm that `posterUrl` and `videoUrl` use flat `https://remotion.media/elements/<category>-<slug>-preview.png` and `.mp4` paths. Preview assets are composited onto the standard background and use MP4 for broad browser, social-card, and embed compatibility, even when the Element itself supports transparency. These explicit URLs are the publishing source of truth.--When the Element has Studio-editable controls, also review it using the [interactivity best practices skill](../interactivity-best-practices/SKILL.md).--If the Element imports a package that is not available to `packages/docs`, add it to `packages/docs/package.json`, run `bun install`, and include `bun.lock`.--## 3. Add it to the gallery--- Confirm that the entry in `packages/docs/src/components/Elements/element-definitions.ts` places the Element in the generated overview and category library.-- Add `'<category>/<slug>/index'` to the matching category in `packages/docs/elements-sidebars.ts`.--Preserve the ordering used by the sidebar. Do not add a manual link to the category index: the visual and raw Markdown libraries are generated from the central definitions. If the task explicitly introduces a new category, create an index that renders the filtered `ElementLibrary` and add its sidebar group as part of this step.--Before considering gallery registration complete, verify that the Element appears on the overview page, its category page, and the generated raw Markdown routes.--Do not edit `packages/docs/src/remotion/Root.tsx`; Element compositions are derived from the central definitions.--## 4. Format and test--Format the changed TypeScript and TSX files only. For the usual files:--```bash-bunx oxfmt \- packages/docs/elements/<category>/<slug>/<slug>.tsx \- packages/docs/src/components/Elements/element-definitions.ts \- packages/docs/elements-sidebars.ts \- --write--cd packages/docs-bun test src/test/elements.test.ts-```--## 5. Render and inspect the previews--Perform the preview verification required by the Element Guidelines. Render only the new Element, using its `posterFrame` from `element-definitions.ts`:--```bash-cd packages/docs-mkdir -p .element-previews/<category>/<slug>-bunx remotion still \- src/remotion/entry.ts \- element-<category>-<slug> \- .element-previews/<category>/<slug>/preview.png \- --frame=<poster-frame> --gl=angle --overwrite-bunx remotion render \- src/remotion/entry.ts \- element-<category>-<slug> \- .element-previews/<category>/<slug>/preview.mp4 \- --codec=h264 --crf=23 --image-format=png --pixel-format=yuv420p \- --gl=angle --muted --overwrite-cd ../..-```--Do not run `render-element-previews` without an Element filter, because that renders every Element and clears the complete preview output. If uploading is explicitly requested later, use:--```bash-cd packages/docs-bun run render-element-previews --element=<category>/<slug> --upload-cd ../..-```--The filtered command clears and regenerates only that Element's nested local review output, then uses its explicit metadata URLs for the public locations and R2 keys.--Inspect `packages/docs/.element-previews/<category>/<slug>/preview.png` and `preview.mp4`, then give both paths to the developer for visual review. Stop and wait for the developer to explicitly confirm that both previews look correct. Do not run the final repository checks or finish the publishing workflow until that approval is received.--Do not commit the ignored output or upload previews unless uploading was explicitly requested and maintainer R2 credentials are available.--## 6. Run final repository checks--```bash-bun run build-bun run stylecheck-git diff --check-git status --short-```--Before finishing, verify that the page is listed in the generated overview and category library, the generated raw Markdown, and the sidebar; all checks pass; and only intended files are part of the change. Report the commands run, their results, and the preview files inspected.diff --git a/.agents/skills/scaffold-element/SKILL.md b/.agents/skills/scaffold-element/SKILL.mdindex 050bd7bc44..3da69d3730 100644--- a/.agents/skills/scaffold-element/SKILL.md+++ b/.agents/skills/scaffold-element/SKILL.md@@ -7,7 +7,7 @@ description: Scaffold a new Remotion Element with a correctly configured previewThe source of truth for design and quality criteria is the [Element Guidelines](../../../packages/docs/elements/guidelines.mdx). Read them completely before making changes. If this skill and the guidelines diverge on acceptance criteria, follow the guidelines.-This skill owns the technical scaffolding workflow. Use the [`publish-element` skill](../publish-element/SKILL.md) when the Element is ready for the gallery.+This skill owns the technical scaffolding workflow. Use the [`submit-element` skill](../submit-element/SKILL.md) when the Element is ready for the gallery.## 1. Plan the preview@@ -20,11 +20,11 @@ Choose an existing category and a kebab-case slug. Before creating files, determ- External source dependencies- Preview padding, which affects only the docs preview and not the Element bounds- A provisional poster frame-- Explicit poster and video URLs using the flat asset convention:- - `https://remotion.media/elements/<category>-<slug>-preview.png`- - `https://remotion.media/elements/<category>-<slug>-preview.mp4`+- Explicit local poster and video review URLs using the flat asset convention:+ - `/elements/<category>-<slug>-preview.png`+ - `/elements/<category>-<slug>-preview.mp4`-Preview videos are always opaque MP4 files for broad browser, social-card, and embed compatibility. Elements that are transparent in a composition are composited onto the standard preview background for these assets.+The files do not exist during scaffolding and are not needed by the development composition. The [`submit-element` skill](../submit-element/SKILL.md) renders them and either uploads them directly for a repository writer or adds them to an external contribution for review. Preview videos are always opaque MP4 files for broad browser, social-card, and embed compatibility. Elements that are transparent in a composition are composited onto the standard preview background for these assets.Inspect `packages/docs/elements-template/` and at least one existing Element in the same category. Do not create a new category unless the task explicitly requires one.@@ -45,7 +45,7 @@ Implement only enough of the component in the generated `<slug>.tsx` file to pro## 3. Register the development composition-Import and register the component in `packages/docs/src/components/Elements/element-definitions.ts` using the planned preview metadata. Set `installationMode` explicitly and use the same `durationInFrames` for the preview and installed Element. Add the explicit `preview` object next to the render metadata, including `posterUrl` and `videoUrl`. The URLs in this object are the source of truth for publishing; do not add a helper that derives production URLs from the Element slug.+Import and register the component in `packages/docs/src/components/Elements/element-definitions.ts` using the planned preview metadata. Set `installationMode` explicitly and use the same `durationInFrames` for the preview and installed Element. Add the explicit `preview` object next to the render metadata, including the local `posterUrl` and `videoUrl`. Keep the matching local poster URL in the MDX page frontmatter. The submission workflow replaces these paths with public `https://remotion.media` URLs after a direct member upload, or the acceptance workflow replaces them after an external contribution is approved.Do not edit `packages/docs/src/remotion/Root.tsx`. It automatically creates a composition for every central definition using the same sizing and wrapper used by published Elements.@@ -66,7 +66,7 @@ bun test src/test/elements.test.tscd ../..```-Do not add the category-index or sidebar entries and do not render final preview assets yet. Those belong to the publishing workflow.+Do not add the category-index or sidebar entries and do not render preview assets yet. Those belong to the submission workflow.## 5. Hand off development@@ -80,4 +80,4 @@ bun run remotionThen tell them to open the `elements` folder and select `element-<category>-<slug>`. Development should start in that composition so the Element is always evaluated with its configured dimensions, duration, padding, and preview background.-Report the created files, composition ID, focused test result, and that the next step after development is the [`publish-element` skill](../publish-element/SKILL.md).+Report the created files, composition ID, focused test result, and that the next step after development is the [`submit-element` skill](../submit-element/SKILL.md).diff --git a/.agents/skills/submit-element/SKILL.md b/.agents/skills/submit-element/SKILL.mdnew file mode 100644index 0000000000..3a257f155a--- /dev/null+++ b/.agents/skills/submit-element/SKILL.md@@ -0,0 +1,166 @@+---+name: submit-element+description: Finalize a developed Remotion Element, add it to the docs gallery, and prepare either a direct member submission or an externally reviewable contribution.+---++# Submit a Remotion Element++The source of truth for design and quality criteria is the [Element Guidelines](../../../packages/docs/elements/guidelines.mdx). Read them completely before making changes. If this skill and the guidelines diverge on acceptance criteria, follow the guidelines.++This skill owns the contributor submission workflow. It starts with an Element created by the [`scaffold-element` skill](../scaffold-element/SKILL.md). Repository writers upload reviewed previews directly. Other contributors commit temporary review assets that a maintainer later processes with the [`accept-element` skill](../accept-element/SKILL.md).++## 1. Confirm the Element is ready++Confirm these files and the matching entry in `packages/docs/src/components/Elements/element-definitions.ts` already exist:++- `packages/docs/elements/<category>/<slug>/index.mdx`+- `packages/docs/elements/<category>/<slug>/<slug>.tsx`++Do not launch the Studio from this skill. Before continuing, require the developer to explicitly confirm that they visually reviewed `element-<category>-<slug>` in the docs Remotion Studio and that it looks correct. Do not infer approval from completed tests or from the agent's own inspection. If the developer has not approved it or more visual development is needed, give them these commands and stop the submission workflow:++```bash+bun run build+cd packages/docs+bun run remotion+```++## 2. Select the submission path++Determine the authenticated GitHub account's permission on the canonical repository. Do not infer membership from Git remotes, branch names, or commit email.++```bash+login=$(gh api user --jq '.login' 2>/dev/null || true)+permission=$(+ if [ -n "$login" ]; then+ gh api "repos/remotion-dev/remotion/collaborators/$login/permission" \+ --jq '.permission' 2>/dev/null || true+ fi+)+printf 'GitHub user: %s\nRepository permission: %s\n' \+ "${login:-unknown}" "${permission:-unknown}"+```++Use the **direct member path** only when `permission` is `write`, `maintain`, or `admin`. Before continuing on that path, verify without printing their values that Bun can read both `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`:++```bash+bun -e 'process.exit(Bun.env.AWS_ACCESS_KEY_ID && Bun.env.AWS_SECRET_ACCESS_KEY ? 0 : 1)'+```++If a repository writer is missing either credential, stop and report that direct preview upload credentials are required. Do not silently commit temporary assets for them.++Use the **external contribution path** when the permission is `read`, `triage`, `none`, unknown, or the GitHub lookup fails. This path does not require upload credentials.++## 3. Perform the submission review++Review the finished source, MDX page, and central definition against the Element Guidelines and the technical requirements in the [`scaffold-element` skill](../scaffold-element/SKILL.md). Resolve placeholder content and finalize the description, display name, contributors, dimensions, duration, `installationMode`, declared dependencies, preview padding, and poster frame.++Keep the local review URLs in place while rendering and reviewing:++- `posterUrl: '/elements/<category>-<slug>-preview.png'`+- `videoUrl: '/elements/<category>-<slug>-preview.mp4'`+- `image: /elements/<category>-<slug>-preview.png` in the page frontmatter++Preview assets are composited onto the standard background and use MP4 for broad browser, social-card, and embed compatibility, even when the Element itself supports transparency.++When the Element has Studio-editable controls, also review it using the [interactivity best practices skill](../interactivity-best-practices/SKILL.md).++If the Element imports a package that is not available to `packages/docs`, add it to `packages/docs/package.json`, run `bun install`, and include `bun.lock`.++## 4. Add it to the gallery++- Confirm that the entry in `packages/docs/src/components/Elements/element-definitions.ts` places the Element in the generated overview and category library.+- Add `'<category>/<slug>/index'` to the matching category in `packages/docs/elements-sidebars.ts`.++Preserve the ordering used by the sidebar. Do not add a manual link to the category index: the visual and raw Markdown libraries are generated from the central definitions. If the task explicitly introduces a new category, create an index that renders the filtered `ElementLibrary` and add its sidebar group as part of this step.++Before considering gallery registration complete, verify that the Element appears on the overview page, its category page, and the generated raw Markdown routes.++Do not edit `packages/docs/src/remotion/Root.tsx`; Element compositions are derived from the central definitions.++## 5. Render and inspect the previews++Render only the submitted Element:++```bash+cd packages/docs+bun run render-element-previews --element=<category>/<slug>+cd ../..+```++Do not run `render-element-previews` without an Element filter, because that renders every Element and clears the complete preview output.++Inspect these files and give both paths to the developer for visual review:++- `packages/docs/.element-previews/<category>/<slug>/preview.png`+- `packages/docs/.element-previews/<category>/<slug>/preview.mp4`++Stop and wait for the developer to explicitly confirm that both previews look correct. Do not upload or copy the assets until that approval is received.++## 6A. Direct member path: Upload the render++Do not copy the previews into `packages/docs/static/elements` and do not add them to Git. Upload the exact reviewed render:++```bash+cd packages/docs+bun run upload-element-preview \+ --element=<category>/<slug> \+ --source=render+cd ../..+```++The uploader validates the local URLs, signatures, combined size, uploaded sizes, public HTTP responses, and content types. Do not continue unless both uploads are verified.++Then:++1. Replace the local `posterUrl` and `videoUrl` in `packages/docs/src/components/Elements/element-definitions.ts` with the printed `https://remotion.media` URLs.+2. Replace the local `image` URL in `packages/docs/elements/<category>/<slug>/index.mdx` with the public poster URL.+3. Confirm that no matching files exist under `packages/docs/static/elements`.++If the Element changes visually after this upload, restore the local URLs, render and review it again, rerun the direct upload, and only then restore the public URLs.++## 6B. External contribution path: Add review assets++Do not upload to R2 or replace the local URLs. Copy the exact reviewed files to their flat review paths:++```bash+mkdir -p packages/docs/static/elements+cp packages/docs/.element-previews/<category>/<slug>/preview.png \+ packages/docs/static/elements/<category>-<slug>-preview.png+cp packages/docs/.element-previews/<category>/<slug>/preview.mp4 \+ packages/docs/static/elements/<category>-<slug>-preview.mp4+```++The PNG and MP4 must total no more than 10 MiB. Do not add the ignored `.element-previews` directory. The two files under `packages/docs/static/elements` are intentionally tracked and must be included in the pull request so the contributor and reviewers do not get 404 responses.++The [`accept-element` skill](../accept-element/SKILL.md) uploads the approved assets and replaces the local URLs after review.++## 7. Format and test++Format the changed TypeScript and TSX files only. For the usual files:++```bash+bunx oxfmt \+ packages/docs/elements/<category>/<slug>/<slug>.tsx \+ packages/docs/src/components/Elements/element-definitions.ts \+ packages/docs/elements-sidebars.ts \+ --write++cd packages/docs+bun test src/test/elements.test.ts+cd ../..+```++For direct member submissions, the focused test validates the exact public URLs and the absence of local review assets. For external contributions, it validates the local URLs, flat review assets, file signatures, and combined contribution size.++## 8. Run final repository checks++```bash+bun run build+bun run stylecheck+git diff --check+git status --short+```++Before finishing, verify that the page is listed in the generated overview and category library, the generated raw Markdown, and the sidebar; all checks pass; and only intended files are part of the change.++For the direct member path, report the two verified public preview URLs and confirm that no preview assets are tracked. For the external path, report the two tracked review assets and keep âAllow edits from maintainersâ enabled if a pull request is opened. In both cases, stop after preparing the contribution for review.diff --git a/packages/docs/elements-template/index.mdx b/packages/docs/elements-template/index.mdxindex fccf466ddb..c5ea21c961 100644--- a/packages/docs/elements-template/index.mdx+++ b/packages/docs/elements-template/index.mdx@@ -1,6 +1,7 @@---title: Element titledescription: One sentence describing what this element shows.+image: /elements/category-element-title-preview.png---import {ElementPage} from '@site/src/components/Elements/ElementPage';@@ -20,8 +21,8 @@ export const elementDefinition = {height: 1080,posterFrame: 60,preview: {- posterUrl: 'https://remotion.media/elements/category-element-title-preview.png',- videoUrl: 'https://remotion.media/elements/category-element-title-preview.mp4',+ posterUrl: '/elements/category-element-title-preview.png',+ videoUrl: '/elements/category-element-title-preview.mp4',},previewPadding: 0,slug: 'category/element-title',diff --git a/packages/docs/elements/submit-an-element.mdx b/packages/docs/elements/submit-an-element.mdxindex d363361183..a341c24402 100644--- a/packages/docs/elements/submit-an-element.mdx+++ b/packages/docs/elements/submit-an-element.mdx@@ -11,12 +11,12 @@ Before starting, read the [Element Guidelines](/elements/guidelines). They descr## Use the Agent Skills-Two [Agent Skills](https://agentskills.io/) are available in the Remotion repository. They contain the technical workflow, including file layout, metadata, previews, and validation:+Two [Agent Skills](https://agentskills.io/) define the contribution workflow:-- Use the [`scaffold-element` Agent Skill](https://github.com/remotion-dev/remotion/blob/main/.agents/skills/scaffold-element/SKILL.md) to scaffold and register an Element for development.-- Use the [`publish-element` Agent Skill](https://github.com/remotion-dev/remotion/blob/main/.agents/skills/publish-element/SKILL.md) after developing and reviewing the Element in Remotion Studio. It adds the Element to the gallery, renders its previews, and runs the final checks.+- Use the [`scaffold-element` Agent Skill](https://github.com/remotion-dev/remotion/blob/main/.agents/skills/scaffold-element/SKILL.md) to create the repository files and development composition.+- Use the [`submit-element` Agent Skill](https://github.com/remotion-dev/remotion/blob/main/.agents/skills/submit-element/SKILL.md) after reviewing the Element in Remotion Studio. It adds the Element to the gallery and prepares it for review.-Ask your coding agent to use the appropriate skill. The workflows are separate so you can develop and review an Element before preparing it for publication.+Ask your coding agent to use the skills in that order.## Open the pull request@@ -24,7 +24,9 @@ When submitting an Element as a pull request, include:- The Element implementation, page, and gallery registration- What makes it useful-- The rendered preview+- A working PNG and MP4 preview- Links to inspiration, if any+The submission skill prepares the previews so they work in the pull request deployment. Keep âAllow edits from maintainersâ enabled on the pull request.+[Open a pull request on GitHub](https://github.com/remotion-dev/remotion/compare)diff --git a/packages/docs/package.json b/packages/docs/package.jsonindex 89761af66b..6c4bfe32f6 100644--- a/packages/docs/package.json+++ b/packages/docs/package.json@@ -20,7 +20,8 @@"test": "bun test src","remotion": "remotion studio src/remotion/entry.ts","render-cards": "bun run render-cards.ts",- "render-element-previews": "bun run render-element-previews.ts"+ "render-element-previews": "bun run render-element-previews.ts",+ "upload-element-preview": "bun run upload-element-preview.ts"},"dependencies": {"@remotion/studio-protocol": "workspace:*",diff --git a/packages/docs/render-element-previews.ts b/packages/docs/render-element-previews.tsindex b6e0ec5878..cb5eefa123 100644--- a/packages/docs/render-element-previews.ts+++ b/packages/docs/render-element-previews.ts@@ -2,14 +2,15 @@ import {mkdirSync, rmSync} from 'fs';import path from 'path';import {bundle} from '@remotion/bundler';import {getCompositions, renderMedia, renderStill} from '@remotion/renderer';-import {S3Client} from 'bun';import {elementDefinitions} from './src/components/Elements/element-definitions';import {getElementCompositionId} from './src/components/Elements/element-utils';-const r2Endpoint =- 'https://2fe488b3b0f4deee223aef7464784c46.r2.cloudflarestorage.com';-const r2Bucket = 'parser-media';-const upload = process.argv.includes('--upload');+if (process.argv.includes('--upload')) {+ throw new Error(+ 'Preview rendering no longer uploads. Use upload-element-preview after review.',+ );+}+const outputDirectoryArgument = process.argv.find((argument) =>argument.startsWith('--output-dir='),);@@ -44,80 +45,6 @@ const definitionsToRender = selectedElementDefinition? [selectedElementDefinition]: allElementDefinitions;-const getUploadKey = (publicUrl: string) => {- const url = new URL(publicUrl);- if (- url.origin !== 'https://remotion.media' ||- !url.pathname.startsWith('/elements/')- ) {- throw new Error(`Unexpected Element preview URL: ${publicUrl}`);- }-- return url.pathname.slice(1);-};--const ensureUploadCredentials = () => {- if (!Bun.env.AWS_ACCESS_KEY_ID || !Bun.env.AWS_SECRET_ACCESS_KEY) {- throw new Error(- '--upload requires AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY',- );- }-- return {- accessKeyId: Bun.env.AWS_ACCESS_KEY_ID,- secretAccessKey: Bun.env.AWS_SECRET_ACCESS_KEY,- };-};--const uploadAsset = async ({- client,- contentType,- filePath,- key,- publicUrl,-}: {- client: S3Client;- contentType: string;- filePath: string;- key: string;- publicUrl: string;-}) => {- const file = Bun.file(filePath, {type: contentType});- await client.write(key, file);-- const remote = await client.stat(key);- if (remote.size !== file.size) {- throw new Error(- `Uploaded size mismatch for ${key}: expected ${file.size}, got ${remote.size}`,- );- }-- const response = await fetch(`${publicUrl}?verify=${Date.now()}`, {- method: 'HEAD',- });- if (!response.ok) {- throw new Error(`Could not verify ${publicUrl}: HTTP ${response.status}`);- }-- const remoteContentType = response.headers.get('content-type');- if (remoteContentType !== contentType) {- throw new Error(- `Unexpected content type for ${publicUrl}: expected ${contentType}, got ${remoteContentType}`,- );- }-- console.log(`Uploaded ${publicUrl} (${file.size} bytes)`);-};--const credentials = upload ? ensureUploadCredentials() : null;-const client = credentials- ? new S3Client({- ...credentials,- bucket: r2Bucket,- endpoint: r2Endpoint,- })- : null;-if (selectedElementSlug === null) {rmSync(outputDirectory, {force: true, recursive: true});} else {@@ -163,7 +90,6 @@ for (const actualId of actualCompositionIds) {}for (const definition of definitionsToRender) {- const {posterUrl, videoUrl} = definition.preview;const compositionId = getElementCompositionId(definition.slug);const composition = elementCompositions.find((candidate) => candidate.id === compositionId,@@ -204,30 +130,9 @@ for (const definition of definitionsToRender) {console.log(`Rendered ${pngPath}`);console.log(`Rendered ${videoPath}`);-- if (client) {- await uploadAsset({- client,- contentType: 'image/png',- filePath: pngPath,- key: getUploadKey(posterUrl),- publicUrl: posterUrl,- });- await uploadAsset({- client,- contentType: 'video/mp4',- filePath: videoPath,- key: getUploadKey(videoUrl),- publicUrl: videoUrl,- });- }}const renderedScope = selectedElementSlug? `Element ${selectedElementSlug}`: 'all Element previews';-console.log(- upload- ? `Rendered and uploaded ${renderedScope}.`- : `Rendered ${renderedScope} to ${outputDirectory}.`,-);+console.log(`Rendered ${renderedScope} to ${outputDirectory}.`);diff --git a/packages/docs/src/components/Elements/element-definitions.ts b/packages/docs/src/components/Elements/element-definitions.tsindex 6b2b39e418..bd1c0836f2 100644--- a/packages/docs/src/components/Elements/element-definitions.ts+++ b/packages/docs/src/components/Elements/element-definitions.ts@@ -23,8 +23,12 @@ import {TextMarker} from '../../../elements/text/text-marker/text-marker';import type {Contributor} from '../Credits';export type ElementPreviewMetadata = {- readonly posterUrl: `https://remotion.media/elements/${string}-preview.png`;- readonly videoUrl: `https://remotion.media/elements/${string}-preview.mp4`;+ readonly posterUrl:+ | `/elements/${string}-preview.png`+ | `https://remotion.media/elements/${string}-preview.png`;+ readonly videoUrl:+ | `/elements/${string}-preview.mp4`+ | `https://remotion.media/elements/${string}-preview.mp4`;};export type ElementDefinition = {diff --git a/packages/docs/src/test/elements.test.ts b/packages/docs/src/test/elements.test.tsindex 762f88b4d5..e0b287a2d5 100644--- a/packages/docs/src/test/elements.test.ts+++ b/packages/docs/src/test/elements.test.ts@@ -23,6 +23,17 @@ import {Seo} from '../components/Seo';const elementsRoot = path.join(__dirname, '..', '..', 'elements');const templateRoot = path.join(__dirname, '..', '..', 'elements-template');+const staticElementsRoot = path.join(+ __dirname,+ '..',+ '..',+ 'static',+ 'elements',+);+const elementSidebars = readFileSync(+ path.join(__dirname, '..', '..', 'elements-sidebars.ts'),+ 'utf8',+);const elementDefinitionList = Object.values(elementDefinitions);const exactVersionPattern =/^(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-]+)*)?$/;@@ -250,7 +261,7 @@ describe('Element library', () => {});describe('Element social previews', () => {- test('uses the published poster in each Element page frontmatter', () => {+ test('uses the matching poster in each Element page frontmatter', () => {for (const definition of elementDefinitionList) {const mdx = readFileSync(path.join(elementsRoot, definition.slug, 'index.mdx'),@@ -260,7 +271,7 @@ describe('Element social previews', () => {}});- test('renders Open Graph video metadata for published previews', () => {+ test('renders Open Graph video metadata for previews', () => {for (const definition of elementDefinitionList) {const url = definition.preview.videoUrl;const markup = renderToStaticMarkup(@@ -453,7 +464,7 @@ describe('Element preview definitions', () => {}});- test('uses stable composition IDs and explicit flat MP4 preview URLs', () => {+ test('uses stable composition IDs and flat review or published preview paths', () => {const compositionIds = elementDefinitionList.map((definition) =>getElementCompositionId(definition.slug),);@@ -461,23 +472,59 @@ describe('Element preview definitions', () => {for (const definition of elementDefinitionList) {const assetSlug = definition.slug.replaceAll('/', '-');- expect(String(definition.preview.posterUrl)).toBe(- `https://remotion.media/elements/${assetSlug}-preview.png`,+ const localPosterUrl = `/elements/${assetSlug}-preview.png`;+ const localVideoUrl = `/elements/${assetSlug}-preview.mp4`;+ const publicPosterUrl = `https://remotion.media${localPosterUrl}`;+ const publicVideoUrl = `https://remotion.media${localVideoUrl}`;+ const posterPath = path.join(+ staticElementsRoot,+ `${assetSlug}-preview.png`,);- expect(String(definition.preview.videoUrl)).toBe(- `https://remotion.media/elements/${assetSlug}-preview.mp4`,+ const videoPath = path.join(+ staticElementsRoot,+ `${assetSlug}-preview.mp4`,);+ const usesReviewUrls = definition.preview.posterUrl === localPosterUrl;++ if (usesReviewUrls) {+ expect(String(definition.preview.videoUrl)).toBe(localVideoUrl);++ const isSubmitted = elementSidebars.includes(+ `'${definition.slug}/index'`,+ );+ expect(existsSync(posterPath)).toBe(isSubmitted);+ expect(existsSync(videoPath)).toBe(isSubmitted);+ if (isSubmitted) {+ const poster = readFileSync(posterPath);+ const video = readFileSync(videoPath);+ expect(Array.from(poster.subarray(0, 8))).toEqual([+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,+ ]);+ expect(video.subarray(4, 8).toString('ascii')).toBe('ftyp');+ expect(+ statSync(posterPath).size + statSync(videoPath).size,+ ).toBeLessThanOrEqual(10 * 1024 * 1024);+ }+ } else {+ expect(String(definition.preview.posterUrl)).toBe(publicPosterUrl);+ expect(String(definition.preview.videoUrl)).toBe(publicVideoUrl);+ expect(existsSync(posterPath)).toBe(false);+ expect(existsSync(videoPath)).toBe(false);+ }}});- test('the Element template includes explicit defaults and preview URLs', () => {+ test('the Element template includes explicit defaults and local preview URLs', () => {const template = readFileSync(path.join(templateRoot, 'index.mdx'), 'utf8');expect(template).toContain("installationMode: 'wrapped'");expect(template).toContain(- "posterUrl: 'https://remotion.media/elements/category-element-title-preview.png'",+ 'image: /elements/category-element-title-preview.png',+ );+ expect(template).toContain(+ "posterUrl: '/elements/category-element-title-preview.png'",);expect(template).toContain(- "videoUrl: 'https://remotion.media/elements/category-element-title-preview.mp4'",+ "videoUrl: '/elements/category-element-title-preview.mp4'",);});diff --git a/packages/docs/tsconfig.json b/packages/docs/tsconfig.jsonindex ceaa5ec2f8..1df876295a 100644--- a/packages/docs/tsconfig.json+++ b/packages/docs/tsconfig.json@@ -58,6 +58,7 @@"exclude": ["copy-convert.ts","render-cards.ts",- "render-element-previews.ts"+ "render-element-previews.ts",+ "upload-element-preview.ts"]}diff --git a/packages/docs/upload-element-preview.ts b/packages/docs/upload-element-preview.tsnew file mode 100644index 0000000000..87d77cc2bc--- /dev/null+++ b/packages/docs/upload-element-preview.ts@@ -0,0 +1,200 @@+import {execFileSync} from 'child_process';+import path from 'path';+import {S3Client} from 'bun';+import {elementDefinitions} from './src/components/Elements/element-definitions';++const elementArguments = process.argv.filter((argument) =>+ argument.startsWith('--element='),+);+const sourceArguments = process.argv.filter((argument) =>+ argument.startsWith('--source='),+);+if (process.argv.includes('--element')) {+ throw new Error('Use --element=<category>/<slug>');+}++if (process.argv.includes('--source')) {+ throw new Error('Use --source=render or --source=submission');+}++if (elementArguments.length !== 1) {+ throw new Error('Specify exactly one --element=<category>/<slug> argument');+}++if (sourceArguments.length !== 1) {+ throw new Error('Specify exactly one --source=render|submission argument');+}++const source = sourceArguments[0].slice('--source='.length);+if (source !== 'render' && source !== 'submission') {+ throw new Error(`Invalid preview source: ${source}`);+}++const selectedElementSlug = elementArguments[0].slice('--element='.length);+const definition = Object.values(elementDefinitions).find(+ (candidate) => candidate.slug === selectedElementSlug,+);+if (!definition) {+ throw new Error(`Unknown Element: ${selectedElementSlug}`);+}++const assetSlug = definition.slug.replaceAll('/', '-');+const expectedPosterUrl = `/elements/${assetSlug}-preview.png` as const;+const expectedVideoUrl = `/elements/${assetSlug}-preview.mp4` as const;+if (+ definition.preview.posterUrl !== expectedPosterUrl ||+ definition.preview.videoUrl !== expectedVideoUrl+) {+ throw new Error(+ `${definition.slug} must use its local review URLs before its previews can be uploaded`,+ );+}++const sourceDirectory =+ source === 'render'+ ? path.join(process.cwd(), '.element-previews', definition.slug)+ : path.join(process.cwd(), 'static', 'elements');+const assets = [+ {+ contentType: 'image/png',+ filePath: path.join(+ sourceDirectory,+ source === 'render' ? 'preview.png' : `${assetSlug}-preview.png`,+ ),+ localUrl: expectedPosterUrl,+ },+ {+ contentType: 'video/mp4',+ filePath: path.join(+ sourceDirectory,+ source === 'render' ? 'preview.mp4' : `${assetSlug}-preview.mp4`,+ ),+ localUrl: expectedVideoUrl,+ },+] as const;++let totalSize = 0;+for (const asset of assets) {+ if (source === 'submission') {+ try {+ execFileSync(+ 'git',+ ['ls-files', '--error-unmatch', '--', asset.filePath],+ {+ cwd: process.cwd(),+ stdio: 'ignore',+ },+ );+ } catch {+ throw new Error(+ `Submitted preview asset must be committed: ${asset.filePath}`,+ );+ }++ const gitStatus = execFileSync(+ 'git',+ ['status', '--short', '--', asset.filePath],+ {+ cwd: process.cwd(),+ encoding: 'utf8',+ },+ );+ if (gitStatus.trim() !== '') {+ throw new Error(+ `Submitted preview asset must be unmodified: ${asset.filePath}`,+ );+ }+ }++ const file = Bun.file(asset.filePath, {type: asset.contentType});+ if (!(await file.exists())) {+ throw new Error(`Missing approved preview asset: ${asset.filePath}`);+ }++ totalSize += file.size;+ const header = new Uint8Array(await file.slice(0, 12).arrayBuffer());+ if (+ asset.contentType === 'image/png' &&+ (header.length < 8 ||+ header[0] !== 0x89 ||+ header[1] !== 0x50 ||+ header[2] !== 0x4e ||+ header[3] !== 0x47 ||+ header[4] !== 0x0d ||+ header[5] !== 0x0a ||+ header[6] !== 0x1a ||+ header[7] !== 0x0a)+ ) {+ throw new Error(`Invalid PNG signature: ${asset.filePath}`);+ }++ if (+ asset.contentType === 'video/mp4' &&+ (header.length < 8 ||+ header[4] !== 0x66 ||+ header[5] !== 0x74 ||+ header[6] !== 0x79 ||+ header[7] !== 0x70)+ ) {+ throw new Error(`Invalid MP4 signature: ${asset.filePath}`);+ }+}++const maxCombinedSize = 10 * 1024 * 1024;+if (totalSize > maxCombinedSize) {+ throw new Error(+ `Element previews total ${totalSize} bytes; the limit is ${maxCombinedSize} bytes`,+ );+}++if (!Bun.env.AWS_ACCESS_KEY_ID || !Bun.env.AWS_SECRET_ACCESS_KEY) {+ throw new Error(+ 'Uploading requires AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY',+ );+}++const client = new S3Client({+ accessKeyId: Bun.env.AWS_ACCESS_KEY_ID,+ secretAccessKey: Bun.env.AWS_SECRET_ACCESS_KEY,+ bucket: 'parser-media',+ endpoint: 'https://2fe488b3b0f4deee223aef7464784c46.r2.cloudflarestorage.com',+});++for (const asset of assets) {+ const file = Bun.file(asset.filePath, {type: asset.contentType});+ const key = asset.localUrl.slice(1);+ const publicUrl = `https://remotion.media${asset.localUrl}`;+ await client.write(key, file);++ const remote = await client.stat(key);+ if (remote.size !== file.size) {+ throw new Error(+ `Uploaded size mismatch for ${key}: expected ${file.size}, got ${remote.size}`,+ );+ }++ const response = await fetch(`${publicUrl}?verify=${Date.now()}`, {+ method: 'HEAD',+ });+ if (!response.ok) {+ throw new Error(`Could not verify ${publicUrl}: HTTP ${response.status}`);+ }++ const remoteContentType = response.headers.get('content-type');+ if (remoteContentType !== asset.contentType) {+ throw new Error(+ `Unexpected content type for ${publicUrl}: expected ${asset.contentType}, got ${remoteContentType}`,+ );+ }++ console.log(`Uploaded ${publicUrl} (${file.size} bytes)`);+}++console.log('Upload verified. Replace the review URLs with:');+console.log(`https://remotion.media${expectedPosterUrl}`);+console.log(`https://remotion.media${expectedVideoUrl}`);+if (source === 'submission') {+ console.log('Then delete the two files from packages/docs/static/elements.');+} else {+ console.log('Keep the ignored .element-previews files out of Git.');+}