@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/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
+ '&': '&',
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/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
+ }
@@ -0,0 +1,143 @@
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. 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.
9
+ */
10
+
11
+ import fs from 'node:fs'
12
+ import path from 'node:path'
13
+ import { createRequire } from 'node:module'
14
+ import { fileURLToPath } from 'node:url'
15
+
16
+ /**
17
+ * A `require` that resolves from the site root `cwd`, as if the site's own
18
+ * `package.json` asked. Use it for packages the site installs (core, a theme,
19
+ * an optional highlighter): resolved from a plugin, they would come from the
20
+ * plugin's dependencies or not be found at all. The `package.json` need not
21
+ * exist; only its folder counts.
22
+ *
23
+ * @param {string} [cwd] the site root (default `process.cwd()`)
24
+ * @returns {NodeJS.Require} use `.resolve(spec)` for a path, call it to load
25
+ */
26
+ export function requireFromSite(cwd = process.cwd()) {
27
+ return createRequire(path.join(path.resolve(cwd), 'package.json'))
28
+ }
29
+
30
+ /**
31
+ * The `version` of the package the module at `url` belongs to: the nearest
32
+ * `package.json` with a `version`, from the module's folder upwards (a
33
+ * `{ "type": "module" }` manifest in between is skipped). `null` when there is
34
+ * none or it cannot be read.
35
+ *
36
+ * @param {string|URL} url the module's `import.meta.url` (a path works too)
37
+ * @returns {string|null}
38
+ * @example ownVersion(import.meta.url) // '1.7.0'
39
+ */
40
+ export function ownVersion(url) {
41
+ const file = String(url).startsWith('file:') ? fileURLToPath(url) : path.resolve(String(url))
42
+ let dir = path.dirname(file)
43
+ for (;;) {
44
+ const version = readVersion(path.join(dir, 'package.json'))
45
+ if (version !== undefined) return version
46
+ const parent = path.dirname(dir)
47
+ if (parent === dir) return null
48
+ dir = parent
49
+ }
50
+ }
51
+
52
+ // The manifest's version; `undefined` when the file does not exist or names no
53
+ // version (keep walking up), `null` when it exists but cannot be parsed.
54
+ function readVersion(file) {
55
+ let text
56
+ try {
57
+ text = fs.readFileSync(file, 'utf-8')
58
+ } catch {
59
+ return undefined
60
+ }
61
+ try {
62
+ const { version } = JSON.parse(text)
63
+ return typeof version === 'string' ? version : undefined
64
+ } catch {
65
+ return null
66
+ }
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
+ }
package/src/urls.js ADDED
@@ -0,0 +1,243 @@
1
+ /**
2
+ * Site URLs, `base_path`, path containment and `srcset`, shared by every
3
+ * Nera plugin and tool (`@nera-static/plugin-utils/urls`).
4
+ *
5
+ * Absolute URLs are percent-encoded (`joinUrl`, `siteUrl`), so a canonical
6
+ * link, a sitemap `<loc>` and a feed `<link>` of the same page are the same
7
+ * string. The `base_path` helpers give exactly `@nera-static/core`'s output.
8
+ */
9
+
10
+ import path from 'node:path'
11
+ import { loadPluginConfig } from './config.js'
12
+ import { isPlainObject } from './values.js'
13
+
14
+ // A percent-escape that is already valid: `%` and two hex digits. The
15
+ // capture group keeps it in `split`'s output, at the odd indexes.
16
+ const PERCENT_ESCAPE = /(%[0-9A-Fa-f]{2})/
17
+
18
+ // A URL scheme (`https:`, `mailto:`, `data:`, …), per RFC 3986.
19
+ const SCHEME = /^[a-z][a-z0-9+.-]*:/i
20
+
21
+ // ASCII whitespace as the HTML standard defines it for `srcset`.
22
+ const WHITESPACE = /[\t\n\f\r ]/
23
+
24
+ // The origin without whitespace and trailing slashes, '' for a non-string.
25
+ const trimOrigin = (origin) => (typeof origin === 'string' ? origin.trim().replace(/\/+$/, '') : '')
26
+
27
+ /**
28
+ * The site origin without surrounding whitespace and trailing slashes:
29
+ * `app.origin`, else `app_origin` from the site's
30
+ * `config/canonical-links.yaml` (`app.folders.config` honoured), the order
31
+ * canonical-links, sitemap, feed and validate use. `''` when neither is a
32
+ * non-blank string. The file is only read when `app.origin` is blank or
33
+ * missing; a missing file reads as no origin.
34
+ *
35
+ * @param {{ cwd?: string, app?: object }} [options]
36
+ * @returns {string} e.g. `'https://example.com'`, or `''`
37
+ */
38
+ export function resolveOrigin({ cwd = process.cwd(), app } = {}) {
39
+ const own = trimOrigin(app?.origin)
40
+ if (own) return own
41
+ const canonical = loadPluginConfig('canonical-links', { cwd, app })
42
+ return trimOrigin(isPlainObject(canonical) ? canonical.app_origin : undefined)
43
+ }
44
+
45
+ /**
46
+ * `value` with everything a URL may not contain percent-encoded (space,
47
+ * non-ASCII, a `%` that starts no valid escape, …), while valid `%XX`
48
+ * escapes and URL delimiters (`/ ? # & =` …) stay as they are, so an
49
+ * already-encoded path is not encoded twice. Lone surrogates become
50
+ * `%EF%BF%BD` (U+FFFD) instead of throwing. `null` and `undefined` give
51
+ * `''`, other non-strings are converted with `String()`.
52
+ *
53
+ * @param {unknown} value a path such as `meta.href`
54
+ * @returns {string}
55
+ */
56
+ export function encodePath(value) {
57
+ const text = value === null || value === undefined ? '' : String(value)
58
+ return text
59
+ .toWellFormed()
60
+ .split(PERCENT_ESCAPE)
61
+ .map((part, index) => (index % 2 ? part : encodeURI(part)))
62
+ .join('')
63
+ }
64
+
65
+ /**
66
+ * The absolute URL of a page: `origin` + `basePath` + the logical `href`
67
+ * (`meta.href`), with the path percent-encoded by `encodePath` but
68
+ * otherwise verbatim (`/index.html` stays). `origin` is used as given
69
+ * (from `resolveOrigin`), `basePath` is core's normalised `app.basePath`
70
+ * (`''` or `'/sub'`).
71
+ *
72
+ * @param {string} origin
73
+ * @param {string} [basePath]
74
+ * @param {string} href
75
+ * @returns {string} e.g. `'https://ex.com/sub/%C3%BCber%20uns.html'`
76
+ */
77
+ export function joinUrl(origin, basePath, href) {
78
+ return `${origin}${encodePath(`${basePath || ''}${href}`)}`
79
+ }
80
+
81
+ /**
82
+ * The site's own URL: `origin` + `basePath` without trailing slashes,
83
+ * percent-encoded like `joinUrl`. Ids such as `<siteUrl>/#website` and
84
+ * absolute links hang off it. A non-string `basePath` gives `origin`.
85
+ *
86
+ * @param {string} origin
87
+ * @param {string} [basePath]
88
+ * @returns {string} e.g. `'https://ex.com/sub'`
89
+ */
90
+ export function siteUrl(origin, basePath) {
91
+ if (typeof basePath !== 'string') return origin
92
+ return `${origin}${encodePath(basePath.replace(/\/+$/, ''))}`
93
+ }
94
+
95
+ /**
96
+ * A site's `base_path` (config/app.yaml) as a URL prefix, exactly as core
97
+ * normalises it into `app.basePath`: a non-string, blank text or `/` gives
98
+ * `''` (a root-served site); otherwise trimmed, trailing slashes dropped and
99
+ * one leading slash guaranteed (`'nera-website'` → `'/nera-website'`,
100
+ * `'/foo/bar/'` → `'/foo/bar'`).
101
+ *
102
+ * @param {unknown} raw
103
+ * @returns {string}
104
+ */
105
+ export function normalizeBasePath(raw) {
106
+ if (typeof raw !== 'string') return ''
107
+ const trimmed = raw.trim()
108
+ if (trimmed === '' || trimmed === '/') return ''
109
+ const noTrailing = trimmed.replace(/\/+$/, '')
110
+ return noTrailing.startsWith('/') ? noTrailing : `/${noTrailing}`
111
+ }
112
+
113
+ /**
114
+ * `url` under `basePath`, as core prefixes every root-absolute URL of a
115
+ * built page: only a string starting with one `/` is prefixed. A
116
+ * protocol-relative `//cdn/…`, a relative or absolute URL with a scheme, a
117
+ * non-string, and a value already under `basePath` (`basePath` itself or
118
+ * `basePath/…`) are returned unchanged, so applying it twice is harmless.
119
+ * An empty `basePath` changes nothing.
120
+ *
121
+ * @param {unknown} url
122
+ * @param {string} basePath normalised, `''` or `'/sub'`
123
+ * @returns {unknown} the prefixed string, or `url` itself
124
+ */
125
+ export function withBasePath(url, basePath) {
126
+ if (!basePath || typeof url !== 'string') return url
127
+ if (!url.startsWith('/') || url.startsWith('//')) return url
128
+ if (url === basePath || url.startsWith(`${basePath}/`)) return url
129
+ return `${basePath}${url}`
130
+ }
131
+
132
+ /**
133
+ * The logical path of a root-absolute `url` under `basePath`, the inverse
134
+ * of `withBasePath`: `basePath` itself gives `'/'`, `basePath/…` loses the
135
+ * prefix, anything else (another path, `/subway` for `/sub`, a non-string)
136
+ * is returned unchanged. An empty `basePath` changes nothing.
137
+ *
138
+ * @param {unknown} url
139
+ * @param {string} basePath normalised, `''` or `'/sub'`
140
+ * @returns {unknown} the stripped string, or `url` itself
141
+ */
142
+ export function stripBasePath(url, basePath) {
143
+ if (!basePath || typeof url !== 'string') return url
144
+ if (url === basePath) return '/'
145
+ return url.startsWith(`${basePath}/`) ? url.slice(basePath.length) : url
146
+ }
147
+
148
+ /**
149
+ * Whether `url` starts with a URL scheme (`https:`, `mailto:`, `tel:`,
150
+ * `data:`, case-insensitive). `//host/…` has none; a non-string is `false`.
151
+ *
152
+ * @param {unknown} url
153
+ * @returns {boolean}
154
+ */
155
+ export function hasScheme(url) {
156
+ return typeof url === 'string' && SCHEME.test(url)
157
+ }
158
+
159
+ /**
160
+ * Whether the path `target` is `root` itself or lies below it, compared
161
+ * lexically after `path.resolve` (symlinks are not followed). A child
162
+ * folder literally named `..foo` is inside. With `self: false`, `root`
163
+ * itself does not count ("strictly below").
164
+ *
165
+ * @param {string} root
166
+ * @param {string} target
167
+ * @param {{ self?: boolean }} [options]
168
+ * @returns {boolean}
169
+ */
170
+ export function isInside(root, target, { self = true } = {}) {
171
+ const relative = path.relative(root, target)
172
+ if (relative === '') return self
173
+ return !relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative)
174
+ }
175
+
176
+ // The image candidates of a `srcset` value, with each URL's position, by
177
+ // the HTML standard's rule: candidates are separated by commas, a URL runs
178
+ // to the next whitespace (so `?a=1,2` and `data:…;base64,…` stay whole), a
179
+ // URL's trailing commas end the candidate, and the descriptors run to the
180
+ // next comma outside parentheses.
181
+ function srcsetCandidates(value) {
182
+ const candidates = []
183
+ let pos = 0
184
+ while (pos < value.length) {
185
+ while (pos < value.length && (value[pos] === ',' || WHITESPACE.test(value[pos]))) pos++
186
+ if (pos >= value.length) break
187
+
188
+ const start = pos
189
+ while (pos < value.length && !WHITESPACE.test(value[pos])) pos++
190
+ let end = pos
191
+ if (value[end - 1] === ',') {
192
+ while (value[end - 1] === ',') end--
193
+ candidates.push({ start, end })
194
+ continue
195
+ }
196
+ candidates.push({ start, end })
197
+
198
+ // The standard's tokenizer does not nest parentheses: the first `)`
199
+ // leaves them, whatever `(` came before it.
200
+ let inParens = false
201
+ while (pos < value.length && (value[pos] !== ',' || inParens)) {
202
+ if (value[pos] === '(') inParens = true
203
+ else if (value[pos] === ')') inParens = false
204
+ pos++
205
+ }
206
+ }
207
+ return candidates
208
+ }
209
+
210
+ /**
211
+ * The URLs of a `srcset` value, in order, parsed by the HTML standard's
212
+ * candidate rule: a URL ends at whitespace, so a comma inside it
213
+ * (`/a.jpg?a=1,2`, a data URI) does not split it. A non-string gives `[]`.
214
+ *
215
+ * @param {unknown} value e.g. `'/a.jpg 1x, /b.jpg 2x'`
216
+ * @returns {string[]}
217
+ */
218
+ export function srcsetUrls(value) {
219
+ if (typeof value !== 'string') return []
220
+ return srcsetCandidates(value).map(({ start, end }) => value.slice(start, end))
221
+ }
222
+
223
+ /**
224
+ * `value` with every candidate URL of the `srcset` replaced by
225
+ * `fn(url, index)` (converted with `String()`), found as `srcsetUrls`
226
+ * finds them. Everything else, descriptors, commas and whitespace, is kept
227
+ * byte for byte, so an `fn` that returns its argument gives `value` back.
228
+ * A non-string is returned unchanged.
229
+ *
230
+ * @param {unknown} value
231
+ * @param {(url: string, index: number) => unknown} fn
232
+ * @returns {unknown}
233
+ */
234
+ export function mapSrcset(value, fn) {
235
+ if (typeof value !== 'string') return value
236
+ let result = ''
237
+ let last = 0
238
+ srcsetCandidates(value).forEach(({ start, end }, index) => {
239
+ result += value.slice(last, start) + String(fn(value.slice(start, end), index))
240
+ last = end
241
+ })
242
+ return result + value.slice(last)
243
+ }