-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathcore.ts
More file actions
378 lines (357 loc) · 13.9 KB
/
core.ts
File metadata and controls
378 lines (357 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
import type { LintContext, HyperframeLintFinding } from "../context";
import postcss from "postcss";
import {
readAttr,
truncateSnippet,
extractCompositionIdsFromCss,
getInlineScriptSyntaxError,
TIMELINE_REGISTRY_INIT_PATTERN,
TIMELINE_REGISTRY_ASSIGN_PATTERN,
INVALID_SCRIPT_CLOSE_PATTERN,
} from "../utils";
function escapeRegExp(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function selectorTargetsCompositionId(selector: string, compositionId: string): boolean {
const escaped = escapeRegExp(compositionId);
return new RegExp(
String.raw`\[\s*data-composition-id\s*=\s*(?:"${escaped}"|'${escaped}')\s*\]`,
).test(selector);
}
function isStudioTimelineElement(tag: { raw: string; name: string }): boolean {
if (["script", "style", "link", "meta", "template", "noscript"].includes(tag.name)) {
return false;
}
return Boolean(
readAttr(tag.raw, "data-start") ||
readAttr(tag.raw, "data-track-index") ||
readAttr(tag.raw, "data-track") ||
readAttr(tag.raw, "data-composition-src") ||
readAttr(tag.raw, "data-composition-file"),
);
}
function describeStudioElement(tag: { raw: string; name: string }): string {
const parts = [`<${tag.name}`];
const className = readAttr(tag.raw, "class");
const compositionId = readAttr(tag.raw, "data-composition-id");
const dataStart = readAttr(tag.raw, "data-start");
const dataTrack = readAttr(tag.raw, "data-track-index") ?? readAttr(tag.raw, "data-track");
if (className) {
const primaryClass = className
.split(/\s+/)
.map((value) => value.trim())
.find((value) => value && value !== "clip");
if (primaryClass) parts.push(` class="${primaryClass}"`);
}
if (compositionId) parts.push(` data-composition-id="${compositionId}"`);
if (dataStart) parts.push(` data-start="${dataStart}"`);
if (dataTrack) parts.push(` data-track-index="${dataTrack}"`);
parts.push(">");
return parts.join("");
}
export const coreRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [
// root_missing_composition_id + root_missing_dimensions
({ rootTag }) => {
const findings: HyperframeLintFinding[] = [];
if (!rootTag || !readAttr(rootTag.raw, "data-composition-id")) {
findings.push({
code: "root_missing_composition_id",
severity: "error",
message: "Root composition is missing `data-composition-id`.",
elementId: rootTag ? readAttr(rootTag.raw, "id") || undefined : undefined,
fixHint: "Add a stable `data-composition-id` to the entry composition wrapper.",
snippet: truncateSnippet(rootTag?.raw || ""),
});
}
if (!rootTag || !readAttr(rootTag.raw, "data-width") || !readAttr(rootTag.raw, "data-height")) {
findings.push({
code: "root_missing_dimensions",
severity: "error",
message: "Root composition is missing `data-width` or `data-height`.",
elementId: rootTag ? readAttr(rootTag.raw, "id") || undefined : undefined,
fixHint: "Set numeric `data-width` and `data-height` on the entry composition root.",
snippet: truncateSnippet(rootTag?.raw || ""),
});
}
return findings;
},
// missing_timeline_registry + timeline_registry_missing_init
({ source }) => {
const findings: HyperframeLintFinding[] = [];
if (
!TIMELINE_REGISTRY_INIT_PATTERN.test(source) &&
!TIMELINE_REGISTRY_ASSIGN_PATTERN.test(source)
) {
findings.push({
code: "missing_timeline_registry",
severity: "error",
message: "Missing `window.__timelines` registration.",
fixHint: "Register each composition timeline on `window.__timelines[compositionId]`.",
});
}
if (
TIMELINE_REGISTRY_ASSIGN_PATTERN.test(source) &&
!TIMELINE_REGISTRY_INIT_PATTERN.test(source)
) {
findings.push({
code: "timeline_registry_missing_init",
severity: "error",
message:
"`window.__timelines[…] = …` is used without initializing `window.__timelines` first.",
fixHint:
"Add `window.__timelines = window.__timelines || {};` before any timeline assignment.",
});
}
return findings;
},
// timeline_id_mismatch
({ source }) => {
const findings: HyperframeLintFinding[] = [];
const htmlCompIds = new Set<string>();
const timelineRegKeys = new Set<string>();
const compIdRe = /data-composition-id\s*=\s*["']([^"']+)["']/gi;
const tlKeyRe = /window\.__timelines\[\s*["']([^"']+)["']\s*\]/g;
let m: RegExpExecArray | null;
while ((m = compIdRe.exec(source)) !== null) {
if (m[1]) htmlCompIds.add(m[1]);
}
while ((m = tlKeyRe.exec(source)) !== null) {
if (m[1]) timelineRegKeys.add(m[1]);
}
for (const key of timelineRegKeys) {
if (!htmlCompIds.has(key)) {
findings.push({
code: "timeline_id_mismatch",
severity: "error",
message: `Timeline registered as "${key}" but no element has data-composition-id="${key}". The runtime cannot auto-nest this timeline.`,
fixHint: `Change window.__timelines["${key}"] to match the data-composition-id attribute, or vice versa.`,
});
}
}
return findings;
},
// invalid_inline_script_syntax (malformed close tag)
({ source }) => {
if (!INVALID_SCRIPT_CLOSE_PATTERN.test(source)) return [];
return [
{
code: "invalid_inline_script_syntax",
severity: "error",
message: "Detected malformed inline `<script>` closing syntax.",
fixHint: "Close inline scripts with a valid `</script>` tag.",
},
];
},
// invalid_inline_script_syntax (JS parse error)
({ scripts }) => {
const findings: HyperframeLintFinding[] = [];
for (const script of scripts) {
const attrs = script.attrs || "";
if (
/\bsrc\s*=/.test(attrs) ||
/\btype\s*=\s*["'](?:application\/json|importmap|module)["']/.test(attrs)
)
continue;
const syntaxError = getInlineScriptSyntaxError(script.content);
if (!syntaxError) continue;
findings.push({
code: "invalid_inline_script_syntax",
severity: "error",
message: `Inline script has invalid syntax: ${syntaxError}`,
fixHint: "Fix the inline script syntax before render verification.",
snippet: truncateSnippet(script.content),
});
}
return findings;
},
// host_missing_composition_id
({ tags }) => {
const findings: HyperframeLintFinding[] = [];
for (const tag of tags) {
const src = readAttr(tag.raw, "data-composition-src");
if (!src) continue;
if (readAttr(tag.raw, "data-composition-id")) continue;
findings.push({
code: "host_missing_composition_id",
severity: "error",
message: `Composition host for "${src}" is missing \`data-composition-id\`.`,
elementId: readAttr(tag.raw, "id") || undefined,
fixHint: "Set `data-composition-id` on every `data-composition-src` host element.",
snippet: truncateSnippet(tag.raw),
});
}
return findings;
},
// scoped_css_missing_wrapper
({ styles, compositionIds }) => {
const findings: HyperframeLintFinding[] = [];
const scopedCssCompositionIds = new Set<string>();
for (const style of styles) {
for (const compId of extractCompositionIdsFromCss(style.content)) {
scopedCssCompositionIds.add(compId);
}
}
for (const compId of scopedCssCompositionIds) {
if (compositionIds.has(compId)) continue;
findings.push({
code: "scoped_css_missing_wrapper",
severity: "warning",
message: `Scoped CSS targets composition "${compId}" but no matching wrapper exists in this HTML.`,
selector: `[data-composition-id="${compId}"]`,
fixHint:
"Preserve the matching composition wrapper or align the CSS scope to an existing wrapper.",
});
}
return findings;
},
// composition_self_attribute_selector
({ styles, rootCompositionId, rootTag }) => {
const findings: HyperframeLintFinding[] = [];
if (!rootCompositionId) return findings;
const seenSelectors = new Set<string>();
const rootId = readAttr(rootTag?.raw || "", "id");
for (const style of styles) {
let root: postcss.Root;
try {
root = postcss.parse(style.content);
} catch {
continue;
}
root.walkRules((rule) => {
for (const selector of rule.selectors) {
if (!selectorTargetsCompositionId(selector, rootCompositionId)) continue;
if (seenSelectors.has(selector)) continue;
seenSelectors.add(selector);
findings.push({
code: "composition_self_attribute_selector",
severity: "warning",
message:
"Selector matches the block's own id; will leak to sibling instances when the block is embedded twice.",
selector,
fixHint: rootId
? `Use #${rootId} for clearer authoring intent and instance-isolated styling.`
: "Add a stable id to the composition root and use that id selector for clearer authoring intent and instance-isolated styling.",
});
}
});
}
return findings;
},
// studio_missing_editable_id
({ tags, rootTag }) => {
const findings: HyperframeLintFinding[] = [];
for (const tag of tags) {
if (rootTag && tag.index === rootTag.index) continue;
if (!isStudioTimelineElement(tag)) continue;
if (readAttr(tag.raw, "id")) continue;
const descriptor = describeStudioElement(tag);
findings.push({
code: "studio_missing_editable_id",
severity: "warning",
message: `${descriptor} has no id, so Studio cannot use a stable edit target for its timeline and canvas controls.`,
selector: readAttr(tag.raw, "data-composition-id")
? `[data-composition-id="${readAttr(tag.raw, "data-composition-id")}"]`
: undefined,
fixHint:
'Add a stable, human-readable id such as id="hero-title" or id="scene-1-card" to every timeline-visible element you want agents or Studio to edit.',
snippet: truncateSnippet(tag.raw),
});
}
return findings;
},
// non_deterministic_code
({ scripts }) => {
const findings: HyperframeLintFinding[] = [];
const patterns: Array<{ pattern: RegExp; label: string; hint: string }> = [
{
pattern: /Math\.random\s*\(/,
label: "Math.random()",
hint: "Use a seeded PRNG (e.g. a simple mulberry32) so renders are deterministic across frames.",
},
{
pattern: /Date\.now\s*\(/,
label: "Date.now()",
hint: "Remove time-dependent code. Use GSAP timeline position instead of wall-clock time.",
},
{
pattern: /new\s+Date\s*\(/,
label: "new Date()",
hint: "Remove time-dependent code. Use GSAP timeline position instead of wall-clock time.",
},
{
pattern: /performance\.now\s*\(/,
label: "performance.now()",
hint: "Remove time-dependent code. Use GSAP timeline position instead of wall-clock time.",
},
{
pattern: /crypto\.getRandomValues\s*\(/,
label: "crypto.getRandomValues()",
hint: "Remove time-dependent code. Use a seeded PRNG for deterministic renders.",
},
];
for (const script of scripts) {
// Strip comments to avoid false positives
const stripped = script.content.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "");
for (const { pattern, label, hint } of patterns) {
if (pattern.test(stripped)) {
findings.push({
code: "non_deterministic_code",
severity: "error",
message: `Script contains \`${label}\` which produces non-deterministic output. Renders may differ between frames or runs.`,
fixHint: hint,
snippet: truncateSnippet(script.content),
});
}
}
}
return findings;
},
// pointer_events_none
({ tags, styles }) => {
const findings: HyperframeLintFinding[] = [];
const reported = new Set<string>();
for (const tag of tags) {
if (["script", "style", "link", "meta", "template", "noscript"].includes(tag.name)) continue;
const inlineStyle = readAttr(tag.raw, "style") ?? "";
if (!/pointer-events\s*:\s*none/i.test(inlineStyle)) continue;
const id = readAttr(tag.raw, "id");
const key = id ?? tag.raw;
if (reported.has(key)) continue;
reported.add(key);
findings.push({
code: "pointer_events_none",
severity: "info",
message: `<${tag.name}${id ? ` id="${id}"` : ""}> has \`pointer-events: none\` in its inline style. Elements with this property are harder to select in the Studio preview.`,
elementId: id || undefined,
fixHint:
"If this element should be selectable in the Studio, remove `pointer-events: none` or move it to a wrapper that doesn't contain editable content.",
snippet: truncateSnippet(tag.raw),
});
}
for (const style of styles) {
let root: postcss.Root;
try {
root = postcss.parse(style.content);
} catch {
continue;
}
root.walkDecls("pointer-events", (decl) => {
if (decl.value.trim().toLowerCase() !== "none") return;
const rule = decl.parent;
if (!rule || rule.type !== "rule") return;
const selector = (rule as postcss.Rule).selector;
if (reported.has(selector)) return;
reported.add(selector);
findings.push({
code: "pointer_events_none",
severity: "info",
message: `\`${selector}\` sets \`pointer-events: none\`. Elements matching this selector are harder to select in the Studio preview.`,
selector,
fixHint:
"If these elements should be selectable in the Studio, remove `pointer-events: none` or move it to a wrapper that doesn't contain editable content.",
});
});
}
return findings;
},
];