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
fix: restore short --variable label in CSS value input (#5694)
Oleg Isonen4748fa5f1e69
diff --git a/apps/builder/app/builder/builder.tsx b/apps/builder/app/builder/builder.tsxindex 420a65032a..a78943243a 100644--- a/apps/builder/app/builder/builder.tsx+++ b/apps/builder/app/builder/builder.tsx@@ -45,10 +45,7 @@ import { useSyncPageUrl } from "~/shared/pages";import { useMount, useUnmount } from "~/shared/hook-utils/use-mount";import { subscribeCommands } from "~/builder/shared/commands";import { ProjectSettings } from "~/shared/project-settings";-import type {- PlanFeatures,- Purchase,-} from "@webstudio-is/trpc-interface/plan-features";+import type { PlanFeatures, Purchase } from "@webstudio-is/plans";import {$activeSidebarPanel,$dataLoadingState,diff --git a/apps/builder/app/builder/features/style-panel/shared/css-value-input/css-value-input.tsx b/apps/builder/app/builder/features/style-panel/shared/css-value-input/css-value-input.tsxindex a6b3a5dbbe..695a512b80 100644--- a/apps/builder/app/builder/features/style-panel/shared/css-value-input/css-value-input.tsx+++ b/apps/builder/app/builder/features/style-panel/shared/css-value-input/css-value-input.tsx@@ -349,8 +349,7 @@ const itemToString = (item: CssValueInputValue | null) => {return "";}if (item.type === "var") {- // Use toValue to include fallback when present- return toValue(item as StyleValue);+ return `--${item.value}`;}if (item.type === "keyword") {// E.g. we want currentcolor to be lower case@@ -920,7 +919,10 @@ export const CssValueInput = ({if (event.target instanceof HTMLInputElement) {// We are setting the value on focus because we might have removed the var() from the value,// but once focused, we need to show the full value- event.target.value = itemToString(value);+ event.target.value =+ value.type === "var"+ ? toValue(value as StyleValue)+ : itemToString(value);}}}autoFocus={autoFocus}diff --git a/apps/builder/app/dashboard/dashboard.stories.tsx b/apps/builder/app/dashboard/dashboard.stories.tsxindex 6e2b2f7ea4..d96e0b9010 100644--- a/apps/builder/app/dashboard/dashboard.stories.tsx+++ b/apps/builder/app/dashboard/dashboard.stories.tsx@@ -11,10 +11,7 @@ import {import { Dashboard, DashboardSetup } from "./dashboard";import { Card as CardComponent, CardContent, CardFooter } from "./shared/card";import { ThumbnailWithAbbr, ThumbnailLinkWithAbbr } from "./shared/thumbnail";-import {- defaultPlanFeatures,- type PlanFeatures,-} from "@webstudio-is/trpc-interface/plan-features";+import { defaultPlanFeatures, type PlanFeatures } from "@webstudio-is/plans";import type { DashboardProject } from "@webstudio-is/dashboard";import { updateCsrfToken } from "~/shared/csrf.client";diff --git a/apps/builder/app/dashboard/shared/types.ts b/apps/builder/app/dashboard/shared/types.tsindex 1353710c4d..35890fedbb 100644--- a/apps/builder/app/dashboard/shared/types.ts+++ b/apps/builder/app/dashboard/shared/types.ts@@ -1,10 +1,7 @@import type { DashboardProject } from "@webstudio-is/dashboard";import type { WorkspaceWithRelation, Role } from "@webstudio-is/project";import type { User } from "~/shared/db/user.server";-import type {- PlanFeatures,- Purchase,-} from "@webstudio-is/trpc-interface/plan-features";+import type { PlanFeatures, Purchase } from "@webstudio-is/plans";import type { Notifications } from "~/shared/polly/types";export type DashboardData = {diff --git a/apps/builder/app/dashboard/workspace/manage-members-dialog.test.ts b/apps/builder/app/dashboard/workspace/manage-members-dialog.test.tsnew file mode 100644index 0000000000..0b1278d361--- /dev/null+++ b/apps/builder/app/dashboard/workspace/manage-members-dialog.test.ts@@ -0,0 +1,225 @@+import { describe, test, expect } from "vitest";+import { __testing__ } from "./manage-members-dialog";++const { computeAvailableSeats } = __testing__;++const owner = {+ userId: "owner-1",+ email: "[email protected]",+ username: "owner",+};++const makeData = ({+ maxSeats = 5,+ members = [] as {+ userId: string;+ email: string;+ relation: "administrators" | "builders" | "editors" | "viewers";+ createdAt: string;+ username: string;+ }[],+ pendingInvites = [] as {+ notificationId: string;+ recipientId: string;+ email: string;+ relation: "administrators" | "builders" | "editors" | "viewers";+ createdAt: string;+ }[],+} = {}) => ({ owner, members, pendingInvites, maxSeats });++describe("computeAvailableSeats", () => {+ test("returns undefined when membersData is undefined", () => {+ expect(computeAvailableSeats(undefined, [])).toBeUndefined();+ });++ test("returns maxSeats when workspace is empty", () => {+ expect(computeAvailableSeats(makeData({ maxSeats: 5 }), [])).toBe(5);+ });++ test("subtracts accepted members", () => {+ const members = [+ {+ userId: "u1",+ email: "[email protected]",+ relation: "editors" as const,+ createdAt: "",+ username: "",+ },+ {+ userId: "u2",+ email: "[email protected]",+ relation: "viewers" as const,+ createdAt: "",+ username: "",+ },+ ];+ expect(computeAvailableSeats(makeData({ maxSeats: 5, members }), [])).toBe(+ 3+ );+ });++ test("subtracts confirmed pending invites", () => {+ const pendingInvites = [+ {+ notificationId: "n1",+ recipientId: "r1",+ email: "[email protected]",+ relation: "editors" as const,+ createdAt: "",+ },+ ];+ expect(+ computeAvailableSeats(makeData({ maxSeats: 5, pendingInvites }), [])+ ).toBe(4);+ });++ test("subtracts optimistic pending entries not yet confirmed", () => {+ const optimistic = [+ {+ notificationId: "opt-1",+ email: "[email protected]",+ relation: "viewers" as const,+ },+ ];+ expect(computeAvailableSeats(makeData({ maxSeats: 5 }), optimistic)).toBe(+ 4+ );+ });++ test("does not double-count optimistic entry already confirmed as pending invite", () => {+ const pendingInvites = [+ {+ notificationId: "n1",+ recipientId: "r1",+ email: "[email protected]",+ relation: "editors" as const,+ createdAt: "",+ },+ ];+ const optimistic = [+ {+ notificationId: "opt-1",+ email: "[email protected]",+ relation: "editors" as const,+ },+ ];+ // confirmed invite already counts; optimistic for same email is ignored+ expect(+ computeAvailableSeats(+ makeData({ maxSeats: 5, pendingInvites }),+ optimistic+ )+ ).toBe(4);+ });++ test("does not double-count optimistic entry already in accepted members", () => {+ const members = [+ {+ userId: "u1",+ email: "[email protected]",+ relation: "editors" as const,+ createdAt: "",+ username: "",+ },+ ];+ const optimistic = [+ {+ notificationId: "opt-1",+ email: "[email protected]",+ relation: "editors" as const,+ },+ ];+ expect(+ computeAvailableSeats(makeData({ maxSeats: 5, members }), optimistic)+ ).toBe(4);+ });++ test("returns 0 when all seats are used", () => {+ const members = [+ {+ userId: "u1",+ email: "[email protected]",+ relation: "editors" as const,+ createdAt: "",+ username: "",+ },+ ];+ expect(computeAvailableSeats(makeData({ maxSeats: 1, members }), [])).toBe(+ 0+ );+ });++ test("returns negative when seats are exceeded", () => {+ const members = [+ {+ userId: "u1",+ email: "[email protected]",+ relation: "editors" as const,+ createdAt: "",+ username: "",+ },+ {+ userId: "u2",+ email: "[email protected]",+ relation: "viewers" as const,+ createdAt: "",+ username: "",+ },+ ];+ const optimistic = [+ {+ notificationId: "opt-1",+ email: "[email protected]",+ relation: "viewers" as const,+ },+ ];+ // 1 maxSeat − 2 members − 1 optimistic = -2+ expect(+ computeAvailableSeats(makeData({ maxSeats: 1, members }), optimistic)+ ).toBe(-2);+ });++ test("confirmedMaxSeats overrides stale server maxSeats when higher", () => {+ // Scenario: user confirmed paying for 2 extra seats but webhook hasn't fired.+ // Server still returns maxSeats=3, but confirmedMaxSeats=5.+ const members = [+ {+ userId: "u1",+ email: "[email protected]",+ relation: "editors" as const,+ createdAt: "",+ username: "",+ },+ ];+ const pendingInvites = [+ {+ notificationId: "n1",+ recipientId: "r1",+ email: "[email protected]",+ relation: "editors" as const,+ createdAt: "",+ },+ {+ notificationId: "n2",+ recipientId: "r2",+ email: "[email protected]",+ relation: "editors" as const,+ createdAt: "",+ },+ ];+ // maxSeats=3 (stale), but 1 member + 2 pending = 3 occupied → would be 0 available.+ // confirmedMaxSeats=5 → effectiveMax=5, available = 5-1-2 = 2.+ expect(+ computeAvailableSeats(+ makeData({ maxSeats: 3, members, pendingInvites }),+ [],+ 5+ )+ ).toBe(2);+ });++ test("confirmedMaxSeats is ignored when server maxSeats is already higher", () => {+ // Webhook fired: server returns maxSeats=5, confirmedMaxSeats=4 (stale override).+ expect(computeAvailableSeats(makeData({ maxSeats: 5 }), [], 4)).toBe(5);+ });+});diff --git a/apps/builder/app/dashboard/workspace/manage-members-dialog.tsx b/apps/builder/app/dashboard/workspace/manage-members-dialog.tsxindex 7e2bf0f63c..576693826b 100644--- a/apps/builder/app/dashboard/workspace/manage-members-dialog.tsx+++ b/apps/builder/app/dashboard/workspace/manage-members-dialog.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import { useRevalidator } from "@remix-run/react";import {Button,@@ -27,6 +27,43 @@ import { type Workspace, type Role } from "@webstudio-is/project";import { nativeClient, trpcClient } from "~/shared/trpc/trpc-client";import { RoleSelect } from "./role-select";+const inviteMembers = async (+ emails: string[],+ workspaceId: string,+ relation: Role+): Promise<string[]> => {+ const failed: string[] = [];+ for (const email of emails) {+ try {+ const result = await nativeClient.workspace.addMember.mutate({+ workspaceId,+ email,+ relation,+ });+ if (!result.success) {+ failed.push(`${email}: ${result.error}`);+ }+ } catch (error) {+ const raw = error instanceof Error ? error.message : "Unknown error";+ // tRPC surfaces Zod input validation failures as a JSON array of issues.+ // Extract the human-readable message(s) instead of dumping raw JSON.+ let message = raw;+ try {+ const issues = JSON.parse(raw);+ if (Array.isArray(issues) && issues.length > 0) {+ message = issues+ .map((i: { message?: string }) => i.message ?? "Invalid value")+ .join(", ");+ }+ } catch {+ // not JSON — use raw message as-is+ }+ failed.push(`${email}: ${message}`);+ }+ }+ return failed;+};+const memberItemStyle = css({paddingInline: theme.spacing[5],paddingBlock: theme.spacing[3],@@ -84,7 +121,7 @@ const MemberRow = (props: MemberRowProps) => {if (role === "pending") {return (<Text color="subtle" variant="regular">- Pending+ Pending…</Text>);}@@ -201,26 +238,74 @@ const MemberRow = (props: MemberRowProps) => {);};+type OptimisticPendingInvite = {+ notificationId: string;+ email: string;+ relation: Role;+};++const computeAvailableSeats = (+ membersData:+ | Extract<+ Exclude<+ ReturnType<typeof trpcClient.workspace.listMembers.useQuery>["data"],+ undefined+ >,+ { success: true }+ >["data"]+ | undefined,+ optimisticPending: OptimisticPendingInvite[],+ // Optimistic upper bound for maxSeats set when extra seats are confirmed,+ // to avoid flickering while the Stripe webhook has not yet updated TransactionLog.+ confirmedMaxSeats?: number+): number | undefined => {+ if (membersData === undefined) {+ return;+ }+ const effectiveMaxSeats =+ confirmedMaxSeats !== undefined+ ? Math.max(membersData.maxSeats, confirmedMaxSeats)+ : membersData.maxSeats;+ const knownEmails = new Set([+ membersData.owner.email,+ ...membersData.members.map((m) => m.email ?? ""),+ ...membersData.pendingInvites.map((i) => i.email),+ ]);+ const extraCount = optimisticPending.filter(+ (o) => !knownEmails.has(o.email)+ ).length;+ return (+ effectiveMaxSeats -+ membersData.members.length -+ membersData.pendingInvites.length -+ extraCount+ );+};+const MemberList = ({workspaceId,canRemove,- refreshKey,+ membersData,onRefresh,+ optimisticPending,+ onRemoveOptimistic,}: {workspaceId: string;canRemove: boolean;- refreshKey: number;+ membersData:+ | Extract<+ Exclude<+ ReturnType<typeof trpcClient.workspace.listMembers.useQuery>["data"],+ undefined+ >,+ { success: true }+ >["data"]+ | undefined;onRefresh: () => void;+ optimisticPending: OptimisticPendingInvite[];+ onRemoveOptimistic: (notificationId: string) => void;}) => {- const { load, data } = trpcClient.workspace.listMembers.useQuery();-- useEffect(() => {- load({ workspaceId });- }, [load, workspaceId, refreshKey]);-- const result = data && "data" in data ? data.data : undefined;-- if (result === undefined) {+ if (membersData === undefined) {return (<Text color="subtle" align="center">Loading members…@@ -228,7 +313,17 @@ const MemberList = ({);}- const { owner, members, pendingInvites } = result;+ const { owner, members, pendingInvites } = membersData;++ // Emails already covered by confirmed pending invites or accepted members+ const knownEmails = new Set([+ owner.email,+ ...members.map((m) => m.email ?? ""),+ ...pendingInvites.map((i) => i.email),+ ]);+ const extraOptimistic = optimisticPending.filter(+ (o) => !knownEmails.has(o.email)+ );let index = 0;@@ -265,11 +360,57 @@ const MemberList = ({}}/>))}+ {extraOptimistic.map((invite) => (+ <MemberRow+ key={invite.notificationId}+ email={invite.email}+ role="pending"+ relation={invite.relation}+ canRemove={canRemove}+ index={index++}+ onRemove={() => onRemoveOptimistic(invite.notificationId)}+ />+ ))}</Box></List>);};+const ExtraSeatsConfirmDialog = ({+ memberCount,+ extraSeats,+ onConfirm,+ onCancel,+}: {+ memberCount: number;+ extraSeats: number;+ onConfirm: () => void;+ onCancel: () => void;+}) => (+ <Dialog open onOpenChange={(open) => !open && onCancel()}>+ <DialogContent>+ <DialogTitle>Extra seats will be charged</DialogTitle>+ <Flex direction="column" gap="2" css={{ padding: theme.spacing[5] }}>+ <Text>+ {`Inviting ${memberCount} member${+ memberCount === 1 ? "" : "s"+ } will add ${extraSeats} extra seat${+ extraSeats === 1 ? "" : "s"+ } to your billing.`}+ </Text>+ </Flex>+ <DialogActions>+ <Button color="neutral" onClick={onCancel}>+ Cancel+ </Button>+ <Button autoFocus onClick={onConfirm}>+ Confirm+ </Button>+ </DialogActions>+ </DialogContent>+ </Dialog>+);+export const ManageMembersDialog = ({workspace,userId,@@ -284,15 +425,77 @@ export const ManageMembersDialog = ({const isOwner = workspace.userId === userId;const revalidator = useRevalidator();const [errors, setErrors] = useState<string[]>();- const [membersKey, setMembersKey] = useState(0);const [inviting, setInviting] = useState(false);const [inviteRelation, setInviteRelation] = useState<Role>("viewers");+ const [optimisticPending, setOptimisticPending] = useState<+ OptimisticPendingInvite[]+ >([]);+ const [pendingConfirm, setPendingConfirm] = useState<{+ emails: string[];+ relation: Role;+ extraSeats: number;+ }>();+ // Optimistic maxSeats ceiling: set when the user confirms extra-seat charges so+ // the footer and confirmation gate stay correct while the Stripe webhook is in+ // flight (TransactionLog not yet updated).+ const [confirmedMaxSeats, setConfirmedMaxSeats] = useState<number>();+ const formRef = useRef<HTMLFormElement>(null);++ const { load, data } = trpcClient.workspace.listMembers.useQuery();+ const membersData = data?.success ? data.data : undefined;+ const handleRefresh = useCallback(() => {+ load({ workspaceId: workspace.id });+ }, [load, workspace.id]);useEffect(() => {if (isOpen && isOwner) {- setMembersKey((key) => key + 1);+ load({ workspaceId: workspace.id });}- }, [isOpen, isOwner]);+ }, [isOpen, isOwner, load, workspace.id]);++ // Clear the optimistic override once the server reflects the paid seats.+ useEffect(() => {+ if (+ membersData !== undefined &&+ confirmedMaxSeats !== undefined &&+ membersData.maxSeats >= confirmedMaxSeats+ ) {+ setConfirmedMaxSeats(undefined);+ }+ }, [membersData, confirmedMaxSeats]);++ const availableSeats = computeAvailableSeats(+ membersData,+ optimisticPending,+ confirmedMaxSeats+ );++ const performInvite = async (emails: string[], relation: Role) => {+ setErrors(undefined);+ setInviting(true);+ const optimistic: OptimisticPendingInvite[] = emails.map((email) => ({+ notificationId: crypto.randomUUID(),+ email,+ relation,+ }));+ setOptimisticPending((prev) => [...prev, ...optimistic]);++ const failed = await inviteMembers(emails, workspace.id, relation);+ setInviting(false);++ if (failed.length > 0) {+ setErrors(failed);+ const failedEmails = new Set(failed.map((f) => f.split(":")[0].trim()));+ setOptimisticPending((prev) =>+ prev.filter((o) => !failedEmails.has(o.email))+ );+ } else {+ formRef.current?.reset();+ }++ handleRefresh();+ revalidator.revalidate();+ };const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {event.preventDefault();@@ -308,105 +511,135 @@ export const ManageMembersDialog = ({return;}- setErrors(undefined);- setInviting(true);-- const failed: string[] = [];- for (const email of emails) {- try {- const result = await nativeClient.workspace.addMember.mutate({- workspaceId: workspace.id,- email,- relation: inviteRelation,- });- if (!result.success) {- failed.push(`${email}: ${result.error}`);- }- } catch (error) {- const message =- error instanceof Error ? error.message : "Unknown error";- failed.push(`${email}: ${message}`);- }- }-- setInviting(false);-- if (failed.length > 0) {- setErrors(failed);- } else {- (event.target as HTMLFormElement).reset();+ if (availableSeats !== undefined && emails.length > availableSeats) {+ setPendingConfirm({+ emails,+ relation: inviteRelation,+ extraSeats: emails.length - Math.max(0, availableSeats),+ });+ return;}- setMembersKey((key) => key + 1);- revalidator.revalidate();+ await performInvite(emails, inviteRelation);};return (- <Dialog- open={isOpen}- onOpenChange={(open) => {- onOpenChange(open);- if (open === false) {- setErrors(undefined);- }- }}- >- <DialogContent css={{ width: theme.spacing[34] }}>- <Flex as="form" direction="column" gap="3" onSubmit={handleSubmit}>- {isOwner && (- <Flex- gap="1"- direction="column"+ <>+ {pendingConfirm !== undefined && (+ <ExtraSeatsConfirmDialog+ memberCount={pendingConfirm.emails.length}+ extraSeats={pendingConfirm.extraSeats}+ onCancel={() => setPendingConfirm(undefined)}+ onConfirm={async () => {+ const confirm = pendingConfirm;+ setPendingConfirm(undefined);+ // Optimistically raise confirmedMaxSeats so the footer and the+ // confirmation gate reflect the payment before the webhook fires.+ setConfirmedMaxSeats((prev) =>+ Math.max(+ prev ?? 0,+ (membersData?.maxSeats ?? 0) + confirm.extraSeats+ )+ );+ await performInvite(confirm.emails, confirm.relation);+ }}+ />+ )}+ <Dialog+ open={isOpen}+ onOpenChange={(open) => {+ onOpenChange(open);+ if (open === false) {+ setErrors(undefined);+ setConfirmedMaxSeats(undefined);+ }+ }}+ >+ <DialogContent css={{ width: theme.spacing[34] }}>+ <Flex+ as="form"+ ref={formRef}+ direction="column"+ gap="3"+ onSubmit={handleSubmit}+ >+ {isOwner && (+ <Flex+ gap="1"+ direction="column"+ css={{+ px: theme.spacing[7],+ paddingTop: theme.spacing[5],+ }}+ >+ <Label>Invite members</Label>+ <Flex gap="2">+ <Box css={{ flexGrow: 1 }}>+ <InputErrorsTooltip errors={errors}>+ <InputField+ name="emails"+ placeholder="[email protected], [email protected]"+ color={errors ? "error" : undefined}+ />+ </InputErrorsTooltip>+ </Box>+ <RoleSelect+ value={inviteRelation}+ onChange={setInviteRelation}+ />+ <Button+ type="submit"+ state={inviting ? "pending" : undefined}+ >+ Invite+ </Button>+ </Flex>+ </Flex>+ )}+ <ScrollAreaNativecss={{- px: theme.spacing[7],- paddingTop: theme.spacing[5],+ maxHeight: 300,+ paddingTop: isOwner ? undefined : theme.spacing[5],}}>- <Label>Invite members</Label>- <Flex gap="2">- <Box css={{ flexGrow: 1 }}>- <InputErrorsTooltip errors={errors}>- <InputField- name="emails"- placeholder="[email protected], [email protected]"- color={errors ? "error" : undefined}- />- </InputErrorsTooltip>- </Box>- <RoleSelect- value={inviteRelation}- onChange={setInviteRelation}+ <Flex direction="column" gap="2" css={{ px: theme.spacing[7] }}>+ <Text variant="labels">Members</Text>+ <MemberList+ workspaceId={workspace.id}+ canRemove={isOwner}+ membersData={membersData}+ onRefresh={handleRefresh}+ optimisticPending={optimisticPending}+ onRemoveOptimistic={(id) =>+ setOptimisticPending((prev) =>+ prev.filter((o) => o.notificationId !== id)+ )+ }/>- <Button type="submit" state={inviting ? "pending" : undefined}>- Invite- </Button></Flex>+ </ScrollAreaNative>+ </Flex>+ <DialogActions>+ <Flex justify="between" align="center" grow>+ {availableSeats !== undefined ? (+ <Text color={availableSeats <= 0 ? "destructive" : "subtle"}>+ {availableSeats >= 0+ ? `${availableSeats} more seats included`+ : `${-availableSeats} extra seat${-availableSeats === 1 ? "" : "s"} will be charged`}+ </Text>+ ) : (+ <div />+ )}+ <DialogClose>+ <Button color="ghost">Cancel</Button>+ </DialogClose></Flex>- )}- <ScrollAreaNative- css={{- maxHeight: 300,- paddingTop: isOwner ? undefined : theme.spacing[5],- }}- >- <Flex direction="column" gap="2" css={{ px: theme.spacing[7] }}>- <Text variant="labels">Members</Text>- <MemberList- workspaceId={workspace.id}- canRemove={isOwner}- refreshKey={membersKey}- onRefresh={() => setMembersKey((key) => key + 1)}- />- </Flex>- </ScrollAreaNative>- </Flex>- <DialogActions>- <DialogClose>- <Button color="ghost">Cancel</Button>- </DialogClose>- </DialogActions>- <DialogTitle>Members</DialogTitle>- </DialogContent>- </Dialog>+ </DialogActions>+ <DialogTitle>Members</DialogTitle>+ </DialogContent>+ </Dialog>+ </>);};++export const __testing__ = { computeAvailableSeats };diff --git a/apps/builder/app/dashboard/workspace/workspace-dropdown.stories.tsx b/apps/builder/app/dashboard/workspace/workspace-dropdown.stories.tsxindex 2bd4b036c4..1f862f4c32 100644--- a/apps/builder/app/dashboard/workspace/workspace-dropdown.stories.tsx+++ b/apps/builder/app/dashboard/workspace/workspace-dropdown.stories.tsx@@ -1,7 +1,7 @@import type { StoryFn } from "@storybook/react";import { createMemoryRouter, RouterProvider } from "react-router-dom";import type { WorkspaceWithRelation } from "@webstudio-is/project";-import { defaultPlanFeatures } from "@webstudio-is/trpc-interface/plan-features";+import { defaultPlanFeatures } from "@webstudio-is/plans";import { $planFeatures } from "~/shared/nano-states";import { $workspaces } from "./workspace-stores";import { WorkspaceSelector } from "./workspace-dropdown";diff --git a/apps/builder/app/routes/_ui.(builder).tsx b/apps/builder/app/routes/_ui.(builder).tsxindex 593d3d10a1..6d9a322f2d 100644--- a/apps/builder/app/routes/_ui.(builder).tsx+++ b/apps/builder/app/routes/_ui.(builder).tsx@@ -20,8 +20,8 @@ import {authorizeProject,} from "@webstudio-is/trpc-interface/index.server";import { createContext } from "~/shared/context.server";-import { getPlanInfo } from "@webstudio-is/trpc-interface/plan-client";-import { defaultPlanFeatures } from "@webstudio-is/trpc-interface/plan-features";+import { getPlanInfo } from "@webstudio-is/plans/index.server";+import { defaultPlanFeatures } from "@webstudio-is/plans";import { dashboardPath, isBuilder, isDashboard } from "~/shared/router-utils";import env from "~/env/env.server";diff --git a/apps/builder/app/routes/_ui.login._index.tsx b/apps/builder/app/routes/_ui.login._index.tsxindex 63be3ec243..5dea3e0137 100644--- a/apps/builder/app/routes/_ui.login._index.tsx+++ b/apps/builder/app/routes/_ui.login._index.tsx@@ -8,7 +8,7 @@ import { useLoaderData, type MetaFunction } from "@remix-run/react";import { findAuthenticatedUser } from "~/services/auth.server";import env from "~/env/env.server";import type { LoginProps } from "~/auth/index.client";-import { parsePlansEnv } from "@webstudio-is/trpc-interface/plan-features";+import { parsePlansEnv } from "@webstudio-is/plans";import { useLoginErrorMessage } from "~/shared/session";import {comparePathnames,diff --git a/apps/builder/app/services/workspace-router.server.ts b/apps/builder/app/services/workspace-router.server.tsindex 4c03ce4430..8ac3c48e1a 100644--- a/apps/builder/app/services/workspace-router.server.ts+++ b/apps/builder/app/services/workspace-router.server.ts@@ -6,8 +6,8 @@ import {} from "@webstudio-is/trpc-interface/index.server";import { workspace as workspaceApi } from "@webstudio-is/project/index.server";import { roles } from "@webstudio-is/trpc-interface/authorize";-import { getPlanInfo } from "@webstudio-is/trpc-interface/plan-client";-import { defaultPlanFeatures } from "@webstudio-is/trpc-interface/plan-features";+import { getPlanInfo, getPaidSeats } from "@webstudio-is/plans/index.server";+import { defaultPlanFeatures } from "@webstudio-is/plans";import env from "~/env/env.server";const Name = z.string().min(2).max(100);@@ -230,9 +230,44 @@ export const workspaceRouter = router({}// Pre-charge the seat before adding the member (Figma model).+ // We validate user existence first so that a missing account never+ // triggers a billing change.// When the payment worker is configured, a billing failure aborts the// invite so the member is never added. When the worker URL is not set// (self-hosted / dev), syncOwnerSeats returns early and this is a no-op.++ // Validate the invitee exists and is not already a member before+ // touching billing. This mirrors the checks in workspaceApi.addMember+ // so that we never charge for a doomed invite.+ const inviteeResult = await ctx.postgrest.client+ .from("User")+ .select("id")+ .eq("email", input.email)+ .maybeSingle();+ if (inviteeResult.error) {+ throw inviteeResult.error;+ }+ if (inviteeResult.data === null) {+ throw new Error(+ `No Webstudio account found for "${input.email}". The user needs to sign up first.`+ );+ }+ const existingMemberResult = await ctx.postgrest.client+ .from("WorkspaceMember")+ .select("userId")+ .eq("workspaceId", input.workspaceId)+ .eq("userId", inviteeResult.data.id)+ .is("removedAt", null)+ .maybeSingle();+ if (existingMemberResult.error) {+ throw existingMemberResult.error;+ }+ if (existingMemberResult.data !== null) {+ throw new Error(+ `${input.email} is already a member of this workspace.`+ );+ }+try {await syncOwnerSeats(input.workspaceId, ctx, +1);} catch (error) {@@ -298,7 +333,16 @@ export const workspaceRouter = router({.query(async ({ input, ctx }) => {try {const members = await workspaceApi.listMembers(input, ctx);- return { success: true as const, data: members };+ const paidSeats = await getPaidSeats(members.owner.userId, ctx);+ return {+ success: true as const,+ data: {+ ...members,+ // Falls back to minSeats (seats included in the plan) when no+ // subscription event exists yet (free plan, AppSumo, etc.).+ maxSeats: paidSeats ?? ctx.planFeatures.minSeats,+ },+ };} catch (error) {return createErrorResponse(error);}diff --git a/apps/builder/app/shared/context.server.ts b/apps/builder/app/shared/context.server.tsindex 4fb1f61be4..b44dc3b3b7 100644--- a/apps/builder/app/shared/context.server.ts+++ b/apps/builder/app/shared/context.server.ts@@ -4,11 +4,11 @@ import { authenticator } from "~/services/auth.server";import { trpcSharedClient } from "~/services/trpc.server";import { entryApi } from "./entri/entri-api.server";-import { defaultPlanFeatures } from "@webstudio-is/trpc-interface/plan-features";+import { defaultPlanFeatures } from "@webstudio-is/plans";import {getPlanInfo,getAuthorizationOwnerId,-} from "@webstudio-is/trpc-interface/plan-client";+} from "@webstudio-is/plans/index.server";import { staticEnv } from "~/env/env.static.server";import { createClient } from "@webstudio-is/postgrest/index.server";import { builderAuthenticator } from "~/services/builder-auth.server";diff --git a/apps/builder/app/shared/nano-states/misc.ts b/apps/builder/app/shared/nano-states/misc.tsindex b6ba4d466f..a28b566a2f 100644--- a/apps/builder/app/shared/nano-states/misc.ts+++ b/apps/builder/app/shared/nano-states/misc.ts@@ -10,7 +10,7 @@ import {defaultPlanFeatures,type PlanFeatures,type Purchase,-} from "@webstudio-is/trpc-interface/plan-features";+} from "@webstudio-is/plans";import type { Role } from "@webstudio-is/project";import type { User } from "~/shared/db/user.server";import { toast, type Placement } from "@webstudio-is/design-system";diff --git a/apps/builder/app/shared/permissions.ts b/apps/builder/app/shared/permissions.tsindex 511e561453..8efcb91466 100644--- a/apps/builder/app/shared/permissions.ts+++ b/apps/builder/app/shared/permissions.ts@@ -1,6 +1,6 @@import type { Role } from "@webstudio-is/project";import type { AuthPermit } from "@webstudio-is/trpc-interface/index.server";-import type { PlanFeatures } from "@webstudio-is/trpc-interface/plan-features";+import type { PlanFeatures } from "@webstudio-is/plans";/*** Human-readable descriptions of what each workspace role can do.diff --git a/apps/builder/app/shared/polly/topic-resolvers.server.test.ts b/apps/builder/app/shared/polly/topic-resolvers.server.test.tsindex f23a580e8f..c45d3b36d5 100644--- a/apps/builder/app/shared/polly/topic-resolvers.server.test.ts+++ b/apps/builder/app/shared/polly/topic-resolvers.server.test.ts@@ -6,13 +6,11 @@ import {json,} from "@webstudio-is/postgrest/testing";import type { AppContext } from "@webstudio-is/trpc-interface/index.server";-import { __testing__ } from "@webstudio-is/trpc-interface/plan-client";import { resolveTopics } from "./topic-resolvers.server";const server = createTestServer();afterEach(() => {- __testing__.resetProductCache();delete process.env.PLANS;});diff --git a/apps/builder/app/shared/polly/topic-resolvers.server.ts b/apps/builder/app/shared/polly/topic-resolvers.server.tsindex 3b79fdc26b..e7bc0cc773 100644--- a/apps/builder/app/shared/polly/topic-resolvers.server.ts+++ b/apps/builder/app/shared/polly/topic-resolvers.server.ts@@ -1,7 +1,7 @@import { notification } from "@webstudio-is/project/index.server";import { db as dashboardDb } from "@webstudio-is/dashboard/index.server";-import { getPlanInfo } from "@webstudio-is/trpc-interface/plan-client";-import { defaultPlanFeatures } from "@webstudio-is/trpc-interface/plan-features";+import { getPlanInfo } from "@webstudio-is/plans/index.server";+import { defaultPlanFeatures } from "@webstudio-is/plans";import { publicStaticEnv } from "~/env/env.static";import type { TopicResolvers, TopicName, SubscriptionResponse } from "./types";diff --git a/packages/plans/src/index.server.ts b/packages/plans/src/index.server.tsindex c98c6e670c..821442e44d 100644--- a/packages/plans/src/index.server.ts+++ b/packages/plans/src/index.server.ts@@ -1,6 +1,7 @@export * from "./index";export {getPlanInfo,+ getPaidSeats,getAuthorizationOwnerId,parsePlansEnv,parseProductMeta,diff --git a/packages/plans/src/plan-client.server.test.ts b/packages/plans/src/plan-client.server.test.tsindex afac7097ea..2d5e607f23 100644--- a/packages/plans/src/plan-client.server.test.ts+++ b/packages/plans/src/plan-client.server.test.ts@@ -8,7 +8,7 @@ import {import { type PlanFeatures, defaultPlanFeatures } from "./plan-features";import { getPlanInfo, __testing__ } from "./plan-client.server";-const { parseProductMeta, mergeProductMetas, resetProductCache } = __testing__;+const { parseProductMeta, mergeProductMetas } = __testing__;// ---------------------------------------------------------------------------// Unit tests for private helpers@@ -17,7 +17,6 @@ const { parseProductMeta, mergeProductMetas, resetProductCache } = __testing__;const server = createTestServer();beforeEach(() => {- resetProductCache();vi.unstubAllEnvs();});@@ -137,23 +136,6 @@ describe("getPlanInfo (msw)", () => {const result = await getPlanInfo(["user-1"], testContext);expect(result.get("user-1")?.purchases[0].planName).toBe("Pro");});-- test("Product table is queried only once across two calls (cache hit)", async () => {- vi.stubEnv("PLANS", JSON.stringify([]));- let productFetchCount = 0;- server.use(- db.get("UserProduct", () => json([proUserProduct])),- db.get("Product", () => {- productFetchCount += 1;- return json([proProduct]);- })- );-- await getPlanInfo(["user-1"], testContext);- await getPlanInfo(["user-1"], testContext);-- expect(productFetchCount).toBe(1);- });});/** Full-featured plan for use in tests — all booleans true, numeric limits at max */diff --git a/packages/plans/src/plan-client.server.ts b/packages/plans/src/plan-client.server.tsindex a2285e66c8..5491f6056e 100644--- a/packages/plans/src/plan-client.server.ts+++ b/packages/plans/src/plan-client.server.ts@@ -75,22 +75,33 @@ type Product = { id: string; name: string; meta: unknown };// The promise itself is cached to deduplicate concurrent cold-start requests.let productCachePromise: Promise<Map<string, Product>> | undefined;-const getProductCache = (+const fetchProducts = (postgrest: PostgrestContext-): Promise<Map<string, Product>> => {- if (productCachePromise !== undefined) {- return productCachePromise;- }- const promise: Promise<Map<string, Product>> = Promise.resolve(+): Promise<Map<string, Product>> =>+ Promise.resolve(postgrest.client.from("Product").select("id, name, meta")).then((result) => {if (result.error) {- productCachePromise = undefined;console.error(result.error);throw new Error("Failed to fetch products");}return new Map(result.data.map((p) => [p.id, p as Product]));});++const getProductCache = (+ postgrest: PostgrestContext+): Promise<Map<string, Product>> => {+ // Skip caching in test environment so each test gets a fresh fetch.+ if (process.env.VITEST !== undefined) {+ return fetchProducts(postgrest);+ }+ if (productCachePromise !== undefined) {+ return productCachePromise;+ }+ const promise = fetchProducts(postgrest);+ promise.catch(() => {+ productCachePromise = undefined;+ });productCachePromise = promise;return promise;};@@ -194,15 +205,48 @@ export const getPlanInfo = async ();};-/** Resets the module-level product cache. Only for use in tests. */-const resetProductCache = () => {- productCachePromise = undefined;+/**+ * Returns the Stripe subscription item quantity for the given user, derived+ * from the latest customer.subscription.updated/created event in TransactionLog.+ * Returns null when no subscription event exists yet (free plan, AppSumo, etc.).+ */+export const getPaidSeats = async (+ userId: string,+ context: { postgrest: PostgrestContext }+): Promise<number | null> => {+ const result = await context.postgrest.client+ .from("TransactionLog")+ .select("eventData")+ .eq("userId", userId)+ .in("eventType", [+ "customer.subscription.updated",+ "customer.subscription.created",+ ])+ .order("eventCreated", { ascending: false })+ .limit(1)+ .maybeSingle();++ if (result.error) {+ throw result.error;+ }++ const eventData = result.data?.eventData as+ | {+ data?: {+ object?: {+ items?: { data?: Array<{ quantity?: unknown }> };+ };+ };+ }+ | null+ | undefined;+ const rawQuantity = eventData?.data?.object?.items?.data?.[0]?.quantity;+ return typeof rawQuantity === "number" ? rawQuantity : null;};export const __testing__ = {parseProductMeta,mergeProductMetas,- resetProductCache,};export const getAuthorizationOwnerId = (diff --git a/packages/postgrest/src/__generated__/db-types.ts b/packages/postgrest/src/__generated__/db-types.tsindex cfda64e433..4f3443c3e1 100644--- a/packages/postgrest/src/__generated__/db-types.ts+++ b/packages/postgrest/src/__generated__/db-types.ts@@ -990,7 +990,6 @@ export type Database = {customerEmail: string | null;customerId: string | null;productId: string | null;- seatQuantity: number | null;subscriptionId: string | null;userId: string | null;};diff --git a/packages/prisma-client/prisma/migrations/20260413000000_user_product_drop_seat_quantity/migration.sql b/packages/prisma-client/prisma/migrations/20260413000000_user_product_drop_seat_quantity/migration.sqlnew file mode 100644index 0000000000..5b162e5d0f--- /dev/null+++ b/packages/prisma-client/prisma/migrations/20260413000000_user_product_drop_seat_quantity/migration.sql@@ -0,0 +1,50 @@+-- Remove seatQuantity from UserProduct view.+-- Seat quantity is now derived directly from TransactionLog in the application layer.+-- NOTE: PostgreSQL's CREATE OR REPLACE VIEW cannot remove columns; DROP + CREATE is required.+DROP VIEW IF EXISTS "UserProduct";+CREATE VIEW "UserProduct" AS (+ SELECT+ "userId",+ "subscriptionId",+ "productId",+ "customerId",+ "customerEmail"+ FROM+ "TransactionLog" AS tl+ WHERE+ "status" = 'complete'+ AND "eventType" = 'checkout.session.completed'+ AND NOT EXISTS (+ SELECT+ 1+ FROM+ "TransactionLog" AS tlexsists+ WHERE+ tlexsists."subscriptionId" = tl."subscriptionId"+ AND tlexsists."eventType" = 'customer.subscription.deleted'+ AND tlexsists."status" = 'canceled'+ AND tlexsists."eventCreated" > tl."eventCreated")+ AND NOT EXISTS (+ SELECT+ 1+ FROM+ "TransactionLog" AS tlexsists+ WHERE+ tlexsists."paymentIntent" = tl."paymentIntent"+ AND tlexsists."eventType" = 'charge.refunded'+ AND tlexsists."status" = 'succeeded'+ AND tlexsists."eventCreated" > tl."eventCreated")+ ORDER BY+ "userId",+ "eventCreated" DESC)+ UNION ALL (+ SELECT+ "userId",+ "subscriptionId",+ "productId",+ "customerId",+ "customerEmail"+ FROM+ "TransactionLog"+ WHERE+ "eventType" = 'appsumo.activate');diff --git a/packages/project/package.json b/packages/project/package.jsonindex 6654405fc2..9e420b79b7 100644--- a/packages/project/package.json+++ b/packages/project/package.json@@ -14,6 +14,7 @@"@webstudio-is/asset-uploader": "workspace:*","@webstudio-is/authorization-token": "workspace:*","@webstudio-is/feature-flags": "workspace:*",+ "@webstudio-is/plans": "workspace:*","@webstudio-is/postgrest": "workspace:*","@webstudio-is/project-build": "workspace:*","@webstudio-is/trpc-interface": "workspace:*",diff --git a/packages/project/src/db/notification.test.ts b/packages/project/src/db/notification.test.tsindex bde759cf47..9f4e1ca26b 100644--- a/packages/project/src/db/notification.test.ts+++ b/packages/project/src/db/notification.test.ts@@ -7,7 +7,7 @@ import {testContext,} from "@webstudio-is/postgrest/testing";import type { AppContext } from "@webstudio-is/trpc-interface/index.server";-import { defaultPlanFeatures } from "@webstudio-is/trpc-interface/plan-features";+import { defaultPlanFeatures } from "@webstudio-is/plans";import { accept, __testing__ } from "./notification";const { describeNotification } = __testing__;diff --git a/packages/project/src/db/project.test.ts b/packages/project/src/db/project.test.tsindex c4e4cadb58..f778c41759 100644--- a/packages/project/src/db/project.test.ts+++ b/packages/project/src/db/project.test.ts@@ -7,7 +7,7 @@ import {testContext,} from "@webstudio-is/postgrest/testing";import type { AppContext } from "@webstudio-is/trpc-interface/index.server";-import { defaultPlanFeatures } from "@webstudio-is/trpc-interface/plan-features";+import { defaultPlanFeatures } from "@webstudio-is/plans";import { create } from "./project";const server = createTestServer();diff --git a/packages/project/src/db/workspace.test.ts b/packages/project/src/db/workspace.test.tsindex 7979a667af..6159e40aca 100644--- a/packages/project/src/db/workspace.test.ts+++ b/packages/project/src/db/workspace.test.ts@@ -8,7 +8,7 @@ import {} from "@webstudio-is/postgrest/testing";import type { AppContext } from "@webstudio-is/trpc-interface/index.server";import { AuthorizationError } from "@webstudio-is/trpc-interface/index.server";-import { defaultPlanFeatures } from "@webstudio-is/trpc-interface/plan-features";+import { defaultPlanFeatures } from "@webstudio-is/plans";import {create,rename,@@ -255,17 +255,18 @@ describe("countAllMembers (msw)", () => {describe("addMember (msw)", () => {const ownerWorkspace = { id: "ws-1", userId: "user-1" };- test("silently succeeds when invited email does not exist", async () => {+ test("throws when invited email does not exist", async () => {server.use(db.get("Workspace", () => json(ownerWorkspace)),db.get("User", () => json(null)));- const result = await addMember(- { workspaceId: "ws-1", email: "[email protected]", relation: "editors" },- createContext()- );- expect(typeof result.notificationId).toBe("string");+ await expect(+ addMember(+ { workspaceId: "ws-1", email: "[email protected]", relation: "editors" },+ createContext()+ )+ ).rejects.toThrow('No Webstudio account found for "[email protected]"');});test("throws when inviting yourself", async () => {@@ -284,7 +285,7 @@ describe("addMember (msw)", () => {).rejects.toThrow("already the owner");});- test("silently succeeds when invitee is already a member", async () => {+ test("throws when invitee is already a member", async () => {server.use(db.get("Workspace", () => json(ownerWorkspace)),db.get("User", () =>@@ -293,11 +294,12 @@ describe("addMember (msw)", () => {db.get("WorkspaceMember", () => json({ userId: "user-2" })));- const result = await addMember(- { workspaceId: "ws-1", email: "[email protected]", relation: "editors" },- createContext()- );- expect(typeof result.notificationId).toBe("string");+ await expect(+ addMember(+ { workspaceId: "ws-1", email: "[email protected]", relation: "editors" },+ createContext()+ )+ ).rejects.toThrow("[email protected] is already a member");});});diff --git a/packages/project/src/db/workspace.ts b/packages/project/src/db/workspace.tsindex e3f9d8c3ea..aae6ccf253 100644--- a/packages/project/src/db/workspace.ts+++ b/packages/project/src/db/workspace.ts@@ -368,10 +368,10 @@ export const addMember = async (throw user.error;}- // User not found — silently succeed without creating a placeholder.- // Returns the same shape to prevent email enumeration.if (user.data === null) {- return { notificationId: crypto.randomUUID() };+ throw new Error(+ `No Webstudio account found for "${email}". The user needs to sign up first.`+ );}if (user.data.id === userId) {@@ -394,8 +394,7 @@ export const addMember = async (}if (existing.data !== null) {- // Already a member — silently succeed- return { notificationId: crypto.randomUUID() };+ throw new Error(`${email} is already a member of this workspace.`);}// Create a pending notification instead of inserting directlydiff --git a/packages/project/src/trpc/workspace-router.ts b/packages/project/src/trpc/workspace-router.tsindex e75406b467..76d62afc9a 100644--- a/packages/project/src/trpc/workspace-router.ts+++ b/packages/project/src/trpc/workspace-router.ts@@ -82,8 +82,6 @@ export const workspaceRouter = router({}const { notificationId } = await workspaceApi.addMember(input, ctx);- // notificationId is always returned — it's a real ID for existing users- // and a fake UUID for non-existing users to prevent email enumeration.return { success: true as const, notificationId };} catch (error) {return createErrorResponse(error);diff --git a/packages/trpc-interface/package.json b/packages/trpc-interface/package.jsonindex 1264ee5668..0a3af4b8c5 100644--- a/packages/trpc-interface/package.json+++ b/packages/trpc-interface/package.json@@ -28,14 +28,6 @@"webstudio": "./src/index.server.ts","import": "./src/index.server.ts"},- "./plan-features": {- "webstudio": "./src/shared/plan-features.ts",- "import": "./src/shared/plan-features.ts"- },- "./plan-client": {- "webstudio": "./src/shared/plan-client.server.ts",- "import": "./src/shared/plan-client.server.ts"- },"./authorize": {"webstudio": "./src/authorize/role.ts","import": "./src/authorize/role.ts"diff --git a/packages/trpc-interface/src/authorize/project.server.test.ts b/packages/trpc-interface/src/authorize/project.server.test.tsindex 00700eb494..801dd245fe 100644--- a/packages/trpc-interface/src/authorize/project.server.test.ts+++ b/packages/trpc-interface/src/authorize/project.server.test.ts@@ -6,7 +6,7 @@ import {testContext,} from "@webstudio-is/postgrest/testing";import type { AppContext } from "../context/context.server";-import { defaultPlanFeatures } from "../shared/plan-features";+import { defaultPlanFeatures } from "@webstudio-is/plans";import {checkProjectPermit,hasProjectPermit,diff --git a/packages/trpc-interface/src/shared/plan-client.server.ts b/packages/trpc-interface/src/shared/plan-client.server.tsdeleted file mode 100644index d07390ee60..0000000000--- a/packages/trpc-interface/src/shared/plan-client.server.ts+++ /dev/null@@ -1,7 +0,0 @@-// Re-exported from @webstudio-is/plans — all plan client logic lives there.-export {- getPlanInfo,- getAuthorizationOwnerId,- parsePlansEnv,- __testing__,-} from "@webstudio-is/plans/index.server";diff --git a/packages/trpc-interface/src/shared/plan-features.ts b/packages/trpc-interface/src/shared/plan-features.tsdeleted file mode 100644index 253005a21a..0000000000--- a/packages/trpc-interface/src/shared/plan-features.ts+++ /dev/null@@ -1,7 +0,0 @@-// Re-exported from @webstudio-is/plans — all plan feature logic lives there.-export {- PlanFeaturesSchema,- defaultPlanFeatures,- parsePlansEnv,-} from "@webstudio-is/plans";-export type { PlanFeatures, Purchase } from "@webstudio-is/plans";diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 5af5517278..f38cab655a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1767,6 +1767,9 @@ importers:'@webstudio-is/feature-flags':specifier: workspace:*version: link:../feature-flags+ '@webstudio-is/plans':+ specifier: workspace:*+ version: link:../plans'@webstudio-is/postgrest':specifier: workspace:*version: link:../postgrest