Skip to content

Commit 051336c

Browse files
authored
fix(lint): stop three rules matching code a composition only displays (#2811)
A code-explainer composition renders selectors and API calls as text. `stripJsStringLiterals` blanks string and template contents (offsets preserved) so `composition_id_selector_in_comment`, `template_literal_selector` and `raf_animation_loop` scan real code only. The scanner tracks regex-vs-division context so a regex literal's own quotes cannot open a phantom string and blank the rest of the script; on any unbalanced scan it returns the source unchanged, so an unmodelled parse degrades to the pre-existing behaviour rather than blanking code on an error-severity gate.
1 parent 39ad272 commit 051336c

4 files changed

Lines changed: 584 additions & 9 deletions

File tree

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

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -474,6 +474,94 @@ describe("composition rules", () => {
474474
expect(findings[0]?.fixHint).toContain('[data-composition-id="scene"][data-start="0"]');
475475
});
476476

477+
it("keeps reporting a missing duration source when the same script defeats the lexer", async () => {
478+
const html = `
479+
<!DOCTYPE html>
480+
<html><body>
481+
<div data-composition-id="main" data-width="1920" data-height="1080"></div>
482+
<script>
483+
var of = 2; var r = of /2;
484+
// window.__timelines["main"] = gsap.timeline({ paused: true });
485+
</script>
486+
</body></html>`;
487+
const result = await lintHyperframeHtml(html, { filePath: "compositions/main.html" });
488+
const findings = result.findings.filter(
489+
(f) => f.code === "root_composition_missing_duration_source",
490+
);
491+
expect(findings.length).toBe(1);
492+
expect(findings[0]?.severity).toBe("error");
493+
});
494+
495+
it("reports a split data-attribute selector that lives only in a script string literal", async () => {
496+
const html = `
497+
<!DOCTYPE html>
498+
<html><body>
499+
<div data-composition-id="main" data-width="1920" data-height="1080"></div>
500+
<script>
501+
window.__timelines = window.__timelines || {};
502+
document.querySelector('[data-composition-id="main" data-start="0"]');
503+
window.__timelines["main"] = gsap.timeline({ paused: true });
504+
</script>
505+
</body></html>`;
506+
const result = await lintHyperframeHtml(html, { filePath: "compositions/main.html" });
507+
const findings = result.findings.filter((f) => f.code === "split_data_attribute_selector");
508+
expect(findings.length).toBe(1);
509+
expect(findings[0]?.severity).toBe("error");
510+
});
511+
512+
it("does not report a template-literal selector that only appears in a comment or a string", async () => {
513+
const html = `
514+
<html><body>
515+
<div data-composition-id="main" data-width="1920" data-height="1080"><code id="snippet"></code></div>
516+
<script>
517+
window.__timelines = window.__timelines || {};
518+
// Hardcoded on purpose — do NOT use document.querySelector(\`#\${id}\`) here.
519+
const SAMPLE = 'document.querySelector(\`[data-composition-id="\${compId}"]\`)';
520+
document.getElementById("snippet").textContent = SAMPLE;
521+
window.__timelines["main"] = gsap.timeline({ paused: true });
522+
</script>
523+
</body></html>`;
524+
const result = await lintHyperframeHtml(html);
525+
expect(result.findings.find((f) => f.code === "template_literal_selector")).toBeUndefined();
526+
});
527+
528+
it("reports a template-literal selector in code position and quotes the real source", async () => {
529+
const html = `
530+
<html><body>
531+
<div data-composition-id="main" data-width="1920" data-height="1080"></div>
532+
<script>
533+
window.__timelines = window.__timelines || {};
534+
const compId = "main";
535+
const el = document.querySelector(\`[data-composition-id="\${compId}"]\`);
536+
window.__timelines["main"] = gsap.timeline({ paused: true });
537+
</script>
538+
</body></html>`;
539+
const result = await lintHyperframeHtml(html);
540+
const finding = result.findings.find((f) => f.code === "template_literal_selector");
541+
expect(finding?.severity).toBe("error");
542+
expect(finding?.snippet).toContain("data-composition-id");
543+
});
544+
545+
it("does not report a split data-attribute selector written inside a CSS comment", async () => {
546+
const html = `
547+
<html><body>
548+
<div data-composition-id="main" data-width="1920" data-height="1080"></div>
549+
<style>
550+
/* never write [data-composition-id="main" data-start="0"] — split the brackets */
551+
#root { background: #111; }
552+
</style>
553+
<script>
554+
window.__timelines = window.__timelines || {};
555+
// and not [data-composition-id="main" data-start="0"] in a JS comment either
556+
window.__timelines["main"] = gsap.timeline({ paused: true });
557+
</script>
558+
</body></html>`;
559+
const result = await lintHyperframeHtml(html);
560+
expect(result.findings.filter((f) => f.code === "split_data_attribute_selector")).toHaveLength(
561+
0,
562+
);
563+
});
564+
477565
describe("timed_element_missing_clip_class", () => {
478566
it("flags element with data-start but no class='clip'", async () => {
479567
const html = `
@@ -768,6 +856,41 @@ describe("composition rules", () => {
768856
);
769857
expect(finding).toBeUndefined();
770858
});
859+
860+
it("does not flag a call the composition only renders as on-screen text", async () => {
861+
const html = `
862+
<html><body>
863+
<div data-composition-id="c1" data-width="1920" data-height="1080"><code id="snippet"></code></div>
864+
<script>
865+
window.__timelines = window.__timelines || {};
866+
const fn = "step";
867+
document.getElementById("snippet").textContent = "requestAnimationFrame(step);";
868+
document.getElementById("snippet").title = \`requestAnimationFrame(\${fn});\`;
869+
window.__timelines["c1"] = gsap.timeline({ paused: true });
870+
</script>
871+
</body></html>`;
872+
const result = await lintHyperframeHtml(html);
873+
expect(
874+
result.findings.find((f) => f.code === "requestanimationframe_in_composition"),
875+
).toBeUndefined();
876+
});
877+
878+
it("still flags a call inside a template interpolation, which is code", async () => {
879+
const html = `
880+
<html><body>
881+
<div data-composition-id="c1" data-width="1920" data-height="1080"><code id="snippet"></code></div>
882+
<script>
883+
window.__timelines = window.__timelines || {};
884+
const label = \`frame \${requestAnimationFrame(() => {})}\`;
885+
document.getElementById("snippet").textContent = label;
886+
window.__timelines["c1"] = gsap.timeline({ paused: true });
887+
</script>
888+
</body></html>`;
889+
const result = await lintHyperframeHtml(html);
890+
expect(
891+
result.findings.find((f) => f.code === "requestanimationframe_in_composition")?.severity,
892+
).toBe("error");
893+
});
771894
});
772895

773896
describe("missing_data_no_timeline", () => {

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

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@ import {
44
readAttr,
55
readDecodedAttr,
66
readJsonAttr,
7+
stripCssComments,
78
stripJsComments,
9+
stripJsCode,
810
truncateSnippet,
911
WINDOW_TIMELINE_ASSIGN_PATTERN,
1012
} from "../utils";
@@ -487,8 +489,8 @@ export const compositionRules: Array<(ctx: LintContext) => HyperframeLintFinding
487489
});
488490
}
489491
};
490-
for (const style of styles) scan(style.content);
491-
for (const script of scripts) scan(script.content);
492+
for (const style of styles) scan(stripCssComments(style.content));
493+
for (const script of scripts) scan(stripJsComments(script.content));
492494
return findings;
493495
},
494496

@@ -498,8 +500,9 @@ export const compositionRules: Array<(ctx: LintContext) => HyperframeLintFinding
498500
for (const script of scripts) {
499501
const templateLiteralSelectorPattern =
500502
/(?:querySelector|querySelectorAll)\s*\(\s*`[^`]*\$\{[^}]+\}[^`]*`\s*\)/g;
503+
const scanned = stripJsCode(script.content);
501504
let tlMatch: RegExpExecArray | null;
502-
while ((tlMatch = templateLiteralSelectorPattern.exec(script.content)) !== null) {
505+
while ((tlMatch = templateLiteralSelectorPattern.exec(scanned)) !== null) {
503506
findings.push({
504507
code: "template_literal_selector",
505508
severity: "error",
@@ -508,7 +511,9 @@ export const compositionRules: Array<(ctx: LintContext) => HyperframeLintFinding
508511
"The HTML bundler's CSS parser crashes on these. Use a hardcoded string instead.",
509512
fixHint:
510513
"Replace the template literal variable with a hardcoded string. The bundler's CSS parser cannot handle interpolated variables in script content.",
511-
snippet: truncateSnippet(tlMatch[0]),
514+
snippet: truncateSnippet(
515+
script.content.slice(tlMatch.index, tlMatch.index + tlMatch[0].length),
516+
),
512517
});
513518
}
514519
}
@@ -648,7 +653,7 @@ export const compositionRules: Array<(ctx: LintContext) => HyperframeLintFinding
648653
if (isRegistrySourceFile(options.filePath) || isRegistryInstalledFile(rawSource)) return [];
649654
const findings: HyperframeLintFinding[] = [];
650655
for (const script of scripts) {
651-
const stripped = stripJsComments(script.content);
656+
const stripped = stripJsCode(script.content);
652657
if (/requestAnimationFrame\s*\(/.test(stripped)) {
653658
findings.push({
654659
code: "requestanimationframe_in_composition",

‎packages/lint/src/utils.test.ts‎

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
import { describe, it, expect } from "vitest";
2+
import { stripCssComments, stripJsComments, stripJsStringLiterals } from "./utils.js";
3+
4+
const scan = (src: string) => stripJsStringLiterals(stripJsComments(src));
5+
const findsRaf = (src: string) => /requestAnimationFrame\s*\(/.test(scan(src));
6+
7+
describe("stripJsStringLiterals", () => {
8+
it("blanks a call the composition only renders as text", () => {
9+
expect(findsRaf('const CODE = "requestAnimationFrame(step);";')).toBe(false);
10+
expect(findsRaf("const CODE = `requestAnimationFrame(${fn});`;")).toBe(false);
11+
});
12+
13+
it("keeps a call in a template interpolation, which is code", () => {
14+
expect(findsRaf("const label = `frame ${requestAnimationFrame(cb)}`;")).toBe(true);
15+
});
16+
17+
it.each([
18+
"const re = /[\"']/g;",
19+
"const re = /'/;",
20+
"const re = /[`]/;",
21+
"const r = s.split(/['\"]/);",
22+
'const r = s.replace(/[^a-z\']/g, "");',
23+
"if (a) { } /'/.test(x);",
24+
"const a = b / c / d;",
25+
"const p = i++ / total;",
26+
"const q = --i / total;",
27+
])("does not let %j blank the rest of the script", (prefix) => {
28+
expect(findsRaf(`${prefix}\nrequestAnimationFrame(step);`)).toBe(true);
29+
});
30+
31+
it.each([
32+
"function a(s) {\n let ok = flag\n return /'/.test(s)\n}\n",
33+
"for (const x of /'/.source) {}\n",
34+
])("keeps a call bracketed by two quote-bearing regexes after %j", (prefix) => {
35+
expect(findsRaf(`${prefix}requestAnimationFrame(step);\n${prefix}`)).toBe(true);
36+
});
37+
38+
it.each([
39+
"const clip = { in: 0.5, out: 5.5 }; const r = clip.in / clip.out;",
40+
"const r = data.new / 2;",
41+
"const r = list.of / 2;",
42+
"const r = sw.case / 2;",
43+
"const r = o?.in / 2;",
44+
"const p = i++ / total;",
45+
"const q = --i / total;",
46+
])("finds a call on the same line as %j", (prefix) => {
47+
expect(findsRaf(`${prefix} requestAnimationFrame(step);`)).toBe(true);
48+
});
49+
50+
it.each([
51+
"foo(/abc\nrequestAnimationFrame(step);",
52+
"var of = 2;\nvar r = of /2;\nrequestAnimationFrame(step);",
53+
"var q = 1;\nx = /a\\\nrequestAnimationFrame(step);",
54+
])("falls back to the source when a slash never closes on its line: %j", (src) => {
55+
expect(scan(src)).toBe(src);
56+
expect(findsRaf(src)).toBe(true);
57+
});
58+
59+
it("falls back to the source when a backslash ends a mis-read regex line", () => {
60+
const src = "var a = b in /x\\\n y = 'requestAnimationFrame(' / z /;";
61+
expect(scan(src)).toBe(src);
62+
expect(findsRaf(src)).toBe(true);
63+
});
64+
65+
it("falls back to the source when the scan ends mid-literal", () => {
66+
const src = 'const p = "C:\\Users\\demo\\";\nrequestAnimationFrame(step);';
67+
expect(scan(src)).toBe(src);
68+
expect(findsRaf(src)).toBe(true);
69+
});
70+
71+
it("preserves length and newline positions", () => {
72+
for (const src of [
73+
'const a = "x\\\ny";\nrequestAnimationFrame(step);',
74+
"const t = `a\nb${x}c\nd`;",
75+
"const r = /a\\/b/g;\n",
76+
]) {
77+
const out = scan(src);
78+
expect(out.length).toBe(src.length);
79+
expect([...out].filter((c) => c === "\n").length).toBe(
80+
[...src].filter((c) => c === "\n").length,
81+
);
82+
}
83+
});
84+
});
85+
86+
describe("stripJsStringLiterals scaling", () => {
87+
it("stays linear in slash-dense input", () => {
88+
const time = (n: number) => {
89+
const src = "a=b/c;".repeat(n);
90+
let best = Infinity;
91+
for (let run = 0; run < 3; run += 1) {
92+
const started = performance.now();
93+
stripJsStringLiterals(src);
94+
best = Math.min(best, performance.now() - started);
95+
}
96+
return best;
97+
};
98+
const small = Math.max(time(20_000), 0.5);
99+
const large = time(160_000);
100+
expect(large / small).toBeLessThan(24);
101+
expect(large).toBeLessThan(2_000);
102+
});
103+
});
104+
105+
describe("stripJsComments", () => {
106+
const strip = (src: string) => stripJsComments(src);
107+
108+
it("keeps a regex literal that ends in an escaped slash from opening a comment", () => {
109+
const src = 'var proto = /^https?:\\/\\//; var el = document.querySelector("#hero");';
110+
expect(strip(src)).toBe(src);
111+
});
112+
113+
it("still strips a real comment that follows a regex literal", () => {
114+
const src = "var proto = /^https?:\\/\\//; // trailing note\nvar x = 1;";
115+
const out = strip(src);
116+
expect(out).toContain("/^https?:\\/\\//;");
117+
expect(out).not.toContain("trailing note");
118+
expect(out).toHaveLength(src.length);
119+
});
120+
121+
it("does not read a slash inside a string as a comment", () => {
122+
const src = 'var s = "a // b"; var t = 1;';
123+
expect(strip(src)).toBe(src);
124+
});
125+
126+
it("falls back to the source when a slash never closes on its line", () => {
127+
const src = "var of = 2;\nvar r = of /2; // note\n";
128+
expect(strip(src)).toBe(src);
129+
});
130+
});
131+
132+
describe("stripCssComments", () => {
133+
it("keeps a rule sandwiched between comment markers printed as content", () => {
134+
const css =
135+
'#o::before{content:"/*"}\n[data-composition-id="main" data-start="0"]{color:red}\n#c::after{content:"*/"}';
136+
const out = stripCssComments(css);
137+
expect(out.length).toBe(css.length);
138+
expect(out).toContain('data-composition-id="main" data-start="0"');
139+
});
140+
141+
it("blanks a real comment and an unterminated one, keeping length", () => {
142+
for (const css of ["/* gone */#a{color:red}", "#a{color:red}/* open"]) {
143+
const out = stripCssComments(css);
144+
expect(out.length).toBe(css.length);
145+
expect(out).not.toContain("/*");
146+
expect(out).toContain("#a{color:red}");
147+
}
148+
});
149+
});

0 commit comments

Comments
 (0)