@miragon/slidev-validator 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.
Files changed (34) hide show
  1. package/README.md +167 -0
  2. package/bin/index.mjs +178 -0
  3. package/package.json +50 -0
  4. package/src/config.mjs +186 -0
  5. package/src/engine.mjs +115 -0
  6. package/src/glob.mjs +47 -0
  7. package/src/helpers.mjs +113 -0
  8. package/src/index.mjs +59 -0
  9. package/src/presets/recommended.mjs +12 -0
  10. package/src/presets/required.mjs +13 -0
  11. package/src/rendered-runner.mjs +106 -0
  12. package/src/report.mjs +87 -0
  13. package/src/rules/index.mjs +58 -0
  14. package/src/rules/rendered/card-white.mjs +13 -0
  15. package/src/rules/rendered/element-overflow.mjs +28 -0
  16. package/src/rules/rendered/heading-black.mjs +13 -0
  17. package/src/rules/rendered/measure.mjs +76 -0
  18. package/src/rules/rendered/no-em-dash.mjs +11 -0
  19. package/src/rules/rendered/no-emoji.mjs +11 -0
  20. package/src/rules/rendered/no-inline-font.mjs +13 -0
  21. package/src/rules/rendered/no-nested-bullets.mjs +13 -0
  22. package/src/rules/rendered/no-restyled-bullets.mjs +13 -0
  23. package/src/rules/rendered/overlay-safe-area.mjs +43 -0
  24. package/src/rules/rendered/safe-area/config.mjs +38 -0
  25. package/src/rules/rendered/safe-area/measure.mjs +93 -0
  26. package/src/rules/rendered/safe-area/model.mjs +179 -0
  27. package/src/rules/source/content-heading.mjs +93 -0
  28. package/src/rules/source/excalidraw-built-transparent.mjs +43 -0
  29. package/src/rules/source/excalidraw-committed-light.mjs +35 -0
  30. package/src/rules/source/no-html-entities.mjs +28 -0
  31. package/src/rules/source/no-raw-html.mjs +48 -0
  32. package/src/rules/source/sanctioned-layout.mjs +78 -0
  33. package/src/slide-files.mjs +25 -0
  34. package/src/versions.mjs +81 -0
@@ -0,0 +1,35 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { excalidrawSvgFiles, toRel } from '../../helpers.mjs'
3
+
4
+ /**
5
+ * The COMMITTED .excalidraw.svg is the editable source. It must render light in
6
+ * editor previews (IntelliJ/Finder/GitHub): NO dark-mode invert filter on the root
7
+ * <svg>, and a baked full-canvas LIGHT background (#F9F7F7 or #FFFFFF). The
8
+ * chapter-resources plugin (deck/vite.config.ts) strips that background at
9
+ * serve/build time — validated by the sibling excalidraw-built-transparent rule.
10
+ */
11
+ const LIGHT = /^#(?:f9f7f7|ffffff)$/i
12
+
13
+ export const excalidrawCommittedLight = {
14
+ id: 'excalidraw-committed-light',
15
+ type: 'source',
16
+ title: 'committed excalidraw diagrams are light (no dark filter, light background)',
17
+ message: 'Committed Excalidraw diagrams must be light (no dark filter, light background)',
18
+ meta: { category: 'recommended', default: 'error' },
19
+ check() {
20
+ const offenders = []
21
+ for (const file of excalidrawSvgFiles()) {
22
+ const svg = readFileSync(file, 'utf8')
23
+ const rel = toRel(file)
24
+ const tag = (svg.match(/<svg\b[^>]*>/) || [''])[0]
25
+ if (/\bfilter=/.test(tag)) offenders.push({ file: rel, message: 'dark-mode filter on <svg> (must be light)' })
26
+ const dim = tag.match(/\bwidth="(\d+)"[^>]*\bheight="(\d+)"/)
27
+ if (dim) {
28
+ const m = svg.match(new RegExp(`<rect x="0" y="0" width="${dim[1]}" height="${dim[2]}"[^>]*\\bfill="(#[0-9a-fA-F]{6})"`))
29
+ if (!m) offenders.push({ file: rel, message: 'no full-canvas background rect (needs a light <rect> so it previews light)' })
30
+ else if (!LIGHT.test(m[1])) offenders.push({ file: rel, message: `background ${m[1]} is not light (must be #F9F7F7 or #FFFFFF)` })
31
+ }
32
+ }
33
+ return offenders
34
+ },
35
+ }
@@ -0,0 +1,28 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { slideSourceFiles, toRel } from '../../helpers.mjs'
3
+
4
+ /**
5
+ * Authors must write the literal character, never an HTML escape: an entity like
6
+ * &#39; renders to ' in the DOM, so it slips past the rendered-slide checks and
7
+ * silently litters the source. Catch them here, at the source.
8
+ */
9
+ const ENTITY = /&(#[0-9]+|#x[0-9a-fA-F]+|[a-zA-Z][a-zA-Z0-9]+);/
10
+
11
+ export const noHtmlEntities = {
12
+ id: 'no-html-entities',
13
+ type: 'source',
14
+ title: 'no HTML entities in slide source',
15
+ message: 'HTML entities must not appear in slide source — write the literal character instead',
16
+ meta: { category: 'required', default: 'error' },
17
+ check() {
18
+ const offenders = []
19
+ for (const file of slideSourceFiles()) {
20
+ const rel = toRel(file)
21
+ readFileSync(file, 'utf8').split('\n').forEach((line, i) => {
22
+ const m = line.match(ENTITY)
23
+ if (m) offenders.push({ file: rel, line: i + 1, message: `${m[0]} → ${line.trim()}` })
24
+ })
25
+ }
26
+ return offenders
27
+ },
28
+ }
@@ -0,0 +1,48 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { slideSourceFiles, toRel } from '../../helpers.mjs'
3
+
4
+ /**
5
+ * Consistency guardrail: a slide is markdown + Miragon/Slidev components, never raw
6
+ * HTML. PascalCase tags (<Card>, <Figure>, …) are components; Slidev/Vue built-ins
7
+ * (<template>, <v-clicks>, …) are allowed; any other lowercase tag (<div>, <span>,
8
+ * <style>, <br>, …) is raw HTML and must become a component or plain markdown.
9
+ * Fenced code blocks and speaker-note comments are exempt.
10
+ */
11
+ const ALLOWED = new Set(['template', 'component', 'slot', 'transition', 'transition-group', 'keep-alive', 'teleport', 'suspense'])
12
+
13
+ /** Replace a matched region with blanks, preserving newlines so line numbers stay true. */
14
+ const blank = (text, re) => text.replace(re, (m) => m.replace(/[^\n]/g, ' '))
15
+
16
+ /**
17
+ * A real tag: `<` (optional `/`) + name, immediately followed by whitespace, `/` or
18
+ * `>`. The lookahead rejects markdown autolinks and prose like `<https://…>`.
19
+ */
20
+ const TAG = /<\/?([A-Za-z][A-Za-z0-9-]*)(?=[\s/>])/g
21
+
22
+ export const noRawHtml = {
23
+ id: 'no-raw-html',
24
+ type: 'source',
25
+ title: 'no raw HTML in slide source — markdown and components only',
26
+ message: 'Slides must use markdown and components only — replace raw HTML with a component or plain markdown',
27
+ meta: { category: 'required', default: 'error' },
28
+ check() {
29
+ const offenders = []
30
+ for (const file of slideSourceFiles()) {
31
+ const rel = toRel(file)
32
+ let src = readFileSync(file, 'utf8')
33
+ src = blank(src, /```[\s\S]*?```/g) // fenced code blocks
34
+ src = blank(src, /<!--[\s\S]*?-->/g) // HTML comments (speaker notes)
35
+ src = blank(src, /`[^`\n]*`/g) // inline code spans
36
+ src.split('\n').forEach((line, i) => {
37
+ TAG.lastIndex = 0
38
+ let m
39
+ while ((m = TAG.exec(line))) {
40
+ const tag = m[1]
41
+ if (/^[A-Z]/.test(tag) || tag.startsWith('v-') || ALLOWED.has(tag)) continue
42
+ offenders.push({ file: rel, line: i + 1, message: `<${tag}> → ${line.trim()}` })
43
+ }
44
+ })
45
+ }
46
+ return offenders
47
+ },
48
+ }
@@ -0,0 +1,78 @@
1
+ import { readFileSync, readdirSync, existsSync } from 'node:fs'
2
+ import { createRequire } from 'node:module'
3
+ import { pathToFileURL } from 'node:url'
4
+ import { dirname, join } from 'node:path'
5
+ import { parseSync } from '@slidev/parser'
6
+ import { repoRoot, slideSourceFiles, toRel } from '../../helpers.mjs'
7
+
8
+ /**
9
+ * The theme's layout archetypes live one-.vue-file-per-layout under the toolkit's
10
+ * `layouts/`. Resolve the INSTALLED `@miragon/slidev-toolkit` from the deck's own
11
+ * root first (a scaffolded deck consumes the toolkit purely from npm and has no
12
+ * `packages/toolkit/` source tree). Fall back to the in-repo source so the
13
+ * template monorepo itself still verifies.
14
+ */
15
+ function layoutsDir() {
16
+ try {
17
+ const from = pathToFileURL(join(repoRoot(), 'package.json'))
18
+ const pkg = createRequire(from).resolve('@miragon/slidev-toolkit/package.json')
19
+ return join(dirname(pkg), 'layouts')
20
+ } catch {
21
+ return join(repoRoot(), 'packages', 'toolkit', 'layouts')
22
+ }
23
+ }
24
+
25
+ /**
26
+ * Slidev built-in layouts allowed even though they are not theme archetypes.
27
+ * Only `default`, which hosts full-bleed component slides (the Agenda). `none` is
28
+ * deliberately NOT here: it renders a slide with no layout wrapper at all.
29
+ */
30
+ const BUILTIN_LAYOUTS = ['default']
31
+
32
+ function sanctionedLayouts() {
33
+ const names = new Set(BUILTIN_LAYOUTS)
34
+ const dir = layoutsDir()
35
+ if (existsSync(dir)) {
36
+ for (const f of readdirSync(dir)) {
37
+ if (f.endsWith('.vue')) names.add(f.slice(0, -'.vue'.length))
38
+ }
39
+ }
40
+ return names
41
+ }
42
+
43
+ function slideFrontmatters(file) {
44
+ const parsed = parseSync(readFileSync(file, 'utf8'), file)
45
+ return parsed.slides.map((s) => ({
46
+ layout: s.frontmatter?.layout,
47
+ src: s.frontmatter?.src,
48
+ start: (s.start ?? 0) + 1,
49
+ }))
50
+ }
51
+
52
+ /**
53
+ * Consistency guardrail: every slide must opt into a layout archetype, so no slide
54
+ * silently falls back to a freehand/default rendering that drifts off the design
55
+ * system. The allowed set is DERIVED from the installed toolkit's `layouts/*.vue`
56
+ * (never hardcoded), plus the built-in `default`. `src:` import stubs are exempt.
57
+ */
58
+ export const sanctionedLayout = {
59
+ id: 'sanctioned-layout',
60
+ type: 'source',
61
+ title: 'every slide declares a sanctioned layout',
62
+ message: 'Every slide must declare a sanctioned layout archetype',
63
+ meta: { category: 'required', default: 'error' },
64
+ check() {
65
+ const allowed = sanctionedLayouts()
66
+ const list = [...allowed].sort().join(', ')
67
+ const offenders = []
68
+ for (const file of slideSourceFiles()) {
69
+ const rel = toRel(file)
70
+ for (const s of slideFrontmatters(file)) {
71
+ if (s.src) continue // import stub — the layout lives in the imported file
72
+ if (!s.layout) offenders.push({ file: rel, line: s.start, message: `no layout: declared. Add one of: ${list}` })
73
+ else if (!allowed.has(s.layout)) offenders.push({ file: rel, line: s.start, message: `layout: ${s.layout} is not a sanctioned archetype. Use one of: ${list}` })
74
+ }
75
+ }
76
+ return offenders
77
+ },
78
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Map each rendered slide (1-based page number) back to the chapter source file it
3
+ * came from, so rendered violations can be attributed to a file and matched by the
4
+ * config's `overrides`/`exceptions` globs. Uses Slidev's own FS loader, which
5
+ * resolves the deck's `src:` imports into a flat slide list with per-slide
6
+ * `source.filepath`. Best-effort: on any failure, callers fall back to the entry.
7
+ */
8
+
9
+ import { load } from '@slidev/parser/fs'
10
+ import { repoRoot, deckEntry, toRel } from './helpers.mjs'
11
+
12
+ /** page number (1-based) → repo-relative source file. */
13
+ export async function slideFileMap() {
14
+ const map = new Map()
15
+ try {
16
+ const data = await load(repoRoot(), deckEntry())
17
+ for (const s of data.slides) {
18
+ const fp = s.source?.filepath
19
+ if (fp) map.set((s.index ?? 0) + 1, toRel(fp))
20
+ }
21
+ } catch {
22
+ // leave empty — caller falls back to the deck entry
23
+ }
24
+ return map
25
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Version + compatibility resolution.
3
+ *
4
+ * The validator declares a peerDependency range on `@miragon/slidev-toolkit`
5
+ * (package.json). The rules encode brand invariants that must match the theme, and
6
+ * `sanctioned-layout` reads the theme's installed layouts — so a validator run must
7
+ * know which toolkit it is validating against and warn when the pair is out of
8
+ * range. A tiny semver satisfies() covers the simple ranges we ship (">=1.15.0 <2").
9
+ */
10
+
11
+ import { readFileSync } from 'node:fs'
12
+ import { createRequire } from 'node:module'
13
+ import { pathToFileURL } from 'node:url'
14
+ import { join, dirname } from 'node:path'
15
+ import { fileURLToPath } from 'node:url'
16
+ import { repoRoot } from './helpers.mjs'
17
+
18
+ const HERE = dirname(fileURLToPath(import.meta.url))
19
+
20
+ /** This validator's own version + declared toolkit peer range. */
21
+ export function selfInfo() {
22
+ const pkg = JSON.parse(readFileSync(join(HERE, '..', 'package.json'), 'utf8'))
23
+ return { version: pkg.version, toolkitRange: pkg.peerDependencies?.['@miragon/slidev-toolkit'] ?? '*' }
24
+ }
25
+
26
+ /** The installed toolkit version resolved from the deck root, or null. */
27
+ export function resolvedToolkitVersion() {
28
+ try {
29
+ const from = pathToFileURL(join(repoRoot(), 'package.json'))
30
+ const p = createRequire(from).resolve('@miragon/slidev-toolkit/package.json')
31
+ return JSON.parse(readFileSync(p, 'utf8')).version
32
+ } catch {
33
+ // In the monorepo the workspace symlink may not be resolvable from a bare cwd;
34
+ // fall back to the in-repo source.
35
+ try {
36
+ return JSON.parse(readFileSync(join(repoRoot(), 'packages', 'toolkit', 'package.json'), 'utf8')).version
37
+ } catch {
38
+ return null
39
+ }
40
+ }
41
+ }
42
+
43
+ function parseVer(v) {
44
+ // Accept partial versions in ranges ("2" → 2.0.0, "1.15" → 1.15.0).
45
+ const m = String(v).match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?/)
46
+ return m ? [Number(m[1]), Number(m[2] || 0), Number(m[3] || 0)] : null
47
+ }
48
+
49
+ function cmp(a, b) {
50
+ for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1
51
+ return 0
52
+ }
53
+
54
+ /** Minimal semver satisfies for space-separated comparator ranges (>=, >, <=, <, =). */
55
+ export function satisfies(version, range) {
56
+ if (!range || range === '*') return true
57
+ const v = parseVer(version)
58
+ if (!v) return false
59
+ return range
60
+ .trim()
61
+ .split(/\s+/)
62
+ .every((token) => {
63
+ const m = token.match(/^(>=|<=|>|<|=)?\s*v?(\d+(?:\.\d+){0,2})/)
64
+ if (!m) return true
65
+ const op = m[1] || '='
66
+ const t = parseVer(m[2])
67
+ const c = cmp(v, t)
68
+ if (op === '>=') return c >= 0
69
+ if (op === '<=') return c <= 0
70
+ if (op === '>') return c > 0
71
+ if (op === '<') return c < 0
72
+ return c === 0
73
+ })
74
+ }
75
+
76
+ /** { ok, installed, range } describing toolkit ↔ validator compatibility. */
77
+ export function compat() {
78
+ const { toolkitRange } = selfInfo()
79
+ const installed = resolvedToolkitVersion()
80
+ return { ok: installed ? satisfies(installed, toolkitRange) : false, installed, range: toolkitRange }
81
+ }