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.

feat: allow restore from published backup (#5320)

Bogdan Chadkin5632a40940b1
diff --git a/apps/builder/app/builder/features/project-settings/project-settings.tsx b/apps/builder/app/builder/features/project-settings/project-settings.tsx
index 833fd2869a..3651a26715 100644
--- a/apps/builder/app/builder/features/project-settings/project-settings.tsx
+++ b/apps/builder/app/builder/features/project-settings/project-settings.tsx
@@ -1,3 +1,4 @@
+import type { FunctionComponent } from "react";
import { useStore } from "@nanostores/react";
import {
Dialog,
@@ -11,22 +12,24 @@ import {
ListItem,
Text,
} from "@webstudio-is/design-system";
-import { $openProjectSettings } from "~/shared/nano-states/project-settings";
+import {
+ $openProjectSettings,
+ type SectionName,
+} from "~/shared/nano-states/project-settings";
+import { $isDesignMode } from "~/shared/nano-states";
+import { leftPanelWidth, rightPanelWidth } from "./utils";
import { SectionGeneral } from "./section-general";
import { SectionRedirects } from "./section-redirects";
import { SectionPublish } from "./section-publish";
import { SectionMarketplace } from "./section-marketplace";
-import { leftPanelWidth, rightPanelWidth } from "./utils";
-import type { FunctionComponent } from "react";
-import { $isDesignMode } from "~/shared/nano-states";
-
-type SectionName = "general" | "redirects" | "publish" | "marketplace";
+import { SectionBackups } from "./section-backups";
const sections = new Map<SectionName, FunctionComponent>([
["general", SectionGeneral],
["redirects", SectionRedirects],
["publish", SectionPublish],
["marketplace", SectionMarketplace],
+ ["backups", SectionBackups],
] as const);
export const ProjectSettingsView = ({
@@ -39,6 +42,9 @@ export const ProjectSettingsView = ({
onOpenChange?: (isOpen: boolean) => void;
}) => {
const isDesignMode = useStore($isDesignMode);
+ const SectionComponent = currentSection
+ ? sections.get(currentSection)
+ : undefined;
return (
<Dialog
@@ -100,12 +106,9 @@ export const ProjectSettingsView = ({
})}
</Flex>
</List>
- <ScrollArea>
+ <ScrollArea css={{ width: "100%" }}>
<Grid gap={2} css={{ py: theme.spacing[5] }}>
- {currentSection === "general" && <SectionGeneral />}
- {currentSection === "redirects" && <SectionRedirects />}
- {currentSection === "publish" && <SectionPublish />}
- {currentSection === "marketplace" && <SectionMarketplace />}
+ {SectionComponent && <SectionComponent />}
<div />
</Grid>
</ScrollArea>
diff --git a/apps/builder/app/builder/features/project-settings/section-backups.tsx b/apps/builder/app/builder/features/project-settings/section-backups.tsx
new file mode 100644
index 0000000000..6986bde16e
--- /dev/null
+++ b/apps/builder/app/builder/features/project-settings/section-backups.tsx
@@ -0,0 +1,146 @@
+import { useStore } from "@nanostores/react";
+import { useEffect, useState } from "react";
+import {
+ Grid,
+ Text,
+ Button,
+ Select,
+ Dialog,
+ DialogTitle,
+ DialogTrigger,
+ DialogContent,
+ DialogClose,
+ Flex,
+ theme,
+ toast,
+ PanelBanner,
+ Link,
+ rawTheme,
+} from "@webstudio-is/design-system";
+import { UpgradeIcon } from "@webstudio-is/icons";
+import { nativeClient, trpcClient } from "~/shared/trpc/trpc-client";
+import { $project, $userPlanFeatures } from "~/shared/nano-states";
+import { sectionSpacing } from "./utils";
+import cmsUpgradeBanner from "../settings-panel/cms-upgrade-banner.svg?url";
+
+const formatPublishDate = (date: string) => {
+ try {
+ const formatter = new Intl.DateTimeFormat("en", {
+ dateStyle: "long",
+ timeStyle: "short",
+ });
+ return formatter.format(new Date(date));
+ } catch {
+ return date;
+ }
+};
+
+export const SectionBackups = () => {
+ const { hasProPlan } = useStore($userPlanFeatures);
+ const { data, load } = trpcClient.project.publishedBuilds.useQuery();
+ const projectId = $project.get()?.id ?? "";
+ useEffect(() => {
+ load({ projectId });
+ }, [load, projectId]);
+ const options = data?.success ? data.data : [];
+ const [backupBuild = options.at(0), setBackupBuild] = useState<
+ undefined | (typeof options)[number]
+ >();
+ const restore = async () => {
+ if (!backupBuild?.buildId) {
+ return;
+ }
+ const result = await nativeClient.project.restoreDevelopmentBuild.mutate({
+ projectId,
+ fromBuildId: backupBuild.buildId,
+ });
+ if (result.success) {
+ location.reload();
+ return;
+ }
+ toast.error(result.error);
+ };
+
+ return (
+ <Grid gap={2} css={sectionSpacing}>
+ <Text variant="titles">Backups</Text>
+ <Select
+ placeholder="No backups"
+ options={options}
+ getValue={(option) => option.buildId ?? ""}
+ getLabel={(option) => {
+ if (!option.createdAt) {
+ return;
+ }
+ let label = formatPublishDate(option.createdAt);
+ if (option.domains) {
+ label += ` (${option.domains})`;
+ }
+ return label;
+ }}
+ value={backupBuild}
+ onChange={setBackupBuild}
+ />
+ <Dialog>
+ <DialogTrigger asChild>
+ <Button
+ css={{ justifySelf: "start" }}
+ disabled={!hasProPlan || options.length === 0}
+ >
+ Restore
+ </Button>
+ </DialogTrigger>
+ <DialogContent width={320}>
+ <DialogTitle>Restore published version</DialogTitle>
+ <Flex
+ direction="column"
+ css={{ padding: theme.panel.padding }}
+ gap={2}
+ >
+ <Text>
+ Are you sure you want to restore the project to its published
+ version?
+ </Text>
+ {backupBuild?.createdAt && (
+ <Text color="destructive">
+ All changes made after{" "}
+ {formatPublishDate(backupBuild.createdAt)} will be lost.
+ </Text>
+ )}
+ <Flex gap="2" justify="end">
+ <DialogClose>
+ <Button color="ghost">Cancel</Button>
+ </DialogClose>
+ <DialogClose>
+ <Button color="destructive" onClick={restore}>
+ Restore
+ </Button>
+ </DialogClose>
+ </Flex>
+ </Flex>
+ </DialogContent>
+ </Dialog>
+ {!hasProPlan && (
+ <PanelBanner>
+ <img
+ src={cmsUpgradeBanner}
+ alt="Upgrade for backups"
+ width={rawTheme.spacing[28]}
+ style={{ aspectRatio: "4.1" }}
+ />
+ <Text variant="regularBold">Upgrade to restore from backups</Text>
+ <Flex align="center" gap={1}>
+ <UpgradeIcon />
+ <Link
+ color="inherit"
+ target="_blank"
+ href="https://webstudio.is/pricing"
+ >
+ Upgrade to Pro
+ </Link>
+ </Flex>
+ </PanelBanner>
+ )}
+ </Grid>
+ );
+};
diff --git a/apps/builder/app/shared/help.tsx b/apps/builder/app/shared/help.tsx
index 1fb41fee10..57b6a74ecf 100644
--- a/apps/builder/app/shared/help.tsx
+++ b/apps/builder/app/shared/help.tsx
@@ -1,9 +1,4 @@
-import {
- ContentIcon,
- DiscordIcon,
- LifeBuoyIcon,
- YoutubeIcon,
-} from "@webstudio-is/icons";
+import { ContentIcon, DiscordIcon, YoutubeIcon } from "@webstudio-is/icons";
export const help = [
{
diff --git a/apps/builder/app/shared/nano-states/project-settings.ts b/apps/builder/app/shared/nano-states/project-settings.ts
index 9ad3609840..629a9a8f77 100644
--- a/apps/builder/app/shared/nano-states/project-settings.ts
+++ b/apps/builder/app/shared/nano-states/project-settings.ts
@@ -1,5 +1,10 @@
import { atom } from "nanostores";
-export const $openProjectSettings = atom<
- "general" | "redirects" | "publish" | "marketplace" | undefined
->();
+export type SectionName =
+ | "general"
+ | "redirects"
+ | "publish"
+ | "marketplace"
+ | "backups";
+
+export const $openProjectSettings = atom<SectionName | undefined>();
diff --git a/packages/postgrest/src/__generated__/db-types.ts b/packages/postgrest/src/__generated__/db-types.ts
index 7d581eda00..f224dd88e8 100644
--- a/packages/postgrest/src/__generated__/db-types.ts
+++ b/packages/postgrest/src/__generated__/db-types.ts
@@ -442,6 +442,13 @@ export type Database = {
referencedRelation: "LatestStaticBuildPerProject";
referencedColumns: ["buildId"];
},
+ {
+ foreignKeyName: "latestBuildVirtual_buildId_fkey";
+ columns: ["buildId"];
+ isOneToOne: true;
+ referencedRelation: "published_builds";
+ referencedColumns: ["buildId"];
+ },
{
foreignKeyName: "latestBuildVirtual_domainsVirtualId_fkey";
columns: ["domainsVirtualId"];
@@ -805,6 +812,42 @@ export type Database = {
},
];
};
+ published_builds: {
+ Row: {
+ buildId: string | null;
+ createdAt: string | null;
+ domains: string | null;
+ projectId: string | null;
+ };
+ Insert: {
+ buildId?: string | null;
+ createdAt?: string | null;
+ domains?: never;
+ projectId?: string | null;
+ };
+ Update: {
+ buildId?: string | null;
+ createdAt?: string | null;
+ domains?: never;
+ projectId?: string | null;
+ };
+ Relationships: [
+ {
+ foreignKeyName: "Build_projectId_fkey";
+ columns: ["projectId"];
+ isOneToOne: false;
+ referencedRelation: "DashboardProject";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "Build_projectId_fkey";
+ columns: ["projectId"];
+ isOneToOne: false;
+ referencedRelation: "Project";
+ referencedColumns: ["id"];
+ },
+ ];
+ };
user_publish_count: {
Row: {
count: number | null;
@@ -851,23 +894,15 @@ export type Database = {
};
};
create_production_build: {
- Args: {
- project_id: string;
- deployment: string;
- };
+ Args: { project_id: string; deployment: string };
Returns: string;
};
database_cleanup: {
- Args: {
- from_date?: string;
- to_date?: string;
- };
+ Args: { from_date?: string; to_date?: string };
Returns: undefined;
};
domainsVirtual: {
- Args: {
- "": Database["public"]["Tables"]["Project"]["Row"];
- };
+ Args: { "": Database["public"]["Tables"]["Project"]["Row"] };
Returns: {
cname: string;
createdAt: string;
@@ -883,37 +918,21 @@ export type Database = {
verified: boolean;
}[];
};
- latestBuildVirtual:
- | {
- Args: {
- "": Database["public"]["Tables"]["Project"]["Row"];
- };
- Returns: {
- buildId: string;
- createdAt: string;
- domain: string;
- domainsVirtualId: string;
- projectId: string;
- publishStatus: Database["public"]["Enums"]["PublishStatus"];
- }[];
- }
- | {
- Args: {
- "": Database["public"]["Tables"]["domainsVirtual"]["Row"];
- };
- Returns: {
- buildId: string;
- createdAt: string;
- domain: string;
- domainsVirtualId: string;
- projectId: string;
- publishStatus: Database["public"]["Enums"]["PublishStatus"];
- }[];
- };
+ latestBuildVirtual: {
+ Args:
+ | { "": Database["public"]["Tables"]["Project"]["Row"] }
+ | { "": Database["public"]["Tables"]["domainsVirtual"]["Row"] };
+ Returns: {
+ buildId: string;
+ createdAt: string;
+ domain: string;
+ domainsVirtualId: string;
+ projectId: string;
+ publishStatus: Database["public"]["Enums"]["PublishStatus"];
+ }[];
+ };
latestProjectDomainBuildVirtual: {
- Args: {
- "": Database["public"]["Tables"]["Project"]["Row"];
- };
+ Args: { "": Database["public"]["Tables"]["Project"]["Row"] };
Returns: {
buildId: string;
createdAt: string;
@@ -923,6 +942,10 @@ export type Database = {
publishStatus: Database["public"]["Enums"]["PublishStatus"];
}[];
};
+ restore_development_build: {
+ Args: { project_id: string; from_build_id: string };
+ Returns: string;
+ };
};
Enums: {
AuthorizationRelation:
@@ -945,27 +968,29 @@ export type Database = {
};
};
-type PublicSchema = Database[Extract<keyof Database, "public">];
+type DefaultSchema = Database[Extract<keyof Database, "public">];
export type Tables<
- PublicTableNameOrOptions extends
- | keyof (PublicSchema["Tables"] & PublicSchema["Views"])
+ DefaultSchemaTableNameOrOptions extends
+ | keyof (DefaultSchema["Tables"] & DefaultSchema["Views"])
| { schema: keyof Database },
- TableName extends PublicTableNameOrOptions extends { schema: keyof Database }
- ? keyof (Database[PublicTableNameOrOptions["schema"]]["Tables"] &
- Database[PublicTableNameOrOptions["schema"]]["Views"])
+ TableName extends DefaultSchemaTableNameOrOptions extends {
+ schema: keyof Database;
+ }
+ ? keyof (Database[DefaultSchemaTableNameOrOptions["schema"]]["Tables"] &
+ Database[DefaultSchemaTableNameOrOptions["schema"]]["Views"])
: never = never,
-> = PublicTableNameOrOptions extends { schema: keyof Database }
- ? (Database[PublicTableNameOrOptions["schema"]]["Tables"] &
- Database[PublicTableNameOrOptions["schema"]]["Views"])[TableName] extends {
+> = DefaultSchemaTableNameOrOptions extends { schema: keyof Database }
+ ? (Database[DefaultSchemaTableNameOrOptions["schema"]]["Tables"] &
+ Database[DefaultSchemaTableNameOrOptions["schema"]]["Views"])[TableName] extends {
Row: infer R;
}
? R
: never
- : PublicTableNameOrOptions extends keyof (PublicSchema["Tables"] &
- PublicSchema["Views"])
- ? (PublicSchema["Tables"] &
- PublicSchema["Views"])[PublicTableNameOrOptions] extends {
+ : DefaultSchemaTableNameOrOptions extends keyof (DefaultSchema["Tables"] &
+ DefaultSchema["Views"])
+ ? (DefaultSchema["Tables"] &
+ DefaultSchema["Views"])[DefaultSchemaTableNameOrOptions] extends {
Row: infer R;
}
? R
@@ -973,20 +998,22 @@ export type Tables<
: never;
export type TablesInsert<
- PublicTableNameOrOptions extends
- | keyof PublicSchema["Tables"]
+ DefaultSchemaTableNameOrOptions extends
+ | keyof DefaultSchema["Tables"]
| { schema: keyof Database },
- TableName extends PublicTableNameOrOptions extends { schema: keyof Database }
- ? keyof Database[PublicTableNameOrOptions["schema"]]["Tables"]
+ TableName extends DefaultSchemaTableNameOrOptions extends {
+ schema: keyof Database;
+ }
+ ? keyof Database[DefaultSchemaTableNameOrOptions["schema"]]["Tables"]
: never = never,
-> = PublicTableNameOrOptions extends { schema: keyof Database }
- ? Database[PublicTableNameOrOptions["schema"]]["Tables"][TableName] extends {
+> = DefaultSchemaTableNameOrOptions extends { schema: keyof Database }
+ ? Database[DefaultSchemaTableNameOrOptions["schema"]]["Tables"][TableName] extends {
Insert: infer I;
}
? I
: never
- : PublicTableNameOrOptions extends keyof PublicSchema["Tables"]
- ? PublicSchema["Tables"][PublicTableNameOrOptions] extends {
+ : DefaultSchemaTableNameOrOptions extends keyof DefaultSchema["Tables"]
+ ? DefaultSchema["Tables"][DefaultSchemaTableNameOrOptions] extends {
Insert: infer I;
}
? I
@@ -994,20 +1021,22 @@ export type TablesInsert<
: never;
export type TablesUpdate<
- PublicTableNameOrOptions extends
- | keyof PublicSchema["Tables"]
+ DefaultSchemaTableNameOrOptions extends
+ | keyof DefaultSchema["Tables"]
| { schema: keyof Database },
- TableName extends PublicTableNameOrOptions extends { schema: keyof Database }
- ? keyof Database[PublicTableNameOrOptions["schema"]]["Tables"]
+ TableName extends DefaultSchemaTableNameOrOptions extends {
+ schema: keyof Database;
+ }
+ ? keyof Database[DefaultSchemaTableNameOrOptions["schema"]]["Tables"]
: never = never,
-> = PublicTableNameOrOptions extends { schema: keyof Database }
- ? Database[PublicTableNameOrOptions["schema"]]["Tables"][TableName] extends {
+> = DefaultSchemaTableNameOrOptions extends { schema: keyof Database }
+ ? Database[DefaultSchemaTableNameOrOptions["schema"]]["Tables"][TableName] extends {
Update: infer U;
}
? U
: never
- : PublicTableNameOrOptions extends keyof PublicSchema["Tables"]
- ? PublicSchema["Tables"][PublicTableNameOrOptions] extends {
+ : DefaultSchemaTableNameOrOptions extends keyof DefaultSchema["Tables"]
+ ? DefaultSchema["Tables"][DefaultSchemaTableNameOrOptions] extends {
Update: infer U;
}
? U
@@ -1015,21 +1044,23 @@ export type TablesUpdate<
: never;
export type Enums<
- PublicEnumNameOrOptions extends
- | keyof PublicSchema["Enums"]
+ DefaultSchemaEnumNameOrOptions extends
+ | keyof DefaultSchema["Enums"]
| { schema: keyof Database },
- EnumName extends PublicEnumNameOrOptions extends { schema: keyof Database }
- ? keyof Database[PublicEnumNameOrOptions["schema"]]["Enums"]
+ EnumName extends DefaultSchemaEnumNameOrOptions extends {
+ schema: keyof Database;
+ }
+ ? keyof Database[DefaultSchemaEnumNameOrOptions["schema"]]["Enums"]
: never = never,
-> = PublicEnumNameOrOptions extends { schema: keyof Database }
- ? Database[PublicEnumNameOrOptions["schema"]]["Enums"][EnumName]
- : PublicEnumNameOrOptions extends keyof PublicSchema["Enums"]
- ? PublicSchema["Enums"][PublicEnumNameOrOptions]
+> = DefaultSchemaEnumNameOrOptions extends { schema: keyof Database }
+ ? Database[DefaultSchemaEnumNameOrOptions["schema"]]["Enums"][EnumName]
+ : DefaultSchemaEnumNameOrOptions extends keyof DefaultSchema["Enums"]
+ ? DefaultSchema["Enums"][DefaultSchemaEnumNameOrOptions]
: never;
export type CompositeTypes<
PublicCompositeTypeNameOrOptions extends
- | keyof PublicSchema["CompositeTypes"]
+ | keyof DefaultSchema["CompositeTypes"]
| { schema: keyof Database },
CompositeTypeName extends PublicCompositeTypeNameOrOptions extends {
schema: keyof Database;
@@ -1038,6 +1069,31 @@ export type CompositeTypes<
: never = never,
> = PublicCompositeTypeNameOrOptions extends { schema: keyof Database }
? Database[PublicCompositeTypeNameOrOptions["schema"]]["CompositeTypes"][CompositeTypeName]
- : PublicCompositeTypeNameOrOptions extends keyof PublicSchema["CompositeTypes"]
- ? PublicSchema["CompositeTypes"][PublicCompositeTypeNameOrOptions]
+ : PublicCompositeTypeNameOrOptions extends keyof DefaultSchema["CompositeTypes"]
+ ? DefaultSchema["CompositeTypes"][PublicCompositeTypeNameOrOptions]
: never;
+
+export const Constants = {
+ graphql_public: {
+ Enums: {},
+ },
+ public: {
+ Enums: {
+ AuthorizationRelation: [
+ "viewers",
+ "editors",
+ "builders",
+ "administrators",
+ ],
+ DomainStatus: ["INITIALIZING", "ACTIVE", "ERROR", "PENDING"],
+ MarketplaceApprovalStatus: [
+ "UNLISTED",
+ "PENDING",
+ "APPROVED",
+ "REJECTED",
+ ],
+ PublishStatus: ["PENDING", "PUBLISHED", "FAILED"],
+ UploadStatus: ["UPLOADING", "UPLOADED"],
+ },
+ },
+} as const;
diff --git a/packages/prisma-client/prisma/migrations/20250710163439_restore_development_build/migration.sql b/packages/prisma-client/prisma/migrations/20250710163439_restore_development_build/migration.sql
new file mode 100644
index 0000000000..4738614071
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20250710163439_restore_development_build/migration.sql
@@ -0,0 +1,43 @@
+DROP FUNCTION IF EXISTS restore_development_build;
+CREATE FUNCTION restore_development_build(
+ project_id text,
+ from_build_id text
+) RETURNS text AS $$
+BEGIN
+ UPDATE "Build"
+ SET
+ "version" = source."version",
+ "lastTransactionId" = source."lastTransactionId",
+ "pages" = source."pages",
+ "breakpoints" = source."breakpoints",
+ "styles" = source."styles",
+ "styleSources" = source."styleSources",
+ "styleSourceSelections" = source."styleSourceSelections",
+ "props" = source."props",
+ "dataSources" = source."dataSources",
+ "resources" = source."resources",
+ "instances" = source."instances",
+ "marketplaceProduct" = source."marketplaceProduct"
+ FROM (
+ SELECT * FROM "Build"
+ WHERE "projectId" = project_id AND "id" = from_build_id
+ ) as source
+ WHERE "Build"."projectId" = project_id AND "Build"."deployment" IS NULL;
+ RETURN 'OK';
+END;
+$$ LANGUAGE plpgsql;
+
+DROP VIEW IF EXISTS published_builds;
+CREATE VIEW published_builds AS
+SELECT
+ build.id AS "buildId",
+ build."projectId",
+ build."createdAt",
+ (
+ SELECT string_agg(list.value, ', ')
+ FROM jsonb_array_elements_text(build.deployment::jsonb -> 'domains') AS list(value)
+ ) AS domains
+FROM "Build" as build
+WHERE build.deployment IS NOT NULL
+ AND build."isCleaned"=FALSE
+ORDER BY build."projectId", build."createdAt" DESC;
diff --git a/packages/project/package.json b/packages/project/package.json
index 429901a79f..05867e8d21 100644
--- a/packages/project/package.json
+++ b/packages/project/package.json
@@ -11,6 +11,7 @@
"dependencies": {
"@trpc/server": "^10.45.2",
"@webstudio-is/asset-uploader": "workspace:*",
+ "@webstudio-is/authorization-token": "workspace:*",
"@webstudio-is/project-build": "workspace:*",
"@webstudio-is/trpc-interface": "workspace:*",
"nanoid": "^5.1.5",
diff --git a/packages/project/src/trpc/project-router.ts b/packages/project/src/trpc/project-router.ts
index bfb3ab8071..d1ffead21b 100644
--- a/packages/project/src/trpc/project-router.ts
+++ b/packages/project/src/trpc/project-router.ts
@@ -1,6 +1,11 @@
import * as db from "../db";
import { z } from "zod";
-import { router, procedure } from "@webstudio-is/trpc-interface/index.server";
+import {
+ router,
+ procedure,
+ AuthorizationError,
+ authorizeProject,
+} from "@webstudio-is/trpc-interface/index.server";
import { MarketplaceApprovalStatus, Title } from "../shared/schema";
export const projectRouter = router({
@@ -95,6 +100,84 @@ export const projectRouter = router({
} as const;
}
}),
+
+ publishedBuilds: procedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ })
+ )
+ .query(async ({ input, ctx }) => {
+ try {
+ if (
+ ctx.authorization.type !== "user" &&
+ ctx.authorization.type !== "token"
+ ) {
+ throw new Error("Not authorized");
+ }
+ const publishedBuilds = await ctx.postgrest.client
+ .from("published_builds")
+ .select("*")
+ .eq("projectId", input.projectId);
+ if (publishedBuilds.error) {
+ throw publishedBuilds.error;
+ }
+ return {
+ success: true,
+ data: publishedBuilds.data,
+ };
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : "Unknown error",
+ } as const;
+ }
+ }),
+
+ restoreDevelopmentBuild: procedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ fromBuildId: z.string(),
+ })
+ )
+ .mutation(
+ async ({
+ input,
+ ctx,
+ }): Promise<{ success: true } | { success: false; error: string }> => {
+ try {
+ const permit = await authorizeProject.getProjectPermit(
+ {
+ projectId: input.projectId,
+ permits: ["build", "admin"],
+ },
+ ctx
+ );
+ if (!permit) {
+ throw new AuthorizationError("Not authorized");
+ }
+ const build = await ctx.postgrest.client.rpc(
+ "restore_development_build",
+ {
+ project_id: input.projectId,
+ from_build_id: input.fromBuildId,
+ }
+ );
+ if (build.error) {
+ throw build.error;
+ }
+ return {
+ success: true,
+ };
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : "Unknown error",
+ } as const;
+ }
+ }
+ ),
});
export type ProjectRouter = typeof projectRouter;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index f62dae6c0c..72010c8b2f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1783,6 +1783,9 @@ importers:
'@webstudio-is/asset-uploader':
specifier: workspace:*
version: link:../asset-uploader
+ '@webstudio-is/authorization-token':
+ specifier: workspace:*
+ version: link:../authorization-token
'@webstudio-is/project-build':
specifier: workspace:*
version: link:../project-build