diff --git a/.github/workflows/cli-r2-static.yaml b/.github/workflows/cli-r2-static.yaml index 8eb1af737e..dc15e31e91 100644 --- a/.github/workflows/cli-r2-static.yaml +++ b/.github/workflows/cli-r2-static.yaml @@ -59,7 +59,9 @@ jobs: # Despite being listed as a dependency, @remix-run/dev does not install the remix cli. # TODO: Minimize artefact size due to frequent downloads on each publish. - name: pnpm deploy - run: pnpm --filter 'ssg-cloudflare-pages' deploy "${{ github.workspace }}/../ssg-template" + run: | + pnpm --filter 'ssg-cloudflare-pages' deploy "${{ github.workspace }}/../ssg-template" + touch "${{ github.workspace }}/../ssg-template/.webstudio-cli-sync-build-v1" - name: Verify optional Assets build dependency is omitted run: test ! -e node_modules/@webstudio-is/content-engine/package.json diff --git a/.github/workflows/cli-r2.yaml b/.github/workflows/cli-r2.yaml index 36762d5699..c8f4c55129 100644 --- a/.github/workflows/cli-r2.yaml +++ b/.github/workflows/cli-r2.yaml @@ -56,11 +56,10 @@ jobs: - name: pnpm build run: pnpm --filter 'webstudio-cloudflare-template^...' run build - # Ideally, execute 'pnpm deploy --prod', but @remix-run/dev doesn't support this flag. - # Despite being listed as a dependency, @remix-run/dev does not install the remix cli. - # TODO: Minimize artefact size due to frequent downloads on each publish. - name: pnpm deploy - run: pnpm --filter 'webstudio-cloudflare-template' deploy "${{ github.workspace }}/../cloudflare-template" + run: | + pnpm --filter 'webstudio-cloudflare-template' deploy --prod "${{ github.workspace }}/../cloudflare-template" + touch "${{ github.workspace }}/../cloudflare-template/.webstudio-cli-sync-build-v1" - name: Verify optional Assets build dependency is omitted run: test ! -e node_modules/@webstudio-is/content-engine/package.json diff --git a/apps/builder/e2e/schema/schema-d80d56c69de9396969ab3f21663642108aaf2d96.sql b/apps/builder/e2e/schema/schema-d80d56c69de9396969ab3f21663642108aaf2d96.sql new file mode 100644 index 0000000000..939198687f --- /dev/null +++ b/apps/builder/e2e/schema/schema-d80d56c69de9396969ab3f21663642108aaf2d96.sql @@ -0,0 +1,1914 @@ +-- +-- PostgreSQL database dump +-- + +\restrict webstudioE2ESchema + +-- Dumped from database version 15.19 (Debian 15.19-1.pgdg12+2) +-- Dumped by pg_dump version 15.19 (Debian 15.19-1.pgdg12+2) + +SET statement_timeout = 0; +SET lock_timeout = 0; +SET idle_in_transaction_session_timeout = 0; +SET client_encoding = 'UTF8'; +SET standard_conforming_strings = on; +SELECT pg_catalog.set_config('search_path', '', false); +SET check_function_bodies = false; +SET xmloption = content; +SET client_min_messages = warning; +SET row_security = off; + +ALTER TABLE IF EXISTS ONLY public."latestBuildVirtual" DROP CONSTRAINT IF EXISTS "latestBuildVirtual_projectId_fkey"; +ALTER TABLE IF EXISTS ONLY public."latestBuildVirtual" DROP CONSTRAINT IF EXISTS "latestBuildVirtual_domainsVirtualId_fkey"; +ALTER TABLE IF EXISTS ONLY public."latestBuildVirtual" DROP CONSTRAINT IF EXISTS "latestBuildVirtual_buildId_fkey"; +ALTER TABLE IF EXISTS ONLY public."domainsVirtual" DROP CONSTRAINT IF EXISTS "domainsVirtual_projectId_fkey"; +ALTER TABLE IF EXISTS ONLY public."domainsVirtual" DROP CONSTRAINT IF EXISTS "domainsVirtual_domainId_fkey"; +ALTER TABLE IF EXISTS ONLY public."Workspace" DROP CONSTRAINT IF EXISTS "Workspace_userId_fkey"; +ALTER TABLE IF EXISTS ONLY public."WorkspaceMember" DROP CONSTRAINT IF EXISTS "WorkspaceMember_workspaceId_fkey"; +ALTER TABLE IF EXISTS ONLY public."WorkspaceMember" DROP CONSTRAINT IF EXISTS "WorkspaceMember_userId_fkey"; +ALTER TABLE IF EXISTS ONLY public."TransactionLog" DROP CONSTRAINT IF EXISTS "TransactionLog_userId_fkey"; +ALTER TABLE IF EXISTS ONLY public."TransactionLog" DROP CONSTRAINT IF EXISTS "TransactionLog_productId_fkey"; +ALTER TABLE IF EXISTS ONLY public."Project" DROP CONSTRAINT IF EXISTS "Project_workspaceId_fkey"; +ALTER TABLE IF EXISTS ONLY public."Project" DROP CONSTRAINT IF EXISTS "Project_userId_fkey"; +ALTER TABLE IF EXISTS ONLY public."Project" DROP CONSTRAINT IF EXISTS "Project_previewImageAssetId_id_fkey"; +ALTER TABLE IF EXISTS ONLY public."ProjectDomain" DROP CONSTRAINT IF EXISTS "ProjectDomain_projectId_fkey"; +ALTER TABLE IF EXISTS ONLY public."ProjectDomain" DROP CONSTRAINT IF EXISTS "ProjectDomain_domainId_fkey"; +ALTER TABLE IF EXISTS ONLY public."File" DROP CONSTRAINT IF EXISTS "File_uploaderProjectId_fkey"; +ALTER TABLE IF EXISTS ONLY public."ClientReferences" DROP CONSTRAINT IF EXISTS "ClientReferences_userId_fkey"; +ALTER TABLE IF EXISTS ONLY public."Build" DROP CONSTRAINT IF EXISTS "Build_projectId_fkey"; +ALTER TABLE IF EXISTS ONLY public."AuthorizationToken" DROP CONSTRAINT IF EXISTS "AuthorizationToken_projectId_fkey"; +ALTER TABLE IF EXISTS ONLY public."Asset" DROP CONSTRAINT IF EXISTS "Asset_name_fkey"; +ALTER TABLE IF EXISTS ONLY public."Asset" DROP CONSTRAINT IF EXISTS "Asset_folderId_projectId_fkey"; +ALTER TABLE IF EXISTS ONLY public."AssetFolder" DROP CONSTRAINT IF EXISTS "AssetFolder_projectId_fkey"; +ALTER TABLE IF EXISTS ONLY public."AssetFolder" DROP CONSTRAINT IF EXISTS "AssetFolder_parentId_projectId_fkey"; +ALTER TABLE IF EXISTS ONLY public."AssetFileMetadata" DROP CONSTRAINT IF EXISTS "AssetFileMetadata_assetId_projectId_fkey"; +DROP INDEX IF EXISTS public."Workspace_userId_isDefault_key"; +DROP INDEX IF EXISTS public."WorkspaceMember_userId_idx"; +DROP INDEX IF EXISTS public."User_email_key"; +DROP INDEX IF EXISTS public."TransactionLog_eventId_productId_key"; +DROP INDEX IF EXISTS public."Project_isDeleted_marketplaceApprovalStatus_idx"; +DROP INDEX IF EXISTS public."Project_id_isDeleted_key"; +DROP INDEX IF EXISTS public."Project_id_domain_key"; +DROP INDEX IF EXISTS public."Project_domain_key"; +DROP INDEX IF EXISTS public."Project_domain_isDeleted_key"; +DROP INDEX IF EXISTS public."ProjectDomain_txtRecord_key"; +DROP INDEX IF EXISTS public."ProjectDomain_domainId_idx"; +DROP INDEX IF EXISTS public."Notification_recipientId_status_idx"; +DROP INDEX IF EXISTS public."File_uploaderProjectId_contentHash_extension_key"; +DROP INDEX IF EXISTS public."Domain_domain_key"; +DROP INDEX IF EXISTS public."ClientReferences_reference_service_key"; +DROP INDEX IF EXISTS public."Build_projectId_createdAt_idx"; +DROP INDEX IF EXISTS public."Build_id_key"; +DROP INDEX IF EXISTS public."Build_dev_index"; +DROP INDEX IF EXISTS public."AuthorizationToken_token_key"; +DROP INDEX IF EXISTS public."AssetFolder_unique_sibling_name"; +DROP INDEX IF EXISTS public."AssetFolder_projectId_parentId_idx"; +ALTER TABLE IF EXISTS ONLY public."latestBuildVirtual" DROP CONSTRAINT IF EXISTS "latestBuildVirtual_pkey"; +ALTER TABLE IF EXISTS ONLY public."latestBuildVirtual" DROP CONSTRAINT IF EXISTS "latestBuildVirtual_domainsVirtualId_key"; +ALTER TABLE IF EXISTS ONLY public."latestBuildVirtual" DROP CONSTRAINT IF EXISTS "latestBuildVirtual_buildId_key"; +ALTER TABLE IF EXISTS ONLY public."domainsVirtual" DROP CONSTRAINT IF EXISTS "domainsVirtual_pkey"; +ALTER TABLE IF EXISTS ONLY public._prisma_migrations DROP CONSTRAINT IF EXISTS _prisma_migrations_pkey; +ALTER TABLE IF EXISTS ONLY public."Workspace" DROP CONSTRAINT IF EXISTS "Workspace_pkey"; +ALTER TABLE IF EXISTS ONLY public."WorkspaceMember" DROP CONSTRAINT IF EXISTS "WorkspaceMember_pkey"; +ALTER TABLE IF EXISTS ONLY public."User" DROP CONSTRAINT IF EXISTS "User_pkey"; +ALTER TABLE IF EXISTS ONLY public."TransactionLog" DROP CONSTRAINT IF EXISTS "TransactionLog_pkey"; +ALTER TABLE IF EXISTS ONLY public."Project" DROP CONSTRAINT IF EXISTS "Project_pkey"; +ALTER TABLE IF EXISTS ONLY public."ProjectDomain" DROP CONSTRAINT IF EXISTS "ProjectDomain_pkey"; +ALTER TABLE IF EXISTS ONLY public."Product" DROP CONSTRAINT IF EXISTS "Product_pkey"; +ALTER TABLE IF EXISTS ONLY public."Notification" DROP CONSTRAINT IF EXISTS "Notification_pkey"; +ALTER TABLE IF EXISTS ONLY public."File" DROP CONSTRAINT IF EXISTS "File_pkey"; +ALTER TABLE IF EXISTS ONLY public."Domain" DROP CONSTRAINT IF EXISTS "Domain_pkey"; +ALTER TABLE IF EXISTS ONLY public."ClientReferences" DROP CONSTRAINT IF EXISTS "ClientReferences_pkey"; +ALTER TABLE IF EXISTS ONLY public."Build" DROP CONSTRAINT IF EXISTS "Build_pkey"; +ALTER TABLE IF EXISTS ONLY public."AuthorizationToken" DROP CONSTRAINT IF EXISTS "AuthorizationToken_pkey"; +ALTER TABLE IF EXISTS ONLY public."Asset" DROP CONSTRAINT IF EXISTS "Asset_pkey"; +ALTER TABLE IF EXISTS ONLY public."AssetFolder" DROP CONSTRAINT IF EXISTS "AssetFolder_pkey"; +ALTER TABLE IF EXISTS ONLY public."AssetFileMetadata" DROP CONSTRAINT IF EXISTS "AssetFileMetadata_pkey"; +DROP VIEW IF EXISTS public.user_publish_count; +DROP VIEW IF EXISTS public.published_builds; +DROP TABLE IF EXISTS public._prisma_migrations; +DROP VIEW IF EXISTS public."WorkspaceProjectAuthorization"; +DROP TABLE IF EXISTS public."WorkspaceMember"; +DROP TABLE IF EXISTS public."Workspace"; +DROP VIEW IF EXISTS public."UserProduct"; +DROP TABLE IF EXISTS public."User"; +DROP TABLE IF EXISTS public."TransactionLog"; +DROP TABLE IF EXISTS public."ProjectDomain"; +DROP TABLE IF EXISTS public."Product"; +DROP TABLE IF EXISTS public."Notification"; +DROP VIEW IF EXISTS public."LatestStaticBuildPerProject"; +DROP TABLE IF EXISTS public."File"; +DROP TABLE IF EXISTS public."Domain"; +DROP TABLE IF EXISTS public."ClientReferences"; +DROP TABLE IF EXISTS public."AssetFolder"; +DROP TABLE IF EXISTS public."AssetFileMetadata"; +DROP TABLE IF EXISTS public."Asset"; +DROP VIEW IF EXISTS public."ApprovedMarketplaceProduct"; +DROP TABLE IF EXISTS public."AuthorizationToken"; +DROP FUNCTION IF EXISTS public.swap_asset_file(project_id text, asset_id text, expected_name text, replacement_name text); +DROP FUNCTION IF EXISTS public.restore_development_build(project_id text, from_build_id text); +DROP FUNCTION IF EXISTS public.replace_asset_file_metadata(p_project_id text, p_asset_id text, p_revision text, p_document jsonb, p_source jsonb); +DROP FUNCTION IF EXISTS public."latestProjectDomainBuildVirtual"(public."Project"); +DROP FUNCTION IF EXISTS public."latestBuildVirtual"(public."domainsVirtual"); +DROP FUNCTION IF EXISTS public."latestBuildVirtual"(public."Project"); +DROP FUNCTION IF EXISTS public."latestBuildVirtual"(public."DashboardProject"); +DROP TABLE IF EXISTS public."latestBuildVirtual"; +DROP VIEW IF EXISTS public."DashboardProject"; +DROP TABLE IF EXISTS public."Build"; +DROP FUNCTION IF EXISTS public."domainsVirtual"(public."Project"); +DROP TABLE IF EXISTS public."domainsVirtual"; +DROP FUNCTION IF EXISTS public.delete_stale_asset_file_metadata(p_project_id text, p_asset_ids text[]); +DROP FUNCTION IF EXISTS public.delete_asset_file_metadata_if_matches(p_project_id text, p_asset_id text, p_revision text, p_document jsonb); +DROP FUNCTION IF EXISTS public.database_cleanup(from_date timestamp without time zone, to_date timestamp without time zone); +DROP FUNCTION IF EXISTS public.create_production_build_expected(project_id text, deployment text, expected_version integer); +DROP FUNCTION IF EXISTS public.create_production_build(project_id text, deployment text); +DROP FUNCTION IF EXISTS public.clone_project(project_id text, user_id text, title text, domain text); +DROP TABLE IF EXISTS public."Project"; +DROP TYPE IF EXISTS public."UploadStatus"; +DROP TYPE IF EXISTS public."PublishStatus"; +DROP TYPE IF EXISTS public."MarketplaceApprovalStatus"; +DROP TYPE IF EXISTS public."DomainStatus"; +DROP TYPE IF EXISTS public."AuthorizationRelation"; +DROP SCHEMA IF EXISTS public; +-- +-- Name: public; Type: SCHEMA; Schema: -; Owner: - +-- + +CREATE SCHEMA public; + + +-- +-- Name: SCHEMA public; Type: COMMENT; Schema: -; Owner: - +-- + +COMMENT ON SCHEMA public IS 'standard public schema'; + + +-- +-- Name: AuthorizationRelation; Type: TYPE; Schema: public; Owner: - +-- + +CREATE TYPE public."AuthorizationRelation" AS ENUM ( + 'viewers', + 'editors', + 'builders', + 'administrators' +); + + +-- +-- Name: DomainStatus; Type: TYPE; Schema: public; Owner: - +-- + +CREATE TYPE public."DomainStatus" AS ENUM ( + 'INITIALIZING', + 'ACTIVE', + 'ERROR', + 'PENDING' +); + + +-- +-- Name: MarketplaceApprovalStatus; Type: TYPE; Schema: public; Owner: - +-- + +CREATE TYPE public."MarketplaceApprovalStatus" AS ENUM ( + 'UNLISTED', + 'PENDING', + 'APPROVED', + 'REJECTED' +); + + +-- +-- Name: PublishStatus; Type: TYPE; Schema: public; Owner: - +-- + +CREATE TYPE public."PublishStatus" AS ENUM ( + 'PENDING', + 'PUBLISHED', + 'FAILED' +); + + +-- +-- Name: UploadStatus; Type: TYPE; Schema: public; Owner: - +-- + +CREATE TYPE public."UploadStatus" AS ENUM ( + 'UPLOADING', + 'UPLOADED' +); + + +SET default_tablespace = ''; + +SET default_table_access_method = heap; + +-- +-- Name: Project; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."Project" ( + id text NOT NULL, + title text NOT NULL, + domain text NOT NULL, + "userId" text, + "isDeleted" boolean DEFAULT false NOT NULL, + "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL, + "previewImageAssetId" text, + "marketplaceApprovalStatus" public."MarketplaceApprovalStatus" DEFAULT 'UNLISTED'::public."MarketplaceApprovalStatus" NOT NULL, + tags text[], + "workspaceId" uuid +); + + +-- +-- Name: clone_project(text, text, text, text); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public.clone_project(project_id text, user_id text, title text, domain text) RETURNS public."Project" + LANGUAGE plpgsql + AS $$ +DECLARE + old_project "Project"; + new_project "Project"; +BEGIN + SELECT * FROM "Project" WHERE id = project_id INTO old_project; + + INSERT INTO "Project" (id, "userId", title, domain) + VALUES (gen_random_uuid(), user_id, title, domain) + RETURNING * INTO new_project; + + INSERT INTO "AssetFolder" (id, "projectId", name, "parentId", "createdAt") + SELECT id, new_project.id, name, "parentId", "createdAt" + FROM "AssetFolder" + WHERE "projectId" = old_project.id; + + INSERT INTO "Asset" ( + id, + name, + "projectId", + filename, + description, + "folderId" + ) + SELECT + asset.id, + asset.name, + new_project.id, + asset.filename, + asset.description, + asset."folderId" + FROM "Asset" AS asset, "File" AS file + WHERE + asset.name = file.name AND + file.status = 'UPLOADED' AND + asset."projectId" = old_project.id; + + UPDATE "Project" + SET "previewImageAssetId" = old_project."previewImageAssetId" + WHERE id = new_project.id; + + INSERT INTO "Build" ( + id, + "projectId", + pages, + "styleSources", + "styleSourceSelections", + styles, + breakpoints, + props, + instances, + "dataSources", + resources, + "marketplaceProduct", + "projectSettings" + ) + SELECT + gen_random_uuid(), + new_project.id, + pages, + "styleSources", + "styleSourceSelections", + styles, + breakpoints, + props, + instances, + "dataSources", + resources, + "marketplaceProduct", + "projectSettings" + FROM "Build" + WHERE "projectId" = old_project.id AND deployment IS NULL; + + RETURN new_project; +END; +$$; + + +-- +-- Name: create_production_build(text, text); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public.create_production_build(project_id text, deployment text) RETURNS text + LANGUAGE plpgsql + AS $$ +DECLARE + new_build_id text; +BEGIN + INSERT INTO "Build" ( + version, + "lastTransactionId", + pages, + breakpoints, + styles, + "styleSources", + "styleSourceSelections", + props, + "dataSources", + resources, + instances, + "marketplaceProduct", + "projectSettings", + "publishStatus", + "projectId", + id, + deployment + ) + SELECT + version, + "lastTransactionId", + pages, + breakpoints, + styles, + "styleSources", + "styleSourceSelections", + props, + "dataSources", + resources, + instances, + "marketplaceProduct", + "projectSettings", + "publishStatus", + "projectId", + extensions.uuid_generate_v4(), + create_production_build.deployment + FROM "Build" + WHERE "projectId" = project_id AND "Build".deployment IS NULL + RETURNING id INTO new_build_id; + + RETURN new_build_id; +END; +$$; + + +-- +-- Name: create_production_build_expected(text, text, integer); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public.create_production_build_expected(project_id text, deployment text, expected_version integer) RETURNS text + LANGUAGE plpgsql + AS $$ +DECLARE + new_build_id text; +BEGIN + INSERT INTO "Build" ( + version, "lastTransactionId", pages, breakpoints, styles, "styleSources", + "styleSourceSelections", props, "dataSources", resources, instances, + "marketplaceProduct", "projectSettings", "publishStatus", "projectId", id, + deployment + ) + SELECT + version, "lastTransactionId", pages, breakpoints, styles, "styleSources", + "styleSourceSelections", props, "dataSources", resources, instances, + "marketplaceProduct", "projectSettings", "publishStatus", "projectId", + extensions.uuid_generate_v4(), create_production_build_expected.deployment + FROM "Build" + WHERE "projectId" = project_id + AND "Build".deployment IS NULL + AND version = expected_version + RETURNING id INTO new_build_id; + + RETURN new_build_id; +END; +$$; + + +-- +-- Name: database_cleanup(timestamp without time zone, timestamp without time zone); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public.database_cleanup(from_date timestamp without time zone DEFAULT '2020-01-01 00:00:00'::timestamp without time zone, to_date timestamp without time zone DEFAULT '2099-12-31 23:59:59'::timestamp without time zone) RETURNS void + LANGUAGE plpgsql + AS $$ +BEGIN + WITH latest_builds AS ( + SELECT "buildId" FROM "Project" p, LATERAL "latestProjectDomainBuildVirtual"(p) + UNION + SELECT "buildId" FROM "Project" p, LATERAL "latestBuildVirtual"(p) + UNION + SELECT lb."buildId" + FROM "Project" p, LATERAL "domainsVirtual"(p) dv, LATERAL "latestBuildVirtual"(dv) lb + ) + UPDATE "Build" + SET + "styleSources" = '[]', + styles = '[]', + breakpoints = '[]', + "styleSourceSelections" = '[]', + props = '[]', + instances = '[]', + "dataSources" = '[]', + resources = '[]', + "marketplaceProduct" = '{}', + "projectSettings" = '{"meta":{},"compiler":{}}', + "isCleaned" = true + WHERE deployment IS NOT NULL + AND id NOT IN (SELECT "buildId" FROM latest_builds) + AND "isCleaned" = false + AND "createdAt" BETWEEN from_date AND to_date; +END; +$$; + + +-- +-- Name: delete_asset_file_metadata_if_matches(text, text, text, jsonb); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public.delete_asset_file_metadata_if_matches(p_project_id text, p_asset_id text, p_revision text, p_document jsonb) RETURNS integer + LANGUAGE plpgsql + AS $$ +DECLARE + deleted_count INTEGER; +BEGIN + PERFORM pg_catalog.pg_advisory_xact_lock( + pg_catalog.hashtextextended( + pg_catalog.jsonb_build_array(p_project_id, p_asset_id)::TEXT, + 0 + ) + ); + + DELETE FROM public."AssetFileMetadata" + WHERE "projectId" = p_project_id + AND "assetId" = p_asset_id + AND "revision" = p_revision + AND "document" = p_document; + GET DIAGNOSTICS deleted_count = ROW_COUNT; + RETURN deleted_count; +END; +$$; + + +-- +-- Name: delete_stale_asset_file_metadata(text, text[]); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public.delete_stale_asset_file_metadata(p_project_id text, p_asset_ids text[]) RETURNS integer + LANGUAGE plpgsql + AS $$ +DECLARE + asset_id TEXT; + deleted_count INTEGER; + total_deleted INTEGER := 0; +BEGIN + FOR asset_id IN + SELECT DISTINCT requested_asset_id + FROM pg_catalog.unnest(p_asset_ids) AS requested_asset_id + ORDER BY requested_asset_id + LOOP + PERFORM pg_catalog.pg_advisory_xact_lock( + pg_catalog.hashtextextended( + pg_catalog.jsonb_build_array(p_project_id, asset_id)::TEXT, + 0 + ) + ); + + IF NOT EXISTS ( + SELECT 1 + FROM public."Asset" AS asset + INNER JOIN public."File" AS file ON file."name" = asset."name" + WHERE asset."projectId" = p_project_id + AND asset."id" = asset_id + AND file."status" = 'UPLOADED' + ) THEN + DELETE FROM public."AssetFileMetadata" + WHERE "projectId" = p_project_id + AND "assetId" = asset_id; + GET DIAGNOSTICS deleted_count = ROW_COUNT; + total_deleted := total_deleted + deleted_count; + END IF; + END LOOP; + + RETURN total_deleted; +END; +$$; + + +-- +-- Name: domainsVirtual; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."domainsVirtual" ( + id text NOT NULL, + "domainId" text NOT NULL, + "projectId" text NOT NULL, + domain text NOT NULL, + status public."DomainStatus" DEFAULT 'INITIALIZING'::public."DomainStatus" NOT NULL, + error text, + "domainTxtRecord" text, + "expectedTxtRecord" text NOT NULL, + cname text NOT NULL, + verified boolean DEFAULT false NOT NULL, + "createdAt" timestamp(3) with time zone NOT NULL, + "updatedAt" timestamp(3) with time zone NOT NULL +); + + +-- +-- Name: TABLE "domainsVirtual"; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON TABLE public."domainsVirtual" IS 'Virtual table representing domains related to each project. This table enforces a 1-1 relationship with the Project table and is used for API interaction (postgrest types).'; + + +-- +-- Name: COLUMN "domainsVirtual"."domainId"; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON COLUMN public."domainsVirtual"."domainId" IS 'Unique identifier for the domain (Domain table reference).'; + + +-- +-- Name: COLUMN "domainsVirtual"."projectId"; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON COLUMN public."domainsVirtual"."projectId" IS 'Unique identifier for the project, acting as the primary key (1-1 relationship with Project table).'; + + +-- +-- Name: COLUMN "domainsVirtual".domain; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON COLUMN public."domainsVirtual".domain IS 'The domain name (must not be NULL).'; + + +-- +-- Name: COLUMN "domainsVirtual".status; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON COLUMN public."domainsVirtual".status IS 'Current status of the domain, with a default of INITIALIZING.'; + + +-- +-- Name: COLUMN "domainsVirtual".error; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON COLUMN public."domainsVirtual".error IS 'Optional error message field populated if the domain status is ERROR.'; + + +-- +-- Name: COLUMN "domainsVirtual"."domainTxtRecord"; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON COLUMN public."domainsVirtual"."domainTxtRecord" IS 'Current TXT record for the domain, coming from the Domain table.'; + + +-- +-- Name: COLUMN "domainsVirtual"."expectedTxtRecord"; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON COLUMN public."domainsVirtual"."expectedTxtRecord" IS 'Expected TXT record for the domain, pulled from the ProjectDomain table.'; + + +-- +-- Name: COLUMN "domainsVirtual".verified; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON COLUMN public."domainsVirtual".verified IS 'Boolean flag indicating whether the domain is verified (true if TXT records match, false otherwise).'; + + +-- +-- Name: COLUMN "domainsVirtual"."createdAt"; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON COLUMN public."domainsVirtual"."createdAt" IS 'Timestamp indicating when the ProjectDomain entry was created.'; + + +-- +-- Name: COLUMN "domainsVirtual"."updatedAt"; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON COLUMN public."domainsVirtual"."updatedAt" IS 'Timestamp indicating when the Domain was last updated.'; + + +-- +-- Name: domainsVirtual(public."Project"); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public."domainsVirtual"(public."Project") RETURNS SETOF public."domainsVirtual" + LANGUAGE sql STABLE + AS $_$ + -- This function retrieves all the domain information associated with a specific project by joining the Domain and ProjectDomain tables. + -- It returns a result set conforming to the "domainsVirtual" structure, including fields such as domain status, error, verification status, etc. + SELECT + "Domain".id || '-' || "ProjectDomain"."projectId" as id, + "Domain".id AS "domainId", -- Domain ID from Domain table + "ProjectDomain"."projectId", -- Project ID from ProjectDomain table + "Domain".domain, -- Domain name + "Domain".status, -- Current domain status + "Domain".error, -- Error message, if any + "Domain"."txtRecord" AS "domainTxtRecord", -- Current TXT record from Domain table + "ProjectDomain"."txtRecord" AS "expectedTxtRecord", -- Expected TXT record from ProjectDomain table + "ProjectDomain"."cname" AS "cname", + CASE + WHEN "Domain"."txtRecord" = "ProjectDomain"."txtRecord" THEN true -- If TXT records match, domain is verified + ELSE false + END AS "verified", -- Boolean flag for verification status + "ProjectDomain"."createdAt", -- Creation timestamp from ProjectDomain table + "Domain"."updatedAt" -- Last updated timestamp from Domain table + FROM + "Domain" + JOIN + "ProjectDomain" ON "Domain".id = "ProjectDomain"."domainId" -- Joining Domain and ProjectDomain on domainId + WHERE + "ProjectDomain"."projectId" = $1.id -- Filtering by projectId passed as an argument to the function + ORDER BY "ProjectDomain"."createdAt", "Domain".id; -- Stable sort +$_$; + + +-- +-- Name: FUNCTION "domainsVirtual"(public."Project"); Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON FUNCTION public."domainsVirtual"(public."Project") IS 'Function that retrieves domain-related data for a given project by joining the Domain and ProjectDomain tables. It returns a result set that conforms to the structure defined in the domainsVirtual virtual table.'; + + +-- +-- Name: Build; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."Build" ( + id text NOT NULL, + "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL, + pages text NOT NULL, + "projectId" text NOT NULL, + "styleSources" text DEFAULT '[]'::text NOT NULL, + styles text DEFAULT '[]'::text NOT NULL, + breakpoints text DEFAULT '[]'::text NOT NULL, + "styleSourceSelections" text DEFAULT '[]'::text NOT NULL, + props text DEFAULT '[]'::text NOT NULL, + instances text DEFAULT '[]'::text NOT NULL, + "updatedAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL, + version integer DEFAULT 0 NOT NULL, + deployment text, + "publishStatus" public."PublishStatus" DEFAULT 'PENDING'::public."PublishStatus" NOT NULL, + "dataSources" text DEFAULT '[]'::text NOT NULL, + "lastTransactionId" text, + resources text DEFAULT '[]'::text NOT NULL, + "marketplaceProduct" text DEFAULT '{}'::text NOT NULL, + "isCleaned" boolean DEFAULT false, + "projectSettings" text DEFAULT '{"meta":{},"compiler":{}}'::text NOT NULL +); + + +-- +-- Name: DashboardProject; Type: VIEW; Schema: public; Owner: - +-- + +CREATE VIEW public."DashboardProject" AS + SELECT "Project".id, + "Project".title, + "Project".tags, + "Project".domain, + "Project"."userId", + "Project"."workspaceId", + "Project"."isDeleted", + "Project"."createdAt", + "Project"."previewImageAssetId", + "Project"."marketplaceApprovalStatus", + (EXISTS ( SELECT 1 + FROM public."Build" + WHERE (("Build"."projectId" = "Project".id) AND ("Build".deployment IS NOT NULL)))) AS "isPublished" + FROM public."Project"; + + +-- +-- Name: latestBuildVirtual; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."latestBuildVirtual" ( + "buildId" text NOT NULL, + "projectId" text NOT NULL, + "domainsVirtualId" text NOT NULL, + domain text NOT NULL, + "createdAt" timestamp(3) with time zone NOT NULL, + "publishStatus" public."PublishStatus" NOT NULL, + "updatedAt" timestamp(3) with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: TABLE "latestBuildVirtual"; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON TABLE public."latestBuildVirtual" IS 'Virtual table representing the latest build for each project, enforcing a 1-1 relationship with the Project table. Used ONLY for postgrest types'; + + +-- +-- Name: COLUMN "latestBuildVirtual"."projectId"; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON COLUMN public."latestBuildVirtual"."projectId" IS 'Identifier for the project, enforcing a 1-1 relationship with the Project table as a primary key'; + + +-- +-- Name: COLUMN "latestBuildVirtual"."updatedAt"; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON COLUMN public."latestBuildVirtual"."updatedAt" IS 'Timestamp indicating when the Build was last updated'; + + +-- +-- Name: latestBuildVirtual(public."DashboardProject"); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public."latestBuildVirtual"(public."DashboardProject") RETURNS SETOF public."latestBuildVirtual" + LANGUAGE sql STABLE ROWS 1 + AS $_$ +SELECT + lbv.* +FROM + "Project" p, + LATERAL "latestBuildVirtual"(p) lbv +WHERE + p.id = $1.id +LIMIT 1; + +$_$; + + +-- +-- Name: FUNCTION "latestBuildVirtual"(public."DashboardProject"); Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON FUNCTION public."latestBuildVirtual"(public."DashboardProject") IS 'Wrapper function to make latestBuildVirtual work with DashboardProject view for PostgREST computed fields.'; + + +-- +-- Name: latestBuildVirtual(public."Project"); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public."latestBuildVirtual"(public."Project") RETURNS SETOF public."latestBuildVirtual" + LANGUAGE sql STABLE ROWS 1 + AS $_$ +SELECT + b.id AS "buildId", + b."projectId", + '' as "domainsVirtualId", + -- Use CASE to determine which domain to select based on conditions + CASE + WHEN (b.deployment :: jsonb ->> 'projectDomain') = p.domain + OR (b.deployment :: jsonb -> 'domains') @> to_jsonb(array [p.domain]) THEN p.domain + ELSE d.domain + END AS "domain", + b."createdAt", + b."publishStatus", + b."updatedAt" +FROM + "Build" b + JOIN "Project" p ON b."projectId" = p.id + LEFT JOIN "ProjectDomain" pd ON pd."projectId" = p.id + LEFT JOIN "Domain" d ON d.id = pd."domainId" +WHERE + b."projectId" = $1.id + AND b.deployment IS NOT NULL -- 'destination' IS NULL for backward compatibility; 'destination' = 'saas' for non-static builds + AND ( + (b.deployment :: jsonb ->> 'destination') IS NULL + OR (b.deployment :: jsonb ->> 'destination') = 'saas' + ) + AND ( + -- Check if 'projectDomain' matches p.domain + (b.deployment :: jsonb ->> 'projectDomain') = p.domain -- Check if 'domains' contains p.domain or d.domain + OR (b.deployment :: jsonb -> 'domains') @> to_jsonb(array [p.domain]) + OR (b.deployment :: jsonb -> 'domains') @> to_jsonb(array [d.domain]) + ) +ORDER BY + b."createdAt" DESC +LIMIT + 1; + +$_$; + + +-- +-- Name: FUNCTION "latestBuildVirtual"(public."Project"); Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON FUNCTION public."latestBuildVirtual"(public."Project") IS 'This function computes the latest build for a project, ensuring it is a production (non-static) build, where the domain matches either the Project.domain field or exists in the related Domain table. It provides backward compatibility for older records with a missing "destination" field.'; + + +-- +-- Name: latestBuildVirtual(public."domainsVirtual"); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public."latestBuildVirtual"(public."domainsVirtual") RETURNS SETOF public."latestBuildVirtual" + LANGUAGE sql STABLE ROWS 1 + AS $_$ +SELECT + b.id AS "buildId", + b."projectId", + '' as "domainsVirtualId", + d."domain", + b."createdAt", + b."publishStatus", + b."updatedAt" +FROM + "Build" b + JOIN "Domain" d ON d.id = $1."domainId" +WHERE + b."projectId" = $1."projectId" + AND b.deployment IS NOT NULL + AND (b.deployment :: jsonb -> 'domains') @> to_jsonb(array [d.domain]) +ORDER BY + b."createdAt" DESC +LIMIT + 1; + +$_$; + + +-- +-- Name: FUNCTION "latestBuildVirtual"(public."domainsVirtual"); Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON FUNCTION public."latestBuildVirtual"(public."domainsVirtual") IS 'Returns the latest build for a given project and domain as a computed field for PostgREST.'; + + +-- +-- Name: latestProjectDomainBuildVirtual(public."Project"); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public."latestProjectDomainBuildVirtual"(public."Project") RETURNS SETOF public."latestBuildVirtual" + LANGUAGE sql STABLE ROWS 1 + AS $_$ +SELECT + b.id AS "buildId", + b."projectId", + '' as "domainsVirtualId", + p.domain AS "domain", + b."createdAt", + b."publishStatus", + b."updatedAt" +FROM + "Build" b + JOIN "Project" p ON b."projectId" = p.id + LEFT JOIN "ProjectDomain" pd ON pd."projectId" = p.id +WHERE + b."projectId" = $1.id + AND b.deployment IS NOT NULL + AND ( + (b.deployment :: jsonb ->> 'destination') IS NULL + OR (b.deployment :: jsonb ->> 'destination') = 'saas' + ) + AND ( + (b.deployment :: jsonb ->> 'projectDomain') = p.domain + OR (b.deployment :: jsonb -> 'domains') @> to_jsonb(array [p.domain]) + ) +ORDER BY + b."createdAt" DESC +LIMIT + 1; + +$_$; + + +-- +-- Name: FUNCTION "latestProjectDomainBuildVirtual"(public."Project"); Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON FUNCTION public."latestProjectDomainBuildVirtual"(public."Project") IS 'This function computes the latest build for a project domain, ensuring it is a production (non-static) build, where the domain matches either the Project.domain field or exists in the related Domain table. It provides backward compatibility for older records with a missing "destination" field.'; + + +-- +-- Name: replace_asset_file_metadata(text, text, text, jsonb, jsonb); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public.replace_asset_file_metadata(p_project_id text, p_asset_id text, p_revision text, p_document jsonb, p_source jsonb) RETURNS boolean + LANGUAGE plpgsql + AS $$ +BEGIN + PERFORM pg_catalog.pg_advisory_xact_lock( + pg_catalog.hashtextextended( + pg_catalog.jsonb_build_array(p_project_id, p_asset_id)::TEXT, + 0 + ) + ); + + PERFORM 1 + FROM public."Asset" AS asset + INNER JOIN public."File" AS file ON file."name" = asset."name" + WHERE asset."projectId" = p_project_id + AND asset."id" = p_asset_id + AND asset."filename" IS NOT DISTINCT FROM p_source->>'filename' + AND asset."description" IS NOT DISTINCT FROM p_source->>'description' + AND asset."folderId" IS NOT DISTINCT FROM p_source->>'folderId' + AND file."name" = p_source->>'storageName' + AND file."updatedAt" = (p_source->>'fileUpdatedAt')::TIMESTAMPTZ + AND file."size" = (p_source->>'fileSize')::INTEGER + AND file."status" = 'UPLOADED' + FOR UPDATE OF asset, file; + + IF NOT FOUND THEN + RETURN FALSE; + END IF; + + INSERT INTO public."AssetFileMetadata" ( + "projectId", + "assetId", + "revision", + "document", + "updatedAt" + ) VALUES ( + p_project_id, + p_asset_id, + p_revision, + p_document, + CURRENT_TIMESTAMP + ) + ON CONFLICT ("projectId", "assetId") + DO UPDATE SET + "revision" = EXCLUDED."revision", + "document" = EXCLUDED."document", + "updatedAt" = EXCLUDED."updatedAt" + WHERE "AssetFileMetadata"."revision" IS DISTINCT FROM EXCLUDED."revision" + OR "AssetFileMetadata"."document" IS DISTINCT FROM EXCLUDED."document"; + + RETURN TRUE; +END; +$$; + + +-- +-- Name: restore_development_build(text, text); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public.restore_development_build(project_id text, from_build_id text) RETURNS text + LANGUAGE plpgsql + AS $$ +BEGIN + UPDATE "Build" + SET + version = source.version, + "lastTransactionId" = source."lastTransactionId", + pages = source.pages, + breakpoints = source.breakpoints, + styles = source.styles, + "styleSources" = source."styleSources", + "styleSourceSelections" = source."styleSourceSelections", + props = source.props, + "dataSources" = source."dataSources", + resources = source.resources, + instances = source.instances, + "marketplaceProduct" = source."marketplaceProduct", + "projectSettings" = source."projectSettings" + FROM ( + SELECT * FROM "Build" + WHERE "projectId" = project_id AND id = from_build_id + ) AS source + WHERE "Build"."projectId" = project_id AND "Build".deployment IS NULL; + RETURN 'OK'; +END; +$$; + + +-- +-- Name: swap_asset_file(text, text, text, text); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public.swap_asset_file(project_id text, asset_id text, expected_name text, replacement_name text) RETURNS text + LANGUAGE plpgsql + AS $$ +DECLARE + current_name text; +BEGIN + SELECT "name" + INTO current_name + FROM "Asset" + WHERE "projectId" = project_id AND "id" = asset_id + FOR UPDATE; + + IF current_name IS NULL THEN + RETURN 'not_found'; + END IF; + + IF current_name <> expected_name THEN + RETURN 'conflict'; + END IF; + + IF NOT EXISTS ( + SELECT 1 + FROM "File" + WHERE + "name" = replacement_name + AND "status" = 'UPLOADED' + AND "uploaderProjectId" = project_id + ) THEN + RETURN 'invalid_revision'; + END IF; + + UPDATE "File" + SET "isDeleted" = false + WHERE "name" = replacement_name; + + UPDATE "Asset" + SET "name" = replacement_name + WHERE "projectId" = project_id AND "id" = asset_id; + + UPDATE "File" + SET "isDeleted" = true + WHERE + "name" = expected_name + AND NOT EXISTS ( + SELECT 1 FROM "Asset" WHERE "name" = expected_name + ); + + RETURN 'updated'; +END; +$$; + + +-- +-- Name: AuthorizationToken; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."AuthorizationToken" ( + token text NOT NULL, + "projectId" text NOT NULL, + name text DEFAULT ''::text NOT NULL, + relation public."AuthorizationRelation" DEFAULT 'viewers'::public."AuthorizationRelation" NOT NULL, + "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL, + "canClone" boolean DEFAULT true NOT NULL, + "canCopy" boolean DEFAULT true NOT NULL, + "canPublish" boolean DEFAULT false NOT NULL, + "canUseApi" boolean DEFAULT false NOT NULL +); + + +-- +-- Name: ApprovedMarketplaceProduct; Type: VIEW; Schema: public; Owner: - +-- + +CREATE VIEW public."ApprovedMarketplaceProduct" AS + SELECT DISTINCT ON (build."projectId") build."projectId", + build."marketplaceProduct", + ( SELECT auth.token + FROM public."AuthorizationToken" auth + WHERE ((auth."projectId" = build."projectId") AND (auth.relation = 'viewers'::public."AuthorizationRelation")) + ORDER BY auth.token + LIMIT 1) AS "authorizationToken" + FROM public."Build" build + WHERE ((build.deployment IS NOT NULL) AND (build."projectId" IN ( SELECT "Project".id + FROM public."Project" + WHERE (("Project"."isDeleted" = false) AND ("Project"."marketplaceApprovalStatus" = ('APPROVED'::text)::public."MarketplaceApprovalStatus"))))) + ORDER BY build."projectId", build."createdAt" DESC, build.id; + + +-- +-- Name: Asset; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."Asset" ( + id text NOT NULL, + "projectId" text NOT NULL, + name text NOT NULL, + description text, + filename text, + "folderId" text +); + + +-- +-- Name: AssetFileMetadata; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."AssetFileMetadata" ( + "projectId" text NOT NULL, + "assetId" text NOT NULL, + revision text NOT NULL, + document jsonb NOT NULL, + "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL, + "updatedAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL, + CONSTRAINT "AssetFileMetadata_document_identity_check" CHECK ((((jsonb_typeof(document) = 'object'::text) AND (jsonb_typeof((document -> '_id'::text)) = 'string'::text) AND ((document ->> '_id'::text) = "assetId") AND (jsonb_typeof((document -> 'revision'::text)) = 'string'::text) AND ((document ->> 'revision'::text) = revision)) IS TRUE)) +); + + +-- +-- Name: AssetFolder; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."AssetFolder" ( + id text DEFAULT gen_random_uuid() NOT NULL, + "projectId" text NOT NULL, + name text NOT NULL, + "parentId" text, + "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL, + CONSTRAINT "AssetFolder_name_not_blank" CHECK ((btrim(name) <> ''::text)) +); + + +-- +-- Name: ClientReferences; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."ClientReferences" ( + reference text DEFAULT extensions.uuid_generate_v4() NOT NULL, + service text NOT NULL, + "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL, + "userId" text NOT NULL +); + + +-- +-- Name: Domain; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."Domain" ( + id text NOT NULL, + domain text NOT NULL, + "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL, + "txtRecord" text, + status public."DomainStatus" DEFAULT 'INITIALIZING'::public."DomainStatus" NOT NULL, + error text, + "updatedAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL +); + + +-- +-- Name: File; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."File" ( + name text NOT NULL, + format text NOT NULL, + size integer NOT NULL, + description text, + "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL, + meta text DEFAULT '{}'::text NOT NULL, + status public."UploadStatus" DEFAULT 'UPLOADING'::public."UploadStatus" NOT NULL, + "uploaderProjectId" text, + "isDeleted" boolean DEFAULT false NOT NULL, + "updatedAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL, + "contentHash" character varying(64) +); + + +-- +-- Name: LatestStaticBuildPerProject; Type: VIEW; Schema: public; Owner: - +-- + +CREATE VIEW public."LatestStaticBuildPerProject" AS + SELECT DISTINCT ON (bld."projectId") bld.id AS "buildId", + bld."projectId", + bld."updatedAt", + bld."publishStatus" + FROM public."Build" bld + WHERE ((bld.deployment IS NOT NULL) AND (((bld.deployment)::jsonb ->> 'destination'::text) = 'static'::text)) + ORDER BY bld."projectId", bld."createdAt" DESC, bld.id; + + +-- +-- Name: Notification; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."Notification" ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + type text NOT NULL, + "recipientId" text NOT NULL, + "senderId" text NOT NULL, + status text DEFAULT 'pending'::text NOT NULL, + payload jsonb DEFAULT '{}'::jsonb NOT NULL, + "createdAt" timestamp(3) with time zone DEFAULT now() NOT NULL, + "respondedAt" timestamp(3) with time zone +); + + +-- +-- Name: Product; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."Product" ( + id text NOT NULL, + name text NOT NULL, + description text, + features text[], + images text[], + meta jsonb NOT NULL, + "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL +); + + +-- +-- Name: ProjectDomain; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."ProjectDomain" ( + "projectId" text NOT NULL, + "domainId" text NOT NULL, + "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL, + "txtRecord" text NOT NULL, + cname text NOT NULL +); + + +-- +-- Name: TransactionLog; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."TransactionLog" ( + "eventId" text NOT NULL, + "productId" text, + "userId" text, + "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL, + "eventData" jsonb, + "eventCreated" integer GENERATED ALWAYS AS ((("eventData" #>> '{created}'::text[]))::integer) STORED, + "eventType" text GENERATED ALWAYS AS (("eventData" #>> '{type}'::text[])) STORED, + status text GENERATED ALWAYS AS (("eventData" #>> '{data,object,status}'::text[])) STORED, + "customerId" text GENERATED ALWAYS AS (("eventData" #>> '{data,object,customer}'::text[])) STORED, + "customerEmail" text GENERATED ALWAYS AS (("eventData" #>> '{data,object,customer_details,email}'::text[])) STORED, + "subscriptionId" text GENERATED ALWAYS AS ( +CASE + WHEN (("eventData" #>> '{data,object,object}'::text[]) = 'subscription'::text) THEN ("eventData" #>> '{data,object,id}'::text[]) + ELSE ("eventData" #>> '{data,object,subscription}'::text[]) +END) STORED, + "paymentIntent" text GENERATED ALWAYS AS (("eventData" #>> '{data,object,payment_intent}'::text[])) STORED +); + + +-- +-- Name: User; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."User" ( + id text NOT NULL, + "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL, + email text, + image text, + provider text, + username text, + "projectsTags" jsonb DEFAULT '[]'::jsonb NOT NULL +); + + +-- +-- Name: UserProduct; Type: VIEW; Schema: public; Owner: - +-- + +CREATE VIEW public."UserProduct" AS +( SELECT tl."userId", + tl."subscriptionId", + tl."productId", + tl."customerId", + tl."customerEmail" + FROM public."TransactionLog" tl + WHERE ((tl.status = 'complete'::text) AND (tl."eventType" = 'checkout.session.completed'::text) AND (NOT (EXISTS ( SELECT 1 + FROM public."TransactionLog" failed + WHERE ((failed."eventType" = 'checkout.session.async_payment_failed'::text) AND ((failed."eventData" #>> '{data,object,id}'::text[]) = (tl."eventData" #>> '{data,object,id}'::text[])) AND (failed."eventCreated" >= tl."eventCreated"))))) AND (NOT (EXISTS ( SELECT 1 + FROM public."TransactionLog" tlexsists + WHERE ((tlexsists."subscriptionId" = tl."subscriptionId") AND (tlexsists."eventType" = 'customer.subscription.deleted'::text) AND (tlexsists.status = 'canceled'::text) AND (tlexsists."eventCreated" > tl."eventCreated"))))) AND (NOT (EXISTS ( SELECT 1 + FROM public."TransactionLog" tlexsists + WHERE ((tlexsists."paymentIntent" = tl."paymentIntent") AND (tlexsists."eventType" = 'charge.refunded'::text) AND (tlexsists.status = 'succeeded'::text) AND (tlexsists."eventCreated" > tl."eventCreated")))))) + ORDER BY tl."userId", tl."eventCreated" DESC) +UNION ALL + SELECT "TransactionLog"."userId", + "TransactionLog"."subscriptionId", + "TransactionLog"."productId", + "TransactionLog"."customerId", + "TransactionLog"."customerEmail" + FROM public."TransactionLog" + WHERE ("TransactionLog"."eventType" = 'appsumo.activate'::text); + + +-- +-- Name: Workspace; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."Workspace" ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + name text NOT NULL, + "isDefault" boolean DEFAULT false NOT NULL, + "createdAt" timestamp(3) with time zone DEFAULT now() NOT NULL, + "userId" text NOT NULL, + "isDeleted" boolean DEFAULT false NOT NULL +); + + +-- +-- Name: WorkspaceMember; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."WorkspaceMember" ( + "workspaceId" uuid NOT NULL, + "userId" text NOT NULL, + relation public."AuthorizationRelation" DEFAULT 'administrators'::public."AuthorizationRelation" NOT NULL, + "createdAt" timestamp(3) with time zone DEFAULT now() NOT NULL, + "removedAt" timestamp(3) with time zone +); + + +-- +-- Name: WorkspaceProjectAuthorization; Type: VIEW; Schema: public; Owner: - +-- + +CREATE VIEW public."WorkspaceProjectAuthorization" AS + SELECT w."userId", + p.id AS "projectId", + 'own'::text AS relation + FROM (public."Workspace" w + JOIN public."Project" p ON ((p."workspaceId" = w.id))) + WHERE ((w."isDeleted" = false) AND (p."isDeleted" = false)) +UNION ALL + SELECT wm."userId", + p.id AS "projectId", + (wm.relation)::text AS relation + FROM ((public."WorkspaceMember" wm + JOIN public."Workspace" w ON ((w.id = wm."workspaceId"))) + JOIN public."Project" p ON ((p."workspaceId" = wm."workspaceId"))) + WHERE ((wm."removedAt" IS NULL) AND (w."isDeleted" = false) AND (p."isDeleted" = false)); + + +-- +-- Name: _prisma_migrations; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public._prisma_migrations ( + id character varying(36) NOT NULL, + checksum character varying(64) NOT NULL, + finished_at timestamp with time zone, + migration_name character varying(255) NOT NULL, + logs text, + rolled_back_at timestamp with time zone, + started_at timestamp with time zone DEFAULT now() NOT NULL, + applied_steps_count integer DEFAULT 0 NOT NULL +); + + +-- +-- Name: published_builds; Type: VIEW; Schema: public; Owner: - +-- + +CREATE VIEW public.published_builds AS + SELECT build.id AS "buildId", + build."projectId", + build."createdAt", + ( SELECT string_agg(list.value, ', '::text) AS string_agg + FROM jsonb_array_elements_text(((build.deployment)::jsonb -> 'domains'::text)) list(value)) AS domains + FROM public."Build" build + WHERE ((build.deployment IS NOT NULL) AND (build."isCleaned" = false)) + ORDER BY build."projectId", build."createdAt" DESC; + + +-- +-- Name: user_publish_count; Type: VIEW; Schema: public; Owner: - +-- + +CREATE VIEW public.user_publish_count AS + SELECT DISTINCT "Project"."userId" AS user_id, + count(*) AS count + FROM (public."Build" + LEFT JOIN public."Project" ON (("Project".id = "Build"."projectId"))) + WHERE ((date_trunc('day'::text, "Build"."createdAt") = date_trunc('day'::text, now())) AND ("Build".deployment IS NOT NULL)) + GROUP BY "Project"."userId"; + + +-- +-- Name: AssetFileMetadata AssetFileMetadata_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."AssetFileMetadata" + ADD CONSTRAINT "AssetFileMetadata_pkey" PRIMARY KEY ("projectId", "assetId"); + + +-- +-- Name: AssetFolder AssetFolder_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."AssetFolder" + ADD CONSTRAINT "AssetFolder_pkey" PRIMARY KEY (id, "projectId"); + + +-- +-- Name: Asset Asset_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."Asset" + ADD CONSTRAINT "Asset_pkey" PRIMARY KEY (id, "projectId"); + + +-- +-- Name: AuthorizationToken AuthorizationToken_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."AuthorizationToken" + ADD CONSTRAINT "AuthorizationToken_pkey" PRIMARY KEY (token, "projectId"); + + +-- +-- Name: Build Build_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."Build" + ADD CONSTRAINT "Build_pkey" PRIMARY KEY (id, "projectId"); + + +-- +-- Name: ClientReferences ClientReferences_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."ClientReferences" + ADD CONSTRAINT "ClientReferences_pkey" PRIMARY KEY ("userId", service); + + +-- +-- Name: Domain Domain_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."Domain" + ADD CONSTRAINT "Domain_pkey" PRIMARY KEY (id); + + +-- +-- Name: File File_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."File" + ADD CONSTRAINT "File_pkey" PRIMARY KEY (name); + + +-- +-- Name: Notification Notification_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."Notification" + ADD CONSTRAINT "Notification_pkey" PRIMARY KEY (id); + + +-- +-- Name: Product Product_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."Product" + ADD CONSTRAINT "Product_pkey" PRIMARY KEY (id); + + +-- +-- Name: ProjectDomain ProjectDomain_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."ProjectDomain" + ADD CONSTRAINT "ProjectDomain_pkey" PRIMARY KEY ("projectId", "domainId"); + + +-- +-- Name: Project Project_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."Project" + ADD CONSTRAINT "Project_pkey" PRIMARY KEY (id); + + +-- +-- Name: TransactionLog TransactionLog_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."TransactionLog" + ADD CONSTRAINT "TransactionLog_pkey" PRIMARY KEY ("eventId"); + + +-- +-- Name: User User_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."User" + ADD CONSTRAINT "User_pkey" PRIMARY KEY (id); + + +-- +-- Name: WorkspaceMember WorkspaceMember_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."WorkspaceMember" + ADD CONSTRAINT "WorkspaceMember_pkey" PRIMARY KEY ("workspaceId", "userId"); + + +-- +-- Name: Workspace Workspace_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."Workspace" + ADD CONSTRAINT "Workspace_pkey" PRIMARY KEY (id); + + +-- +-- Name: _prisma_migrations _prisma_migrations_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public._prisma_migrations + ADD CONSTRAINT _prisma_migrations_pkey PRIMARY KEY (id); + + +-- +-- Name: domainsVirtual domainsVirtual_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."domainsVirtual" + ADD CONSTRAINT "domainsVirtual_pkey" PRIMARY KEY (id); + + +-- +-- Name: latestBuildVirtual latestBuildVirtual_buildId_key; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."latestBuildVirtual" + ADD CONSTRAINT "latestBuildVirtual_buildId_key" UNIQUE ("buildId"); + + +-- +-- Name: latestBuildVirtual latestBuildVirtual_domainsVirtualId_key; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."latestBuildVirtual" + ADD CONSTRAINT "latestBuildVirtual_domainsVirtualId_key" UNIQUE ("domainsVirtualId"); + + +-- +-- Name: latestBuildVirtual latestBuildVirtual_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."latestBuildVirtual" + ADD CONSTRAINT "latestBuildVirtual_pkey" PRIMARY KEY ("projectId"); + + +-- +-- Name: AssetFolder_projectId_parentId_idx; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX "AssetFolder_projectId_parentId_idx" ON public."AssetFolder" USING btree ("projectId", "parentId"); + + +-- +-- Name: AssetFolder_unique_sibling_name; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "AssetFolder_unique_sibling_name" ON public."AssetFolder" USING btree ("projectId", COALESCE("parentId", ''::text), lower(btrim(name))); + + +-- +-- Name: AuthorizationToken_token_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "AuthorizationToken_token_key" ON public."AuthorizationToken" USING btree (token); + + +-- +-- Name: Build_dev_index; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "Build_dev_index" ON public."Build" USING btree ("projectId") WHERE (deployment IS NULL); + + +-- +-- Name: Build_id_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "Build_id_key" ON public."Build" USING btree (id); + + +-- +-- Name: Build_projectId_createdAt_idx; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX "Build_projectId_createdAt_idx" ON public."Build" USING btree ("projectId", "createdAt" DESC); + + +-- +-- Name: INDEX "Build_projectId_createdAt_idx"; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON INDEX public."Build_projectId_createdAt_idx" IS 'Used to speedup ApprovedMarketplaceProduct view'; + + +-- +-- Name: ClientReferences_reference_service_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "ClientReferences_reference_service_key" ON public."ClientReferences" USING btree (reference, service); + + +-- +-- Name: Domain_domain_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "Domain_domain_key" ON public."Domain" USING btree (domain); + + +-- +-- Name: File_uploaderProjectId_contentHash_extension_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "File_uploaderProjectId_contentHash_extension_key" ON public."File" USING btree ("uploaderProjectId", "contentHash", ( +CASE + WHEN ((strpos(reverse(name), '.'::text) = ANY (ARRAY[0, 1])) OR (((length(name) - strpos(reverse(name), '.'::text)) + 1) = 1)) THEN ''::text + ELSE lower(reverse(split_part(reverse(name), '.'::text, 1))) +END)) WHERE ("contentHash" IS NOT NULL); + + +-- +-- Name: Notification_recipientId_status_idx; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX "Notification_recipientId_status_idx" ON public."Notification" USING btree ("recipientId", status); + + +-- +-- Name: ProjectDomain_domainId_idx; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX "ProjectDomain_domainId_idx" ON public."ProjectDomain" USING btree ("domainId"); + + +-- +-- Name: ProjectDomain_txtRecord_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "ProjectDomain_txtRecord_key" ON public."ProjectDomain" USING btree ("txtRecord"); + + +-- +-- Name: Project_domain_isDeleted_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "Project_domain_isDeleted_key" ON public."Project" USING btree (domain, "isDeleted"); + + +-- +-- Name: Project_domain_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "Project_domain_key" ON public."Project" USING btree (domain); + + +-- +-- Name: Project_id_domain_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "Project_id_domain_key" ON public."Project" USING btree (id, domain); + + +-- +-- Name: Project_id_isDeleted_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "Project_id_isDeleted_key" ON public."Project" USING btree (id, "isDeleted"); + + +-- +-- Name: Project_isDeleted_marketplaceApprovalStatus_idx; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX "Project_isDeleted_marketplaceApprovalStatus_idx" ON public."Project" USING btree ("isDeleted", "marketplaceApprovalStatus"); + + +-- +-- Name: INDEX "Project_isDeleted_marketplaceApprovalStatus_idx"; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON INDEX public."Project_isDeleted_marketplaceApprovalStatus_idx" IS 'Used to speedup ApprovedMarketplaceProduct view'; + + +-- +-- Name: TransactionLog_eventId_productId_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "TransactionLog_eventId_productId_key" ON public."TransactionLog" USING btree ("eventId", "productId"); + + +-- +-- Name: User_email_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "User_email_key" ON public."User" USING btree (email); + + +-- +-- Name: WorkspaceMember_userId_idx; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX "WorkspaceMember_userId_idx" ON public."WorkspaceMember" USING btree ("userId"); + + +-- +-- Name: Workspace_userId_isDefault_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "Workspace_userId_isDefault_key" ON public."Workspace" USING btree ("userId", "isDefault") WHERE ("isDefault" = true); + + +-- +-- Name: AssetFileMetadata AssetFileMetadata_assetId_projectId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."AssetFileMetadata" + ADD CONSTRAINT "AssetFileMetadata_assetId_projectId_fkey" FOREIGN KEY ("assetId", "projectId") REFERENCES public."Asset"(id, "projectId") ON UPDATE CASCADE ON DELETE CASCADE; + + +-- +-- Name: AssetFolder AssetFolder_parentId_projectId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."AssetFolder" + ADD CONSTRAINT "AssetFolder_parentId_projectId_fkey" FOREIGN KEY ("parentId", "projectId") REFERENCES public."AssetFolder"(id, "projectId") ON UPDATE CASCADE; + + +-- +-- Name: AssetFolder AssetFolder_projectId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."AssetFolder" + ADD CONSTRAINT "AssetFolder_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES public."Project"(id) ON UPDATE CASCADE ON DELETE CASCADE; + + +-- +-- Name: Asset Asset_folderId_projectId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."Asset" + ADD CONSTRAINT "Asset_folderId_projectId_fkey" FOREIGN KEY ("folderId", "projectId") REFERENCES public."AssetFolder"(id, "projectId") ON UPDATE CASCADE; + + +-- +-- Name: Asset Asset_name_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."Asset" + ADD CONSTRAINT "Asset_name_fkey" FOREIGN KEY (name) REFERENCES public."File"(name) ON UPDATE CASCADE ON DELETE RESTRICT; + + +-- +-- Name: AuthorizationToken AuthorizationToken_projectId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."AuthorizationToken" + ADD CONSTRAINT "AuthorizationToken_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES public."Project"(id) ON UPDATE CASCADE ON DELETE RESTRICT; + + +-- +-- Name: Build Build_projectId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."Build" + ADD CONSTRAINT "Build_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES public."Project"(id) ON UPDATE CASCADE ON DELETE RESTRICT; + + +-- +-- Name: ClientReferences ClientReferences_userId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."ClientReferences" + ADD CONSTRAINT "ClientReferences_userId_fkey" FOREIGN KEY ("userId") REFERENCES public."User"(id) ON UPDATE CASCADE ON DELETE RESTRICT; + + +-- +-- Name: File File_uploaderProjectId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."File" + ADD CONSTRAINT "File_uploaderProjectId_fkey" FOREIGN KEY ("uploaderProjectId") REFERENCES public."Project"(id) ON UPDATE CASCADE ON DELETE SET NULL; + + +-- +-- Name: ProjectDomain ProjectDomain_domainId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."ProjectDomain" + ADD CONSTRAINT "ProjectDomain_domainId_fkey" FOREIGN KEY ("domainId") REFERENCES public."Domain"(id) ON UPDATE CASCADE ON DELETE RESTRICT; + + +-- +-- Name: ProjectDomain ProjectDomain_projectId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."ProjectDomain" + ADD CONSTRAINT "ProjectDomain_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES public."Project"(id) ON UPDATE CASCADE ON DELETE RESTRICT; + + +-- +-- Name: Project Project_previewImageAssetId_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."Project" + ADD CONSTRAINT "Project_previewImageAssetId_id_fkey" FOREIGN KEY ("previewImageAssetId", id) REFERENCES public."Asset"(id, "projectId") ON UPDATE CASCADE ON DELETE RESTRICT; + + +-- +-- Name: Project Project_userId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."Project" + ADD CONSTRAINT "Project_userId_fkey" FOREIGN KEY ("userId") REFERENCES public."User"(id) ON UPDATE CASCADE ON DELETE SET NULL; + + +-- +-- Name: Project Project_workspaceId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."Project" + ADD CONSTRAINT "Project_workspaceId_fkey" FOREIGN KEY ("workspaceId") REFERENCES public."Workspace"(id) ON UPDATE CASCADE ON DELETE SET NULL; + + +-- +-- Name: TransactionLog TransactionLog_productId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."TransactionLog" + ADD CONSTRAINT "TransactionLog_productId_fkey" FOREIGN KEY ("productId") REFERENCES public."Product"(id) ON UPDATE CASCADE ON DELETE SET NULL; + + +-- +-- Name: TransactionLog TransactionLog_userId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."TransactionLog" + ADD CONSTRAINT "TransactionLog_userId_fkey" FOREIGN KEY ("userId") REFERENCES public."User"(id) ON UPDATE CASCADE ON DELETE SET NULL; + + +-- +-- Name: WorkspaceMember WorkspaceMember_userId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."WorkspaceMember" + ADD CONSTRAINT "WorkspaceMember_userId_fkey" FOREIGN KEY ("userId") REFERENCES public."User"(id) ON UPDATE CASCADE ON DELETE CASCADE; + + +-- +-- Name: WorkspaceMember WorkspaceMember_workspaceId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."WorkspaceMember" + ADD CONSTRAINT "WorkspaceMember_workspaceId_fkey" FOREIGN KEY ("workspaceId") REFERENCES public."Workspace"(id) ON UPDATE CASCADE ON DELETE CASCADE; + + +-- +-- Name: Workspace Workspace_userId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."Workspace" + ADD CONSTRAINT "Workspace_userId_fkey" FOREIGN KEY ("userId") REFERENCES public."User"(id) ON UPDATE CASCADE ON DELETE RESTRICT; + + +-- +-- Name: domainsVirtual domainsVirtual_domainId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."domainsVirtual" + ADD CONSTRAINT "domainsVirtual_domainId_fkey" FOREIGN KEY ("domainId") REFERENCES public."Domain"(id); + + +-- +-- Name: domainsVirtual domainsVirtual_projectId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."domainsVirtual" + ADD CONSTRAINT "domainsVirtual_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES public."Project"(id); + + +-- +-- Name: latestBuildVirtual latestBuildVirtual_buildId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."latestBuildVirtual" + ADD CONSTRAINT "latestBuildVirtual_buildId_fkey" FOREIGN KEY ("buildId") REFERENCES public."Build"(id); + + +-- +-- Name: latestBuildVirtual latestBuildVirtual_domainsVirtualId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."latestBuildVirtual" + ADD CONSTRAINT "latestBuildVirtual_domainsVirtualId_fkey" FOREIGN KEY ("domainsVirtualId") REFERENCES public."domainsVirtual"(id); + + +-- +-- Name: latestBuildVirtual latestBuildVirtual_projectId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."latestBuildVirtual" + ADD CONSTRAINT "latestBuildVirtual_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES public."Project"(id); + + +-- +-- PostgreSQL database dump complete +-- + +\unrestrict webstudioE2ESchema + diff --git a/fixtures/webstudio-cloudflare-template/package.json b/fixtures/webstudio-cloudflare-template/package.json index 8581e6d634..2c859ac2c2 100644 --- a/fixtures/webstudio-cloudflare-template/package.json +++ b/fixtures/webstudio-cloudflare-template/package.json @@ -30,6 +30,7 @@ "dependencies": { "@remix-run/cloudflare": "2.16.5", "@remix-run/cloudflare-pages": "2.16.5", + "@remix-run/dev": "2.16.5", "@remix-run/node": "2.16.5", "@remix-run/react": "2.16.5", "@remix-run/server-runtime": "2.16.5", @@ -49,18 +50,17 @@ "zod": "^4.4.3", "@shikijs/langs": "4.4.1", "@shikijs/themes": "4.4.1", - "shiki": "4.4.1" + "lightningcss": "1.31.1", + "shiki": "4.4.1", + "vite": "^6.3.4", + "wrangler": "4.130.0" }, "devDependencies": { "@cloudflare/workers-types": "^4.20240620.0", - "@remix-run/dev": "2.16.5", "@types/react": "^18.2.70", "@types/react-dom": "^18.2.25", "fast-glob": "^3.3.2", - "typescript": "7.0.2", - "vite": "^6.3.4", - "wrangler": "4.130.0", - "lightningcss": "1.31.1" + "typescript": "7.0.2" }, "devEngines": { "runtime": { diff --git a/fixtures/webstudio-features/package.json b/fixtures/webstudio-features/package.json index 9822ba9e95..15f1920e5f 100644 --- a/fixtures/webstudio-features/package.json +++ b/fixtures/webstudio-features/package.json @@ -42,8 +42,7 @@ "@types/react": "^18.2.70", "@types/react-dom": "^18.2.25", "fast-glob": "^3.3.2", - "typescript": "7.0.2", - "webstudio": "workspace:*" + "typescript": "7.0.2" }, "engines": { "node": ">=22.12.0" diff --git a/packages/cli/src/bin.test.ts b/packages/cli/src/bin.test.ts index ed8c17e122..e80cb80443 100644 --- a/packages/cli/src/bin.test.ts +++ b/packages/cli/src/bin.test.ts @@ -1,6 +1,6 @@ import { spawnSync } from "node:child_process"; import { existsSync } from "node:fs"; -import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; @@ -95,3 +95,34 @@ test("local launcher restores shell cwd when pnpm starts from package directory" await rm(projectRoot, { recursive: true, force: true }); } }, 15_000); + +test("build without a template keeps its existing CLI error", async () => { + const projectRoot = await mkdtemp( + join(tmpdir(), "webstudio-bin-build-test-") + ); + const env: NodeJS.ProcessEnv = { + ...process.env, + PWD: projectRoot, + WEBSTUDIO_CONFIG_DIR: join(projectRoot, "config"), + }; + delete env.NODE_OPTIONS; + delete env.WEBSTUDIO_LOCAL_CLI_BOOTSTRAPPED; + + try { + await mkdir(join(projectRoot, ".webstudio")); + await writeFile(join(projectRoot, ".webstudio", "data.json"), "{}"); + const result = spawnSync(process.execPath, [localPath, "build"], { + cwd: packageRoot, + env, + encoding: "utf-8", + }); + + expect(result.status).toBe(1); + expect(result.stdout + result.stderr).toContain("Template is not provided"); + expect(result.stdout + result.stderr).toContain( + "Please check webstudio --help for more details" + ); + } finally { + await rm(projectRoot, { recursive: true, force: true }); + } +}, 30_000); diff --git a/packages/cli/src/cli.test.ts b/packages/cli/src/cli.test.ts index ff89733556..261ee4282f 100644 --- a/packages/cli/src/cli.test.ts +++ b/packages/cli/src/cli.test.ts @@ -6,6 +6,7 @@ import { cliCommandMetadata, } from "./commands/api-command-metadata"; import { + buildCommandOptions, getTopLevelMcpToolForwardArgs, getTopLevelMcpToolHint, handleOutputStreamError, @@ -101,6 +102,31 @@ const getHelpOutput = async (args: string[]) => { }; describe("registerCommands", () => { + test("build accepts sync flags without requiring a template", async () => { + const output = await getHelpOutput(["build", "--help"]); + + expect(output).toContain("--buildId"); + expect(output).toContain("--origin"); + expect(output).toContain("--authToken"); + expect(output).toContain("--template"); + }); + + test("build requires a template without a build id", async () => { + const cli = (makeCLI() as CommonYargsArgv) + .exitProcess(false) + .command("build", "", buildCommandOptions, () => undefined) + .fail((message, error) => { + throw error ?? new Error(message); + }); + + await expect(async () => cli.parseAsync(["build"])).rejects.toThrow( + "Template is not provided\nPlease check webstudio --help for more details" + ); + await expect( + cli.parseAsync(["build", "--buildId", "build-1"]) + ).resolves.toMatchObject({ buildId: "build-1", template: [] }); + }); + test("exits successfully on broken pipe output errors", () => { const exitProcess = vi.fn((code?: number) => { throw new Error(`exit ${code}`); diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index 3be54c117b..58a5970c4a 100644 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -178,20 +178,20 @@ export const rootCliEpilogue = [ "MCP tool shortcuts are forwarded to mcp single-op-call for shell-driven agents.", ].join("\n"); +export const buildCommandOptions = (yargs: CommonYargsArgv) => + buildOptions(syncOptions(yargs)).check((options) => { + if (options.buildId === undefined && options.template.length === 0) { + return "Template is not provided\nPlease check webstudio --help for more details"; + } + return true; + }); + export const registerCommands = (cmd: CommonYargsArgv) => { - cmd.command( - ["build"], - "Build the project", - (yargs: CommonYargsArgv) => { - return buildOptions(yargs).demandOption( - "template", - "Please specify a template to use for the build" - ); - }, - build - ); + cmd.command(["build"], "Build the project", buildCommandOptions, build); cmd.command(["link"], "Link the project with the cloud", linkOptions, link); - cmd.command(["sync"], "Sync your project", syncOptions, sync); + cmd.command(["sync"], "Sync your project", syncOptions, async (options) => { + await sync(options); + }); cmd.command( ["import"], "Import the synced project bundle into another project", diff --git a/packages/cli/src/commands/build.test.ts b/packages/cli/src/commands/build.test.ts new file mode 100644 index 0000000000..6336ae3940 --- /dev/null +++ b/packages/cli/src/commands/build.test.ts @@ -0,0 +1,129 @@ +import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, expect, test, vi } from "vitest"; +import { build } from "./build"; + +const originalCwd = process.cwd(); +const directories: string[] = []; + +const useSyncedProject = async () => { + const directory = await mkdtemp(join(tmpdir(), "webstudio-build-command-")); + directories.push(directory); + process.chdir(directory); + await mkdir(".webstudio"); + await writeFile(".webstudio/data.json", "{}"); +}; + +afterEach(async () => { + vi.restoreAllMocks(); + process.chdir(originalCwd); + await Promise.all( + directories + .splice(0) + .map((directory) => rm(directory, { recursive: true, force: true })) + ); +}); + +test("syncs before building and expands published static templates", async () => { + await useSyncedProject(); + const order: string[] = []; + const sync = vi.fn(async () => { + order.push("sync"); + return ["ssg-netlify" as const]; + }); + const prebuild = vi.fn(async () => { + order.push("build"); + }); + + await build( + { + assets: true, + template: [], + buildId: "build-1", + origin: "https://example.com", + authToken: "token", + }, + { sync, prebuild } + ); + + expect(order).toEqual(["sync", "build"]); + expect(sync).toHaveBeenCalledWith({ + assets: true, + template: [], + buildId: "build-1", + origin: "https://example.com", + authToken: "token", + }); + expect(prebuild).toHaveBeenCalledWith( + expect.objectContaining({ template: ["ssg", "ssg-netlify"] }) + ); +}); + +test("keeps explicit templates for hosted publishing", async () => { + await useSyncedProject(); + const sync = vi.fn(async () => ["ssg" as const]); + const prebuild = vi.fn(async () => undefined); + + await build( + { assets: false, template: ["internal", "cloudflare"], buildId: "build-1" }, + { sync, prebuild } + ); + + expect(prebuild).toHaveBeenCalledWith( + expect.objectContaining({ template: ["internal", "cloudflare"] }) + ); +}); + +test("does not build if sync fails", async () => { + const failure = new Error("sync failed"); + const sync = vi.fn(async (): Promise => { + throw failure; + }); + const prebuild = vi.fn(async () => undefined); + + await expect( + build( + { assets: true, template: ["ssg"], buildId: "build-1" }, + { sync, prebuild } + ) + ).rejects.toBe(failure); + expect(prebuild).not.toHaveBeenCalled(); +}); + +test("passes missing hosted templates to existing build validation", async () => { + await useSyncedProject(); + const sync = vi.fn(async () => undefined); + const prebuild = vi.fn(async ({ template }: { template: string[] }) => { + if (template.length === 0) { + throw new Error("missing template"); + } + }); + + await expect( + build( + { assets: true, template: [], buildId: "build-1" }, + { sync, prebuild } + ) + ).rejects.toThrow("missing template"); + expect(sync).toHaveBeenCalledOnce(); + expect(prebuild).toHaveBeenCalledWith( + expect.objectContaining({ template: [] }) + ); +}); + +test("builds an already synced project without fetching it again", async () => { + await useSyncedProject(); + const sync = vi.fn(async () => undefined); + const prebuild = vi.fn(async () => undefined); + + await build( + { assets: false, template: ["react-router"] }, + { sync, prebuild } + ); + + expect(sync).not.toHaveBeenCalled(); + expect(prebuild).toHaveBeenCalledWith( + expect.objectContaining({ template: ["react-router"] }) + ); +}); diff --git a/packages/cli/src/commands/build.ts b/packages/cli/src/commands/build.ts index cbc2c8ac0b..7c881cd25f 100644 --- a/packages/cli/src/commands/build.ts +++ b/packages/cli/src/commands/build.ts @@ -12,6 +12,7 @@ import type { StrictYargsOptionsToInterface, } from "./yargs-types"; import { mapToTemplatesFromOptions } from "../build-utils"; +import { sync } from "./sync"; export const buildOptions = (yargs: CommonYargsArgv) => yargs @@ -34,8 +35,22 @@ export const buildOptions = (yargs: CommonYargsArgv) => // @todo: use options.assets to define if we need to download assets export const build = async ( - options: StrictYargsOptionsToInterface + options: StrictYargsOptionsToInterface & { + buildId?: string; + origin?: string; + authToken?: string; + }, + dependencies = { sync, prebuild } ) => { + const syncedTemplates = + options.buildId === undefined + ? undefined + : await dependencies.sync(options); + const templates = + options.template.length > 0 + ? options.template + : mapToTemplatesFromOptions(syncedTemplates ?? []); + try { await access(LOCAL_DATA_FILE); } catch (error: unknown) { @@ -49,5 +64,5 @@ export const build = async ( throw error; } - await prebuild(options); + await dependencies.prebuild({ ...options, template: templates }); }; diff --git a/packages/cli/src/commands/sync.test.ts b/packages/cli/src/commands/sync.test.ts index eb4cde96b1..da0371bc93 100644 --- a/packages/cli/src/commands/sync.test.ts +++ b/packages/cli/src/commands/sync.test.ts @@ -272,10 +272,71 @@ test("downloads project bundle asset files into local project bundle", async () expect(indicator.message).toHaveBeenCalledWith("Downloading 1 asset files"); }); +test("skips asset downloads for a hosted build with assets disabled", async () => { + const assets = [createImageAssetFixture()]; + loadProjectBundleByBuildId.mockResolvedValue( + createProjectBundle({ + assets, + build: { deployment: { destination: "saas", domains: [] } }, + }) + ); + + await sync( + { + assets: false, + authToken: "token-1", + buildId: "build-1", + origin: "https://example.com", + }, + dependencies + ); + + expect(downloadAssetFiles).not.toHaveBeenCalled(); + const data = JSON.parse(await readFile(".webstudio/data.json", "utf8")); + expect(data.assets).toEqual(assets); +}); + +test.each([ + { + name: "static build", + deployment: { + destination: "static" as const, + name: "site.zip", + assetsDomain: "https://assets.example.com", + templates: ["ssg" as const], + }, + }, + { name: "build without a destination", deployment: undefined }, +])( + "downloads non-MDX assets for a $name with assets disabled", + async ({ deployment }) => { + const assets = [createImageAssetFixture()]; + loadProjectBundleByBuildId.mockResolvedValue( + createProjectBundle({ assets, build: { deployment } }) + ); + + await sync( + { + assets: false, + authToken: "token-1", + buildId: "build-1", + origin: "https://example.com", + }, + dependencies + ); + + expect(downloadAssetFiles).toHaveBeenCalledWith({ + assets, + origin: "https://example.com", + }); + } +); + test.each([ { name: "hosted", deployment: { destination: "saas" as const, domains: [] }, + fullContentQuery: false, }, { name: "SSG", @@ -285,10 +346,21 @@ test.each([ assetsDomain: "https://assets.example.com", templates: ["ssg" as const], }, + fullContentQuery: false, + }, + { + name: "build without a destination", + deployment: undefined, + fullContentQuery: false, + }, + { + name: "hosted with a full-content text query", + deployment: { destination: "saas" as const, domains: [] }, + fullContentQuery: true, }, ])( "$name publish sync compiles required MDX articles", - async ({ deployment }) => { + async ({ deployment, fullContentQuery }) => { const source = "# Published from the runner"; const article = { ...createImageAssetFixture(), @@ -300,9 +372,19 @@ test.each([ meta: {}, }; const image = createImageAssetFixture(); + const textAsset = { + ...createImageAssetFixture(), + id: "text", + name: "note.txt", + type: "file" as const, + format: "txt", + size: new TextEncoder().encode("Important note").byteLength, + meta: {}, + }; + const assets = [article, image, ...(fullContentQuery ? [textAsset] : [])]; loadProjectBundleByBuildId.mockResolvedValue( createProjectBundle({ - assets: [article, image], + assets, build: { deployment, instances: [ @@ -345,7 +427,57 @@ test.each([ value: article.id, }, ], + ...(fullContentQuery + ? [ + [ + "text-query-prop", + { + id: "text-query-prop", + instanceId: "root", + name: "text", + type: "resource" as const, + value: "text-query", + }, + ] as [ + string, + { + id: string; + instanceId: string; + name: string; + type: "resource"; + value: string; + }, + ], + ] + : []), ], + resources: fullContentQuery + ? [ + [ + "text-query", + { + id: "text-query", + name: "Text", + control: "system" as const, + method: "post" as const, + url: '"/$resources/assets"', + headers: [], + body: createStructuredAssetQueryResourceBody({ + where: { + field: ["id"], + operator: "eq", + value: '"text"', + }, + sort: [], + limit: "1", + offset: "0", + output: { mode: "all", includeMetadata: true }, + content: { mode: "full" }, + }), + }, + ], + ] + : [], }, }) ); @@ -355,14 +487,19 @@ test.each([ assets.map((asset: { id: string; name: string }) => writeFile( `.webstudio/assets/${asset.name}`, - asset.id === article.id ? source : "image" + asset.id === article.id + ? source + : asset.id === textAsset.id + ? "Important note" + : "image" ) ) ); }); - await sync( + const syncedTemplates = await sync( { + assets: false, authToken: "token-1", buildId: "build-1", origin: "https://example.com", @@ -370,19 +507,32 @@ test.each([ dependencies ); + expect(syncedTemplates).toEqual( + deployment?.destination === "static" ? ["ssg"] : undefined + ); + const data = JSON.parse(await readFile(".webstudio/data.json", "utf8")); expect(downloadAssetFiles).toHaveBeenCalledWith({ - assets: [article, image], + assets: + deployment?.destination === "saas" && !fullContentQuery + ? [article] + : assets, origin: "https://example.com", }); expect(data.assetIndex.documents).toContainEqual( expect.objectContaining({ _id: article.id, extension: "mdx" }) ); + expect(data.assets).toEqual(assets); expect(Object.values(data.assetIndex.contents)).toContain(source); + if (fullContentQuery) { + expect(Object.values(data.assetIndex.contents)).toContain( + "Important note" + ); + } await prebuild({ assets: false, - template: [deployment.destination === "static" ? "ssg" : "react-router"], + template: [deployment?.destination === "static" ? "ssg" : "react-router"], }); const generatedPage = await readFile( "app/__generated__/_index.tsx", @@ -800,11 +950,14 @@ test("syncs current editable data without requiring a published project", async })); const current = createProjectBundle({ - build: { version: 438 }, + build: { + version: 438, + deployment: { destination: "saas", domains: [] }, + }, assets: [createImageAssetFixture()], }); loadCurrentProjectBundle.mockResolvedValue(current); - await sync({}, { ...dependencies, resolveApiConnection }); + await sync({ assets: false }, { ...dependencies, resolveApiConnection }); expect(loadProjectBundleByProjectId).not.toHaveBeenCalled(); expect(loadCurrentProjectBundle).toHaveBeenCalledWith({ authToken: "share-token", @@ -815,6 +968,10 @@ test("syncs current editable data without requiring a published project", async const data = JSON.parse(await readFile(".webstudio/data.json", "utf8")); expect(data.build.version).toBe(438); expect(data.assets).toEqual(current.assets); + expect(downloadAssetFiles).toHaveBeenCalledWith({ + assets: current.assets, + origin: "https://example.com", + }); }); test("explains unpublished project bundle errors when synchronizing by build id", async () => { diff --git a/packages/cli/src/commands/sync.ts b/packages/cli/src/commands/sync.ts index f449fa1d90..5f1ea10dab 100644 --- a/packages/cli/src/commands/sync.ts +++ b/packages/cli/src/commands/sync.ts @@ -49,8 +49,12 @@ import { import { createReachableAssetContentCompilationPlan, getHomePage, + getMimeTypeByFilename, } from "@webstudio-is/sdk"; -import { parseContentDatabaseMaxBytes } from "@webstudio-is/content-engine"; +import { + getDocumentFormatByContentType, + parseContentDatabaseMaxBytes, +} from "@webstudio-is/content-engine"; import { compileContentSource, compileContentUntilPlanIsStable, @@ -154,7 +158,11 @@ export const syncOptions = (yargs: CommonYargsArgv) => describe: "[Experimental] Service token", }); -type SyncOptions = Partial>; +type SyncOptions = Partial< + StrictYargsOptionsToInterface +> & { + assets?: boolean; +}; const unpublishedProjectBundleMessage = [ "The selected build cannot be exported.", @@ -275,13 +283,14 @@ export const sync = async ( }, }); - const createContentSource = () => + const createContentSource = (metadataOnlyNonDocumentAssets = false) => createFileSystemContentSource({ projectId: project.build.projectId, assets: project.assets, folders: new Map( (project.assetFolders ?? []).map((folder) => [folder.id, folder]) ), + metadataOnlyNonDocumentAssets, }); const isStaticBuild = project.build.deployment?.destination === "static"; @@ -307,12 +316,36 @@ export const sync = async ( publicationPlan?.queries.some(({ id }) => id.startsWith("__content-block-mdx__:") ) === true; + const metadataOnlyNonDocumentAssets = + options.assets === false && + options.buildId !== undefined && + project.build.deployment?.destination === "saas" && + needsMdxCompilation && + publicationPlan?.queries.some( + ({ id, content }) => + !id.startsWith("__content-block-mdx__:") && + (content.mode === "full" || content.mode === "range") + ) !== true; const assetsToDownload = - options.buildId !== undefined && !isStaticBuild && !needsMdxCompilation - ? project.assets.filter( - (asset) => asset.format !== "md" && asset.format !== "mdx" - ) - : project.assets; + options.assets === false && + options.buildId !== undefined && + project.build.deployment?.destination === "saas" && + !needsMdxCompilation + ? [] + : metadataOnlyNonDocumentAssets + ? project.assets.filter( + (asset) => + getDocumentFormatByContentType( + getMimeTypeByFilename(asset.name) + ) !== undefined + ) + : options.buildId !== undefined && + !isStaticBuild && + !needsMdxCompilation + ? project.assets.filter( + (asset) => asset.format !== "md" && asset.format !== "mdx" + ) + : project.assets; if (assetsToDownload.length > 0) { syncing.message(`Downloading ${assetsToDownload.length} asset files`); if (project.origin === undefined) { @@ -348,7 +381,7 @@ export const sync = async ( const plan = candidateDiscoveryPlan ?? publicationPlan; if (plan !== undefined) { syncing.message("Preparing local content index"); - const source = createContentSource(); + const source = createContentSource(metadataOnlyNonDocumentAssets); const maxBytes = getPublishedMdxContentDatabaseMaxBytes({ baseBytes: parseContentDatabaseMaxBytes( process.env.CONTENT_DATABASE_MAX_BYTES @@ -423,4 +456,8 @@ export const sync = async ( ? `Project bundle synchronized; AGENTS.md blocked by user-owned file at ${agents.path}. Next: webstudio build` : `Project bundle synchronized successfully (AGENTS.md: ${agents.status}). Next: webstudio build` ); + + return project.build.deployment?.destination === "static" + ? project.build.deployment.templates + : undefined; }; diff --git a/packages/cli/src/filesystem-content-source.test.ts b/packages/cli/src/filesystem-content-source.test.ts index 62f250b87c..0a2202525a 100644 --- a/packages/cli/src/filesystem-content-source.test.ts +++ b/packages/cli/src/filesystem-content-source.test.ts @@ -29,7 +29,7 @@ afterEach(async () => { ); }); -const createAsset = (name: string): Asset => ({ +const createAsset = (name: string): Extract => ({ id: "post", projectId: "project", type: "file", @@ -78,6 +78,125 @@ const plan = createContentCompilationPlan([ ]); describe("filesystem content source", () => { + test("indexes binary metadata without local bytes while reading JSON, Markdown, and MDX", async () => { + const directory = await createTemporaryDirectory(); + const documents = [ + { name: "data.json", format: "json", content: '{"title":"Data"}' }, + { name: "article.md", format: "md", content: "# Markdown" }, + { name: "article.mdx", format: "mdx", content: "# MDX" }, + ]; + const assets: Asset[] = [ + ...documents.map(({ name, format, content }) => ({ + ...createAsset(name), + id: name, + format, + size: new TextEncoder().encode(content).byteLength, + })), + { + ...createAsset("image.png"), + id: "image", + format: "png", + size: 123, + }, + ]; + for (const { name, content } of documents) { + await writeFile(join(directory, name), content); + } + const source = createFileSystemContentSource({ + projectId: "project", + assets, + folders, + assetsDirectory: directory, + metadataOnlyNonDocumentAssets: true, + }); + const snapshot = await source.openSnapshot(); + expect(snapshot.files).toContainEqual( + expect.objectContaining({ + id: "image", + size: 123, + contentType: "image/png", + }) + ); + const documentSources = await snapshot.loadDocumentSources?.(); + expect(documentSources?.map(({ id }) => id)).toEqual( + documents.map(({ name }) => name) + ); + for (const [index, { content }] of documents.entries()) { + expect( + new TextDecoder().decode( + await readBoundedBytes(documentSources?.[index].source ?? "", 100) + ) + ).toBe(content); + } + const metadataPlan = createContentCompilationPlan([ + createLiteralContentCompilationQuery({ + id: "files", + query: { + where: { all: [] }, + sort: [], + limit: 10, + offset: 0, + output: { mode: "all", includeMetadata: true }, + content: { mode: "none" }, + }, + }), + ]); + const { artifact } = await compileContentSource({ + projectId: "project", + source, + plan: metadataPlan, + }); + expect(artifact.documents).toContainEqual( + expect.objectContaining({ + _id: "image", + size: 123, + mimeType: "image/png", + }) + ); + const fullContentPlan = createContentCompilationPlan([ + createLiteralContentCompilationQuery({ + id: "documents", + query: { + where: { + any: ["application/json", "text/markdown", "text/mdx"].map( + (mimeType) => ({ + field: ["mimeType"], + operator: "eq" as const, + value: mimeType, + }) + ), + }, + sort: [], + limit: 10, + offset: 0, + output: { mode: "all", includeMetadata: true }, + content: { mode: "full" }, + }, + }), + ]); + const compiledDocuments = await compileContentSource({ + projectId: "project", + source, + plan: fullContentPlan, + }); + expect(Object.values(compiledDocuments.artifact.contents ?? {})).toEqual( + expect.arrayContaining(documents.map(({ content }) => content)) + ); + }); + + test("rejects unsafe metadata-only asset paths", async () => { + const directory = await createTemporaryDirectory(); + await expect( + createFileSystemContentSource({ + projectId: "project", + assets: [createAsset("../outside.png")], + folders, + assetsDirectory: directory, + metadataOnlyNonDocumentAssets: true, + }).openSnapshot() + ).rejects.toThrow("Asset path escapes"); + }); + test("uses the shared parser and hydrates matching local content", async () => { const directory = await createTemporaryDirectory(); const name = "hello_hash.md"; diff --git a/packages/cli/src/filesystem-content-source.ts b/packages/cli/src/filesystem-content-source.ts index 157423f8a4..46892fcb61 100644 --- a/packages/cli/src/filesystem-content-source.ts +++ b/packages/cli/src/filesystem-content-source.ts @@ -18,6 +18,7 @@ import { } from "@webstudio-is/content-engine"; import { createAssetFolderHierarchy, + createAssetContentRevision, formatAssetName, getFileNameParts, getMimeTypeByFilename, @@ -149,28 +150,50 @@ export const createFileSystemContentSource = ({ assets, folders, assetsDirectory = LOCAL_ASSETS_DIR, + metadataOnlyNonDocumentAssets = false, }: { projectId: string; assets: readonly Asset[]; folders: AssetFolders; assetsDirectory?: string; + metadataOnlyNonDocumentAssets?: boolean; }): ContentSource => ({ openSnapshot: async () => { const hierarchy = createAssetFolderHierarchy(folders); const requestedAssetsDirectoryPath = resolve(assetsDirectory); + const hasLocalFiles = assets.some( + (asset) => + metadataOnlyNonDocumentAssets === false || + getDocumentFormatByContentType(getMimeTypeByFilename(asset.name)) !== + undefined + ); const assetsDirectoryPath = - assets.length === 0 + hasLocalFiles === false ? requestedAssetsDirectoryPath : await realpath(requestedAssetsDirectoryPath); const captured = await Promise.all( assets.map(async (asset) => { + const mimeType = getMimeTypeByFilename(asset.name); + const metadataOnly = + metadataOnlyNonDocumentAssets && + getDocumentFormatByContentType(mimeType) === undefined; const sourcePath = getLocalAssetPath(asset.name, assetsDirectory); - const filePath = await resolveContentFilePath({ - assetsDirectoryPath, - filePath: sourcePath, - }); - const identity = await getFileIdentity(filePath); - const revision = `fs:${serializeFileIdentity(identity)}`; + const filePath = metadataOnly + ? undefined + : await resolveContentFilePath({ + assetsDirectoryPath, + filePath: sourcePath, + }); + const identity = + filePath === undefined ? undefined : await getFileIdentity(filePath); + const revision = + identity === undefined + ? createAssetContentRevision({ + storageName: asset.name, + updatedAt: asset.updatedAt ?? asset.createdAt, + size: asset.size, + }) + : `fs:${serializeFileIdentity(identity)}`; const name = formatAssetName(asset); const extension = getFileNameParts(asset.name).extension.toLowerCase(); const folderId = hierarchy.resolveFolderId(asset.folderId); @@ -192,8 +215,8 @@ export const createFileSystemContentSource = ({ : { description: asset.description }), ...(extension === "" ? {} : { extension }), ...(folderId === undefined ? {} : { folderId, folderNames }), - mimeType: getMimeTypeByFilename(asset.name), - size: Number(identity.size), + mimeType, + size: identity === undefined ? asset.size : Number(identity.size), createdAt: asset.createdAt, revision, contentRef: asset.name, @@ -215,28 +238,35 @@ export const createFileSystemContentSource = ({ revision, files: captured.map(({ entry }) => createContentSourceFile(entry)), loadDocumentSources: async () => - captured - .filter( - ({ entry }) => - getDocumentFormatByContentType(entry.document.mimeType) !== - undefined - ) - .map(({ entry, filePath, identity }) => ({ - id: entry.assetId, - source: { - async *[Symbol.asyncIterator]() { - const bytes = await readSnapshotFile({ - path: filePath, - identity, - maximumBytes: entry.document.size, - }); - if (bytes.byteLength !== entry.document.size) { - throw new Error("Content source file size changed"); - } - yield bytes; + captured.flatMap(({ entry, filePath, identity }) => { + if ( + getDocumentFormatByContentType(entry.document.mimeType) === + undefined + ) { + return []; + } + if (filePath === undefined || identity === undefined) { + throw new Error("Content source document is missing"); + } + return [ + { + id: entry.assetId, + source: { + async *[Symbol.asyncIterator]() { + const bytes = await readSnapshotFile({ + path: filePath, + identity, + maximumBytes: entry.document.size, + }); + if (bytes.byteLength !== entry.document.size) { + throw new Error("Content source file size changed"); + } + yield bytes; + }, }, }, - })), + ]; + }), loadEntries: async ( plan?: ContentCompilationPlan, options?: { maximumContentBytes: number } @@ -261,11 +291,15 @@ export const createFileSystemContentSource = ({ base: entry, requirements, readBytes: (maximumBytes) => - readSnapshotFile({ - path: filePath, - identity, - maximumBytes, - }), + filePath === undefined || identity === undefined + ? Promise.reject( + new Error("Content source file is missing") + ) + : readSnapshotFile({ + path: filePath, + identity, + maximumBytes, + }), }) ) ); @@ -274,7 +308,10 @@ export const createFileSystemContentSource = ({ plan, loadContent: async (entry) => { const capturedFile = capturedById.get(entry.assetId); - if (capturedFile === undefined) { + if ( + capturedFile?.filePath === undefined || + capturedFile.identity === undefined + ) { throw new Error("Content source snapshot is incomplete"); } const bytes = await readSnapshotFile({ @@ -299,7 +336,7 @@ export const createFileSystemContentSource = ({ isCurrent: async () => { try { if ( - assets.length > 0 && + hasLocalFiles && (await realpath(requestedAssetsDirectoryPath)) !== assetsDirectoryPath ) { @@ -309,8 +346,13 @@ export const createFileSystemContentSource = ({ await Promise.all( captured.map( async ({ sourcePath, filePath, identity }) => - (await realpath(sourcePath)) === filePath && - isSameFileIdentity(identity, await getFileIdentity(filePath)) + filePath === undefined || + identity === undefined || + ((await realpath(sourcePath)) === filePath && + isSameFileIdentity( + identity, + await getFileIdentity(filePath) + )) ) ) ).every(Boolean); diff --git a/packages/cli/src/prebuild.test.ts b/packages/cli/src/prebuild.test.ts index 17731da47c..2a5e520c85 100644 --- a/packages/cli/src/prebuild.test.ts +++ b/packages/cli/src/prebuild.test.ts @@ -8473,6 +8473,11 @@ export const createManagedFormResourceFetch = () => { dependencies: { "local-package": "1.0.0", }, + devDependencies: { + "local-package": "1.0.0", + "local-dev-package": "1.0.0", + existing: "2.0.0", + }, }), "utf8" ); @@ -8523,6 +8528,9 @@ export const createManagedFormResourceFetch = () => { expect(packageJson.scripts.local).toEqual("echo local"); expect(packageJson.dependencies.existing).toEqual("1.0.0"); expect(packageJson.dependencies["local-package"]).toEqual("1.0.0"); + expect(packageJson.devDependencies["local-package"]).toBeUndefined(); + expect(packageJson.devDependencies["local-dev-package"]).toEqual("1.0.0"); + expect(packageJson.devDependencies.existing).toEqual("2.0.0"); const tsconfig = JSON.parse(await readFile("tsconfig.json", "utf8")); expect(tsconfig.compilerOptions.strict).toEqual(false); diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.ts index 5ebf98afd1..f57e4e62d3 100644 --- a/packages/cli/src/prebuild.ts +++ b/packages/cli/src/prebuild.ts @@ -565,13 +565,27 @@ const mergeJsonInto = async (sourcePath: string, destinationPath: string) => { throw new Error(error); } ); - const content = JSON.stringify( - merge(JSON.parse(destinationJson), JSON.parse(sourceJson), { + const mergedJson = merge( + JSON.parse(destinationJson), + JSON.parse(sourceJson), + { arrayMerge: (_target, source) => source, - }), - null, - " " + } ); + if (basename(destinationPath) === "package.json") { + const packageJson = mergedJson as { + dependencies?: Record; + devDependencies?: Record; + }; + for (const [dependency, specifier] of Object.entries( + packageJson.dependencies ?? {} + )) { + if (packageJson.devDependencies?.[dependency] === specifier) { + delete packageJson.devDependencies[dependency]; + } + } + } + const content = JSON.stringify(mergedJson, null, " "); await writeFile(destinationPath, content, "utf8"); }; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 063d00e6cb..f288150d6a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1025,6 +1025,9 @@ importers: '@remix-run/cloudflare-pages': specifier: 2.16.5 version: 2.16.5(@cloudflare/workers-types@4.20240701.0)(typescript@7.0.2) + '@remix-run/dev': + specifier: 2.16.5 + version: 2.16.5(patch_hash=yortwzoeu3uj2blmdikhhw5byy)(@remix-run/react@2.16.5(react-dom@18.3.0-canary-14898b6a9-20240318(react@18.3.0-canary-14898b6a9-20240318))(react@18.3.0-canary-14898b6a9-20240318)(typescript@7.0.2))(@remix-run/serve@2.16.5(typescript@7.0.2))(@types/node@22.13.10)(jiti@2.4.2)(lightningcss@1.31.1)(tsx@4.19.3)(typescript@7.0.2)(vite@6.3.4(@types/node@22.13.10)(jiti@2.4.2)(lightningcss@1.31.1)(tsx@4.19.3)(yaml@2.9.0))(wrangler@4.130.0(@cloudflare/workers-types@4.20240701.0))(yaml@2.9.0) '@remix-run/node': specifier: 2.16.5 version: 2.16.5(typescript@7.0.2) @@ -1067,6 +1070,9 @@ importers: isbot: specifier: ^5.1.25 version: 5.1.25 + lightningcss: + specifier: 1.31.1 + version: 1.31.1 react: specifier: 18.3.0-canary-14898b6a9-20240318 version: 18.3.0-canary-14898b6a9-20240318 @@ -1076,12 +1082,18 @@ importers: shiki: specifier: 4.4.1 version: 4.4.1 + vite: + specifier: 6.3.4 + version: 6.3.4(@types/node@22.13.10)(jiti@2.4.2)(lightningcss@1.31.1)(tsx@4.19.3)(yaml@2.9.0) webstudio: specifier: workspace:* version: link:../../packages/cli worktop: specifier: 0.8.0-next.18 version: 0.8.0-next.18 + wrangler: + specifier: 4.130.0 + version: 4.130.0(@cloudflare/workers-types@4.20240701.0) zod: specifier: ^4.4.3 version: 4.4.3 @@ -1089,9 +1101,6 @@ importers: '@cloudflare/workers-types': specifier: ^4.20240620.0 version: 4.20240701.0 - '@remix-run/dev': - specifier: 2.16.5 - version: 2.16.5(patch_hash=yortwzoeu3uj2blmdikhhw5byy)(@remix-run/react@2.16.5(react-dom@18.3.0-canary-14898b6a9-20240318(react@18.3.0-canary-14898b6a9-20240318))(react@18.3.0-canary-14898b6a9-20240318)(typescript@7.0.2))(@remix-run/serve@2.16.5(typescript@7.0.2))(@types/node@22.13.10)(jiti@2.4.2)(lightningcss@1.31.1)(tsx@4.19.3)(typescript@7.0.2)(vite@6.3.4(@types/node@22.13.10)(jiti@2.4.2)(lightningcss@1.31.1)(tsx@4.19.3)(yaml@2.9.0))(wrangler@4.130.0(@cloudflare/workers-types@4.20240701.0))(yaml@2.9.0) '@types/react': specifier: ^18.2.70 version: 18.2.79 @@ -1101,18 +1110,9 @@ importers: fast-glob: specifier: ^3.3.2 version: 3.3.2 - lightningcss: - specifier: 1.31.1 - version: 1.31.1 typescript: specifier: 7.0.2 version: 7.0.2 - vite: - specifier: 6.3.4 - version: 6.3.4(@types/node@22.13.10)(jiti@2.4.2)(lightningcss@1.31.1)(tsx@4.19.3)(yaml@2.9.0) - wrangler: - specifier: 4.130.0 - version: 4.130.0(@cloudflare/workers-types@4.20240701.0) fixtures/webstudio-features: dependencies: