diff --git a/packages/studio-server/src/helpers/subComposition.test.ts b/packages/studio-server/src/helpers/subComposition.test.ts index fab5ef96a1..6b1d80406e 100644 --- a/packages/studio-server/src/helpers/subComposition.test.ts +++ b/packages/studio-server/src/helpers/subComposition.test.ts @@ -6,7 +6,12 @@ import { describe, expect, it, onTestFinished } from "vitest"; import { gsapCdnDist } from "@hyperframes/core/gsap-cdn"; import { parseHTML } from "linkedom"; import { AFTER_FONTS_SCRIPT_TYPE } from "@hyperframes/core/compiler"; -import { buildSubCompositionHtml, hasBaseElement } from "./subComposition"; +import { + buildSubCompositionHtml, + hasBaseElement, + rootHeadContent, + tagRootCompositionFile, +} from "./subComposition"; function makeTempProject(files: Record): string { const dir = mkdtempSync(join(tmpdir(), "hf-subcomp-preview-")); @@ -596,3 +601,130 @@ describe("hasBaseElement", () => { } }); }); + +/** A seeded generator, so a failing page can be reproduced from the test's output. */ +function seededPick(seed: number): (n: number) => number { + let state = seed; + return (n) => { + state ^= state << 13; + state ^= state >>> 17; + state ^= state << 5; + state >>>= 0; + return state % n; + }; +} + +function generatedPages(pieces: string[], seed: number, count: number): string[] { + const pick = seededPick(seed); + return Array.from({ length: count }, () => + Array.from({ length: 1 + pick(14) }, () => pieces[pick(pieces.length)]).join(""), + ); +} + +function expectFast(run: () => void, budgetMs: number): void { + const started = performance.now(); + run(); + expect(performance.now() - started).toBeLessThan(budgetMs); +} + +describe("rootHeadContent", () => { + const regexHead = (html: string) => html.match(/]*>([\s\S]*?)<\/head>/i)?.[1] ?? ""; + + it("captures the inner head of ordinary pages", () => { + expect( + rootHeadContent('x'), + ).toBe("x"); + expect(rootHeadContent("")).toBe(""); + expect(rootHeadContent("no head")).toBe(""); + }); + + it("captures what the regex captured, on generated pages", () => { + const pieces = [ + "", + "", + "", + "]*>[\s\S]*?<\/head>/i.test(page)) found++; + } + expect(found).toBeGreaterThan(1_000); + }); + + it("takes time in proportion to the page on openers that never close", () => { + // The regex rescanned to the end from every opener: seconds at this size, four times as long per doubling. + const shapes = [ + "".repeat(100_000), + `${"".repeat(100_000)} rootHeadContent(page), 100); + }); +}); + +describe("tagRootCompositionFile", () => { + const regexTag = (bodyHtml: string, compPath: string) => { + const match = bodyHtml.match(/<[a-zA-Z][^>]*\bdata-composition-id=/); + if (match?.index == null) return bodyHtml; + const tagEnd = bodyHtml.indexOf(">", match.index); + if (tagEnd === -1) return bodyHtml; + if (bodyHtml.slice(match.index, tagEnd).includes("data-composition-file")) return bodyHtml; + return `${bodyHtml.slice(0, tagEnd)} data-composition-file="${compPath}"${bodyHtml.slice(tagEnd)}`; + }; + + it("tags the first composition root and leaves a tagged one alone", () => { + expect(tagRootCompositionFile('

', "c/a.html")).toBe( + '

', + ); + const tagged = '
'; + expect(tagRootCompositionFile(tagged, "c/a.html")).toBe(tagged); + expect(tagRootCompositionFile("
", "c/a.html")).toBe( + "
", + ); + }); + + it("tags what the regex tagged, on generated pages", () => { + const pieces = [ + "", + " ", + "x", + "data-composition-id=", + " data-composition-id=", + " data-composition-id=1>", + "data-composition-file", + '"', + ]; + let tagged = 0; + for (const page of generatedPages(pieces, 5, 20_000)) { + const out = tagRootCompositionFile(page, "a.html"); + expect(out, page).toBe(regexTag(page, "a.html")); + if (out !== page) tagged++; + } + expect(tagged).toBeGreaterThan(1_000); + }); + + it("takes time in proportion to the page on openers that never close", () => { + // A script's text keeps its `<` through serialization, so the page can be one long run of openers. + const shapes = [ + " tagRootCompositionFile(page, "a.html"), 100); + }); +}); diff --git a/packages/studio-server/src/helpers/subComposition.ts b/packages/studio-server/src/helpers/subComposition.ts index 8d2e3f73ef..adfc16b3ca 100644 --- a/packages/studio-server/src/helpers/subComposition.ts +++ b/packages/studio-server/src/helpers/subComposition.ts @@ -233,21 +233,67 @@ function promoteTemplateCompositionId(rawComp: string, body: Element): void { * studio resolves its top-level elements to the right source file. Idempotent; * a no-op when no composition element is present. */ -function tagRootCompositionFile(bodyHtml: string, compPath: string): string { - const match = bodyHtml.match(/<[a-zA-Z][^>]*\bdata-composition-id=/); - if (match?.index == null) return bodyHtml; - const tagEnd = bodyHtml.indexOf(">", match.index); - if (tagEnd === -1) return bodyHtml; - if (bodyHtml.slice(match.index, tagEnd).includes("data-composition-file")) return bodyHtml; +export function tagRootCompositionFile(bodyHtml: string, compPath: string): string { + const tag = firstCompositionIdTag(bodyHtml); + if (!tag) return bodyHtml; + if (bodyHtml.slice(tag.start, tag.end).includes("data-composition-file")) return bodyHtml; return ( - bodyHtml.slice(0, tagEnd) + + bodyHtml.slice(0, tag.end) + ` data-composition-file="${escapeAttrValue(compPath)}"` + - bodyHtml.slice(tagEnd) + bodyHtml.slice(tag.end) ); } +const TAG_OPENER = /<[a-zA-Z]/g; +const COMPOSITION_ID_ATTR = "data-composition-id="; + +/** + * The first start tag with a `data-composition-id=` attribute, from its `<` to its `>`: the tag + * `/<[a-zA-Z][^>]*\bdata-composition-id=/` finds, in time linear in the page. That regex rescans to + * the next `>` from every opener, which is quadratic on a long run of openers with no `>`. An opener + * inside another opener's tag can only do worse than that opener, so each tag is checked once. + * Null when there is no such tag, or it never closes. + */ +function firstCompositionIdTag(html: string): { start: number; end: number } | null { + TAG_OPENER.lastIndex = 0; + for (let open = TAG_OPENER.exec(html); open; open = TAG_OPENER.exec(html)) { + const close = html.indexOf(">", open.index); + const tag = html.slice(open.index, close === -1 ? html.length : close); + if (hasBoundedAttr(tag, COMPOSITION_ID_ATTR, 2)) { + return close === -1 ? null : { start: open.index, end: close }; + } + if (close === -1) return null; + TAG_OPENER.lastIndex = close; + } + return null; +} + +/** Whether `name` appears in `tag` at or after `from` with a non-word character before it, as `\bname` would. */ +function hasBoundedAttr(tag: string, name: string, from: number): boolean { + for (let at = tag.indexOf(name, from); at !== -1; at = tag.indexOf(name, at + 1)) { + if (!/\w/.test(tag[at - 1] ?? "")) return true; + } + return false; +} + +const HEAD_OPENER = //gi; + +/** + * The inner HTML of the page's ``: what `/]*>([\s\S]*?)<\/head>/i` captures, in time + * linear in the page. That regex rescans to the end of the page from every `` or the `` is missing. Only the first opener can match: a later one has no `>` or + * `` that the first could not also use. + */ export function rootHeadContent(rootHtml: string): string { - return rootHtml.match(/]*>([\s\S]*?)<\/head>/i)?.[1] ?? ""; + HEAD_OPENER.lastIndex = 0; + const open = HEAD_OPENER.exec(rootHtml); + if (!open) return ""; + const gt = rootHtml.indexOf(">", open.index + open[0].length); + if (gt === -1) return ""; + HEAD_CLOSER.lastIndex = gt + 1; + const close = HEAD_CLOSER.exec(rootHtml); + return close ? rootHtml.slice(gt + 1, close.index) : ""; } /**