@nera-static/plugin-utils 1.7.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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
+ }
package/src/sort.js ADDED
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Comparators for every sort that shapes build output, shared by every Nera
3
+ * plugin and tool (`@nera-static/plugin-utils/sort`).
4
+ *
5
+ * They compare UTF-16 code units, like `<` on strings, never with
6
+ * `localeCompare`: the order is the same on every machine and in every
7
+ * locale (uppercase before lowercase, ASCII before other letters).
8
+ */
9
+
10
+ const asString = (value) => (typeof value === 'string' ? value : '')
11
+
12
+ /**
13
+ * Compares two strings by code unit, for `Array.prototype.sort`. A value
14
+ * that is not a string compares as `''`, so it sorts first.
15
+ *
16
+ * @param {unknown} a
17
+ * @param {unknown} b
18
+ * @returns {-1 | 0 | 1}
19
+ */
20
+ export function byString(a, b) {
21
+ const left = asString(a)
22
+ const right = asString(b)
23
+ return left < right ? -1 : left > right ? 1 : 0
24
+ }
25
+
26
+ const hrefOf = (item) => item?.meta?.href ?? item?.href
27
+
28
+ /**
29
+ * Compares two pages (`{ meta }`) or two metas by `href`, by code unit (see
30
+ * `byString`); a missing `href` sorts first.
31
+ *
32
+ * @param {{ meta?: { href?: unknown }, href?: unknown } | undefined | null} a
33
+ * @param {{ meta?: { href?: unknown }, href?: unknown } | undefined | null} b
34
+ * @returns {-1 | 0 | 1}
35
+ */
36
+ export function byHref(a, b) {
37
+ return byString(hrefOf(a), hrefOf(b))
38
+ }