From f30bdb7679eb2d7fcfe283884c1dbb62f7476ccd Mon Sep 17 00:00:00 2001 From: Oleg Isonen Date: Mon, 9 Nov 2026 17:02:11 +0000 Subject: [PATCH] fix: Keep malformed styles from blocking publish (#6665) Malformed saved CSS can stop a site from publishing. This restores Vite's stylesheet pipeline with Lightning CSS and lets publishing continue when generated CSS is invalid. ## What changed - Save validation uses the shared CSS parser for touched declarations and now rejects malformed style state selectors. The CSS editor already reports malformed pasted declarations and omits them from saved styles. - Publish skips older malformed declarations and warns without including their values. - Generated CSS is imported by Remix, React Router, and Vike, so Vite processes the stylesheet and emits its asset. - Before Vite runs, the CLI checks generated CSS with Lightning CSS and esbuild. If the stylesheet cannot build, it warns and uses preset and font CSS; if that also fails, it uses an empty stylesheet. - The domain publish check parses the current project CSS and shows a warning without blocking publish. The parser catches the malformed cases reproduced with Lightning CSS and esbuild; the CLI's compiler check remains the final guard. It skips malformed declarations just as the CLI does. The early check reads assets and generates and parses CSS once more per validation. Content Block styles created during publishing and static template publishing are covered by the CLI fallback, but not by this early warning. - The temporary hashed public stylesheet path and its larger fixture size allowances are removed. The direct PostCSS dependency remains removed. ## Checklist - [x] Restore Vite CSS imports with Lightning CSS in every site template. - [x] Keep malformed CSS from failing publish and warn when fallback CSS is used. - [x] Test the reported escaped property in React Router and Cloudflare Remix builds. - [x] Test malformed CSS recovery in React Router and Vike builds. - [x] Verify the prerendered Vike page links to the generated CSS asset. - [x] Regenerate fixtures and review the diff. - [x] Review documentation impact: the existing publishing guide needs no change for this warning in the publish flow. - [x] Run CLI typecheck, lint, formatting, package boundaries, CLI build, and frozen lockfile check. - [x] Confirm CSS compiler failure cases with focused tests. - [x] Validate CSS-affecting inputs at save, including style states that bypass the editor picker. - [x] Warn in domain pre-publish validation when current project CSS fails compiler checks. - [x] Verify pasted CSS diagnostics and save behavior in the editor. - [x] Review the new diff and rerun relevant tests, typechecks, and Builder build. - [x] Remove the Builder runtime's native Lightning CSS dependency and test the known compiler failure cases with CSS-tree. - [x] Verify staging Builder and CLI workflows for the latest commit. - [ ] Verify a site publish on staging with a project compatible with this branch. The first attempt used a project with a style source type this branch cannot read. - [x] Reject CSS-tree recoverable parse errors in declaration validation and add a regression test. - [x] Keep project-build within its existing package entrypoints and rerun the affected checks. - [x] Monitor required PR checks to completion. ## Verification Local: affected tests, four package typechecks, Builder and CLI builds, root lint, formatting, package boundaries, and frozen lockfile check passed. The fixture pipeline passed for the earlier commit; this commit changes no fixture inputs or outputs. The new invalid-declaration regression test failed when its filter was removed, then passed when restored. The incomplete `rgb()` parser test failed before the review fix and passed afterward. Full css-data and project-build test suites passed. The Builder runtime uses CSS-tree for the early warning because Vercel omitted Lightning CSS's native binary from the deployed function; the CLI still runs Lightning CSS and esbuild during publishing. The replacement staging deployment, fixture checks, both CLI R2 workflows, main workflow, and all required PR checks passed. Staging publish attempt: CLI sync stopped at `build.styleSources[520]` before CSS generation. This branch accepts only `token` and `local` sources; open PR #6663 adds `tagStyle` and the CSS generation it needs. The failing record could not be read directly with the available share token, so the exact saved type remains unconfirmed. Use a project without Tag styles, or test a combined integration branch after an explicit scope decision. Replaces #6662. --------- Co-authored-by: Codex --- .../app/builder/features/publish/publish.tsx | 37 ++- .../advanced/style-block-dialog.test.tsx | 6 + .../app/services/api-router.server.test.ts | 61 ++++ .../builder/app/services/api-router.server.ts | 50 ++- .../services/project-import.server.test.ts | 39 +++ .../app/services/project-import.server.ts | 15 +- fixtures/react-router-cloudflare/package.json | 3 +- .../react-router-cloudflare/vite.config.ts | 1 + fixtures/react-router-docker/package.json | 3 +- fixtures/react-router-docker/vite.config.ts | 1 + fixtures/react-router-netlify/package.json | 3 +- fixtures/react-router-netlify/vite.config.ts | 1 + fixtures/react-router-vercel/package.json | 3 +- fixtures/react-router-vercel/vite.config.ts | 1 + fixtures/ssg-cloudflare-pages/package.json | 3 +- fixtures/ssg-cloudflare-pages/vite.config.ts | 1 + .../ssg-netlify-by-project-id/package.json | 3 +- .../ssg-netlify-by-project-id/vite.config.ts | 1 + .../package.json | 3 +- .../vite.config.ts | 1 + fixtures/webstudio-features/package.json | 3 +- packages/cli/package.json | 1 + packages/cli/src/prebuild.test.ts | 291 ++++++++++++++++++ packages/cli/src/prebuild.ts | 65 +++- .../cli/templates/cloudflare/vite.config.ts | 1 + packages/cli/templates/defaults/package.json | 1 + .../cli/templates/defaults/vite.config.ts | 1 + .../react-router-cloudflare/vite.config.ts | 1 + .../react-router-netlify/vite.config.ts | 1 + .../cli/templates/react-router/package.json | 1 + .../cli/templates/react-router/vite.config.ts | 1 + .../cli/templates/saas-helpers/vite.config.ts | 1 + packages/cli/templates/ssg/package.json | 1 + packages/cli/templates/ssg/vite.config.ts | 1 + packages/css-data/src/parse-css.test.ts | 32 ++ packages/css-data/src/parse-css.ts | 71 +++++ packages/project-build/package.json | 2 +- packages/project-build/src/db/styles.test.ts | 69 +++++ packages/project-build/src/db/styles.ts | 27 ++ packages/project/src/db/build-patch-core.ts | 4 +- packages/project/src/db/build-patch.test.ts | 103 +++++++ pnpm-lock.yaml | 116 +++---- 42 files changed, 940 insertions(+), 90 deletions(-) create mode 100644 packages/project-build/src/db/styles.test.ts diff --git a/apps/builder/app/builder/features/publish/publish.tsx b/apps/builder/app/builder/features/publish/publish.tsx index 05ca9f0f51..73711237d8 100644 --- a/apps/builder/app/builder/features/publish/publish.tsx +++ b/apps/builder/app/builder/features/publish/publish.tsx @@ -266,19 +266,22 @@ const runPublishDiagnostics = async ( projectId: Project["id"], domains?: string[] ) => { + const cssBuildWarningText = + "Some project styles cannot be processed for publishing. Publishing can continue using base and font styles."; const auditFindings = getPrePublishAuditFindings(); - const diagnostics = + const validation = domains === undefined - ? await nativeClient.build.contentDatabasePublishDiagnostics.query({ + ? undefined + : await nativeClient.api.publish.validate.query({ projectId, - }) - : ( - await nativeClient.api.publish.validate.query({ - projectId, - target: "staging", - domains, - }) - ).diagnostics; + target: "staging", + domains, + }); + const diagnostics = + validation?.diagnostics ?? + (await nativeClient.build.contentDatabasePublishDiagnostics.query({ + projectId, + })); const contentFindings = getContentDatabasePublishFindings(diagnostics).map( (finding) => ({ ...finding, @@ -290,7 +293,17 @@ const runPublishDiagnostics = async ( ), }) ); - const findings = [...auditFindings, ...contentFindings]; + const cssWarning = + validation?.cssValid === false + ? [ + { + severity: "warning" as const, + title: cssBuildWarningText, + reportText: cssBuildWarningText, + }, + ] + : []; + const findings = [...auditFindings, ...contentFindings, ...cssWarning]; return { passed: findings.every(({ severity }) => severity !== "error"), findings, @@ -1178,7 +1191,7 @@ const Publish = ({ progress.start(() => runPublishAfterBestEffortChecks({ checks: async () => { - const checks = await runPublishDiagnostics(project.id); + const checks = await runPublishDiagnostics(project.id, domains); diagnostics.setFindings(checks.findings); }, onCheckFailure: (error) => { diff --git a/apps/builder/app/builder/features/style-panel/sections/advanced/style-block-dialog.test.tsx b/apps/builder/app/builder/features/style-panel/sections/advanced/style-block-dialog.test.tsx index 57a9174640..63b7bc6b22 100644 --- a/apps/builder/app/builder/features/style-panel/sections/advanced/style-block-dialog.test.tsx +++ b/apps/builder/app/builder/features/style-panel/sections/advanced/style-block-dialog.test.tsx @@ -275,6 +275,12 @@ test("reports a missing separator at the next declaration", () => { expect(parseBlock("color: red;\nbackground: blue").diagnostics).toEqual([]); }); +test("reports malformed pasted CSS without saving the broken declaration", () => { + const parsed = parseBlock("color: red }"); + expect(parsed.diagnostics.length).toBeGreaterThan(0); + expect(parsed.styleMap.has("color")).toBe(false); +}); + test("Enter adds a separator before a new declaration line", async () => { render( { const loadBuild = vi .spyOn(projectBuild, "loadDevBuildByProjectId") .mockResolvedValue({ + pages: createDefaultPages({ rootInstanceId: "root" }), + breakpoints: [], + styles: [], + styleSourceSelections: [], dataSources: [], props: [], resources: [], instances: [], } as never); + vi.spyOn(assetUploader, "loadAssetDataByProject").mockResolvedValue({ + assets: [], + assetFolders: [], + }); const loadBundle = vi .spyOn(db, "loadProjectBundleByProjectId") .mockResolvedValue(createPublishedProjectBundleFixture()); @@ -1372,6 +1380,7 @@ describe("api router permits", () => { target, domains: expected, diagnostics: { mdxOmissions: [], mdxErrors: [] }, + cssValid: true, }); expect(loadBuild).toHaveBeenCalledWith(expect.anything(), "project-1"); expect(loadBundle).toHaveBeenCalledWith( @@ -1385,6 +1394,58 @@ describe("api router permits", () => { } ); + test("warns before publishing when generated CSS cannot build", async () => { + vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true); + vi.spyOn(authDb, "getTokenInfo").mockResolvedValue( + createToken({ canPublish: true }) + ); + vi.spyOn(projectApi, "loadById").mockResolvedValue({ + domain: "project.wstd.dev", + domainsVirtual: [], + } as never); + const build = createEditableContentBuild(); + build.breakpoints = [{ id: "base", label: "Base" }]; + build.styleSourceSelections = [{ instanceId: "root", values: ["source"] }]; + build.styles = [ + { + styleSourceId: "source", + breakpointId: "base", + state: "/*", + property: "color", + value: { type: "keyword", value: "red" }, + }, + ]; + vi.spyOn(projectBuild, "loadDevBuildByProjectId").mockResolvedValue(build); + vi.spyOn(assetUploader, "loadAssetDataByProject").mockResolvedValue({ + assets: [], + assetFolders: [], + }); + vi.spyOn(db, "loadProjectBundleByProjectId").mockResolvedValue( + createPublishedProjectBundleFixture() + ); + + await expect( + createCaller(createContext(true)).publish.validate({ + projectId: "project-1", + target: "staging", + }) + ).resolves.toMatchObject({ valid: true, cssValid: false }); + build.styles[0].state = ":hover"; + await expect( + createCaller(createContext(true)).publish.validate({ + projectId: "project-1", + target: "staging", + }) + ).resolves.toMatchObject({ valid: true, cssValid: true }); + build.styles[0].value = { type: "unparsed", value: "red }" }; + await expect( + createCaller(createContext(true)).publish.validate({ + projectId: "project-1", + target: "staging", + }) + ).resolves.toMatchObject({ valid: true, cssValid: true }); + }); + test.each( [ [], diff --git a/apps/builder/app/services/api-router.server.ts b/apps/builder/app/services/api-router.server.ts index d327b68af9..968e0d6971 100644 --- a/apps/builder/app/services/api-router.server.ts +++ b/apps/builder/app/services/api-router.server.ts @@ -12,6 +12,8 @@ import { setMarketplaceApprovalStatus, } from "@webstudio-is/project/index.server"; import { loadDevBuildByProjectId } from "@webstudio-is/project-build/server"; +import { hasCssSyntaxError } from "@webstudio-is/css-data"; +import { parseGeneratedStyleDeclaration } from "@webstudio-is/project-build/persistence"; import { singlePlayerVersionMismatchError } from "@webstudio-is/project/build-patch-core.server"; import { createProjectDomain, @@ -62,7 +64,12 @@ import { loadApiToken, } from "./api-permits.server"; import { componentMetas } from "~/shared/component-metas.server"; -import type { Asset, AssetFolder } from "@webstudio-is/sdk"; +import { + generateCss, + getStyleDeclKey, + type Asset, + type AssetFolder, +} from "@webstudio-is/sdk"; import { createContentBlockApplication, type BuilderRuntimeContext, @@ -598,6 +605,44 @@ const loadRuntimeAssetData = async (ctx: AppContext, projectId: string) => { }); }; +const canPublishBuildCss = async (build: CompactBuild, assets: Asset[]) => { + const usedComponents = new Set( + build.instances.map((instance) => instance.component) + ); + const { cssText } = generateCss({ + assets: new Map(assets.map((asset) => [asset.id, asset])), + instances: new Map( + build.instances.map((instance) => [instance.id, instance]) + ), + props: new Map(build.props.map((prop) => [prop.id, prop])), + breakpoints: new Map( + build.breakpoints.map((breakpoint) => [breakpoint.id, breakpoint]) + ), + styles: new Map( + build.styles + .filter( + (style) => parseGeneratedStyleDeclaration(style).errors.length === 0 + ) + .map((style) => [getStyleDeclKey(style), style]) + ), + styleSourceSelections: new Map( + build.styleSourceSelections.map((selection) => [ + selection.instanceId, + selection, + ]) + ), + componentMetas: new Map( + [...componentMetas].filter(([name]) => usedComponents.has(name)) + ), + assetBaseUrl: "", + atomic: + build.projectSettings?.compiler?.atomicStyles ?? + build.pages?.compiler?.atomicStyles ?? + true, + }); + return hasCssSyntaxError(cssText) === false; +}; + const createServerContentBlockApplication = ({ ctx, projectId, @@ -1175,11 +1220,14 @@ export const apiRouter = router({ ctx, { build } ); + const { assets } = await loadRuntimeAssetData(ctx, input.projectId); + const cssValid = await canPublishBuildCss(build, assets); return { valid: true, target: input.target, domains, diagnostics, + cssValid, }; }, { command: "validate-publish", client: "validatePublish" } diff --git a/apps/builder/app/services/project-import.server.test.ts b/apps/builder/app/services/project-import.server.test.ts index e7f6d5e3c3..0891dfccfd 100644 --- a/apps/builder/app/services/project-import.server.test.ts +++ b/apps/builder/app/services/project-import.server.test.ts @@ -301,6 +301,45 @@ describe("build import helpers", () => { ]); }); + test("rejects malformed imported CSS before storing assets or the build", async () => { + const data = createData(); + data.build.styles = [ + [ + "source-1:base:invalid:", + { + styleSourceId: "source-1", + breakpointId: "base", + property: "color", + value: { type: "unparsed", value: "red; width: 10px" }, + }, + ], + ] as never; + + expect(() => + createBuildImportUpdate({ + data, + lastTransactionId: "import-tx", + updatedAt: "2024-02-01T00:00:00.000Z", + version: 4, + }) + ).toThrow(); + + const calls: string[] = []; + await expect( + importPublishedProjectBundle( + { + ctx: { + postgrest: { client: createPostgrestClient(calls) }, + } as never, + data, + projectId: "target-project", + }, + { hasProjectPermit, loadDevBuildByProjectId } + ) + ).rejects.toThrow(); + expect(calls).toEqual([]); + }); + test.each([ { marker: 1, expected: "ResourceForm" }, { marker: undefined, expected: "WebhookForm" }, diff --git a/apps/builder/app/services/project-import.server.ts b/apps/builder/app/services/project-import.server.ts index 3c42781387..fdc9f215a0 100644 --- a/apps/builder/app/services/project-import.server.ts +++ b/apps/builder/app/services/project-import.server.ts @@ -8,6 +8,7 @@ import { serializeData, serializeStyles, serializeStyleSourceSelections, + writableStyles, } from "@webstudio-is/project-build/persistence"; import { createAssetFolderRows, @@ -122,7 +123,7 @@ const createBuildImportUpdate = ({ marketplaceProduct: serializeConfig(data.build.marketplaceProduct), }), breakpoints: serializeData(toMap(data.build.breakpoints)), - styles: serializeStyles(toMap(data.build.styles)), + styles: serializeStyles(writableStyles.parse(toMap(data.build.styles))), styleSources: serializeData(toMap(data.build.styleSources)), styleSourceSelections: serializeStyleSourceSelections( toMap(data.build.styleSourceSelections) @@ -384,6 +385,12 @@ export const importPublishedProjectBundle = async ( const build = await dependencies.loadDevBuildByProjectId(ctx, projectId); const nextVersion = build.version + 1; + const buildUpdate = createBuildImportUpdate({ + data, + lastTransactionId: createId(), + updatedAt: new Date().toISOString(), + version: nextVersion, + }); assertImportedAssets(data.assets); const { assets: normalizedAssets, folders: importedAssetFolders } = @@ -402,12 +409,6 @@ export const importPublishedProjectBundle = async ( assetStore: dependencies.assetStore ?? createAssetClient(), }); } - const buildUpdate = createBuildImportUpdate({ - data, - lastTransactionId: createId(), - updatedAt: new Date().toISOString(), - version: nextVersion, - }); const update = await ctx.postgrest.client .from("Build") .update(buildUpdate, { count: "exact" }) diff --git a/fixtures/react-router-cloudflare/package.json b/fixtures/react-router-cloudflare/package.json index 1c7ad42c22..0fdaf19170 100644 --- a/fixtures/react-router-cloudflare/package.json +++ b/fixtures/react-router-cloudflare/package.json @@ -37,7 +37,8 @@ "@react-router/serve": "^7.5.3", "@shikijs/langs": "4.4.1", "@shikijs/themes": "4.4.1", - "shiki": "4.4.1" + "shiki": "4.4.1", + "lightningcss": "1.31.1" }, "type": "module", "private": true, diff --git a/fixtures/react-router-cloudflare/vite.config.ts b/fixtures/react-router-cloudflare/vite.config.ts index 6d7464d544..028fa040f3 100644 --- a/fixtures/react-router-cloudflare/vite.config.ts +++ b/fixtures/react-router-cloudflare/vite.config.ts @@ -3,6 +3,7 @@ import { cloudflare } from "@cloudflare/vite-plugin"; import { reactRouter } from "@react-router/dev/vite"; export default defineConfig({ + css: { transformer: "lightningcss" }, optimizeDeps: { entries: ["app/root.tsx", "app/routes/**/*.{ts,tsx}"], }, diff --git a/fixtures/react-router-docker/package.json b/fixtures/react-router-docker/package.json index 4a5b442625..4a38752f9e 100644 --- a/fixtures/react-router-docker/package.json +++ b/fixtures/react-router-docker/package.json @@ -33,7 +33,8 @@ "@webstudio-is/wsauth": "workspace:*", "@shikijs/langs": "4.4.1", "@shikijs/themes": "4.4.1", - "shiki": "4.4.1" + "shiki": "4.4.1", + "lightningcss": "1.31.1" }, "private": true, "sideEffects": false, diff --git a/fixtures/react-router-docker/vite.config.ts b/fixtures/react-router-docker/vite.config.ts index 84cd08fb33..d57efc586a 100644 --- a/fixtures/react-router-docker/vite.config.ts +++ b/fixtures/react-router-docker/vite.config.ts @@ -9,6 +9,7 @@ const templateDirectory = fileURLToPath(new URL(".", import.meta.url)); const templateNodeModules = new URL("./node_modules", import.meta.url); export default defineConfig({ + css: { transformer: "lightningcss" }, // Local previews share node_modules, but must not share optimizer state. cacheDir: ".react-router/vite", build: { diff --git a/fixtures/react-router-netlify/package.json b/fixtures/react-router-netlify/package.json index 74955258d0..678efbc7bc 100644 --- a/fixtures/react-router-netlify/package.json +++ b/fixtures/react-router-netlify/package.json @@ -34,7 +34,8 @@ "@react-router/serve": "^7.5.3", "@shikijs/langs": "4.4.1", "@shikijs/themes": "4.4.1", - "shiki": "4.4.1" + "shiki": "4.4.1", + "lightningcss": "1.31.1" }, "type": "module", "private": true, diff --git a/fixtures/react-router-netlify/vite.config.ts b/fixtures/react-router-netlify/vite.config.ts index e0b1e2baf1..f82deba8f4 100644 --- a/fixtures/react-router-netlify/vite.config.ts +++ b/fixtures/react-router-netlify/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from "vite"; import netlifyPlugin from "@netlify/vite-plugin-react-router"; export default defineConfig({ + css: { transformer: "lightningcss" }, optimizeDeps: { entries: ["app/root.tsx", "app/routes/**/*.{ts,tsx}"], }, diff --git a/fixtures/react-router-vercel/package.json b/fixtures/react-router-vercel/package.json index 68ea6cac37..32c9e772d4 100644 --- a/fixtures/react-router-vercel/package.json +++ b/fixtures/react-router-vercel/package.json @@ -34,7 +34,8 @@ "@react-router/serve": "^7.5.3", "@shikijs/langs": "4.4.1", "@shikijs/themes": "4.4.1", - "shiki": "4.4.1" + "shiki": "4.4.1", + "lightningcss": "1.31.1" }, "private": true, "type": "module", diff --git a/fixtures/react-router-vercel/vite.config.ts b/fixtures/react-router-vercel/vite.config.ts index 84cd08fb33..d57efc586a 100644 --- a/fixtures/react-router-vercel/vite.config.ts +++ b/fixtures/react-router-vercel/vite.config.ts @@ -9,6 +9,7 @@ const templateDirectory = fileURLToPath(new URL(".", import.meta.url)); const templateNodeModules = new URL("./node_modules", import.meta.url); export default defineConfig({ + css: { transformer: "lightningcss" }, // Local previews share node_modules, but must not share optimizer state. cacheDir: ".react-router/vite", build: { diff --git a/fixtures/ssg-cloudflare-pages/package.json b/fixtures/ssg-cloudflare-pages/package.json index 8ee3e71374..ec3244e37b 100644 --- a/fixtures/ssg-cloudflare-pages/package.json +++ b/fixtures/ssg-cloudflare-pages/package.json @@ -29,7 +29,8 @@ "@vitejs/plugin-react": "^4.7.0", "typescript": "7.0.2", "vite": "7.1.12", - "webstudio": "workspace:*" + "webstudio": "workspace:*", + "lightningcss": "1.31.1" }, "dependencies": { "@webstudio-is/image": "workspace:*", diff --git a/fixtures/ssg-cloudflare-pages/vite.config.ts b/fixtures/ssg-cloudflare-pages/vite.config.ts index 83d1624d67..fb7a9c3739 100644 --- a/fixtures/ssg-cloudflare-pages/vite.config.ts +++ b/fixtures/ssg-cloudflare-pages/vite.config.ts @@ -6,6 +6,7 @@ const sourceConditions = process.env.WEBSTUDIO_LOCAL_CLI_BOOTSTRAPPED === "1" ? ["webstudio"] : []; export default defineConfig({ + css: { transformer: "lightningcss" }, plugins: [react(), vike()], resolve: { conditions: [...sourceConditions, "browser", "development|production"], diff --git a/fixtures/ssg-netlify-by-project-id/package.json b/fixtures/ssg-netlify-by-project-id/package.json index 87ad06fc74..aca4c51807 100644 --- a/fixtures/ssg-netlify-by-project-id/package.json +++ b/fixtures/ssg-netlify-by-project-id/package.json @@ -29,7 +29,8 @@ "@vitejs/plugin-react": "^4.7.0", "typescript": "7.0.2", "vite": "7.1.12", - "webstudio": "workspace:*" + "webstudio": "workspace:*", + "lightningcss": "1.31.1" }, "dependencies": { "@webstudio-is/image": "workspace:*", diff --git a/fixtures/ssg-netlify-by-project-id/vite.config.ts b/fixtures/ssg-netlify-by-project-id/vite.config.ts index 83d1624d67..fb7a9c3739 100644 --- a/fixtures/ssg-netlify-by-project-id/vite.config.ts +++ b/fixtures/ssg-netlify-by-project-id/vite.config.ts @@ -6,6 +6,7 @@ const sourceConditions = process.env.WEBSTUDIO_LOCAL_CLI_BOOTSTRAPPED === "1" ? ["webstudio"] : []; export default defineConfig({ + css: { transformer: "lightningcss" }, plugins: [react(), vike()], resolve: { conditions: [...sourceConditions, "browser", "development|production"], diff --git a/fixtures/webstudio-cloudflare-template/package.json b/fixtures/webstudio-cloudflare-template/package.json index 3a985081db..8581e6d634 100644 --- a/fixtures/webstudio-cloudflare-template/package.json +++ b/fixtures/webstudio-cloudflare-template/package.json @@ -59,7 +59,8 @@ "fast-glob": "^3.3.2", "typescript": "7.0.2", "vite": "^6.3.4", - "wrangler": "4.130.0" + "wrangler": "4.130.0", + "lightningcss": "1.31.1" }, "devEngines": { "runtime": { diff --git a/fixtures/webstudio-cloudflare-template/vite.config.ts b/fixtures/webstudio-cloudflare-template/vite.config.ts index 938c8bec6f..5f09094251 100644 --- a/fixtures/webstudio-cloudflare-template/vite.config.ts +++ b/fixtures/webstudio-cloudflare-template/vite.config.ts @@ -25,6 +25,7 @@ const conditions = hasPrivateFolders : ["webstudio"]; export default defineConfig(({ mode }) => ({ + css: { transformer: "lightningcss" }, resolve: { conditions: [...conditions, "browser", "development|production"], }, diff --git a/fixtures/webstudio-features/package.json b/fixtures/webstudio-features/package.json index c57fbfea5a..9822ba9e95 100644 --- a/fixtures/webstudio-features/package.json +++ b/fixtures/webstudio-features/package.json @@ -35,7 +35,8 @@ "@react-router/serve": "^7.5.3", "@shikijs/langs": "4.4.1", "@shikijs/themes": "4.4.1", - "shiki": "4.4.1" + "shiki": "4.4.1", + "lightningcss": "1.31.1" }, "devDependencies": { "@types/react": "^18.2.70", diff --git a/packages/cli/package.json b/packages/cli/package.json index 0867cf0ed7..1d76e8f1c5 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -60,6 +60,7 @@ "execa": "^10.0.1", "fast-deep-equal": "^3.1.3", "immer": "^10.1.1", + "lightningcss": "1.31.1", "p-limit": "^6.2.0", "parse5": "7.3.0", "path-key": "^4.0.0", diff --git a/packages/cli/src/prebuild.test.ts b/packages/cli/src/prebuild.test.ts index b8ba3c8c37..75fb7a0545 100644 --- a/packages/cli/src/prebuild.test.ts +++ b/packages/cli/src/prebuild.test.ts @@ -830,6 +830,267 @@ test("hydrates encoded filenames from an embedded SSG database", async () => { }); describe("prebuild", () => { + test.each([true, false])( + "publishes escaped CSS properties through Lightning CSS (atomic: %s)", + async (atomicStyles) => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const siteData = createSiteData(); + siteData.build.pages.compiler = { atomicStyles }; + siteData.build.breakpoints = [ + ["base", { id: "base", label: "Base" }], + ] as never; + siteData.build.styleSources = [ + ["source", { id: "source", type: "local" }], + ] as never; + siteData.build.styleSourceSelections = [ + ["root", { instanceId: "root", values: ["source"] }], + ] as never; + siteData.build.styles = [ + [ + "source:base:invalid:", + { + styleSourceId: "source", + breakpointId: "base", + property: + "--pE--_WitxzZqY_3KruPxn-\\ \\>\\ \\.figma-block-translate", + value: { type: "unparsed", value: "none" }, + }, + ], + [ + "source:base:color:", + { + styleSourceId: "source", + breakpointId: "base", + property: "color", + value: { type: "keyword", value: "red" }, + }, + ], + ] as never; + await writeSiteData(siteData); + + await prebuild({ assets: false, template: ["react-router"] }); + + expect(warn).not.toHaveBeenCalled(); + const css = await readFile("app/__generated__/index.css", "utf8"); + expect(css).toContain("color: red"); + expect(css).toContain("figma-block-translate"); + await symlink(join(originalCwd, "node_modules"), "node_modules", "dir"); + await runGeneratedCommand("react-router", ["build"]); + const cssFiles = (await readdir("build/client/assets")).filter((file) => + file.endsWith(".css") + ); + expect(cssFiles.length).toBeGreaterThan(0); + const bundledCss = await Promise.all( + cssFiles.map((file) => readFile(`build/client/assets/${file}`, "utf8")) + ); + expect( + bundledCss.some((css) => css.includes("figma-block-translate")) + ).toBe(true); + }, + 30_000 + ); + + test.each(["react-router", "ssg"] as const)( + "publishes when a generated CSS rule is malformed (%s)", + async (template) => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const siteData = createSiteData(); + siteData.build.breakpoints = [ + ["base", { id: "base", label: "Base" }], + ] as never; + siteData.build.styleSources = [ + ["source", { id: "source", type: "local" }], + ] as never; + siteData.build.styleSourceSelections = [ + ["root", { instanceId: "root", values: ["source"] }], + ] as never; + siteData.build.styles = [ + [ + "source:base:color:bad-state", + { + styleSourceId: "source", + breakpointId: "base", + state: "/*", + property: "color", + value: { type: "keyword", value: "red" }, + }, + ], + ] as never; + await writeSiteData(siteData); + + await prebuild({ assets: false, template: [template] }); + + expect( + warn.mock.calls.map(([value]) => JSON.parse(String(value))) + ).toContainEqual( + expect.objectContaining({ + type: "webstudio-build-warning", + code: "invalid-generated-css", + severity: "warning", + }) + ); + await symlink(join(originalCwd, "node_modules"), "node_modules", "dir"); + const css = await readFile("app/__generated__/index.css", "utf8"); + expect(css).not.toContain("/*"); + if (template === "ssg") { + await prerenderSsg(); + } else { + await runGeneratedCommand("react-router", ["build"]); + expect( + (await readdir("build/client/assets")).some((file) => + file.endsWith(".css") + ) + ).toBe(true); + } + }, + 60_000 + ); + + test("skips a recovered malformed declaration without dropping valid styles", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const siteData = createSiteData(); + siteData.build.breakpoints = [ + ["base", { id: "base", label: "Base" }], + ] as never; + siteData.build.styleSources = [ + ["source", { id: "source", type: "local" }], + ] as never; + siteData.build.styleSourceSelections = [ + ["root", { instanceId: "root", values: ["source"] }], + ] as never; + siteData.build.styles = [ + [ + "source:base:color:", + { + styleSourceId: "source", + breakpointId: "base", + property: "color", + value: { type: "unparsed", value: "rgb(1, 2, 3" }, + }, + ], + [ + "source:base:backgroundColor:", + { + styleSourceId: "source", + breakpointId: "base", + property: "backgroundColor", + value: { type: "keyword", value: "red" }, + }, + ], + ] as never; + await writeSiteData(siteData); + + await prebuild({ assets: false, template: ["defaults"] }); + + expect(await readFile("app/__generated__/index.css", "utf8")).toContain( + "background-color: red" + ); + expect( + warn.mock.calls.map(([value]) => JSON.parse(String(value)).code) + ).toContain("invalid-css-declaration"); + expect( + warn.mock.calls.map(([value]) => JSON.parse(String(value)).code) + ).not.toContain("invalid-generated-css"); + }); + + test("links generated CSS in prerendered SSG output", async () => { + const siteData = createSiteData(); + siteData.build.breakpoints = [ + ["base", { id: "base", label: "Base" }], + ] as never; + siteData.build.styleSources = [ + ["source", { id: "source", type: "local" }], + ] as never; + siteData.build.styleSourceSelections = [ + ["root", { instanceId: "root", values: ["source"] }], + ] as never; + siteData.build.styles = [ + [ + "source:base:color:", + { + styleSourceId: "source", + breakpointId: "base", + property: "color", + value: { type: "keyword", value: "red" }, + }, + ], + ] as never; + await writeSiteData(siteData); + + await prebuild({ assets: false, template: ["ssg"] }); + await expect( + readFile("app/__generated__/index.css", "utf8") + ).resolves.toContain("color: red"); + await symlink(join(originalCwd, "node_modules"), "node_modules", "dir"); + await prerenderSsg(); + + const html = parseHtml(await readFile("dist/client/index.html", "utf8")); + const stylesheets = findElementsByTagName(html, "link") + .filter((element) => + element.attrs.some( + ({ name, value }) => name === "rel" && value === "stylesheet" + ) + ) + .map( + (element) => element.attrs.find(({ name }) => name === "href")?.value + ); + expect(stylesheets).toHaveLength(1); + const stylesheet = stylesheets[0]; + expect(stylesheet).toMatch(/^\/assets\/static\/.*\.css$/); + await expect( + readFile(`dist/client${stylesheet}`, "utf8") + ).resolves.toContain("red"); + }, 60_000); + + test("builds the Cloudflare Remix site with the escaped property", async () => { + const siteData = createSiteData(); + siteData.build.breakpoints = [ + ["base", { id: "base", label: "Base" }], + ] as never; + siteData.build.styleSources = [ + ["source", { id: "source", type: "local" }], + ] as never; + siteData.build.styleSourceSelections = [ + ["root", { instanceId: "root", values: ["source"] }], + ] as never; + siteData.build.styles = [ + [ + "source:base:escaped:", + { + styleSourceId: "source", + breakpointId: "base", + property: "--pE--_WitxzZqY_3KruPxn-\\ \\>\\ \\.figma-block-translate", + value: { type: "unparsed", value: "none" }, + }, + ], + ] as never; + await writeSiteData(siteData); + await prebuild({ assets: false, template: ["defaults", "cloudflare"] }); + await symlink(join(originalCwd, "node_modules"), "node_modules", "dir"); + const viteConfig = await readFile("vite.config.ts", "utf8"); + await writeFile( + "vite.config.ts", + viteConfig + .replaceAll( + 'conditions: ["browser", "development|production"]', + 'conditions: ["webstudio", "browser", "development|production"]' + ) + .replaceAll( + 'conditions: ["node", "development|production"]', + 'conditions: ["webstudio", "node", "development|production"]' + ) + ); + await runGeneratedCommand("remix", ["vite:build"]); + const cssFiles = (await readdir("build/client/assets")).filter((file) => + file.endsWith(".css") + ); + const bundledCss = await Promise.all( + cssFiles.map((file) => readFile(`build/client/assets/${file}`, "utf8")) + ); + expect( + bundledCss.some((css) => css.includes("figma-block-translate")) + ).toBe(true); + }, 60_000); test.each([true, false])( "imports managed Form formatting only when used (%s)", async (hasErrors) => { @@ -2271,6 +2532,36 @@ describe("prebuild", () => { await expect(readFile("app/routes/custom.tsx", "utf8")).resolves.toBe( "custom" ); + + const oldCss = await readFile("app/__generated__/index.css", "utf8"); + siteData.build.breakpoints = [ + ["base", { id: "base", label: "Base" }], + ] as never; + siteData.build.styleSources = [ + ["source", { id: "source", type: "local" }], + ] as never; + siteData.build.styleSourceSelections = [ + ["root", { instanceId: "root", values: ["source"] }], + ] as never; + siteData.build.styles = [ + [ + "source:base:color:", + { + styleSourceId: "source", + breakpointId: "base", + property: "color", + value: { type: "keyword", value: "red" }, + }, + ], + ] as never; + await writeSiteData(siteData); + await prebuild({ + assets: false, + template: ["react-router"], + incremental: true, + }); + const css = await readFile("app/__generated__/index.css", "utf8"); + expect(css).not.toBe(oldCss); }); test("rejects generated manifests that point outside owned output", async () => { diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.ts index 62b3aca6c9..1636fe1d59 100644 --- a/packages/cli/src/prebuild.ts +++ b/packages/cli/src/prebuild.ts @@ -12,6 +12,8 @@ import { rm, cp, readFile, writeFile, readdir } from "node:fs/promises"; import { cwd, exit } from "node:process"; import { fileURLToPath } from "node:url"; import { parse } from "acorn"; +import { transform as transformCss } from "esbuild"; +import { transform as transformLightningCss } from "lightningcss"; import { log, spinner } from "@clack/prompts"; import merge from "deepmerge"; import deepEqual from "fast-deep-equal"; @@ -81,6 +83,7 @@ import { getZodValidationIssues, createAssetUrlsByPath, } from "@webstudio-is/project-build/runtime"; +import { parseGeneratedStyleDeclaration } from "@webstudio-is/project-build/persistence"; import { createPublishedBuildContentCompilationPlan, getDynamicPublishedMdxSourceBlockIds, @@ -157,9 +160,14 @@ const contentRuntimeBundleUrl = new URL( const contentRuntimeFile = "$resources.asset-query-vendor.js"; const appRoot = "app"; const generatedDir = join(appRoot, "__generated__"); +const generatedCssDir = join("public", "__webstudio", "css"); const sitemapModule = join(generatedDir, "$resources.sitemap.xml"); const routesDir = join(appRoot, "routes"); -const generatedOutputDirectories = [generatedDir, routesDir] as const; +const generatedOutputDirectories = [ + generatedDir, + routesDir, + generatedCssDir, +] as const; type SiteDataByPage = { [id: Page["id"]]: { @@ -1020,6 +1028,9 @@ export const prebuild = async (options: { if (options.incremental !== true) { await rm(routesDir, { recursive: true, force: true }); } + if (options.incremental !== true) { + await rm(generatedCssDir, { recursive: true, force: true }); + } const generatedFiles = new Set(); const previousGeneratedFiles = @@ -1678,12 +1689,29 @@ export const createManagedFormResourceFetch = ({ request, context, projectDomain } } - const { cssText, classes } = generateCss({ + const publishableStyles = new Map(publishedStyles); + for (const [key, style] of publishedStyles) { + if (parseGeneratedStyleDeclaration(style).errors.length === 0) { + continue; + } + publishableStyles.delete(key); + console.warn( + JSON.stringify({ + type: "webstudio-build-warning", + code: "invalid-css-declaration", + severity: "warning", + styleSourceId: style.styleSourceId, + breakpointId: style.breakpointId, + property: style.property, + }) + ); + } + const cssConfig = { instances: publishedInstances, props: publishedProps, assets, breakpoints: publishedBreakpoints, - styles: publishedStyles, + styles: publishableStyles, styleSourceSelections: publishedStyleSourceSelections, // pass only used metas to not generate unused preset styles componentMetas: usedMetas, @@ -1692,9 +1720,34 @@ export const createManagedFormResourceFetch = ({ request, context, projectDomain siteData.build.projectSettings?.compiler.atomicStyles ?? pages.compiler?.atomicStyles ?? true, - }); - - await writeGeneratedFile(join(generatedDir, "index.css"), cssText); + }; + const { cssText, classes } = generateCss(cssConfig); + const canBuildCss = async (css: string) => { + try { + transformLightningCss({ filename: "index.css", code: Buffer.from(css) }); + await transformCss(css, { loader: "css", minify: true }); + return true; + } catch { + return false; + } + }; + let generatedCss = cssText; + if ((await canBuildCss(cssText)) === false) { + const fallbackCss = generateCss({ + ...cssConfig, + styles: new Map(), + }).cssText; + generatedCss = (await canBuildCss(fallbackCss)) ? fallbackCss : ""; + console.warn( + JSON.stringify({ + type: "webstudio-build-warning", + code: "invalid-generated-css", + severity: "warning", + fallback: generatedCss === "" ? "empty" : "presets-and-fonts", + }) + ); + } + await writeGeneratedFile(join(generatedDir, "index.css"), generatedCss); for (const page of generatedPages) { const scope = createScope([ diff --git a/packages/cli/templates/cloudflare/vite.config.ts b/packages/cli/templates/cloudflare/vite.config.ts index 69110f79b1..c8afae308a 100644 --- a/packages/cli/templates/cloudflare/vite.config.ts +++ b/packages/cli/templates/cloudflare/vite.config.ts @@ -5,6 +5,7 @@ import { import { defineConfig } from "vite"; export default defineConfig(({ mode }) => ({ + css: { transformer: "lightningcss" }, plugins: [ // without this, remixCloudflareDevProxy trying to load workerd even for production (it's not needed for production) mode === "production" ? undefined : remixCloudflareDevProxy(), diff --git a/packages/cli/templates/defaults/package.json b/packages/cli/templates/defaults/package.json index ab0f3ef6e1..86c2ed1930 100644 --- a/packages/cli/templates/defaults/package.json +++ b/packages/cli/templates/defaults/package.json @@ -30,6 +30,7 @@ "@remix-run/dev": "2.16.5", "@types/react": "^18.2.70", "@types/react-dom": "^18.2.25", + "lightningcss": "1.31.1", "typescript": "7.0.2", "vite": "^6.3.4" }, diff --git a/packages/cli/templates/defaults/vite.config.ts b/packages/cli/templates/defaults/vite.config.ts index 9cd2d0659a..c3145272be 100644 --- a/packages/cli/templates/defaults/vite.config.ts +++ b/packages/cli/templates/defaults/vite.config.ts @@ -2,6 +2,7 @@ import { defineConfig } from "vite"; import { vitePlugin as remix } from "@remix-run/dev"; export default defineConfig({ + css: { transformer: "lightningcss" }, plugins: [ remix({ future: { diff --git a/packages/cli/templates/react-router-cloudflare/vite.config.ts b/packages/cli/templates/react-router-cloudflare/vite.config.ts index 6d7464d544..028fa040f3 100644 --- a/packages/cli/templates/react-router-cloudflare/vite.config.ts +++ b/packages/cli/templates/react-router-cloudflare/vite.config.ts @@ -3,6 +3,7 @@ import { cloudflare } from "@cloudflare/vite-plugin"; import { reactRouter } from "@react-router/dev/vite"; export default defineConfig({ + css: { transformer: "lightningcss" }, optimizeDeps: { entries: ["app/root.tsx", "app/routes/**/*.{ts,tsx}"], }, diff --git a/packages/cli/templates/react-router-netlify/vite.config.ts b/packages/cli/templates/react-router-netlify/vite.config.ts index e0b1e2baf1..f82deba8f4 100644 --- a/packages/cli/templates/react-router-netlify/vite.config.ts +++ b/packages/cli/templates/react-router-netlify/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from "vite"; import netlifyPlugin from "@netlify/vite-plugin-react-router"; export default defineConfig({ + css: { transformer: "lightningcss" }, optimizeDeps: { entries: ["app/root.tsx", "app/routes/**/*.{ts,tsx}"], }, diff --git a/packages/cli/templates/react-router/package.json b/packages/cli/templates/react-router/package.json index 1de026278d..5860ea22f1 100644 --- a/packages/cli/templates/react-router/package.json +++ b/packages/cli/templates/react-router/package.json @@ -24,6 +24,7 @@ "@webstudio-is/sdk-components-react": "0.0.0-webstudio-version", "@webstudio-is/wsauth": "0.0.0-webstudio-version", "isbot": "^5.1.25", + "lightningcss": "1.31.1", "react": "18.3.0-canary-14898b6a9-20240318", "react-dom": "18.3.0-canary-14898b6a9-20240318", "react-router": "^7.5.3", diff --git a/packages/cli/templates/react-router/vite.config.ts b/packages/cli/templates/react-router/vite.config.ts index 84cd08fb33..d57efc586a 100644 --- a/packages/cli/templates/react-router/vite.config.ts +++ b/packages/cli/templates/react-router/vite.config.ts @@ -9,6 +9,7 @@ const templateDirectory = fileURLToPath(new URL(".", import.meta.url)); const templateNodeModules = new URL("./node_modules", import.meta.url); export default defineConfig({ + css: { transformer: "lightningcss" }, // Local previews share node_modules, but must not share optimizer state. cacheDir: ".react-router/vite", build: { diff --git a/packages/cli/templates/saas-helpers/vite.config.ts b/packages/cli/templates/saas-helpers/vite.config.ts index 938c8bec6f..5f09094251 100644 --- a/packages/cli/templates/saas-helpers/vite.config.ts +++ b/packages/cli/templates/saas-helpers/vite.config.ts @@ -25,6 +25,7 @@ const conditions = hasPrivateFolders : ["webstudio"]; export default defineConfig(({ mode }) => ({ + css: { transformer: "lightningcss" }, resolve: { conditions: [...conditions, "browser", "development|production"], }, diff --git a/packages/cli/templates/ssg/package.json b/packages/cli/templates/ssg/package.json index 1adb4aabba..c270908b6e 100644 --- a/packages/cli/templates/ssg/package.json +++ b/packages/cli/templates/ssg/package.json @@ -26,6 +26,7 @@ "@types/react": "^18.2.70", "@types/react-dom": "^18.2.25", "@vitejs/plugin-react": "^4.7.0", + "lightningcss": "1.31.1", "typescript": "7.0.2", "vite": "7.1.12" }, diff --git a/packages/cli/templates/ssg/vite.config.ts b/packages/cli/templates/ssg/vite.config.ts index 83d1624d67..fb7a9c3739 100644 --- a/packages/cli/templates/ssg/vite.config.ts +++ b/packages/cli/templates/ssg/vite.config.ts @@ -6,6 +6,7 @@ const sourceConditions = process.env.WEBSTUDIO_LOCAL_CLI_BOOTSTRAPPED === "1" ? ["webstudio"] : []; export default defineConfig({ + css: { transformer: "lightningcss" }, plugins: [react(), vike()], resolve: { conditions: [...sourceConditions, "browser", "development|production"], diff --git a/packages/css-data/src/parse-css.test.ts b/packages/css-data/src/parse-css.test.ts index 5df796793a..b4d539e344 100644 --- a/packages/css-data/src/parse-css.test.ts +++ b/packages/css-data/src/parse-css.test.ts @@ -2,12 +2,44 @@ import { describe, expect, test } from "vitest"; import { camelCaseProperty, hasUnsupportedCssTemplateRules, + hasCssSyntaxError, parseClassBasedSelector, parseCss, + parseSingleCssDeclaration, parseMediaQuery, } from "./parse-css"; import { propertyVarTestFixtures } from "./__generated__/property-var-test-fixtures"; +test("single declaration parser rejects CSS that changes the rule structure", () => { + expect( + parseSingleCssDeclaration('content:"a; } b"', "content").errors + ).toEqual([]); + expect( + parseSingleCssDeclaration("color:red; width:10px", "color").errors.length + ).toBeGreaterThan(0); + expect( + parseSingleCssDeclaration("color:red} b{width:10px", "color").errors.length + ).toBeGreaterThan(0); +}); + +test("single declaration parser rejects recovered syntax errors", () => { + expect( + parseSingleCssDeclaration("color:rgb(1, 2, 3", "color").errors.length + ).toBeGreaterThan(0); +}); + +test.each([ + ["", false], + ["a{color:red}", false], + ["/* comment */ @media (min-width: 600px) { a { color: red } }", false], + ["a{--p\\ \\>\\ \\.figma-block-translate:none}", false], + ["a{color:red}}", true], + ["a{color:rgb(1, 2, 3}", true], + ["a{color:red/*}", true], +] as const)("detects stylesheet syntax errors in %s", (css, expected) => { + expect(hasCssSyntaxError(css)).toBe(expected); +}); + describe("Parse CSS", () => { test("flex with a nested calc basis matches explicit longhands", () => { const basis = "calc((100% - var(--space-lg)) / 2)"; diff --git a/packages/css-data/src/parse-css.ts b/packages/css-data/src/parse-css.ts index 2ffaf18898..9a17ec254d 100644 --- a/packages/css-data/src/parse-css.ts +++ b/packages/css-data/src/parse-css.ts @@ -32,6 +32,77 @@ export type ParsedStyleDecl = { value: StyleValue; }; +export const parseSingleCssDeclaration = ( + declarationCss: string, + expectedProperty: string +): { + declaration?: { property: string; value: string }; + errors: string[]; +} => { + let root: csstree.CssNode; + let parseError = false; + try { + root = csstree.parse(`a{${declarationCss}}`, { + onParseError: () => { + parseError = true; + }, + }); + } catch { + return { errors: ["Invalid CSS declaration"] }; + } + if (parseError) { + return { errors: ["Invalid CSS declaration"] }; + } + if (root.type !== "StyleSheet") { + return { errors: ["Expected one CSS rule"] }; + } + const rules = root.children.toArray(); + const rule = rules[0]; + if ( + rules.length !== 1 || + rule?.type !== "Rule" || + csstree.generate(rule.prelude) !== "a" + ) { + return { errors: ["Expected one CSS rule"] }; + } + const declarations = rule.block.children.toArray(); + const declaration = declarations[0]; + if ( + declarations.length !== 1 || + declaration?.type !== "Declaration" || + declaration.property !== expectedProperty + ) { + return { errors: ["Expected one CSS declaration"] }; + } + return { + declaration: { + property: declaration.property, + value: csstree.generate(declaration.value), + }, + errors: [], + }; +}; + +export const hasCssSyntaxError = (css: string): boolean => { + const endRule = ".__webstudio_css_end__{--webstudio-css-end:1}"; + let parseError = false; + try { + const stylesheet = csstree.parse(`${css}\n${endRule}`, { + onParseError: () => { + parseError = true; + }, + }); + const lastRule = stylesheet.children.toArray().at(-1); + return ( + parseError || + lastRule?.type !== "Rule" || + csstree.generate(lastRule) !== endRule + ); + } catch { + return true; + } +}; + export const hasUnsupportedCssTemplateRules = (source: string): boolean => { try { const ast = csstree.parse(source, { context: "declarationList" }); diff --git a/packages/project-build/package.json b/packages/project-build/package.json index 6f95d9b081..a30b492c70 100644 --- a/packages/project-build/package.json +++ b/packages/project-build/package.json @@ -67,8 +67,8 @@ "dependencies": { "@emotion/hash": "^0.9.2", "@modelcontextprotocol/sdk": "^1.10.0", - "@webstudio-is/content-engine": "workspace:*", "@webstudio-is/authorization-token": "workspace:*", + "@webstudio-is/content-engine": "workspace:*", "@webstudio-is/css-data": "workspace:*", "@webstudio-is/css-engine": "workspace:*", "@webstudio-is/expression": "workspace:*", diff --git a/packages/project-build/src/db/styles.test.ts b/packages/project-build/src/db/styles.test.ts new file mode 100644 index 0000000000..b82aac27f1 --- /dev/null +++ b/packages/project-build/src/db/styles.test.ts @@ -0,0 +1,69 @@ +import { expect, test } from "vitest"; +import type { StyleDecl } from "@webstudio-is/sdk"; +import { parseGeneratedStyleDeclaration, writableStyles } from "./styles"; + +const style = (property: string, value = "none"): StyleDecl => ({ + styleSourceId: "source", + breakpointId: "base", + property: property as StyleDecl["property"], + value: { type: "unparsed", value }, +}); + +test("parses CSS emitted from a saved style", () => { + expect( + parseGeneratedStyleDeclaration(style("backgroundColor", "red")) + ).toEqual({ + declaration: { property: "background-color", value: "red" }, + errors: [], + }); + expect( + parseGeneratedStyleDeclaration(style("content", '"a; } b"')).errors + ).toEqual([]); + expect( + parseGeneratedStyleDeclaration(style("color", "red /* comment */")).errors + ).toEqual([]); +}); + +test("accepts escaped CSS properties used in generated stylesheets", () => { + expect( + parseGeneratedStyleDeclaration( + style("--pE--_WitxzZqY_3KruPxn-\\ \\>\\ \\.figma-block-translate") + ).errors + ).toEqual([]); +}); + +test("rejects CSS values that create additional declarations or rules", () => { + for (const [property, value] of [ + ["color", "red; width: 10px"], + ["color", "red } a { width: 10px"], + ["color", "rgb(1, 2, 3"], + ]) { + const result = parseGeneratedStyleDeclaration(style(property, value)); + expect(result.declaration).toBeUndefined(); + expect(result.errors.length).toBeGreaterThan(0); + } +}); + +test("rejects malformed writable style maps", () => { + const invalid = style("color", "red; width: 10px"); + expect( + writableStyles.safeParse(new Map([["invalid", invalid]])).success + ).toBe(false); + expect( + writableStyles.safeParse(new Map([["valid", style("color", "red")]])) + .success + ).toBe(true); +}); + +test("rejects malformed state selectors before saving styles", () => { + expect( + writableStyles.safeParse( + new Map([["invalid", { ...style("color", "red"), state: "/*" }]]) + ).success + ).toBe(false); + expect( + writableStyles.safeParse( + new Map([["valid", { ...style("color", "red"), state: ":hover" }]]) + ).success + ).toBe(true); +}); diff --git a/packages/project-build/src/db/styles.ts b/packages/project-build/src/db/styles.ts index fa9f7d8015..543f5c8f2f 100644 --- a/packages/project-build/src/db/styles.ts +++ b/packages/project-build/src/db/styles.ts @@ -1,9 +1,36 @@ +import { generateStyleMap, hyphenateProperty } from "@webstudio-is/css-engine"; +import { + parseSingleCssDeclaration, + validateSelector, +} from "@webstudio-is/css-data"; import { type Styles, type StyleDecl, getStyleDeclKey, + styles, } from "@webstudio-is/sdk"; +export const parseGeneratedStyleDeclaration = ({ + property, + value, +}: StyleDecl): { + declaration?: { property: string; value: string }; + errors: string[]; +} => { + const declarationCss = generateStyleMap(new Map([[property, value]])); + return parseSingleCssDeclaration(declarationCss, hyphenateProperty(property)); +}; + +export const writableStyles = styles.refine((value) => + Array.from(value.values()).every( + (style) => + parseGeneratedStyleDeclaration(style).errors.length === 0 && + (style.state === undefined || + style.state === "" || + validateSelector(style.state).success) + ) +); + export const parseStyles = (stylesString: string): Styles => { const stylesList = JSON.parse(stylesString) as StyleDecl[]; return new Map(stylesList.map((item) => [getStyleDeclKey(item), item])); diff --git a/packages/project/src/db/build-patch-core.ts b/packages/project/src/db/build-patch-core.ts index 9d8335208b..a6328aed71 100644 --- a/packages/project/src/db/build-patch-core.ts +++ b/packages/project/src/db/build-patch-core.ts @@ -32,7 +32,6 @@ import { styleSources, type StyleSource, type Styles, - styles, getHomePage, } from "@webstudio-is/sdk"; import { @@ -44,6 +43,7 @@ import { findCycles, getPropAssetError, } from "@webstudio-is/project-build/runtime"; +import { writableStyles } from "@webstudio-is/project-build/persistence"; import { parsePages, serializePages, @@ -571,7 +571,7 @@ export const createBuildPatchUpdate = async ({ if (buildData.styles) { const stylesData = buildData.styles; - validateTouchedMap(styles, stylesData, touchedStyles); + validateTouchedMap(writableStyles, stylesData, touchedStyles); update.styles = serializeStyles(stylesData); } diff --git a/packages/project/src/db/build-patch.test.ts b/packages/project/src/db/build-patch.test.ts index 4b30a3196a..719f145a05 100644 --- a/packages/project/src/db/build-patch.test.ts +++ b/packages/project/src/db/build-patch.test.ts @@ -1690,6 +1690,109 @@ describe("patchBuild", () => { ).rejects.toThrow(); }); + test("rejects an invalid style while leaving older invalid styles editable", async () => { + const invalidStyle = { + styleSourceId: "source", + breakpointId: "base", + property: "backgroundColor", + value: { type: "unparsed", value: "red; width: 10px" }, + }; + const build = { ...buildRow, styles: JSON.stringify([invalidStyle]) }; + const input = { + loadAssets: async () => ({ + assets: [], + changedAssetIds: new Set(), + }), + build, + clientVersion: 3, + }; + const validUpdate = await createBuildPatchUpdate({ + ...input, + transactions: [ + transaction({ + payload: [ + { + namespace: "styles", + patches: [ + { + op: "add", + path: ["source:base:color:"], + value: { + ...invalidStyle, + property: "color", + value: { type: "unparsed", value: "red" }, + }, + }, + ], + }, + ], + }), + ], + }); + expect(validUpdate.status).toBe("ok"); + if (validUpdate.status === "ok") { + expect(JSON.parse(validUpdate.update?.styles ?? "")).toHaveLength(2); + } + + await expect( + createBuildPatchUpdate({ + ...input, + transactions: [ + transaction({ + payload: [ + { + namespace: "styles", + patches: [ + { + op: "add", + path: ["source:base:new:"], + value: invalidStyle, + }, + ], + }, + ], + }), + ], + }) + ).rejects.toThrow(); + }); + + test("rejects a malformed state selector while saving a style", async () => { + const build = { ...buildRow, styles: JSON.stringify([]) }; + await expect( + createBuildPatchUpdate({ + build, + clientVersion: 3, + loadAssets: async () => ({ + assets: [], + changedAssetIds: new Set(), + }), + transactions: [ + transaction({ + payload: [ + { + namespace: "styles", + patches: [ + { + op: "add", + path: ["source:base:color:/*"], + value: { + styleSourceId: "source", + breakpointId: "base", + property: "color", + state: "/*", + value: { type: "unparsed", value: "red" }, + }, + }, + ], + }, + ], + }), + ], + }) + ).rejects.toThrow(); + }); + test("validates only touched instances while preserving untouched instances", async () => { const buildWithInvalidUntouchedInstance = { ...buildRow, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 860c92cbe8..e72b6554d5 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -596,6 +596,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 @@ -681,6 +684,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 @@ -760,6 +766,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 @@ -839,6 +848,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 @@ -922,6 +934,9 @@ importers: '@vitejs/plugin-react': specifier: ^4.7.0 version: 4.7.0(vite@7.1.12(@types/node@22.13.10)(jiti@2.4.2)(lightningcss@1.31.1)(tsx@4.19.3)(yaml@2.9.0)) + lightningcss: + specifier: 1.31.1 + version: 1.31.1 typescript: specifier: 7.0.2 version: 7.0.2 @@ -986,6 +1001,9 @@ importers: '@vitejs/plugin-react': specifier: ^4.7.0 version: 4.7.0(vite@7.1.12(@types/node@22.13.10)(jiti@2.4.2)(lightningcss@1.31.1)(tsx@4.19.3)(yaml@2.9.0)) + lightningcss: + specifier: 1.31.1 + version: 1.31.1 typescript: specifier: 7.0.2 version: 7.0.2 @@ -1080,6 +1098,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 @@ -1140,6 +1161,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 @@ -1320,6 +1344,9 @@ importers: immer: specifier: ^10.1.1 version: 10.1.1 + lightningcss: + specifier: 1.31.1 + version: 1.31.1 p-limit: specifier: ^6.2.0 version: 6.2.0 @@ -8708,10 +8735,6 @@ packages: engines: {node: '>=0.10'} hasBin: true - detect-libc@2.0.3: - resolution: {integrity: sha512-bwy0MGW55bG41VqxxypOsdSdGqLwXPI/focwgTYCFMbdUiBAxLg9CFzG08sz2aqzknwiX7Hkl0bQENjg8iLByw==} - engines: {node: '>=8'} - detect-libc@2.1.2: resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} engines: {node: '>=8'} @@ -11165,10 +11188,6 @@ packages: resolution: {integrity: sha512-vuwillviilfKZsg0VGj5R/YwwcHx4SLsIOI/7K6mQkWx+l5cUHTjj5g0AasTBcyXsbfTgrwsUNmVUb5xVwyPwg==} engines: {node: ^10 || ^12 || >=14} - postcss@8.5.3: - resolution: {integrity: sha512-dle9A3yYxlBSrt8Fu+IpjGT8SY8hN0mlaA6GY8t0P5PjIOZemULz/E2Bnm/2dcUOena75OTNkHI76uZBNUUq3A==} - engines: {node: ^10 || ^12 || >=14} - powershell-utils@0.1.0: resolution: {integrity: sha512-dM0jVuXJPsDN6DvRpea484tCUaMiXWjuCn++HGTqUWzGDjv5tZkEZldAJ/UMlqRYGFrD/etByo4/xOuC/snX2A==} engines: {node: '>=20'} @@ -16694,10 +16713,10 @@ snapshots: picocolors: 1.1.1 picomatch: 2.3.1 pidtree: 0.6.0 - postcss: 8.5.3 - postcss-discard-duplicates: 5.1.0(postcss@8.5.3) - postcss-load-config: 4.0.1(postcss@8.5.3) - postcss-modules: 6.0.0(postcss@8.5.3) + postcss: 8.5.16 + postcss-discard-duplicates: 5.1.0(postcss@8.5.16) + postcss-load-config: 4.0.1(postcss@8.5.16) + postcss-modules: 6.0.0(postcss@8.5.16) prettier: 2.8.7 pretty-ms: 7.0.1 react-refresh: 0.14.2 @@ -16777,10 +16796,10 @@ snapshots: picocolors: 1.1.1 picomatch: 2.3.1 pidtree: 0.6.0 - postcss: 8.5.3 - postcss-discard-duplicates: 5.1.0(postcss@8.5.3) - postcss-load-config: 4.0.1(postcss@8.5.3) - postcss-modules: 6.0.0(postcss@8.5.3) + postcss: 8.5.16 + postcss-discard-duplicates: 5.1.0(postcss@8.5.16) + postcss-load-config: 4.0.1(postcss@8.5.16) + postcss-modules: 6.0.0(postcss@8.5.16) prettier: 2.8.7 pretty-ms: 7.0.1 react-refresh: 0.14.2 @@ -16860,10 +16879,10 @@ snapshots: picocolors: 1.1.1 picomatch: 2.3.1 pidtree: 0.6.0 - postcss: 8.5.3 - postcss-discard-duplicates: 5.1.0(postcss@8.5.3) - postcss-load-config: 4.0.1(postcss@8.5.3) - postcss-modules: 6.0.0(postcss@8.5.3) + postcss: 8.5.16 + postcss-discard-duplicates: 5.1.0(postcss@8.5.16) + postcss-load-config: 4.0.1(postcss@8.5.16) + postcss-modules: 6.0.0(postcss@8.5.16) prettier: 2.8.7 pretty-ms: 7.0.1 react-refresh: 0.14.2 @@ -18913,8 +18932,6 @@ snapshots: detect-libc@1.0.3: {} - detect-libc@2.0.3: {} - detect-libc@2.1.2: {} detect-node-es@1.1.0: {} @@ -20113,9 +20130,9 @@ snapshots: dependencies: safer-buffer: 2.1.2 - icss-utils@5.1.0(postcss@8.5.3): + icss-utils@5.1.0(postcss@8.5.16): dependencies: - postcss: 8.5.3 + postcss: 8.5.16 ieee754@1.2.1: {} @@ -20523,7 +20540,6 @@ snapshots: lightningcss-linux-x64-musl: 1.31.1 lightningcss-win32-arm64-msvc: 1.31.1 lightningcss-win32-x64-msvc: 1.31.1 - optional: true lilconfig@2.1.0: {} @@ -22203,48 +22219,48 @@ snapshots: possible-typed-array-names@1.0.0: {} - postcss-discard-duplicates@5.1.0(postcss@8.5.3): + postcss-discard-duplicates@5.1.0(postcss@8.5.16): dependencies: - postcss: 8.5.3 + postcss: 8.5.16 - postcss-load-config@4.0.1(postcss@8.5.3): + postcss-load-config@4.0.1(postcss@8.5.16): dependencies: lilconfig: 2.1.0 yaml: 2.9.0 optionalDependencies: - postcss: 8.5.3 + postcss: 8.5.16 - postcss-modules-extract-imports@3.0.0(postcss@8.5.3): + postcss-modules-extract-imports@3.0.0(postcss@8.5.16): dependencies: - postcss: 8.5.3 + postcss: 8.5.16 - postcss-modules-local-by-default@4.0.0(postcss@8.5.3): + postcss-modules-local-by-default@4.0.0(postcss@8.5.16): dependencies: - icss-utils: 5.1.0(postcss@8.5.3) - postcss: 8.5.3 + icss-utils: 5.1.0(postcss@8.5.16) + postcss: 8.5.16 postcss-selector-parser: 6.0.11 postcss-value-parser: 4.2.0 - postcss-modules-scope@3.0.0(postcss@8.5.3): + postcss-modules-scope@3.0.0(postcss@8.5.16): dependencies: - postcss: 8.5.3 + postcss: 8.5.16 postcss-selector-parser: 6.0.11 - postcss-modules-values@4.0.0(postcss@8.5.3): + postcss-modules-values@4.0.0(postcss@8.5.16): dependencies: - icss-utils: 5.1.0(postcss@8.5.3) - postcss: 8.5.3 + icss-utils: 5.1.0(postcss@8.5.16) + postcss: 8.5.16 - postcss-modules@6.0.0(postcss@8.5.3): + postcss-modules@6.0.0(postcss@8.5.16): dependencies: generic-names: 4.0.0 - icss-utils: 5.1.0(postcss@8.5.3) + icss-utils: 5.1.0(postcss@8.5.16) lodash.camelcase: 4.3.0 - postcss: 8.5.3 - postcss-modules-extract-imports: 3.0.0(postcss@8.5.3) - postcss-modules-local-by-default: 4.0.0(postcss@8.5.3) - postcss-modules-scope: 3.0.0(postcss@8.5.3) - postcss-modules-values: 4.0.0(postcss@8.5.3) + postcss: 8.5.16 + postcss-modules-extract-imports: 3.0.0(postcss@8.5.16) + postcss-modules-local-by-default: 4.0.0(postcss@8.5.16) + postcss-modules-scope: 3.0.0(postcss@8.5.16) + postcss-modules-values: 4.0.0(postcss@8.5.16) string-hash: 1.1.3 postcss-selector-parser@6.0.11: @@ -22265,12 +22281,6 @@ snapshots: picocolors: 1.1.1 source-map-js: 1.2.1 - postcss@8.5.3: - dependencies: - nanoid: 3.3.15 - picocolors: 1.1.1 - source-map-js: 1.2.1 - powershell-utils@0.1.0: {} prettier@2.8.7: {} @@ -22981,7 +22991,7 @@ snapshots: sharp@0.33.5: dependencies: color: 4.2.3 - detect-libc: 2.0.3 + detect-libc: 2.1.2 semver: 7.7.1 optionalDependencies: '@img/sharp-darwin-arm64': 0.33.5