@nera-static/test-utils 0.0.0-stage → 1.0.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.
- package/CHANGELOG.md +22 -0
- package/LICENSE +21 -0
- package/README.md +479 -2
- package/package.json +71 -5
- package/src/cli.js +182 -0
- package/src/console.js +24 -0
- package/src/contrast.js +34 -0
- package/src/core.js +26 -0
- package/src/files.js +124 -0
- package/src/html.js +126 -0
- package/src/index.js +10 -0
- package/src/publish-template.js +297 -0
- package/src/site.js +179 -0
- package/src/theme/contract.js +399 -0
- package/src/theme/coupling.js +136 -0
- package/src/theme/fixture.js +202 -0
- package/src/theme/index.js +9 -0
- package/src/theme/override.js +114 -0
- package/src/theme/plugin-classes.js +115 -0
- package/src/theme/subdirectory.js +165 -0
- package/src/theme/suite.js +151 -0
- package/src/theme/tokens.js +228 -0
- package/src/vitest.js +49 -0
- package/src/yaml.js +75 -0
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// What the theme build suites share: the wrapper that turns a list of cases
|
|
2
|
+
// into one `it` each (D5), the option checks and the reader of a build's
|
|
3
|
+
// pages that turns a missing build into a problem instead of an error.
|
|
4
|
+
import fs from 'node:fs'
|
|
5
|
+
import path from 'node:path'
|
|
6
|
+
import { describe, expect, it } from 'vitest'
|
|
7
|
+
import { escapeRegExp } from '@nera-static/plugin-utils/html'
|
|
8
|
+
import { isPlainObject } from '@nera-static/plugin-utils/values'
|
|
9
|
+
import { pages } from '../html.js'
|
|
10
|
+
|
|
11
|
+
// Re-exported for the suites, so each imports its helpers from one place.
|
|
12
|
+
export { escapeRegExp, isPlainObject }
|
|
13
|
+
|
|
14
|
+
// A path below a root: not empty, not absolute, no `..` segment.
|
|
15
|
+
export const isRelative = (value) => typeof value === 'string' && value !== '' && !path.isAbsolute(value) && !value.split(/[\\/]/).includes('..')
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Refuse a build output path that is not absolute: it is the `public` of a
|
|
19
|
+
* `buildVariants` result, read with `inject('builds')`.
|
|
20
|
+
*
|
|
21
|
+
* @param {string} option the option as the caller writes it, e.g. `'overrideSuite({ overridden })'`
|
|
22
|
+
* @param {unknown} value
|
|
23
|
+
* @param {string} example e.g. `'builds.default.public'`
|
|
24
|
+
*/
|
|
25
|
+
export function checkPublicOption(option, value, example) {
|
|
26
|
+
if (typeof value !== 'string' || !path.isAbsolute(value)) {
|
|
27
|
+
throw new TypeError(`${option} expects the absolute public/ dir of a build, e.g. ${example} from inject('builds'), got ${JSON.stringify(value)}.`)
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// One class name, as the HTML readers match it.
|
|
32
|
+
export const isClassName = (value) => typeof value === 'string' && /^[\w-]+$/.test(value)
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* A `class="…"` attribute (with its leading whitespace) that holds
|
|
36
|
+
* `className` among its classes.
|
|
37
|
+
*
|
|
38
|
+
* @param {string} className
|
|
39
|
+
* @returns {RegExp}
|
|
40
|
+
*/
|
|
41
|
+
export const classAttr = (className) => new RegExp(`\\sclass="(?:[^"]*\\s)?${escapeRegExp(className)}(?:\\s[^"]*)?"`)
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Refuse a class name the HTML readers cannot match.
|
|
45
|
+
*
|
|
46
|
+
* @param {string} option
|
|
47
|
+
* @param {unknown} value
|
|
48
|
+
*/
|
|
49
|
+
export function checkClassOption(option, value) {
|
|
50
|
+
if (!isClassName(value)) {
|
|
51
|
+
throw new TypeError(`${option} expects one class name such as 'site-footer', got ${JSON.stringify(value)}.`)
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The pages of a build, or the problem that there are none: a build that
|
|
57
|
+
* failed has no public/ dir, and that is a red case, not a crash.
|
|
58
|
+
*
|
|
59
|
+
* @param {string} publicDir
|
|
60
|
+
* @param {string} build names the build in the problem, e.g. `'the build with the override'`
|
|
61
|
+
* @returns {{ built: { file: string, html: string }[], problems: string[] }}
|
|
62
|
+
*/
|
|
63
|
+
export function readPages(publicDir, build) {
|
|
64
|
+
if (!fs.existsSync(publicDir)) {
|
|
65
|
+
return { built: [], problems: [`${publicDir} does not exist: ${build} wrote no public/ dir. Read its build.stdout/build.stderr from inject('builds') for the reason.`] }
|
|
66
|
+
}
|
|
67
|
+
const built = pages(publicDir)
|
|
68
|
+
if (built.length === 0) return { built, problems: [`${publicDir} holds no .html page: ${build} rendered nothing. Check the fixture's pages and their layout.`] }
|
|
69
|
+
return { built, problems: [] }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Refuse a theme repo root that is not an absolute, existing dir.
|
|
74
|
+
*
|
|
75
|
+
* @param {string} suite the suite's name, e.g. `'contractSuite'`
|
|
76
|
+
* @param {unknown} root
|
|
77
|
+
*/
|
|
78
|
+
export function checkRootOption(suite, root) {
|
|
79
|
+
if (typeof root !== 'string' || !path.isAbsolute(root) || !fs.existsSync(root)) {
|
|
80
|
+
throw new TypeError(`${suite}({ root }) expects the absolute path of the theme repo, got ${JSON.stringify(root)}. Anchor it on the test file: path.resolve(import.meta.dirname, '..').`)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Refuse a list option that is not an array of class names (`allowEmpty`
|
|
86
|
+
* false: not empty either).
|
|
87
|
+
*
|
|
88
|
+
* @param {string} option the option as the caller writes it, e.g. `'contractSuite({ classes })'`
|
|
89
|
+
* @param {unknown} value
|
|
90
|
+
* @param {boolean} [allowEmpty]
|
|
91
|
+
*/
|
|
92
|
+
export function checkClassList(option, value, allowEmpty = true) {
|
|
93
|
+
if (!Array.isArray(value) || (!allowEmpty && value.length === 0) || !value.every(isClassName)) {
|
|
94
|
+
throw new TypeError(`${option} expects ${allowEmpty ? 'an' : 'a non-empty'} array of class names such as ['site-footer', 'post__title'], got ${JSON.stringify(value)}.`)
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* The text of a file the suite reads, or the problem that it is missing:
|
|
100
|
+
* a red case, not a crash.
|
|
101
|
+
*
|
|
102
|
+
* @param {string} file absolute path
|
|
103
|
+
* @param {string} fix what to do when it is missing, e.g. `'Pass the theme\'s stylesheet as { css }.'`
|
|
104
|
+
* @returns {{ text: string, problems: string[] }}
|
|
105
|
+
*/
|
|
106
|
+
export const readText = (file, fix) =>
|
|
107
|
+
fs.existsSync(file) ? { text: fs.readFileSync(file, 'utf-8'), problems: [] } : { text: '', problems: [`${file} does not exist. ${fix}`] }
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* A class name written in Pug source: after `.` (the `.name` shorthand) or
|
|
111
|
+
* inside a quoted string, not followed by more of a name.
|
|
112
|
+
*
|
|
113
|
+
* @param {string} className
|
|
114
|
+
* @returns {RegExp}
|
|
115
|
+
*/
|
|
116
|
+
export const classInSource = (className) => new RegExp(`(\\.|'|")${escapeRegExp(className)}(?![\\w-])`)
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* A class selector `.name` in a stylesheet, not followed by more of a name.
|
|
120
|
+
*
|
|
121
|
+
* @param {string} className
|
|
122
|
+
* @returns {RegExp}
|
|
123
|
+
*/
|
|
124
|
+
export const classSelector = (className) => new RegExp(`\\.${escapeRegExp(className)}(?![\\w-])`)
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Where the first element with `className` among its classes starts in
|
|
128
|
+
* `html`, or -1.
|
|
129
|
+
*
|
|
130
|
+
* @param {string} html
|
|
131
|
+
* @param {string} className
|
|
132
|
+
* @returns {number}
|
|
133
|
+
*/
|
|
134
|
+
export const classIndex = (html, className) => html.search(classAttr(className))
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Register `cases` as one `it` per case inside `describe(title)`, each
|
|
138
|
+
* expecting its `check()` to find no problem.
|
|
139
|
+
*
|
|
140
|
+
* @param {string} title
|
|
141
|
+
* @param {{ name: string, check: () => string[] }[]} cases
|
|
142
|
+
*/
|
|
143
|
+
export function registerCases(title, cases) {
|
|
144
|
+
describe(title, () => {
|
|
145
|
+
for (const { name, check } of cases) {
|
|
146
|
+
it(name, () => {
|
|
147
|
+
expect(check()).toEqual([])
|
|
148
|
+
})
|
|
149
|
+
}
|
|
150
|
+
})
|
|
151
|
+
}
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
// §S7 "Tokens" and §S2.5 of a theme: the defaults of config/theme.yaml are
|
|
2
|
+
// emitted as custom properties in one `:root` rule on every page, a site
|
|
3
|
+
// override changes only its token, a value with `}` is not emitted, and the
|
|
4
|
+
// theme's stylesheet reads every token with the same default and applies
|
|
5
|
+
// what it reads. Modelled on the five themes' `test/tokens.test.js`.
|
|
6
|
+
import fs from 'node:fs'
|
|
7
|
+
import path from 'node:path'
|
|
8
|
+
import { loadYaml } from '../yaml.js'
|
|
9
|
+
import { checkPublicOption, checkRootOption, escapeRegExp, isPlainObject, isRelative, readPages, readText, registerCases } from './suite.js'
|
|
10
|
+
|
|
11
|
+
const isScalar = (value) => typeof value === 'string' || typeof value === 'number'
|
|
12
|
+
// `group.name` of a token, as config/theme.yaml nests it under `tokens:`.
|
|
13
|
+
const TOKEN = /^[a-z][\w-]*\.[a-z][\w-]*$/i
|
|
14
|
+
|
|
15
|
+
// The first <style> block of a page: core's inline token rule.
|
|
16
|
+
const styleOf = (html) => (/<style>([\s\S]*?)<\/style>/.exec(html) || [])[1] || ''
|
|
17
|
+
|
|
18
|
+
function checkToken(option, value, needsBrace) {
|
|
19
|
+
if (!isPlainObject(value) || typeof value.token !== 'string' || !TOKEN.test(value.token) || !isScalar(value.value) || (needsBrace && !String(value.value).includes('}'))) {
|
|
20
|
+
const example = needsBrace ? '{ token: \'color.injected\', value: \'red}body{display:none\' }' : '{ token: \'color.accent\', value: \'#006400\' }'
|
|
21
|
+
throw new TypeError(`tokensSuite({ ${option} }) expects the token the overrides variant sets as { token: 'group.name', value }${needsBrace ? ' with a } in its value' : ''}, e.g. ${example}, got ${JSON.stringify(value)}.`)
|
|
22
|
+
}
|
|
23
|
+
const [group, name] = value.token.split('.')
|
|
24
|
+
return { group, name, value: String(value.value) }
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function normalize({ root, defaults, overrides, prefix, override, injected, config = 'config/theme.yaml', css = 'assets/css/theme.css', ignoreLocals = ['--nera-'] } = {}) {
|
|
28
|
+
checkRootOption('tokensSuite', root)
|
|
29
|
+
checkPublicOption('tokensSuite({ defaults })', defaults, 'builds.default.public')
|
|
30
|
+
checkPublicOption('tokensSuite({ overrides })', overrides, 'builds.overrides.public')
|
|
31
|
+
if (typeof prefix !== 'string' || !/^--[a-z][a-z0-9]*(-[a-z0-9]+)*$/.test(prefix)) {
|
|
32
|
+
throw new TypeError(`tokensSuite({ prefix }) expects the custom-property prefix of the public tokens without a trailing dash, e.g. '--theme', got ${JSON.stringify(prefix)}.`)
|
|
33
|
+
}
|
|
34
|
+
if (!isRelative(config)) throw new TypeError(`tokensSuite({ config }) expects the theme's config file relative to root, e.g. 'config/theme.yaml', got ${JSON.stringify(config)}.`)
|
|
35
|
+
if (css !== null && !isRelative(css)) throw new TypeError(`tokensSuite({ css }) expects the theme's stylesheet relative to root, e.g. 'assets/css/theme.css', or null to skip the stylesheet cases, got ${JSON.stringify(css)}.`)
|
|
36
|
+
if (!Array.isArray(ignoreLocals) || !ignoreLocals.every((p) => typeof p === 'string' && p.startsWith('--'))) {
|
|
37
|
+
throw new TypeError(`tokensSuite({ ignoreLocals }) expects custom-property prefixes such as ['--nera-'], got ${JSON.stringify(ignoreLocals)}.`)
|
|
38
|
+
}
|
|
39
|
+
const configFile = path.join(root, config)
|
|
40
|
+
if (!fs.existsSync(configFile)) throw new Error(`tokensSuite: ${configFile} does not exist. Pass the theme's config file as { config }, relative to ${root}.`)
|
|
41
|
+
const tokens = loadYaml(configFile)?.tokens
|
|
42
|
+
if (!isPlainObject(tokens) || !Object.values(tokens).every(isPlainObject)) {
|
|
43
|
+
throw new Error(`tokensSuite: ${configFile} has no tokens: mapping of groups (tokens: { color: { accent: '#…' } }). The suite reads the defaults from it.`)
|
|
44
|
+
}
|
|
45
|
+
const property = (group, name) => `${prefix}-${group}-${name.replace(/_/g, '-')}`
|
|
46
|
+
return {
|
|
47
|
+
root,
|
|
48
|
+
defaults,
|
|
49
|
+
overrides,
|
|
50
|
+
prefix,
|
|
51
|
+
config,
|
|
52
|
+
css: css === null ? null : path.join(root, css),
|
|
53
|
+
cssName: css,
|
|
54
|
+
ignoreLocals,
|
|
55
|
+
override: checkToken('override', override, false),
|
|
56
|
+
injected: injected === undefined ? undefined : checkToken('injected', injected, true),
|
|
57
|
+
property,
|
|
58
|
+
tokens: Object.entries(tokens).flatMap(([group, values]) => Object.entries(values).map(([name, value]) => ({ group, name, value, property: property(group, name) }))),
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// `<property>: <value>;` in a style rule.
|
|
63
|
+
const declaration = (property, value) => new RegExp(`${escapeRegExp(property)}:\\s*${escapeRegExp(String(value))};`)
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Case: config/theme.yaml holds scalar defaults, the overridden token among
|
|
67
|
+
* them with a default other than the override, and not the injected one.
|
|
68
|
+
*/
|
|
69
|
+
function readsDefaults({ config, tokens, override, injected, property }) {
|
|
70
|
+
const problems = []
|
|
71
|
+
if (tokens.length === 0) problems.push(`${config} defines no token. Add the theme's defaults under tokens:.`)
|
|
72
|
+
for (const { property: prop, value } of tokens) {
|
|
73
|
+
if (!isScalar(value)) problems.push(`${config}: ${prop} has the default ${JSON.stringify(value)}; a token's default is a string or a number.`)
|
|
74
|
+
}
|
|
75
|
+
const accent = tokens.find((t) => t.group === override.group && t.name === override.name)
|
|
76
|
+
if (accent === undefined) problems.push(`${config} has no tokens.${override.group}.${override.name}, the token the overrides variant changes. Override a token the theme defines.`)
|
|
77
|
+
else if (String(accent.value) === override.value) problems.push(`${config}: ${property(override.group, override.name)} defaults to ${override.value}, the override's own value, so the override proves nothing. Override it with another value.`)
|
|
78
|
+
if (injected && tokens.some((t) => t.group === injected.group && t.name === injected.name)) {
|
|
79
|
+
problems.push(`${config} defines tokens.${injected.group}.${injected.name}, the token the overrides variant injects. Inject a site token the theme does not define.`)
|
|
80
|
+
}
|
|
81
|
+
return problems
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Problems with one page's token rule: not a single leading `:root` rule,
|
|
86
|
+
* or a token not at `expected(token)`.
|
|
87
|
+
*/
|
|
88
|
+
function ruleProblems(file, html, tokens, expected) {
|
|
89
|
+
const style = styleOf(html)
|
|
90
|
+
if (!/^\s*:root\s*\{/.test(style)) return [`${file}: the first <style> is not a :root rule (${JSON.stringify(style.slice(0, 60))}). The theme's layout must emit the tokens as :root { … } in the head.`]
|
|
91
|
+
const wrong = tokens.filter((t) => !declaration(t.property, expected(t)).test(style)).map((t) => `${t.property}: ${expected(t)}`)
|
|
92
|
+
return wrong.length === 0 ? [] : [`${file}: the :root rule lacks ${wrong.join('; ')}. Emit every token of config/theme.yaml, a site value over the default.`]
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Case: every page of the default build emits every default token.
|
|
97
|
+
*/
|
|
98
|
+
function emitsDefaults({ defaults, tokens }) {
|
|
99
|
+
const { built, problems } = readPages(defaults, 'the default build')
|
|
100
|
+
for (const { file, html } of built) problems.push(...ruleProblems(file, html, tokens, (t) => t.value))
|
|
101
|
+
return problems
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Case: every page of the overrides build emits the override, not its
|
|
106
|
+
* default, and every other token at its default.
|
|
107
|
+
*/
|
|
108
|
+
function emitsOverride({ overrides, tokens, override, property }) {
|
|
109
|
+
const { built, problems } = readPages(overrides, 'the overrides build')
|
|
110
|
+
const prop = property(override.group, override.name)
|
|
111
|
+
const isOverridden = (t) => t.property === prop
|
|
112
|
+
const fallback = tokens.find(isOverridden)
|
|
113
|
+
for (const { file, html } of built) {
|
|
114
|
+
problems.push(...ruleProblems(file, html, tokens, (t) => (isOverridden(t) ? override.value : t.value)))
|
|
115
|
+
if (fallback && declaration(prop, fallback.value).test(styleOf(html))) {
|
|
116
|
+
problems.push(`${file}: the :root rule still declares ${prop}: ${fallback.value}, the default, next to the override. A site value replaces the default.`)
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return problems
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Case: no page of the overrides build emits the injected token or its
|
|
124
|
+
* value, and the token rule holds one `{` and one `}`.
|
|
125
|
+
*/
|
|
126
|
+
function dropsInjected({ overrides, injected, property }) {
|
|
127
|
+
const { built, problems } = readPages(overrides, 'the overrides build')
|
|
128
|
+
const prop = property(injected.group, injected.name)
|
|
129
|
+
for (const { file, html } of built) {
|
|
130
|
+
if (html.includes(prop) || html.includes(injected.value)) {
|
|
131
|
+
problems.push(`${file}: emits ${prop} or its value ${JSON.stringify(injected.value)}. Drop a token value that contains } before it reaches the :root rule.`)
|
|
132
|
+
}
|
|
133
|
+
const braces = (styleOf(html).match(/[{}]/g) || []).join('')
|
|
134
|
+
if (braces !== '{}') problems.push(`${file}: the :root rule holds the braces "${braces}", expected one { and one }. A token value must not open or close a rule.`)
|
|
135
|
+
}
|
|
136
|
+
return problems
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const readCss = ({ css, root }) => readText(css, `Pass the theme's stylesheet as { css } relative to ${root}, or css: null to skip the stylesheet cases.`)
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Case: the stylesheet reads every token as `var(<prop>, <its default>)`,
|
|
143
|
+
* at least once, and reads no other property of the prefix.
|
|
144
|
+
*/
|
|
145
|
+
function readsEveryToken(opts) {
|
|
146
|
+
const { text, problems } = readCss(opts)
|
|
147
|
+
if (problems.length > 0) return problems
|
|
148
|
+
const known = new Set(opts.tokens.map((t) => t.property))
|
|
149
|
+
for (const { property, value } of opts.tokens) {
|
|
150
|
+
const uses = [...text.matchAll(new RegExp(`var\\(${escapeRegExp(property)}(,\\s*([^;]*?))?\\)(?=[;\\s/,)])`, 'g'))]
|
|
151
|
+
if (uses.length === 0) problems.push(`${opts.cssName} never reads ${property}. Use the token, or remove it from ${opts.config}.`)
|
|
152
|
+
for (const use of uses) {
|
|
153
|
+
if (use[2] !== String(value)) problems.push(`${opts.cssName}: ${use[0]} falls back to ${JSON.stringify(use[2] ?? null)}, expected the default from ${opts.config}: var(${property}, ${value}).`)
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
for (const [, prop] of text.matchAll(new RegExp(`var\\((${escapeRegExp(opts.prefix)}-[\\w-]+)`, 'g'))) {
|
|
157
|
+
if (!known.has(prop)) problems.push(`${opts.cssName} reads ${prop}, which ${opts.config} does not define. Add it under tokens:, or use a property of the theme's own name.`)
|
|
158
|
+
}
|
|
159
|
+
return problems
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Case: every local custom property that reads a token is applied
|
|
164
|
+
* somewhere in the stylesheet (`ignoreLocals` prefixes excepted: a
|
|
165
|
+
* plugin's `--nera-*` property is applied by the plugin's own CSS).
|
|
166
|
+
*/
|
|
167
|
+
function appliesEveryLocal(opts) {
|
|
168
|
+
const { text, problems } = readCss(opts)
|
|
169
|
+
if (problems.length > 0) return problems
|
|
170
|
+
for (const [, local, token] of text.matchAll(new RegExp(`(--[\\w-]+):\\s*var\\((${escapeRegExp(opts.prefix)}-[\\w-]+)`, 'g'))) {
|
|
171
|
+
if (opts.ignoreLocals.some((p) => local.startsWith(p))) continue
|
|
172
|
+
if (!text.includes(`var(${local})`)) problems.push(`${opts.cssName}: ${local} reads ${token} but nothing applies var(${local}). Use it, or drop it.`)
|
|
173
|
+
}
|
|
174
|
+
return problems
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* The cases `tokensSuite` registers, each a name and a `check()` that
|
|
179
|
+
* returns the problems it found (empty when the case holds).
|
|
180
|
+
*
|
|
181
|
+
* @param {object} options see `tokensSuite`
|
|
182
|
+
* @returns {{ name: string, check: () => string[] }[]}
|
|
183
|
+
*/
|
|
184
|
+
export function tokensCases(options) {
|
|
185
|
+
const opts = normalize(options)
|
|
186
|
+
const cases = [
|
|
187
|
+
{ name: `reads its defaults from ${opts.config}`, check: () => readsDefaults(opts) },
|
|
188
|
+
{ name: 'emits every default token in one :root rule on every page', check: () => emitsDefaults(opts) },
|
|
189
|
+
{ name: `emits the site's ${opts.override.group}.${opts.override.name} and keeps every other token at its default`, check: () => emitsOverride(opts) },
|
|
190
|
+
]
|
|
191
|
+
if (opts.injected) cases.push({ name: 'does not emit a value containing }', check: () => dropsInjected(opts) })
|
|
192
|
+
if (opts.css !== null) {
|
|
193
|
+
cases.push(
|
|
194
|
+
{ name: `${opts.cssName} reads every token as var(${opts.prefix}-…, <the same default>)`, check: () => readsEveryToken(opts) },
|
|
195
|
+
{ name: `${opts.cssName} applies every local property that reads a token`, check: () => appliesEveryLocal(opts) },
|
|
196
|
+
)
|
|
197
|
+
}
|
|
198
|
+
return cases
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Register the "Tokens" cases of a theme (§S7, §S2.5) in a
|
|
203
|
+
* `describe('Tokens')`, one `it` each, on builds made by
|
|
204
|
+
* `buildVariants`/`themeGlobalSetup`. The defaults are read from the
|
|
205
|
+
* theme's `config/theme.yaml` (core's YAML parser).
|
|
206
|
+
*
|
|
207
|
+
* Cases: reads its defaults from the config (the overridden token among
|
|
208
|
+
* them, with another default; the injected one not); emits every default
|
|
209
|
+
* in one `:root` rule on every page of `defaults`; emits the override and
|
|
210
|
+
* every other default on every page of `overrides`; with `injected`, does
|
|
211
|
+
* not emit a value containing `}`; unless `css: null`, the stylesheet reads
|
|
212
|
+
* every token as `var(<prop>, <its default>)` and no unknown one, and
|
|
213
|
+
* applies every local property that reads a token.
|
|
214
|
+
*
|
|
215
|
+
* @param {object} options
|
|
216
|
+
* @param {string} options.root absolute root of the theme repo
|
|
217
|
+
* @param {string} options.defaults public/ dir of the fixture as committed (`builds.default.public`)
|
|
218
|
+
* @param {string} options.overrides public/ dir of the variant that overrides tokens (`builds.overrides.public`)
|
|
219
|
+
* @param {string} options.prefix the tokens' custom-property prefix, e.g. `'--theme'` (`<prefix>-<group>-<name>`)
|
|
220
|
+
* @param {{ token: string, value: string }} options.override the token the variant changes, e.g. `{ token: 'color.accent', value: '#006400' }`
|
|
221
|
+
* @param {{ token: string, value: string }} [options.injected] a site token whose value holds `}`, which must not be emitted
|
|
222
|
+
* @param {string} [options.config] the theme's config relative to root, default `'config/theme.yaml'`
|
|
223
|
+
* @param {string | null} [options.css] the theme's stylesheet relative to root, default `'assets/css/theme.css'`; `null` skips its two cases
|
|
224
|
+
* @param {string[]} [options.ignoreLocals] local property prefixes the "applies" case skips, default `['--nera-']`
|
|
225
|
+
*/
|
|
226
|
+
export function tokensSuite(options) {
|
|
227
|
+
registerCases('Tokens', tokensCases(options))
|
|
228
|
+
}
|
package/src/vitest.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { isPlainObject } from '@nera-static/plugin-utils/values'
|
|
2
|
+
import { defineConfig } from 'vitest/config'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The canonical `test` block every Nera repo uses (`3-tests.md` §4.2).
|
|
6
|
+
* Frozen so a caller cannot change the preset for every later config.
|
|
7
|
+
*/
|
|
8
|
+
export const CANONICAL_TEST = Object.freeze({
|
|
9
|
+
include: Object.freeze(['test/**/*.test.js']),
|
|
10
|
+
environment: 'node',
|
|
11
|
+
restoreMocks: true,
|
|
12
|
+
unstubEnvs: true,
|
|
13
|
+
unstubGlobals: true,
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
// What a value that is not a plain object is, for the error message.
|
|
17
|
+
function kindOf(value) {
|
|
18
|
+
if (value === null) return 'null'
|
|
19
|
+
if (Array.isArray(value)) return 'an array'
|
|
20
|
+
if (typeof value === 'object') return `a ${value.constructor?.name ?? 'object'} instance`
|
|
21
|
+
return typeof value
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Build a repo's vitest config from the canonical `test` block.
|
|
26
|
+
*
|
|
27
|
+
* Keys in `test` are merged over the canonical ones (shallow: a key you pass
|
|
28
|
+
* replaces the canonical value, e.g. your own `include` array). Only add what
|
|
29
|
+
* the repo really needs (`testTimeout`, `hookTimeout`, `globalSetup`,
|
|
30
|
+
* `isolate`) and say why in a comment next to it.
|
|
31
|
+
*
|
|
32
|
+
* @param {object} [test] vitest `test` options to add or override
|
|
33
|
+
* @returns {import('vitest/config').UserConfig}
|
|
34
|
+
*/
|
|
35
|
+
export function neraConfig(test = {}) {
|
|
36
|
+
if (!isPlainObject(test)) {
|
|
37
|
+
throw new TypeError(
|
|
38
|
+
`neraConfig(test) expects a plain object of vitest "test" options, got ${kindOf(test)}. Pass e.g. neraConfig({ testTimeout: 30000 }) or call neraConfig() with no argument.`,
|
|
39
|
+
)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
return defineConfig({
|
|
43
|
+
test: {
|
|
44
|
+
...CANONICAL_TEST,
|
|
45
|
+
include: [...CANONICAL_TEST.include],
|
|
46
|
+
...test,
|
|
47
|
+
},
|
|
48
|
+
})
|
|
49
|
+
}
|
package/src/yaml.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import { createRequire } from 'node:module'
|
|
3
|
+
import { FRONTMATTER_OPTIONS, splitFrontmatter } from '@nera-static/plugin-utils/frontmatter'
|
|
4
|
+
import { resolveCore } from './core.js'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Load the `yaml` package core itself depends on, resolved from core's own
|
|
8
|
+
* location, so a test parses exactly as the build does and the consumer needs
|
|
9
|
+
* no `yaml` dependency of its own.
|
|
10
|
+
*
|
|
11
|
+
* Core is resolved from `from`, by default this package's own location: core
|
|
12
|
+
* is a peer dependency, which npm installs next to this package in the
|
|
13
|
+
* consumer's tree, so that is the consumer's core, not a copy of ours.
|
|
14
|
+
*
|
|
15
|
+
* @param {string | URL} [from] where to resolve `@nera-static/core` from
|
|
16
|
+
* @returns {typeof import('yaml')}
|
|
17
|
+
*/
|
|
18
|
+
export function loadCoreYaml(from = import.meta.url) {
|
|
19
|
+
const corePath = resolveCore('parseYaml, loadYaml and frontmatter parse with the yaml package of', from)
|
|
20
|
+
return createRequire(corePath)('yaml')
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
let yaml
|
|
24
|
+
|
|
25
|
+
// Resolved on the first call, so importing the package never needs core.
|
|
26
|
+
const coreYaml = () => (yaml ??= loadCoreYaml())
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Parse YAML text the way core reads `config/*.yaml` (yaml's defaults).
|
|
30
|
+
*
|
|
31
|
+
* @param {string} text YAML source
|
|
32
|
+
* @returns {unknown} the parsed value (`null` for an empty document)
|
|
33
|
+
*/
|
|
34
|
+
export function parseYaml(text) {
|
|
35
|
+
if (typeof text !== 'string') {
|
|
36
|
+
throw new TypeError(`parseYaml(text) expects a string, got ${typeof text}. To read a file, use loadYaml(file).`)
|
|
37
|
+
}
|
|
38
|
+
return coreYaml().parse(text)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Read and parse a YAML file. A parse error names the file.
|
|
43
|
+
*
|
|
44
|
+
* @param {string} file path of the YAML file
|
|
45
|
+
* @returns {unknown} the parsed value (`null` for an empty file)
|
|
46
|
+
*/
|
|
47
|
+
export function loadYaml(file) {
|
|
48
|
+
const text = fs.readFileSync(file, 'utf-8')
|
|
49
|
+
try {
|
|
50
|
+
return parseYaml(text)
|
|
51
|
+
} catch (err) {
|
|
52
|
+
throw new Error(`loadYaml: ${file} is not valid YAML: ${err.message}`, { cause: err })
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* A page's frontmatter, found and parsed as core does: the block between a
|
|
58
|
+
* `---` first line and the next `---` line (or the end of the file), with
|
|
59
|
+
* core's options, so YAML dates become Date objects. Fence rule and options
|
|
60
|
+
* are plugin-utils' (`splitFrontmatter`, `FRONTMATTER_OPTIONS`), the parser
|
|
61
|
+
* is core's own `yaml`.
|
|
62
|
+
*
|
|
63
|
+
* @param {string} file path of the Markdown page
|
|
64
|
+
* @returns {Record<string, unknown>} the frontmatter, `{}` when the page has none
|
|
65
|
+
*/
|
|
66
|
+
export function frontmatter(file) {
|
|
67
|
+
const split = splitFrontmatter(fs.readFileSync(file, 'utf-8'))
|
|
68
|
+
if (!split) return {}
|
|
69
|
+
|
|
70
|
+
try {
|
|
71
|
+
return coreYaml().parse(split.yamlText, FRONTMATTER_OPTIONS) || {}
|
|
72
|
+
} catch (err) {
|
|
73
|
+
throw new Error(`frontmatter: the frontmatter of ${file} is not valid YAML: ${err.message}`, { cause: err })
|
|
74
|
+
}
|
|
75
|
+
}
|