🎥 Make videos programmatically with React
Elements: Add rendered previews and R2 upload utilities
Igor Samokhovets49880d789e0f
diff --git a/bun.lock b/bun.lockindex e1c782d08d..52196adfbc 100644--- a/bun.lock+++ b/bun.lock@@ -2159,8 +2159,11 @@"remotion": "workspace:*",},"devDependencies": {+ "@aws-sdk/client-s3": "3.986.0","@react-router/dev": "8.3.0",+ "@remotion/bundler": "workspace:*","@remotion/eslint-config-flat": "workspace:*",+ "@remotion/renderer": "workspace:*","@tailwindcss/vite": "4.3.3","@types/node": "22.20.0","@types/react": "19.2.7",diff --git a/packages/template-element-library/.env.example b/packages/template-element-library/.env.examplenew file mode 100644index 0000000000..f3fc9ada20--- /dev/null+++ b/packages/template-element-library/.env.example@@ -0,0 +1,8 @@+# Copy to .env. Never commit credentials or prefix them with VITE_.+AWS_ACCESS_KEY_ID=+AWS_SECRET_ACCESS_KEY=+AWS_REGION=auto+S3_ENDPOINT=https://YOUR_ACCOUNT_ID.r2.cloudflarestorage.com+S3_BUCKET=your-bucket+S3_PUBLIC_URL=https://media.example.com+S3_PREFIX=element-previewsdiff --git a/packages/template-element-library/.gitignore b/packages/template-element-library/.gitignoreindex 71196306e6..a0f7ab2452 100644--- a/packages/template-element-library/.gitignore+++ b/packages/template-element-library/.gitignore@@ -3,4 +3,7 @@ node_modules/build/out/.env+.env.*+!.env.example+public/previews/.DS_Storediff --git a/packages/template-element-library/README.md b/packages/template-element-library/README.mdindex 0d3a90b6c2..4fc1de24a3 100644--- a/packages/template-element-library/README.md+++ b/packages/template-element-library/README.md@@ -26,10 +26,32 @@ For exports and upgrades, see [`npx remotion render`](https://www.remotion.dev/d- `remotion/`: authoring compositions and the preview stage.- `lib/element-payload.ts`: raw source loading and Studio Protocol payloads.-To add an Element, create `elements/<slug>/<slug>.tsx`, add it to `elements/registry.ts`, and register its authoring composition in `remotion/Root.tsx`. The website and Studio use the same source files.+To add an Element, create `elements/<slug>/<slug>.tsx`, add its metadata to `elements/registry.ts`, map its component in `remotion/ElementPreview.tsx`, and register its authoring composition in `remotion/Root.tsx`. The detail page, preview renderer, and Studio use the same source files. Gallery previews are rendered assets, not live Players.See the [Element guidelines](https://www.remotion.dev/elements/guidelines), [interactivity documentation](https://www.remotion.dev/docs/studio/interactivity), and [library integration guide](https://www.remotion.dev/docs/studio-protocol/component-library-integration) for layout, assets, dependencies, and installation requirements.+## Render and upload previews++The starter previews are hosted on `remotion.media`. The gallery and caption picker use posters and hover/focus videos from `elements/previews.json`. Rendering uses a separate entry point, `remotion/previews.tsx`, with dimensions and default props from the registry. Source edits appear in the listing after you rerender.++```sh+npm run render-previews+# Or render one Element:+npm run render-previews -- --element=animated-title+```++This renders PNG posters and muted MP4 videos into ignored `public/previews/` directories and updates the manifest to local URLs. Transparent previews use WebM instead of MP4. Review the results with `npm run dev`. Playback failures and reduced-motion preferences retain the poster. Pass `--browser-executable=/path/to/chrome` to use an existing browser.++To publish previews, copy `.env.example` to `.env` and configure your own S3-compatible bucket, endpoint, public HTTPS URL, and credentials. For R2, enable a [public domain](https://developers.cloudflare.com/r2/buckets/public-buckets/) for the bucket. Credentials are used only by the upload script; never prefix them with `VITE_`.++```sh+npm run upload-previews+# Or upload one reviewed Element:+npm run upload-previews -- --element=animated-title+```++Uploads use unique URLs and verify public content types and SHA-256 checksums before updating `elements/previews.json`. Existing hosted assets are never overwritten. Commit the updated manifest, then rebuild the website. Local renders remain ignored and can be removed after upload; shipping local previews instead is also supported.+## Caption styles`/captions` is a separate gallery and Studio caption-style picker. Library registration includes this URL as `captionStylesUrl`. In Studio's captions context, the page hides navigation, uses a transparent background, and reflects selection and Reset through [`subscribeToCaptionStyleSelection()`](https://www.remotion.dev/docs/studio-protocol/subscribe-to-caption-style-selection).diff --git a/packages/template-element-library/app/components/caption-style-button.tsx b/packages/template-element-library/app/components/caption-style-button.tsxindex 2b9d8bd815..3c95b8caee 100644--- a/packages/template-element-library/app/components/caption-style-button.tsx+++ b/packages/template-element-library/app/components/caption-style-button.tsx@@ -2,7 +2,7 @@ import { CheckCircleIcon } from "@heroicons/react/16/solid";import { setStudioDragData } from "@remotion/studio-protocol";import { useState, type RefObject } from "react";import type { CatalogEntry } from "../../lib/element-payload";-import { ElementPreview } from "./element-preview";+import { RenderedPreview } from "./rendered-preview";export const CaptionStyleButton = ({entry,@@ -48,9 +48,8 @@ export const CaptionStyleButton = ({aria-hiddenclassName="transparency-grid pointer-events-none flex aspect-video items-center overflow-hidden rounded-lg">- <ElementPreview+ <RenderedPreviewdefinition={entry.definition}- controls={false}playing={hovered || focused}/></div>diff --git a/packages/template-element-library/app/components/element-card.tsx b/packages/template-element-library/app/components/element-card.tsxindex 59eaba2a61..f6acbe7aa4 100644--- a/packages/template-element-library/app/components/element-card.tsx+++ b/packages/template-element-library/app/components/element-card.tsx@@ -2,7 +2,7 @@ import { useState } from "react";import { Link, useOutletContext } from "react-router";import { setStudioDragData } from "@remotion/studio-protocol";import type { CatalogEntry } from "../../lib/element-payload";-import { ElementPreview } from "./element-preview";+import { RenderedPreview } from "./rendered-preview";import { StudioActions } from "./studio-actions";export const ElementCard = ({ entry }: { entry: CatalogEntry }) => {@@ -39,9 +39,8 @@ export const ElementCard = ({ entry }: { entry: CatalogEntry }) => {className={`relative flex aspect-video items-center overflow-hidden rounded-[min(1vw,8px)] bg-neutral-50 outline-1 -outline-offset-1 outline-black/5 [&>div]:pointer-events-none ${definition.previewBackground === "transparent" ? "transparency-grid" : ""}`}aria-hidden>- <ElementPreview+ <RenderedPreviewdefinition={definition}- controls={false}playing={hovered || focused}/></div>diff --git a/packages/template-element-library/app/components/element-preview.tsx b/packages/template-element-library/app/components/element-preview.tsxindex ebdfd482df..e85e65144d 100644--- a/packages/template-element-library/app/components/element-preview.tsx+++ b/packages/template-element-library/app/components/element-preview.tsx@@ -1,43 +1,20 @@-import { Player, type PlayerRef } from "@remotion/player";-import { useEffect, useMemo, useRef, type CSSProperties } from "react";+import { Player } from "@remotion/player";+import { useMemo, type CSSProperties } from "react";import type { ElementDefinition } from "../../elements/registry";import { ElementPreview as PreviewComposition } from "../../remotion/ElementPreview";export const ElementPreview = ({definition,- controls,- playing,}: {definition: ElementDefinition;- controls: boolean;- playing: boolean;}) => {- const player = useRef<PlayerRef>(null);const inputProps = useMemo(() => ({ slug: definition.slug }),[definition.slug],);- useEffect(() => {- if (controls) return;- const preference = window.matchMedia("(prefers-reduced-motion: reduce)");- const update = () => {- if (playing && !preference.matches) {- player.current?.seekTo(0);- player.current?.play();- } else {- player.current?.pause();- player.current?.seekTo(definition.posterFrame);- }- };- update();- preference.addEventListener("change", update);- return () => preference.removeEventListener("change", update);- }, [controls, playing, definition.posterFrame]);-return (<Player- ref={player}component={PreviewComposition}inputProps={inputProps}compositionWidth={definition.width}@@ -45,10 +22,7 @@ export const ElementPreview = ({durationInFrames={definition.durationInFrames}fps={definition.fps}initialFrame={definition.posterFrame}- controls={controls}- clickToPlay={controls}- doubleClickToFullscreen={controls}- spaceKeyToPlayOrPause={controls}+ controlsloopclassName="bg-(--preview-background)"style={diff --git a/packages/template-element-library/app/components/rendered-preview.tsx b/packages/template-element-library/app/components/rendered-preview.tsxnew file mode 100644index 0000000000..010f6b2ad1--- /dev/null+++ b/packages/template-element-library/app/components/rendered-preview.tsx@@ -0,0 +1,80 @@+import { useEffect, useRef, useState } from "react";+import type { ElementDefinition } from "../../elements/registry";+import previews from "../../elements/previews.json";++export const RenderedPreview = ({+ definition,+ playing,+}: {+ definition: ElementDefinition;+ playing: boolean;+}) => {+ const assets = (+ previews as Record<string, { posterUrl: string; videoUrl: string }>+ )[definition.slug];+ const video = useRef<HTMLVideoElement>(null);+ const [reducedMotion, setReducedMotion] = useState(true);+ const [failed, setFailed] = useState(false);+ const shouldPlay = playing && !reducedMotion && !failed;++ useEffect(() => {+ const preference = window.matchMedia("(prefers-reduced-motion: reduce)");+ const update = () => setReducedMotion(preference.matches);+ update();+ preference.addEventListener("change", update);+ return () => preference.removeEventListener("change", update);+ }, []);++ useEffect(() => {+ setFailed(false);+ }, [playing, assets?.videoUrl]);++ useEffect(() => {+ const element = video.current;+ if (!element) return;+ let canceled = false;+ element.play().catch(() => {+ if (!canceled) setFailed(true);+ });+ return () => {+ canceled = true;+ element.pause();+ };+ }, [shouldPlay, assets?.videoUrl]);++ if (!assets) {+ return (+ <div className="w-full p-4 text-center text-base text-muted sm:text-sm">+ Run render-previews+ </div>+ );+ }++ return (+ <div className="pointer-events-none relative w-full" aria-hidden>+ <img+ alt=""+ src={assets.posterUrl}+ width={definition.width}+ height={definition.height}+ loading="lazy"+ decoding="async"+ draggable={false}+ className="w-full"+ />+ {shouldPlay ? (+ <video+ ref={video}+ src={assets.videoUrl}+ poster={assets.posterUrl}+ muted+ loop+ playsInline+ preload="none"+ onError={() => setFailed(true)}+ className="absolute inset-0 size-full"+ />+ ) : null}+ </div>+ );+};diff --git a/packages/template-element-library/app/routes/element.tsx b/packages/template-element-library/app/routes/element.tsxindex 81115f0ca7..83d0e5740f 100644--- a/packages/template-element-library/app/routes/element.tsx+++ b/packages/template-element-library/app/routes/element.tsx@@ -78,12 +78,7 @@ export default function ElementPage() {<divclassName={`min-w-0 overflow-hidden rounded-[min(1vw,8px)] outline-1 -outline-offset-1 outline-black/5 ${definition.previewBackground === "transparent" ? "transparency-grid" : ""}`}>- <ElementPreview- key={slug}- definition={definition}- controls- playing={false}- />+ <ElementPreview key={slug} definition={definition} /></div><aside aria-label="Element details" className="min-w-0"><StudioActions key={slug} entry={entry} variant="default" />diff --git a/packages/template-element-library/elements/previews.json b/packages/template-element-library/elements/previews.jsonnew file mode 100644index 0000000000..1628626e62--- /dev/null+++ b/packages/template-element-library/elements/previews.json@@ -0,0 +1,18 @@+{+ "animated-title": {+ "posterUrl": "https://remotion.media/templates/element-library/animated-title/67dc134e-2db2-4be7-8b71-52099e95182a/preview.png",+ "videoUrl": "https://remotion.media/templates/element-library/animated-title/67dc134e-2db2-4be7-8b71-52099e95182a/preview.mp4"+ },+ "lower-third": {+ "posterUrl": "https://remotion.media/templates/element-library/lower-third/67dc134e-2db2-4be7-8b71-52099e95182a/preview.png",+ "videoUrl": "https://remotion.media/templates/element-library/lower-third/67dc134e-2db2-4be7-8b71-52099e95182a/preview.mp4"+ },+ "animated-background": {+ "posterUrl": "https://remotion.media/templates/element-library/animated-background/67dc134e-2db2-4be7-8b71-52099e95182a/preview.png",+ "videoUrl": "https://remotion.media/templates/element-library/animated-background/67dc134e-2db2-4be7-8b71-52099e95182a/preview.mp4"+ },+ "accent-captions": {+ "posterUrl": "https://remotion.media/templates/element-library/accent-captions/67dc134e-2db2-4be7-8b71-52099e95182a/preview.png",+ "videoUrl": "https://remotion.media/templates/element-library/accent-captions/67dc134e-2db2-4be7-8b71-52099e95182a/preview.webm"+ }+}diff --git a/packages/template-element-library/elements/registry.ts b/packages/template-element-library/elements/registry.tsindex a8b9f66774..456e80a36d 100644--- a/packages/template-element-library/elements/registry.ts+++ b/packages/template-element-library/elements/registry.ts@@ -5,18 +5,12 @@ import type {ElementInitialProps,ElementInstallationMode,} from "@remotion/studio-protocol";-import type { ComponentType } from "react";-import { AccentCaptions } from "./accent-captions/accent-captions";-import { AnimatedTitle } from "./animated-title/animated-title";-import { LowerThird } from "./lower-third/lower-third";-import { AnimatedBackground } from "./animated-background/animated-background";export type ElementDefinition = {slug: string;displayName: string;category: string;description: string;- component: ComponentType<Record<string, unknown>>;width: number;height: number;fps: number;@@ -37,7 +31,6 @@ export const elements: readonly ElementDefinition[] = [displayName: "Animated title",category: "Text",description: "A centered title with a soft entrance and exit.",- component: AnimatedTitle,width: 1280,height: 720,fps: 30,@@ -56,7 +49,6 @@ export const elements: readonly ElementDefinition[] = [displayName: "Lower third",category: "Overlays",description: "An animated name and role label for your footage.",- component: LowerThird,width: 1280,height: 720,fps: 30,@@ -75,7 +67,6 @@ export const elements: readonly ElementDefinition[] = [displayName: "Moving grid",category: "Backgrounds",description: "A looping grid with adjustable background and line colors.",- component: AnimatedBackground,width: 1280,height: 720,fps: 30,@@ -95,7 +86,6 @@ export const elements: readonly ElementDefinition[] = [category: "Captions",description:"Word-by-word captions with a warm highlight and a crisp outline.",- component: AccentCaptions,width: 900,height: 300,fps: 30,diff --git a/packages/template-element-library/package.json b/packages/template-element-library/package.jsonindex 6b6e355fee..14ef6da840 100644--- a/packages/template-element-library/package.json+++ b/packages/template-element-library/package.json@@ -11,7 +11,9 @@"preview": "sirv build/client --single __spa-fallback.html","typecheck": "react-router typegen && tsc","lint": "eslint . && react-router typegen && tsc",- "remotion:studio": "remotion studio"+ "remotion:studio": "remotion studio",+ "render-previews": "node scripts/render-previews.ts",+ "upload-previews": "node --env-file-if-exists=.env scripts/upload-previews.ts"},"sideEffects": ["*.css"@@ -30,7 +32,10 @@"isbot": "5.1.40"},"devDependencies": {+ "@aws-sdk/client-s3": "3.986.0","@react-router/dev": "8.3.0",+ "@remotion/bundler": "workspace:*",+ "@remotion/renderer": "workspace:*","@remotion/eslint-config-flat": "workspace:*","@types/node": "22.20.0","@types/react": "19.2.7",diff --git a/packages/template-element-library/remotion/ElementPreview.tsx b/packages/template-element-library/remotion/ElementPreview.tsxindex c06e1fd39e..b4dbfb82ea 100644--- a/packages/template-element-library/remotion/ElementPreview.tsx+++ b/packages/template-element-library/remotion/ElementPreview.tsx@@ -1,12 +1,24 @@import { Sequence } from "remotion";import { elements } from "../elements/registry";+import { AnimatedTitle } from "../elements/animated-title/animated-title";+import { LowerThird } from "../elements/lower-third/lower-third";+import { AnimatedBackground } from "../elements/animated-background/animated-background";+import { AccentCaptions } from "../elements/accent-captions/accent-captions";+import type { ComponentType } from "react";++const components: Record<string, ComponentType<Record<string, unknown>>> = {+ "animated-title": AnimatedTitle,+ "lower-third": LowerThird,+ "animated-background": AnimatedBackground,+ "accent-captions": AccentCaptions,+};export const ElementPreview = ({ slug }: { slug: string }) => {const definition = elements.find((element) => element.slug === slug);- if (!definition) {+ const Component = components[slug];+ if (!definition || !Component) {throw new Error(`Unknown Element: ${slug}`);}- const Component = definition.component;const dimensions = definition.dimensions;return (diff --git a/packages/template-element-library/remotion/previews.tsx b/packages/template-element-library/remotion/previews.tsxnew file mode 100644index 0000000000..c2d5598469--- /dev/null+++ b/packages/template-element-library/remotion/previews.tsx@@ -0,0 +1,20 @@+import { Composition, registerRoot } from "remotion";+import { elements } from "../elements/registry";+import { ElementPreview } from "./ElementPreview";++registerRoot(() => (+ <>+ {elements.map((element) => (+ <Composition+ key={element.slug}+ id={element.slug}+ component={ElementPreview}+ width={element.width}+ height={element.height}+ fps={element.fps}+ durationInFrames={element.durationInFrames}+ defaultProps={{ slug: element.slug }}+ />+ ))}+ </>+));diff --git a/packages/template-element-library/scripts/render-previews.ts b/packages/template-element-library/scripts/render-previews.tsnew file mode 100644index 0000000000..a4d422a559--- /dev/null+++ b/packages/template-element-library/scripts/render-previews.ts@@ -0,0 +1,86 @@+import { randomUUID } from "node:crypto";+import { mkdir, readFile, rename, writeFile } from "node:fs/promises";+import path from "node:path";+import { parseArgs } from "node:util";+import { bundle } from "@remotion/bundler";+import { getCompositions, renderMedia, renderStill } from "@remotion/renderer";+import { elements } from "../elements/registry.ts";++const { values } = parseArgs({+ options: {+ element: { type: "string" },+ "browser-executable": { type: "string" },+ help: { type: "boolean", short: "h" },+ },+});+if (values.help) {+ console.log(+ "Usage: npm run render-previews -- [--element=<slug>] [--browser-executable=<path>]",+ );+ process.exit(0);+}++const selected =+ values.element === undefined+ ? elements+ : elements.filter(({ slug }) => slug === values.element);+if (selected.length === 0)+ throw new Error(`Unknown Element: ${values.element}`);+for (const { slug } of selected) {+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug)) {+ throw new Error(`Invalid Element slug: ${slug}`);+ }+}++const manifestPath = path.resolve("elements/previews.json");+const previews: Record<string, { posterUrl: string; videoUrl: string }> =+ JSON.parse(await readFile(manifestPath, "utf8"));+const browserExecutable = values["browser-executable"] ?? null;+const serveUrl = await bundle({+ entryPoint: path.resolve("remotion/previews.tsx"),+});+const compositions = await getCompositions({+ serveUrl,+ inputProps: {},+ browserExecutable,+});+const version = randomUUID();++for (const definition of selected) {+ const composition = compositions.find(({ id }) => id === definition.slug);+ if (!composition)+ throw new Error(`Missing preview composition: ${definition.slug}`);+ const transparent = definition.previewBackground === "transparent";+ const directory = `/previews/${definition.slug}/${version}`;+ const posterUrl = `${directory}/preview.png`;+ const videoUrl = `${directory}/preview.${transparent ? "webm" : "mp4"}`;+ await mkdir(path.join("public", directory), { recursive: true });+ console.log(`Rendering ${definition.displayName}`);+ await renderStill({+ serveUrl,+ composition,+ browserExecutable,+ frame: definition.posterFrame,+ imageFormat: "png",+ output: path.join("public", posterUrl),+ });+ await renderMedia({+ serveUrl,+ composition,+ browserExecutable,+ codec: transparent ? "vp9" : "h264",+ pixelFormat: transparent ? "yuva420p" : "yuv420p",+ imageFormat: "png",+ crf: transparent ? 30 : 23,+ muted: true,+ outputLocation: path.join("public", videoUrl),+ });+ previews[definition.slug] = { posterUrl, videoUrl };+}++const temporaryManifest = `${manifestPath}.${version}.tmp`;+await writeFile(temporaryManifest, `${JSON.stringify(previews, null, 2)}\n`);+await rename(temporaryManifest, manifestPath);+console.log(+ "Previews rendered. Review them on the website before running upload-previews.",+);diff --git a/packages/template-element-library/scripts/upload-previews.ts b/packages/template-element-library/scripts/upload-previews.tsnew file mode 100644index 0000000000..e40859508e--- /dev/null+++ b/packages/template-element-library/scripts/upload-previews.ts@@ -0,0 +1,176 @@+import { createHash, randomUUID } from "node:crypto";+import { readFile, rename, writeFile } from "node:fs/promises";+import path from "node:path";+import { parseArgs } from "node:util";+import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";+import { elements } from "../elements/registry.ts";++const { values } = parseArgs({+ options: {+ element: { type: "string" },+ help: { type: "boolean", short: "h" },+ },+});+if (values.help) {+ console.log(+ "Usage: npm run upload-previews -- [--element=<slug>]\nConfigure .env using .env.example. Render and review previews first.",+ );+ process.exit(0);+}++const selected =+ values.element === undefined+ ? elements+ : elements.filter(({ slug }) => slug === values.element);+if (selected.length === 0)+ throw new Error(`Unknown Element: ${values.element}`);++const {+ S3_ENDPOINT,+ S3_BUCKET,+ S3_PUBLIC_URL,+ AWS_ACCESS_KEY_ID,+ AWS_SECRET_ACCESS_KEY,+} = process.env;+if (+ !S3_ENDPOINT ||+ !S3_BUCKET ||+ !S3_PUBLIC_URL ||+ !AWS_ACCESS_KEY_ID ||+ !AWS_SECRET_ACCESS_KEY+) {+ throw new Error(+ "Missing upload configuration. Copy .env.example to .env and configure your bucket, public URL, and credentials.",+ );+}+const publicBase = new URL(`${S3_PUBLIC_URL.replace(/\/$/, "")}/`);+if (+ publicBase.protocol !== "https:" ||+ publicBase.username ||+ publicBase.password ||+ publicBase.search ||+ publicBase.hash+) {+ throw new Error(+ "S3_PUBLIC_URL must be a public HTTPS URL without credentials, a query, or a fragment.",+ );+}+const prefix = process.env.S3_PREFIX ?? "element-previews";+if (!/^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(prefix)) {+ throw new Error(+ "S3_PREFIX must contain slash-separated letters, numbers, underscores, or hyphens.",+ );+}+const manifestPath = path.resolve("elements/previews.json");+const previews: Record<string, { posterUrl: string; videoUrl: string }> =+ JSON.parse(await readFile(manifestPath, "utf8"));+const version = randomUUID();+const uploads: {+ slug: string;+ field: "posterUrl" | "videoUrl";+ bytes: Buffer;+ contentType: string;+ key: string;+ publicUrl: string;+}[] = [];++for (const definition of selected) {+ const { slug } = definition;+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug))+ throw new Error(`Invalid Element slug: ${slug}`);+ const preview = previews[slug];+ if (!preview) throw new Error(`Run render-previews for ${slug} first.`);+ let size = 0;+ for (const field of ["posterUrl", "videoUrl"] as const) {+ const url = preview[field];+ const extension =+ field === "posterUrl"+ ? "png"+ : definition.previewBackground === "transparent"+ ? "webm"+ : "mp4";+ const pattern = new RegExp(+ `^/previews/${slug}/[a-f0-9-]+/preview\\.${extension}$`,+ );+ if (typeof url !== "string" || !pattern.test(url)) {+ throw new Error(+ `Render and review local previews for ${slug} before uploading. Hosted previews are not downloaded or overwritten.`,+ );+ }+ const bytes = await readFile(path.join("public", url));+ const valid =+ extension === "png"+ ? bytes+ .subarray(0, 8)+ .equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))+ : extension === "webm"+ ? bytes.subarray(0, 4).equals(Buffer.from([26, 69, 223, 163]))+ : bytes.subarray(4, 8).toString() === "ftyp";+ if (!valid) throw new Error(`Invalid ${extension} preview: ${url}`);+ size += bytes.length;+ const key = `${prefix}/${slug}/${version}/preview.${extension}`;+ uploads.push({+ slug,+ field,+ bytes,+ key,+ contentType: extension === "png" ? "image/png" : `video/${extension}`,+ publicUrl: new URL(key, publicBase).href,+ });+ }+ if (size > 10 * 1024 * 1024)+ throw new Error(`Previews for ${slug} exceed 10 MiB.`);+}++const client = new S3Client({+ endpoint: S3_ENDPOINT,+ region: process.env.AWS_REGION ?? "auto",+ credentials: {+ accessKeyId: AWS_ACCESS_KEY_ID,+ secretAccessKey: AWS_SECRET_ACCESS_KEY,+ },+});+try {+ for (const asset of uploads) {+ await client.send(+ new PutObjectCommand({+ Bucket: S3_BUCKET,+ Key: asset.key,+ Body: asset.bytes,+ ContentType: asset.contentType,+ CacheControl: "public, max-age=31536000, immutable",+ IfNoneMatch: "*",+ }),+ );+ const response = await fetch(asset.publicUrl, {+ signal: AbortSignal.timeout(30_000),+ });+ if (+ !response.ok ||+ response.headers.get("content-type")?.split(";")[0] !== asset.contentType+ ) {+ throw new Error(+ `Public preview verification failed: ${asset.publicUrl} (${response.status}). The manifest has not been changed.`,+ );+ }+ const remote = Buffer.from(await response.arrayBuffer());+ if (+ createHash("sha256").update(remote).digest("hex") !==+ createHash("sha256").update(asset.bytes).digest("hex")+ ) {+ throw new Error(+ `Uploaded preview checksum mismatch: ${asset.publicUrl}. The manifest has not been changed.`,+ );+ }+ previews[asset.slug][asset.field] = asset.publicUrl;+ console.log(`Verified ${asset.publicUrl}`);+ }+ const temporaryManifest = `${manifestPath}.${version}.tmp`;+ await writeFile(temporaryManifest, `${JSON.stringify(previews, null, 2)}\n`);+ await rename(temporaryManifest, manifestPath);+ console.log(+ "Updated elements/previews.json with verified hosted URLs. Local preview files are kept for review and ignored by Git.",+ );+} finally {+ client.destroy();+}