@nera-static/plugin-utils 1.7.0 → 1.9.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/dates.js ADDED
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Frontmatter dates, shared by every Nera plugin and tool
3
+ * (`@nera-static/plugin-utils/dates`): parsing, the W3C format, the decided
4
+ * key lists and a date comparator.
5
+ *
6
+ * Nothing here reads the build machine's time zone: a time without an
7
+ * offset is read as UTC, as YAML reads an unquoted timestamp, so the same
8
+ * site gives the same dates and the same order on every machine.
9
+ */
10
+
11
+ // `YYYY-MM-DD`, optionally `T` or a space, `hh:mm`, optional `:ss` and
12
+ // fraction, and an optional `Z` or `±hh:mm` offset.
13
+ const DATE_STRING = new RegExp(
14
+ '^(\\d{4})-(\\d{2})-(\\d{2})' +
15
+ '(?:[T ](\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d+))?)?\\s*(Z|[+-]\\d{2}:\\d{2})?)?$'
16
+ )
17
+
18
+ const MINUTE = 60 * 1000
19
+
20
+ /**
21
+ * Frontmatter keys tried for a page's published date, in order. `createdAt`
22
+ * is left out on purpose: core fills it from the file's birth time when the
23
+ * frontmatter has no date, and CI stamps every file the same.
24
+ */
25
+ export const PUBLISHED_KEYS = Object.freeze(['date', 'datePublished', 'published'])
26
+
27
+ /** Frontmatter keys tried for a page's updated date, in order. */
28
+ export const UPDATED_KEYS = Object.freeze(['updated', 'updatedAt', 'lastmod', 'dateModified'])
29
+
30
+ const KEYS = { published: PUBLISHED_KEYS, updated: UPDATED_KEYS }
31
+
32
+ const validDate = (date) => (Number.isNaN(date.getTime()) ? null : date)
33
+
34
+ // The offset `±hh:mm` in milliseconds, or null when it is out of range.
35
+ function offsetOf(zone) {
36
+ if (zone === undefined || zone === 'Z') return 0
37
+ const hours = Number(zone.slice(1, 3))
38
+ const minutes = Number(zone.slice(4, 6))
39
+ if (hours > 23 || minutes > 59) return null
40
+ return (zone[0] === '-' ? -1 : 1) * (hours * 60 + minutes) * MINUTE
41
+ }
42
+
43
+ /**
44
+ * A frontmatter value as a `Date`, or `null` when it is not a usable date.
45
+ *
46
+ * Accepts a valid `Date` (core parses an unquoted frontmatter date into one)
47
+ * or a string `YYYY-MM-DD`, optionally followed by `T` or a space and
48
+ * `hh:mm[:ss[.fraction]]` with an optional `Z` or `±hh:mm` offset
49
+ * (surrounding whitespace is ignored). A string without an offset is read as
50
+ * UTC. A day or time that does not exist (`2026-02-30`, `24:00`, `09:60`) is
51
+ * not usable; neither is any other type or form (`1.10.2026`, a number).
52
+ *
53
+ * @param {unknown} value
54
+ * @returns {Date | null}
55
+ */
56
+ export function toDate(value) {
57
+ if (value instanceof Date) return validDate(value)
58
+ if (typeof value !== 'string') return null
59
+ const match = DATE_STRING.exec(value.trim())
60
+ if (!match) return null
61
+ const [, year, month, day, hour = '0', minute = '0', second = '0', fraction = '', zone] = match
62
+ const parts = [year, month, day, hour, minute, second].map(Number)
63
+ const wall = new Date(Date.UTC(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]))
64
+ // `Date.UTC` rolls an impossible day or time over (Feb 30 into March,
65
+ // 24:00 into the next day); a value that does not read back is refused.
66
+ const exists = wall.getUTCFullYear() === parts[0]
67
+ && wall.getUTCMonth() === parts[1] - 1
68
+ && wall.getUTCDate() === parts[2]
69
+ && wall.getUTCHours() === parts[3]
70
+ && wall.getUTCMinutes() === parts[4]
71
+ && wall.getUTCSeconds() === parts[5]
72
+ const offset = offsetOf(zone)
73
+ if (!exists || offset === null) return null
74
+ const milliseconds = Number(fraction.padEnd(3, '0').slice(0, 3))
75
+ return validDate(new Date(wall.getTime() + milliseconds - offset))
76
+ }
77
+
78
+ /**
79
+ * A date in W3C Datetime form, in UTC: `YYYY-MM-DD` for UTC midnight (an
80
+ * unquoted `2026-10-01`), else `YYYY-MM-DDThh:mm:ssZ` without milliseconds.
81
+ * Accepts whatever `toDate` accepts; `null` when that is not a usable date.
82
+ *
83
+ * @param {unknown} value
84
+ * @returns {string | null}
85
+ */
86
+ export function formatW3C(value) {
87
+ const date = toDate(value)
88
+ if (!date) return null
89
+ const iso = date.toISOString()
90
+ if (iso.endsWith('T00:00:00.000Z')) return iso.slice(0, 10)
91
+ return iso.replace(/\.\d{3}Z$/, 'Z')
92
+ }
93
+
94
+ // A rejected value as a warning shows it.
95
+ function show(value) {
96
+ if (value instanceof Date) return 'an invalid date'
97
+ return JSON.stringify(value) ?? String(value)
98
+ }
99
+
100
+ const isAbsent = (value) => value === undefined || value === null
101
+ || (typeof value === 'string' && value.trim() === '')
102
+
103
+ /**
104
+ * A page's published or updated date: the first key of `PUBLISHED_KEYS`
105
+ * resp. `UPDATED_KEYS` whose value is a usable date (see `toDate`), or
106
+ * `null` when none is. A present value that is not a date is skipped with
107
+ * one warning (`<href>: ignoring <key> <value>, …`) and the next key is
108
+ * tried; an absent, `null` or blank value is skipped silently. Keys after
109
+ * the first usable one are not read.
110
+ *
111
+ * @param {object | undefined | null} meta the page's `meta`
112
+ * @param {'published' | 'updated'} kind
113
+ * @param {{ warn?: (message: string) => void }} [options]
114
+ * @returns {Date | null}
115
+ * @throws {TypeError} when `kind` is neither `'published'` nor `'updated'`
116
+ */
117
+ export function pageDate(meta, kind, { warn = console.warn } = {}) {
118
+ if (!Object.hasOwn(KEYS, kind)) {
119
+ throw new TypeError(`pageDate: kind must be 'published' or 'updated', got ${show(kind)}`)
120
+ }
121
+ for (const key of KEYS[kind]) {
122
+ const value = meta?.[key]
123
+ if (isAbsent(value)) continue
124
+ const date = toDate(value)
125
+ if (date) return date
126
+ const where = typeof meta.href === 'string' && meta.href !== '' ? meta.href : 'a page without href'
127
+ warn(`${where}: ignoring ${key} ${show(value)}, expected a date like 2026-10-01 or 2026-10-01T09:30:00Z`)
128
+ }
129
+ return null
130
+ }
131
+
132
+ /**
133
+ * A comparator by date, for `Array.prototype.sort`: `get(item)` returns the
134
+ * item's date in any form `toDate` accepts. Oldest first, or newest first
135
+ * with `descending`; items without a usable date go last in both
136
+ * directions. Equal dates compare as `0`, so chain a tie-break
137
+ * (`byDate(get)(a, b) || byHref(a, b)`) for an order that does not depend
138
+ * on the input.
139
+ *
140
+ * @param {(item: any) => unknown} get
141
+ * @param {{ descending?: boolean }} [options]
142
+ * @returns {(a: any, b: any) => number}
143
+ */
144
+ export function byDate(get, { descending = false } = {}) {
145
+ if (typeof get !== 'function') {
146
+ throw new TypeError('byDate: get must be a function that returns an item\'s date')
147
+ }
148
+ const direction = descending ? -1 : 1
149
+ return (a, b) => {
150
+ const left = toDate(get(a))
151
+ const right = toDate(get(b))
152
+ if (!left || !right) return (left ? 0 : 1) - (right ? 0 : 1)
153
+ return direction * (left.getTime() - right.getTime())
154
+ }
155
+ }
package/src/files.js ADDED
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Listing the files under a folder, shared by every Nera plugin and tool
3
+ * (`@nera-static/plugin-utils/files`).
4
+ *
5
+ * One walker for the two ways `@nera-static/core` lists files: the pages
6
+ * folder (dotfiles skipped, names relative to the folder, as the
7
+ * `fs-readdir-recursive` package did) and an assets folder (dotfiles kept,
8
+ * absolute paths). Both orders are the same: depth first, the entries of each
9
+ * folder sorted by their bytes, as libuv's `readdir` returns them on POSIX.
10
+ */
11
+ import fs from 'node:fs'
12
+ import path from 'node:path'
13
+
14
+ // Byte order of two entry names, the order libuv's `scandir` sorts by
15
+ // (`strcmp`), so the result is the same on every file system and platform.
16
+ const byBytes = (a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b))
17
+
18
+ // The extensions a file may have, from the `ext` option.
19
+ const extensionList = (ext) => {
20
+ if (ext === undefined) return null
21
+ return Array.isArray(ext) ? ext : [ext]
22
+ }
23
+
24
+ /**
25
+ * Every file under `dir`, depth first, the entries of each folder in byte
26
+ * order. Symbolic links are followed: a linked file is listed under the link's
27
+ * name, a linked folder is walked, a dangling link is skipped, and a link back
28
+ * to a folder that is already being walked (an ancestor, or the folder
29
+ * itself) is not walked again, so a loop ends. Only regular files are listed;
30
+ * sockets, FIFOs and devices are not. A `dir` that does not exist or is no
31
+ * folder gives `[]`.
32
+ *
33
+ * @param {string} dir the folder to walk
34
+ * @param {object} [options]
35
+ * @param {boolean} [options.dotfiles=false] list entries whose name starts
36
+ * with `.`; when `false`, a dot folder is not entered either
37
+ * @param {string|string[]} [options.ext] keep only files with this extension
38
+ * (or one of these), compared exactly with `path.extname`: `'.md'`, not
39
+ * `'md'`, and `'.MD'` is another extension
40
+ * @param {boolean} [options.relative=false] paths relative to `dir` (with the
41
+ * platform separator) instead of absolute ones
42
+ * @returns {string[]}
43
+ * @example walkFiles('pages', { relative: true }) // ['blog/a.md', 'index.md']
44
+ */
45
+ export function walkFiles(dir, { dotfiles = false, ext, relative = false } = {}) {
46
+ const root = path.resolve(dir)
47
+ const extensions = extensionList(ext)
48
+ const files = []
49
+
50
+ const walk = (folder, ancestors) => {
51
+ let real
52
+ try {
53
+ real = fs.realpathSync(folder)
54
+ } catch {
55
+ return
56
+ }
57
+ if (ancestors.has(real)) return
58
+ const inside = new Set(ancestors).add(real)
59
+
60
+ const names = fs.readdirSync(folder).sort(byBytes)
61
+ for (const name of names) {
62
+ if (!dotfiles && name.startsWith('.')) continue
63
+ const full = path.join(folder, name)
64
+ let stat
65
+ try {
66
+ stat = fs.statSync(full)
67
+ } catch {
68
+ continue
69
+ }
70
+ if (stat.isDirectory()) {
71
+ walk(full, inside)
72
+ } else if (stat.isFile() && (!extensions || extensions.includes(path.extname(name)))) {
73
+ files.push(relative ? path.relative(root, full) : full)
74
+ }
75
+ }
76
+ }
77
+
78
+ if (fs.statSync(root, { throwIfNoEntry: false })?.isDirectory()) walk(root, new Set())
79
+ return files
80
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * How a Nera page's frontmatter is found and parsed, shared by core, the
3
+ * validator and every tool that reads page files
4
+ * (`@nera-static/plugin-utils/frontmatter`).
5
+ *
6
+ * Both mirror `@nera-static/core` (`src/core.js`): its options object and its
7
+ * markdown-it block rule. A difference between the two is a defect here, so
8
+ * a page the validator accepts parses the same way in the build.
9
+ */
10
+
11
+ /**
12
+ * The `yaml` parse options core reads frontmatter with: unquoted dates
13
+ * become `Date` objects (`timestamp`), `<<` merge keys work, and a repeated
14
+ * key takes the last value. Pass them to `yaml.parse` or `yaml.parseDocument`
15
+ * from your own `yaml` dependency; this package does not depend on `yaml`.
16
+ * Frozen, nested array included, so no caller can change them for another.
17
+ */
18
+ export const FRONTMATTER_OPTIONS = Object.freeze({
19
+ schema: 'core',
20
+ customTags: Object.freeze(['timestamp']),
21
+ merge: true,
22
+ uniqueKeys: false,
23
+ })
24
+
25
+ const FENCE = '---'
26
+
27
+ /**
28
+ * Splits a page file into its frontmatter YAML and its Markdown body, by
29
+ * core's rule: line endings are read as markdown-it reads them (CRLF and a
30
+ * lone CR as LF), the first line must be exactly `---`, and the next line
31
+ * that is exactly `---` closes the block (`----` or `--- ` do not). Without
32
+ * a closing line the rest of the file is YAML and the body is empty; an
33
+ * empty block gives `''`. A leading BOM or indentation means no frontmatter,
34
+ * as in core.
35
+ *
36
+ * @param {string} raw the file's text
37
+ * @returns {{ yamlText: string, body: string } | null} `null` when the file
38
+ * does not start with a `---` line (or `raw` is not a string)
39
+ */
40
+ export function splitFrontmatter(raw) {
41
+ if (typeof raw !== 'string') return null
42
+ const lines = raw.replace(/\r\n?/g, '\n').split('\n')
43
+ if (lines[0] !== FENCE) return null
44
+ const close = lines.indexOf(FENCE, 1)
45
+ if (close === -1) return { yamlText: lines.slice(1).join('\n'), body: '' }
46
+ return {
47
+ yamlText: lines.slice(1, close).join('\n'),
48
+ body: lines.slice(close + 1).join('\n'),
49
+ }
50
+ }
package/src/glob.js ADDED
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Pattern matching for page hrefs and site assets, shared by every Nera
3
+ * plugin and tool (`@nera-static/plugin-utils/glob`).
4
+ *
5
+ * Two rule sets, kept apart on purpose: `matchesPattern`/`matchesAny` are the
6
+ * `*` glob of the sitemap and feed `exclude` lists; `readIgnoreList` and
7
+ * `isIgnoredAsset` mirror how `@nera-static/core` applies `.neraignore`
8
+ * (`getIgnoredFiles`/`ignoreFiles` in `src/render.js`), which knows no
9
+ * wildcards at all.
10
+ */
11
+ import fs from 'node:fs'
12
+ import path from 'node:path'
13
+ import { escapeRegExp } from './html.js'
14
+
15
+ /** The site's ignore list, read from the site root as core reads it. */
16
+ export const IGNORE_FILE = '.neraignore'
17
+
18
+ /**
19
+ * Whether `href` matches `pattern`: `*` matches any run of characters
20
+ * (including `/` and none at all), everything else is literal, anchored at
21
+ * both ends. A value that is not a string never matches.
22
+ *
23
+ * @param {unknown} href
24
+ * @param {unknown} pattern
25
+ * @returns {boolean}
26
+ * @example matchesPattern('/drafts/a.html', '/drafts/*') // true
27
+ */
28
+ export function matchesPattern(href, pattern) {
29
+ if (typeof href !== 'string' || typeof pattern !== 'string') return false
30
+ const source = pattern.split('*').map(escapeRegExp).join('.*')
31
+ return new RegExp(`^${source}$`).test(href)
32
+ }
33
+
34
+ /**
35
+ * Whether `href` matches any of `patterns` (see `matchesPattern`).
36
+ *
37
+ * @param {unknown} href
38
+ * @param {unknown[]} [patterns]
39
+ * @returns {boolean}
40
+ */
41
+ export function matchesAny(href, patterns = []) {
42
+ return Array.isArray(patterns) && patterns.some((pattern) => matchesPattern(href, pattern))
43
+ }
44
+
45
+ /**
46
+ * The patterns in the site's `.neraignore`: one per line, trimmed, blank
47
+ * lines dropped, `[]` when the file does not exist. Read from `cwd`, the
48
+ * site root, not from `assets/`, as core reads it.
49
+ *
50
+ * @param {string} [cwd] the site root
51
+ * @returns {string[]}
52
+ */
53
+ export function readIgnoreList(cwd = process.cwd()) {
54
+ const file = path.join(cwd, IGNORE_FILE)
55
+ if (!fs.existsSync(file)) return []
56
+ return fs
57
+ .readFileSync(file, 'utf8')
58
+ .split('\n')
59
+ .map((line) => line.trim())
60
+ .filter((line) => line !== '')
61
+ }
62
+
63
+ /**
64
+ * Whether core's site asset pass skips `file`: its path relative to `root`
65
+ * (the assets folder), with POSIX separators, equals a pattern or starts with
66
+ * a pattern plus `/`. There are no wildcards and no trailing-slash form:
67
+ * `images` skips `images/a.png`, `images/` skips nothing, and `robots` does
68
+ * not skip `robots.txt`. Core's `ignoreFiles` returns the opposite (whether
69
+ * to keep the file); this name says what `true` means.
70
+ *
71
+ * @param {string[]} ignoreList from `readIgnoreList`
72
+ * @param {string} file an absolute path, or one relative to the same base as `root`
73
+ * @param {string} root the assets folder the patterns are relative to
74
+ * @returns {boolean}
75
+ */
76
+ export function isIgnoredAsset(ignoreList, file, root) {
77
+ const relative = path.relative(root, file).replace(/\\/g, '/')
78
+ return ignoreList.some((pattern) => relative === pattern || relative.startsWith(`${pattern}/`))
79
+ }
package/src/html.js ADDED
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Escaping for HTML, XML and regular expressions, shared by every Nera plugin
3
+ * and tool (`@nera-static/plugin-utils/html`).
4
+ *
5
+ * Each escaper takes any value: `null` and `undefined` give `''`, everything
6
+ * else is converted with `String()` first.
7
+ */
8
+
9
+ const HTML_ENTITIES = {
10
+ '&': '&amp;',
11
+ '<': '&lt;',
12
+ '>': '&gt;',
13
+ '"': '&quot;',
14
+ '\'': '&#39;',
15
+ }
16
+
17
+ const XML_ENTITIES = {
18
+ '&': '&amp;',
19
+ '<': '&lt;',
20
+ '>': '&gt;',
21
+ '"': '&quot;',
22
+ '\'': '&apos;',
23
+ }
24
+
25
+ // Characters XML 1.0 does not allow anywhere in a document, not even
26
+ // escaped: C0 controls other than tab, LF and CR, lone surrogates, and
27
+ // U+FFFE/U+FFFF.
28
+ const XML_INVALID = new RegExp([
29
+ '[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F\\uFFFE\\uFFFF]',
30
+ '[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])',
31
+ '(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]',
32
+ ].join('|'), 'g')
33
+
34
+ // Every character with a meaning in a JavaScript regular expression.
35
+ const REGEXP_SPECIAL = /[.*+?^${}()|[\]\\]/g
36
+
37
+ const asString = (value) => (value === null || value === undefined ? '' : String(value))
38
+
39
+ /**
40
+ * `value` escaped for HTML: `& < > " '` become entities (`'` as `&#39;`), so
41
+ * the result is safe in a text node and in a double- or single-quoted
42
+ * attribute value. Escapes once: `&amp;` becomes `&amp;amp;`.
43
+ *
44
+ * @param {unknown} value
45
+ * @returns {string}
46
+ */
47
+ export function escapeHtml(value) {
48
+ return asString(value).replace(/[&<>"']/g, (char) => HTML_ENTITIES[char])
49
+ }
50
+
51
+ /**
52
+ * `value` escaped for XML: `& < > " '` become entities (`'` as `&apos;`), and
53
+ * the characters XML 1.0 forbids even escaped (C0 controls but tab, LF and
54
+ * CR; lone surrogates; U+FFFE and U+FFFF) are dropped, so any page text
55
+ * yields a well-formed document.
56
+ *
57
+ * @param {unknown} value
58
+ * @returns {string}
59
+ */
60
+ export function escapeXml(value) {
61
+ return asString(value)
62
+ .replace(XML_INVALID, '')
63
+ .replace(/[&<>"']/g, (char) => XML_ENTITIES[char])
64
+ }
65
+
66
+ /**
67
+ * `value` with every regular-expression special character
68
+ * (`. * + ? ^ $ { } ( ) | [ ] \`) escaped, for building a `RegExp` that
69
+ * matches the text literally.
70
+ *
71
+ * @param {unknown} value
72
+ * @returns {string}
73
+ */
74
+ export function escapeRegExp(value) {
75
+ return asString(value).replace(REGEXP_SPECIAL, '\\$&')
76
+ }
package/src/lang.js ADDED
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Languages of a site and its pages, and values translated per language,
3
+ * shared by every Nera plugin and tool (`@nera-static/plugin-utils/lang`).
4
+ *
5
+ * A language is text (see `isText`), trimmed: `lang: 'de '` is `de`, and a
6
+ * blank `lang` counts as absent.
7
+ */
8
+
9
+ import { isPlainObject, isText, textOr } from './values.js'
10
+
11
+ /**
12
+ * The site's language: `app.lang` trimmed, or `fallback` when it is missing,
13
+ * not a string or blank.
14
+ *
15
+ * @param {{ lang?: unknown } | undefined | null} app
16
+ * @param {string} [fallback]
17
+ * @returns {string}
18
+ */
19
+ export function siteLang(app, fallback = 'en') {
20
+ return textOr(app?.lang, fallback)
21
+ }
22
+
23
+ /**
24
+ * A page's language: `meta.lang` trimmed, else the site's (see `siteLang`),
25
+ * else `fallback`.
26
+ *
27
+ * @param {{ lang?: unknown } | undefined | null} meta
28
+ * @param {{ lang?: unknown } | undefined | null} app
29
+ * @param {string} [fallback]
30
+ * @returns {string}
31
+ */
32
+ export function pageLang(meta, app, fallback = 'en') {
33
+ return textOr(meta?.lang) ?? siteLang(app, fallback)
34
+ }
35
+
36
+ /**
37
+ * The languages of a site: `app.lang` plus the keys of `app.translations`,
38
+ * each trimmed; blank ones are left out. Empty when the site sets neither.
39
+ *
40
+ * @param {{ lang?: unknown, translations?: unknown } | undefined | null} app
41
+ * @returns {Set<string>}
42
+ */
43
+ export function siteLanguages(app) {
44
+ const languages = new Set()
45
+ if (isText(app?.lang)) languages.add(app.lang.trim())
46
+ if (isPlainObject(app?.translations)) {
47
+ for (const key of Object.keys(app.translations)) {
48
+ if (isText(key)) languages.add(key.trim())
49
+ }
50
+ }
51
+ return languages
52
+ }
53
+
54
+ /**
55
+ * Whether `value` is a language map: a non-empty plain object (see
56
+ * `isPlainObject`) — and, when `languages` is given, one whose keys are all
57
+ * among them. A subset counts, so a map lacking one language is still a
58
+ * language map (and `localize` falls back).
59
+ *
60
+ * @param {unknown} value
61
+ * @param {Iterable<string>} [languages] e.g. `siteLanguages(app)`
62
+ * @returns {boolean}
63
+ */
64
+ export function isLanguageMap(value, languages) {
65
+ if (!isPlainObject(value)) return false
66
+ const keys = Object.keys(value)
67
+ if (keys.length === 0) return false
68
+ if (languages === undefined) return true
69
+ const known = languages instanceof Set ? languages : new Set(languages)
70
+ return keys.every((key) => known.has(key))
71
+ }
72
+
73
+ /**
74
+ * One value in one language. A string is returned as it is. A language map
75
+ * (a plain object) gives its entry for `lang`, else for the first of
76
+ * `fallbacks` it has (each code trimmed, blank ones skipped), else — with
77
+ * `any` — its first entry; an entry counts only when it is text (see
78
+ * `isText`), so `de: ''` or `de: null` falls back.
79
+ * Anything else, and a map without a usable entry, gives `null`.
80
+ *
81
+ * The plugins' chains are options: `{ fallbacks: [siteLang(app)] }`,
82
+ * `{ fallbacks: ['en'], any: true }`, or none at all.
83
+ *
84
+ * @param {unknown} value a string or `{ <lang>: string }`
85
+ * @param {string} lang
86
+ * @param {{ fallbacks?: string[], any?: boolean }} [options]
87
+ * @returns {string | null}
88
+ */
89
+ export function localize(value, lang, { fallbacks = [], any = false } = {}) {
90
+ if (typeof value === 'string') return value
91
+ if (!isPlainObject(value)) return null
92
+ for (const candidate of [lang, ...fallbacks]) {
93
+ const code = textOr(candidate)
94
+ if (code !== undefined && Object.hasOwn(value, code) && isText(value[code])) {
95
+ return value[code]
96
+ }
97
+ }
98
+ if (any) {
99
+ const first = Object.values(value).find(isText)
100
+ if (first !== undefined) return first
101
+ }
102
+ return null
103
+ }
package/src/packages.js CHANGED
@@ -2,7 +2,10 @@
2
2
  * Finding packages the way a site sees them
3
3
  * (`@nera-static/plugin-utils/packages`): `requireFromSite` resolves from the
4
4
  * site's own `node_modules`, not from the calling package's, and `ownVersion`
5
- * reads the version of the package a module belongs to.
5
+ * reads the version of the package a module belongs to. The package-name
6
+ * rules (`isPluginPackage`, `pluginShortName`, `pluginPackage`,
7
+ * `themePackage`) say which packages core loads as plugins and which package
8
+ * a plugin or theme spec names.
6
9
  */
7
10
 
8
11
  import fs from 'node:fs'
@@ -62,3 +65,79 @@ function readVersion(file) {
62
65
  return null
63
66
  }
64
67
  }
68
+
69
+ const SCOPE = '@nera-static/'
70
+ const PLUGIN_PREFIX = 'plugin-'
71
+ const PLUGIN_SCOPE_PREFIX = `${SCOPE}${PLUGIN_PREFIX}`
72
+ // In the scope's `plugin-` namespace, but no plugin: this library.
73
+ const NOT_PLUGINS = new Set([`${PLUGIN_SCOPE_PREFIX}utils`])
74
+ const PLUGIN_NAME = /^[a-z0-9][a-z0-9-]*$/
75
+ const CATALOG_URL = 'https://nera.js.org/plugins/'
76
+
77
+ /**
78
+ * Whether core loads the dependency `name` as a plugin: an
79
+ * `@nera-static/plugin-*` package other than `@nera-static/plugin-utils`
80
+ * (core's `setup-plugins.js` rule). The scope's other members (`core`,
81
+ * `nera`, `validate`, `theme-*`, `starter-*`) are none.
82
+ *
83
+ * @param {unknown} name a package name from a site's `dependencies`
84
+ * @returns {boolean}
85
+ * @example isPluginPackage('@nera-static/plugin-tags') // true
86
+ */
87
+ export function isPluginPackage(name) {
88
+ return typeof name === 'string' && name.startsWith(PLUGIN_SCOPE_PREFIX) && !NOT_PLUGINS.has(name)
89
+ }
90
+
91
+ /**
92
+ * The name core gives a plugin package in its log and in
93
+ * `config/plugin-order.yaml`: the package name without `@nera-static/`
94
+ * (core's `shortPluginName`); any other name is returned unchanged.
95
+ *
96
+ * @param {string} name
97
+ * @returns {string}
98
+ * @example pluginShortName('@nera-static/plugin-tags') // 'plugin-tags'
99
+ */
100
+ export function pluginShortName(name) {
101
+ return name.startsWith(SCOPE) ? name.slice(SCOPE.length) : name
102
+ }
103
+
104
+ /**
105
+ * The official plugin a spec names, in the forms `nera plugin add` takes:
106
+ * `<name>`, `plugin-<name>` or `@nera-static/plugin-<name>`.
107
+ *
108
+ * @param {unknown} spec
109
+ * @returns {{ name: string, pkg: string }} `name` without prefix (`sitemap`),
110
+ * `pkg` the package (`@nera-static/plugin-sitemap`)
111
+ * @throws {TypeError} for anything else: another scope, a version or tag
112
+ * (`x@1`), a path, an uppercase name, `utils` (the library)
113
+ * @example pluginPackage('sitemap') // { name: 'sitemap', pkg: '@nera-static/plugin-sitemap' }
114
+ */
115
+ export function pluginPackage(spec) {
116
+ let name = typeof spec === 'string' ? spec : ''
117
+ if (name.startsWith(PLUGIN_SCOPE_PREFIX)) name = name.slice(PLUGIN_SCOPE_PREFIX.length)
118
+ else if (name.startsWith(PLUGIN_PREFIX)) name = name.slice(PLUGIN_PREFIX.length)
119
+ const pkg = `${PLUGIN_SCOPE_PREFIX}${name}`
120
+ if (!PLUGIN_NAME.test(name) || NOT_PLUGINS.has(pkg)) {
121
+ throw new TypeError(
122
+ `${JSON.stringify(spec)} is not a Nera plugin. Give an official plugin as ` +
123
+ '`<name>`, `plugin-<name>` or `@nera-static/plugin-<name>` (e.g. `sitemap`); ' +
124
+ `the catalog is at ${CATALOG_URL}.`
125
+ )
126
+ }
127
+ return { name, pkg }
128
+ }
129
+
130
+ /**
131
+ * The npm package a `theme:` spec names, by core's rule (`theme.js`): a
132
+ * scoped name or one with a `/` is used verbatim (third-party themes), a bare
133
+ * name becomes `@nera-static/theme-<name>`. `null` for a local theme (a spec
134
+ * starting with `.`) and for a missing or blank spec, which mean no package.
135
+ *
136
+ * @param {unknown} spec `app.theme` (or `NERA_THEME`)
137
+ * @returns {string|null}
138
+ * @example themePackage('blog') // '@nera-static/theme-blog'
139
+ */
140
+ export function themePackage(spec) {
141
+ if (typeof spec !== 'string' || spec.trim() === '' || spec.startsWith('.')) return null
142
+ return spec.includes('/') || spec.startsWith('@') ? spec : `${SCOPE}theme-${spec}`
143
+ }
package/src/pages.js ADDED
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Which pages a plugin acts on (`@nera-static/plugin-utils/pages`): the
3
+ * pages core renders and the pages a site keeps out of search engines.
4
+ */
5
+
6
+ const nonBlank = (value) => typeof value === 'string' && value.trim() !== ''
7
+
8
+ /**
9
+ * Whether core renders the page: its frontmatter names a `layout` and it has
10
+ * an `href`. Core skips a page without `layout` silently, so a sitemap, feed
11
+ * or search index that lists it points at a page that does not exist.
12
+ *
13
+ * @param {object|null|undefined} meta the page's `meta`
14
+ * @returns {boolean}
15
+ * @example isRenderedPage({ layout: 'pages/default.pug', href: '/a.html' }) // true
16
+ */
17
+ export function isRenderedPage(meta) {
18
+ return nonBlank(meta?.layout) && nonBlank(meta?.href)
19
+ }
20
+
21
+ /**
22
+ * Whether the page asks search engines not to index it: its `robots`, or the
23
+ * site's `app.robots` when the page sets none, contains `noindex` (any case,
24
+ * e.g. `'NoIndex, follow'`).
25
+ *
26
+ * @param {object|null|undefined} meta the page's `meta`
27
+ * @param {object|null|undefined} [app] the site's `app`
28
+ * @returns {boolean}
29
+ * @example isNoindex({ robots: 'noindex, follow' }, {}) // true
30
+ */
31
+ export function isNoindex(meta, app) {
32
+ const robots = meta?.robots || app?.robots
33
+ return typeof robots === 'string' && /noindex/i.test(robots)
34
+ }