186 lignes
8.0 KiB
JavaScript
186 lignes
8.0 KiB
JavaScript
#!/usr/bin/env node
|
|
/**
|
|
* tools/build.js
|
|
*
|
|
* Build de production de gastinel.me — zéro dépendance (Node natif).
|
|
*
|
|
* Source : index.html (on continue à l'éditer tel quel, CSS/JS inline).
|
|
* Sortie : dist/ (miroir de /srv/gastinel.me, prêt à déployer)
|
|
* - index.html HTML allégé (commentaires, indentation retirés)
|
|
* - assets/build/app.<hash>.css tous les <style> regroupés + minifiés
|
|
* - assets/build/app.<hash>.js le script principal, chargé en defer
|
|
* - assets/build/<police>.<hash>.woff2 polices renommées (cache immutable)
|
|
* - assets/build/<section>.<hash>.html sections chargées à la demande (FRAGMENTS)
|
|
* - llms.txt, robots.txt, sitemap.xml, data/news.json
|
|
* - un .br et un .gz pour chaque fichier texte (Caddy: precompressed br gzip)
|
|
* - build-manifest.json liste des fichiers + empreintes (utilisé par deploy.js)
|
|
*
|
|
* Usage : node tools/build.js
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const zlib = require('zlib');
|
|
const crypto = require('crypto');
|
|
|
|
const ROOT = path.resolve(__dirname, '..');
|
|
const DIST = path.join(ROOT, 'dist');
|
|
const BUILD_DIR = 'assets/build';
|
|
// Sections retirées du HTML initial (lourdes, peu utiles au référencement).
|
|
const FRAGMENTS = ['termes'];
|
|
const COPY_AS_IS =['llms.txt', 'robots.txt', 'sitemap.xml', 'data/news.json'];
|
|
const COMPRESSIBLE = new Set(['.html', '.css', '.js', '.json', '.txt', '.xml', '.svg']);
|
|
|
|
const hash = (buf) => crypto.createHash('sha256').update(buf).digest('hex').slice(0, 10);
|
|
const md5 = (buf) => crypto.createHash('md5').update(buf).digest('hex');
|
|
const kb = (n) => (n / 1024).toFixed(1) + ' Ko';
|
|
const brotli = (buf) => zlib.brotliCompressSync(buf, {
|
|
params: {
|
|
[zlib.constants.BROTLI_PARAM_QUALITY]: 11,
|
|
[zlib.constants.BROTLI_PARAM_SIZE_HINT]: buf.length,
|
|
},
|
|
});
|
|
|
|
const outputs = {}; // chemin publié -> Buffer
|
|
|
|
function emit(relPath, content) {
|
|
const buf = Buffer.isBuffer(content) ? content : Buffer.from(content, 'utf8');
|
|
outputs[relPath] = buf;
|
|
return relPath;
|
|
}
|
|
|
|
// --- CSS ---------------------------------------------------------------------
|
|
// Minification volontairement prudente : on ne touche ni aux combinateurs
|
|
// (> + ~), ni aux espaces avant ':' (".a :hover" != ".a:hover"), ni à calc().
|
|
// Les chaînes ("...", '...') sont mises de côté pour ne jamais être modifiées.
|
|
function minifyCss(css) {
|
|
const strings = [];
|
|
return css
|
|
.replace(/\/\*[\s\S]*?\*\//g, '')
|
|
.replace(/"(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*'/g, (s) => `\u0000${strings.push(s) - 1}\u0000`)
|
|
.replace(/\s+/g, ' ')
|
|
.replace(/\s*([{};,])\s*/g, '$1')
|
|
.replace(/:\s+/g, ':')
|
|
.replace(/;}/g, '}')
|
|
.replace(/\u0000(\d+)\u0000/g, (m, i) => strings[i])
|
|
.trim();
|
|
}
|
|
|
|
// --- HTML --------------------------------------------------------------------
|
|
// Retire commentaires, indentation de début de ligne et lignes vides.
|
|
// Sûr ici : aucun <pre>/<textarea> ni white-space:pre dans la page, et le seul
|
|
// script restant inline est le JSON-LD (minifié à part).
|
|
function minifyHtml(html) {
|
|
return html
|
|
.replace(/<!--(?!\[if)[\s\S]*?-->/g, '')
|
|
.replace(/\n[ \t]+/g, '\n')
|
|
.replace(/\n{2,}/g, '\n')
|
|
.trim() + '\n';
|
|
}
|
|
|
|
function build() {
|
|
fs.rmSync(DIST, { recursive: true, force: true });
|
|
|
|
const srcPath = path.join(ROOT, 'index.html');
|
|
// git (autocrlf) peut rendre la source en CRLF : on raisonne toujours en LF,
|
|
// comme la prod, pour que les empreintes du garde-fou restent stables.
|
|
const src = fs.readFileSync(srcPath, 'utf8').replace(/\r\n/g, '\n');
|
|
if (/<pre[\s>]|<textarea[\s>]/i.test(src.replace(/<script[\s\S]*?<\/script>/gi, ''))) {
|
|
throw new Error('<pre>/<textarea> détecté : la minification HTML doit être revue.');
|
|
}
|
|
let html = src;
|
|
|
|
// 1. Polices : copies renommées avec empreinte -> cache immutable possible.
|
|
const fontMap = {};
|
|
for (const ref of new Set(html.match(/assets\/fonts\/[\w.-]+\.woff2/g) || [])) {
|
|
const buf = fs.readFileSync(path.join(ROOT, ref));
|
|
const name = path.basename(ref, '.woff2') + '.' + hash(buf) + '.woff2';
|
|
fontMap[ref] = emit(`${BUILD_DIR}/${name}`, buf);
|
|
}
|
|
|
|
// 2. CSS : tous les <style> (head + body), dans l'ordre -> un seul fichier.
|
|
const styles = [];
|
|
let firstStyleAt = -1;
|
|
html = html.replace(/<style>([\s\S]*?)<\/style>\n?/g, (m, css, offset) => {
|
|
if (firstStyleAt < 0) firstStyleAt = offset;
|
|
styles.push(css);
|
|
return firstStyleAt === offset ? '<!--@@CSS@@-->' : '';
|
|
});
|
|
let css = minifyCss(styles.join('\n'));
|
|
// Le CSS déménage dans assets/build/ : ses URL relatives deviennent absolues.
|
|
css = css.replace(/url\((['"]?)(assets\/[^'")]+)\1\)/g, (m, q, ref) =>
|
|
`url(${q}/${fontMap[ref] || ref}${q})`);
|
|
const cssPath = emit(`${BUILD_DIR}/app.${hash(css)}.css`, css);
|
|
|
|
// 3. JS : le script principal (ni src, ni JSON-LD) -> fichier externe en defer.
|
|
const scripts = [];
|
|
html = html.replace(/<script>([\s\S]*?)<\/script>\n?/g, (m, js) => {
|
|
scripts.push(js.trim());
|
|
return '';
|
|
});
|
|
if (scripts.length !== 1) throw new Error(`1 script inline attendu, ${scripts.length} trouvé(s).`);
|
|
const js = scripts[0] + '\n';
|
|
const jsPath = emit(`${BUILD_DIR}/app.${hash(js)}.js`, js);
|
|
|
|
html = html.replace('<!--@@CSS@@-->',
|
|
`<link rel="stylesheet" href="${cssPath}">\n<script src="${jsPath}" defer></script>\n`);
|
|
|
|
// 3b. Sections externalisées : leur contenu part dans un fragment chargé à la
|
|
// demande par le routeur (go -> loadFragment). Section de niveau 0 : se
|
|
// termine par "\n</section>" en début de ligne.
|
|
for (const id of FRAGMENTS) {
|
|
const re = new RegExp(`(<section id="${id}" class="spa-section")>([\\s\\S]*?)\\n</section>\\n`);
|
|
const m = html.match(re);
|
|
if (!m) throw new Error(`Section #${id} introuvable pour le fragment.`);
|
|
if (/<script|<style/i.test(m[2])) throw new Error(`#${id} contient du script/style inline.`);
|
|
const frag = minifyHtml(m[2]);
|
|
const fragPath = emit(`${BUILD_DIR}/${id}.${hash(frag)}.html`, frag);
|
|
html = html.replace(re, `$1 data-fragment="${fragPath}"><p class="fragment-status">Chargement…</p></section>\n`);
|
|
}
|
|
|
|
// 4. JSON-LD compacté.
|
|
html = html.replace(/(<script type="application\/ld\+json">)([\s\S]*?)(<\/script>)/,
|
|
(m, a, json, b) => a + JSON.stringify(JSON.parse(json)) + b);
|
|
|
|
// 5. Préchargements de polices -> versions avec empreinte.
|
|
for (const [ref, out] of Object.entries(fontMap)) html = html.split(`"${ref}"`).join(`"${out}"`);
|
|
|
|
emit('index.html', minifyHtml(html));
|
|
|
|
// 6. Fichiers recopiés tels quels.
|
|
for (const rel of COPY_AS_IS) emit(rel, fs.readFileSync(path.join(ROOT, rel)));
|
|
|
|
// 7. Écriture + précompression.
|
|
const manifest = { source: { 'index.html': md5(Buffer.from(src, 'utf8')) }, files: {} };
|
|
for (const [rel, buf] of Object.entries(outputs)) {
|
|
const abs = path.join(DIST, rel);
|
|
fs.mkdirSync(path.dirname(abs), { recursive: true });
|
|
fs.writeFileSync(abs, buf);
|
|
manifest.files[rel] = md5(buf);
|
|
if (COMPRESSIBLE.has(path.extname(rel))) {
|
|
fs.writeFileSync(abs + '.br', brotli(buf));
|
|
fs.writeFileSync(abs + '.gz', zlib.gzipSync(buf, { level: 9 }));
|
|
manifest.files[rel + '.br'] = md5(fs.readFileSync(abs + '.br'));
|
|
manifest.files[rel + '.gz'] = md5(fs.readFileSync(abs + '.gz'));
|
|
}
|
|
}
|
|
fs.writeFileSync(path.join(DIST, 'build-manifest.json'), JSON.stringify(manifest, null, 2) + '\n');
|
|
|
|
// 8. Rapport.
|
|
const srcBuf = Buffer.from(src, 'utf8');
|
|
const size = (rel) => outputs[rel].length;
|
|
const br = (rel) => fs.statSync(path.join(DIST, rel + '.br')).size;
|
|
const first = ['index.html', cssPath, jsPath];
|
|
console.log('Build OK -> dist/');
|
|
console.log(` source index.html : ${kb(srcBuf.length)} brut, ${kb(brotli(srcBuf).length)} br`);
|
|
for (const rel of first) console.log(` ${rel.padEnd(38)} ${kb(size(rel)).padStart(9)} brut, ${kb(br(rel)).padStart(8)} br`);
|
|
console.log(` 1re visite (HTML+CSS+JS, br) : ${kb(first.reduce((t, r) => t + br(r), 0))}`);
|
|
console.log(` visite suivante (HTML seul, br) : ${kb(br('index.html'))}`);
|
|
return manifest;
|
|
}
|
|
|
|
if (require.main === module) build();
|
|
module.exports = { build, DIST };
|