cook-ssg 2.0.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.
Files changed (37) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +445 -0
  3. package/bin/cook.js +66 -0
  4. package/package.json +75 -0
  5. package/patches/jsdom-fetch-fix.js +52 -0
  6. package/scripts/build.js +212 -0
  7. package/scripts/dev.js +119 -0
  8. package/scripts/plugins/apply-template.js +226 -0
  9. package/scripts/plugins/auto-components.js +215 -0
  10. package/scripts/plugins/bundle.js +338 -0
  11. package/scripts/plugins/copy-src.js +89 -0
  12. package/scripts/plugins/create-dir-from-file.js +144 -0
  13. package/scripts/plugins/create-dist.js +55 -0
  14. package/scripts/plugins/custom-plugins.js +118 -0
  15. package/scripts/plugins/declarative-shadow-dom.js +164 -0
  16. package/scripts/plugins/escape-code-blocks.js +54 -0
  17. package/scripts/plugins/generate-formats.js +361 -0
  18. package/scripts/plugins/generate-fragments.js +126 -0
  19. package/scripts/plugins/generate-sitemap-xml.js +216 -0
  20. package/scripts/plugins/minify-src.js +253 -0
  21. package/scripts/plugins/optimize-images.js +389 -0
  22. package/scripts/plugins/process-html-frontmatter.js +75 -0
  23. package/scripts/plugins/process-markdown.js +384 -0
  24. package/scripts/plugins/repeat-collection.js +296 -0
  25. package/scripts/plugins/replace-components.js +496 -0
  26. package/scripts/plugins/replace-external-link-protocol.js +171 -0
  27. package/scripts/plugins/replace-include.js +273 -0
  28. package/scripts/plugins/replace-inline.js +217 -0
  29. package/scripts/plugins/replace-template-strings.js +121 -0
  30. package/scripts/plugins/set-active-links.js +175 -0
  31. package/scripts/utils/config/config.js +277 -0
  32. package/scripts/utils/get-src/get-src.js +241 -0
  33. package/scripts/utils/logger/logger.js +47 -0
  34. package/scripts/utils/performance/performance.js +35 -0
  35. package/scripts/utils/spinner/spinner.js +112 -0
  36. package/scripts/utils/timer/timer.js +40 -0
  37. package/scripts/utils/util/util.js +719 -0
@@ -0,0 +1,253 @@
1
+ /**
2
+ * @file minify-src.js
3
+ * @description Remove `/dist` and recreate it
4
+ */
5
+
6
+ // IMPORT
7
+ // -----------------------------
8
+ import chalk from 'chalk';
9
+ import fs from 'fs-extra';
10
+ import CleanCSS from 'clean-css';
11
+ import { minify as minifyHtml } from 'html-minifier-terser';
12
+ import * as terser from 'terser';
13
+ import Util from '../utils/util/util.js';
14
+
15
+ // Config
16
+ import { srcPath, distPath, minifyHtmlConfigCustom } from '../utils/config/config.js';
17
+
18
+
19
+ // DEFINE
20
+ // -----------------------------
21
+ /**
22
+ * @description Remove `/dist` and recreate it
23
+ * @param {Object} obj - Deconstructed options object
24
+ * @property {Object} obj.file - The current file's info (name, extension, path, src, etc.)
25
+ * @property {Array} [obj.allowType] - Allowed file types (Opt-in)
26
+ * @property {Array} [obj.disallowType] - Disallowed file types (Opt-out)
27
+ */
28
+ class MinifySrc {
29
+ constructor({file, allowType, disallowType, excludePaths = []}) {
30
+ this.opts = {file, allowType, disallowType, excludePaths};
31
+ this.file = file;
32
+ this.allowType = allowType;
33
+ this.disallowType = disallowType;
34
+ this.excludePaths = excludePaths;
35
+
36
+ // Minfiy CSS
37
+ this.minifyCssConfig = {
38
+ inline: ['none'],
39
+ };
40
+
41
+ // Minfiy HTML
42
+ // Default config with user overrides merged on top
43
+ const defaultHtmlConfig = {
44
+ collapseWhitespace: true,
45
+ removeAttributeQuotes: true,
46
+ removeComments: true,
47
+ removeRedundantAttributes: false,
48
+ removeScriptTypeAttributes: true,
49
+ removeStyleLinkTypeAttributes: true,
50
+ useShortDoctype: true,
51
+ // Skip <code-block> elements — their escaped HTML/JS/CSS content
52
+ // confuses the parser. Also skip any user-provided patterns.
53
+ ignoreCustomFragments: [
54
+ /<code-block[\s\S]*?<\/code-block>/gi,
55
+ /<pre[\s\S]*?<\/pre>/gi,
56
+ ...(minifyHtmlConfigCustom?.ignoreCustomFragments || []),
57
+ ],
58
+ };
59
+ this.minifyHtmlConfig = minifyHtmlConfigCustom
60
+ ? { ...defaultHtmlConfig, ...minifyHtmlConfigCustom, ignoreCustomFragments: defaultHtmlConfig.ignoreCustomFragments }
61
+ : defaultHtmlConfig;
62
+
63
+ // Minfiy JS
64
+ this.minifyJsConfig = {};
65
+
66
+ // Init terminal logging
67
+ if (process.env.LOGGER) Util.initLogging.call(this);
68
+ }
69
+
70
+ // INIT
71
+ // -----------------------------
72
+ // Note: `process.env.DEV_CHANGED_PAGE` is defined in `browserSync.watch()` in dev.js
73
+ async init() {
74
+ // Early Exit: File type not allowed
75
+ const allowed = Util.isAllowedType(this.opts);
76
+ if (!allowed) return;
77
+ // Early Exit: Don't minify in development
78
+ if (process.env.NODE_ENV === 'development') return;
79
+ // Early Exit: User opted out (example, unminify in stage)
80
+ if (process.env.MINIFY === 'false') return;
81
+
82
+ // START LOGGING
83
+ this.startLog();
84
+
85
+ // Destructure options
86
+ const { file } = this;
87
+
88
+ // Minify source differently based on the file type
89
+ let newSrc;
90
+ switch (file.ext) {
91
+ case 'css': newSrc = this.minCss({file}); break;
92
+ case 'html': newSrc = await this.minHtml({file}); break;
93
+ case 'js': newSrc = await this.minJs({file}); break;
94
+ }
95
+
96
+ // Store new source
97
+ file.src = newSrc;
98
+
99
+ // END LOGGING
100
+ this.endLog();
101
+ }
102
+
103
+
104
+ // PRIMARY MINIFY METHODS
105
+ // -----------------------------
106
+ async minHtml({file}) {
107
+ // MINIFY HTML — wrapped in try/catch so parse errors on pages with
108
+ // complex inline code examples don't crash the entire build
109
+ try {
110
+ file.src = await minifyHtml(file.src, this.minifyHtmlConfig);
111
+ // MINIFY INLINE CSS
112
+ file.src = this.minifyInline(file, 'style', this.minCss.bind(this));
113
+ // MINIFY INLINE SCRIPTS
114
+ file.src = await this.minifyInlineAsync(file, 'script', this.minJs.bind(this));
115
+ } catch (err) {
116
+ // Skip minification for this file — likely has unescaped code examples
117
+ // that confuse the HTML parser. The unminified output is still valid.
118
+ if (process.env.LOGGER) console.warn(` ⚠ Skipped minification for ${file.path}: ${err.message.substring(0, 80)}`);
119
+ }
120
+ // Return new src
121
+ return file.src;
122
+ }
123
+
124
+ async minJs({file}) {
125
+ const result = await terser.minify(file.src, this.minifyJsConfig);
126
+ return result.code;
127
+ }
128
+
129
+ minCss({file}) {
130
+ // Minify source
131
+ file.src = new CleanCSS(this.minifyCssConfig).minify(file.src).styles;
132
+ // Replace '@import' calls with their inlined source
133
+ file.src = this.replaceCssImports({file});
134
+ // Return modified file source
135
+ return file.src;
136
+ }
137
+
138
+
139
+ // HELPER METHODS
140
+ // -----------------------------
141
+
142
+ /**
143
+ * @description
144
+ * @param {Object} opts - The argument object
145
+ * @property {Object} file - The file source properties (ext,name,path,src)
146
+ * @private
147
+ */
148
+ // TODO: The regex could likely be done a little nicer if we could use lookbehinds.
149
+ // Instead for now, the pattern matches: url(/css/variables.css
150
+ // so we just lop off the first four characters
151
+ replaceCssImports({file}) {
152
+ let path, replaceSrc;
153
+ // Check for @import and replace them with their source
154
+ const pattern = /@import\s*url\(([/.\_\-)a-z]*);/gim;
155
+ const matches = file.src.match(pattern);
156
+ if (matches) {
157
+ matches.forEach((m,i) => {
158
+ path = m.match(/url\(.*(?=\))/gim)[0].slice(4);
159
+ // If path has /src at the start, strip it off
160
+ path = path.replace(/^\/src/, '');
161
+ // Get source to replace
162
+ replaceSrc = fs.readFileSync(`${srcPath}${path}`, 'utf-8');
163
+ // Minimize it
164
+ replaceSrc = new CleanCSS(this.minifyCssConfig).minify(replaceSrc).styles;
165
+ // Replace @import with source
166
+ // console.log('\nsrc', fileSource.src)
167
+ file.src = file.src.replace(m, replaceSrc);
168
+ });
169
+ }
170
+ return file.src;
171
+ }
172
+
173
+ /**
174
+ * @description Minify inline `<style>` tags
175
+ * @param {Object} file - The current file items (ext,name,path,src)
176
+ * @param {String} selector - The html element string selector for querying
177
+ * @param {Object} type - The minification method to use
178
+ * @private
179
+ */
180
+ minifyInline(file, selector, type) {
181
+ const dom = Util.jsdom.dom({src: file.src});
182
+ const group = dom.window.document.querySelectorAll(selector);
183
+ let minifiedSrc;
184
+ group.forEach((el,i) => {
185
+ file.src = el.textContent;
186
+ // Minify content
187
+ minifiedSrc = type({file});
188
+ // Update tag with new minified source
189
+ el.textContent = minifiedSrc;
190
+ });
191
+ // Store updated file source
192
+ file.src = Util.setSrc({dom});
193
+ // Return updated file source
194
+ return file.src;
195
+ }
196
+
197
+ /**
198
+ * @description Minify inline `<script>` tags (async version for terser)
199
+ * @param {Object} file - The current file items (ext,name,path,src)
200
+ * @param {String} selector - The html element string selector for querying
201
+ * @param {Object} type - The minification method to use
202
+ * @private
203
+ */
204
+ async minifyInlineAsync(file, selector, type) {
205
+ const dom = Util.jsdom.dom({src: file.src});
206
+ const group = dom.window.document.querySelectorAll(selector);
207
+ for (const el of group) {
208
+ file.src = el.textContent;
209
+ // Minify content
210
+ const minifiedSrc = await type({file});
211
+ // Update tag with new minified source
212
+ el.textContent = minifiedSrc;
213
+ }
214
+ // Store updated file source
215
+ file.src = Util.setSrc({dom});
216
+ // Return updated file source
217
+ return file.src;
218
+ }
219
+
220
+
221
+ // LOGGING
222
+ // -----------------------------
223
+ // Display additional terminal logging when `process.env.LOGGER` enabled
224
+
225
+ startLog(total) {
226
+ // Early Exit: Logging not allowed
227
+ if (!process.env.LOGGER) return;
228
+ // Start Spinner
229
+ this.loading.start(chalk.magenta('Minifying source'));
230
+ // Start timer
231
+ this.timer.start();
232
+ }
233
+
234
+ endLog() {
235
+ // Early Exit: Logging not allowed
236
+ if (!process.env.LOGGER) return;
237
+ // Stop Spinner and Timer
238
+ this.loading.stop(`Minified source ${this.timer.end()}`);
239
+ }
240
+
241
+
242
+ // EXPORT WRAPPER
243
+ // -----------------------------
244
+ // Export function wrapper instead of class for `build.js` simplicity
245
+ static async export(opts) {
246
+ return new MinifySrc(opts).init();
247
+ }
248
+ }
249
+
250
+
251
+ // EXPORT
252
+ // -----------------------------
253
+ export default MinifySrc.export;
@@ -0,0 +1,389 @@
1
+ /**
2
+ * @file optimize-images.js
3
+ * @description Two-phase image optimization pipeline.
4
+ *
5
+ * Phase 1 (Generate): Scans dist/ for raster images, generates responsive
6
+ * derivatives in AVIF/WebP at configured widths using sharp, with content-hash
7
+ * disk caching for instant rebuilds of unchanged images.
8
+ *
9
+ * Phase 2 (Rewrite): Finds <img> tags with local src in HTML pages, rewrites
10
+ * them to <picture> with <source> + fallback <img>, adding width/height,
11
+ * loading="lazy", and srcset/sizes.
12
+ */
13
+
14
+ // IMPORTS
15
+ // -----------------------------
16
+ import chalk from 'chalk';
17
+ import { createHash } from 'node:crypto';
18
+ import { existsSync } from 'node:fs';
19
+ import { promises as fs } from 'node:fs';
20
+ import path from 'node:path';
21
+ import sharp from 'sharp';
22
+ import Logger from '../utils/logger/logger.js';
23
+ import Util from '../utils/util/util.js';
24
+
25
+ // Config
26
+ import { distPath, images as imagesConfig } from '../utils/config/config.js';
27
+
28
+
29
+ // ============================================================================
30
+ // Phase 1: Generate derivatives
31
+ // ============================================================================
32
+
33
+ class OptimizeImagesGenerate {
34
+ constructor({ store }) {
35
+ this.store = store;
36
+ this.config = {
37
+ enabled: true,
38
+ widths: [320, 640, 960, 1280, 1920],
39
+ formats: ['avif', 'webp'],
40
+ quality: { avif: 60, webp: 75, jpeg: 80, png: 80 },
41
+ sizes: '(min-width: 60rem) 960px, 100vw',
42
+ loading: 'lazy',
43
+ cache: '.cache/images',
44
+ ...imagesConfig,
45
+ };
46
+
47
+ // Initialize manifest on store
48
+ this.store.imageManifest = {};
49
+ }
50
+
51
+ async init() {
52
+ // Early exit: disabled
53
+ if (!this.config.enabled) return;
54
+
55
+ // Show terminal message
56
+ Logger.persist.header('\nOptimize Images');
57
+
58
+ // Find all raster images in dist/
59
+ const imageFiles = await this.findImages(distPath);
60
+
61
+ if (!imageFiles.length) {
62
+ Logger.persist.success('No images found (skipped)');
63
+ return;
64
+ }
65
+
66
+ // Ensure cache directory exists
67
+ await Util.createDirectory(this.config.cache);
68
+
69
+ // Load disk cache manifest
70
+ const cacheManifestPath = path.join(this.config.cache, 'manifest.json');
71
+ let diskCache = {};
72
+ if (existsSync(cacheManifestPath)) {
73
+ try {
74
+ diskCache = JSON.parse(await fs.readFile(cacheManifestPath, 'utf-8'));
75
+ } catch {
76
+ diskCache = {};
77
+ }
78
+ }
79
+
80
+ let generated = 0;
81
+ let cached = 0;
82
+
83
+ for (const imgPath of imageFiles) {
84
+ const result = await this.processImage(imgPath, diskCache);
85
+ if (result.fromCache) cached++;
86
+ else generated++;
87
+ }
88
+
89
+ // Write updated disk cache
90
+ await fs.writeFile(cacheManifestPath, JSON.stringify(diskCache, null, 2), 'utf-8');
91
+
92
+ Logger.persist.success(`Images: ${generated} generated, ${cached} cached (${imageFiles.length} total)`);
93
+ }
94
+
95
+ /**
96
+ * Recursively find raster images in a directory
97
+ * @param {string} dir - Directory to search
98
+ * @returns {string[]} Array of image file paths
99
+ */
100
+ async findImages(dir) {
101
+ const rasterExts = ['.jpg', '.jpeg', '.png', '.webp'];
102
+ const allPaths = Util.getPaths(dir, dir, []);
103
+ if (!allPaths) return [];
104
+ return allPaths.filter(p => {
105
+ const ext = path.extname(p).toLowerCase();
106
+ return rasterExts.includes(ext);
107
+ });
108
+ }
109
+
110
+ /**
111
+ * Process a single image: hash, check cache, generate derivatives
112
+ * @param {string} imgPath - Absolute path to source image
113
+ * @param {Object} diskCache - Disk cache manifest object (mutated)
114
+ * @returns {{ fromCache: boolean }}
115
+ */
116
+ async processImage(imgPath, diskCache) {
117
+ // Read file and compute content hash
118
+ const buffer = await fs.readFile(imgPath);
119
+ const hash = createHash('md5').update(buffer).digest('hex');
120
+
121
+ // Get relative path from dist for manifest key
122
+ const relPath = imgPath.replace(`${distPath}/`, '/');
123
+
124
+ // Check disk cache
125
+ if (diskCache[relPath] && diskCache[relPath].hash === hash) {
126
+ // Verify derivatives still exist
127
+ const allExist = diskCache[relPath].derivatives.every(d =>
128
+ existsSync(path.join(distPath, d.path))
129
+ );
130
+ if (allExist) {
131
+ this.store.imageManifest[relPath] = diskCache[relPath];
132
+ return { fromCache: true };
133
+ }
134
+ }
135
+
136
+ // Get image metadata
137
+ const metadata = await sharp(buffer).metadata();
138
+ const srcWidth = metadata.width;
139
+ const srcHeight = metadata.height;
140
+
141
+ // Determine which widths to generate (no upscaling)
142
+ const fittingWidths = this.config.widths.filter(w => w <= srcWidth);
143
+ // If no configured width fits, use the source width for format conversion
144
+ const widths = fittingWidths.length > 0 ? fittingWidths : [srcWidth];
145
+
146
+ const parsed = path.parse(imgPath);
147
+ const baseName = parsed.name;
148
+ const baseDir = parsed.dir;
149
+ const srcExt = parsed.ext.toLowerCase();
150
+
151
+ // Determine the original format name for quality lookup
152
+ const origFormat = (srcExt === '.jpg' || srcExt === '.jpeg') ? 'jpeg' : srcExt.slice(1);
153
+
154
+ const derivatives = [];
155
+
156
+ // Generate derivatives for each format + width
157
+ const allFormats = [...this.config.formats, origFormat];
158
+ // Deduplicate (e.g., if source is .webp and webp is in formats)
159
+ const uniqueFormats = [...new Set(allFormats)];
160
+
161
+ for (const format of uniqueFormats) {
162
+ for (const width of widths) {
163
+ const outExt = format === 'jpeg' ? 'jpg' : format;
164
+ const outName = `${baseName}-${width}w.${outExt}`;
165
+ const outPath = path.join(baseDir, outName);
166
+ const quality = this.config.quality[format] || this.config.quality.jpeg || 80;
167
+
168
+ // Calculate proportional height
169
+ const height = Math.round((width / srcWidth) * srcHeight);
170
+
171
+ let pipeline = sharp(buffer).resize(width, height, { fit: 'inside', withoutEnlargement: true });
172
+
173
+ if (format === 'avif') pipeline = pipeline.avif({ quality });
174
+ else if (format === 'webp') pipeline = pipeline.webp({ quality });
175
+ else if (format === 'jpeg') pipeline = pipeline.jpeg({ quality });
176
+ else if (format === 'png') pipeline = pipeline.png({ quality });
177
+
178
+ await pipeline.toFile(outPath);
179
+
180
+ derivatives.push({
181
+ path: outPath.replace(`${distPath}`, '').replace(/\\/g, '/'),
182
+ format,
183
+ width,
184
+ height,
185
+ });
186
+ }
187
+ }
188
+
189
+ // Build manifest entry
190
+ const entry = {
191
+ hash,
192
+ width: srcWidth,
193
+ height: srcHeight,
194
+ derivatives,
195
+ };
196
+
197
+ this.store.imageManifest[relPath] = entry;
198
+ diskCache[relPath] = entry;
199
+
200
+ return { fromCache: false };
201
+ }
202
+
203
+
204
+ // EXPORT WRAPPER
205
+ // -----------------------------
206
+ static async exportGenerate(opts) {
207
+ return new OptimizeImagesGenerate(opts).init();
208
+ }
209
+ }
210
+
211
+
212
+ // ============================================================================
213
+ // Phase 2: Rewrite <img> to <picture>
214
+ // ============================================================================
215
+
216
+ class OptimizeImagesRewrite {
217
+ constructor({ file, store, allowType, disallowType }) {
218
+ this.opts = { file, allowType, disallowType };
219
+ this.file = file;
220
+ this.store = store;
221
+ this.config = {
222
+ enabled: true,
223
+ sizes: '(min-width: 60rem) 960px, 100vw',
224
+ loading: 'lazy',
225
+ ...imagesConfig,
226
+ };
227
+ }
228
+
229
+ async init() {
230
+ // Early exit: disabled
231
+ if (!this.config.enabled) return;
232
+
233
+ // Early exit: no manifest
234
+ if (!this.store.imageManifest || Object.keys(this.store.imageManifest).length === 0) return;
235
+
236
+ // Early exit: file type not allowed
237
+ const allowed = Util.isAllowedType(this.opts);
238
+ if (!allowed) return;
239
+
240
+ // Parse HTML
241
+ const dom = Util.jsdom.dom({ src: this.file.src });
242
+ const document = dom.window.document;
243
+
244
+ // Find all <img> tags
245
+ const imgs = document.querySelectorAll('img');
246
+ if (!imgs.length) return;
247
+
248
+ let rewrote = 0;
249
+
250
+ for (const img of imgs) {
251
+ const changed = this.rewriteImg(img, document);
252
+ if (changed) rewrote++;
253
+ }
254
+
255
+ // Only update source if we made changes
256
+ if (rewrote > 0) {
257
+ this.file.src = Util.setSrc({ dom });
258
+ }
259
+ }
260
+
261
+ /**
262
+ * Rewrite a single <img> element to <picture> if applicable
263
+ * @param {Element} img - The <img> element
264
+ * @param {Document} document - The DOM document
265
+ * @returns {boolean} Whether the img was rewritten
266
+ */
267
+ rewriteImg(img, document) {
268
+ // --- Skip checks ---
269
+
270
+ // Skip: data-no-optimize attribute
271
+ if (img.hasAttribute('data-no-optimize')) return false;
272
+
273
+ // Skip: already inside a <picture> element
274
+ if (img.parentElement && img.parentElement.tagName === 'PICTURE') return false;
275
+
276
+ const src = img.getAttribute('src');
277
+ if (!src) return false;
278
+
279
+ // Skip: external URLs
280
+ if (src.startsWith('http://') || src.startsWith('https://') || src.startsWith('//')) return false;
281
+
282
+ // Skip: data URIs
283
+ if (src.startsWith('data:')) return false;
284
+
285
+ // Skip: SVG
286
+ if (src.toLowerCase().endsWith('.svg')) return false;
287
+
288
+ // Skip: GIF
289
+ if (src.toLowerCase().endsWith('.gif')) return false;
290
+
291
+ // --- Lookup in manifest ---
292
+
293
+ // Normalize src to match manifest keys (ensure leading /)
294
+ const normalizedSrc = src.startsWith('/') ? src : `/${src}`;
295
+ const manifestEntry = this.store.imageManifest[normalizedSrc];
296
+
297
+ if (!manifestEntry) {
298
+ return false;
299
+ }
300
+
301
+ // --- Build <picture> ---
302
+
303
+ const derivatives = manifestEntry.derivatives;
304
+ const authorSizes = img.getAttribute('sizes') || this.config.sizes;
305
+
306
+ // Group derivatives by format
307
+ const byFormat = {};
308
+ for (const d of derivatives) {
309
+ if (!byFormat[d.format]) byFormat[d.format] = [];
310
+ byFormat[d.format].push(d);
311
+ }
312
+
313
+ // Sort each format's derivatives by width
314
+ for (const format of Object.keys(byFormat)) {
315
+ byFormat[format].sort((a, b) => a.width - b.width);
316
+ }
317
+
318
+ // Determine original format
319
+ const srcExt = path.extname(src).toLowerCase();
320
+ const origFormat = (srcExt === '.jpg' || srcExt === '.jpeg') ? 'jpeg' : srcExt.slice(1);
321
+
322
+ // Create <picture> element
323
+ const picture = document.createElement('picture');
324
+
325
+ // Add <source> elements for each modern format (avif, webp)
326
+ for (const format of this.config.formats) {
327
+ if (!byFormat[format]) continue;
328
+ const source = document.createElement('source');
329
+ const mimeType = format === 'avif' ? 'image/avif' : `image/${format}`;
330
+ source.setAttribute('type', mimeType);
331
+ source.setAttribute('srcset', byFormat[format].map(d => `${d.path} ${d.width}w`).join(', '));
332
+ source.setAttribute('sizes', authorSizes);
333
+ picture.appendChild(source);
334
+ }
335
+
336
+ // Build fallback <img>
337
+ // Pick the derivative closest to 960px (or largest available) for the src
338
+ const origDerivatives = byFormat[origFormat] || [];
339
+ let fallbackSrc = src;
340
+ if (origDerivatives.length > 0) {
341
+ const target = origDerivatives.find(d => d.width >= 960) || origDerivatives[origDerivatives.length - 1];
342
+ fallbackSrc = target.path;
343
+ }
344
+
345
+ // Clone all original attributes to the new img
346
+ const newImg = document.createElement('img');
347
+ for (const attr of Array.from(img.attributes)) {
348
+ if (attr.name === 'src') continue;
349
+ if (attr.name === 'sizes') continue;
350
+ newImg.setAttribute(attr.name, attr.value);
351
+ }
352
+ newImg.setAttribute('src', fallbackSrc);
353
+
354
+ // Add srcset for original format
355
+ if (origDerivatives.length > 0) {
356
+ newImg.setAttribute('srcset', origDerivatives.map(d => `${d.path} ${d.width}w`).join(', '));
357
+ newImg.setAttribute('sizes', authorSizes);
358
+ }
359
+
360
+ // Add width/height from manifest
361
+ newImg.setAttribute('width', String(manifestEntry.width));
362
+ newImg.setAttribute('height', String(manifestEntry.height));
363
+
364
+ // Add loading="lazy" unless author specified a loading attribute
365
+ if (!img.hasAttribute('loading')) {
366
+ newImg.setAttribute('loading', this.config.loading);
367
+ }
368
+
369
+ picture.appendChild(newImg);
370
+
371
+ // Replace original <img> with <picture>
372
+ img.replaceWith(picture);
373
+
374
+ return true;
375
+ }
376
+
377
+
378
+ // EXPORT WRAPPER
379
+ // -----------------------------
380
+ static async exportRewrite(opts) {
381
+ return new OptimizeImagesRewrite(opts).init();
382
+ }
383
+ }
384
+
385
+
386
+ // EXPORTS
387
+ // -----------------------------
388
+ export const optimizeImagesGenerate = OptimizeImagesGenerate.exportGenerate;
389
+ export const optimizeImagesRewrite = OptimizeImagesRewrite.exportRewrite;