@skilldeck/studio 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,458 @@
1
+ #!/usr/bin/env node
2
+ // studio / lint-comp.mjs
3
+ //
4
+ // Static checks for an HTML video composition before it is rendered: the timeline
5
+ // (gaps, overlaps, scenes past the end, off-frame cuts), local assets that do not
6
+ // exist, remote assets and webfonts, non-deterministic script (Math.random,
7
+ // Date.now, performance.now, timers, network), unseekable CSS transitions,
8
+ // unpreloaded @font-face files, and malformed SRT/VTT captions.
9
+ //
10
+ // node lint-comp.mjs <composition.html> [--strict] [--json]
11
+ //
12
+ // Exit 0 when there are no errors (warnings allowed unless --strict), 1 when the
13
+ // composition has findings that fail, 2 on bad usage or an unreadable file.
14
+ // Zero dependencies. Node 22+.
15
+
16
+ import fs from 'node:fs'
17
+ import path from 'node:path'
18
+ import { pathToFileURL } from 'node:url'
19
+
20
+ const HELP = `lint-comp: check an HTML video composition before rendering
21
+
22
+ node lint-comp.mjs <composition.html> [options]
23
+
24
+ --strict warnings fail too (exit 1)
25
+ --json machine-readable output
26
+
27
+ Exit codes: 0 clean, 1 findings that fail, 2 usage error or unreadable file.
28
+ `
29
+
30
+ const EPS = 1e-6
31
+
32
+ // ---------------------------------------------------------------------------
33
+ // Light HTML parsing (regex based, line-preserving)
34
+ // ---------------------------------------------------------------------------
35
+
36
+ /** Replace a span with spaces but keep newlines, so offsets and line numbers survive. */
37
+ const blank = (s) => s.replace(/[^\n]/g, ' ')
38
+
39
+ /** 1-based line number of a character offset. */
40
+ export function lineOf(text, index) {
41
+ let n = 1
42
+ for (let i = 0; i < index && i < text.length; i++) if (text.charCodeAt(i) === 10) n++
43
+ return n
44
+ }
45
+
46
+ /** Parse a tag's attribute string into a lower-cased name -> value map ('' for bare attributes). */
47
+ export function parseAttrs(s) {
48
+ const out = {}
49
+ const re = /([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g
50
+ let m
51
+ while ((m = re.exec(s))) out[m[1].toLowerCase()] = m[2] ?? m[3] ?? m[4] ?? ''
52
+ return out
53
+ }
54
+
55
+ /**
56
+ * Split an HTML document into tags, inline scripts and inline styles.
57
+ * Comments are ignored; script/style bodies are not scanned as markup.
58
+ */
59
+ export function parseHtml(html) {
60
+ let text = html.replace(/<!--[\s\S]*?-->/g, blank)
61
+ const scripts = []
62
+ const styles = []
63
+ text = text.replace(/<(script|style)\b([^>]*)>([\s\S]*?)<\/\1\s*>/gi, (all, tag, attrs, body, offset) => {
64
+ const bodyOffset = offset + all.indexOf('>') + 1
65
+ const entry = { attrs: parseAttrs(attrs), content: body, line: lineOf(html, bodyOffset), tagLine: lineOf(html, offset) }
66
+ ;(tag.toLowerCase() === 'script' ? scripts : styles).push(entry)
67
+ // keep the opening tag visible to the tag scanner, blank the body
68
+ return all.slice(0, all.indexOf('>') + 1) + blank(body) + all.slice(all.indexOf('>') + 1 + body.length)
69
+ })
70
+ const tags = []
71
+ const re = /<([a-zA-Z][\w-]*)\b((?:[^>"']|"[^"]*"|'[^']*')*)>/g
72
+ let m
73
+ while ((m = re.exec(text))) tags.push({ tag: m[1].toLowerCase(), attrs: parseAttrs(m[2]), line: lineOf(html, m.index) })
74
+ return { tags, scripts, styles }
75
+ }
76
+
77
+ const num = (v) => (v === undefined || v === '' ? NaN : Number(v))
78
+
79
+ /** Read the composition root and its scenes from the markup. */
80
+ export function parseComposition(html) {
81
+ const { tags, scripts, styles } = parseHtml(html)
82
+ const rootTag = tags.find((t) => 'data-composition' in t.attrs)
83
+ const root = rootTag
84
+ ? {
85
+ line: rootTag.line,
86
+ width: num(rootTag.attrs['data-width']),
87
+ height: num(rootTag.attrs['data-height']),
88
+ fps: num(rootTag.attrs['data-fps']),
89
+ duration: num(rootTag.attrs['data-duration']),
90
+ }
91
+ : null
92
+ const scenes = tags
93
+ .filter((t) => 'data-scene' in t.attrs)
94
+ .map((t, i) => ({
95
+ id: t.attrs.id || t.attrs['data-scene'] || `scene#${i + 1}`,
96
+ start: num(t.attrs['data-start']),
97
+ duration: num(t.attrs['data-duration']),
98
+ track: t.attrs['data-track'] === undefined ? 0 : num(t.attrs['data-track']),
99
+ line: t.line,
100
+ }))
101
+ const captions = scripts
102
+ .filter((s) => 'data-captions' in s.attrs)
103
+ .map((s) => ({ format: s.attrs['data-captions'] || 'auto', text: s.content, line: s.line }))
104
+ return { root, scenes, tags, scripts, styles, captions }
105
+ }
106
+
107
+ // ---------------------------------------------------------------------------
108
+ // Timeline
109
+ // ---------------------------------------------------------------------------
110
+
111
+ const fmt = (t) => `${Number(t.toFixed(3))}s`
112
+
113
+ /** Gaps (track 0 only), overlaps (per track), scenes past the end, off-frame cuts. */
114
+ export function lintTimeline(root, scenes) {
115
+ const findings = []
116
+ const add = (severity, rule, message, line) => findings.push({ severity, rule, message, line })
117
+ const { duration, fps } = root
118
+ const valid = []
119
+ for (const s of scenes) {
120
+ if (!Number.isFinite(s.start) || s.start < 0) add('error', 'scene-timing', `${s.id}: data-start must be a number >= 0`, s.line)
121
+ else if (!Number.isFinite(s.duration) || s.duration <= 0) add('error', 'scene-timing', `${s.id}: data-duration must be a number > 0`, s.line)
122
+ else if (!Number.isInteger(s.track) || s.track < 0) add('error', 'scene-timing', `${s.id}: data-track must be a whole number >= 0`, s.line)
123
+ else valid.push(s)
124
+ }
125
+ if (Number.isFinite(duration)) {
126
+ for (const s of valid) {
127
+ const end = s.start + s.duration
128
+ if (end > duration + EPS) add('error', 'scene-past-end', `${s.id} ends at ${fmt(end)}, after the composition ends at ${fmt(duration)}`, s.line)
129
+ }
130
+ }
131
+ if (Number.isFinite(fps) && fps > 0) {
132
+ for (const s of valid) {
133
+ for (const [label, t] of [['starts', s.start], ['ends', s.start + s.duration]]) {
134
+ const f = t * fps
135
+ if (Math.abs(f - Math.round(f)) > 1e-4) add('warn', 'off-frame', `${s.id} ${label} at ${fmt(t)}, between frames at ${fps} fps (nearest ${fmt(Math.round(f) / fps)})`, s.line)
136
+ }
137
+ }
138
+ }
139
+ const tracks = new Map()
140
+ for (const s of valid) tracks.set(s.track, [...(tracks.get(s.track) ?? []), s])
141
+ if (!tracks.has(0)) add('error', 'no-scenes', 'no scenes on the main track: add elements with data-scene, data-start and data-duration', root.line)
142
+ for (const [track, list] of [...tracks].sort((a, b) => a[0] - b[0])) {
143
+ list.sort((a, b) => a.start - b.start || a.line - b.line)
144
+ let covered = 0
145
+ let last = null
146
+ for (const s of list) {
147
+ if (last && s.start < covered - EPS) {
148
+ add('error', 'overlap', `${s.id} (${fmt(s.start)}-${fmt(s.start + s.duration)}) overlaps ${last.id} until ${fmt(covered)} on track ${track}; move one to another data-track if the layering is intended`, s.line)
149
+ } else if (track === 0 && s.start > covered + EPS) {
150
+ add('error', 'gap', `gap ${fmt(covered)}-${fmt(s.start)} before ${s.id}: nothing is on screen`, s.line)
151
+ }
152
+ if (s.start + s.duration > covered) {
153
+ covered = s.start + s.duration
154
+ last = s
155
+ }
156
+ }
157
+ if (track === 0 && Number.isFinite(duration) && covered < duration - EPS) {
158
+ add('error', 'gap', `gap ${fmt(covered)}-${fmt(duration)} at the end: the last scene ends before the composition`, last?.line ?? root.line)
159
+ }
160
+ }
161
+ return findings
162
+ }
163
+
164
+ // ---------------------------------------------------------------------------
165
+ // Captions (SRT / WebVTT)
166
+ // ---------------------------------------------------------------------------
167
+
168
+ /** Parse "01:02:03,456", "02:03.456" or "02:03.5" into seconds; NaN if malformed. */
169
+ export function parseTimestamp(s) {
170
+ const m = /^(?:(\d+):)?(\d{1,2}):(\d{2})[.,](\d{1,3})$/.exec(String(s).trim())
171
+ if (!m) return NaN
172
+ return Number(m[1] ?? 0) * 3600 + Number(m[2]) * 60 + Number(m[3]) + Number((m[4] + '00').slice(0, 3)) / 1000
173
+ }
174
+
175
+ /** Parse SRT or WebVTT text into cues. Returns { format, cues, errors }. */
176
+ export function parseCaptions(text, format = 'auto') {
177
+ const src = String(text).replace(/\r\n?/g, '\n').replace(/^/, '').trim()
178
+ const fmtName = format === 'auto' ? (/^WEBVTT\b/.test(src) ? 'vtt' : 'srt') : format
179
+ const cues = []
180
+ const errors = []
181
+ let lineNo = 1
182
+ for (const block of src.split(/\n[ \t]*\n/)) {
183
+ const lines = block.split('\n')
184
+ const blockLine = lineNo
185
+ lineNo += lines.length + 1
186
+ const i = lines.findIndex((l) => l.includes('-->'))
187
+ if (i < 0) {
188
+ if (/^(WEBVTT|NOTE|STYLE|REGION)\b/.test(lines[0]) || !block.trim()) continue
189
+ errors.push({ line: blockLine, message: `no "-->" timing line in cue "${lines[0].slice(0, 40)}"` })
190
+ continue
191
+ }
192
+ const [a, b = ''] = lines[i].split('-->')
193
+ const start = parseTimestamp(a)
194
+ const end = parseTimestamp(b.trim().split(/\s+/)[0])
195
+ if (!Number.isFinite(start) || !Number.isFinite(end)) {
196
+ errors.push({ line: blockLine + i, message: `malformed timing "${lines[i].trim()}"` })
197
+ continue
198
+ }
199
+ if (end <= start) {
200
+ errors.push({ line: blockLine + i, message: `cue ends (${fmt(end)}) before it starts (${fmt(start)})` })
201
+ continue
202
+ }
203
+ const body = lines
204
+ .slice(i + 1)
205
+ .join('\n')
206
+ .replace(/<[^>]+>/g, '')
207
+ .trim()
208
+ cues.push({ start, end, text: body, line: blockLine + i })
209
+ }
210
+ return { format: fmtName, cues, errors }
211
+ }
212
+
213
+ export function lintCaptions(captions, root, { hasTarget }) {
214
+ const findings = []
215
+ for (const c of captions) {
216
+ const { cues, errors } = parseCaptions(c.text, c.format)
217
+ for (const e of errors) findings.push({ severity: 'error', rule: 'caption-parse', message: e.message, line: c.line + e.line - 1 })
218
+ const sorted = [...cues].sort((x, y) => x.start - y.start)
219
+ for (let i = 1; i < sorted.length; i++) {
220
+ if (sorted[i].start < sorted[i - 1].end - EPS) findings.push({ severity: 'warn', rule: 'caption-overlap', message: `cue at ${fmt(sorted[i].start)} starts before the previous cue ends (${fmt(sorted[i - 1].end)})`, line: c.line + sorted[i].line - 1 })
221
+ }
222
+ for (const q of cues) {
223
+ if (Number.isFinite(root.duration) && q.end > root.duration + EPS) findings.push({ severity: 'warn', rule: 'caption-past-end', message: `cue "${q.text.slice(0, 30)}" ends at ${fmt(q.end)}, after the composition ends`, line: c.line + q.line - 1 })
224
+ }
225
+ if (!cues.length && !errors.length) findings.push({ severity: 'warn', rule: 'caption-parse', message: 'captions block has no cues', line: c.line })
226
+ }
227
+ if (captions.length && !hasTarget) findings.push({ severity: 'warn', rule: 'caption-target', message: 'captions are defined but no element has data-caption-target, so they never show', line: captions[0].line })
228
+ return findings
229
+ }
230
+
231
+ // ---------------------------------------------------------------------------
232
+ // Script and CSS determinism
233
+ // ---------------------------------------------------------------------------
234
+
235
+ /** Remove JS comments while keeping offsets (good enough for a lint, not a parser). */
236
+ export function stripJsComments(code) {
237
+ return code.replace(/\/\*[\s\S]*?\*\//g, blank).replace(/(^|[^:\\"'`])\/\/[^\n]*/g, (m, pre) => pre + blank(m.slice(pre.length)))
238
+ }
239
+
240
+ const SCRIPT_RULES = [
241
+ { rule: 'math-random', severity: 'error', re: /\bMath\.random\s*\(/g, message: 'Math.random() gives different frames on every render; use __studio.random(seed)' },
242
+ { rule: 'wall-clock', severity: 'error', re: /\bDate\.now\s*\(|\bnew\s+Date\s*\(\s*\)/g, message: 'wall-clock time differs per render; derive everything from the seek time t' },
243
+ { rule: 'wall-clock', severity: 'error', re: /\bperformance\.now\s*\(/g, message: 'performance.now() is wall-clock time; derive everything from the seek time t' },
244
+ { rule: 'timer-animation', severity: 'error', re: /\bsetInterval\s*\(/g, message: 'setInterval-driven animation cannot be seeked; move it into __studio.onSeek(fn)' },
245
+ { rule: 'timer-animation', severity: 'warn', re: /\bsetTimeout\s*\(/g, message: 'setTimeout runs on wall-clock time, not the composition clock; prefer __studio.onSeek(fn)' },
246
+ { rule: 'raf-animation', severity: 'warn', re: /\brequestAnimationFrame\s*\(/g, message: 'requestAnimationFrame loops run on wall-clock time; drive state from __studio.onSeek(fn)' },
247
+ ]
248
+
249
+ /** Scan JS for non-deterministic calls and network access. `line` is the line the code starts on. */
250
+ export function scanScript(code, line = 1) {
251
+ const src = stripJsComments(code)
252
+ const findings = []
253
+ const at = (i) => line + lineOf(src, i) - 1
254
+ for (const r of SCRIPT_RULES) {
255
+ for (const m of src.matchAll(r.re)) findings.push({ severity: r.severity, rule: r.rule, message: r.message, line: at(m.index) })
256
+ }
257
+ for (const m of src.matchAll(/\bfetch\s*\(\s*(['"`]?)([^'"`)\s]*)\1|\bnew\s+(XMLHttpRequest|WebSocket|EventSource)\b|\bimport\s*\(\s*['"](https?:[^'"]+)/g)) {
258
+ const url = m[2] ?? m[4] ?? ''
259
+ const remote = /^(https?:|wss?:)?\/\//.test(url) || /WebSocket|EventSource/.test(m[3] ?? '') || Boolean(m[4])
260
+ findings.push({
261
+ severity: 'error',
262
+ rule: 'network',
263
+ message: remote
264
+ ? `network access at render time (${url || m[3]}) makes frames depend on the network; vendor the data next to the composition and inline it`
265
+ : `${m[3] ?? 'fetch'}${url ? ` of "${url}"` : ''} fails over file:// in headless Chrome; inline the data in <script type="application/json">`,
266
+ line: at(m.index),
267
+ })
268
+ }
269
+ return findings
270
+ }
271
+
272
+ const isRemote = (u) => /^(https?:)?\/\//i.test(u)
273
+ const isSkippable = (u) => !u || /^(data:|blob:|about:|javascript:|mailto:|#|\$\{|\{\{)/i.test(u)
274
+
275
+ /** url(...) references in CSS with their offsets. */
276
+ export function cssUrls(css) {
277
+ const out = []
278
+ for (const m of css.matchAll(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g)) out.push({ url: m[2].trim(), index: m.index })
279
+ for (const m of css.matchAll(/@import\s+(['"])([^'"]+)\1/g)) out.push({ url: m[2].trim(), index: m.index })
280
+ return out
281
+ }
282
+
283
+ /** Unseekable transitions and @font-face sources in a stylesheet. */
284
+ export function scanCss(css, line = 1) {
285
+ const findings = []
286
+ const fonts = []
287
+ for (const m of css.matchAll(/(?:^|[;{\s])transition(?:-property)?\s*:\s*([^;}]*)/g)) {
288
+ if (/^\s*(none|initial|unset)\s*$/.test(m[1])) continue
289
+ findings.push({ severity: 'warn', rule: 'css-transition', message: 'CSS transitions start when state changes and are not seekable; use @keyframes animations', line: line + lineOf(css, m.index) - 1 })
290
+ }
291
+ for (const m of css.matchAll(/@font-face\s*\{([^}]*)\}/g)) {
292
+ for (const u of cssUrls(m[1])) fonts.push({ url: u.url, line: line + lineOf(css, m.index) - 1 })
293
+ }
294
+ return { findings, fonts }
295
+ }
296
+
297
+ // ---------------------------------------------------------------------------
298
+ // The whole composition
299
+ // ---------------------------------------------------------------------------
300
+
301
+ const ASSET_ATTRS = { src: ['img', 'video', 'audio', 'source', 'script', 'iframe', 'embed', 'track', 'input'], poster: ['video'], href: ['link'], 'xlink:href': ['image', 'use'] }
302
+
303
+ /**
304
+ * Lint composition HTML. `baseDir` resolves relative assets; `exists` and
305
+ * `readFile` are injectable for tests.
306
+ */
307
+ export function lintComposition(html, { baseDir = '.', file = 'composition.html', exists = fs.existsSync, readFile = (p) => fs.readFileSync(p, 'utf8') } = {}) {
308
+ const comp = parseComposition(html)
309
+ const findings = []
310
+ const add = (severity, rule, message, line, where = file) => findings.push({ severity, rule, message, line, file: where })
311
+ const push = (list, where = file) => list.forEach((f) => findings.push({ file: where, ...f }))
312
+
313
+ // root and clock
314
+ const { root } = comp
315
+ if (!root) {
316
+ add('error', 'no-root', 'no composition root: add data-composition with data-width, data-height, data-fps and data-duration', 1)
317
+ } else {
318
+ for (const k of ['width', 'height']) if (!Number.isInteger(root[k]) || root[k] <= 0) add('error', 'root-config', `data-${k} must be a positive whole number of pixels`, root.line)
319
+ if (!Number.isFinite(root.fps) || root.fps <= 0 || root.fps > 240) add('error', 'root-config', 'data-fps must be a number between 1 and 240', root.line)
320
+ if (!Number.isFinite(root.duration) || root.duration <= 0) add('error', 'root-config', 'data-duration must be a positive number of seconds', root.line)
321
+ if ((root.width % 2 || root.height % 2) && Number.isInteger(root.width) && Number.isInteger(root.height)) add('warn', 'odd-dimensions', `${root.width}x${root.height} has an odd side; H.264 (yuv420p) needs even dimensions`, root.line)
322
+ push(lintTimeline(root, comp.scenes))
323
+ }
324
+ const hasRuntime = comp.scripts.some((s) => 'data-studio-runtime' in s.attrs || /window\.__studio\s*=/.test(s.content))
325
+ if (!hasRuntime) add('error', 'no-clock', 'no seekable clock: include the studio runtime (<script data-studio-runtime>) or define window.__studio.seek(t)', root?.line ?? 1)
326
+
327
+ // captions
328
+ if (root) push(lintCaptions(comp.captions, root, { hasTarget: comp.tags.some((t) => 'data-caption-target' in t.attrs) }))
329
+
330
+ // inline scripts (skip the runtime and data blocks)
331
+ for (const s of comp.scripts) {
332
+ const type = (s.attrs.type || 'text/javascript').toLowerCase()
333
+ if ('data-studio-runtime' in s.attrs || 'data-captions' in s.attrs) continue
334
+ if (!/javascript|module|^$/.test(type)) continue
335
+ push(scanScript(s.content, s.line))
336
+ }
337
+
338
+ // assets, fonts, stylesheets
339
+ const preloadedFonts = new Set()
340
+ const fontFaces = []
341
+ const checkRef = (ref, line, where, dir, kind = 'asset') => {
342
+ if (isSkippable(ref)) return null
343
+ if (isRemote(ref)) {
344
+ const font = kind === 'font' || /fonts\.(googleapis|gstatic)\.com|use\.typekit|fonts\.bunny/.test(ref)
345
+ add('error', font ? 'remote-font' : 'remote-asset', `${ref} loads over the network at render time; download it next to the composition and reference it relatively`, line, where)
346
+ return null
347
+ }
348
+ const clean = decodeURI(ref.split(/[?#]/)[0])
349
+ if (clean.startsWith('/')) {
350
+ add('error', 'absolute-asset', `${ref} is root-absolute and resolves to the filesystem root under file://; use a relative path`, line, where)
351
+ return null
352
+ }
353
+ const abs = path.resolve(dir, clean)
354
+ if (!exists(abs)) {
355
+ add('error', 'missing-asset', `${ref} not found (looked for ${path.relative(process.cwd(), abs) || abs})`, line, where)
356
+ return null
357
+ }
358
+ return abs
359
+ }
360
+
361
+ const scanStylesheet = (css, line, where, dir) => {
362
+ const { findings: f, fonts } = scanCss(css, line)
363
+ push(f, where)
364
+ for (const font of fonts) fontFaces.push({ ...font, where, dir })
365
+ const fontUrls = new Set(fonts.map((x) => x.url))
366
+ for (const u of cssUrls(css)) if (!fontUrls.has(u.url)) checkRef(u.url, line + lineOf(css, u.index) - 1, where, dir)
367
+ }
368
+
369
+ for (const t of comp.tags) {
370
+ for (const [attr, tagNames] of Object.entries(ASSET_ATTRS)) {
371
+ if (!(attr in t.attrs) || !tagNames.includes(t.tag)) continue
372
+ const ref = t.attrs[attr]
373
+ if (t.tag === 'link') {
374
+ const rel = (t.attrs.rel || '').toLowerCase()
375
+ if (!/stylesheet|preload|icon|modulepreload/.test(rel)) continue
376
+ const isFont = rel.includes('preload') && t.attrs.as === 'font'
377
+ const abs = checkRef(ref, t.line, file, baseDir, isFont || /fonts\./.test(ref) ? 'font' : 'asset')
378
+ if (isFont && abs) preloadedFonts.add(abs)
379
+ if (abs && rel.includes('stylesheet')) {
380
+ try {
381
+ scanStylesheet(readFile(abs), 1, path.relative(baseDir, abs), path.dirname(abs))
382
+ } catch {}
383
+ }
384
+ continue
385
+ }
386
+ const abs = checkRef(ref, t.line, file, baseDir)
387
+ if (abs && t.tag === 'script') {
388
+ try {
389
+ push(scanScript(readFile(abs), 1), path.relative(baseDir, abs))
390
+ } catch {}
391
+ }
392
+ }
393
+ if (t.attrs.srcset) for (const part of t.attrs.srcset.split(',')) checkRef(part.trim().split(/\s+/)[0], t.line, file, baseDir)
394
+ if (t.attrs.style) for (const u of cssUrls(t.attrs.style)) checkRef(u.url, t.line, file, baseDir)
395
+ if (t.tag === 'video' && 'autoplay' in t.attrs) add('warn', 'autoplay', '<video autoplay> plays on wall-clock time; the runtime seeks media itself, remove autoplay', t.line)
396
+ }
397
+ for (const s of comp.styles) scanStylesheet(s.content, s.line, file, baseDir)
398
+
399
+ for (const f of fontFaces) {
400
+ if (isRemote(f.url)) {
401
+ add('error', 'remote-font', `@font-face loads ${f.url} over the network; download the font file and reference it relatively`, f.line, f.where)
402
+ continue
403
+ }
404
+ const abs = checkRef(f.url, f.line, f.where, f.dir, 'font')
405
+ if (abs && !preloadedFonts.has(abs)) add('warn', 'font-not-preloaded', `${f.url} is not preloaded; first frames can render in a fallback font. Add <link rel="preload" as="font" href="${f.url}" crossorigin>`, f.line, f.where)
406
+ }
407
+
408
+ findings.sort((a, b) => (a.severity === b.severity ? 0 : a.severity === 'error' ? -1 : 1) || (a.file === b.file ? (a.line ?? 0) - (b.line ?? 0) : 0))
409
+ const errors = findings.filter((f) => f.severity === 'error').length
410
+ return {
411
+ file,
412
+ config: root && { width: root.width, height: root.height, fps: root.fps, duration: root.duration, frames: Number.isFinite(root.fps * root.duration) ? Math.round(root.fps * root.duration) : null },
413
+ scenes: comp.scenes.map(({ id, start, duration, track, line }) => ({ id, start, duration, end: start + duration, track, line })),
414
+ captions: comp.captions.reduce((n, c) => n + parseCaptions(c.text, c.format).cues.length, 0),
415
+ findings,
416
+ errors,
417
+ warnings: findings.length - errors,
418
+ ok: errors === 0,
419
+ }
420
+ }
421
+
422
+ export function lintFile(file, opts = {}) {
423
+ const html = fs.readFileSync(file, 'utf8')
424
+ return lintComposition(html, { baseDir: path.dirname(path.resolve(file)), file: path.basename(file), ...opts })
425
+ }
426
+
427
+ export function formatReport(r) {
428
+ const out = []
429
+ if (r.config) out.push(`${r.file}: ${r.config.width}x${r.config.height} @ ${r.config.fps} fps, ${r.config.duration}s (${r.config.frames} frames), ${r.scenes.length} scenes, ${r.captions} caption cues`)
430
+ else out.push(`${r.file}`)
431
+ for (const f of r.findings) out.push(` ${f.severity === 'error' ? 'error' : 'warn '} ${f.file}:${f.line ?? '?'} ${f.rule.padEnd(18)} ${f.message}`)
432
+ out.push(r.findings.length ? `${r.errors} error(s), ${r.warnings} warning(s)` : 'clean: no findings')
433
+ return out.join('\n')
434
+ }
435
+
436
+ function main(argv) {
437
+ if (argv.includes('--help') || argv.includes('-h')) {
438
+ process.stdout.write(HELP)
439
+ return 0
440
+ }
441
+ const [file] = argv.filter((a) => !a.startsWith('--'))
442
+ if (!file) {
443
+ process.stderr.write(HELP)
444
+ return 2
445
+ }
446
+ let report
447
+ try {
448
+ report = lintFile(file)
449
+ } catch (err) {
450
+ process.stderr.write(`lint-comp: cannot read ${file}: ${err.message}\n`)
451
+ return 2
452
+ }
453
+ if (argv.includes('--json')) console.log(JSON.stringify(report, null, 2))
454
+ else console.log(formatReport(report))
455
+ return report.errors || (argv.includes('--strict') && report.warnings) ? 1 : 0
456
+ }
457
+
458
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) process.exitCode = main(process.argv.slice(2))