Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/reference/lint-rules.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,12 @@ The preview slows to a crawl.
**Fix:** Let the runtime hide hidden clips; it already hides their contents.
For a state of your own, toggle a class or data attribute from your script and select on that.

### `html_read_unlike_browser`

**Error.** The file holds markup that a browser reads differently from HyperFrames' HTML reader. One example is tags or comments in a `title`, `style`, `script`, `textarea` or `xmp` inside an `<svg>` or `<math>` element. Preview, render and edit all refuse the file. Lint reports this one error for the file and lints the rest of the project. The message names what was found.

**Fix:** Keep only plain text in the element the message names, with no tags or comments.

### `invalid_inline_script_syntax`

**Error.** An inline `<script>` is closed with malformed syntax.
Expand Down
4 changes: 2 additions & 2 deletions packages/lint/src/hevcPreviewLint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
maskNonScannableRanges,
resolveExistingLocalAsset,
} from "@hyperframes/parsers/asset-resolution";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import { parseLintHtml } from "./readableHtml.js";
import type { HyperframeLintFinding } from "./types.js";
import { mediaSrcOf, mediaSrcTagRe } from "./utils";

Expand Down Expand Up @@ -150,7 +150,7 @@ interface UnresolvedFiniteVideoSlot extends Omit<LocalFiniteVideoSlot, "src"> {
}

function collectVideoElements(html: string): Element[] {
const { document } = parseHTML(html);
const { document } = parseLintHtml(html);
const roots: ParentNode[] = [document];
const videos: Element[] = [];
for (let index = 0; index < roots.length; index++) {
Expand Down
87 changes: 87 additions & 0 deletions packages/lint/src/htmlReadUnlikeBrowser.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { lintHyperframeHtml } from "./hyperframeLinter.js";
import { lintProject } from "./project.js";

const HIDDEN = "<svg><title><!-- </title><img src=x onerror=f()> --></title></svg>";
const page = (body: string) =>
`<!DOCTYPE html><html><head></head><body><div data-composition-id="main" data-width="320" data-height="180" data-start="0" data-duration="2">${body}</div></body></html>`;
const scene = (body: string) =>
`<template><div data-composition-id="scene" data-width="320" data-height="180">${body}</div></template>`;
const host = (src: string) =>
`<div data-composition-id="scene" data-composition-src="${src}" data-start="0" data-duration="1"></div>`;

const dirs: string[] = [];
afterEach(() => {
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});

function project(files: Record<string, string>): string {
const dir = mkdtempSync(join(tmpdir(), "hf-lint-refused-"));
dirs.push(dir);
for (const [path, html] of Object.entries(files)) {
mkdirSync(dirname(join(dir, path)), { recursive: true });
writeFileSync(join(dir, path), html);
}
return dir;
}

const refusalsIn = (findings: { code: string; file?: string }[]) =>
findings.filter((finding) => finding.code === "html_read_unlike_browser");

// fails without the fix: the parser's refusal escaped lint, so `hyperframes lint` failed the whole run with a
// runtime_error instead of naming the file.
describe("a file the HTML parser refuses", () => {
it("is one error finding when linted on its own", async () => {
const result = await lintHyperframeHtml(page(HIDDEN));
expect(result.ok).toBe(false);
expect(refusalsIn(result.findings)).toHaveLength(1);
expect(result.findings[0]?.message).toMatch(/can't be read the way a browser reads them/);
});

it("is a finding on the root, not a failed run", async () => {
const dir = project({ "index.html": page(HIDDEN) });
const { results, totalErrors } = await lintProject(dir);
expect(refusalsIn(results[0]!.result.findings)).toHaveLength(1);
expect(totalErrors).toBeGreaterThan(0);
});

it("is a finding on its own file while the rest of the project is still linted", async () => {
const dir = project({
"index.html": page(host("compositions/scene.html")),
"compositions/scene.html": scene(HIDDEN),
});
const { results } = await lintProject(dir);
const sceneResult = results.find((entry) => entry.file === "compositions/scene.html");
expect(refusalsIn(sceneResult!.result.findings)).toHaveLength(1);
expect(refusalsIn(results[0]!.result.findings)).toHaveLength(0);
});

it("leaves the report whole when the mounted file's name is URL-encoded", async () => {
const dir = project({
"index.html": page(
`${host("scenes/my%20scene.html")}<audio src="missing.mp3" data-start="0"></audio>`,
),
"scenes/my scene.html": scene(HIDDEN),
});
const { results } = await lintProject(dir);
const codes = results.flatMap((entry) => entry.result.findings.map((finding) => finding.code));
expect(codes).toContain("audio_src_not_found");
});

it("is named when a scene outside compositions/ mounts it", async () => {
const dir = project({
"index.html": page(host("scenes/scene.html")),
"scenes/scene.html": scene(HIDDEN),
});
const { results } = await lintProject(dir);
const messages = results.flatMap((entry) =>
entry.result.findings.map((finding) => finding.message),
);
expect(messages.join("\n")).toMatch(
/scenes\/scene\.html[\s\S]*can't be read the way a browser reads them/,
);
});
});
18 changes: 18 additions & 0 deletions packages/lint/src/hyperframeLinter.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { htmlReadUnlikeBrowserFinding } from "./readableHtml.js";
import type {
HyperframeLintFinding,
HyperframeLintResult,
Expand Down Expand Up @@ -135,6 +136,23 @@ export async function lintHyperframeHtml(
options: HyperframeLinterOptions = {},
): Promise<HyperframeLintResult> {
const startedAt = performance.now();
const refusal = htmlReadUnlikeBrowserFinding(html);
if (refusal) {
const finding = options.filePath ? { ...refusal, file: options.filePath } : refusal;
return {
ok: false,
errorCount: 1,
warningCount: 0,
infoCount: 0,
findings: [finding],
timings: {
totalMs: performance.now() - startedAt,
groupMs: {},
slowestRule: "",
slowestRuleMs: 0,
},
};
}
const ctx = buildLintContext(html, options);
const { findings: rawFindings, timings } = await runRules(ctx, options.filePath);
const locate = createSourceLocator(html);
Expand Down
31 changes: 17 additions & 14 deletions packages/lint/src/project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import {
checkSubCompositionUsability,
templateContent,
} from "@hyperframes/parsers/sub-composition-validity";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import { htmlReadUnlikeBrowserFinding, parseLintHtml } from "./readableHtml.js";
import postcss from "postcss";
import {
cleanAssetUrl,
Expand Down Expand Up @@ -65,9 +65,9 @@ import type {
import type { ParsableDocumentLike } from "@hyperframes/parsers/sub-composition-validity";
import { isAudibleVideo, isAudibleVideoTag, mediaSrcOf, mediaSrcTagRe } from "./utils";

/** Adapts linkedom's `parseHTML` to the `checkSubCompositionUsability` contract. */
/** Adapts `parseLintHtml` to the `checkSubCompositionUsability` contract. */
function parseSubCompHtml(html: string): ParsableDocumentLike {
return parseHTML(html).document as unknown as ParsableDocumentLike;
return parseLintHtml(html).document as unknown as ParsableDocumentLike;
}

/** The file a source was read from, as per-file findings carry it. */
Expand Down Expand Up @@ -212,7 +212,7 @@ function collectExternalStyles(
reader: LinkedFileReader,
): NonNullable<HyperframeLinterOptions["externalStyles"]> {
const styles: NonNullable<HyperframeLinterOptions["externalStyles"]> = [];
const { document } = parseHTML(html);
const { document } = parseLintHtml(html);
for (const { href, content, rootRelativePath } of collectLocalStylesheets(
projectDir,
document,
Expand Down Expand Up @@ -254,7 +254,7 @@ function collectExternalScripts(
): Pick<HyperframeLinterOptions, "externalScripts" | "scriptsOutsideProjectUnread"> {
const scripts: NonNullable<HyperframeLinterOptions["externalScripts"]> = [];
const scriptsOutsideProjectUnread: string[] = [];
const { document } = parseHTML(html);
const { document } = parseLintHtml(html);
for (const element of querySelectorAllIncludingTemplates(document, "script[src]")) {
const src = element.getAttribute("src") ?? "";
if (!isLocalStylesheetHref(src) || /\.min\.m?js(?:[?#]|$)/i.test(src)) continue;
Expand Down Expand Up @@ -294,7 +294,7 @@ function collectExternalScripts(

function collectCssSources(projectDir: string, html: string, compSrcPath?: string): CssSource[] {
const sources: CssSource[] = [];
const { document } = parseHTML(html);
const { document } = parseLintHtml(html);

for (const style of querySelectorAllIncludingTemplates(document, "style")) {
sources.push({ content: style.textContent ?? "" });
Expand Down Expand Up @@ -347,7 +347,7 @@ function mountedSources(
const sources: HtmlSource[] = [{ html: rootHtml, compSrcPath: rootCompSrcPath }];
const seen = new Set<string>();
for (const source of sources) {
const { document } = parseHTML(source.html);
const { document } = parseLintHtml(source.html);
for (const host of querySelectorAllIncludingTemplates(document, "[data-composition-src]")) {
const src = host.getAttribute("data-composition-src")?.trim();
if (!src || longerThanAnyPath(src)) continue;
Expand All @@ -369,7 +369,7 @@ function mountedSources(
function declaredProjectFontFamilies(projectDir: string, sources: HtmlSource[]): string[] {
const families = new Set<string>();
for (const { html, compSrcPath } of sources) {
const { document } = parseHTML(html);
const { document } = parseLintHtml(html);
const styles = [
...querySelectorAllIncludingTemplates(document, "style").map((style) => ({
content: style.textContent ?? "",
Expand Down Expand Up @@ -518,7 +518,7 @@ function lintBlankRootWithStandaloneComposition(
rootHtml: string,
htmlSources: HtmlSource[],
): HyperframeLintFinding[] {
const { document: rootDocument } = parseHTML(rootHtml);
const { document: rootDocument } = parseLintHtml(rootHtml);
const root = rootDocument.querySelector("body [data-composition-id]");
// A no-media scaffold has no rendered descendants and can silently mask an authored file below.
// A scaffold that retained its A-roll <video>/<audio> is visibly non-blank, so this rule leaves it
Expand All @@ -530,7 +530,7 @@ function lintBlankRootWithStandaloneComposition(
const standaloneCandidates: string[] = [];
for (const source of htmlSources) {
if (!source.compSrcPath) continue;
const { document } = parseHTML(source.html);
const { document } = parseLintHtml(source.html);
const composition = document.querySelector("body [data-composition-id]");
if (!composition) continue;
const authoredTimedContent = Array.from(
Expand Down Expand Up @@ -814,7 +814,7 @@ function lintLinkedStylesheetAssets(
for (const { html, compSrcPath } of htmlSources) {
for (const { content, rootRelativePath } of collectLocalStylesheets(
projectDir,
parseHTML(html).document,
parseLintHtml(html).document,
compSrcPath,
)) {
let root: postcss.Root;
Expand Down Expand Up @@ -910,7 +910,7 @@ function collectMainTimelineAudio(projectDir: string, rootHtml: string): AudioSp
const spans: AudioSpan[] = [];
type Placement = { file: TimingFile; origin: number; slots: HostSlot[]; mounting: string[] };
const mount = (html: string, at: Omit<Placement, "file">) => {
const { document } = parseHTML(html);
const { document } = parseLintHtml(html);
const root = querySelectorAllIncludingTemplates(document, "[data-composition-id]")[0];
if (root) visit(root, { ...at, file: timingFile(document) });
};
Expand Down Expand Up @@ -940,7 +940,7 @@ function collectMainTimelineAudio(projectDir: string, rootHtml: string): AudioSp
visit(el, inner);
}
};
const { document } = parseHTML(rootHtml);
const { document } = parseLintHtml(rootHtml);
visit(document, { file: timingFile(document), origin: 0, slots: [], mounting: [] });
return spans;
}
Expand Down Expand Up @@ -1089,7 +1089,10 @@ function lintMissingOrEmptySubComposition(
}

const fileHtml = read.text;
const validity = checkSubCompositionUsability(fileHtml, parseSubCompHtml);
const refusal = htmlReadUnlikeBrowserFinding(fileHtml);
const validity = refusal
? { ok: false, detail: `the parser refuses it. ${refusal.message.replace(/\.$/, "")}` }
: checkSubCompositionUsability(fileHtml, parseSubCompHtml);
if (!validity.ok) {
if (!checked.has(srcPath)) {
checked.set(srcPath, {
Expand Down
28 changes: 28 additions & 0 deletions packages/lint/src/readableHtml.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { HtmlReadUnlikeBrowserError, parseHTML } from "@hyperframes/parsers/linkedom";
import type { HyperframeLintFinding } from "./types.js";

export function htmlReadUnlikeBrowserFinding(html: string): HyperframeLintFinding | null {
try {
parseHTML(html);
return null;
} catch (error) {
if (!(error instanceof HtmlReadUnlikeBrowserError)) throw error;
return {
code: "html_read_unlike_browser",
severity: "error",
message: error.message,
fixHint:
"Take the tags or comments out of the element the message names. Preview and render refuse this file until then.",
};
}
}

/** Reads a file the parser refuses as empty: its own html_read_unlike_browser finding reports it. */
export function parseLintHtml(html: string): ReturnType<typeof parseHTML> {
try {
return parseHTML(html);
} catch (error) {
if (error instanceof HtmlReadUnlikeBrowserError) return parseHTML("");
throw error;
}
}
Loading