Skip to content

Commit 16871a1

Browse files
fix: preview and bundled scripts run where and when the author put them (#5014)
* fix(core): bundled local scripts keep their own place, defer and async The bundler joined every local <script src> into one inline script at the first one's position. That dropped defer and async (a deferred main.js ran before a deferred CDN gsap), moved later files ahead of CDN scripts between them, and let one file's error stop the rest. Each local script is now inlined where it stands with its attributes; a deferred or async one keeps its tag with its file as a data: URL. Inline-script merging also no longer folds in nomodule scripts, which dropped the attribute. * fix: preview scripts run after the runtime when the bundler fails, and inlined files are escaped - When the bundler returns nothing or throws, the preview places the runtime where the bundled page does (end of head) instead of after the composition's scripts or not at all; core's placement moves to insertRuntimeTag. - Every HTML-spec JavaScript MIME type counts as a classic script for merging and the web-font gate. - Inlined local files and merged runs are escaped with escapeInlineScriptSource. * fix: deferred local scripts run late without data: URLs, and authored runtime reads survive - Local defer/async scripts are inlined in their own tag with the attribute kept; the font-gate runner (and its old-runtime fallback) runs an inline classic defer script after the classic scripts, in document order, so a page policy that allows inline scripts but not data: still runs them. - stripEmbeddedRuntimeScripts matches the bootstrap attribute and runtime file names on the tag, not runtime words in an authored script's text. - The preview applies its runtime on every path, so an adapter page without one still gets it; the inline escaper writes <!-- as \x3C!--, valid in a unicode regex. * fix: a deferred inline script waits for the deferred CDN script before it to load * fix: an authored script that mentions the runtime marker no longer stops the runtime being added * fix: only inlined deferred files run late, head ones included, and renders skip a CDN runtime link * fix: deferred head files run as before, and one selector owns the deferred-file rule * fix: a local file's legacy <!-- comment no longer breaks its merged run, and escapes keep case * fix: a local file inlined on its own keeps working with a legacy <!-- comment * test(core): a local non-JavaScript file keeps its text as written
1 parent b45818f commit 16871a1

18 files changed

Lines changed: 606 additions & 130 deletions

‎packages/core/src/compiler/htmlBundler.test.ts‎

Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2514,6 +2514,190 @@ describe("bundleToSingleHtml script order", () => {
25142514
}
25152515
});
25162516

2517+
const LOCAL_ORDER_GSAP = "https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js";
2518+
async function bundledBody(scripts: string, files: Record<string, string>) {
2519+
const dir = makeTempProject({
2520+
"index.html": `<!doctype html>
2521+
<html><body>
2522+
<div data-composition-id="root" data-width="320" data-height="180"></div>
2523+
${scripts}
2524+
</body></html>`,
2525+
...files,
2526+
});
2527+
try {
2528+
const { document } = parseHTML(await bundleToSingleHtml(dir));
2529+
return [...document.querySelectorAll("body script")];
2530+
} finally {
2531+
rmSync(dir, { recursive: true, force: true });
2532+
}
2533+
}
2534+
2535+
it("keeps each local script in its own place around a CDN script", async () => {
2536+
const scripts = await bundledBody(
2537+
`<script src="setup.js"></script>
2538+
<script src="${LOCAL_ORDER_GSAP}"></script>
2539+
<script src="main.js"></script>`,
2540+
{ "setup.js": "window.SETUP_RAN = 1;", "main.js": "window.MAIN_RAN = gsap.version;" },
2541+
);
2542+
const setupAt = scripts.findIndex((el) => el.textContent?.includes("SETUP_RAN"));
2543+
const gsapAt = scripts.findIndex((el) => el.getAttribute("src") === LOCAL_ORDER_GSAP);
2544+
const mainAt = scripts.findIndex((el) => el.textContent?.includes("MAIN_RAN"));
2545+
expect(setupAt).toBeGreaterThan(-1);
2546+
expect(setupAt).toBeLessThan(gsapAt);
2547+
expect(gsapAt).toBeLessThan(mainAt);
2548+
});
2549+
2550+
it.each(["defer", "async"])(
2551+
"inlines a local %s script in its own tag, keeping the attribute so the runtime times it",
2552+
async (when) => {
2553+
const scripts = await bundledBody(
2554+
`<script>window.FIRST = 1;</script>
2555+
<script ${when} src="main.js"></script>
2556+
<script>window.LAST = 1;</script>`,
2557+
{ "main.js": "window.MAIN_RAN = 1;" },
2558+
);
2559+
const main = scripts.find((el) => el.textContent?.includes("MAIN_RAN"));
2560+
expect(main?.hasAttribute(when)).toBe(true);
2561+
expect(main?.hasAttribute("src")).toBe(false);
2562+
expect(main?.getAttribute("data-hf-inlined-src")).toBe("main.js");
2563+
expect(main?.textContent).not.toMatch(/FIRST|LAST/);
2564+
},
2565+
);
2566+
2567+
it.each(["", ' type="text/babel"'])(
2568+
"escapes a local file's script-closing text, so the page keeps its structure (%s)",
2569+
async (type) => {
2570+
const scripts = await bundledBody(
2571+
`<script${type} src="main.js"></script><p id="after">ok</p>`,
2572+
{
2573+
"main.js": `window.CLOSE = "</script><p id='leak'>x</p>"; window.OPEN = "<!-- <script>";`,
2574+
},
2575+
);
2576+
const holder = scripts.find((el) => el.textContent?.includes("window.CLOSE"));
2577+
expect(holder?.textContent).toContain("window.OPEN");
2578+
expect(holder?.textContent).not.toMatch(/<\/script|<!--/i);
2579+
expect(holder?.ownerDocument.getElementById("leak")).toBeNull();
2580+
},
2581+
);
2582+
2583+
it.each([
2584+
["a local file", `<script nomodule src="legacy.js"></script>`],
2585+
["an inline script", `<script nomodule>window.LEGACY_RAN = 1;</script>`],
2586+
])("keeps nomodule on %s, so modern browsers still skip it", async (_, legacy) => {
2587+
const scripts = await bundledBody(
2588+
`<script>window.FIRST = 1;</script>\n ${legacy}\n <script>window.LAST = 1;</script>`,
2589+
{
2590+
"legacy.js": "window.LEGACY_RAN = 1;",
2591+
},
2592+
);
2593+
const holder = scripts.find((el) => el.textContent?.includes("LEGACY_RAN"));
2594+
expect(holder?.hasAttribute("nomodule")).toBe(true);
2595+
expect(holder?.textContent).not.toMatch(/FIRST|LAST/);
2596+
});
2597+
2598+
it("keeps a local script's non-JavaScript type, so it is not run as JavaScript", async () => {
2599+
const scripts = await bundledBody(`<script type="text/babel" src="app.jsx"></script>`, {
2600+
"app.jsx": "const App = () => <div />;",
2601+
});
2602+
const holder = scripts.find((el) => el.textContent?.includes("const App"));
2603+
expect(holder?.getAttribute("type")).toBe("text/babel");
2604+
});
2605+
2606+
it.each(["", ' type="text/babel"'])(
2607+
"keeps a local file's unicode regex for <!-- valid JavaScript (%s)",
2608+
async (type) => {
2609+
const scripts = await bundledBody(`<script${type} src="main.js"></script>`, {
2610+
"main.js": "window.HAS_COMMENT = /<!--/u.test(document.body.innerHTML);",
2611+
});
2612+
const holder = scripts.find((el) => el.textContent?.includes("HAS_COMMENT"));
2613+
expect(() => new Function(holder?.textContent ?? "")).not.toThrow();
2614+
},
2615+
);
2616+
2617+
it("keeps an authored script that reads the runtime global", async () => {
2618+
const scripts = await bundledBody(
2619+
`<script>if (window.__hyperframeRuntime) window.AUTHOR_SEEN = 1;</script>`,
2620+
{},
2621+
);
2622+
expect(scripts.some((el) => el.textContent?.includes("AUTHOR_SEEN"))).toBe(true);
2623+
});
2624+
2625+
it("keeps a run that merges a local file with a legacy <!-- comment valid, every script in order", async () => {
2626+
const scripts = await bundledBody(
2627+
`<script src="esc.js"></script>
2628+
<script src="legacy.js"></script>
2629+
<script>window.RAN.push("a");</script>
2630+
<script>window.RAN.push("b");</script>
2631+
<script src="plain.js"></script>`,
2632+
{
2633+
"esc.js": 'window.RAN = ["esc"]; window.CLOSE = "</script>";',
2634+
"legacy.js": '<!-- a legacy comment\nwindow.RAN.push("legacy");',
2635+
"plain.js": 'window.RAN.push("plain");',
2636+
},
2637+
);
2638+
const merged = scripts.find((el) => el.textContent?.includes('"plain"'));
2639+
expect(merged?.textContent).not.toMatch(/<\/script|<!--/i);
2640+
const page = { RAN: [] as string[] };
2641+
new Function("window", merged?.textContent ?? "")(page);
2642+
expect(page.RAN).toEqual(["esc", "legacy", "a", "b", "plain"]);
2643+
});
2644+
2645+
it.each([
2646+
["in <head>", `<script src="legacy.js"></script>`, ""],
2647+
["deferred in <body>", "", `<script defer src="legacy.js"></script>`],
2648+
])(
2649+
"keeps a local file with a legacy <!-- comment valid when it is inlined on its own (%s)",
2650+
async (_, head, body) => {
2651+
const dir = makeTempProject({
2652+
"index.html": `<!doctype html>
2653+
<html><head>${head}</head><body>
2654+
<div data-composition-id="root" data-width="320" data-height="180"></div>
2655+
${body}
2656+
</body></html>`,
2657+
"legacy.js": '<!-- a legacy comment\nwindow.RAN = ["legacy"];',
2658+
});
2659+
try {
2660+
const { document } = parseHTML(await bundleToSingleHtml(dir));
2661+
const file = document.querySelector("script[data-hf-inlined-src]");
2662+
expect(file?.textContent).not.toContain("<!--");
2663+
const page = { RAN: [] as string[] };
2664+
new Function("window", file?.textContent ?? "")(page);
2665+
expect(page.RAN).toEqual(["legacy"]);
2666+
} finally {
2667+
rmSync(dir, { recursive: true, force: true });
2668+
}
2669+
},
2670+
);
2671+
2672+
it("leaves a local non-JavaScript file's text as written", async () => {
2673+
const scripts = await bundledBody(`<script type="application/json" src="data.json"></script>`, {
2674+
"data.json": "[1,2]",
2675+
});
2676+
expect(scripts.find((el) => el.getAttribute("type") === "application/json")?.textContent).toBe(
2677+
"[1,2]",
2678+
);
2679+
});
2680+
2681+
it("still adds the runtime when an authored script mentions its marker attribute", async () => {
2682+
const dir = makeTempProject({
2683+
"index.html": `<!doctype html>
2684+
<html><head></head><body>
2685+
<div data-composition-id="root" data-width="320" data-height="180"></div>
2686+
<script>window.MARKER = document.querySelector("[data-hyperframes-preview-runtime]");</script>
2687+
</body></html>`,
2688+
});
2689+
try {
2690+
const { document } = parseHTML(await bundleToSingleHtml(dir));
2691+
const scripts = [...document.querySelectorAll("script")];
2692+
expect(
2693+
scripts.filter((el) => el.hasAttribute("data-hyperframes-preview-runtime")),
2694+
).toHaveLength(1);
2695+
expect(scripts.some((el) => el.textContent?.includes("window.MARKER"))).toBe(true);
2696+
} finally {
2697+
rmSync(dir, { recursive: true, force: true });
2698+
}
2699+
});
2700+
25172701
it("still merges adjacent inline scripts into one at the end of the body", async () => {
25182702
const dir = makeTempProject({
25192703
"index.html": `<!doctype html>

‎packages/core/src/compiler/htmlBundler.ts‎

Lines changed: 15 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@ import {
44
deferScriptsUntilFonts,
55
UNCONDITIONAL_CSS_KEY,
66
headStyleRuns,
7+
INLINED_FILE_ATTR,
78
inlineScriptRuns,
9+
isJavaScriptType,
810
styleElementsFor,
911
type CompositionStyle,
1012
} from "./scriptRuns";
@@ -28,7 +30,8 @@ import { transformSync } from "esbuild";
2830
import { compileHtml, type MediaDurationProber } from "./htmlCompiler";
2931
import {
3032
RUNTIME_BOOTSTRAP_ATTR,
31-
insertBeforeCloseTag,
33+
escapeInlineScriptSource,
34+
insertRuntimeTag,
3235
parseHTMLContent,
3336
stripEmbeddedRuntimeScripts,
3437
} from "./htmlDocument";
@@ -62,7 +65,6 @@ function getRuntimeScriptUrl(): string {
6265

6366
function injectInterceptor(html: string, runtimeMode: "inline" | "placeholder" = "inline"): string {
6467
const sanitized = stripEmbeddedRuntimeScripts(html);
65-
if (sanitized.includes(RUNTIME_BOOTSTRAP_ATTR)) return sanitized;
6668

6769
// Three modes for the runtime <script>:
6870
// 1. HYPERFRAME_RUNTIME_URL env var set → emit src="<url>" (production CDN deploy).
@@ -82,19 +84,7 @@ function injectInterceptor(html: string, runtimeMode: "inline" | "placeholder" =
8284
const inlinedRuntime = getHyperframeRuntimeScript();
8385
tag = `<script ${RUNTIME_BOOTSTRAP_ATTR}="1">${inlinedRuntime}</script>`;
8486
}
85-
const withHead = insertBeforeCloseTag(sanitized, "head", `${tag}\n`);
86-
if (withHead !== null) return withHead;
87-
const htmlOpenMatch = sanitized.match(/<html\b[^>]*>/i);
88-
if (htmlOpenMatch?.index != null) {
89-
const insertPos = htmlOpenMatch.index + htmlOpenMatch[0].length;
90-
return `${sanitized.slice(0, insertPos)}<head>${tag}</head>${sanitized.slice(insertPos)}`;
91-
}
92-
const doctypeIdx = sanitized.toLowerCase().indexOf("<!doctype");
93-
if (doctypeIdx >= 0) {
94-
const insertPos = sanitized.indexOf(">", doctypeIdx) + 1;
95-
return sanitized.slice(0, insertPos) + tag + sanitized.slice(insertPos);
96-
}
97-
return tag + sanitized;
87+
return insertRuntimeTag(sanitized, tag);
9888
}
9989

10090
function isRelativeUrl(url: string): boolean {
@@ -749,7 +739,7 @@ function coalesceHeadStylesAndBodyScripts(document: Document): void {
749739
for (const el of members) el.remove();
750740
if (!mergedJs) continue;
751741
const inlineScript = document.createElement("script");
752-
inlineScript.textContent = stripJsCommentsParserSafe(mergedJs);
742+
inlineScript.textContent = escapeInlineScriptSource(stripJsCommentsParserSafe(mergedJs));
753743
if (anchor) anchor.before(inlineScript);
754744
else document.body.appendChild(inlineScript);
755745
}
@@ -1226,9 +1216,6 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
12261216
templateEl.remove();
12271217
}
12281218

1229-
// Inline local JS
1230-
const localJsChunks: string[] = [];
1231-
let jsAnchorPlaced = false;
12321219
for (const el of [...document.querySelectorAll("script[src]")]) {
12331220
const src = el.getAttribute("src");
12341221
if (!src || !isRelativeUrl(src)) continue;
@@ -1240,27 +1227,9 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
12401227
const jsPath = resolveEntryPath(src);
12411228
const js = jsPath ? safeReadFile(jsPath) : null;
12421229
if (js == null) continue;
1243-
localJsChunks.push(js);
1244-
if (!jsAnchorPlaced) {
1245-
const anchor = document.createElement("script");
1246-
anchor.setAttribute("data-hf-bundled-local-js", "1");
1247-
el.replaceWith(anchor);
1248-
jsAnchorPlaced = true;
1249-
} else {
1250-
el.remove();
1251-
}
1252-
}
1253-
if (localJsChunks.length > 0) {
1254-
const anchor = document.querySelector('script[data-hf-bundled-local-js="1"]');
1255-
const joinedJs = joinJsChunks(localJsChunks);
1256-
if (anchor) {
1257-
anchor.removeAttribute("data-hf-bundled-local-js");
1258-
anchor.textContent = joinedJs;
1259-
} else {
1260-
const script = document.createElement("script");
1261-
script.textContent = joinedJs;
1262-
document.body.appendChild(script);
1263-
}
1230+
el.setAttribute(INLINED_FILE_ATTR, src);
1231+
el.removeAttribute("src");
1232+
el.textContent = js;
12641233
}
12651234

12661235
for (const link of compExternalLinks) ensureExternalLinkTag(document, link);
@@ -1294,6 +1263,12 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
12941263
enforceCompositionPixelSizing(document);
12951264
autoHealMissingCompositionIds(document);
12961265
coalesceHeadStylesAndBodyScripts(document);
1266+
for (const el of document.querySelectorAll(`script[${INLINED_FILE_ATTR}]`)) {
1267+
const js = el.textContent ?? "";
1268+
el.textContent = escapeInlineScriptSource(
1269+
isJavaScriptType(el) ? stripJsCommentsParserSafe(js) : js,
1270+
);
1271+
}
12971272
deferScriptsUntilFonts(document, (el) => el.hasAttribute(RUNTIME_BOOTSTRAP_ATTR));
12981273
injectTextRenderingRule(document);
12991274

‎packages/core/src/compiler/htmlDocument.test.ts‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,24 @@ describe("htmlDocument helpers", () => {
6969
expect(stripped).toContain("window.__renderReady");
7070
});
7171

72+
it.each([
73+
["reads the runtime global", "if (window.__hyperframeRuntime) window.seen = 1;"],
74+
[
75+
"queries the bootstrap attribute",
76+
'document.querySelector("[data-hyperframes-preview-runtime]");',
77+
],
78+
["names a runtime file", 'console.log("hyperframe.runtime.iife.js");'],
79+
["sets up window.__player", "window.__player = window.__player || {};"],
80+
])("keeps an authored script that %s", (_, source) => {
81+
const html = `<script>${source}</script>`;
82+
expect(stripEmbeddedRuntimeScripts(html)).toBe(html);
83+
});
84+
85+
it("strips a runtime file linked with a query string or uppercase name", () => {
86+
const html = '<script src="/static/HYPERFRAME.RUNTIME.IIFE.JS?v=2"></script><p>kept</p>';
87+
expect(stripEmbeddedRuntimeScripts(html)).toBe("<p>kept</p>");
88+
});
89+
7290
it("does not treat non-script tags as scripts when stripping runtimes", () => {
7391
const html = "<scripture>window.__playerReady = true;</scripture>";
7492

@@ -99,7 +117,7 @@ describe("htmlDocument helpers", () => {
99117
);
100118

101119
expect(injected).toContain("<\\/script ><script>window.pwned = true;<\\/script>");
102-
expect(injected).toContain("<\\!-- kept as script text");
120+
expect(injected).toContain("\\x3C!-- kept as script text");
103121
expect(injected).not.toContain("</script ><script>window.pwned = true;");
104122
});
105123

@@ -148,7 +166,7 @@ describe("htmlDocument helpers", () => {
148166
expect(stripped).toBe("<p>İİ</p><p>kept</p>");
149167

150168
const escaped = injectScriptsIntoHtml(page, ['x="İİ</SCRIPT>"'], []);
151-
expect(escaped).toContain('<script>x="İİ<\\/script>"</script>');
169+
expect(escaped).toContain('<script>x="İİ<\\/SCRIPT>"</script>');
152170
});
153171

154172
it("skips a script tag written inside an attribute value", () => {

0 commit comments

Comments
 (0)