Skip to content

Commit 571c99c

Browse files
fix(sdk): read a composition's variables from its root when its html has none (#4454)
* fix(sdk): read a composition's variables from its root when its html has none * fix: composition metadata and lint also read variables declared on the root * fix(sdk): keep root declarations on the root through undo and prefer them like the runtime * fix(sdk): read variables from both <html> and the root, editing each where declared
1 parent 278bc71 commit 571c99c

13 files changed

Lines changed: 297 additions & 133 deletions

File tree

‎packages/lint/src/rules/composition.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1119,6 +1119,15 @@ describe("composition rules", () => {
11191119
});
11201120

11211121
describe("invalid_composition_variables_declaration", () => {
1122+
it("checks a declaration on the composition root too", async () => {
1123+
const html = `<html><body><div data-composition-id="x" data-composition-variables='[{"id":12345}]'></div></body></html>`;
1124+
const result = await lintHyperframeHtml(html);
1125+
const finding = result.findings.find(
1126+
(f) => f.code === "invalid_composition_variables_declaration",
1127+
);
1128+
expect(finding).toBeDefined();
1129+
});
1130+
11221131
it("warns when data-composition-variables is unparseable JSON", async () => {
11231132
const html = `<html data-composition-variables='[{not json'><body><div data-composition-id="x"></div></body></html>`;
11241133
const result = await lintHyperframeHtml(html);

‎packages/lint/src/rules/composition.ts‎

Lines changed: 98 additions & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -384,6 +384,99 @@ function collectDeclaredVariableIds(htmlTagRaw: string): Set<string> | null {
384384
* template/fragment sub-comps hold it on their composition root div. Returns
385385
* null if any occurrence has unparseable JSON.
386386
*/
387+
// fallow-ignore-next-line complexity
388+
function variablesDeclarationFindings(
389+
tag: OpenTag,
390+
tags: readonly OpenTag[],
391+
): HyperframeLintFinding[] {
392+
const raw = readJsonAttr(tag.raw, "data-composition-variables");
393+
if (!raw) return [];
394+
395+
let parsed: unknown;
396+
try {
397+
parsed = JSON.parse(raw);
398+
} catch (err) {
399+
const reason = err instanceof Error ? err.message : "unknown";
400+
return [
401+
{
402+
code: "invalid_composition_variables_declaration",
403+
severity: "error",
404+
message: `data-composition-variables is not valid JSON (${reason}).`,
405+
fixHint:
406+
'Provide a JSON array of variable declarations: data-composition-variables=\'[{"id":"title","type":"string","label":"Title","default":"Hello"}]\'.',
407+
snippet: truncateSnippet(tag.raw),
408+
},
409+
];
410+
}
411+
412+
if (!Array.isArray(parsed)) {
413+
return [
414+
{
415+
code: "invalid_composition_variables_declaration",
416+
severity: "error",
417+
message: "data-composition-variables must be a JSON array of variable declarations.",
418+
fixHint:
419+
'Wrap declarations in [] and give each an id, type, label, and default: \'[{"id":"title","type":"string","label":"Title","default":"Hello"}]\'.',
420+
snippet: truncateSnippet(tag.raw),
421+
},
422+
];
423+
}
424+
425+
const findings: HyperframeLintFinding[] = [];
426+
const knownTypes = new Set<string>(COMPOSITION_VARIABLE_TYPES);
427+
// Ids whose value the runtime pushes through isSafeMediaUrl: every
428+
// data-var-src binding, plus image-typed variables (always consumed as a
429+
// URL even when the binding lives in a sub-composition this file can't see).
430+
const varSrcIds = new Set<string>();
431+
for (const other of tags) {
432+
const bound = readAttr(other.raw, "data-var-src");
433+
if (bound) varSrcIds.add(bound);
434+
}
435+
for (let i = 0; i < parsed.length; i += 1) {
436+
const entry = parsed[i];
437+
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
438+
findings.push({
439+
code: "invalid_composition_variables_declaration",
440+
severity: "error",
441+
message: `data-composition-variables entry [${i}] must be an object with id, type, label, and default.`,
442+
snippet: truncateSnippet(tag.raw),
443+
});
444+
continue;
445+
}
446+
const e = entry as Record<string, unknown>;
447+
const missing: string[] = [];
448+
if (typeof e.id !== "string") missing.push("id");
449+
if (typeof e.type !== "string" || !knownTypes.has(e.type)) missing.push("type");
450+
if (typeof e.label !== "string") missing.push("label");
451+
if (!("default" in e)) missing.push("default");
452+
if (missing.length > 0) {
453+
findings.push({
454+
code: "invalid_composition_variables_declaration",
455+
severity: "error",
456+
message: `data-composition-variables entry [${i}] is missing or has invalid: ${missing.join(", ")}. Type must be one of string, number, color, boolean, enum, font, image.`,
457+
snippet: truncateSnippet(tag.raw),
458+
});
459+
continue;
460+
}
461+
const id = String(e.id);
462+
if (
463+
(e.type === "image" || varSrcIds.has(id)) &&
464+
typeof e.default === "string" &&
465+
e.default.length > 0 &&
466+
!isSafeMediaUrl(e.default)
467+
) {
468+
findings.push({
469+
code: "unloadable_media_variable_default",
470+
severity: "error",
471+
message: `Variable "${id}" defaults to a URL the runtime will refuse to load, so any element bound to it renders its authored fallback src instead and the render still exits 0.`,
472+
fixHint: `Media URLs must be relative, http(s), blob:, or a data:image/* URI. Copy the file into the project and reference it relatively (e.g. "assets/bg.png") rather than by absolute path.`,
473+
snippet: truncateSnippet(tag.raw),
474+
});
475+
}
476+
}
477+
return findings;
478+
}
479+
387480
export function collectAllDeclaredVariableIds(tags: readonly OpenTag[]): Set<string> | null {
388481
const all = new Set<string>();
389482
for (const tag of tags) {
@@ -1011,97 +1104,11 @@ export const compositionRules: Array<(ctx: LintContext) => HyperframeLintFinding
10111104
// on any structural problem. Surface JSON / shape failures so authors
10121105
// catch them at lint time rather than wondering why their `getVariables()`
10131106
// defaults aren't applied.
1014-
// fallow-ignore-next-line complexity
1015-
({ tags }) => {
1016-
const htmlTag = findHtmlTag(tags);
1017-
if (!htmlTag) return [];
1018-
const raw = readJsonAttr(htmlTag.raw, "data-composition-variables");
1019-
if (!raw) return [];
1020-
1021-
let parsed: unknown;
1022-
try {
1023-
parsed = JSON.parse(raw);
1024-
} catch (err) {
1025-
const reason = err instanceof Error ? err.message : "unknown";
1026-
return [
1027-
{
1028-
code: "invalid_composition_variables_declaration",
1029-
severity: "error",
1030-
message: `data-composition-variables is not valid JSON (${reason}).`,
1031-
fixHint:
1032-
'Provide a JSON array of variable declarations: data-composition-variables=\'[{"id":"title","type":"string","label":"Title","default":"Hello"}]\'.',
1033-
snippet: truncateSnippet(htmlTag.raw),
1034-
},
1035-
];
1036-
}
1037-
1038-
if (!Array.isArray(parsed)) {
1039-
return [
1040-
{
1041-
code: "invalid_composition_variables_declaration",
1042-
severity: "error",
1043-
message: "data-composition-variables must be a JSON array of variable declarations.",
1044-
fixHint:
1045-
'Wrap declarations in [] and give each an id, type, label, and default: \'[{"id":"title","type":"string","label":"Title","default":"Hello"}]\'.',
1046-
snippet: truncateSnippet(htmlTag.raw),
1047-
},
1048-
];
1049-
}
1050-
1051-
const findings: HyperframeLintFinding[] = [];
1052-
const knownTypes = new Set<string>(COMPOSITION_VARIABLE_TYPES);
1053-
// Ids whose value the runtime pushes through isSafeMediaUrl: every
1054-
// data-var-src binding, plus image-typed variables (always consumed as a
1055-
// URL even when the binding lives in a sub-composition this file can't see).
1056-
const varSrcIds = new Set<string>();
1057-
for (const tag of tags) {
1058-
const bound = readAttr(tag.raw, "data-var-src");
1059-
if (bound) varSrcIds.add(bound);
1060-
}
1061-
for (let i = 0; i < parsed.length; i += 1) {
1062-
const entry = parsed[i];
1063-
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
1064-
findings.push({
1065-
code: "invalid_composition_variables_declaration",
1066-
severity: "error",
1067-
message: `data-composition-variables entry [${i}] must be an object with id, type, label, and default.`,
1068-
snippet: truncateSnippet(htmlTag.raw),
1069-
});
1070-
continue;
1071-
}
1072-
const e = entry as Record<string, unknown>;
1073-
const missing: string[] = [];
1074-
if (typeof e.id !== "string") missing.push("id");
1075-
if (typeof e.type !== "string" || !knownTypes.has(e.type)) missing.push("type");
1076-
if (typeof e.label !== "string") missing.push("label");
1077-
if (!("default" in e)) missing.push("default");
1078-
if (missing.length > 0) {
1079-
findings.push({
1080-
code: "invalid_composition_variables_declaration",
1081-
severity: "error",
1082-
message: `data-composition-variables entry [${i}] is missing or has invalid: ${missing.join(", ")}. Type must be one of string, number, color, boolean, enum, font, image.`,
1083-
snippet: truncateSnippet(htmlTag.raw),
1084-
});
1085-
continue;
1086-
}
1087-
const id = String(e.id);
1088-
if (
1089-
(e.type === "image" || varSrcIds.has(id)) &&
1090-
typeof e.default === "string" &&
1091-
e.default.length > 0 &&
1092-
!isSafeMediaUrl(e.default)
1093-
) {
1094-
findings.push({
1095-
code: "unloadable_media_variable_default",
1096-
severity: "error",
1097-
message: `Variable "${id}" defaults to a URL the runtime will refuse to load, so any element bound to it renders its authored fallback src instead and the render still exits 0.`,
1098-
fixHint: `Media URLs must be relative, http(s), blob:, or a data:image/* URI. Copy the file into the project and reference it relatively (e.g. "assets/bg.png") rather than by absolute path.`,
1099-
snippet: truncateSnippet(htmlTag.raw),
1100-
});
1101-
}
1102-
}
1103-
return findings;
1104-
},
1107+
// Checked on every element that declares: <html>, or the composition root.
1108+
({ tags }) =>
1109+
tags
1110+
.filter((tag) => readJsonAttr(tag.raw, "data-composition-variables"))
1111+
.flatMap((tag) => variablesDeclarationFindings(tag, tags)),
11051112

11061113
// html_dir_attribute_breaks_render — valid non-LTR dir values on
11071114
// <html> renders correctly in preview/snapshot but produces a fully

‎packages/parsers/src/htmlParser.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -790,6 +790,25 @@ describe("extractCompositionMetadata", () => {
790790
expect(meta.variables[1].type).toBe("number");
791791
});
792792

793+
it("reads variables declared on the composition root, templated or not", () => {
794+
const decl = (id: string, def = "x") =>
795+
JSON.stringify([{ id, type: "string", label: id, default: def }]);
796+
const onRoot = `<!DOCTYPE html><html><body><div data-composition-id="c" data-composition-variables='${decl("title")}'></div></body></html>`;
797+
expect(extractCompositionMetadata(onRoot).variables.map((v) => v.id)).toEqual(["title"]);
798+
const inTemplate = `<!DOCTYPE html><html><body><template id="c-template"><div data-composition-id="c" data-composition-variables='${decl("sub")}'></div></template></body></html>`;
799+
expect(extractCompositionMetadata(inTemplate).variables.map((v) => v.id)).toEqual(["sub"]);
800+
});
801+
802+
it("merges <html> and root declarations, the root winning a shared id", () => {
803+
const html = `<!DOCTYPE html>
804+
<html data-composition-variables='[{"id":"title","type":"string","label":"T","default":"A"},{"id":"count","type":"number","label":"C","default":1}]'>
805+
<body><div data-composition-id="c" data-composition-variables='[{"id":"title","type":"string","label":"T","default":"B"}]'></div></body>
806+
</html>`;
807+
const vars = extractCompositionMetadata(html).variables;
808+
expect(vars.map((v) => v.id)).toEqual(["title", "count"]);
809+
expect(vars[0]?.default).toBe("B");
810+
});
811+
793812
// T9 — CompositionVariable font/image parse (WS-B R1 implemented).
794813

795814
it("parses a font variable (type: font) with name and source", () => {

‎packages/parsers/src/htmlParser.ts‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -803,11 +803,19 @@ export function extractCompositionMetadata(html: string): CompositionMetadata {
803803
const durationStr = htmlEl.getAttribute("data-composition-duration");
804804
const compositionDuration = durationStr ? parseFloat(durationStr) : null;
805805

806-
// TODO(template-var-carriers): reads `<html>` only. A template/fragment comp
807-
// that declares variables on its `[data-composition-id]` root div (the
808-
// dual-carrier contract from #2081) reports no variables when its metadata is
809-
// extracted standalone (e.g. CLI --variables validation of a sub-comp file).
810-
const variables = parseCompositionVariables(htmlEl);
806+
// Declarations live on <html> or on the composition root (inside its <template> when
807+
// templated); like the runtime, read both and let the root's win on a shared id.
808+
const root = (doc.querySelector("template")?.content ?? doc).querySelector(
809+
"[data-composition-id]",
810+
);
811+
const variables = [
812+
...new Map(
813+
[
814+
...parseCompositionVariables(htmlEl),
815+
...(root && root !== htmlEl ? parseCompositionVariables(root) : []),
816+
].map((v) => [v.id, v]),
817+
).values(),
818+
];
811819

812820
return {
813821
compositionId,

‎packages/sdk/src/engine/apply-patches.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -264,13 +264,19 @@ function applyOne(parsed: ParsedDocument, patch: JsonPatchOp, p: ParsedPath): vo
264264
case "variableDeclaration": {
265265
if (!p.id) return;
266266
if (patch.op === "remove") {
267-
removeVariableDeclarationEntry(declarationElement(parsed.document, parsed.wrapped), p.id);
267+
removeVariableDeclarationEntry(
268+
declarationElement(parsed.document, parsed.wrapped, p.id),
269+
p.id,
270+
);
268271
} else if (isRawDeclarationEntry(patch.value)) {
269272
// Replay is faithful, not strict: inverse patches capture raw entries
270273
// (loose hand-authored declarations included) and undo must restore
271274
// them verbatim — gating on isCompositionVariable here would make
272275
// undo of a remove/update on a loose entry silently no-op.
273-
writeVariableDeclaration(declarationElement(parsed.document, parsed.wrapped), patch.value);
276+
writeVariableDeclaration(
277+
declarationElement(parsed.document, parsed.wrapped, p.id),
278+
patch.value,
279+
);
274280
}
275281
break;
276282
}
@@ -282,7 +288,7 @@ function applyOne(parsed: ParsedDocument, patch: JsonPatchOp, p: ParsedPath): vo
282288
// CSS compat is handled by explicit style-path patches emitted by mutate.ts,
283289
// so we do NOT write CSS here — the style case above handles those patches.
284290
applyVariableDefault(
285-
declarationElement(parsed.document, parsed.wrapped),
291+
declarationElement(parsed.document, parsed.wrapped, p.id),
286292
p.id,
287293
patch.op === "remove" ? null : patch.value,
288294
);

‎packages/sdk/src/engine/model.ts‎

Lines changed: 33 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
*/
77

88
import { parseHTML } from "linkedom";
9+
import { findVariableDeclaration } from "./variableModel.js";
910
import {
1011
ensureHfIds,
1112
isCompositionTemplate,
@@ -169,15 +170,40 @@ export function isNewHostBoundary(el: Element): boolean {
169170
}
170171

171172
/**
172-
* The element that carries composition-level declarations
173-
* (`data-composition-variables`). Full-document comps use `<html>`; a wrapped
174-
* template/fragment comp has a synthetic `<html>` that serialize() strips, so
175-
* its declarations must live on the composition root div (where values/metadata
176-
* already live) to survive save.
173+
* The elements carrying `data-composition-variables`, in the runtime's merge
174+
* order: `<html>`, then the composition root, whose entries win a shared id. A
175+
* wrapped template/fragment comp has a synthetic `<html>` that serialize()
176+
* strips, so only its root counts.
177177
*/
178-
export function declarationElement(document: Document, wrapped: boolean): Element | null {
178+
export function declarationCarriers(document: Document, wrapped: boolean): Element[] {
179+
const root = findRoot(document);
180+
const html = wrapped
181+
? null
182+
: (document as Document & { documentElement?: Element }).documentElement;
183+
const carriers = [html, root].filter(
184+
(el): el is Element => !!el?.hasAttribute("data-composition-variables"),
185+
);
186+
return [...new Set(carriers)];
187+
}
188+
189+
/**
190+
* Where a declaration op lands: the carrier that declares `id` (the root first,
191+
* as it wins), else the root if it carries declarations, else `<html>` (the
192+
* root div for wrapped comps).
193+
*/
194+
export function declarationElement(
195+
document: Document,
196+
wrapped: boolean,
197+
id?: string,
198+
): Element | null {
199+
const winnerFirst = declarationCarriers(document, wrapped).reverse();
200+
const owner =
201+
id === undefined ? undefined : winnerFirst.find((el) => findVariableDeclaration(el, id));
202+
if (owner) return owner;
179203
if (wrapped) return findRoot(document);
180-
return (document as Document & { documentElement?: Element }).documentElement ?? null;
204+
return (
205+
winnerFirst[0] ?? (document as Document & { documentElement?: Element }).documentElement ?? null
206+
);
181207
}
182208

183209
export function findRoot(document: Document): Element | null {

0 commit comments

Comments
 (0)