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.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
Publish tracking (#1726)
Ivan Starkov5e439b77e525
diff --git a/apps/builder/app/builder/features/topbar/add-domain.tsx b/apps/builder/app/builder/features/topbar/add-domain.tsxindex 8ac693e430..ca2e79a939 100644--- a/apps/builder/app/builder/features/topbar/add-domain.tsx+++ b/apps/builder/app/builder/features/topbar/add-domain.tsx@@ -23,20 +23,22 @@ type DomainsAddProps = {input: { projectId: Project["id"] },onSuccess: () => void) => void;- domainLoadingState: "idle" | "submitting";+ domainState: "idle" | "submitting";+ isPublishing: boolean;};export const AddDomain = ({projectId,onCreate,refreshDomainResult,- domainLoadingState,+ domainState,+ isPublishing,}: DomainsAddProps) => {const id = useId();const {send: create,- state,- error: createSystemError,+ state: сreateState,+ error: сreateSystemError,} = trpc.create.useMutation();const [isOpen, setIsOpen] = useState(false);const [domain, setDomain] = useState("");@@ -95,7 +97,9 @@ export const AddDomain = ({autoFocusplaceholder="your-domain.com"value={domain}- disabled={state !== "idle" || domainLoadingState !== "idle"}+ disabled={+ isPublishing || сreateState !== "idle" || domainState !== "idle"+ }onKeyDown={(event) => {if (event.key === "Enter") {handleCreate();@@ -117,10 +121,10 @@ export const AddDomain = ({<Text color="destructive">{error}</Text></>)}- {createSystemError !== undefined && (+ {сreateSystemError !== undefined && (<>{/* Something happened with network, api etc */}- <Text color="destructive">{createSystemError}</Text>+ <Text color="destructive">{сreateSystemError}</Text><Text color="subtle">Please try again later</Text></>)}@@ -128,7 +132,9 @@ export const AddDomain = ({)}<Button- disabled={state !== "idle" || domainLoadingState !== "idle"}+ disabled={+ isPublishing || сreateState !== "idle" || domainState !== "idle"+ }color={isOpen ? "primary" : "neutral"}css={{ width: "100%", flexShrink: 0 }}onClick={() => {diff --git a/apps/builder/app/builder/features/topbar/domains.tsx b/apps/builder/app/builder/features/topbar/domains.tsxindex 03e48aff18..c53dcadd4f 100644--- a/apps/builder/app/builder/features/topbar/domains.tsx+++ b/apps/builder/app/builder/features/topbar/domains.tsx@@ -24,10 +24,13 @@ import type { DomainStatus } from "@webstudio-is/prisma-client";import { CollapsibleDomainSection } from "./collapsible-domain-section";import env from "~/shared/env";import { useCallback, useEffect, useState } from "react";+import type { PublishStatus } from "@webstudio-is/prisma-client";+// eslint-disable-next-line import/no-internal-modules+import formatDistance from "date-fns/formatDistance";const trpc = createTrpcFetchProxy<DomainRouter>(builderDomainsPath);-type Domain = {+export type Domain = {projectId: Project["id"];domain: {domain: string;@@ -38,6 +41,14 @@ type Domain = {txtRecord: string;cname: string;verified: boolean;+ latestBuid: null | {+ projectId: string;+ buildId: string;+ isLatestBuild: boolean;+ publishStatus: PublishStatus;+ updatedAt: string;+ domainId: string;+ };};const InputEllipsis = styled(InputField, {@@ -74,6 +85,39 @@ export const getStatus = (projectDomain: Domain) =>? (`VERIFIED_${projectDomain.domain.status}` as const): `UNVERIFIED`;+export const PENDING_TIMEOUT = 60 * 3 * 1000;++export const getPublishStatusAndText = ({+ updatedAt,+ publishStatus,+}: Pick<NonNullable<Domain["latestBuid"]>, "updatedAt" | "publishStatus">) => {+ let status = publishStatus;++ const delta = Date.now() - new Date(updatedAt).getTime();+ // Assume build failed after 3 minutes++ if (publishStatus === "PENDING" && delta > PENDING_TIMEOUT) {+ status = "FAILED";+ }++ const textStart =+ status === "PUBLISHED"+ ? "Published"+ : status === "FAILED"+ ? "Publish failed"+ : "Publishing started";++ const statusText = `${textStart} ${formatDistance(+ new Date(updatedAt),+ new Date(),+ {+ addSuffix: true,+ }+ )}`;++ return { statusText, status };+};+const getStatusText = (props: {projectDomain: Domain;isLoading: boolean;@@ -96,7 +140,16 @@ const getStatusText = (props: {break;case "VERIFIED_ACTIVE":isVerifiedActive = true;- text = "Status: Active";+ text = "Status: Active, not published";++ if (props.projectDomain.latestBuid !== null) {+ const publishText = getPublishStatusAndText(+ props.projectDomain.latestBuid+ );++ text = publishText.statusText;+ isVerifiedActive = publishText.status !== "FAILED";+ }break;case "VERIFIED_ERROR":text = props.projectDomain.domain.error ?? text;@@ -149,7 +202,8 @@ const DomainItem = (props: {input: { projectId: Project["id"] },onSuccess?: () => void) => void;- domainLoadingState: "idle" | "submitting";+ domainState: "idle" | "submitting";+ isPublishing: boolean;}) => {const {send: verify,@@ -175,12 +229,12 @@ const DomainItem = (props: {const [isStatusLoading, setIsStatusLoading] = useState(true);const isRemoveInProgress =- removeState !== "idle" || props.domainLoadingState !== "idle";+ removeState !== "idle" || props.domainState !== "idle";const isCheckStateInProgress =verifyState !== "idle" ||updateStatusState !== "idle" ||- props.domainLoadingState !== "idle";+ props.domainState !== "idle";const status = props.projectDomain.verified? (`VERIFIED_${props.projectDomain.domain.status}` as `VERIFIED_${DomainStatus}`)@@ -335,7 +389,7 @@ const DomainItem = (props: {<Text color="destructive">{verifySystemError}</Text>)}<Button- disabled={isCheckStateInProgress}+ disabled={props.isPublishing || isCheckStateInProgress}color="primary"css={{ width: "100%", flexShrink: 0, mt: theme.spacing[3] }}onClick={handleVerify}@@ -354,7 +408,7 @@ const DomainItem = (props: {<Text color="destructive">{updateStatusError}</Text>)}<Button- disabled={isCheckStateInProgress}+ disabled={props.isPublishing || isCheckStateInProgress}color="primary"css={{ width: "100%", flexShrink: 0, mt: theme.spacing[3] }}onClick={handleUpdateStatus}@@ -373,7 +427,7 @@ const DomainItem = (props: {)}<Button- disabled={isRemoveInProgress}+ disabled={props.isPublishing || isRemoveInProgress}color="neutral"css={{ width: "100%", flexShrink: 0 }}onClick={() => {@@ -485,14 +539,16 @@ type DomainsProps = {input: { projectId: Project["id"] },onSuccess?: () => void) => void;- domainLoadingState: "idle" | "submitting";+ domainState: "idle" | "submitting";+ isPublishing: boolean;};export const Domains = ({newDomains,domains,refreshDomainResult,- domainLoadingState,+ domainState,+ isPublishing,}: DomainsProps) => {return (<>@@ -502,7 +558,8 @@ export const Domains = ({projectDomain={projectDomain}initiallyOpen={newDomains.has(projectDomain.domain.domain)}refreshDomainResult={refreshDomainResult}- domainLoadingState={domainLoadingState}+ domainState={domainState}+ isPublishing={isPublishing}/>))}</>diff --git a/apps/builder/app/builder/features/topbar/publish.tsx b/apps/builder/app/builder/features/topbar/publish.tsxindex 15a88f6712..e9296ad629 100644--- a/apps/builder/app/builder/features/topbar/publish.tsx+++ b/apps/builder/app/builder/features/topbar/publish.tsx@@ -1,4 +1,4 @@-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect, useMemo, useState } from "react";import {Button,useId,@@ -16,6 +16,7 @@ import {InputField,Separator,ScrollArea,+ Box,} from "@webstudio-is/design-system";import { useIsPublishDialogOpen } from "../../shared/nano-states";import { validateProjectDomain, type Project } from "@webstudio-is/project";@@ -23,7 +24,13 @@ import { getPublishedUrl } from "~/shared/router-utils";import { theme } from "@webstudio-is/design-system";import { useAuthPermit } from "~/shared/nano-states";import { isFeatureEnabled } from "@webstudio-is/feature-flags";-import { Domains, getStatus } from "./domains";+import {+ Domains,+ getPublishStatusAndText,+ getStatus,+ type Domain,+ PENDING_TIMEOUT,+} from "./domains";import { CollapsibleDomainSection } from "./collapsible-domain-section";import {CheckCircleIcon,@@ -37,9 +44,34 @@ import { AddDomain } from "./add-domain";const trpc = createTrpcFetchProxy<DomainRouter>(builderDomainsPath);-type PublishButtonProps = { project: Project };+type ProjectData =+ | {+ success: true;+ project: Project;+ }+ | {+ success: false;+ error: string;+ };++type ChangeProjectDomainProps = {+ project: Project;+ projectState: "idle" | "submitting";+ isPublishing: boolean;+ projectLoad: (+ props: { projectId: Project["id"] },+ callback: (projectData: ProjectData) => void+ ) => void;+};++type TimeoutId = undefined | ReturnType<typeof setTimeout>;-const ChangeProjectDomain = (props: PublishButtonProps) => {+const ChangeProjectDomain = ({+ project,+ projectLoad,+ projectState,+ isPublishing,+}: ChangeProjectDomainProps) => {const id = useId();const {@@ -48,24 +80,12 @@ const ChangeProjectDomain = (props: PublishButtonProps) => {error: updateProjectSystemError,} = trpc.updateProjectDomain.useMutation();- const {- load: loadProject,- data: projectData,- state: projectState,- error: projectSystemError,- } = trpc.project.useQuery();-- const [domain, setDomain] = useState(props.project.domain);+ const [domain, setDomain] = useState(project.domain);const [error, setError] = useState<string>();- let project = props.project;- if (projectData?.success) {- project = projectData.project;- }-const refreshProject = useCallback(() =>- loadProject({ projectId: props.project.id }, (projectData) => {+ projectLoad({ projectId: project.id }, (projectData) => {if (projectData?.success === false) {setError(projectData.error);return;@@ -73,7 +93,7 @@ const ChangeProjectDomain = (props: PublishButtonProps) => {setDomain(projectData.project.domain);}),- [loadProject, props.project.id]+ [projectLoad, project.id]);useEffect(() => {@@ -107,32 +127,20 @@ const ChangeProjectDomain = (props: PublishButtonProps) => {});};- if (projectSystemError !== undefined) {- return (- <Flex- css={{- m: theme.spacing[9],- overflowWrap: "anywhere",- }}- gap={2}- direction={"column"}- >- <Text color="destructive">{projectSystemError}</Text>- <Text color="subtle">Please try again later</Text>- </Flex>- );- }-- if (projectData === undefined) {- return <div />;- }+ const { statusText, status } =+ project.latestBuild != null+ ? getPublishStatusAndText(project.latestBuild)+ : {+ statusText: "Not published",+ status: "PENDING",+ };return (<CollapsibleDomainSectiontitle={publishedUrl.host}suffix={<Grid flow="column">- <Tooltip content={error !== undefined ? error : "Everything is ok"}>+ <Tooltip content={error !== undefined ? error : statusText}><Flexalign={"center"}justify={"center"}@@ -141,12 +149,16 @@ const ChangeProjectDomain = (props: PublishButtonProps) => {width: theme.spacing[12],height: theme.spacing[12],color:- error !== undefined+ error !== undefined || status === "FAILED"? theme.colors.foregroundDestructive: theme.colors.foregroundSuccessText,}}>- {error !== undefined ? <AlertIcon /> : <CheckCircleIcon />}+ {error !== undefined || status === "FAILED" ? (+ <AlertIcon />+ ) : (+ <CheckCircleIcon />+ )}</Flex></Tooltip>@@ -172,7 +184,9 @@ const ChangeProjectDomain = (props: PublishButtonProps) => {placeholder="Domain"value={domain}disabled={- updateProjectDomainState !== "idle" || projectState !== "idle"+ isPublishing ||+ updateProjectDomainState !== "idle" ||+ projectState !== "idle"}onChange={(event) => {setError(undefined);@@ -208,11 +222,19 @@ const ChangeProjectDomain = (props: PublishButtonProps) => {};const Publish = ({- projectId,- domains,+ project,+ domainsToPublish,+ refresh,++ isPublishing,+ setIsPublishing,}: {- projectId: Project["id"];- domains: string[];+ project: Project;+ domainsToPublish: Domain[];+ refresh: () => void;++ isPublishing: boolean;+ setIsPublishing: (isPublishing: boolean) => void;}) => {const {send: publish,@@ -221,6 +243,34 @@ const Publish = ({error: publishSystemError,} = trpc.publish.useMutation();+ useEffect(() => {+ if (isPublishing) {+ let timeoutHandle: TimeoutId;+ let totalCalls = 0;+ const timeout = 10000;+ // Repeat few more times than timeout+ const repeat = PENDING_TIMEOUT / timeout + 5;++ // Call refresh+ const execRefresh = () => {+ if (totalCalls < repeat) {+ totalCalls += 1;+ clearTimeout(timeoutHandle);+ timeoutHandle = setTimeout(() => {+ refresh();+ execRefresh();+ }, timeout);+ }+ };++ execRefresh();++ return () => {+ clearTimeout(timeoutHandle);+ };+ }+ }, [isPublishing, refresh]);+return (<Flexcss={{@@ -241,54 +291,137 @@ const Publish = ({<Text color="destructive">{publishData.error}</Text>)}- <Button- color="positive"- disabled={publishState !== "idle"}- onClick={() => {- publish({ projectId, domains });- }}+ <Tooltip+ content={+ publishState !== "idle" || isPublishing+ ? "Publish process in progress"+ : undefined+ }>- Publish- </Button>+ <Button+ color="positive"+ disabled={publishState !== "idle" || isPublishing}+ onClick={() => {+ setIsPublishing(true);++ publish(+ {+ projectId: project.id,+ domains: domainsToPublish.map(+ (projectDomain) => projectDomain.domain.domain+ ),+ },+ () => {+ refresh();+ }+ );+ }}+ >+ Publish+ </Button>+ </Tooltip></Flex>);};-const Content = (props: PublishButtonProps) => {+const Content = (props: { projectId: Project["id"] }) => {const [newDomains, setNewDomains] = useState(new Set<string>());const {data: domainsResult,- load: refreshDomainResult,- state: domainLoadingState,+ load: domainRefresh,+ state: domainState,+ error: domainSystemError,} = trpc.findMany.useQuery();+ const {+ load: projectLoad,+ data: projectData,+ state: projectState,+ error: projectSystemError,+ } = trpc.project.useQuery();+useEffect(() => {- refreshDomainResult({ projectId: props.project.id });- }, [refreshDomainResult, props.project.id]);-- // In the future we would allow to select what domains to publish,- // now we just publish all verified and active domains- const domainsToPublish = domainsResult?.success- ? domainsResult.data- .filter(- (projectDomain) => getStatus(projectDomain) === "VERIFIED_ACTIVE"- )- .map((projectDomain) => projectDomain.domain.domain)- : [];+ projectLoad({ projectId: props.projectId });+ domainRefresh({ projectId: props.projectId });+ }, [domainRefresh, props.projectId, projectLoad]);++ const domainsToPublish = useMemo(+ () =>+ domainsResult?.success+ ? domainsResult.data.filter(+ (projectDomain) => getStatus(projectDomain) === "VERIFIED_ACTIVE"+ )+ : [],+ [domainsResult]+ );++ const latestBuilds = useMemo(+ () => [+ projectData?.success ? projectData.project.latestBuild ?? null : null,+ ...domainsToPublish.map((domain) => domain.latestBuid),+ ],+ [domainsToPublish, projectData]+ );++ const hasPendingState = useMemo(+ () =>+ latestBuilds.some((latestBuild) => {+ if (latestBuild === null) {+ return false;+ }+ const { status } = getPublishStatusAndText(latestBuild);+ if (status === "PENDING") {+ return true;+ }+ }),+ [latestBuilds]+ );++ const [isPublishing, setIsPublishing] = useState(hasPendingState);++ useEffect(() => {+ setIsPublishing(hasPendingState);+ }, [hasPendingState, setIsPublishing]);return (<><ScrollArea>- <ChangeProjectDomain project={props.project} />+ {projectSystemError !== undefined && (+ <Flex+ css={{+ m: theme.spacing[9],+ overflowWrap: "anywhere",+ }}+ gap={2}+ direction={"column"}+ >+ <Text color="destructive">{projectSystemError}</Text>+ <Text color="subtle">Please try again later</Text>+ </Flex>+ )}++ {projectData?.success && (+ <ChangeProjectDomain+ projectLoad={projectLoad}+ projectState={projectState}+ project={projectData.project}+ isPublishing={isPublishing}+ />+ )}{isFeatureEnabled("domains") && (<>+ {domainSystemError !== undefined && (+ <Text color="destructive">{domainSystemError}</Text>+ )}+{domainsResult?.success === true && (<DomainsnewDomains={newDomains}domains={domainsResult.data}- refreshDomainResult={refreshDomainResult}- domainLoadingState={domainLoadingState}+ refreshDomainResult={domainRefresh}+ domainState={domainState}+ isPublishing={isPublishing}/>)}{domainsResult?.success === false && (@@ -312,24 +445,41 @@ const Content = (props: PublishButtonProps) => {</Flex><AddDomain- projectId={props.project.id}- refreshDomainResult={refreshDomainResult}- domainLoadingState={domainLoadingState}+ projectId={props.projectId}+ refreshDomainResult={domainRefresh}+ domainState={domainState}onCreate={(domain) => {setNewDomains((prev) => {return new Set([...prev, domain]);});}}+ isPublishing={isPublishing}/></>)}- <Publish projectId={props.project.id} domains={domainsToPublish} />+ {projectData?.success === true ? (+ <Publish+ project={projectData.project}+ domainsToPublish={domainsToPublish}+ refresh={() => {+ projectLoad({ projectId: props.projectId });+ domainRefresh({ projectId: props.projectId });+ }}+ isPublishing={isPublishing}+ setIsPublishing={setIsPublishing}+ />+ ) : (+ <Box css={{ height: theme.spacing[8] }} />+ )}</>);};-export const PublishButton = ({ project }: PublishButtonProps) => {+type PublishProps = {+ projectId: Project["id"];+};+export const PublishButton = ({ projectId }: PublishProps) => {const [isOpen, setIsOpen] = useIsPublishDialogOpen();const [authPermit] = useAuthPermit();@@ -358,7 +508,7 @@ export const PublishButton = ({ project }: PublishButtonProps) => {}}><FloatingPanelPopoverTitle>Publish</FloatingPanelPopoverTitle>- <Content project={project} />+ <Content projectId={projectId} /></FloatingPanelPopoverContent></FloatingPanelPopover>);diff --git a/apps/builder/app/builder/features/topbar/topbar.tsx b/apps/builder/app/builder/features/topbar/topbar.tsxindex 8d28880e8c..4aefbaa354 100644--- a/apps/builder/app/builder/features/topbar/topbar.tsx+++ b/apps/builder/app/builder/features/topbar/topbar.tsx@@ -71,7 +71,7 @@ export const Topbar = ({ gridArea, project, publish }: TopbarProps) => {<SyncStatus /><PreviewButton /><ShareButton projectId={project.id} />- <PublishButton project={project} />+ <PublishButton projectId={project.id} /></ToolbarToggleGroup></Toolbar></nav>diff --git a/apps/builder/app/dashboard/dashboard.stories.tsx b/apps/builder/app/dashboard/dashboard.stories.tsxindex 84104649c2..21c830c57a 100644--- a/apps/builder/app/dashboard/dashboard.stories.tsx+++ b/apps/builder/app/dashboard/dashboard.stories.tsx@@ -40,6 +40,7 @@ export const WithProjects: ComponentStory<typeof Dashboard> = () => {userId: null,isDeleted: false,isPublished: false,+ latestBuild: null,},];const router = createRouter(<Dashboard user={user} projects={projects} />);diff --git a/apps/builder/package.json b/apps/builder/package.jsonindex 3878b5d4c3..2cd644f2e2 100644--- a/apps/builder/package.json+++ b/apps/builder/package.json@@ -58,6 +58,7 @@"@webstudio-is/sdk-components-react-remix": "workspace:^","@webstudio-is/trpc-interface": "workspace:^","colord": "^2.9.3",+ "date-fns": "^2.30.0","debug": "^4.3.4","detect-font": "^0.1.5","downshift": "^6.1.7",diff --git a/packages/domain/src/db/domain.ts b/packages/domain/src/db/domain.tsindex b5c52a4841..6c5d5e035c 100644--- a/packages/domain/src/db/domain.ts+++ b/packages/domain/src/db/domain.ts@@ -1,5 +1,11 @@import { v4 as uuid } from "uuid";-import { prisma, type Project, type Domain } from "@webstudio-is/prisma-client";+import {+ prisma,+ type Project,+ type Domain,+ type ProjectWithDomain,+ type LatestBuildPerProjectDomain,+} from "@webstudio-is/prisma-client";import {authorizeProject,type AppContext,@@ -8,13 +14,21 @@ import {import { validateDomain } from "./validate";import { cnameFromUserId } from "./cname-from-user-id";-const getProjectDomains = async (projectId: Project["id"]) =>+export type ProjectDomain = ProjectWithDomain & {+ domain: Domain;+ latestBuid: null | LatestBuildPerProjectDomain;+};++const getProjectDomains = async (+ projectId: Project["id"]+): Promise<ProjectDomain[]> =>await prisma.projectWithDomain.findMany({where: {projectId,},include: {domain: true,+ latestBuid: true,},orderBy: [{@@ -27,8 +41,7 @@ export const findMany = async (props: { projectId: Project["id"] },context: AppContext): Promise<- | { success: false; error: string }- | { success: true; data: Awaited<ReturnType<typeof getProjectDomains>> }+ { success: false; error: string } | { success: true; data: ProjectDomain[] }> => {// Only builder of the project can list domainsconst canList = await authorizeProject.hasProjectPermit(diff --git a/packages/domain/src/trpc/domain.ts b/packages/domain/src/trpc/domain.tsindex e4b2b890a9..beb8640c88 100644--- a/packages/domain/src/trpc/domain.ts+++ b/packages/domain/src/trpc/domain.ts@@ -13,6 +13,7 @@ export const domainRouter = router({.query(async ({ input, ctx }) => {try {const project = await projectDb.project.loadById(input.projectId, ctx);+return {success: true,project,@@ -28,18 +29,19 @@ export const domainRouter = router({.input(z.object({ projectId: z.string(), domains: z.array(z.string()) })).mutation(async ({ input, ctx }) => {try {+ const project = await projectDb.project.loadById(input.projectId, ctx);+const build = await createProductionBuild({projectId: input.projectId,deployment: {domains: input.domains,+ projectDomain: project.domain,},},ctx);- const project = await projectDb.project.loadById(input.projectId, ctx);-const { deploymentTrpc, env } = ctx.deployment;const result = deploymentTrpc.publish.mutate({diff --git a/packages/prisma-client/prisma/migrations/20230606165920_deployment-project-domain/migration.sql b/packages/prisma-client/prisma/migrations/20230606165920_deployment-project-domain/migration.sqlnew file mode 100644index 0000000000..d93c8f7b37--- /dev/null+++ b/packages/prisma-client/prisma/migrations/20230606165920_deployment-project-domain/migration.sql@@ -0,0 +1,10 @@+UPDATE+ "Build"+SET+ deployment = deployment::jsonb ||('{"projectDomain": "' || "Project".domain || '" }')::jsonb+FROM+ "Project"+WHERE+ "Project".id = "Build"."projectId"+ AND "Build".deployment IS NOT NULL;+diff --git a/packages/prisma-client/prisma/migrations/20230606234538_latest-build/migration.sql b/packages/prisma-client/prisma/migrations/20230606234538_latest-build/migration.sqlnew file mode 100644index 0000000000..bf9623bd39--- /dev/null+++ b/packages/prisma-client/prisma/migrations/20230606234538_latest-build/migration.sql@@ -0,0 +1,95 @@+-- CreateEnum+CREATE TYPE "PublishStatus" AS ENUM ('PENDING', 'PUBLISHED', 'FAILED');++-- AlterTable+ALTER TABLE "Build" ADD COLUMN "publishStatus" "PublishStatus" NOT NULL DEFAULT 'PENDING';++-- Update existing and published+UPDATE "Build" SET "publishStatus" = 'PUBLISHED' WHERE deployment IS NOT NULL;++-- CreateIndex+CREATE UNIQUE INDEX "Project_id_domain_key" ON "Project"("id", "domain");+++CREATE OR REPLACE VIEW "LatestBuildPerProjectDomain" AS+WITH lbd AS (+ SELECT DISTINCT ON ("projectId",+ "domain")+ jsonb_array_elements_text(deployment::jsonb -> 'domains') AS "domain",+ bld.id AS "buildId",+ bld."projectId",+ bld."updatedAt",+ bld."publishStatus"+ FROM+ "Build" bld+ WHERE+ bld.deployment IS NOT NULL+ ORDER BY+ bld."projectId",+ "domain",+ bld."createdAt" DESC,+ "buildId"+),+lb AS (+ SELECT DISTINCT ON ("projectId")+ bld.id AS "buildId",+ bld."projectId",+ bld."updatedAt",+ bld."publishStatus"+ FROM+ "Build" bld+ WHERE+ bld.deployment IS NOT NULL+ ORDER BY+ bld."projectId",+ bld."createdAt" DESC,+ "buildId"+)+SELECT+ d.id AS "domainId",+ lbd."projectId",+ lbd."buildId",+ coalesce(lbd."updatedAt" = lb."updatedAt", FALSE) AS "isLatestBuild",+ lbd."publishStatus",+ lbd."updatedAt"+FROM+ lbd,+ lb,+ "Domain" d+WHERE+ lbd.domain = d.domain+ AND lb."projectId" = lbd."projectId";++CREATE OR REPLACE VIEW "LatestBuildPerProject" AS+WITH lb AS (+ SELECT DISTINCT ON ("projectId")+ bld.id AS "buildId",+ bld."projectId",+ bld."updatedAt"+ FROM+ "Build" bld+ WHERE+ bld.deployment IS NOT NULL+ ORDER BY+ bld."projectId",+ bld."createdAt" DESC,+ "buildId"+)+SELECT DISTINCT ON ("projectId", "domain")+ bld.id AS "buildId",+ bld."projectId",+ deployment::jsonb ->> 'projectDomain' AS domain,+ coalesce(bld."updatedAt" = lb."updatedAt", FALSE) AS "isLatestBuild",+ bld."updatedAt",+ bld."publishStatus"+FROM+ "Build" bld,+ lb+WHERE+ bld.deployment IS NOT NULL+ AND lb."projectId" = bld."projectId"+ORDER BY+ bld."projectId",+ "domain",+ bld."createdAt" DESC,+ "buildId";diff --git a/packages/prisma-client/prisma/schema.prisma b/packages/prisma-client/prisma/schema.prismaindex 03e5a9e416..c98c7f9b67 100644--- a/packages/prisma-client/prisma/schema.prisma+++ b/packages/prisma-client/prisma/schema.prisma@@ -62,19 +62,27 @@ model User {}model Project {- id String @id @default(uuid())- createdAt DateTime @default(now())+ id String @id @default(uuid())+ createdAt DateTime @default(now())title String- domain String @unique- user User? @relation(fields: [userId], references: [id])+ domain String @unique+ user User? @relation(fields: [userId], references: [id])userId String?build Build[]- isDeleted Boolean @default(false)+ isDeleted Boolean @default(false)files File[]- ProjectDomain ProjectDomain[]+ projectDomain ProjectDomain[]+ latestBuild LatestBuildPerProject?@@unique([id, isDeleted])@@unique([domain, isDeleted])+ @@unique([id, domain])+}++enum PublishStatus {+ PENDING+ PUBLISHED+ FAILED}model Build {@@ -94,7 +102,8 @@ model Build {props String @default("[]")instances String @default("[]")- deployment String?+ deployment String?+ publishStatus PublishStatus @default(PENDING)@@id([id, projectId])}@@ -132,13 +141,14 @@ model Domain {createdAt DateTime @default(now())updatedAt DateTime @default(now()) @updatedAt- ProjectDomain ProjectDomain[]+ ProjectDomain ProjectDomain[]// Last known txtRecord of the domain (to check domain ownership)- txtRecord String?+ txtRecord String?// create, init, pending, active, error- status DomainStatus @default(INITIALIZING)+ status DomainStatus @default(INITIALIZING)// In case of status="error", this will contain the error message- error String?+ error String?+projectWithDomain ProjectWithDomain[]}@@ -174,9 +184,39 @@ view ProjectWithDomain {// To count statistics per useruserId 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])+}+// Dashboardview DashboardProject {id String @id @default(uuid())diff --git a/packages/prisma-client/src/prisma.ts b/packages/prisma-client/src/prisma.tsindex 252ee7ff61..86cfa5aaeb 100644--- a/packages/prisma-client/src/prisma.ts+++ b/packages/prisma-client/src/prisma.ts@@ -58,7 +58,7 @@ prisma.$on("query", (e) => {);// eslint-disable-next-line no-console- console.log("Params: " + e.params.slice(0, 100));+ console.log("Params: " + e.params.slice(0, 200));// eslint-disable-next-line no-consoleconsole.log("Duration: " + e.duration + "ms");});diff --git a/packages/prisma-client/src/types.ts b/packages/prisma-client/src/types.tsindex a3331d8a5a..ec7a182f16 100644--- a/packages/prisma-client/src/types.ts+++ b/packages/prisma-client/src/types.ts@@ -9,4 +9,8 @@ export type {AuthorizationToken,DomainStatus,Domain,+ ProjectWithDomain,+ LatestBuildPerProjectDomain,+ LatestBuildPerProject,+ PublishStatus,} from "./__generated__";diff --git a/packages/project-build/src/schema/deployment.ts b/packages/project-build/src/schema/deployment.tsindex 5c6076bd49..8c2e038346 100644--- a/packages/project-build/src/schema/deployment.ts+++ b/packages/project-build/src/schema/deployment.ts@@ -2,6 +2,7 @@ import { z } from "zod";export const Deployment = z.object({domains: z.array(z.string()),+ projectDomain: z.string(),});export type Deployment = z.infer<typeof Deployment>;diff --git a/packages/project/src/db/project.ts b/packages/project/src/db/project.tsindex b137ce2df6..b1002c0fde 100644--- a/packages/project/src/db/project.ts+++ b/packages/project/src/db/project.ts@@ -28,6 +28,9 @@ export const loadById = async (const data = await prisma.project.findUnique({where: { id_isDeleted: { id: projectId, isDeleted: false } },+ include: {+ latestBuild: true,+ },});return Project.parse(data);diff --git a/packages/project/src/shared/schema.ts b/packages/project/src/shared/schema.tsindex cf990ed279..04b52b1870 100644--- a/packages/project/src/shared/schema.ts+++ b/packages/project/src/shared/schema.ts@@ -16,6 +16,16 @@ export const Project = z.object({userId: z.string().nullable(),isDeleted: z.boolean(),domain: z.string(),+ latestBuild: z.optional(+ z+ .object({+ buildId: z.string(),+ isLatestBuild: z.boolean(),+ publishStatus: z.enum(["PENDING", "PUBLISHED", "FAILED"]),+ updatedAt: z.date().transform((date) => date.toISOString()),+ })+ .nullable()+ ),});export type Project = z.infer<typeof Project>;diff --git a/packages/trpc-interface/src/shared/deployment.ts b/packages/trpc-interface/src/shared/deployment.tsindex f951b123b3..383acecfcc 100644--- a/packages/trpc-interface/src/shared/deployment.ts+++ b/packages/trpc-interface/src/shared/deployment.ts@@ -30,6 +30,9 @@ export const deploymentRouter = router({.input(PublishInput).output(Output).mutation(async ({ input, ctx }) => {- return { success: false, error: "Not implemented" };+ return {+ success: false,+ error: `Not implemented, use buildId=${input.buildId}`,+ };}),});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 6e44f04c04..f8913c3af8 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -170,6 +170,9 @@ importers:colord:specifier: ^2.9.3version: 2.9.3+ date-fns:+ specifier: ^2.30.0+ version: 2.30.0debug:specifier: ^4.3.4version: 4.3.4@@ -3753,6 +3756,12 @@ packages:dependencies:regenerator-runtime: 0.13.11+ /@babel/[email protected]:+ resolution: {integrity: sha512-XsDuspWKLUsxwCp6r7EhsExHtYfbe5oAGQ19kqngTdCPUoPQzOPdUbD/pB9PJiwb2ptYKQDjSJT3R6dC+EPqfQ==}+ engines: {node: '>=6.9.0'}+ dependencies:+ regenerator-runtime: 0.13.11+/@babel/[email protected]:resolution: {integrity: sha512-8SegXApWe6VoNw0r9JHpSteLKTpTiLZ4rMlGIm9JQ18KiCtyQiAMEazujAHrUS5flrcqYZa75ukev3P6QmUwUw==}engines: {node: '>=6.9.0'}@@ -9783,7 +9792,7 @@ packages:resolution: {integrity: sha512-Cg7TFGpIr01vOQNODXOOaGz2NpCU5gl8x1qJFbb6hbZxR7XrcE2vtbAsTAbJ7/xwJtUuJEw8K8Zr/AE0LHlesg==}engines: {node: '>=10', npm: '>=6'}dependencies:- '@babel/runtime': 7.20.13+ '@babel/runtime': 7.22.3cosmiconfig: 7.0.1resolve: 1.22.1@@ -11019,6 +11028,13 @@ packages:resolution: {integrity: sha512-WboRycPNsVw3B3TL559F7kuBUM4d8CgMEvk6xEJlOp7OBPjt6G7z8WMWlD2rOFZLk6OYfFIUGsCOWzcQH9K2og==}engines: {node: '>= 6'}+ resolution: {integrity: sha512-fnULvOpxnC5/Vg3NCiWelDsLiUc9bRwAPs/+LfTLNvetFCtCTN+yQz15C/fs4AwX1R9K5GLtLfn8QW+dWisaAw==}+ engines: {node: '>=0.11'}+ dependencies:+ '@babel/runtime': 7.22.3+ dev: false+resolution: {integrity: sha512-QqLF6inIDwiATrfROIyQtwOQxjZuek13WRYZ7donU5wJPLoP67MnYxA6QtqdvdBy2mMqv5m3UefBVdJjvevOYg==}engines: {node: '>=0.11.0'}@@ -14677,7 +14693,7 @@ packages:resolution: {integrity: sha512-prXSYk799h3GY3iOWnC6ZigYzMPjxN2svgjJ9shk7oMadSNX3wXy0B6F32PMJv7qtMnrIbUxoEHzbutvxR2LBQ==}engines: {node: '>=6.0.0', npm: '>=6.0.0', yarn: '>=1.0.0'}dependencies:- '@babel/runtime': 7.20.13+ '@babel/runtime': 7.22.3app-root-dir: 1.0.2core-js: 3.23.3dotenv: 8.6.0@@ -15101,7 +15117,7 @@ packages:resolution: {integrity: sha512-1N4qp+jE0pL5Xv4uEcwVUhIkwdUO3S/9gML90nqKA7v7FcOS5vUtatfzok9S9U1EJU8dHWlcv95WLnKmmxZI9w==}dependencies:- '@babel/runtime': 7.20.13+ '@babel/runtime': 7.22.3dev: true@@ -16631,7 +16647,7 @@ packages:resolution: {integrity: sha512-Sz2Lkdxz6F2Pgnpi9U5Ng/WdWAUZxmHrNPoVlm3aAemxoy2Qy7LGjQg4uf8qKelDAUW94F4np3iH2YPf2qefcQ==}engines: {node: '>=10'}dependencies:- '@babel/runtime': 7.20.13+ '@babel/runtime': 7.22.3dev: false@@ -17137,7 +17153,7 @@ packages:dependencies:'@babel/core': 7.21.0'@babel/generator': 7.21.1- '@babel/runtime': 7.20.13+ '@babel/runtime': 7.22.3ast-types: 0.14.2commander: 2.20.3doctrine: 3.0.0@@ -17237,7 +17253,7 @@ packages:peerDependencies:react: ^16.8.4 || ^17.0.0dependencies:- '@babel/runtime': 7.20.13+ '@babel/runtime': 7.22.3is-dom: 1.1.0prop-types: 15.8.1react: 17.0.2@@ -17526,7 +17542,7 @@ packages:resolution: {integrity: sha512-knzmNAcuyxV+gQCufkYcvOqX/qIIfHLv0u5x79kRxuGojfYVky1f15TzZEu2Avte8QGepvUNTnLskf8E6X6Vyg==}dependencies:- '@babel/runtime': 7.20.13+ '@babel/runtime': 7.22.3resolution: {integrity: sha512-J6SDjUgDxQj5NusnOtdFxDwN/+HWykR8GELwctJ7mdqhcyy1xEc4SRFHUXvxTp661YaVKAjfRLZ9cCqS6tn32A==}