Skip to content

Write HTML. Render video. Built for agents.

fix(lint): check passes valid sub-compositions and scene-relative asset paths (#5337)

Miguel Ángel5ec2dd2e121f
diff --git a/packages/cli/src/server/studioServer.ts b/packages/cli/src/server/studioServer.ts
index ee293d316e..47e4567476 100644
--- a/packages/cli/src/server/studioServer.ts
+++ b/packages/cli/src/server/studioServer.ts
@@ -534,7 +534,7 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
if (resolve(dir) === resolve(projectDir)) cachedProjectSignature = null;
},
- async lint(html: string, opts?: { filePath?: string; isSubComposition?: boolean }) {
+ async lint(html, opts) {
const { lintHyperframeHtml } = await import("@hyperframes/lint");
return await lintHyperframeHtml(html, { ...opts, host: "studio" });
},
diff --git a/packages/lint/src/browser.test.ts b/packages/lint/src/browser.test.ts
index 3f52c219f9..f038db0355 100644
--- a/packages/lint/src/browser.test.ts
+++ b/packages/lint/src/browser.test.ts
@@ -1,9 +1,23 @@
+import { existsSync, readFileSync } from "node:fs";
+import { builtinModules } from "node:module";
+import { dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import { lintHyperframeHtml, shouldBlockRender } from "./browser.js";
// Guards that @hyperframes/lint/browser exposes a working, node-free rule engine.
// (The platform:"browser" tsup build is the compile-time node-free guarantee;
// this verifies the API actually runs.)
+const IMPORT_SPECIFIER =
+ /^(?:import|export)\s[^"';]*?\bfrom\s+["']([^"']+)["']|^import\s+["']([^"']+)["']|\bimport\(\s*["']([^"']+)["']\s*\)/gm;
+
+const isNodeBuiltin = (spec: string) => spec.startsWith("node:") || builtinModules.includes(spec);
+
+const resolveSource = (path: string): string => {
+ const base = path.replace(/\.js$/, "");
+ return [`${base}.ts`, `${base}/index.ts`].find((candidate) => existsSync(candidate)) ?? path;
+};
+
describe("@hyperframes/lint/browser", () => {
it("lints an HTML string with no filesystem access", async () => {
const html = `<html><body>
@@ -14,6 +28,31 @@ describe("@hyperframes/lint/browser", () => {
expect(Array.isArray(result.findings)).toBe(true);
});
+ it("reaches no node: module, including through @hyperframes/parsers", () => {
+ const parsersDir = resolve(fileURLToPath(import.meta.url), "../../../parsers");
+ const parsersExports = JSON.parse(readFileSync(`${parsersDir}/package.json`, "utf8")).exports;
+ const seen = new Set<string>();
+ const nodeImports: string[] = [];
+ const importedFile = (file: string, spec: string): string | null => {
+ if (spec.startsWith(".")) return resolveSource(resolve(dirname(file), spec));
+ if (!spec.startsWith("@hyperframes/parsers")) return null;
+ return resolve(parsersDir, parsersExports[spec.replace("@hyperframes/parsers", ".")].bun);
+ };
+ const visit = (file: string) => {
+ if (seen.has(file)) return;
+ seen.add(file);
+ for (const [, from, bare, dynamic] of readFileSync(file, "utf8").matchAll(IMPORT_SPECIFIER)) {
+ const spec = from ?? bare ?? dynamic ?? "";
+ if (isNodeBuiltin(spec)) nodeImports.push(`${file}: ${spec}`);
+ const next = importedFile(file, spec);
+ if (next) visit(next);
+ }
+ };
+ visit(resolve(fileURLToPath(import.meta.url), "../browser.ts"));
+ expect(seen.size).toBeGreaterThan(10);
+ expect(nodeImports).toEqual([]);
+ });
+
it("exposes the pure shouldBlockRender gate", () => {
expect(shouldBlockRender(true, false, 1, 0)).toBe(true);
expect(shouldBlockRender(true, false, 0, 3)).toBe(false);
diff --git a/packages/lint/src/context.ts b/packages/lint/src/context.ts
index a8a4e559d3..c01fbadd59 100644
--- a/packages/lint/src/context.ts
+++ b/packages/lint/src/context.ts
@@ -61,6 +61,7 @@ export function buildLintContext(html: string, options: HyperframeLinterOptions
raw: style.content,
index: -1,
file: style.file ?? style.href,
+ rootRelativePath: style.rootRelativePath,
})),
];
const scripts = structure.scripts;
diff --git a/packages/lint/src/project.test.ts b/packages/lint/src/project.test.ts
index 5080dbc137..438c272ffa 100644
--- a/packages/lint/src/project.test.ts
+++ b/packages/lint/src/project.test.ts
@@ -902,3 +902,68 @@ describe("audio-aware project rules", () => {
});
});
});
+
+describe("sub-composition files", () => {
+ const sceneFindings = async (project: string) =>
+ (await lintProject(project)).results.find((result) => result.file === "compositions/scene.html")
+ ?.result.findings ?? [];
+
+ it("resolves a scene's ../assets/ path from its own folder, as preview and render do", async () => {
+ const project = makeProject(validHtml(), {
+ "scene.html": `<template id="scene-template">
+ <div data-composition-id="scene" data-width="1920" data-height="1080">
+ <img src="../assets/logo.png" alt=""><img src="../../outside.png" alt="">
+ </div>
+</template>`,
+ });
+ mkdirSync(join(project, "assets"));
+ writeFileSync(join(project, "assets", "logo.png"), "");
+ const finding = (await sceneFindings(project)).find(
+ (f) => f.code === "invalid_parent_traversal_in_asset_path",
+ );
+ expect(finding?.message).toContain("1 asset path(s)");
+ expect(finding?.message).toContain("../../");
+ });
+
+ it("resolves a linked stylesheet's url()s from the stylesheet's own folder", async () => {
+ const project = makeProject(
+ validHtml().replace(
+ "<body>",
+ '<head><link rel="stylesheet" href="styles/main.css"></head><body>',
+ ),
+ {
+ "scene.html": `<template id="scene-template">
+ <link rel="stylesheet" href="../styles/escape.css">
+ <div data-composition-id="scene" data-width="1920" data-height="1080"></div>
+</template>`,
+ },
+ );
+ mkdirSync(join(project, "styles"));
+ writeFileSync(
+ join(project, "styles", "main.css"),
+ "@font-face { src: url('../fonts/B.woff2'); }",
+ );
+ writeFileSync(
+ join(project, "styles", "escape.css"),
+ ".a { background: url('../../outside.png'); }",
+ );
+ const { results } = await lintProject(project);
+ const traversal = (file: string) =>
+ results
+ .find((result) => result.file === file)
+ ?.result.findings.find((f) => f.code === "invalid_parent_traversal_in_asset_path");
+ expect(traversal("index.html")).toBeUndefined();
+ expect(traversal("compositions/scene.html")?.message).toContain("../../");
+ });
+
+ it("does not stop the check over a scene without its own size", async () => {
+ const project = makeProject(validHtml(), {
+ "scene.html": `<template id="scene-template">
+ <div data-composition-id="scene"><p>Hi</p></div>
+</template>`,
+ });
+ expect((await sceneFindings(project)).map((f) => f.code)).not.toContain(
+ "root_missing_dimensions",
+ );
+ });
+});
diff --git a/packages/lint/src/project.ts b/packages/lint/src/project.ts
index 4d5eccdd48..afd4910d05 100644
--- a/packages/lint/src/project.ts
+++ b/packages/lint/src/project.ts
@@ -116,15 +116,15 @@ function collectExternalStyles(
projectDir: string,
html: string,
compSrcPath?: string,
-): Array<{ href: string; content: string; file?: string }> {
- const styles: Array<{ href: string; content: string; file?: string }> = [];
+): NonNullable<HyperframeLinterOptions["externalStyles"]> {
+ const styles: NonNullable<HyperframeLinterOptions["externalStyles"]> = [];
const { document } = parseHTML(html);
for (const { href, content, rootRelativePath } of collectLocalStylesheets(
projectDir,
document,
compSrcPath,
)) {
- styles.push({ href, content, file: join(projectDir, rootRelativePath) });
+ styles.push({ href, content, file: join(projectDir, rootRelativePath), rootRelativePath });
}
return styles;
}
@@ -193,6 +193,7 @@ export async function lintProject(
const rootResult = await lintHyperframeHtml(rootHtml, {
...hostOptions,
filePath: indexPath,
+ compSrcPath: rootFile,
externalStyles: collectExternalStyles(projectDir, rootHtml, rootCompSrcPath),
});
results.push({ file: rootFile, result: rootResult, contentHash: contentDigest(rootHtml) });
@@ -234,6 +235,7 @@ export async function lintProject(
...hostOptions,
filePath,
isSubComposition: true,
+ compSrcPath,
externalStyles: collectExternalStyles(projectDir, html, compSrcPath),
});
results.push({
diff --git a/packages/lint/src/rules/composition.test.ts b/packages/lint/src/rules/composition.test.ts
index 494f78dc68..a2c4b33d13 100644
--- a/packages/lint/src/rules/composition.test.ts
+++ b/packages/lint/src/rules/composition.test.ts
@@ -1347,65 +1347,108 @@ describe("composition rules", () => {
describe("invalid_parent_traversal_in_asset_path", () => {
const RULE_CODE = "invalid_parent_traversal_in_asset_path";
- it("errors when an <img> src uses ../capture/", async () => {
- const html = `<html><body>
- <div data-composition-id="x">
- <img src="../capture/assets/logo.svg" alt="logo">
- </div>
- </body></html>`;
- const result = await lintHyperframeHtml(html, {
- filePath: "/project/compositions/scene.html",
- });
- const finding = result.findings.find((f) => f.code === RULE_CODE);
- expect(finding).toBeDefined();
+ const lintAt = (compSrcPath: string, body: string) =>
+ lintHyperframeHtml(`<html><body><div data-composition-id="x">${body}</div></body></html>`, {
+ compSrcPath,
+ }).then((result) => result.findings.find((f) => f.code === RULE_CODE));
+
+ it("errors when the root file's <img> src climbs out of the project with ../capture/", async () => {
+ const finding = await lintAt("index.html", `<img src="../capture/assets/logo.svg" alt="">`);
expect(finding?.severity).toBe("error");
expect(finding?.message).toContain("../capture/");
});
- it("errors when a <video> src uses ../assets/ (HF#1698 shape)", async () => {
- const html = `<html><body>
- <div data-composition-id="x">
- <video src="../assets/clip.mp4" muted></video>
- </div>
- </body></html>`;
- const result = await lintHyperframeHtml(html, {
- filePath: "/project/compositions/scene.html",
- });
- const finding = result.findings.find((f) => f.code === RULE_CODE);
- expect(finding).toBeDefined();
- expect(finding?.severity).toBe("error");
- expect(finding?.message).toContain("../assets/");
+ it("accepts ../assets/ from compositions/scene.html: it resolves to the project's assets/", async () => {
+ expect(
+ await lintAt("compositions/scene.html", `<video src="../assets/clip.mp4" muted></video>`),
+ ).toBeUndefined();
});
- it("errors when a <video> src uses ../../assets/ from a nested compositions/frames/ file", async () => {
- const html = `<html><body>
- <div data-composition-id="x">
- <video src="../../assets/clip.mp4" muted></video>
- </div>
- </body></html>`;
- const result = await lintHyperframeHtml(html, {
- filePath: "/project/compositions/frames/scene.html",
- });
- const finding = result.findings.find((f) => f.code === RULE_CODE);
- expect(finding).toBeDefined();
+ it("errors when ../../assets/ from compositions/scene.html climbs out of the project", async () => {
+ const finding = await lintAt(
+ "compositions/scene.html",
+ `<video src="../../assets/clip.mp4" muted></video>`,
+ );
expect(finding?.message).toContain("../../assets/");
});
- it("errors when a <link> href uses ../fonts/", async () => {
+ it("resolves from a nested compositions/frames/ file's own folder", async () => {
+ const nested = "compositions/frames/scene.html";
+ expect(
+ await lintAt(nested, `<video src="../../assets/clip.mp4" muted></video>`),
+ ).toBeUndefined();
+ expect(await lintAt(nested, `<img src="../../../x.png" alt="">`)).toBeDefined();
+ });
+
+ it("errors on an encoded or backslashed climb out of the project", async () => {
+ const scene = "compositions/scene.html";
+ expect(await lintAt(scene, `<img src="../%2E%2e/x.png" alt="">`)).toBeDefined();
+ expect(await lintAt(scene, `<img src="../..\\x.png" alt="">`)).toBeDefined();
+ });
+
+ it("errors on a climb from the root file however its first segment is written", async () => {
+ for (const src of ["%2e%2e/x.png", "..\\x.png", "assets/../../x.png", "&#46;&#46;/x.png"]) {
+ expect(await lintAt("index.html", `<img src="${src}" alt="">`)).toBeDefined();
+ }
+ });
+
+ it("counts an absolute or ..-containing file path's folder as the project root", async () => {
+ for (const file of [
+ "/srv/project/index.html",
+ "C:\\project\\index.html",
+ "sub/../index.html",
+ ]) {
+ expect(await lintAt(file, `<img src="../x.png" alt="">`)).toBeDefined();
+ }
+ });
+
+ it("reads an encoded %2f as a separator, as render decodes it", async () => {
+ expect(
+ await lintAt("compositions/scene.html", `<img src="..%2f..%2fx.png" alt="">`),
+ ).toBeDefined();
+ });
+
+ it("never counts a file path's leading .. below the project root", async () => {
+ expect(await lintAt("../x/scene.html", `<img src="../y.png" alt="">`)).toBeUndefined();
+ });
+
+ it("ignores URLs with a scheme, absolute paths and fragments", async () => {
+ for (const src of ["https://cdn.example.com/../../x.png", "/../x.png", "#../x"]) {
+ expect(await lintAt("index.html", `<img src="${src}" alt="">`)).toBeUndefined();
+ }
+ });
+
+ it("ignores a path's query and hash", async () => {
+ expect(
+ await lintAt("compositions/scene.html", `<img src="../assets/x.png#/../../../../" alt="">`),
+ ).toBeUndefined();
+ });
+
+ it("treats a file linted without compSrcPath as the project root", async () => {
+ const { findings } = await lintHyperframeHtml(
+ `<html><body><div data-composition-id="x"><img src="../x.png" alt=""></div></body></html>`,
+ );
+ expect(findings.map((f) => f.code)).toContain(RULE_CODE);
+ });
+
+ it("errors when a path dips out of the project midway or the file path starts with ./", async () => {
+ const scene = "compositions/scene.html";
+ expect(await lintAt(scene, `<img src="../assets/../../x.png" alt="">`)).toBeDefined();
+ expect(await lintAt(`./${scene}`, `<img src="../../x.png" alt="">`)).toBeDefined();
+ });
+
+ it("errors when a <link> href climbs out of the project with ../fonts/", async () => {
const html = `<html><head>
<link rel="stylesheet" href="../fonts/brand.css">
</head><body>
<div data-composition-id="x"></div>
</body></html>`;
- const result = await lintHyperframeHtml(html, {
- filePath: "/project/compositions/scene.html",
- });
+ const result = await lintHyperframeHtml(html, { compSrcPath: "index.html" });
const finding = result.findings.find((f) => f.code === RULE_CODE);
- expect(finding).toBeDefined();
expect(finding?.message).toContain("../fonts/");
});
- it("errors when a CSS url() uses ../assets/ in a <style> block (counts all occurrences)", async () => {
+ it("errors when CSS url()s in a <style> block climb out of the project (counts all occurrences)", async () => {
const html = `<html><body>
<style>
@font-face { font-family: 'Brand'; src: url('../fonts/Brand.woff2'); }
@@ -1413,25 +1456,16 @@ describe("composition rules", () => {
</style>
<div data-composition-id="x"></div>
</body></html>`;
- const result = await lintHyperframeHtml(html, {
- filePath: "/project/compositions/scene.html",
- });
+ const result = await lintHyperframeHtml(html, { compSrcPath: "index.html" });
const finding = result.findings.find((f) => f.code === RULE_CODE);
- expect(finding).toBeDefined();
expect(finding?.message).toContain("2 asset path(s)");
});
- it("errors when an inline style url() uses ../assets/", async () => {
- const html = `<html><body>
- <div data-composition-id="x">
- <div style="background-image: url('../assets/hero.png');"></div>
- </div>
- </body></html>`;
- const result = await lintHyperframeHtml(html, {
- filePath: "/project/compositions/scene.html",
- });
- const finding = result.findings.find((f) => f.code === RULE_CODE);
- expect(finding).toBeDefined();
+ it("errors when an inline style url() climbs out of the project", async () => {
+ const finding = await lintAt(
+ "index.html",
+ `<div style="background-image: url('../assets/hero.png');"></div>`,
+ );
expect(finding?.message).toContain("../assets/");
});
diff --git a/packages/lint/src/rules/composition.ts b/packages/lint/src/rules/composition.ts
index 81d28a0907..49cd251eda 100644
--- a/packages/lint/src/rules/composition.ts
+++ b/packages/lint/src/rules/composition.ts
@@ -133,6 +133,26 @@ function extractCssUrlReferences(css: string): string[] {
return out;
}
+function folderDepth(filePath: string): number {
+ if (/^(?:[a-z]:)?[\\/]/i.test(filePath)) return 0;
+ let depth = 0;
+ for (const segment of filePath.split(/[\\/]/).slice(0, -1)) {
+ if (segment === "..") depth = Math.max(0, depth - 1);
+ else if (segment && segment !== ".") depth += 1;
+ }
+ return depth;
+}
+
+function climbsAboveRoot(fileDepth: number, path: string): boolean {
+ let depth = fileDepth;
+ for (const segment of path.split("/")) {
+ if (segment === "..") depth -= 1;
+ else if (segment && segment !== ".") depth += 1;
+ if (depth < 0) return true;
+ }
+ return false;
+}
+
// Top-level CSS selectors (comma-split) in a stylesheet, skipping at-rule headers
// (@media/@keyframes/...) and keyframe stops. Heuristic — the lint layer has no
// full CSS parser, and rules elsewhere in this file scan CSS the same way.
@@ -635,37 +655,27 @@ export const compositionRules: Array<(ctx: LintContext) => HyperframeLintFinding
return findings;
},
- // invalid_parent_traversal_in_asset_path — catches `../` traversal in src,
- // href, inline-style url(), and <style> url() asset references on
- // compositions. Sub-compositions live under compositions/ but are served
- // with the project root as their base URL, so any `../`-traversing path
- // climbs above the project root and 404s in Studio preview. Renders
- // tolerate it because the server-side bundler rewrites `../foo` against
- // each sub-composition's source path; the runtime now mirrors that fallback
- // (see rewriteSubCompositionAssetPaths in runtime/compositionLoader.ts), but
- // the authoring-time signal is still wrong — flag it at lint time so the
- // baked path is plain root-relative and matches what the bundler emits.
- //
- // Mirrors the runtime fallback's surface: `[src]` / `[href]` attribute
- // values, `[style]` inline url(), and `<style>` block url() references.
- // Skips absolute URLs (http(s)://, //, data:, /-prefixed root-relative),
- // hash anchors, and plain relative paths (`assets/x.mp4`) — only `../`
- // traversal is flagged. Subsumes the older `../capture/`-specific rule.
+ // invalid_parent_traversal_in_asset_path — a `../` path in src, href or a CSS url() that leaves
+ // the project once resolved from the file's own folder, as the bundler, producer and runtime
+ // resolve it. "../assets/x" from compositions/ stays inside and passes.
// fallow-ignore-next-line complexity
({ tags, styles, rawSource, options }) => {
if (isRegistrySourceFile(options.filePath) || isRegistryInstalledFile(rawSource)) return [];
const offenders: string[] = [];
- const collect = (value: string | null) => {
- if (!value) return;
- const trimmed = value.trim();
- if (!trimmed.startsWith("../") && trimmed !== "..") return;
- offenders.push(trimmed);
+ const fileDepth = folderDepth(options.compSrcPath ?? "index.html");
+ const collect = (value: string | null, depth = fileDepth) => {
+ const trimmed = value?.trim() ?? "";
+ if (/^(?:[a-z][a-z0-9+.-]*:|[\\/#])/i.test(trimmed)) return;
+ const path = (trimmed.split(/[?#]/, 1)[0] ?? "")
+ .replace(/\\|%2f/gi, "/")
+ .replace(/%2e/gi, ".");
+ if (climbsAboveRoot(depth, path)) offenders.push(trimmed);
};
for (const tag of tags) {
- collect(readAttr(tag.raw, "src"));
- collect(readAttr(tag.raw, "href"));
+ collect(readDecodedAttr(tag.raw, "src"));
+ collect(readDecodedAttr(tag.raw, "href"));
// Use readJsonAttr for `style` — inline url('...') values contain the
// opposite quote, which readAttr's [^"']+ class would truncate.
const styleAttr = readJsonAttr(tag.raw, "style");
@@ -674,7 +684,8 @@ export const compositionRules: Array<(ctx: LintContext) => HyperframeLintFinding
}
}
for (const style of styles) {
- for (const url of extractCssUrlReferences(style.content)) collect(url);
+ const depth = style.rootRelativePath ? folderDepth(style.rootRelativePath) : fileDepth;
+ for (const url of extractCssUrlReferences(style.content)) collect(url, depth);
}
if (offenders.length === 0) return [];
@@ -697,9 +708,9 @@ export const compositionRules: Array<(ctx: LintContext) => HyperframeLintFinding
severity: "error",
message:
`Found ${offenders.length} asset path(s) traversing above the project root with "../" ` +
- `(${prefixSummary}). Renders rewrite this against each sub-composition's source path, but Studio preview and other live consumers resolve against the project root and 404.`,
+ `(${prefixSummary}), resolved from the folder of the file that holds them. Render and preview clamp them to the project root or resolve them outside it, so they load a different file than written, or none.`,
fixHint:
- 'Use plain root-relative paths (e.g. "assets/...", "capture/...", "fonts/...") — compositions are served with the project root as their base URL, so paths must be root-relative, not relative to the compositions/ directory.',
+ 'Point the path at a file inside the project: from compositions/scene.html, "../assets/x.png" and "assets/x.png" both reach the project\'s assets folder.',
},
];
},
diff --git a/packages/lint/src/rules/core.test.ts b/packages/lint/src/rules/core.test.ts
index 0a3634e670..31e2445cf1 100644
--- a/packages/lint/src/rules/core.test.ts
+++ b/packages/lint/src/rules/core.test.ts
@@ -426,6 +426,26 @@ describe("core rules", () => {
expect(result.findings.find((f) => f.code === "root_missing_dimensions")).toBeUndefined();
});
+ it("does not ask a sub-composition for its own size: a mounted one fills its host", async () => {
+ const html = `<template id="scene-template">
+ <div id="scene" data-composition-id="scene"><p>Hi</p></div>
+</template>`;
+ const result = await lintHyperframeHtml(html, { isSubComposition: true });
+ expect(result.findings.find((f) => f.code === "root_missing_dimensions")).toBeUndefined();
+ expect(result.findings.find((f) => f.code === "root_missing_composition_id")).toBeUndefined();
+ });
+
+ it("finds a sub-composition's root inside <template> when <html> carries its variables", async () => {
+ const html = `<html lang="en" data-composition-variables='[{"id":"title","type":"string","label":"Title","default":"Hi"}]'>
+<template id="scene-template">
+ <div id="scene" data-composition-id="scene" data-width="1280" data-height="720"></div>
+</template>
+</html>`;
+ const result = await lintHyperframeHtml(html, { isSubComposition: true });
+ expect(result.findings.find((f) => f.code === "root_missing_composition_id")).toBeUndefined();
+ expect(result.findings.find((f) => f.code === "root_missing_dimensions")).toBeUndefined();
+ });
+
it("still treats an <svg> as the root when it carries composition markers itself", async () => {
const html = `
<html><body>
diff --git a/packages/lint/src/rules/core.ts b/packages/lint/src/rules/core.ts
index cc21a75f01..09c6c19e50 100644
--- a/packages/lint/src/rules/core.ts
+++ b/packages/lint/src/rules/core.ts
@@ -490,7 +490,7 @@ export const coreRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [
// root_missing_composition_id + root_missing_dimensions
// fallow-ignore-next-line complexity
- ({ rootTag }) => {
+ ({ rootTag, options }) => {
const findings: HyperframeLintFinding[] = [];
if (!rootTag || !readDecodedAttr(rootTag.raw, "data-composition-id")) {
findings.push({
@@ -502,7 +502,10 @@ export const coreRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [
snippet: truncateSnippet(rootTag?.raw || ""),
});
}
- if (!rootTag || !readAttr(rootTag.raw, "data-width") || !readAttr(rootTag.raw, "data-height")) {
+ if (
+ !options.isSubComposition &&
+ (!rootTag || !readAttr(rootTag.raw, "data-width") || !readAttr(rootTag.raw, "data-height"))
+ ) {
findings.push({
code: "root_missing_dimensions",
severity: "error",
diff --git a/packages/lint/src/types.ts b/packages/lint/src/types.ts
index b5dcaee16a..21c39e99fc 100644
--- a/packages/lint/src/types.ts
+++ b/packages/lint/src/types.ts
@@ -40,7 +40,13 @@ export type HyperframeLintResult = {
export type HyperframeLinterOptions = {
filePath?: string;
isSubComposition?: boolean;
- externalStyles?: Array<{ href: string; content: string; file?: string }>;
+ compSrcPath?: string;
+ externalStyles?: Array<{
+ href: string;
+ content: string;
+ file?: string;
+ rootRelativePath?: string;
+ }>;
/**
* Set to `true` when linting compositions destined for distributed / Lambda
* rendering, where system-font capture (`allowSystemFontCapture`) is
diff --git a/packages/lint/src/utils.ts b/packages/lint/src/utils.ts
index b27fccba1a..dc274a4cf4 100644
--- a/packages/lint/src/utils.ts
+++ b/packages/lint/src/utils.ts
@@ -16,6 +16,7 @@ export type OpenTag = {
export type ExtractedBlock = {
contentStart?: number;
file?: string;
+ rootRelativePath?: string;
attrs: string;
content: string;
raw: string;
@@ -147,18 +148,18 @@ export function findHtmlTag(tags: readonly OpenTag[]): OpenTag | null {
return tags.find((tag) => tag.name === "html") ?? null;
}
+const hasCompositionMarker = (tag: OpenTag): boolean =>
+ Boolean(
+ readDecodedAttr(tag.raw, "data-composition-id") ||
+ readAttr(tag.raw, "data-width") ||
+ readAttr(tag.raw, "data-height"),
+ );
+
// fallow-ignore-next-line complexity
export function findRootTag(source: string, parsedTags?: readonly OpenTag[]): OpenTag | null {
const tags = parsedTags ?? parseHtmlStructure(source).tags;
const bodyTag = tags.find((tag) => tag.name === "body");
- if (
- bodyTag &&
- (readDecodedAttr(bodyTag.raw, "data-composition-id") ||
- readAttr(bodyTag.raw, "data-width") ||
- readAttr(bodyTag.raw, "data-height"))
- ) {
- return bodyTag;
- }
+ if (bodyTag && hasCompositionMarker(bodyTag)) return bodyTag;
const bodyStart = bodyTag ? bodyTag.index + bodyTag.raw.length : 0;
const bodyEnd = bodyTag?.closeIndex ?? source.length;
const bodyTags = tags.filter((tag) => tag.index >= bodyStart && tag.index < bodyEnd);
@@ -170,6 +171,7 @@ export function findRootTag(source: string, parsedTags?: readonly OpenTag[]): Op
for (const tag of bodyTags) {
if (tag.index < skipBefore) continue;
if (["script", "style", "meta", "link", "title"].includes(tag.name)) continue;
+ if ((tag.name === "html" || tag.name === "head") && !hasCompositionMarker(tag)) continue;
// A leading <svg> block (icon/gradient/filter <defs>, referenced by url(#id)
// from elsewhere in the document) is shared visual plumbing, not the
// composition root — two independent reports of this being mistaken for
@@ -178,12 +180,7 @@ export function findRootTag(source: string, parsedTags?: readonly OpenTag[]): Op
// the composition markers itself, so an intentionally SVG-rooted composition
// (data-composition-id/data-width/data-height directly on the <svg>) is
// still eligible as the root.
- if (
- tag.name === "svg" &&
- !readDecodedAttr(tag.raw, "data-composition-id") &&
- !readAttr(tag.raw, "data-width") &&
- !readAttr(tag.raw, "data-height")
- ) {
+ if (tag.name === "svg" && !hasCompositionMarker(tag)) {
// No closing tag found (malformed HTML) — skip everything rather than
// risk returning one of the svg's own children as the root.
skipBefore = tag.endIndex ?? Infinity;
diff --git a/packages/parsers/src/rewriteSubCompPaths.test.ts b/packages/parsers/src/rewriteSubCompPaths.test.ts
index 69c8cc53b5..3dab235942 100644
--- a/packages/parsers/src/rewriteSubCompPaths.test.ts
+++ b/packages/parsers/src/rewriteSubCompPaths.test.ts
@@ -30,6 +30,18 @@ describe("rewriteAssetPath", () => {
expect(rewriteAssetPath("compositions/scene.html", "../icon.svg")).toBe("icon.svg");
});
+ it("rewrites a backslash-separated `..\\` path like its slash form", () => {
+ expect(rewriteAssetPath("compositions/scene.html", "..\\assets\\x.png")).toBe("assets/x.png");
+ });
+
+ it("keeps an encoded backslash in the name and a leading backslash absolute, as browsers do", () => {
+ const exists = () => true;
+ expect(rewriteAssetPath("compositions/scene.html", "a%5Cb.png", exists)).toBe(
+ "compositions/a%5Cb.png",
+ );
+ expect(rewriteAssetPath("compositions/scene.html", "\\x.png", exists)).toBe("\\x.png");
+ });
+
it("leaves plain relative paths untouched", () => {
expect(rewriteAssetPath("compositions/scene.html", "assets/logo.png")).toBe("assets/logo.png");
});
diff --git a/packages/parsers/src/rewriteSubCompPaths.ts b/packages/parsers/src/rewriteSubCompPaths.ts
index 614d3f3239..9bb06dac0f 100644
--- a/packages/parsers/src/rewriteSubCompPaths.ts
+++ b/packages/parsers/src/rewriteSubCompPaths.ts
@@ -78,8 +78,9 @@ export function rewriteAssetPath(
const compDir = dirname(compSrcPath);
if (!compDir || compDir === ".") return relativePath;
const { basePath, suffix } = splitUrlSuffix(relativePath);
- if (!basePath) return relativePath;
- const filePath = decodeWellFormedEscapes(basePath);
+ const slashed = basePath.replace(/\\/g, "/");
+ if (!slashed || slashed.startsWith("/")) return relativePath;
+ const filePath = decodeWellFormedEscapes(slashed);
const sibling = resolve("/", join(compDir, filePath)).slice(1);
if (!needsRewrite(filePath) && (!assetExists || !assetExists(sibling))) return relativePath;
return encodeUrlPath(sibling) + suffix;
diff --git a/packages/producer/src/services/hyperframeLint.ts b/packages/producer/src/services/hyperframeLint.ts
index b316928862..fd3d9be1f2 100644
--- a/packages/producer/src/services/hyperframeLint.ts
+++ b/packages/producer/src/services/hyperframeLint.ts
@@ -154,5 +154,8 @@ export function prepareHyperframeLintBody(
export async function runHyperframeLint(
prepared: PreparedHyperframeLintInput,
): Promise<HyperframeLintResult> {
- return lintHyperframeHtml(prepared.html, { filePath: prepared.entryFile });
+ return lintHyperframeHtml(prepared.html, {
+ filePath: prepared.entryFile,
+ compSrcPath: prepared.entryFile,
+ });
}
diff --git a/packages/studio-server/src/routes/lint.test.ts b/packages/studio-server/src/routes/lint.test.ts
index e7d134aff3..07953634a1 100644
--- a/packages/studio-server/src/routes/lint.test.ts
+++ b/packages/studio-server/src/routes/lint.test.ts
@@ -142,6 +142,7 @@ describe("registerLintRoutes — dot-directory exclusion (#1384)", () => {
expect(singleFileLint).toHaveBeenCalledWith("<html><body>intro</body></html>", {
filePath: "scenes/intro.html",
isSubComposition: true,
+ compSrcPath: "scenes/intro.html",
});
expect(payload.findings).toContainEqual(
expect.objectContaining({ code: "scene_finding", file: "scenes/intro.html" }),
diff --git a/packages/studio-server/src/routes/lint.ts b/packages/studio-server/src/routes/lint.ts
index 4e1c99251e..ecc34842d5 100644
--- a/packages/studio-server/src/routes/lint.ts
+++ b/packages/studio-server/src/routes/lint.ts
@@ -34,7 +34,11 @@ async function lintUncoveredHtml(
for (const file of htmlFiles) {
if (coveredFiles.has(file)) continue;
const content = readFileSync(join(projectDir, file), "utf-8");
- const result = await adapter.lint(content, { filePath: file, isSubComposition: true });
+ const result = await adapter.lint(content, {
+ filePath: file,
+ isSubComposition: true,
+ compSrcPath: file,
+ });
for (const finding of result?.findings ?? []) {
findings.push({ ...finding, file });
}
diff --git a/packages/studio-server/src/types.ts b/packages/studio-server/src/types.ts
index 719bbc317f..8e55b2885d 100644
--- a/packages/studio-server/src/types.ts
+++ b/packages/studio-server/src/types.ts
@@ -128,7 +128,7 @@ export interface StudioApiAdapter {
/** Lint a single HTML string. */
lint(
html: string,
- opts?: { filePath?: string; isSubComposition?: boolean },
+ opts?: { filePath?: string; isSubComposition?: boolean; compSrcPath?: string },
): Promise<LintResult> | LintResult;
/**