Standardize public images on WebP and add conversion tooling
All checks were successful
Deploy Sokko G / deploy (push) Successful in 20s
All checks were successful
Deploy Sokko G / deploy (push) Successful in 20s
This commit is contained in:
parent
75592d7d7a
commit
ca39b76282
883 changed files with 503 additions and 90 deletions
152
scripts/convert-public-images.mjs
Normal file
152
scripts/convert-public-images.mjs
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
// Rôle : convertit des PNG publics vers le format WebP canonique du site.
|
||||
import { spawn } from "node:child_process";
|
||||
import { readdir, rename, rm, stat } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
const PRESETS = new Set(["default", "picture", "photo", "drawing", "icon", "text"]);
|
||||
const options = {
|
||||
allowLarger: false,
|
||||
dryRun: false,
|
||||
force: false,
|
||||
lossless: false,
|
||||
preset: "picture",
|
||||
keepSource: false,
|
||||
quality: 90
|
||||
};
|
||||
const inputs = [];
|
||||
|
||||
function printHelp() {
|
||||
console.log(`Usage: npm run images:convert -- <fichier-ou-dossier...> [options]
|
||||
|
||||
Convertit récursivement les fichiers PNG en WebP dans le même dossier.
|
||||
Chaque PNG source est supprimé après une conversion réussie.
|
||||
|
||||
Options :
|
||||
--quality=<1-100> Qualité avec pertes (défaut : 90)
|
||||
--preset=<nom> default, picture, photo, drawing, icon ou text
|
||||
--lossless Utilise WebP sans perte ; ignore quality et preset
|
||||
--allow-larger Accepte un WebP plus lourd que le PNG source
|
||||
--keep-source Conserve le PNG source pour une comparaison ponctuelle
|
||||
--force Remplace un WebP déjà présent
|
||||
--dry-run Affiche les conversions sans écrire de fichier
|
||||
--help Affiche cette aide`);
|
||||
}
|
||||
|
||||
for (const argument of process.argv.slice(2)) {
|
||||
if (argument === "--help" || argument === "-h") {
|
||||
printHelp();
|
||||
process.exit(0);
|
||||
} else if (argument === "--allow-larger") options.allowLarger = true;
|
||||
else if (argument === "--dry-run") options.dryRun = true;
|
||||
else if (argument === "--force") options.force = true;
|
||||
else if (argument === "--lossless") options.lossless = true;
|
||||
else if (argument === "--keep-source") options.keepSource = true;
|
||||
else if (argument.startsWith("--quality=")) options.quality = Number(argument.slice("--quality=".length));
|
||||
else if (argument.startsWith("--preset=")) options.preset = argument.slice("--preset=".length);
|
||||
else if (argument.startsWith("--")) throw new Error(`Option inconnue : ${argument}`);
|
||||
else inputs.push(argument);
|
||||
}
|
||||
|
||||
if (!Number.isInteger(options.quality) || options.quality < 1 || options.quality > 100) {
|
||||
throw new Error("--quality doit être un entier compris entre 1 et 100.");
|
||||
}
|
||||
if (!PRESETS.has(options.preset)) throw new Error(`Preset WebP inconnu : ${options.preset}`);
|
||||
if (inputs.length === 0) {
|
||||
printHelp();
|
||||
process.exitCode = 1;
|
||||
} else {
|
||||
await convertInputs();
|
||||
}
|
||||
|
||||
async function collectPngFiles(input) {
|
||||
const inputPath = path.resolve(input);
|
||||
const inputStat = await stat(inputPath);
|
||||
if (inputStat.isFile()) {
|
||||
if (!inputPath.toLowerCase().endsWith(".png")) throw new Error(`Le fichier n'est pas un PNG : ${input}`);
|
||||
return [inputPath];
|
||||
}
|
||||
if (!inputStat.isDirectory()) throw new Error(`Entrée non prise en charge : ${input}`);
|
||||
|
||||
const entries = await readdir(inputPath, { withFileTypes: true });
|
||||
return (await Promise.all(entries.map((entry) => {
|
||||
const entryPath = path.join(inputPath, entry.name);
|
||||
if (entry.isDirectory()) return collectPngFiles(entryPath);
|
||||
return entry.isFile() && entry.name.toLowerCase().endsWith(".png") ? [entryPath] : [];
|
||||
}))).flat();
|
||||
}
|
||||
|
||||
function runFfmpeg(argumentsList) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn("ffmpeg", argumentsList, { stdio: ["ignore", "ignore", "pipe"] });
|
||||
let stderr = "";
|
||||
child.stderr.setEncoding("utf8");
|
||||
child.stderr.on("data", (chunk) => { stderr += chunk; });
|
||||
child.once("error", (error) => reject(error.code === "ENOENT" ? new Error("ffmpeg est requis pour convertir les images.") : error));
|
||||
child.once("close", (code) => code === 0 ? resolve() : reject(new Error(stderr.trim() || `ffmpeg a quitté avec le code ${code}.`)));
|
||||
});
|
||||
}
|
||||
|
||||
async function convertImage(source) {
|
||||
const target = source.replace(/\.png$/i, ".webp");
|
||||
const relativeSource = path.relative(process.cwd(), source);
|
||||
const relativeTarget = path.relative(process.cwd(), target);
|
||||
try {
|
||||
await stat(target);
|
||||
if (!options.force) {
|
||||
console.log(`Ignoré : ${relativeTarget} existe déjà (utiliser --force pour le remplacer).`);
|
||||
return null;
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.code !== "ENOENT") throw error;
|
||||
}
|
||||
|
||||
if (options.dryRun) {
|
||||
console.log(`[simulation] ${relativeSource} -> ${relativeTarget}${options.keepSource ? "" : " puis suppression du PNG"}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
const temporaryTarget = `${target}.${process.pid}.tmp.webp`;
|
||||
const encoding = options.lossless
|
||||
? ["-lossless", "1", "-quality", "100", "-compression_level", "6", "-pix_fmt", "bgra"]
|
||||
: ["-preset", options.preset, "-quality", String(options.quality), "-compression_level", "6"];
|
||||
try {
|
||||
await runFfmpeg(["-y", "-v", "error", "-i", source, "-c:v", "libwebp", ...encoding, temporaryTarget]);
|
||||
const [sourceStat, targetStat] = await Promise.all([stat(source), stat(temporaryTarget)]);
|
||||
if (targetStat.size === 0) throw new Error(`La conversion de ${relativeSource} a produit un fichier vide.`);
|
||||
if (targetStat.size >= sourceStat.size && !options.allowLarger) {
|
||||
await rm(temporaryTarget);
|
||||
console.log(`Conservé : ${relativeSource}, le WebP serait plus lourd (${sourceStat.size} -> ${targetStat.size} octets).`);
|
||||
return null;
|
||||
}
|
||||
await rename(temporaryTarget, target);
|
||||
if (!options.keepSource) await rm(source);
|
||||
console.log(`${relativeSource} -> ${relativeTarget} (${sourceStat.size} -> ${targetStat.size} octets)`);
|
||||
return { sourceBytes: sourceStat.size, targetBytes: targetStat.size };
|
||||
} catch (error) {
|
||||
await rm(temporaryTarget, { force: true });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function convertInputs() {
|
||||
const collected = (await Promise.all(inputs.map(collectPngFiles))).flat();
|
||||
const sources = [...new Set(collected)].sort((left, right) => left.localeCompare(right, "fr"));
|
||||
if (sources.length === 0) {
|
||||
console.log("Aucun fichier PNG trouvé.");
|
||||
return;
|
||||
}
|
||||
|
||||
const results = [];
|
||||
for (const source of sources) {
|
||||
const result = await convertImage(source);
|
||||
if (result) results.push(result);
|
||||
}
|
||||
if (options.dryRun || results.length === 0) return;
|
||||
|
||||
const sourceBytes = results.reduce((total, result) => total + result.sourceBytes, 0);
|
||||
const targetBytes = results.reduce((total, result) => total + result.targetBytes, 0);
|
||||
const difference = Math.abs((sourceBytes - targetBytes) * 100 / sourceBytes).toFixed(1);
|
||||
const evolution = targetBytes <= sourceBytes ? `${difference} % de moins` : `${difference} % de plus`;
|
||||
console.log(`${results.length} image(s) convertie(s) : ${sourceBytes} -> ${targetBytes} octets (${evolution}).`);
|
||||
if (options.keepSource) console.log("Les PNG source sont conservés pour comparaison.");
|
||||
}
|
||||
139
scripts/measure-public-assets.mjs
Normal file
139
scripts/measure-public-assets.mjs
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
// Rôle : mesure les octets chargés par l'accueil et Aniimo sur le build servi par le serveur Node.
|
||||
import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
|
||||
import { platform } from "node:os";
|
||||
import { basename, join } from "node:path";
|
||||
import { gzipSync } from "node:zlib";
|
||||
import assert from "node:assert/strict";
|
||||
import { chromium } from "@playwright/test";
|
||||
import { createStaticServer } from "../server.mjs";
|
||||
|
||||
const label = String(process.argv[2] || "current").replace(/[^a-z0-9_-]+/gi, "-");
|
||||
const viewport = { width: 1440, height: 900 };
|
||||
const budgets = {
|
||||
publicImageBytes: 25_000_000,
|
||||
cssGzipBytes: 70_000,
|
||||
routeTransferBytes: {
|
||||
"home-cold": 1_750_000,
|
||||
"aniimo-after-home": 3_000_000
|
||||
}
|
||||
};
|
||||
|
||||
async function listFiles(root) {
|
||||
const entries = await readdir(root, { withFileTypes: true });
|
||||
return (await Promise.all(entries.map(async (entry) => {
|
||||
const path = join(root, entry.name);
|
||||
return entry.isDirectory() ? listFiles(path) : [path];
|
||||
}))).flat();
|
||||
}
|
||||
|
||||
async function measureEntries(page, includeDocument) {
|
||||
return page.evaluate(({ withDocument }) => {
|
||||
const resources = performance.getEntriesByType("resource");
|
||||
const entries = withDocument ? [...performance.getEntriesByType("navigation"), ...resources] : resources;
|
||||
const summarize = (values) => ({
|
||||
requests: values.length,
|
||||
transferBytes: values.reduce((sum, entry) => sum + entry.transferSize, 0),
|
||||
encodedBytes: values.reduce((sum, entry) => sum + entry.encodedBodySize, 0),
|
||||
decodedBytes: values.reduce((sum, entry) => sum + entry.decodedBodySize, 0)
|
||||
});
|
||||
return {
|
||||
...summarize(entries),
|
||||
images: summarize(resources.filter((entry) => entry.initiatorType === "img" || /\.(?:png|webp|jpe?g)(?:\?|$)/i.test(entry.name))),
|
||||
styles: summarize(resources.filter((entry) => entry.initiatorType === "link" && /\.css(?:\?|$)/i.test(entry.name))),
|
||||
largestTransfers: [...resources]
|
||||
.sort((left, right) => right.transferSize - left.transferSize)
|
||||
.slice(0, 10)
|
||||
.map((entry) => ({ path: new URL(entry.name).pathname, transferBytes: entry.transferSize }))
|
||||
};
|
||||
}, { withDocument: includeDocument });
|
||||
}
|
||||
|
||||
async function routeReport(page, { name, route, selector, includeDocument }) {
|
||||
if (!includeDocument) await page.evaluate(() => performance.clearResourceTimings());
|
||||
await page.goto(route, { waitUntil: "networkidle" });
|
||||
await page.locator(selector).first().waitFor({ state: "visible" });
|
||||
await page.waitForTimeout(500);
|
||||
const metrics = await measureEntries(page, includeDocument);
|
||||
const images = await page.locator("img").evaluateAll(async (nodes) => {
|
||||
const loaded = nodes.filter((node) => node.complete && node.naturalWidth > 0);
|
||||
await Promise.all(loaded.map((node) => node.decode()));
|
||||
return { present: nodes.length, decoded: loaded.length };
|
||||
});
|
||||
return { name, route, ...metrics, imageElements: images };
|
||||
}
|
||||
|
||||
const imageFiles = await listFiles("website/public/static/img");
|
||||
const cssFiles = (await listFiles("website/dist/assets")).filter((file) => file.endsWith(".css"));
|
||||
const server = createStaticServer();
|
||||
await new Promise((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(0, "127.0.0.1", resolve);
|
||||
});
|
||||
|
||||
let browser;
|
||||
try {
|
||||
const address = server.address();
|
||||
const baseURL = `http://127.0.0.1:${address.port}`;
|
||||
browser = await chromium.launch();
|
||||
const context = await browser.newContext({ viewport, serviceWorkers: "block" });
|
||||
const page = await context.newPage();
|
||||
const errors = [];
|
||||
page.on("pageerror", (error) => errors.push(error.message));
|
||||
page.on("requestfailed", (request) => errors.push(`${request.url()}: ${request.failure()?.errorText || "request failed"}`));
|
||||
|
||||
const routes = [];
|
||||
routes.push(await routeReport(page, {
|
||||
name: "home-cold",
|
||||
route: `${baseURL}/#/`,
|
||||
selector: ".home-page, .hero",
|
||||
includeDocument: true
|
||||
}));
|
||||
routes.push(await routeReport(page, {
|
||||
name: "aniimo-after-home",
|
||||
route: `${baseURL}/#/games/aniimo/aniimos`,
|
||||
selector: ".aniimo-grid .aniimo-card",
|
||||
includeDocument: false
|
||||
}));
|
||||
|
||||
assert.deepEqual(errors, []);
|
||||
const css = await Promise.all(cssFiles.map(async (file) => {
|
||||
const content = await readFile(file);
|
||||
return { file: basename(file), bytes: content.length, gzipBytes: gzipSync(content).length };
|
||||
}));
|
||||
const report = {
|
||||
measuredAt: new Date().toISOString(),
|
||||
label,
|
||||
platform: platform(),
|
||||
browser: browser.version(),
|
||||
viewport,
|
||||
protocol: "HTTP/1.1 local server.mjs, fresh browser context, no throttling",
|
||||
budgets,
|
||||
repository: {
|
||||
publicImageFiles: imageFiles.length,
|
||||
publicImageBytes: (await Promise.all(imageFiles.map((file) => stat(file)))).reduce((sum, entry) => sum + entry.size, 0),
|
||||
css
|
||||
},
|
||||
routes
|
||||
};
|
||||
await mkdir(".local/performance", { recursive: true });
|
||||
const output = `.local/performance/public-assets-${label}.json`;
|
||||
await writeFile(output, `${JSON.stringify(report, null, 2)}\n`);
|
||||
console.table(routes.map((route) => ({
|
||||
route: route.name,
|
||||
requests: route.requests,
|
||||
transferBytes: route.transferBytes,
|
||||
imageRequests: route.images.requests,
|
||||
imageTransferBytes: route.images.transferBytes
|
||||
})));
|
||||
console.log(`CSS: ${css.map((entry) => `${entry.file} ${entry.bytes} bytes (${entry.gzipBytes} gzip)`).join(", ")}`);
|
||||
console.log(`Public images: ${report.repository.publicImageFiles} files, ${report.repository.publicImageBytes} bytes`);
|
||||
console.log(`Report: ${output}`);
|
||||
assert.ok(report.repository.publicImageBytes <= budgets.publicImageBytes, `Public images exceed ${budgets.publicImageBytes} bytes`);
|
||||
assert.ok(css.every((entry) => entry.gzipBytes <= budgets.cssGzipBytes), `A CSS bundle exceeds ${budgets.cssGzipBytes} gzip bytes`);
|
||||
for (const route of routes) {
|
||||
assert.ok(route.transferBytes <= budgets.routeTransferBytes[route.name], `${route.name} exceeds ${budgets.routeTransferBytes[route.name]} transfer bytes`);
|
||||
}
|
||||
} finally {
|
||||
await browser?.close();
|
||||
await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue