Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

Add ability to build templates from the templates folder for scaffolding projects in cli (#2035)

Jaya Krishna Namburu7097efe71fa4
diff --git a/.eslintrc.js b/.eslintrc.js
index 454ea28626..b6922a4fff 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -6,5 +6,6 @@ module.exports = {
"**/__generated__/**/*",
"/packages/prisma-client/prisma/migrations",
"/codemod",
+ "apps/cli/templates/",
],
};
diff --git a/apps/cli/package.json b/apps/cli/package.json
index 99b25e6295..e3a25b7b7e 100644
--- a/apps/cli/package.json
+++ b/apps/cli/package.json
@@ -9,12 +9,17 @@
"webstudio": "./bin.js"
},
"scripts": {
- "dev": "build-package --watch",
- "build": "build-package"
+ "build:templates": "tsx ./templates/build.ts",
+ "build": "pnpm build:templates && build-package"
},
"license": "MIT",
"dependencies": {
+ "@webstudio-is/asset-uploader": "workspace:^",
"@webstudio-is/http-client": "workspace:^",
+ "@webstudio-is/project-build": "workspace:^",
+ "@webstudio-is/react-sdk": "workspace:^",
+ "@webstudio-is/sdk-components-react": "workspace:^",
+ "@webstudio-is/sdk-components-react-remix": "workspace:^",
"env-paths": "^3.0.0",
"ora": "^7.0.1",
"strip-indent": "^4.0.0"
@@ -22,6 +27,7 @@
"devDependencies": {
"@types/node": "^18.13.0",
"@webstudio-is/scripts": "workspace:^",
- "@webstudio-is/tsconfig": "workspace:^"
+ "@webstudio-is/tsconfig": "workspace:^",
+ "tsx": "^3.12.6"
}
}
diff --git a/apps/cli/src/__generated__/router.ts b/apps/cli/src/__generated__/router.ts
new file mode 100644
index 0000000000..b3b4d809c5
--- /dev/null
+++ b/apps/cli/src/__generated__/router.ts
@@ -0,0 +1,145 @@
+/*
+
+This is an auto-generated file. Please don't change manually.
+If needed to make any changes. Add them to ./templates folder and run pnpm run build:templates
+
+*/
+
+import { ASSETS_BASE } from "../config";
+
+export const getRouteTemplate = () => {
+ return `import {
+ V2_MetaFunction,
+ LinksFunction,
+ LinkDescriptor,
+ ActionArgs,
+ json,
+} from "@remix-run/node";
+
+import {
+ InstanceRoot,
+ type RootPropsData,
+ type Data,
+} from "@webstudio-is/react-sdk";
+import { n8nHandler, hasMatchingForm } from "@webstudio-is/form-handlers";
+
+import {
+ fontAssets,
+ components,
+ pageData,
+ user,
+ projectId,
+ utils,
+} from "../__generated__/index";
+import css from "../__generated__/index.css";
+
+export type PageData = Omit<Data, "build"> & {
+ build: Pick<Data["build"], "props" | "instances" | "dataSources">;
+};
+
+export const meta: V2_MetaFunction = () => {
+ const { page } = pageData;
+ return [{ title: page?.title || "Webstudio", ...page?.meta }];
+};
+
+export const links: LinksFunction = () => {
+ const result: LinkDescriptor[] = [];
+
+ result.push({
+ rel: "stylesheet",
+ href: css,
+ });
+
+ for (const asset of fontAssets) {
+ if (asset.type === "font") {
+ result.push({
+ rel: "preload",
+ href: "${ASSETS_BASE}" + asset.name,
+ as: "font",
+ crossOrigin: "anonymous",
+ // @todo add mimeType
+ // type: asset.mimeType,
+ });
+ }
+ }
+
+ return result;
+};
+
+const getRequestHost = (request: Request): string =>
+ request.headers.get("x-forwarded-host") || request.headers.get("host") || "";
+
+export const action = async ({ request, context }: ActionArgs) => {
+ const formData = await request.formData();
+
+ // We're throwing rather than returning \`{ success: false }\`
+ // because this isn't supposed to happen normally: bug or malicious user
+ if (hasMatchingForm(formData, pageData.build.instances) === false) {
+ throw json("Form not found", { status: 404 });
+ }
+
+ const email = user?.email;
+
+ if (email == null) {
+ return { success: false };
+ }
+
+ // wrapped in try/catch just in cases \`new URL()\` throws
+ // (should not happen)
+ let pageUrl: URL;
+ try {
+ pageUrl = new URL(request.url);
+ pageUrl.host = getRequestHost(request);
+ } catch {
+ return { success: false };
+ }
+
+ const formInfo = {
+ formData,
+ projectId,
+ pageUrl: pageUrl.toString(),
+ toEmail: email,
+ fromEmail: pageUrl.hostname + "@webstudio.email",
+ };
+
+ const result = await n8nHandler({
+ formInfo,
+ hookUrl: context.N8N_FORM_EMAIL_HOOK as string,
+ });
+
+ return result;
+};
+
+const Outlet = () => {
+ const pagesCanvasData: PageData = pageData;
+
+ const page = pagesCanvasData.page;
+
+ if (page === undefined) {
+ throw json("Page not found", {
+ status: 404,
+ });
+ }
+
+ const assetBaseUrl = "${ASSETS_BASE}";
+ const imageBaseUrl = "${ASSETS_BASE}";
+
+ const params: Data["params"] = {
+ assetBaseUrl,
+ imageBaseUrl,
+ };
+
+ const data: RootPropsData = {
+ build: pagesCanvasData.build,
+ assets: pagesCanvasData.assets,
+ page,
+ pages: pagesCanvasData.pages,
+ params,
+ };
+
+ return <InstanceRoot data={data} components={components} utils={utils} />;
+};
+
+export default Outlet;
+`;
+};
diff --git a/apps/cli/src/__generated__/templates.ts b/apps/cli/src/__generated__/templates.ts
new file mode 100644
index 0000000000..917e9948b1
--- /dev/null
+++ b/apps/cli/src/__generated__/templates.ts
@@ -0,0 +1,42 @@
+/*
+
+This is an auto-generated file. Please don't change manually.
+If needed to make any changes. Add them to ./templates folder and run pnpm run build:templates
+
+*/
+
+import type { Folder, ProjectTarget } from "../args";
+
+export const templates: Record<ProjectTarget, Folder> = {
+ defaults: {
+ name: "defaults",
+ files: [
+ {
+ name: "package.json",
+ content:
+ '{\n "private": true,\n "sideEffects": false,\n "scripts": {\n "build": "remix build",\n "dev": "remix dev",\n "start": "remix-serve build",\n "typecheck": "tsc"\n },\n "dependencies": {\n "@remix-run/css-bundle": "^1.19.2",\n "@remix-run/node": "^1.19.2",\n "@remix-run/react": "^1.19.2",\n "@webstudio-is/react-sdk": "^0.82.0",\n "@webstudio-is/sdk-components-react-remix": "^0.82.0",\n "@webstudio-is/sdk-components-react": "^0.82.0",\n "@webstudio-is/form-handlers": "^0.75.0",\n "isbot": "^3.6.8",\n "react": "^18.2.0",\n "react-dom": "^18.2.0"\n },\n "devDependencies": {\n "@remix-run/serve": "^1.19.2",\n "@remix-run/dev": "^1.19.2",\n "@remix-run/eslint-config": "^1.19.2",\n "@types/react": "^18.0.35",\n "@types/react-dom": "^18.0.11",\n "eslint": "^8.38.0",\n "typescript": "^5.0.4"\n },\n "engines": {\n "node": ">=18.0.0"\n }\n}\n',
+ encoding: "utf-8",
+ },
+ {
+ name: "remix.config.js",
+ content:
+ '/** @type {import(\'@remix-run/dev\').AppConfig} */\nmodule.exports = {\n ignoredRouteFiles: ["**/.*"],\n serverModuleFormat: "cjs",\n serverDependenciesToBundle: [\n /@webstudio-is\\/(?!prisma-client)/,\n "nanoevents",\n "nanostores",\n "@nanostores/react",\n ],\n future: {\n v2_errorBoundary: true,\n v2_headers: true,\n v2_meta: true,\n v2_normalizeFormMethod: true,\n v2_routeConvention: true,\n },\n};\n',
+ encoding: "utf-8",
+ },
+ ],
+ subFolders: [
+ {
+ name: "app",
+ files: [
+ {
+ name: "root.tsx",
+ content:
+ 'export { Root as default } from "@webstudio-is/react-sdk";\n',
+ encoding: "utf-8",
+ },
+ ],
+ subFolders: [],
+ },
+ ],
+ },
+};
diff --git a/apps/cli/src/args.ts b/apps/cli/src/args.ts
index d80902a7af..676f4f939c 100644
--- a/apps/cli/src/args.ts
+++ b/apps/cli/src/args.ts
@@ -10,6 +10,7 @@ export const showHelp = () =>
Commands:
link Link to an existing webstudio project
sync Sync the linked webstudio project with the latest build
+ build Build the linked webstudio project with a remix template.
Flags:
--help -h Show this help message
@@ -26,7 +27,7 @@ type DefaultArgs = Pick<
"values"
>;
-type Commands = "link" | "sync";
+type Commands = "link" | "sync" | "build";
export type Command = (
args: DefaultArgs & { positionals: string[] }
@@ -45,4 +46,27 @@ export const CLI_ARGS_OPTIONS = {
type: "boolean" as const,
short: "h",
},
+ type: {
+ type: "string" as const,
+ short: "t",
+ default: "defaults",
+ },
+};
+
+export type File = {
+ name: string;
+ content: string;
+ encoding: "utf-8";
+};
+
+export type Folder = {
+ name: string;
+ files: File[];
+ subFolders: Folder[];
+};
+
+export type ProjectTarget = "defaults";
+
+export const SupportedProjects: Record<ProjectTarget, boolean> = {
+ defaults: true,
};
diff --git a/apps/cli/src/cli.ts b/apps/cli/src/cli.ts
index d310475ab4..8f2d450b29 100644
--- a/apps/cli/src/cli.ts
+++ b/apps/cli/src/cli.ts
@@ -4,6 +4,7 @@ import { GLOBAL_CONFIG_FILE } from "./config";
import { ensureFileInPath } from "./fs-utils";
import { link } from "./commands/link";
import { sync } from "./commands/sync";
+import { build } from "./commands/build";
import { showHelp, CLI_ARGS_OPTIONS } from "./args";
import type { SupportedCommands } from "./args";
import packageJSON from "../package.json" assert { type: "json" };
@@ -11,6 +12,7 @@ import packageJSON from "../package.json" assert { type: "json" };
const commands: SupportedCommands = {
link,
sync,
+ build,
};
export const main = async () => {
diff --git a/apps/cli/src/commands/build.ts b/apps/cli/src/commands/build.ts
new file mode 100644
index 0000000000..6911ad15ba
--- /dev/null
+++ b/apps/cli/src/commands/build.ts
@@ -0,0 +1,35 @@
+import { writeFile, access } from "node:fs/promises";
+import { cwd } from "node:process";
+import { join } from "node:path";
+import { ensureFileInPath } from "../fs-utils";
+import type { Command, Folder } from "../args";
+import { prebuild } from "../prebuild";
+import { templates } from "../__generated__/templates";
+import { LOCAL_DATA_FILE } from "../config";
+
+export const build: Command = async () => {
+ try {
+ await access(LOCAL_DATA_FILE);
+ await parseFolderAndWriteFiles(templates["defaults"], cwd());
+ await prebuild();
+ } catch (error) {
+ if (error.code === "ENOENT") {
+ throw new Error(
+ `You need to link a webstudio project before building it. Run \`webstudio link\` to link a project.`
+ );
+ }
+ throw error;
+ }
+};
+
+const parseFolderAndWriteFiles = async (folder: Folder, path: string) => {
+ for (const file of folder.files) {
+ const filePath = join(path, file.name);
+ await ensureFileInPath(filePath);
+ await writeFile(filePath, file.content, "utf8");
+ }
+
+ for (const subFolder of folder.subFolders) {
+ await parseFolderAndWriteFiles(subFolder, join(path, subFolder.name));
+ }
+};
diff --git a/apps/cli/src/config.ts b/apps/cli/src/config.ts
index de2c170006..f0b97478ed 100644
--- a/apps/cli/src/config.ts
+++ b/apps/cli/src/config.ts
@@ -11,6 +11,8 @@ export const GLOBAL_CONFIG_FILE = join(
export const LOCAL_CONFIG_FILE = ".webstudio/config.json";
export const LOCAL_DATA_FILE = ".webstudio/data.json";
+export const ASSETS_BASE = "/assets/";
+
export type LocalConfig = {
projectId: string;
};
diff --git a/apps/cli/src/fs-utils.ts b/apps/cli/src/fs-utils.ts
index 7c78dbd470..6f47bab901 100644
--- a/apps/cli/src/fs-utils.ts
+++ b/apps/cli/src/fs-utils.ts
@@ -4,7 +4,6 @@ import {
mkdir,
writeFile,
constants,
- rm,
readFile,
} from "node:fs/promises";
@@ -28,17 +27,6 @@ export const ensureFolderExists = async (folderPath: string) => {
}
};
-export const deleteFolderIfExists = async (generatedDir: string) => {
- try {
- await rm(generatedDir, { recursive: true });
- } catch (error) {
- if (error.code === "ENOENT") {
- return;
- }
- throw error;
- }
-};
-
export const loadJSONFile = async <T>(filePath: string): Promise<T | null> => {
try {
const content = await readFile(filePath, "utf8");
diff --git a/apps/cli/src/prebuild.ts b/apps/cli/src/prebuild.ts
new file mode 100644
index 0000000000..22c4e95c82
--- /dev/null
+++ b/apps/cli/src/prebuild.ts
@@ -0,0 +1,254 @@
+import { join, relative, dirname } from "node:path";
+import { writeFileSync } from "node:fs";
+import { rm, mkdir } from "node:fs/promises";
+import {
+ generateCssText,
+ generateUtilsExport,
+ type Params,
+ type Data,
+} from "@webstudio-is/react-sdk";
+import {
+ findTreeInstanceIds,
+ type Instance,
+ type Prop,
+ type Build,
+ type Page,
+} from "@webstudio-is/project-build";
+import * as baseComponentMetas from "@webstudio-is/sdk-components-react/metas";
+import * as remixComponentMetas from "@webstudio-is/sdk-components-react-remix/metas";
+import type { Asset, ImageAsset } from "@webstudio-is/asset-uploader";
+
+import { getRouteTemplate } from "./__generated__/router";
+import { ASSETS_BASE, LOCAL_DATA_FILE } from "./config";
+import { ensureFileInPath, ensureFolderExists, loadJSONFile } from "./fs-utils";
+
+type ComponentsByPage = {
+ [path: string]: Set<string>;
+};
+
+type SiteDataByPage = {
+ [path: string]: {
+ page: Page;
+ build: Pick<Build, "props" | "instances" | "dataSources" | "deployment">;
+ assets: Array<Asset>;
+ params?: Params;
+ pages: Array<Page>;
+ };
+};
+
+type RemixRoutes = {
+ routes: Array<{
+ path: string;
+ file: string;
+ }>;
+};
+
+export const prebuild = async () => {
+ const appRoot = "app";
+
+ const routesDir = join(appRoot, "routes");
+ await rm(routesDir, { recursive: true, force: true });
+ await mkdir(routesDir, { recursive: true });
+
+ const generatedDir = join(appRoot, "__generated__");
+ await rm(generatedDir, { recursive: true, force: true });
+ await mkdir(generatedDir, { recursive: true });
+
+ await ensureFolderExists(join("public", ASSETS_BASE));
+
+ const siteData = await loadJSONFile<
+ Data & { user?: { email: string | null } }
+ >(LOCAL_DATA_FILE);
+
+ if (siteData === null) {
+ throw new Error(
+ `Project data is missing, please make sure you the project is synced.`
+ );
+ }
+
+ const {
+ assets,
+ build: { deployment },
+ } = siteData;
+ const fontAssets: Data["assets"] = [];
+ const imageAssets: ImageAsset[] = [];
+
+ for (const asset of assets) {
+ if (asset.type === "image") {
+ imageAssets.push(asset);
+ }
+
+ if (asset.type === "font") {
+ fontAssets.push(asset);
+ }
+ }
+
+ const remixRoutes: RemixRoutes = {
+ routes: [],
+ };
+
+ const componentsByPage: ComponentsByPage = {};
+ const siteDataByPage: SiteDataByPage = {};
+
+ const componentMetas = new Map(
+ Object.entries({ ...baseComponentMetas, ...remixComponentMetas })
+ );
+
+ for (const page of Object.values(siteData.pages)) {
+ const originPath = page.path;
+ const path = originPath === "" ? "index" : originPath.replace("/", "");
+
+ if (path !== "index") {
+ remixRoutes.routes.push({
+ path: originPath === "" ? "/" : originPath,
+ file: `routes/${path}.tsx`,
+ });
+ }
+
+ const instanceMap = new Map(siteData.build.instances);
+ const pageInstanceSet = findTreeInstanceIds(
+ instanceMap,
+ page.rootInstanceId
+ );
+ const instances: [Instance["id"], Instance][] =
+ siteData.build.instances.filter(([id]) => pageInstanceSet.has(id));
+
+ const props: [Prop["id"], Prop][] = [];
+ for (const [_propId, prop] of siteData.build.props) {
+ if (pageInstanceSet.has(prop.instanceId)) {
+ props.push([prop.id, prop]);
+ }
+ }
+
+ siteDataByPage[path] = {
+ build: {
+ props,
+ instances,
+ dataSources: siteData.build.dataSources,
+ },
+ pages: siteData.pages,
+ page,
+ assets: siteData.assets,
+ };
+
+ componentsByPage[path] = new Set();
+ for (const [_instanceId, instance] of instances) {
+ if (instance.component) {
+ componentsByPage[path].add(instance.component);
+ }
+ }
+ }
+
+ const cssText = generateCssText(
+ {
+ assets: siteData.assets,
+ breakpoints: siteData.build?.breakpoints,
+ styles: siteData.build?.styles,
+ styleSourceSelections: siteData.build?.styleSourceSelections,
+ componentMetas,
+ },
+ {
+ assetBaseUrl: ASSETS_BASE,
+ }
+ );
+
+ await ensureFileInPath(join(generatedDir, "index.css"), cssText);
+
+ for (const [pathName, pageComponents] of Object.entries(componentsByPage)) {
+ let relativePath = "../__generated__";
+ const statements = Array.from(pageComponents).join(", ");
+ const pageData = siteDataByPage[pathName];
+
+ const utilsExport = generateUtilsExport({
+ page: pageData.page,
+ metas: componentMetas,
+ instances: new Map(pageData.build.instances),
+ props: new Map(pageData.build.props),
+ dataSources: new Map(pageData.build.dataSources),
+ });
+
+ const pageExports = `/* This is a auto generated file for building the project */ \n
+ import type { PageData } from "~/routes/template";
+ import type { Components } from "@webstudio-is/react-sdk";
+ import * as sdk from "@webstudio-is/react-sdk";
+ import { ${statements} } from "@webstudio-is/sdk-components-react";
+ import * as remixComponents from "@webstudio-is/sdk-components-react-remix";
+ export const components = new Map(Object.entries(Object.assign({ ${statements} }, remixComponents ))) as Components;
+ export const fontAssets = ${JSON.stringify(fontAssets)};
+ export const pageData: PageData = ${JSON.stringify(pageData)};
+ export const user: { email: string | null } | undefined = ${JSON.stringify(
+ siteData.user
+ )};
+ export const projectId = "${siteData.build.projectId}";
+
+ ${utilsExport}
+ `;
+
+ /* Changing the pathName to index for the index page, so that remix will use the index.tsx file as index:true in the manifest file.
+
+ It is generated by @remix-run/cloudflare somewhere here (https://github.com/remix-run/remix/blob/8851599c47f5d372fb537026a9ee0931a8753262/packages/remix-react/routes.tsx#L50). If there was no index.ts file, the manifest file containing all the routing was incorrect and nothing responded to root (/) requests. That is why the main file is renamed to index so Remix will use it as /.
+
+ */
+ pathName === "main" ? "index" : pathName;
+
+ const fileLocationGeneratedDir = join(generatedDir, pathName);
+ const fileLocationRoutesDir = join(routesDir, pathName);
+
+ if (pathName !== "index") {
+ // If the pathName is not index, we need to create the directory structure for the generated files, set the relative path to the generated directory
+ if (!pathName.includes("/")) {
+ await ensureFolderExists(fileLocationRoutesDir);
+ await ensureFolderExists(fileLocationGeneratedDir);
+
+ relativePath = relative(fileLocationRoutesDir, generatedDir);
+ } else {
+ const dirnameRoutesDir = dirname(fileLocationRoutesDir);
+ relativePath = relative(dirnameRoutesDir, generatedDir);
+ }
+ }
+ if (!pathName.includes("/") && pathName !== "index") {
+ // As there could be pages with /blog and with /blog/post1, we need to create the index.tsx file for the /blog directory, and not blog.tsx in the parent directory
+ writeFileSync(
+ join(fileLocationGeneratedDir, `index.ts`),
+ pageExports,
+ "utf8"
+ );
+
+ let routeIndexFile = getRouteTemplate();
+
+ routeIndexFile = routeIndexFile.replace(
+ "../__generated__/index",
+ `${relativePath}/${pathName}/index`
+ );
+ routeIndexFile = routeIndexFile.replace(
+ "../__generated__/index.css",
+ `${relativePath}/index.css`
+ );
+
+ writeFileSync(
+ join(fileLocationRoutesDir, `index.tsx`),
+ routeIndexFile,
+ "utf8"
+ );
+ } else {
+ writeFileSync(join(generatedDir, `${pathName}.ts`), pageExports, "utf8");
+
+ let routeFile = getRouteTemplate();
+
+ routeFile = routeFile.replace(
+ "../__generated__/index",
+ `${relativePath}/${pathName}`
+ );
+ routeFile = routeFile.replace(
+ "../__generated__/index.css",
+ `${relativePath}/index.css`
+ );
+
+ writeFileSync(join(routesDir, `_${pathName}.tsx`), routeFile, "utf8");
+ }
+ }
+
+ if (deployment?.projectDomain === undefined) {
+ throw new Error("Project is not deployed yet, cannot download assets");
+ }
+};
diff --git a/apps/cli/templates/build.ts b/apps/cli/templates/build.ts
new file mode 100644
index 0000000000..f610fd3a4f
--- /dev/null
+++ b/apps/cli/templates/build.ts
@@ -0,0 +1,116 @@
+import { readdirSync, lstatSync, readFileSync, writeFileSync } from "node:fs";
+import { rm } from "node:fs/promises";
+import { join } from "node:path";
+import { type Folder, SupportedProjects } from "../src/args";
+import { ensureFileInPath } from "../src/fs-utils";
+
+const TEMPLATES_TO_BUILD = Object.keys(SupportedProjects);
+const TEMPLATES_JSON: Record<string, Folder> = {};
+const TEMPLATES_JSON_PATH = new URL(
+ "../src/__generated__/templates.ts",
+ import.meta.url
+).pathname;
+const ROUTER_TEMPLATE_PATH = new URL(
+ "../src/__generated__/router.ts",
+ import.meta.url
+).pathname;
+
+console.info("Building Templates...");
+await rm(new URL("../src/__generated__", import.meta.url).pathname, {
+ recursive: true,
+ force: true,
+});
+
+const parseFolder = (folderPath: string): Folder | undefined => {
+ const isDirectory = lstatSync(folderPath).isDirectory();
+ if (isDirectory === false) {
+ return;
+ }
+
+ const folderName = folderPath.split("/").pop();
+ if (folderName === undefined) {
+ return;
+ }
+
+ const folder: Folder = {
+ name: folderName,
+ files: [],
+ subFolders: [],
+ };
+
+ const files = readdirSync(folderPath);
+
+ for (const file of files) {
+ const filePath = join(folderPath, file);
+ const statSync = lstatSync(filePath);
+ const isDirectory = statSync.isDirectory();
+ const isFile = statSync.isFile();
+
+ if (isDirectory) {
+ const subFolder = parseFolder(filePath);
+ if (subFolder !== undefined) {
+ folder.subFolders.push(subFolder);
+ }
+ }
+
+ if (isFile) {
+ const content = readFileSync(filePath, "utf-8");
+ folder.files.push({
+ name: file,
+ content,
+ encoding: "utf-8",
+ });
+ }
+ }
+
+ return folder;
+};
+
+await ensureFileInPath(TEMPLATES_JSON_PATH);
+
+for (const template of TEMPLATES_TO_BUILD) {
+ const templatePath = new URL(`./${template}`, import.meta.url).pathname;
+ const templateFiles = parseFolder(templatePath);
+ if (templateFiles === undefined) {
+ throw new Error(`Template ${template} not found`);
+ }
+ TEMPLATES_JSON[template] = templateFiles;
+}
+
+const content = `/*
+
+This is an auto-generated file. Please don't change manually.
+If needed to make any changes. Add them to ./templates folder and run pnpm run build:templates
+
+*/
+
+import type { Folder, ProjectTarget } from "../args"\n
+export const templates: Record<ProjectTarget, Folder> = ${JSON.stringify(
+ TEMPLATES_JSON,
+ null,
+ 2
+)}`;
+
+writeFileSync(TEMPLATES_JSON_PATH, content, "utf-8");
+
+/*
+ Building route template
+*/
+const routeTemplateFile = readFileSync(
+ new URL("./route-template.ts", import.meta.url).pathname,
+ "utf-8"
+);
+const routeTemplateContent = `/*
+
+This is an auto-generated file. Please don't change manually.
+If needed to make any changes. Add them to ./templates folder and run pnpm run build:templates
+
+*/
+
+import { ASSETS_BASE } from "../config";
+
+export const getRouteTemplate = () => {
+ return \`${routeTemplateFile.replace(/ASSETS_BASE/g, '"${ASSETS_BASE}"')}\`
+ }`;
+
+await ensureFileInPath(ROUTER_TEMPLATE_PATH, routeTemplateContent);
diff --git a/apps/cli/templates/defaults/app/root.tsx b/apps/cli/templates/defaults/app/root.tsx
new file mode 100644
index 0000000000..d873875663
--- /dev/null
+++ b/apps/cli/templates/defaults/app/root.tsx
@@ -0,0 +1 @@
+export { Root as default } from "@webstudio-is/react-sdk";
diff --git a/apps/cli/templates/defaults/package.json b/apps/cli/templates/defaults/package.json
new file mode 100644
index 0000000000..fd0bc3f0e4
--- /dev/null
+++ b/apps/cli/templates/defaults/package.json
@@ -0,0 +1,34 @@
+{
+ "private": true,
+ "sideEffects": false,
+ "scripts": {
+ "build": "remix build",
+ "dev": "remix dev",
+ "start": "remix-serve build",
+ "typecheck": "tsc"
+ },
+ "dependencies": {
+ "@remix-run/css-bundle": "^1.19.2",
+ "@remix-run/node": "^1.19.2",
+ "@remix-run/react": "^1.19.2",
+ "@webstudio-is/react-sdk": "^0.82.0",
+ "@webstudio-is/sdk-components-react-remix": "^0.82.0",
+ "@webstudio-is/sdk-components-react": "^0.82.0",
+ "@webstudio-is/form-handlers": "^0.75.0",
+ "isbot": "^3.6.8",
+ "react": "^18.2.0",
+ "react-dom": "^18.2.0"
+ },
+ "devDependencies": {
+ "@remix-run/serve": "^1.19.2",
+ "@remix-run/dev": "^1.19.2",
+ "@remix-run/eslint-config": "^1.19.2",
+ "@types/react": "^18.0.35",
+ "@types/react-dom": "^18.0.11",
+ "eslint": "^8.38.0",
+ "typescript": "^5.0.4"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+}
diff --git a/apps/cli/templates/defaults/remix.config.js b/apps/cli/templates/defaults/remix.config.js
new file mode 100644
index 0000000000..b2da45dbbb
--- /dev/null
+++ b/apps/cli/templates/defaults/remix.config.js
@@ -0,0 +1,18 @@
+/** @type {import('@remix-run/dev').AppConfig} */
+module.exports = {
+ ignoredRouteFiles: ["**/.*"],
+ serverModuleFormat: "cjs",
+ serverDependenciesToBundle: [
+ /@webstudio-is\/(?!prisma-client)/,
+ "nanoevents",
+ "nanostores",
+ "@nanostores/react",
+ ],
+ future: {
+ v2_errorBoundary: true,
+ v2_headers: true,
+ v2_meta: true,
+ v2_normalizeFormMethod: true,
+ v2_routeConvention: true,
+ },
+};
diff --git a/apps/cli/templates/route-template.ts b/apps/cli/templates/route-template.ts
new file mode 100644
index 0000000000..d250af4164
--- /dev/null
+++ b/apps/cli/templates/route-template.ts
@@ -0,0 +1,133 @@
+import {
+ V2_MetaFunction,
+ LinksFunction,
+ LinkDescriptor,
+ ActionArgs,
+ json,
+} from "@remix-run/node";
+
+import {
+ InstanceRoot,
+ type RootPropsData,
+ type Data,
+} from "@webstudio-is/react-sdk";
+import { n8nHandler, hasMatchingForm } from "@webstudio-is/form-handlers";
+
+import {
+ fontAssets,
+ components,
+ pageData,
+ user,
+ projectId,
+ utils,
+} from "../__generated__/index";
+import css from "../__generated__/index.css";
+
+export type PageData = Omit<Data, "build"> & {
+ build: Pick<Data["build"], "props" | "instances" | "dataSources">;
+};
+
+export const meta: V2_MetaFunction = () => {
+ const { page } = pageData;
+ return [{ title: page?.title || "Webstudio", ...page?.meta }];
+};
+
+export const links: LinksFunction = () => {
+ const result: LinkDescriptor[] = [];
+
+ result.push({
+ rel: "stylesheet",
+ href: css,
+ });
+
+ for (const asset of fontAssets) {
+ if (asset.type === "font") {
+ result.push({
+ rel: "preload",
+ href: ASSETS_BASE + asset.name,
+ as: "font",
+ crossOrigin: "anonymous",
+ // @todo add mimeType
+ // type: asset.mimeType,
+ });
+ }
+ }
+
+ return result;
+};
+
+const getRequestHost = (request: Request): string =>
+ request.headers.get("x-forwarded-host") || request.headers.get("host") || "";
+
+export const action = async ({ request, context }: ActionArgs) => {
+ const formData = await request.formData();
+
+ // We're throwing rather than returning \`{ success: false }\`
+ // because this isn't supposed to happen normally: bug or malicious user
+ if (hasMatchingForm(formData, pageData.build.instances) === false) {
+ throw json("Form not found", { status: 404 });
+ }
+
+ const email = user?.email;
+
+ if (email == null) {
+ return { success: false };
+ }
+
+ // wrapped in try/catch just in cases \`new URL()\` throws
+ // (should not happen)
+ let pageUrl: URL;
+ try {
+ pageUrl = new URL(request.url);
+ pageUrl.host = getRequestHost(request);
+ } catch {
+ return { success: false };
+ }
+
+ const formInfo = {
+ formData,
+ projectId,
+ pageUrl: pageUrl.toString(),
+ toEmail: email,
+ fromEmail: pageUrl.hostname + "@webstudio.email",
+ };
+
+ const result = await n8nHandler({
+ formInfo,
+ hookUrl: context.N8N_FORM_EMAIL_HOOK as string,
+ });
+
+ return result;
+};
+
+const Outlet = () => {
+ const pagesCanvasData: PageData = pageData;
+
+ const page = pagesCanvasData.page;
+
+ if (page === undefined) {
+ throw json("Page not found", {
+ status: 404,
+ });
+ }
+
+ const assetBaseUrl = ASSETS_BASE;
+ const imageBaseUrl = ASSETS_BASE;
+
+ const params: Data["params"] = {
+ assetBaseUrl,
+ imageBaseUrl,
+ };
+
+ const data: RootPropsData = {
+ build: pagesCanvasData.build,
+ assets: pagesCanvasData.assets,
+ page,
+ pages: pagesCanvasData.pages,
+ params,
+ };
+
+ return <InstanceRoot data={data} components={components} utils={utils} />;
+};
+
+export default Outlet;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 5387539b4a..867f17c7d3 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -358,9 +358,24 @@ importers:
apps/cli:
dependencies:
+ '@webstudio-is/asset-uploader':
+ specifier: workspace:^
+ version: link:../../packages/asset-uploader
'@webstudio-is/http-client':
specifier: workspace:^
version: link:../../packages/http-client
+ '@webstudio-is/project-build':
+ specifier: workspace:^
+ version: link:../../packages/project-build
+ '@webstudio-is/react-sdk':
+ specifier: workspace:^
+ version: link:../../packages/react-sdk
+ '@webstudio-is/sdk-components-react':
+ specifier: workspace:^
+ version: link:../../packages/sdk-components-react
+ '@webstudio-is/sdk-components-react-remix':
+ specifier: workspace:^
+ version: link:../../packages/sdk-components-react-remix
env-paths:
specifier: ^3.0.0
version: 3.0.0
@@ -380,6 +395,9 @@ importers:
'@webstudio-is/tsconfig':
specifier: workspace:^
version: link:../../packages/tsconfig
+ tsx:
+ specifier: ^3.12.6
+ version: 3.12.6
packages/asset-uploader:
dependencies:
@@ -7678,7 +7696,7 @@ packages:
cssesc: 3.0.0
csstype: 3.1.1
deep-object-diff: 1.1.9
- deepmerge: 4.3.0
+ deepmerge: 4.3.1
media-query-parser: 2.0.2
outdent: 0.8.0
dev: true
@@ -8992,8 +9010,8 @@ packages:
resolution: {integrity: sha512-Rn+RuwkmkDwCi2/oXOFS9Gsr5lJZu/yTGpK7wAaAIE75CC+LCGEZHpY6VQJa/RoJcrmaA/docWJZvYohlNkWPA==}
dev: true
- resolution: {integrity: sha512-z2wJZXrmeHdvYJp/Ux55wIjqo81G5Bp4c+oELTW+7ar6SogWHajt5a9gO3s3IDaGSAXjDk0vlQKN3rms8ab3og==}
+ resolution: {integrity: sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==}
engines: {node: '>=0.10.0'}
@@ -11317,7 +11335,7 @@ packages:
babel-jest: 29.6.2(@babel/[email protected])
chalk: 4.1.2
ci-info: 3.8.0
- deepmerge: 4.3.0
+ deepmerge: 4.3.1
glob: 7.2.3
graceful-fs: 4.2.10
jest-circus: 29.6.2
@@ -11356,7 +11374,7 @@ packages:
babel-jest: 29.6.2(@babel/[email protected])
chalk: 4.1.2
ci-info: 3.8.0
- deepmerge: 4.3.0
+ deepmerge: 4.3.1
glob: 7.2.3
graceful-fs: 4.2.10
jest-circus: 29.6.2