Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
14 commits
Select commit Hold shift + click to select a range
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
22 changes: 22 additions & 0 deletions packages/cli/src/utils/publishProject.cssUrls.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { describe, expect, it } from "vitest";
import { rewriteCssUrls } from "./publishProject.js";

describe("publish CSS url rewriting", () => {
it("rewrites the urls a resolver claims", () => {
const css = `a{background:url( "img/a.png" )} b{background:url(b.png)}`;
const out = rewriteCssUrls(css, "/p", "index.html", (url) =>
url === "b.png" ? "assets/b.png" : null,
);
expect(out).toEqual({
css: `a{background:url( "img/a.png" )} b{background:url(assets/b.png)}`,
modified: true,
});
});

it("scans 1 MB of unclosed url( in well under a second", () => {
const css = "url(".repeat(250_000);
const started = performance.now();
expect(rewriteCssUrls(css, "/p", "index.html", () => null)).toEqual({ css, modified: false });
expect(performance.now() - started).toBeLessThan(1000);
});
});
5 changes: 3 additions & 2 deletions packages/cli/src/utils/publishProject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ import { parseHTML } from "linkedom";
import AdmZip from "adm-zip";
import type { Ignore } from "ignore";
import { projectIgnore } from "@hyperframes/lint";
import { CSS_URL_RE, isNonRelativeUrl, isPathInside, rewriteSrcsetUrls } from "@hyperframes/core";
import { isNonRelativeUrl, isPathInside, rewriteSrcsetUrls } from "@hyperframes/core";
import { cssUrlMatches, replaceMatches } from "@hyperframes/parsers/css-url-scans";
import { decodeUrlPathVariants, encodeUrlPath } from "@hyperframes/parsers";
import { buildAuthHeaders } from "../auth/client.js";
import { tryResolveCredential } from "../auth/index.js";
Expand Down Expand Up @@ -559,7 +560,7 @@ export function rewriteCssUrls(
resolveTarget: HtmlAttributeResolver,
): { css: string; modified: boolean } {
let modified = false;
const rewritten = css.replace(CSS_URL_RE, (full, quote: string, rawUrl: string) => {
const rewritten = replaceMatches(css, cssUrlMatches(css), (full, quote, rawUrl) => {
const target = resolveTarget((rawUrl || "").trim(), referrerAbsDir);
if (!target) return full;
modified = true;
Expand Down
106 changes: 106 additions & 0 deletions packages/core/src/compiler/htmlBundler.cssComments.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { bundleToSingleHtml, restoreCssPlaceholders } from "./htmlBundler";

async function bundleWithStylesheet(css: string, imported = ""): Promise<string> {
const dir = mkdtempSync(join(tmpdir(), "hf-css-comments-"));
try {
writeFileSync(join(dir, "style.css"), css);
writeFileSync(join(dir, "part.css"), imported);
writeFileSync(
join(dir, "index.html"),
'<html><head><link rel="stylesheet" href="style.css"></head><body><main data-composition-id="root" data-width="320" data-height="180"></main></body></html>',
);
return await bundleToSingleHtml(dir, { runtime: "placeholder" });
} finally {
rmSync(dir, { recursive: true, force: true });
}
}

describe("stylesheet comments in the bundle", () => {
it("keep their text verbatim, replacement patterns included", async () => {
const css = "/* $' $& $$ */ .a { color: red } /* b */";
expect(await bundleWithStylesheet(css)).toContain(css);
});

it("bundle 400 KB of comments and unclosed comment openers in well under two seconds", async () => {
const css = "/**/".repeat(50_000) + "/* ".repeat(66_000);
const started = performance.now();
expect(await bundleWithStylesheet(css)).toContain("/**//**/");
expect(performance.now() - started).toBeLessThan(2000);
});

it("inline imported stylesheets verbatim, replacement patterns included", async () => {
const part = '.b { content: "$\' $&" }';
expect(await bundleWithStylesheet('@import "part.css"; .a { color: red }', part)).toContain(
part,
);
});

it("inline every import of a sheet imported many times", async () => {
const css = '@import "part.css"; '.repeat(50);
expect((await bundleWithStylesheet(css, ".b{}")).split(".b{}")).toHaveLength(51);
});
});

/** The restore it replaces: each comment, then each import, swapped in at its first occurrence. */
function sequentialRestore(css: string, comments: string[], imports: string[]): string {
let out = css;
comments.forEach((text, i) => (out = out.replace(`/*__hf_c${i}__*/`, text)));
imports.forEach((text, i) => {
out = out.replace(`/*__hf_import_${comments.length + i}__*/`, text);
});
return out;
}

const PIECES = [
"a",
" ",
"{",
"}",
";",
"/*",
"*/",
"/**/",
"url(x)",
"\n",
"@media x {",
"_hf_",
"c1",
];

describe("CSS placeholder restore", () => {
it("puts back what the sequential restore put back on 20,000 generated sheets", () => {
let seed = 3;
const next = (n: number) =>
Math.floor(((seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648) * n);
const text = () => Array.from({ length: next(6) }, () => PIECES[next(PIECES.length)]).join("");
const differences: string[] = [];
for (let run = 0; run < 20_000; run++) {
const comments = Array.from({ length: next(4) }, () => `/*${text()}*/`);
const imports = Array.from({ length: next(4) }, text);
const placeholders = new Map<string, string>();
comments.forEach((c, i) => placeholders.set(`/*__hf_c${i}__*/`, c));
imports.forEach((c, i) => placeholders.set(`/*__hf_import_${comments.length + i}__*/`, c));
const keys = [...placeholders.keys()].sort(() => next(2) - 0.5);
const css = keys.map((key) => text() + key).join("") + text();
if (restoreCssPlaceholders(css, placeholders) !== sequentialRestore(css, comments, imports))
differences.push(css);
}
expect(differences).toEqual([]);
});

it("puts back 20,000 placeholders of 200 bytes each in well under a second", () => {
const placeholders = new Map<string, string>();
for (let i = 0; i < 20_000; i++)
placeholders.set(`/*__hf_import_${i}__*/`, `.b{}/*${"x".repeat(192)}*/`);
const css = [...placeholders.keys()].join(" ");
const started = performance.now();
expect(restoreCssPlaceholders(css, placeholders)).toHaveLength(
css.length - [...placeholders.keys()].join("").length + 20_000 * 200,
);
expect(performance.now() - started).toBeLessThan(1000);
});
});
91 changes: 43 additions & 48 deletions packages/core/src/compiler/htmlBundler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,14 @@ import {
decodedUrlPath,
splitUrlSuffix,
} from "@hyperframes/parsers/asset-paths";
import { CSS_URL_RE, isNonRelativeUrl } from "./assetPaths.js";
import {
blockCommentMatches,
cssImportMatches,
cssUrlMatches,
rawCssUrlMatches,
replaceMatches,
} from "@hyperframes/parsers/css-url-scans";
import { isNonRelativeUrl } from "./assetPaths.js";
import { rewriteSrcsetUrls } from "./srcset.js";
import { compileHtml, type MediaDurationProber } from "./htmlCompiler";
import {
Expand Down Expand Up @@ -146,30 +153,20 @@ function safeReadFile(filePath: string): string | null {
}
}

const CSS_IMPORT_RE =
/@import\s+(?:url\(\s*(["']?)([^)"']+)\1\s*\)|(["'])([^"']+)\3)\s*([^;]*);\s*/g;
const CSS_PLACEHOLDER_RE = /\/\*__hf_(?:c|import_)\d+__\*\//g;

const CSS_COMMENT_RE = /\/\*[\s\S]*?\*\//g;
export function restoreCssPlaceholders(css: string, texts: ReadonlyMap<string, string>): string {
return css.replace(CSS_PLACEHOLDER_RE, (placeholder) => texts.get(placeholder) ?? placeholder);
}

function withCommentsStripped<T>(
css: string,
fn: (stripped: string) => T,
): { result: T; restore: (s: string) => string } {
const comments: string[] = [];
const stripped = css.replace(CSS_COMMENT_RE, (m) => {
const idx = comments.length;
comments.push(m);
return `/*__hf_c${idx}__*/`;
function withCommentsStripped(css: string): { stripped: string; comments: Map<string, string> } {
const comments = new Map<string, string>();
const stripped = replaceMatches(css, blockCommentMatches(css), (m) => {
const placeholder = `/*__hf_c${comments.size}__*/`;
comments.set(placeholder, m);
return placeholder;
});
const result = fn(stripped);
const restore = (s: string) => {
let out = s;
for (let i = 0; i < comments.length; i++) {
out = out.replace(`/*__hf_c${i}__*/`, comments[i]!);
}
return out;
};
return { result, restore };
return { stripped, comments };
}

function resolveRelativeUrlPath(fromDir: string, basePath: string): string {
Expand All @@ -180,7 +177,7 @@ function rebaseCssUrls(css: string, cssFileDir: string, projectDir: string): str
const resolvedRoot = resolve(projectDir);
const resolvedDir = resolve(cssFileDir);
if (resolvedDir === resolvedRoot) return css;
return css.replace(CSS_URL_RE, (full, quote: string, urlValue: string) => {
return replaceMatches(css, cssUrlMatches(css), (full, quote, urlValue) => {
const decoded = decodeCssEscapes(urlValue);
if (!decoded || !isRelativeUrl(decoded)) return full;
const { basePath, suffix } = splitUrlSuffix(decoded);
Expand Down Expand Up @@ -275,10 +272,10 @@ function inlineCssFile(
projectDir: string,
activeImports: Set<string>,
): string {
const { result: strippedCss, restore: restoreComments } = withCommentsStripped(css, (s) => s);
const importPlaceholders: string[] = [];
const withPlaceholders = strippedCss.replace(
CSS_IMPORT_RE,
const { stripped: strippedCss, comments: placeholders } = withCommentsStripped(css);
const withPlaceholders = replaceMatches(
strippedCss,
cssImportMatches(strippedCss),
(full, _q1, urlPath, _q2, barePath, mediaQuery) => {
const importPath = urlPath ?? barePath;
if (!importPath || !isRelativeUrl(importPath)) return full;
Expand All @@ -294,17 +291,15 @@ function inlineCssFile(
activeImports.delete(resolved);
const trimmedMedia = (mediaQuery || "").trim();
const block = trimmedMedia ? `@media ${trimmedMedia} {\n${inlined}\n}\n` : inlined + "\n";
const idx = importPlaceholders.length;
importPlaceholders.push(block);
return `/*__hf_import_${idx}__*/`;
const placeholder = `/*__hf_import_${placeholders.size}__*/`;
placeholders.set(placeholder, block);
return placeholder;
},
);
let rebased = rebaseCssUrls(withPlaceholders, cssFileDir, projectDir);
rebased = restoreComments(rebased);
for (let i = 0; i < importPlaceholders.length; i++) {
rebased = rebased.replace(`/*__hf_import_${i}__*/`, importPlaceholders[i]!);
}
return rebased;
return restoreCssPlaceholders(
rebaseCssUrls(withPlaceholders, cssFileDir, projectDir),
placeholders,
);
}

function safeReadFileBuffer(filePath: string): Buffer | null {
Expand Down Expand Up @@ -507,14 +502,11 @@ function rewriteColorGradingLutWithInlinedAssets(value: string, inlineAsset: Ass

function rewriteCssUrlsWithInlinedAssets(cssText: string, inlineAsset: AssetInliner): string {
if (!cssText) return cssText;
return cssText.replace(
/\burl\(\s*(["']?)([^)"']+)\1\s*\)/g,
(_full, quote: string, rawUrl: string) => {
const maybeInlined = inlineAsset((rawUrl || "").trim());
if (!maybeInlined) return _full;
return `url(${quote || ""}${maybeInlined}${quote || ""})`;
},
);
return replaceMatches(cssText, rawCssUrlMatches(cssText), (_full, quote, rawUrl) => {
const maybeInlined = inlineAsset((rawUrl || "").trim());
if (!maybeInlined) return _full;
return `url(${quote || ""}${maybeInlined}${quote || ""})`;
});
}

/**
Expand Down Expand Up @@ -716,7 +708,8 @@ function joinCssHoistingImports(sheets: string[]): string {
const imports = new Set<string>();
const cssParts: string[] = [];
for (const sheet of sheets) {
const rest = sheet.trim().replace(CSS_IMPORT_RE, (match) => {
const trimmed = sheet.trim();
const rest = replaceMatches(trimmed, cssImportMatches(trimmed), (match) => {
imports.add(match.trim());
return "";
});
Expand All @@ -730,9 +723,11 @@ function placeSceneStylesLikeRender(document: Document): void {
const styles = [...document.querySelectorAll("head style")];
const imports = new Set<string>();
for (const el of styles) {
el.textContent = (el.textContent || "")
.replace(CSS_IMPORT_RE, (match) => (imports.add(match.trim()), ""))
.trim();
const css = el.textContent || "";
el.textContent = replaceMatches(css, cssImportMatches(css), (match) => {
imports.add(match.trim());
return "";
}).trim();
}
styles.slice(1).reduce((previous, el) => (previous.after(el), el), styles[0]!);
if (imports.size === 0) return;
Expand Down
36 changes: 12 additions & 24 deletions packages/core/src/compiler/svgIdNamespacing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
* data-hf-authored-id for script lookup compatibility.
*/

import { replaceMatches, urlHashRefMatches } from "@hyperframes/parsers/css-url-scans";
import postcss from "postcss";
import { escapeCssIdentifier } from "./selectorIdTokens";
import {
Expand All @@ -22,21 +23,6 @@ const ID_ATTR = "id";
* generalized from "the composition root" to any renamed descendant. */
export const SVG_AUTHORED_ID_ATTR = "data-hf-authored-id";

/**
* Matches a `url(#id)` funcref value — quoted or bare — as used by
* `clip-path`, `filter`, `mask`, `fill`, `stroke`, `marker-start/mid/end`,
* `cursor`, `mask-image`, and equally by any of those written into an inline
* `style` attribute or a `<style>` declaration value. One pattern covers all
* of them because CSS only ever spells an id reference this way in a
* property VALUE — a bare `#id` (no `url()`) is exclusively a *selector*.
*
* The captured id is the literal fragment text. A fragment is a URL, not a
* CSS identifier, so it carries no CSS escapes; the replacement keeps the
* original quoting and only swaps the id, which stays a valid fragment
* because the namespace prefix is restricted to `[A-Za-z0-9_-]`.
*/
const URL_HASH_REF_RE = /(url\(\s*)(["']?)#([^"')\s]+)\2(\s*\))/gi;

/**
* Attributes carrying a bare `#id` fragment reference rather than a
* `url(#id)` funcref — SVG's `<use>`, `<a>`, `<pattern>`, `<textPath>`,
Expand All @@ -51,9 +37,16 @@ function sanitizeNamespaceSegment(value: string): string {
return value.replace(/[^a-zA-Z0-9_-]/g, "-");
}

/**
* Rewrites each `url(#id)` funcref, quoted or bare, in a property value: `clip-path`, `filter`,
* `mask`, `fill`, `stroke`, markers, `cursor` and `mask-image`, inline or in a `<style>`. CSS
* spells an id reference this way only in a value; a bare `#id` is a selector. A fragment is a
* URL, not a CSS identifier, so it carries no escapes; the replacement keeps the quoting and
* swaps only the id, which stays a valid fragment because the prefix is `[A-Za-z0-9_-]`.
*/
function rewriteUrlHashRefs(value: string, idMap: ReadonlyMap<string, string>): string {
if (!value || !value.toLowerCase().includes("url(")) return value;
return value.replace(URL_HASH_REF_RE, (full, pre, quote, id: string, post) => {
return replaceMatches(value, urlHashRefMatches(value), (full, pre, quote, id, post) => {
const mapped = idMap.get(id);
return mapped ? `${pre}${quote}#${mapped}${quote}${post}` : full;
});
Expand All @@ -73,9 +66,7 @@ function nativeReferenceValue(
const mapped = idMap.get(value.slice(1));
return mapped ? `#${mapped}` : value;
}
URL_HASH_REF_RE.lastIndex = 0;
const hasUrl = URL_HASH_REF_RE.test(value);
URL_HASH_REF_RE.lastIndex = 0;
const hasUrl = !urlHashRefMatches(value).next().done;
return hasUrl ? rewriteUrlHashRefs(value, idMap) : null;
}

Expand Down Expand Up @@ -176,11 +167,8 @@ function collectUrlHashRefsFromText(
filter: ReadonlySet<string>,
out: Set<string>,
): void {
let m: RegExpExecArray | null;
URL_HASH_REF_RE.lastIndex = 0;
while ((m = URL_HASH_REF_RE.exec(text))) {
const refId = m[3]!;
if (filter.has(refId)) out.add(refId);
for (const { parts } of urlHashRefMatches(text)) {
if (filter.has(parts[3])) out.add(parts[3]);
}
}

Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/runtime/compositionLoader.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { rawCssUrlMatches, replaceMatches } from "@hyperframes/parsers/css-url-scans";
import { findSceneTemplate } from "@hyperframes/parsers/sub-composition-validity";
import { wallClearTimeout, wallSetTimeout } from "./wallClock";
import {
Expand Down Expand Up @@ -75,7 +76,6 @@ type PendingScript =

const EXTERNAL_SCRIPT_LOAD_TIMEOUT_MS = 8000;
const BARE_RELATIVE_PATH_RE = /^(?![a-zA-Z][a-zA-Z\d+\-.]*:)(?!\/\/)(?!\/)(?!\.\.?\/).+/;
const CSS_URL_RE = /\burl\(\s*(["']?)([^)"']+)\1\s*\)/g;
const PATH_ATTRS = ["src", "href"] as const;

/**
Expand Down Expand Up @@ -129,7 +129,7 @@ function rewriteRuntimeAssetPath(value: string, compositionUrl: URL | null): str

function rewriteRuntimeCssAssetUrls(cssText: string, compositionUrl: URL | null): string {
if (!compositionUrl || !cssText) return cssText;
return cssText.replace(CSS_URL_RE, (full, quote: string, rawUrl: string) => {
return replaceMatches(cssText, rawCssUrlMatches(cssText), (full, quote, rawUrl) => {
const rewritten = rewriteRuntimeAssetPath(rawUrl || "", compositionUrl);
if (rewritten === rawUrl) return full;
return `url(${quote || ""}${rewritten}${quote || ""})`;
Expand Down
Loading
Loading