@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/src/cli.js ADDED
@@ -0,0 +1,182 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { spawn } from 'node:child_process'
4
+ import { expect } from 'vitest'
5
+ import { tempDir } from './files.js'
6
+
7
+ // Every rule of `nera check` and `nera validate`, the opt-in ones included,
8
+ // as the starters' scaffold tests list them.
9
+ const STRICT_RULES = Object.freeze([
10
+ 'a11y-html-lang', 'a11y-title', 'a11y-h1', 'a11y-heading-skip', 'a11y-img-alt',
11
+ 'a11y-form-label', 'a11y-link-name', 'a11y-main', 'a11y-skip-link', 'a11y-nav-name',
12
+ 'a11y-duplicate-id', 'a11y-viewport-zoom', 'a11y-link-lang', 'a11y-target-blank',
13
+ 'a11y-reduced-motion', 'privacy-third-party', 'privacy-consent-leak', 'privacy-insecure',
14
+ 'privacy-storage', 'legal-imprint-link', 'legal-privacy-link', 'legal-outdated-law',
15
+ 'seo-jsonld',
16
+ ])
17
+
18
+ /**
19
+ * A `config/validate.yaml` that turns every check rule on at `error` and
20
+ * names the English imprint and privacy pages, for a scaffold test that the
21
+ * site stays clean under the strictest settings. Write it into a site before
22
+ * `expectCleanBuild(site)`.
23
+ */
24
+ export const STRICT_VALIDATE = `rules:
25
+ ${STRICT_RULES.map((rule) => ` ${rule}: error`).join('\n')}
26
+ legal:
27
+ imprint:
28
+ en: /imprint.html
29
+ privacy:
30
+ en: /privacy.html
31
+ `
32
+
33
+ // What a clean build never prints, on stdout or stderr: a warning from core,
34
+ // a plugin or the validator, a deprecation, an error mark, a missing views
35
+ // folder. The strictest of the starters' and themes' patterns.
36
+ const UNCLEAN_LOG = /warn|⚠|❌|deprecat|Views folder not found/i
37
+
38
+ const isDir = (dir) => typeof dir === 'string' && path.isAbsolute(dir) && fs.existsSync(dir) && fs.statSync(dir).isDirectory()
39
+
40
+ /**
41
+ * The bin file of the `@nera-static/nera` installed for `root`: the first
42
+ * `node_modules/@nera-static/nera` from `root` upwards, as Node resolves a
43
+ * package, read without importing it.
44
+ *
45
+ * @param {string} root the dir to resolve from
46
+ * @returns {string} absolute path of the CLI's bin file
47
+ */
48
+ function resolveCli(root) {
49
+ for (let dir = root; ; dir = path.dirname(dir)) {
50
+ const manifest = path.join(dir, 'node_modules', '@nera-static', 'nera', 'package.json')
51
+ if (fs.existsSync(manifest)) {
52
+ const { bin } = JSON.parse(fs.readFileSync(manifest, 'utf-8'))
53
+ const file = typeof bin === 'string' ? bin : bin?.nera
54
+ if (typeof file !== 'string') {
55
+ throw new Error(`nera(): ${manifest} names no "nera" bin. Reinstall it: npm install --save-dev @nera-static/nera`)
56
+ }
57
+ return path.join(path.dirname(manifest), file)
58
+ }
59
+ if (path.dirname(dir) === dir) break
60
+ }
61
+ throw new Error(
62
+ `nera() runs the @nera-static/nera installed for ${root}, and there is none. Add it as a devDependency there (npm install --save-dev @nera-static/nera), or pass the repo root that has it: nera(cwd, args, { root: repoRoot }).`,
63
+ )
64
+ }
65
+
66
+ /**
67
+ * Run the installed `nera` CLI in `cwd`, without colours (`NO_COLOR=1`,
68
+ * `FORCE_COLOR=0`). Never rejects on a non-zero exit: the exit code is part
69
+ * of the result.
70
+ *
71
+ * The CLI is the one installed for `root` (by default `cwd`), found from
72
+ * there upwards as Node resolves a package. Pass the repo root when `cwd`
73
+ * has no `node_modules` of its own, e.g. the temp dir `nera new` runs in.
74
+ *
75
+ * @param {string} cwd absolute dir to run in
76
+ * @param {string[]} args CLI arguments, e.g. `['build', '--check']`
77
+ * @param {{ root?: string }} [options] `root`: the dir whose `@nera-static/nera` runs
78
+ * @returns {Promise<{ code: number, stdout: string, stderr: string }>}
79
+ */
80
+ export async function nera(cwd, args, { root = cwd } = {}) {
81
+ if (!isDir(cwd)) {
82
+ throw new TypeError(`nera(cwd, args) expects cwd as the absolute path of an existing dir, got ${JSON.stringify(cwd)}.`)
83
+ }
84
+ if (!Array.isArray(args) || !args.every((arg) => typeof arg === 'string')) {
85
+ throw new TypeError(`nera(cwd, args) expects args as an array of strings, e.g. ['build', '--check'], got ${JSON.stringify(args)}.`)
86
+ }
87
+ if (!isDir(root)) {
88
+ throw new TypeError(`nera(cwd, args, { root }) expects root as the absolute path of an existing dir, got ${JSON.stringify(root)}. Anchor it on the test file: path.resolve(import.meta.dirname, '..').`)
89
+ }
90
+ const cli = resolveCli(root)
91
+
92
+ return new Promise((resolve, reject) => {
93
+ const child = spawn(process.execPath, [cli, ...args], {
94
+ cwd,
95
+ env: { ...process.env, NO_COLOR: '1', FORCE_COLOR: '0' },
96
+ })
97
+ let stdout = ''
98
+ let stderr = ''
99
+ child.stdout.on('data', (chunk) => (stdout += chunk))
100
+ child.stderr.on('data', (chunk) => (stderr += chunk))
101
+ child.on('error', reject)
102
+ child.on('close', (code) => resolve({ code, stdout, stderr }))
103
+ })
104
+ }
105
+
106
+ const describeRun = (args, cwd, { code, stdout, stderr }) =>
107
+ `nera ${args.join(' ')} in ${cwd} exited ${code}.\n--- stdout\n${stdout}\n--- stderr\n${stderr}`
108
+
109
+ /**
110
+ * Scaffold a site from the starter at `repoRoot` with `nera new --starter
111
+ * <repoRoot> --yes --no-install`, offline, into a fresh temp dir, and link
112
+ * the starter repo's `node_modules` into it, so the site builds with the
113
+ * CLI, theme and plugins the repo installed.
114
+ *
115
+ * Inside a test file the temp dir is removed after the file; from a
116
+ * `globalSetup`, remove `path.dirname(site)` in its teardown.
117
+ *
118
+ * @param {string} repoRoot absolute root of the starter repo (has `node_modules`)
119
+ * @param {string} name the site's folder name
120
+ * @param {string[]} [args] more `nera new` arguments, e.g. `['--name', 'Brot & Zeit', '--lang', 'de']`
121
+ * @returns {Promise<string>} the site root
122
+ */
123
+ export async function scaffoldStarter(repoRoot, name, args = []) {
124
+ if (!isDir(repoRoot)) {
125
+ throw new TypeError(`scaffoldStarter(repoRoot, name) expects repoRoot as the absolute path of the starter repo, got ${JSON.stringify(repoRoot)}. Anchor it on the test file: path.resolve(import.meta.dirname, '..').`)
126
+ }
127
+ if (typeof name !== 'string' || name === '' || /[\\/]/.test(name)) {
128
+ throw new TypeError(`scaffoldStarter(repoRoot, name) expects name as a folder name without path separators, got ${JSON.stringify(name)}.`)
129
+ }
130
+ const modules = path.join(repoRoot, 'node_modules')
131
+ if (!fs.existsSync(modules)) {
132
+ throw new Error(`scaffoldStarter: ${repoRoot} has no node_modules to link into the site. Run npm install there first.`)
133
+ }
134
+
135
+ const dir = tempDir('nera-starter-')
136
+ const newArgs = ['new', name, '--starter', repoRoot, '--yes', '--no-install', ...args]
137
+ const result = await nera(dir, newArgs, { root: repoRoot })
138
+ if (result.code !== 0) {
139
+ // No temp dir left behind, also in a globalSetup.
140
+ fs.rmSync(dir, { recursive: true, force: true })
141
+ throw new Error(`scaffoldStarter: ${describeRun(newArgs, dir, result)}`)
142
+ }
143
+
144
+ const site = path.join(dir, name)
145
+ fs.symlinkSync(modules, path.join(site, 'node_modules'), 'dir')
146
+ return site
147
+ }
148
+
149
+ /**
150
+ * Assert that the site builds, checks and validates clean: `nera build
151
+ * --check` and `nera validate` exit 0 and print "No problems found", their
152
+ * `--json` forms report `{ ok: true, results: [] }`, and no build or check
153
+ * output (stdout and stderr) holds a warning, a deprecation, an error mark
154
+ * or "Views folder not found". Each failure names the command, the site and
155
+ * its full output.
156
+ *
157
+ * @param {string} site absolute site root
158
+ * @param {{ root?: string }} [options] passed to `nera()`
159
+ * @returns {Promise<void>}
160
+ */
161
+ export async function expectCleanBuild(site, options = {}) {
162
+ for (const args of [['build', '--check'], ['validate']]) {
163
+ const result = await nera(site, args, options)
164
+ const out = `${result.stdout}\n${result.stderr}`
165
+ const where = describeRun(args, site, result)
166
+ expect(result.code, where).toBe(0)
167
+ expect(out, where).toContain('No problems found')
168
+ expect(out, `${where}\nThe output holds a warning or an error mark; fix what it names.`).not.toMatch(UNCLEAN_LOG)
169
+ }
170
+
171
+ for (const args of [['build', '--check', '--json'], ['validate', '--json']]) {
172
+ const result = await nera(site, args, options)
173
+ const where = describeRun(args, site, result)
174
+ let json
175
+ try {
176
+ json = JSON.parse(result.stdout)
177
+ } catch (err) {
178
+ throw new Error(`expectCleanBuild: stdout is not JSON (${err.message}). ${where}`, { cause: err })
179
+ }
180
+ expect(json, where).toEqual({ ok: true, results: [] })
181
+ }
182
+ }
package/src/console.js ADDED
@@ -0,0 +1,24 @@
1
+ import { vi } from 'vitest'
2
+
3
+ const METHODS = ['log', 'info', 'warn', 'error', 'debug']
4
+
5
+ /**
6
+ * Silence a `console` method and collect what is written to it.
7
+ *
8
+ * The spy is a `vi.spyOn`, so the preset's `restoreMocks` puts the real
9
+ * method back after each test. Each call's arguments are joined with a space,
10
+ * as the copies in the fleet do (`console.warn('⚠️ x:', message)` becomes
11
+ * `'⚠️ x: <message>'`).
12
+ *
13
+ * @param {'log' | 'info' | 'warn' | 'error' | 'debug'} method the console method to capture
14
+ * @returns {() => string[]} returns the lines written so far
15
+ */
16
+ export function captureConsole(method) {
17
+ if (!METHODS.includes(method)) {
18
+ throw new TypeError(
19
+ `captureConsole(method) expects one of ${METHODS.map((name) => `'${name}'`).join(', ')}, got ${JSON.stringify(method)}.`,
20
+ )
21
+ }
22
+ const spy = vi.spyOn(console, method).mockImplementation(() => {})
23
+ return () => spy.mock.calls.map((call) => call.join(' '))
24
+ }
@@ -0,0 +1,34 @@
1
+ // WCAG 2.2 relative luminance and contrast ratio, as the themes compute them:
2
+ // the current sRGB threshold 0.04045 (the plugins' copies used the older
3
+ // 0.03928; no #rrggbb value lies between the two, so no verdict changes).
4
+
5
+ const HEX = /^#([0-9a-f]{6})$/i
6
+
7
+ /**
8
+ * The relative luminance of a `#rrggbb` colour (WCAG 2.2).
9
+ *
10
+ * @param {string} hex e.g. `'#1a1a1a'`, either case
11
+ * @returns {number} 0 (black) to 1 (white)
12
+ */
13
+ export function luminance(hex) {
14
+ const match = typeof hex === 'string' ? HEX.exec(hex) : null
15
+ if (!match) {
16
+ throw new TypeError(`luminance(hex) expects a #rrggbb colour, got ${JSON.stringify(hex)}. Write short forms and names out, e.g. '#ffffff'.`)
17
+ }
18
+ const [r, g, b] = [0, 2, 4]
19
+ .map((i) => parseInt(match[1].slice(i, i + 2), 16) / 255)
20
+ .map((c) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4))
21
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b
22
+ }
23
+
24
+ /**
25
+ * The contrast ratio of two `#rrggbb` colours, in either order (WCAG 2.2).
26
+ *
27
+ * @param {string} a
28
+ * @param {string} b
29
+ * @returns {number} 1 to 21; text needs 4.5 (AA), large text 3
30
+ */
31
+ export function contrast(a, b) {
32
+ const [light, dark] = [luminance(a), luminance(b)].sort((x, y) => y - x)
33
+ return (light + 0.05) / (dark + 0.05)
34
+ }
package/src/core.js ADDED
@@ -0,0 +1,26 @@
1
+ import { createRequire } from 'node:module'
2
+
3
+ /**
4
+ * The entry file of the `@nera-static/core` the consumer installed.
5
+ *
6
+ * Core is an optional peer dependency, which npm installs next to this
7
+ * package in the consumer's tree, so resolving it from this package's own
8
+ * location (`from`, by default) finds the consumer's core, not a copy of
9
+ * ours. Nothing here imports core at module load: only the helpers that need
10
+ * it call this, so a repo that never builds a site does not need core.
11
+ *
12
+ * @param {string} helpers the helpers that need core, named in the error
13
+ * @param {string | URL} [from] where to resolve `@nera-static/core` from
14
+ * @returns {string} absolute path of core's entry file
15
+ */
16
+ export function resolveCore(helpers, from = import.meta.url) {
17
+ try {
18
+ return createRequire(from).resolve('@nera-static/core')
19
+ } catch (err) {
20
+ if (err.code !== 'MODULE_NOT_FOUND') throw err
21
+ throw new Error(
22
+ `${helpers} @nera-static/core, which is not installed. Add it as a devDependency: npm install --save-dev @nera-static/core`,
23
+ { cause: err },
24
+ )
25
+ }
26
+ }
package/src/files.js ADDED
@@ -0,0 +1,124 @@
1
+ import fs from 'node:fs'
2
+ import os from 'node:os'
3
+ import path from 'node:path'
4
+ import { afterAll } from 'vitest'
5
+ import { isPlainObject } from '@nera-static/plugin-utils/values'
6
+
7
+ // Every dir `tempDir` creates in this test file, removed once the file is
8
+ // done: after all its tests rather than after each, because suites create
9
+ // their site once in `beforeAll` and read it in several tests.
10
+ //
11
+ // The hook is registered when this module is evaluated, because vitest runs
12
+ // an `afterAll` only when it is registered while the test file is collected:
13
+ // one registered later, from a hook or a test, is accepted and silently never
14
+ // runs. Vitest evaluates this module once per test file (also when it is an
15
+ // external dependency in node_modules, as long as `isolate` is on, the
16
+ // default), so every test file gets its own registry. Outside a test file
17
+ // (a `globalSetup`, a plain script) there is no runner to register with, so
18
+ // `afterAll` throws; the dirs are then the caller's to remove.
19
+ const created = []
20
+
21
+ try {
22
+ afterAll(() => {
23
+ for (const dir of created.splice(0)) fs.rmSync(dir, { recursive: true, force: true })
24
+ })
25
+ } catch {
26
+ // Not inside a test file: see above.
27
+ }
28
+
29
+ /**
30
+ * Create a fresh directory under `os.tmpdir()`, removed after the test file.
31
+ *
32
+ * The path is the real one: on macOS the tmpdir sits behind the
33
+ * `/var` -> `/private/var` symlink, and `process.cwd()` inside the dir
34
+ * reports the real path, so paths built from both sides would disagree in
35
+ * `path.relative`.
36
+ *
37
+ * Called outside a test file (a `globalSetup`), the dir is not removed
38
+ * automatically; remove it in the setup's teardown.
39
+ *
40
+ * @param {string} [prefix] start of the dir's name, no path separators
41
+ * @returns {string} the absolute, realpath'd dir
42
+ */
43
+ export function tempDir(prefix = 'nera-test-') {
44
+ if (typeof prefix !== 'string' || prefix === '' || /[\\/]/.test(prefix)) {
45
+ throw new TypeError(
46
+ `tempDir(prefix) expects a non-empty name without path separators, got ${JSON.stringify(prefix)}. Pass e.g. tempDir('nera-sitemap-'); the dir always goes under os.tmpdir().`,
47
+ )
48
+ }
49
+ const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), prefix)))
50
+ created.push(dir)
51
+ return dir
52
+ }
53
+
54
+ /**
55
+ * Write files below `root`, creating parent dirs. A `null` value removes the
56
+ * file or dir at that path instead (no error when it is already gone).
57
+ *
58
+ * @param {string} root absolute dir the paths are relative to
59
+ * @param {Record<string, string | Uint8Array | null>} files relative path -> content
60
+ * @returns {string} `root`, for chaining
61
+ */
62
+ export function writeFiles(root, files) {
63
+ if (typeof root !== 'string' || !path.isAbsolute(root)) {
64
+ throw new TypeError(
65
+ `writeFiles(root, files) expects an absolute root dir, got ${JSON.stringify(root)}. Pass the dir tempDir() returned.`,
66
+ )
67
+ }
68
+ if (!isPlainObject(files)) {
69
+ throw new TypeError(
70
+ 'writeFiles(root, files) expects an object of { \'relative/path\': content | null }, e.g. { \'config/app.yaml\': \'name: Test\\n\' }.',
71
+ )
72
+ }
73
+
74
+ for (const [rel, content] of Object.entries(files)) {
75
+ const file = path.resolve(root, rel)
76
+ const inside = path.relative(root, file)
77
+ if (inside === '' || inside.startsWith('..') || path.isAbsolute(inside)) {
78
+ throw new Error(
79
+ `writeFiles: "${rel}" points outside ${root}. Use a path relative to the root, without "..".`,
80
+ )
81
+ }
82
+ if (content === null) {
83
+ fs.rmSync(file, { recursive: true, force: true })
84
+ continue
85
+ }
86
+ if (typeof content !== 'string' && !(content instanceof Uint8Array)) {
87
+ throw new TypeError(
88
+ `writeFiles: the content of "${rel}" is ${typeof content}. Pass a string, a Buffer, or null to remove the file.`,
89
+ )
90
+ }
91
+ fs.mkdirSync(path.dirname(file), { recursive: true })
92
+ fs.writeFileSync(file, content)
93
+ }
94
+ return root
95
+ }
96
+
97
+ /**
98
+ * Every file below `dir`, recursively, as sorted paths relative to `dir`
99
+ * with `/` separators on every platform.
100
+ *
101
+ * @param {string} dir the dir to walk
102
+ * @param {string[]} [extensions] keep only these extensions (`['.html']`); all files when omitted
103
+ * @returns {string[]}
104
+ */
105
+ export function listFiles(dir, extensions) {
106
+ if (extensions !== undefined && !(Array.isArray(extensions) && extensions.every((ext) => typeof ext === 'string' && ext.startsWith('.')))) {
107
+ throw new TypeError(
108
+ `listFiles(dir, extensions) expects extensions as an array like ['.html', '.css'], got ${JSON.stringify(extensions)}.`,
109
+ )
110
+ }
111
+
112
+ const out = []
113
+ const walk = (current) => {
114
+ for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
115
+ const full = path.join(current, entry.name)
116
+ if (entry.isDirectory()) walk(full)
117
+ else if (!extensions || extensions.includes(path.extname(entry.name))) {
118
+ out.push(path.relative(dir, full).split(path.sep).join('/'))
119
+ }
120
+ }
121
+ }
122
+ walk(dir)
123
+ return out.sort()
124
+ }
package/src/html.js ADDED
@@ -0,0 +1,126 @@
1
+ // Readers for built pages. `countTags`, `tags`, `attr`, `elementByClass` and
2
+ // `stripTags` keep the behaviour of the themes' byte-identical
3
+ // `test/helpers/html.js`: core beautifies its HTML, so attribute-level
4
+ // regular expressions are enough. `$` and `jsonLd` parse with cheerio for
5
+ // what needs a real parser.
6
+ import fs from 'node:fs'
7
+ import path from 'node:path'
8
+ import * as cheerio from 'cheerio'
9
+ import { listFiles } from './files.js'
10
+
11
+ /**
12
+ * Every built page below `publicDir`, sorted by path.
13
+ *
14
+ * @param {string} publicDir the site's `public/` dir
15
+ * @returns {{ file: string, html: string }[]} `file` relative to `publicDir`, `/`-separated
16
+ */
17
+ export function pages(publicDir) {
18
+ return listFiles(publicDir, ['.html']).map((file) => ({
19
+ file,
20
+ html: fs.readFileSync(path.join(publicDir, file), 'utf-8'),
21
+ }))
22
+ }
23
+
24
+ /**
25
+ * One built page's HTML.
26
+ *
27
+ * @param {string} publicDir the site's `public/` dir
28
+ * @param {string} file path relative to `publicDir`
29
+ * @returns {string}
30
+ */
31
+ export function page(publicDir, file) {
32
+ return fs.readFileSync(path.join(publicDir, file), 'utf-8')
33
+ }
34
+
35
+ /**
36
+ * Count the opening tags of `name` (`<h1>`, `<h1 class="…">`, not `<h1x>`).
37
+ *
38
+ * @param {string} html
39
+ * @param {string} name tag name
40
+ * @returns {number}
41
+ */
42
+ export const countTags = (html, name) => (html.match(new RegExp(`<${name}[\\s>]`, 'g')) || []).length
43
+
44
+ /**
45
+ * Every opening tag of `name`, as its attribute string (`' class="a"'`, `''`
46
+ * for a bare tag). Read one attribute from it with `attr`.
47
+ *
48
+ * @param {string} html
49
+ * @param {string} name tag name
50
+ * @returns {string[]}
51
+ */
52
+ export const tags = (html, name) => [...html.matchAll(new RegExp(`<${name}(\\s[^>]*)?>`, 'g'))].map((m) => m[1] || '')
53
+
54
+ /**
55
+ * One attribute's value from an attribute string (from `tags`).
56
+ *
57
+ * @param {string} attrs attribute string
58
+ * @param {string} name attribute name
59
+ * @returns {string | undefined} the value, `undefined` when the attribute is missing
60
+ */
61
+ export function attr(attrs, name) {
62
+ const match = new RegExp(`(?:^|\\s)${name}="([^"]*)"`).exec(attrs)
63
+ return match ? match[1] : undefined
64
+ }
65
+
66
+ /**
67
+ * The inner HTML of the first `tag` element with `className` among its
68
+ * classes, nested elements of the same tag included.
69
+ *
70
+ * @param {string} html
71
+ * @param {string} tag tag name
72
+ * @param {string} className one class name
73
+ * @returns {string | undefined} `undefined` when there is no such element
74
+ */
75
+ export function elementByClass(html, tag, className) {
76
+ const open = new RegExp(`<${tag}\\s[^>]*class="(?:[^"]*\\s)?${className}(?:\\s[^"]*)?"[^>]*>`).exec(html)
77
+ if (!open) return undefined
78
+ let depth = 1
79
+ const re = new RegExp(`<(/?)${tag}[\\s>]`, 'g')
80
+ re.lastIndex = open.index + open[0].length
81
+ let match
82
+ while ((match = re.exec(html))) {
83
+ depth += match[1] ? -1 : 1
84
+ if (depth === 0) return html.slice(open.index + open[0].length, match.index)
85
+ }
86
+ return undefined
87
+ }
88
+
89
+ /**
90
+ * The text of `html`: tags removed, whitespace collapsed to single spaces.
91
+ *
92
+ * @param {string} html
93
+ * @returns {string}
94
+ */
95
+ export const stripTags = (html) => html.replace(/<[^>]*>/g, '').replace(/\s+/g, ' ').trim()
96
+
97
+ /**
98
+ * Parse `html` with cheerio.
99
+ *
100
+ * @param {string} html
101
+ * @returns {import('cheerio').CheerioAPI}
102
+ */
103
+ export const $ = (html) => cheerio.load(html)
104
+
105
+ /**
106
+ * Every `<script type="application/ld+json">` block of `html`, parsed, in
107
+ * document order. A block that is not valid JSON fails with its number and
108
+ * its start.
109
+ *
110
+ * @param {string} html
111
+ * @returns {unknown[]}
112
+ */
113
+ export function jsonLd(html) {
114
+ const doc = cheerio.load(html)
115
+ return doc('script[type="application/ld+json"]').toArray().map((script, index) => {
116
+ const text = doc(script).text()
117
+ try {
118
+ return JSON.parse(text)
119
+ } catch (err) {
120
+ throw new Error(
121
+ `jsonLd: JSON-LD block ${index + 1} is not valid JSON (${err.message}): ${text.trim().slice(0, 80)}`,
122
+ { cause: err },
123
+ )
124
+ }
125
+ })
126
+ }
package/src/index.js ADDED
@@ -0,0 +1,10 @@
1
+ // Entry point `@nera-static/test-utils`: the base, site, HTML and CLI helpers
2
+ // and `publishTemplateSuite`.
3
+ export { tempDir, writeFiles, listFiles } from './files.js'
4
+ export { captureConsole } from './console.js'
5
+ export { parseYaml, loadYaml, frontmatter } from './yaml.js'
6
+ export { folders, makeSite, buildSite, useSiteCwd, readPublic } from './site.js'
7
+ export { pages, page, countTags, tags, attr, elementByClass, stripTags, $, jsonLd } from './html.js'
8
+ export { luminance, contrast } from './contrast.js'
9
+ export { nera, scaffoldStarter, expectCleanBuild, STRICT_VALIDATE } from './cli.js'
10
+ export { publishTemplateSuite } from './publish-template.js'