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.

chore: Publish plans package (#5690)

Oleg Isonen8ed5707a8d48
diff --git a/apps/builder/app/routes/auth.dev.tsx b/apps/builder/app/routes/auth.dev.tsx
index 635ce5feee..256f66d918 100644
--- a/apps/builder/app/routes/auth.dev.tsx
+++ b/apps/builder/app/routes/auth.dev.tsx
@@ -5,7 +5,7 @@ import { AUTH_PROVIDERS } from "~/shared/session";
import { clearReturnToCookie, returnToPath } from "~/services/cookie.server";
import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";
import { redirect, setNoStoreToRedirect } from "~/services/no-store-redirect";
-import { applyDevPlan } from "~/services/dev-plan.server";
+import { applyDevPlan } from "@webstudio-is/plans/index.server";
import { createPostgrestContext } from "~/shared/context.server";
export default function Dev() {
diff --git a/apps/builder/package.json b/apps/builder/package.json
index 8cfa0e3adc..cc83328a32 100644
--- a/apps/builder/package.json
+++ b/apps/builder/package.json
@@ -82,6 +82,7 @@
"@webstudio-is/sdk-components-react-radix": "workspace:*",
"@webstudio-is/template": "workspace:*",
"@webstudio-is/trpc-interface": "workspace:*",
+ "@webstudio-is/plans": "workspace:*",
"args-tokenizer": "^0.3.0",
"bcp-47": "^2.1.0",
"change-case": "^5.4.4",
diff --git a/packages/plans/package.json b/packages/plans/package.json
new file mode 100644
index 0000000000..97f10ce049
--- /dev/null
+++ b/packages/plans/package.json
@@ -0,0 +1,32 @@
+{
+ "name": "@webstudio-is/plans",
+ "version": "0.0.0-webstudio-version",
+ "description": "Plan features and billing logic for Webstudio",
+ "author": "Webstudio <[email protected]>",
+ "homepage": "https://webstudio.is",
+ "license": "AGPL-3.0-or-later",
+ "type": "module",
+ "scripts": {
+ "typecheck": "tsgo --noEmit",
+ "test": "vitest run"
+ },
+ "dependencies": {
+ "zod": "^3.24.2"
+ },
+ "devDependencies": {
+ "@webstudio-is/postgrest": "workspace:*",
+ "@webstudio-is/tsconfig": "workspace:*",
+ "vitest": "^3.1.2"
+ },
+ "exports": {
+ ".": {
+ "webstudio": "./src/index.ts",
+ "import": "./src/index.ts"
+ },
+ "./index.server": {
+ "webstudio": "./src/index.server.ts",
+ "import": "./src/index.server.ts"
+ }
+ },
+ "sideEffects": false
+}
diff --git a/apps/builder/app/services/dev-plan.server.test.ts b/packages/plans/src/dev-plan.server.test.ts
similarity index 97%
rename from apps/builder/app/services/dev-plan.server.test.ts
rename to packages/plans/src/dev-plan.server.test.ts
index 86b3c2e73a..f8e2def42f 100644
--- a/apps/builder/app/services/dev-plan.server.test.ts
+++ b/packages/plans/src/dev-plan.server.test.ts
@@ -6,7 +6,7 @@ import {
json,
empty,
} from "@webstudio-is/postgrest/testing";
-import { applyDevPlan } from "~/services/dev-plan.server";
+import { applyDevPlan } from "./dev-plan.server";
const server = createTestServer();
diff --git a/apps/builder/app/services/dev-plan.server.ts b/packages/plans/src/dev-plan.server.ts
similarity index 93%
rename from apps/builder/app/services/dev-plan.server.ts
rename to packages/plans/src/dev-plan.server.ts
index 64360e3b7f..bf247e4397 100644
--- a/apps/builder/app/services/dev-plan.server.ts
+++ b/packages/plans/src/dev-plan.server.ts
@@ -1,4 +1,6 @@
-import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
+import type { Client } from "@webstudio-is/postgrest/index.server";
+
+type PostgrestContext = { client: Client };
/**
* Upsert or delete dev plan rows in the DB for the given user email.
@@ -12,7 +14,7 @@ import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
export const applyDevPlan = async (
email: string,
planName: string | null,
- context: Pick<AppContext, "postgrest">
+ context: { postgrest: PostgrestContext }
) => {
const { postgrest } = context;
// Resolve userId from email (user was already created by the authenticator).
diff --git a/packages/plans/src/index.server.ts b/packages/plans/src/index.server.ts
new file mode 100644
index 0000000000..c98c6e670c
--- /dev/null
+++ b/packages/plans/src/index.server.ts
@@ -0,0 +1,11 @@
+export * from "./index";
+export {
+ getPlanInfo,
+ getAuthorizationOwnerId,
+ parsePlansEnv,
+ parseProductMeta,
+ mergeProductMetas,
+ buildPurchases,
+ __testing__,
+} from "./plan-client.server";
+export { applyDevPlan } from "./dev-plan.server";
diff --git a/packages/plans/src/index.ts b/packages/plans/src/index.ts
new file mode 100644
index 0000000000..856b2aa502
--- /dev/null
+++ b/packages/plans/src/index.ts
@@ -0,0 +1,6 @@
+export {
+ PlanFeaturesSchema,
+ defaultPlanFeatures,
+ parsePlansEnv,
+} from "./plan-features";
+export type { PlanFeatures, Purchase } from "./plan-features";
diff --git a/packages/trpc-interface/src/shared/plan-client.server.test.ts b/packages/plans/src/plan-client.server.test.ts
similarity index 100%
rename from packages/trpc-interface/src/shared/plan-client.server.test.ts
rename to packages/plans/src/plan-client.server.test.ts
diff --git a/packages/plans/src/plan-client.server.ts b/packages/plans/src/plan-client.server.ts
new file mode 100644
index 0000000000..a2285e66c8
--- /dev/null
+++ b/packages/plans/src/plan-client.server.ts
@@ -0,0 +1,218 @@
+import type { Client } from "@webstudio-is/postgrest/index.server";
+import {
+ type PlanFeatures,
+ PlanFeaturesSchema,
+ defaultPlanFeatures,
+ parsePlansEnv,
+ type Purchase,
+} from "./plan-features";
+
+export { parsePlansEnv } from "./plan-features";
+
+type PostgrestContext = { client: Client };
+
+type AuthorizationContext =
+ | { type: "token"; ownerId: string }
+ | { type: "user"; userId: string }
+ | { type: "service" }
+ | { type: "anonymous" };
+
+type PlanInfo = {
+ planFeatures: PlanFeatures;
+ purchases: Array<Purchase>;
+};
+
+export const parseProductMeta = (meta: unknown): Partial<PlanFeatures> => {
+ const result = PlanFeaturesSchema.partial().safeParse(meta);
+ return result.success ? result.data : {};
+};
+
+export const mergeProductMetas = (
+ productMetas: Array<PlanFeatures>
+): PlanFeatures => {
+ if (productMetas.length === 0) {
+ return defaultPlanFeatures;
+ }
+
+ return Object.fromEntries(
+ (Object.keys(defaultPlanFeatures) as Array<keyof PlanFeatures>).map(
+ (key) => {
+ const vals = productMetas.map((item) => item[key]);
+ const merged =
+ typeof defaultPlanFeatures[key] === "boolean"
+ ? (vals as Array<boolean>).some(Boolean)
+ : Math.max(...(vals as Array<number>));
+ return [key, merged];
+ }
+ )
+ ) as PlanFeatures;
+};
+
+export const buildPurchases = (
+ userProducts: Array<{
+ productId: string | null | undefined;
+ subscriptionId: string | null | undefined;
+ }>,
+ productIdToName: Map<string, string>
+): Array<Purchase> => {
+ const purchases: Array<Purchase> = [];
+ for (const userProduct of userProducts) {
+ if (userProduct.productId === null || userProduct.productId === undefined) {
+ continue;
+ }
+ purchases.push({
+ planName: productIdToName.get(userProduct.productId) ?? "",
+ subscriptionId: userProduct.subscriptionId ?? undefined,
+ });
+ }
+ return purchases;
+};
+
+type Product = { id: string; name: string; meta: unknown };
+
+// Products are admin-created and rarely change. Cache them for the lifetime of the
+// server instance to avoid a repeated DB round-trip on every request.
+// The promise itself is cached to deduplicate concurrent cold-start requests.
+let productCachePromise: Promise<Map<string, Product>> | undefined;
+
+const getProductCache = (
+ postgrest: PostgrestContext
+): Promise<Map<string, Product>> => {
+ if (productCachePromise !== undefined) {
+ return productCachePromise;
+ }
+ const promise: 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]));
+ });
+ productCachePromise = promise;
+ return promise;
+};
+
+export const getPlanInfo = async (
+ userIds: string[],
+ context: { postgrest: PostgrestContext }
+): Promise<Map<string, PlanInfo>> => {
+ const { postgrest } = context;
+
+ if (userIds.length === 0) {
+ return new Map();
+ }
+
+ const userProductsResult = await postgrest.client
+ .from("UserProduct")
+ .select("userId, subscriptionId, productId")
+ .in("userId", userIds);
+
+ if (userProductsResult.error) {
+ console.error(userProductsResult.error);
+ throw new Error("Failed to fetch user products");
+ }
+
+ const userProductsByUserId = new Map<
+ string,
+ Array<{
+ productId: string | null;
+ subscriptionId: string | null;
+ }>
+ >();
+
+ for (const row of userProductsResult.data) {
+ if (row.userId === null) {
+ continue;
+ }
+ const rows = userProductsByUserId.get(row.userId) ?? [];
+ rows.push({
+ productId: row.productId,
+ subscriptionId: row.subscriptionId,
+ });
+ userProductsByUserId.set(row.userId, rows);
+ }
+
+ const productIds = [
+ ...new Set(
+ userProductsResult.data.flatMap(({ productId }) =>
+ productId === null || productId === undefined ? [] : [productId]
+ )
+ ),
+ ];
+
+ if (productIds.length === 0) {
+ return new Map(
+ userIds.map((userId) => [
+ userId,
+ { planFeatures: defaultPlanFeatures, purchases: [] },
+ ])
+ );
+ }
+
+ const allProducts = await getProductCache(postgrest);
+ const productById = new Map(
+ productIds.flatMap((id) => {
+ const product = allProducts.get(id);
+ return product !== undefined ? [[id, product] as const] : [];
+ })
+ );
+ const productIdToName = new Map(
+ [...productById.values()].map((product) => [product.id, product.name])
+ );
+ const plansByName = parsePlansEnv(process.env.PLANS ?? "[]");
+
+ return new Map(
+ userIds.map((userId) => {
+ const userProducts = userProductsByUserId.get(userId) ?? [];
+ const productMetas = userProducts.flatMap(({ productId }) => {
+ if (productId === null || productId === undefined) {
+ return [];
+ }
+ const product = productById.get(productId);
+ if (product === undefined) {
+ return [];
+ }
+ return [
+ {
+ ...(plansByName.get(product.name) ?? defaultPlanFeatures),
+ ...parseProductMeta(product.meta),
+ },
+ ];
+ });
+
+ return [
+ userId,
+ {
+ planFeatures: mergeProductMetas(productMetas),
+ purchases: buildPurchases(userProducts, productIdToName),
+ },
+ ];
+ })
+ );
+};
+
+/** Resets the module-level product cache. Only for use in tests. */
+const resetProductCache = () => {
+ productCachePromise = undefined;
+};
+
+export const __testing__ = {
+ parseProductMeta,
+ mergeProductMetas,
+ resetProductCache,
+};
+
+export const getAuthorizationOwnerId = (
+ authorization: AuthorizationContext
+): string | undefined => {
+ if (authorization.type === "token") {
+ return authorization.ownerId;
+ }
+ if (authorization.type === "user") {
+ return authorization.userId;
+ }
+ return undefined;
+};
diff --git a/packages/trpc-interface/src/shared/plan-features.test.ts b/packages/plans/src/plan-features.test.ts
similarity index 100%
rename from packages/trpc-interface/src/shared/plan-features.test.ts
rename to packages/plans/src/plan-features.test.ts
diff --git a/packages/plans/src/plan-features.ts b/packages/plans/src/plan-features.ts
new file mode 100644
index 0000000000..b56137a723
--- /dev/null
+++ b/packages/plans/src/plan-features.ts
@@ -0,0 +1,150 @@
+import { z } from "zod";
+
+/**
+ * Zod schema for validating partial plan features from external sources
+ * (e.g. product.meta JSON blobs). Only known keys of the correct type
+ * are kept — anything else is silently stripped.
+ */
+export const PlanFeaturesSchema = z.object({
+ canDownloadAssets: z.boolean(),
+ canRestoreBackups: z.boolean(),
+ allowAdditionalPermissions: z.boolean(),
+ allowDynamicData: z.boolean(),
+ allowContentMode: z.boolean(),
+ allowStagingPublish: z.boolean(),
+ maxContactEmailsPerProject: z.number().nonnegative(),
+ maxDomainsAllowedPerUser: z.number().nonnegative(),
+ maxDailyPublishesPerUser: z.number().nonnegative(),
+ maxWorkspaces: z.number().nonnegative(),
+ maxProjectsAllowedPerUser: z.number().nonnegative(),
+ maxAssetsPerProject: z.number().nonnegative(),
+ minSeats: z.number().nonnegative(),
+ maxSeatsPerWorkspace: z.number().nonnegative(),
+});
+
+export type PlanFeatures = z.infer<typeof PlanFeaturesSchema>;
+
+// Compile-time guard: all PlanFeatures values must be boolean or number.
+// If a new field with a different type is added to PlanFeaturesSchema, this line will error.
+type _AssertBooleanOrNumber =
+ PlanFeatures extends Record<string, boolean | number> ? true : never;
+const _checkPlanFeaturesValueTypes: _AssertBooleanOrNumber = true;
+void _checkPlanFeaturesValueTypes;
+
+/** Default (free) plan — the baseline, all features disabled / at minimum limits */
+export const defaultPlanFeatures: PlanFeatures = {
+ canDownloadAssets: false,
+ canRestoreBackups: false,
+ allowAdditionalPermissions: false,
+ allowDynamicData: false,
+ allowContentMode: false,
+ allowStagingPublish: false,
+ maxContactEmailsPerProject: 0,
+ maxDomainsAllowedPerUser: 0,
+ maxDailyPublishesPerUser: 10,
+ maxWorkspaces: 1,
+ maxProjectsAllowedPerUser: 100,
+ maxAssetsPerProject: 50,
+ minSeats: 0,
+ maxSeatsPerWorkspace: 0,
+};
+
+/** All user purchases (subscriptions and LTDs). subscriptionId present only for recurring subscriptions */
+export type Purchase = {
+ planName: string;
+ subscriptionId?: string;
+};
+
+/**
+ * Parse the PLANS env variable (JSON array of {name, extends?, features}).
+ * - features is partial when extends is used; the parent plan fills in the rest.
+ * - The final merged features are validated against the full PlanFeaturesSchema.
+ * - Invalid entries are skipped with a console.error.
+ * - An extends reference to an unknown plan name throws an error.
+ * Returns a Map of plan name → resolved PlanFeatures.
+ */
+export const parsePlansEnv = (raw: string): Map<string, PlanFeatures> => {
+ try {
+ const parsed = JSON.parse(raw);
+ if (!Array.isArray(parsed)) {
+ return new Map();
+ }
+
+ type PlanEntry = {
+ name: string;
+ extends?: string;
+ features: Partial<PlanFeatures>;
+ };
+
+ // First pass: validate entry structure and collect partial features.
+ const entries: PlanEntry[] = parsed.flatMap((item) => {
+ if (
+ typeof item !== "object" ||
+ item === null ||
+ typeof item.name !== "string"
+ ) {
+ console.error("Invalid PLANS entry (missing name):", item);
+ return [];
+ }
+ if ("extends" in item && typeof item.extends !== "string") {
+ console.error("Invalid PLANS entry (extends must be a string):", item);
+ return [];
+ }
+ const result = PlanFeaturesSchema.partial().safeParse(
+ "features" in item ? item.features : {}
+ );
+ if (!result.success) {
+ console.error(
+ `Invalid PLANS entry "${item.name}" features:`,
+ result.error.flatten()
+ );
+ return [];
+ }
+ return [
+ {
+ name: item.name,
+ extends: "extends" in item ? (item.extends as string) : undefined,
+ features: result.data,
+ } satisfies PlanEntry,
+ ];
+ });
+
+ // Build name → partial features map for resolving extends.
+ const byName = new Map<string, Partial<PlanFeatures>>(
+ entries.map((e) => [e.name, e.features])
+ );
+
+ // Second pass: resolve extends and validate the full feature set.
+ // Every entry implicitly extends defaultPlanFeatures; "extends" picks a named plan on top of that.
+ const resolved = new Map<string, PlanFeatures>();
+ for (const entry of entries) {
+ if (entry.extends !== undefined && !byName.has(entry.extends)) {
+ throw new Error(
+ `PLANS entry "${entry.name}" extends unknown plan "${entry.extends}"`
+ );
+ }
+ const parentFeatures: PlanFeatures =
+ entry.extends === undefined
+ ? defaultPlanFeatures
+ : { ...defaultPlanFeatures, ...byName.get(entry.extends)! };
+ const result = PlanFeaturesSchema.safeParse({
+ ...parentFeatures,
+ ...entry.features,
+ });
+ if (!result.success) {
+ console.error(
+ `Invalid PLANS entry "${entry.name}" features after resolving extends:`,
+ result.error.flatten()
+ );
+ continue;
+ }
+ resolved.set(entry.name, result.data);
+ }
+ return resolved;
+ } catch (error) {
+ if (error instanceof Error && error.message.startsWith("PLANS entry")) {
+ throw error;
+ }
+ return new Map();
+ }
+};
diff --git a/packages/plans/tsconfig.json b/packages/plans/tsconfig.json
new file mode 100644
index 0000000000..d2e5040f8f
--- /dev/null
+++ b/packages/plans/tsconfig.json
@@ -0,0 +1,3 @@
+{
+ "extends": "@webstudio-is/tsconfig/base.json"
+}
diff --git a/packages/trpc-interface/package.json b/packages/trpc-interface/package.json
index 35721e0c06..1264ee5668 100644
--- a/packages/trpc-interface/package.json
+++ b/packages/trpc-interface/package.json
@@ -1,6 +1,6 @@
{
"name": "@webstudio-is/trpc-interface",
- "version": "0.0.0",
+ "version": "0.0.0-webstudio-version",
"description": "Webstudio TRPC Interface",
"author": "Webstudio <[email protected]>",
"homepage": "https://webstudio.is",
@@ -11,6 +11,7 @@
},
"dependencies": {
"@webstudio-is/feature-flags": "workspace:*",
+ "@webstudio-is/plans": "workspace:*",
"@trpc/client": "^10.45.2",
"@trpc/server": "^10.45.2",
"memoize": "^10.0.0",
@@ -24,19 +25,22 @@
},
"exports": {
"./index.server": {
- "webstudio": "./src/index.server.ts"
+ "webstudio": "./src/index.server.ts",
+ "import": "./src/index.server.ts"
},
"./plan-features": {
- "webstudio": "./src/shared/plan-features.ts"
+ "webstudio": "./src/shared/plan-features.ts",
+ "import": "./src/shared/plan-features.ts"
},
"./plan-client": {
- "webstudio": "./src/shared/plan-client.server.ts"
+ "webstudio": "./src/shared/plan-client.server.ts",
+ "import": "./src/shared/plan-client.server.ts"
},
"./authorize": {
- "webstudio": "./src/authorize/role.ts"
+ "webstudio": "./src/authorize/role.ts",
+ "import": "./src/authorize/role.ts"
}
},
"license": "AGPL-3.0-or-later",
- "private": true,
"sideEffects": false
}
diff --git a/packages/trpc-interface/src/context/context.server.ts b/packages/trpc-interface/src/context/context.server.ts
index 9f69ddc36b..634d97ed7d 100644
--- a/packages/trpc-interface/src/context/context.server.ts
+++ b/packages/trpc-interface/src/context/context.server.ts
@@ -1,6 +1,6 @@
import type { TrpcInterfaceClient } from "../shared/shared-router";
import type { Client } from "@webstudio-is/postgrest/index.server";
-import type { PlanFeatures, Purchase } from "../shared/plan-features";
+import type { PlanFeatures, Purchase } from "@webstudio-is/plans";
/**
* All necessary parameters for Authorization
diff --git a/packages/trpc-interface/src/shared/plan-client.server.ts b/packages/trpc-interface/src/shared/plan-client.server.ts
index 2c3f9affef..d07390ee60 100644
--- a/packages/trpc-interface/src/shared/plan-client.server.ts
+++ b/packages/trpc-interface/src/shared/plan-client.server.ts
@@ -1,208 +1,7 @@
-import {
- type PlanFeatures,
- PlanFeaturesSchema,
- defaultPlanFeatures,
+// Re-exported from @webstudio-is/plans — all plan client logic lives there.
+export {
+ getPlanInfo,
+ getAuthorizationOwnerId,
parsePlansEnv,
- type Purchase,
-} from "./plan-features";
-import type { AppContext } from "../context/context.server";
-
-export { parsePlansEnv } from "./plan-features";
-
-type PlanInfo = {
- planFeatures: PlanFeatures;
- purchases: Array<Purchase>;
-};
-
-const parseProductMeta = (meta: unknown): Partial<PlanFeatures> => {
- const result = PlanFeaturesSchema.partial().safeParse(meta);
- return result.success ? result.data : {};
-};
-
-const mergeProductMetas = (productMetas: Array<PlanFeatures>): PlanFeatures => {
- if (productMetas.length === 0) {
- return defaultPlanFeatures;
- }
-
- return Object.fromEntries(
- (Object.keys(defaultPlanFeatures) as Array<keyof PlanFeatures>).map(
- (key) => {
- const vals = productMetas.map((item) => item[key]);
- const merged =
- typeof defaultPlanFeatures[key] === "boolean"
- ? (vals as Array<boolean>).some(Boolean)
- : Math.max(...(vals as Array<number>));
- return [key, merged];
- }
- )
- ) as PlanFeatures;
-};
-
-const buildPurchases = (
- userProducts: Array<{
- productId: string | null | undefined;
- subscriptionId: string | null | undefined;
- }>,
- productIdToName: Map<string, string>
-): Array<Purchase> => {
- const purchases: Array<Purchase> = [];
- for (const userProduct of userProducts) {
- if (userProduct.productId === null || userProduct.productId === undefined) {
- continue;
- }
- purchases.push({
- planName: productIdToName.get(userProduct.productId) ?? "",
- subscriptionId: userProduct.subscriptionId ?? undefined,
- });
- }
- return purchases;
-};
-
-type Product = { id: string; name: string; meta: unknown };
-
-// Products are admin-created and rarely change. Cache them for the lifetime of the
-// server instance to avoid a repeated DB round-trip on every request.
-// The promise itself is cached to deduplicate concurrent cold-start requests.
-let productCachePromise: Promise<Map<string, Product>> | undefined;
-
-const getProductCache = (
- postgrest: AppContext["postgrest"]
-): Promise<Map<string, Product>> => {
- if (productCachePromise !== undefined) {
- return productCachePromise;
- }
- const promise: 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]));
- });
- productCachePromise = promise;
- return promise;
-};
-
-export const getPlanInfo = async (
- userIds: string[],
- context: Pick<AppContext, "postgrest">
-): Promise<Map<string, PlanInfo>> => {
- const { postgrest } = context;
-
- if (userIds.length === 0) {
- return new Map();
- }
-
- const userProductsResult = await postgrest.client
- .from("UserProduct")
- .select("userId, subscriptionId, productId")
- .in("userId", userIds);
-
- if (userProductsResult.error) {
- console.error(userProductsResult.error);
- throw new Error("Failed to fetch user products");
- }
-
- const userProductsByUserId = new Map<
- string,
- Array<{
- productId: string | null;
- subscriptionId: string | null;
- }>
- >();
-
- for (const row of userProductsResult.data) {
- if (row.userId === null) {
- continue;
- }
- const rows = userProductsByUserId.get(row.userId) ?? [];
- rows.push({
- productId: row.productId,
- subscriptionId: row.subscriptionId,
- });
- userProductsByUserId.set(row.userId, rows);
- }
-
- const productIds = [
- ...new Set(
- userProductsResult.data.flatMap(({ productId }) =>
- productId === null || productId === undefined ? [] : [productId]
- )
- ),
- ];
-
- if (productIds.length === 0) {
- return new Map(
- userIds.map((userId) => [
- userId,
- { planFeatures: defaultPlanFeatures, purchases: [] },
- ])
- );
- }
-
- const allProducts = await getProductCache(postgrest);
- const productById = new Map(
- productIds.flatMap((id) => {
- const product = allProducts.get(id);
- return product !== undefined ? [[id, product] as const] : [];
- })
- );
- const productIdToName = new Map(
- [...productById.values()].map((product) => [product.id, product.name])
- );
- const plansByName = parsePlansEnv(process.env.PLANS ?? "[]");
-
- return new Map(
- userIds.map((userId) => {
- const userProducts = userProductsByUserId.get(userId) ?? [];
- const productMetas = userProducts.flatMap(({ productId }) => {
- if (productId === null || productId === undefined) {
- return [];
- }
- const product = productById.get(productId);
- if (product === undefined) {
- return [];
- }
- return [
- {
- ...(plansByName.get(product.name) ?? defaultPlanFeatures),
- ...parseProductMeta(product.meta),
- },
- ];
- });
-
- return [
- userId,
- {
- planFeatures: mergeProductMetas(productMetas),
- purchases: buildPurchases(userProducts, productIdToName),
- },
- ];
- })
- );
-};
-
-/** Resets the module-level product cache. Only for use in tests. */
-const resetProductCache = () => {
- productCachePromise = undefined;
-};
-
-export const __testing__ = {
- parseProductMeta,
- mergeProductMetas,
- resetProductCache,
-};
-
-export const getAuthorizationOwnerId = (
- authorization: AppContext["authorization"]
-): string | undefined => {
- if (authorization.type === "token") {
- return authorization.ownerId;
- }
- if (authorization.type === "user") {
- return authorization.userId;
- }
- return undefined;
-};
+ __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.ts
index b56137a723..253005a21a 100644
--- a/packages/trpc-interface/src/shared/plan-features.ts
+++ b/packages/trpc-interface/src/shared/plan-features.ts
@@ -1,150 +1,7 @@
-import { z } from "zod";
-
-/**
- * Zod schema for validating partial plan features from external sources
- * (e.g. product.meta JSON blobs). Only known keys of the correct type
- * are kept — anything else is silently stripped.
- */
-export const PlanFeaturesSchema = z.object({
- canDownloadAssets: z.boolean(),
- canRestoreBackups: z.boolean(),
- allowAdditionalPermissions: z.boolean(),
- allowDynamicData: z.boolean(),
- allowContentMode: z.boolean(),
- allowStagingPublish: z.boolean(),
- maxContactEmailsPerProject: z.number().nonnegative(),
- maxDomainsAllowedPerUser: z.number().nonnegative(),
- maxDailyPublishesPerUser: z.number().nonnegative(),
- maxWorkspaces: z.number().nonnegative(),
- maxProjectsAllowedPerUser: z.number().nonnegative(),
- maxAssetsPerProject: z.number().nonnegative(),
- minSeats: z.number().nonnegative(),
- maxSeatsPerWorkspace: z.number().nonnegative(),
-});
-
-export type PlanFeatures = z.infer<typeof PlanFeaturesSchema>;
-
-// Compile-time guard: all PlanFeatures values must be boolean or number.
-// If a new field with a different type is added to PlanFeaturesSchema, this line will error.
-type _AssertBooleanOrNumber =
- PlanFeatures extends Record<string, boolean | number> ? true : never;
-const _checkPlanFeaturesValueTypes: _AssertBooleanOrNumber = true;
-void _checkPlanFeaturesValueTypes;
-
-/** Default (free) plan — the baseline, all features disabled / at minimum limits */
-export const defaultPlanFeatures: PlanFeatures = {
- canDownloadAssets: false,
- canRestoreBackups: false,
- allowAdditionalPermissions: false,
- allowDynamicData: false,
- allowContentMode: false,
- allowStagingPublish: false,
- maxContactEmailsPerProject: 0,
- maxDomainsAllowedPerUser: 0,
- maxDailyPublishesPerUser: 10,
- maxWorkspaces: 1,
- maxProjectsAllowedPerUser: 100,
- maxAssetsPerProject: 50,
- minSeats: 0,
- maxSeatsPerWorkspace: 0,
-};
-
-/** All user purchases (subscriptions and LTDs). subscriptionId present only for recurring subscriptions */
-export type Purchase = {
- planName: string;
- subscriptionId?: string;
-};
-
-/**
- * Parse the PLANS env variable (JSON array of {name, extends?, features}).
- * - features is partial when extends is used; the parent plan fills in the rest.
- * - The final merged features are validated against the full PlanFeaturesSchema.
- * - Invalid entries are skipped with a console.error.
- * - An extends reference to an unknown plan name throws an error.
- * Returns a Map of plan name → resolved PlanFeatures.
- */
-export const parsePlansEnv = (raw: string): Map<string, PlanFeatures> => {
- try {
- const parsed = JSON.parse(raw);
- if (!Array.isArray(parsed)) {
- return new Map();
- }
-
- type PlanEntry = {
- name: string;
- extends?: string;
- features: Partial<PlanFeatures>;
- };
-
- // First pass: validate entry structure and collect partial features.
- const entries: PlanEntry[] = parsed.flatMap((item) => {
- if (
- typeof item !== "object" ||
- item === null ||
- typeof item.name !== "string"
- ) {
- console.error("Invalid PLANS entry (missing name):", item);
- return [];
- }
- if ("extends" in item && typeof item.extends !== "string") {
- console.error("Invalid PLANS entry (extends must be a string):", item);
- return [];
- }
- const result = PlanFeaturesSchema.partial().safeParse(
- "features" in item ? item.features : {}
- );
- if (!result.success) {
- console.error(
- `Invalid PLANS entry "${item.name}" features:`,
- result.error.flatten()
- );
- return [];
- }
- return [
- {
- name: item.name,
- extends: "extends" in item ? (item.extends as string) : undefined,
- features: result.data,
- } satisfies PlanEntry,
- ];
- });
-
- // Build name → partial features map for resolving extends.
- const byName = new Map<string, Partial<PlanFeatures>>(
- entries.map((e) => [e.name, e.features])
- );
-
- // Second pass: resolve extends and validate the full feature set.
- // Every entry implicitly extends defaultPlanFeatures; "extends" picks a named plan on top of that.
- const resolved = new Map<string, PlanFeatures>();
- for (const entry of entries) {
- if (entry.extends !== undefined && !byName.has(entry.extends)) {
- throw new Error(
- `PLANS entry "${entry.name}" extends unknown plan "${entry.extends}"`
- );
- }
- const parentFeatures: PlanFeatures =
- entry.extends === undefined
- ? defaultPlanFeatures
- : { ...defaultPlanFeatures, ...byName.get(entry.extends)! };
- const result = PlanFeaturesSchema.safeParse({
- ...parentFeatures,
- ...entry.features,
- });
- if (!result.success) {
- console.error(
- `Invalid PLANS entry "${entry.name}" features after resolving extends:`,
- result.error.flatten()
- );
- continue;
- }
- resolved.set(entry.name, result.data);
- }
- return resolved;
- } catch (error) {
- if (error instanceof Error && error.message.startsWith("PLANS entry")) {
- throw error;
- }
- return new Map();
- }
-};
+// 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.yaml
index 0719867396..5af5517278 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -262,6 +262,9 @@ importers:
'@webstudio-is/image':
specifier: workspace:*
version: link:../../packages/image
+ '@webstudio-is/plans':
+ specifier: workspace:*
+ version: link:../../packages/plans
'@webstudio-is/postgrest':
specifier: workspace:*
version: link:../../packages/postgrest
@@ -1693,6 +1696,22 @@ importers:
specifier: ^3.1.2
+ packages/plans:
+ dependencies:
+ zod:
+ specifier: ^3.24.2
+ version: 3.24.2
+ devDependencies:
+ '@webstudio-is/postgrest':
+ specifier: workspace:*
+ version: link:../postgrest
+ '@webstudio-is/tsconfig':
+ specifier: workspace:*
+ version: link:../tsconfig
+ vitest:
+ specifier: ^3.1.2
+
packages/postgrest:
dependencies:
'@supabase/postgrest-js':
@@ -2272,6 +2291,9 @@ importers:
'@webstudio-is/feature-flags':
specifier: workspace:*
version: link:../feature-flags
+ '@webstudio-is/plans':
+ specifier: workspace:*
+ version: link:../plans
memoize:
specifier: ^10.0.0
version: 10.0.0