🎥 Make videos programmatically with React
`@remotion/lambda`: add `deploySiteFromBundle` API to deploy pre-built bundles (#9413)
Igor Samokhovetsc93092596f69
diff --git a/packages/bundler/src/bundle.ts b/packages/bundler/src/bundle.tsindex 526d22ab19..fc2e5faa77 100644--- a/packages/bundler/src/bundle.ts+++ b/packages/bundler/src/bundle.ts@@ -60,6 +60,23 @@ const trimTrailingSlash = (p: string): string => {return p;};+export const getBundlePublicPath = (publicPath: string | null): string => {+ return publicPath ?? './';+};++export const getBundleStaticHash = (publicPath: string): string => {+ if (publicPath === './') {+ return './public';+ }++ return (+ '/' ++ [trimTrailingSlash(trimLeadingSlash(publicPath)), 'public']+ .filter(Boolean)+ .join('/')+ );+};+export type MandatoryLegacyBundleOptions = {webpackOverride: WebpackOverrideFn;outDir: string | null;@@ -331,12 +348,8 @@ export const internalBundle = async (}}- const publicPath = actualArgs?.publicPath ?? '/';- const staticHash =- '/' +- [trimTrailingSlash(trimLeadingSlash(publicPath)), 'public']- .filter(Boolean)- .join('/');+ const publicPath = getBundlePublicPath(actualArgs.publicPath);+ const staticHash = getBundleStaticHash(publicPath);const from = options?.publicDir? path.resolve(resolvedRemotionRoot, options.publicDir)diff --git a/packages/bundler/src/test/relocatable-bundle.test.ts b/packages/bundler/src/test/relocatable-bundle.test.tsnew file mode 100644index 0000000000..4474099e9b--- /dev/null+++ b/packages/bundler/src/test/relocatable-bundle.test.ts@@ -0,0 +1,20 @@+import {expect, test} from 'bun:test';+import {getBundlePublicPath, getBundleStaticHash} from '../bundle';+import {getOutputConfig} from '../shared-bundler-config';++test('defaults bundles to a relocatable public path', () => {+ const publicPath = getBundlePublicPath(null);++ expect(publicPath).toBe('./');+ expect(getBundleStaticHash(publicPath)).toBe('./public');+});++test('preserves explicit absolute public paths', () => {+ expect(getBundlePublicPath('/')).toBe('/');+ expect(getBundleStaticHash('/')).toBe('/public');+ expect(getBundleStaticHash('/sites/alpha/')).toBe('/sites/alpha/public');+});++test('lets Webpack and Rspack derive chunk paths from the bundle script URL', () => {+ expect(getOutputConfig('production')).not.toHaveProperty('publicPath');+});diff --git a/packages/docs/docs/bundle.mdx b/packages/docs/docs/bundle.mdxindex 69efbd388e..80d023eb42 100644--- a/packages/docs/docs/bundle.mdx+++ b/packages/docs/docs/bundle.mdx@@ -82,6 +82,8 @@ Whether to use [Rspack](https://rspack.dev) instead of Webpack as the bundler. D<Options id="public-path" />+From <AvailableFrom v="4.0.497" inline />, the default `./` makes the bundle relocatable. Earlier versions defaulted to `/`. Pass `/` to retain an origin-root URL.+### `rootDir?`<AvailableFrom v="3.1.6" />The directory in which the Remotion project is rooted in. This should be set to the directory that contains the `package.json` which installs Remotion. By default, it is the current working directory.@@ -139,6 +141,8 @@ It is still supported in Remotion v3, but we encourage to migrate to the new funA promise which will resolve into a `string` specifying the output directory.+Pass this directory to [`deploySiteFromBundle()`](/docs/lambda/deploysitefrombundle) to upload it to Remotion Lambda without bundling again.+## See also- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/bundler/src/bundle.ts)@@ -147,3 +151,4 @@ A promise which will resolve into a `string` specifying the output directory.- [renderMedia()](/docs/renderer/render-media)- [stitchFramesToVideo()](/docs/renderer/stitch-frames-to-video)- [Calling bundle() in bundled code](/docs/troubleshooting/bundling-bundle)+- [`deploySiteFromBundle()`](/docs/lambda/deploysitefrombundle)diff --git a/packages/docs/docs/cli/bundle.mdx b/packages/docs/docs/cli/bundle.mdxindex a5ac2b154e..56337d18bb 100644--- a/packages/docs/docs/cli/bundle.mdx+++ b/packages/docs/docs/cli/bundle.mdx@@ -16,6 +16,8 @@ npx remotion bundle <serve-url|entry-file>?You may pass a [Serve URL](/docs/terminology/serve-url) or an [entry point](/docs/terminology/entry-point) as the first argument, otherwise the entry point will be [determined](/docs/terminology/entry-point#which-entry-point-is-being-used).+From <AvailableFrom v="4.0.497" inline />, bundles created by this command are relocatable by default. Upload them to Remotion Lambda using [`deploySiteFromBundle()`](/docs/lambda/deploysitefrombundle).+## Flags### `--config`diff --git a/packages/docs/docs/lambda/deploysite.mdx b/packages/docs/docs/lambda/deploysite.mdxindex 2bf37e61ef..0e5820241c 100644--- a/packages/docs/docs/lambda/deploysite.mdx+++ b/packages/docs/docs/lambda/deploysite.mdx@@ -8,6 +8,8 @@ crumb: 'Lambda API'Takes a Remotion project, bundles it and uploads it to an S3 bucket. Once uploaded, a Lambda function can render any composition in the Remotion project by specifying the URL.+If the project was already bundled in an earlier build step, use [`deploySiteFromBundle()`](/docs/lambda/deploysitefrombundle) to upload it without bundling again.+- If you make changes locally, you need to redeploy the site. You can use [`siteName`](#sitename) to overwrite the previous site.- Note that the Remotion project will be deployed to a subdirectory, not the root of the domain. Therefore you must ensure that if you have specified paths in your Remotion project, they are able to handle this scenario.- Before calling this function, you should create a bucket, see [`getOrCreateBucket()`](/docs/lambda/getorcreatebucket).@@ -157,6 +159,7 @@ From `v3.3.7`, this function is incremental: It only compares the contents of th## See also- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/lambda/src/api/deploy-site.ts)+- [`deploySiteFromBundle()`](/docs/lambda/deploysitefrombundle)- [CLI equivalent: `npx remotion lambda sites create`](/docs/lambda/cli/sites/create)- [getSites()](/docs/lambda/getsites)- [deleteSite()](/docs/lambda/deletesite)diff --git a/packages/docs/docs/lambda/deploysitefrombundle.mdx b/packages/docs/docs/lambda/deploysitefrombundle.mdxnew file mode 100644index 0000000000..83730fc369--- /dev/null+++ b/packages/docs/docs/lambda/deploysitefrombundle.mdx@@ -0,0 +1,178 @@+---+image: /generated/articles-docs-lambda-deploysitefrombundle.png+id: deploysitefrombundle+title: deploySiteFromBundle()+slug: /lambda/deploysitefrombundle+crumb: 'Lambda API'+---++# deploySiteFromBundle()<AvailableFrom v="4.0.497" />++Uploads a local [Remotion Bundle](/docs/terminology/bundle) to an S3 bucket.++Use this API to build an artifact once and deploy it in a later Docker or CI stage. Before calling it, retrieve a bucket using [`getOrCreateBucket()`](/docs/lambda/getorcreatebucket).++## Example++Create the bundle in the default `build` directory:++```bash title="Build step"+npx remotion bundle+```++Deploy that directory later:++```ts twoslash title="deploy.ts"+import {deploySiteFromBundle} from '@remotion/lambda';++const {serveUrl, siteName} = await deploySiteFromBundle({+ bucketName: 'remotionlambda-c7fsl3d',+ region: 'us-east-1',+ bundleDir: './build',+});++console.log(serveUrl, siteName);+```++The bundle directory is read but not modified or deleted.++:::caution+Deploy only trusted artifacts. Symbolic links to files are followed and the target contents are uploaded. Symbolic links to directories are rejected.+:::++The bundle must be relocatable. Bundles created using `npx remotion bundle` from v4.0.497 are relocatable by default.++## Arguments++An object with the following properties:++### `bucketName`++The bucket to which the site is deployed. It must have been created by Remotion Lambda.++### `region`++The AWS region containing the bucket.++### `bundleDir`++The local directory containing the bundle. It must contain `index.html` and `bundle.js` files at its root.++The default output directory of `npx remotion bundle` is `./build`. Pass a different path when the bundle is stored elsewhere:++```ts twoslash title="deploy.ts"+import {deploySiteFromBundle} from '@remotion/lambda';++const {serveUrl} = await deploySiteFromBundle({+ bucketName: 'remotionlambda-c7fsl3d',+ region: 'us-east-1',+ bundleDir: '/custom/artifact',+});+```++If you created the bundle using the [`bundle()`](/docs/bundle) Node.js API without specifying `outDir`, pass its return value as `bundleDir`.++### `siteName?`++The S3 subfolder to deploy to. If omitted, a random name is generated and returned.++If the site already exists, changed files are uploaded and stale files are deleted. Pass [`throwIfSiteExists`](#throwifsiteexists) to reject instead.++Allowed characters: `0-9`, `a-z`, `A-Z`, `-`, `!`, `_`, `.`, `*`, `'`, `(`, `)`.++### `options?`++Deployment callbacks and bucket validation options.++#### `onUploadProgress?`++Called while files are uploaded. The callback receives an object with the following fields.++##### `totalFiles`++The number of files being uploaded.++##### `filesUploaded`++The number of fully uploaded files.++##### `totalSize`++The total number of bytes being uploaded.++##### `sizeUploaded`++The number of bytes uploaded so far.++#### `onDiffingProgress?`++Called while local file hashes are compared with S3. It receives the number of processed bytes and a boolean indicating whether comparison is complete.++#### `bypassBucketNameValidation?`++Allows deploying to a bucket whose name does not start with `remotionlambda-`. Default: `false`.++### `privacy?`++Either `public` or `no-acl`. Default: `public`.++The site must have a public URL because the Lambda browser opens it while rendering.++### `throwIfSiteExists?`++<Options id="throw-if-site-exists" />++### `forcePathStyle?`++Passes `forcePathStyle` to the AWS S3 client. Default: `false`.++### `requestHandler?`++A custom AWS SDK request handler, for example when using a [proxy](/docs/lambda/proxy). Default: `null`.++### `logLevel?`++<Options id="log" />++## Return value++A promise resolving to an object with the following fields:++### `serveUrl`++The Serve URL of the deployed site, for example `https://remotionlambda-12345.s3.eu-central-1.amazonaws.com/sites/abcdef/index.html`.++Use it with [`renderMediaOnLambda()`](/docs/lambda/rendermediaonlambda), [`renderStillOnLambda()`](/docs/lambda/renderstillonlambda), or the Lambda render CLI commands.++### `siteName`++The supplied site name, or the generated random name when `siteName` was omitted.++### `stats`++Statistics about the incremental deployment.++#### `uploadedFiles`++The number of uploaded files.++#### `deletedFiles`++The number of stale S3 files that were deleted.++#### `untouchedFiles`++The number of files that were already identical on S3.++## Compatibility++<CompatibilityTable chrome={false} firefox={false} safari={false} nodejs={true} bun={true} serverlessFunctions={false} clientSideRendering={false} serverSideRendering={false} player={false} studio={false} />++## See also++- [`deploySite()`](/docs/lambda/deploysite)+- [`bundle()`](/docs/bundle)+- [`npx remotion bundle`](/docs/cli/bundle)+- [`getSites()`](/docs/lambda/getsites)+- [`deleteSite()`](/docs/lambda/deletesite)+- [Source code](https://github.com/remotion-dev/remotion/blob/main/packages/lambda/src/api/deploy-site-from-bundle.ts)diff --git a/packages/docs/docs/lambda/table-of-contents.tsx b/packages/docs/docs/lambda/table-of-contents.tsxindex 9bee3e063d..c0a47e4aed 100644--- a/packages/docs/docs/lambda/table-of-contents.tsx+++ b/packages/docs/docs/lambda/table-of-contents.tsx@@ -38,6 +38,10 @@ export const TableOfContents: React.FC = () => {<strong>deploySite()</strong><div>Bundle and upload a site to S3</div></TOCItem>+ <TOCItem link="/docs/lambda/deploysitefrombundle">+ <strong>deploySiteFromBundle()</strong>+ <div>Upload an existing bundle to S3</div>+ </TOCItem><TOCItem link="/docs/lambda/getawsclient"><strong>getAwsClient()</strong><div>Access the AWS SDK directly</div>diff --git a/packages/docs/docs/studio/deploy-static.mdx b/packages/docs/docs/studio/deploy-static.mdxindex 2d298ffad7..752f5907d4 100644--- a/packages/docs/docs/studio/deploy-static.mdx+++ b/packages/docs/docs/studio/deploy-static.mdx@@ -74,7 +74,7 @@ jobs:- name: install packagesrun: npm i- name: Bundle Studio- run: npx remotion bundle --public-path="./"+ run: npx remotion bundle- name: Deploy Studiouses: JamesIves/github-pages-deploy-action@v4with:@@ -84,7 +84,7 @@ jobs:The above code will deploy the bundled Remotion Studio to a branch `gh-pages`.:::note-The --public-path flag for `npx remotion bundle` is available only from remotion version `4.0.127`+Before Remotion v4.0.497, pass `--public-path="./"`. Upgrade to v4.0.497 or newer if the bundle uses files from the `public/` directory at a nested URL.:::<Step>3</Step> Go to the settings of your repository (github.com/[username]/[repo]/settings/pages) <br />diff --git a/packages/docs/docs/troubleshooting/bundling-bundle.mdx b/packages/docs/docs/troubleshooting/bundling-bundle.mdxindex 01f504925f..cf74378a46 100644--- a/packages/docs/docs/troubleshooting/bundling-bundle.mdx+++ b/packages/docs/docs/troubleshooting/bundling-bundle.mdx@@ -42,7 +42,7 @@ See how to parametrize the [content with input props](/docs/passing-props) as we**If you are using a long-running server:** we recommend to call `bundle()` once in a Node.js context and then reusing it for the lifetime of the server. See: [Rendering in Node.js](/docs/ssr-node)-**If you are rendering on Lambda**: Create a bundle and deploy it once either via [`npx remotion sites create`](/docs/lambda/cli/sites/create) or using [`deploySite()`](/docs/lambda/deploysite) in a non-bundled Node.js script and then refer to the bundle via the URL that you get back.+**If you are rendering on Lambda**: Create a bundle during the build step and upload it later using [`deploySiteFromBundle()`](/docs/lambda/deploysitefrombundle). You may also bundle and upload together using [`npx remotion lambda sites create`](/docs/lambda/cli/sites/create) or [`deploySite()`](/docs/lambda/deploysite). Refer to the deployed bundle using the URL returned by the deployment.In both cases, do all parameterization of the video using [input props](/docs/parameterized-rendering).@@ -53,3 +53,4 @@ In both cases, do all parameterization of the video using [input props](/docs/pa- [Parameterized rendering](/docs/parameterized-rendering)- [`bundle()`](/docs/bundle)- [`deploySite()`](/docs/lambda/deploysite)+- [`deploySiteFromBundle()`](/docs/lambda/deploysitefrombundle)diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.tsindex 90bad0e0e6..eb85aaaa93 100644--- a/packages/docs/sidebars.ts+++ b/packages/docs/sidebars.ts@@ -421,6 +421,7 @@ const sidebars: SidebarsConfig = {'lambda/getfunctions','lambda/deletesite','lambda/deploysite',+ 'lambda/deploysitefrombundle','lambda/getawsclient','lambda/getregions','lambda/getsites',diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.tsindex ca4a712854..dd6008b45b 100644--- a/packages/docs/src/data/articles.ts+++ b/packages/docs/src/data/articles.ts@@ -3203,6 +3203,15 @@ export const articles = [noAi: false,slug: 'lambda/deploysite',},+ {+ id: 'deploysitefrombundle',+ title: 'deploySiteFromBundle()',+ relativePath: 'docs/lambda/deploysitefrombundle.mdx',+ compId: 'articles-docs-lambda-deploysitefrombundle',+ crumb: 'Lambda API',+ noAi: false,+ slug: 'lambda/deploysitefrombundle',+ },{id: 'disk-size',title: 'Disk size',diff --git a/packages/docs/static/generated/articles-docs-lambda-deploysitefrombundle.png b/packages/docs/static/generated/articles-docs-lambda-deploysitefrombundle.pngnew file mode 100644index 0000000000..f0362dd5b9Binary files /dev/null and b/packages/docs/static/generated/articles-docs-lambda-deploysitefrombundle.png differdiff --git a/packages/lambda/src/api/deploy-site-from-bundle.ts b/packages/lambda/src/api/deploy-site-from-bundle.tsnew file mode 100644index 0000000000..506558479f--- /dev/null+++ b/packages/lambda/src/api/deploy-site-from-bundle.ts@@ -0,0 +1,101 @@+import type {AwsRegion, RequestHandler} from '@remotion/lambda-client';+import {LambdaClientInternals, type AwsProvider} from '@remotion/lambda-client';+import type {ToOptions} from '@remotion/renderer';+import type {BrowserSafeApis} from '@remotion/renderer/client';+import {wrapWithErrorHandling} from '@remotion/renderer/error-handling';+import type {+ FullClientSpecifics,+ ProviderSpecifics,+} from '@remotion/serverless';+import {awsFullClientSpecifics} from '../functions/full-client-implementation';+import {+ deploySiteWithBundle,+ type DeploySiteOutput,+ type DeploySiteWithBundleOptions,+} from '../shared/deploy-site-with-bundle';+import {validateBundleDir} from '../shared/validate-bundle-dir';++export type DeploySiteFromBundleOutput = DeploySiteOutput;++type MandatoryParameters = {+ bucketName: string;+ region: AwsRegion;+ bundleDir: string;+};++type OptionalParameters = {+ siteName: string;+ options: DeploySiteWithBundleOptions;+ privacy: 'public' | 'no-acl';+ forcePathStyle: boolean;+ requestHandler: RequestHandler | null;+} & ToOptions<typeof BrowserSafeApis.optionsMap.deploySiteLambda>;++export type DeploySiteFromBundleInput = MandatoryParameters &+ Partial<OptionalParameters>;++export type InternalDeploySiteFromBundleInput = MandatoryParameters &+ OptionalParameters & {+ indent: boolean;+ providerSpecifics: ProviderSpecifics<AwsProvider>;+ fullClientSpecifics: FullClientSpecifics<AwsProvider>;+ };++const mandatoryDeploySiteFromBundle = ({+ bucketName,+ bundleDir,+ region,+ siteName,+ options,+ privacy,+ throwIfSiteExists,+ providerSpecifics,+ forcePathStyle,+ fullClientSpecifics,+ requestHandler,+}: InternalDeploySiteFromBundleInput): DeploySiteFromBundleOutput => {+ const resolvedBundleDir = validateBundleDir(bundleDir);++ return deploySiteWithBundle({+ bucketName,+ region,+ siteName,+ options,+ privacy,+ throwIfSiteExists,+ providerSpecifics,+ forcePathStyle,+ fullClientSpecifics,+ requestHandler,+ getBundle: () => Promise.resolve(resolvedBundleDir),+ });+};++export const internalDeploySiteFromBundle: (+ input: InternalDeploySiteFromBundleInput,+) => DeploySiteFromBundleOutput = wrapWithErrorHandling(+ mandatoryDeploySiteFromBundle,+);++/*+ * @description Deploys an existing Remotion bundle to an S3 bucket without bundling it again.+ * @see [Documentation](https://remotion.dev/docs/lambda/deploysitefrombundle)+ */+export const deploySiteFromBundle = (args: DeploySiteFromBundleInput) => {+ return internalDeploySiteFromBundle({+ bucketName: args.bucketName,+ bundleDir: args.bundleDir,+ region: args.region,+ options: args.options ?? {},+ privacy: args.privacy ?? 'public',+ siteName:+ args.siteName ?? LambdaClientInternals.awsImplementation.randomHash(),+ indent: false,+ logLevel: args.logLevel ?? 'info',+ throwIfSiteExists: args.throwIfSiteExists ?? false,+ providerSpecifics: LambdaClientInternals.awsImplementation,+ forcePathStyle: args.forcePathStyle ?? false,+ fullClientSpecifics: awsFullClientSpecifics,+ requestHandler: args.requestHandler ?? null,+ });+};diff --git a/packages/lambda/src/api/deploy-site.ts b/packages/lambda/src/api/deploy-site.tsindex 9bede8b472..d7bc33095d 100644--- a/packages/lambda/src/api/deploy-site.ts+++ b/packages/lambda/src/api/deploy-site.ts@@ -2,10 +2,7 @@ import fs from 'node:fs';import {type GitSource, type WebpackOverrideFn} from '@remotion/bundler';import type {AwsRegion, RequestHandler} from '@remotion/lambda-client';import {LambdaClientInternals, type AwsProvider} from '@remotion/lambda-client';-import {- getSitesKey,- REMOTION_BUCKET_PREFIX,-} from '@remotion/lambda-client/constants';+import {getSitesKey} from '@remotion/lambda-client/constants';import type {ToOptions} from '@remotion/renderer';import type {BrowserSafeApis} from '@remotion/renderer/client';import {wrapWithErrorHandling} from '@remotion/renderer/error-handling';@@ -14,10 +11,13 @@ import type {ProviderSpecifics,UploadDirProgress,} from '@remotion/serverless';-import {validateBucketName, validatePrivacy} from '@remotion/serverless';import {awsFullClientSpecifics} from '../functions/full-client-implementation';-import {getS3DiffOperations} from '../shared/get-s3-operations';-import {validateSiteName} from '../shared/validate-site-name';+import {+ deploySiteWithBundle,+ type DeploySiteOutput,+} from '../shared/deploy-site-with-bundle';++export type {DeploySiteOutput};type MandatoryParameters = {entryPoint: string;@@ -51,16 +51,6 @@ type OptionalParameters = {export type DeploySiteInput = MandatoryParameters & Partial<OptionalParameters>;-export type DeploySiteOutput = Promise<{- serveUrl: string;- siteName: string;- stats: {- uploadedFiles: number;- deletedFiles: number;- untouchedFiles: number;- };-}>;-const mandatoryDeploySite = async ({bucketName,entryPoint,@@ -79,141 +69,56 @@ const mandatoryDeploySite = async ({providerSpecifics: ProviderSpecifics<AwsProvider>;fullClientSpecifics: FullClientSpecifics<AwsProvider>;}): DeploySiteOutput => {- LambdaClientInternals.validateAwsRegion(region);- validateBucketName({- bucketName,- bucketNamePrefix: REMOTION_BUCKET_PREFIX,- options: {- mustStartWithRemotion: !options?.bypassBucketNameValidation,- },- });-- validateSiteName(siteName);- validatePrivacy(privacy, false);-- const accountId = await providerSpecifics.getAccountId({region});+ let generatedBundleDir: string | null = null;- const bucketExists = await providerSpecifics.bucketExists({+ const result = await deploySiteWithBundle({bucketName,region,- expectedBucketOwner: accountId,+ siteName,+ options,+ privacy,+ throwIfSiteExists,+ providerSpecifics,forcePathStyle,+ fullClientSpecifics,requestHandler,- });- if (!bucketExists) {- throw new Error(`No bucket with the name ${bucketName} exists`);- }-- const subFolder = getSitesKey(siteName);-- const [files, bundled] = await Promise.all([- providerSpecifics.listObjects({- bucketName,- expectedBucketOwner: accountId,- region,- // The `/` is important to not accidentially delete sites with the same name but containing a suffix.- prefix: `${subFolder}/`,- forcePathStyle,- requestHandler,- }),- fullClientSpecifics.bundleSite({- publicPath: `/${subFolder}/`,- webpackOverride: options?.webpackOverride ?? ((f) => f),- enableCaching: options?.enableCaching ?? true,- publicDir: options?.publicDir ?? null,- rootDir: options?.rootDir ?? null,- ignoreRegisterRootWarning: options?.ignoreRegisterRootWarning ?? false,- onProgress: options?.onBundleProgress ?? (() => undefined),- entryPoint,- gitSource,- bufferStateDelayInMilliseconds: null,- maxTimelineTracks: null,- onDirectoryCreated: () => undefined,- onPublicDirCopyProgress: () => undefined,- onSymlinkDetected: () => undefined,- outDir: null,- askAIEnabled: options?.askAIEnabled ?? true,- interactivityEnabled: options?.interactivityEnabled ?? true,- audioLatencyHint: null,- keyboardShortcutsEnabled: options?.keyboardShortcutsEnabled ?? true,- renderDefaults: null,- rspack: options?.rspack ?? false,- symlinkPublicDir: false,- }),- ]);-- if (throwIfSiteExists && files.length > 0) {- throw new Error(- '`throwIfSiteExists` was passed as true, but there are already files in this folder: ' +- files- .slice(0, 5)- .map((f) => f.Key)- .join(', '),- );- }-- options.onDiffingProgress?.(0, false);-- let totalBytes = 0;-- const {toDelete, toUpload, existingCount} = await getS3DiffOperations({- objects: files,- bundle: bundled,- prefix: subFolder,- onProgress: (bytes) => {- totalBytes = bytes;- options.onDiffingProgress?.(bytes, false);+ getBundle: async () => {+ generatedBundleDir = await fullClientSpecifics.bundleSite({+ publicPath: `/${getSitesKey(siteName)}/`,+ webpackOverride: options.webpackOverride ?? ((f) => f),+ enableCaching: options.enableCaching ?? true,+ publicDir: options.publicDir ?? null,+ rootDir: options.rootDir ?? null,+ ignoreRegisterRootWarning: options.ignoreRegisterRootWarning ?? false,+ onProgress: options.onBundleProgress ?? (() => undefined),+ entryPoint,+ gitSource,+ bufferStateDelayInMilliseconds: null,+ maxTimelineTracks: null,+ onDirectoryCreated: () => undefined,+ onPublicDirCopyProgress: () => undefined,+ onSymlinkDetected: () => undefined,+ outDir: null,+ askAIEnabled: options.askAIEnabled ?? true,+ interactivityEnabled: options.interactivityEnabled ?? true,+ audioLatencyHint: null,+ keyboardShortcutsEnabled: options.keyboardShortcutsEnabled ?? true,+ renderDefaults: null,+ rspack: options.rspack ?? false,+ symlinkPublicDir: false,+ });++ return generatedBundleDir;},- fullClientSpecifics,});- options.onDiffingProgress?.(totalBytes, true);-- await Promise.all([- fullClientSpecifics.uploadDir({- bucket: bucketName,- region,- localDir: bundled,- onProgress: options?.onUploadProgress ?? (() => undefined),- keyPrefix: subFolder,- privacy: privacy ?? 'public',- toUpload,- forcePathStyle,- requestHandler,- }),- Promise.all(- toDelete.map((d) => {- return providerSpecifics.deleteFile({- bucketName,- customCredentials: null,- key: d.Key as string,- region,- forcePathStyle,- requestHandler,- });- }),- ),- ]);-- if (fs.existsSync(bundled)) {- fs.rmSync(bundled, {+ if (generatedBundleDir && fs.existsSync(generatedBundleDir)) {+ fs.rmSync(generatedBundleDir, {recursive: true,});}- return {- serveUrl: LambdaClientInternals.makeS3ServeUrl({- bucketName,- subFolder,- region,- }),- siteName,- stats: {- uploadedFiles: toUpload.length,- deletedFiles: toDelete.length,- untouchedFiles: existingCount,- },- };+ return result;};export type InternalDeploySiteInput = MandatoryParameters &@@ -227,8 +132,8 @@ export const internalDeploySite: () => DeploySiteOutput = wrapWithErrorHandling(mandatoryDeploySite);/*- * @description Deploys a Remotion project to a GCP storage bucket to prepare it for rendering on Cloud Run.- * @see [Documentation](https://remotion.dev/docs/cloudrun/deploysite)+ * @description Bundles a Remotion project and deploys it to an S3 bucket for rendering on AWS Lambda.+ * @see [Documentation](https://remotion.dev/docs/lambda/deploysite)*/export const deploySite = (args: DeploySiteInput) => {return internalDeploySite({diff --git a/packages/lambda/src/index.ts b/packages/lambda/src/index.tsindex c5d9b7850a..b20debd924 100644--- a/packages/lambda/src/index.ts+++ b/packages/lambda/src/index.ts@@ -47,6 +47,11 @@ import type {import {deployFunction} from './api/deploy-function';import type {DeploySiteInput, DeploySiteOutput} from './api/deploy-site';import {deploySite} from './api/deploy-site';+import type {+ DeploySiteFromBundleInput,+ DeploySiteFromBundleOutput,+} from './api/deploy-site-from-bundle';+import {deploySiteFromBundle} from './api/deploy-site-from-bundle';import type {DownloadMediaInput,DownloadMediaOutput,@@ -133,6 +138,7 @@ export {deleteSite,deployFunction,deploySite,+ deploySiteFromBundle,downloadMedia,estimatePrice,getAwsClient,@@ -162,6 +168,8 @@ export type {DeleteSiteOutput,DeployFunctionInput,DeployFunctionOutput,+ DeploySiteFromBundleInput,+ DeploySiteFromBundleOutput,DeploySiteInput,DeploySiteOutput,DownloadMediaInput,diff --git a/packages/lambda/src/shared/deploy-site-with-bundle.ts b/packages/lambda/src/shared/deploy-site-with-bundle.tsnew file mode 100644index 0000000000..f1151b9e11--- /dev/null+++ b/packages/lambda/src/shared/deploy-site-with-bundle.ts@@ -0,0 +1,167 @@+import type {AwsRegion, RequestHandler} from '@remotion/lambda-client';+import {LambdaClientInternals, type AwsProvider} from '@remotion/lambda-client';+import {+ getSitesKey,+ REMOTION_BUCKET_PREFIX,+} from '@remotion/lambda-client/constants';+import type {+ FullClientSpecifics,+ ProviderSpecifics,+ UploadDirProgress,+} from '@remotion/serverless';+import {validateBucketName, validatePrivacy} from '@remotion/serverless';+import {getS3DiffOperations} from './get-s3-operations';+import {validateSiteName} from './validate-site-name';++export type DeploySiteOutput = Promise<{+ serveUrl: string;+ siteName: string;+ stats: {+ uploadedFiles: number;+ deletedFiles: number;+ untouchedFiles: number;+ };+}>;++export type DeploySiteWithBundleOptions = {+ onUploadProgress?: (upload: UploadDirProgress) => void;+ onDiffingProgress?: (bytes: number, done: boolean) => void;+ bypassBucketNameValidation?: boolean;+};++export type DeploySiteWithBundleInput = {+ bucketName: string;+ region: AwsRegion;+ siteName: string;+ options: DeploySiteWithBundleOptions;+ privacy: 'public' | 'no-acl';+ throwIfSiteExists: boolean;+ providerSpecifics: ProviderSpecifics<AwsProvider>;+ forcePathStyle: boolean;+ fullClientSpecifics: FullClientSpecifics<AwsProvider>;+ requestHandler: RequestHandler | null;+ getBundle: () => Promise<string>;+};++export const deploySiteWithBundle: (+ input: DeploySiteWithBundleInput,+) => DeploySiteOutput = async ({+ bucketName,+ region,+ siteName,+ options,+ privacy,+ throwIfSiteExists,+ providerSpecifics,+ forcePathStyle,+ fullClientSpecifics,+ requestHandler,+ getBundle,+}) => {+ LambdaClientInternals.validateAwsRegion(region);+ validateBucketName({+ bucketName,+ bucketNamePrefix: REMOTION_BUCKET_PREFIX,+ options: {+ mustStartWithRemotion: !options.bypassBucketNameValidation,+ },+ });++ validateSiteName(siteName);+ validatePrivacy(privacy, false);++ const accountId = await providerSpecifics.getAccountId({region});++ const bucketExists = await providerSpecifics.bucketExists({+ bucketName,+ region,+ expectedBucketOwner: accountId,+ forcePathStyle,+ requestHandler,+ });+ if (!bucketExists) {+ throw new Error(`No bucket with the name ${bucketName} exists`);+ }++ const subFolder = getSitesKey(siteName);++ const [files, bundleDir] = await Promise.all([+ providerSpecifics.listObjects({+ bucketName,+ expectedBucketOwner: accountId,+ region,+ // The `/` is important to not accidentally delete sites with the same name but containing a suffix.+ prefix: `${subFolder}/`,+ forcePathStyle,+ requestHandler,+ }),+ getBundle(),+ ]);++ if (throwIfSiteExists && files.length > 0) {+ throw new Error(+ '`throwIfSiteExists` was passed as true, but there are already files in this folder: ' ++ files+ .slice(0, 5)+ .map((f) => f.Key)+ .join(', '),+ );+ }++ options.onDiffingProgress?.(0, false);++ let totalBytes = 0;++ const {toDelete, toUpload, existingCount} = await getS3DiffOperations({+ objects: files,+ bundle: bundleDir,+ prefix: subFolder,+ onProgress: (bytes) => {+ totalBytes = bytes;+ options.onDiffingProgress?.(bytes, false);+ },+ fullClientSpecifics,+ });++ options.onDiffingProgress?.(totalBytes, true);++ await Promise.all([+ fullClientSpecifics.uploadDir({+ bucket: bucketName,+ region,+ localDir: bundleDir,+ onProgress: options.onUploadProgress ?? (() => undefined),+ keyPrefix: subFolder,+ privacy,+ toUpload,+ forcePathStyle,+ requestHandler,+ }),+ Promise.all(+ toDelete.map((d) => {+ return providerSpecifics.deleteFile({+ bucketName,+ customCredentials: null,+ key: d.Key as string,+ region,+ forcePathStyle,+ requestHandler,+ });+ }),+ ),+ ]);++ return {+ serveUrl: LambdaClientInternals.makeS3ServeUrl({+ bucketName,+ subFolder,+ region,+ }),+ siteName,+ stats: {+ uploadedFiles: toUpload.length,+ deletedFiles: toDelete.length,+ untouchedFiles: existingCount,+ },+ };+};diff --git a/packages/lambda/src/shared/validate-bundle-dir.ts b/packages/lambda/src/shared/validate-bundle-dir.tsnew file mode 100644index 0000000000..db95b76dd7--- /dev/null+++ b/packages/lambda/src/shared/validate-bundle-dir.ts@@ -0,0 +1,94 @@+import fs from 'node:fs';+import path from 'node:path';++const getPublicPath = (indexHtml: string): unknown => {+ const match = indexHtml.match(+ /window\.remotion_publicPath\s*=\s*("(?:[^"\\]|\\.)*")\s*;/,+ );++ if (!match) {+ return null;+ }++ try {+ return JSON.parse(match[1]);+ } catch (error) {+ throw new Error(+ 'Could not parse `window.remotion_publicPath` in the bundle index.html.',+ {cause: error},+ );+ }+};++const validateNoDirectorySymlinks = (+ directory: string,+ bundleDir: string,+): void => {+ for (const entry of fs.readdirSync(directory, {withFileTypes: true})) {+ const entryPath = path.join(directory, entry.name);+ if (entry.isSymbolicLink()) {+ if (fs.statSync(entryPath).isDirectory()) {+ throw new Error(+ `The bundle directory ${bundleDir} contains a symbolic link to a directory at ${path.relative(bundleDir, entryPath)}. Directory symbolic links are not supported by \`deploySiteFromBundle()\`.`,+ );+ }++ continue;+ }++ if (entry.isDirectory()) {+ validateNoDirectorySymlinks(entryPath, bundleDir);+ }+ }+};++export const validateBundleDir = (bundleDir: unknown): string => {+ if (typeof bundleDir !== 'string') {+ throw new TypeError(+ `The \`bundleDir\` must be a string, but received ${JSON.stringify(bundleDir)}.`,+ );+ }++ const resolvedBundleDir = path.resolve(bundleDir);++ if (!fs.existsSync(resolvedBundleDir)) {+ throw new Error(+ `The bundle directory ${resolvedBundleDir} does not exist. Run \`npx remotion bundle\` or pass a valid \`bundleDir\`.`,+ );+ }++ if (!fs.statSync(resolvedBundleDir).isDirectory()) {+ throw new Error(+ `The bundle path ${resolvedBundleDir} is not a directory. Pass the directory returned by \`bundle()\` or created by \`npx remotion bundle\`.`,+ );+ }++ const indexHtmlPath = path.join(resolvedBundleDir, 'index.html');+ if (!fs.existsSync(indexHtmlPath) || !fs.statSync(indexHtmlPath).isFile()) {+ throw new Error(+ `The bundle directory ${resolvedBundleDir} does not contain an index.html file at its root.`,+ );+ }++ const bundleScriptPath = path.join(resolvedBundleDir, 'bundle.js');+ if (+ !fs.existsSync(bundleScriptPath) ||+ !fs.statSync(bundleScriptPath).isFile()+ ) {+ throw new Error(+ `The bundle directory ${resolvedBundleDir} does not contain a bundle.js file at its root.`,+ );+ }++ const indexHtml = fs.readFileSync(indexHtmlPath, 'utf8');+ const publicPath = getPublicPath(indexHtml);+ if (publicPath !== './') {+ throw new Error(+ `The bundle at ${resolvedBundleDir} is not relocatable. Rebuild it using Remotion v4.0.497 or newer.`,+ );+ }++ validateNoDirectorySymlinks(resolvedBundleDir, resolvedBundleDir);++ return resolvedBundleDir;+};diff --git a/packages/lambda/src/test/integration/deploy-site-from-bundle.test.ts b/packages/lambda/src/test/integration/deploy-site-from-bundle.test.tsnew file mode 100644index 0000000000..a02c3c1734--- /dev/null+++ b/packages/lambda/src/test/integration/deploy-site-from-bundle.test.ts@@ -0,0 +1,380 @@+import {afterEach, expect, test} from 'bun:test';+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import {internalGetOrCreateBucket} from '@remotion/serverless';+import {VERSION} from 'remotion/version';+import {internalDeploySiteFromBundle} from '../../api/deploy-site-from-bundle';+import {mockFullClientSpecifics} from '../mock-implementation';+import {mockImplementation} from '../mocks/mock-implementation';+import {resetMockStore} from '../mocks/mock-store';++const temporaryDirectories: string[] = [];++const relocatableIndexHtml = `<!DOCTYPE html>+<html>+<head></head>+<body>+<script>window.remotion_publicPath = "./";</script>+<script>window.siteVersion = '11'; window.remotion_version = '${VERSION}';</script>+</body>+</html>`;++const makeBundle = (files: Record<string, string>) => {+ const bundleDir = mkdtempSync(+ path.join(os.tmpdir(), 'remotion-bundle-test-'),+ );+ temporaryDirectories.push(bundleDir);+ writeFileSync(path.join(bundleDir, 'index.html'), relocatableIndexHtml);++ for (const [file, contents] of Object.entries(files)) {+ const filePath = path.join(bundleDir, file);+ mkdirSync(path.dirname(filePath), {recursive: true});+ writeFileSync(filePath, contents);+ }++ return bundleDir;+};++const makeBucket = async () => {+ const {bucketName} = await internalGetOrCreateBucket({+ region: 'ap-northeast-1',+ providerSpecifics: mockImplementation,+ customCredentials: null,+ enableFolderExpiry: false,+ forcePathStyle: false,+ skipPutAcl: false,+ requestHandler: null,+ logLevel: 'error',+ });++ return bucketName;+};++const deployBundle = ({+ bucketName,+ bundleDir,+ siteName,+ throwIfSiteExists = false,+ providerSpecifics = mockImplementation,+ fullClientSpecifics = mockFullClientSpecifics,+}: {+ bucketName: string;+ bundleDir: string;+ siteName: string;+ throwIfSiteExists?: boolean;+ providerSpecifics?: typeof mockImplementation;+ fullClientSpecifics?: typeof mockFullClientSpecifics;+}) => {+ return internalDeploySiteFromBundle({+ bucketName,+ bundleDir,+ region: 'ap-northeast-1',+ siteName,+ providerSpecifics,+ indent: false,+ logLevel: 'error',+ options: {},+ privacy: 'public',+ throwIfSiteExists,+ forcePathStyle: false,+ fullClientSpecifics,+ requestHandler: null,+ });+};++afterEach(() => {+ for (const directory of temporaryDirectories.splice(0)) {+ rmSync(directory, {recursive: true, force: true});+ }++ resetMockStore();+});++test('deploys a caller-owned bundle without invoking the bundler', async () => {+ const bundleDir = makeBundle({+ 'bundle.js': 'console.log("bundle")',+ 'assets/chunk.js': 'console.log("chunk")',+ });+ const bundleBefore = readFileSync(path.join(bundleDir, 'index.html'));+ const bucketName = await makeBucket();++ const fullClientSpecifics = {+ ...mockFullClientSpecifics,+ bundleSite: () => {+ throw new Error('The bundler must not be called');+ },+ };++ const result = await deployBundle({+ bucketName,+ bundleDir,+ siteName: 'from-bundle-basic',+ fullClientSpecifics,+ });++ expect(result).toEqual({+ serveUrl:+ 'https://remotionlambda-apnortheast1-abcdef.s3.ap-northeast-1.amazonaws.com/sites/from-bundle-basic/index.html',+ siteName: 'from-bundle-basic',+ stats: {+ deletedFiles: 0,+ untouchedFiles: 0,+ uploadedFiles: 3,+ },+ });+ expect(existsSync(bundleDir)).toBe(true);+ expect(readFileSync(path.join(bundleDir, 'index.html'))).toEqual(+ bundleBefore,+ );++ const files = await mockImplementation.listObjects({+ bucketName,+ expectedBucketOwner: null,+ prefix: 'sites/from-bundle-basic/',+ region: 'ap-northeast-1',+ continuationToken: undefined,+ forcePathStyle: false,+ requestHandler: null,+ });+ expect(files.map((file) => file.Key).sort()).toEqual([+ 'sites/from-bundle-basic/assets/chunk.js',+ 'sites/from-bundle-basic/bundle.js',+ 'sites/from-bundle-basic/index.html',+ ]);+});++test('incrementally uploads and deletes files without deleting either bundle', async () => {+ const firstBundle = makeBundle({+ 'bundle.js': 'first',+ 'stale.js': 'stale',+ });+ const secondBundle = makeBundle({+ 'bundle.js': 'second',+ 'new.js': 'new',+ });+ const bucketName = await makeBucket();++ await deployBundle({+ bucketName,+ bundleDir: firstBundle,+ siteName: 'from-bundle-incremental',+ });+ const result = await deployBundle({+ bucketName,+ bundleDir: secondBundle,+ siteName: 'from-bundle-incremental',+ });++ expect(result.stats).toEqual({+ deletedFiles: 1,+ untouchedFiles: 2,+ uploadedFiles: 1,+ });+ expect(existsSync(firstBundle)).toBe(true);+ expect(existsSync(secondBundle)).toBe(true);++ const files = await mockImplementation.listObjects({+ bucketName,+ expectedBucketOwner: null,+ prefix: 'sites/from-bundle-incremental/',+ region: 'ap-northeast-1',+ continuationToken: undefined,+ forcePathStyle: false,+ requestHandler: null,+ });+ expect(files.map((file) => file.Key).sort()).toEqual([+ 'sites/from-bundle-incremental/bundle.js',+ 'sites/from-bundle-incremental/index.html',+ 'sites/from-bundle-incremental/new.js',+ ]);+});++test('keeps the caller bundle when deployment fails', async () => {+ const bundleDir = makeBundle({'bundle.js': 'bundle'});+ const bucketName = await makeBucket();+ const fullClientSpecifics = {+ ...mockFullClientSpecifics,+ uploadDir: () => Promise.reject(new Error('Upload failed')),+ };++ await expect(+ deployBundle({+ bucketName,+ bundleDir,+ siteName: 'from-bundle-failure',+ fullClientSpecifics,+ }),+ ).rejects.toThrow('Upload failed');+ expect(existsSync(bundleDir)).toBe(true);+});++test('supports throwIfSiteExists without deleting the caller bundle', async () => {+ const firstBundle = makeBundle({'bundle.js': 'first'});+ const secondBundle = makeBundle({'bundle.js': 'second'});+ const bucketName = await makeBucket();++ await deployBundle({+ bucketName,+ bundleDir: firstBundle,+ siteName: 'from-bundle-existing',+ });+ await expect(+ deployBundle({+ bucketName,+ bundleDir: secondBundle,+ siteName: 'from-bundle-existing',+ throwIfSiteExists: true,+ }),+ ).rejects.toThrow('there are already files in this folder');+ expect(existsSync(secondBundle)).toBe(true);+});++test('validates the local bundle before making an AWS request', async () => {+ let awsCalls = 0;+ const providerSpecifics: typeof mockImplementation = {+ ...mockImplementation,+ getAccountId: () => {+ awsCalls++;+ return Promise.resolve('123456789');+ },+ };+ const missingPathParent = mkdtempSync(+ path.join(os.tmpdir(), 'missing-remotion-bundle-test-'),+ );+ temporaryDirectories.push(missingPathParent);+ const missingPath = path.join(missingPathParent, 'missing');++ await expect(+ deployBundle({+ bucketName: 'remotionlambda-testing',+ bundleDir: missingPath,+ siteName: 'from-bundle-validation',+ providerSpecifics,+ }),+ ).rejects.toThrow('does not exist');+ expect(awsCalls).toBe(0);++ const filePath = path.join(+ mkdtempSync(path.join(os.tmpdir(), 'remotion-bundle-file-test-')),+ 'bundle',+ );+ temporaryDirectories.push(path.dirname(filePath));+ writeFileSync(filePath, 'not a directory');+ await expect(+ deployBundle({+ bucketName: 'remotionlambda-testing',+ bundleDir: filePath,+ siteName: 'from-bundle-validation',+ providerSpecifics,+ }),+ ).rejects.toThrow('is not a directory');++ const withoutIndex = makeBundle({});+ rmSync(path.join(withoutIndex, 'index.html'));+ await expect(+ deployBundle({+ bucketName: 'remotionlambda-testing',+ bundleDir: withoutIndex,+ siteName: 'from-bundle-validation',+ providerSpecifics,+ }),+ ).rejects.toThrow('does not contain an index.html');++ const withoutBundleScript = makeBundle({});+ await expect(+ deployBundle({+ bucketName: 'remotionlambda-testing',+ bundleDir: withoutBundleScript,+ siteName: 'from-bundle-validation',+ providerSpecifics,+ }),+ ).rejects.toThrow('does not contain a bundle.js');++ const incompatible = makeBundle({'bundle.js': 'bundle'});+ writeFileSync(+ path.join(incompatible, 'index.html'),+ '<script>window.remotion_publicPath = "/";</script>',+ );+ await expect(+ deployBundle({+ bucketName: 'remotionlambda-testing',+ bundleDir: incompatible,+ siteName: 'from-bundle-validation',+ providerSpecifics,+ }),+ ).rejects.toThrow('is not relocatable');++ const malformedPublicPath = makeBundle({'bundle.js': 'bundle'});+ writeFileSync(+ path.join(malformedPublicPath, 'index.html'),+ '<script>window.remotion_publicPath = "\\x";</script>',+ );+ await expect(+ deployBundle({+ bucketName: 'remotionlambda-testing',+ bundleDir: malformedPublicPath,+ siteName: 'from-bundle-validation',+ providerSpecifics,+ }),+ ).rejects.toMatchObject({+ message: expect.stringContaining(+ 'Could not parse `window.remotion_publicPath`',+ ),+ cause: expect.any(SyntaxError),+ });+ expect(awsCalls).toBe(0);+});++if (process.platform !== 'win32') {+ test('uploads file symlinks and rejects directory symlinks before AWS requests', async () => {+ const externalDirectory = mkdtempSync(+ path.join(os.tmpdir(), 'remotion-symlink-target-test-'),+ );+ temporaryDirectories.push(externalDirectory);+ const externalFile = path.join(externalDirectory, 'target.txt');+ writeFileSync(externalFile, 'linked contents');++ const fileLinkBundle = makeBundle({'bundle.js': 'bundle'});+ symlinkSync(externalFile, path.join(fileLinkBundle, 'linked.txt'));+ const bucketName = await makeBucket();+ const result = await deployBundle({+ bucketName,+ bundleDir: fileLinkBundle,+ siteName: 'from-bundle-file-link',+ });+ expect(result.stats.uploadedFiles).toBe(3);++ const directoryLinkBundle = makeBundle({'bundle.js': 'bundle'});+ symlinkSync(+ externalDirectory,+ path.join(directoryLinkBundle, 'linked-directory'),+ 'dir',+ );+ let awsCalls = 0;+ const providerSpecifics: typeof mockImplementation = {+ ...mockImplementation,+ getAccountId: () => {+ awsCalls++;+ return Promise.resolve('123456789');+ },+ };+ await expect(+ deployBundle({+ bucketName,+ bundleDir: directoryLinkBundle,+ siteName: 'from-bundle-directory-link',+ providerSpecifics,+ }),+ ).rejects.toThrow('symbolic link to a directory');+ expect(awsCalls).toBe(0);+ });+}diff --git a/packages/lambda/src/test/integration/deploy-site.test.ts b/packages/lambda/src/test/integration/deploy-site.test.tsindex 7078eee718..c3f3a49605 100644--- a/packages/lambda/src/test/integration/deploy-site.test.ts+++ b/packages/lambda/src/test/integration/deploy-site.test.ts@@ -377,16 +377,20 @@ test('Should not delete site with same prefix', async () => {requestHandler: null,});expect(- files.map((f) => {- return f.Key;- }),- ).toEqual([- // Should not delete my-site-staging (same bucket name but with suffix)- ...getDirFiles('/path/to/bundle-2').map((f) => {- return 'sites/my-site-staging/' + f.name;- }),- ...getDirFiles('/path/to/bundle-1').map((f) => {- return 'sites/my-site/' + f.name;- }),- ]);+ files+ .map((f) => {+ return f.Key;+ })+ .sort(),+ ).toEqual(+ [+ // Should not delete my-site-staging (same bucket name but with suffix)+ ...getDirFiles('/path/to/bundle-2').map((f) => {+ return 'sites/my-site-staging/' + f.name;+ }),+ ...getDirFiles('/path/to/bundle-1').map((f) => {+ return 'sites/my-site/' + f.name;+ }),+ ].sort(),+ );});diff --git a/packages/lambda/src/test/mocks/upload-dir.ts b/packages/lambda/src/test/mocks/upload-dir.tsindex 06839bbe57..d2a7dbfb49 100644--- a/packages/lambda/src/test/mocks/upload-dir.ts+++ b/packages/lambda/src/test/mocks/upload-dir.ts@@ -1,3 +1,5 @@+import {existsSync, readdirSync, readFileSync} from 'node:fs';+import path from 'node:path';import {VERSION} from 'remotion/version';import type {MockFile, uploadDir as original} from '../../api/upload-dir';import {writeMockS3File} from './mock-store';@@ -6,6 +8,7 @@ const mockIndexHtml = `<!DOCTYPE html><html lang="en"><head><title>Test</title></head><body>+<script>window.remotion_publicPath = "./";</script><script>window.siteVersion = '11';window.remotion_version = '${VERSION}';@@ -13,6 +16,22 @@ const mockIndexHtml = `<!DOCTYPE html></body></html>`;+const getRealDirFiles = (dir: string, rootDir: string): MockFile[] => {+ return readdirSync(dir, {withFileTypes: true}).flatMap((entry) => {+ const absolutePath = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ return getRealDirFiles(absolutePath, rootDir);+ }++ return [+ {+ name: path.relative(rootDir, absolutePath).split(path.sep).join('/'),+ content: readFileSync(absolutePath, 'utf8'),+ },+ ];+ });+};+export const getDirFiles = (dir: string): MockFile[] => {if (dir === '/path/to/bundle-1') {return [@@ -48,11 +67,17 @@ export const getDirFiles = (dir: string): MockFile[] => {];}+ if (existsSync(dir)) {+ return getRealDirFiles(dir, dir);+ }+throw new Error('could not get dir for ' + dir);};export const mockUploadDir: typeof original = async (input) => {- const files = getDirFiles(input.localDir);+ const files = getDirFiles(input.localDir).filter((file) =>+ input.toUpload.includes(file.name),+ );for (const file of files) {await writeMockS3File({privacy: input.privacy,diff --git a/packages/renderer/src/options/public-path.tsx b/packages/renderer/src/options/public-path.tsxindex 744b6e3e58..3765e7c8f5 100644--- a/packages/renderer/src/options/public-path.tsx+++ b/packages/renderer/src/options/public-path.tsx@@ -11,10 +11,9 @@ export const publicPathOption = {return (<>The path of the URL where the bundle is going to be hosted. By default- it is <code>/</code>, meaning that the bundle is going to be hosted at- the root of the domain (e.g. <code>https://localhost:3000/</code>). If- you are deploying to a subdirectory (e.g. <code>/sites/my-site/</code>),- you should set this to the subdirectory.+ it is <code>./</code>, making the bundle relocatable. Set an absolute+ path such as <code>/sites/my-site/</code> to host the bundle at a fixed+ location.</>);},diff --git a/packages/studio-shared/src/studio-html.ts b/packages/studio-shared/src/studio-html.tsindex f21704c409..303327920f 100644--- a/packages/studio-shared/src/studio-html.ts+++ b/packages/studio-shared/src/studio-html.ts@@ -65,6 +65,17 @@ export const studioHtml = ({studioRuntimeConfig,}: StudioHtmlOptions) => {const scriptUrl = bundleScriptUrl ?? `${publicPath}bundle.js`;+ const isRelativeBundle = mode === 'bundle' && publicPath === './';+ const staticBaseValue = isRelativeBundle+ ? `new URL(${JSON.stringify(staticHash)}, window.location.href).pathname`+ : JSON.stringify(staticHash);+ const staticFilesValue = isRelativeBundle+ ? `${JSON.stringify(publicFiles)}.map((file) => ({...file, src: new URL(file.src, window.location.href).pathname}))`+ : JSON.stringify(publicFiles);+ const publicFolderExistsValue =+ isRelativeBundle && publicFolderExists+ ? `new URL(${JSON.stringify(publicFolderExists)}, window.location.href).pathname`+ : JSON.stringify(publicFolderExists);return `<!DOCTYPE html>@@ -85,7 +96,7 @@ export const studioHtml = ({<script>window.remotion_sampleRate = ${sampleRate};</script><script>window.remotion_previewSampleRate = ${sampleRate};</script>${mode === 'dev' ? `<script>window.remotion_logLevel = "${logLevel}";</script>` : ''}- <script>window.remotion_staticBase = "${staticHash}";</script>+ <script>window.remotion_staticBase = ${staticBaseValue};</script>${editorName? `<script>window.remotion_editorName = "${editorName}";</script>`@@ -148,10 +159,10 @@ export const studioHtml = ({<script>window.remotion_isReadOnlyStudio = ${readOnlyStudio ? 'true' : 'false'};</script>`.trimStart(): ''}- <script>window.remotion_staticFiles = ${JSON.stringify(publicFiles)}</script>+ <script>window.remotion_staticFiles = ${staticFilesValue}</script><script>window.remotion_installedPackages = ${JSON.stringify(installedDependencies)}</script><script>window.remotion_packageManager = ${JSON.stringify(packageManager)}</script>- <script>window.remotion_publicFolderExists = ${JSON.stringify(publicFolderExists)};</script>+ <script>window.remotion_publicFolderExists = ${publicFolderExistsValue};</script><script>// Increment this value when the generated bundle format or behavior changes// in a backwards-incompatible way. It is not the Remotion package versiondiff --git a/packages/studio-shared/src/test/studio-html.test.ts b/packages/studio-shared/src/test/studio-html.test.tsnew file mode 100644index 0000000000..2d3f9c0f00--- /dev/null+++ b/packages/studio-shared/src/test/studio-html.test.ts@@ -0,0 +1,85 @@+import {expect, test} from 'bun:test';+import {studioHtml} from '../studio-html';++const makeHtml = ({+ publicPath,+ staticHash,+ publicFolderExists,+}: {+ publicPath: string;+ staticHash: string;+ publicFolderExists: string;+}) => {+ return studioHtml({+ publicPath,+ staticHash,+ editorName: null,+ inputProps: null,+ remotionRoot: '/project',+ studioServerCommand: null,+ renderQueue: null,+ numberOfAudioTags: 0,+ audioLatencyHint: 'playback',+ sampleRate: 48000,+ publicFiles: [+ {+ name: 'image.png',+ lastModified: 0,+ sizeInBytes: 100,+ src: `${staticHash}/image.png`,+ },+ ],+ publicFolderExists,+ fileSystemPlatform: null,+ includeFavicon: true,+ title: 'Remotion Bundle',+ renderDefaults: undefined,+ gitSource: null,+ projectName: 'test',+ installedDependencies: null,+ packageManager: 'unknown',+ logLevel: 'info',+ mode: 'bundle',+ });+};++test('makes relative bundles resolve public assets from the document URL', () => {+ const html = makeHtml({+ publicPath: './',+ staticHash: './public',+ publicFolderExists: './public',+ });++ expect(html).toContain('href="./favicon.ico"');+ expect(html).toContain('src="./bundle.js"');+ expect(html).toContain(+ 'window.remotion_staticBase = new URL("./public", window.location.href).pathname;',+ );+ expect(html).toContain(+ 'src: new URL(file.src, window.location.href).pathname',+ );+ expect(html).toContain(+ 'window.remotion_publicFolderExists = new URL("./public", window.location.href).pathname;',+ );++ expect(+ new URL('./public/image.png', 'https://example.com/sites/alpha/index.html')+ .pathname,+ ).toBe('/sites/alpha/public/image.png');+});++test('preserves explicitly absolute bundle paths', () => {+ const html = makeHtml({+ publicPath: '/sites/alpha/',+ staticHash: '/sites/alpha/public',+ publicFolderExists: '/sites/alpha/public',+ });++ expect(html).toContain('href="/sites/alpha/favicon.ico"');+ expect(html).toContain('src="/sites/alpha/bundle.js"');+ expect(html).toContain('window.remotion_staticBase = "/sites/alpha/public";');+ expect(html).toContain(+ 'window.remotion_publicFolderExists = "/sites/alpha/public";',+ );+ expect(html).not.toContain('.map((file)');+});