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.

refactor: convert page meta fields into expressions (#2853)

Bogdan Chadkin84fc906721ea
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/custom-metadata.stories.tsx b/apps/builder/app/builder/features/sidebar-left/panels/pages/custom-metadata.stories.tsx
index cbbde4f8a1..bc8f12cdfc 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/custom-metadata.stories.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/custom-metadata.stories.tsx
@@ -14,7 +14,11 @@ export const Basic = () => {
return (
<Box css={{ width: 448, margin: 20 }}>
- <CustomMetadata customMetas={customMetas} onChange={setCustomMetas} />
+ <CustomMetadata
+ variableValues={new Map()}
+ customMetas={customMetas}
+ onChange={setCustomMetas}
+ />
</Box>
);
};
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/custom-metadata.tsx b/apps/builder/app/builder/features/sidebar-left/panels/pages/custom-metadata.tsx
index ff5bb05f03..597cca91bf 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/custom-metadata.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/custom-metadata.tsx
@@ -10,6 +10,7 @@ import {
} from "@webstudio-is/design-system";
import { DeleteIcon, PlusIcon } from "@webstudio-is/icons";
import { useId } from "react";
+import { computeExpression } from "~/shared/nano-states";
type Meta = {
property: string;
@@ -17,11 +18,13 @@ type Meta = {
};
type CustomMetadataProps = {
+ variableValues: Map<string, unknown>;
customMetas: Meta[];
onChange: (value: Meta[]) => void;
};
const PropertyContent = (props: {
+ variableValues: Map<string, unknown>;
property: string;
content: string;
onDelete: () => void;
@@ -30,6 +33,8 @@ const PropertyContent = (props: {
const propertyId = useId();
const contentId = useId();
+ const content = computeExpression(props.content, props.variableValues);
+
return (
<Grid
gap={2}
@@ -68,9 +73,9 @@ const PropertyContent = (props: {
tabIndex={1}
id={contentId}
property="path"
- value={props.content}
+ value={content}
onChange={(event) => {
- props.onChange(props.property, event.target.value);
+ props.onChange(props.property, JSON.stringify(event.target.value));
}}
/>
</InputErrorsTooltip>
@@ -137,6 +142,7 @@ export const CustomMetadata = (props: CustomMetadataProps) => {
{props.customMetas.map((meta, index) => (
<PropertyContent
key={index}
+ variableValues={props.variableValues}
property={meta.property}
content={meta.content}
onChange={(property, content) => {
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/page-settings.tsx b/apps/builder/app/builder/features/sidebar-left/panels/pages/page-settings.tsx
index 73b5815ea2..7be962947e 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/page-settings.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/page-settings.tsx
@@ -1,5 +1,11 @@
import { z } from "zod";
-import { type FocusEventHandler, useState, useCallback, Fragment } from "react";
+import {
+ type FocusEventHandler,
+ useState,
+ useCallback,
+ Fragment,
+ useMemo,
+} from "react";
import { useStore } from "@nanostores/react";
import { useDebouncedCallback } from "use-debounce";
import { useUnmount } from "react-use";
@@ -62,6 +68,7 @@ import {
$selectedInstanceSelector,
$dataSources,
$dataSourceVariables,
+ computeExpression,
} from "~/shared/nano-states";
import { nanoid } from "nanoid";
import { serverSyncStore } from "~/shared/sync";
@@ -84,16 +91,16 @@ const fieldDefaultValues = {
name: "Untitled",
parentFolderId: ROOT_FOLDER_ID,
path: "/untitled",
- title: "Untitled",
- description: "",
isHomePage: false,
- excludePageFromSearch: false,
- socialImageUrl: "",
+ title: `"Untitled"`,
+ description: `""`,
+ excludePageFromSearch: `false`,
+ socialImageUrl: `""`,
socialImageAssetId: "",
customMetas: [
{
property: "",
- content: "",
+ content: `""`,
},
],
};
@@ -296,6 +303,7 @@ const FormFields = ({
const assets = useStore($assets);
const pages = useStore($pages);
const dataSourceVariables = useStore($dataSourceVariables);
+ const variableValues = useMemo(() => new Map(), []);
if (pages === undefined) {
return;
@@ -330,6 +338,17 @@ const FormFields = ({
.replace(/\/+/g, "/");
const pageUrl = `https://${pageDomainAndPath}`;
+ const title = String(computeExpression(values.title, variableValues));
+ const description = String(
+ computeExpression(values.description, variableValues)
+ );
+ const socialImageUrl = String(
+ computeExpression(values.socialImageUrl, variableValues)
+ );
+ const excludePageFromSearch = Boolean(
+ computeExpression(values.excludePageFromSearch, variableValues)
+ );
+
return (
<Grid css={{ height: "100%" }}>
<ScrollArea>
@@ -519,8 +538,8 @@ const FormFields = ({
siteName={pages?.meta?.siteName ?? ""}
faviconUrl={faviconUrl}
pageUrl={pageUrl}
- titleLink={values.title}
- snippet={values.description}
+ titleLink={title}
+ snippet={description}
/>
</Box>
</Box>
@@ -537,9 +556,12 @@ const FormFields = ({
name="title"
placeholder="My awesome project - About"
disabled={disabled}
- value={values.title}
+ value={title}
onChange={(event) => {
- onChange({ field: "title", value: event.target.value });
+ onChange({
+ field: "title",
+ value: JSON.stringify(event.target.value),
+ });
}}
/>
</InputErrorsTooltip>
@@ -554,9 +576,12 @@ const FormFields = ({
id={fieldIds.description}
name="description"
disabled={disabled}
- value={values.description}
+ value={description}
onChange={(value) => {
- onChange({ field: "description", value });
+ onChange({
+ field: "description",
+ value: JSON.stringify(value),
+ });
}}
autoGrow
maxRows={10}
@@ -565,11 +590,12 @@ const FormFields = ({
<Grid flow={"column"} gap={1} justify={"start"} align={"center"}>
<Checkbox
id={fieldIds.excludePageFromSearch}
- checked={values.excludePageFromSearch}
+ checked={excludePageFromSearch}
onCheckedChange={() => {
+ const newValue = !excludePageFromSearch;
onChange({
field: "excludePageFromSearch",
- value: !values.excludePageFromSearch,
+ value: newValue.toString(),
});
}}
/>
@@ -599,11 +625,11 @@ const FormFields = ({
{isFeatureEnabled("cms") && (
<InputField
placeholder="https://www.url.com"
- value={values.socialImageUrl}
+ value={socialImageUrl}
onChange={(event) => {
onChange({
field: "socialImageUrl",
- value: event.target.value,
+ value: JSON.stringify(event.target.value),
});
onChange({ field: "socialImageAssetId", value: "" });
}}
@@ -645,17 +671,18 @@ const FormFields = ({
ogImageUrl={
socialImageAsset?.type === "image"
? socialImageAsset.name
- : values.socialImageUrl
+ : socialImageUrl
}
ogUrl={pageUrl}
- ogTitle={values.title}
- ogDescription={values.description}
+ ogTitle={title}
+ ogDescription={description}
/>
</Grid>
<Separator />
<CustomMetadata
+ variableValues={variableValues}
customMetas={values.customMetas}
onChange={(customMetas) => {
onChange({
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/page-utils.test.ts b/apps/builder/app/builder/features/sidebar-left/panels/pages/page-utils.test.ts
index 292f5e8a5b..989bbf6f01 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/page-utils.test.ts
+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/page-utils.test.ts
@@ -33,7 +33,7 @@ describe("toTreeData", () => {
name: "Home",
path: "",
rootInstanceId: "id",
- title: "Home",
+ title: `"Home"`,
},
id: "homePageId",
type: "page",
@@ -69,7 +69,7 @@ describe("toTreeData", () => {
name: "Home",
path: "",
rootInstanceId: "id",
- title: "Home",
+ title: `"Home"`,
},
id: "homePageId",
type: "page",
@@ -96,7 +96,7 @@ describe("toTreeData", () => {
name: "Page",
path: "/page",
rootInstanceId: "id",
- title: "Page",
+ title: `"Page"`,
});
pages.folders.push({
id: "folderId",
@@ -121,7 +121,7 @@ describe("toTreeData", () => {
name: "Home",
path: "",
rootInstanceId: "id",
- title: "Home",
+ title: `"Home"`,
},
id: "homePageId",
type: "page",
@@ -141,7 +141,7 @@ describe("toTreeData", () => {
name: "Page",
path: "/page",
rootInstanceId: "id",
- title: "Page",
+ title: `"Page"`,
},
},
],
@@ -183,7 +183,7 @@ describe("toTreeData", () => {
id: "homePageId",
name: "Home",
path: "",
- title: "Home",
+ title: `"Home"`,
meta: {},
rootInstanceId: "id",
},
@@ -222,7 +222,7 @@ describe("reparentOrphansMutable", () => {
name: "Page",
path: "/page",
rootInstanceId: "rootInstanceId",
- title: "Page",
+ title: `"Page"`,
});
pages.folders.push({
id: "folderId",
@@ -476,7 +476,7 @@ describe("getExistingRoutePaths", () => {
name: "Page",
path: "/page",
rootInstanceId: "rootInstanceId",
- title: "Page",
+ title: `"Page"`,
});
pages.pages.push({
@@ -485,7 +485,7 @@ describe("getExistingRoutePaths", () => {
name: "Blog",
path: "/blog/:id",
rootInstanceId: "rootInstanceId",
- title: "Blog",
+ title: `"Blog"`,
});
const result = getExistingRoutePaths(pages);
diff --git a/apps/builder/app/shared/nano-states/props.test.ts b/apps/builder/app/shared/nano-states/props.test.ts
index af62526a7c..980ab79c23 100644
--- a/apps/builder/app/shared/nano-states/props.test.ts
+++ b/apps/builder/app/shared/nano-states/props.test.ts
@@ -9,6 +9,7 @@ import { $instances } from "./instances";
import {
$propValuesByInstanceSelector,
$variableValuesByInstanceSelector,
+ computeExpression,
} from "./props";
import { $pages, $selectedPageId } from "./pages";
import {
@@ -830,3 +831,7 @@ test("stop variables lookup outside of slots", () => {
cleanStores($variableValuesByInstanceSelector);
});
+
+test("compute expression when invalid syntax", () => {
+ expect(computeExpression("https://github.com", new Map())).toEqual(undefined);
+});
diff --git a/apps/builder/app/shared/nano-states/props.ts b/apps/builder/app/shared/nano-states/props.ts
index ad57f3ed11..3fd2c47021 100644
--- a/apps/builder/app/shared/nano-states/props.ts
+++ b/apps/builder/app/shared/nano-states/props.ts
@@ -132,7 +132,7 @@ const $dataSourcesLogic = computed(
}
);
-const computeExpression = (
+export const computeExpression = (
expression: string,
variables: Map<DataSource["id"], unknown>
) => {
@@ -141,12 +141,12 @@ const computeExpression = (
const identifier = encodeDataSourceVariable(id);
code += `const ${identifier} = ${JSON.stringify(value)};\n`;
}
- const transpiled = validateExpression(expression, {
- effectful: true,
- optional: true,
- });
- code += `return (${transpiled})`;
try {
+ const transpiled = validateExpression(expression, {
+ effectful: true,
+ optional: true,
+ });
+ code += `return (${transpiled})`;
const result = new Function(code)();
return result;
} catch {
diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.ts
index cad67d929f..240a0f70f0 100644
--- a/packages/cli/src/prebuild.ts
+++ b/packages/cli/src/prebuild.ts
@@ -29,6 +29,7 @@ import {
generateResourcesLoader,
collectionComponent,
generatePageMeta,
+ executeExpression,
} from "@webstudio-is/react-sdk";
import type {
Instance,
@@ -563,7 +564,7 @@ export const user: { email: string | null } | undefined = ${JSON.stringify(
)};
export const projectId = "${siteData.build.projectId}";
-${generatePageMeta({ page: pageData.page, dataSources })}
+${generatePageMeta({ scope, page: pageData.page, dataSources })}
${pageComponent}
@@ -620,7 +621,12 @@ ${utilsExport}
export const sitemap = ${JSON.stringify(
{
pages: siteData.pages
- .filter((page) => page.meta.excludePageFromSearch !== true)
+ // ignore pages with excludePageFromSearch bound to variables
+ // because there is no data from cms available at build time
+ .filter(
+ (page) =>
+ executeExpression(page.meta.excludePageFromSearch) !== true
+ )
.map((page) => ({
path: page.path,
lastModified: siteData.build.updatedAt,
diff --git a/packages/prisma-client/prisma/migrations/20240131200102_page_meta_expressions/migration.ts b/packages/prisma-client/prisma/migrations/20240131200102_page_meta_expressions/migration.ts
new file mode 100644
index 0000000000..a8f395de05
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20240131200102_page_meta_expressions/migration.ts
@@ -0,0 +1,168 @@
+import { PrismaClient } from "./client";
+
+type Folder = {
+ id: string;
+ name: string;
+ slug: string;
+ children: string[];
+};
+
+type Page = {
+ path: string;
+ id: string;
+ name: string;
+ title: string;
+ meta: {
+ description?: string;
+ title?: string;
+ // convert boolean to expression
+ excludePageFromSearch?: any;
+ socialImageAssetId?: string;
+ socialImageUrl?: string;
+ custom?: Array<{
+ property: string;
+ content: string;
+ }>;
+ };
+ rootInstanceId: string;
+ pathVariableId?: string;
+};
+
+type ProjectMeta = {
+ siteName?: string;
+ faviconAssetId?: string;
+ code?: string;
+};
+
+type PageRedirectSchema = {
+ old: string;
+ new: string;
+};
+
+type ProjectSettings = {
+ atomicStyles?: boolean;
+ redirects?: PageRedirectSchema[];
+};
+
+type Pages = {
+ meta?: ProjectMeta;
+ settings?: ProjectSettings;
+ homePage: Page;
+ pages: Page[];
+ folders: Folder[];
+};
+
+/**
+ * convert all fields to js expression
+ * string -> `"string"`
+ * false -> `false`
+ * undefined -> undefined
+ */
+const mutatePageMeta = (page: Page) => {
+ page.title = JSON.stringify(page.title);
+ page.meta.description = JSON.stringify(page.meta.description);
+ page.meta.excludePageFromSearch = JSON.stringify(
+ page.meta.excludePageFromSearch
+ );
+ page.meta.socialImageUrl = JSON.stringify(page.meta.socialImageUrl);
+ page.meta.description = JSON.stringify(page.meta.description);
+ if (page.meta.custom) {
+ for (const item of page.meta.custom) {
+ item.content = JSON.stringify(item.content);
+ }
+ }
+};
+
+export default async () => {
+ const client = new PrismaClient({
+ // Uncomment to see the queries in console as the migration runs
+ // log: ["query", "info", "warn", "error"],
+ });
+
+ await client.$transaction(
+ async (prisma) => {
+ const chunkSize = 1000;
+ let cursor: undefined | string = undefined;
+ let hasNext = true;
+
+ while (hasNext) {
+ console.log("CHUNK", cursor);
+ console.time("read");
+
+ const cursorOptions: {} = cursor
+ ? {
+ skip: 1, // Skip the cursor
+ cursor: { id: cursor },
+ }
+ : {};
+
+ const builds = await prisma.build.findMany({
+ select: {
+ id: true,
+ pages: true,
+ },
+ take: chunkSize,
+ orderBy: {
+ id: "asc",
+ },
+ where: {
+ AND: [
+ {
+ deployment: null,
+ },
+ ],
+ },
+
+ ...cursorOptions,
+ });
+ console.timeEnd("read");
+
+ console.time("parse-change");
+ cursor = builds.at(-1)?.id;
+ hasNext = builds.length === chunkSize;
+ const changedBuilds: typeof builds = [];
+
+ for (const build of builds) {
+ const buildId = build.id;
+ try {
+ const pages: Pages = JSON.parse(build.pages);
+
+ mutatePageMeta(pages.homePage);
+ for (const page of pages.pages) {
+ mutatePageMeta(page);
+ }
+
+ build.pages = JSON.stringify(pages);
+ changedBuilds.push(build);
+ } catch {
+ console.info(`build ${buildId} cannot be converted`);
+ }
+ }
+ console.timeEnd("parse-change");
+ console.log("changedBuilds.length", changedBuilds.length);
+ console.time("update");
+
+ const sql = `
+ UPDATE "Build"
+ SET
+ "pages" = data."pages"
+ FROM unnest(ARRAY[$1], ARRAY[$2]) as data(id, pages)
+ WHERE "Build"."id" = data."id"
+ `;
+
+ if (changedBuilds.length === 0) {
+ return;
+ }
+ const res = await prisma.$executeRawUnsafe(
+ sql,
+ changedBuilds.map((changedBuild) => changedBuild.id),
+ changedBuilds.map((changedBuild) => changedBuild.pages)
+ );
+
+ console.timeEnd("update");
+ console.log("res", res);
+ }
+ },
+ { timeout: 3600000 }
+ );
+};
diff --git a/packages/prisma-client/prisma/migrations/20240131200102_page_meta_expressions/schema.prisma b/packages/prisma-client/prisma/migrations/20240131200102_page_meta_expressions/schema.prisma
new file mode 100644
index 0000000000..6dfb9fb1d3
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20240131200102_page_meta_expressions/schema.prisma
@@ -0,0 +1,317 @@
+// DO NOT EDIT THIS FILE!
+// This is a copy of your schema.prisma that corresponds to the state of the database
+// when all migrations up until this one are applied.
+// It's used to generate a Prisma Client for the migration.
+
+// This is your Prisma schema file,
+// learn more about it in the docs: https://pris.ly/d/prisma-schema
+
+generator client {
+ provider = "prisma-client-js"
+ previewFeatures = ["views"]
+ // see commands.ts
+ output = "client"
+}
+
+datasource db {
+ provider = "postgres"
+ url = env("DATABASE_URL")
+ directUrl = env("DIRECT_URL")
+}
+
+model Team {
+ id String @id @default(uuid())
+ users User[]
+}
+
+enum UploadStatus {
+ UPLOADING
+ UPLOADED
+}
+
+model File {
+ name String @id
+ format String
+ size Int
+ description String?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @default(now()) @updatedAt
+ meta String @default("{}")
+ status UploadStatus @default(UPLOADING)
+ isDeleted Boolean @default(false)
+ uploaderProject Project? @relation(fields: [uploaderProjectId], references: [id])
+ uploaderProjectId String?
+ assets Asset[]
+}
+
+model Asset {
+ id String @default(uuid()) // not unique!
+ projectId String
+ file File @relation(fields: [name], references: [name])
+ name String
+ Project Project[]
+ DashboardProject DashboardProject[]
+
+ @@id([id, projectId])
+}
+
+model User {
+ id String @id @default(uuid())
+ email String? @unique
+ provider String?
+ image String?
+ username String?
+ createdAt DateTime @default(now())
+ team Team? @relation(fields: [teamId], references: [id])
+ teamId String?
+ projects Project[]
+ clientReferences ClientReferences[]
+ checkout TransactionLog[]
+ products UserProduct[]
+}
+
+// User client references in external services like stripe etc
+model ClientReferences {
+ reference String @default(dbgenerated())
+ service String
+ createdAt DateTime @default(now())
+ user User @relation(fields: [userId], references: [id])
+ userId String
+
+ @@id([userId, service])
+ @@unique([reference, service])
+}
+
+model Product {
+ id String @id
+ name String
+ description String?
+ features String[]
+ images String[]
+ meta Json
+
+ createdAt DateTime @default(now())
+ checkout TransactionLog[]
+ userProducts UserProduct[]
+}
+
+model TransactionLog {
+ // Stripe event id (debug and idempotency purposes)
+ eventId String @id
+ userId String?
+ user User? @relation(fields: [userId], references: [id])
+
+ productId String?
+ product Product? @relation(fields: [productId], references: [id])
+
+ createdAt DateTime @default(now())
+
+ eventData Json? @default(dbgenerated())
+
+ eventType String? @default(dbgenerated())
+ eventCreated Int? @default(dbgenerated())
+
+ // paid
+ status String? @default(dbgenerated())
+
+ customerId String? @default(dbgenerated())
+ customerEmail String? @default(dbgenerated())
+
+ subscriptionId String? @default(dbgenerated())
+
+ // Used for Refund
+ paymentIntent String? @default(dbgenerated())
+
+ @@unique([eventId, productId])
+}
+
+view UserProduct {
+ userId String
+ user User @relation(fields: [userId], references: [id])
+ productId String
+ product Product @relation(fields: [productId], references: [id])
+ // subscriptionId and customerId not null for subscriptions
+ subscriptionId String?
+ customerId String?
+ // Easier to debug
+ customerEmail String?
+
+ @@unique([userId, productId])
+}
+
+model Project {
+ id String @id @default(uuid())
+ createdAt DateTime @default(now())
+ title String
+ domain String @unique
+ user User? @relation(fields: [userId], references: [id])
+ userId String?
+ build Build[]
+ isDeleted Boolean @default(false)
+ files File[]
+ projectDomain ProjectDomain[]
+ latestBuild LatestBuildPerProject?
+ authorizationToken AuthorizationToken[]
+ previewImageAsset Asset? @relation(fields: [previewImageAssetId, id], references: [id, projectId])
+ previewImageAssetId String?
+
+ @@unique([id, isDeleted])
+ @@unique([domain, isDeleted])
+ @@unique([id, domain])
+}
+
+enum PublishStatus {
+ PENDING
+ PUBLISHED
+ FAILED
+}
+
+model Build {
+ id String @unique @default(uuid())
+ version Int @default(0)
+ lastTransactionId String?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @default(now()) @updatedAt
+ pages String
+
+ project Project @relation(fields: [projectId], references: [id])
+ projectId String
+
+ breakpoints String @default("[]")
+ styles String @default("[]")
+ styleSources String @default("[]")
+ styleSourceSelections String @default("[]")
+ props String @default("[]")
+ dataSources String @default("[]")
+ resources String @default("[]")
+ instances String @default("[]")
+
+ deployment String?
+ publishStatus PublishStatus @default(PENDING)
+
+ @@id([id, projectId])
+}
+
+enum AuthorizationRelation {
+ viewers
+ editors
+ builders
+ administrators
+}
+
+model AuthorizationToken {
+ token String @default(uuid())
+ projectId String
+ project Project @relation(fields: [projectId], references: [id])
+ name String @default("")
+ relation AuthorizationRelation @default(viewers)
+ createdAt DateTime @default(now())
+
+ @@id([token, projectId])
+ @@unique([token])
+}
+
+enum DomainStatus {
+ INITIALIZING
+ ACTIVE
+ ERROR
+ PENDING
+}
+
+// Domains + last known status and last known txtRecord
+// In the future we can update this table using queue, n8n or temporal workflows.
+// As of now updates are done during UI interactions
+model Domain {
+ id String @id @default(uuid())
+ domain String @unique
+ createdAt DateTime @default(now())
+ updatedAt DateTime @default(now()) @updatedAt
+
+ ProjectDomain ProjectDomain[]
+ // Last known txtRecord of the domain (to check domain ownership)
+ txtRecord String?
+ // create, init, pending, active, error
+ status DomainStatus @default(INITIALIZING)
+ // In case of status="error", this will contain the error message
+ error String?
+
+ projectWithDomain ProjectWithDomain[]
+}
+
+model ProjectDomain {
+ projectId String
+ project Project @relation(fields: [projectId], references: [id])
+ domainId String
+ domain Domain @relation(fields: [domainId], references: [id])
+ createdAt DateTime @default(now())
+ // Generated txt record to check domain ownership
+ txtRecord String @unique @default(uuid())
+
+ // CNAME record to point to the domain
+ cname String
+
+ @@id([projectId, domainId])
+ @@index([domainId])
+}
+
+view ProjectWithDomain {
+ projectId String
+
+ domainId String
+ domain Domain @relation(fields: [domainId], references: [id])
+ txtRecord String
+
+ createdAt DateTime
+
+ // CNAME record to point to the domain
+ cname String
+
+ verified Boolean
+ // To count statistics per user
+ userId String?
+
+ // We can deploy on per domain basis, here for each project domain we have latest build
+ latestBuid LatestBuildPerProjectDomain?
+
+ @@id([projectId, domainId])
+}
+
+view LatestBuildPerProjectDomain {
+ domainId String
+ buildId String
+ projectId String
+ projectWithDomain ProjectWithDomain @relation(fields: [projectId, domainId], references: [projectId, domainId])
+
+ isLatestBuild Boolean
+ publishStatus PublishStatus
+ updatedAt DateTime
+
+ @@id([projectId, domainId])
+}
+
+view LatestBuildPerProject {
+ buildId String
+
+ projectId String
+ domain String
+ project Project @relation(fields: [projectId, domain], references: [id, domain])
+
+ isLatestBuild Boolean
+ publishStatus PublishStatus
+ updatedAt DateTime
+
+ @@id([projectId, domain])
+}
+
+// Dashboard
+view DashboardProject {
+ id String @id @default(uuid())
+ createdAt DateTime @default(now())
+ title String
+ domain String
+ userId String?
+ previewImageAsset Asset? @relation(fields: [previewImageAssetId, id], references: [id, projectId])
+ previewImageAssetId String?
+ isDeleted Boolean @default(false)
+ isPublished Boolean
+}
diff --git a/packages/project-build/src/shared/pages-utils.test.ts b/packages/project-build/src/shared/pages-utils.test.ts
index 93f75341cd..9882b4008b 100644
--- a/packages/project-build/src/shared/pages-utils.test.ts
+++ b/packages/project-build/src/shared/pages-utils.test.ts
@@ -13,7 +13,7 @@ test("createDefaultPages", () => {
id: "homePageId",
name: "Home",
path: "",
- title: "Home",
+ title: `"Home"`,
meta: {},
rootInstanceId: "rootInstanceId",
},
diff --git a/packages/project-build/src/shared/pages-utils.ts b/packages/project-build/src/shared/pages-utils.ts
index 2f4bff7c56..459308f7ba 100644
--- a/packages/project-build/src/shared/pages-utils.ts
+++ b/packages/project-build/src/shared/pages-utils.ts
@@ -27,7 +27,7 @@ export const createDefaultPages = ({
id: homePageId,
name: "Home",
path: homePagePath,
- title: "Home",
+ title: `"Home"`,
meta: {},
rootInstanceId,
},
diff --git a/packages/react-sdk/src/expression.test.ts b/packages/react-sdk/src/expression.test.ts
index 04e0bb05e7..278b70d981 100644
--- a/packages/react-sdk/src/expression.test.ts
+++ b/packages/react-sdk/src/expression.test.ts
@@ -2,6 +2,7 @@ import { expect, test } from "@jest/globals";
import {
decodeDataSourceVariable,
encodeDataSourceVariable,
+ executeExpression,
validateExpression,
} from "./expression";
@@ -158,3 +159,9 @@ test("encode/decode variable names", () => {
);
expect(decodeDataSourceVariable("myVarName")).toEqual(undefined);
});
+
+test("execute expression", () => {
+ expect(executeExpression(undefined)).toEqual(undefined);
+ expect(executeExpression("1 + 1")).toEqual(2);
+ expect(executeExpression("someVariable + 1")).toEqual(undefined);
+});
diff --git a/packages/react-sdk/src/expression.ts b/packages/react-sdk/src/expression.ts
index 1e6ec443a6..cf94b2a523 100644
--- a/packages/react-sdk/src/expression.ts
+++ b/packages/react-sdk/src/expression.ts
@@ -209,3 +209,12 @@ export const generateExpression = ({
},
});
};
+
+export const executeExpression = (expression: undefined | string) => {
+ try {
+ const fn = new Function(`return (${expression})`);
+ return fn();
+ } catch {
+ // empty block
+ }
+};
diff --git a/packages/react-sdk/src/index.ts b/packages/react-sdk/src/index.ts
index 4c11454f85..8599fa6d75 100644
--- a/packages/react-sdk/src/index.ts
+++ b/packages/react-sdk/src/index.ts
@@ -21,6 +21,7 @@ export {
validateExpression,
encodeDataSourceVariable,
decodeDataSourceVariable,
+ executeExpression,
} from "./expression";
export { getIndexesWithinAncestors } from "./instance-utils";
export * from "./hook";
diff --git a/packages/react-sdk/src/page-meta-generator.test.ts b/packages/react-sdk/src/page-meta-generator.test.ts
index 7298194731..59759c4bec 100644
--- a/packages/react-sdk/src/page-meta-generator.test.ts
+++ b/packages/react-sdk/src/page-meta-generator.test.ts
@@ -1,15 +1,17 @@
import { expect, test } from "@jest/globals";
import { generatePageMeta } from "./page-meta-generator";
+import { createScope } from "@webstudio-is/sdk";
test("generate minimal static page meta factory", () => {
expect(
generatePageMeta({
+ scope: createScope(),
page: {
id: "",
name: "",
path: "",
rootInstanceId: "",
- title: "Page title",
+ title: `"Page title"`,
meta: {},
},
dataSources: new Map(),
@@ -36,19 +38,20 @@ test("generate minimal static page meta factory", () => {
test("generate complete static page meta factory", () => {
expect(
generatePageMeta({
+ scope: createScope(),
page: {
id: "",
name: "",
path: "",
rootInstanceId: "",
- title: "Page title",
+ title: `"Page title"`,
meta: {
- description: "Page description",
- excludePageFromSearch: true,
+ description: `"Page description"`,
+ excludePageFromSearch: "true",
socialImageAssetId: "social-image-name",
custom: [
- { property: "custom-property-1", content: "custom content 1" },
- { property: "custom-property-2", content: "custom content 2" },
+ { property: "custom-property-1", content: `"custom content 1"` },
+ { property: "custom-property-2", content: `"custom content 2"` },
],
},
},
@@ -84,14 +87,15 @@ test("generate complete static page meta factory", () => {
test("generate asset url instead of id", () => {
expect(
generatePageMeta({
+ scope: createScope(),
page: {
id: "",
name: "",
path: "",
rootInstanceId: "",
- title: "Page title",
+ title: `"Page title"`,
meta: {
- socialImageUrl: "https://my-image",
+ socialImageUrl: `"https://my-image"`,
},
},
dataSources: new Map(),
@@ -118,16 +122,17 @@ test("generate asset url instead of id", () => {
test("generate custom meta ignoring empty property name", () => {
expect(
generatePageMeta({
+ scope: createScope(),
page: {
id: "",
name: "",
path: "",
rootInstanceId: "",
- title: "Page title",
+ title: `"Page title"`,
meta: {
custom: [
- { property: "custom-property", content: "custom content 1" },
- { property: "", content: "custom content 2" },
+ { property: "custom-property", content: `"custom content 1"` },
+ { property: "", content: `"custom content 2"` },
],
},
},
diff --git a/packages/react-sdk/src/page-meta-generator.ts b/packages/react-sdk/src/page-meta-generator.ts
index b87a2b0d7e..bcd3d7f045 100644
--- a/packages/react-sdk/src/page-meta-generator.ts
+++ b/packages/react-sdk/src/page-meta-generator.ts
@@ -1,4 +1,5 @@
-import type { Asset, DataSources, Page } from "@webstudio-is/sdk";
+import type { Asset, DataSources, Page, Scope } from "@webstudio-is/sdk";
+import { generateExpression } from "./expression";
export type PageMeta = {
title: string;
@@ -10,20 +11,37 @@ export type PageMeta = {
};
export const generatePageMeta = ({
+ scope,
page,
+ dataSources,
}: {
+ scope: Scope;
page: Page;
dataSources: DataSources;
}) => {
- const titleExpression = JSON.stringify(page.title);
- const descriptionExpression = JSON.stringify(page.meta.description);
- const excludePageFromSearchExpression = JSON.stringify(
- page.meta.excludePageFromSearch
- );
+ const titleExpression = generateExpression({
+ expression: page.title,
+ dataSources,
+ scope,
+ });
+ const descriptionExpression = generateExpression({
+ expression: page.meta.description ?? "undefined",
+ dataSources,
+ scope,
+ });
+ const excludePageFromSearchExpression = generateExpression({
+ expression: page.meta.excludePageFromSearch ?? "undefined",
+ dataSources,
+ scope,
+ });
const socialImageAssetIdExpression = JSON.stringify(
page.meta.socialImageAssetId
);
- const socialImageUrlExpression = JSON.stringify(page.meta.socialImageUrl);
+ const socialImageUrlExpression = generateExpression({
+ expression: page.meta.socialImageUrl ?? "undefined",
+ dataSources,
+ scope,
+ });
let generated = "";
generated += `export const getPageMeta = ({}: {\n`;
generated += ` params: Record<string, undefined | string>;\n`;
@@ -42,7 +60,11 @@ export const generatePageMeta = ({
continue;
}
const propertyExpression = JSON.stringify(customMeta.property);
- const contentExpression = JSON.stringify(customMeta.content);
+ const contentExpression = generateExpression({
+ scope,
+ dataSources,
+ expression: customMeta.content,
+ });
generated += ` {\n`;
generated += ` property: ${propertyExpression},\n`;
generated += ` content: ${contentExpression},\n`;
diff --git a/packages/sdk/src/schema/pages.ts b/packages/sdk/src/schema/pages.ts
index d2d5fb53e3..092d71c095 100644
--- a/packages/sdk/src/schema/pages.ts
+++ b/packages/sdk/src/schema/pages.ts
@@ -43,7 +43,7 @@ const commonPageFields = {
meta: z.object({
description: z.string().optional(),
title: z.string().optional(),
- excludePageFromSearch: z.boolean().optional(),
+ excludePageFromSearch: z.string().optional(),
socialImageAssetId: z.string().optional(),
socialImageUrl: z.string().optional(),
custom: z