@nera-static/plugin-utils 1.6.1 → 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.
package/index.js CHANGED
@@ -1,31 +1,10 @@
1
- import fs from 'fs'
2
- import path from 'path'
3
- // js-yaml 5 dropped the default export; `load` is a named export now.
4
- import { load } from 'js-yaml'
5
-
6
- // js-yaml 5 throws on a document with no content, where 4 returned undefined.
7
- // A packaged config whose every key is commented out is the normal case here —
8
- // that is how plugins ship their defaults — so it has to keep behaving like an
9
- // absent config instead of crashing the build. Real syntax errors still throw.
10
- function hasNoDocument(content) {
11
- return content
12
- .split('\n')
13
- .every((line) => {
14
- const trimmed = line.trim()
15
- return trimmed === '' || trimmed.startsWith('#')
16
- })
17
- }
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { getConfig } from './src/config.js'
18
4
 
19
- export function getConfig(filePath) {
20
- if (fs.existsSync(filePath)) {
21
- const content = fs.readFileSync(filePath, 'utf-8')
22
- if (hasNoDocument(content)) {
23
- return {}
24
- }
25
- return load(content) || {}
26
- }
27
- return {}
28
- }
5
+ // `getConfig` lives in `src/config.js` with the rest of the config helpers
6
+ // (`@nera-static/plugin-utils/config`); `.` keeps exporting it unchanged.
7
+ export { getConfig }
29
8
 
30
9
  /**
31
10
  * Turns a user-authored string into a URL-safe slug, for anything that becomes
@@ -105,12 +84,19 @@ export function validateNeraProject(expectedPackageName = 'dummy') {
105
84
  * same way the generator does (core.js), so a plugin publishes where the build
106
85
  * will actually look:
107
86
  *
108
- * 1. An explicit `folders.<key>` in config/app.yaml always wins.
87
+ * 1. An explicit `folders.<key>` string in config/app.yaml always wins,
88
+ * resolved against the project root as core does — a blank one too
89
+ * (`views: ''` is the root itself). A non-string value (`views:` with
90
+ * nothing after it) is no folder and falls through.
109
91
  * 2. Otherwise, if a local `theme/` folder exists, it is `theme/<key>` — the
110
92
  * generator renders themed sites from `theme/views` and serves from
111
93
  * `theme/assets`, and a plugin's files are the site's own override layer,
112
94
  * so they belong there.
113
- * 3. Otherwise the deprecated root `<key>/`, byte-identical to before the
95
+ * 3. The same when `theme:` names a theme package and the site has neither
96
+ * `theme/` nor a root `views/` (core's `themeOnly`): the theme supplies
97
+ * every view, and the first override, a plugin's included, starts
98
+ * `theme/`. Core decides this by the root `views/` alone, for both keys.
99
+ * 4. Otherwise the deprecated root `<key>/`, byte-identical to before the
114
100
  * theme system existed.
115
101
  *
116
102
  * @param {string} cwd - Project root
@@ -121,11 +107,14 @@ function resolvePresentationDir(cwd, key) {
121
107
  const appConfig = getConfig(path.resolve(cwd, 'config/app.yaml'))
122
108
  const explicit = appConfig?.folders?.[key]
123
109
 
124
- if (typeof explicit === 'string' && explicit.trim()) {
110
+ if (typeof explicit === 'string') {
125
111
  return path.resolve(cwd, explicit)
126
112
  }
127
113
 
128
- if (fs.existsSync(path.resolve(cwd, 'theme'))) {
114
+ const themeOnly =
115
+ Boolean(appConfig?.theme) && !fs.existsSync(path.resolve(cwd, 'views'))
116
+
117
+ if (themeOnly || fs.existsSync(path.resolve(cwd, 'theme'))) {
129
118
  return path.resolve(cwd, 'theme', key)
130
119
  }
131
120
 
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@nera-static/plugin-utils",
3
- "version": "1.6.1",
4
- "description": "Shared utility functions for Nera plugins (config loading, template publishing)",
3
+ "version": "1.8.0",
4
+ "description": "Shared helpers for Nera plugins and tools: config loading, template publishing, and subpath exports for values, logging, languages, dates, URLs and base_path, escaping, frontmatter, globs, package names and pages",
5
5
  "main": "index.js",
6
6
  "type": "module",
7
7
  "repository": {
8
8
  "type": "git",
9
- "url": "https://github.com/seebaermichi/nera-plugin-utils.git"
9
+ "url": "git+https://github.com/seebaermichi/nera-plugin-utils.git"
10
10
  },
11
11
  "bugs": {
12
12
  "url": "https://github.com/seebaermichi/nera-plugin-utils/issues"
@@ -31,7 +31,8 @@
31
31
  "devDependencies": {
32
32
  "eslint": "^10.8.0",
33
33
  "husky": "^9.1.7",
34
- "vitest": "^5.0.0"
34
+ "vitest": "^5.0.0",
35
+ "yaml": "^2.4.1"
35
36
  },
36
37
  "scripts": {
37
38
  "test": "vitest",
@@ -40,10 +41,25 @@
40
41
  "prepare": "husky"
41
42
  },
42
43
  "exports": {
43
- ".": "./index.js"
44
+ ".": "./index.js",
45
+ "./values": "./src/values.js",
46
+ "./log": "./src/log.js",
47
+ "./config": "./src/config.js",
48
+ "./packages": "./src/packages.js",
49
+ "./guard": "./src/guard.js",
50
+ "./html": "./src/html.js",
51
+ "./lang": "./src/lang.js",
52
+ "./dates": "./src/dates.js",
53
+ "./sort": "./src/sort.js",
54
+ "./urls": "./src/urls.js",
55
+ "./frontmatter": "./src/frontmatter.js",
56
+ "./glob": "./src/glob.js",
57
+ "./pages": "./src/pages.js"
44
58
  },
45
59
  "files": [
46
- "index.js"
60
+ "index.js",
61
+ "src",
62
+ "CHANGELOG.md"
47
63
  ],
48
64
  "engines": {
49
65
  "node": ">=20.0.0"
package/src/config.js ADDED
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Reading and checking a site's plugin config files
3
+ * (`@nera-static/plugin-utils/config`): `getConfig` parses one YAML file,
4
+ * `loadPluginConfig` finds a plugin's file in the site, and
5
+ * `createConfigReader` merges it over the plugin's defaults key by key, with
6
+ * one set of warnings for the whole fleet.
7
+ */
8
+
9
+ import fs from 'node:fs'
10
+ import path from 'node:path'
11
+ // js-yaml 5 dropped the default export; `load` is a named export now.
12
+ import { load } from 'js-yaml'
13
+ import { isPlainObject, textOr } from './values.js'
14
+
15
+ // js-yaml 5 throws on a document with no content, where 4 returned undefined.
16
+ // A packaged config whose every key is commented out is the normal case here —
17
+ // that is how plugins ship their defaults — so it has to keep behaving like an
18
+ // absent config instead of crashing the build. Real syntax errors still throw.
19
+ function hasNoDocument(content) {
20
+ return content
21
+ .split('\n')
22
+ .every((line) => {
23
+ const trimmed = line.trim()
24
+ return trimmed === '' || trimmed.startsWith('#')
25
+ })
26
+ }
27
+
28
+ /**
29
+ * The parsed YAML file at `filePath`, or `{}` when it is missing or holds
30
+ * nothing but comments and blank lines. Malformed YAML throws.
31
+ *
32
+ * @param {string} filePath
33
+ * @returns {unknown} whatever the document holds (usually a mapping)
34
+ */
35
+ export function getConfig(filePath) {
36
+ if (fs.existsSync(filePath)) {
37
+ const content = fs.readFileSync(filePath, 'utf-8')
38
+ if (hasNoDocument(content)) {
39
+ return {}
40
+ }
41
+ return load(content) || {}
42
+ }
43
+ return {}
44
+ }
45
+
46
+ /**
47
+ * The site's `config/<name>.yaml`, parsed by `getConfig` and not checked
48
+ * (`{}` when it is missing). The folder is `app.folders.config` when set,
49
+ * else `config`, relative to `cwd`.
50
+ *
51
+ * @param {string} name the file name without `.yaml` (`'sitemap'`)
52
+ * @param {{ cwd?: string, app?: object }} [options]
53
+ * @returns {unknown} the raw parsed document, for `createConfigReader`
54
+ */
55
+ export function loadPluginConfig(name, { cwd = process.cwd(), app } = {}) {
56
+ const folder = textOr(app?.folders?.config, 'config')
57
+ return getConfig(path.resolve(cwd, folder, `${name}.yaml`))
58
+ }
59
+
60
+ /**
61
+ * A value as a warning shows it: `a date` for a `Date`, else its JSON, else
62
+ * `String(value)` (for `undefined`, a function, or what JSON cannot write).
63
+ *
64
+ * @param {unknown} value
65
+ * @returns {string}
66
+ */
67
+ function show(value) {
68
+ if (value instanceof Date) return 'a date'
69
+ try {
70
+ return JSON.stringify(value) ?? String(value)
71
+ } catch {
72
+ return String(value)
73
+ }
74
+ }
75
+
76
+ /**
77
+ * The defaults-and-readers skeleton every plugin config shares. Every
78
+ * message starts with `<file>: ` and goes to `warn`:
79
+ *
80
+ * - `expected a mapping at the top level, using defaults`
81
+ * - `ignoring unknown key <where><key>`
82
+ * - `invalid <key> <value>, using <fallback>` — or `, ignoring it` when the
83
+ * fallback is `null` or `undefined`
84
+ * - `ignoring <path>, expected <what>`
85
+ *
86
+ * `normalize(raw)` starts from a fresh copy of `defaults` and, for each key
87
+ * of `raw`, calls `readers[key](value, current, reader)` and stores what it
88
+ * returns. A key without its own reader warns as unknown (also `constructor`
89
+ * or `toString`, which every object inherits), a `null` value (an empty key
90
+ * in YAML) keeps the default, and a reader that returns `undefined` keeps it
91
+ * too. The third argument is the reader object itself, so a reader warns
92
+ * through `reader.bad`, `reader.ignore` or `reader.warn` with the same prefix.
93
+ *
94
+ * @param {object} options
95
+ * @param {string} options.file the file as the site owner knows it
96
+ * (`'config/sitemap.yaml'`)
97
+ * @param {object} options.defaults the full default config, a plain object;
98
+ * each `defaults()` and `normalize()` call gets its own deep copy
99
+ * @param {Record<string, (value: unknown, current: unknown, reader: object) => unknown>} options.readers
100
+ * one function per known top-level key
101
+ * @param {(msg: string) => void} [options.warn] where messages go (default
102
+ * `console.warn`; usually a `createLogger(...).warn`)
103
+ * @returns {{
104
+ * defaults: () => object,
105
+ * normalize: (raw: unknown) => object,
106
+ * show: (value: unknown) => string,
107
+ * bad: (key: string, value: unknown, fallback: unknown) => unknown,
108
+ * ignore: (where: string, what: string) => undefined,
109
+ * unknown: (where: string, key: string) => void,
110
+ * warn: (msg: string) => void,
111
+ * }}
112
+ */
113
+ export function createConfigReader({ file, defaults, readers, warn = console.warn }) {
114
+ if (!isPlainObject(defaults)) {
115
+ throw new TypeError(`createConfigReader(${show(file)}): defaults must be a plain object`)
116
+ }
117
+ if (!isPlainObject(readers)) {
118
+ throw new TypeError(`createConfigReader(${show(file)}): readers must be a plain object`)
119
+ }
120
+
121
+ const reader = {
122
+ defaults: () => structuredClone(defaults),
123
+ show,
124
+ warn: (msg) => warn(`${file}: ${msg}`),
125
+ bad(key, value, fallback) {
126
+ const using = fallback === null || fallback === undefined
127
+ ? 'ignoring it'
128
+ : `using ${show(fallback)}`
129
+ reader.warn(`invalid ${key} ${show(value)}, ${using}`)
130
+ return fallback
131
+ },
132
+ ignore(where, what) {
133
+ reader.warn(`ignoring ${where}, expected ${what}`)
134
+ return undefined
135
+ },
136
+ unknown(where, key) {
137
+ reader.warn(`ignoring unknown key ${where}${show(key)}`)
138
+ },
139
+ normalize(raw) {
140
+ const config = reader.defaults()
141
+ if (raw === null || raw === undefined) return config
142
+ if (!isPlainObject(raw)) {
143
+ reader.warn('expected a mapping at the top level, using defaults')
144
+ return config
145
+ }
146
+ for (const [key, value] of Object.entries(raw)) {
147
+ if (!Object.hasOwn(readers, key)) {
148
+ reader.unknown('', key)
149
+ continue
150
+ }
151
+ // A key present but empty reads as null; treat it like an absent key.
152
+ if (value === null) continue
153
+ const result = readers[key](value, config[key], reader)
154
+ if (result !== undefined) config[key] = result
155
+ }
156
+ return config
157
+ },
158
+ }
159
+ return reader
160
+ }
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
+ }
@@ -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/guard.js ADDED
@@ -0,0 +1,105 @@
1
+ /**
2
+ * The core version guard (`@nera-static/plugin-utils/guard`). A plugin that
3
+ * relies on a hook of a newer `@nera-static/core` (`getAssets` since 4.13.0)
4
+ * is silently never called on an older one, and the build still exits 0. The
5
+ * plugin checks core's version from `getAppData` and fails loudly instead;
6
+ * `peerDependencies` reports the same at install time, this catches an
7
+ * install that ignored it.
8
+ */
9
+
10
+ import { createRequire } from 'node:module'
11
+ import { requireFromSite } from './packages.js'
12
+ import { textOr } from './values.js'
13
+
14
+ /** The floor `assertCoreVersion` checks when none is given: the `getAssets` hook. */
15
+ export const GET_ASSETS_CORE = '4.13.0'
16
+
17
+ // `x.y.z` with an optional `-prerelease` and `+build` (ignored), surrounding
18
+ // whitespace allowed; `null` for anything else.
19
+ function parseVersion(version) {
20
+ if (typeof version !== 'string') return null
21
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(version.trim())
22
+ return match ? { numbers: match.slice(1, 4).map(Number), prerelease: match[4] !== undefined } : null
23
+ }
24
+
25
+ /**
26
+ * Whether `version` is `floor` or later, by semver precedence: major, minor
27
+ * and patch compared as numbers, and a prerelease (`4.13.0-beta.1`) below its
28
+ * release. Surrounding whitespace is ignored. Anything that is no version is
29
+ * `false`.
30
+ *
31
+ * @param {unknown} version
32
+ * @param {string} floor a plain `x.y.z` version
33
+ * @returns {boolean}
34
+ * @throws {TypeError} when `floor` is not a plain `x.y.z` version
35
+ */
36
+ export function satisfiesFloor(version, floor) {
37
+ const need = parseVersion(floor)
38
+ if (!need || need.prerelease) {
39
+ throw new TypeError(`satisfiesFloor: floor must be a plain x.y.z version, got ${JSON.stringify(floor)}`)
40
+ }
41
+ const have = parseVersion(version)
42
+ if (!have) return false
43
+ for (let i = 0; i < 3; i++) {
44
+ if (have.numbers[i] !== need.numbers[i]) return have.numbers[i] > need.numbers[i]
45
+ }
46
+ return !have.prerelease
47
+ }
48
+
49
+ /**
50
+ * The version of `@nera-static/core` this build most likely runs on, or
51
+ * `null` when it cannot be found. Resolved from the site root `cwd` first,
52
+ * then, when given, from `from`: the plugin's `import.meta.url`, for a
53
+ * symlinked plugin that resolves from its real path, where its devDependency
54
+ * core answers for the site's. Without `from` only the site is asked.
55
+ *
56
+ * @param {{ cwd?: string, from?: string|URL }} [options]
57
+ * @returns {string|null}
58
+ */
59
+ export function coreVersion({ cwd = process.cwd(), from } = {}) {
60
+ const requires = [() => requireFromSite(cwd)]
61
+ if (from !== undefined) requires.push(() => createRequire(from))
62
+ for (const make of requires) {
63
+ try {
64
+ const { version } = make()('@nera-static/core/package.json')
65
+ if (typeof version === 'string') return version
66
+ } catch {
67
+ // Not found from here: ask the next one.
68
+ }
69
+ }
70
+ return null
71
+ }
72
+
73
+ /**
74
+ * Throw when core is known to be older than `need`. An unknown version passes:
75
+ * some core is calling the plugin, and refusing on a guess would block a
76
+ * working setup.
77
+ *
78
+ * @param {object} options
79
+ * @param {string} options.plugin who is asking, verbatim (`'plugin-sitemap'`)
80
+ * @param {string} [options.need] the floor (default `GET_ASSETS_CORE`)
81
+ * @param {string} [options.why] what needs it (default `'the getAssets hook'`)
82
+ * @param {string} [options.cwd] the site root, for `coreVersion`
83
+ * @param {string|URL} [options.from] the plugin's `import.meta.url`, for `coreVersion`
84
+ * @param {string|null} [options.version] core's version (default `coreVersion({ cwd, from })`)
85
+ * @param {string} [options.hint] a plugin-specific way out, appended after the update advice
86
+ * (e.g. "Or set assets: false in config/code-blocks.yaml."); a blank hint adds nothing
87
+ * @throws {Error} `<plugin>: @nera-static/core <version> is too old; it needs >= <need> (<why>). Update with … [<hint>]`
88
+ */
89
+ export function assertCoreVersion({
90
+ plugin,
91
+ need = GET_ASSETS_CORE,
92
+ why = 'the getAssets hook',
93
+ cwd,
94
+ from,
95
+ version = coreVersion({ cwd, from }),
96
+ hint,
97
+ }) {
98
+ if (version === null || satisfiesFloor(version, need)) return
99
+ const extra = textOr(hint, '')
100
+ throw new Error(
101
+ `${plugin}: @nera-static/core ${version} is too old; it needs >= ${need} (${why}). ` +
102
+ 'Update with `npm update @nera-static/nera` (or `@nera-static/core`).' +
103
+ (extra && ` ${extra}`)
104
+ )
105
+ }