@nera-static/plugin-images 1.0.3 → 1.1.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.
@@ -1,8 +1,9 @@
1
- import fs from 'fs'
2
- import path from 'path'
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
3
  import { resolveTheme } from '@nera-static/core/theme'
4
+ import { hasScheme, isInside, stripBasePath } from '@nera-static/plugin-utils/urls'
4
5
 
5
- // URL in the rendered HTML → absolute source file (ROADMAP D5).
6
+ // URL in the rendered HTML → absolute source file.
6
7
  //
7
8
  // Lookup order is the site's assets folder, then the theme's: the same order
8
9
  // in which the site's files override the theme's in `public/`, so the plugin
@@ -10,9 +11,6 @@ import { resolveTheme } from '@nera-static/core/theme'
10
11
 
11
12
  export const RASTER_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.webp', '.avif', '.tif', '.tiff']
12
13
 
13
- // `http:`, `https:`, `mailto:`, `data:`, … and protocol-relative `//host/…`.
14
- const SCHEME = /^[a-z][a-z0-9+.-]*:/i
15
-
16
14
  /**
17
15
  * The folders a source image may live in, most specific first.
18
16
  *
@@ -36,19 +34,6 @@ export function sourceRoots({ app = {}, cwd = process.cwd() } = {}) {
36
34
  return roots
37
35
  }
38
36
 
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
37
  /**
53
38
  * Split `src` into path, query and hash without touching their encoding.
54
39
  */
@@ -85,7 +70,7 @@ export function resolveSource(src, { pageHref = '/index.html', basePath = '', ro
85
70
  const url = typeof src === 'string' ? src.trim() : ''
86
71
  if (url === '') return { skip: 'empty' }
87
72
  if (/^data:/i.test(url)) return { skip: 'data' }
88
- if (url.startsWith('//') || SCHEME.test(url)) return { skip: 'external' }
73
+ if (url.startsWith('//') || hasScheme(url)) return { skip: 'external' }
89
74
 
90
75
  const { pathname: raw, search, hash } = splitUrl(url)
91
76
  if (raw === '') return { skip: 'empty' }
@@ -101,9 +86,7 @@ export function resolveSource(src, { pageHref = '/index.html', basePath = '', ro
101
86
  if (decoded.startsWith('/')) {
102
87
  // Root-absolute: a base_path prefix is a deploy detail, not part of the
103
88
  // asset's location under assets/.
104
- logical = basePath && (decoded === basePath || decoded.startsWith(`${basePath}/`))
105
- ? decoded.slice(basePath.length) || '/'
106
- : decoded
89
+ logical = stripBasePath(decoded, basePath)
107
90
  } else {
108
91
  // Page-relative: against the page's own folder, in the logical
109
92
  // (un-prefixed) namespace `meta.href` lives in.
@@ -1,14 +1,14 @@
1
1
  import { load } from 'cheerio'
2
2
  import { MIME_TYPES } from './transform.js'
3
3
 
4
- // The content pass (ROADMAP D5, D6): every `<img>` in a page's rendered HTML
4
+ // The content pass: every `<img>` in a page's rendered HTML
5
5
  // that the plugin may process is handed to a callback, and the image it
6
6
  // describes replaces the `<img>` as `<picture>` markup. Which file a URL means
7
7
  // and how its variants are produced is the callback's business; this module
8
8
  // only decides which elements to touch and what the output looks like.
9
9
 
10
10
  // Attributes the plugin computes itself. An author's own value for these is
11
- // replaced (width/height always reflect the emitted variant, D6).
11
+ // replaced (width/height always reflect the emitted variant).
12
12
  const OWNED = new Set(['src', 'srcset', 'sizes', 'width', 'height'])
13
13
 
14
14
  // Loading hints. An author's explicit value wins (decided 2026-10-09); the
@@ -36,7 +36,7 @@ function srcsetOf(variants, outputPath) {
36
36
  /**
37
37
  * Group planned variants by format, keeping `planVariants`' order: modern
38
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
39
+ * by width. A WebP source with `formats: [avif, webp]` therefore yields
40
40
  * one modern group, not two: its WebP set *is* the fallback.
41
41
  */
42
42
  function groupByFormat(variants) {
@@ -52,7 +52,7 @@ function groupByFormat(variants) {
52
52
  }
53
53
 
54
54
  /**
55
- * The inline style of a placeholder (D10), or `''` without one:
55
+ * The inline style of a placeholder, or `''` without one:
56
56
  * `background-color` for `color`, the data URI as a covering
57
57
  * `background-image` for `blur`.
58
58
  *
@@ -65,9 +65,9 @@ export function placeholderStyle({ color, blur }) {
65
65
  }
66
66
 
67
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.
68
+ * The attributes of the new `<img>`, in a fixed order (the same input always
69
+ * gives the same bytes): the computed ones first, then the author's own in
70
+ * their original order, then the loading hints.
71
71
  *
72
72
  * A placeholder adds `style` right after `height`; an author's own `style` is
73
73
  * appended to it there, so the author's declarations still win.
@@ -111,8 +111,8 @@ export function imgAttributes(original, image, eager) {
111
111
  * The data behind one image's markup: the fallback `<img>` (`src`, `srcset`,
112
112
  * `sizes`, `width`, `height`, `type`) and one `{ type, srcset }` per modern
113
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)
114
+ * and the frontmatter pass hands it to templates as `meta.images.<key>`,
115
+ * so both always describe the same files the same way. A placeholder
116
116
  * comes along as `color` or `blur` when the image has one.
117
117
  *
118
118
  * @param {{ variants: object[], width: number, height: number }} image
@@ -142,7 +142,7 @@ export function pictureData(image, { outputPath, sizes }) {
142
142
  }
143
143
 
144
144
  /**
145
- * Build the replacement for one `<img>` (D6).
145
+ * Build the replacement for one `<img>`.
146
146
  *
147
147
  * With at least one modern format, a `<picture>` with one `<source>` per
148
148
  * modern format and the fallback `<img>`; with none (`formats: []`), the
@@ -169,7 +169,7 @@ export function buildPicture($, original, image, { outputPath, sizes, eager }) {
169
169
  const CAPTION_ATTR = 'title'
170
170
 
171
171
  /**
172
- * The `<p>` an image may turn into a `<figure>` (D8): its parent paragraph,
172
+ * The `<p>` an image may turn into a `<figure>`: its parent paragraph,
173
173
  * when the image is that paragraph's only content (whitespace aside) and the
174
174
  * paragraph carries no attributes of its own. markdown-it wraps a lone
175
175
  * image in a bare `<p>`, and `<figure>` inside `<p>` is invalid HTML, so the
@@ -182,7 +182,7 @@ function figureSlot(node) {
182
182
  const parent = node.parent()
183
183
  if (!parent.is('p') || Object.keys(parent.attr() || {}).length > 0) return null
184
184
  const alone = parent.contents().toArray().every((child) =>
185
- child === node[0] || (child.type === 'text' && child.data.trim() === '')
185
+ child === node[0] || (child.type === 'text' && child.data.trim() === ''),
186
186
  )
187
187
  return alone ? parent : null
188
188
  }
@@ -190,26 +190,26 @@ function figureSlot(node) {
190
190
  /**
191
191
  * Rewrite every processable `<img>` in `html`.
192
192
  *
193
- * Left untouched (D5): an `<img>` inside `<picture>`, one with a `srcset`
193
+ * Left untouched: an `<img>` inside `<picture>`, one with a `srcset`
194
194
  * already set, and one carrying `data-nera-skip` (the attribute itself is
195
195
  * removed). Everything else is offered to `handle(src)`, which answers with
196
196
  *
197
197
  * - `null`: leave the `<img>` as it is (external, SVG, missing file, encode
198
198
  * error: the callback decides and warns);
199
- * - `{ src }`: leave it in place, but with this `src` (`?skip`, D7, whose
199
+ * - `{ src }`: leave it in place, but with this `src` (`?skip`, whose
200
200
  * parameters are stripped);
201
201
  * - `{ image, sizes?, loading? }`: the generated image, with this image's
202
202
  * `sizes` (default: `options.sizes`) and an explicit `loading` (`?loading`,
203
203
  * which overrides the author's attribute and the eager-first choice).
204
204
  *
205
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
206
+ * `eagerFirst` is set (decided 2026-10-09: an untouched SVG or external
207
207
  * image before it does not count).
208
208
  *
209
209
  * With `figure: 'title'`, a rewritten image with a non-empty `title` that is
210
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>`.
211
+ * `figcaption.nera-image__caption`, and the `title` attribute is dropped.
212
+ * Otherwise the title stays on the `<img>`.
213
213
  *
214
214
  * Images are generated concurrently; the markup is assembled afterwards in
215
215
  * document order, so the result does not depend on encode timing.
@@ -279,7 +279,7 @@ export async function rewriteHtml(html, { handle, outputPath, sizes, eagerFirst,
279
279
  $('<figure>')
280
280
  .addClass('nera-image')
281
281
  .append(picture)
282
- .append($('<figcaption>').addClass('nera-image__caption').text(title))
282
+ .append($('<figcaption>').addClass('nera-image__caption').text(title)),
283
283
  )
284
284
  } else {
285
285
  node.replaceWith(picture)
package/src/transform.js CHANGED
@@ -1,11 +1,11 @@
1
- import fs from 'fs'
2
- import path from 'path'
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
3
  import sharp from 'sharp'
4
4
 
5
5
  // What to produce for one source image (planVariants, pure) and how to produce
6
- // one variant (encodeVariant, sharp). ROADMAP D6 (output), D7 (parameters).
6
+ // one variant (encodeVariant, sharp).
7
7
 
8
- // The `<img>` fallback stays in the source's own family (D6); formats a
8
+ // The `<img>` fallback stays in the source's own family; formats a
9
9
  // browser cannot show in `<img>` fall back to JPEG. sharp reports AVIF (and
10
10
  // HEIC) sources as `heif`.
11
11
  const FALLBACK_FORMAT = {
@@ -114,7 +114,7 @@ function sizer(source, geo) {
114
114
  /**
115
115
  * Plan every variant of one image. Pure: no I/O, the main unit-test target.
116
116
  *
117
- * Widths (D6, D7): the config widths, or with `w` those below `w` plus `w` and
117
+ * Widths: the config widths, or with `w` those below `w` plus `w` and
118
118
  * `2w` (retina). Never upscaled: config widths above the source are dropped
119
119
  * and the source width is used when none is left; `w`/`2w` are capped at it.
120
120
  *
@@ -124,10 +124,10 @@ function sizer(source, geo) {
124
124
  * `entropy` for sharp's strategies). `contain` pads to the aspect, `inside`
125
125
  * scales to fit within it. `w` + `h` take precedence over `ratio`.
126
126
  *
127
- * Formats: one set per modern format, then the fallback (D6). A modern format
127
+ * Formats: one set per modern format, then the fallback. A modern format
128
128
  * equal to the fallback is produced once, as the fallback. `fallback` forces
129
- * the fallback format instead of deriving it from the source (the og preset,
130
- * D9, is always JPEG).
129
+ * the fallback format instead of deriving it from the source (the og preset
130
+ * is always JPEG).
131
131
  *
132
132
  * @param {{ width: number, height: number, format: string }} source oriented
133
133
  * @param {object} options `{ widths, formats, quality, w?, h?, ratio?, fit?, focus?, q?, fallback? }`
@@ -142,7 +142,7 @@ export function planVariants(source, options) {
142
142
  let candidates
143
143
  if (w) {
144
144
  candidates = [...widths.filter((x) => x < w), w, 2 * w].map((x) =>
145
- Math.min(x, max)
145
+ Math.min(x, max),
146
146
  )
147
147
  } else {
148
148
  candidates = widths.filter((x) => x <= max)
@@ -168,7 +168,7 @@ export function planVariants(source, options) {
168
168
  fit: geo.fit,
169
169
  crop: geo.crop,
170
170
  aspect: geo.aspect,
171
- }))
171
+ })),
172
172
  )
173
173
  }
174
174
 
@@ -195,18 +195,18 @@ function shape(input, { width, height, fit, crop }) {
195
195
 
196
196
  function encoder(image, { format, quality }) {
197
197
  switch (format) {
198
- case 'avif':
199
- return image.avif({ quality })
200
- case 'webp':
201
- return image.webp({ quality })
202
- case 'png':
203
- // Lossless; `quality` only matters with palette quantisation, which
204
- // stays off (see the config reference).
205
- return image.png()
206
- case 'jpeg':
207
- return image.flatten({ background: '#ffffff' }).jpeg({ quality, mozjpeg: true })
208
- default:
209
- throw new Error(`unsupported output format "${format}"`)
198
+ case 'avif':
199
+ return image.avif({ quality })
200
+ case 'webp':
201
+ return image.webp({ quality })
202
+ case 'png':
203
+ // Lossless; `quality` only matters with palette quantisation, which
204
+ // stays off (see the config reference).
205
+ return image.png()
206
+ case 'jpeg':
207
+ return image.flatten({ background: '#ffffff' }).jpeg({ quality, mozjpeg: true })
208
+ default:
209
+ throw new Error(`unsupported output format "${format}"`)
210
210
  }
211
211
  }
212
212
 
@@ -215,7 +215,7 @@ function encoder(image, { format, quality }) {
215
215
  *
216
216
  * Applies EXIF orientation, crops, resizes, converts to sRGB and encodes.
217
217
  * Metadata is stripped: that is sharp's default, and `.withMetadata()` is never
218
- * called (D6). The file is written to a temporary name and renamed into place,
218
+ * called. The file is written to a temporary name and renamed into place,
219
219
  * so an interrupted build never leaves a truncated file the cache would later
220
220
  * take for a finished one.
221
221
  *
@@ -250,7 +250,7 @@ const scaled = (variant, width) => {
250
250
  const hex = (value) => Math.round(value).toString(16).padStart(2, '0')
251
251
 
252
252
  /**
253
- * The placeholder of one image (D10), computed from its largest variant's
253
+ * The placeholder of one image, computed from its largest variant's
254
254
  * geometry so it shows the same crop the visitor will see.
255
255
  *
256
256
  * - `color`: the dominant colour as `#rrggbb`;
package/src/guard.js DELETED
@@ -1,73 +0,0 @@
1
- import { createRequire } from 'module'
2
- import path from 'path'
3
-
4
- // D12 runtime safety net. The plugin rewrites pages to reference files it only
5
- // hands to core through `getAssets`, which core calls from 4.13.0 on. On an
6
- // older core the hook is never called, every rewritten page points at missing
7
- // files, and the build would still exit 0. So the plugin checks core's version
8
- // and fails loudly instead. `peerDependencies` reports the same at install
9
- // time; this catches an install that ignored it.
10
-
11
- export const REQUIRED_CORE = '4.13.0'
12
-
13
- const parse = (version) => {
14
- const match = /^(\d+)\.(\d+)\.(\d+)/.exec(String(version).trim())
15
- return match ? match.slice(1, 4).map(Number) : null
16
- }
17
-
18
- /**
19
- * True when `version` is at least `required` (major.minor.patch; a
20
- * prerelease suffix is ignored). False for anything unparseable.
21
- */
22
- export function satisfies(version, required = REQUIRED_CORE) {
23
- const have = parse(version)
24
- const need = parse(required)
25
- if (!have || !need) return false
26
- for (let i = 0; i < 3; i++) {
27
- if (have[i] !== need[i]) return have[i] > need[i]
28
- }
29
- return true
30
- }
31
-
32
- /**
33
- * The version of `@nera-static/core` this build most likely runs on, or
34
- * `null` when it cannot be found.
35
- *
36
- * Resolved from the site root first: that is the core `nera` loads. Only
37
- * when the site has none is it resolved from the plugin's own location. The
38
- * plugin's location alone is not enough: Node resolves a symlinked plugin
39
- * (`npm install ../nera-plugin-images`, `npm link`) from its real path, where
40
- * its own devDependency core would answer for the site's (found in the
41
- * slice 7 field test, decided 2026-10-09).
42
- *
43
- * @param {string} [cwd]
44
- */
45
- export function coreVersion(cwd = process.cwd()) {
46
- const bases = [path.join(cwd, 'package.json'), import.meta.url]
47
- for (const base of bases) {
48
- try {
49
- return createRequire(base)('@nera-static/core/package.json').version
50
- } catch {
51
- // Try the next base.
52
- }
53
- }
54
- return null
55
- }
56
-
57
- /**
58
- * Throw when core is known to be older than `REQUIRED_CORE`. An unknown
59
- * version (core not resolvable from here) passes: the plugin is running inside
60
- * a build, so some core is calling it, and refusing on a guess would block a
61
- * working setup.
62
- *
63
- * @param {string|null} version
64
- */
65
- export function assertCoreVersion(version) {
66
- if (version === null || satisfies(version)) return
67
- throw new Error(
68
- `plugin-images: @nera-static/core ${version} is too old; this plugin needs ` +
69
- `>= ${REQUIRED_CORE} (the getAssets hook). Without it, pages would link ` +
70
- 'to image files that are never copied to public/. Update with ' +
71
- '`npm update @nera-static/nera` (or `@nera-static/core`).'
72
- )
73
- }
package/src/warn.js DELETED
@@ -1,6 +0,0 @@
1
- // One prefix for every message the plugin prints, matching the fleet's
2
- // `⚠️ plugin-<name>: …` style, so a site owner can tell where a warning came
3
- // from in a build log full of other plugins.
4
- export function warn(message) {
5
- console.warn(`⚠️ plugin-images: ${message}`)
6
- }