Skip to content

Write HTML. Render video. Built for agents.

fix(core): a data script in a sub-composition no longer stops every timeline (#5205)

Miguel Ángele1b60933dbd2
diff --git a/bun.lock b/bun.lock
index 64948f4e61..28dfb581fd 100644
--- a/bun.lock
+++ b/bun.lock
@@ -116,6 +116,7 @@
"@hyperframes/lint": "workspace:*",
"@hyperframes/parsers": "workspace:*",
"@hyperframes/studio-server": "workspace:*",
+ "acorn": "^8.17.0",
"bpm-detective": "^2.0.5",
"linkedom": "^0.18.12",
"postcss": "^8.5.8",
diff --git a/packages/core/package.json b/packages/core/package.json
index 9f647802bc..1d657012ea 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -902,6 +902,7 @@
"@hyperframes/lint": "workspace:*",
"@hyperframes/parsers": "workspace:*",
"@hyperframes/studio-server": "workspace:*",
+ "acorn": "^8.17.0",
"bpm-detective": "^2.0.5",
"linkedom": "^0.18.12",
"postcss": "^8.5.8",
diff --git a/packages/core/src/compiler/compositionAssembly.test.ts b/packages/core/src/compiler/compositionAssembly.test.ts
index f6a256a44b..76254294f8 100644
--- a/packages/core/src/compiler/compositionAssembly.test.ts
+++ b/packages/core/src/compiler/compositionAssembly.test.ts
@@ -126,6 +126,14 @@ describe("planCompositionAssembly", () => {
expect(ids(plan.scriptSources)).toEqual(["head-script", "body-script"]);
});
+ it.each([
+ [`<script nomodule></script>`, false],
+ [`<script type="module" nomodule></script>`, true],
+ ])("extracts %s only when a browser runs it: %s", (script, runs) => {
+ const plan = planFor(`<template><div data-composition-id="s">${script}</div></template>`, "s");
+ expect(plan.scriptSources).toHaveLength(runs ? 1 : 0);
+ });
+
it("does not treat a templated composition's page head as an asset source", () => {
// The head belongs to the host page, not to the composition; only the
// non-templated (full-document) shape carries composition assets in <head>.
diff --git a/packages/core/src/compiler/compositionAssembly.ts b/packages/core/src/compiler/compositionAssembly.ts
index 256ae161c4..97198ecb39 100644
--- a/packages/core/src/compiler/compositionAssembly.ts
+++ b/packages/core/src/compiler/compositionAssembly.ts
@@ -34,7 +34,64 @@ const SCRIPT_SELECTOR = "script";
*/
const HOISTED_LINK_SELECTOR = 'link[rel="stylesheet"], link[rel="preconnect"]';
-export const EXTRACTED_COMPOSITION_ASSET_SELECTOR = `${STYLE_SELECTOR}, ${SCRIPT_SELECTOR}, ${HOISTED_LINK_SELECTOR}`;
+// The HTML spec's JavaScript MIME type essence matches: a script with any of these types runs as classic.
+const JAVASCRIPT_TYPES = new Set([
+ "",
+ "application/ecmascript",
+ "application/javascript",
+ "application/x-ecmascript",
+ "application/x-javascript",
+ "text/ecmascript",
+ "text/javascript",
+ "text/javascript1.0",
+ "text/javascript1.1",
+ "text/javascript1.2",
+ "text/javascript1.3",
+ "text/javascript1.4",
+ "text/javascript1.5",
+ "text/jscript",
+ "text/livescript",
+ "text/x-ecmascript",
+ "text/x-javascript",
+]);
+
+const scriptType = (el: AssemblyAttributed) => (el.getAttribute("type") || "").trim().toLowerCase();
+
+export function isJavaScriptType(el: AssemblyAttributed): boolean {
+ return JAVASCRIPT_TYPES.has(scriptType(el));
+}
+
+/**
+ * A data block (application/json, text/template, ...) or a classic nomodule script never runs,
+ * so it is mounted as authored.
+ */
+function isExecutableScript(el: AssemblyAttributed): boolean {
+ const type = scriptType(el);
+ if (type === "module" || type === "importmap") return true;
+ return JAVASCRIPT_TYPES.has(type) && el.getAttribute("nomodule") === null;
+}
+
+function inertScripts<TElement extends AssemblyAttributed>(
+ node: AssemblyQueryable<TElement> | null | undefined,
+): TElement[] {
+ return toArray(node?.querySelectorAll(SCRIPT_SELECTOR)).filter((el) => !isExecutableScript(el));
+}
+
+export function executableScripts<TElement extends AssemblyAttributed>(
+ node: AssemblyQueryable<TElement> | null | undefined,
+): TElement[] {
+ return toArray(node?.querySelectorAll(SCRIPT_SELECTOR)).filter(isExecutableScript);
+}
+
+/** The styles, scripts and links both paths extract, so the mounted copy must drop them. */
+export function extractedCompositionAssets<TElement extends AssemblyAttributed>(
+ node: AssemblyQueryable<TElement>,
+): TElement[] {
+ return [
+ ...toArray(node.querySelectorAll(`${STYLE_SELECTOR}, ${HOISTED_LINK_SELECTOR}`)),
+ ...executableScripts(node),
+ ];
+}
/**
* The compiler's nesting cap, enforced against the ancestry chain rather than a
@@ -136,6 +193,9 @@ export interface CompositionAssemblyPlan<TElement extends AssemblyAttributed> {
/** Head and content links to hoist into the host document. */
linkSources: TElement[];
+ /** Inert scripts the mounted root would leave behind; both paths mount them next to it. */
+ inertScriptsOutsideRoot: TElement[];
+
/**
* Nodes that may declare the composition's variable defaults, in precedence
* order — later wins. Full-document compositions declare on `<html>`;
@@ -159,9 +219,9 @@ function toArray<TElement>(items: Iterable<TElement> | null | undefined): TEleme
* how it is identified. Pure: it reads attributes and runs selectors, and does
* not mutate, fetch, or touch a filesystem.
*/
-export function planCompositionAssembly<TElement extends AssemblyAttributed>(
- input: CompositionAssemblyInput<TElement>,
-): CompositionAssemblyPlan<TElement> {
+export function planCompositionAssembly<
+ TElement extends AssemblyAttributed & AssemblyQueryable<TElement>,
+>(input: CompositionAssemblyInput<TElement>): CompositionAssemblyPlan<TElement> {
const { contentNode, head, documentElement, hasTemplate, compositionId } = input;
const compositionRoots = toArray(contentNode.querySelectorAll(COMPOSITION_ROOT_SELECTOR));
@@ -177,6 +237,7 @@ export function planCompositionAssembly<TElement extends AssemblyAttributed>(
// A templated composition's <head> belongs to its host page, not to it.
const assetHead = hasTemplate ? null : (head ?? null);
+ const mountedInert = innerRoot ? inertScripts(innerRoot) : [];
return {
innerRoot,
@@ -187,14 +248,15 @@ export function planCompositionAssembly<TElement extends AssemblyAttributed>(
...toArray(assetHead?.querySelectorAll(STYLE_SELECTOR)),
...toArray(contentNode.querySelectorAll(STYLE_SELECTOR)),
],
- scriptSources: [
- ...toArray(assetHead?.querySelectorAll(SCRIPT_SELECTOR)),
- ...toArray(contentNode.querySelectorAll(SCRIPT_SELECTOR)),
- ],
+ scriptSources: [...executableScripts(assetHead), ...executableScripts(contentNode)],
linkSources: [
...toArray(head?.querySelectorAll(HOISTED_LINK_SELECTOR)),
...toArray(contentNode.querySelectorAll(HOISTED_LINK_SELECTOR)),
],
+ inertScriptsOutsideRoot: [
+ ...inertScripts(assetHead),
+ ...(innerRoot ? inertScripts(contentNode).filter((el) => !mountedInert.includes(el)) : []),
+ ],
variableDefaultCarriers: [documentElement, innerRoot].filter(
(carrier): carrier is TElement => carrier != null,
),
diff --git a/packages/core/src/compiler/htmlBundler.test.ts b/packages/core/src/compiler/htmlBundler.test.ts
index 76588417f0..abbdafe8f3 100644
--- a/packages/core/src/compiler/htmlBundler.test.ts
+++ b/packages/core/src/compiler/htmlBundler.test.ts
@@ -3,8 +3,13 @@ import { mkdtempSync, writeFileSync, mkdirSync, symlinkSync, rmSync } from "node
import { tmpdir } from "node:os";
import { join } from "node:path";
import { parseHTML } from "linkedom";
+import { parse as parseJs } from "acorn";
import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";
-import { bundleToSingleHtml, emitRootCompositionVariableStyles } from "./htmlBundler";
+import {
+ bundleToSingleHtml,
+ emitRootCompositionVariableStyles,
+ parsesAsScript,
+} from "./htmlBundler";
import { ensureExternalScriptTag } from "./externalScripts";
import { resetUnknownEnumWarnings } from "../runtime/getVariables";
import { sanitizeCssValue } from "../runtime/applyVariableBindings";
@@ -2870,6 +2875,237 @@ describe("bundleToSingleHtml script order", () => {
});
});
+describe("bundleToSingleHtml composition scripts that are not JavaScript", () => {
+ const sceneFile = (id: string, extra: string) => `<template id="${id}-template">
+<div data-composition-id="${id}" data-width="320" data-height="180" data-duration="2">
+ ${extra}
+ <script>window.__timelines = window.__timelines || {}; window.__timelines.${id} = 1;</script>
+</div></template>`;
+
+ async function bundleFilm(
+ sceneExtra: string,
+ options?: { sceneParts?: boolean },
+ files: Record<string, string> = {},
+ ) {
+ const dir = makeTempProject({
+ "index.html": `<!doctype html>
+<html><body>
+ <div id="root" data-composition-id="main" data-width="320" data-height="180" data-duration="4">
+ <div data-composition-id="intro" data-composition-src="compositions/intro.html" data-start="0" data-duration="2"></div>
+ <div data-composition-id="scene" data-composition-src="compositions/scene.html" data-start="2" data-duration="2"></div>
+ </div>
+ <script>window.__timelines = window.__timelines || {}; window.__timelines.main = 1;</script>
+</body></html>`,
+ "compositions/intro.html": sceneFile("intro", ""),
+ "compositions/scene.html": sceneFile("scene", sceneExtra),
+ ...files,
+ });
+ try {
+ const html = await bundleToSingleHtml(dir, options);
+ return Object.assign(parseHTML(html).document, { html });
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }
+
+ const runnable = (document: Document) =>
+ [...document.querySelectorAll("body script:not([src]):not([nomodule])")].filter((el) =>
+ [null, AFTER_FONTS_SCRIPT_TYPE].includes(el.getAttribute("type")),
+ );
+ const parses = (el: Element) => {
+ try {
+ parseJs(el.textContent ?? "", { ecmaVersion: "latest", sourceType: "script" });
+ return true;
+ } catch {
+ return false;
+ }
+ };
+ const timelinesThatRun = (document: Document) =>
+ ["main", "intro", "scene"].filter((id) =>
+ runnable(document).some(
+ (el) => parses(el) && (el.textContent ?? "").includes(`__timelines.${id} =`),
+ ),
+ );
+
+ it("keeps a sub-composition's JSON data script readable and out of the JavaScript", async () => {
+ const document = await bundleFilm(
+ `<script type="application/json" id="meta">{"title": "x", "beats": [1, 2]}</script>`,
+ );
+ const meta = document.querySelector('script[type="application/json"]');
+ expect(meta?.getAttribute("id")).toBe("meta");
+ expect(JSON.parse(meta?.textContent ?? "")).toEqual({ title: "x", beats: [1, 2] });
+ expect(runnable(document).every(parses)).toBe(true);
+ expect(runnable(document).some((el) => el.textContent?.includes('"beats"'))).toBe(false);
+ expect(timelinesThatRun(document)).toEqual(["main", "intro", "scene"]);
+ });
+
+ // Bun 1.3's vm.Script accepts all of these; CI runs Node, so this pins the rules, not the engine.
+ it.each([
+ ["window.broken = {:", false],
+ ["window.broken = 1; return;", false],
+ ["export const broken = 1;", false],
+ ["window.ok = 1;", true],
+ ])("parsesAsScript(%j) is %s", (source, parses) => {
+ expect(parsesAsScript(source)).toBe(parses);
+ });
+
+ const BROKEN_INLINE = [`<script>window.broken = {:</script>`, {}] as const;
+ // An inline script is wrapped in a function, where return is legal; a local file is not.
+ const BROKEN_RETURN = [
+ `<script src="return.js"></script>`,
+ { "compositions/return.js": "window.broken = 1; return;" },
+ ] as const;
+ const BROKEN_FILE = [
+ `<script src="lib.js"></script>`,
+ { "compositions/lib.js": "export const broken = 1;" },
+ ] as const;
+ it.each([
+ [false, ...BROKEN_INLINE],
+ [true, ...BROKEN_INLINE],
+ [false, ...BROKEN_FILE],
+ [true, ...BROKEN_FILE],
+ [false, ...BROKEN_RETURN],
+ [true, ...BROKEN_RETURN],
+ ])(
+ "keeps a sub-composition script that does not parse apart, so the others still run (sceneParts %s, %s)",
+ async (sceneParts, extra, files) => {
+ const document = await bundleFilm(extra, { sceneParts }, files);
+ const broken = runnable(document).filter((el) => !parses(el));
+ expect(broken).toHaveLength(1);
+ expect(broken[0]!.textContent).toContain("broken");
+ expect(timelinesThatRun(document)).toEqual(["main", "intro", "scene"]);
+ },
+ );
+
+ it("mounts a JSON data script authored outside the composition root next to it", async () => {
+ const dir = makeTempProject({
+ "index.html": `<!doctype html>
+<html><body>
+ <div id="root" data-composition-id="main" data-width="320" data-height="180" data-duration="4">
+ <div data-composition-id="scene" data-composition-src="compositions/scene.html" data-start="0" data-duration="2"></div>
+ <div data-composition-id="page" data-composition-src="compositions/page.html" data-start="2" data-duration="2"></div>
+ </div>
+</body></html>`,
+ "compositions/scene.html": `<template id="scene-template">
+ <script type="application/json" id="beside">{"where": "template"}</script>
+ <div data-composition-id="scene" data-width="320" data-height="180"></div>
+</template>`,
+ "compositions/page.html": `<!doctype html>
+<html><head><script type="application/json" id="in-head">{"where": "head"}</script></head>
+<body><div data-composition-id="page" data-width="320" data-height="180"></div></body></html>`,
+ });
+ try {
+ const document = parseHTML(await bundleToSingleHtml(dir)).document;
+ const beside = document.querySelector('[data-composition-id="scene"] #beside');
+ const inHead = document.querySelector('[data-composition-id="page"] #in-head');
+ expect(JSON.parse(beside?.textContent ?? "")).toEqual({ where: "template" });
+ expect(JSON.parse(inHead?.textContent ?? "")).toEqual({ where: "head" });
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ it("does not run a sub-composition's nomodule script", async () => {
+ const document = await bundleFilm(`<script nomodule>window.LEGACY_ONLY = 1;</script>`);
+ expect(runnable(document).some((el) => el.textContent?.includes("LEGACY_ONLY"))).toBe(false);
+ });
+
+ it("runs an inline template composition's module script as a module and merges its import map", async () => {
+ const dir = makeTempProject({
+ "index.html": `<!doctype html>
+<html><body>
+ <template id="card-template"><div data-composition-id="card" data-width="320" data-height="180">
+ <script type="importmap">{"imports": {"lib": "./lib.js"}}</script>
+ <script type="module">import "lib"; window.CARD_MODULE = 1;</script>
+ </div></template>
+ <div id="root" data-composition-id="main" data-width="320" data-height="180" data-duration="2">
+ <div data-composition-id="card" data-start="0" data-duration="2"></div>
+ </div>
+</body></html>`,
+ });
+ try {
+ const document = parseHTML(await bundleToSingleHtml(dir)).document;
+ expect(runnable(document).some((el) => el.textContent?.includes("CARD_MODULE"))).toBe(false);
+ const modules = [...document.querySelectorAll("script")].filter((el) =>
+ (el.getAttribute("type") ?? "").includes("module"),
+ );
+ expect(modules.some((el) => el.textContent?.includes("CARD_MODULE"))).toBe(true);
+ const map = document.querySelector('script[type="importmap"]');
+ expect(JSON.parse(map?.textContent ?? "{}").imports).toEqual({ lib: "./lib.js" });
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ it("keeps an inline template composition's JSON data script readable and out of the JavaScript", async () => {
+ const dir = makeTempProject({
+ "index.html": `<!doctype html>
+<html><body>
+ <template id="card-template"><div data-composition-id="card" data-width="320" data-height="180">
+ <script type="application/json" id="card-meta">{"title": "x"}</script>
+ <script>window.__timelines = window.__timelines || {}; window.__timelines.card = 1;</script>
+ </div></template>
+ <div id="root" data-composition-id="main" data-width="320" data-height="180" data-duration="2">
+ <div data-composition-id="card" data-start="0" data-duration="2"></div>
+ </div>
+</body></html>`,
+ });
+ try {
+ const document = parseHTML(await bundleToSingleHtml(dir)).document;
+ const meta = document.querySelector('[data-composition-id="card"] #card-meta');
+ expect(meta?.getAttribute("type")).toBe("application/json");
+ expect(JSON.parse(meta?.textContent ?? "")).toEqual({ title: "x" });
+ expect(runnable(document).every(parses)).toBe(true);
+ expect(runnable(document).some((el) => el.textContent?.includes("__timelines.card ="))).toBe(
+ true,
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ it("mounts a JSON data script authored beside the root of an inline template composition", async () => {
+ const dir = makeTempProject({
+ "index.html": `<!doctype html>
+<html><body>
+ <template id="card-template">
+ <script type="application/json" id="beside">{"where": "template"}</script>
+ <div data-composition-id="card" data-width="320" data-height="180"></div>
+ </template>
+ <div id="root" data-composition-id="main" data-width="320" data-height="180" data-duration="2">
+ <div data-composition-id="card" data-start="0" data-duration="2"></div>
+ </div>
+</body></html>`,
+ });
+ try {
+ const document = parseHTML(await bundleToSingleHtml(dir)).document;
+ const beside = document.querySelector('[data-composition-id="card"] #beside');
+ expect(JSON.parse(beside?.textContent ?? "")).toEqual({ where: "template" });
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ it.each([
+ [false, `<script>window.broken = {:</script>`],
+ [true, `<script>window.broken = {:</script>`],
+ [true, ""],
+ ])(
+ "escapes a composition script it does not merge (sceneParts %s, extra %j)",
+ async (sceneParts, extra) => {
+ const document = await bundleFilm(
+ `<script src="lib.js"></script>${extra}`,
+ { sceneParts },
+ { "compositions/lib.js": 'window.tag = "</script><b>LEAK</b><!--";' },
+ );
+ expect(document.html).not.toContain("</script><b>LEAK");
+ const lib = runnable(document).find((el) => el.textContent?.includes("LEAK"));
+ const literal = lib?.textContent?.match(/window\.tag\s*=\s*("(?:[^"\\]|\\.)*")/)?.[1];
+ expect(new Function(`return ${literal}`)()).toBe("</script><b>LEAK</b><!--");
+ },
+ );
+});
+
describe("bundleToSingleHtml sceneParts", () => {
const film = () =>
makeTempProject({
diff --git a/packages/core/src/compiler/htmlBundler.ts b/packages/core/src/compiler/htmlBundler.ts
index b41893abcb..e51c48a875 100644
--- a/packages/core/src/compiler/htmlBundler.ts
+++ b/packages/core/src/compiler/htmlBundler.ts
@@ -6,17 +6,21 @@ import {
headStyleRuns,
INLINED_FILE_ATTR,
inlineScriptRuns,
- isJavaScriptType,
styleElementsFor,
type CompositionStyle,
} from "./scriptRuns";
+import {
+ executableScripts,
+ isJavaScriptType,
+ planCompositionAssembly,
+} from "./compositionAssembly";
import { SCENE_PART_ATTR } from "../sceneParts";
import {
ensureExternalScriptTag,
readExternalScriptAttributes,
type ExternalScriptAttributes,
} from "./externalScripts";
-import { emitMountedModuleScripts } from "./importMaps";
+import { emitMountedModuleScripts, parseImportMap, type ImportMap } from "./importMaps";
import { markFlattenedInnerRoot } from "../runtime/flattenedRoot";
export { FLATTENED_INNER_ROOT_STRIP_ATTRS } from "../runtime/flattenedRoot";
import { parseHostVariableValues, warnUnknownEnumValues } from "../runtime/getVariables";
@@ -24,6 +28,7 @@ import { sanitizeCssValue } from "../runtime/applyVariableBindings";
import { cssVariableName } from "../tokenSlug";
import { AsyncLocalStorage } from "async_hooks";
import { readFileSync, existsSync, statSync } from "fs";
+import { parse as parseJs } from "acorn";
import { resolve, relative, dirname, isAbsolute, sep } from "path";
import {
decodeCssEscapes,
@@ -48,6 +53,7 @@ import {
dedupeFontFaceRules,
scopeCssToComposition,
wrapInlineScriptWithErrorBoundary,
+ scopedModulePrelude,
wrapScopedCompositionScript,
} from "./compositionScoping";
import { validateHyperframeHtmlContract } from "./staticGuard";
@@ -58,7 +64,6 @@ import {
inlineSubCompositions,
refuseSwapsReachedByRootScripts,
} from "./inlineSubCompositions";
-import { queryByAttr } from "../utils/cssSelector";
import { isSafePath, resolveWithinProject } from "../safePath.js";
import { ensureHfIds } from "@hyperframes/parsers/hf-ids";
import { HF_COLOR_GRADING_ATTR } from "../colorGrading";
@@ -744,10 +749,14 @@ function coalesceHeadStylesAndBodyScripts(document: Document): void {
isPinned,
)) {
const mergedJs = joinJsChunks(members.map((el) => el.textContent || ""));
+ if (mergedJs && !parsesAsScript(mergedJs)) {
+ for (const el of members) el.textContent = inlineScriptSource(el.textContent || "");
+ continue;
+ }
for (const el of members) el.remove();
if (!mergedJs) continue;
const inlineScript = document.createElement("script");
- inlineScript.textContent = escapeInlineScriptSource(stripJsCommentsParserSafe(mergedJs));
+ inlineScript.textContent = inlineScriptSource(mergedJs);
if (anchor) anchor.before(inlineScript);
else document.body.appendChild(inlineScript);
}
@@ -799,6 +808,17 @@ function joinJsChunks(chunks: string[]): string {
.join("\n");
}
+// acorn in script mode, not the host engine: Bun 1.3's vm.Script compiles lazily and accepts anything.
+// esbuild accepts export, top-level await and return, which a <script> rejects; acorn does not.
+export function parsesAsScript(source: string): boolean {
+ try {
+ parseJs(source, { ecmaVersion: "latest", sourceType: "script" });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
function stripJsCommentsParserSafe(source: string): string {
if (!source) return source;
try {
@@ -809,6 +829,10 @@ function stripJsCommentsParserSafe(source: string): string {
}
}
+function inlineScriptSource(js: string): string {
+ return escapeInlineScriptSource(stripJsCommentsParserSafe(js));
+}
+
export interface BundleOptions {
/** Project-relative HTML entry to bundle. Defaults to `index.html`. */
entryFile?: string;
@@ -928,11 +952,24 @@ function hoistCompositionScripts(
authoredRootId: string | undefined;
seenCompScriptSrcs: Set<string>;
compScriptChunks: DeferredScriptChunk[];
+ importMaps: ImportMap[];
+ moduleScripts: string[];
},
): void {
- for (const scriptEl of [...container.querySelectorAll("script")]) {
+ for (const scriptEl of executableScripts(container)) {
const externalSrc = (scriptEl.getAttribute("src") || "").trim();
- if (externalSrc) {
+ const type = (scriptEl.getAttribute("type") || "").trim().toLowerCase();
+ if (!externalSrc && type === "importmap") {
+ const map = parseImportMap(scriptEl.textContent || "", (url) => url);
+ if (map) opts.importMaps.push(map);
+ else
+ console.warn(
+ `[HyperFrames] ${opts.compId}: import map is not valid JSON, so it is skipped.`,
+ );
+ } else if (!externalSrc && type === "module") {
+ const prelude = opts.compId ? scopedModulePrelude(opts.runtimeCompId || opts.compId) : "";
+ opts.moduleScripts.push(prelude + (scriptEl.textContent || ""));
+ } else if (externalSrc) {
hoistExternalScript(
externalSrc,
opts.projectDir,
@@ -1133,8 +1170,12 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
const hostIdentity = hostIdentityByElement.get(host);
const runtimeCompId = hostIdentity?.runtimeCompositionId || compId;
const innerDoc = parseHTMLContent(templateHtml);
- const innerRoot = queryByAttr(innerDoc, "data-composition-id", compId);
- const authoredRootId = innerRoot?.getAttribute("id")?.trim() || null;
+ const plan = planCompositionAssembly<Element>({
+ contentNode: innerDoc,
+ hasTemplate: true,
+ compositionId: compId,
+ });
+ const { innerRoot, authoredRootId } = plan;
const runtimeScope = runtimeCompId
? cssAttributeSelector("data-composition-id", runtimeCompId)
: "";
@@ -1183,6 +1224,8 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
authoredRootId: authoredRootId ?? undefined,
seenCompScriptSrcs,
compScriptChunks,
+ importMaps: subCompResult.importMaps,
+ moduleScripts: subCompResult.moduleScripts,
});
// Copy dimension attributes from inner root to host if not already set
@@ -1218,10 +1261,14 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
authoredRootId: undefined,
seenCompScriptSrcs,
compScriptChunks,
+ importMaps: subCompResult.importMaps,
+ moduleScripts: subCompResult.moduleScripts,
});
host.innerHTML = innerDoc.body.innerHTML || "";
}
+ for (const el of plan.inertScriptsOutsideRoot)
+ host.insertAdjacentHTML("beforeend", el.outerHTML);
}
// Remove the template element from the document
@@ -1261,12 +1308,15 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
}
}
for (const { scene, chunks } of scriptRuns) {
- const script = document.createElement("script");
- if (scene) script.setAttribute(SCENE_PART_ATTR, scene);
- script.textContent = joinJsChunks(
- chunks.map((chunk) => (typeof chunk === "string" ? chunk : chunk())),
- );
- document.body.appendChild(script);
+ const texts = chunks.map((chunk) => (typeof chunk === "string" ? chunk : chunk()));
+ const joined = joinJsChunks(texts);
+ const skipsRunMerge = Boolean(scene);
+ for (const text of parsesAsScript(joined) ? [joined] : texts.filter(Boolean)) {
+ const script = document.createElement("script");
+ if (scene) script.setAttribute(SCENE_PART_ATTR, scene);
+ script.textContent = skipsRunMerge ? inlineScriptSource(text) : text;
+ document.body.appendChild(script);
+ }
}
emitMountedModuleScripts(document, subCompResult.importMaps, subCompResult.moduleScripts);
diff --git a/packages/core/src/compiler/index.ts b/packages/core/src/compiler/index.ts
index 06e102e96c..c8fda718af 100644
--- a/packages/core/src/compiler/index.ts
+++ b/packages/core/src/compiler/index.ts
@@ -36,6 +36,7 @@ export {
prepareFlattenedInnerRoot,
FLATTENED_INNER_ROOT_STRIP_ATTRS,
emitRootCompositionVariableStyles,
+ parsesAsScript,
} from "./htmlBundler";
export { readDeclaredDefaults, parseHostVariableValues } from "../runtime/getVariables";
@@ -69,11 +70,11 @@ export {
deferScriptsUntilFonts,
headStyleRuns,
inlineScriptRuns,
- isJavaScriptType,
styleElementsFor,
type CompositionStyle,
type InlineScriptRun,
} from "./scriptRuns";
+export { isJavaScriptType } from "./compositionAssembly";
// Static guard
export {
diff --git a/packages/core/src/compiler/inlineSubCompositions.ts b/packages/core/src/compiler/inlineSubCompositions.ts
index fd3f15731b..d49fb693b0 100644
--- a/packages/core/src/compiler/inlineSubCompositions.ts
+++ b/packages/core/src/compiler/inlineSubCompositions.ts
@@ -43,7 +43,7 @@ import {
import {
enumerateNestedCompositionHosts,
planCompositionAssembly,
- EXTRACTED_COMPOSITION_ASSET_SELECTOR,
+ extractedCompositionAssets,
} from "./compositionAssembly";
import { SCENE_NO_SWAP_ATTR, SCENE_PART_ATTR } from "../sceneParts";
@@ -610,8 +610,7 @@ export function inlineSubCompositions(
// Inject content into the host element
if (innerRoot) {
innerRoot.setAttribute("data-composition-file", src);
- for (const child of [...innerRoot.querySelectorAll(EXTRACTED_COMPOSITION_ASSET_SELECTOR)])
- child.remove();
+ for (const child of extractedCompositionAssets(innerRoot)) child.remove();
if (flattenInnerRoot) {
const prepared = flattenInnerRoot(innerRoot);
if (!compId && scopeCompId) {
@@ -635,14 +634,15 @@ export function inlineSubCompositions(
}
}
} else {
- for (const child of [...contentDoc.querySelectorAll(EXTRACTED_COMPOSITION_ASSET_SELECTOR)])
- child.remove();
+ for (const child of extractedCompositionAssets(contentDoc)) child.remove();
// linkedom fragment parsing: when content is `<div data-composition-id="X">...</div>`,
// the div becomes documentElement and body is empty. Fall back to documentElement.outerHTML
// to preserve the composition wrapper.
const bodyHtml = contentDoc.body?.innerHTML || "";
hostEl.innerHTML = bodyHtml || contentDoc.documentElement?.outerHTML || "";
}
+ for (const el of plan.inertScriptsOutsideRoot)
+ hostEl.insertAdjacentHTML("beforeend", el.outerHTML);
hostEl.setAttribute("data-composition-file", src);
hostEl.removeAttribute("data-composition-src");
diff --git a/packages/core/src/compiler/scriptRuns.ts b/packages/core/src/compiler/scriptRuns.ts
index b2ee24b44f..c0ec7c8b37 100644
--- a/packages/core/src/compiler/scriptRuns.ts
+++ b/packages/core/src/compiler/scriptRuns.ts
@@ -1,34 +1,11 @@
+import { isJavaScriptType } from "./compositionAssembly";
+
export interface InlineScriptRun {
members: Element[];
/** First later script that executes on its own; the merged run must stay before it. Null: end of body. */
anchor: Element | null;
}
-// The HTML spec's JavaScript MIME type essence matches: a script with any of these types runs as classic.
-const JAVASCRIPT_TYPES = new Set([
- "",
- "application/ecmascript",
- "application/javascript",
- "application/x-ecmascript",
- "application/x-javascript",
- "text/ecmascript",
- "text/javascript",
- "text/javascript1.0",
- "text/javascript1.1",
- "text/javascript1.2",
- "text/javascript1.3",
- "text/javascript1.4",
- "text/javascript1.5",
- "text/jscript",
- "text/livescript",
- "text/x-ecmascript",
- "text/x-javascript",
-]);
-
-export function isJavaScriptType(el: Element): boolean {
- return JAVASCRIPT_TYPES.has((el.getAttribute("type") || "").trim().toLowerCase());
-}
-
function isClassicInline(el: Element): boolean {
return !el.hasAttribute("nomodule") && isJavaScriptType(el);
}
diff --git a/packages/core/src/runtime/compositionLoader.test.ts b/packages/core/src/runtime/compositionLoader.test.ts
index 3f066cce84..325bfa1135 100644
--- a/packages/core/src/runtime/compositionLoader.test.ts
+++ b/packages/core/src/runtime/compositionLoader.test.ts
@@ -1503,6 +1503,54 @@ describe("loadCompositions inline templates", () => {
expect(injectedScripts[0].textContent).toContain("inline template script");
});
+ it("leaves a JSON data script in the mounted content instead of running it", async () => {
+ const template = document.createElement("template");
+ template.id = "data-comp-template";
+ template.innerHTML = `
+ <div data-composition-id="data-comp" data-width="1920" data-height="1080">
+ <script type="application/json" id="meta">{"title": "x"}</script>
+ <script>window.__dataCompRan = 1;</script>
+ </div>
+ `;
+ document.body.appendChild(template);
+ const host = document.createElement("div");
+ host.setAttribute("data-composition-id", "data-comp");
+ document.body.appendChild(host);
+
+ const { injectedScripts } = await loadFixture();
+
+ expect(injectedScripts.map((script) => script.textContent).join("\n")).not.toContain("title");
+ expect(injectedScripts.some((script) => script.textContent?.includes("__dataCompRan"))).toBe(
+ true,
+ );
+ const meta = host.querySelector("#meta");
+ expect(meta?.getAttribute("type")).toBe("application/json");
+ expect(JSON.parse(meta?.textContent ?? "")).toEqual({ title: "x" });
+ });
+
+ it("mounts a JSON data script authored beside the composition root, and never runs a nomodule script", async () => {
+ const template = document.createElement("template");
+ template.id = "beside-comp-template";
+ template.innerHTML = `
+ <script type="application/json" id="beside">{"where": "template"}</script>
+ <script nomodule>window.__legacyOnly = 1;</script>
+ <div data-composition-id="beside-comp" data-width="1920" data-height="1080"></div>
+ `;
+ document.body.appendChild(template);
+ const host = document.createElement("div");
+ host.setAttribute("data-composition-id", "beside-comp");
+ document.body.appendChild(host);
+
+ const { injectedScripts } = await loadFixture();
+
+ expect(JSON.parse(host.querySelector("#beside")?.textContent ?? "")).toEqual({
+ where: "template",
+ });
+ expect(injectedScripts.some((script) => script.textContent?.includes("__legacyOnly"))).toBe(
+ false,
+ );
+ });
+
it("copies dimension attributes from template inner root to host", async () => {
const template = document.createElement("template");
template.id = "dim-comp-template";
diff --git a/packages/core/src/runtime/compositionLoader.ts b/packages/core/src/runtime/compositionLoader.ts
index 0f7814e0af..3e83a8e219 100644
--- a/packages/core/src/runtime/compositionLoader.ts
+++ b/packages/core/src/runtime/compositionLoader.ts
@@ -5,7 +5,7 @@ import {
} from "../compiler/svgSelectorAliases";
import {
planCompositionAssembly,
- EXTRACTED_COMPOSITION_ASSET_SELECTOR,
+ extractedCompositionAssets,
} from "../compiler/compositionAssembly";
import {
scopeCssToComposition,
@@ -225,7 +225,7 @@ function resetCompositionHost(host: Element) {
* inline-template path, and mutating it would leave a remount with no styles.
*/
function stripExtractedCompositionAssets(node: ParentNode): void {
- for (const el of Array.from(node.querySelectorAll(EXTRACTED_COMPOSITION_ASSET_SELECTOR))) {
+ for (const el of extractedCompositionAssets(node)) {
el.remove();
}
}
@@ -579,6 +579,8 @@ async function mountCompositionContent(params: {
params.host.innerHTML = params.fallbackBodyInnerHtml;
stripExtractedCompositionAssets(params.host);
}
+ for (const el of plan.inertScriptsOutsideRoot)
+ params.host.appendChild(document.importNode(el, true));
// Stash the per-instance variables BEFORE running scripts. The scoped
// `getVariables()` injected by `compositionScoping.ts` reads from
diff --git a/packages/producer/src/services/htmlCompiler.scriptOrder.test.ts b/packages/producer/src/services/htmlCompiler.scriptOrder.test.ts
index 9661ad0ea2..b5b3ba21b6 100644
--- a/packages/producer/src/services/htmlCompiler.scriptOrder.test.ts
+++ b/packages/producer/src/services/htmlCompiler.scriptOrder.test.ts
@@ -140,4 +140,90 @@ describe("compileForRender script order", () => {
expect(text.some((t) => t.includes(mark))).toBe(true);
}
});
+
+ it("merges adjacent inline scripts on a page with no <head>", async () => {
+ const dir = project({
+ "index.html": `<!doctype html>
+<html><body>
+ <div data-composition-id="root" data-width="320" data-height="180"></div>
+ <script>window.FIRST_HALF = 1;</script>
+ <script>window.SECOND_HALF = 1;</script>
+</body></html>`,
+ });
+ const { html } = await compileForRender(dir, join(dir, "index.html"), join(dir, ".downloads"), {
+ allowSystemFontCapture: false,
+ });
+ const scripts = [...parseHTML(html).document.querySelectorAll("body script")];
+ const first = scripts.find((el) => el.textContent?.includes("FIRST_HALF"));
+ expect(first?.textContent).toContain("SECOND_HALF");
+ });
+
+ describe("composition scripts that are not JavaScript", () => {
+ const scene = (id: string, extra: string) => `<template id="${id}-template">
+<div data-composition-id="${id}" data-width="320" data-height="180" data-duration="2">
+ ${extra}
+ <script>window.__timelines = window.__timelines || {}; window.__timelines.${id} = 1;</script>
+</div></template>`;
+
+ async function compileFilm(sceneExtra: string) {
+ const dir = project({
+ "index.html": `<!doctype html>
+<html><head></head><body>
+ <div id="root" data-composition-id="main" data-width="320" data-height="180" data-duration="4">
+ <div data-composition-id="intro" data-composition-src="compositions/intro.html" data-start="0" data-duration="2"></div>
+ <div data-composition-id="scene" data-composition-src="compositions/scene.html" data-start="2" data-duration="2"></div>
+ </div>
+ <script>window.__timelines = window.__timelines || {}; window.__timelines.main = 1;</script>
+</body></html>`,
+ "compositions/intro.html": scene("intro", ""),
+ "compositions/scene.html": scene("scene", sceneExtra),
+ });
+ const { html } = await compileForRender(
+ dir,
+ join(dir, "index.html"),
+ join(dir, ".downloads"),
+ {
+ allowSystemFontCapture: false,
+ },
+ );
+ return parseHTML(html).document;
+ }
+
+ const runnable = (document: Document) => [
+ ...document.querySelectorAll(`body script[type="${AFTER_FONTS_SCRIPT_TYPE}"]:not([src])`),
+ ];
+ const parses = (el: Element) => {
+ try {
+ new Function(el.textContent ?? "");
+ return true;
+ } catch {
+ return false;
+ }
+ };
+ const timelinesThatRun = (document: Document) =>
+ ["main", "intro", "scene"].filter((id) =>
+ runnable(document).some(
+ (el) => parses(el) && (el.textContent ?? "").includes(`__timelines.${id} =`),
+ ),
+ );
+
+ it("keeps a sub-composition's JSON data script readable and out of the JavaScript", async () => {
+ const document = await compileFilm(
+ `<script type="application/json" id="meta">{"title": "x", "beats": [1, 2]}</script>`,
+ );
+ const meta = document.querySelector('script[type="application/json"]');
+ expect(meta?.getAttribute("id")).toBe("meta");
+ expect(JSON.parse(meta?.textContent ?? "")).toEqual({ title: "x", beats: [1, 2] });
+ expect(runnable(document).every(parses)).toBe(true);
+ expect(timelinesThatRun(document)).toEqual(["main", "intro", "scene"]);
+ });
+
+ it("keeps a sub-composition script that does not parse apart, so the others still run", async () => {
+ const document = await compileFilm(`<script>window.broken = {:</script>`);
+ const broken = runnable(document).filter((el) => !parses(el));
+ expect(broken).toHaveLength(1);
+ expect(broken[0]!.textContent).toContain("window.broken");
+ expect(timelinesThatRun(document)).toEqual(["main", "intro", "scene"]);
+ });
+ });
});
diff --git a/packages/producer/src/services/htmlCompiler.ts b/packages/producer/src/services/htmlCompiler.ts
index db9762c74b..4c8417c954 100644
--- a/packages/producer/src/services/htmlCompiler.ts
+++ b/packages/producer/src/services/htmlCompiler.ts
@@ -54,6 +54,7 @@ import {
parseHostVariableValues,
headStyleRuns,
inlineScriptRuns,
+ parsesAsScript,
styleElementsFor,
insertBeforeCloseTag,
isRuntimeFileUrl,
@@ -906,9 +907,9 @@ function coalesceHeadStylesAndBodyScripts(html: string): string {
const { document } = parseHTML(html);
const head = document.querySelector("head");
const body = document.querySelector("body");
- if (!head) return html;
+ if (!head && !body) return html;
- const styleEls = Array.from(head.querySelectorAll("style"));
+ const styleEls = head ? Array.from(head.querySelectorAll("style")) : [];
const importRe = /@import\s+url\([^)]*\)\s*;|@import\s+["'][^"']+["']\s*;/gi;
for (const run of styleEls.length > 1 ? headStyleRuns(styleEls) : []) {
const imports: string[] = [];
@@ -945,6 +946,7 @@ function coalesceHeadStylesAndBodyScripts(html: string): string {
.filter(Boolean)
.join("\n;\n")
.trim();
+ if (mergedJs && !parsesAsScript(mergedJs)) continue;
for (const el of members) el.remove();
if (!mergedJs) continue;
const script = document.createElement("script");
@@ -1103,9 +1105,12 @@ function inlineSubCompositions(
let pending = variablesByCompScript ? [variablesByCompScript] : [];
const flushInline = () => {
if (!pending.length) return;
- const scriptEl = document.createElement("script");
- scriptEl.textContent = pending.join("\n;\n");
- body.appendChild(scriptEl);
+ const joined = pending.join("\n;\n");
+ for (const text of parsesAsScript(joined) ? [joined] : pending) {
+ const scriptEl = document.createElement("script");
+ scriptEl.textContent = text;
+ body.appendChild(scriptEl);
+ }
pending = [];
};
for (const item of result.scriptItems) {