@nera-static/plugin-images 0.0.0-stage → 1.0.1

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/params.js ADDED
@@ -0,0 +1,173 @@
1
+ import { FITS, MODERN_FORMATS } from './config.js'
2
+ import { STRATEGIES } from './transform.js'
3
+
4
+ // Per-image options as Glide-style query parameters on the image URL
5
+ // (ROADMAP D7): `![alt](/images/a.jpg?w=800&ratio=16:9)`. Query strings
6
+ // survive Markdown rendering untouched, so the plugin reads them from the
7
+ // rendered `src`. Parsing is pure: problems come back as `warnings` for the
8
+ // caller to print with the page and the URL, and a bad value falls back to the
9
+ // default rather than failing the build.
10
+
11
+ export const PARAMS = ['w', 'h', 'ratio', 'fit', 'focus', 'q', 'formats', 'sizes', 'loading', 'skip']
12
+
13
+ const POSITIVE_INT = /^[1-9]\d*$/
14
+ const NUMBER = '(\\d+(?:\\.\\d+)?)'
15
+ const RATIO = new RegExp(`^${NUMBER}:${NUMBER}$`)
16
+ const FOCUS = new RegExp(`^${NUMBER},${NUMBER}$`)
17
+
18
+ const show = (value) => JSON.stringify(value)
19
+
20
+ // The query string as `[key, value]` pairs, decoded like a browser would
21
+ // (`+` is a space, so `?sizes=50vw` and `?sizes=(min-width:+600px)+50vw` work).
22
+ function pairs(search) {
23
+ const query = search.startsWith('?') ? search.slice(1) : search
24
+ return query === '' ? [] : [...new URLSearchParams(query)]
25
+ }
26
+
27
+ const readers = {
28
+ w: (value) => (POSITIVE_INT.test(value) ? Number(value) : undefined),
29
+ h: (value) => (POSITIVE_INT.test(value) ? Number(value) : undefined),
30
+ q: (value) => {
31
+ const q = POSITIVE_INT.test(value) ? Number(value) : 0
32
+ return q >= 1 && q <= 100 ? q : undefined
33
+ },
34
+ ratio: (value) => {
35
+ const match = RATIO.exec(value)
36
+ if (!match) return undefined
37
+ const [width, height] = [Number(match[1]), Number(match[2])]
38
+ return width > 0 && height > 0 ? width / height : undefined
39
+ },
40
+ fit: (value) => (FITS.includes(value) ? value : undefined),
41
+ focus: (value) => {
42
+ if (STRATEGIES.includes(value)) return value
43
+ const match = FOCUS.exec(value)
44
+ if (!match) return undefined
45
+ const [x, y] = [Number(match[1]), Number(match[2])]
46
+ return x <= 100 && y <= 100 ? { x, y } : undefined
47
+ },
48
+ sizes: (value) => (value.trim() === '' ? undefined : value.trim()),
49
+ loading: (value) => (value === 'eager' || value === 'lazy' ? value : undefined),
50
+ }
51
+
52
+ // `formats=none` → no modern format; `formats=webp,avif` → in that order.
53
+ // Unknown entries are dropped with a warning; nothing usable left falls back
54
+ // to the config's formats.
55
+ function readFormats(value, warnings) {
56
+ if (value === 'none') return []
57
+ const formats = []
58
+ for (const format of value.split(',').map((f) => f.trim())) {
59
+ if (MODERN_FORMATS.includes(format)) {
60
+ if (!formats.includes(format)) formats.push(format)
61
+ } else {
62
+ warnings.push(`unknown format ${show(format)} in formats ignored`)
63
+ }
64
+ }
65
+ if (formats.length === 0) {
66
+ warnings.push(`invalid formats ${show(value)}, using the default`)
67
+ return undefined
68
+ }
69
+ return formats
70
+ }
71
+
72
+ /**
73
+ * Parse an image URL's query string (D7).
74
+ *
75
+ * @param {string} search the query, with or without the leading `?`
76
+ * @returns {{
77
+ * skip: boolean,
78
+ * options: { w?, h?, ratio?, fit?, focus?, q?, formats? },
79
+ * sizes?: string,
80
+ * loading?: 'eager'|'lazy',
81
+ * warnings: string[],
82
+ * }} `options` holds only the parameters that were given and valid, ready to
83
+ * spread over the config's `planVariants` options
84
+ */
85
+ export function parseParams(search = '') {
86
+ const result = { skip: false, options: {}, warnings: [] }
87
+ const values = {}
88
+
89
+ for (const [key, value] of pairs(search)) {
90
+ if (!PARAMS.includes(key)) {
91
+ result.warnings.push(`unknown parameter ${show(key)} ignored`)
92
+ continue
93
+ }
94
+ // A repeated parameter: the last one wins, as with URLSearchParams.get.
95
+ values[key] = value
96
+ }
97
+
98
+ if ('skip' in values) result.skip = true
99
+
100
+ for (const [key, value] of Object.entries(values)) {
101
+ if (key === 'skip') continue
102
+ const parsed = key === 'formats'
103
+ ? readFormats(value, result.warnings)
104
+ : readers[key](value)
105
+ if (parsed === undefined) {
106
+ if (key !== 'formats') {
107
+ result.warnings.push(`invalid ${key} ${show(value)}, using the default`)
108
+ }
109
+ continue
110
+ }
111
+ if (key === 'sizes' || key === 'loading') result[key] = parsed
112
+ else result.options[key] = parsed
113
+ }
114
+
115
+ // Parameters that are valid but cannot do anything on their own. The plan
116
+ // ignores them; say so rather than leave the author guessing.
117
+ const { w, h, ratio, fit, focus } = result.options
118
+ const aspect = Boolean((w && h) || ratio)
119
+ if (h && !w) {
120
+ result.warnings.push('h has no effect without w, ignored')
121
+ }
122
+ if (fit && !aspect) {
123
+ result.warnings.push('fit has no effect without ratio or w and h, ignored')
124
+ }
125
+ if (focus && (!aspect || (fit && fit !== 'cover'))) {
126
+ result.warnings.push('focus only applies to a cover crop (ratio or w and h), ignored')
127
+ }
128
+ return result
129
+ }
130
+
131
+ /**
132
+ * The `sizes` attribute for one image: an explicit `?sizes`, else one derived
133
+ * from `?w` (D7), else the config default.
134
+ *
135
+ * @param {ReturnType<typeof parseParams>} params
136
+ * @param {string} fallback the config's `sizes`
137
+ */
138
+ export function sizesFor(params, fallback) {
139
+ if (params.sizes) return params.sizes
140
+ const { w } = params.options
141
+ return w ? `(min-width: ${w}px) ${w}px, 100vw` : fallback
142
+ }
143
+
144
+ /**
145
+ * `src` without the recognized parameters (D7), for an image the plugin
146
+ * leaves in place (`?skip`). Unknown parameters (a cache buster, say) and the
147
+ * hash stay exactly as written; an emptied query loses its `?`.
148
+ *
149
+ * @param {string} src
150
+ */
151
+ export function stripParams(src) {
152
+ const hashAt = src.indexOf('#')
153
+ const hash = hashAt === -1 ? '' : src.slice(hashAt)
154
+ const rest = hashAt === -1 ? src : src.slice(0, hashAt)
155
+ const queryAt = rest.indexOf('?')
156
+ if (queryAt === -1) return src
157
+
158
+ const kept = rest
159
+ .slice(queryAt + 1)
160
+ .split('&')
161
+ .filter((part) => {
162
+ if (part === '') return false
163
+ const key = part.split('=')[0]
164
+ let name
165
+ try {
166
+ name = decodeURIComponent(key.replace(/\+/g, ' '))
167
+ } catch {
168
+ return true
169
+ }
170
+ return !PARAMS.includes(name)
171
+ })
172
+ return `${rest.slice(0, queryAt)}${kept.length ? `?${kept.join('&')}` : ''}${hash}`
173
+ }
package/src/queue.js ADDED
@@ -0,0 +1,61 @@
1
+ // Bounded-concurrency task queue with keyed de-duplication (ROADMAP D13).
2
+ // No dependency: it is a counter, a waiting list and a promise map.
3
+ //
4
+ // The same image used on several pages produces the same variant keys, so a
5
+ // key that is already queued, running or finished returns the existing
6
+ // promise instead of encoding again. The map lives as long as the queue,
7
+ // which is one build.
8
+
9
+ /**
10
+ * @param {{ concurrency?: number }} [options] at least 1
11
+ */
12
+ export function createQueue({ concurrency = 1 } = {}) {
13
+ const limit = Math.max(1, Math.floor(concurrency) || 1)
14
+ const waiting = []
15
+ const byKey = new Map()
16
+ let running = 0
17
+
18
+ const next = () => {
19
+ while (running < limit && waiting.length > 0) {
20
+ const { task, resolve, reject } = waiting.shift()
21
+ running++
22
+ Promise.resolve()
23
+ .then(task)
24
+ .then(resolve, reject)
25
+ .finally(() => {
26
+ running--
27
+ next()
28
+ })
29
+ }
30
+ }
31
+
32
+ return {
33
+ /**
34
+ * Schedule `task` (a function returning a promise). With a `key`, a
35
+ * second call for the same key returns the first call's promise and
36
+ * never runs its own task.
37
+ *
38
+ * @template T
39
+ * @param {() => Promise<T>|T} task
40
+ * @param {string} [key]
41
+ * @returns {Promise<T>}
42
+ */
43
+ add(task, key) {
44
+ if (key !== undefined && byKey.has(key)) return byKey.get(key)
45
+
46
+ const promise = new Promise((resolve, reject) => {
47
+ waiting.push({ task, resolve, reject })
48
+ })
49
+ if (key !== undefined) byKey.set(key, promise)
50
+ next()
51
+ return promise
52
+ },
53
+
54
+ get running() {
55
+ return running
56
+ },
57
+ get pending() {
58
+ return waiting.length
59
+ },
60
+ }
61
+ }
@@ -0,0 +1,135 @@
1
+ import fs from 'fs'
2
+ import path from 'path'
3
+ import { resolveTheme } from '@nera-static/core/theme'
4
+
5
+ // URL in the rendered HTML → absolute source file (ROADMAP D5).
6
+ //
7
+ // Lookup order is the site's assets folder, then the theme's: the same order
8
+ // in which the site's files override the theme's in `public/`, so the plugin
9
+ // processes exactly the file a visitor would otherwise have downloaded.
10
+
11
+ export const RASTER_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.webp', '.avif', '.tif', '.tiff']
12
+
13
+ // `http:`, `https:`, `mailto:`, `data:`, … and protocol-relative `//host/…`.
14
+ const SCHEME = /^[a-z][a-z0-9+.-]*:/i
15
+
16
+ /**
17
+ * The folders a source image may live in, most specific first.
18
+ *
19
+ * During the plugin stage `app.theme` is no longer the spec string from
20
+ * app.yaml but core's `{ name, package, config }` object (core attaches it
21
+ * before running plugins), so the spec is read back from `.name`.
22
+ *
23
+ * @param {{ app?: object, cwd?: string }} options
24
+ * @returns {string[]} absolute directories (site assets, then theme assets)
25
+ */
26
+ export function sourceRoots({ app = {}, cwd = process.cwd() } = {}) {
27
+ const roots = [path.resolve(cwd, app.folders?.assets || './assets')]
28
+
29
+ const spec = typeof app.theme === 'object' && app.theme !== null
30
+ ? app.theme.name
31
+ : app.theme
32
+ const theme = resolveTheme({ app: { ...app, theme: spec }, cwd })
33
+ if (theme && !roots.includes(theme.assetsRoot)) {
34
+ roots.push(theme.assetsRoot)
35
+ }
36
+ return roots
37
+ }
38
+
39
+ /**
40
+ * True when `file` is `root` itself or below it.
41
+ */
42
+ export function isInside(root, file) {
43
+ const relative = path.relative(root, file)
44
+ return (
45
+ relative === '' ||
46
+ (relative !== '..' &&
47
+ !relative.startsWith(`..${path.sep}`) &&
48
+ !path.isAbsolute(relative))
49
+ )
50
+ }
51
+
52
+ /**
53
+ * Split `src` into path, query and hash without touching their encoding.
54
+ */
55
+ export function splitUrl(src) {
56
+ const hashAt = src.indexOf('#')
57
+ const hash = hashAt === -1 ? '' : src.slice(hashAt)
58
+ const rest = hashAt === -1 ? src : src.slice(0, hashAt)
59
+ const queryAt = rest.indexOf('?')
60
+ return {
61
+ pathname: queryAt === -1 ? rest : rest.slice(0, queryAt),
62
+ search: queryAt === -1 ? '' : rest.slice(queryAt),
63
+ hash,
64
+ }
65
+ }
66
+
67
+ /**
68
+ * Resolve an image URL from a page to a source file.
69
+ *
70
+ * Returns `{ file, root, pathname, search, hash }` on success, where
71
+ * `pathname` is the site-logical URL path (base_path stripped, page-relative
72
+ * resolved, decoded). Otherwise `{ skip: reason }`:
73
+ *
74
+ * - `empty` blank `src`
75
+ * - `external` any scheme (`http:`, `https:`, …) or protocol-relative `//`
76
+ * - `data` a `data:` URI
77
+ * - `unsupported` not a raster format the plugin processes (`.svg`, `.gif`, …)
78
+ * - `missing` looks local but no such file under any root (caller warns)
79
+ * - `outside` resolves outside every root (caller warns)
80
+ *
81
+ * @param {string} src the `src` attribute as rendered
82
+ * @param {{ pageHref?: string, basePath?: string, roots: string[] }} options
83
+ */
84
+ export function resolveSource(src, { pageHref = '/index.html', basePath = '', roots }) {
85
+ const url = typeof src === 'string' ? src.trim() : ''
86
+ if (url === '') return { skip: 'empty' }
87
+ if (/^data:/i.test(url)) return { skip: 'data' }
88
+ if (url.startsWith('//') || SCHEME.test(url)) return { skip: 'external' }
89
+
90
+ const { pathname: raw, search, hash } = splitUrl(url)
91
+ if (raw === '') return { skip: 'empty' }
92
+
93
+ let decoded
94
+ try {
95
+ decoded = decodeURIComponent(raw)
96
+ } catch {
97
+ return { skip: 'missing' }
98
+ }
99
+
100
+ let logical
101
+ if (decoded.startsWith('/')) {
102
+ // Root-absolute: a base_path prefix is a deploy detail, not part of the
103
+ // asset's location under assets/.
104
+ logical = basePath && (decoded === basePath || decoded.startsWith(`${basePath}/`))
105
+ ? decoded.slice(basePath.length) || '/'
106
+ : decoded
107
+ } else {
108
+ // Page-relative: against the page's own folder, in the logical
109
+ // (un-prefixed) namespace `meta.href` lives in.
110
+ logical = path.posix.join(path.posix.dirname(pageHref), decoded)
111
+ }
112
+ // Normalizing an absolute posix path clamps `..` at `/`, like a browser.
113
+ const pathname = path.posix.normalize(logical)
114
+
115
+ if (!RASTER_EXTENSIONS.includes(path.posix.extname(pathname).toLowerCase())) {
116
+ return { skip: 'unsupported' }
117
+ }
118
+
119
+ let outside = 0
120
+ for (const root of roots) {
121
+ const file = path.join(root, ...pathname.split('/').filter(Boolean))
122
+ if (!isInside(root, file)) {
123
+ outside++
124
+ continue
125
+ }
126
+ try {
127
+ if (fs.statSync(file).isFile()) {
128
+ return { file, root, pathname, search, hash }
129
+ }
130
+ } catch {
131
+ // Not under this root; try the next.
132
+ }
133
+ }
134
+ return { skip: outside === roots.length && roots.length > 0 ? 'outside' : 'missing' }
135
+ }
@@ -0,0 +1,294 @@
1
+ import { load } from 'cheerio'
2
+ import { MIME_TYPES } from './transform.js'
3
+
4
+ // The content pass (ROADMAP D5, D6): every `<img>` in a page's rendered HTML
5
+ // that the plugin may process is handed to a callback, and the image it
6
+ // describes replaces the `<img>` as `<picture>` markup. Which file a URL means
7
+ // and how its variants are produced is the callback's business; this module
8
+ // only decides which elements to touch and what the output looks like.
9
+
10
+ // Attributes the plugin computes itself. An author's own value for these is
11
+ // replaced (width/height always reflect the emitted variant, D6).
12
+ const OWNED = new Set(['src', 'srcset', 'sizes', 'width', 'height'])
13
+
14
+ // Loading hints. An author's explicit value wins (decided 2026-10-09); the
15
+ // plugin fills in only what is missing, consistent with the mode in effect.
16
+ const LOADING_HINTS = new Set(['loading', 'decoding', 'fetchpriority'])
17
+
18
+ const SKIP_ATTR = 'data-nera-skip'
19
+
20
+ const EAGER = { loading: 'eager', fetchpriority: 'high' }
21
+ const LAZY = { loading: 'lazy', decoding: 'async' }
22
+
23
+ /**
24
+ * Join a cache file name onto the public output path (`/_img` + name).
25
+ */
26
+ export function publicUrl(outputPath, file) {
27
+ return `${outputPath}/${file}`
28
+ }
29
+
30
+ function srcsetOf(variants, outputPath) {
31
+ return variants
32
+ .map((variant) => `${publicUrl(outputPath, variant.file)} ${variant.width}w`)
33
+ .join(', ')
34
+ }
35
+
36
+ /**
37
+ * Group planned variants by format, keeping `planVariants`' order: modern
38
+ * formats first in `formats` order, the `<img>` fallback last, each ascending
39
+ * by width (D13). A WebP source with `formats: [avif, webp]` therefore yields
40
+ * one modern group, not two: its WebP set *is* the fallback.
41
+ */
42
+ function groupByFormat(variants) {
43
+ const groups = new Map()
44
+ for (const variant of variants) {
45
+ if (!groups.has(variant.format)) groups.set(variant.format, [])
46
+ groups.get(variant.format).push(variant)
47
+ }
48
+ return [...groups].map(([format, list]) => ({
49
+ format,
50
+ variants: [...list].sort((a, b) => a.width - b.width),
51
+ }))
52
+ }
53
+
54
+ /**
55
+ * The inline style of a placeholder (D10), or `''` without one:
56
+ * `background-color` for `color`, the data URI as a covering
57
+ * `background-image` for `blur`.
58
+ *
59
+ * @param {{ color?: string, blur?: string }} image
60
+ */
61
+ export function placeholderStyle({ color, blur }) {
62
+ if (blur) return `background-image:url(${blur});background-size:cover`
63
+ if (color) return `background-color:${color}`
64
+ return ''
65
+ }
66
+
67
+ /**
68
+ * The attributes of the new `<img>`, in a fixed order (D13): the computed
69
+ * ones first, then the author's own in their original order, then the
70
+ * loading hints.
71
+ *
72
+ * A placeholder adds `style` right after `height`; an author's own `style` is
73
+ * appended to it there, so the author's declarations still win.
74
+ *
75
+ * @param {object} original the original `<img>`'s attributes
76
+ * @param {object} image `{ src, srcset, sizes, width, height, color?, blur? }`
77
+ * @param {boolean} eager whether this is the page's eager image
78
+ */
79
+ export function imgAttributes(original, image, eager) {
80
+ const attrs = {
81
+ src: image.src,
82
+ srcset: image.srcset,
83
+ sizes: image.sizes,
84
+ width: String(image.width),
85
+ height: String(image.height),
86
+ }
87
+ const placeholder = placeholderStyle(image)
88
+ if (placeholder) {
89
+ const own = original.style?.trim().replace(/;$/, '')
90
+ attrs.style = own ? `${placeholder};${own}` : placeholder
91
+ }
92
+ for (const [name, value] of Object.entries(original)) {
93
+ if (OWNED.has(name) || LOADING_HINTS.has(name) || name === SKIP_ATTR) continue
94
+ if (name === 'style' && placeholder) continue
95
+ attrs[name] = value
96
+ }
97
+
98
+ // An author's `loading` decides the mode; otherwise the plugin's choice.
99
+ const authorLoading = original.loading?.toLowerCase()
100
+ const mode = authorLoading === 'eager' || authorLoading === 'lazy'
101
+ ? (authorLoading === 'eager' ? EAGER : LAZY)
102
+ : (eager ? EAGER : LAZY)
103
+ for (const name of ['loading', 'decoding', 'fetchpriority']) {
104
+ if (original[name] !== undefined) attrs[name] = original[name]
105
+ else if (mode[name] !== undefined) attrs[name] = mode[name]
106
+ }
107
+ return attrs
108
+ }
109
+
110
+ /**
111
+ * The data behind one image's markup: the fallback `<img>` (`src`, `srcset`,
112
+ * `sizes`, `width`, `height`, `type`) and one `{ type, srcset }` per modern
113
+ * format, in `formats` order. The content pass builds its `<picture>` from it,
114
+ * and the frontmatter pass hands it to templates as `meta.images.<key>` (D9),
115
+ * so both always describe the same files the same way. A placeholder (D10)
116
+ * comes along as `color` or `blur` when the image has one.
117
+ *
118
+ * @param {{ variants: object[], width: number, height: number }} image
119
+ * what `generate` returned (variants carry their cache `file`)
120
+ * @param {{ outputPath: string, sizes: string }} options
121
+ */
122
+ export function pictureData(image, { outputPath, sizes }) {
123
+ const groups = groupByFormat(image.variants)
124
+ const fallback = groups[groups.length - 1]
125
+ const largest = fallback.variants[fallback.variants.length - 1]
126
+
127
+ const data = {
128
+ src: publicUrl(outputPath, largest.file),
129
+ srcset: srcsetOf(fallback.variants, outputPath),
130
+ sizes,
131
+ width: image.width,
132
+ height: image.height,
133
+ type: MIME_TYPES[fallback.format],
134
+ sources: groups.slice(0, -1).map((group) => ({
135
+ type: MIME_TYPES[group.format],
136
+ srcset: srcsetOf(group.variants, outputPath),
137
+ })),
138
+ }
139
+ if (image.color) data.color = image.color
140
+ if (image.blur) data.blur = image.blur
141
+ return data
142
+ }
143
+
144
+ /**
145
+ * Build the replacement for one `<img>` (D6).
146
+ *
147
+ * With at least one modern format, a `<picture>` with one `<source>` per
148
+ * modern format and the fallback `<img>`; with none (`formats: []`), the
149
+ * `<img>` alone, still with `srcset`.
150
+ *
151
+ * @param {import('cheerio').CheerioAPI} $
152
+ * @param {object} original the original `<img>`'s attributes
153
+ * @param {{ variants: object[], width: number, height: number }} image
154
+ * what `generate` returned (variants carry their cache `file`)
155
+ * @param {{ outputPath: string, sizes: string, eager: boolean }} options
156
+ */
157
+ export function buildPicture($, original, image, { outputPath, sizes, eager }) {
158
+ const data = pictureData(image, { outputPath, sizes })
159
+ const img = $('<img>').attr(imgAttributes(original, data, eager))
160
+ if (data.sources.length === 0) return img
161
+
162
+ const picture = $('<picture>')
163
+ for (const source of data.sources) {
164
+ picture.append($('<source>').attr({ type: source.type, srcset: source.srcset, sizes }))
165
+ }
166
+ return picture.append(img)
167
+ }
168
+
169
+ const CAPTION_ATTR = 'title'
170
+
171
+ /**
172
+ * The `<p>` an image may turn into a `<figure>` (D8): its parent paragraph,
173
+ * when the image is that paragraph's only content (whitespace aside) and the
174
+ * paragraph carries no attributes of its own. markdown-it wraps a lone
175
+ * image in a bare `<p>`, and `<figure>` inside `<p>` is invalid HTML, so the
176
+ * figure replaces the paragraph. Anywhere else (inline with text, inside a
177
+ * link, in raw HTML) the context may not allow a `<figure>`, so there is none.
178
+ *
179
+ * @returns {import('cheerio').Cheerio|null}
180
+ */
181
+ function figureSlot(node) {
182
+ const parent = node.parent()
183
+ if (!parent.is('p') || Object.keys(parent.attr() || {}).length > 0) return null
184
+ const alone = parent.contents().toArray().every((child) =>
185
+ child === node[0] || (child.type === 'text' && child.data.trim() === '')
186
+ )
187
+ return alone ? parent : null
188
+ }
189
+
190
+ /**
191
+ * Rewrite every processable `<img>` in `html`.
192
+ *
193
+ * Left untouched (D5): an `<img>` inside `<picture>`, one with a `srcset`
194
+ * already set, and one carrying `data-nera-skip` (the attribute itself is
195
+ * removed). Everything else is offered to `handle(src)`, which answers with
196
+ *
197
+ * - `null`: leave the `<img>` as it is (external, SVG, missing file, encode
198
+ * error: the callback decides and warns);
199
+ * - `{ src }`: leave it in place, but with this `src` (`?skip`, D7, whose
200
+ * parameters are stripped);
201
+ * - `{ image, sizes?, loading? }`: the generated image, with this image's
202
+ * `sizes` (default: `options.sizes`) and an explicit `loading` (`?loading`,
203
+ * which overrides the author's attribute and the eager-first choice).
204
+ *
205
+ * The first image actually rewritten on the page is the eager one when
206
+ * `eagerFirst` is set (D6, decided 2026-10-09: an untouched SVG or external
207
+ * image before it does not count).
208
+ *
209
+ * With `figure: 'title'`, a rewritten image with a non-empty `title` that is
210
+ * alone in its paragraph becomes `figure.nera-image` with the title as
211
+ * `figcaption.nera-image__caption`, and the `title` attribute is dropped
212
+ * (D8). Otherwise the title stays on the `<img>`.
213
+ *
214
+ * Images are generated concurrently; the markup is assembled afterwards in
215
+ * document order, so the result does not depend on encode timing.
216
+ *
217
+ * @param {string} html a page's rendered content
218
+ * @param {object} options
219
+ * @param {(src: string) => Promise<object|null>} options.handle
220
+ * @param {string} options.outputPath public URL path, e.g. `/_img`
221
+ * @param {string} options.sizes default `sizes`
222
+ * @param {boolean} options.eagerFirst
223
+ * @param {'title'|false} [options.figure]
224
+ * @returns {Promise<{ html: string, count: number }>} `html` is the input
225
+ * unchanged (same string) when nothing was touched
226
+ */
227
+ export async function rewriteHtml(html, { handle, outputPath, sizes, eagerFirst, figure = false }) {
228
+ if (typeof html !== 'string' || !/<img\b/i.test(html)) {
229
+ return { html, count: 0 }
230
+ }
231
+
232
+ const $ = load(html, null, false)
233
+ let changed = false
234
+ const candidates = []
235
+
236
+ $('img').each((_, el) => {
237
+ const node = $(el)
238
+ if (node.attr(SKIP_ATTR) !== undefined) {
239
+ node.removeAttr(SKIP_ATTR)
240
+ changed = true
241
+ return
242
+ }
243
+ if (node.closest('picture').length > 0) return
244
+ if (node.attr('srcset') !== undefined) return
245
+ candidates.push(node)
246
+ })
247
+
248
+ const results = await Promise.all(candidates.map((node) => handle(node.attr('src') ?? '')))
249
+
250
+ let count = 0
251
+ candidates.forEach((node, i) => {
252
+ const result = results[i]
253
+ if (!result) return
254
+
255
+ if (!result.image) {
256
+ if (result.src !== node.attr('src')) {
257
+ node.attr('src', result.src)
258
+ changed = true
259
+ }
260
+ return
261
+ }
262
+
263
+ const original = { ...node.attr() }
264
+ if (result.loading) original.loading = result.loading
265
+
266
+ const title = original[CAPTION_ATTR]
267
+ const slot = figure === 'title' && title && title.trim() !== '' ? figureSlot(node) : null
268
+ if (slot) delete original[CAPTION_ATTR]
269
+
270
+ const eager = eagerFirst && count === 0
271
+ const picture = buildPicture($, original, result.image, {
272
+ outputPath,
273
+ sizes: result.sizes || sizes,
274
+ eager,
275
+ })
276
+
277
+ if (slot) {
278
+ slot.replaceWith(
279
+ $('<figure>')
280
+ .addClass('nera-image')
281
+ .append(picture)
282
+ .append($('<figcaption>').addClass('nera-image__caption').text(title))
283
+ )
284
+ } else {
285
+ node.replaceWith(picture)
286
+ }
287
+ count++
288
+ changed = true
289
+ })
290
+
291
+ // Re-serializing can normalize unrelated markup (entities, quoting), so a
292
+ // page without a rewritten image keeps its exact original string.
293
+ return { html: changed ? $.html() : html, count }
294
+ }