fix(studio-server): preview head scripts land in the head when an attribute holds <head> text (#8704)

* fix(studio-server): place the preview variables tag by reading the document

The tag that carries `?variables=` into a preview was placed after the
first "<head" text in the file. That text can also sit inside an attribute
value or a comment, and a tag placed there is not a script: the page got no
variables and the <html> element picked up extra attributes.

core gains headContentStart, built on the tokenizer helpers htmlDocument
already has. It reads the document prefix the way a browser does (comments,
doctype, quoted attribute values) and returns the position after the real
<head> start tag, else after <html>, else after the doctype, else 0.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* fix(studio-server): place the GSAP fallback script by reading the document

The preview route put this script after the first literal "<head>" in the
page, which can be text inside an attribute value or a comment. It now uses
headContentStart, the same as the preview variables tag. A page whose head
tag has attributes also gets the script inside the head now, where before it
went ahead of the doctype.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* fix(core): headContentStart keeps a leading byte-order mark first

With no doctype, html or head tag the position was 0, ahead of the mark.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* chore(core): trim comments added with head placement

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
James Russo
2026-11-24 13:51:54 +00:00
committed by GitHub
co-authored by Claude Fable 5.2
parent 42ad487987
commit 07e03e8fed
6 changed files with 173 additions and 22 deletions
@@ -6,6 +6,7 @@ import {
findStartTags,
injectScriptsAtHeadStart,
injectScriptsIntoHtml,
headContentStart,
injectTagsAtHeadStart,
insertBeforeCloseTag,
insertRuntimeTag,
@@ -448,6 +449,45 @@ describe("injectTagsAtHeadStart on long adversarial input", () => {
});
});
describe("headContentStart", () => {
it.each([
[
"<!doctype html><html lang='en'><head id='h'>x",
"<!doctype html><html lang='en'><head id='h'>",
],
["<!doctype html><html lang='en'><body>x", "<!doctype html><html lang='en'>"],
[" \n<!DOCTYPE html><div>x", " \n<!DOCTYPE html>"],
["<div>x", ""],
["text<head>x", ""],
[
"<html a=\"<head>\" b='<head>' c=<head><HEAD>x",
"<html a=\"<head>\" b='<head>' c=<head><HEAD>",
],
[
"<!-- <head> --><!doctype html><!-- <html> --><head>x",
"<!-- <head> --><!doctype html><!-- <html> --><head>",
],
["<!--><html a='--><head>'><head>x", "<!--><html a='--><head>'><head>"],
["<!-- <head> never closed", ""],
["<!doctype html><html><body><head>x", "<!doctype html><html>"],
["<!doctype html><title><head></title>", "<!doctype html>"],
["<html a='<head>x", ""],
["<headless><head>x", ""],
["\uFEFF<div>x", "\uFEFF"],
["\uFEFF<!doctype html><html><head>x", "\uFEFF<!doctype html><html><head>"],
])("reads %j up to the end of its own head start tag", (html, before) => {
expect(headContentStart(html)).toBe(before.length);
});
it("is one pass over long runs of comments, attributes and unclosed tags", () => {
const prolog = "<!-- <head> -->".repeat(20_000) + "<html" + " a='<head>'".repeat(20_000) + ">";
expect(headContentStart(prolog + "<head>x")).toBe(prolog.length + 6);
expect(headContentStart("<!-- a --!>".repeat(20_000) + "<head>")).toBe(11 * 20_000 + 6);
expect(headContentStart("<html " + "a=".repeat(20_000))).toBe(0);
expect(headContentStart("<head".repeat(20_000) + ">")).toBe(0);
});
});
describe("hasCompositionOutsideTemplates", () => {
it.each([
["a root in <body>", '<body><div data-composition-id="main"></div></body>', true],
@@ -431,6 +431,44 @@ export function injectTagsAtHeadStart(html: string, tags: string): string {
return insertBeforeDocumentTag(html, "<body", `${tags}\n`) ?? `${tags}\n${html}`;
}
const BYTE_ORDER_MARK = 0xfeff;
export function headContentStart(html: string): number {
let cursor = html.charCodeAt(0) === BYTE_ORDER_MARK ? 1 : 0;
let at = cursor;
for (;;) {
const prolog = skipProlog(html, cursor);
at = Math.max(at, prolog.doctypeEnd);
cursor = prolog.next;
const isHead = isTagAt(html, cursor, "<head");
if (!isHead && !isTagAt(html, cursor, "<html")) return at;
const end = findTagEnd(html, cursor + 1);
if (end === -1) return at;
if (isHead) return end + 1;
at = cursor = end + 1;
}
}
function skipProlog(html: string, from: number): { next: number; doctypeEnd: number } {
let doctypeEnd = 0;
let next = from;
while (next < html.length) {
const end = prologItemEnd(html, next);
if (end <= next) break;
if (startsWithLower(html, "<!doctype", next)) doctypeEnd = end;
next = end;
}
return { next, doctypeEnd };
}
function prologItemEnd(html: string, at: number): number {
if (isHtmlWhitespace(html.charAt(at))) return at + 1;
if (html.startsWith("<!--", at)) return skipComment(html, at);
if (!html.startsWith("<!", at) && !html.startsWith("<?", at)) return at;
const close = html.indexOf(">", at);
return close === -1 ? -1 : close + 1;
}
export function injectScriptsAtHeadStart(html: string, scripts: readonly string[]): string {
if (scripts.length === 0) return html;
return injectTagsAtHeadStart(html, inlineScriptTags(scripts));
@@ -1,4 +1,5 @@
import { describe, expect, it } from "vitest";
import { parseHTML } from "linkedom";
import { injectPreviewVariables } from "./previewVariables";
const SCRIPT = '<script data-hf-preview-variables>window.__hfVariables={"a":1};</script>';
@@ -19,10 +20,32 @@ describe("injectPreviewVariables", () => {
[" \n<!DOCTYPE html>x", " \n<!DOCTYPE html>", "x"],
["fragment", "", "fragment"],
["x<!doctype html>y", "", "x<!doctype html>y"],
["<headless>x", "<headless>", "x"],
["<head attr='>'>x", "<head attr='>", "'>x"],
["<html><head", "<html>", "<head"],
["<head<head>x", "<head<head>", "x"],
["<head attr='>'>x", "<head attr='>'>", "x"],
['<html a="<head>"><head>x', '<html a="<head>"><head>', "x"],
["<html a='<head>' b=<head><body>x", "<html a='<head>' b=<head>", "<body>x"],
["<html a = '>' / b><head>x", "<html a = '>' / b><head>", "x"],
[
"<!-- <head> --><!doctype html><html><head>x",
"<!-- <head> --><!doctype html><html><head>",
"x",
],
["<!doctype html><!-- <head> --><body>x", "<!doctype html>", "<!-- <head> --><body>x"],
["<!--><html a='--><head>'><head>x", "<!--><html a='--><head>'><head>", "x"],
["<!--!><head>--><head>x", "<!--!><head>--><head>", "x"],
["<!-- a --!><head>x", "<!-- a --!><head>", "x"],
["<!---!><head>--><head>x", "<!---!><head>--><head>", "x"],
["<!---><head>x", "<!---><head>", "x"],
["<!-- <head> never closed", "", "<!-- <head> never closed"],
["<?xml version='1.0'?><html><head>x", "<?xml version='1.0'?><html><head>", "x"],
["\uFEFF<!doctype html><head>x", "\uFEFF<!doctype html><head>", "x"],
['<html a="<head>x', "", '<html a="<head>x'],
['<html ="<head>"><head>x', '<html ="<head>', '"><head>x'],
["<headless>x", "", "<headless>x"],
["<head<head>x", "", "<head<head>x"],
["<html><body><head>x", "<html>", "<body><head>x"],
["<html>text<head>x", "<html>", "text<head>x"],
["<title><head></title>x", "", "<title><head></title>x"],
])("preserves insertion boundaries (case %#)", (html, before, after) => {
expect(injectPreviewVariables(html, { a: 1 })).toBe(before + SCRIPT + after);
});
@@ -31,7 +54,33 @@ describe("injectPreviewVariables", () => {
const malformed = prefix.repeat(20_000);
expect(injectPreviewVariables(malformed, { a: 1 })).toBe(SCRIPT + malformed);
expect(injectPreviewVariables(malformed + ">tail", { a: 1 })).toBe(
malformed + ">" + SCRIPT + "tail",
SCRIPT + malformed + ">tail",
);
});
it.each([
[
"an attribute of <html> holds <head> and <header> text",
`<!doctype html><html lang="en" data-composition-variables='[{"label":"Page <header> and <head> text"}]'><head><title>t</title></head><body></body></html>`,
],
[
"a leading comment holds <head>",
`<!-- the <head> goes below --><!doctype html><html lang="en" data-x="1"><head><title>t</title></head><body></body></html>`,
],
])("puts one script in <head> and leaves <html> as written when %s", (_name, html) => {
const before = parseHTML(html).document;
const { document } = parseHTML(
injectPreviewVariables(html, { x: '" onpointermove="1', y: "' onclick='1", z: "-->" }),
);
const scripts = document.querySelectorAll("script[data-hf-preview-variables]");
expect(scripts).toHaveLength(1);
expect(scripts[0]?.parentElement).toBe(document.head);
expect(document.head.firstElementChild).toBe(scripts[0]);
expect(document.documentElement.getAttributeNames()).toEqual(
before.documentElement.getAttributeNames(),
);
expect(document.documentElement.getAttribute("data-composition-variables")).toBe(
before.documentElement.getAttribute("data-composition-variables"),
);
});
@@ -1,3 +1,5 @@
import { headContentStart } from "@hyperframes/core/compiler/html-document";
/**
* Inject preview variable overrides: `?variables=<json>` becomes
* `window.__hfVariables` set before any composition script runs — the exact
@@ -11,18 +13,9 @@ export function injectPreviewVariables(html: string, values: Record<string, unkn
// breaking out of the injected tag.
const json = JSON.stringify(values).replace(/</g, "\\u003c");
const tag = `<script data-hf-preview-variables>window.__hfVariables=${json};</script>`;
// Insert as early as possible without ever landing before the doctype —
// content before <!doctype> flips the document into quirks mode, so the
// fallback chain is <head…> → <html…> → after the doctype → prepend.
for (const pattern of [/<head/i, /<html/i, /^\s*<!doctype/i]) {
const match = pattern.exec(html);
if (match) {
// If the first prefix has no closing >, no later prefix can close either.
const end = html.indexOf(">", match.index + match[0].length);
if (end < 0) continue;
const at = end + 1;
return html.slice(0, at) + tag + html.slice(at);
}
}
return tag + html;
// Placed where a browser's tokenizer starts the head, never at the text "<head": that text can sit
// in an attribute value or a comment. To reproduce: `<html data-x='a <head> b'>` previewed with
// `?variables={"a":"\" b=\""}` must give one script in <head> and leave <html>'s attributes alone.
const at = headContentStart(html);
return html.slice(0, at) + tag + html.slice(at);
}
@@ -1627,6 +1627,34 @@ describe("preview ?variables= injection", () => {
expect(injected?.[1]).not.toContain("</script>");
});
it("serves every head script inside <head> when an attribute of <html> holds <head> text", async () => {
const projectDir = createProjectDir();
const app = new Hono();
registerPreviewRoutes(app, createAdapter(projectDir));
const label = '[{"label":"Page <head> and <header> text"}]';
writeFileSync(
join(projectDir, "index.html"),
`<!doctype html><html lang="en" data-composition-variables='${label}'><head><title>t</title></head><body><div data-composition-id="main" data-width="320" data-height="180"></div></body></html>`,
);
const values = { title: '" b="1', other: "' c='1" };
const res = await app.request(
`http://localhost/projects/demo/preview?variables=${encodeURIComponent(JSON.stringify(values))}`,
);
const { document } = parseHTML(await res.text());
const root = document.documentElement;
expect(root.getAttributeNames().filter((name) => name !== "style")).toEqual([
"lang",
"data-composition-variables",
]);
expect(root.getAttribute("data-composition-variables")).toBe(label);
for (const attr of ["data-hf-preview-variables", "data-hf-gsap-fallback"]) {
const scripts = document.querySelectorAll(`script[${attr}]`);
expect(scripts, attr).toHaveLength(1);
expect(scripts[0]?.parentElement, attr).toBe(document.head);
}
});
it("returns 400 for invalid JSON and non-object payloads", async () => {
const projectDir = createProjectDir();
const app = new Hono();
+7 -4
View File
@@ -42,7 +42,11 @@ import {
normalizeGsapBaseUrl,
normalizeGsapLocalRoot,
} from "@hyperframes/core/gsap-cdn";
import { findStartTags, injectTagsAtHeadStart } from "@hyperframes/core/compiler/html-document";
import {
findStartTags,
headContentStart,
injectTagsAtHeadStart,
} from "@hyperframes/core/compiler/html-document";
import { hasAuthoredCode } from "../helpers/authoredCode.js";
import { THUMBNAIL_NO_AUTHORED_CODE_META } from "../helpers/screenshotClip.js";
import { isWithinProjectRoot } from "@hyperframes/parsers/asset-resolution";
@@ -445,9 +449,8 @@ function gsapCdnFallbackScript(baseUrl: string): string {
function injectGsapCdnFallback(html: string, baseUrl: string): string {
if (html.includes(GSAP_FALLBACK_ATTR)) return html;
if (html.includes("<head>"))
return html.replace("<head>", "<head>" + gsapCdnFallbackScript(baseUrl));
return gsapCdnFallbackScript(baseUrl) + html;
const at = headContentStart(html);
return html.slice(0, at) + gsapCdnFallbackScript(baseUrl) + html.slice(at);
}
/**