-
- );
- })}
-
-
-
-
-
- {categoryItems?.map((item, index) => {
- return (
- {
- onSelect(item);
- onOpenAbout(undefined);
- }}
- >
- {
- onOpenAbout(isOpen ? item.projectId : undefined);
- }}
- />
-
- );
- })}
-
-
-
-
-
-
- );
-};
diff --git a/apps/builder/app/builder/features/marketplace/templates.tsx b/apps/builder/app/builder/features/marketplace/templates.tsx
deleted file mode 100644
index 64a4c7ff728f..000000000000
--- a/apps/builder/app/builder/features/marketplace/templates.tsx
+++ /dev/null
@@ -1,235 +0,0 @@
-import { useMemo } from "react";
-import {
- Button,
- Flex,
- List,
- ListItem,
- ScrollArea,
- Separator,
- theme,
- Link,
- Tooltip,
-} from "@webstudio-is/design-system";
-import { ChevronLeftIcon, ExternalLinkIcon } from "@webstudio-is/icons";
-import {
- ROOT_FOLDER_ID,
- type Asset,
- type Page,
- type WebstudioData,
-} from "@webstudio-is/sdk";
-import type { MarketplaceProduct } from "@webstudio-is/project-build";
-import { mapGroupBy } from "~/shared/shim";
-import { CollapsibleSection } from "~/builder/shared/collapsible-section";
-import { builderUrl } from "~/shared/router-utils";
-import {
- extractWebstudioFragment,
- findClosestInsertable,
- insertWebstudioFragmentAt,
- updateWebstudioData,
-} from "~/shared/instance-utils";
-import { insertPageCopyMutable } from "~/shared/page-utils";
-import { Card } from "./card";
-import type { MarketplaceOverviewItem } from "~/shared/marketplace/types";
-import { selectPage } from "~/shared/awareness";
-
-/**
- * Insert page as a template.
- * - Currently only supports inserting everything from the body
- * - Could be extended to support children of some other instance e.g. Marketplace Item
- */
-const insertSection = ({
- data,
- instanceId,
-}: {
- data: WebstudioData;
- instanceId: string;
-}) => {
- const fragment = extractWebstudioFragment(data, instanceId);
- const body = fragment.instances.find(
- (instance) => instance.component === "Body"
- );
- // remove body and use its children as root insrances
- if (body) {
- fragment.instances = fragment.instances.filter(
- (instance) => instance.component !== "Body"
- );
- fragment.children = body.children;
- }
- const insertable = findClosestInsertable(fragment);
- if (insertable) {
- insertWebstudioFragmentAt(fragment, insertable);
- }
-};
-
-const insertPage = ({
- data: sourceData,
- pageId,
-}: {
- data: WebstudioData;
- pageId: Page["id"];
-}) => {
- let newPageId: undefined | Page["id"];
- updateWebstudioData((targetData) => {
- newPageId = insertPageCopyMutable({
- source: { data: sourceData, pageId },
- target: { data: targetData, folderId: ROOT_FOLDER_ID },
- });
- });
- if (newPageId) {
- selectPage(newPageId);
- }
-};
-
-type TemplateData = {
- title?: string;
- thumbnailAsset?: Asset;
- pageId: string;
- rootInstanceId: string;
-};
-
-const getTemplatesDataByCategory = (
- data?: WebstudioData
-): Map> => {
- if (data === undefined) {
- return new Map();
- }
- const pages = [data.pages.homePage, ...data.pages.pages]
- .filter((page) => page.marketplace?.include)
- .map((page) => {
- // category can be empty string
- const category = page.marketplace?.category || "Pages";
- const thumbnailAsset =
- data.assets.get(page.marketplace?.thumbnailAssetId ?? "") ??
- data.assets.get(page.meta.socialImageAssetId ?? "");
- return {
- category,
- title: page.name,
- thumbnailAsset,
- pageId: page.id,
- rootInstanceId: page.rootInstanceId,
- };
- });
- return mapGroupBy(pages, (page) => page.category);
-};
-
-export const Templates = ({
- name,
- projectId,
- productCategory,
- authorizationToken,
- data,
- onOpenChange,
-}: {
- name: string;
- projectId: string;
- productCategory: MarketplaceProduct["category"];
- authorizationToken: MarketplaceOverviewItem["authorizationToken"];
- data: WebstudioData;
- onOpenChange: (isOpen: boolean) => void;
-}) => {
- const templatesDataByCategory = useMemo(
- () => getTemplatesDataByCategory(data),
- [data]
- );
-
- if (templatesDataByCategory === undefined || data === undefined) {
- return;
- }
-
- const hasAuthToken = authorizationToken != null;
-
- return (
-
-
- }
- onClick={() => {
- onOpenChange(false);
- }}
- color="neutral"
- >
- {name}
-
-
-
-
-
-
-
-
-
- {Array.from(templatesDataByCategory.keys())
- .sort()
- .map((category) => {
- return (
-
-
-
- {templatesDataByCategory
- .get(category)
- ?.map((templateData, index) => {
- return (
- {
- if (productCategory === "sectionTemplates") {
- insertSection({
- data,
- instanceId: templateData.rootInstanceId,
- });
- }
- if (
- productCategory === "pageTemplates" ||
- productCategory === "integrationTemplates"
- ) {
- insertPage({
- data,
- pageId: templateData.pageId,
- });
- }
- }}
- >
-
-
- );
- })}
-
-
-
- );
- })}
-
-
- );
-};
diff --git a/apps/builder/app/builder/features/marketplace/utils.ts b/apps/builder/app/builder/features/marketplace/utils.ts
deleted file mode 100644
index bf0664fe919f..000000000000
--- a/apps/builder/app/builder/features/marketplace/utils.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import {
- getStyleDeclKey,
- type Asset,
- type WebstudioData,
-} from "@webstudio-is/sdk";
-import type { CompactBuild } from "@webstudio-is/project-build";
-
-const getPair = (item: Item) =>
- [item.id, item] as const;
-
-export const toWebstudioData = (
- data: CompactBuild & { assets: Asset[] }
-): WebstudioData => ({
- assets: new Map(data.assets.map(getPair)),
- instances: new Map(data.instances.map(getPair)),
- dataSources: new Map(data.dataSources.map(getPair)),
- resources: new Map(data.resources.map(getPair)),
- props: new Map(data.props.map(getPair)),
- pages: data.pages,
- breakpoints: new Map(data.breakpoints.map(getPair)),
- styleSources: new Map(data.styleSources.map(getPair)),
- styleSourceSelections: new Map(
- data.styleSourceSelections.map((item) => [item.instanceId, item])
- ),
- styles: new Map(data.styles.map((item) => [getStyleDeclKey(item), item])),
-});
diff --git a/apps/builder/app/builder/features/pages/page-settings.stories.tsx b/apps/builder/app/builder/features/pages/page-settings.stories.tsx
index 279f07c4e014..cbb1b0928f3a 100644
--- a/apps/builder/app/builder/features/pages/page-settings.stories.tsx
+++ b/apps/builder/app/builder/features/pages/page-settings.stories.tsx
@@ -68,8 +68,6 @@ $project.set({
userId: "userId",
domain: "new-2x9tcd",
- marketplaceApprovalStatus: "UNLISTED",
-
latestStaticBuild: null,
previewImageAssetId: null,
previewImageAsset: {
diff --git a/apps/builder/app/builder/features/pages/page-settings.tsx b/apps/builder/app/builder/features/pages/page-settings.tsx
index 573e52d95622..3fff451de15e 100644
--- a/apps/builder/app/builder/features/pages/page-settings.tsx
+++ b/apps/builder/app/builder/features/pages/page-settings.tsx
@@ -109,7 +109,6 @@ import {
import { Form } from "./form";
import type { UserPlanFeatures } from "~/shared/db/user-plan-features.server";
import { useUnmount } from "~/shared/hook-utils/use-mount";
-import { Card } from "../marketplace/card";
import { selectInstance } from "~/shared/awareness";
import { computeExpression } from "~/shared/data-variables";
@@ -128,9 +127,6 @@ const fieldDefaultValues = {
redirect: `""`,
documentType: "html" as (typeof documentTypes)[number],
customMetas: [{ property: "", content: `""` }],
- marketplaceInclude: false,
- marketplaceCategory: "",
- marketplaceThumbnailAssetId: "",
};
const fieldNames = Object.keys(
@@ -317,9 +313,6 @@ const toFormValues = (
documentType: page.meta.documentType ?? fieldDefaultValues.documentType,
isHomePage,
customMetas: page.meta.custom ?? fieldDefaultValues.customMetas,
- marketplaceInclude: page.marketplace?.include ?? false,
- marketplaceCategory: page.marketplace?.category ?? "",
- marketplaceThumbnailAssetId: page.marketplace?.thumbnailAssetId ?? "",
};
};
@@ -609,101 +602,6 @@ const fieldsetStyle = css({
},
});
-const MarketplaceSection = ({
- values,
- onChange,
-}: {
- values: Values;
- onChange: OnChange;
-}) => {
- const excludeId = useId();
- const categoryId = useId();
- const categoryMeta = values.customMetas.find(
- ({ property }) => property === "ws:category"
- );
- // @todo remove after all stores are migrated
- const categoryFallback = String(
- computeExpression(categoryMeta?.content ?? `""`, new Map())
- );
- const category = values.marketplaceCategory ?? categoryFallback ?? "Pages";
- const assets = useStore($assets);
- const thumbnailAsset = assets.get(values.marketplaceThumbnailAssetId);
- const thumnailFallbackAsset = assets.get(values.socialImageAssetId);
- return (
-
-
-
-
- onChange({ field: "marketplaceInclude", value })
- }
- />
-
-
-
-
-
- onChange({
- field: "marketplaceCategory",
- value: event.target.value,
- })
- }
- />
-
-
-
- onChange({ field: "marketplaceThumbnailAssetId", value })
- }
- >
-
-
-
- {thumbnailAsset?.type === "image" && (
-
- onChange({ field: "marketplaceThumbnailAssetId", value: "" })
- }
- />
- )}
-
-
-
-
- {category && }
-
-
-
-
-
- );
-};
-
const FormFields = ({
systemDataSourceId,
autoSelect,
@@ -1224,15 +1122,6 @@ const FormFields = ({
- {(project?.marketplaceApprovalStatus === "PENDING" ||
- project?.marketplaceApprovalStatus === "APPROVED" ||
- project?.marketplaceApprovalStatus === "REJECTED") && (
- <>
-
-
- >
- )}
-
@@ -1471,25 +1360,6 @@ const updatePage = (pageId: Page["id"], values: Partial) => {
if (values.parentFolderId !== undefined) {
registerFolderChildMutable(folders, page.id, values.parentFolderId);
}
-
- if (values.marketplaceInclude !== undefined) {
- page.marketplace ??= {};
- page.marketplace.include = values.marketplaceInclude;
- }
- if (values.marketplaceCategory !== undefined) {
- page.marketplace ??= {};
- page.marketplace.category =
- values.marketplaceCategory.length > 0
- ? values.marketplaceCategory
- : undefined;
- }
- if (values.marketplaceThumbnailAssetId !== undefined) {
- page.marketplace ??= {};
- page.marketplace.thumbnailAssetId =
- values.marketplaceThumbnailAssetId.length > 0
- ? values.marketplaceThumbnailAssetId
- : undefined;
- }
};
serverSyncStore.createTransaction([$pages], (pages) => {
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 833fd2869ad1..c6640c15e123 100644
--- a/apps/builder/app/builder/features/project-settings/project-settings.tsx
+++ b/apps/builder/app/builder/features/project-settings/project-settings.tsx
@@ -15,18 +15,16 @@ import { $openProjectSettings } from "~/shared/nano-states/project-settings";
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";
+type SectionName = "general" | "redirects" | "publish";
const sections = new Map([
["general", SectionGeneral],
["redirects", SectionRedirects],
["publish", SectionPublish],
- ["marketplace", SectionMarketplace],
] as const);
export const ProjectSettingsView = ({
@@ -105,7 +103,6 @@ export const ProjectSettingsView = ({
{currentSection === "general" && }
{currentSection === "redirects" && }
{currentSection === "publish" && }
- {currentSection === "marketplace" && }
diff --git a/apps/builder/app/builder/features/project-settings/section-marketplace.tsx b/apps/builder/app/builder/features/project-settings/section-marketplace.tsx
deleted file mode 100644
index 35020cf797d5..000000000000
--- a/apps/builder/app/builder/features/project-settings/section-marketplace.tsx
+++ /dev/null
@@ -1,357 +0,0 @@
-import { useStore } from "@nanostores/react";
-import {
- Grid,
- InputField,
- Label,
- theme,
- Text,
- TextArea,
- Button,
- css,
- Flex,
- CheckboxAndLabel,
- Checkbox,
- InputErrorsTooltip,
- PanelBanner,
- Select,
- Box,
-} from "@webstudio-is/design-system";
-import { Image, wsImageLoader } from "@webstudio-is/image";
-import { useState } from "react";
-import {
- MarketplaceProduct,
- marketplaceCategories,
-} from "@webstudio-is/project-build";
-import { ImageControl } from "./image-control";
-import { $assets, $marketplaceProduct, $project } from "~/shared/nano-states";
-import { useIds } from "~/shared/form-utils";
-import { MarketplaceApprovalStatus } from "@webstudio-is/project";
-import { serverSyncStore } from "~/shared/sync";
-import { trpcClient } from "~/shared/trpc/trpc-client";
-import { rightPanelWidth, sectionSpacing } from "./utils";
-
-const thumbnailStyle = css({
- borderRadius: theme.borderRadius[4],
- outlineWidth: 1,
- outlineStyle: "solid",
- outlineColor: theme.colors.borderMain,
- width: theme.spacing[28],
- aspectRatio: "1.91",
- background: "#DFE3E6",
-});
-
-const thumbnailImageStyle = css({
- display: "block",
- width: "100%",
- height: "100%",
- variants: {
- hasAsset: {
- true: {
- objectFit: "cover",
- },
- },
- },
-});
-
-const defaultMarketplaceProduct: Partial = {
- category: "sectionTemplates",
-};
-
-const validate = (data: MarketplaceProduct) => {
- const parsedResult = MarketplaceProduct.safeParse(data);
- if (parsedResult.success === false) {
- return parsedResult.error.formErrors.fieldErrors;
- }
-};
-
-const useMarketplaceApprovalStatus = () => {
- const { send, data, state } =
- trpcClient.project.setMarketplaceApprovalStatus.useMutation();
- const project = useStore($project);
-
- const status =
- data?.marketplaceApprovalStatus ??
- project?.marketplaceApprovalStatus ??
- "UNLISTED";
-
- const handleSuccess = ({
- marketplaceApprovalStatus,
- }: {
- marketplaceApprovalStatus: MarketplaceApprovalStatus;
- }) => {
- const project = $project.get();
- if (project) {
- $project.set({
- ...project,
- marketplaceApprovalStatus,
- });
- }
- };
-
- return {
- status,
- state,
- submit() {
- if (project) {
- send(
- {
- projectId: project.id,
- marketplaceApprovalStatus: "PENDING",
- },
- handleSuccess
- );
- }
- },
- unlist() {
- if (project) {
- send(
- {
- projectId: project.id,
- marketplaceApprovalStatus: "UNLISTED",
- },
- handleSuccess
- );
- }
- },
- };
-};
-
-export const SectionMarketplace = () => {
- const project = useStore($project);
- const approval = useMarketplaceApprovalStatus();
- const [data, setData] = useState(() => $marketplaceProduct.get());
- const ids = useIds([
- "name",
- "category",
- "author",
- "email",
- "website",
- "issues",
- "description",
- "isConfirmed",
- ]);
- const assets = useStore($assets);
- const [isConfirmed, setIsConfirmed] = useState(false);
- const [errors, setErrors] = useState>();
-
- if (data === undefined || project === undefined) {
- return;
- }
- const asset = assets.get(data.thumbnailAssetId ?? "");
-
- const handleSave = (
- setting: Setting
- ) => {
- return (value: MarketplaceProduct[Setting]) => {
- const nextData = {
- ...defaultMarketplaceProduct,
- ...data,
- [setting]: value,
- };
- const errors = validate(nextData);
- setErrors(errors);
- setData(nextData);
-
- if (errors) {
- return;
- }
- serverSyncStore.createTransaction(
- [$marketplaceProduct],
- (marketplaceProduct) => {
- if (marketplaceProduct === undefined) {
- return;
- }
- Object.assign(marketplaceProduct, nextData);
- }
- );
- };
- };
-
- return (
-
-
- Marketplace
-
-
-
-
- {
- handleSave("name")(event.target.value);
- }}
- />
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- The optimal dimensions in marketplace are 600x315 px or larger
- with a 1.91:1 aspect ratio.
-
-
-
-
-
-
-
-
-
-
-
-
- {
- handleSave("author")(event.target.value);
- }}
- />
-
-
-
-
-
-
- {
- handleSave("email")(event.target.value);
- }}
- />
-
-
-
-
-
-
- {
- handleSave("website")(event.target.value);
- }}
- />
-
-
-
-
-
-
- {
- handleSave("issues")(event.target.value);
- }}
- />
-
-
-
-
-
-
-
-
-
-
-
-
-
- {`Don't forget to publish your project after every change to make your
- changes available in the marketplace!`}
-
-
-
-
- {approval.status === "UNLISTED" && (
-
-
- {
- if (typeof value === "boolean") {
- setIsConfirmed(value);
- }
- }}
- />
-
-
-
- )}
-
-
- Status: {approval.status.toLocaleLowerCase()}
- {approval.status === "UNLISTED" ? (
-
- ) : (
-
- )}
-
-
- );
-};
diff --git a/apps/builder/app/builder/shared/nano-states/index.ts b/apps/builder/app/builder/shared/nano-states/index.ts
index b4a63ffaf6a2..181a0240e744 100644
--- a/apps/builder/app/builder/shared/nano-states/index.ts
+++ b/apps/builder/app/builder/shared/nano-states/index.ts
@@ -108,7 +108,6 @@ export type SidebarPanelName =
| "components"
| "navigator"
| "pages"
- | "marketplace"
| "none";
// Only used internally to avoid directly setting the value without using setActiveSidebarPanel.
diff --git a/apps/builder/app/builder/sidebar-left/sidebar-left.tsx b/apps/builder/app/builder/sidebar-left/sidebar-left.tsx
index 7a91aeb3855a..6af5e35b5e3c 100644
--- a/apps/builder/app/builder/sidebar-left/sidebar-left.tsx
+++ b/apps/builder/app/builder/sidebar-left/sidebar-left.tsx
@@ -46,27 +46,9 @@ import { ComponentsPanel } from "~/builder/features/components";
import { PagesPanel } from "~/builder/features/pages";
import { NavigatorPanel } from "~/builder/features/navigator";
import { AssetsPanel } from "~/builder/features/assets";
-import { MarketplacePanel } from "~/builder/features/marketplace";
const none = { Panel: () => null };
-const AiTabTrigger = () => {
- return (
- {
- setSetting(
- "isAiCommandBarVisible",
- getSetting("isAiCommandBarVisible") ? false : true
- );
- }}
- >
-
-
- );
-};
-
const HelpTabTrigger = () => {
const [helpIsOpen, setHelpIsOpen] = useState(false);
return (
@@ -158,15 +140,6 @@ const panels: PanelConfig[] = [
Icon: ImageIcon,
Panel: AssetsPanel,
},
- {
- name: "marketplace",
- label: "Marketplace",
- Icon: ExtensionIcon,
- Panel: MarketplacePanel,
- visibility: {
- content: false,
- },
- },
];
type SidebarLeftProps = {
@@ -264,7 +237,6 @@ export const SidebarLeft = ({ publish }: SidebarLeftProps) => {
})}
- {isDesignMode && }
diff --git a/apps/builder/app/dashboard/dashboard.stories.tsx b/apps/builder/app/dashboard/dashboard.stories.tsx
index 6f6a3a441287..5335272adffd 100644
--- a/apps/builder/app/dashboard/dashboard.stories.tsx
+++ b/apps/builder/app/dashboard/dashboard.stories.tsx
@@ -17,7 +17,6 @@ const user = {
image: null,
username: "Taylor",
teamId: null,
- provider: "github",
};
const createRouter = (element: JSX.Element, path: string, current?: string) =>
@@ -47,7 +46,6 @@ const projects = [
previewImageAsset: null,
previewImageAssetId: "",
latestBuildVirtual: null,
- marketplaceApprovalStatus: "UNLISTED" as const,
} as DashboardProject,
];
diff --git a/apps/builder/app/env/env.server.ts b/apps/builder/app/env/env.server.ts
index ce3c2517ca4b..e50aaa7a425e 100644
--- a/apps/builder/app/env/env.server.ts
+++ b/apps/builder/app/env/env.server.ts
@@ -2,8 +2,6 @@
const env = {
// Authentication
DEV_LOGIN: process.env.DEV_LOGIN,
- GH_CLIENT_ID: process.env.GH_CLIENT_ID,
- GH_CLIENT_SECRET: process.env.GH_CLIENT_SECRET,
GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID,
GOOGLE_CLIENT_SECRET: process.env.GOOGLE_CLIENT_SECRET,
diff --git a/apps/builder/app/routes/_ui.login._index.tsx b/apps/builder/app/routes/_ui.login._index.tsx
index 246df700f718..505f16ed7268 100644
--- a/apps/builder/app/routes/_ui.login._index.tsx
+++ b/apps/builder/app/routes/_ui.login._index.tsx
@@ -86,7 +86,6 @@ export const loader = async ({
return json(
{
isSecretLoginEnabled: env.DEV_LOGIN === "true",
- isGithubEnabled: Boolean(env.GH_CLIENT_ID && env.GH_CLIENT_SECRET),
isGoogleEnabled: Boolean(
env.GOOGLE_CLIENT_ID && env.GOOGLE_CLIENT_SECRET
),
diff --git a/apps/builder/app/routes/auth.github.tsx b/apps/builder/app/routes/auth.github.tsx
deleted file mode 100644
index 6f9efcd56079..000000000000
--- a/apps/builder/app/routes/auth.github.tsx
+++ /dev/null
@@ -1,54 +0,0 @@
-import { type ActionFunctionArgs } from "@remix-run/server-runtime";
-import { authenticator } from "~/services/auth.server";
-import { dashboardPath, isDashboard, loginPath } from "~/shared/router-utils";
-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";
-
-export default function GH() {
- return null;
-}
-
-export const action = async ({ request }: ActionFunctionArgs) => {
- if (false === isDashboard(request)) {
- throw new Response("Not Found", {
- status: 404,
- });
- }
-
- preventCrossOriginCookie(request);
- // CSRF token checks are not necessary for dashboard-only pages.
- // All POST requests from the builder or canvas app are safeguarded by preventCrossOriginCookie
-
- const returnTo = (await returnToPath(request)) ?? dashboardPath();
-
- try {
- return await authenticator.authenticate("github", request, {
- successRedirect: returnTo,
- throwOnError: true,
- });
- } catch (error) {
- // all redirects are basically errors and in that case we don't want to catch it
- if (error instanceof Response) {
- return setNoStoreToRedirect(await clearReturnToCookie(request, error));
- }
-
- const message = error instanceof Error ? error?.message : "unknown error";
-
- console.error({
- error,
- extras: {
- loginMethod: AUTH_PROVIDERS.LOGIN_GITHUB,
- },
- });
-
- return redirect(
- loginPath({
- error: AUTH_PROVIDERS.LOGIN_GITHUB,
- message: message,
- returnTo,
- })
- );
- }
-};
diff --git a/apps/builder/app/routes/auth.github_.callback.tsx b/apps/builder/app/routes/auth.github_.callback.tsx
deleted file mode 100644
index bf0325e0f6f3..000000000000
--- a/apps/builder/app/routes/auth.github_.callback.tsx
+++ /dev/null
@@ -1,53 +0,0 @@
-import { type LoaderFunctionArgs } from "@remix-run/server-runtime";
-import { authenticator } from "~/services/auth.server";
-import { dashboardPath, isDashboard, loginPath } from "~/shared/router-utils";
-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 { allowedDestinations } from "~/services/destinations.server";
-
-export const loader = async ({ request }: LoaderFunctionArgs) => {
- if (false === isDashboard(request)) {
- throw new Response("Not Found", {
- status: 404,
- });
- }
- preventCrossOriginCookie(request);
-
- allowedDestinations(request, ["document"]);
- // CSRF token checks are not necessary for dashboard-only pages.
- // All requests from the builder or canvas app are safeguarded either by preventCrossOriginCookie for fetch requests
- // or by allowedDestinations for iframe requests.
-
- const returnTo = (await returnToPath(request)) ?? dashboardPath();
-
- try {
- await authenticator.authenticate("github", request, {
- successRedirect: returnTo,
- throwOnError: true,
- });
- } catch (error) {
- // all redirects are basically errors and in that case we don't want to catch it
- if (error instanceof Response) {
- return setNoStoreToRedirect(await clearReturnToCookie(request, error));
- }
-
- const message = error instanceof Error ? error?.message : "unknown error";
-
- console.error({
- error,
- extras: {
- loginMethod: AUTH_PROVIDERS.LOGIN_GITHUB,
- },
- });
-
- return redirect(
- loginPath({
- error: AUTH_PROVIDERS.LOGIN_GITHUB,
- message,
- returnTo,
- })
- );
- }
-};
diff --git a/apps/builder/app/routes/rest.ai._index.ts b/apps/builder/app/routes/rest.ai._index.ts
deleted file mode 100644
index f005197a3643..000000000000
--- a/apps/builder/app/routes/rest.ai._index.ts
+++ /dev/null
@@ -1,298 +0,0 @@
-import { z } from "zod";
-import type { ActionFunctionArgs } from "@remix-run/server-runtime";
-import {
- copywriter,
- operations,
- templateGenerator,
- createGptModel,
- type GptModelMessageFormat,
- createErrorResponse,
- type ModelMessage,
-} from "@webstudio-is/ai/index.server";
-import {
- copywriter as clientCopywriter,
- operations as clientOperations,
- queryImagesAndMutateTemplate,
-} from "@webstudio-is/ai";
-import env from "~/env/env.server";
-import { createContext } from "~/shared/context.server";
-import { authorizeProject } from "@webstudio-is/trpc-interface/index.server";
-import { loadDevBuildByProjectId } from "@webstudio-is/project-build/index.server";
-import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";
-import { checkCsrf } from "~/services/csrf-session.server";
-
-export const RequestParams = z.object({
- projectId: z.string().min(1, "nonempty"),
- instanceId: z.string().min(1, "nonempty"),
- prompt: z.string().min(1, "nonempty").max(1200),
- components: z.array(z.string()),
- jsx: z.string().min(1, "nonempty"),
- command: z.union([
- // Using client* friendly imports because RequestParams
- // is used to parse the form data on the client too.
- z.literal(clientCopywriter.name),
- z.literal(clientOperations.editStylesName),
- z.literal(clientOperations.generateTemplatePromptName),
- z.literal(clientOperations.deleteInstanceName),
- ]),
-});
-
-// Override Vercel's default serverless functions timeout.
-export const config = {
- maxDuration: 180, // seconds
-};
-
-export const action = async ({ request }: ActionFunctionArgs) => {
- preventCrossOriginCookie(request);
- await checkCsrf(request);
-
- const context = await createContext(request);
- // @todo Reinstate isFeatureEnabled('ai')
-
- if (env.OPENAI_KEY === undefined) {
- return {
- id: "ai",
- ...createErrorResponse({
- error: "ai.invalidApiKey",
- status: 401,
- message: "Invalid OpenAI API key",
- debug: "Invalid OpenAI API key",
- }),
- llmMessages: [],
- };
- }
-
- if (
- env.OPENAI_ORG === undefined ||
- env.OPENAI_ORG.startsWith("org-") === false
- ) {
- return {
- id: "ai",
- ...createErrorResponse({
- error: "ai.invalidOrg",
- status: 401,
- message: "Invalid OpenAI API organization",
- debug: "Invalid OpenAI API organization",
- }),
- llmMessages: [],
- };
- }
-
- if (env.PEXELS_API_KEY === undefined) {
- return {
- id: "ai",
- ...createErrorResponse({
- error: "ai.invalidApiKey",
- status: 401,
- message: "Invalid Pexels API key",
- debug: "Invalid Pexels API key",
- }),
- llmMessages: [],
- };
- }
- const PEXELS_API_KEY = env.PEXELS_API_KEY;
-
- const parsed = RequestParams.safeParse(await request.json());
-
- if (parsed.success === false) {
- return {
- id: "ai",
- ...createErrorResponse({
- error: "ai.invalidRequest",
- status: 401,
- message: "Invalid request data",
- debug: "Invalid request data",
- }),
- llmMessages: [],
- };
- }
-
- const requestContext = await createContext(request);
-
- if (requestContext.authorization.type !== "user") {
- return {
- id: "ai",
- ...createErrorResponse({
- error: "unauthorized",
- status: 401,
- message: "You don't have edit access to this project",
- debug: "Unauthorized access attempt",
- }),
- llmMessages: [],
- };
- }
-
- if (requestContext.authorization.userId === undefined) {
- return {
- id: "ai",
- ...createErrorResponse({
- error: "unauthorized",
- status: 401,
- message: "You don't have edit access to this project",
- debug: "Unauthorized access attempt",
- }),
- llmMessages: [],
- };
- }
-
- const { prompt, components, jsx, projectId, instanceId, command } =
- parsed.data;
-
- if (command === copywriter.name) {
- const canEdit = await authorizeProject.hasProjectPermit(
- { projectId: projectId, permit: "edit" },
- requestContext
- );
-
- if (canEdit === false) {
- return {
- id: copywriter.name,
- ...createErrorResponse({
- error: "unauthorized",
- status: 401,
- message: "You don't have edit access to this project",
- debug: "Unauthorized access attempt",
- }),
- llmMessages: [],
- };
- }
-
- const { instances } = await loadDevBuildByProjectId(context, projectId);
-
- const model = createGptModel({
- apiKey: env.OPENAI_KEY,
- organization: env.OPENAI_ORG,
- temperature: 0,
- model: "gpt-3.5-turbo",
- });
-
- const copywriterChain = copywriter.createChain();
- const copywriterResponse = await copywriterChain({
- model,
- context: {
- prompt,
- textInstances: copywriter.collectTextInstances({
- instances: new Map(
- instances.map((instance) => [instance.id, instance])
- ),
- rootInstanceId: instanceId,
- }),
- },
- });
-
- if (copywriterResponse.success === false) {
- return copywriterResponse;
- }
-
- // Return the copywriter generation stream.
- return copywriterResponse.data;
- }
-
- // If the request requires context about the instances tree use the Operations chain.
-
- const llmMessages: ModelMessage[] = [];
-
- const model = createGptModel({
- apiKey: env.OPENAI_KEY,
- organization: env.OPENAI_ORG,
- temperature: 0,
- model: "gpt-3.5-turbo",
- });
-
- const chain = operations.createChain();
-
- const response = await chain({
- model,
- context: {
- prompt,
- components,
- jsx,
- },
- });
-
- if (response.success === false) {
- return response;
- }
-
- llmMessages.push(...response.llmMessages);
-
- // The operations chain can detect a user interface generation request.
- // In such cases we let this chain select the insertion point
- // and then handle the generation request with a standalone chain called template-generator
- // that has a dedicate and comprehensive prompt.
-
- const generateTemplatePrompts: {
- dataIndex: number;
- operation: operations.generateTemplatePrompt.wsOperation;
- }[] = [];
- response.data.forEach((operation, dataIndex) => {
- if (operation.operation === "generateTemplatePrompt") {
- // preserve the index in response.data to update it after executing operations
- generateTemplatePrompts.push({ dataIndex, operation });
- }
- });
-
- if (generateTemplatePrompts.length > 0) {
- const generationModel = createGptModel({
- apiKey: env.OPENAI_KEY,
- organization: env.OPENAI_ORG,
- temperature: 0,
- model: "gpt-4",
- });
-
- const generationChain =
- templateGenerator.createChain();
-
- const results = await Promise.all(
- generateTemplatePrompts.map(async ({ dataIndex, operation }) => {
- const result = await generationChain({
- model: generationModel,
- context: {
- prompt:
- operation.llmPrompt +
- (operation.classNames && operation.classNames.length > 0
- ? `.\nSuggested Tailwind classes: ${operation.classNames}`
- : ""),
-
- components,
- },
- });
- if (result.success) {
- await queryImagesAndMutateTemplate({
- template: result.data,
- apiKey: PEXELS_API_KEY,
- });
- }
- return {
- dataIndex,
- operation,
- result,
- };
- })
- );
-
- for (const { dataIndex, operation, result } of results) {
- llmMessages.push(...result.llmMessages);
-
- if (result.success === false) {
- return {
- ...result,
- llmMessages,
- };
- }
-
- // Replace generateTemplatePrompt.wsOperation with the AI-generated Webstudio template.
- response.data[dataIndex] = {
- operation: "insertTemplate",
- addTo: operation.addTo,
- addAtIndex: operation.addAtIndex,
- template: result.data,
- };
- }
- }
-
- return {
- ...response,
- llmMessages,
- };
-};
diff --git a/apps/builder/app/routes/rest.ai.audio.transcriptions.ts b/apps/builder/app/routes/rest.ai.audio.transcriptions.ts
deleted file mode 100644
index c8eaf08608e0..000000000000
--- a/apps/builder/app/routes/rest.ai.audio.transcriptions.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import type { ActionFunctionArgs } from "@remix-run/server-runtime";
-import { z } from "zod";
-import { checkCsrf } from "~/services/csrf-session.server";
-import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";
-
-const zTranscription = z.object({
- text: z.string().transform((value) => value.trim()),
-});
-
-// @todo: move to AI package
-export const action = async ({ request }: ActionFunctionArgs) => {
- preventCrossOriginCookie(request);
- await checkCsrf(request);
-
- // @todo: validate request
- const formData = await request.formData();
- formData.append("model", "whisper-1");
-
- const response = await fetch(
- "https://api.openai.com/v1/audio/transcriptions",
- {
- method: "POST",
- headers: {
- Authorization: `Bearer ${process.env.OPENAI_KEY}`,
- },
- body: formData,
- }
- );
-
- if (response.ok === false) {
- const message = await response.text();
-
- console.error("ERROR", response.status, message);
-
- return {
- success: false,
- error: {
- status: response.status,
- message,
- },
- } as const;
- }
-
- // @todo untyped
- const data = zTranscription.safeParse(await response.json());
-
- if (data.success === false) {
- console.error("ERROR openai transcriptions", data.error);
- }
-
- return data;
-};
diff --git a/apps/builder/app/routes/rest.ai.detect.ts b/apps/builder/app/routes/rest.ai.detect.ts
deleted file mode 100644
index 91c4cfee814b..000000000000
--- a/apps/builder/app/routes/rest.ai.detect.ts
+++ /dev/null
@@ -1,126 +0,0 @@
-import { z } from "zod";
-import type { ActionFunctionArgs } from "@remix-run/server-runtime";
-import {
- commandDetect,
- createGptModel,
- type GptModelMessageFormat,
- createErrorResponse,
- copywriter,
- operations,
-} from "@webstudio-is/ai/index.server";
-
-import env from "~/env/env.server";
-import { createContext } from "~/shared/context.server";
-import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";
-import { checkCsrf } from "~/services/csrf-session.server";
-
-export const RequestParams = z.object({
- prompt: z.string().max(1200),
-});
-
-export const action = async ({ request }: ActionFunctionArgs) => {
- preventCrossOriginCookie(request);
- await checkCsrf(request);
-
- // @todo Reinstate isFeatureEnabled('ai')
-
- if (env.OPENAI_KEY === undefined) {
- return {
- id: "ai",
- ...createErrorResponse({
- error: "ai.invalidApiKey",
- status: 401,
- message: "Invalid OpenAI API key",
- debug: "Invalid OpenAI API key",
- }),
- llmMessages: [],
- };
- }
-
- if (
- env.OPENAI_ORG === undefined ||
- env.OPENAI_ORG.startsWith("org-") === false
- ) {
- return {
- id: "ai",
- ...createErrorResponse({
- error: "ai.invalidOrg",
- status: 401,
- message: "Invalid OpenAI API organization",
- debug: "Invalid OpenAI API organization",
- }),
- llmMessages: [],
- };
- }
-
- const requestJson = await request.json();
- const parsed = RequestParams.safeParse(requestJson);
-
- if (parsed.success === false) {
- return {
- id: "ai",
- ...createErrorResponse({
- error: "ai.invalidRequest",
- status: 401,
- message: `RequestParams.safeParse failed on ${JSON.stringify(
- requestJson
- )}`,
- debug: "Invalid request data",
- }),
- llmMessages: [],
- };
- }
-
- const requestContext = await createContext(request);
-
- if (requestContext.authorization.type !== "user") {
- return {
- id: "ai",
- ...createErrorResponse({
- error: "unauthorized",
- status: 401,
- message: "You don't have edit access to this project",
- debug: "Unauthorized access attempt",
- }),
- llmMessages: [],
- };
- }
-
- if (requestContext.authorization.userId === undefined) {
- return {
- id: "ai",
- ...createErrorResponse({
- error: "unauthorized",
- status: 401,
- message: "You don't have edit access to this project",
- debug: "Unauthorized access attempt",
- }),
- llmMessages: [],
- };
- }
-
- const { prompt } = parsed.data;
-
- const model = createGptModel({
- apiKey: env.OPENAI_KEY,
- organization: env.OPENAI_ORG,
- temperature: 0,
- model: "gpt-3.5-turbo",
- });
-
- const commandDetectChain = commandDetect.createChain();
- return commandDetectChain({
- model,
- context: {
- prompt,
- commands: {
- [copywriter.name]:
- "rewrites, rephrases, shortens, increases length or translates text",
- [operations.editStyles.name]: "edits styles",
- [operations.generateTemplatePrompt.name]:
- "handles a user interface generation request",
- [operations.deleteInstance.name]: "deletes elements",
- },
- },
- });
-};
diff --git a/apps/builder/app/routes/rest.patch.ts b/apps/builder/app/routes/rest.patch.ts
index 898928176440..366ab351d589 100644
--- a/apps/builder/app/routes/rest.patch.ts
+++ b/apps/builder/app/routes/rest.patch.ts
@@ -18,11 +18,7 @@ import {
Resources,
Resource,
} from "@webstudio-is/sdk";
-import {
- type Build,
- findCycles,
- MarketplaceProduct,
-} from "@webstudio-is/project-build";
+import { type Build, findCycles } from "@webstudio-is/project-build";
import {
parsePages,
parseStyleSourceSelections,
@@ -32,8 +28,6 @@ import {
serializeStyles,
parseData,
serializeData,
- parseConfig,
- serializeConfig,
loadRawBuildById,
parseInstanceData,
} from "@webstudio-is/project-build/index.server";
@@ -167,7 +161,6 @@ export const action = async ({
styleSources?: StyleSources;
styleSourceSelections?: StyleSourceSelections;
styles?: Styles;
- marketplaceProduct?: MarketplaceProduct;
} = {};
let previewImageAssetId: string | null | undefined = undefined;
@@ -295,19 +288,6 @@ export const action = async ({
continue;
}
- if (namespace === "marketplaceProduct") {
- const marketplaceProduct =
- buildData.marketplaceProduct ??
- parseConfig(build.marketplaceProduct);
-
- buildData.marketplaceProduct = applyPatches(
- marketplaceProduct,
- patches
- );
-
- continue;
- }
-
return { status: "error", errors: `Unknown namespace "${namespace}"` };
}
}
@@ -380,12 +360,6 @@ export const action = async ({
dbBuildData.styles = serializeStyles(buildData.styles);
}
- if (buildData.marketplaceProduct) {
- dbBuildData.marketplaceProduct = serializeConfig(
- MarketplaceProduct.parse(buildData.marketplaceProduct)
- );
- }
-
const update = await context.postgrest.client
.from("Build")
.update(dbBuildData, { count: "exact" })
diff --git a/apps/builder/app/services/auth.server.ts b/apps/builder/app/services/auth.server.ts
index f24f0db5190b..da456c7dd93a 100644
--- a/apps/builder/app/services/auth.server.ts
+++ b/apps/builder/app/services/auth.server.ts
@@ -1,6 +1,5 @@
import { Authenticator } from "remix-auth";
import { FormStrategy } from "remix-auth-form";
-import { GitHubStrategy, type GitHubProfile } from "remix-auth-github";
import { GoogleStrategy, type GoogleProfile } from "remix-auth-google";
import * as db from "~/shared/db";
import { sessionStorage } from "~/services/session.server";
@@ -35,7 +34,7 @@ const strategyCallback = async ({
profile,
request,
}: {
- profile: GitHubProfile | GoogleProfile;
+ profile: GoogleProfile;
request: Request;
}) => {
const context = await createContext(request);
@@ -62,18 +61,6 @@ export const authenticator = new Authenticator(sessionStorage, {
throwOnError: true,
});
-if (env.GH_CLIENT_ID && env.GH_CLIENT_SECRET) {
- const github = new GitHubStrategy(
- {
- clientID: env.GH_CLIENT_ID,
- clientSecret: env.GH_CLIENT_SECRET,
- callbackURL: `${callbackOrigin}${authCallbackPath({ provider: "github" })}`,
- },
- strategyCallback
- );
- authenticator.use(github, "github");
-}
-
if (env.GOOGLE_CLIENT_ID && env.GOOGLE_CLIENT_SECRET) {
const google = new GoogleStrategy(
{
diff --git a/apps/builder/app/services/trcp-router.server.ts b/apps/builder/app/services/trcp-router.server.ts
index 1805d9370af8..786c8e95ce11 100644
--- a/apps/builder/app/services/trcp-router.server.ts
+++ b/apps/builder/app/services/trcp-router.server.ts
@@ -1,5 +1,4 @@
import { router } from "@webstudio-is/trpc-interface/index.server";
-import { marketplaceRouter } from "../shared/marketplace/router.server";
import { domainRouter } from "@webstudio-is/domain/index.server";
import { projectRouter } from "@webstudio-is/project/index.server";
import { authorizationTokenRouter } from "@webstudio-is/authorization-token/index.server";
@@ -7,7 +6,6 @@ import { dashboardProjectRouter } from "@webstudio-is/dashboard/index.server";
import { logoutRouter } from "./logout-router.server";
export const appRouter = router({
- marketplace: marketplaceRouter,
domain: domainRouter,
project: projectRouter,
authorizationToken: authorizationTokenRouter,
diff --git a/apps/builder/app/shared/builder-data.ts b/apps/builder/app/shared/builder-data.ts
index 872bfeae824b..a4314dc024bd 100644
--- a/apps/builder/app/shared/builder-data.ts
+++ b/apps/builder/app/shared/builder-data.ts
@@ -1,12 +1,10 @@
import { getStyleDeclKey, type WebstudioData } from "@webstudio-is/sdk";
-import type { MarketplaceProduct } from "@webstudio-is/project-build";
import type { loader } from "~/routes/rest.data.$projectId";
import {
$assets,
$breakpoints,
$dataSources,
$instances,
- $marketplaceProduct,
$pages,
$props,
$resources,
@@ -16,9 +14,7 @@ import {
} from "./nano-states";
import { fetch } from "~/shared/fetch.client";
-export type BuilderData = WebstudioData & {
- marketplaceProduct: undefined | MarketplaceProduct;
-};
+export type BuilderData = WebstudioData;
export const getBuilderData = (): BuilderData => {
const pages = $pages.get();
@@ -36,7 +32,6 @@ export const getBuilderData = (): BuilderData => {
styleSources: $styleSources.get(),
styles: $styles.get(),
assets: $assets.get(),
- marketplaceProduct: $marketplaceProduct.get(),
};
};
@@ -71,7 +66,6 @@ export const loadBuilderData = async ({
data.styleSourceSelections.map((item) => [item.instanceId, item])
),
styles: new Map(data.styles.map((item) => [getStyleDeclKey(item), item])),
- marketplaceProduct: data.marketplaceProduct,
} satisfies BuilderData & { version: number };
}
diff --git a/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.test.tsx b/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.test.tsx
index c830c3e951d4..1da5d9b97ad9 100644
--- a/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.test.tsx
+++ b/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.test.tsx
@@ -100,7 +100,6 @@ beforeEach(() => {
userId: "",
isDeleted: false,
previewImageAsset: null,
- marketplaceApprovalStatus: "PENDING",
latestStaticBuild: null,
domainsVirtual: [],
latestBuildVirtual: null,
diff --git a/apps/builder/app/shared/db/user.server.ts b/apps/builder/app/shared/db/user.server.ts
index fb74d02d07f8..dac251a20873 100644
--- a/apps/builder/app/shared/db/user.server.ts
+++ b/apps/builder/app/shared/db/user.server.ts
@@ -1,6 +1,5 @@
import type { Database } from "@webstudio-is/postrest/index.server";
import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
-import type { GitHubProfile } from "remix-auth-github";
import type { GoogleProfile } from "remix-auth-google";
export type User = Database["public"]["Tables"]["User"]["Row"];
@@ -64,7 +63,7 @@ const genericCreateAccount = async (
export const createOrLoginWithOAuth = async (
context: AppContext,
- profile: GoogleProfile | GitHubProfile
+ profile: GoogleProfile
): Promise => {
const userData = {
email: (profile.emails ?? [])[0]?.value,
diff --git a/apps/builder/app/shared/marketplace/db.server.ts b/apps/builder/app/shared/marketplace/db.server.ts
deleted file mode 100644
index d033a7b4a55b..000000000000
--- a/apps/builder/app/shared/marketplace/db.server.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-import { MarketplaceProduct } from "@webstudio-is/project-build";
-import type { MarketplaceOverviewItem } from "./types";
-import {
- loadApprovedProdBuildByProjectId,
- parseConfig,
-} from "@webstudio-is/project-build/index.server";
-import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
-import type { Project } from "@webstudio-is/project";
-import { loadAssetsByProject } from "@webstudio-is/asset-uploader/index.server";
-
-export const getBuildProdData = async (
- { projectId }: { projectId: Project["id"] },
- context: AppContext
-) => {
- const build = await loadApprovedProdBuildByProjectId(context, projectId);
-
- const assets = await loadAssetsByProject(projectId, context, {
- skipPermissionsCheck: true,
- });
-
- return {
- ...build,
- assets,
- };
-};
-
-export const getItems = async (
- context: AppContext
-): Promise> => {
- const approvedMarketplaceProducts = await context.postgrest.client
- .from("ApprovedMarketplaceProduct")
- .select();
- if (approvedMarketplaceProducts.error) {
- throw approvedMarketplaceProducts.error;
- }
-
- const items: MarketplaceOverviewItem[] = [];
-
- for (const product of approvedMarketplaceProducts.data) {
- if (product.marketplaceProduct === null || product.projectId === null) {
- continue;
- }
- const parsedProduct = MarketplaceProduct.safeParse(
- parseConfig(product.marketplaceProduct)
- );
-
- if (parsedProduct.success === false) {
- console.error(parsedProduct.error.formErrors.fieldErrors);
- continue;
- }
-
- items.push({
- projectId: product.projectId,
- authorizationToken: product.authorizationToken ?? undefined,
- ...parsedProduct.data,
- });
- }
- const assetIds = items
- .map((item) => item.thumbnailAssetId)
- .filter((value): value is string => value != null);
-
- const assets = new Map();
- if (assetIds.length > 0) {
- const data = await context.postgrest.client
- .from("Asset")
- .select()
- .in("id", assetIds);
- if (data.error) {
- throw data.error;
- }
- for (const asset of data.data) {
- assets.set(asset.id, asset.name);
- }
- }
-
- return items.map((item) => {
- return {
- ...item,
- thumbnailAssetName: assets.get(item.thumbnailAssetId),
- };
- });
-};
diff --git a/apps/builder/app/shared/marketplace/router.server.ts b/apps/builder/app/shared/marketplace/router.server.ts
deleted file mode 100644
index e83b14627393..000000000000
--- a/apps/builder/app/shared/marketplace/router.server.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { z } from "zod";
-import {
- procedure,
- router,
- createCacheMiddleware,
-} from "@webstudio-is/trpc-interface/index.server";
-import { getItems, getBuildProdData } from "./db.server";
-
-const cacheMiddleware = createCacheMiddleware(60 * 3); // 60 * 3 = 3 minutes cache
-const cachedProcedure = procedure.use(cacheMiddleware);
-
-export const marketplaceRouter = router({
- getItems: cachedProcedure.query(async ({ ctx }) => {
- return await getItems(ctx);
- }),
- getBuildData: cachedProcedure
- .input(
- z.object({
- projectId: z.string(),
- })
- )
- .query(async ({ input, ctx }) => {
- return await getBuildProdData(input, ctx);
- }),
-});
diff --git a/apps/builder/app/shared/marketplace/types.ts b/apps/builder/app/shared/marketplace/types.ts
deleted file mode 100644
index 9336f8e27a5d..000000000000
--- a/apps/builder/app/shared/marketplace/types.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import type { MarketplaceProduct } from "@webstudio-is/project-build";
-import type { Asset } from "@webstudio-is/sdk";
-
-export type MarketplaceOverviewItem = MarketplaceProduct & {
- projectId: string;
- authorizationToken?: string | undefined;
- thumbnailAssetName?: Asset["name"];
-};
diff --git a/apps/builder/app/shared/nano-states/misc.ts b/apps/builder/app/shared/nano-states/misc.ts
index f8002292e64e..6bc05fd90bb4 100644
--- a/apps/builder/app/shared/nano-states/misc.ts
+++ b/apps/builder/app/shared/nano-states/misc.ts
@@ -17,7 +17,6 @@ import type {
} from "@webstudio-is/sdk";
import type { Style } from "@webstudio-is/css-engine";
import type { Project } from "@webstudio-is/project";
-import type { MarketplaceProduct } from "@webstudio-is/project-build";
import type { TokenPermissions } from "@webstudio-is/authorization-token";
import type { DragStartPayload } from "~/canvas/shared/use-drag-drop";
import { type InstanceSelector } from "../tree-utils";
@@ -461,6 +460,4 @@ export const $dragAndDropState = atom({
isDragging: false,
});
-export const $marketplaceProduct = atom();
-
export const $canvasToolsVisible = atom(true);
diff --git a/apps/builder/app/shared/nano-states/project-settings.ts b/apps/builder/app/shared/nano-states/project-settings.ts
index 9ad360984030..1706dcaad24c 100644
--- a/apps/builder/app/shared/nano-states/project-settings.ts
+++ b/apps/builder/app/shared/nano-states/project-settings.ts
@@ -1,5 +1,5 @@
import { atom } from "nanostores";
export const $openProjectSettings = atom<
- "general" | "redirects" | "publish" | "marketplace" | undefined
+ "general" | "redirects" | "publish" | undefined
>();
diff --git a/apps/builder/app/shared/router-utils/path-utils.ts b/apps/builder/app/shared/router-utils/path-utils.ts
index 4f87e727b1fd..2e6db40300c3 100644
--- a/apps/builder/app/shared/router-utils/path-utils.ts
+++ b/apps/builder/app/shared/router-utils/path-utils.ts
@@ -107,17 +107,11 @@ export const userPlanSubscriptionPath = () => {
return `/n8n/billing_portal/sessions?${urlSearchParams.toString()}`;
};
-export const authCallbackPath = ({
- provider,
-}: {
- provider: "google" | "github";
-}) => `/auth/${provider}/callback`;
+export const authCallbackPath = ({ provider }: { provider: "google" }) =>
+ `/auth/${provider}/callback`;
-export const authPath = ({
- provider,
-}: {
- provider: "google" | "github" | "dev";
-}) => `/auth/${provider}`;
+export const authPath = ({ provider }: { provider: "google" | "dev" }) =>
+ `/auth/${provider}`;
export const restAssetsPath = () => {
return `/rest/assets`;
@@ -147,6 +141,3 @@ export const restAi = (subEndpoint?: "detect" | "audio/transcriptions") =>
typeof subEndpoint === "string" ? `/rest/ai/${subEndpoint}` : "/rest/ai";
export const restResourcesLoader = () => `/rest/resources-loader`;
-
-export const marketplacePath = (method: string) =>
- `/builder/marketplace/${method}`;
diff --git a/apps/builder/app/shared/session/use-login-error-message.ts b/apps/builder/app/shared/session/use-login-error-message.ts
index 2b4be607decf..d82fb8c103f1 100644
--- a/apps/builder/app/shared/session/use-login-error-message.ts
+++ b/apps/builder/app/shared/session/use-login-error-message.ts
@@ -3,14 +3,11 @@ import { useSearchParams } from "@remix-run/react";
export const AUTH_PROVIDERS = {
LOGIN_DEV: "login_dev",
- LOGIN_GITHUB: "login_github",
LOGIN_GOOGLE: "login_google",
} as const;
export const LOGIN_ERROR_MESSAGES = {
[AUTH_PROVIDERS.LOGIN_DEV]: "There has been an issue logging you in with dev",
- [AUTH_PROVIDERS.LOGIN_GITHUB]:
- "There has been an issue logging you in with Github",
[AUTH_PROVIDERS.LOGIN_GOOGLE]:
"There has been an issue logging you in with Google",
};
@@ -43,9 +40,6 @@ export const useLoginErrorMessage = (): string => {
case AUTH_PROVIDERS.LOGIN_DEV:
setMessageToReturn(LOGIN_ERROR_MESSAGES[AUTH_PROVIDERS.LOGIN_DEV]);
break;
- case AUTH_PROVIDERS.LOGIN_GITHUB:
- setMessageToReturn(LOGIN_ERROR_MESSAGES[AUTH_PROVIDERS.LOGIN_GITHUB]);
- break;
case AUTH_PROVIDERS.LOGIN_GOOGLE:
setMessageToReturn(LOGIN_ERROR_MESSAGES[AUTH_PROVIDERS.LOGIN_GOOGLE]);
break;
diff --git a/apps/builder/app/shared/sync/sync-stores.ts b/apps/builder/app/shared/sync/sync-stores.ts
index 64cb63d5ae60..6e589c323104 100644
--- a/apps/builder/app/shared/sync/sync-stores.ts
+++ b/apps/builder/app/shared/sync/sync-stores.ts
@@ -27,7 +27,6 @@ import {
$selectedInstanceStates,
$resources,
$resourceValues,
- $marketplaceProduct,
$canvasIframeState,
$uploadingFilesDataStore,
$memoryProps,
@@ -79,7 +78,6 @@ export const registerContainers = () => {
serverSyncStore.register("dataSources", $dataSources);
serverSyncStore.register("resources", $resources);
serverSyncStore.register("assets", $assets);
- serverSyncStore.register("marketplaceProduct", $marketplaceProduct);
};
export const createObjectPool = () => {
diff --git a/apps/builder/package.json b/apps/builder/package.json
index 7f735455421e..47d8127abdb0 100644
--- a/apps/builder/package.json
+++ b/apps/builder/package.json
@@ -54,7 +54,6 @@
"@trpc/server": "^10.45.2",
"@tsndr/cloudflare-worker-jwt": "^2.5.3",
"@vercel/remix": "2.15.2",
- "@webstudio-is/ai": "workspace:*",
"@webstudio-is/asset-uploader": "workspace:*",
"@webstudio-is/authorization-token": "workspace:*",
"@webstudio-is/css-data": "workspace:*",
@@ -106,7 +105,6 @@
"react-script-hook": "^1.7.2",
"remix-auth": "^3.7.0",
"remix-auth-form": "^1.5.0",
- "remix-auth-github": "^1.7.0",
"remix-auth-google": "^2.0.0",
"remix-auth-oauth2": "^2.3.0",
"shallow-equal": "^3.1.0",
diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.sitemap.xml.ts b/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.sitemap.xml.ts
deleted file mode 100644
index 3385a96eab63..000000000000
--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.sitemap.xml.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-export const sitemap = [
- {
- path: "/",
- lastModified: "2024-09-03",
- },
-];
diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.server.tsx b/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.server.tsx
deleted file mode 100644
index abaf39176bec..000000000000
--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.server.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-/* eslint-disable */
-/* This is a auto generated file for building the project */
-
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
-export const getResources = (_props: { system: System }) => {
- const _data = new Map([]);
- const _action = new Map([]);
- return { data: _data, action: _action };
-};
-
-export const getPageMeta = ({
- system,
- resources,
-}: {
- system: System;
- resources: Record;
-}): PageMeta => {
- return {
- title: "Home",
- description: undefined,
- excludePageFromSearch: undefined,
- language: undefined,
- socialImageAssetName: undefined,
- socialImageUrl: undefined,
- status: undefined,
- redirect: undefined,
- custom: [],
- };
-};
-
-type Params = Record;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
-
-export const projectId = "8a7358b1-7de3-459d-b7b1-56dddfb6ce1e";
-
-export const contactEmail = "hello@webstudio.is";
diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.tsx b/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.tsx
deleted file mode 100644
index 81c342dc370c..000000000000
--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.tsx
+++ /dev/null
@@ -1,33 +0,0 @@
-/* eslint-disable */
-/* This is a auto generated file for building the project */
-
-import { Fragment, useState } from "react";
-import type { FontAsset, ImageAsset } from "@webstudio-is/sdk";
-import { useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
-import {
- Body as Body,
- Heading as Heading,
-} from "@webstudio-is/sdk-components-react";
-
-export const siteName = undefined;
-
-export const favIconAsset: ImageAsset | undefined = undefined;
-
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: FontAsset[] = [];
-
-export const pageBackgroundImageAssets: ImageAsset[] = [];
-
-export const CustomCode = () => {
- return <>>;
-};
-
-const Page = ({}: { system: any }) => {
- return (
-
- {"FIXTURE-CLIENT-DO-NOT-TOUCH"}
-
- );
-};
-
-export { Page };
diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/index.css b/fixtures/ssg-netlify-by-project-id/app/__generated__/index.css
deleted file mode 100644
index 3b9a2ccc741a..000000000000
--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/index.css
+++ /dev/null
@@ -1,69 +0,0 @@
-@media all {
- :root {
- display: grid;
- min-height: 100%;
- font-family: Arial, Roboto, sans-serif;
- font-size: 16px;
- line-height: 1.2;
- white-space: pre-wrap;
- white-space-collapse: preserve;
- }
- :where(body.w-body) {
- box-sizing: border-box;
- border-top-width: 1px;
- border-right-width: 1px;
- border-bottom-width: 1px;
- border-left-width: 1px;
- -webkit-font-smoothing: antialiased;
- -moz-osx-font-smoothing: grayscale;
- margin: 0;
- }
- :where(h1.w-heading) {
- box-sizing: border-box;
- border-top-width: 1px;
- border-right-width: 1px;
- border-bottom-width: 1px;
- border-left-width: 1px;
- outline-width: 1px;
- }
- :where(h2.w-heading) {
- box-sizing: border-box;
- border-top-width: 1px;
- border-right-width: 1px;
- border-bottom-width: 1px;
- border-left-width: 1px;
- outline-width: 1px;
- }
- :where(h3.w-heading) {
- box-sizing: border-box;
- border-top-width: 1px;
- border-right-width: 1px;
- border-bottom-width: 1px;
- border-left-width: 1px;
- outline-width: 1px;
- }
- :where(h4.w-heading) {
- box-sizing: border-box;
- border-top-width: 1px;
- border-right-width: 1px;
- border-bottom-width: 1px;
- border-left-width: 1px;
- outline-width: 1px;
- }
- :where(h5.w-heading) {
- box-sizing: border-box;
- border-top-width: 1px;
- border-right-width: 1px;
- border-bottom-width: 1px;
- border-left-width: 1px;
- outline-width: 1px;
- }
- :where(h6.w-heading) {
- box-sizing: border-box;
- border-top-width: 1px;
- border-right-width: 1px;
- border-bottom-width: 1px;
- border-left-width: 1px;
- outline-width: 1px;
- }
-}
diff --git a/fixtures/ssg/.webstudio/data.json b/fixtures/ssg/.webstudio/data.json
index 8f97956ab8a2..e8b2af5c93b5 100644
--- a/fixtures/ssg/.webstudio/data.json
+++ b/fixtures/ssg/.webstudio/data.json
@@ -43,9 +43,6 @@
}
]
},
- "marketplace": {
- "include": false
- },
"path": "/another-page"
}
],
@@ -453,9 +450,6 @@
}
]
},
- "marketplace": {
- "include": false
- },
"path": "/another-page"
}
],
diff --git a/fixtures/webstudio-cloudflare-template/.webstudio/data.json b/fixtures/webstudio-cloudflare-template/.webstudio/data.json
index 8f97956ab8a2..e8b2af5c93b5 100644
--- a/fixtures/webstudio-cloudflare-template/.webstudio/data.json
+++ b/fixtures/webstudio-cloudflare-template/.webstudio/data.json
@@ -43,9 +43,6 @@
}
]
},
- "marketplace": {
- "include": false
- },
"path": "/another-page"
}
],
@@ -453,9 +450,6 @@
}
]
},
- "marketplace": {
- "include": false
- },
"path": "/another-page"
}
],
diff --git a/fixtures/webstudio-remix-netlify-edge-functions/.webstudio/data.json b/fixtures/webstudio-remix-netlify-edge-functions/.webstudio/data.json
index 8f97956ab8a2..e8b2af5c93b5 100644
--- a/fixtures/webstudio-remix-netlify-edge-functions/.webstudio/data.json
+++ b/fixtures/webstudio-remix-netlify-edge-functions/.webstudio/data.json
@@ -43,9 +43,6 @@
}
]
},
- "marketplace": {
- "include": false
- },
"path": "/another-page"
}
],
@@ -453,9 +450,6 @@
}
]
},
- "marketplace": {
- "include": false
- },
"path": "/another-page"
}
],
diff --git a/fixtures/webstudio-remix-netlify-functions/.webstudio/data.json b/fixtures/webstudio-remix-netlify-functions/.webstudio/data.json
index 7dc933cfb601..cc0bb3d1bdd5 100644
--- a/fixtures/webstudio-remix-netlify-functions/.webstudio/data.json
+++ b/fixtures/webstudio-remix-netlify-functions/.webstudio/data.json
@@ -43,9 +43,6 @@
}
]
},
- "marketplace": {
- "include": false
- },
"path": "/another-page"
}
],
@@ -455,9 +452,6 @@
}
]
},
- "marketplace": {
- "include": false
- },
"path": "/another-page"
}
],
diff --git a/fixtures/webstudio-remix-vercel/.webstudio/data.json b/fixtures/webstudio-remix-vercel/.webstudio/data.json
index aaa100ed3307..3634a0ff40ab 100644
--- a/fixtures/webstudio-remix-vercel/.webstudio/data.json
+++ b/fixtures/webstudio-remix-vercel/.webstudio/data.json
@@ -130,9 +130,6 @@
"documentType": "html",
"custom": []
},
- "marketplace": {
- "include": false
- },
"path": "/expressions"
},
{
@@ -151,9 +148,6 @@
"documentType": "html",
"custom": []
},
- "marketplace": {
- "include": false
- },
"path": "/class-names"
},
{
@@ -177,9 +171,6 @@
}
]
},
- "marketplace": {
- "include": false
- },
"path": "/sitemap.xml"
},
{
@@ -198,9 +189,6 @@
"documentType": "html",
"custom": []
},
- "marketplace": {
- "include": false
- },
"path": "/content-block"
},
{
@@ -5282,9 +5270,6 @@
"documentType": "html",
"custom": []
},
- "marketplace": {
- "include": false
- },
"path": "/expressions"
},
{
@@ -5303,9 +5288,6 @@
"documentType": "html",
"custom": []
},
- "marketplace": {
- "include": false
- },
"path": "/class-names"
},
{
@@ -5329,9 +5311,6 @@
}
]
},
- "marketplace": {
- "include": false
- },
"path": "/sitemap.xml"
},
{
@@ -5350,9 +5329,6 @@
"documentType": "html",
"custom": []
},
- "marketplace": {
- "include": false
- },
"path": "/content-block"
},
{
diff --git a/packages/ai/.prettierignore b/packages/ai/.prettierignore
deleted file mode 100644
index a61127f38845..000000000000
--- a/packages/ai/.prettierignore
+++ /dev/null
@@ -1 +0,0 @@
-src/chains/**/*.prompt.md
diff --git a/packages/ai/LICENSE b/packages/ai/LICENSE
deleted file mode 100644
index be3f7b28e564..000000000000
--- a/packages/ai/LICENSE
+++ /dev/null
@@ -1,661 +0,0 @@
- GNU AFFERO GENERAL PUBLIC LICENSE
- Version 3, 19 November 2007
-
- Copyright (C) 2007 Free Software Foundation, Inc.
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The GNU Affero General Public License is a free, copyleft license for
-software and other kinds of works, specifically designed to ensure
-cooperation with the community in the case of network server software.
-
- The licenses for most software and other practical works are designed
-to take away your freedom to share and change the works. By contrast,
-our General Public Licenses are intended to guarantee your freedom to
-share and change all versions of a program--to make sure it remains free
-software for all its users.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-them if you wish), that you receive source code or can get it if you
-want it, that you can change the software or use pieces of it in new
-free programs, and that you know you can do these things.
-
- Developers that use our General Public Licenses protect your rights
-with two steps: (1) assert copyright on the software, and (2) offer
-you this License which gives you legal permission to copy, distribute
-and/or modify the software.
-
- A secondary benefit of defending all users' freedom is that
-improvements made in alternate versions of the program, if they
-receive widespread use, become available for other developers to
-incorporate. Many developers of free software are heartened and
-encouraged by the resulting cooperation. However, in the case of
-software used on network servers, this result may fail to come about.
-The GNU General Public License permits making a modified version and
-letting the public access it on a server without ever releasing its
-source code to the public.
-
- The GNU Affero General Public License is designed specifically to
-ensure that, in such cases, the modified source code becomes available
-to the community. It requires the operator of a network server to
-provide the source code of the modified version running there to the
-users of that server. Therefore, public use of a modified version, on
-a publicly accessible server, gives the public access to the source
-code of the modified version.
-
- An older license, called the Affero General Public License and
-published by Affero, was designed to accomplish similar goals. This is
-a different license, not a version of the Affero GPL, but Affero has
-released a new version of the Affero GPL which permits relicensing under
-this license.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- TERMS AND CONDITIONS
-
- 0. Definitions.
-
- "This License" refers to version 3 of the GNU Affero General Public License.
-
- "Copyright" also means copyright-like laws that apply to other kinds of
-works, such as semiconductor masks.
-
- "The Program" refers to any copyrightable work licensed under this
-License. Each licensee is addressed as "you". "Licensees" and
-"recipients" may be individuals or organizations.
-
- To "modify" a work means to copy from or adapt all or part of the work
-in a fashion requiring copyright permission, other than the making of an
-exact copy. The resulting work is called a "modified version" of the
-earlier work or a work "based on" the earlier work.
-
- A "covered work" means either the unmodified Program or a work based
-on the Program.
-
- To "propagate" a work means to do anything with it that, without
-permission, would make you directly or secondarily liable for
-infringement under applicable copyright law, except executing it on a
-computer or modifying a private copy. Propagation includes copying,
-distribution (with or without modification), making available to the
-public, and in some countries other activities as well.
-
- To "convey" a work means any kind of propagation that enables other
-parties to make or receive copies. Mere interaction with a user through
-a computer network, with no transfer of a copy, is not conveying.
-
- An interactive user interface displays "Appropriate Legal Notices"
-to the extent that it includes a convenient and prominently visible
-feature that (1) displays an appropriate copyright notice, and (2)
-tells the user that there is no warranty for the work (except to the
-extent that warranties are provided), that licensees may convey the
-work under this License, and how to view a copy of this License. If
-the interface presents a list of user commands or options, such as a
-menu, a prominent item in the list meets this criterion.
-
- 1. Source Code.
-
- The "source code" for a work means the preferred form of the work
-for making modifications to it. "Object code" means any non-source
-form of a work.
-
- A "Standard Interface" means an interface that either is an official
-standard defined by a recognized standards body, or, in the case of
-interfaces specified for a particular programming language, one that
-is widely used among developers working in that language.
-
- The "System Libraries" of an executable work include anything, other
-than the work as a whole, that (a) is included in the normal form of
-packaging a Major Component, but which is not part of that Major
-Component, and (b) serves only to enable use of the work with that
-Major Component, or to implement a Standard Interface for which an
-implementation is available to the public in source code form. A
-"Major Component", in this context, means a major essential component
-(kernel, window system, and so on) of the specific operating system
-(if any) on which the executable work runs, or a compiler used to
-produce the work, or an object code interpreter used to run it.
-
- The "Corresponding Source" for a work in object code form means all
-the source code needed to generate, install, and (for an executable
-work) run the object code and to modify the work, including scripts to
-control those activities. However, it does not include the work's
-System Libraries, or general-purpose tools or generally available free
-programs which are used unmodified in performing those activities but
-which are not part of the work. For example, Corresponding Source
-includes interface definition files associated with source files for
-the work, and the source code for shared libraries and dynamically
-linked subprograms that the work is specifically designed to require,
-such as by intimate data communication or control flow between those
-subprograms and other parts of the work.
-
- The Corresponding Source need not include anything that users
-can regenerate automatically from other parts of the Corresponding
-Source.
-
- The Corresponding Source for a work in source code form is that
-same work.
-
- 2. Basic Permissions.
-
- All rights granted under this License are granted for the term of
-copyright on the Program, and are irrevocable provided the stated
-conditions are met. This License explicitly affirms your unlimited
-permission to run the unmodified Program. The output from running a
-covered work is covered by this License only if the output, given its
-content, constitutes a covered work. This License acknowledges your
-rights of fair use or other equivalent, as provided by copyright law.
-
- You may make, run and propagate covered works that you do not
-convey, without conditions so long as your license otherwise remains
-in force. You may convey covered works to others for the sole purpose
-of having them make modifications exclusively for you, or provide you
-with facilities for running those works, provided that you comply with
-the terms of this License in conveying all material for which you do
-not control copyright. Those thus making or running the covered works
-for you must do so exclusively on your behalf, under your direction
-and control, on terms that prohibit them from making any copies of
-your copyrighted material outside their relationship with you.
-
- Conveying under any other circumstances is permitted solely under
-the conditions stated below. Sublicensing is not allowed; section 10
-makes it unnecessary.
-
- 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-
- No covered work shall be deemed part of an effective technological
-measure under any applicable law fulfilling obligations under article
-11 of the WIPO copyright treaty adopted on 20 December 1996, or
-similar laws prohibiting or restricting circumvention of such
-measures.
-
- When you convey a covered work, you waive any legal power to forbid
-circumvention of technological measures to the extent such circumvention
-is effected by exercising rights under this License with respect to
-the covered work, and you disclaim any intention to limit operation or
-modification of the work as a means of enforcing, against the work's
-users, your or third parties' legal rights to forbid circumvention of
-technological measures.
-
- 4. Conveying Verbatim Copies.
-
- You may convey verbatim copies of the Program's source code as you
-receive it, in any medium, provided that you conspicuously and
-appropriately publish on each copy an appropriate copyright notice;
-keep intact all notices stating that this License and any
-non-permissive terms added in accord with section 7 apply to the code;
-keep intact all notices of the absence of any warranty; and give all
-recipients a copy of this License along with the Program.
-
- You may charge any price or no price for each copy that you convey,
-and you may offer support or warranty protection for a fee.
-
- 5. Conveying Modified Source Versions.
-
- You may convey a work based on the Program, or the modifications to
-produce it from the Program, in the form of source code under the
-terms of section 4, provided that you also meet all of these conditions:
-
- a) The work must carry prominent notices stating that you modified
- it, and giving a relevant date.
-
- b) The work must carry prominent notices stating that it is
- released under this License and any conditions added under section
- 7. This requirement modifies the requirement in section 4 to
- "keep intact all notices".
-
- c) You must license the entire work, as a whole, under this
- License to anyone who comes into possession of a copy. This
- License will therefore apply, along with any applicable section 7
- additional terms, to the whole of the work, and all its parts,
- regardless of how they are packaged. This License gives no
- permission to license the work in any other way, but it does not
- invalidate such permission if you have separately received it.
-
- d) If the work has interactive user interfaces, each must display
- Appropriate Legal Notices; however, if the Program has interactive
- interfaces that do not display Appropriate Legal Notices, your
- work need not make them do so.
-
- A compilation of a covered work with other separate and independent
-works, which are not by their nature extensions of the covered work,
-and which are not combined with it such as to form a larger program,
-in or on a volume of a storage or distribution medium, is called an
-"aggregate" if the compilation and its resulting copyright are not
-used to limit the access or legal rights of the compilation's users
-beyond what the individual works permit. Inclusion of a covered work
-in an aggregate does not cause this License to apply to the other
-parts of the aggregate.
-
- 6. Conveying Non-Source Forms.
-
- You may convey a covered work in object code form under the terms
-of sections 4 and 5, provided that you also convey the
-machine-readable Corresponding Source under the terms of this License,
-in one of these ways:
-
- a) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by the
- Corresponding Source fixed on a durable physical medium
- customarily used for software interchange.
-
- b) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by a
- written offer, valid for at least three years and valid for as
- long as you offer spare parts or customer support for that product
- model, to give anyone who possesses the object code either (1) a
- copy of the Corresponding Source for all the software in the
- product that is covered by this License, on a durable physical
- medium customarily used for software interchange, for a price no
- more than your reasonable cost of physically performing this
- conveying of source, or (2) access to copy the
- Corresponding Source from a network server at no charge.
-
- c) Convey individual copies of the object code with a copy of the
- written offer to provide the Corresponding Source. This
- alternative is allowed only occasionally and noncommercially, and
- only if you received the object code with such an offer, in accord
- with subsection 6b.
-
- d) Convey the object code by offering access from a designated
- place (gratis or for a charge), and offer equivalent access to the
- Corresponding Source in the same way through the same place at no
- further charge. You need not require recipients to copy the
- Corresponding Source along with the object code. If the place to
- copy the object code is a network server, the Corresponding Source
- may be on a different server (operated by you or a third party)
- that supports equivalent copying facilities, provided you maintain
- clear directions next to the object code saying where to find the
- Corresponding Source. Regardless of what server hosts the
- Corresponding Source, you remain obligated to ensure that it is
- available for as long as needed to satisfy these requirements.
-
- e) Convey the object code using peer-to-peer transmission, provided
- you inform other peers where the object code and Corresponding
- Source of the work are being offered to the general public at no
- charge under subsection 6d.
-
- A separable portion of the object code, whose source code is excluded
-from the Corresponding Source as a System Library, need not be
-included in conveying the object code work.
-
- A "User Product" is either (1) a "consumer product", which means any
-tangible personal property which is normally used for personal, family,
-or household purposes, or (2) anything designed or sold for incorporation
-into a dwelling. In determining whether a product is a consumer product,
-doubtful cases shall be resolved in favor of coverage. For a particular
-product received by a particular user, "normally used" refers to a
-typical or common use of that class of product, regardless of the status
-of the particular user or of the way in which the particular user
-actually uses, or expects or is expected to use, the product. A product
-is a consumer product regardless of whether the product has substantial
-commercial, industrial or non-consumer uses, unless such uses represent
-the only significant mode of use of the product.
-
- "Installation Information" for a User Product means any methods,
-procedures, authorization keys, or other information required to install
-and execute modified versions of a covered work in that User Product from
-a modified version of its Corresponding Source. The information must
-suffice to ensure that the continued functioning of the modified object
-code is in no case prevented or interfered with solely because
-modification has been made.
-
- If you convey an object code work under this section in, or with, or
-specifically for use in, a User Product, and the conveying occurs as
-part of a transaction in which the right of possession and use of the
-User Product is transferred to the recipient in perpetuity or for a
-fixed term (regardless of how the transaction is characterized), the
-Corresponding Source conveyed under this section must be accompanied
-by the Installation Information. But this requirement does not apply
-if neither you nor any third party retains the ability to install
-modified object code on the User Product (for example, the work has
-been installed in ROM).
-
- The requirement to provide Installation Information does not include a
-requirement to continue to provide support service, warranty, or updates
-for a work that has been modified or installed by the recipient, or for
-the User Product in which it has been modified or installed. Access to a
-network may be denied when the modification itself materially and
-adversely affects the operation of the network or violates the rules and
-protocols for communication across the network.
-
- Corresponding Source conveyed, and Installation Information provided,
-in accord with this section must be in a format that is publicly
-documented (and with an implementation available to the public in
-source code form), and must require no special password or key for
-unpacking, reading or copying.
-
- 7. Additional Terms.
-
- "Additional permissions" are terms that supplement the terms of this
-License by making exceptions from one or more of its conditions.
-Additional permissions that are applicable to the entire Program shall
-be treated as though they were included in this License, to the extent
-that they are valid under applicable law. If additional permissions
-apply only to part of the Program, that part may be used separately
-under those permissions, but the entire Program remains governed by
-this License without regard to the additional permissions.
-
- When you convey a copy of a covered work, you may at your option
-remove any additional permissions from that copy, or from any part of
-it. (Additional permissions may be written to require their own
-removal in certain cases when you modify the work.) You may place
-additional permissions on material, added by you to a covered work,
-for which you have or can give appropriate copyright permission.
-
- Notwithstanding any other provision of this License, for material you
-add to a covered work, you may (if authorized by the copyright holders of
-that material) supplement the terms of this License with terms:
-
- a) Disclaiming warranty or limiting liability differently from the
- terms of sections 15 and 16 of this License; or
-
- b) Requiring preservation of specified reasonable legal notices or
- author attributions in that material or in the Appropriate Legal
- Notices displayed by works containing it; or
-
- c) Prohibiting misrepresentation of the origin of that material, or
- requiring that modified versions of such material be marked in
- reasonable ways as different from the original version; or
-
- d) Limiting the use for publicity purposes of names of licensors or
- authors of the material; or
-
- e) Declining to grant rights under trademark law for use of some
- trade names, trademarks, or service marks; or
-
- f) Requiring indemnification of licensors and authors of that
- material by anyone who conveys the material (or modified versions of
- it) with contractual assumptions of liability to the recipient, for
- any liability that these contractual assumptions directly impose on
- those licensors and authors.
-
- All other non-permissive additional terms are considered "further
-restrictions" within the meaning of section 10. If the Program as you
-received it, or any part of it, contains a notice stating that it is
-governed by this License along with a term that is a further
-restriction, you may remove that term. If a license document contains
-a further restriction but permits relicensing or conveying under this
-License, you may add to a covered work material governed by the terms
-of that license document, provided that the further restriction does
-not survive such relicensing or conveying.
-
- If you add terms to a covered work in accord with this section, you
-must place, in the relevant source files, a statement of the
-additional terms that apply to those files, or a notice indicating
-where to find the applicable terms.
-
- Additional terms, permissive or non-permissive, may be stated in the
-form of a separately written license, or stated as exceptions;
-the above requirements apply either way.
-
- 8. Termination.
-
- You may not propagate or modify a covered work except as expressly
-provided under this License. Any attempt otherwise to propagate or
-modify it is void, and will automatically terminate your rights under
-this License (including any patent licenses granted under the third
-paragraph of section 11).
-
- However, if you cease all violation of this License, then your
-license from a particular copyright holder is reinstated (a)
-provisionally, unless and until the copyright holder explicitly and
-finally terminates your license, and (b) permanently, if the copyright
-holder fails to notify you of the violation by some reasonable means
-prior to 60 days after the cessation.
-
- Moreover, your license from a particular copyright holder is
-reinstated permanently if the copyright holder notifies you of the
-violation by some reasonable means, this is the first time you have
-received notice of violation of this License (for any work) from that
-copyright holder, and you cure the violation prior to 30 days after
-your receipt of the notice.
-
- Termination of your rights under this section does not terminate the
-licenses of parties who have received copies or rights from you under
-this License. If your rights have been terminated and not permanently
-reinstated, you do not qualify to receive new licenses for the same
-material under section 10.
-
- 9. Acceptance Not Required for Having Copies.
-
- You are not required to accept this License in order to receive or
-run a copy of the Program. Ancillary propagation of a covered work
-occurring solely as a consequence of using peer-to-peer transmission
-to receive a copy likewise does not require acceptance. However,
-nothing other than this License grants you permission to propagate or
-modify any covered work. These actions infringe copyright if you do
-not accept this License. Therefore, by modifying or propagating a
-covered work, you indicate your acceptance of this License to do so.
-
- 10. Automatic Licensing of Downstream Recipients.
-
- Each time you convey a covered work, the recipient automatically
-receives a license from the original licensors, to run, modify and
-propagate that work, subject to this License. You are not responsible
-for enforcing compliance by third parties with this License.
-
- An "entity transaction" is a transaction transferring control of an
-organization, or substantially all assets of one, or subdividing an
-organization, or merging organizations. If propagation of a covered
-work results from an entity transaction, each party to that
-transaction who receives a copy of the work also receives whatever
-licenses to the work the party's predecessor in interest had or could
-give under the previous paragraph, plus a right to possession of the
-Corresponding Source of the work from the predecessor in interest, if
-the predecessor has it or can get it with reasonable efforts.
-
- You may not impose any further restrictions on the exercise of the
-rights granted or affirmed under this License. For example, you may
-not impose a license fee, royalty, or other charge for exercise of
-rights granted under this License, and you may not initiate litigation
-(including a cross-claim or counterclaim in a lawsuit) alleging that
-any patent claim is infringed by making, using, selling, offering for
-sale, or importing the Program or any portion of it.
-
- 11. Patents.
-
- A "contributor" is a copyright holder who authorizes use under this
-License of the Program or a work on which the Program is based. The
-work thus licensed is called the contributor's "contributor version".
-
- A contributor's "essential patent claims" are all patent claims
-owned or controlled by the contributor, whether already acquired or
-hereafter acquired, that would be infringed by some manner, permitted
-by this License, of making, using, or selling its contributor version,
-but do not include claims that would be infringed only as a
-consequence of further modification of the contributor version. For
-purposes of this definition, "control" includes the right to grant
-patent sublicenses in a manner consistent with the requirements of
-this License.
-
- Each contributor grants you a non-exclusive, worldwide, royalty-free
-patent license under the contributor's essential patent claims, to
-make, use, sell, offer for sale, import and otherwise run, modify and
-propagate the contents of its contributor version.
-
- In the following three paragraphs, a "patent license" is any express
-agreement or commitment, however denominated, not to enforce a patent
-(such as an express permission to practice a patent or covenant not to
-sue for patent infringement). To "grant" such a patent license to a
-party means to make such an agreement or commitment not to enforce a
-patent against the party.
-
- If you convey a covered work, knowingly relying on a patent license,
-and the Corresponding Source of the work is not available for anyone
-to copy, free of charge and under the terms of this License, through a
-publicly available network server or other readily accessible means,
-then you must either (1) cause the Corresponding Source to be so
-available, or (2) arrange to deprive yourself of the benefit of the
-patent license for this particular work, or (3) arrange, in a manner
-consistent with the requirements of this License, to extend the patent
-license to downstream recipients. "Knowingly relying" means you have
-actual knowledge that, but for the patent license, your conveying the
-covered work in a country, or your recipient's use of the covered work
-in a country, would infringe one or more identifiable patents in that
-country that you have reason to believe are valid.
-
- If, pursuant to or in connection with a single transaction or
-arrangement, you convey, or propagate by procuring conveyance of, a
-covered work, and grant a patent license to some of the parties
-receiving the covered work authorizing them to use, propagate, modify
-or convey a specific copy of the covered work, then the patent license
-you grant is automatically extended to all recipients of the covered
-work and works based on it.
-
- A patent license is "discriminatory" if it does not include within
-the scope of its coverage, prohibits the exercise of, or is
-conditioned on the non-exercise of one or more of the rights that are
-specifically granted under this License. You may not convey a covered
-work if you are a party to an arrangement with a third party that is
-in the business of distributing software, under which you make payment
-to the third party based on the extent of your activity of conveying
-the work, and under which the third party grants, to any of the
-parties who would receive the covered work from you, a discriminatory
-patent license (a) in connection with copies of the covered work
-conveyed by you (or copies made from those copies), or (b) primarily
-for and in connection with specific products or compilations that
-contain the covered work, unless you entered into that arrangement,
-or that patent license was granted, prior to 28 March 2007.
-
- Nothing in this License shall be construed as excluding or limiting
-any implied license or other defenses to infringement that may
-otherwise be available to you under applicable patent law.
-
- 12. No Surrender of Others' Freedom.
-
- If conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot convey a
-covered work so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you may
-not convey it at all. For example, if you agree to terms that obligate you
-to collect a royalty for further conveying from those to whom you convey
-the Program, the only way you could satisfy both those terms and this
-License would be to refrain entirely from conveying the Program.
-
- 13. Remote Network Interaction; Use with the GNU General Public License.
-
- Notwithstanding any other provision of this License, if you modify the
-Program, your modified version must prominently offer all users
-interacting with it remotely through a computer network (if your version
-supports such interaction) an opportunity to receive the Corresponding
-Source of your version by providing access to the Corresponding Source
-from a network server at no charge, through some standard or customary
-means of facilitating copying of software. This Corresponding Source
-shall include the Corresponding Source for any work covered by version 3
-of the GNU General Public License that is incorporated pursuant to the
-following paragraph.
-
- Notwithstanding any other provision of this License, you have
-permission to link or combine any covered work with a work licensed
-under version 3 of the GNU General Public License into a single
-combined work, and to convey the resulting work. The terms of this
-License will continue to apply to the part which is the covered work,
-but the work with which it is combined will remain governed by version
-3 of the GNU General Public License.
-
- 14. Revised Versions of this License.
-
- The Free Software Foundation may publish revised and/or new versions of
-the GNU Affero General Public License from time to time. Such new versions
-will be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
- Each version is given a distinguishing version number. If the
-Program specifies that a certain numbered version of the GNU Affero General
-Public License "or any later version" applies to it, you have the
-option of following the terms and conditions either of that numbered
-version or of any later version published by the Free Software
-Foundation. If the Program does not specify a version number of the
-GNU Affero General Public License, you may choose any version ever published
-by the Free Software Foundation.
-
- If the Program specifies that a proxy can decide which future
-versions of the GNU Affero General Public License can be used, that proxy's
-public statement of acceptance of a version permanently authorizes you
-to choose that version for the Program.
-
- Later license versions may give you additional or different
-permissions. However, no additional obligations are imposed on any
-author or copyright holder as a result of your choosing to follow a
-later version.
-
- 15. Disclaimer of Warranty.
-
- THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
-APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
-HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
-OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
-THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
-IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
-ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 16. Limitation of Liability.
-
- IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
-THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
-GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
-USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
-DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
-PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
-EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGES.
-
- 17. Interpretation of Sections 15 and 16.
-
- If the disclaimer of warranty and limitation of liability provided
-above cannot be given local legal effect according to their terms,
-reviewing courts shall apply local law that most closely approximates
-an absolute waiver of all civil liability in connection with the
-Program, unless a warranty or assumption of liability accompanies a
-copy of the Program in return for a fee.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-state the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
-
- Copyright (C)
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU Affero General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU Affero General Public License for more details.
-
- You should have received a copy of the GNU Affero General Public License
- along with this program. If not, see .
-
-Also add information on how to contact you by electronic and paper mail.
-
- If your software can interact with users remotely through a computer
-network, you should also make sure that it provides a way for users to
-get its source. For example, if your program is a web application, its
-interface could display a "Source" link that leads users to an archive
-of the code. There are many ways you could offer source, and different
-solutions will be better for different programs; see section 13 for the
-specific requirements.
-
- You should also get your employer (if you work as a programmer) or school,
-if any, to sign a "copyright disclaimer" for the program, if necessary.
-For more information on this, and how to apply and follow the GNU AGPL, see
-.
diff --git a/packages/ai/README.md b/packages/ai/README.md
deleted file mode 100644
index 257294aad864..000000000000
--- a/packages/ai/README.md
+++ /dev/null
@@ -1,35 +0,0 @@
-# Webstudio AI
-
-The Webstudio AI package offers two main features:
-
-### LLM Abstraction
-
-A minimal abstraction for a generic, vendor-agnostic messages format and LLM client, allowing for building features without using model-specific APIs.
-
-See [details](./src/models/README.md).
-
-An implementation of the above that uses the OpenAI chat completion endpoint is [available here](./src/models/gpt.ts).
-
-### Chains
-
-A common interface for chains. Chains are regular async functions that can execute an arbitrary number of steps, including calling a LLM via a [model client](./src/models).
-
-See [details](./src/chains/README.md).
-
-## Usage
-
-Install the package
-
-```
-pnpm i @webstudio-is/ai
-```
-
-For an example usage check out the [base example](./src/chains/README.md#example-chain) and [the copywriter chain](./src/chains/copywriter/chain.ts) that generates copy for Webstudio.
-
-### Prompt templates
-
-This package comes with a small CLI that allows to turn prompt templates from markdown files to TypeScript modules, which is what you would use in your chain.
-
-```
-pnpm run build:prompts
-```
diff --git a/packages/ai/bin/build-prompts.ts b/packages/ai/bin/build-prompts.ts
deleted file mode 100644
index 5bcc88e70963..000000000000
--- a/packages/ai/bin/build-prompts.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import fg from "fast-glob";
-import * as fs from "node:fs";
-import * as path from "node:path";
-
-const GENERATED_FILES_DIR = "__generated__";
-const [globs] = process.argv.slice(2);
-
-if (!globs || !globs.trim()) {
- throw new Error(
- "Please provide glob patterns (space separated) as arguments to match your prompts"
- );
-}
-
-const prompts = fg.sync(globs);
-
-if (prompts.length === 0) {
- throw new Error("No prompt files found");
-}
-
-prompts.forEach((filePath) => {
- const generatedDir = path.join(path.dirname(filePath), GENERATED_FILES_DIR);
-
- fs.mkdirSync(generatedDir, { recursive: true });
-
- const generatedFile = `${path.basename(filePath, ".md")}.ts`;
- const generatedPath = path.join(generatedDir, generatedFile);
-
- const content = fs
- .readFileSync(filePath, "utf-8")
- .replace(/`/g, "\\`")
- .replace(/\$/g, "\\$"); // @todo technically we should escape only the $ that belong to template literals.;
-
- fs.writeFileSync(generatedPath, `export const prompt = \`${content}\`;\n`);
-
- console.info(`Done generating argTypes for ${generatedPath}`);
-});
diff --git a/packages/ai/package.json b/packages/ai/package.json
deleted file mode 100644
index 00cd1ecc7795..000000000000
--- a/packages/ai/package.json
+++ /dev/null
@@ -1,40 +0,0 @@
-{
- "private": true,
- "name": "@webstudio-is/ai",
- "version": "0.0.0",
- "description": "Webstudio AI Tools",
- "author": "Webstudio ",
- "homepage": "https://webstudio.is",
- "type": "module",
- "scripts": {
- "typecheck": "tsc",
- "build:prompts": "tsx ./bin/build-prompts.ts \"./src/chains/**/*.prompt.md\""
- },
- "devDependencies": {
- "@webstudio-is/tsconfig": "workspace:^",
- "fast-glob": "^3.3.2"
- },
- "exports": {
- ".": {
- "webstudio": "./src/index.ts"
- },
- "./index.server": {
- "webstudio": "./src/index.server.ts"
- }
- },
- "license": "AGPL-3.0-or-later",
- "sideEffects": false,
- "dependencies": {
- "@webstudio-is/css-data": "workspace:*",
- "@webstudio-is/jsx-utils": "workspace:*",
- "@webstudio-is/react-sdk": "workspace:*",
- "@webstudio-is/sdk": "workspace:*",
- "ai": "^2.2.12",
- "escape-string-regexp": "^5.0.0",
- "mdast-util-from-markdown": "^2.0.2",
- "openai": "^4.8.0",
- "unist-util-visit-parents": "^6.0.1",
- "zod": "^3.22.4",
- "zod-to-json-schema": "^3.21.4"
- }
-}
diff --git a/packages/ai/src/chains/README.md b/packages/ai/src/chains/README.md
deleted file mode 100644
index 44af72f5be0d..000000000000
--- a/packages/ai/src/chains/README.md
+++ /dev/null
@@ -1,110 +0,0 @@
-# Chains
-
-A chain an async function that executes an arbitrarty number of steps, including calling a LLM via a [model client](../models).
-
-For example a chain can be used to manipulate some input data, make a LLM call and then parse, validate and transform the result.
-
-Chain files are modules that export a `createChain` factory. Each instance created by the factory gets a reference to a `model` client and a `context` object which includes input data such as prompt and other relevant methods for the specific chain.
-
-Additionally each chain should export types for `Context` and `Response` data (using these names) both as zod and TypeScript types.
-zod types must have a `Schema` suffix, for example `Response`.
-
-Generally you use chains server-side in your API request handler.
-
-## Example Chain
-
-chains/vibes/index.ts
-
-```typescript
-import { z } from "zod";
-import type {
- Model as BaseModel,
- ModelMessage,
- ChainStream,
-} from "../../types";
-import { formatPrompt } from "../../utils/format-prompt";
-
-export const Context = z.object({
- // A message from a user.
- message: z.string(),
-});
-export type Context = z.infer;
-
-export const Response = z.string();
-export type Response = z.infer;
-
-export const createChain = (): ChainStream<
- BaseModel,
- Response,
- Context
-> =>
- async function chain({ model, context }) {
- const { message } = context;
-
- const userMessage: ModelMessage = [
- "user",
- formatPrompt(
- { message },
- `
-What is the vibe of the following message?
-
-\`\`\`
-{message}
-\`\`\`
-
-Reply with "positive" or "negative"`
- ),
- ];
-
- const messages = model.generateMessages([userMessage]);
-
- const response = await model.request({ messages });
-
- if (response.success == false) {
- return response;
- }
-
- if (response.choices[0].includes("negative")) {
- return {
- success: false,
- status: 403,
- statusText: "Forbidden",
- message: "Not cool. Try with a nice message instead.",
- };
- }
-
- return response;
- };
-```
-
-## Example Usage
-
-Server side:
-
-```typescript
-import {
- vibes,
- createGptModel
- type GptModelMessageFormat
-} from "@webstudio-is/ai";
-
-export async function handler({ request }) {
- const { message } = await request.json();
-
- const model = createGptModel({
- apiKey: process.env.OPENAI_KEY,
- organization: process.env.OPENAI_ORG,
- temperature: 0.5,
- model: "gpt-3.5-turbo",
- });
-
- const chain = vibes.createChain();
-
- return chain({
- model,
- context: {
- message
- }
- })
-}
-```
diff --git a/packages/ai/src/chains/command-detect/README.md b/packages/ai/src/chains/command-detect/README.md
deleted file mode 100644
index 1d1bdfde70c9..000000000000
--- a/packages/ai/src/chains/command-detect/README.md
+++ /dev/null
@@ -1,45 +0,0 @@
-# Command Detection Chain
-
-Uses Streaming: `false`.
-
-Given a prompt and a list of possible commands and descriptions, it returns an array of operations matching the prompt request.
-
-## Usage
-
-```typescript
-import {
- commandDetect,
- createGptModel
- type GptModelMessageFormat
-} from "@webstudio-is/ai";
-
-export async function handler({ request }) {
- const { prompt, } = await request.json();
-
- const model = createGptModel({
- apiKey: process.env.OPENAI_KEY,
- organization: process.env.OPENAI_ORG,
- temperature: 0,
- model: "gpt-3.5-turbo",
- });
-
- const chain = commandDetect.createChain();
-
- const result = await chain({
- model,
- context: {
- prompt,
- commands: {
- "copywriter": "writes, rewrites, translates text",
- "edit-styles": "edits styles",
- // ...
- }
- }
- });
-
- if (result.succes === true) {
- // An array of detected command names.
- console.info(result.data);
- }
-}
-```
diff --git a/packages/ai/src/chains/command-detect/__generated__/command-detect.system.prompt.ts b/packages/ai/src/chains/command-detect/__generated__/command-detect.system.prompt.ts
deleted file mode 100644
index 5599400a7ee5..000000000000
--- a/packages/ai/src/chains/command-detect/__generated__/command-detect.system.prompt.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-export const prompt = `Given a prompt where a user requests you to perform a task, you should determine what's the task type.
-
-Avaliable tasks are provided below as an object with task_name:task_description pairs:
-
-\`\`\`json
-{commands}
-\`\`\`
-
-The task description can help you infer the task name to pick. For example if the user is asking to translate you should respond with ["copywrite"]
-
-Respond with a valid JSON array of task names that are relevant for the user request. Start with [
-
-Do not start your response with \`\`\`json
-`;
diff --git a/packages/ai/src/chains/command-detect/__generated__/command-detect.user.prompt.ts b/packages/ai/src/chains/command-detect/__generated__/command-detect.user.prompt.ts
deleted file mode 100644
index 5f09af279985..000000000000
--- a/packages/ai/src/chains/command-detect/__generated__/command-detect.user.prompt.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-export const prompt = `User request:
-
-\`\`\`
-{prompt}
-\`\`\`
-`;
diff --git a/packages/ai/src/chains/command-detect/chain.server.ts b/packages/ai/src/chains/command-detect/chain.server.ts
deleted file mode 100644
index 3e8adfa2997a..000000000000
--- a/packages/ai/src/chains/command-detect/chain.server.ts
+++ /dev/null
@@ -1,89 +0,0 @@
-import type { Model as BaseModel, ModelMessage, Chain } from "../../types";
-import { formatPrompt } from "../../utils/format-prompt";
-import { prompt as promptSystemTemplate } from "./__generated__/command-detect.system.prompt";
-import { prompt as promptUserTemplate } from "./__generated__/command-detect.user.prompt";
-import { createErrorResponse } from "../../utils/create-error-response";
-import { type AiContext, AiResponse, name } from "./schema";
-
-/**
- * Command Detect Chain
- *
- * Given a prompt and a list of possible commands and descriptions, it returns an array of operations matching the prompt request.
- */
-
-export { name };
-
-export const createChain = (): Chain<
- BaseModel,
- AiContext,
- AiResponse
-> =>
- async function chain({ model, context }) {
- const { prompt, commands } = context;
-
- const llmMessages: ModelMessage[] = [
- [
- "system",
- formatPrompt(
- {
- commands: JSON.stringify(commands),
- },
- promptSystemTemplate
- ),
- ],
- ["user", formatPrompt({ prompt }, promptUserTemplate)],
- ];
-
- const messages = model.generateMessages(llmMessages);
-
- const completion = await model.completion({
- id: name,
- messages,
- });
-
- if (completion.success === false) {
- return {
- ...completion,
- llmMessages,
- };
- }
-
- const completionText = completion.data.choices[0];
- llmMessages.push(["assistant", completionText]);
-
- let detectedCommands = [];
- try {
- detectedCommands = AiResponse.parse(JSON.parse(completionText));
- const expectedCommands = new Set(Object.keys(commands));
- for (const command of detectedCommands) {
- if (expectedCommands.has(command) === false) {
- throw new Error("Invalid command name detected " + command);
- }
- }
- } catch (error) {
- return {
- id: name,
- ...createErrorResponse({
- status: 500,
- error: `ai.${name}.parseError`,
- message:
- error instanceof Error
- ? error.message
- : "Failed to parse the completion",
- debug: (
- "Failed to parse the completion " +
- (error instanceof Error ? error.message : "")
- ).trim(),
- }),
- llmMessages,
- };
- }
-
- console.info(JSON.stringify({ prompt, detectedCommands }));
-
- return {
- ...completion,
- data: detectedCommands,
- llmMessages,
- };
- };
diff --git a/packages/ai/src/chains/command-detect/command-detect.system.prompt.md b/packages/ai/src/chains/command-detect/command-detect.system.prompt.md
deleted file mode 100644
index 36cfa370790b..000000000000
--- a/packages/ai/src/chains/command-detect/command-detect.system.prompt.md
+++ /dev/null
@@ -1,13 +0,0 @@
-Given a prompt where a user requests you to perform a task, you should determine what's the task type.
-
-Avaliable tasks are provided below as an object with task_name:task_description pairs:
-
-```json
-{commands}
-```
-
-The task description can help you infer the task name to pick. For example if the user is asking to translate you should respond with ["copywrite"]
-
-Respond with a valid JSON array of task names that are relevant for the user request. Start with [
-
-Do not start your response with ```json
diff --git a/packages/ai/src/chains/command-detect/command-detect.user.prompt.md b/packages/ai/src/chains/command-detect/command-detect.user.prompt.md
deleted file mode 100644
index 90f3c42d659a..000000000000
--- a/packages/ai/src/chains/command-detect/command-detect.user.prompt.md
+++ /dev/null
@@ -1,5 +0,0 @@
-User request:
-
-```
-{prompt}
-```
diff --git a/packages/ai/src/chains/command-detect/schema.ts b/packages/ai/src/chains/command-detect/schema.ts
deleted file mode 100644
index 5ee979535f85..000000000000
--- a/packages/ai/src/chains/command-detect/schema.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { z } from "zod";
-
-export const name = "command-detect";
-
-export const AiContext = z.object({
- // The prompt provides the original user request.
- prompt: z.string(),
- // Command name - description pairs.
- commands: z.record(z.string(), z.string()),
-});
-export type AiContext = z.infer;
-
-export const AiResponse = z.array(z.string());
-export type AiResponse = z.infer;
diff --git a/packages/ai/src/chains/copywriter/README.md b/packages/ai/src/chains/copywriter/README.md
deleted file mode 100644
index 5ac46b921367..000000000000
--- a/packages/ai/src/chains/copywriter/README.md
+++ /dev/null
@@ -1,170 +0,0 @@
-# Copywriter chain
-
-Uses Streaming: `true`.
-
-Given a description and an Webstudio component instance id, this chain generates copy for the instance and all its descendant text nodes.
-
-## Usage
-
-Server side:
-
-```typescript
-import {
- copywriter,
- createGptModel
- type GptModelMessageFormat
-} from "@webstudio-is/ai";
-
-export async function handler({ request }) {
- const { prompt, projectId, textInstances } = await request.json();
-
- const model = createGptModel({
- apiKey: process.env.OPENAI_KEY,
- organization: process.env.OPENAI_ORG,
- temperature: 0.5,
- model: "gpt-3.5-turbo",
- });
-
- const chain = copywriter.createChain();
-
- const response = await chain({
- model,
- context: {
- prompt,
- textInstances
- }
- });
-
- if (response.success === false) {
- return response;
- }
-
- // Respond with the text generation stream.
- return response.stream;
-}
-```
-
-Client side:
-
-```tsx
-import {
- copywriter,
- handleAiRequest,
- type RemixStreamingTextResponse
-} from "@webstudio-is/ai";
-
-function UiComponent() {
- const [error, setError] = useState();
-
- return (
-
- );
-}
-```
-
-Note that this is a streaming chain therefore the response will stream plain text which will need parsing. Given the simplicity of the task the response could be parsed incrementally and consumed right away. Below is a proof of concept:
-
-```tsx
-import untruncateJson from "untruncate-json";
-import { copywriter } from "@webstudio-is/ai";
-
-// ...
-
-// within UiComponent
-
-const [json, setJson] = useState([]);
-
-useEffect(() => {
- try {
- const jsonResponse = z
- .array(copywriter.TextInstance)
- .parse(JSON.parse(untruncateJson(completion)));
-
- const currenTextInstance = jsonResponse.pop();
-
- if (currenTextInstance === undefined) {
- return;
- }
-
- console.clear();
- console.info(currenTextInstance);
- // patchTextInstance(currenTextInstance);
- } catch (error) {
- /**/
- }
-}, [completion]);
-```
diff --git a/packages/ai/src/chains/copywriter/__generated__/copy.system.prompt.ts b/packages/ai/src/chains/copywriter/__generated__/copy.system.prompt.ts
deleted file mode 100644
index 688d64f57af9..000000000000
--- a/packages/ai/src/chains/copywriter/__generated__/copy.system.prompt.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-export const prompt = `You are a copywriter AI and your task is to produce an array of copy completions for a web page section.
-
-The user will provide a list of copy snippets to edit and an edit request. You must fulfill the edit request ignoring the current text value if necessary.
-
-The copy must pop, be unique and in line with the user request, so do not generate generic lorem ipsum text nor use generic names. Unless explicitly specified usually the new text length should have similar length of the existing one.
-
-You will respond with the exact original input array of copy to complete replacing only the \`text\` property with the generated copy.
-
-Example list of copy to complete: [{instanceId:'abc',index:0,type:'Heading',text:''}]
-Example completion: [{instanceId:'abc',index:0,type:'Heading',text:'Make a Change'}]
-
-Start responses with [{
-`;
diff --git a/packages/ai/src/chains/copywriter/__generated__/copy.user.prompt.ts b/packages/ai/src/chains/copywriter/__generated__/copy.user.prompt.ts
deleted file mode 100644
index 6762405d254f..000000000000
--- a/packages/ai/src/chains/copywriter/__generated__/copy.user.prompt.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-export const prompt = `List of all the copy snippets to edit:
-
-\`\`\`
-{text_nodes}
-\`\`\`
-
-Edit request:
-
-\`\`\`
-{prompt}
-\`\`\`
-`;
diff --git a/packages/ai/src/chains/copywriter/chain.server.ts b/packages/ai/src/chains/copywriter/chain.server.ts
deleted file mode 100644
index 9983aea37675..000000000000
--- a/packages/ai/src/chains/copywriter/chain.server.ts
+++ /dev/null
@@ -1,141 +0,0 @@
-import { z } from "zod";
-import type { Instance, Instances } from "@webstudio-is/sdk";
-import type { Model as BaseModel, ModelMessage, Chain } from "../../types";
-import { formatPrompt } from "../../utils/format-prompt";
-import { prompt as promptSystemTemplate } from "./__generated__/copy.system.prompt";
-import { prompt as promptUserTemplate } from "./__generated__/copy.user.prompt";
-import { createErrorResponse } from "../../utils/create-error-response";
-import type { RemixStreamingTextResponse } from "../../utils/remix-streaming-text-response";
-import { type Context, name, TextInstance } from "./schema";
-
-/**
- * Copywriter chain.
- *
- * Given a description and an instance id,
- * this chain generates copy for the instance and all its descendant text nodes.
- */
-
-export { name };
-
-export const createChain = (): Chain<
- BaseModel,
- Context,
- RemixStreamingTextResponse
-> =>
- async function chain({ model, context }) {
- const { prompt, textInstances } = context;
-
- if (textInstances.length === 0) {
- const message = "No text nodes found for the instance";
- return {
- id: name,
- ...createErrorResponse({
- status: 404,
- error: "ai.copywriter.textNodesNotFound",
- message,
- debug: message,
- }),
- llmMessages: [],
- };
- }
-
- if (z.array(TextInstance).safeParse(textInstances).success === false) {
- const message = "Invalid nodes list";
- return {
- id: name,
- ...createErrorResponse({
- status: 404,
- error: `ai.${name}.parseError`,
- message,
- debug: message,
- }),
- llmMessages: [],
- };
- }
-
- const llmMessages: ModelMessage[] = [
- ["system", promptSystemTemplate],
- [
- "user",
- formatPrompt(
- {
- prompt,
- text_nodes: JSON.stringify(textInstances),
- },
- promptUserTemplate
- ),
- ],
- ];
-
- const messages = model.generateMessages(llmMessages);
-
- const response = await model.completionStream({
- id: name,
- messages,
- });
-
- return {
- ...response,
- llmMessages,
- };
- };
-
-export const collectTextInstances = ({
- instances,
- rootInstanceId,
- textComponents = new Set(["Heading", "Paragraph", "Text"]),
-}: {
- instances: Instances;
- rootInstanceId: Instance["id"];
- textComponents?: Set;
-}) => {
- const textInstances: TextInstance[] = [];
-
- const rootInstance = instances.get(rootInstanceId);
-
- if (rootInstance === undefined) {
- return textInstances;
- }
-
- const nodeType =
- rootInstance.component === "Heading" ||
- rootInstance.component === "Paragraph"
- ? rootInstance.component
- : "Text";
-
- // Instances can have a number of text child nodes without interleaving components.
- // When this is the case we treat the child nodes as a single text node,
- // otherwise the AI would generate children.length chunks of separate text.
- // To signal that a textInstance is "joint" we set the index to -1.
- if (rootInstance.children.every((child) => child.type === "text")) {
- textInstances.push({
- instanceId: rootInstanceId,
- index: -1,
- type: nodeType,
- text: rootInstance.children.map((child) => child.value).join(" "),
- });
- } else {
- rootInstance.children.forEach((child, index) => {
- if (child.type === "text") {
- if (textComponents.has(rootInstance.component)) {
- textInstances.push({
- instanceId: rootInstanceId,
- index,
- type: nodeType,
- text: child.value,
- });
- }
- } else if (child.type === "id") {
- textInstances.push(
- ...collectTextInstances({
- instances,
- rootInstanceId: child.value,
- textComponents,
- })
- );
- }
- });
- }
-
- return textInstances;
-};
diff --git a/packages/ai/src/chains/copywriter/copy.system.prompt.md b/packages/ai/src/chains/copywriter/copy.system.prompt.md
deleted file mode 100644
index 420a60b1bc86..000000000000
--- a/packages/ai/src/chains/copywriter/copy.system.prompt.md
+++ /dev/null
@@ -1,12 +0,0 @@
-You are a copywriter AI and your task is to produce an array of copy completions for a web page section.
-
-The user will provide a list of copy snippets to edit and an edit request. You must fulfill the edit request ignoring the current text value if necessary.
-
-The copy must pop, be unique and in line with the user request, so do not generate generic lorem ipsum text nor use generic names. Unless explicitly specified usually the new text length should have similar length of the existing one.
-
-You will respond with the exact original input array of copy to complete replacing only the `text` property with the generated copy.
-
-Example list of copy to complete: [{instanceId:'abc',index:0,type:'Heading',text:''}]
-Example completion: [{instanceId:'abc',index:0,type:'Heading',text:'Make a Change'}]
-
-Start responses with [{
diff --git a/packages/ai/src/chains/copywriter/copy.user.prompt.md b/packages/ai/src/chains/copywriter/copy.user.prompt.md
deleted file mode 100644
index c9144ad58a40..000000000000
--- a/packages/ai/src/chains/copywriter/copy.user.prompt.md
+++ /dev/null
@@ -1,11 +0,0 @@
-List of all the copy snippets to edit:
-
-```
-{text_nodes}
-```
-
-Edit request:
-
-```
-{prompt}
-```
diff --git a/packages/ai/src/chains/copywriter/schema.ts b/packages/ai/src/chains/copywriter/schema.ts
deleted file mode 100644
index 8cc829b6f285..000000000000
--- a/packages/ai/src/chains/copywriter/schema.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { z } from "zod";
-
-export const name = "copywriter";
-
-export const TextInstance = z.object({
- instanceId: z.string(),
- index: z.number(),
- type: z.union([
- z.literal("Heading"),
- z.literal("Paragraph"),
- z.literal("Text"),
- ]),
- text: z.string(),
-});
-
-export type TextInstance = z.infer;
-
-export const Context = z.object({
- // The prompt provides context about the copy to generate and comes from the user.
- prompt: z.string(),
- // An array of text nodes to generate copy for.
- textInstances: z.array(TextInstance),
-});
-export type Context = z.infer;
-
-export const Response = z.array(TextInstance);
-export type Response = z.infer;
diff --git a/packages/ai/src/chains/operations/README.md b/packages/ai/src/chains/operations/README.md
deleted file mode 100644
index c05382d4352b..000000000000
--- a/packages/ai/src/chains/operations/README.md
+++ /dev/null
@@ -1,149 +0,0 @@
-# Operations Chain
-
-Uses Streaming: `false`.
-
-Given a description, available components and an existing instance as JSX and CSS, it generates a series of edit operations to fulfill an edit request coming from the user.
-
-## Architecture
-
-At the core of this chain are a number of atomic operations that represent tasks that the LLM can do on an input Webstudio tree, converted to JSX and CSS.
-
-Each operation is a file containing:
-
-- `aiOperation`: an LLM-friendly operation schema to produce an operation to alter the input JSX and/or CSS.
-- `wsOperation`: a Webstudio-friendly operation to apply a LLM-result (postprocessed or not) to a Webstudio project.
-- `aiOperationToWs`: an utility to convert an `aiOperation` to a `wsOperation`.
-
-### aiOperation
-
-An aiOperation is a Zod schema definition for an object with a descriptive `operation` property that identifies the operation to do on the input JSX and CSS. The `operation` property is mandatory since it enables a discriminated union.
-
-Each operation can define additional properties that the LLM will fill out based on the user request and task. For example an aiOperation can include a property indicating which JSX element to modify.
-
-aiOperations are written in an LLM-friendly language and are located in the [operations](./operations) folder.
-
-#### Usage in the Operations chain
-
-The Operations chain from this module assumes that every JSX element has a Webstudio instance id in a `data-ws-id` attribute. The LLM will reference these ids to associate an operation with a particular element instance.
-
-The chain converts a Zod union of all the supported operations to a JSON Schema definition that is injected in the LLM prompt. Additionally the LLM will get the Webstudio tree as JSX and CSS and a user prompt, and will respond with an array of operations to alter the input JSX.
-
-Once the LLM responds with an array of aiOperations, these can be transformed to Webstudio-friendly operations with utilities called aiOperationToWs. The results of these transformations are called wsOperation.
-
-For example an aiOperation might contain style changes in the form of Tailwind CSS classes and the companion `aiOperationToWs` can turn them into Webstudio-compatible styles returining a wsOperation.
-
-Once all the wsOperations are ready they are sent to the client which has specific logic to apply each of these to the Webstudio project.
-
-##### Special Case for User Interfaces
-
-Generating quality user interfaces might be challenging with LLMs.
-
-Having to do so within a generic operations framework like the one described above makes it even more challenging.
-
-For this reason when it comes to generating user interfaces, the Operation chain instead offers an operation called [`generateTemplatePrompt`](./operations/generate-template-prompt.ts) that provides information about insertion point in the existing UI and a prompt, possibly enhanced.
-
-Another chain can use these information and a more sophisticated prompt and model to then generate the user interface and return a [`generateInsertTemplate`](./operations/generate-insert-template.ts) wsOperation. Webstudio does exactly this in a rest endpoint, using the [`template-generator`](../template-generator) chain with gpt4 instead of gpt-3.5-turbo.
-
-## Usage
-
-Server side:
-
-```typescript
-import {
- operations,
- templateGenerator,
- createGptModel
- type GptModelMessageFormat
-} from "@webstudio-is/ai";
-
-export async function handler({ request }) {
- const { prompt, components, jsx } = await request.json();
-
- const model = createGptModel({
- apiKey: process.env.OPENAI_KEY,
- organization: process.env.OPENAI_ORG,
- temperature: 0.2,
- model: "gpt-3.5-turbo",
- });
-
- const chain = operations.createChain();
-
- const response = await chain({
- model,
- context: {
- prompt,
- components,
- jsx
- }
- });
-
- if (response.success === false) {
- return response;
- }
-
- const promptOperations = getGenerateTemplatePromptsWsOperations(response.data);
-
- if (promptOperations.length > 0) {
- const model = createGptModel({
- apiKey: process.env.OPENAI_KEY,
- organization: process.env.OPENAI_ORG,
- temperature: 0.2,
- model: "gpt-4",
- });
- const chain = templateGenerator.createChain();
-
- const results = await Promise.all(promptOperations.map(operation => chain({
- model,
- context: {
- prompt: operation.llmPrompt,
- components,
- }
- }));
-
- replaceGenerateTemplateWithInsertTemplateWsOperations(
- promptOperations,
- results,
- response,
- );
- }
-
- return {
- success: true,
- data: response.data,
- };
-}
-```
-
-Client side:
-
-```tsx
-import {
- operations,
- handleAiRequest
-} from "@webstudio-is/ai";
-import { applyOperations } from "./apply-operations";
-
-const abortController = new AbortController();
-
-handleAiRequest(
- fetch(
- '/rest/ai/op',
- {
- method: 'POST',
- body: JSON.stringify({
- prompt,
- components: getAvailableComponentsFromWebstudioMetas(...),
- jsx: getJsxAndCssForSelectedInstance(...),
- }),
- signal: abortController.signal
- }
- ),
- {
- signal: abortController.signal
- }
-).then((result) => {
- if (result.success === true && result.id === operations.name) {
- applyOperations(result.data);
- }
-});
-```
diff --git a/packages/ai/src/chains/operations/__generated__/operations.system.prompt.ts b/packages/ai/src/chains/operations/__generated__/operations.system.prompt.ts
deleted file mode 100644
index 23235ca4615b..000000000000
--- a/packages/ai/src/chains/operations/__generated__/operations.system.prompt.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-export const prompt = `Given a JSX snippet and an edit request from the user, your task is to generate an array of edit operations to accomplish the requested task.
-
-The available operations are defined by the following JSON schema which you should follow strictly:
-
-\`\`\`json
-{operationsSchema}
-\`\`\`
-
-All the required schema properties must have values.
-
-Properties value contain descriptions with instructions on how to fill them out. When they do please keep those in mind when generating a completion.
-
-Respond with an array of operations as JSON and no other text. Start with [{"operation":
-
-Do not start your response with \`\`\`json
-`;
diff --git a/packages/ai/src/chains/operations/__generated__/operations.user.prompt.ts b/packages/ai/src/chains/operations/__generated__/operations.user.prompt.ts
deleted file mode 100644
index 91a2b59824c2..000000000000
--- a/packages/ai/src/chains/operations/__generated__/operations.user.prompt.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-export const prompt = `\`\`\`jsx{jsx}
-
-\`\`\`
-
-The request:
-
-\`\`\`
-{prompt}
-\`\`\`
-`;
diff --git a/packages/ai/src/chains/operations/chain.server.ts b/packages/ai/src/chains/operations/chain.server.ts
deleted file mode 100644
index d92f3e57447b..000000000000
--- a/packages/ai/src/chains/operations/chain.server.ts
+++ /dev/null
@@ -1,181 +0,0 @@
-import type { Model as BaseModel, ModelMessage, Chain } from "../../types";
-import { formatPrompt } from "../../utils/format-prompt";
-import { prompt as promptSystemTemplate } from "./__generated__/operations.system.prompt";
-import { prompt as promptUserTemplate } from "./__generated__/operations.user.prompt";
-import { zodToJsonSchema } from "zod-to-json-schema";
-import { postProcessTemplate } from "../../utils/jsx-to-template.server";
-import { createErrorResponse } from "../../utils/create-error-response";
-import {
- type WsOperations,
- AiOperations,
- name,
- OperationContext,
-} from "./schema";
-import * as editStyles from "./edit-styles.server";
-import * as generateTemplatePrompt from "./generate-template-prompt.server";
-// import * as generateInsertTemplate from "./generate-insert-template.server";
-import * as deleteInstance from "./delete-instance.server";
-
-export * as editStyles from "./edit-styles.server";
-export * as generateTemplatePrompt from "./generate-template-prompt.server";
-export * as generateInsertTemplate from "./generate-insert-template.server";
-export * as deleteInstance from "./delete-instance.server";
-
-/**
- * Operations Chain.
- *
- * Given a description, available components and an existing instance as JSX and CSS,
- * it generates a series of edit operations to fulfill an edit request coming from the user.
- */
-
-export { name };
-
-const aiToWs = (aiOperations: AiOperations) => {
- return aiOperations
- .map((aiOperation) => {
- if (aiOperation.operation === "editStylesWithTailwindCSS") {
- return editStyles.aiOperationToWs(aiOperation);
- }
- if (aiOperation.operation === "generateTemplatePrompt") {
- return generateTemplatePrompt.aiOperationToWs(aiOperation);
- }
- // if (aiOperation.operation === "generateInstanceWithTailwindStyles") {
- // return generateInsertTemplate.aiOperationToWs(aiOperation);
- // }
- if (aiOperation.operation === "deleteInstance") {
- return deleteInstance.aiOperationToWs(aiOperation);
- }
- })
- .filter(function (value: T): value is NonNullable {
- return value !== undefined;
- });
-};
-
-export const createChain = (): Chain<
- BaseModel,
- OperationContext,
- WsOperations
-> =>
- async function chain({ model, context }) {
- const { prompt, components, jsx } = context;
-
- // @todo Make it so this chain can run only for
- // a specific operation among the supported ones.
- // This could be passed as context.operations.
- const operationsSchema = zodToJsonSchema(
- AiOperations.element,
- "AiOperations"
- );
-
- const llmMessages: ModelMessage[] = [
- [
- "system",
- formatPrompt(
- {
- operationsSchema: JSON.stringify(operationsSchema),
- components: components.join(", "),
- },
- promptSystemTemplate
- ),
- ],
- [
- "user",
- formatPrompt(
- {
- prompt,
- jsx,
- },
- promptUserTemplate
- ),
- ],
- ];
-
- const messages = model.generateMessages(llmMessages);
-
- const completion = await model.completion({
- id: name,
- messages,
- });
-
- if (completion.success === false) {
- return {
- ...completion,
- llmMessages,
- };
- }
-
- const completionText = completion.data.choices[0];
- llmMessages.push(["assistant", completionText]);
-
- let parsedCompletion;
-
- try {
- parsedCompletion = AiOperations.safeParse(JSON.parse(completionText));
- } catch (error) {
- return {
- id: name,
- ...createErrorResponse({
- status: 500,
- error: "ai.parseError",
- message: `Failed to parse completion JSON ${error}`,
- debug: `Failed to parse completion JSON ${error}`,
- }),
- tokens: completion.tokens,
- llmMessages,
- } as const;
- }
-
- if (parsedCompletion.success === false) {
- return {
- id: name,
- ...createErrorResponse({
- status: 500,
- error: "ai.parseError",
- message: `Failed to parse completion ${parsedCompletion.error.message}`,
- debug: `Failed to parse completion ${parsedCompletion.error.message}`,
- }),
- tokens: completion.tokens,
- llmMessages,
- } as const;
- }
-
- const aiOperations = parsedCompletion.data;
-
- let wsOperations: WsOperations = [];
- try {
- wsOperations = await Promise.all(aiToWs(aiOperations));
-
- for (const wsOperation of wsOperations) {
- if (wsOperation.operation === "insertTemplate") {
- // Clean up template and ensure valid components in templates
- postProcessTemplate(wsOperation.template, components);
- }
- }
- } catch (error) {
- return {
- id: name,
- ...createErrorResponse({
- status: 500,
- error: "ai.parseError",
- message:
- error instanceof Error
- ? error.message
- : "Failed to parse the completion",
-
- debug: (
- "Failed to convert operations. " +
- (error instanceof Error ? error.message : "")
- ).trim(),
- tokens: completion.tokens,
- }),
- llmMessages,
- } as const;
- }
-
- const { data, ...response } = completion;
- return {
- ...response,
- data: wsOperations,
- llmMessages,
- };
- };
diff --git a/packages/ai/src/chains/operations/delete-instance.server.ts b/packages/ai/src/chains/operations/delete-instance.server.ts
deleted file mode 100644
index d00da3d68583..000000000000
--- a/packages/ai/src/chains/operations/delete-instance.server.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import type { aiOperation, wsOperation } from "./delete-instance";
-
-export { name } from "./delete-instance";
-
-export type { wsOperation };
-
-export const aiOperationToWs = async (
- operation: aiOperation
-): Promise => operation;
diff --git a/packages/ai/src/chains/operations/delete-instance.ts b/packages/ai/src/chains/operations/delete-instance.ts
deleted file mode 100644
index 2ea2f5a8f7dc..000000000000
--- a/packages/ai/src/chains/operations/delete-instance.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { z } from "zod";
-import { idAttribute } from "@webstudio-is/react-sdk";
-
-export const name = "delete-instance";
-
-const wsId = z.string().describe(`The element's ${idAttribute} to remove`);
-
-export const aiOperation = z.object({
- operation: z.literal("deleteInstance"),
- wsId,
-});
-export type aiOperation = z.infer;
-
-export const wsOperation = aiOperation;
-export type wsOperation = z.infer;
diff --git a/packages/ai/src/chains/operations/edit-styles.server.ts b/packages/ai/src/chains/operations/edit-styles.server.ts
deleted file mode 100644
index c717446e930b..000000000000
--- a/packages/ai/src/chains/operations/edit-styles.server.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { parseTailwindToWebstudio } from "@webstudio-is/css-data";
-import type { aiOperation, wsOperation } from "./edit-styles";
-
-export { name } from "./edit-styles";
-
-export type { wsOperation };
-
-export const aiOperationToWs = async (
- operation: aiOperation
-): Promise => {
- if (operation.className === "") {
- throw new Error(`Operation ${operation.operation} className is empty`);
- }
- const styles = await parseTailwindToWebstudio(operation.className);
- return {
- operation: "applyStyles",
- instanceIds: operation.wsIds,
- styles: styles,
- };
-};
diff --git a/packages/ai/src/chains/operations/edit-styles.ts b/packages/ai/src/chains/operations/edit-styles.ts
deleted file mode 100644
index bfff682454df..000000000000
--- a/packages/ai/src/chains/operations/edit-styles.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { z } from "zod";
-import { EmbedTemplateStyleDecl } from "@webstudio-is/sdk";
-import { idAttribute } from "@webstudio-is/react-sdk";
-
-export const name = "edit-styles";
-
-const wsId = z
- .string()
- .describe(`The ${idAttribute} value of the element being edited.`);
-
-export const aiOperation = z.object({
- operation: z.literal("editStylesWithTailwindCSS"),
- wsIds: z.array(wsId),
- className: z
- .string()
- .describe(
- "A list of Tailwind CSS classes to add or override existing styles. Always use the square brackets notation eg. mb-[10px] instead of mb-10"
- ),
-});
-export type aiOperation = z.infer;
-
-export const wsOperation = z.object({
- operation: z.literal("applyStyles"),
- instanceIds: z.array(wsId),
- styles: z.array(EmbedTemplateStyleDecl),
-});
-export type wsOperation = z.infer;
diff --git a/packages/ai/src/chains/operations/generate-insert-template.server.ts b/packages/ai/src/chains/operations/generate-insert-template.server.ts
deleted file mode 100644
index 7aed23b6809e..000000000000
--- a/packages/ai/src/chains/operations/generate-insert-template.server.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { jsxToTemplate } from "../../utils/jsx-to-template.server";
-import type { aiOperation, wsOperation } from "./generate-insert-template";
-
-export type { wsOperation };
-
-export const aiOperationToWs = async (
- operation: aiOperation
-): Promise => {
- return {
- operation: "insertTemplate",
- addTo: operation.addTo,
- addAtIndex: operation.addAtIndex,
- template: await jsxToTemplate(operation.jsx),
- };
-};
diff --git a/packages/ai/src/chains/operations/generate-insert-template.ts b/packages/ai/src/chains/operations/generate-insert-template.ts
deleted file mode 100644
index 4466bd7fb8a6..000000000000
--- a/packages/ai/src/chains/operations/generate-insert-template.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { z } from "zod";
-import { WsEmbedTemplate } from "@webstudio-is/sdk";
-import { idAttribute } from "@webstudio-is/react-sdk";
-
-// Currently this operation is used is a separate LLM call after the main one has returned an insert-instance operation. This is to produce better results.
-// Effectively the aiOperation from this module is not used. The separate chain will call the LLM and we use the resulting completion to construct an aiOperation by hand
-// and pass it to this file's aiOperationToWs, replacing the initial insert-instance operation.
-
-export const name = "generate-insert-template";
-
-const wsId = z
- .string()
- .describe(
- `The ${idAttribute} value of the host element. The result will be added to this element.`
- );
-
-export const aiOperation = z.object({
- operation: z
- .literal("generateInstanceWithTailwindStyles")
- .describe(
- "Using the provided components, it generates a high-end beautiful UI as JSX. Eg Hi The JSX to insert. Every JSX element must be styled with Tailwind CSS. For icons use the Heroicon component setting a name prop and a type one that can be solid or outline. For images set an alt text for screen readers, width and height props but omit the src prop. Exclusively use the following components: ```{components}```"
- ),
- addTo: wsId,
- addAtIndex: z
- .number()
- .describe("The index at which the new instance must be inserted"),
- jsx: z.string().describe(`The generated JSX`),
-});
-export type aiOperation = z.infer;
-
-export const wsOperation = z.object({
- operation: z.literal("insertTemplate"),
- addTo: wsId,
- addAtIndex: z.number(),
- template: WsEmbedTemplate,
-});
-export type wsOperation = z.infer;
diff --git a/packages/ai/src/chains/operations/generate-template-prompt.server.ts b/packages/ai/src/chains/operations/generate-template-prompt.server.ts
deleted file mode 100644
index 31c5714cd77c..000000000000
--- a/packages/ai/src/chains/operations/generate-template-prompt.server.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import type { aiOperation, wsOperation } from "./generate-template-prompt";
-
-export { name } from "./generate-template-prompt";
-
-export type { wsOperation };
-
-export const aiOperationToWs = async (
- operation: aiOperation
-): Promise => operation;
diff --git a/packages/ai/src/chains/operations/generate-template-prompt.ts b/packages/ai/src/chains/operations/generate-template-prompt.ts
deleted file mode 100644
index b8a81e142606..000000000000
--- a/packages/ai/src/chains/operations/generate-template-prompt.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { z } from "zod";
-import { idAttribute } from "@webstudio-is/react-sdk";
-
-// Currently this operation is used to prepare a context for the insert-template operations.
-// insert-template is processed as a regular chain in a separate LLM call. This is to produce better results.
-
-export const name = "generate-template-prompt";
-
-const wsId = z
- .string()
- .describe(
- `The ${idAttribute} value of the host element. The result will be added to this element.`
- );
-
-export const aiOperation = z.object({
- operation: z
- .literal("generateTemplatePrompt")
- .describe(
- "Provides instructions to LLM on how to generate new user interface elements and where to insert them"
- ),
- addTo: wsId,
- addAtIndex: z
- .number()
- .describe("The index at which the new instance must be inserted"),
- llmPrompt: z
- .string()
- .describe(
- `Enhanced user prompt from this chat. The description will be passed to another LLM to generate a user interface with JSX.`
- ),
- classNames: z
- .string()
- .optional()
- .describe(
- "A list of suggested Tailwind CSS classes matching the style of the request code. Always use the square brackets notation eg. mb-[10px] instead of mb-10"
- ),
-});
-export type aiOperation = z.infer;
-
-export const wsOperation = aiOperation;
-export type wsOperation = z.infer;
diff --git a/packages/ai/src/chains/operations/operations.system.prompt.md b/packages/ai/src/chains/operations/operations.system.prompt.md
deleted file mode 100644
index b6e429154b52..000000000000
--- a/packages/ai/src/chains/operations/operations.system.prompt.md
+++ /dev/null
@@ -1,15 +0,0 @@
-Given a JSX snippet and an edit request from the user, your task is to generate an array of edit operations to accomplish the requested task.
-
-The available operations are defined by the following JSON schema which you should follow strictly:
-
-```json
-{operationsSchema}
-```
-
-All the required schema properties must have values.
-
-Properties value contain descriptions with instructions on how to fill them out. When they do please keep those in mind when generating a completion.
-
-Respond with an array of operations as JSON and no other text. Start with [{"operation":
-
-Do not start your response with ```json
diff --git a/packages/ai/src/chains/operations/operations.user.prompt.md b/packages/ai/src/chains/operations/operations.user.prompt.md
deleted file mode 100644
index cc740b5e9adf..000000000000
--- a/packages/ai/src/chains/operations/operations.user.prompt.md
+++ /dev/null
@@ -1,9 +0,0 @@
-```jsx{jsx}
-
-```
-
-The request:
-
-```
-{prompt}
-```
diff --git a/packages/ai/src/chains/operations/schema.ts b/packages/ai/src/chains/operations/schema.ts
deleted file mode 100644
index 830cfa1b1956..000000000000
--- a/packages/ai/src/chains/operations/schema.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-import { z } from "zod";
-import * as editStyles from "./edit-styles";
-import * as generateTemplatePrompt from "./generate-template-prompt";
-import * as generateInsertTemplate from "./generate-insert-template";
-import * as deleteInstance from "./delete-instance";
-
-export {
- name as editStylesName,
- aiOperation as editStylesAiOperation,
- wsOperation as editStylesWsOperation,
-} from "./edit-styles";
-
-export {
- name as generateTemplatePromptName,
- aiOperation as generateTemplatePromptAiOperation,
- wsOperation as generateTemplatePromptWsOperation,
-} from "./generate-template-prompt";
-
-export {
- name as generateInsertTemplateName,
- aiOperation as generateInsertTemplateAiOperation,
- wsOperation as generateInsertTemplateWsOperation,
-} from "./generate-insert-template";
-
-export {
- name as deleteInstanceName,
- aiOperation as deleteInstanceAiOperation,
- wsOperation as deleteInstanceWsOperation,
-} from "./delete-instance";
-
-export const name = "operations";
-
-export const OperationContext = z.object({
- prompt: z.string().describe("Edit request from the user"),
- components: z.array(z.string()).describe("Available Webstudio components"),
- jsx: z.string().describe("Input JSX to edit"),
-});
-export type OperationContext = z.infer;
-
-// AiOperations are supported LLM operations.
-// A valid completion is then converted to WsOperations
-// which is the final format that we send to the client.
-
-export const AiOperations = z.array(
- z.discriminatedUnion("operation", [
- editStyles.aiOperation,
- generateTemplatePrompt.aiOperation,
- // Currently disable generateInsertTemplate operations
- // this is because with the current "operations" chain prompt the LLM produces poor quality results.
- // Instead we let the LLM enhance the user prompt producing generateTemplatePrompt operations.
- // Later on we can manually process these and call another better fitting chain to generate the user interface
- // and replace generateTemplatePrompt wsOperations with generateInsertTemplate wsOperations.
- //
- // generateInsertTemplate.aiOperation,
- deleteInstance.aiOperation,
- ])
-);
-export type AiOperations = z.infer;
-
-export const WsOperations = z.array(
- z.discriminatedUnion("operation", [
- editStyles.wsOperation,
- generateTemplatePrompt.wsOperation,
- generateInsertTemplate.wsOperation,
- deleteInstance.wsOperation,
- ])
-);
-export type WsOperations = z.infer;
diff --git a/packages/ai/src/chains/template-generator/README.md b/packages/ai/src/chains/template-generator/README.md
deleted file mode 100644
index 47ca721fbe1c..000000000000
--- a/packages/ai/src/chains/template-generator/README.md
+++ /dev/null
@@ -1,100 +0,0 @@
-# Template Generator Chain
-
-Uses Streaming: `false`.
-
-Given a UI section or widget description, this chain generates a Webstudio Embed Template representing the UI.
-
-## Usage
-
-Server side:
-
-```typescript
-import {
- templateGenerator,
- createGptModel
- type GptModelMessageFormat
-} from "@webstudio-is/ai";
-
-export async function handler({ request }) {
- const { prompt, components } = await request.json();
-
- const model = createGptModel({
- apiKey: process.env.OPENAI_KEY,
- organization: process.env.OPENAI_ORG,
- temperature: 0.5,
- model: "gpt-3.5-turbo",
- });
-
- const chain = templateGenerator.createChain();
-
- const response = await chain({
- model,
- context: {
- prompt,
- components, // This is an array of available component names.
- }
- });
-
- // response.data contains the template
-
- return response;
-}
-```
-
-Client side:
-
-```tsx
-import { templateGenerator, handleAiRequest } from "@webstudio-is/ai";
-
-function UiComponent() {
- const [error, setError] = useState();
-
- return (
-
- );
-}
-```
diff --git a/packages/ai/src/chains/template-generator/__generated__/template-generator.system.prompt.ts b/packages/ai/src/chains/template-generator/__generated__/template-generator.system.prompt.ts
deleted file mode 100644
index a1feaa07e75b..000000000000
--- a/packages/ai/src/chains/template-generator/__generated__/template-generator.system.prompt.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-export const prompt = `You are a design system engineer and your task is to generate a JSX tree for a design request coming from a client.
-
-The user will provide a description of the design request and you will generate the JSX using the design system components below and Tailwind CSS classes for styling.
-
-The resulting JSX must represent a high-end, polished and detailed user interface. Meticulosly style every element and ensure proper layout, spacing. Add interesting touches like round corners and shadows. Use the Tailwind CSS palette. Unless otherwise asked by the user, use a black and white colors and light mode.
-
-Exclusively use components below and absolutely no other JSX element:
-
-\`\`\`
-{components},Heroicon
-\`\`\`
-
-Follow the rules below:
-
-- Don't import or use any dependency or external library
-- Pick the appropriate components including advanced ones in the list if necessary. For example if the user asks for a dropdown and you find a fitting component in the design system use that instead of generic basic one like box image text etc
-- Don't use components that are not in the list above. For example if a \`div\` is not in the list then you cannot use to generate a completion
-- Don't use JSX Fragments
-- Don't use JSX comments
-- Don't use CSS grid for layout, use flexbox instead
-- Only use valid Tailwind CSS classes. Always use the square brackets notation eg. mb-[10px] instead of mb-10
-- Don't add round corners and shadow to top-level containers
-- Don't add any props to components
-- For images leave the \`src\` prop empty and add a good on-topic description as \`alt\` attribute for screen readers. Additionally set a \`width\` and \`height\` props for the image size
-- For icons use the Heroicons via the \`Heroicon\` component which takes a valid icon \`name\` and icon \`type\` as prop. The type can be solid or outline.
-- Titles and subtitles should pop and be interesting, bold and very creative
-- Don't use lorem ipsum placeholder text. Instead craft short text that is creative and exciting and fits the client request
-- Don't use placeholder names like Jon or Jane Doe but rather invent random ones
-
-Don't use markdown and respond only with a valid JSX string. Start with <
-`;
diff --git a/packages/ai/src/chains/template-generator/__generated__/template-generator.user.prompt.ts b/packages/ai/src/chains/template-generator/__generated__/template-generator.user.prompt.ts
deleted file mode 100644
index b287abc3e005..000000000000
--- a/packages/ai/src/chains/template-generator/__generated__/template-generator.user.prompt.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-export const prompt = `Design request:
-
-\`\`\`
-{prompt}
-\`\`\`
-`;
diff --git a/packages/ai/src/chains/template-generator/chain.server.ts b/packages/ai/src/chains/template-generator/chain.server.ts
deleted file mode 100644
index 7c94a2f47afd..000000000000
--- a/packages/ai/src/chains/template-generator/chain.server.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-import type { Model as BaseModel, ModelMessage, Chain } from "../../types";
-import { formatPrompt } from "../../utils/format-prompt";
-import { prompt as promptSystemTemplate } from "./__generated__/template-generator.system.prompt";
-import { prompt as promptUserTemplate } from "./__generated__/template-generator.user.prompt";
-import { WsEmbedTemplate } from "@webstudio-is/sdk";
-import {
- jsxToTemplate,
- postProcessTemplate,
-} from "../../utils/jsx-to-template.server";
-import { createErrorResponse } from "../../utils/create-error-response";
-import { getCode } from "../../utils/get-code";
-import { type Context, type Response, name } from "./schema";
-
-/**
- * Template Generator Chain.
- *
- * Given a UI section or widget description, this chain generates a Webstudio Embed Template representing the UI.
- */
-
-export { name };
-
-export const createChain = (): Chain<
- BaseModel,
- Context,
- Response
-> =>
- async function chain({ model, context }) {
- const { prompt, components } = context;
-
- const llmMessages: ModelMessage[] = [
- [
- "system",
- formatPrompt(
- {
- components: components.join(", "),
- },
- promptSystemTemplate
- ),
- ],
- ["user", formatPrompt({ prompt }, promptUserTemplate)],
- ];
-
- const messages = model.generateMessages(llmMessages);
-
- const completion = await model.completion({
- id: name,
- messages,
- });
-
- if (completion.success === false) {
- return {
- ...completion,
- llmMessages,
- };
- }
-
- const completionText = completion.data.choices[0];
- llmMessages.push(["assistant", completionText]);
-
- let template: WsEmbedTemplate;
-
- try {
- template = await jsxToTemplate(getCode(completionText, "jsx"));
- } catch (error) {
- const debug = `Failed to parse the completion error="${
- error instanceof Error ? error.message : ""
- }" completionText="${completionText}"`.trim();
- return {
- id: name,
- ...createErrorResponse({
- status: 500,
- message: debug,
- debug,
- }),
- llmMessages,
- };
- }
-
- try {
- postProcessTemplate(template, components);
- } catch (error) {
- const debug = (
- "Invalid completion " + (error instanceof Error ? error.message : "")
- ).trim();
-
- return {
- id: name,
- ...createErrorResponse({
- status: 500,
- message: debug,
- debug,
- }),
- llmMessages,
- };
- }
-
- return {
- ...completion,
- data: template,
- llmMessages,
- };
- };
diff --git a/packages/ai/src/chains/template-generator/schema.ts b/packages/ai/src/chains/template-generator/schema.ts
deleted file mode 100644
index 4b740b946055..000000000000
--- a/packages/ai/src/chains/template-generator/schema.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { z } from "zod";
-import { WsEmbedTemplate } from "@webstudio-is/sdk";
-
-export const name = "template-generator";
-
-export const Context = z.object({
- // The prompt provides the original user request.
- prompt: z.string(),
- components: z.array(z.string()),
-});
-export type Context = z.infer;
-
-export const Response = WsEmbedTemplate;
-export type Response = z.infer;
diff --git a/packages/ai/src/chains/template-generator/template-generator.system.prompt.md b/packages/ai/src/chains/template-generator/template-generator.system.prompt.md
deleted file mode 100644
index 15285cde89a7..000000000000
--- a/packages/ai/src/chains/template-generator/template-generator.system.prompt.md
+++ /dev/null
@@ -1,30 +0,0 @@
-You are a design system engineer and your task is to generate a JSX tree for a design request coming from a client.
-
-The user will provide a description of the design request and you will generate the JSX using the design system components below and Tailwind CSS classes for styling.
-
-The resulting JSX must represent a high-end, polished and detailed user interface. Meticulosly style every element and ensure proper layout, spacing. Add interesting touches like round corners and shadows. Use the Tailwind CSS palette. Unless otherwise asked by the user, use a black and white colors and light mode.
-
-Exclusively use components below and absolutely no other JSX element:
-
-```
-{components},Heroicon
-```
-
-Follow the rules below:
-
-- Don't import or use any dependency or external library
-- Pick the appropriate components including advanced ones in the list if necessary. For example if the user asks for a dropdown and you find a fitting component in the design system use that instead of generic basic one like box image text etc
-- Don't use components that are not in the list above. For example if a `div` is not in the list then you cannot use to generate a completion
-- Don't use JSX Fragments
-- Don't use JSX comments
-- Don't use CSS grid for layout, use flexbox instead
-- Only use valid Tailwind CSS classes. Always use the square brackets notation eg. mb-[10px] instead of mb-10
-- Don't add round corners and shadow to top-level containers
-- Don't add any props to components
-- For images leave the `src` prop empty and add a good on-topic description as `alt` attribute for screen readers. Additionally set a `width` and `height` props for the image size
-- For icons use the Heroicons via the `Heroicon` component which takes a valid icon `name` and icon `type` as prop. The type can be solid or outline.
-- Titles and subtitles should pop and be interesting, bold and very creative
-- Don't use lorem ipsum placeholder text. Instead craft short text that is creative and exciting and fits the client request
-- Don't use placeholder names like Jon or Jane Doe but rather invent random ones
-
-Don't use markdown and respond only with a valid JSX string. Start with <
diff --git a/packages/ai/src/chains/template-generator/template-generator.user.prompt.md b/packages/ai/src/chains/template-generator/template-generator.user.prompt.md
deleted file mode 100644
index c4c9359ae897..000000000000
--- a/packages/ai/src/chains/template-generator/template-generator.user.prompt.md
+++ /dev/null
@@ -1,5 +0,0 @@
-Design request:
-
-```
-{prompt}
-```
diff --git a/packages/ai/src/image.ts b/packages/ai/src/image.ts
deleted file mode 100644
index 12236dab65d9..000000000000
--- a/packages/ai/src/image.ts
+++ /dev/null
@@ -1,177 +0,0 @@
-import type {
- EmbedTemplateInstance,
- EmbedTemplateProp,
- WsEmbedTemplate,
-} from "@webstudio-is/sdk";
-
-const isRemoteImageGeneratedByAi = (url: string) => {
- // wsai search param is added when image is queried by ai
- // and allows to distinct image urls added by user manually
- try {
- return new URL(url).searchParams.get("wsai") === "true";
- } catch {
- return false;
- }
-};
-
-const canAiRegenerateImage = (src: undefined | EmbedTemplateProp) => {
- // asset images should not be regenerated
- if (src && src?.type !== "string") {
- return false;
- }
- // regenerate when image is not specified
- if (src === undefined || src.value.trim() === "") {
- return true;
- }
- return isRemoteImageGeneratedByAi(src.value);
-};
-
-type PexelsPhotoResource = {
- id: number;
- width: number;
- height: number;
- url: string;
- photographer: string;
- photographer_url: string;
- photographer_id: number;
- avg_color: string;
- src: {
- original: string;
- large2x: string;
- large: string;
- medium: string;
- small: string;
- portrait: string;
- landscape: string;
- tiny: string;
- };
- liked: boolean;
- alt: string;
-};
-
-type PexelsSearchResponse = {
- photos: PexelsPhotoResource[];
- page: number;
- per_page: number;
- total_results: number;
- next_page?: string;
- prev_page?: string;
-};
-
-const searchImageInPexels = async ({
- query,
- apiKey,
-}: {
- query: string;
- apiKey: string;
-}) => {
- const url = new URL("https://api.pexels.com/v1/search");
- url.searchParams.set("query", query);
- url.searchParams.set("per_page", "1");
- const response = await fetch(url, {
- headers: {
- Authorization: apiKey,
- },
- });
- const result: PexelsSearchResponse = await response.json();
- return result;
-};
-
-const queryImageAndMutateInstance = async (
- apiKey: string,
- instance: EmbedTemplateInstance
-) => {
- if (instance.props === undefined) {
- return;
- }
- const alt = instance.props.find((prop) => prop.name === "alt");
- if (alt?.type !== "string") {
- return;
- }
- const imageSearchResult = await searchImageInPexels({
- query: alt.value,
- apiKey,
- });
- const [result] = imageSearchResult.photos;
- const url = new URL(result.src.original);
- // mark remote image as generated by ai
- url.searchParams.set("wsai", "true");
- const newSrc: EmbedTemplateProp = {
- name: "src",
- type: "string",
- value: url.href,
- };
- // @todo simplify with props and styles object format
- const srcIndex = instance.props.findIndex((prop) => prop.name === "src");
- if (srcIndex === -1) {
- instance.props.push(newSrc);
- } else {
- instance.props[srcIndex] = newSrc;
- }
- const title: EmbedTemplateProp = {
- name: "title",
- type: "string",
- value: `Credit: ${result.photographer}`,
- };
- const titleIndex = instance.props.findIndex((prop) => prop.name === "title");
- if (titleIndex === -1) {
- instance.props.push(title);
- } else {
- instance.props[titleIndex] = title;
- }
- // prevent image deformation when ai specifies image size
- const hasObjectFit = instance.styles?.some(
- (styleDecl) => styleDecl.property === "objectFit"
- );
- if (hasObjectFit === false) {
- instance.styles = instance.styles ?? [];
- instance.styles.push({
- property: "objectFit",
- value: { type: "keyword", value: "cover" },
- });
- }
-};
-
-const traverseTemplate = (
- template: WsEmbedTemplate,
- fn: (node: WsEmbedTemplate[number]) => void
-) => {
- for (const node of template) {
- fn(node);
- if (node.type === "instance") {
- traverseTemplate(node.children, fn);
- }
- }
-};
-
-export const queryImagesAndMutateTemplate = async ({
- template,
- apiKey,
-}: {
- template: WsEmbedTemplate;
- apiKey: string;
-}) => {
- const imageInstances = new Set();
- traverseTemplate(template, (instance) => {
- if (instance.type === "instance" && instance.component === "Image") {
- if (instance.props === undefined) {
- return;
- }
- const src = instance.props.find((prop) => prop.name === "src");
- const alt = instance.props.find((prop) => prop.name === "alt");
- if (
- canAiRegenerateImage(src) === false ||
- // skip when no alt to generate image from
- alt?.type !== "string"
- ) {
- return;
- }
- imageInstances.add(instance);
- }
- });
- await Promise.allSettled(
- Array.from(imageInstances).map((instance) =>
- queryImageAndMutateInstance(apiKey, instance)
- )
- );
-};
diff --git a/packages/ai/src/index.server.ts b/packages/ai/src/index.server.ts
deleted file mode 100644
index 6f484fa1a0e8..000000000000
--- a/packages/ai/src/index.server.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-/** Chains */
-export * as commandDetect from "./chains/command-detect/chain.server";
-export * as copywriter from "./chains/copywriter/chain.server";
-export * as operations from "./chains/operations/chain.server";
-export * as templateGenerator from "./chains/template-generator/chain.server";
-
-/** Models */
-export {
- create as createGptModel,
- type Model as GptModel,
- type ModelConfig as GptModelConfig,
- type ModelMessageFormat as GptModelMessageFormat,
-} from "./models/gpt";
-
-/** Utils */
-export * from "./utils/handle-ai-request";
-export * from "./utils/create-error-response";
-export * from "./utils/remix-streaming-text-response";
-
-/** Types */
-export * from "./types";
diff --git a/packages/ai/src/index.ts b/packages/ai/src/index.ts
deleted file mode 100644
index 3105f5f93200..000000000000
--- a/packages/ai/src/index.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-/** Chains */
-export * as commandDetect from "./chains/command-detect/schema";
-export * as copywriter from "./chains/copywriter/schema";
-export * as operations from "./chains/operations/schema";
-export * as templateGenerator from "./chains/template-generator/schema";
-
-/** Utils */
-export * from "./utils/handle-ai-request";
-export * from "./utils/create-error-response";
-export * from "./utils/remix-streaming-text-response";
-
-/** Types */
-export * from "./types";
-
-export * from "./image";
diff --git a/packages/ai/src/models/README.md b/packages/ai/src/models/README.md
deleted file mode 100644
index 11168a85a0eb..000000000000
--- a/packages/ai/src/models/README.md
+++ /dev/null
@@ -1,20 +0,0 @@
-# Models
-
-The Webstudio AI package contemplates a generic, vendor-agnostic messages format and LLM client.
-
-Each vendor (eg. OpenAI) implementation follows the same API and is passed to [chains](../chains) which can use them to interact with a model. This allows to swap LLM without having to modify the chain(s).
-
-```tsx
-export type Model = {
- // Turns ModelMessages into a model-specific messages format.
- generateMessages: ModelGenerateMessages;
- // JSON completion.
- completion: ModelCompletion;
- // Streaming completion.
- completionStream: ModelCompletionStream;
-};
-```
-
-Currently the package offers an implementation that allows to use OpenAI's Chat Completion endpoint.
-
-Please refer to the [type definitions](../types.ts) for the baseline vendor-agnostic format and the [OpenAI implementation](./gpt.ts) in this folder for an example.
diff --git a/packages/ai/src/models/gpt.ts b/packages/ai/src/models/gpt.ts
deleted file mode 100644
index 15e11a341e7e..000000000000
--- a/packages/ai/src/models/gpt.ts
+++ /dev/null
@@ -1,165 +0,0 @@
-import OpenAI from "openai";
-import { OpenAIStream } from "ai";
-import type {
- Model as BaseModel,
- ModelCompletion,
- ModelCompletionStream,
- ModelGenerateMessages,
-} from "../types";
-import { createErrorResponse } from "../utils/create-error-response";
-import { RemixStreamingTextResponse } from "../utils/remix-streaming-text-response";
-
-export type Model = BaseModel;
-export type ModelMessageFormat = OpenAI.Chat.Completions.ChatCompletionMessage;
-
-export type ModelConfig = {
- apiKey: string;
- organization: string;
- temperature: number;
- model?: "gpt-3.5-turbo" | "gpt-3.5-turbo-16k" | "gpt-4" | "gpt-4-32k";
- endpoint?: string;
-};
-
-export const create = function createModel(config: ModelConfig): Model {
- return {
- generateMessages,
- completion: createCompletion(config),
- completionStream: createCompletionStream(config),
- };
-};
-
-export const generateMessages: ModelGenerateMessages = (
- messages
-) => {
- return messages.map(([role, content]) => ({ role, content }));
-};
-
-export const createCompletion = (
- config: ModelConfig
-): ModelCompletion =>
- async function completion({
- id,
- messages,
- }: {
- id: string;
- messages: ModelMessageFormat[];
- }) {
- try {
- const openai = new OpenAI({
- apiKey: config.apiKey,
- organization: config.organization,
- });
-
- const completion = await openai.chat.completions.create({
- model: config.model ?? "gpt-3.5-turbo",
- temperature: config.temperature,
- messages,
- });
-
- return {
- id,
- type: "json",
- success: true,
- tokens: {
- prompt: completion.usage?.prompt_tokens || 0,
- completion: completion.usage?.completion_tokens || 0,
- },
- data: {
- choices: completion.choices.map(
- (choice) => choice?.message?.content || ""
- ),
- },
- } as const;
- } catch (error) {
- return errorToResponse(id, error);
- }
- };
-
-export const createCompletionStream = (
- config: ModelConfig
-): ModelCompletionStream =>
- async function completeStream({
- id,
- messages,
- }: {
- id: string;
- messages: ModelMessageFormat[];
- }) {
- try {
- const openai = new OpenAI({
- apiKey: config.apiKey,
- organization: config.organization,
- });
-
- const response = await openai.chat.completions.create({
- stream: true,
- model: config.model ?? "gpt-3.5-turbo",
- temperature: config.temperature,
- messages,
- });
-
- const stream = OpenAIStream(response);
- return {
- id,
- type: "stream",
- success: true,
- data: new RemixStreamingTextResponse(stream),
- tokens: {
- prompt: -1,
- completion: -1,
- },
- } as const;
- } catch (error) {
- return errorToResponse(id, error);
- }
- };
-
-const errorToResponse = (id: string, error: unknown) => {
- let status = 500;
- let debug =
- error != null &&
- typeof error === "object" &&
- "message" in error &&
- typeof error.message === "string"
- ? error.message
- : "";
-
- if (error instanceof OpenAI.APIError) {
- if (typeof error.status === "number") {
- status = error.status;
- }
- debug += `\n ${error.message}`;
- }
-
- return {
- id,
- ...createErrorResponse({
- status,
- error: getErrorType(error, status),
- message: debug,
- debug,
- }),
- } as const;
-};
-const getErrorType = (error: unknown, status: number) => {
- if (error instanceof OpenAI.APIError) {
- if (error.code && error.code in errorCodes) {
- return `ai.${errorCodes[error.code as keyof typeof errorCodes]}`;
- }
- if (status in errorHttpCodes) {
- return `ai.${errorHttpCodes[status as keyof typeof errorHttpCodes]}`;
- }
- }
- return `ai.unknownError`;
-};
-
-const errorCodes = {
- context_length_exceeded: "contextLengthExceeded",
- rate_limit_exceeded: "rateLimitExceeded",
- insufficient_quota: "spendingQuotaLimitReached",
-};
-
-const errorHttpCodes = {
- 401: "invalidAuthOrApiKey",
- 503: "engineOverloaded",
-};
diff --git a/packages/ai/src/models/index.ts b/packages/ai/src/models/index.ts
deleted file mode 100644
index f2a81094d8bb..000000000000
--- a/packages/ai/src/models/index.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-export {
- create as createGptModel,
- type Model as GptModel,
- type ModelConfig as GptModelConfig,
- type ModelMessageFormat as GptModelMessageFormat,
-} from "./gpt";
diff --git a/packages/ai/src/types.ts b/packages/ai/src/types.ts
deleted file mode 100644
index f447f8478404..000000000000
--- a/packages/ai/src/types.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-import { type RemixStreamingTextResponse } from "./utils/remix-streaming-text-response";
-
-/**
- * Generic Response types used both by Models and Chains.
- */
-
-// @todo Convert the response types to Zod
-// so that responses can be parsed and validated on the client.
-
-export type Tokens = {
- prompt: number;
- completion: number;
-};
-
-export type SuccessResponse = {
- type: ResponseData extends RemixStreamingTextResponse ? "stream" : "json";
- success: true;
- tokens: Tokens;
- data: ResponseData;
-};
-
-export type ErrorResponse = {
- type: "json";
- success: false;
- tokens: Tokens;
- data: {
- status: number;
- error: string;
- message: string;
- debug?: string;
- };
-};
-
-type Response = {
- id: string;
-} & (SuccessResponse | ErrorResponse);
-
-/**
- * Models types.
- *
- * Types for a generic vendor-agnostic LLM client.
- * Each vendor (eg. OpenAI) implementation must follow these types.
- */
-
-export type ModelMessage = ["system" | "user" | "assistant", string];
-
-export type Model = {
- // Turns ModelMessages into a model-specific messages format.
- generateMessages: ModelGenerateMessages;
- completion: ModelCompletion;
- completionStream: ModelCompletionStream;
-};
-
-export type ModelGenerateMessages = (
- messages: ModelMessage[]
-) => ModelMessageFormat[];
-
-export type ModelCompletion = (args: {
- id: string;
- messages: ReturnType>;
-}) => Promise>;
-
-export type ModelCompletionStream = (args: {
- id: string;
- messages: ReturnType>;
-}) => Promise>;
-
-/**
- * Chains types.
- *
- * A chain an async function that executes an arbitrarty number of steps, including calling a LLM.
- * Chain files are modules that export a createChain factory.
- * Each instance generated by the factory gets a reference to a model client (types below)
- * and a context object which includes input data such as prompt and other relevant methods for the chain.
- *
- * Additionally each chain should export types for Context and Response data (using these names) both as zod and TypeScript types.
- * zod types must have a Schema suffix. For example Response.
- */
-
-export type ModelResponse = Response & {
- llmMessages: ModelMessage[];
-};
-
-export type Chain = (args: {
- model: Model;
- context: Context;
-}) => Promise>;
diff --git a/packages/ai/src/utils/create-error-response.ts b/packages/ai/src/utils/create-error-response.ts
deleted file mode 100644
index 34ab9960efb3..000000000000
--- a/packages/ai/src/utils/create-error-response.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import type { ErrorResponse, Tokens } from "../types";
-
-export const createErrorResponse = ({
- status,
- error,
- message,
- debug,
- tokens,
-}: {
- status?: number;
- error?: string;
- message: string;
- debug?: string;
- tokens?: Tokens;
-}): ErrorResponse => ({
- type: "json",
- success: false,
- tokens: tokens || {
- prompt: -1,
- completion: -1,
- },
- data: {
- status: status || 500,
- error: error || "ai.unknownError",
- message: message || "Something went wrong",
- debug: debug || undefined,
- },
-});
diff --git a/packages/ai/src/utils/format-prompt.ts b/packages/ai/src/utils/format-prompt.ts
deleted file mode 100644
index 8bff6684de2e..000000000000
--- a/packages/ai/src/utils/format-prompt.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import escapeStringRegexp from "escape-string-regexp";
-
-// If necessary replace with utility with an actual templating library.
-export const formatPrompt = function getMessage(
- replacements: Record,
- template: string
-) {
- let message = template;
- Object.entries(replacements).forEach(([key, value]) => {
- if (typeof value === "string") {
- message = message.replace(
- new RegExp(`{${escapeStringRegexp(key)}}`, "g"),
- value.replace(/`/g, "\\`")
- );
- }
- });
- return message;
-};
diff --git a/packages/ai/src/utils/get-code.ts b/packages/ai/src/utils/get-code.ts
deleted file mode 100644
index 4262f459fb08..000000000000
--- a/packages/ai/src/utils/get-code.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { fromMarkdown as parseMarkdown } from "mdast-util-from-markdown";
-import { visitParents } from "unist-util-visit-parents";
-
-export const getCode = function getCode(text: string, lang: string) {
- const tree = parseMarkdown(text);
- let code = text;
- const codeBlocks: string[] = [];
-
- visitParents(tree, "code", (node) => {
- if (node.lang === lang) {
- codeBlocks.unshift(node.value.trim());
- } else if (!node.lang) {
- codeBlocks.push(node.value.trim());
- }
- });
-
- if (codeBlocks.length > 0) {
- code = codeBlocks[0];
- }
-
- return code;
-};
diff --git a/packages/ai/src/utils/handle-ai-request.ts b/packages/ai/src/utils/handle-ai-request.ts
deleted file mode 100644
index afebeec9dd2a..000000000000
--- a/packages/ai/src/utils/handle-ai-request.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import { createChunkDecoder } from "ai";
-import type { ModelResponse } from "../types";
-import { RemixStreamingTextResponse } from "./remix-streaming-text-response";
-
-type RequestOptions = {
- onChunk?: (
- operationId: string,
- data: {
- completion: string;
- chunk: Uint8Array | undefined;
- decodedChunk: string;
- done: boolean;
- }
- ) => void;
- onResponseReceived: (response: Response) => void;
-};
-
-export const handleAiRequest = async (
- request: Promise,
- options: RequestOptions
-) => {
- const response = await request;
-
- await options.onResponseReceived?.(response);
-
- const isStream =
- (response.headers.get("content-type") || "").startsWith("text/plain") &&
- response.body instanceof ReadableStream;
-
- if (isStream) {
- // @todo Add delimiter to text streaming response to extract the operation id.
- const operationId = "copywriter";
-
- let completion = "";
- const reader = response.body.getReader();
- const decoder = createChunkDecoder();
-
- while (true) {
- const { done, value } = await reader.read();
-
- if (done) {
- break;
- }
-
- const decodedChunk = decoder(value);
- completion += decodedChunk;
-
- options.onChunk?.(operationId, {
- completion,
- chunk: value,
- decodedChunk,
- done,
- });
- }
-
- return {
- id: operationId,
- type: "stream",
- success: true,
- data: new RemixStreamingTextResponse(
- new Blob([completion], { type: "text/plain" }).stream()
- ),
- tokens: { prompt: -1, completion: -1 },
- } as const;
- }
-
- // @todo Convert the response types to Zod
- // so that responses can be parsed and validated on the client.
- return (await response.json()) as ModelResponse;
-};
diff --git a/packages/ai/src/utils/jsx-to-template.server.ts b/packages/ai/src/utils/jsx-to-template.server.ts
deleted file mode 100644
index c618753171bb..000000000000
--- a/packages/ai/src/utils/jsx-to-template.server.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import {
- heroiconsToSvgEmbed,
- jsxToWSEmbedTemplate,
- tailwindToWebstudio,
- traverseTemplate,
-} from "@webstudio-is/jsx-utils";
-import { WsEmbedTemplate } from "@webstudio-is/sdk";
-
-export const jsxToTemplate = async (jsx: string) => {
- const template = await jsxToWSEmbedTemplate(jsx);
- await tailwindToWebstudio(template);
- heroiconsToSvgEmbed(template);
- return template;
-};
-
-export const postProcessTemplate = (
- template: WsEmbedTemplate,
- components: string[]
-) => {
- traverseTemplate(template, (node) => {
- if (node.type === "instance") {
- if (components.includes(node.component) === false) {
- // Replace invalid components with Fragment if available
- if (components.includes("Fragment")) {
- node.component = "Fragment";
- delete node.props;
- delete node.styles;
- } else {
- throw new Error("Invalid component in template " + node.component);
- }
- }
-
- if (node.props !== undefined) {
- node.props = node.props.filter(
- (prop) => prop.name.startsWith("data-ws-") === false
- );
- }
- }
- });
-};
diff --git a/packages/ai/src/utils/remix-streaming-text-response.ts b/packages/ai/src/utils/remix-streaming-text-response.ts
deleted file mode 100644
index 0c8350cdb277..000000000000
--- a/packages/ai/src/utils/remix-streaming-text-response.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { StreamingTextResponse } from "ai";
-
-// vercel/ai's StreamingTextResponse does not include request.headers.raw()
-// which @vercel/remix uses when deployed on vercel.
-// Therefore we use a custom one.
-export class RemixStreamingTextResponse extends StreamingTextResponse {
- constructor(res: ReadableStream, init?: ResponseInit) {
- super(res, init);
- this.getRequestHeaders();
- }
-
- getRequestHeaders() {
- return addRawHeaders(this.headers);
- }
-}
-
-const addRawHeaders = (headers: Headers) => {
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
- // @ts-ignore
- headers.raw = () => {
- const rawHeaders: { [k in string]: string[] } = {};
- const headerEntries = headers.entries();
- for (const [key, value] of headerEntries) {
- const headerKey = key.toLowerCase();
- if (headerKey in rawHeaders) {
- rawHeaders[headerKey].push(value);
- } else {
- rawHeaders[headerKey] = [value];
- }
- }
- return rawHeaders;
- };
- return headers;
-};
diff --git a/packages/ai/tsconfig.json b/packages/ai/tsconfig.json
deleted file mode 100644
index d2e5040f8f2c..000000000000
--- a/packages/ai/tsconfig.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "extends": "@webstudio-is/tsconfig/base.json"
-}
diff --git a/packages/dashboard/src/db/projects.ts b/packages/dashboard/src/db/projects.ts
index 657120b61fa1..31ae33821312 100644
--- a/packages/dashboard/src/db/projects.ts
+++ b/packages/dashboard/src/db/projects.ts
@@ -32,12 +32,7 @@ export const findMany = async (userId: string, context: AppContext) => {
return data.data as SetNonNullable<
(typeof data.data)[number],
- | "id"
- | "title"
- | "domain"
- | "isDeleted"
- | "createdAt"
- | "marketplaceApprovalStatus"
+ "id" | "title" | "domain" | "isDeleted" | "createdAt"
>[];
};
@@ -60,11 +55,6 @@ export const findManyByIds = async (
}
return data.data as SetNonNullable<
(typeof data.data)[number],
- | "id"
- | "title"
- | "domain"
- | "isDeleted"
- | "createdAt"
- | "marketplaceApprovalStatus"
+ "id" | "title" | "domain" | "isDeleted" | "createdAt"
>[];
};
diff --git a/packages/design-system/src/components/ai-command-bar/autogrow-text-area.stories.tsx b/packages/design-system/src/components/ai-command-bar/autogrow-text-area.stories.tsx
deleted file mode 100644
index b2354272fb77..000000000000
--- a/packages/design-system/src/components/ai-command-bar/autogrow-text-area.stories.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-import { AutogrowTextArea } from "./autogrow-text-area";
-import { Box } from "../box";
-import { Grid } from "../grid";
-import { ScrollArea } from "../scroll-area";
-import { StorySection, StoryGrid } from "../storybook";
-
-export default {
- title: "Library/Autogrow Text Area",
-};
-
-export const Demo = () => {
- return (
- <>
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- >
- );
-};
-Demo.storyName = "Autogrow Text Area";
diff --git a/packages/design-system/src/components/ai-command-bar/autogrow-text-area.tsx b/packages/design-system/src/components/ai-command-bar/autogrow-text-area.tsx
deleted file mode 100644
index fc62a13d23d1..000000000000
--- a/packages/design-system/src/components/ai-command-bar/autogrow-text-area.tsx
+++ /dev/null
@@ -1,98 +0,0 @@
-/**
- * Implementation of the autogrowing text input for the AI
- * https://www.figma.com/file/xCBegXEWxROLqA1Y31z2Xo/%F0%9F%93%96-Webstudio-Design-Docs?node-id=7586%3A48784&mode=dev
- */
-
-import { type ComponentProps, type Ref, forwardRef } from "react";
-import { type CSS, css, theme } from "../../stitches.config";
-import { textVariants } from "../text";
-import { Grid } from "../grid";
-import { useControllableState } from "@radix-ui/react-use-controllable-state";
-
-const commonStyle = css(textVariants.regular, {
- border: "none",
- paddingRight: 0,
- paddingLeft: 0,
- paddingTop: 0,
- paddingBottom: 0,
- boxSizing: "border-box",
- gridArea: "1 / 1 / 2 / 2",
- background: "transparent",
- color: "inherit",
- textWrap: "wrap",
- overflowWrap: "break-word",
- whiteSpace: "pre-wrap",
- overflow: "hidden",
-});
-
-const style = css(commonStyle, {
- outline: "none",
- resize: "none",
- "&::placeholder": {
- color: theme.colors.foregroundContrastSubtle,
- },
- "&:disabled": {
- color: theme.colors.foregroundDisabled,
- // @todo: Ask Taylor if we should use the same color as the placeholder
- opacity: 0.6,
- },
- variants: {
- state: {
- invalid: {
- color: theme.colors.foregroundDestructive,
- },
- },
- },
-});
-
-type Props = Omit<
- ComponentProps<"textarea">,
- "value" | "defaultValue" | "onChange"
-> & {
- css?: CSS;
- state?: "invalid";
- value?: string;
- defaultValue?: string;
- onChange?: (value: string) => void;
-};
-
-export const AutogrowTextArea = forwardRef(
- (
- { css, className, state, value, defaultValue, onChange, ...props }: Props,
- ref: Ref
- ) => {
- // use
- const [textValue, setTextValue] = useControllableState({
- prop: value,
- defaultProp: defaultValue,
- onChange,
- });
-
- return (
-
-