Skip to content

Write HTML. Render video. Built for agents.

fix(core): namespace SVG ids during composition inline to prevent cross-scene collisions (#3494)

miga-heygenbd873ec35c58
diff --git a/packages/core/src/compiler/compositionScoping.test.ts b/packages/core/src/compiler/compositionScoping.test.ts
index 9c6e82d547..f2dd16a395 100644
--- a/packages/core/src/compiler/compositionScoping.test.ts
+++ b/packages/core/src/compiler/compositionScoping.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { parseHTML } from "linkedom";
+import { JSDOM } from "jsdom";
import {
buildVariablesByCompScript,
dedupeFontFaceRules,
@@ -1292,3 +1293,132 @@ describe("dedupeFontFaceRules", () => {
expect(dedupeFontFaceRules([a, b])[0]).not.toContain("@font-face");
});
});
+
+describe("composition scoping – renamed-id selector runtime", () => {
+ // Real jsdom windows: the shim patches Element.prototype, which a plain
+ // object window cannot exercise.
+ function bootWindow(html: string, script: string, compId: string, gsap?: unknown) {
+ const dom = new JSDOM(html, { runScripts: "outside-only" });
+ const window = dom.window as unknown as Window & typeof globalThis & Record<string, unknown>;
+ window.__captured = {};
+ if (gsap) window.gsap = gsap;
+ window.eval(wrapScopedCompositionScript(script, compId));
+ return { window, captured: window.__captured as Record<string, unknown> };
+ }
+
+ const TWO_INSTANCES = `
+ <div data-composition-id="other"><svg><path id="shape"/></svg></div>
+ <div data-composition-id="scene">
+ <svg class="art"><path id="scene--shape" data-hf-authored-id="shape"/><rect class="r"/></svg>
+ </div>`;
+
+ it("leaves Element.prototype untouched when no id was renamed", () => {
+ const { window, captured } = bootWindow(
+ `<div data-composition-id="scene"><svg><path id="shape"/></svg></div>`,
+ `window.__captured.hit = document.querySelector("svg").querySelector("#shape");`,
+ "scene",
+ );
+ expect(window.__hfRenamedIdSelectorShim).toBeUndefined();
+ expect(captured.hit).toBe(window.document.querySelector("path"));
+ });
+
+ it("rewrites #authoredId to match a renamed element from element and document lookups", () => {
+ const { window, captured } = bootWindow(
+ TWO_INSTANCES,
+ `var svg = document.querySelector("svg.art");
+ window.__captured.viaElement = svg.querySelector("#shape");
+ window.__captured.viaElementAll = svg.querySelectorAll("#shape, #shape.x, path#shape").length;
+ window.__captured.viaDocument = document.querySelector("#shape");
+ window.__captured.viaDocumentAll = document.querySelectorAll("#shape").length;
+ window.__captured.byId = document.getElementById("shape");
+ window.__captured.notAnId = svg.querySelector('[data-x="#shape"]');`,
+ "scene",
+ );
+ const renamed = window.document.querySelector('[data-hf-authored-id="shape"]');
+ const other = window.document.querySelector('[data-composition-id="other"] path');
+ expect(window.__hfRenamedIdSelectorShim).toBe(true);
+ expect(captured.viaElement).toBe(renamed);
+ expect(captured.viaElementAll).toBe(1);
+ expect(captured.viaDocument).toBe(renamed);
+ expect(captured.viaDocumentAll).toBe(1);
+ expect(captured.byId).toBe(renamed);
+ expect(captured.notAnId).toBeNull();
+ // The rewrite is `:is(#shape, [data-hf-authored-id="shape"])` — a
+ // superset — so an Element lookup inside the OTHER instance, whose id
+ // was never renamed, still finds its own element.
+ expect(other!.id).toBe("shape");
+ expect(
+ window.document.querySelector('[data-composition-id="other"] svg')!.querySelector("#shape"),
+ ).toBe(other);
+ });
+
+ it("resolves GSAP array targets through the scoped lookup", () => {
+ const { window, captured } = bootWindow(
+ TWO_INSTANCES,
+ `window.__captured.targets = gsap.to(["#shape", ".r", document.querySelector("svg.art")], {});
+ window.__captured.toArray = gsap.utils.toArray("#shape");`,
+ "scene",
+ { to: (targets: unknown) => targets, utils: { toArray: (targets: unknown) => targets } },
+ );
+ const scene = window.document.querySelector('[data-composition-id="scene"]')!;
+ expect(captured.targets).toEqual([
+ scene.querySelector("path"),
+ scene.querySelector("rect"),
+ scene.querySelector("svg"),
+ ]);
+ expect(captured.toArray).toEqual([scene.querySelector("path")]);
+ });
+
+ it("matches an escaped authored id spelled with CSS escapes in a script selector", () => {
+ const { captured, window } = bootWindow(
+ `<div data-composition-id="other"><svg><filter id="fx.1"/></svg></div>
+ <div data-composition-id="scene"><svg class="art"><filter id="scene--fx.1" data-hf-authored-id="fx.1"/></svg></div>`,
+ `window.__captured.viaDocument = document.querySelector("#fx\\\\.1");
+ window.__captured.viaElement = document.querySelector("svg.art").querySelector("#fx\\\\.1");`,
+ "scene",
+ );
+ const renamed = window.document.querySelector('[data-hf-authored-id="fx.1"]');
+ expect(captured.viaDocument).toBe(renamed);
+ expect(captured.viaElement).toBe(renamed);
+ });
+ it("distinguishes compound selectors from escaped literal ids", () => {
+ const { captured } = bootWindow(
+ `<div data-composition-id="scene"><svg>
+ <path id="foo" class="bar"/><path id="scene--foo.bar" data-hf-authored-id="foo.bar"/>
+ </svg></div>`,
+ String.raw`var svg = document.querySelector("svg");
+ window.__captured.compound = svg.querySelector("#foo.bar").id;
+ window.__captured.literal = svg.querySelector("#foo\\.bar").id;
+ window.__captured.hex = svg.querySelector("#foo\\2e bar").id;
+ window.__captured.suffix = svg.querySelector("#foo\\.bar2");`,
+ "scene",
+ );
+ expect(captured.compound).toBe("foo");
+ expect(captured.literal).toBe("scene--foo.bar");
+ expect(captured.hex).toBe("scene--foo.bar");
+ expect(captured.suffix).toBeNull();
+ });
+
+ it("refreshes renamed ids after a scene is replaced and its script runs again", () => {
+ const { window } = bootWindow(TWO_INSTANCES, "", "scene");
+ window.document.querySelector('[data-composition-id="scene"]')!.innerHTML =
+ '<svg><path id="scene--new" data-hf-authored-id="new"/></svg>';
+ window.eval(
+ wrapScopedCompositionScript(
+ 'window.__captured.hit = document.querySelector("svg").querySelector("#new").id;',
+ "scene",
+ ),
+ );
+ expect((window.__captured as Record<string, unknown>).hit).toBe("scene--new");
+ });
+ it("preserves escaped hashes and brackets in runtime class selectors", () => {
+ const { captured } = bootWindow(
+ `<div data-composition-id="scene"><svg><path id="scene--shape" data-hf-authored-id="shape"/><rect class="foo#shape"/><circle class="foo[bar"/></svg></div>`,
+ String.raw`window.__captured.hash = document.querySelector("svg").querySelector(".foo\\#shape").tagName;
+ window.__captured.bracket = document.querySelector("svg").querySelector(".foo\\[bar").tagName;`,
+ "scene",
+ );
+ expect(captured.hash).toBe("rect");
+ expect(captured.bracket).toBe("circle");
+ });
+});
diff --git a/packages/core/src/compiler/compositionScoping.ts b/packages/core/src/compiler/compositionScoping.ts
index 5cfc34dfd0..d97f0f7e1d 100644
--- a/packages/core/src/compiler/compositionScoping.ts
+++ b/packages/core/src/compiler/compositionScoping.ts
@@ -1,4 +1,5 @@
import postcss, { type AtRule, type Node, type Rule } from "postcss";
+import { escapeCssIdentifier, replaceSelectorIdTokens } from "./selectorIdTokens";
import { SCENE_PARTS_META } from "../sceneParts";
const AUTHORED_ROOT_ID_ATTR = "data-hf-authored-id";
@@ -12,80 +13,19 @@ function escapeCssAttributeValue(value: string): string {
return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
}
-function escapeCssIdentifier(value: string): string {
- if (!value) return value;
- const escaped = value.replace(/[^a-zA-Z0-9_-]/g, (char) => `\\${char}`);
- return escaped.replace(/^-?\d/, (match) => `\\${match}`);
-}
-
function getAuthoredRootIdSelectorForms(authoredRootId: string): string[] {
const trimmed = authoredRootId.trim();
if (!trimmed) return [];
return Array.from(new Set([trimmed, escapeCssIdentifier(trimmed)])).filter(Boolean);
}
-function isSelectorNameChar(char: string | undefined): boolean {
- return !!char && /[\w-]/.test(char);
-}
-
function replaceAuthoredRootIdSelectors(
selector: string,
authoredRootId: string,
replacement: string,
): string {
- const forms = getAuthoredRootIdSelectorForms(authoredRootId).sort((a, b) => b.length - a.length);
- if (forms.length === 0) return selector;
-
- let result = "";
- let bracketDepth = 0;
- let quote: '"' | "'" | null = null;
-
- for (let index = 0; index < selector.length; index += 1) {
- const char = selector[index];
- const previousChar = index > 0 ? selector[index - 1] : "";
-
- if (quote) {
- result += char;
- if (char === quote && previousChar !== "\\") {
- quote = null;
- }
- continue;
- }
-
- if (char === '"' || char === "'") {
- quote = char;
- result += char;
- continue;
- }
-
- if (char === "[") {
- bracketDepth += 1;
- result += char;
- continue;
- }
-
- if (char === "]") {
- bracketDepth = Math.max(0, bracketDepth - 1);
- result += char;
- continue;
- }
-
- if (char === "#" && bracketDepth === 0) {
- const matchedForm = forms.find((form) => selector.startsWith(form, index + 1));
- if (matchedForm) {
- const nextChar = selector[index + 1 + matchedForm.length];
- if (!isSelectorNameChar(nextChar)) {
- result += replacement;
- index += matchedForm.length;
- continue;
- }
- }
- }
-
- result += char;
- }
-
- return result;
+ const forms = getAuthoredRootIdSelectorForms(authoredRootId);
+ return replaceSelectorIdTokens(selector, forms, () => replacement);
}
function normalizeAuthoredRootIdSelector(selector: string, authoredRootId?: string | null): string {
@@ -347,6 +287,7 @@ export function scopedModulePrelude(
return `const __hyperframes = (function(__hfBaseHyperframes, __hfTimelineCompId, __hfCompositionSrc) {
return ${SCOPED_HYPERFRAMES_EXPRESSION};
})(window.__hyperframes, ${jsonScriptLiteral(timelineCompositionId)}, ${jsonScriptLiteral(compositionSrc?.trim() || null)});
+${wrapScopedCompositionScript("", timelineCompositionId)}
`;
}
@@ -371,9 +312,6 @@ export function wrapScopedCompositionScript(
const timingSelectorPatternLiteral = jsonScriptLiteral(
String.raw`\s*\[\s*data-(?:start|duration)\s*=\s*(?:"[^"]*"|'[^']*')\s*\]`,
);
- const authoredRootIdFormsLiteral = jsonScriptLiteral(
- getAuthoredRootIdSelectorForms(authoredRootId?.trim() || ""),
- );
return `(function(){
var __hfCompId = ${compositionIdLiteral};
var __hfTimelineCompId = ${timelineCompositionIdLiteral};
@@ -390,15 +328,19 @@ export function wrapScopedCompositionScript(
var __hfRoot = null;
var __hfRootSelectorPattern = ${rootSelectorPatternLiteral};
var __hfTimingSelectorPattern = ${timingSelectorPatternLiteral};
- var __hfAuthoredRootIdForms = ${authoredRootIdFormsLiteral};
var __hfAuthoredRootSelector = __hfAuthoredRootId
? "[" + __hfAuthoredRootAttr + '="' + __hfEscapeAttr(__hfAuthoredRootId) + '"]'
: "";
- var __hfIsSelectorNameChar = function(char) {
- return !!char && /[\\w-]/.test(char);
+ var __hfCssEscape = function(value) {
+ var text = value + "";
+ if (typeof CSS !== "undefined" && CSS && typeof CSS.escape === "function") {
+ try { return CSS.escape(text); } catch {}
+ }
+ return text.replace(/[^a-zA-Z0-9_-]/g, function(char) { return "\\\\" + char; });
};
- var __hfReplaceAuthoredRootIdSelectors = function(selector) {
- if (!__hfAuthoredRootSelector || !__hfAuthoredRootIdForms.length || typeof selector !== "string") {
+ // Decode complete CSS identifiers before comparing authored ids.
+ var __hfRewriteIdSelectors = function(selector, entries) {
+ if (!entries || !entries.length || typeof selector !== "string" || selector.indexOf("#") === -1) {
return selector;
}
var result = "";
@@ -406,10 +348,17 @@ export function wrapScopedCompositionScript(
var quote = null;
for (var index = 0; index < selector.length; index += 1) {
var char = selector[index];
- var previousChar = index > 0 ? selector[index - 1] : "";
+ if (char === "\\\\") {
+ var escape = selector.slice(index).match(/^\\\\(?:[0-9a-fA-F]{1,6}(?:\\r\\n|[ \\t\\r\\n\\f])?|[\\s\\S])/);
+ if (escape) {
+ result += escape[0];
+ index += escape[0].length - 1;
+ continue;
+ }
+ }
if (quote) {
result += char;
- if (char === quote && previousChar !== "\\\\") {
+ if (char === quote) {
quote = null;
}
continue;
@@ -430,36 +379,83 @@ export function wrapScopedCompositionScript(
continue;
}
if (char === "#" && bracketDepth === 0) {
- var matchedForm = null;
- for (var formIndex = 0; formIndex < __hfAuthoredRootIdForms.length; formIndex += 1) {
- var form = __hfAuthoredRootIdForms[formIndex];
- if (selector.slice(index + 1, index + 1 + form.length) === form) {
- matchedForm = form;
- break;
- }
- }
- if (matchedForm) {
- var nextChar = selector[index + 1 + matchedForm.length];
- if (!__hfIsSelectorNameChar(nextChar)) {
- result += __hfAuthoredRootSelector;
- index += matchedForm.length;
- continue;
- }
+ var token = selector.slice(index + 1).match(/^(?:[\\w\\u0080-\\uffff-]|\\\\(?:[0-9a-fA-F]{1,6}(?:\\r\\n|[ \\t\\r\\n\\f])?|[^\\r\\n\\f]))+/);
+ if (token) {
+ var decoded = token[0].replace(/\\\\([0-9a-fA-F]{1,6})(?:\\r\\n|[ \\t\\r\\n\\f])?|\\\\([^\\r\\n\\f])/g, function(_, hex, escaped) {
+ if (!hex) return escaped;
+ var code = parseInt(hex, 16);
+ return String.fromCodePoint(!code || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff) ? 0xfffd : code);
+ });
+ var matched = entries.find(function(entry) { return entry.id === decoded; });
+ result += matched ? matched.replacement : "#" + token[0];
+ index += token[0].length;
+ continue;
}
}
result += char;
}
return result;
};
+ var __hfAuthoredRootEntries = __hfAuthoredRootSelector
+ ? [{ id: __hfAuthoredRootId, replacement: __hfAuthoredRootSelector }]
+ : [];
+ // Include both renamed and untouched instances. Each wrapper refreshes this
+ // document-wide cache because preview scene swaps can introduce new ids.
+ var __hfRenamedIdEntries = function() {
+ if (window.__hfRenamedIdSelectorEntries) return window.__hfRenamedIdSelectorEntries;
+ var entries = [];
+ var seen = Object.create(null);
+ var nodes;
+ try {
+ nodes = window.document.querySelectorAll("[" + __hfAuthoredRootAttr + "][id]");
+ } catch {
+ nodes = [];
+ }
+ for (var i = 0; i < nodes.length; i += 1) {
+ var authored = nodes[i].getAttribute(__hfAuthoredRootAttr);
+ if (!authored || seen[authored] || authored === nodes[i].id) continue;
+ seen[authored] = true;
+ var escaped = __hfCssEscape(authored);
+ entries.push({
+ id: authored,
+ replacement: ":is(#" + escaped + ", [" + __hfAuthoredRootAttr + '="' + __hfEscapeAttr(authored) + '"])',
+ });
+ }
+ window.__hfRenamedIdSelectorEntries = entries;
+ return window.__hfRenamedIdSelectorEntries;
+ };
+ // element.querySelector("#authored") on an arbitrary Element never passes
+ // through the scoped document proxy, so the same rewrite is installed once
+ // per document on Element.prototype — only when at least one id was
+ // actually renamed, so a document without collisions runs untouched
+ // natives. Document.prototype is deliberately NOT patched: an unscoped
+ // document-wide lookup cannot know which instance it means, and rewriting
+ // it would only widen the ambiguity.
+ var __hfInstallRenamedIdSelectorShim = function() {
+ if (window.__hfRenamedIdSelectorShim) return;
+ var entries = __hfRenamedIdEntries();
+ if (!entries.length) return;
+ var proto = window.Element && window.Element.prototype;
+ if (!proto || typeof proto.querySelector !== "function" || typeof proto.querySelectorAll !== "function") {
+ return;
+ }
+ var nativeQuerySelector = proto.querySelector;
+ var nativeQuerySelectorAll = proto.querySelectorAll;
+ proto.querySelector = function(selector) {
+ return nativeQuerySelector.call(this, __hfRewriteIdSelectors(selector, __hfRenamedIdEntries()));
+ };
+ proto.querySelectorAll = function(selector) {
+ return nativeQuerySelectorAll.call(this, __hfRewriteIdSelectors(selector, __hfRenamedIdEntries()));
+ };
+ window.__hfRenamedIdSelectorShim = true;
+ };
var __hfNormalizeSelector = function(selector) {
if (!__hfCompId || typeof selector !== "string") return selector;
var normalized = selector
.replace(new RegExp(__hfRootSelectorPattern + '(?:' + __hfTimingSelectorPattern + ')+', 'g'), __hfRootSelector)
.replace(new RegExp('(?:' + __hfTimingSelectorPattern + ')+' + __hfRootSelectorPattern, 'g'), __hfRootSelector);
- if (__hfAuthoredRootSelector) {
- normalized = __hfReplaceAuthoredRootIdSelectors(normalized);
- }
- return normalized;
+ normalized = __hfRewriteIdSelectors(normalized, __hfAuthoredRootEntries);
+ return __hfRewriteIdSelectors(normalized, __hfRenamedIdEntries());
};
var __hfFindRoot = function() {
if (!__hfRoot && __hfRootSelector) {
@@ -609,6 +605,7 @@ export function wrapScopedCompositionScript(
resolved.push(item);
return resolved;
}, []);
+
};
var __hfScopeTimeline = function(timeline) {
if (!timeline || timeline.__hfScopedCompositionRoot === __hfFindRoot()) return timeline;
@@ -721,6 +718,8 @@ ${source.replace(/<\/(script)/gi, "<\\/$1")}
});
};
__hfFindRoot();
+ window.__hfRenamedIdSelectorEntries = null;
+ __hfInstallRenamedIdSelectorShim();
__hfRecordAnimations(__hfRun);
})();`;
}
diff --git a/packages/core/src/compiler/inlineSubCompositions.test.ts b/packages/core/src/compiler/inlineSubCompositions.test.ts
index 55100ac4f0..43cfd3c63a 100644
--- a/packages/core/src/compiler/inlineSubCompositions.test.ts
+++ b/packages/core/src/compiler/inlineSubCompositions.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import { parseHTML } from "linkedom";
import { ensureExternalLinkTag, inlineSubCompositions } from "./inlineSubCompositions";
import { readDeclaredDefaults, parseHostVariableValues } from "../runtime/getVariables";
+import { JSDOM } from "jsdom";
// Fixtures reference GSAP CDN but are never loaded in a real browser — resolveHtml is mocked.
@@ -700,3 +701,394 @@ describe("inlineSubCompositions – sub-composition asset paths", () => {
);
});
});
+
+/**
+ * Mirror of the bundler's runtime-id assignment (`assignBundledRuntimeCompositionIds`
+ * in htmlBundler.ts): a host whose authored composition id appears more than
+ * once gets a document-unique `<id>__hf<n>` runtime id. Reproduced here rather
+ * than imported because htmlBundler.ts statically imports esbuild, which
+ * refuses to load inside a jsdom test realm on Windows.
+ */
+function assignTestRuntimeCompositionIds(
+ hosts: Element[],
+): Map<Element, { authoredCompositionId: string | null; runtimeCompositionId: string | null }> {
+ const counts = new Map<string, number>();
+ for (const host of hosts) {
+ const id = host.getAttribute("data-composition-id");
+ if (id) counts.set(id, (counts.get(id) ?? 0) + 1);
+ }
+ const seen = new Map<string, number>();
+ const identities = new Map<
+ Element,
+ { authoredCompositionId: string | null; runtimeCompositionId: string | null }
+ >();
+ for (const host of hosts) {
+ const authored = host.getAttribute("data-composition-id");
+ if (!authored) {
+ identities.set(host, { authoredCompositionId: null, runtimeCompositionId: null });
+ continue;
+ }
+ let runtime = authored;
+ if ((counts.get(authored) ?? 0) > 1) {
+ const index = (seen.get(authored) ?? 0) + 1;
+ seen.set(authored, index);
+ runtime = `${authored}__hf${index}`;
+ host.setAttribute("data-hf-original-composition-id", authored);
+ host.setAttribute("data-composition-id", runtime);
+ }
+ identities.set(host, { authoredCompositionId: authored, runtimeCompositionId: runtime });
+ }
+ return identities;
+}
+
+/** Inline `hostEntries` (each pointing at a source in `sources`) into one
+ * bundler-shaped document with runtime composition ids assigned. */
+function inlineScenes(
+ sources: Record<string, string>,
+ hostEntries: Array<{ compId: string; src: string }>,
+) {
+ const hostsMarkup = hostEntries
+ .map(
+ ({ compId, src }, i) =>
+ `<div data-composition-id="${compId}" data-composition-src="${src}"
+ data-start="0" data-duration="4" data-track-index="${i}"></div>`,
+ )
+ .join("\n");
+ const { document } = parseHTML(`<!DOCTYPE html>
+<html><body>
+ <div data-composition-id="main">${hostsMarkup}</div>
+</body></html>`);
+ const hosts = Array.from(document.querySelectorAll("[data-composition-src]"));
+ const hostIdentityMap = assignTestRuntimeCompositionIds(hosts);
+ const result = inlineSubCompositions(document, hosts, {
+ resolveHtml: (src) => sources[src] ?? null,
+ parseHtml: (html) => parseHTML(html).document,
+ hostIdentityMap,
+ });
+ return { document, result };
+}
+
+describe("inlineSubCompositions – #3490 nested SVG id collisions", () => {
+ // Same shape as the issue repro: a composition-scoped clipPath, a <use>
+ // target, and a CSS filter, all hardcoded ids a catalog block or a scene
+ // author has no reason to think are unsafe to repeat.
+ function svgScene(compId: string, color: string): string {
+ return `<!DOCTYPE html><html><body><div id="${compId}" data-composition-id="${compId}" data-width="100" data-height="100">
+ <svg width="0" height="0">
+ <clipPath id="clip"><rect width="10" height="10"/></clipPath>
+ <symbol id="shape"><circle r="5" fill="${color}"/></symbol>
+ <filter id="fx"><feFlood flood-color="${color}"/></filter>
+ </svg>
+ <g class="clipped" clip-path="url(#clip)"><use class="shape" href="#shape"></use></g>
+ <div class="fx-target" style="filter:url(#fx)"></div>
+ <style>#${compId} .fx-target { filter: url(#fx); }</style>
+ </div></body></html>`;
+ }
+
+ it("gives two sibling scenes reusing #clip/#shape/#fx distinct, non-colliding ids", () => {
+ const { document, result } = inlineScenes(
+ { "scene-a.html": svgScene("scene-a", "red"), "scene-b.html": svgScene("scene-b", "blue") },
+ [
+ { compId: "scene-a", src: "scene-a.html" },
+ { compId: "scene-b", src: "scene-b.html" },
+ ],
+ );
+
+ // Exactly one "clip" survives verbatim (the first instance keeps its
+ // authored id) and no id repeats across the two scenes — the exact
+ // document-order collision the browser resolves incorrectly before this
+ // fix.
+ const allIds = Array.from(document.querySelectorAll("[id]")).map((el) => el.getAttribute("id"));
+ expect(allIds.filter((id) => id === "clip")).toHaveLength(1);
+ expect(new Set(allIds).size).toBe(allIds.length);
+
+ const [gA, gB] = Array.from(document.querySelectorAll("g.clipped"));
+ const [useA, useB] = Array.from(document.querySelectorAll("use.shape"));
+ const [fxA, fxB] = Array.from(document.querySelectorAll(".fx-target"));
+
+ const clipA = gA!.getAttribute("clip-path");
+ const clipB = gB!.getAttribute("clip-path");
+ expect(clipA).toMatch(/^url\(#.*clip\)$/);
+ expect(clipA).not.toBe(clipB);
+
+ const hrefA = useA!.getAttribute("href");
+ const hrefB = useB!.getAttribute("href");
+ expect(hrefA).toMatch(/^#.*shape$/);
+ expect(hrefA).not.toBe(hrefB);
+
+ // <use>/clip-path must resolve to the id actually declared in THIS
+ // scene's <svg>, not merely to a unique-looking string.
+ const clipAId = clipA!.slice("url(#".length, -1);
+ const shapeAId = hrefA!.slice(1);
+ expect(document.getElementById(clipAId)?.closest("svg")).toBeTruthy();
+ expect(document.getElementById(shapeAId)?.closest("svg")).toBeTruthy();
+
+ const styleFxA = fxA!.getAttribute("style");
+ const styleFxB = fxB!.getAttribute("style");
+ expect(styleFxA).not.toBe(styleFxB);
+
+ // The CSS text (`<style>#scene-a .fx-target { filter: url(#fx) }`)
+ // extracted alongside the DOM (never re-injected by this shared function
+ // — that is the caller's job) must resolve to the SAME renamed id the
+ // element attribute above did, or the two diverge and the rule stops
+ // matching once inlined.
+ const styles = result.styles.map((style) => style.css).join("\n");
+ const fxAId = styleFxA!.match(/url\(#([^)]+)\)/)?.[1];
+ expect(fxAId).toBeTruthy();
+ expect(styles).toContain(`filter: url(#${fxAId})`);
+ });
+
+ it("disambiguates the same catalog block used twice in one scene", () => {
+ const block = svgScene("block", "green");
+ const { document } = inlineScenes({ "block.html": block }, [
+ { compId: "block", src: "block.html" },
+ { compId: "block", src: "block.html" },
+ ]);
+
+ const uses = Array.from(document.querySelectorAll("use.shape"));
+ expect(uses).toHaveLength(2);
+ const hrefs = uses.map((u) => u.getAttribute("href"));
+ expect(hrefs[0]).not.toBe(hrefs[1]);
+ expect(new Set(hrefs).size).toBe(2);
+
+ // Each <use> must still resolve within the merged document.
+ for (const href of hrefs) {
+ const id = href!.slice(1);
+ expect(document.getElementById(id)).toBeTruthy();
+ }
+ });
+
+ it("records the authored id on the renamed (second) instance only", () => {
+ // Mirrors #646: an author's own script calling
+ // document.getElementById('shape') from inside its composition must
+ // still find its element after this module renames the real id — the
+ // scoped shim falls back to data-hf-authored-id.
+ const { document } = inlineScenes(
+ { "scene-a.html": svgScene("scene-a", "red"), "scene-b.html": svgScene("scene-b", "blue") },
+ [
+ { compId: "scene-a", src: "scene-a.html" },
+ { compId: "scene-b", src: "scene-b.html" },
+ ],
+ );
+ const sceneARoot = document.querySelector('[data-composition-id="scene-a"]')!;
+ const sceneBRoot = document.querySelector('[data-composition-id="scene-b"]')!;
+ expect(sceneARoot.querySelector('[data-hf-authored-id="shape"]')).toBeNull();
+ expect(sceneARoot.querySelector("symbol")!.getAttribute("id")).toBe("shape");
+ const authoredMatch = sceneBRoot.querySelector('[data-hf-authored-id="shape"]');
+ expect(authoredMatch).toBeTruthy();
+ expect(authoredMatch).toBe(sceneBRoot.querySelector("symbol"));
+ });
+});
+
+describe("inlineSubCompositions – renamed SVG ids stay reachable from author scripts", () => {
+ // These tests execute the compiled, scoped scripts inside a real jsdom
+ // window built from the assembled document — the same thing the browser
+ // does — so they exercise the selector runtime in compositionScoping.ts,
+ // not just the DOM rewrite.
+ function scriptedScene(compId: string, script: string, extra = ""): string {
+ return `<!DOCTYPE html><html><body><div id="${compId}" data-composition-id="${compId}" data-width="100" data-height="100">
+ <svg class="art" width="0" height="0">
+ <path id="shape" d="M0,0 L10,10"/>
+ <use class="ref" href="#shape"></use>
+ </svg>
+ ${extra}
+ <script>${script}</script>
+ </div></body></html>`;
+ }
+
+ function inlineAndBoot(
+ sources: Record<string, string>,
+ hostEntries: Array<{ compId: string; src: string }>,
+ fakeGsap?: (window: Window & typeof globalThis) => unknown,
+ ) {
+ const { document, result } = inlineScenes(sources, hostEntries);
+ const dom = new JSDOM(document.toString(), { runScripts: "outside-only" });
+ const window = dom.window as unknown as Window & typeof globalThis & Record<string, unknown>;
+ window.__captured = {};
+ if (fakeGsap) (window as Record<string, unknown>).gsap = fakeGsap(window);
+ for (const script of result.scripts) window.eval(script);
+ return { window, result, captured: window.__captured as Record<string, unknown> };
+ }
+
+ it("single composition: native and script references to the same element both keep resolving", () => {
+ const { window, captured } = inlineAndBoot(
+ {
+ "scene.html": scriptedScene(
+ "scene",
+ `var svg = document.querySelector("svg.art");
+ window.__captured.viaDocument = document.querySelector("#shape");
+ window.__captured.viaElement = svg.querySelector("#shape");
+ window.__captured.byId = document.getElementById("shape");
+ window.__captured.all = document.querySelectorAll("#shape").length;`,
+ ),
+ },
+ [{ compId: "scene", src: "scene.html" }],
+ );
+ const path = window.document.querySelector("path")!;
+ // Ids are byte-for-byte untouched: no collision, no rename, no shim.
+ expect(path.getAttribute("id")).toBe("shape");
+ expect(path.hasAttribute("data-hf-authored-id")).toBe(false);
+ expect(window.document.querySelector("use")!.getAttribute("href")).toBe("#shape");
+ expect((window as Record<string, unknown>).__hfRenamedIdSelectorShim).toBeUndefined();
+ expect(captured.viaDocument).toBe(path);
+ expect(captured.viaElement).toBe(path);
+ expect(captured.byId).toBe(path);
+ expect(captured.all).toBe(1);
+ });
+
+ it("two colliding compositions: native refs point at their own element and each script still finds its own", () => {
+ const probe = `var svg = document.querySelector("svg.art");
+ window.__captured[__hfProbeName] = {
+ viaDocument: document.querySelector("#shape"),
+ viaElement: svg.querySelector("#shape"),
+ viaElementAll: svg.querySelectorAll("#shape").length,
+ byId: document.getElementById("shape"),
+ gsapTargets: gsap.to(["#shape", ".ref"], {}),
+ toArray: gsap.utils.toArray("#shape"),
+ };`;
+ const { window, captured } = inlineAndBoot(
+ {
+ "scene-a.html": scriptedScene("scene-a", `var __hfProbeName = "a"; ${probe}`),
+ "scene-b.html": scriptedScene("scene-b", `var __hfProbeName = "b"; ${probe}`),
+ },
+ [
+ { compId: "scene-a", src: "scene-a.html" },
+ { compId: "scene-b", src: "scene-b.html" },
+ ],
+ () => ({
+ to: (targets: unknown) => targets,
+ utils: { toArray: (targets: unknown) => targets },
+ }),
+ );
+ const [rootA, rootB] = Array.from(
+ window.document.querySelectorAll(
+ '[data-composition-id="scene-a"], [data-composition-id="scene-b"]',
+ ),
+ );
+ const pathA = rootA!.querySelector("path")!;
+ const pathB = rootB!.querySelector("path")!;
+
+ // DOM: A keeps the authored id, B is renamed and its <use> follows.
+ expect(pathA.getAttribute("id")).toBe("shape");
+ expect(pathB.getAttribute("id")).not.toBe("shape");
+ expect(pathB.getAttribute("data-hf-authored-id")).toBe("shape");
+ expect(rootA!.querySelector("use")!.getAttribute("href")).toBe("#shape");
+ expect(rootB!.querySelector("use")!.getAttribute("href")).toBe(`#${pathB.getAttribute("id")}`);
+
+ // Scripts: every lookup form resolves to the element of ITS OWN scene.
+ const a = captured.a as Record<string, unknown>;
+ const b = captured.b as Record<string, unknown>;
+ expect(a.viaDocument).toBe(pathA);
+ expect(a.viaElement).toBe(pathA);
+ expect(a.byId).toBe(pathA);
+ expect(b.viaDocument).toBe(pathB);
+ expect(b.viaElement).toBe(pathB);
+ expect(b.viaElementAll).toBe(1);
+ expect(b.byId).toBe(pathB);
+ // GSAP selector arrays resolve string entries through the scoped lookup.
+ expect(a.gsapTargets).toEqual([pathA, rootA!.querySelector("use.ref")]);
+ expect(b.gsapTargets).toEqual([pathB, rootB!.querySelector("use.ref")]);
+ expect(a.toArray).toEqual([pathA]);
+ expect(b.toArray).toEqual([pathB]);
+ expect((window as Record<string, unknown>).__hfRenamedIdSelectorShim).toBe(true);
+ });
+
+ it("escaped CSS id: a styled element that is also natively referenced keeps its rule after rename", () => {
+ function fxScene(compId: string): string {
+ return `<!DOCTYPE html><html><body><div id="${compId}" data-composition-id="${compId}" data-width="100" data-height="100">
+ <svg width="0" height="0"><filter id="fx.1"><feFlood flood-color="red"/></filter></svg>
+ <rect class="target" filter="url(#fx.1)"></rect>
+ <style>#fx\\.1 { color: red; } .target { filter: url(#fx.1); }</style>
+ <script>window.__captured[${JSON.stringify(compId)}] = document.querySelector("#fx\\\\.1");</script>
+ </div></body></html>`;
+ }
+ const { window, result, captured } = inlineAndBoot(
+ { "scene-a.html": fxScene("scene-a"), "scene-b.html": fxScene("scene-b") },
+ [
+ { compId: "scene-a", src: "scene-a.html" },
+ { compId: "scene-b", src: "scene-b.html" },
+ ],
+ );
+ const [rootA, rootB] = Array.from(
+ window.document.querySelectorAll(
+ '[data-composition-id="scene-a"], [data-composition-id="scene-b"]',
+ ),
+ );
+ const filterA = rootA!.querySelector("filter")!;
+ const filterB = rootB!.querySelector("filter")!;
+ expect(filterA.getAttribute("id")).toBe("fx.1");
+ expect(filterB.getAttribute("id")).toBe("scene-b--fx.1");
+ expect(rootB!.querySelector("rect")!.getAttribute("filter")).toBe("url(#scene-b--fx.1)");
+
+ // Scene B's stylesheet was rewritten with a VALID escaped selector and a
+ // matching url(); scene A's is untouched.
+ const [cssA, cssB] = result.styles.map((style) => style.css);
+ expect(cssA).toContain(String.raw`#fx\.1`);
+ expect(cssA).toContain("url(#fx.1)");
+ expect(cssB).toContain(String.raw`#scene-b--fx\.1`);
+ expect(cssB).toContain("url(#scene-b--fx.1)");
+ expect(cssB).not.toContain(String.raw`#fx\.1`);
+
+ // The rewritten selector actually matches the renamed element in a real
+ // selector engine.
+ const ruleSelector = /(\[data-composition-id="scene-b"\][^{]*#scene-b--fx\\\.1)\s*\{/.exec(
+ cssB!,
+ )?.[1];
+ expect(ruleSelector).toBeTruthy();
+ expect(window.document.querySelector(ruleSelector!)).toBe(filterB);
+
+ // And the author's own escaped selector still resolves through the
+ // scoped document proxy in both scenes.
+ expect(captured["scene-a"]).toBe(filterA);
+ expect(captured["scene-b"]).toBe(filterB);
+ });
+});
+
+describe("SVG namespacing compatibility on current compiler", () => {
+ it.each([false, true])(
+ "preserves inherited native references and child styles (shadow=%s)",
+ (shadow) => {
+ const parent = `<div data-composition-id="parent"><svg><linearGradient id="paint"><stop stop-color="red"/></linearGradient><rect fill="url(#paint)"/></svg>
+ <div data-composition-id="child" data-composition-src="child.html"></div></div>`;
+ const child = `<div data-composition-id="child"><svg>${shadow ? '<linearGradient id="paint"><stop stop-color="green"/></linearGradient>' : ""}<rect class="child-paint" fill="url(#paint)"/></svg>
+ <style media="screen" title="child">.child-paint { fill: url(#paint) }</style></div>`;
+ const { document } = parseHTML(
+ '<html><body><div data-composition-id="parent" data-composition-src="parent.html"></div><svg><linearGradient id="paint"><stop stop-color="blue"/></linearGradient></svg></body></html>',
+ );
+ const result = inlineSubCompositions(
+ document,
+ [...document.querySelectorAll("[data-composition-src]")],
+ {
+ resolveHtml: (src) => (src === "parent.html" ? parent : child),
+ parseHtml: (html) => parseHTML(html).document,
+ },
+ );
+ const rect = document.querySelector(".child-paint")!;
+ const id = rect.getAttribute("fill")!.slice(5, -1);
+ expect(document.getElementById(id)!.querySelector("stop")!.getAttribute("stop-color")).toBe(
+ shadow ? "green" : "red",
+ );
+ expect(result.styles[0]).toEqual({
+ css: expect.stringContaining(`url(#${id})`),
+ media: "screen",
+ title: "child",
+ });
+ },
+ );
+
+ it("initializes selector compatibility for module-only compositions", () => {
+ const scene = (
+ id: string,
+ ) => `<div data-composition-id="${id}"><svg><path id="shape"/><use href="#shape"/></svg>
+ <script type="module">window.moduleHit = document.querySelector('[data-composition-id="b"]').querySelector('#shape').id;</script></div>`;
+ const { document, result } = inlineScenes({ "a.html": scene("a"), "b.html": scene("b") }, [
+ { compId: "a", src: "a.html" },
+ { compId: "b", src: "b.html" },
+ ]);
+ expect(result.scripts).toHaveLength(0);
+ const dom = new JSDOM(document.toString(), { runScripts: "outside-only" });
+ for (const script of result.moduleScripts) dom.window.eval(script);
+ expect(dom.window.moduleHit).toBe("b--shape");
+ dom.window.close();
+ });
+});
diff --git a/packages/core/src/compiler/inlineSubCompositions.ts b/packages/core/src/compiler/inlineSubCompositions.ts
index 9581116f3c..de322221b2 100644
--- a/packages/core/src/compiler/inlineSubCompositions.ts
+++ b/packages/core/src/compiler/inlineSubCompositions.ts
@@ -30,6 +30,11 @@ import {
scopedModulePrelude,
wrapScopedCompositionScript,
} from "./compositionScoping";
+import {
+ namespaceCollidingSvgIds,
+ rewriteSvgIdReferencesInCss,
+ type SvgIdScope,
+} from "./svgIdNamespacing";
import {
checkSubCompositionUsability,
resolveSubCompositionContent,
@@ -336,6 +341,7 @@ export function inlineSubCompositions(
const moduleScripts: string[] = [];
const externalLinks: ExternalLink[] = [];
const variablesByComp: Record<string, Record<string, unknown>> = {};
+ const svgIdScopes: Array<SvgIdScope & { styleStart: number; styleEnd: number }> = [];
const sceneHosts = new Map<string, Element>();
const queue = hosts.map((element) => ({
@@ -486,12 +492,14 @@ export function inlineSubCompositions(
// Head-sourced assets come first: a non-templated sub-composition's <head>
// carries its backgrounds, positioning and fonts, and a <head> library tag
// (GSAP from a CDN) has to run before the content scripts calling into it.
+ const styleStart = styles.length;
for (const styleEl of plan.styleSources) {
if (cssStyleMergeKey(styleEl) === undefined) continue;
styles.push(compositionStyle(styleEl, scopeSubStyle(styleEl.textContent || "")));
if (scene) styleScenes.push(scene);
styleEl.remove();
}
+ const styleEnd = styles.length;
// Head- and content-sourced scripts take the same branch.
for (const scriptEl of plan.scriptSources) {
@@ -645,8 +653,46 @@ export function inlineSubCompositions(
for (const nestedHost of nested.hosts) {
queue.push({ element: nestedHost.host, ancestry: nestedAncestry, scene });
}
+
+ // Remember this instance for the SVG id pass below. Keyed on the
+ // document-unique runtime id (falling back to the authored id for an
+ // anonymous host with no duplicate instances) — the same identity CSS
+ // scoping and script scoping already key on. Nested hosts are excluded
+ // because each of them is recorded as its own scope when dequeued.
+ svgIdScopes.push({
+ root: hostEl,
+ namespace: runtimeCompId || scopeCompId,
+ exclude: nested.hosts.map((nestedHost) => nestedHost.host),
+ styleStart,
+ styleEnd,
+ });
}
+ // SVG ids (`<clipPath id="clip">`, `<symbol id="shape">`, `<filter
+ // id="fx">`, …) are namespaced only once EVERY instance is in the document:
+ // whether an id collides is a property of the assembled document, not of one
+ // composition file, and an id that stays unique must stay untouched so the
+ // author's own `#id` lookups keep working. Each instance's extracted
+ // `<style>` text gets the same substitution its DOM just received. See
+ // svgIdNamespacing.ts for why this is a rename, unlike the sibling
+ // getElementById/media-id fixes.
+ const svgIdMaps = namespaceCollidingSvgIds(
+ document,
+ svgIdScopes.map(({ root, namespace, exclude, styleStart, styleEnd }) => ({
+ root,
+ namespace,
+ exclude,
+ cssTexts: styles.slice(styleStart, styleEnd).map((style) => style.css),
+ })),
+ );
+ svgIdMaps.forEach((idMap, index) => {
+ if (idMap.size === 0) return;
+ const { styleStart, styleEnd } = svgIdScopes[index]!;
+ for (let i = styleStart; i < styleEnd; i += 1) {
+ styles[i]!.css = rewriteSvgIdReferencesInCss(styles[i]!.css, idMap);
+ }
+ });
+
return {
styles,
styleScenes,
diff --git a/packages/core/src/compiler/selectorIdTokens.test.ts b/packages/core/src/compiler/selectorIdTokens.test.ts
new file mode 100644
index 0000000000..c1f631e46a
--- /dev/null
+++ b/packages/core/src/compiler/selectorIdTokens.test.ts
@@ -0,0 +1,89 @@
+import { describe, expect, it } from "vitest";
+import {
+ decodeCssIdentifierAt,
+ escapeCssIdentifier,
+ replaceSelectorIdTokens,
+} from "./selectorIdTokens";
+
+describe("decodeCssIdentifierAt", () => {
+ it("reads a plain identifier and stops at the first non-name character", () => {
+ expect(decodeCssIdentifierAt("clip rect", 0)).toEqual({ value: "clip", end: 4 });
+ expect(decodeCssIdentifierAt("#clip2.x", 1)).toEqual({ value: "clip2", end: 6 });
+ expect(decodeCssIdentifierAt("#", 1)).toBeNull();
+ expect(decodeCssIdentifierAt("# a", 1)).toBeNull();
+ });
+
+ it("decodes character and hex escapes, consuming one trailing whitespace after hex", () => {
+ expect(decodeCssIdentifierAt(String.raw`fx\.1`, 0)).toEqual({ value: "fx.1", end: 5 });
+ expect(decodeCssIdentifierAt(String.raw`fx\2e\31 {`, 0)).toEqual({ value: "fx.1", end: 9 });
+ expect(decodeCssIdentifierAt("fx\\2e\\31\r\n{", 0)).toEqual({ value: "fx.1", end: 10 });
+ expect(decodeCssIdentifierAt(String.raw`\31 st`, 0)).toEqual({ value: "1st", end: 6 });
+ });
+
+ it("maps out-of-range and surrogate code points to U+FFFD", () => {
+ expect(decodeCssIdentifierAt(String.raw`a\0 b`, 0)?.value).toBe("a�b");
+ expect(decodeCssIdentifierAt(String.raw`a\d800 b`, 0)?.value).toBe("a�b");
+ expect(decodeCssIdentifierAt(String.raw`a\110000 b`, 0)?.value).toBe("a�b");
+ });
+
+ it("accepts non-ASCII name characters unescaped", () => {
+ expect(decodeCssIdentifierAt("héllo.x", 0)).toEqual({ value: "héllo", end: 5 });
+ });
+});
+
+describe("escapeCssIdentifier", () => {
+ it("follows the CSS.escape algorithm", () => {
+ expect(escapeCssIdentifier("clip")).toBe("clip");
+ expect(escapeCssIdentifier("fx.1")).toBe(String.raw`fx\.1`);
+ expect(escapeCssIdentifier("a b")).toBe(String.raw`a\ b`);
+ expect(escapeCssIdentifier("1st")).toBe(String.raw`\31 st`);
+ expect(escapeCssIdentifier("-1")).toBe(String.raw`-\31 `);
+ expect(escapeCssIdentifier("-")).toBe(String.raw`\-`);
+ expect(escapeCssIdentifier("a\u0000b")).toBe("a�b");
+ expect(escapeCssIdentifier("ab")).toBe(String.raw`a\1 b`);
+ expect(escapeCssIdentifier("héllo")).toBe("héllo");
+ });
+
+ it("round-trips through decodeCssIdentifierAt", () => {
+ for (const id of ["clip", "fx.1", "1st", "-1", "a b", "x:y", "tab\there", "ünï", "-"]) {
+ const escaped = escapeCssIdentifier(id);
+ expect(decodeCssIdentifierAt(escaped, 0)).toEqual({ value: id, end: escaped.length });
+ }
+ });
+});
+
+describe("replaceSelectorIdTokens", () => {
+ const swap = (selector: string, ids: string[]) =>
+ replaceSelectorIdTokens(selector, ids, (id) => `<${id}>`);
+
+ it("replaces whole-token ids only", () => {
+ expect(swap("#clip rect, #clip2 > #clip.x", ["clip"])).toBe("<clip> rect, #clip2 > <clip>.x");
+ });
+
+ it("matches escaped spellings of a raw id", () => {
+ expect(swap(String.raw`#fx\.1 .a`, ["fx.1"])).toBe("<fx.1> .a");
+ expect(swap(String.raw`#fx\2e\31 .a`, ["fx.1"])).toBe("<fx.1> .a");
+ });
+
+ it("skips ids inside strings and attribute selectors", () => {
+ const selector = `[href="#clip"] #clip a[data-x='#clip'], [data-y=#clip]`;
+ expect(swap(selector, ["clip"])).toBe(
+ `[href="#clip"] <clip> a[data-x='#clip'], [data-y=#clip]`,
+ );
+ });
+
+ it("does not treat a longer identifier as a shorter candidate", () => {
+ expect(swap("#clip-b", ["clip"])).toBe("#clip-b");
+ expect(swap("#clipé", ["clip"])).toBe("#clipé");
+ expect(swap(String.raw`#clip\:x`, ["clip"])).toBe(String.raw`#clip\:x`);
+ });
+});
+
+it("does not rewrite escaped hashes inside class names", () => {
+ expect(replaceSelectorIdTokens(String.raw`.foo\#clip #clip`, ["clip"], () => "#new")).toBe(
+ String.raw`.foo\#clip #new`,
+ );
+ expect(replaceSelectorIdTokens(String.raw`.foo\[bar #clip`, ["clip"], () => "#new")).toBe(
+ String.raw`.foo\[bar #new`,
+ );
+});
diff --git a/packages/core/src/compiler/selectorIdTokens.ts b/packages/core/src/compiler/selectorIdTokens.ts
new file mode 100644
index 0000000000..0ee8ee3820
--- /dev/null
+++ b/packages/core/src/compiler/selectorIdTokens.ts
@@ -0,0 +1,208 @@
+/**
+ * Shared low-level scanner: walk a CSS selector and replace whole-token
+ * `#id` occurrences that sit outside quotes and attribute-selector brackets.
+ *
+ * Extracted from `compositionScoping.ts`'s authored-root-id rewrite (the
+ * original, single-id version of this scan) so `svgIdNamespacing.ts` can
+ * reuse the exact same quote/bracket-tracking logic for its many-id rewrite
+ * instead of a second, drifting copy of the same state machine.
+ *
+ * Split into two small passes rather than one branch-heavy loop: first mark
+ * which offsets are outside a quoted string or an attribute-selector
+ * bracket (`markUnguardedOffsets`), then walk the selector once more,
+ * consulting that mask, to actually splice in replacements
+ * (`replaceSelectorIdTokens`). Each pass stays simple enough to read at a
+ * glance instead of one function juggling both jobs.
+ *
+ * The `#id` token is read as a CSS identifier per CSS Syntax Level 3
+ * (`decodeCssIdentifierAt`): `\.`-style and `\HEX `-style escapes are
+ * decoded before the id is compared against the candidate list, so a
+ * stylesheet spelling `#fx\.1` matches the element whose raw `id` attribute
+ * is `fx.1`. Callers emit replacement selectors through
+ * `escapeCssIdentifier`, the inverse operation.
+ */
+
+/** Unescaped name code points: `[A-Za-z0-9_-]` plus any non-ASCII. */
+function isNameChar(char: string | undefined): boolean {
+ if (!char) return false;
+ return /[\w-]/.test(char) || char.charCodeAt(0) >= 0x80;
+}
+
+/** CSS whitespace as defined by CSS Syntax Level 3 (`\r\n` handled by the caller). */
+function isCssWhitespace(char: string | undefined): boolean {
+ return char === " " || char === "\t" || char === "\n" || char === "\r" || char === "\f";
+}
+
+const HEX_ESCAPE_RE = /^[0-9a-fA-F]{1,6}/;
+
+/** Out-of-range and surrogate code points decode to U+FFFD, as the spec requires. */
+function sanitizeCodePoint(codePoint: number): number {
+ const isSurrogate = codePoint >= 0xd800 && codePoint <= 0xdfff;
+ return codePoint === 0 || codePoint > 0x10ffff || isSurrogate ? 0xfffd : codePoint;
+}
+
+/** A hex escape swallows ONE following whitespace; `\r\n` counts as one. */
+function skipEscapeWhitespace(text: string, index: number): number {
+ if (text[index] === "\r" && text[index + 1] === "\n") return index + 2;
+ return isCssWhitespace(text[index]) ? index + 1 : index;
+}
+
+/**
+ * "Consume an escaped code point" (CSS Syntax Level 3) with `text[index]`
+ * being the backslash: 1-6 hex digits plus one optional trailing whitespace
+ * decode to that code point, any other non-newline character decodes to
+ * itself. Returns `null` for an invalid escape (trailing backslash or a
+ * backslash before a newline), which ends the identifier.
+ */
+function consumeCssEscape(text: string, index: number): { value: string; end: number } | null {
+ const next = text[index + 1];
+ if (next === undefined || next === "\n") return null;
+ const hex = HEX_ESCAPE_RE.exec(text.slice(index + 1, index + 7));
+ if (!hex) return { value: next, end: index + 2 };
+ const codePoint = sanitizeCodePoint(Number.parseInt(hex[0], 16));
+ return {
+ value: String.fromCodePoint(codePoint),
+ end: skipEscapeWhitespace(text, index + 1 + hex[0].length),
+ };
+}
+
+/**
+ * Read one CSS identifier starting at `start` and return its decoded value
+ * plus the offset just past it, or `null` when no identifier starts there.
+ * Follows the "consume an ident sequence" algorithm of CSS Syntax Level 3.
+ */
+export function decodeCssIdentifierAt(
+ text: string,
+ start: number,
+): { value: string; end: number } | null {
+ let index = start;
+ let value = "";
+ while (index < text.length) {
+ const char = text[index]!;
+ if (char === "\\") {
+ const escape = consumeCssEscape(text, index);
+ if (!escape) break;
+ value += escape.value;
+ index = escape.end;
+ continue;
+ }
+ if (!isNameChar(char)) break;
+ value += char;
+ index += 1;
+ }
+ return index === start ? null : { value, end: index };
+}
+
+const CODE_UNIT_HYPHEN = 0x2d;
+
+function isDigitCodeUnit(codeUnit: number): boolean {
+ return codeUnit >= 0x30 && codeUnit <= 0x39;
+}
+
+/** Code units `CSS.escape` copies through verbatim: `[A-Za-z0-9_-]` and non-ASCII. */
+function isPlainNameCodeUnit(codeUnit: number): boolean {
+ return (
+ codeUnit >= 0x80 ||
+ codeUnit === CODE_UNIT_HYPHEN ||
+ codeUnit === 0x5f ||
+ isDigitCodeUnit(codeUnit) ||
+ (codeUnit >= 0x41 && codeUnit <= 0x5a) ||
+ (codeUnit >= 0x61 && codeUnit <= 0x7a)
+ );
+}
+
+/** Code units `CSS.escape` writes as a hex escape: control characters, and a
+ * digit in a position where it would otherwise start a number. */
+function needsHexEscape(value: string, index: number): boolean {
+ const codeUnit = value.charCodeAt(index);
+ if ((codeUnit >= 0x01 && codeUnit <= 0x1f) || codeUnit === 0x7f) return true;
+ if (!isDigitCodeUnit(codeUnit)) return false;
+ return index === 0 || (index === 1 && value.charCodeAt(0) === CODE_UNIT_HYPHEN);
+}
+
+/**
+ * Serialize `value` as a CSS identifier — the `CSS.escape()` algorithm from
+ * CSSOM, implemented here because Node has no `CSS` global. Every output is
+ * a valid `#ident` selector body that `decodeCssIdentifierAt` round-trips
+ * back to `value`.
+ */
+export function escapeCssIdentifier(value: string): string {
+ let result = "";
+ for (let index = 0; index < value.length; index += 1) {
+ const codeUnit = value.charCodeAt(index);
+ const char = value[index]!;
+ if (codeUnit === 0) result += "\uFFFD";
+ else if (needsHexEscape(value, index)) result += `\\${codeUnit.toString(16)} `;
+ else if (index === 0 && value.length === 1 && codeUnit === CODE_UNIT_HYPHEN)
+ result += `\\${char}`;
+ else if (isPlainNameCodeUnit(codeUnit)) result += char;
+ else result += `\\${char}`;
+ }
+ return result;
+}
+
+/**
+ * A full attribute-selector bracket (`[data-x="a"]`, quotes optional, `]`
+ * inside a quoted value tolerated) or a bare quoted string. Either is a
+ * region where a literal `#` is never an id-selector prefix — the CSS parser
+ * itself never looks for one there — so `markUnguardedOffsets` below can
+ * find every such region with one pass of `matchAll` instead of a hand-rolled
+ * character-by-character state machine. Inside the bracket alternative, bare
+ * characters exclude the quote marks so each position matches exactly one
+ * branch (no ambiguous backtracking).
+ */
+const GUARDED_SELECTOR_SEGMENT_RE =
+ /\\(?:[0-9a-fA-F]{1,6}(?:\r\n|[ \t\r\n\f])?|[\s\S])|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\[(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^\]"'])*\]/g;
+
+/**
+ * `mask[i]` is `true` when `selector[i]` sits outside both a quoted string
+ * and an attribute-selector bracket — the two places a literal `#` is never
+ * an id selector prefix.
+ */
+function markUnguardedOffsets(selector: string): boolean[] {
+ const mask = new Array<boolean>(selector.length).fill(true);
+ for (const match of selector.matchAll(GUARDED_SELECTOR_SEGMENT_RE)) {
+ const start = match.index;
+ mask.fill(false, start, start + match[0].length);
+ }
+ return mask;
+}
+
+/**
+ * Replace every whole-token `#id` in `selector` whose DECODED identifier is
+ * in `candidateIds`, skipping occurrences inside a quoted string or an
+ * attribute-selector bracket.
+ *
+ * Because the whole identifier is consumed before comparing, `#clip2` is
+ * never mistaken for `#clip`, and `#fx\.1` matches the candidate `fx.1`.
+ * `resolveReplacement` receives the matched (decoded) id and returns the
+ * full replacement text (including its own leading `#`, if any) to splice
+ * in.
+ */
+export function replaceSelectorIdTokens(
+ selector: string,
+ candidateIds: readonly string[],
+ resolveReplacement: (matchedId: string) => string,
+): string {
+ if (candidateIds.length === 0 || !selector.includes("#")) return selector;
+ const candidates = new Set(candidateIds);
+ const unguarded = markUnguardedOffsets(selector);
+
+ let result = "";
+ let index = 0;
+ while (index < selector.length) {
+ const token =
+ unguarded[index] && selector[index] === "#"
+ ? decodeCssIdentifierAt(selector, index + 1)
+ : null;
+ if (token && candidates.has(token.value)) {
+ result += resolveReplacement(token.value);
+ index = token.end;
+ } else {
+ result += selector[index];
+ index += 1;
+ }
+ }
+
+ return result;
+}
diff --git a/packages/core/src/compiler/svgIdNamespacing.test.ts b/packages/core/src/compiler/svgIdNamespacing.test.ts
new file mode 100644
index 0000000000..5ff2b47230
--- /dev/null
+++ b/packages/core/src/compiler/svgIdNamespacing.test.ts
@@ -0,0 +1,396 @@
+import { describe, expect, it } from "vitest";
+import { parseHTML } from "linkedom";
+import {
+ SVG_AUTHORED_ID_ATTR,
+ namespaceCollidingSvgIds,
+ rewriteSvgIdReferencesInCss,
+ type SvgIdScope,
+} from "./svgIdNamespacing";
+
+type ScopeSpec = { namespace: string; html: string; cssTexts?: string[] };
+
+/** Assemble one document with a `<div class="scope">` per instance — the
+ * shape the inline pipeline leaves behind — and namespace across them. */
+function namespace(specs: ScopeSpec[], { before = "", after = "" } = {}) {
+ const { document } = parseHTML(
+ `<!DOCTYPE html><html><body>${before}${specs
+ .map((spec) => `<div class="scope">${spec.html}</div>`)
+ .join("")}${after}</body></html>`,
+ );
+ const roots = [...document.querySelectorAll("div.scope")];
+ const scopes: SvgIdScope[] = specs.map((spec, index) => ({
+ root: roots[index]!,
+ namespace: spec.namespace,
+ cssTexts: spec.cssTexts,
+ }));
+ const idMaps = namespaceCollidingSvgIds(
+ document as unknown as Parameters<typeof namespaceCollidingSvgIds>[0],
+ scopes,
+ );
+ return { document, roots, idMaps };
+}
+
+const CLIPPED =
+ '<svg><clipPath id="clip"><rect/></clipPath></svg><div clip-path="url(#clip)"></div>';
+
+describe("namespaceCollidingSvgIds", () => {
+ it("is a no-op when there are no svg ids", () => {
+ const { idMaps } = namespace([
+ { namespace: "scene-a", html: "<div><p>hello</p></div>" },
+ { namespace: "scene-b", html: "<div><p>hello</p></div>" },
+ ]);
+ expect(idMaps.every((m) => m.size === 0)).toBe(true);
+ });
+
+ it("leaves a single composition byte-for-byte unchanged, even with native references", () => {
+ // The reviewer's repro: one composition, `<use href="#shape">` next to
+ // `<path id="shape">`. Nothing collides, so nothing may be renamed —
+ // otherwise `svg.querySelector("#shape")` breaks for no reason.
+ const { document, idMaps } = namespace([
+ {
+ namespace: "scene-a",
+ html: '<svg><path id="shape" d="M0,0"/><use href="#shape"></use></svg>',
+ },
+ ]);
+ expect(idMaps[0]!.size).toBe(0);
+ const path = document.querySelector("path")!;
+ expect(path.getAttribute("id")).toBe("shape");
+ expect(path.hasAttribute(SVG_AUTHORED_ID_ATTR)).toBe(false);
+ expect(document.querySelector("use")!.getAttribute("href")).toBe("#shape");
+ expect(document.querySelector("svg")!.querySelector("#shape")).toBe(path);
+ });
+
+ it("leaves two compositions alone when their ids do not collide", () => {
+ const { idMaps } = namespace([
+ { namespace: "scene-a", html: CLIPPED },
+ { namespace: "scene-b", html: CLIPPED.replaceAll("clip", "clip-b") },
+ ]);
+ expect(idMaps.every((m) => m.size === 0)).toBe(true);
+ });
+
+ it("does not rename when namespace is empty (anonymous host)", () => {
+ const { document, idMaps } = namespace([
+ { namespace: "", html: CLIPPED },
+ { namespace: "", html: CLIPPED },
+ ]);
+ expect(idMaps.every((m) => m.size === 0)).toBe(true);
+ for (const el of document.querySelectorAll("clipPath")) {
+ expect(el.getAttribute("id")).toBe("clip");
+ }
+ });
+
+ it("never renames colliding svg ids that have no native reference (JS-only ids)", () => {
+ // Two scenes each animate `#cut-1` from a script and nothing else refers
+ // to it. Renaming would make the id unreachable for a global library
+ // that reads `document` directly, so both instances keep it — the
+ // documented residual collision for the JS-only class.
+ const { document, idMaps } = namespace([
+ { namespace: "scene-a", html: '<svg><path id="cut-1" d="M0,0 L10,10"></path></svg>' },
+ { namespace: "scene-b", html: '<svg><path id="cut-1" d="M0,0 L10,10"></path></svg>' },
+ ]);
+ expect(idMaps.every((m) => m.size === 0)).toBe(true);
+ expect([...document.querySelectorAll("path")].map((p) => p.getAttribute("id"))).toEqual([
+ "cut-1",
+ "cut-1",
+ ]);
+ });
+
+ it("keeps the first colliding instance and renames the later one, recording the authored id", () => {
+ const { document, idMaps, roots } = namespace([
+ { namespace: "scene-a", html: CLIPPED },
+ { namespace: "scene-b", html: CLIPPED },
+ ]);
+ expect(idMaps[0]!.size).toBe(0);
+ expect(idMaps[1]!.get("clip")).toBe("scene-b--clip");
+
+ const clipA = roots[0]!.querySelector("clipPath")!;
+ const clipB = roots[1]!.querySelector("clipPath")!;
+ expect(clipA.getAttribute("id")).toBe("clip");
+ expect(clipA.hasAttribute(SVG_AUTHORED_ID_ATTR)).toBe(false);
+ expect(clipB.getAttribute("id")).toBe("scene-b--clip");
+ expect(clipB.getAttribute(SVG_AUTHORED_ID_ATTR)).toBe("clip");
+
+ // Native resolution binds `url(#clip)` to the FIRST `id="clip"` in
+ // document order — which is now the only one, and scene A's own.
+ expect(roots[0]!.querySelector("div")!.getAttribute("clip-path")).toBe("url(#clip)");
+ expect(roots[1]!.querySelector("div")!.getAttribute("clip-path")).toBe("url(#scene-b--clip)");
+ expect(document.querySelectorAll('[id="clip"]')).toHaveLength(1);
+ });
+
+ it("renames a natively-referenced instance that collides with an id the parent document owns", () => {
+ // The top-level document is outside every scope and can never be
+ // renamed, so it is the keeper even though the inlined instance comes
+ // first in document order.
+ const { document, idMaps, roots } = namespace([{ namespace: "scene-a", html: CLIPPED }], {
+ after:
+ '<svg><clipPath id="clip"><rect/></clipPath></svg><div id="parent-user" clip-path="url(#clip)"></div>',
+ });
+ expect(idMaps[0]!.get("clip")).toBe("scene-a--clip");
+ expect(roots[0]!.querySelector("clipPath")!.getAttribute("id")).toBe("scene-a--clip");
+ expect(roots[0]!.querySelector("div")!.getAttribute("clip-path")).toBe("url(#scene-a--clip)");
+ expect(document.querySelector("#parent-user")!.getAttribute("clip-path")).toBe("url(#clip)");
+ });
+
+ it("renames a natively-referenced instance that collides with a JS-only id elsewhere", () => {
+ // Scene A's `#clip` is JS-only (unrenamable) and comes first; scene B's
+ // is natively referenced. B must be renamed even though A is untouched,
+ // or B's `url(#clip)` would bind to A's element.
+ const { roots, idMaps } = namespace([
+ { namespace: "scene-a", html: '<svg><clipPath id="clip"><rect/></clipPath></svg>' },
+ { namespace: "scene-b", html: CLIPPED },
+ ]);
+ expect(idMaps[0]!.size).toBe(0);
+ expect(idMaps[1]!.get("clip")).toBe("scene-b--clip");
+ expect(roots[0]!.querySelector("clipPath")!.getAttribute("id")).toBe("clip");
+ expect(roots[1]!.querySelector("clipPath")!.getAttribute("id")).toBe("scene-b--clip");
+
+ // And the mirror image: the JS-only instance comes SECOND. It still
+ // cannot be renamed, so the natively-referenced first instance is.
+ const mirrored = namespace([
+ { namespace: "scene-a", html: CLIPPED },
+ { namespace: "scene-b", html: '<svg><clipPath id="clip"><rect/></clipPath></svg>' },
+ ]);
+ expect(mirrored.idMaps[0]!.get("clip")).toBe("scene-a--clip");
+ expect(mirrored.idMaps[1]!.size).toBe(0);
+ expect(mirrored.roots[0]!.querySelector("div")!.getAttribute("clip-path")).toBe(
+ "url(#scene-a--clip)",
+ );
+ expect(mirrored.roots[1]!.querySelector("clipPath")!.getAttribute("id")).toBe("clip");
+ });
+
+ it("rewrites filter/mask/fill/stroke/marker url() references in the renamed instance", () => {
+ const html = `
+ <svg>
+ <filter id="fx"></filter>
+ <mask id="msk"></mask>
+ <linearGradient id="grad"></linearGradient>
+ <marker id="arrow"></marker>
+ </svg>
+ <div style="filter:url(#fx); mask: url('#msk')"></div>
+ <rect fill="url(#grad)" stroke="url(#grad)" marker-start="url(#arrow)" marker-end="url(#arrow)"></rect>
+ `;
+ const { roots } = namespace([
+ { namespace: "scene-a", html },
+ { namespace: "scene-b", html },
+ ]);
+ const div = roots[1]!.querySelector("div")!;
+ expect(div.getAttribute("style")).toBe("filter:url(#scene-b--fx); mask: url('#scene-b--msk')");
+ const rect = roots[1]!.querySelector("rect")!;
+ expect(rect.getAttribute("fill")).toBe("url(#scene-b--grad)");
+ expect(rect.getAttribute("stroke")).toBe("url(#scene-b--grad)");
+ expect(rect.getAttribute("marker-start")).toBe("url(#scene-b--arrow)");
+ expect(rect.getAttribute("marker-end")).toBe("url(#scene-b--arrow)");
+ // The keeper instance is untouched.
+ expect(roots[0]!.querySelector("div")!.getAttribute("style")).toBe(
+ "filter:url(#fx); mask: url('#msk')",
+ );
+ });
+
+ it("rewrites <use href> and xlink:href fragment refs", () => {
+ const html =
+ '<svg><symbol id="shape"></symbol><use href="#shape"></use><use xlink:href="#shape"></use></svg>';
+ const { roots } = namespace([
+ { namespace: "scene-a", html },
+ { namespace: "scene-c", html },
+ ]);
+ const uses = [...roots[1]!.querySelectorAll("use")];
+ expect(uses[0]!.getAttribute("href")).toBe("#scene-c--shape");
+ expect(uses[1]!.getAttribute("xlink:href")).toBe("#scene-c--shape");
+ });
+
+ it("counts a url(#id) reference from the instance's extracted <style> text as native", () => {
+ const svg = '<svg><filter id="rough-filter"><feTurbulence/></filter></svg>';
+ const { roots, idMaps } = namespace([
+ { namespace: "scene-a", html: svg, cssTexts: [".title { filter: url(#rough-filter); }"] },
+ { namespace: "scene-b", html: svg, cssTexts: [".title { filter: url(#rough-filter); }"] },
+ ]);
+ expect(idMaps[1]!.get("rough-filter")).toBe("scene-b--rough-filter");
+ expect(roots[1]!.querySelector("filter")!.getAttribute("id")).toBe("scene-b--rough-filter");
+ });
+
+ it("leaves unrelated hrefs and non-fragment urls untouched", () => {
+ const html =
+ CLIPPED +
+ '<a href="https://example.com/#clip">link</a>' +
+ '<div class="bg" style="background:url(image.png)"></div>';
+ const { roots } = namespace([
+ { namespace: "scene-a", html },
+ { namespace: "scene-d", html },
+ ]);
+ expect(roots[1]!.querySelector("a")!.getAttribute("href")).toBe("https://example.com/#clip");
+ expect(roots[1]!.querySelector("div.bg")!.getAttribute("style")).toBe(
+ "background:url(image.png)",
+ );
+ });
+
+ it("skips excluded nested subtrees so a nested instance keeps its own scope", () => {
+ const nestedHtml =
+ '<div class="nested">' +
+ CLIPPED +
+ "</div>" +
+ '<svg><filter id="fx"></filter></svg><div style="filter:url(#fx)"></div>';
+ const { document } = parseHTML(
+ `<!DOCTYPE html><html><body><div class="outer">${nestedHtml}</div><div class="other">${CLIPPED}</div></body></html>`,
+ );
+ const outer = document.querySelector("div.outer")!;
+ const nested = document.querySelector("div.nested")!;
+ const other = document.querySelector("div.other")!;
+ const idMaps = namespaceCollidingSvgIds(
+ document as unknown as Parameters<typeof namespaceCollidingSvgIds>[0],
+ [
+ { root: outer, namespace: "outer", exclude: [nested] },
+ { root: nested, namespace: "nested" },
+ { root: other, namespace: "other" },
+ ],
+ );
+ // `clip` collides between the nested instance (first in document order,
+ // the keeper) and `other`; the OUTER scope must not claim the nested
+ // element as its own.
+ expect(idMaps[0]!.size).toBe(0);
+ expect(idMaps[1]!.size).toBe(0);
+ expect(idMaps[2]!.get("clip")).toBe("other--clip");
+ expect(nested.querySelector("clipPath")!.getAttribute("id")).toBe("clip");
+ expect(other.querySelector("clipPath")!.getAttribute("id")).toBe("other--clip");
+ });
+
+ it("mints a fresh id when the namespaced candidate is already taken", () => {
+ const { roots, idMaps } = namespace(
+ [
+ { namespace: "block", html: CLIPPED },
+ { namespace: "block", html: CLIPPED },
+ { namespace: "block", html: CLIPPED },
+ ],
+ { before: '<div id="block--clip"></div>' },
+ );
+ // Same authored id, same namespace (the producer path has no runtime
+ // ids), plus a pre-existing `block--clip`: every minted id is still
+ // document-unique.
+ expect(idMaps[0]!.size).toBe(0);
+ expect(idMaps[1]!.get("clip")).toBe("block--clip-2");
+ expect(idMaps[2]!.get("clip")).toBe("block--clip-3");
+ expect(roots[1]!.querySelector("div")!.getAttribute("clip-path")).toBe("url(#block--clip-2)");
+ });
+
+ it("does not overwrite an authored id recorded by an earlier pass", () => {
+ const { document } = parseHTML(
+ `<!DOCTYPE html><html><body><div class="scope">${CLIPPED}</div><div class="scope">${CLIPPED.replace(
+ 'id="clip"',
+ 'id="clip" data-hf-authored-id="original"',
+ )}</div></body></html>`,
+ );
+ const roots = [...document.querySelectorAll("div.scope")];
+ namespaceCollidingSvgIds(
+ document as unknown as Parameters<typeof namespaceCollidingSvgIds>[0],
+ [
+ { root: roots[0]!, namespace: "a" },
+ { root: roots[1]!, namespace: "b" },
+ ],
+ );
+ const renamed = roots[1]!.querySelector("clipPath")!;
+ expect(renamed.getAttribute("id")).toBe("b--clip");
+ expect(renamed.getAttribute(SVG_AUTHORED_ID_ATTR)).toBe("original");
+ });
+});
+
+it("preserves the first document target when a child has no local definition", () => {
+ const { document, idMaps } = namespace(
+ [
+ {
+ namespace: "earlier",
+ html: '<svg><linearGradient id="paint"/><rect fill="url(#paint)"/></svg>',
+ },
+ {
+ namespace: "parent",
+ html: '<svg><linearGradient id="paint"/><rect fill="url(#paint)"/></svg>',
+ },
+ { namespace: "child", html: '<svg><rect class="child" fill="url(#paint)"/></svg>' },
+ ],
+ { after: '<svg><linearGradient id="paint"/></svg>' },
+ );
+ expect(document.querySelector(".child")!.getAttribute("fill")).toBe("url(#earlier--paint)");
+ expect(idMaps[2]!.get("paint")).toBe("earlier--paint");
+});
+
+describe("rewriteSvgIdReferencesInCss", () => {
+ it("is a no-op with an empty map", () => {
+ const css = "#clip { fill: red; }";
+ expect(rewriteSvgIdReferencesInCss(css, new Map())).toBe(css);
+ });
+
+ it("rewrites a bare id selector to the namespaced id", () => {
+ const idMap = new Map([["clip", "scene-a--clip"]]);
+ const css = "#clip rect { fill: red; }";
+ expect(rewriteSvgIdReferencesInCss(css, idMap)).toContain("#scene-a--clip rect");
+ });
+
+ it("rewrites a url(#id) declaration value", () => {
+ const idMap = new Map([["fx", "scene-a--fx"]]);
+ const css = ".glow { filter: url(#fx); }";
+ expect(rewriteSvgIdReferencesInCss(css, idMap)).toContain("filter: url(#scene-a--fx)");
+ });
+
+ it("does not touch an id selector for an id outside the map", () => {
+ const idMap = new Map([["clip", "scene-a--clip"]]);
+ const css = "#other { fill: red; }";
+ expect(rewriteSvgIdReferencesInCss(css, idMap)).toBe(css);
+ });
+
+ it("does not confuse a short id with a longer one that starts with it", () => {
+ const idMap = new Map([
+ ["clip", "scene-a--clip"],
+ ["clip2", "scene-a--clip2"],
+ ]);
+ const css = "#clip2 { fill: red; }";
+ const result = rewriteSvgIdReferencesInCss(css, idMap);
+ expect(result).toContain("#scene-a--clip2");
+ expect(result).not.toContain("scene-a--clipscene-a");
+ });
+
+ it("matches an escaped id selector and emits a valid escaped replacement", () => {
+ // `id="fx.1"` is spelled `#fx\.1` in CSS. The raw id must be matched
+ // through the escape, and the renamed id re-escaped, or the rule
+ // silently stops applying after the rename.
+ const idMap = new Map([["fx.1", "scene-b--fx.1"]]);
+ const css = String.raw`#fx\.1 { opacity: .5; } .x { filter: url(#fx.1); }`;
+ const result = rewriteSvgIdReferencesInCss(css, idMap);
+ expect(result).toContain(String.raw`#scene-b--fx\.1 { opacity: .5; }`);
+ expect(result).toContain("filter: url(#scene-b--fx.1)");
+ });
+
+ it("decodes hex identifier escapes before matching", () => {
+ // `\31 ` is the hex escape for "1"; `\2e` for "."; both spell `fx.1`.
+ const idMap = new Map([["fx.1", "scene-b--fx.1"]]);
+ const css = String.raw`#fx\2e\31 { opacity: .5; } #fx\2e 1 { color: red }`;
+ const result = rewriteSvgIdReferencesInCss(css, idMap);
+ // The whitespace after `\31 ` belongs to the escape, so it is consumed.
+ expect(result).toMatch(/#scene-b--fx\\\.1\s*\{ opacity: \.5; \}/);
+ expect(result).toMatch(/#scene-b--fx\\\.1\s*\{ color: red \}/);
+ });
+
+ it("re-escapes characters the renamed id still carries", () => {
+ const idMap = new Map([["a b", "scene-b--a b"]]);
+ const css = String.raw`#a\ b { opacity: .5; }`;
+ expect(rewriteSvgIdReferencesInCss(css, idMap)).toContain(String.raw`#scene-b--a\ b {`);
+ });
+
+ it("leaves a #id inside an attribute selector or string untouched", () => {
+ const idMap = new Map([["clip", "scene-a--clip"]]);
+ const css = `[data-ref="#clip"] { fill: red; } .x::after { content: "#clip"; }`;
+ expect(rewriteSvgIdReferencesInCss(css, idMap)).toBe(css);
+ });
+});
+
+it("rewrites case-insensitive CSS URL functions in attributes and styles", () => {
+ const { roots, idMaps } = namespace([
+ { namespace: "a", html: CLIPPED },
+ {
+ namespace: "b",
+ html: '<svg><clipPath id="clip"/><rect clip-path="URL(#clip)"/></svg>',
+ cssTexts: ["rect { clip-path: Url(#clip) }"],
+ },
+ ]);
+ expect(roots[1]!.querySelector("rect")!.getAttribute("clip-path")).toBe("URL(#b--clip)");
+ expect(rewriteSvgIdReferencesInCss("rect { clip-path: Url(#clip) }", idMaps[1]!)).toContain(
+ "Url(#b--clip)",
+ );
+});
diff --git a/packages/core/src/compiler/svgIdNamespacing.ts b/packages/core/src/compiler/svgIdNamespacing.ts
new file mode 100644
index 0000000000..eadc20e241
--- /dev/null
+++ b/packages/core/src/compiler/svgIdNamespacing.ts
@@ -0,0 +1,436 @@
+/**
+ * Native SVG url()/href references resolve by document order, bypassing JS scoping.
+ * Rename only colliding, natively referenced SVG ids; leave JS-only ids reachable
+ * by libraries that bypass the scoped selector shim. The first unrenamable element
+ * keeps the authored id (otherwise the first element does). Renamed elements retain
+ * data-hf-authored-id for script lookup compatibility.
+ */
+
+import postcss from "postcss";
+import { escapeCssIdentifier, replaceSelectorIdTokens } from "./selectorIdTokens";
+
+const ID_ATTR = "id";
+
+/** Reused from `compositionScoping.ts`'s `AUTHORED_ROOT_ID_ATTR` in spirit —
+ * same purpose (let a renamed id still resolve by its authored name), now
+ * generalized from "the composition root" to any renamed descendant. */
+export const SVG_AUTHORED_ID_ATTR = "data-hf-authored-id";
+
+/**
+ * Matches a `url(#id)` funcref value — quoted or bare — as used by
+ * `clip-path`, `filter`, `mask`, `fill`, `stroke`, `marker-start/mid/end`,
+ * `cursor`, `mask-image`, and equally by any of those written into an inline
+ * `style` attribute or a `<style>` declaration value. One pattern covers all
+ * of them because CSS only ever spells an id reference this way in a
+ * property VALUE — a bare `#id` (no `url()`) is exclusively a *selector*.
+ *
+ * The captured id is the literal fragment text. A fragment is a URL, not a
+ * CSS identifier, so it carries no CSS escapes; the replacement keeps the
+ * original quoting and only swaps the id, which stays a valid fragment
+ * because the namespace prefix is restricted to `[A-Za-z0-9_-]`.
+ */
+const URL_HASH_REF_RE = /(url\(\s*)(["']?)#([^"')\s]+)\2(\s*\))/gi;
+
+/**
+ * Attributes carrying a bare `#id` fragment reference rather than a
+ * `url(#id)` funcref — SVG's `<use>`, `<a>`, `<pattern>`, `<textPath>`,
+ * `<feImage>`, `<mpath>`, and so on. Matching by suffix also covers
+ * namespaced `xlink:href`, however a given DOM implementation exposes it.
+ */
+function isHrefAttrName(name: string): boolean {
+ return name === "href" || name.endsWith(":href");
+}
+
+function sanitizeNamespaceSegment(value: string): string {
+ return value.replace(/[^a-zA-Z0-9_-]/g, "-");
+}
+
+function rewriteUrlHashRefs(value: string, idMap: ReadonlyMap<string, string>): string {
+ if (!value || !value.toLowerCase().includes("url(")) return value;
+ return value.replace(URL_HASH_REF_RE, (full, pre, quote, id: string, post) => {
+ const mapped = idMap.get(id);
+ return mapped ? `${pre}${quote}#${mapped}${quote}${post}` : full;
+ });
+}
+
+function rewriteHrefValue(value: string, idMap: ReadonlyMap<string, string>): string | null {
+ if (!value.startsWith("#")) return null;
+ const mapped = idMap.get(value.slice(1));
+ return mapped ? `#${mapped}` : null;
+}
+
+/** Rewrite every id reference carried on one element's attributes. CSS text
+ * inside a `<style>` element is handled separately by
+ * `rewriteSvgIdReferencesInCss` — it is extracted and scoped as a raw
+ * string elsewhere in the inline pipeline, never visited by this walk. */
+function rewriteElementIdReferences(el: Element, idMap: ReadonlyMap<string, string>): void {
+ const attrs = el.attributes ? Array.from(el.attributes) : [];
+ for (const attr of attrs) {
+ const { name, value } = attr;
+ if (!value) continue;
+ if (isHrefAttrName(name)) {
+ const rewritten = rewriteHrefValue(value, idMap);
+ if (rewritten) {
+ el.setAttribute(name, rewritten);
+ continue;
+ }
+ }
+ if (value.toLowerCase().includes("url(")) {
+ const rewritten = rewriteUrlHashRefs(value, idMap);
+ if (rewritten !== value) el.setAttribute(name, rewritten);
+ }
+ }
+}
+
+/** Structural shape both a linkedom/live-DOM `Element` and `Document`
+ * satisfy — mirrors the narrow-interface pattern `mediaRenderIds.ts` and
+ * `compositionAssembly.ts` already use so this module works unmodified
+ * across the preview bundler and the render compiler. */
+interface SvgIdQueryable {
+ querySelectorAll(selector: string): Iterable<Element>;
+}
+
+/** One inlined composition instance, as seen in the ASSEMBLED document. */
+export interface SvgIdScope {
+ /** The element whose subtree holds this instance's content (the host). */
+ root: Element;
+ /**
+ * Document-unique prefix for ids renamed in this scope — the instance's
+ * runtime composition id. An empty namespace makes the scope read-only:
+ * an anonymous host has no identity to prefix with, the same guard
+ * `scopeCssToComposition` and `wrapScopedCompositionScript` apply.
+ */
+ namespace: string;
+ /**
+ * Nested composition hosts inside `root` whose content belongs to their
+ * OWN scope. Their subtrees are skipped both when collecting this scope's
+ * ids and when rewriting its references.
+ */
+ exclude?: readonly Element[];
+ /**
+ * This instance's extracted `<style>` text (already removed from the DOM
+ * by the inline pipeline). Scanned for `url(#id)` references so a filter
+ * that is only applied from a stylesheet still counts as natively
+ * referenced. The caller rewrites these strings afterwards via
+ * `rewriteSvgIdReferencesInCss` with the returned map.
+ */
+ cssTexts?: readonly string[];
+}
+
+function collectUrlHashRefsFromText(
+ text: string,
+ filter: ReadonlySet<string>,
+ out: Set<string>,
+): void {
+ let m: RegExpExecArray | null;
+ URL_HASH_REF_RE.lastIndex = 0;
+ while ((m = URL_HASH_REF_RE.exec(text))) {
+ const refId = m[3]!;
+ if (filter.has(refId)) out.add(refId);
+ }
+}
+
+function collectHrefFragmentRef(attr: Attr, filter: ReadonlySet<string>, out: Set<string>): void {
+ if (isHrefAttrName(attr.name) && attr.value.startsWith("#")) {
+ const id = attr.value.slice(1);
+ if (filter.has(id)) out.add(id);
+ }
+}
+
+/**
+ * Ids referenced by native browser resolution — `url(#id)` funcrefs and
+ * bare `href="#id"` fragment refs — as opposed to JavaScript-only refs
+ * (e.g. GSAP's `tl.to("#cut-1")`). Global libraries access `document`
+ * directly and bypass the composition-scoped querySelector Proxy, so only
+ * natively-referenced ids are safe to rename.
+ *
+ * RESIDUAL, BY DESIGN: two instances that both animate the same JS-ONLY id
+ * (two catalog scenes each doing `tl.to("#cut-1")`) both keep `id="cut-1"`.
+ * Scripts wrapped by `wrapScopedCompositionScript` still find their own
+ * element (the scoped `document`/GSAP proxies filter to the instance root),
+ * but an UNSCOPED lookup — a third-party library reading `document` directly
+ * — binds to the first instance in document order, exactly as it did before
+ * this module existed. Broadening this pre-scan to JS-only ids would trade
+ * that residual for breaking every such library lookup outright (the
+ * regression that motivated the gate), so the residual stays.
+ *
+ * Also not pre-scanned: references a script injects at runtime
+ * (`el.setAttribute("clip-path", "url(#foo)")` as the ONLY reference to
+ * `#foo`). Static markup and stylesheets are the contract.
+ */
+function collectNativelyReferencedIds(
+ elements: readonly Element[],
+ cssTexts: readonly string[],
+ svgIds: ReadonlySet<string>,
+): Set<string> {
+ const referenced = new Set<string>();
+ for (const el of elements) {
+ for (const attr of el.attributes ? Array.from(el.attributes) : []) {
+ if (!attr.value) continue;
+ collectHrefFragmentRef(attr, svgIds, referenced);
+ if (attr.value.toLowerCase().includes("url("))
+ collectUrlHashRefsFromText(attr.value, svgIds, referenced);
+ }
+ }
+ for (const text of cssTexts) {
+ if (text.toLowerCase().includes("url(")) collectUrlHashRefsFromText(text, svgIds, referenced);
+ }
+ return referenced;
+}
+
+function isExcluded(el: Element, exclude: readonly Element[]): boolean {
+ return exclude.some((excluded) => excluded === el || excluded.contains(el));
+}
+
+/** `root` plus every descendant that is not inside an excluded subtree. */
+function collectScopeElements(scope: SvgIdScope): Element[] {
+ const exclude = scope.exclude ?? [];
+ const descendants = [...scope.root.querySelectorAll("*")];
+ const own = exclude.length ? descendants.filter((el) => !isExcluded(el, exclude)) : descendants;
+ return [scope.root, ...own];
+}
+
+interface ResolvedScope {
+ elements: Element[];
+ /** Elements this scope may rename: inside an `<svg>` subtree, carrying an
+ * id that something in this same scope references natively. */
+ renamable: Set<Element>;
+}
+
+/** Every `<svg>`-subtree element in the scope that carries an id. */
+function collectSvgIdElements(scope: SvgIdScope): Element[] {
+ const exclude = scope.exclude ?? [];
+ const matches = [...scope.root.querySelectorAll("svg [id], svg[id]")];
+ return exclude.length ? matches.filter((el) => !isExcluded(el, exclude)) : matches;
+}
+
+function resolveScope(scope: SvgIdScope): ResolvedScope {
+ const elements = collectScopeElements(scope);
+ const renamable = new Set<Element>();
+ if (!scope.namespace) return { elements, renamable };
+
+ const svgIdElements = collectSvgIdElements(scope);
+ const svgIds = new Set<string>();
+ for (const el of svgIdElements) {
+ const id = el.getAttribute(ID_ATTR);
+ if (id) svgIds.add(id);
+ }
+ if (svgIds.size === 0) return { elements, renamable };
+
+ const nativelyReferenced = collectNativelyReferencedIds(elements, scope.cssTexts ?? [], svgIds);
+ for (const el of svgIdElements) {
+ const id = el.getAttribute(ID_ATTR);
+ if (id && nativelyReferenced.has(id)) renamable.add(el);
+ }
+ return { elements, renamable };
+}
+
+interface IdCensus {
+ /** Every element carrying each id, in document order — the order native
+ * resolution uses. */
+ elementsById: Map<string, Element[]>;
+ /** Every id in the document, extended with each minted id so no two
+ * renames (or a rename and an authored id) can ever coincide. */
+ usedIds: Set<string>;
+}
+
+function buildIdCensus(document: SvgIdQueryable): IdCensus {
+ const elementsById = new Map<string, Element[]>();
+ const usedIds = new Set<string>();
+ for (const el of document.querySelectorAll("[id]")) {
+ const id = el.getAttribute(ID_ATTR);
+ if (!id) continue;
+ usedIds.add(id);
+ const list = elementsById.get(id);
+ if (list) list.push(el);
+ else elementsById.set(id, [el]);
+ }
+ return { elementsById, usedIds };
+}
+
+function hasAnyCollision(census: IdCensus): boolean {
+ for (const elements of census.elementsById.values()) {
+ if (elements.length > 1) return true;
+ }
+ return false;
+}
+
+/** A namespaced id that is not already taken anywhere in the document. */
+function mintNamespacedId(namespace: string, originalId: string, usedIds: Set<string>): string {
+ const base = `${sanitizeNamespaceSegment(namespace)}--${originalId}`;
+ let candidate = base;
+ for (let n = 2; usedIds.has(candidate); n += 1) candidate = `${base}-${n}`;
+ usedIds.add(candidate);
+ return candidate;
+}
+
+/**
+ * Decide, per scope, which ids get renamed and to what. For every colliding
+ * id the keeper is the first element in document order that no scope can
+ * rename, else simply the first element; every other renamable element's
+ * scope receives a mapping for that id.
+ */
+function planRenames(
+ census: IdCensus,
+ scopes: readonly SvgIdScope[],
+ scopeIndexByRenamable: ReadonlyMap<Element, number>,
+): Map<string, string>[] {
+ const idMaps = scopes.map(() => new Map<string, string>());
+ for (const [id, elements] of census.elementsById) {
+ if (elements.length < 2) continue;
+ const keeper = elements.find((el) => !scopeIndexByRenamable.has(el)) ?? elements[0]!;
+ for (const el of elements) {
+ if (el === keeper) continue;
+ const scopeIndex = scopeIndexByRenamable.get(el);
+ if (scopeIndex === undefined) continue;
+ const idMap = idMaps[scopeIndex]!;
+ if (!idMap.has(id)) {
+ idMap.set(id, mintNamespacedId(scopes[scopeIndex]!.namespace, id, census.usedIds));
+ }
+ }
+ }
+ return idMaps;
+}
+
+/** Rename the planned elements in one scope and rewrite every reference in
+ * that scope's attributes to match. */
+function applyRenames(resolved: ResolvedScope, idMap: ReadonlyMap<string, string>): void {
+ for (const el of resolved.elements) {
+ const currentId = el.getAttribute(ID_ATTR);
+ if (currentId && resolved.renamable.has(el) && idMap.has(currentId)) {
+ if (!el.hasAttribute(SVG_AUTHORED_ID_ATTR)) el.setAttribute(SVG_AUTHORED_ID_ATTR, currentId);
+ el.setAttribute(ID_ATTR, idMap.get(currentId)!);
+ }
+ rewriteElementIdReferences(el, idMap);
+ }
+}
+
+/**
+ * Rename every colliding, natively-referenced SVG id across the inlined
+ * composition instances in `scopes` and rewrite each instance's attribute
+ * references (`href`/`xlink:href`, any `url(#id)` funcref — including inside
+ * a `style` attribute) to match.
+ *
+ * Returns one old-id -> new-id map per scope, in the same order, so the
+ * caller can apply the identical substitution to that instance's separately
+ * extracted `<style>` text via `rewriteSvgIdReferencesInCss`, which this
+ * function never sees. Maps include inherited references whose original target
+ * was renamed elsewhere; scopes with local definitions keep their own mapping.
+ *
+ * `document` must be the ASSEMBLED document every scope root lives in: the
+ * collision census covers the whole thing, including ids the top-level
+ * document declares itself, since those collide with an inlined instance's
+ * ids just as two instances collide with each other.
+ */
+export function namespaceCollidingSvgIds(
+ document: SvgIdQueryable,
+ scopes: readonly SvgIdScope[],
+): Map<string, string>[] {
+ const untouched = scopes.map(() => new Map<string, string>());
+ if (scopes.length === 0) return untouched;
+
+ const census = buildIdCensus(document);
+ if (!hasAnyCollision(census)) return untouched;
+
+ const resolved = scopes.map(resolveScope);
+ const scopeIndexByRenamable = new Map<Element, number>();
+ resolved.forEach(({ renamable }, index) => {
+ for (const el of renamable) scopeIndexByRenamable.set(el, index);
+ });
+ if (scopeIndexByRenamable.size === 0) return untouched;
+
+ const idMaps = planRenames(census, scopes, scopeIndexByRenamable);
+ // A reference without a local definition keeps its original document-order target,
+ // even if that target was renamed in an ancestor or another composition.
+ const referenceMaps = resolved.map((scope, index) => {
+ const references = new Map(idMaps[index]);
+ const localIds = new Set(scope.elements.map((el) => el.getAttribute(ID_ATTR)));
+ for (const [id, elements] of census.elementsById) {
+ if (localIds.has(id)) continue;
+ const targetScope = scopeIndexByRenamable.get(elements[0]!);
+ if (targetScope === undefined) continue;
+ const mapped = idMaps[targetScope]!.get(id);
+ if (mapped) references.set(id, mapped);
+ }
+ return references;
+ });
+ referenceMaps.forEach((idMap, index) => {
+ if (idMap.size > 0) applyRenames(resolved[index]!, idMap);
+ });
+ return referenceMaps;
+}
+
+/**
+ * Whole-token `#id` replacement inside a CSS selector, generalized to many
+ * ids at once and to a literal `#newId` swap instead of an attribute-selector
+ * expansion (a plain descendant/id selector already resolves correctly once
+ * the id itself is unique — no extra scoping needed). Shares its quote- and
+ * bracket-aware scan with `compositionScoping.ts`'s
+ * `replaceAuthoredRootIdSelectors` via `selectorIdTokens.ts`, rather than a
+ * second copy of the same state machine. The scanner decodes CSS identifier
+ * escapes before matching, so `#fx\.1` matches the raw id `fx.1`, and the
+ * replacement is re-escaped so the emitted selector stays valid.
+ */
+function renameIdTokensInSelector(selector: string, idMap: ReadonlyMap<string, string>): string {
+ return replaceSelectorIdTokens(
+ selector,
+ [...idMap.keys()],
+ (matchedId) => `#${escapeCssIdentifier(idMap.get(matchedId)!)}`,
+ );
+}
+
+/**
+ * Apply the same id substitution `namespaceCollidingSvgIds` computed to a
+ * composition's `<style>` text.
+ *
+ * `<style>` content is extracted from the DOM and carried around as a raw
+ * string by the inline pipeline (see `inlineSubCompositions`'s
+ * `scopeSubStyle`), so it is never visited by the attribute walk. Both a bare
+ * `#id` selector (`#clip rect { fill: red }`, already scoped to the right
+ * instance by #556's composition-box prefix, but still naming the PRE-rename
+ * id) and a `url(#id)` declaration value need rewriting here, or a
+ * same-composition stylesheet rule silently stops matching the element whose
+ * id this module just changed.
+ */
+export function rewriteSvgIdReferencesInCss(
+ css: string,
+ idMap: ReadonlyMap<string, string>,
+): string {
+ if (!css || idMap.size === 0) return css;
+ if (!css.includes("#") && !css.toLowerCase().includes("url(")) return css;
+
+ let root: postcss.Root;
+ try {
+ root = postcss.parse(css);
+ } catch {
+ // Unparseable CSS is the caller's problem to report; leaving it untouched
+ // is strictly better than dropping the whole stylesheet here.
+ return css;
+ }
+ let mutated = false;
+
+ root.walkRules((rule) => {
+ const rewritten = rule.selectors.map((selector) => renameIdTokensInSelector(selector, idMap));
+ if (rewritten.some((selector, index) => selector !== rule.selectors[index])) {
+ rule.selectors = rewritten;
+ mutated = true;
+ }
+ });
+ root.walkDecls((decl) => {
+ const rewritten = rewriteUrlHashRefs(decl.value, idMap);
+ if (rewritten !== decl.value) {
+ decl.value = rewritten;
+ mutated = true;
+ }
+ });
+ root.walkAtRules((atRule) => {
+ if (!atRule.params) return;
+ const rewritten = rewriteUrlHashRefs(atRule.params, idMap);
+ if (rewritten !== atRule.params) {
+ atRule.params = rewritten;
+ mutated = true;
+ }
+ });
+
+ return mutated ? root.toResult({ map: false }).css : css;
+}