Files
hyperframes/packages/core/src/compiler/compositionScoping.scoper.test.ts
T
Michael Wang 3f3fa67f9c fix(producer): charge generated mount scripts and scoped styles to the budget (#8094)
* fix(producer): charge generated mount scripts and scoped styles to the expansion budget

The expansion budget charged only the source bytes of each mounted file.
The inliner wraps every inline script in kilobytes of scoping code and
prefixes every style rule with the host's scope, so tiny scripts or a long
composition id over many rules assembled a page hundreds of times larger
than its source.

The inliner now reports what it generates through a chargeEmitted option.
Each wrapped script is charged once built. Each style rule reserves an upper
bound before it is scoped and settles to its real size after, so no rule is
built past the limit. Generated output has its own 32 MB allowance.

* fix(core): reserve the separator postcss re-joins scoped selectors with

The per-rule reservation summed a bound per selector but left out the
separator. postcss's selectors setter re-joins the list with the first
separator in the authored selector, so a wide first separator over many
selectors grew the rule past its reservation before it was charged.

* test(core): give the scoper bound test the same time limit as its neighbour
2026-11-17 22:53:11 +00:00

131 lines
4.8 KiB
TypeScript

// @vitest-environment node
import postcss from "postcss";
import { describe, expect, it, vi } from "vitest";
import { createCompositionCssScoper, scopeCssToComposition } from "./compositionScoping";
const scopeOf = (id: string) => `[data-composition-id="${id}"]`;
// Selector pieces that reach every branch of the scoping: root ids with and without timing
// attributes, document-level selectors, authored root ids, comments, nesting and global at-rules.
const piecesFor = (id: string) => [
".a",
"#card-root",
`[data-composition-id="${id}"]`,
`[data-composition-id='${id}']`,
`[data-composition-id^="${id}"]`,
'[data-start="0"]',
'[data-duration="2"]',
`[data-start="[data-composition-id='${id}']"]`,
"html",
"body",
":root",
"*",
" ",
" > ",
", ",
"/* note */",
":hover",
`[data-composition-id="${id}__hf2"]`,
'[data-composition-id="hf-scope-placeholder"]',
"&",
];
const WRAPPERS = [
(rule: string) => rule,
(rule: string) => `@media (min-width: 10px) { ${rule} }`,
(rule: string) => `@keyframes k { from { opacity: 0; } } ${rule}`,
(rule: string) => `.outer { ${rule} }`,
];
function randomSheets(id: string, count: number): string[] {
const pieces = piecesFor(id);
// mulberry32: a seeded generator whose low bits are as random as its high ones.
let seed = 7;
const next = (n: number) => {
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) % n;
};
return Array.from({ length: count }, () => {
const rules = Array.from({ length: 1 + next(4) }, () => {
const selector = Array.from({ length: 1 + next(5) }, () => pieces[next(pieces.length)]);
return WRAPPERS[next(WRAPPERS.length)]!(`${selector.join("")} { color: red; }`);
});
return rules.join("\n");
});
}
const scopesFor = (id: string) => [
scopeOf(`${id}__hf1`),
scopeOf(`${id}__hf2`),
scopeOf(id),
scopeOf("other"),
scopeOf("price$&tag"),
'[data-composition-id="quote\\"d"]',
"",
];
describe("createCompositionCssScoper", () => {
it("reserves an upper bound for each rule before scoping it and settles to the sheet's size", () => {
const scope = createCompositionCssScoper();
const selectorList = Array.from({ length: 200 }, (_, i) => `.s${i}`).join(", ");
const wideSeparator = `.first,${" ".repeat(5_000)}${selectorList} { color: red; }`;
for (const id of ["card", "c.a:rd", 'ca"rd', "hf-scope-placeholder"]) {
for (const css of [...randomSheets(id, 200), wideSeparator]) {
for (const authoredRootId of [undefined, "card-root"]) {
for (const selector of [...scopesFor(id), scopeOf("x".repeat(500))]) {
for (const scoper of [scope, scopeCssToComposition]) {
const charges: number[] = [];
const options = { compoundAuthoredRoot: true, scopeRootSelectors: true };
const out = scoper(css, id, selector, authoredRootId, {
...options,
charge: (bytes: number) => charges.push(bytes),
});
// Every settlement after a reservation is a refund: the bound held.
expect(Math.max(0, ...charges.slice(1).filter((_, i) => i % 2 === 1))).toBe(0);
expect(charges.reduce((sum, bytes) => sum + bytes, 0)).toBeGreaterThanOrEqual(
out.length,
);
}
}
}
}
}
}, 30_000);
it("scopes every sheet exactly as scopeCssToComposition does, whatever the mount's scope", () => {
const scope = createCompositionCssScoper();
for (const id of ["card", "c.a:rd", 'ca"rd', "ca]rd", "hf-scope-placeholder"]) {
for (const css of randomSheets(id, 300)) {
for (const compound of [false, true]) {
for (const authoredRootId of [undefined, "card-root"]) {
for (const selector of scopesFor(id)) {
const options = { compoundAuthoredRoot: compound, scopeRootSelectors: true };
expect(scope(css, id, selector, authoredRootId, options)).toBe(
scopeCssToComposition(css, id, selector, authoredRootId, options),
);
}
}
}
}
}
}, 30_000);
it("parses a sheet once for all of its mounts", () => {
const parse = vi.spyOn(postcss, "parse");
const scope = createCompositionCssScoper();
const css = `.title { color: var(--accent); } #card-root .row { background: url(a.png); }`;
const scoped = [1, 2, 3, 4].map((n) =>
scope(css, "card", scopeOf(`card__hf${n}`), "card-root"),
);
expect(parse).toHaveBeenCalledOnce();
parse.mockRestore();
scoped.forEach((out, i) => {
expect(out).toBe(
scopeCssToComposition(css, "card", scopeOf(`card__hf${i + 1}`), "card-root"),
);
expect(out).toContain(`${scopeOf(`card__hf${i + 1}`)} .title`);
});
});
});