Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion apps/storefront/scripts/bootstrap-performance.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,7 @@ test("intent prefetch warms documents while navigations prefer current deploys",
assert.match(prerenderSource, /stampServiceWorkerVersion\(generatedAt\)/);
});

test("generated static HTML omits the loader and keeps styles render-blocking", () => {
test("generated static HTML keeps critical styles blocking and defers below-the-fold styles", () => {
const html = '<head><link rel="stylesheet" href="/assets/app.css"></head><body><div id="storefront-bootstrap">Loading</div><noscript>fallback</noscript><div id="root">static</div></body>';
const stripped = stripBootstrapOverlay(html);
assert.doesNotMatch(stripped, /storefront-bootstrap/);
Expand All @@ -339,6 +339,9 @@ test("generated static HTML omits the loader and keeps styles render-blocking",
assert.match(prerenderSource, /<style data-wordpress-critical-style=/);
assert.match(prerenderSource, /escapeInlineCss\(staticStyleAsset\.criticalCss\)/);
assert.match(prerenderSource, /<link rel="stylesheet" href=.*data-wordpress-static-style-source=/);
assert.match(prerenderSource, /media="print" data-wordpress-deferred-style/);
assert.match(prerenderSource, /<noscript><link rel="stylesheet" href=/);
assert.match(prerenderSource, /writeStaticWordPressStyleAssets/);
assert.match(prerenderSource, /<link rel="preload" as="style"/);
assert.match(prerenderSource, /const heroSrcSet = decodeAttributeEntities/);
assert.doesNotMatch(prerenderSource, /staticStyleAsset\?\.inlineCss/);
Expand Down
37 changes: 13 additions & 24 deletions apps/storefront/scripts/prerender.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { staticStyleSourceHash } from "../src/lib/staticStyleContract.mjs";
import { withStorefrontEditorPolicy } from "./security-policy.mjs";
import { normalizeStaticShortcodes } from "../src/lib/staticShortcodeMarkup.mjs";
import { addDefaultCmsIconDimensions } from "../src/lib/cmsIconSizing.mjs";
import { localizeStaticFontAssets } from "./static-font-assets.mjs";
import { writeStaticWordPressStyleAssets } from "./static-wordpress-styles.mjs";
import { stripBootstrapOverlay } from "./static-html.mjs";
import { buildStaticRouteRegistryEntries, resolveStaticRouteRegistryPath } from "./static-route-registry.mjs";
import { sanitizeCmsHtml, sanitizeCmsStyleAttribute } from "../src/lib/cmsBehaviors.ts";
Expand Down Expand Up @@ -1961,6 +1961,9 @@ async function renderRoute(route) {
staticStyleAsset
? `<link rel="stylesheet" href="${escapeAttribute(staticStyleAsset.href)}" data-wordpress-static-style-source="${escapeAttribute(staticStyleAsset.sourceHash)}" />`
: "",
staticStyleAsset?.deferredHref
? `<link rel="stylesheet" href="${escapeAttribute(staticStyleAsset.deferredHref)}" media="print" data-wordpress-deferred-style /><noscript><link rel="stylesheet" href="${escapeAttribute(staticStyleAsset.deferredHref)}" /></noscript>`
: "",
staticTheme ? `<style data-storefront-static-theme>${staticTheme}</style>` : "",
`<script type="application/json" id="storefront-static-layout">${serializeStaticLayoutSeed(routeChromeConfig)}</script>`,
routeChromeConfig.paymentGatewayCache.gateways.length
Expand Down Expand Up @@ -2862,37 +2865,23 @@ async function buildStaticStyleAsset(styles) {
stylesheets,
customCss: styles.customCss,
});
const sections = [
const prefixSections = [
sanitizeWordPressFontFaces(styles.fontFaceStyles),
sanitizeWordPressGlobalStyles(styles.globalStyles),
];
for (const stylesheetUrl of stylesheets) {
sections.push(await fetchStaticStylesheet(stylesheetUrl));
prefixSections.push(await fetchStaticStylesheet(stylesheetUrl));
}
sections.push(
styles.customCss,
return writeStaticWordPressStyleAssets({
prefixSections,
suffixSections: [
WORDPRESS_BLOCK_COMPATIBILITY_CSS,
createWordPressElementTypographyCss(styles.globalStyles),
);
const sourceCss = sections.filter((section) => section.trim()).join("\n");
if (!sourceCss) return null;
if (Buffer.byteLength(sourceCss, "utf8") > 1_500_000) {
throw new Error("Combined WordPress static CSS exceeds the 1.5 MB build limit");
}
const localized = await localizeStaticFontAssets(sourceCss, { outputDirectory });
const css = localized.css;

const contentHash = createHash("sha256").update(css).digest("hex").slice(0, 16);
const filename = `wordpress-static-${contentHash}.css`;
await mkdir(resolve(outputDirectory, "assets"), { recursive: true });
await writeFile(resolve(outputDirectory, "assets", filename), `${css}\n`);
return {
href: `/assets/${filename}`,
],
customCss: styles.customCss,
outputDirectory,
sourceHash,
criticalCss: splitCustomCss(styles.customCss).critical,
fontAssets: localized.fontAssets,
preloadAssets: localized.preloadAssets,
};
});
}

async function writeStaticHydrationAsset(label, entries, generatedAt) {
Expand Down
8 changes: 6 additions & 2 deletions apps/storefront/scripts/static-font-assets.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ function defaultFacePreloads(css, fontAssets) {

export async function localizeStaticFontAssets(
css,
{ outputDirectory, fetchImpl = fetch } = {},
{ outputDirectory, fetchImpl = fetch, preloadCss = css } = {},
) {
if (!outputDirectory) throw new Error("A static font output directory is required");
const fontFaceBlocks = [...css.matchAll(FONT_FACE_PATTERN)].map((match) => match[1]);
Expand Down Expand Up @@ -96,9 +96,13 @@ export async function localizeStaticFontAssets(
const href = replacements.get(sourceUrl);
return href ? `url(${quote}${href}${quote})` : match;
});
const localizedPreloadCss = preloadCss.replace(FONT_URL_PATTERN, (match, quote, sourceUrl) => {
const href = replacements.get(sourceUrl);
return href ? `url(${quote}${href}${quote})` : match;
});
return {
css: localizedCss,
fontAssets,
preloadAssets: defaultFacePreloads(localizedCss, fontAssets),
preloadAssets: defaultFacePreloads(localizedPreloadCss, fontAssets),
};
}
31 changes: 31 additions & 0 deletions apps/storefront/scripts/static-font-assets.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,37 @@ test("deduplicates preloads when different font faces share one localized binary
assert.equal(result.preloadAssets.length, 1);
});

test("preloads critical fonts without pulling deferred-only fonts into the initial page", async () => {
const outputDirectory = await mkdtemp(join(tmpdir(), "storefront-fonts-"));
temporaryDirectories.push(outputDirectory);
const css = `
@font-face{font-family:"Critical";font-style:normal;font-weight:400;src:url("https://cms.test/critical.woff2") format("woff2")}
@font-face{font-family:"Deferred";font-style:normal;font-weight:400;src:url("https://cms.test/deferred.woff2") format("woff2")}
`;
const criticalCss = css.split('@font-face{font-family:"Deferred"')[0];
const result = await localizeStaticFontAssets(css, {
outputDirectory,
preloadCss: criticalCss,
fetchImpl: async (url) => new Response(
Buffer.concat([Buffer.from("wOF2"), Buffer.alloc(28, url.endsWith("deferred.woff2") ? 8 : 7)]),
{ headers: { "content-type": "font/woff2" } },
),
});

assert.equal(result.fontAssets.length, 2);
assert.equal(result.preloadAssets.length, 1);
const [localizedCriticalHref] = result.css
.split('@font-face{font-family:"Deferred"')[0]
.match(/url\("([^"]+)"/)
.slice(1);
const [localizedDeferredHref] = result.css
.split('@font-face{font-family:"Deferred"')[1]
.match(/url\("([^"]+)"/)
.slice(1);
assert.equal(result.preloadAssets[0].href, localizedCriticalHref);
assert.notEqual(result.preloadAssets[0].href, localizedDeferredHref);
});

test("rejects non-font responses instead of publishing untrusted bytes", async () => {
const outputDirectory = await mkdtemp(join(tmpdir(), "storefront-fonts-"));
temporaryDirectories.push(outputDirectory);
Expand Down
62 changes: 62 additions & 0 deletions apps/storefront/scripts/static-wordpress-styles.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { createHash } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import { resolve } from "node:path";
import { splitCustomCss } from "../src/lib/customCssLayers.mjs";
import { localizeStaticFontAssets } from "./static-font-assets.mjs";

export async function writeStaticWordPressStyleAssets({
prefixSections,
suffixSections,
customCss,
outputDirectory,
sourceHash,
}) {
const layers = splitCustomCss(customCss);
const criticalSections = [
...prefixSections,
layers.critical,
...suffixSections,
].filter((section) => section.trim());
const criticalSourceCss = criticalSections.join("\n");
const deferredSourceCss = layers.deferred.trim()
? `/* storefront:deferred */\n${layers.deferred}`
: "";
const sourceCss = [criticalSourceCss, deferredSourceCss].filter(Boolean).join("\n");
if (!sourceCss) return null;
if (Buffer.byteLength(sourceCss, "utf8") > 1_500_000) {
throw new Error("Combined WordPress static CSS exceeds the 1.5 MB build limit");
}

const localized = await localizeStaticFontAssets(sourceCss, {
outputDirectory,
preloadCss: criticalSourceCss,
});
const localizedLayers = splitCustomCss(localized.css);
const criticalHash = createHash("sha256").update(localizedLayers.critical).digest("hex").slice(0, 16);
const criticalFilename = `wordpress-static-${criticalHash}.css`;
await mkdir(resolve(outputDirectory, "assets"), { recursive: true });
await writeFile(
resolve(outputDirectory, "assets", criticalFilename),
`${localizedLayers.critical}\n`,
);

let deferredHref = "";
if (localizedLayers.deferred.trim()) {
const deferredHash = createHash("sha256").update(localizedLayers.deferred).digest("hex").slice(0, 16);
const deferredFilename = `wordpress-deferred-${deferredHash}.css`;
await writeFile(
resolve(outputDirectory, "assets", deferredFilename),
`${localizedLayers.deferred}\n`,
);
deferredHref = `/assets/${deferredFilename}`;
}

return {
href: `/assets/${criticalFilename}`,
deferredHref,
sourceHash,
criticalCss: layers.critical,
fontAssets: localized.fontAssets,
preloadAssets: localized.preloadAssets,
};
}
51 changes: 51 additions & 0 deletions apps/storefront/scripts/static-wordpress-styles.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import assert from "node:assert/strict";
import { mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, test } from "node:test";
import { writeStaticWordPressStyleAssets } from "./static-wordpress-styles.mjs";

const temporaryDirectories = [];

afterEach(async () => {
await Promise.all(temporaryDirectories.splice(0).map((directory) => rm(directory, { recursive: true })));
});

test("writes deferred custom CSS separately from the critical static stylesheet", async () => {
const outputDirectory = await mkdtemp(join(tmpdir(), "storefront-static-css-"));
temporaryDirectories.push(outputDirectory);
const result = await writeStaticWordPressStyleAssets({
prefixSections: [".global { color: black; }"],
suffixSections: [".wp-block { display: block; }"],
customCss: ".hero { color: red; }\n/* storefront:deferred */\n.below-fold { color: blue; }",
outputDirectory,
sourceHash: "source-hash",
});

assert.ok(result);
assert.equal(result.sourceHash, "source-hash");
assert.match(result.deferredHref, /^\/assets\/wordpress-deferred-[a-f0-9]{16}\.css$/);
const criticalCss = await readFile(join(outputDirectory, result.href), "utf8");
const deferredCss = await readFile(join(outputDirectory, result.deferredHref), "utf8");
assert.match(criticalCss, /\.hero/);
assert.match(criticalCss, /\.wp-block/);
assert.doesNotMatch(criticalCss, /\.below-fold/);
assert.match(deferredCss, /\.below-fold/);
assert.doesNotMatch(deferredCss, /\.hero/);
});

test("keeps all custom CSS critical when no deferred marker is present", async () => {
const outputDirectory = await mkdtemp(join(tmpdir(), "storefront-static-css-"));
temporaryDirectories.push(outputDirectory);
const result = await writeStaticWordPressStyleAssets({
prefixSections: [],
suffixSections: [],
customCss: ".page { color: red; }",
outputDirectory,
sourceHash: "source-hash",
});

assert.ok(result);
assert.equal(result.deferredHref, "");
assert.match(await readFile(join(outputDirectory, result.href), "utf8"), /\.page/);
});
Loading