@nera-static/plugin-images 1.0.2 → 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.
package/src/cache.js CHANGED
@@ -1,11 +1,12 @@
1
- import crypto from 'crypto'
2
- import fs from 'fs'
3
- import path from 'path'
1
+ import crypto from 'node:crypto'
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
4
  import { slugify } from '@nera-static/plugin-utils'
5
+ import { isPlainObject } from '@nera-static/plugin-utils/values'
5
6
  import { EXTENSIONS } from './transform.js'
6
- import { warn } from './warn.js'
7
+ import { log } from './log.js'
7
8
 
8
- // The variant cache (ROADMAP D3, D4): `<dir>/files/` holds every generated
9
+ // The variant cache: `<dir>/files/` holds every generated
9
10
  // file, `<dir>/manifest.json` one entry per image. A variant is encoded only
10
11
  // when its file is missing, and pruning removes what a build did not use.
11
12
 
@@ -50,7 +51,7 @@ export function imageKey(digest, options) {
50
51
  }
51
52
 
52
53
  /**
53
- * D3 `hash8` of one variant: source bytes + transform parameters + cache
54
+ * The `hash8` of one variant: source bytes + transform parameters + cache
54
55
  * version. Width is left out on purpose, it is part of the file name, so all
55
56
  * widths of one format share a hash and the files sort together.
56
57
  */
@@ -60,7 +61,7 @@ export function variantHash(digest, { format, quality, fit, crop, aspect }) {
60
61
  }
61
62
 
62
63
  /**
63
- * `<basename>-<hash8>-<width>.<ext>` (D3). The basename is slugified so a
64
+ * `<basename>-<hash8>-<width>.<ext>`. The basename is slugified so a
64
65
  * photo named `Straße am Meer.JPG` yields a URL that needs no escaping;
65
66
  * a name with nothing usable left becomes `image`.
66
67
  */
@@ -78,11 +79,11 @@ function readManifest(file) {
78
79
  }
79
80
  try {
80
81
  const parsed = JSON.parse(raw)
81
- if (parsed?.version === CACHE_VERSION && parsed.entries && typeof parsed.entries === 'object') {
82
+ if (parsed?.version === CACHE_VERSION && isPlainObject(parsed.entries)) {
82
83
  return parsed.entries
83
84
  }
84
85
  } catch {
85
- warn(`ignoring unreadable cache manifest ${file}`)
86
+ log.warn(`ignoring unreadable cache manifest ${file}`)
86
87
  }
87
88
  // Another cache version or a broken file: start empty. Nothing references
88
89
  // the old files any more, so the next prune removes them.
@@ -123,17 +124,17 @@ export function openCache(dir) {
123
124
  /** Write the manifest (temp file + rename, so it is never half-written). */
124
125
  save() {
125
126
  const sorted = Object.fromEntries(
126
- Object.keys(entries).sort().map((key) => [key, entries[key]])
127
+ Object.keys(entries).sort().map((key) => [key, entries[key]]),
127
128
  )
128
129
  writeAtomic(
129
130
  manifestFile,
130
- `${JSON.stringify({ version: CACHE_VERSION, entries: sorted }, null, 2)}\n`
131
+ `${JSON.stringify({ version: CACHE_VERSION, entries: sorted }, null, 2)}\n`,
131
132
  )
132
133
  },
133
134
 
134
135
  /**
135
136
  * Drop every manifest entry not in `usedKeys`, then every file in
136
- * `files/` that no remaining entry lists (D4). Builds are always full,
137
+ * `files/` that no remaining entry lists. Builds are always full,
137
138
  * so "unused this build" means "unused". Returns what was removed.
138
139
  *
139
140
  * @param {Iterable<string>} usedKeys
package/src/config.js CHANGED
@@ -1,13 +1,18 @@
1
- import os from 'os'
2
- import path from 'path'
3
- import { getConfig } from '@nera-static/plugin-utils'
4
- import { warn } from './warn.js'
1
+ import os from 'node:os'
2
+ import { createConfigReader, loadPluginConfig } from '@nera-static/plugin-utils/config'
3
+ import { isPlainObject, isText } from '@nera-static/plugin-utils/values'
4
+ import { log } from './log.js'
5
5
 
6
- // `config/images.yaml` is optional and every key has a default (ROADMAP
7
- // "Configuration"). `getConfig` returns `{}` for a missing file, so each key
8
- // gets its own JS fallback here. A key with a bad value warns and falls back to
9
- // its default rather than failing the build: a typo in an image config must not
10
- // take the site down.
6
+ // `config/images.yaml` is optional and every key has a default. The readers of
7
+ // @nera-static/plugin-utils/config merge the file over defaults() key by key; a
8
+ // key with a bad value warns and keeps its default rather than failing the
9
+ // build: a typo in an image config must not take the site down.
10
+
11
+ /** The config file's name in the site's config folder, without `.yaml`. */
12
+ export const CONFIG_NAME = 'images'
13
+
14
+ /** The config file as the site owner knows it, the prefix of every config warning. */
15
+ export const CONFIG_FILE = `config/${CONFIG_NAME}.yaml`
11
16
 
12
17
  export const MODERN_FORMATS = ['avif', 'webp']
13
18
  export const QUALITY_FORMATS = ['avif', 'webp', 'jpeg', 'png']
@@ -18,6 +23,7 @@ export function defaultConcurrency() {
18
23
  return Math.max(1, os.availableParallelism() - 1)
19
24
  }
20
25
 
26
+ /** The full default config, a fresh copy on every call. */
21
27
  export function defaults() {
22
28
  return {
23
29
  formats: ['avif', 'webp'],
@@ -32,34 +38,24 @@ export function defaults() {
32
38
  output_path: '/_img',
33
39
  cache_dir: '.nera-cache/images',
34
40
  prune: true,
41
+ // Depends on the machine, which is why the shipped config/images.yaml
42
+ // lists it commented out.
35
43
  concurrency: defaultConcurrency(),
36
44
  }
37
45
  }
38
46
 
39
- const isPlainObject = (value) =>
40
- value !== null && typeof value === 'object' && !Array.isArray(value)
41
-
42
47
  const isPositiveInt = (value) => Number.isInteger(value) && value > 0
43
48
 
44
49
  const isQuality = (value) => Number.isInteger(value) && value >= 1 && value <= 100
45
50
 
46
- const show = (value) => JSON.stringify(value)
47
-
48
- function bad(key, value, fallback) {
49
- warn(
50
- `config/images.yaml: invalid ${key} ${show(value)}, using ${show(fallback)}`
51
- )
52
- return fallback
53
- }
54
-
55
- function readFormats(value, fallback) {
56
- if (!Array.isArray(value)) return bad('formats', value, fallback)
51
+ function readFormats(value, current, reader) {
52
+ if (!Array.isArray(value)) return reader.bad('formats', value, current)
57
53
 
58
54
  const formats = []
59
55
  for (const format of value) {
60
56
  if (!MODERN_FORMATS.includes(format)) {
61
- warn(
62
- `config/images.yaml: ignoring unknown format ${show(format)} (supported: ${MODERN_FORMATS.join(', ')})`
57
+ reader.warn(
58
+ `ignoring unknown format ${reader.show(format)} (supported: ${MODERN_FORMATS.join(', ')})`,
63
59
  )
64
60
  } else if (!formats.includes(format)) {
65
61
  formats.push(format)
@@ -69,30 +65,28 @@ function readFormats(value, fallback) {
69
65
  return formats
70
66
  }
71
67
 
72
- function readWidths(value, fallback) {
68
+ function readWidths(value, current, reader) {
73
69
  if (!Array.isArray(value) || value.length === 0) {
74
- return bad('widths', value, fallback)
70
+ return reader.bad('widths', value, current)
75
71
  }
76
72
  const widths = value.filter(isPositiveInt)
77
- if (widths.length === 0) return bad('widths', value, fallback)
73
+ if (widths.length === 0) return reader.bad('widths', value, current)
78
74
  if (widths.length !== value.length) {
79
- warn(
80
- `config/images.yaml: ignoring widths that are not positive integers in ${show(value)}`
81
- )
75
+ reader.warn(`ignoring widths that are not positive integers in ${reader.show(value)}`)
82
76
  }
83
77
 
84
78
  return [...new Set(widths)].sort((a, b) => a - b)
85
79
  }
86
80
 
87
- function readQuality(value, fallback) {
88
- if (!isPlainObject(value)) return bad('quality', value, fallback)
81
+ function readQuality(value, current, reader) {
82
+ if (!isPlainObject(value)) return reader.bad('quality', value, current)
89
83
 
90
- const quality = { ...fallback }
84
+ const quality = { ...current }
91
85
  for (const [format, q] of Object.entries(value)) {
92
86
  if (!QUALITY_FORMATS.includes(format)) {
93
- warn(`config/images.yaml: ignoring quality for unknown format ${show(format)}`)
87
+ reader.warn(`ignoring quality for unknown format ${reader.show(format)}`)
94
88
  } else if (!isQuality(q)) {
95
- quality[format] = bad(`quality.${format}`, q, fallback[format])
89
+ quality[format] = reader.bad(`quality.${format}`, q, current[format])
96
90
  } else {
97
91
  quality[format] = q
98
92
  }
@@ -100,109 +94,89 @@ function readQuality(value, fallback) {
100
94
  return quality
101
95
  }
102
96
 
103
- function readOg(value, fallback) {
97
+ function readOg(value, current, reader) {
104
98
  if (value === false) return false
105
- if (!isPlainObject(value)) return bad('og', value, fallback)
99
+ if (!isPlainObject(value)) return reader.bad('og', value, current)
106
100
 
107
- const og = { ...fallback }
101
+ const og = { ...current }
108
102
  for (const key of ['width', 'height']) {
109
103
  if (value[key] === undefined) continue
110
104
  og[key] = isPositiveInt(value[key])
111
105
  ? value[key]
112
- : bad(`og.${key}`, value[key], fallback[key])
106
+ : reader.bad(`og.${key}`, value[key], current[key])
113
107
  }
114
108
  if (value.fit !== undefined) {
115
109
  og.fit = FITS.includes(value.fit)
116
110
  ? value.fit
117
- : bad('og.fit', value.fit, fallback.fit)
111
+ : reader.bad('og.fit', value.fit, current.fit)
118
112
  }
119
113
  return og
120
114
  }
121
115
 
122
116
  // `/_img`, `_img/`, `/a/b/` → `/_img`, `/a/b`. A root-absolute URL path
123
117
  // without a trailing slash, so `${output_path}/${file}` is always right.
124
- function readOutputPath(value, fallback) {
125
- if (typeof value !== 'string') return bad('output_path', value, fallback)
118
+ function readOutputPath(value, current, reader) {
119
+ if (typeof value !== 'string') return reader.bad('output_path', value, current)
126
120
 
127
121
  const segments = value.split('/').filter(Boolean)
128
122
  if (segments.length === 0 || segments.some((s) => s === '.' || s === '..')) {
129
- return bad('output_path', value, fallback)
123
+ return reader.bad('output_path', value, current)
130
124
  }
131
125
  return `/${segments.join('/')}`
132
126
  }
133
127
 
134
- function readCacheDir(value, fallback) {
135
- if (typeof value !== 'string' || value.trim() === '') {
136
- return bad('cache_dir', value, fallback)
137
- }
138
- return value.trim()
139
- }
128
+ // A trimmed non-blank string, else the default with a warning.
129
+ const readText = (key) => (value, current, reader) =>
130
+ isText(value) ? value.trim() : reader.bad(key, value, current)
131
+
132
+ const readBoolean = (key) => (value, current, reader) =>
133
+ typeof value === 'boolean' ? value : reader.bad(key, value, current)
140
134
 
141
- const readers = {
135
+ const READERS = {
142
136
  formats: readFormats,
143
137
  widths: readWidths,
144
138
  quality: readQuality,
145
139
  og: readOg,
146
140
  output_path: readOutputPath,
147
- cache_dir: readCacheDir,
148
- sizes: (value, fallback) =>
149
- typeof value === 'string' && value.trim() !== ''
150
- ? value.trim()
151
- : bad('sizes', value, fallback),
152
- eager_first: (value, fallback) =>
153
- typeof value === 'boolean' ? value : bad('eager_first', value, fallback),
154
- prune: (value, fallback) =>
155
- typeof value === 'boolean' ? value : bad('prune', value, fallback),
156
- figure: (value, fallback) =>
157
- value === 'title' || value === false ? value : bad('figure', value, fallback),
158
- frontmatter_keys: (value, fallback) =>
141
+ cache_dir: readText('cache_dir'),
142
+ sizes: readText('sizes'),
143
+ eager_first: readBoolean('eager_first'),
144
+ prune: readBoolean('prune'),
145
+ figure: (value, current, reader) =>
146
+ value === 'title' || value === false ? value : reader.bad('figure', value, current),
147
+ frontmatter_keys: (value, current, reader) =>
159
148
  Array.isArray(value) && value.every((k) => typeof k === 'string' && k !== '')
160
149
  ? [...new Set(value)]
161
- : bad('frontmatter_keys', value, fallback),
162
- placeholder: (value, fallback) =>
163
- PLACEHOLDERS.includes(value) ? value : bad('placeholder', value, fallback),
164
- concurrency: (value, fallback) =>
165
- isPositiveInt(value) ? value : bad('concurrency', value, fallback),
150
+ : reader.bad('frontmatter_keys', value, current),
151
+ placeholder: (value, current, reader) =>
152
+ PLACEHOLDERS.includes(value) ? value : reader.bad('placeholder', value, current),
153
+ concurrency: (value, current, reader) =>
154
+ isPositiveInt(value) ? value : reader.bad('concurrency', value, current),
166
155
  }
167
156
 
168
157
  /**
169
158
  * Merge a raw config object over the defaults, key by key, with validation.
170
159
  * Pure apart from warnings; `normalizeConfig({})` is the full default config.
171
160
  *
172
- * @param {object} raw parsed `config/images.yaml` (anything `getConfig` returns)
173
- * @returns {object} complete, validated config
161
+ * @param {unknown} raw parsed `config/images.yaml` (`{}` when it is missing)
162
+ * @param {{ warn?: (message: string) => void }} [options] where warnings go
163
+ * (default the plugin's logger)
164
+ * @returns {ReturnType<typeof defaults>} complete, validated config
174
165
  */
175
- export function normalizeConfig(raw) {
176
- const config = defaults()
177
- if (raw === null || raw === undefined) return config
178
- if (!isPlainObject(raw)) {
179
- warn('config/images.yaml: expected a mapping at the top level, using defaults')
180
- return config
181
- }
182
-
183
- for (const [key, value] of Object.entries(raw)) {
184
- const read = readers[key]
185
- if (!read) {
186
- warn(`config/images.yaml: ignoring unknown key ${show(key)}`)
187
- continue
188
- }
189
- // A key present but empty (`widths:` with nothing after it) reads as
190
- // null; treat it like an absent key rather than an invalid one.
191
- if (value === null) continue
192
- config[key] = read(value, config[key])
193
- }
194
- return config
166
+ export function normalizeConfig(raw, { warn = log.warn } = {}) {
167
+ // A reader per call: the `concurrency` default depends on the machine.
168
+ return createConfigReader({ file: CONFIG_FILE, defaults: defaults(), readers: READERS, warn })
169
+ .normalize(raw)
195
170
  }
196
171
 
197
172
  /**
198
173
  * Read and normalize the site's `config/images.yaml`. Called inside the hook,
199
174
  * not at module scope, so each build (and each test) sees the current file.
200
175
  *
201
- * @param {{ cwd?: string, app?: object }} [options] `app.folders.config` is
202
- * honoured when set, like the rest of the pipeline
203
- * @returns {object} complete, validated config
176
+ * @param {{ cwd?: string, app?: object, warn?: (message: string) => void }} [options]
177
+ * `app.folders.config` is honoured when set, like the rest of the pipeline
178
+ * @returns {ReturnType<typeof defaults>} complete, validated config
204
179
  */
205
- export function loadConfig({ cwd = process.cwd(), app } = {}) {
206
- const folder = app?.folders?.config || 'config'
207
- return normalizeConfig(getConfig(path.resolve(cwd, folder, 'images.yaml')))
180
+ export function loadConfig({ cwd = process.cwd(), app, warn } = {}) {
181
+ return normalizeConfig(loadPluginConfig(CONFIG_NAME, { cwd, app }), { warn })
208
182
  }
@@ -1,13 +1,11 @@
1
- import { warn } from './warn.js'
1
+ import { isPlainObject } from '@nera-static/plugin-utils/values'
2
+ import { log } from './log.js'
2
3
 
3
- // Frontmatter images (ROADMAP D9): for each configured key holding an image
4
+ // Frontmatter images: for each configured key holding an image
4
5
  // path, the plugin prepares variants and writes the data a template needs to
5
6
  // `meta.images.<key>`. The original `meta.<key>` string is never modified:
6
7
  // canonical-links, social plugins and existing templates keep reading it.
7
8
 
8
- const isPlainObject = (value) =>
9
- value !== null && typeof value === 'object' && !Array.isArray(value)
10
-
11
9
  /**
12
10
  * Prepare every configured frontmatter image of one page.
13
11
  *
@@ -32,8 +30,8 @@ export async function frontmatterImages(meta, { keys, prepare }) {
32
30
  if (existing !== undefined && !isPlainObject(existing)) {
33
31
  // An author's own `images:` (a gallery list, say) is theirs; merging
34
32
  // into it or replacing it would break the page's templates.
35
- warn(
36
- `${meta.href || '/index.html'}: meta.images is already set by the page and is not a mapping, frontmatter images not prepared`
33
+ log.warn(
34
+ `${meta.href || '/index.html'}: meta.images is already set by the page and is not a mapping, frontmatter images not prepared`,
37
35
  )
38
36
  return { meta, count: 0 }
39
37
  }
package/src/generate.js CHANGED
@@ -1,4 +1,4 @@
1
- import fs from 'fs'
1
+ import fs from 'node:fs'
2
2
  import { imageKey, sourceDigest, variantFileName, variantHash } from './cache.js'
3
3
  import { encodeVariant, placeholderOf, planVariants, readSourceMeta } from './transform.js'
4
4
 
@@ -18,7 +18,7 @@ export function createGenerator({ cache, queue, encode = encodeVariant, placehol
18
18
  let encoded = 0
19
19
  let placeholders = 0
20
20
 
21
- // A placeholder (D10) from the manifest when the entry already has one for
21
+ // A placeholder from the manifest when the entry already has one for
22
22
  // this mode (or knows the image is transparent), otherwise computed once
23
23
  // per build and image (queue key) and stored with the entry.
24
24
  const placeholderFor = (key, bytes, largest, mode) => {
@@ -35,7 +35,7 @@ export function createGenerator({ cache, queue, encode = encodeVariant, placehol
35
35
  /**
36
36
  * Make sure every variant of `file` under `options` exists in the cache.
37
37
  *
38
- * The source is re-hashed on every call (D4: cheap next to encoding), and
38
+ * The source is re-hashed on every call (cheap next to encoding), and
39
39
  * only variants whose file is missing are encoded. Variants shared with
40
40
  * another page or image are encoded once (queue keyed by file name).
41
41
  *
@@ -47,7 +47,7 @@ export function createGenerator({ cache, queue, encode = encodeVariant, placehol
47
47
  * @param {object} options planVariants options
48
48
  * @param {{ placeholder?: 'none'|'color'|'blur' }} [extra]
49
49
  * @returns {Promise<{ key, width, height, files, source, variants, color?, blur?, transparent? }>}
50
- * `width`/`height` are the largest variant's (D6); every variant
50
+ * `width`/`height` are the largest variant's; every variant
51
51
  * carries its cache `file` name
52
52
  */
53
53
  async function generate(file, options, { placeholder: mode = 'none' } = {}) {
@@ -72,7 +72,7 @@ export function createGenerator({ cache, queue, encode = encodeVariant, placehol
72
72
  queue.add(async () => {
73
73
  await encode(bytes, variant, cache.filePath(variant.file))
74
74
  encoded++
75
- }, variant.file)
75
+ }, variant.file),
76
76
  ),
77
77
  ])
78
78
 
package/src/log.js ADDED
@@ -0,0 +1,7 @@
1
+ import { createLogger } from '@nera-static/plugin-utils/log'
2
+
3
+ /**
4
+ * The plugin's one logger: `log.warn` prints `⚠️ plugin-images: <msg>`, `log.info`
5
+ * (the build summary) prints `ℹ️ plugin-images: <msg>`.
6
+ */
7
+ export const log = createLogger('plugin-images')
package/src/params.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { FITS, MODERN_FORMATS } from './config.js'
2
2
  import { STRATEGIES } from './transform.js'
3
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
4
+ // Per-image options as Glide-style query parameters on the image URL:
5
+ // `![alt](/images/a.jpg?w=800&ratio=16:9)`. Query strings
6
6
  // survive Markdown rendering untouched, so the plugin reads them from the
7
7
  // rendered `src`. Parsing is pure: problems come back as `warnings` for the
8
8
  // caller to print with the page and the URL, and a bad value falls back to the
@@ -70,7 +70,7 @@ function readFormats(value, warnings) {
70
70
  }
71
71
 
72
72
  /**
73
- * Parse an image URL's query string (D7).
73
+ * Parse an image URL's query string.
74
74
  *
75
75
  * @param {string} search the query, with or without the leading `?`
76
76
  * @returns {{
@@ -130,7 +130,7 @@ export function parseParams(search = '') {
130
130
 
131
131
  /**
132
132
  * The `sizes` attribute for one image: an explicit `?sizes`, else one derived
133
- * from `?w` (D7), else the config default.
133
+ * from `?w`, else the config default.
134
134
  *
135
135
  * @param {ReturnType<typeof parseParams>} params
136
136
  * @param {string} fallback the config's `sizes`
@@ -142,7 +142,7 @@ export function sizesFor(params, fallback) {
142
142
  }
143
143
 
144
144
  /**
145
- * `src` without the recognized parameters (D7), for an image the plugin
145
+ * `src` without the recognized parameters, for an image the plugin
146
146
  * leaves in place (`?skip`). Unknown parameters (a cache buster, say) and the
147
147
  * hash stay exactly as written; an emptied query loses its `?`.
148
148
  *
@@ -0,0 +1,206 @@
1
+ import path from 'node:path'
2
+ import { assertCoreVersion } from '@nera-static/plugin-utils/guard'
3
+ import { openCache } from './cache.js'
4
+ import { loadConfig } from './config.js'
5
+ import { frontmatterImages } from './frontmatter.js'
6
+ import { createGenerator } from './generate.js'
7
+ import { log } from './log.js'
8
+ import { parseParams, sizesFor, stripParams } from './params.js'
9
+ import { createQueue } from './queue.js'
10
+ import { resolveSource, sourceRoots, splitUrl } from './resolve-source.js'
11
+ import { pictureData, publicUrl, rewriteHtml } from './rewrite-html.js'
12
+
13
+ // The per-build pipeline behind `getMetaData`: every local raster image in the
14
+ // rendered pages gets its variants in the cache and its `<img>` rewritten as
15
+ // `<picture>` markup; every frontmatter image gets the same variants as data
16
+ // in `meta.images.<key>`, for the `+picture` mixin.
17
+
18
+ /**
19
+ * Throws (once per build, then again for every later image) when core is too
20
+ * old to call `getAssets`: without that hook the variants never reach
21
+ * `public/`. Checked on the first image that will be generated, before
22
+ * anything is encoded, so a site without images still builds on an older
23
+ * core (decided 2026-10-09). An unknown core version passes. Core is looked
24
+ * up from the site first, then from this file, so a symlinked plugin still
25
+ * finds the site's core before its own devDependency.
26
+ */
27
+ function coreCheck(cwd) {
28
+ let result
29
+ return () => {
30
+ if (result === undefined) {
31
+ try {
32
+ assertCoreVersion({ plugin: 'plugin-images', cwd, from: import.meta.url })
33
+ result = null
34
+ } catch (err) {
35
+ result = err
36
+ }
37
+ }
38
+ if (result) throw result
39
+ }
40
+ }
41
+
42
+ /**
43
+ * The og preset: one JPEG at `og.width` × `og.height` with `og.fit`, never
44
+ * upscaled, the file a page's social card points at. Only the frontmatter
45
+ * path's `focus` and `q` carry over; its own geometry (`w`, `ratio`, …) is for
46
+ * the page, not for the social card.
47
+ */
48
+ async function ogImage(generator, file, config, params) {
49
+ const { width, height, fit } = config.og
50
+ const { focus, q } = params.options
51
+ const image = await generator.generate(file, {
52
+ widths: [width],
53
+ formats: [],
54
+ quality: config.quality,
55
+ ratio: width / height,
56
+ fit,
57
+ focus,
58
+ q,
59
+ fallback: 'jpeg',
60
+ })
61
+ const [variant] = image.variants
62
+ return {
63
+ src: publicUrl(config.output_path, variant.file),
64
+ width: variant.width,
65
+ height: variant.height,
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Process every page of one build.
71
+ *
72
+ * @param {{ app: object, pagesData: object[], cwd: string }} options
73
+ * @returns {Promise<{ pagesData: object[], build: { config: object, cache: object, generator: object } }>}
74
+ * the pages (a page object is new only when it changed) and what
75
+ * `getAssets` needs to prune the cache and hand its files to core
76
+ */
77
+ export async function processPages({ app, pagesData, cwd }) {
78
+ const config = loadConfig({ cwd, app })
79
+ const roots = sourceRoots({ app, cwd })
80
+ const cache = openCache(path.resolve(cwd, config.cache_dir))
81
+ const generator = createGenerator({
82
+ cache,
83
+ queue: createQueue({ concurrency: config.concurrency }),
84
+ })
85
+ const ensureCore = coreCheck(cwd)
86
+ const options = {
87
+ widths: config.widths,
88
+ formats: config.formats,
89
+ quality: config.quality,
90
+ }
91
+ // The og image gets no placeholder: it is a file for crawlers, not markup.
92
+ const placeholder = { placeholder: config.placeholder }
93
+
94
+ // What one URL on one page means: `null` (not ours, or left as is with a
95
+ // warning), `{ skip }` (`?skip`, with the recognized parameters stripped)
96
+ // or `{ file, params }`, ready to generate. Shared by both passes so a
97
+ // frontmatter path reads exactly like a Markdown image URL.
98
+ const prepare = (src, href, label) => {
99
+ const resolved = resolveSource(src, {
100
+ pageHref: href,
101
+ basePath: app.basePath || '',
102
+ roots,
103
+ })
104
+ // Not a local URL: neither the file nor the query is ours.
105
+ if (['empty', 'external', 'data'].includes(resolved.skip)) return null
106
+
107
+ const params = parseParams(splitUrl(src.trim()).search)
108
+ if (params.skip) return { skip: stripParams(src) }
109
+
110
+ if (resolved.skip) {
111
+ if (resolved.skip === 'missing' || resolved.skip === 'outside') {
112
+ log.warn(`${href}: ${label}not found, left as is: ${src}`)
113
+ }
114
+ return null
115
+ }
116
+ for (const message of params.warnings) {
117
+ log.warn(`${href}: ${message}: ${src}`)
118
+ }
119
+ ensureCore()
120
+ return { file: resolved.file, params }
121
+ }
122
+
123
+ let images = 0
124
+ const result = []
125
+ // Pages one after another, a page's images concurrently: the queue bounds
126
+ // the encoders, and only one page's source bytes are held at a time.
127
+ for (const page of pagesData) {
128
+ const href = page.meta?.href || '/index.html'
129
+
130
+ const handle = async (src) => {
131
+ const prepared = prepare(src, href, 'image ')
132
+ if (!prepared || prepared.skip) return prepared && { src: prepared.skip }
133
+ try {
134
+ const image = await generator.generate(prepared.file, {
135
+ ...options,
136
+ ...prepared.params.options,
137
+ }, placeholder)
138
+ return {
139
+ image,
140
+ sizes: sizesFor(prepared.params, config.sizes),
141
+ loading: prepared.params.loading,
142
+ }
143
+ } catch (err) {
144
+ log.warn(`${href}: could not process ${src}, left as is (${err.message})`)
145
+ return null
146
+ }
147
+ }
148
+
149
+ // `meta.images.<key>` from the frontmatter keys. The `<img>`
150
+ // attributes a template sets itself (`loading`, `alt`) are the mixin's
151
+ // business, so `?loading` has nothing to act on here.
152
+ const prepareFrontmatter = async (key, src) => {
153
+ const prepared = prepare(src, href, `frontmatter ${key} `)
154
+ if (!prepared || prepared.skip) return null
155
+ const { params } = prepared
156
+ if (params.loading) {
157
+ log.warn(`${href}: loading has no effect on a frontmatter image, ignored: ${src}`)
158
+ }
159
+ try {
160
+ const image = await generator.generate(prepared.file, {
161
+ ...options,
162
+ ...params.options,
163
+ }, placeholder)
164
+ const entry = pictureData(image, {
165
+ outputPath: config.output_path,
166
+ sizes: sizesFor(params, config.sizes),
167
+ })
168
+ if (config.og) {
169
+ entry.og = await ogImage(generator, prepared.file, config, params)
170
+ }
171
+ return entry
172
+ } catch (err) {
173
+ log.warn(`${href}: could not process frontmatter ${key} ${src} (${err.message})`)
174
+ return null
175
+ }
176
+ }
177
+
178
+ const [rewritten, frontmatter] = await Promise.all([
179
+ rewriteHtml(page.content, {
180
+ handle,
181
+ outputPath: config.output_path,
182
+ sizes: config.sizes,
183
+ eagerFirst: config.eager_first,
184
+ figure: config.figure,
185
+ }),
186
+ frontmatterImages(page.meta, {
187
+ keys: config.frontmatter_keys,
188
+ prepare: prepareFrontmatter,
189
+ }),
190
+ ])
191
+ images += rewritten.count + frontmatter.count
192
+
193
+ const changed = rewritten.html !== page.content || frontmatter.meta !== page.meta
194
+ result.push(
195
+ changed ? { ...page, content: rewritten.html, meta: frontmatter.meta } : page,
196
+ )
197
+ }
198
+
199
+ if (images > 0) {
200
+ const placeholders = config.placeholder === 'none'
201
+ ? ''
202
+ : `, ${generator.placeholders} placeholder(s) computed`
203
+ log.info(`${images} image(s), ${generator.encoded} variant(s) encoded${placeholders}`)
204
+ }
205
+ return { pagesData: result, build: { config, cache, generator } }
206
+ }
package/src/queue.js CHANGED
@@ -1,4 +1,4 @@
1
- // Bounded-concurrency task queue with keyed de-duplication (ROADMAP D13).
1
+ // Bounded-concurrency task queue with keyed de-duplication.
2
2
  // No dependency: it is a counter, a waiting list and a promise map.
3
3
  //
4
4
  // The same image used on several pages produces the same variant keys, so a