@nera-static/plugin-utils 1.6.0 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +237 -0
- package/LICENSE +1 -1
- package/README.md +202 -11
- package/index.js +20 -31
- package/package.json +12 -5
- package/src/config.js +160 -0
- package/src/guard.js +105 -0
- package/src/log.js +29 -0
- package/src/packages.js +64 -0
- package/src/values.js +44 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## [1.7.0] - 2026-11-27
|
|
9
|
+
|
|
10
|
+
The helpers that Nera plugins, core and the tools copy from each other now
|
|
11
|
+
live here, one subpath export per family. Nothing in `.` changed, and no
|
|
12
|
+
dependency was added (still `js-yaml` only). Each subpath is documented in
|
|
13
|
+
the README under "Shared helpers".
|
|
14
|
+
|
|
15
|
+
### Added
|
|
16
|
+
|
|
17
|
+
- **`@nera-static/plugin-utils/values`**: `isPlainObject(value)` (prototype
|
|
18
|
+
`Object.prototype` or `null`; arrays, `Date`, `Map` and class instances
|
|
19
|
+
are not plain), `isText(value)` (a string with a non-whitespace
|
|
20
|
+
character) and `textOr(value, fallback)` (the trimmed string, else
|
|
21
|
+
`fallback`)
|
|
22
|
+
- **`@nera-static/plugin-utils/log`**: `createLogger(name, { sink })` with
|
|
23
|
+
`warn`, `info` and the page-scoped `page(page, what, todo)`, printing
|
|
24
|
+
`⚠️ <name>: …` (`ℹ️ ` for `info`)
|
|
25
|
+
- **`@nera-static/plugin-utils/config`**: `getConfig` (the same function as
|
|
26
|
+
in `.`), `loadPluginConfig(name, { cwd, app })`, which honours
|
|
27
|
+
`app.folders.config`, and `createConfigReader({ file, defaults, readers,
|
|
28
|
+
warn })` with the fleet's one message set and a date-aware `show()`.
|
|
29
|
+
Unknown keys are found with `Object.hasOwn`, so a YAML key
|
|
30
|
+
`constructor:` or `toString:` now warns as unknown instead of slipping
|
|
31
|
+
into the config, as it did in every plugin's own reader
|
|
32
|
+
- **`@nera-static/plugin-utils/packages`**: `requireFromSite(cwd)`, a
|
|
33
|
+
`require` that resolves from the site root, and
|
|
34
|
+
`ownVersion(import.meta.url)`, the calling package's version
|
|
35
|
+
- **`@nera-static/plugin-utils/guard`**: `assertCoreVersion({ plugin, need,
|
|
36
|
+
why, cwd, from, version, hint })`, `coreVersion({ cwd, from })`,
|
|
37
|
+
`satisfiesFloor(version, floor)` (a prerelease sorts below its release)
|
|
38
|
+
and `GET_ASSETS_CORE` (`'4.13.0'`), the core version guard five plugins
|
|
39
|
+
carried as identical copies. The optional `hint` is appended after the
|
|
40
|
+
update advice, for a plugin-specific way out such as code-blocks'
|
|
41
|
+
"Or set `assets: false` in config/code-blocks.yaml."
|
|
42
|
+
- **`CHANGELOG.md` is part of the published package**
|
|
43
|
+
|
|
44
|
+
### Changed
|
|
45
|
+
|
|
46
|
+
- **every built-in module is imported with the `node:` prefix**, enforced by
|
|
47
|
+
a lint rule; the README examples follow it
|
|
48
|
+
|
|
49
|
+
### Fixed
|
|
50
|
+
|
|
51
|
+
- **`resolveViewsDir` and `resolveAssetsDir` (and so `publishTemplates`,
|
|
52
|
+
`publishAllTemplates` and `publishAsset`) now follow core's `themeOnly`
|
|
53
|
+
rule.** On a site whose `config/app.yaml` sets `theme:` and which has
|
|
54
|
+
neither a `theme/` nor a root `views/` folder, they resolved to the
|
|
55
|
+
deprecated root `views/` / `assets/`; core uses `theme/views` /
|
|
56
|
+
`theme/assets` there. `npm run publish-template` therefore wrote
|
|
57
|
+
`views/vendor/…`, and the new root `views/` switched the build into the
|
|
58
|
+
deprecated layout. Both now return the `theme/` folder, as core does
|
|
59
|
+
- **an explicit blank `folders.views: ''` or `folders.assets: ''` in
|
|
60
|
+
`config/app.yaml` is kept, as core keeps it**: it is the site root. The
|
|
61
|
+
helpers ignored a blank value and fell back to `theme/<key>` or the root
|
|
62
|
+
`<key>/`, so `publishTemplates` wrote where the build does not look
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
## [1.6.1] - 2026-10-08
|
|
66
|
+
|
|
67
|
+
Documentation only — no code changed.
|
|
68
|
+
|
|
69
|
+
### Fixed
|
|
70
|
+
|
|
71
|
+
- **`README.md` Compatibility still listed `js-yaml ^4.1.0`** as the runtime
|
|
72
|
+
dependency; 1.6.0 moved to `js-yaml ^5.2.2`.
|
|
73
|
+
- **The `bin/publish-template.js` example put a comment above the
|
|
74
|
+
`#!/usr/bin/env node` line.** A hashbang is only valid as the very first
|
|
75
|
+
line, so a script copied verbatim failed with a `SyntaxError`.
|
|
76
|
+
- **"Themed site" is now defined where the publish destination is
|
|
77
|
+
described** — a site with a local `theme/` folder, which is what
|
|
78
|
+
`nera new` scaffolds — so plugin authors know which destination their
|
|
79
|
+
users get
|
|
80
|
+
|
|
81
|
+
## [1.6.0] - 2026-07-27
|
|
82
|
+
|
|
83
|
+
### Changed
|
|
84
|
+
|
|
85
|
+
- **js-yaml 4 → 5.** `getConfig` returns the same shapes it always did for
|
|
86
|
+
every construct a Nera config uses — verified by parsing all 96 YAML files
|
|
87
|
+
across the ecosystem under both versions and diffing the results. One
|
|
88
|
+
difference is worth knowing about: a bare date scalar (`published:
|
|
89
|
+
2026-07-27`) now parses as the string `'2026-07-27'` rather than a `Date`.
|
|
90
|
+
No packaged plugin config declares a date field, so this only affects you
|
|
91
|
+
if you put one in your own `config/<plugin>.yaml` and relied on getting a
|
|
92
|
+
`Date` back
|
|
93
|
+
|
|
94
|
+
### Fixed
|
|
95
|
+
|
|
96
|
+
- **a config file containing only comments no longer throws.** js-yaml 5
|
|
97
|
+
rejects a document with no content, where 4 returned `undefined`. Plugins
|
|
98
|
+
ship their config with every key commented out — that is how the defaults
|
|
99
|
+
are documented — so upgrading would have crashed the build of any site
|
|
100
|
+
that copied one of those files verbatim. Such a file is now treated as an
|
|
101
|
+
absent config and yields `{}`, as before. The same applies to an empty or
|
|
102
|
+
whitespace-only file. Genuinely malformed YAML still throws
|
|
103
|
+
|
|
104
|
+
## [1.5.0] - 2026-07-24
|
|
105
|
+
|
|
106
|
+
### Added
|
|
107
|
+
|
|
108
|
+
- **`resolveViewsDir(cwd?)`** and **`resolveAssetsDir(cwd?)`** — return the
|
|
109
|
+
project's presentation directories the same way the generator does
|
|
110
|
+
(`core.js`): an explicit `folders.<key>` in `config/app.yaml` wins;
|
|
111
|
+
otherwise `theme/views` / `theme/assets` when a local `theme/` folder
|
|
112
|
+
exists; otherwise the deprecated root `views/` / `assets/`
|
|
113
|
+
|
|
114
|
+
- **`publishAsset({ sourceFile, targetPath, force?, expectedPackageName? })`**
|
|
115
|
+
— publishes a single support file (e.g. a plugin's client script) into the
|
|
116
|
+
resolved assets folder, theme-aware, with the same skip-if-exists rule as
|
|
117
|
+
`publishTemplates`. Plugins that ship a runtime asset alongside their
|
|
118
|
+
templates (`plugin-search`, `plugin-contact-form`) should copy it through
|
|
119
|
+
here instead of a hand-rolled root `assets/` copy
|
|
120
|
+
|
|
121
|
+
### Changed
|
|
122
|
+
|
|
123
|
+
- **`publishTemplates` / `publishAllTemplates` now publish theme-aware.** The
|
|
124
|
+
destination is `resolveViewsDir()/vendor/<plugin>` rather than a hardcoded
|
|
125
|
+
root `views/vendor/<plugin>`. On a themed site (a local `theme/` folder, so
|
|
126
|
+
the build renders from `theme/views`) templates now land in
|
|
127
|
+
`theme/views/vendor/…`, where the generator's layered resolver actually
|
|
128
|
+
looks — publishing to root `views/vendor/` left the includes silently
|
|
129
|
+
resolving to nothing. Sites with no `theme/` folder are unchanged, so this
|
|
130
|
+
is additive rather than breaking
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
## [1.4.0] - 2026-07-22
|
|
134
|
+
|
|
135
|
+
### Added
|
|
136
|
+
|
|
137
|
+
- **`slugify(text)`** — turns a user-authored string into a URL-safe slug,
|
|
138
|
+
for anything that becomes a path segment, an HTML `id`, or a URL fragment.
|
|
139
|
+
`ß` → `ss`, NFKD with combining marks dropped, lowercase, runs of
|
|
140
|
+
non-alphanumerics collapsed to a single `-`, leading and trailing hyphens
|
|
141
|
+
trimmed. Idempotent; returns `''` when nothing usable remains
|
|
142
|
+
|
|
143
|
+
It lives here because two plugins had already written it independently and
|
|
144
|
+
only one got it right. The naive rule, `[^\w]+` → `-`, is ASCII-only:
|
|
145
|
+
`Über uns` becomes `-ber-uns` and `Straße` becomes `stra-e`. A leading
|
|
146
|
+
hyphen is legal in an HTML `id` but is **not a valid CSS identifier**, so
|
|
147
|
+
`#-ber-uns` matches nothing in a stylesheet and `querySelector` throws on
|
|
148
|
+
it. That shipped in `plugin-one-page` until its v3.0.0
|
|
149
|
+
|
|
150
|
+
Purely additive — no existing export changed. `plugin-tags`' `slugifyTag`
|
|
151
|
+
and `plugin-one-page`'s internal helper both delegate here as of
|
|
152
|
+
`plugin-tags` 3.2.1 and `plugin-one-page` 3.0.1, and both keep producing
|
|
153
|
+
byte-identical output; their test suites are reproduced here to prove it
|
|
154
|
+
|
|
155
|
+
## [1.3.1] - 2026-07-21
|
|
156
|
+
|
|
157
|
+
### Fixed
|
|
158
|
+
|
|
159
|
+
- corrected the "Example Plugin Structure" snippet in the README, which
|
|
160
|
+
taught the plugin contract wrongly in three ways: it used the signature
|
|
161
|
+
`getAppData(app)` instead of `getAppData(data)`, returned a bare object
|
|
162
|
+
instead of spreading `...data.app` (which silently discards every other
|
|
163
|
+
plugin's `app` data sitewide), and resolved config against `__dirname`,
|
|
164
|
+
which is undefined in ESM and points at the package rather than the
|
|
165
|
+
user's site
|
|
166
|
+
- documented that `getConfig` returns `{}` for a missing or empty file and
|
|
167
|
+
never throws, so plugins must supply a JS fallback for every key
|
|
168
|
+
- corrected `validateNeraProject`'s description: a `package.json` is
|
|
169
|
+
required unconditionally; the shape check is an alternative to the *name*
|
|
170
|
+
check, not to having a `package.json`
|
|
171
|
+
- documented that `publishAllTemplates` returns `true` when `sourceDir`
|
|
172
|
+
contains no `.pug` files, so a misconfigured publish script exits `0`
|
|
173
|
+
having copied nothing
|
|
174
|
+
|
|
175
|
+
### Added
|
|
176
|
+
|
|
177
|
+
- `## 🧩 Compatibility`, `## 🧪 Development` and `## 🤝 Contributing`
|
|
178
|
+
sections; the Node requirement was previously stated nowhere
|
|
179
|
+
|
|
180
|
+
### Changed
|
|
181
|
+
|
|
182
|
+
- License heading uses the fleet-standard `## 📦 License`
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
## [1.3.0] - 2026-07-21
|
|
186
|
+
|
|
187
|
+
### Changed
|
|
188
|
+
|
|
189
|
+
- raised minimum Node from 18 to 20; Node 18 reached end-of-life on
|
|
190
|
+
2025-04-30 and the dev toolchain requires Node 20+
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
## [1.2.0] - 2026-07-19
|
|
194
|
+
|
|
195
|
+
### Fixed
|
|
196
|
+
|
|
197
|
+
- `publishAllTemplates` now publishes templates in subdirectories.
|
|
198
|
+
Plugins whose views use `partials/` or `helper/` previously shipped
|
|
199
|
+
top-level templates that could not compile
|
|
200
|
+
- `publishTemplates` no longer reports success when a source template
|
|
201
|
+
is missing. Sources are now all verified before anything is copied,
|
|
202
|
+
so a failure cannot leave a partially published destination
|
|
203
|
+
|
|
204
|
+
### Added
|
|
205
|
+
|
|
206
|
+
- `force` option on `publishTemplates` and `publishAllTemplates` to
|
|
207
|
+
re-publish over an existing `views/vendor/<plugin>/` directory. The
|
|
208
|
+
default remains skip-if-exists, so local edits are never discarded
|
|
209
|
+
unless explicitly requested
|
|
210
|
+
- `validateNeraProject` now also accepts any directory containing both
|
|
211
|
+
`config/app.yaml` and `pages/`, so projects not named `nera*` work.
|
|
212
|
+
The existing package-name check is retained as an alternative
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
## [1.1.0] - 2025-07-19
|
|
216
|
+
|
|
217
|
+
### Added
|
|
218
|
+
|
|
219
|
+
- `publishAllTemplates` for publishing every `.pug` file in a plugin's
|
|
220
|
+
views directory without listing them individually
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
## [1.0.5] - 2025-07-14
|
|
224
|
+
|
|
225
|
+
## [1.0.4] - 2025-07-13
|
|
226
|
+
|
|
227
|
+
## [1.0.3] - 2025-07-11
|
|
228
|
+
|
|
229
|
+
## [1.0.2] - 2025-07-11
|
|
230
|
+
|
|
231
|
+
## [1.0.1] - 2025-07-11
|
|
232
|
+
|
|
233
|
+
## [1.0.0] - 2025-07-11
|
|
234
|
+
|
|
235
|
+
Releases up to and including 1.0.5 pre-date this changelog. Dates are
|
|
236
|
+
taken from the npm registry; per-release contents were not recorded at
|
|
237
|
+
the time and have not been reconstructed here.
|
package/LICENSE
CHANGED
package/README.md
CHANGED
|
@@ -25,12 +25,12 @@ npm install @nera-static/plugin-utils
|
|
|
25
25
|
|
|
26
26
|
Reads and parses a YAML config file, returning its contents as a JavaScript object.
|
|
27
27
|
|
|
28
|
-
Returns `{}` if the file does not exist
|
|
28
|
+
Returns `{}` if the file does not exist, is empty or holds nothing but comments. Malformed YAML throws. **Supply a JS fallback for every key you read.** The same function is exported from `@nera-static/plugin-utils/config`, next to `loadPluginConfig` and `createConfigReader` (see [Shared helpers](#-shared-helpers-subpath-exports)), which find the file and check it for you.
|
|
29
29
|
|
|
30
30
|
Plugins read config from the *user's* site, not from the package. The `config/<name>.yaml` shipped inside a plugin is documentation only; it is never merged with the user's copy. Resolve against `process.cwd()`:
|
|
31
31
|
|
|
32
32
|
```js
|
|
33
|
-
import path from 'path'
|
|
33
|
+
import path from 'node:path'
|
|
34
34
|
import { getConfig } from '@nera-static/plugin-utils'
|
|
35
35
|
|
|
36
36
|
const config = getConfig(path.resolve(process.cwd(), 'config/my-plugin.yaml'))
|
|
@@ -91,7 +91,7 @@ if (validateNeraProject()) {
|
|
|
91
91
|
|
|
92
92
|
Publishes specific template files from a plugin to a Nera project.
|
|
93
93
|
|
|
94
|
-
The destination is **theme-aware**, resolved exactly as the generator resolves its views folder (see `resolveViewsDir` below): `theme/views/vendor/<pluginName>/` on a themed site, the deprecated root `views/vendor/<pluginName>/` otherwise. If it already exists, publishing is **skipped** and the function returns `true` — this protects the customizations you have made to previously published templates. Pass `force: true` to overwrite them.
|
|
94
|
+
The destination is **theme-aware**, resolved exactly as the generator resolves its views folder (see `resolveViewsDir` below): `theme/views/vendor/<pluginName>/` on a themed site (one with a local `theme/` folder — what `nera new` scaffolds), the deprecated root `views/vendor/<pluginName>/` otherwise. If it already exists, publishing is **skipped** and the function returns `true` — this protects the customizations you have made to previously published templates. Pass `force: true` to overwrite them.
|
|
95
95
|
|
|
96
96
|
```js
|
|
97
97
|
import { publishTemplates } from '@nera-static/plugin-utils'
|
|
@@ -143,7 +143,7 @@ Returns `false` outside a Nera project or when `sourceFile` is missing; a delibe
|
|
|
143
143
|
|
|
144
144
|
#### `resolveViewsDir(cwd?): string` / `resolveAssetsDir(cwd?): string`
|
|
145
145
|
|
|
146
|
-
Return the project's `views` / `assets` directory as an absolute path, resolved the same way the generator does: an explicit `folders.<key>` in `config/app.yaml` wins; otherwise `theme/views` / `theme/assets` when a local `theme/` folder exists; otherwise the deprecated root folder. `publishTemplates` and `publishAsset` use these internally, but they are exported for plugins that need to report or reason about where their files went.
|
|
146
|
+
Return the project's `views` / `assets` directory as an absolute path, resolved the same way the generator does: an explicit `folders.<key>` string in `config/app.yaml` wins, resolved against the project root (a blank `''` is the root itself, as in core); otherwise `theme/views` / `theme/assets` when a local `theme/` folder exists, or when `app.yaml` sets `theme:` and the site has no root `views/` folder (a thin themed site with no presentation of its own); otherwise the deprecated root folder. `publishTemplates` and `publishAsset` use these internally, but they are exported for plugins that need to report or reason about where their files went.
|
|
147
147
|
|
|
148
148
|
> The `__dirname` used in these option examples is not defined in ESM. See the CLI Integration example below for the two lines that define it.
|
|
149
149
|
|
|
@@ -154,8 +154,8 @@ These functions are designed to be used in `bin/publish-template.js` scripts tha
|
|
|
154
154
|
```js
|
|
155
155
|
#!/usr/bin/env node
|
|
156
156
|
|
|
157
|
-
import path from 'path'
|
|
158
|
-
import { fileURLToPath } from 'url'
|
|
157
|
+
import path from 'node:path'
|
|
158
|
+
import { fileURLToPath } from 'node:url'
|
|
159
159
|
import { publishAllTemplates } from '@nera-static/plugin-utils'
|
|
160
160
|
|
|
161
161
|
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
|
@@ -173,6 +173,197 @@ process.exit(result ? 0 : 1)
|
|
|
173
173
|
|
|
174
174
|
---
|
|
175
175
|
|
|
176
|
+
## 🧩 Shared helpers (subpath exports)
|
|
177
|
+
|
|
178
|
+
Since 1.7.0 the helpers that Nera plugins, core and the tools used to copy from each other live here, one subpath per family. Import them from the subpath, never write a local copy. The `.` export above is unchanged. None of them prints unless that is its job (the logger), reads globals beyond a `cwd` default of `process.cwd()`, or calls `process.exit`.
|
|
179
|
+
|
|
180
|
+
| Subpath | Exports |
|
|
181
|
+
|---|---|
|
|
182
|
+
| `@nera-static/plugin-utils/values` | `isPlainObject`, `isText`, `textOr` |
|
|
183
|
+
| `@nera-static/plugin-utils/log` | `createLogger` |
|
|
184
|
+
| `@nera-static/plugin-utils/config` | `getConfig`, `loadPluginConfig`, `createConfigReader` |
|
|
185
|
+
| `@nera-static/plugin-utils/packages` | `requireFromSite`, `ownVersion` |
|
|
186
|
+
| `@nera-static/plugin-utils/guard` | `satisfiesFloor`, `coreVersion`, `assertCoreVersion`, `GET_ASSETS_CORE` |
|
|
187
|
+
|
|
188
|
+
### `/values` — checks for parsed YAML and frontmatter
|
|
189
|
+
|
|
190
|
+
#### `isPlainObject(value: unknown): boolean`
|
|
191
|
+
|
|
192
|
+
`true` for a mapping as YAML or JSON produce it, or `Object.create(null)`: the prototype is `Object.prototype` (of any realm) or `null`. Arrays, `null`, `Date`, `Map` and class instances are `false`, so a frontmatter value like `images: 2026-10-01` (a `Date`) is never taken for a mapping.
|
|
193
|
+
|
|
194
|
+
#### `isText(value: unknown): boolean`
|
|
195
|
+
|
|
196
|
+
`true` for a string with at least one non-whitespace character.
|
|
197
|
+
|
|
198
|
+
#### `textOr(value: unknown, fallback?): string | fallback`
|
|
199
|
+
|
|
200
|
+
The **trimmed** string when `value` is text (see `isText`), otherwise `fallback` (default `undefined`).
|
|
201
|
+
|
|
202
|
+
```js
|
|
203
|
+
import { isPlainObject, isText, textOr } from '@nera-static/plugin-utils/values'
|
|
204
|
+
|
|
205
|
+
isPlainObject({ title: 'Blog' }) // true
|
|
206
|
+
isPlainObject(Object.create(null)) // true
|
|
207
|
+
isPlainObject([]) // false
|
|
208
|
+
isPlainObject(new Date()) // false
|
|
209
|
+
|
|
210
|
+
isText(' Blog ') // true
|
|
211
|
+
isText(' ') // false
|
|
212
|
+
|
|
213
|
+
textOr(' Blog ') // 'Blog'
|
|
214
|
+
textOr('', 'Untitled') // 'Untitled'
|
|
215
|
+
textOr(42, 'Untitled') // 'Untitled'
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
### `/log` — one prefix for every message
|
|
219
|
+
|
|
220
|
+
#### `createLogger(name: string, { sink = console } = {}): { warn, info, page }`
|
|
221
|
+
|
|
222
|
+
Every line starts with `name`, taken verbatim, so a site owner can tell in a build log where a warning came from:
|
|
223
|
+
|
|
224
|
+
- `warn(msg)` prints `⚠️ <name>: <msg>` through `sink.warn`;
|
|
225
|
+
- `info(msg)` prints `ℹ️ <name>: <msg>` through `sink.info`;
|
|
226
|
+
- `page(page, what, todo)` warns about one page: `⚠️ <name>: <page>: <what> — <todo>`.
|
|
227
|
+
|
|
228
|
+
A test passes its own `sink` (an object with `warn` and `info`) instead of spying on `console`.
|
|
229
|
+
|
|
230
|
+
```js
|
|
231
|
+
import { createLogger } from '@nera-static/plugin-utils/log'
|
|
232
|
+
|
|
233
|
+
const log = createLogger('plugin-sitemap')
|
|
234
|
+
|
|
235
|
+
log.warn('no origin set')
|
|
236
|
+
// ⚠️ plugin-sitemap: no origin set
|
|
237
|
+
log.info('wrote sitemap.xml')
|
|
238
|
+
// ℹ️ plugin-sitemap: wrote sitemap.xml
|
|
239
|
+
log.page('/blog/first.html', 'no date', 'add `date:` to its frontmatter')
|
|
240
|
+
// ⚠️ plugin-sitemap: /blog/first.html: no date — add `date:` to its frontmatter
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
### `/config` — finding and checking a plugin's config file
|
|
244
|
+
|
|
245
|
+
#### `getConfig(filePath: string): object`
|
|
246
|
+
|
|
247
|
+
The same function as in `.` (see [Configuration Loading](#configuration-loading)).
|
|
248
|
+
|
|
249
|
+
#### `loadPluginConfig(name: string, { cwd = process.cwd(), app } = {}): unknown`
|
|
250
|
+
|
|
251
|
+
The site's `<cwd>/<folder>/<name>.yaml`, parsed by `getConfig` and **not** checked (`{}` when it is missing). `<folder>` is `app.folders.config` when it is set, else `config`. Pass the `app` your hook receives, so a site that moved its config folder still works.
|
|
252
|
+
|
|
253
|
+
#### `createConfigReader({ file, defaults, readers, warn = console.warn }): reader`
|
|
254
|
+
|
|
255
|
+
The defaults-and-readers skeleton every plugin config shares, with one set of warnings for the whole fleet:
|
|
256
|
+
|
|
257
|
+
- `file` is the file as the site owner knows it (`'config/sitemap.yaml'`); every message starts with `<file>: `.
|
|
258
|
+
- `defaults` is the full default config, a plain object. Each call of `defaults()` or `normalize()` gets its own deep copy (`structuredClone`).
|
|
259
|
+
- `readers` holds one function per known top-level key: `(value, current, reader) => newValue`. `current` is the value so far (the default), `reader` is the object returned here, for its `bad`, `ignore` and `warn`. Returning `undefined` keeps `current`.
|
|
260
|
+
- `warn` is where messages go, usually a `createLogger(...).warn`.
|
|
261
|
+
|
|
262
|
+
`createConfigReader` throws a `TypeError` when `defaults` or `readers` is not a plain object. The returned `reader` has:
|
|
263
|
+
|
|
264
|
+
| Member | Does |
|
|
265
|
+
|---|---|
|
|
266
|
+
| `normalize(raw)` | a fresh copy of `defaults`, with each key of `raw` replaced by what its reader returns. `null`/`undefined` → the defaults, silently. Not a mapping → `expected a mapping at the top level, using defaults`. A key without its own reader (checked with `Object.hasOwn`, so `constructor:` or `toString:` is unknown too) → `ignoring unknown key <key>`. A key whose value is `null` (empty in YAML) keeps its default. |
|
|
267
|
+
| `defaults()` | a fresh deep copy of `defaults` |
|
|
268
|
+
| `bad(key, value, fallback)` | warns `invalid <key> <value>, using <fallback>` (or `, ignoring it` when `fallback` is `null` or `undefined`) and returns `fallback` |
|
|
269
|
+
| `ignore(where, what)` | warns `ignoring <where>, expected <what>` and returns `undefined` |
|
|
270
|
+
| `unknown(where, key)` | warns `ignoring unknown key <where><key>`, for nested mappings (`where` like `'labels.'`) |
|
|
271
|
+
| `show(value)` | a value as the messages show it: `a date` for a `Date`, else its JSON, else `String(value)` |
|
|
272
|
+
| `warn(msg)` | `warn` with the `<file>: ` prefix |
|
|
273
|
+
|
|
274
|
+
```js
|
|
275
|
+
import { createConfigReader, loadPluginConfig } from '@nera-static/plugin-utils/config'
|
|
276
|
+
import { createLogger } from '@nera-static/plugin-utils/log'
|
|
277
|
+
import { isText } from '@nera-static/plugin-utils/values'
|
|
278
|
+
|
|
279
|
+
const log = createLogger('plugin-sitemap')
|
|
280
|
+
|
|
281
|
+
const reader = createConfigReader({
|
|
282
|
+
file: 'config/sitemap.yaml',
|
|
283
|
+
defaults: { changefreq: 'weekly', exclude: [] },
|
|
284
|
+
readers: {
|
|
285
|
+
changefreq: (value, current, r) =>
|
|
286
|
+
isText(value) ? value.trim() : r.bad('changefreq', value, current),
|
|
287
|
+
exclude: (value, current, r) =>
|
|
288
|
+
Array.isArray(value) ? value : r.ignore('exclude', 'a list of paths'),
|
|
289
|
+
},
|
|
290
|
+
warn: log.warn,
|
|
291
|
+
})
|
|
292
|
+
|
|
293
|
+
export function getAppData({ app }) {
|
|
294
|
+
const config = reader.normalize(loadPluginConfig('sitemap', { app }))
|
|
295
|
+
return { ...app, sitemap: config }
|
|
296
|
+
}
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
With `changefreq: 3` and `excludes: []` in the site's `config/sitemap.yaml`, the build prints:
|
|
300
|
+
|
|
301
|
+
```text
|
|
302
|
+
⚠️ plugin-sitemap: config/sitemap.yaml: invalid changefreq 3, using "weekly"
|
|
303
|
+
⚠️ plugin-sitemap: config/sitemap.yaml: ignoring unknown key "excludes"
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
### `/packages` — packages as the site sees them
|
|
307
|
+
|
|
308
|
+
#### `requireFromSite(cwd = process.cwd()): NodeJS.Require`
|
|
309
|
+
|
|
310
|
+
A `require` that resolves from the site root, as if the site's own `package.json` asked. Use it for packages the **site** installs (core, a theme, an optional highlighter): resolved from your plugin, they would come from the plugin's own dependencies, or not be found at all. The `package.json` need not exist; only its folder counts.
|
|
311
|
+
|
|
312
|
+
#### `ownVersion(url: string | URL): string | null`
|
|
313
|
+
|
|
314
|
+
The `version` of the package the module at `url` belongs to: the nearest `package.json` with a `version`, from the module's folder upwards (a `{ "type": "module" }` manifest in between is skipped). `null` when there is none or it cannot be parsed. Pass `import.meta.url`; a plain path works too.
|
|
315
|
+
|
|
316
|
+
```js
|
|
317
|
+
import { ownVersion, requireFromSite } from '@nera-static/plugin-utils/packages'
|
|
318
|
+
|
|
319
|
+
const siteRequire = requireFromSite()
|
|
320
|
+
const themeDir = siteRequire.resolve('@nera-static/theme-blog/package.json')
|
|
321
|
+
|
|
322
|
+
const version = ownVersion(import.meta.url) // your package's version, e.g. '1.2.0'
|
|
323
|
+
```
|
|
324
|
+
|
|
325
|
+
### `/guard` — failing loudly on a too-old core
|
|
326
|
+
|
|
327
|
+
A plugin that relies on a hook of a newer `@nera-static/core` (`getAssets` since 4.13.0) is silently never called on an older one, and the build still exits 0. Check core's version from `getAppData` and fail loudly instead; `peerDependencies` reports the same at install time, the guard catches an install that ignored it.
|
|
328
|
+
|
|
329
|
+
#### `assertCoreVersion({ plugin, need = GET_ASSETS_CORE, why = 'the getAssets hook', cwd, from, version, hint })`
|
|
330
|
+
|
|
331
|
+
Throws when core is known to be older than `need`:
|
|
332
|
+
|
|
333
|
+
```text
|
|
334
|
+
plugin-sitemap: @nera-static/core 4.12.0 is too old; it needs >= 4.13.0 (the getAssets hook). Update with `npm update @nera-static/nera` (or `@nera-static/core`).
|
|
335
|
+
```
|
|
336
|
+
|
|
337
|
+
`plugin` is the name as you want it shown. `version` defaults to `coreVersion({ cwd, from })`. `hint`, when it is a non-blank string, is appended (trimmed) after the update advice, for a way out that only your plugin knows — e.g. ``hint: 'Or set `assets: false` in config/code-blocks.yaml.'``. An **unknown** version passes: some core is calling the plugin, and refusing on a guess would block a working setup.
|
|
338
|
+
|
|
339
|
+
#### `coreVersion({ cwd = process.cwd(), from } = {}): string | null`
|
|
340
|
+
|
|
341
|
+
The version of `@nera-static/core` the build most likely runs on: resolved from the site root `cwd` first, then, when `from` is given, from there. Pass your plugin's `import.meta.url` as `from`, so a symlinked plugin (`npm link`) that resolves from its real path still finds a core. `null` when none is found.
|
|
342
|
+
|
|
343
|
+
#### `satisfiesFloor(version: unknown, floor: string): boolean`
|
|
344
|
+
|
|
345
|
+
Whether `version` is `floor` or later by semver precedence: major, minor and patch compared as numbers, a prerelease (`4.13.0-beta.1`) **below** its release, build metadata ignored, surrounding whitespace allowed. Anything that is no version is `false`. Throws a `TypeError` when `floor` is not a plain `x.y.z`.
|
|
346
|
+
|
|
347
|
+
#### `GET_ASSETS_CORE`
|
|
348
|
+
|
|
349
|
+
`'4.13.0'`, the core release that introduced the `getAssets` hook, and the default `need`.
|
|
350
|
+
|
|
351
|
+
```js
|
|
352
|
+
import { assertCoreVersion, satisfiesFloor } from '@nera-static/plugin-utils/guard'
|
|
353
|
+
|
|
354
|
+
export function getAppData({ app }) {
|
|
355
|
+
assertCoreVersion({ plugin: 'plugin-sitemap', from: import.meta.url })
|
|
356
|
+
return { ...app }
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
satisfiesFloor('4.13.0', '4.13.0') // true
|
|
360
|
+
satisfiesFloor(' 4.14.2 ', '4.13.0') // true
|
|
361
|
+
satisfiesFloor('4.13.0-beta.1', '4.13.0') // false
|
|
362
|
+
satisfiesFloor('latest', '4.13.0') // false
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
---
|
|
366
|
+
|
|
176
367
|
## 🧱 Use Cases
|
|
177
368
|
|
|
178
369
|
This package is intended for use inside Nera plugins to:
|
|
@@ -185,7 +376,7 @@ This package is intended for use inside Nera plugins to:
|
|
|
185
376
|
|
|
186
377
|
```js
|
|
187
378
|
// index.js - Main plugin file
|
|
188
|
-
import path from 'path'
|
|
379
|
+
import path from 'node:path'
|
|
189
380
|
import { getConfig } from '@nera-static/plugin-utils'
|
|
190
381
|
|
|
191
382
|
export function getAppData(data) {
|
|
@@ -209,11 +400,11 @@ A plugin exports `getAppData` and/or `getMetaData`. Both receive a single object
|
|
|
209
400
|
See the [Nera contributing guide](https://github.com/seebaermichi/nera/blob/main/CONTRIBUTING.md) for the full plugin contract.
|
|
210
401
|
|
|
211
402
|
```js
|
|
212
|
-
// bin/publish-template.js - Template publishing script
|
|
213
403
|
#!/usr/bin/env node
|
|
404
|
+
// bin/publish-template.js - Template publishing script
|
|
214
405
|
|
|
215
|
-
import path from 'path'
|
|
216
|
-
import { fileURLToPath } from 'url'
|
|
406
|
+
import path from 'node:path'
|
|
407
|
+
import { fileURLToPath } from 'node:url'
|
|
217
408
|
import { publishAllTemplates } from '@nera-static/plugin-utils'
|
|
218
409
|
|
|
219
410
|
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
|
@@ -262,7 +453,7 @@ Created and maintained by [@seebaermichi](https://github.com/seebaermichi)
|
|
|
262
453
|
## 🧩 Compatibility
|
|
263
454
|
|
|
264
455
|
- **Node.js**: >= 20.0.0
|
|
265
|
-
- **Runtime dependency**: `js-yaml ^
|
|
456
|
+
- **Runtime dependency**: `js-yaml ^5.2.2` only
|
|
266
457
|
- **Nera**: no direct dependency on the generator — this package is used by
|
|
267
458
|
plugins, not by the generator itself
|
|
268
459
|
|
package/index.js
CHANGED
|
@@ -1,31 +1,10 @@
|
|
|
1
|
-
import fs from 'fs'
|
|
2
|
-
import path from 'path'
|
|
3
|
-
|
|
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
|
-
|
|
20
|
-
|
|
21
|
-
|
|
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.
|
|
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'
|
|
110
|
+
if (typeof explicit === 'string') {
|
|
125
111
|
return path.resolve(cwd, explicit)
|
|
126
112
|
}
|
|
127
113
|
|
|
128
|
-
|
|
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.
|
|
3
|
+
"version": "1.7.0",
|
|
4
4
|
"description": "Shared utility functions for Nera plugins (config loading, template publishing)",
|
|
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,7 @@
|
|
|
31
31
|
"devDependencies": {
|
|
32
32
|
"eslint": "^10.8.0",
|
|
33
33
|
"husky": "^9.1.7",
|
|
34
|
-
"vitest": "^
|
|
34
|
+
"vitest": "^5.0.0"
|
|
35
35
|
},
|
|
36
36
|
"scripts": {
|
|
37
37
|
"test": "vitest",
|
|
@@ -40,10 +40,17 @@
|
|
|
40
40
|
"prepare": "husky"
|
|
41
41
|
},
|
|
42
42
|
"exports": {
|
|
43
|
-
".": "./index.js"
|
|
43
|
+
".": "./index.js",
|
|
44
|
+
"./values": "./src/values.js",
|
|
45
|
+
"./log": "./src/log.js",
|
|
46
|
+
"./config": "./src/config.js",
|
|
47
|
+
"./packages": "./src/packages.js",
|
|
48
|
+
"./guard": "./src/guard.js"
|
|
44
49
|
},
|
|
45
50
|
"files": [
|
|
46
|
-
"index.js"
|
|
51
|
+
"index.js",
|
|
52
|
+
"src",
|
|
53
|
+
"CHANGELOG.md"
|
|
47
54
|
],
|
|
48
55
|
"engines": {
|
|
49
56
|
"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/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
|
+
}
|
package/src/log.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one prefix for every message a Nera plugin or tool prints
|
|
3
|
+
* (`@nera-static/plugin-utils/log`), so a site owner can tell in a build log
|
|
4
|
+
* full of other plugins where a warning came from.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* A logger whose messages start with `name`, taken verbatim
|
|
9
|
+
* (`'plugin-sitemap'`, `'validate'`):
|
|
10
|
+
*
|
|
11
|
+
* - `warn(msg)` prints `⚠️ <name>: <msg>` through `sink.warn`;
|
|
12
|
+
* - `info(msg)` prints `ℹ️ <name>: <msg>` through `sink.info`;
|
|
13
|
+
* - `page(page, what, todo)` warns about one page:
|
|
14
|
+
* `⚠️ <name>: <page>: <what> — <todo>`.
|
|
15
|
+
*
|
|
16
|
+
* @param {string} name who is speaking
|
|
17
|
+
* @param {{ sink?: { warn: (msg: string) => void, info: (msg: string) => void } }} [options]
|
|
18
|
+
* where the lines go (default `console`; a test passes its own)
|
|
19
|
+
* @returns {{ warn: (msg: string) => void, info: (msg: string) => void,
|
|
20
|
+
* page: (page: string, what: string, todo: string) => void }}
|
|
21
|
+
*/
|
|
22
|
+
export function createLogger(name, { sink = console } = {}) {
|
|
23
|
+
const warn = (msg) => sink.warn(`⚠️ ${name}: ${msg}`)
|
|
24
|
+
return {
|
|
25
|
+
warn,
|
|
26
|
+
info: (msg) => sink.info(`ℹ️ ${name}: ${msg}`),
|
|
27
|
+
page: (page, what, todo) => warn(`${page}: ${what} — ${todo}`),
|
|
28
|
+
}
|
|
29
|
+
}
|
package/src/packages.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Finding packages the way a site sees them
|
|
3
|
+
* (`@nera-static/plugin-utils/packages`): `requireFromSite` resolves from the
|
|
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.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import fs from 'node:fs'
|
|
9
|
+
import path from 'node:path'
|
|
10
|
+
import { createRequire } from 'node:module'
|
|
11
|
+
import { fileURLToPath } from 'node:url'
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* A `require` that resolves from the site root `cwd`, as if the site's own
|
|
15
|
+
* `package.json` asked. Use it for packages the site installs (core, a theme,
|
|
16
|
+
* an optional highlighter): resolved from a plugin, they would come from the
|
|
17
|
+
* plugin's dependencies or not be found at all. The `package.json` need not
|
|
18
|
+
* exist; only its folder counts.
|
|
19
|
+
*
|
|
20
|
+
* @param {string} [cwd] the site root (default `process.cwd()`)
|
|
21
|
+
* @returns {NodeJS.Require} use `.resolve(spec)` for a path, call it to load
|
|
22
|
+
*/
|
|
23
|
+
export function requireFromSite(cwd = process.cwd()) {
|
|
24
|
+
return createRequire(path.join(path.resolve(cwd), 'package.json'))
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The `version` of the package the module at `url` belongs to: the nearest
|
|
29
|
+
* `package.json` with a `version`, from the module's folder upwards (a
|
|
30
|
+
* `{ "type": "module" }` manifest in between is skipped). `null` when there is
|
|
31
|
+
* none or it cannot be read.
|
|
32
|
+
*
|
|
33
|
+
* @param {string|URL} url the module's `import.meta.url` (a path works too)
|
|
34
|
+
* @returns {string|null}
|
|
35
|
+
* @example ownVersion(import.meta.url) // '1.7.0'
|
|
36
|
+
*/
|
|
37
|
+
export function ownVersion(url) {
|
|
38
|
+
const file = String(url).startsWith('file:') ? fileURLToPath(url) : path.resolve(String(url))
|
|
39
|
+
let dir = path.dirname(file)
|
|
40
|
+
for (;;) {
|
|
41
|
+
const version = readVersion(path.join(dir, 'package.json'))
|
|
42
|
+
if (version !== undefined) return version
|
|
43
|
+
const parent = path.dirname(dir)
|
|
44
|
+
if (parent === dir) return null
|
|
45
|
+
dir = parent
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// The manifest's version; `undefined` when the file does not exist or names no
|
|
50
|
+
// version (keep walking up), `null` when it exists but cannot be parsed.
|
|
51
|
+
function readVersion(file) {
|
|
52
|
+
let text
|
|
53
|
+
try {
|
|
54
|
+
text = fs.readFileSync(file, 'utf-8')
|
|
55
|
+
} catch {
|
|
56
|
+
return undefined
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
const { version } = JSON.parse(text)
|
|
60
|
+
return typeof version === 'string' ? version : undefined
|
|
61
|
+
} catch {
|
|
62
|
+
return null
|
|
63
|
+
}
|
|
64
|
+
}
|
package/src/values.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Value checks for parsed YAML and frontmatter, shared by every Nera plugin
|
|
3
|
+
* and tool (`@nera-static/plugin-utils/values`).
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Whether `value` is a plain object: a mapping as YAML or JSON produce it,
|
|
8
|
+
* or `Object.create(null)`. Arrays, `null`, `Date`, `Map` and class
|
|
9
|
+
* instances are not.
|
|
10
|
+
*
|
|
11
|
+
* An object's prototype must be `null` or an `Object.prototype` — also one
|
|
12
|
+
* of another realm (a `node:vm` context), recognised as the end of its
|
|
13
|
+
* prototype chain, so the check does not depend on this realm's `Object`.
|
|
14
|
+
*
|
|
15
|
+
* @param {unknown} value
|
|
16
|
+
* @returns {boolean}
|
|
17
|
+
*/
|
|
18
|
+
export function isPlainObject(value) {
|
|
19
|
+
if (value === null || typeof value !== 'object') return false
|
|
20
|
+
const prototype = Object.getPrototypeOf(value)
|
|
21
|
+
return prototype === null || Object.getPrototypeOf(prototype) === null
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Whether `value` is a string with at least one non-whitespace character.
|
|
26
|
+
*
|
|
27
|
+
* @param {unknown} value
|
|
28
|
+
* @returns {boolean}
|
|
29
|
+
*/
|
|
30
|
+
export function isText(value) {
|
|
31
|
+
return typeof value === 'string' && value.trim() !== ''
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* `value` trimmed when it is text (see `isText`), otherwise `fallback`.
|
|
36
|
+
*
|
|
37
|
+
* @template T
|
|
38
|
+
* @param {unknown} value
|
|
39
|
+
* @param {T} [fallback] returned for a non-string or a blank string
|
|
40
|
+
* @returns {string | T}
|
|
41
|
+
*/
|
|
42
|
+
export function textOr(value, fallback = undefined) {
|
|
43
|
+
return isText(value) ? value.trim() : fallback
|
|
44
|
+
}
|