Skip to content

Visualize Your Ideas With Code

refactor(vite-plugin): split into smaller plugins (#919)

Jacobf9968d2c13c8
diff --git a/packages/vite-plugin/src/main.ts b/packages/vite-plugin/src/main.ts
index f52fa8b6..c0735a8c 100644
--- a/packages/vite-plugin/src/main.ts
+++ b/packages/vite-plugin/src/main.ts
@@ -1,20 +1,18 @@
-import fg from 'fast-glob';
-import fs from 'fs';
-import mime from 'mime-types';
-import * as os from 'os';
import path from 'path';
-import {Readable} from 'stream';
-import type {Plugin, ResolvedConfig} from 'vite';
-import {openInExplorer} from './openInExplorer';
-import {PLUGIN_OPTIONS, PluginOptions, ProjectData, isPlugin} from './plugins';
+import type {Plugin} from 'vite';
import {
- MotionCanvasCorsProxyOptions,
- motionCanvasCorsProxy,
- setupEnvVarsForProxy,
-} from './proxy-middleware';
-import {getVersions} from './versions';
-
-const AudioExtensions = new Set(['.mp3', '.wav', '.ogg', '.aac', '.flac']);
+ CorsProxyPluginConfig,
+ assetsPlugin,
+ corsProxyPlugin,
+ editorPlugin,
+ exporterPlugin,
+ metaPlugin,
+ projectsPlugin,
+ scenesPlugin,
+ settingsPlugin,
+} from './partials';
+import {PLUGIN_OPTIONS, PluginOptions, isPlugin} from './plugins';
+import {getProjects} from './utils';
export interface MotionCanvasPluginConfig {
/**
@@ -88,7 +86,7 @@ export interface MotionCanvasPluginConfig {
* You can either pass `true` and a config object
* to enable it.
**/
- proxy?: boolean | MotionCanvasCorsProxyOptions;
+ proxy?: boolean | CorsProxyPluginConfig;
/**
* Build the project to run in the editor.
@@ -103,423 +101,38 @@ export default ({
editor = '@motion-canvas/ui',
proxy,
buildForEditor,
-}: MotionCanvasPluginConfig = {}): Plugin => {
+}: MotionCanvasPluginConfig = {}): Plugin[] => {
const plugins: PluginOptions[] = [];
- const editorPath = path.dirname(require.resolve(editor));
- const editorFile = fs.readFileSync(path.resolve(editorPath, 'editor.html'));
- const htmlParts = editorFile
- .toString()
- .replace('{{style}}', `/@fs/${path.resolve(editorPath, 'style.css')}`)
- .split('{{source}}');
- const createHtml = (src: string) => htmlParts[0] + src + htmlParts[1];
- const versions = JSON.stringify(getVersions());
-
- const resolvedEditorId = '\0virtual:editor';
-
- const settingsId = '\0settings';
- const settingsPath = path.resolve(
- os.homedir(),
- '.motion-canvas/settings.json',
- );
- const timeStamps: Record<string, number> = {};
const outputPath = path.resolve(output);
- const projects: ProjectData[] = [];
- const projectLookup: Record<string, ProjectData> = {};
-
- function expandFilePaths(filePaths: string[] | string): string[] {
- const expandedFilePaths = [];
-
- for (const filePath of typeof filePaths === 'string'
- ? [filePaths]
- : filePaths) {
- if (fg.isDynamicPattern(filePath)) {
- const matchingFilePaths = fg.sync(filePath, {onlyFiles: true});
- expandedFilePaths.push(...matchingFilePaths);
- } else {
- expandedFilePaths.push(filePath);
- }
- }
-
- return expandedFilePaths;
- }
-
- const projectList = expandFilePaths(project);
- for (const url of projectList) {
- const {name, dir} = path.posix.parse(url);
- const metaFile = `${name}.meta`;
- const metaData = getMeta(path.join(dir, metaFile));
- const data = {name: metaData?.name ?? name, fileName: name, url};
- projects.push(data);
- projectLookup[name] = data;
- }
-
- let viteConfig: ResolvedConfig;
-
- function source(...lines: string[]) {
- return lines.join('\n');
- }
-
- function getMeta(metaPath: string) {
- if (fs.existsSync(metaPath)) {
- return JSON.parse(fs.readFileSync(metaPath, 'utf8'));
- }
- }
-
- async function createMeta(metaPath: string) {
- if (!fs.existsSync(metaPath)) {
- await fs.promises.writeFile(
- metaPath,
- JSON.stringify({version: 0}, undefined, 2),
- 'utf8',
- );
- }
- }
-
- // Initialize the Proxy Module
- setupEnvVarsForProxy(proxy);
-
- return {
- name: 'motion-canvas',
- async configResolved(resolvedConfig) {
- plugins.push(
- ...resolvedConfig.plugins
- .filter(isPlugin)
- .map(plugin => plugin[PLUGIN_OPTIONS]),
- );
- await Promise.all(
- plugins.map(
- plugin =>
- plugin.config?.({
- output: outputPath,
- projects,
- }),
- ),
- );
- viteConfig = resolvedConfig;
- },
- async load(id) {
- const [base, query] = id.split('?');
- const {name, dir} = path.posix.parse(base);
-
- if (id.startsWith(resolvedEditorId)) {
- if (projects.length === 1) {
- return source(
- `import {editor} from '${editor}';`,
- `import project from '${projects[0].url}?project';`,
- `editor(project);`,
- );
- }
-
- if (query) {
- const params = new URLSearchParams(query);
- const name = params.get('project');
- if (name && name in projectLookup) {
- return source(
- `import {editor} from '${editor}';`,
- `import project from '${projectLookup[name].url}?project';`,
- `editor(project);`,
- );
- }
- }
-
- return source(
- `import {index} from '${editor}';`,
- `index(${JSON.stringify(projects)});`,
- );
- }
-
- if (query) {
- const params = new URLSearchParams(query);
- if (params.has('scene')) {
- const metaFile = `${name}.meta`;
- await createMeta(path.join(dir, metaFile));
- const sceneFile = `${name}`;
-
- return source(
- `import {ValueDispatcher} from '@motion-canvas/core';`,
- `import metaFile from './${metaFile}';`,
- `import description from './${sceneFile}';`,
- `description.name = '${name}';`,
- `metaFile.attach(description.meta);`,
- `if (import.meta.hot) {`,
- ` description.onReplaced = import.meta.hot.data.onReplaced;`,
- `}`,
- `description.onReplaced ??= new ValueDispatcher(description.config);`,
- `if (import.meta.hot) {`,
- ` import.meta.hot.accept();`,
- ` if (import.meta.hot.data.onReplaced) {`,
- ` description.onReplaced.current = description;`,
- ` } else {`,
- ` import.meta.hot.data.onReplaced = description.onReplaced;`,
- ` }`,
- `}`,
- `export default description;`,
- );
- }
-
- if (params.has('project')) {
- const runsInEditor = buildForEditor || viteConfig.command === 'serve';
- const metaFile = `${name}.meta`;
- await createMeta(path.join(dir, metaFile));
-
- const imports: string[] = [];
- const pluginNames: string[] = [];
- let index = 0;
- for (const plugin of plugins) {
- if (plugin.entryPoint) {
- const pluginName = `plugin${index}`;
- let options = (await plugin.runtimeConfig?.()) ?? '';
- if (typeof options !== 'string') {
- options = JSON.stringify(options);
- }
-
- imports.push(`import ${pluginName} from '${plugin.entryPoint}'`);
- pluginNames.push(`${pluginName}(${options})`);
- index++;
- }
- }
-
- let parsed = {};
- try {
- parsed = JSON.parse(
- await fs.promises.readFile(settingsPath, 'utf8'),
- );
- } catch (_) {
- // Ignore an invalid settings file
- }
-
- return source(
- ...imports,
- `import {${
- runsInEditor ? 'editorBootstrap' : 'bootstrap'
- }} from '@motion-canvas/core';`,
- `import {MetaFile} from '@motion-canvas/core';`,
- `import metaFile from './${metaFile}';`,
- `import config from './${name}';`,
- `const settings = new MetaFile('settings', '${settingsId}');`,
- `settings.loadData(${JSON.stringify(parsed)});`,
- `export default ${
- runsInEditor ? 'await editorBootstrap' : 'bootstrap'
- }(`,
- ` '${name}',`,
- ` ${versions},`,
- ` [${pluginNames.join(', ')}],`,
- ` config,`,
- ` metaFile,`,
- ` settings,`,
- `);`,
- );
- }
- }
- },
- async transform(code, id) {
- const [base, query] = id.split('?');
- const {name, dir, ext} = path.posix.parse(base);
-
- if (query) {
- const params = new URLSearchParams(query);
- if (params.has('img')) {
- return source(
- `import {loadImage} from '@motion-canvas/core';`,
- `import image from '/@fs/${base}';`,
- `export default loadImage(image);`,
- );
- }
-
- if (params.has('anim')) {
- const nameRegex = /\D*(\d+)\./;
- let urls: string[] = [];
- for (const file of await fs.promises.readdir(dir)) {
- const match = nameRegex.exec(file);
- if (!match) continue;
- const index = parseInt(match[1]);
- urls[index] = path.posix.join(dir, file);
- }
- urls = urls.filter(Boolean);
-
- return source(
- `import {loadAnimation} from '@motion-canvas/core';`,
- ...urls.map(
- (url, index) => `import image${index} from '/@fs/${url}';`,
- ),
- `export default loadAnimation([${urls
- .map((_, index) => `image${index}`)
- .join(', ')}]);`,
- );
- }
- }
-
- if (ext === '.meta') {
- const sourceFile =
- viteConfig.command === 'build' ? false : JSON.stringify(id);
- return source(
- `import {MetaFile} from '@motion-canvas/core';`,
- `let meta;`,
- `if (import.meta.hot) {`,
- ` meta = import.meta.hot.data.meta;`,
- `}`,
- `meta ??= new MetaFile('${name}', ${sourceFile});`,
- `if (import.meta.hot) {`,
- ` import.meta.hot.accept();`,
- ` import.meta.hot.data.meta = meta;`,
- `}`,
- `meta.loadData(${code});`,
- `export default meta;`,
+ const projects = getProjects(project);
+
+ return [
+ {
+ name: 'motion-canvas',
+ async configResolved(resolvedConfig) {
+ plugins.push(
+ ...resolvedConfig.plugins
+ .filter(isPlugin)
+ .map(plugin => plugin[PLUGIN_OPTIONS]),
);
- }
-
- if (AudioExtensions.has(ext)) {
- return source(
- code,
- `if (import.meta.hot) {`,
- ` import.meta.hot.accept();`,
- `}`,
+ await Promise.all(
+ plugins.map(
+ plugin =>
+ plugin.config?.({
+ output: outputPath,
+ projects: projects.list,
+ }),
+ ),
);
- }
- },
- handleHotUpdate(ctx) {
- const now = Date.now();
- const urls = [];
- const modules = [];
-
- for (const module of ctx.modules) {
- if (
- module.file !== null &&
- timeStamps[module.file] &&
- timeStamps[module.file] + 1000 > now
- ) {
- continue;
- }
-
- urls.push(module.url);
- modules.push(module);
- }
-
- if (urls.length > 0) {
- ctx.server.ws.send('motion-canvas:assets', {urls});
- }
-
- return modules;
- },
- configureServer(server) {
- server.middlewares.use((req, res, next) => {
- if (req.url && bufferedAssets && bufferedAssets.test(req.url)) {
- const file = fs.readFileSync(
- path.resolve(viteConfig.root, req.url.slice(1)),
- );
- Readable.from(file).pipe(res);
- return;
- }
-
- const url = req.url
- ? new URL(req.url, `http://${req.headers.host}`)
- : undefined;
- if (url?.pathname === '/') {
- res.setHeader('Content-Type', 'text/html');
- res.end(createHtml('/@id/__x00__virtual:editor'));
- return;
- }
-
- const name = url?.pathname?.slice(1);
- if (name && name in projectLookup) {
- res.setHeader('Content-Type', 'text/html');
- res.end(createHtml(`/@id/__x00__virtual:editor?project=${name}`));
- return;
- }
-
- if (name === '__open-output-path') {
- if (!fs.existsSync(outputPath)) {
- fs.mkdirSync(outputPath, {recursive: true});
- }
- openInExplorer(outputPath);
- res.end();
- return;
- }
-
- next();
- });
-
- // if proxy is unset (undefined), or set to false,
- // it will not register its middleware — as a result, no
- // proxy is started.
- if (proxy !== false && proxy !== undefined) {
- motionCanvasCorsProxy(server.middlewares, proxy === true ? {} : proxy);
- }
-
- server.ws.on('motion-canvas:meta', async ({source, data}, client) => {
- if (source === settingsId) {
- const outputDirectory = path.dirname(settingsPath);
- if (!fs.existsSync(outputDirectory)) {
- fs.mkdirSync(outputDirectory, {recursive: true});
- }
- await fs.promises.writeFile(
- settingsPath,
- JSON.stringify(data, undefined, 2),
- 'utf8',
- );
- } else {
- timeStamps[source] = Date.now();
- await fs.promises.writeFile(
- source,
- JSON.stringify(data, undefined, 2),
- 'utf8',
- );
- }
- client.send('motion-canvas:meta-ack', {source});
- });
- server.ws.on(
- 'motion-canvas:export',
- async (
- {data, frame, sceneFrame, subDirectories, mimeType, groupByScene},
- client,
- ) => {
- const name = (groupByScene ? sceneFrame : frame)
- .toString()
- .padStart(6, '0');
- const extension = mime.extension(mimeType);
- const outputFilePath = path.join(
- outputPath,
- ...subDirectories,
- `${name}.${extension}`,
- );
- const outputDirectory = path.dirname(outputFilePath);
-
- if (!fs.existsSync(outputDirectory)) {
- fs.mkdirSync(outputDirectory, {recursive: true});
- }
-
- const base64Data = data.slice(data.indexOf(',') + 1);
- await fs.promises.writeFile(outputFilePath, base64Data, {
- encoding: 'base64',
- });
- client.send('motion-canvas:export-ack', {frame});
- },
- );
- },
- config(config) {
- return {
- build: {
- target: buildForEditor ? 'esnext' : 'modules',
- assetsDir: './',
- rollupOptions: {
- preserveEntrySignatures: 'strict',
- input: Object.fromEntries(
- projects.map(project => [project.name, project.url + '?project']),
- ),
- },
- },
- server: {
- port: config?.server?.port ?? 9000,
- },
- esbuild: {
- jsx: 'automatic',
- jsxImportSource: '@motion-canvas/2d/lib',
- },
- optimizeDeps: {
- entries: projects.map(project => project.url),
- exclude: ['preact', 'preact/*', '@preact/signals'],
- },
- };
+ },
},
- };
+ metaPlugin(),
+ settingsPlugin(),
+ scenesPlugin(),
+ exporterPlugin({outputPath}),
+ editorPlugin({editor, projects}),
+ projectsPlugin({projects, plugins, buildForEditor}),
+ assetsPlugin({bufferedAssets}),
+ corsProxyPlugin(proxy),
+ ];
};
diff --git a/packages/vite-plugin/src/partials/assets.ts b/packages/vite-plugin/src/partials/assets.ts
new file mode 100644
index 00000000..683e9edd
--- /dev/null
+++ b/packages/vite-plugin/src/partials/assets.ts
@@ -0,0 +1,58 @@
+import fs from 'fs';
+import path from 'path';
+import {Readable} from 'stream';
+import {ModuleNode, Plugin, ResolvedConfig} from 'vite';
+
+const AUDIO_EXTENSION_REGEX = /\.(mp3|wav|ogg|aac|flac)(?:$|\?)/;
+const AUDIO_HMR_DELAY = 1000;
+
+interface AssetsPluginConfig {
+ bufferedAssets: RegExp | false;
+}
+
+export function assetsPlugin({bufferedAssets}: AssetsPluginConfig): Plugin {
+ let config: ResolvedConfig;
+ return {
+ name: 'motion-canvas:assets',
+
+ configResolved(resolvedConfig) {
+ config = resolvedConfig;
+ },
+
+ configureServer(server) {
+ server.middlewares.use((req, res, next) => {
+ if (req.url && bufferedAssets && bufferedAssets.test(req.url)) {
+ const file = fs.readFileSync(
+ path.resolve(config.root, req.url.slice(1)),
+ );
+ Readable.from(file).pipe(res);
+ return;
+ }
+
+ next();
+ });
+ },
+
+ async handleHotUpdate(ctx) {
+ const urls = [];
+ const modules: ModuleNode[] = [];
+
+ for (const module of ctx.modules) {
+ urls.push(module.url);
+ if (!AUDIO_EXTENSION_REGEX.test(module.url)) {
+ modules.push(module);
+ } else {
+ await new Promise(resolve => {
+ setTimeout(resolve, AUDIO_HMR_DELAY);
+ });
+ }
+ }
+
+ if (urls.length > 0) {
+ ctx.server.ws.send('motion-canvas:assets', {urls});
+ }
+
+ return modules;
+ },
+ };
+}
diff --git a/packages/vite-plugin/src/proxy-middleware.ts b/packages/vite-plugin/src/partials/corsProxy.ts
similarity index 92%
rename from packages/vite-plugin/src/proxy-middleware.ts
rename to packages/vite-plugin/src/partials/corsProxy.ts
index 3f776f9a..72541182 100644
--- a/packages/vite-plugin/src/proxy-middleware.ts
+++ b/packages/vite-plugin/src/partials/corsProxy.ts
@@ -1,28 +1,11 @@
-/**
- * This module provides the proxy located at
- * /cors-proxy/...
- *
- * It is needed when accessing remote resources.
- * Trying to access remote resources works while
- * in preview, but will fail when you try to
- * output the image (= "read" the canvas)
- *
- * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image
- * for reasons
- *
- * Using the proxy circumvents CORS-issues because
- * this way all remote resources are served from the
- * same host as the main app.
- */
-
import followRedirects from 'follow-redirects';
import {IncomingMessage, ServerResponse} from 'http';
-import {Connect} from 'vite';
+import {Connect, Plugin} from 'vite';
/**
* Configuration used by the Proxy plugin
*/
-export interface MotionCanvasCorsProxyOptions {
+export interface CorsProxyPluginConfig {
/**
* Set which types of resources are allowed by default.
*
@@ -45,8 +28,41 @@ export interface MotionCanvasCorsProxyOptions {
allowListHosts?: string[];
}
-export function setupEnvVarsForProxy(
- config: MotionCanvasCorsProxyOptions | undefined | boolean,
+/**
+ * This module provides the proxy located at
+ * /cors-proxy/...
+ *
+ * It is needed when accessing remote resources.
+ * Trying to access remote resources works while
+ * in preview, but will fail when you try to
+ * output the image (= "read" the canvas)
+ *
+ * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image
+ * for reasons
+ *
+ * Using the proxy circumvents CORS-issues because
+ * this way all remote resources are served from the
+ * same host as the main app.
+ */
+export function corsProxyPlugin(
+ config?: CorsProxyPluginConfig | boolean,
+): Plugin {
+ setupEnvVarsForProxy(config);
+ return {
+ name: 'motion-canvas:cors-proxy',
+ configureServer(server) {
+ if (config !== false && config !== undefined) {
+ motionCanvasCorsProxy(
+ server.middlewares,
+ config === true ? {} : config,
+ );
+ }
+ },
+ };
+}
+
+function setupEnvVarsForProxy(
+ config: CorsProxyPluginConfig | undefined | boolean,
) {
// Define Keys for Env Var
const prefix = 'VITE_MC_PROXY_';
@@ -67,9 +83,9 @@ export function setupEnvVarsForProxy(
}
}
-export function motionCanvasCorsProxy(
+function motionCanvasCorsProxy(
middleware: Connect.Server,
- config: MotionCanvasCorsProxyOptions,
+ config: CorsProxyPluginConfig,
) {
// Set the default config if no config was provided
config.allowedMimeTypes ??= ['image/*', 'video/*'];
@@ -224,7 +240,7 @@ function isResultOfAllowedResourceType(
async function tryGetResource(
res: ServerResponse<IncomingMessage>,
sourceUrl: URL,
- config: MotionCanvasCorsProxyOptions,
+ config: CorsProxyPluginConfig,
): Promise<void> {
// Turn this callback into a Promise to avoid additional nesting
const result: IncomingMessage = await new Promise((res, rej) => {
diff --git a/packages/vite-plugin/src/partials/editor.ts b/packages/vite-plugin/src/partials/editor.ts
new file mode 100644
index 00000000..37882766
--- /dev/null
+++ b/packages/vite-plugin/src/partials/editor.ts
@@ -0,0 +1,81 @@
+import fs from 'fs';
+import path from 'path';
+import {Plugin} from 'vite';
+import {Projects} from '../utils';
+
+interface EditorPluginConfig {
+ editor: string;
+ projects: Projects;
+}
+
+export function editorPlugin({editor, projects}: EditorPluginConfig): Plugin {
+ const editorPath = path.dirname(require.resolve(editor));
+ const editorFile = fs.readFileSync(path.resolve(editorPath, 'editor.html'));
+ const htmlParts = editorFile
+ .toString()
+ .replace('{{style}}', `/@fs/${path.resolve(editorPath, 'style.css')}`)
+ .split('{{source}}');
+ const createHtml = (src: string) => htmlParts[0] + src + htmlParts[1];
+
+ const resolvedEditorId = '\0virtual:editor';
+
+ return {
+ name: 'motion-canvas:editor',
+
+ async load(id) {
+ const [, query] = id.split('?');
+
+ if (id.startsWith(resolvedEditorId)) {
+ if (projects.list.length === 1) {
+ /* language=typescript */
+ return `\
+import {editor} from '${editor}';
+import project from '${projects.list[0].url}?project';
+editor(project);
+`;
+ }
+
+ if (query) {
+ const params = new URLSearchParams(query);
+ const name = params.get('project');
+ if (name && projects.lookup.has(name)) {
+ /* language=typescript */
+ return `\
+import {editor} from '${editor}';
+import project from '${projects.lookup.get(name)!.url}?project';
+editor(project);
+`;
+ }
+ }
+
+ /* language=typescript */
+ return `\
+import {index} from '${editor}';
+index(${JSON.stringify(projects)});
+`;
+ }
+ },
+
+ configureServer(server) {
+ server.middlewares.use((req, res, next) => {
+ if (req.url) {
+ const url = new URL(req.url, `http://${req.headers.host}`);
+ if (url.pathname === '/') {
+ res.setHeader('Content-Type', 'text/html');
+ res.end(createHtml('/@id/__x00__virtual:editor'));
+ return;
+ }
+
+ const name = url.pathname.slice(1);
+ if (name && projects.lookup.has(name)) {
+ res.setHeader('Content-Type', 'text/html');
+ res.end(createHtml(`/@id/__x00__virtual:editor?project=${name}`));
+ return;
+ }
+ }
+
+ next();
+ });
+ },
+ };
+}
diff --git a/packages/vite-plugin/src/partials/exporter.ts b/packages/vite-plugin/src/partials/exporter.ts
new file mode 100644
index 00000000..ec887ae8
--- /dev/null
+++ b/packages/vite-plugin/src/partials/exporter.ts
@@ -0,0 +1,59 @@
+import fs from 'fs';
+import mime from 'mime-types';
+import path from 'path';
+import {Plugin} from 'vite';
+import {openInExplorer} from '../openInExplorer';
+
+interface ExporterPluginConfig {
+ outputPath: string;
+}
+
+export function exporterPlugin({outputPath}: ExporterPluginConfig): Plugin {
+ return {
+ name: 'motion-canvas:exporter',
+
+ configureServer(server) {
+ server.middlewares.use((req, res, next) => {
+ if (req.url === '/__open-output-path') {
+ if (!fs.existsSync(outputPath)) {
+ fs.mkdirSync(outputPath, {recursive: true});
+ }
+ openInExplorer(outputPath);
+ res.end();
+ return;
+ }
+
+ next();
+ });
+
+ server.ws.on(
+ 'motion-canvas:export',
+ async (
+ {data, frame, sceneFrame, subDirectories, mimeType, groupByScene},
+ client,
+ ) => {
+ const name = (groupByScene ? sceneFrame : frame)
+ .toString()
+ .padStart(6, '0');
+ const extension = mime.extension(mimeType);
+ const outputFilePath = path.join(
+ outputPath,
+ ...subDirectories,
+ `${name}.${extension}`,
+ );
+ const outputDirectory = path.dirname(outputFilePath);
+
+ if (!fs.existsSync(outputDirectory)) {
+ fs.mkdirSync(outputDirectory, {recursive: true});
+ }
+
+ const base64Data = data.slice(data.indexOf(',') + 1);
+ await fs.promises.writeFile(outputFilePath, base64Data, {
+ encoding: 'base64',
+ });
+ client.send('motion-canvas:export-ack', {frame});
+ },
+ );
+ },
+ };
+}
diff --git a/packages/vite-plugin/src/partials/index.ts b/packages/vite-plugin/src/partials/index.ts
new file mode 100644
index 00000000..0facf4da
--- /dev/null
+++ b/packages/vite-plugin/src/partials/index.ts
@@ -0,0 +1,8 @@
+export * from './assets';
+export * from './corsProxy';
+export * from './editor';
+export * from './exporter';
+export * from './meta';
+export * from './projects';
+export * from './scenes';
+export * from './settings';
diff --git a/packages/vite-plugin/src/partials/meta.ts b/packages/vite-plugin/src/partials/meta.ts
new file mode 100644
index 00000000..8b7e0fa1
--- /dev/null
+++ b/packages/vite-plugin/src/partials/meta.ts
@@ -0,0 +1,78 @@
+import fs from 'fs';
+import path from 'path';
+import {Plugin, ResolvedConfig} from 'vite';
+
+export function metaPlugin(): Plugin {
+ const timeStamps: Record<string, number> = {};
+ let config: ResolvedConfig;
+ return {
+ name: 'motion-canvas:meta',
+
+ configResolved(resolvedConfig) {
+ config = resolvedConfig;
+ },
+
+ async transform(code, id) {
+ const [base] = id.split('?');
+ const {name, ext} = path.posix.parse(base);
+ if (ext !== '.meta') {
+ return;
+ }
+
+ const sourceFile =
+ config.command === 'build' ? false : JSON.stringify(id);
+
+ /* language=typescript */
+ return `\
+import {MetaFile} from '@motion-canvas/core';
+let meta;
+if (import.meta.hot) {
+ meta = import.meta.hot.data.meta;
+}
+meta ??= new MetaFile('${name}', ${sourceFile});
+if (import.meta.hot) {
+ import.meta.hot.accept();
+ import.meta.hot.data.meta = meta;
+}
+meta.loadData(${code});
+export default meta;
+`;
+ },
+
+ configureServer(server) {
+ server.ws.on('motion-canvas:meta', async ({source, data}, client) => {
+ // Ignore virtual meta files.
+ if (source.startsWith('\0')) {
+ return;
+ }
+
+ timeStamps[source] = Date.now();
+ await fs.promises.writeFile(
+ source,
+ JSON.stringify(data, undefined, 2),
+ 'utf8',
+ );
+ client.send('motion-canvas:meta-ack', {source});
+ });
+ },
+
+ handleHotUpdate(ctx) {
+ const now = Date.now();
+ const modules = [];
+
+ for (const module of ctx.modules) {
+ if (
+ module.file !== null &&
+ timeStamps[module.file] &&
+ timeStamps[module.file] + 1000 > now
+ ) {
+ continue;
+ }
+
+ modules.push(module);
+ }
+
+ return modules;
+ },
+ };
+}
diff --git a/packages/vite-plugin/src/partials/projects.ts b/packages/vite-plugin/src/partials/projects.ts
new file mode 100644
index 00000000..8138c005
--- /dev/null
+++ b/packages/vite-plugin/src/partials/projects.ts
@@ -0,0 +1,107 @@
+import path from 'path';
+import {Plugin, ResolvedConfig} from 'vite';
+import {PluginOptions} from '../plugins';
+import {Projects, createMeta} from '../utils';
+import {getVersions} from '../versions';
+
+const PROJECT_QUERY_REGEX = /[?&]project\b/;
+
+interface ProjectPluginConfig {
+ buildForEditor?: boolean;
+ plugins: PluginOptions[];
+ projects: Projects;
+}
+
+export function projectsPlugin({
+ buildForEditor,
+ plugins,
+ projects,
+}: ProjectPluginConfig): Plugin {
+ const versions = JSON.stringify(getVersions());
+ let config: ResolvedConfig;
+ return {
+ name: 'motion-canvas:project',
+
+ configResolved(resolvedConfig) {
+ config = resolvedConfig;
+ },
+
+ async load(id) {
+ if (!PROJECT_QUERY_REGEX.test(id)) {
+ return;
+ }
+
+ const [base] = id.split('?');
+ const {name, dir} = path.posix.parse(base);
+
+ const runsInEditor = buildForEditor || config.command === 'serve';
+ const metaFile = `${name}.meta`;
+ await createMeta(path.join(dir, metaFile));
+
+ const imports: string[] = [];
+ const pluginNames: string[] = [];
+ let index = 0;
+ for (const plugin of plugins) {
+ if (plugin.entryPoint) {
+ const pluginName = `plugin${index}`;
+ let options = (await plugin.runtimeConfig?.()) ?? '';
+ if (typeof options !== 'string') {
+ options = JSON.stringify(options);
+ }
+
+ imports.push(`import ${pluginName} from '${plugin.entryPoint}'`);
+ pluginNames.push(`${pluginName}(${options})`);
+ index++;
+ }
+ }
+
+ /* language=typescript */
+ return `\
+${imports.join('\n')}
+import {${
+ runsInEditor ? 'editorBootstrap' : 'bootstrap'
+ }} from '@motion-canvas/core';
+import {MetaFile} from '@motion-canvas/core';
+ import metaFile from './${metaFile}';
+ import config from './${name}';
+ import settings from 'virtual:settings.meta';
+ export default ${runsInEditor ? 'await editorBootstrap' : 'bootstrap'}(
+ '${name}',
+ ${versions},
+ [${pluginNames.join(', ')}],
+ config,
+ metaFile,
+ settings,
+ );`;
+ },
+
+ config(config) {
+ return {
+ build: {
+ target: buildForEditor ? 'esnext' : 'modules',
+ assetsDir: './',
+ rollupOptions: {
+ preserveEntrySignatures: 'strict',
+ input: Object.fromEntries(
+ projects.list.map(project => [
+ project.name,
+ project.url + '?project',
+ ]),
+ ),
+ },
+ },
+ server: {
+ port: config?.server?.port ?? 9000,
+ },
+ esbuild: {
+ jsx: 'automatic',
+ jsxImportSource: '@motion-canvas/2d/lib',
+ },
+ optimizeDeps: {
+ entries: projects.list.map(project => project.url),
+ exclude: ['preact', 'preact/*', '@preact/signals'],
+ },
+ };
+ },
+ };
+}
diff --git a/packages/vite-plugin/src/partials/scenes.ts b/packages/vite-plugin/src/partials/scenes.ts
new file mode 100644
index 00000000..59ca4c47
--- /dev/null
+++ b/packages/vite-plugin/src/partials/scenes.ts
@@ -0,0 +1,45 @@
+import path from 'path';
+import {Plugin} from 'vite';
+import {createMeta} from '../utils';
+
+const SCENE_QUERY_REGEX = /[?&]scene\b/;
+
+export function scenesPlugin(): Plugin {
+ return {
+ name: 'motion-canvas:scene',
+
+ async load(id) {
+ if (!SCENE_QUERY_REGEX.test(id)) {
+ return;
+ }
+
+ const [base] = id.split('?');
+ const {name, dir} = path.posix.parse(base);
+ const metaFile = `${name}.meta`;
+ await createMeta(path.join(dir, metaFile));
+ const sceneFile = `${name}`;
+
+ /* language=typescript */
+ return `\
+import {ValueDispatcher} from '@motion-canvas/core';
+import metaFile from './${metaFile}';
+import description from './${sceneFile}';
+description.name = '${name}';
+metaFile.attach(description.meta);
+if (import.meta.hot) {
+ description.onReplaced = import.meta.hot.data.onReplaced;
+}
+description.onReplaced ??= new ValueDispatcher(description.config);
+if (import.meta.hot) {
+ import.meta.hot.accept();
+ if (import.meta.hot.data.onReplaced) {
+ description.onReplaced.current = description;
+ } else {
+ import.meta.hot.data.onReplaced = description.onReplaced;
+ }
+}
+export default description;
+`;
+ },
+ };
+}
diff --git a/packages/vite-plugin/src/partials/settings.ts b/packages/vite-plugin/src/partials/settings.ts
new file mode 100644
index 00000000..dab00450
--- /dev/null
+++ b/packages/vite-plugin/src/partials/settings.ts
@@ -0,0 +1,69 @@
+import fs from 'fs';
+import os from 'os';
+import path from 'path';
+import {Plugin} from 'vite';
+
+export function settingsPlugin(): Plugin {
+ const settingsId = 'virtual:settings.meta';
+ const resolvedSettingsId = '\0' + settingsId;
+ const settingsPath = path.resolve(
+ os.homedir(),
+ '.motion-canvas/settings.json',
+ );
+ const outputDirectory = path.dirname(settingsPath);
+
+ return {
+ name: 'motion-canvas:settings',
+
+ resolveId(id) {
+ if (id === settingsId) {
+ return resolvedSettingsId;
+ }
+ },
+
+ async load(id) {
+ if (id === resolvedSettingsId) {
+ let parsed = {};
+ try {
+ parsed = JSON.parse(await fs.promises.readFile(settingsPath, 'utf8'));
+ } catch (_) {
+ // Ignore an invalid settings file
+ }
+
+ return JSON.stringify(parsed);
+ }
+ },
+
+ configureServer(server) {
+ server.ws.on('motion-canvas:meta', async ({source, data}, client) => {
+ if (source !== resolvedSettingsId) {
+ return;
+ }
+
+ await fs.promises.mkdir(outputDirectory, {recursive: true});
+ const newData = JSON.stringify(data, undefined, 2);
+ let oldData = '';
+ try {
+ oldData = await fs.promises.readFile(settingsPath, 'utf8');
+ } catch (_) {
+ // Ignore an invalid settings file
+ }
+
+ if (oldData !== newData) {
+ await Promise.all([
+ fs.promises.writeFile(settingsPath, newData, 'utf8'),
+ // Invalidate the module so that the settings are up-to-date next
+ // time the browser is refreshed.
+ server.moduleGraph.getModuleByUrl(source).then(module => {
+ if (module) {
+ server.moduleGraph.invalidateModule(module);
+ }
+ }),
+ ]);
+ }
+
+ client.send('motion-canvas:meta-ack', {source});
+ });
+ },
+ };
+}
diff --git a/packages/vite-plugin/src/utils.ts b/packages/vite-plugin/src/utils.ts
new file mode 100644
index 00000000..bfcba00d
--- /dev/null
+++ b/packages/vite-plugin/src/utils.ts
@@ -0,0 +1,59 @@
+import fg from 'fast-glob';
+import fs from 'fs';
+import path from 'path';
+import {ProjectData} from './plugins';
+
+export interface Projects {
+ list: ProjectData[];
+ lookup: Map<string, ProjectData>;
+}
+
+export async function createMeta(metaPath: string) {
+ if (!fs.existsSync(metaPath)) {
+ await fs.promises.writeFile(
+ metaPath,
+ JSON.stringify({version: 0}, undefined, 2),
+ 'utf8',
+ );
+ }
+}
+
+export function getProjects(project: string | string[]): Projects {
+ const list: ProjectData[] = [];
+ const lookup = new Map<string, ProjectData>();
+
+ const projectList = expandFilePaths(project);
+ for (const url of projectList) {
+ const {name, dir} = path.posix.parse(url);
+ const metaFile = `${name}.meta`;
+ const metaData = getMeta(path.join(dir, metaFile));
+ const data = {name: metaData?.name ?? name, fileName: name, url};
+ list.push(data);
+ lookup.set(data.name, data);
+ }
+
+ return {list, lookup};
+}
+
+function expandFilePaths(filePaths: string[] | string): string[] {
+ const expandedFilePaths = [];
+
+ for (const filePath of typeof filePaths === 'string'
+ ? [filePaths]
+ : filePaths) {
+ if (fg.isDynamicPattern(filePath)) {
+ const matchingFilePaths = fg.sync(filePath, {onlyFiles: true});
+ expandedFilePaths.push(...matchingFilePaths);
+ } else {
+ expandedFilePaths.push(filePath);
+ }
+ }
+
+ return expandedFilePaths;
+}
+
+function getMeta(metaPath: string) {
+ if (fs.existsSync(metaPath)) {
+ return JSON.parse(fs.readFileSync(metaPath, 'utf8'));
+ }
+}