cook-ssg 2.1.1 → 2.1.3
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/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cook-ssg",
|
|
3
|
-
"version": "2.1.
|
|
3
|
+
"version": "2.1.3",
|
|
4
4
|
"description": "Cook your static pages into a beautifully performing site. Static site generation the web platform way.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
|
-
"cook": "
|
|
7
|
+
"cook": "bin/cook.js"
|
|
8
8
|
},
|
|
9
9
|
"main": "./scripts/build.js",
|
|
10
10
|
"exports": {
|
|
@@ -61,7 +61,8 @@
|
|
|
61
61
|
"fs-extra": "^11.3.2",
|
|
62
62
|
"gray-matter": "^4.0.3",
|
|
63
63
|
"html-minifier-terser": "^7.2.0",
|
|
64
|
-
"jsdom": "^
|
|
64
|
+
"jsdom": "^29.1.0",
|
|
65
|
+
"linkedom": "^0.18.12",
|
|
65
66
|
"lodash.clonedeep": "^4.5.0",
|
|
66
67
|
"lodash.merge": "^4.6.2",
|
|
67
68
|
"marked": "^17.0.1",
|
|
@@ -72,7 +73,6 @@
|
|
|
72
73
|
"devDependencies": {
|
|
73
74
|
"happy-dom": "^20.8.9",
|
|
74
75
|
"http-server": "^14.1.1",
|
|
75
|
-
"
|
|
76
|
-
"npm-check-updates": "^19.2.0"
|
|
76
|
+
"npm-check-updates": "^22.0.1"
|
|
77
77
|
}
|
|
78
78
|
}
|
package/scripts/build.js
CHANGED
|
@@ -17,6 +17,7 @@ import createDist from './plugins/create-dist.js';
|
|
|
17
17
|
import createDirFromFile from './plugins/create-dir-from-file.js';
|
|
18
18
|
import customPlugins from './plugins/custom-plugins.js';
|
|
19
19
|
import declarativeShadowDom from './plugins/declarative-shadow-dom.js';
|
|
20
|
+
import fingerprintAssets from './plugins/fingerprint-assets.js';
|
|
20
21
|
import generateFormats from './plugins/generate-formats.js';
|
|
21
22
|
import generateFragments from './plugins/generate-fragments.js';
|
|
22
23
|
import generateSitemap from './plugins/generate-sitemap-xml.js';
|
|
@@ -207,6 +208,12 @@ class Build {
|
|
|
207
208
|
// PLUGIN: Build and create bundled file
|
|
208
209
|
await bundleBuild({store});
|
|
209
210
|
|
|
211
|
+
// PLUGIN: Fingerprint built CSS/JS, rewrite HTML refs, emit asset manifest
|
|
212
|
+
// Runs after bundleBuild so bundle outputs are also fingerprinted.
|
|
213
|
+
// Must run after generateSitemap (HTML pages already exist) but before
|
|
214
|
+
// user-defined `after` plugins so they see fingerprinted output.
|
|
215
|
+
await fingerprintAssets();
|
|
216
|
+
|
|
210
217
|
// CUSTOM PLUGINS: Run custom user plugins after file loop
|
|
211
218
|
await customPlugins({store, data, plugins: plugins.after, log: 'After' });
|
|
212
219
|
}
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file fingerprint-assets.js
|
|
3
|
+
* @description Content-hash fingerprinting for built CSS and JS assets.
|
|
4
|
+
*
|
|
5
|
+
* Runs as a post-pass over dist/ after all HTML and bundles are written.
|
|
6
|
+
*
|
|
7
|
+
* Phase 1: Hash and rename matching assets (foo.css -> foo.a1b2c3d4.css).
|
|
8
|
+
* Source map files (.map) are renamed alongside their source and the
|
|
9
|
+
* sourceMappingURL comment is updated to point to the new map name.
|
|
10
|
+
* Phase 2: Walk dist/ HTML and rewrite <link href> and <script src> refs.
|
|
11
|
+
* Phase 3: Emit dist/<manifestPath> mapping original -> hashed paths.
|
|
12
|
+
*
|
|
13
|
+
* Out of scope for v1: url() refs inside CSS, image fingerprinting.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
// IMPORTS
|
|
17
|
+
// -----------------------------
|
|
18
|
+
import { createHash } from 'node:crypto';
|
|
19
|
+
import { promises as fs } from 'node:fs';
|
|
20
|
+
import path from 'node:path';
|
|
21
|
+
import { JSDOM } from 'jsdom';
|
|
22
|
+
import Logger from '../utils/logger/logger.js';
|
|
23
|
+
import Util from '../utils/util/util.js';
|
|
24
|
+
|
|
25
|
+
// Config
|
|
26
|
+
import { distPath, fingerprint as fingerprintConfig } from '../utils/config/config.js';
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
// ============================================================================
|
|
30
|
+
// Pure helpers (extracted for unit testing)
|
|
31
|
+
// ============================================================================
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Compute a content hash truncated to the given length.
|
|
35
|
+
* @param {Buffer|string} content
|
|
36
|
+
* @param {number} length - Number of hex chars to keep
|
|
37
|
+
* @param {string} [algorithm='sha256']
|
|
38
|
+
* @returns {string}
|
|
39
|
+
*/
|
|
40
|
+
export function computeHash(content, length, algorithm = 'sha256') {
|
|
41
|
+
return createHash(algorithm).update(content).digest('hex').slice(0, length);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Insert a hash into a filename before the extension.
|
|
46
|
+
* Handles compound extensions like `.js.map` by inserting before the last
|
|
47
|
+
* meaningful extension (e.g. `foo.js.map` -> `foo.{hash}.js.map`).
|
|
48
|
+
* @param {string} filename - Base filename, e.g. "foo.css"
|
|
49
|
+
* @param {string} hash
|
|
50
|
+
* @returns {string} e.g. "foo.{hash}.css"
|
|
51
|
+
*/
|
|
52
|
+
export function fingerprintFilename(filename, hash) {
|
|
53
|
+
// Map files: keep .js.map / .css.map paired with their source hash
|
|
54
|
+
if (filename.endsWith('.js.map')) {
|
|
55
|
+
const stem = filename.slice(0, -'.js.map'.length);
|
|
56
|
+
return `${stem}.${hash}.js.map`;
|
|
57
|
+
}
|
|
58
|
+
if (filename.endsWith('.css.map')) {
|
|
59
|
+
const stem = filename.slice(0, -'.css.map'.length);
|
|
60
|
+
return `${stem}.${hash}.css.map`;
|
|
61
|
+
}
|
|
62
|
+
const ext = path.extname(filename);
|
|
63
|
+
if (!ext) return `${filename}.${hash}`;
|
|
64
|
+
const stem = filename.slice(0, -ext.length);
|
|
65
|
+
return `${stem}.${hash}${ext}`;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Should this href/src be left alone?
|
|
70
|
+
* @param {string} url
|
|
71
|
+
* @returns {boolean}
|
|
72
|
+
*/
|
|
73
|
+
export function isExternalRef(url) {
|
|
74
|
+
if (!url) return true;
|
|
75
|
+
if (url.startsWith('http://') || url.startsWith('https://') || url.startsWith('//')) return true;
|
|
76
|
+
if (url.startsWith('data:')) return true;
|
|
77
|
+
if (url.startsWith('mailto:') || url.startsWith('tel:')) return true;
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Strip query string / fragment from a URL for manifest lookup.
|
|
83
|
+
* Returns { path, suffix } so the suffix can be reattached after rewriting.
|
|
84
|
+
* @param {string} url
|
|
85
|
+
*/
|
|
86
|
+
export function splitUrlSuffix(url) {
|
|
87
|
+
const qIdx = url.search(/[?#]/);
|
|
88
|
+
if (qIdx === -1) return { path: url, suffix: '' };
|
|
89
|
+
return { path: url.slice(0, qIdx), suffix: url.slice(qIdx) };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Rewrite <link href> and <script src> in an HTML string using the manifest.
|
|
94
|
+
* Manifest keys are absolute-from-dist paths (e.g. "/assets/css/site.css").
|
|
95
|
+
* @param {string} html
|
|
96
|
+
* @param {Object} manifest - { "/assets/css/site.css": "/assets/css/site.{hash}.css", ... }
|
|
97
|
+
* @returns {{ html: string, rewrites: number }}
|
|
98
|
+
*/
|
|
99
|
+
export function rewriteHrefs(html, manifest) {
|
|
100
|
+
if (!manifest || Object.keys(manifest).length === 0) return { html, rewrites: 0 };
|
|
101
|
+
|
|
102
|
+
const dom = new JSDOM(html);
|
|
103
|
+
const document = dom.window.document;
|
|
104
|
+
let rewrites = 0;
|
|
105
|
+
|
|
106
|
+
const rewriteAttr = (el, attr) => {
|
|
107
|
+
const original = el.getAttribute(attr);
|
|
108
|
+
if (!original || isExternalRef(original)) return;
|
|
109
|
+
const { path: cleanPath, suffix } = splitUrlSuffix(original);
|
|
110
|
+
const lookupKey = cleanPath.startsWith('/') ? cleanPath : `/${cleanPath}`;
|
|
111
|
+
const replacement = manifest[lookupKey];
|
|
112
|
+
if (!replacement) return;
|
|
113
|
+
// Preserve leading-slash style of the original
|
|
114
|
+
const newValue = cleanPath.startsWith('/') ? replacement : replacement.replace(/^\//, '');
|
|
115
|
+
el.setAttribute(attr, `${newValue}${suffix}`);
|
|
116
|
+
rewrites += 1;
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
document.querySelectorAll('link[href]').forEach(el => rewriteAttr(el, 'href'));
|
|
120
|
+
document.querySelectorAll('script[src]').forEach(el => rewriteAttr(el, 'src'));
|
|
121
|
+
|
|
122
|
+
if (rewrites === 0) return { html, rewrites: 0 };
|
|
123
|
+
return { html: dom.serialize(), rewrites };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
// ============================================================================
|
|
128
|
+
// Plugin
|
|
129
|
+
// ============================================================================
|
|
130
|
+
|
|
131
|
+
class FingerprintAssets {
|
|
132
|
+
constructor() {
|
|
133
|
+
this.config = {
|
|
134
|
+
enabled: false,
|
|
135
|
+
hashLength: 8,
|
|
136
|
+
algorithm: 'sha256',
|
|
137
|
+
types: ['.css', '.js'],
|
|
138
|
+
excludePaths: [],
|
|
139
|
+
manifestPath: 'asset-manifest.json',
|
|
140
|
+
...fingerprintConfig,
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async init() {
|
|
145
|
+
if (!this.config.enabled) return;
|
|
146
|
+
if (process.env.DEV_CHANGED_PAGE) return;
|
|
147
|
+
|
|
148
|
+
Logger.persist.header('\nFingerprint Assets');
|
|
149
|
+
|
|
150
|
+
// Phase 1: Find candidates and hash + rename
|
|
151
|
+
const candidates = await this.findCandidates();
|
|
152
|
+
if (!candidates.length) {
|
|
153
|
+
Logger.persist.success('No matching assets (skipped)');
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const manifest = await this.fingerprintFiles(candidates);
|
|
158
|
+
|
|
159
|
+
// Phase 2: Rewrite HTML references
|
|
160
|
+
const htmlFiles = (Util.getPaths(distPath, distPath, []) || [])
|
|
161
|
+
.filter(p => p.endsWith('.html'));
|
|
162
|
+
let totalRewrites = 0;
|
|
163
|
+
for (const htmlPath of htmlFiles) {
|
|
164
|
+
const original = await fs.readFile(htmlPath, 'utf-8');
|
|
165
|
+
const { html, rewrites } = rewriteHrefs(original, manifest);
|
|
166
|
+
if (rewrites > 0) {
|
|
167
|
+
await fs.writeFile(htmlPath, html, 'utf-8');
|
|
168
|
+
totalRewrites += rewrites;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Phase 3: Write manifest
|
|
173
|
+
const manifestFsPath = path.join(distPath, this.config.manifestPath);
|
|
174
|
+
await fs.writeFile(manifestFsPath, JSON.stringify(manifest, null, 2), 'utf-8');
|
|
175
|
+
|
|
176
|
+
Logger.persist.success(
|
|
177
|
+
`Fingerprinted ${candidates.length} asset(s), rewrote ${totalRewrites} HTML ref(s)`
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Find all dist files matching configured types, excluding configured paths.
|
|
183
|
+
* Returns absolute paths.
|
|
184
|
+
*/
|
|
185
|
+
async findCandidates() {
|
|
186
|
+
const all = Util.getPaths(distPath, distPath, []) || [];
|
|
187
|
+
const excludes = this.config.excludePaths.map(p => (p instanceof RegExp ? p : new RegExp(p)));
|
|
188
|
+
return all.filter(p => {
|
|
189
|
+
// Skip source maps in the candidate list — handled alongside their source.
|
|
190
|
+
if (p.endsWith('.map')) return false;
|
|
191
|
+
const ext = path.extname(p);
|
|
192
|
+
if (!this.config.types.includes(ext)) return false;
|
|
193
|
+
if (excludes.some(r => r.test(p))) return false;
|
|
194
|
+
return true;
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Hash, rename, and (if present) rename the paired .map and patch sourceMappingURL.
|
|
200
|
+
* @param {string[]} candidates - Absolute paths
|
|
201
|
+
* @returns {Promise<Object>} manifest of relative-from-dist mappings
|
|
202
|
+
*/
|
|
203
|
+
async fingerprintFiles(candidates) {
|
|
204
|
+
const manifest = {};
|
|
205
|
+
|
|
206
|
+
for (const absPath of candidates) {
|
|
207
|
+
const buffer = await fs.readFile(absPath);
|
|
208
|
+
const hash = computeHash(buffer, this.config.hashLength, this.config.algorithm);
|
|
209
|
+
|
|
210
|
+
const dir = path.dirname(absPath);
|
|
211
|
+
const baseName = path.basename(absPath);
|
|
212
|
+
const newName = fingerprintFilename(baseName, hash);
|
|
213
|
+
const newAbs = path.join(dir, newName);
|
|
214
|
+
|
|
215
|
+
// Handle paired .map file (if present)
|
|
216
|
+
const mapAbs = `${absPath}.map`;
|
|
217
|
+
let updatedContent = null;
|
|
218
|
+
let mapNewName = null;
|
|
219
|
+
try {
|
|
220
|
+
await fs.access(mapAbs);
|
|
221
|
+
// Rename map file with the same hash
|
|
222
|
+
mapNewName = fingerprintFilename(`${baseName}.map`, hash);
|
|
223
|
+
const mapNewAbs = path.join(dir, mapNewName);
|
|
224
|
+
await fs.rename(mapAbs, mapNewAbs);
|
|
225
|
+
// Patch sourceMappingURL comment to point at the new map name
|
|
226
|
+
const text = buffer.toString('utf-8');
|
|
227
|
+
updatedContent = text.replace(
|
|
228
|
+
/(sourceMappingURL=)([^\s*'"]+)/,
|
|
229
|
+
(_, prefix) => `${prefix}${mapNewName}`
|
|
230
|
+
);
|
|
231
|
+
} catch {
|
|
232
|
+
// No map file
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
if (updatedContent !== null) {
|
|
236
|
+
await fs.writeFile(newAbs, updatedContent, 'utf-8');
|
|
237
|
+
await fs.unlink(absPath);
|
|
238
|
+
} else {
|
|
239
|
+
await fs.rename(absPath, newAbs);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// Build manifest keys as web paths starting with `/`
|
|
243
|
+
const relOriginal = '/' + path.relative(distPath, absPath).split(path.sep).join('/');
|
|
244
|
+
const relNew = '/' + path.relative(distPath, newAbs).split(path.sep).join('/');
|
|
245
|
+
manifest[relOriginal] = relNew;
|
|
246
|
+
|
|
247
|
+
if (mapNewName) {
|
|
248
|
+
const relMapOriginal = '/' + path.relative(distPath, mapAbs).split(path.sep).join('/');
|
|
249
|
+
const relMapNew = '/' + path.relative(distPath, path.join(dir, mapNewName)).split(path.sep).join('/');
|
|
250
|
+
manifest[relMapOriginal] = relMapNew;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
return manifest;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
// EXPORT WRAPPER
|
|
259
|
+
// -----------------------------
|
|
260
|
+
static async export(opts) {
|
|
261
|
+
return new FingerprintAssets(opts).init();
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
// EXPORT
|
|
267
|
+
// -----------------------------
|
|
268
|
+
export default FingerprintAssets.export;
|
|
@@ -153,6 +153,20 @@ const defaultConfig = {
|
|
|
153
153
|
removeAttribute: true,
|
|
154
154
|
},
|
|
155
155
|
|
|
156
|
+
// Fingerprint: Content-hash filenames for built CSS/JS assets
|
|
157
|
+
// When enabled, renames matching dist/ files to foo.{hash}.css and rewrites
|
|
158
|
+
// <link href> / <script src> references in HTML. Emits asset-manifest.json
|
|
159
|
+
// mapping original paths to fingerprinted paths.
|
|
160
|
+
// Out of scope (v1): url() rewrites inside CSS, image fingerprinting.
|
|
161
|
+
fingerprint: {
|
|
162
|
+
enabled: false,
|
|
163
|
+
hashLength: 8,
|
|
164
|
+
algorithm: 'sha256',
|
|
165
|
+
types: ['.css', '.js'],
|
|
166
|
+
excludePaths: [],
|
|
167
|
+
manifestPath: 'asset-manifest.json',
|
|
168
|
+
},
|
|
169
|
+
|
|
156
170
|
// Images: Automatic responsive image optimization
|
|
157
171
|
// Generates AVIF/WebP derivatives at multiple widths, rewrites <img> to <picture>
|
|
158
172
|
images: {
|
|
@@ -259,6 +273,7 @@ export const {
|
|
|
259
273
|
distPath,
|
|
260
274
|
dsd,
|
|
261
275
|
excludePaths,
|
|
276
|
+
fingerprint,
|
|
262
277
|
formats,
|
|
263
278
|
fragments,
|
|
264
279
|
images,
|