Skip to content

Commit ca6ed2c

Browse files
committed
fix(core): preview, render and mount agree on nested sub-composition ids and order
The producer parity test now mounts through the real file server, so the loader's root-relative URLs reach real files. Late nested hosts get their runtime id from core's shared identity map (a repeated composition is suffixed on every instance, a single one keeps its authored id when free), replacing the producer's private copy. The runtime loader still fetches sub-compositions concurrently but mounts them in document order, so their stylesheets land in <head> in a stable cascade order.
1 parent fe51808 commit ca6ed2c

5 files changed

Lines changed: 150 additions & 82 deletions

File tree

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

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -542,13 +542,53 @@ function countBundledAuthoredCompositionIds(hosts: Element[]): Map<string, numbe
542542
return counts;
543543
}
544544

545+
const MOUNTED_HOST =
546+
"[data-composition-src], [data-composition-file], [data-hf-original-composition-id]";
547+
548+
/** Assigns hosts the inliner discovers after the initial pass, on first lookup: a repeated
549+
* composition is suffixed on every late instance, a single one keeps its authored id when free. */
550+
class BundledHostIdentityMap extends Map<Element, BundledHostCompositionIdentity> {
551+
override get(host: Element): BundledHostCompositionIdentity | undefined {
552+
const existing = super.get(host);
553+
if (existing) return existing;
554+
555+
const identity = getBundledHostCompositionIdentity(host);
556+
const authoredId = identity.authoredCompositionId;
557+
if (!authoredId || !shouldAssignBundledRuntimeCompositionId(host, host.ownerDocument)) {
558+
this.set(host, identity);
559+
return identity;
560+
}
561+
562+
const others = Array.from(host.ownerDocument.querySelectorAll("[data-composition-id]")).filter(
563+
(element) => element !== host,
564+
);
565+
const taken = new Set(others.map((element) => element.getAttribute("data-composition-id")));
566+
const repeated = others.some(
567+
(element) =>
568+
element.matches(MOUNTED_HOST) &&
569+
getBundledHostCompositionIdentity(element).authoredCompositionId === authoredId,
570+
);
571+
let instanceIndex = repeated ? 1 : 0;
572+
const idAt = (index: number) =>
573+
index === 0 ? authoredId : uniqueCompositionId(authoredId, index);
574+
while (taken.has(idAt(instanceIndex))) instanceIndex += 1;
575+
const runtimeId = idAt(instanceIndex);
576+
if (instanceIndex > 0) host.setAttribute("data-hf-original-composition-id", authoredId);
577+
else host.removeAttribute("data-hf-original-composition-id");
578+
host.setAttribute("data-composition-id", runtimeId);
579+
const assigned = { authoredCompositionId: authoredId, runtimeCompositionId: runtimeId };
580+
this.set(host, assigned);
581+
return assigned;
582+
}
583+
}
584+
545585
// fallow-ignore-next-line complexity
546586
export function assignBundledRuntimeCompositionIds(
547587
hosts: Element[],
548588
counts: Map<string, number> = countBundledAuthoredCompositionIds(hosts),
549589
): Map<Element, BundledHostCompositionIdentity> {
550590
const instanceByCompositionId = new Map<string, number>();
551-
const identities = new Map<Element, BundledHostCompositionIdentity>();
591+
const identities = new BundledHostIdentityMap();
552592

553593
for (const host of hosts) {
554594
const { authoredCompositionId, runtimeCompositionId: previousRuntimeCompositionId } =

‎packages/core/src/runtime/compositionLoader.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,33 @@ describe("loadCompositions external hosts", () => {
122122
expect(document.querySelectorAll("[data-composition-src] p")).toHaveLength(8);
123123
});
124124

125+
it("adds stylesheets in document order even when an earlier host's fetch finishes last", async () => {
126+
appendExternalHost("https://example.com/order-a.html", "order-a");
127+
appendExternalHost("https://example.com/order-b.html", "order-b");
128+
const page = (name: string) =>
129+
new Response(
130+
`<html><head><link rel="stylesheet" href="./${name}.css"></head><body><p>${name}</p></body></html>`,
131+
{ status: 200 },
132+
);
133+
vi.useFakeTimers();
134+
try {
135+
vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {
136+
if (!String(input).endsWith("order-a.html")) return page("order-b");
137+
await new Promise((resolve) => setTimeout(resolve, 10));
138+
return page("order-a");
139+
});
140+
const loading = loadFixture();
141+
await vi.runAllTimersAsync();
142+
await loading;
143+
} finally {
144+
vi.useRealTimers();
145+
}
146+
const hrefs = Array.from(document.head.querySelectorAll('link[href*="order-"]'), (link) =>
147+
link.getAttribute("href"),
148+
);
149+
expect(hrefs).toEqual(["https://example.com/order-a.css", "https://example.com/order-b.css"]);
150+
});
151+
125152
it("refuses a circular nested external reference without fetching it again", async () => {
126153
const base = document.createElement("base");
127154
base.href = "https://example.com/";

‎packages/core/src/runtime/compositionLoader.ts‎

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -725,10 +725,11 @@ async function mountExternalCompositions(
725725
return !parent || attemptedPaths.has(parent);
726726
});
727727

728+
type PendingMount = () => Promise<MountedComposition | null>;
728729
const mounted: Array<MountedComposition | null> = [];
729730
for (let offset = 0; offset < hosts.length; offset += 4) {
730731
const batch = await Promise.all(
731-
hosts.slice(offset, offset + 4).map(async (host): Promise<MountedComposition | null> => {
732+
hosts.slice(offset, offset + 4).map(async (host): Promise<PendingMount | null> => {
732733
const src = host.getAttribute("data-composition-src");
733734
if (!src) return null;
734735
const hostIdentity = hostIdentityByElement.get(host);
@@ -764,18 +765,25 @@ async function mountExternalCompositions(
764765
failed(new Error(refusal));
765766
return null;
766767
}
767-
const mount = async (mountParams: Parameters<typeof mountCompositionContent>[0]) => {
768-
const composition = await mountCompositionContent(mountParams);
769-
const runScripts = composition.runScripts;
770-
composition.runScripts = async () => {
768+
const mount =
769+
(mountParams: Parameters<typeof mountCompositionContent>[0]): PendingMount =>
770+
async () => {
771771
try {
772-
await runScripts();
772+
const composition = await mountCompositionContent(mountParams);
773+
const runScripts = composition.runScripts;
774+
composition.runScripts = async () => {
775+
try {
776+
await runScripts();
777+
} catch (error) {
778+
failed(error);
779+
}
780+
};
781+
return composition;
773782
} catch (error) {
774783
failed(error);
784+
return null;
775785
}
776786
};
777-
return composition;
778-
};
779787
try {
780788
const localTemplate =
781789
authoredCompositionId != null
@@ -784,7 +792,7 @@ async function mountExternalCompositions(
784792
)
785793
: null;
786794
if (localTemplate) {
787-
return await mount({
795+
return mount({
788796
host,
789797
authoredCompositionId,
790798
runtimeCompositionId,
@@ -816,7 +824,7 @@ async function mountExternalCompositions(
816824
)
817825
: null) ?? doc.querySelector<HTMLTemplateElement>("template");
818826
const sourceNode = template ? template.content : doc.body;
819-
return await mount({
827+
return mount({
820828
host,
821829
authoredCompositionId,
822830
runtimeCompositionId,
@@ -848,7 +856,9 @@ async function mountExternalCompositions(
848856
}
849857
}),
850858
);
851-
mounted.push(...batch);
859+
// Fetch concurrently, mount in document order: mounting appends each composition's
860+
// links and styles to <head>, and that order is the cascade order.
861+
for (const pending of batch) mounted.push(pending ? await pending() : null);
852862
}
853863
return mounted.filter((composition): composition is MountedComposition => composition !== null);
854864
}

‎packages/producer/src/services/htmlCompiler.parity.test.ts‎

Lines changed: 59 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,10 @@ import {
1111
// Deep import: the mount path is not part of core's published export map (it is
1212
// bundled into the runtime IIFE, not imported by consumers). Same shape as
1313
// engine/src/services/videoFrameExtractor.test.ts reaching into core's runtime.
14+
import { nestedCompositionPathFixture } from "../../../core/src/compiler/nestedCompositionPath.testFixture.js";
1415
import { loadCompositions } from "../../../core/src/runtime/compositionLoader.js";
1516
import { compileForRender } from "./htmlCompiler.js";
17+
import { createFileServer } from "@hyperframes/engine";
1618
import { getVerifiedHyperframeRuntimeSource } from "./hyperframeRuntimeLoader.js";
1719

1820
vi.mock("../utils/urlDownloader.js", async (importOriginal) => ({
@@ -76,7 +78,7 @@ type ParityContract = ReturnType<typeof extractCompiledHtmlParityContract>;
7678

7779
/**
7880
* Mount the project the way the player does — parse `index.html` into the live
79-
* document, serve its sub-compositions over a stubbed `fetch`, and let the
81+
* document, serve its sub-compositions through the capture file server, and let the
8082
* runtime assemble them — then read the same contract off the resulting DOM.
8183
*
8284
* This is the third assembly path. Both compiler arms below run the same code
@@ -88,20 +90,26 @@ async function mountContract(dir: string, indexHtml: string): Promise<ParityCont
8890
const parsed = new DOMParser().parseFromString(indexHtml, "text/html");
8991
document.head.innerHTML = parsed.head.innerHTML;
9092
document.body.innerHTML = parsed.body.innerHTML;
91-
vi.spyOn(globalThis, "fetch").mockImplementation(async (input) =>
92-
Promise.resolve(new Response(readFileSync(join(dir, String(input)), "utf8"), { status: 200 })),
93-
);
94-
await loadCompositions({
95-
injectedStyles: [],
96-
injectedScripts: [],
97-
injectedLinks: [],
98-
parseDimensionPx: (value: string | null) => (value ? `${value}px` : null),
99-
// A mount that fails is not a parity result. Surface it instead of
100-
// comparing the contract of an empty host against a compiled one.
101-
onDiagnostic: ({ code, details }) => {
102-
throw new Error(`mount diagnostic ${code}: ${JSON.stringify(details)}`);
103-
},
104-
});
93+
const server = await createFileServer({ projectDir: dir });
94+
const base = document.createElement("base");
95+
base.href = `${server.url}/`;
96+
document.head.prepend(base);
97+
try {
98+
await loadCompositions({
99+
injectedStyles: [],
100+
injectedScripts: [],
101+
injectedLinks: [],
102+
parseDimensionPx: (value: string | null) => (value ? `${value}px` : null),
103+
// A mount that fails is not a parity result. Surface it instead of
104+
// comparing the contract of an empty host against a compiled one.
105+
onDiagnostic: ({ code, details }) => {
106+
throw new Error(`mount diagnostic ${code}: ${JSON.stringify(details)}`);
107+
},
108+
});
109+
} finally {
110+
base.remove();
111+
server.close();
112+
}
105113
return extractCompiledHtmlParityContract(`<!doctype html>${document.documentElement.outerHTML}`);
106114
}
107115

@@ -453,6 +461,42 @@ function assembledContract(contract: ParityContract) {
453461
}
454462

455463
describe("mount/compile assembly parity", () => {
464+
it.each([
465+
{ name: "a free authored id", extraHosts: "", ids: ["card"] },
466+
{
467+
name: "an authored id collision",
468+
extraHosts:
469+
'<div data-composition-id="card" data-composition-src="compositions/cards/card.html"></div>',
470+
ids: ["card", "card__hf1"],
471+
},
472+
{
473+
name: "a reserved suffix collision",
474+
extraHosts:
475+
'<div data-composition-id="card" data-composition-src="compositions/cards/card.html"></div><div data-composition-id="card__hf1" data-composition-src="compositions/cards/card.html"></div>',
476+
ids: ["card", "card__hf1", "card__hf2"],
477+
},
478+
])(
479+
"mounts nested project-root paths with $name identically on all three paths",
480+
async ({ extraHosts, ids }) => {
481+
const result = await contracts({
482+
...nestedCompositionPathFixture,
483+
"index.html": nestedCompositionPathFixture["index.html"]!.replace(
484+
'<div data-composition-id="scene"',
485+
`${extraHosts}<div data-composition-id="scene"`,
486+
),
487+
});
488+
expect(result.render).toEqual(result.preview);
489+
expect(assembledContract(result.mount)).toEqual(assembledContract(result.preview));
490+
expect(result.preview.compositions.map((c) => c.id)).toEqual(expect.arrayContaining(ids));
491+
const cards = [...document.querySelectorAll("[data-proof]")];
492+
expect(cards.map((card) => card.textContent)).toEqual(ids.map(() => "Project-root card"));
493+
const hostIds = cards.map((card) =>
494+
card.closest("[data-composition-src]")?.getAttribute("data-composition-id"),
495+
);
496+
expect(hostIds).toEqual(ids);
497+
},
498+
);
499+
456500
it("keeps a fixture set that still covers the shape the mount path used to drop", () => {
457501
expect(MOUNT_PARITY_FIXTURES.length).toBeGreaterThan(0);
458502
const siblingShaped = MOUNT_PARITY_FIXTURES.filter((fixture) =>

‎packages/producer/src/services/htmlCompiler.ts‎

Lines changed: 2 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,6 @@ import { gsapCdnDist } from "@hyperframes/core/gsap-cdn";
3939
import {
4040
assignBundledRuntimeCompositionIds,
4141
assignMediaRenderIds,
42-
type BundledHostCompositionIdentity,
4342
buildVariablesByCompScript,
4443
inlineSubCompositions as inlineSubCompositionsShared,
4544
ensureExternalLinkTag,
@@ -841,55 +840,6 @@ function promoteCssImportsToLinkTags(html: string): string {
841840
return document.toString();
842841
}
843842

844-
class ProducerHostIdentityMap extends Map<Element, BundledHostCompositionIdentity> {
845-
readonly #document: Document;
846-
readonly #lateInstanceByCompositionId = new Map<string, number>();
847-
848-
constructor(document: Document, initialHosts: Element[]) {
849-
super(assignBundledRuntimeCompositionIds(initialHosts));
850-
this.#document = document;
851-
}
852-
853-
override get(host: Element): BundledHostCompositionIdentity | undefined {
854-
const existing = super.get(host);
855-
if (existing) return existing;
856-
857-
// The shared inliner discovers nested hosts after the producer's initial
858-
// DOM scan. Assign those late hosts on first use so their scope and
859-
// variables key are fixed before any content is processed.
860-
const authoredCompositionId =
861-
(
862-
host.getAttribute("data-hf-original-composition-id") ||
863-
host.getAttribute("data-composition-id") ||
864-
""
865-
).trim() || null;
866-
if (!authoredCompositionId) {
867-
const identity = { authoredCompositionId: null, runtimeCompositionId: null };
868-
this.set(host, identity);
869-
return identity;
870-
}
871-
872-
let instanceIndex = this.#lateInstanceByCompositionId.get(authoredCompositionId) || 0;
873-
let runtimeCompositionId: string;
874-
do {
875-
instanceIndex += 1;
876-
runtimeCompositionId = `${authoredCompositionId}__hf${instanceIndex}`;
877-
} while (
878-
Array.from(this.#document.querySelectorAll("[data-composition-id]")).some(
879-
(element) =>
880-
element !== host && element.getAttribute("data-composition-id") === runtimeCompositionId,
881-
)
882-
);
883-
this.#lateInstanceByCompositionId.set(authoredCompositionId, instanceIndex);
884-
885-
host.setAttribute("data-hf-original-composition-id", authoredCompositionId);
886-
host.setAttribute("data-composition-id", runtimeCompositionId);
887-
const identity = { authoredCompositionId, runtimeCompositionId };
888-
this.set(host, identity);
889-
return identity;
890-
}
891-
}
892-
893843
/**
894844
* Merge each run of adjacent same-condition `<head>` `<style>` blocks into one, `@import`
895845
* rules at its top, and merge each run of adjacent inline `<body>` `<script>` blocks
@@ -989,18 +939,15 @@ function inlineSubCompositions(
989939
// Assign per-instance runtime composition ids before each host is inlined,
990940
// mirroring the preview bundler. Initial hosts are assigned as one pre-pass;
991941
// hosts discovered by the shared inliner's queue are assigned lazily by the
992-
// map above. When the same sub-composition (same authored
942+
// same identity map. When the same sub-composition (same authored
993943
// data-composition-id) is mounted more than once — the reusable-template
994944
// pattern from issue #2064 — each host is rewritten to a unique runtime id
995945
// (`card__hf1`, `card__hf2`). Without this, every instance shares one
996946
// `__hfVariablesByComp` key and one scope selector: the last mount's
997947
// data-variable-values clobbers the earlier ones and all-but-one instance
998948
// renders blank. #2066 fixed the single-instance case but left this
999949
// divergence (snapshot/preview correct, render wrong).
1000-
const hostIdentityByElement = new ProducerHostIdentityMap(
1001-
document as unknown as Document,
1002-
hosts as unknown as Element[],
1003-
);
950+
const hostIdentityByElement = assignBundledRuntimeCompositionIds(hosts as unknown as Element[]);
1004951

1005952
const result = inlineSubCompositionsShared(
1006953
document as unknown as Document,

0 commit comments

Comments
 (0)