@rgaa-audit/cli 0.0.0-stage → 0.4.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/browser.js ADDED
@@ -0,0 +1,61 @@
1
+ // src/browser.js
2
+ 'use strict';
3
+
4
+ const { warn } = require('./logger');
5
+
6
+ function formatBrowserIssue(issue) {
7
+ if (!issue) return '[browser] issue inconnue';
8
+ if (issue.type === 'pageerror') {
9
+ return `[browser][pageerror] ${issue.message || 'Erreur JavaScript inconnue'}`;
10
+ }
11
+ if (issue.type === 'requestfailed') {
12
+ const method = issue.method || 'GET';
13
+ const target = issue.url || '(url inconnue)';
14
+ const failure = issue.failureText || 'échec réseau';
15
+ return `[browser][requestfailed] ${method} ${target} — ${failure}`;
16
+ }
17
+ return `[browser][${issue.type || 'event'}] ${issue.message || 'événement navigateur'}`;
18
+ }
19
+
20
+ async function createBrowser({ headless = true, debug = false, onDebugEvent } = {}) {
21
+ const { chromium } = require('playwright');
22
+ const browser = await chromium.launch({ headless });
23
+ const context = await browser.newContext({
24
+ viewport: { width: 1280, height: 720 },
25
+ locale: 'fr-FR',
26
+ userAgent: `Mozilla/5.0 (compatible; RGAA-Audit-Bot/${require('../package.json').version})`,
27
+ colorScheme: 'light',
28
+ reducedMotion: 'no-preference',
29
+ });
30
+ const page = await context.newPage();
31
+
32
+ const emitDebugEvent = (payload) => {
33
+ if (typeof onDebugEvent === 'function') onDebugEvent(payload);
34
+ if (debug) warn(` ${formatBrowserIssue(payload)}`);
35
+ };
36
+
37
+ // On capte les incidents navigateur sans polluer la sortie standard.
38
+ page.on('pageerror', (error) => {
39
+ emitDebugEvent({
40
+ type: 'pageerror',
41
+ message: String(error?.message || error || '').trim(),
42
+ });
43
+ });
44
+
45
+ page.on('requestfailed', (request) => {
46
+ emitDebugEvent({
47
+ type: 'requestfailed',
48
+ url: request?.url?.() || '',
49
+ method: request?.method?.() || '',
50
+ failureText: request?.failure?.()?.errorText || '',
51
+ });
52
+ });
53
+
54
+ return { browser, page, context };
55
+ }
56
+
57
+ async function closeBrowser(browser) {
58
+ try { await browser.close(); } catch {}
59
+ }
60
+
61
+ module.exports = { createBrowser, closeBrowser, formatBrowserIssue };
@@ -0,0 +1,75 @@
1
+ // src/captures.js
2
+ // Captures annotées des éléments non conformes, reprises dans le rapport HTML vulgarisé.
3
+ 'use strict';
4
+
5
+ const fs = require('node:fs');
6
+ const path = require('node:path');
7
+
8
+ const OVERLAY_ID = '__rgaa_capture_overlay';
9
+ const MARGIN = 24;
10
+ const MAX_CLIP = { width: 900, height: 500 };
11
+
12
+ /**
13
+ * Photographie les premiers éléments non conformes de la page courante, entourés d'un
14
+ * cadre magenta. Ajoute `capture` (chemin du fichier) aux constats concernés.
15
+ */
16
+ async function captureFindings(page, results, { dir, prefix = 'p', max = 6 } = {}) {
17
+ fs.mkdirSync(dir, { recursive: true });
18
+ const done = new Set();
19
+ let taken = 0;
20
+ for (const result of results) {
21
+ if (taken >= max) break;
22
+ if (result.status !== 'NC' || !result.selector || done.has(result.selector)) continue;
23
+ done.add(result.selector);
24
+ const box = await page.evaluate(({ selector, overlayId }) => {
25
+ let el = null;
26
+ try { el = document.querySelector(selector); } catch { return null; }
27
+ if (!el) return null;
28
+ el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
29
+ const r = el.getBoundingClientRect();
30
+ if (r.width < 1 || r.height < 1) return null;
31
+ const overlay = document.createElement('div');
32
+ overlay.id = overlayId;
33
+ overlay.setAttribute('aria-hidden', 'true');
34
+ overlay.style.cssText = `position:fixed;left:${r.left - 4}px;top:${r.top - 4}px;width:${r.width + 8}px;height:${r.height + 8}px;`
35
+ + 'border:3px solid #FF00AA;box-shadow:0 0 0 2px #FFFFFF;border-radius:4px;z-index:2147483647;pointer-events:none;';
36
+ document.documentElement.appendChild(overlay);
37
+ return { x: r.left, y: r.top, width: r.width, height: r.height, vw: window.innerWidth, vh: window.innerHeight };
38
+ }, { selector: result.selector, overlayId: OVERLAY_ID }).catch(() => null);
39
+ if (!box) continue;
40
+
41
+ const x = Math.max(0, Math.floor(box.x - MARGIN));
42
+ const y = Math.max(0, Math.floor(box.y - MARGIN));
43
+ const width = Math.min(MAX_CLIP.width, box.vw - x, Math.ceil(box.width + MARGIN * 2));
44
+ const height = Math.min(MAX_CLIP.height, box.vh - y, Math.ceil(box.height + MARGIN * 2));
45
+ const file = path.join(dir, `nc-${prefix}-${taken + 1}.jpg`);
46
+ try {
47
+ if (width > 0 && height > 0) {
48
+ await page.screenshot({ path: file, clip: { x, y, width, height }, type: 'jpeg', quality: 70, animations: 'disabled' });
49
+ result.capture = file;
50
+ taken++;
51
+ }
52
+ } catch {
53
+ // élément hors de la zone capturable : on continue sans capture
54
+ } finally {
55
+ await page.evaluate((overlayId) => document.getElementById(overlayId)?.remove(), OVERLAY_ID).catch(() => {});
56
+ }
57
+ }
58
+ return taken;
59
+ }
60
+
61
+ /** Copie du rapport avec les captures en data URI, pour un rapport HTML autonome. */
62
+ function attachCaptureData(report) {
63
+ const captures = {};
64
+ for (const r of report.results || []) {
65
+ if (!r.capture || captures[r.capture]) continue;
66
+ try {
67
+ captures[r.capture] = `data:image/jpeg;base64,${fs.readFileSync(r.capture).toString('base64')}`;
68
+ } catch {
69
+ // capture supprimée entre-temps
70
+ }
71
+ }
72
+ return Object.keys(captures).length ? { ...report, captures } : report;
73
+ }
74
+
75
+ module.exports = { captureFindings, attachCaptureData };
@@ -0,0 +1,71 @@
1
+ // src/html-validation.js
2
+ // Validation du code source généré (RGAA 8.2) avec html-validate, exécuté localement :
3
+ // la page n'est envoyée à aucun service. Option --validate-html.
4
+ 'use strict';
5
+
6
+ const MAX_RESULTS_PER_RULE = 5;
7
+ // Déjà contrôlés par le moteur de règles (8.2 id en double) : pas de double compte.
8
+ const SKIPPED_RULES = new Set(['no-dup-id']);
9
+
10
+ function loadValidator() {
11
+ try {
12
+ const { HtmlValidate } = require('html-validate');
13
+ return new HtmlValidate({ extends: ['html-validate:standard'] });
14
+ } catch (err) {
15
+ throw new Error(`html-validate indisponible (Node.js 22.22 ou plus requis) : ${err.message}`);
16
+ }
17
+ }
18
+
19
+ function contextAround(source, line, column) {
20
+ const text = source.split('\n')[line - 1] || '';
21
+ const start = Math.max(0, column - 60);
22
+ return text.slice(start, start + 160).replace(/\s+/g, ' ').trim();
23
+ }
24
+
25
+ /** Transforme les messages html-validate en constats RGAA 8.2 regroupés par règle. */
26
+ function toFindings(messages, source) {
27
+ const byRule = new Map();
28
+ for (const m of messages) {
29
+ if (SKIPPED_RULES.has(m.ruleId)) continue;
30
+ if (!byRule.has(m.ruleId)) byRule.set(m.ruleId, []);
31
+ byRule.get(m.ruleId).push(m);
32
+ }
33
+ return [...byRule.entries()].map(([ruleId, items]) => ({
34
+ id: '8.2',
35
+ rule: `html-${ruleId}`,
36
+ status: 'NC',
37
+ resultType: 'probable_error',
38
+ severity: 'medium',
39
+ confidence: 'high',
40
+ manualReviewRecommended: false,
41
+ source: 'html-validate',
42
+ message: `Code source non valide (${ruleId}) : ${items[0].message}${items.length > 1 ? ` (${items.length} occurrences)` : ''}`,
43
+ count: items.length,
44
+ snippet: contextAround(source, items[0].line, items[0].column),
45
+ examples: items.slice(0, MAX_RESULTS_PER_RULE).map((m) => ({
46
+ selector: m.selector || `ligne ${m.line}, colonne ${m.column}`,
47
+ snippet: contextAround(source, m.line, m.column),
48
+ })),
49
+ rationale: 'Un code mal imbriqué ou invalide peut être interprété différemment par les technologies d’assistance (test 8.2.1).',
50
+ remediationHint: `Voir la règle html-validate « ${ruleId} » : https://html-validate.org/rules/${ruleId}.html`,
51
+ }));
52
+ }
53
+
54
+ async function validatePageHtml(page) {
55
+ const validator = loadValidator();
56
+ const source = await page.content();
57
+ const report = await validator.validateString(source);
58
+ const messages = (report.results[0] && report.results[0].messages) || [];
59
+ const findings = toFindings(messages, source);
60
+ if (!findings.length) {
61
+ findings.push({
62
+ id: '8.2', rule: 'html-valid', status: 'C', resultType: 'good_signal', severity: 'low', confidence: 'high',
63
+ manualReviewRecommended: false, source: 'html-validate', count: 1, examples: [], snippet: null,
64
+ message: 'Code source généré valide (html-validate, règles de conformité au standard).',
65
+ rationale: '', remediationHint: '',
66
+ });
67
+ }
68
+ return findings;
69
+ }
70
+
71
+ module.exports = { validatePageHtml, _internals: { toFindings, contextAround } };
package/src/logger.js ADDED
@@ -0,0 +1,18 @@
1
+ // src/logger.js
2
+ 'use strict';
3
+
4
+ const c = {
5
+ reset: '\x1b[0m',
6
+ dim: '\x1b[2m',
7
+ green: '\x1b[32m',
8
+ yellow: '\x1b[33m',
9
+ red: '\x1b[31m',
10
+ cyan: '\x1b[36m',
11
+ };
12
+
13
+ const log = (...a) => console.log(c.dim + a.join(' ') + c.reset);
14
+ const success = (...a) => console.log(c.green + a.join(' ') + c.reset);
15
+ const warn = (...a) => console.log(c.yellow + a.join(' ') + c.reset);
16
+ const error = (...a) => console.error(c.red + a.join(' ') + c.reset);
17
+
18
+ module.exports = { log, success, warn, error };
@@ -0,0 +1,100 @@
1
+ // src/page-prep.js
2
+ // Préparation d'une page avant mesure : fermeture du bandeau de consentement et
3
+ // bascule vers un thème alternatif piloté par le site (bouton, attribut, classe…).
4
+ 'use strict';
5
+
6
+ const { log, warn } = require('./logger');
7
+
8
+ const CONSENT_CONTAINER_HINT = /cookie|consent|gdpr|rgpd|tarteaucitron|axeptio|didomi|onetrust|cmp|privacy|vie-privee/i;
9
+ // Le refus est préféré à l'acceptation : il ne déclenche aucun traceur pendant l'audit.
10
+ const REFUSE_LABEL = /^(tout\s+)?refuser(\s+tout)?$|^continuer sans accepter$|^je refuse$|^reject( all)?$|^decline( all)?$|^deny$|^refuser les cookies$/i;
11
+ const CLOSE_LABEL = /^(fermer|close|ok|j’ai compris|j'ai compris|compris)$/i;
12
+
13
+ /**
14
+ * Ferme le bandeau de consentement. Avec un sélecteur explicite, clique dessus ; sinon
15
+ * cherche un bouton « Refuser » (à défaut « Fermer ») dans un conteneur qui ressemble à
16
+ * un bandeau cookies. Retourne le libellé cliqué, ou null.
17
+ */
18
+ async function dismissConsent(page, selector = '') {
19
+ if (selector) {
20
+ const target = page.locator(selector).first();
21
+ if (await target.isVisible().catch(() => false)) {
22
+ await target.click({ timeout: 3000 });
23
+ await page.waitForTimeout(300);
24
+ return selector;
25
+ }
26
+ return null;
27
+ }
28
+
29
+ const clicked = await page.evaluate(({ containerHint, refuse, close }) => {
30
+ const containerRe = new RegExp(containerHint.source, containerHint.flags);
31
+ const refuseRe = new RegExp(refuse.source, refuse.flags);
32
+ const closeRe = new RegExp(close.source, close.flags);
33
+ const visible = (el) => {
34
+ const r = el.getBoundingClientRect();
35
+ const s = window.getComputedStyle(el);
36
+ return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none';
37
+ };
38
+ const looksLikeBanner = (el) => {
39
+ let node = el;
40
+ for (let depth = 0; node && depth < 8; depth++, node = node.parentElement) {
41
+ const id = `${node.id} ${typeof node.className === 'string' ? node.className : ''} ${node.getAttribute('aria-label') || ''}`;
42
+ if (containerRe.test(id)) return true;
43
+ const s = window.getComputedStyle(node);
44
+ if ((s.position === 'fixed' || s.position === 'sticky') && /cookie|donn[ée]es|consent|traceur|audience/i.test(node.textContent || '')) return true;
45
+ if (node.getAttribute('role') === 'dialog' && /cookie|consent|traceur/i.test(node.textContent || '')) return true;
46
+ }
47
+ return false;
48
+ };
49
+ const buttons = [...document.querySelectorAll('button, [role="button"], a[href="#"], input[type="button"]')]
50
+ .filter((b) => visible(b) && looksLikeBanner(b));
51
+ const label = (b) => (b.innerText || b.value || b.getAttribute('aria-label') || '').replace(/\s+/g, ' ').trim();
52
+ const target = buttons.find((b) => refuseRe.test(label(b))) || buttons.find((b) => closeRe.test(label(b)));
53
+ if (!target) return null;
54
+ target.click();
55
+ return label(target);
56
+ }, { containerHint: toPlain(CONSENT_CONTAINER_HINT), refuse: toPlain(REFUSE_LABEL), close: toPlain(CLOSE_LABEL) });
57
+
58
+ if (clicked) await page.waitForTimeout(300);
59
+ return clicked;
60
+ }
61
+
62
+ function toPlain(re) {
63
+ return { source: re.source, flags: re.flags };
64
+ }
65
+
66
+ /**
67
+ * Crée la fonction de préparation appelée après chaque navigation ou rechargement.
68
+ * options.dismiss : 'auto' (défaut), 'off', ou un sélecteur CSS du bouton à cliquer.
69
+ */
70
+ function createPagePreparer(page, { dismiss = 'auto' } = {}) {
71
+ let announced = false;
72
+ return async function preparePage() {
73
+ if (dismiss === 'off') return;
74
+ try {
75
+ const clicked = await dismissConsent(page, dismiss === 'auto' ? '' : dismiss);
76
+ if (clicked && !announced) {
77
+ log(` Bandeau de consentement fermé (« ${clicked} »)`);
78
+ announced = true;
79
+ }
80
+ } catch (err) {
81
+ warn(` Fermeture du bandeau de consentement impossible : ${String(err?.message || err).split('\n')[0]}`);
82
+ }
83
+ };
84
+ }
85
+
86
+ /**
87
+ * Bascule vers le thème alternatif du site : clic sur un sélecteur (bouton de thème)
88
+ * et/ou exécution d'un script (ex. document.documentElement.dataset.theme = 'light').
89
+ */
90
+ async function applyAlternateTheme(page, { click = '', script = '' } = {}) {
91
+ if (click) {
92
+ await page.locator(click).first().click({ timeout: 5000 });
93
+ }
94
+ if (script) {
95
+ await page.evaluate(script);
96
+ }
97
+ await page.waitForTimeout(400);
98
+ }
99
+
100
+ module.exports = { createPagePreparer, dismissConsent, applyAlternateTheme };
@@ -0,0 +1,59 @@
1
+ // src/reporters/index.js
2
+ 'use strict';
3
+
4
+ const { requireShared } = require('../shared');
5
+
6
+ const { generateVulgarizedReport } = requireShared('vulgarized-report-template.js');
7
+ const { RGAA_CRITERIA } = requireShared('rgaa-criteria.js');
8
+
9
+ async function generateReport(report, format = 'json') {
10
+ switch (format) {
11
+ case 'html':
12
+ case 'vulgarized':
13
+ return generateVulgarizedReport(report, { includeCliLink: false });
14
+ case 'csv':
15
+ return generateCsv(report);
16
+ default:
17
+ return JSON.stringify(report, null, 2);
18
+ }
19
+ }
20
+
21
+ /**
22
+ * Cellule CSV sûre : guillemets doublés, retours à la ligne aplatis, et neutralisation des
23
+ * débuts de formule (=, +, -, @) puisque les messages reprennent des textes de la page auditée.
24
+ */
25
+ function csvCell(value, max = 0) {
26
+ let text = String(value ?? '').replace(/\s+/g, ' ').trim();
27
+ if (max && text.length > max) text = `${text.slice(0, max)}…`;
28
+ if (/^[=+\-@\t\r]/.test(text)) text = `'${text}`;
29
+ return `"${text.replace(/"/g, '""')}"`;
30
+ }
31
+
32
+ function generateCsv(report) {
33
+ const headers = [
34
+ 'Page', 'Critère', 'Intitulé du critère', 'Statut', 'Type résultat', 'Gravité', 'Confiance',
35
+ 'Revue manuelle', 'Occurrences', 'Message', 'Justification', 'Remédiation', 'Source', 'Contexte',
36
+ 'Sélecteur', 'Extrait',
37
+ ];
38
+ const rows = (report.results || []).map((r) => [
39
+ csvCell(r.pageUrl || report.url || ''),
40
+ csvCell(r.id),
41
+ csvCell(RGAA_CRITERIA[r.id] || ''),
42
+ csvCell(r.status),
43
+ csvCell(r.resultType || ''),
44
+ csvCell(r.severity || ''),
45
+ csvCell(r.confidence || ''),
46
+ csvCell(r.manualReviewRecommended ? 'oui' : 'non'),
47
+ csvCell(r.count || 1),
48
+ csvCell(r.message),
49
+ csvCell(r.rationale),
50
+ csvCell(r.remediationHint),
51
+ csvCell(r.source || 'dom'),
52
+ csvCell(r.context || ''),
53
+ csvCell(r.selector || ''),
54
+ csvCell(r.snippet || '', 200),
55
+ ].join(';'));
56
+ return [headers.map((h) => csvCell(h)).join(';'), ...rows].join('\n');
57
+ }
58
+
59
+ module.exports = { generateReport, _internals: { csvCell, generateCsv } };
@@ -0,0 +1,240 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const os = require('node:os');
5
+ const path = require('node:path');
6
+ const { execFileSync } = require('node:child_process');
7
+ const { requireShared } = require('../shared');
8
+
9
+ const { criterionStatus } = requireShared('rgaa-rules.js');
10
+
11
+ function assertSafeArchiveEntries(zipPath) {
12
+ const listing = execFileSync('unzip', ['-Z1', zipPath], {
13
+ encoding: 'utf8',
14
+ stdio: ['ignore', 'pipe', 'pipe'],
15
+ });
16
+ const entries = String(listing).split(/\r?\n/).map(line => line.trim()).filter(Boolean);
17
+
18
+ for (const entry of entries) {
19
+ const normalized = entry.replace(/\\/g, '/');
20
+ const segments = normalized.split('/').filter(Boolean);
21
+
22
+ const isAbsolute = normalized.startsWith('/') || /^[a-zA-Z]:\//.test(normalized);
23
+ const hasParentTraversal = segments.includes('..');
24
+
25
+ if (isAbsolute || hasParentTraversal) {
26
+ throw new Error(`Archive ODS invalide: chemin dangereux détecté (${entry})`);
27
+ }
28
+ }
29
+ }
30
+
31
+ function xmlEscape(value) {
32
+ return String(value)
33
+ .replace(/&/g, '&amp;')
34
+ .replace(/</g, '&lt;')
35
+ .replace(/>/g, '&gt;')
36
+ .replace(/"/g, '&quot;')
37
+ .replace(/'/g, '&apos;');
38
+ }
39
+
40
+ function aggregateCriterionStatuses(results = []) {
41
+ const byCriterion = new Map();
42
+
43
+ for (const item of results) {
44
+ if (!item || !item.id) continue;
45
+ if (!byCriterion.has(item.id)) byCriterion.set(item.id, []);
46
+ byCriterion.get(item.id).push(item);
47
+ }
48
+
49
+ const summary = new Map();
50
+ for (const [criterionId, items] of byCriterion.entries()) {
51
+ const status = criterionStatus(items.map(i => i.status));
52
+
53
+ // Pour un critère « à vérifier », on ne reporte que les indices détectés, pas les rappels génériques.
54
+ const notes = items
55
+ .filter(i => i.status === status && (status === 'NC' || i.resultType === 'heuristic_warning'))
56
+ .map(i => (status === 'NT' ? `À vérifier : ${i.message}` : i.message))
57
+ .filter(Boolean)
58
+ .slice(0, 3)
59
+ .join(' | ');
60
+
61
+ summary.set(criterionId, { status, notes });
62
+ }
63
+
64
+ return summary;
65
+ }
66
+
67
+ function replaceTextP(rowXml, textIndex, value) {
68
+ let seen = 0;
69
+ return rowXml.replace(/<text:p>[\s\S]*?<\/text:p>/g, match => {
70
+ seen += 1;
71
+ if (seen !== textIndex) return match;
72
+ return `<text:p>${xmlEscape(value)}</text:p>`;
73
+ });
74
+ }
75
+
76
+ function updateCriteriaRows(sheetXml, criterionMap) {
77
+ return sheetXml.replace(/<table:table-row\b[\s\S]*?<\/table:table-row>/g, row => {
78
+ const criterionMatch = row.match(/table:style-name="ce65"[^>]*office:string-value="([0-9]+\.[0-9]+)"/);
79
+ if (!criterionMatch) return row;
80
+
81
+ const criterionId = criterionMatch[1];
82
+ const mapped = criterionMap.get(criterionId);
83
+ if (!mapped) return row;
84
+
85
+ let updated = row;
86
+
87
+ updated = updated.replace(
88
+ /(table:content-validation-name="val1"[^>]*>\s*<text:p>)([^<]*)(<\/text:p>)/,
89
+ (_, start, _old, end) => `${start}${mapped.status}${end}`,
90
+ );
91
+
92
+ updated = updated.replace(
93
+ /(table:content-validation-name="val1"[^>]*)(office:string-value="[^"]*")?/,
94
+ (full, prefix) => {
95
+ const cleaned = full.replace(/\s*office:string-value="[^"]*"/, '');
96
+ return `${cleaned} office:string-value="${xmlEscape(mapped.status)}"`;
97
+ },
98
+ );
99
+
100
+ if ((mapped.status === 'NC' || mapped.status === 'NT') && mapped.notes) {
101
+ const note = xmlEscape(mapped.notes);
102
+ // Place quick remediation hints in "Modifications à apporter" when the template still has
103
+ // two repeated empty cells for columns 6-7.
104
+ updated = updated.replace(
105
+ /<table:table-cell table:style-name="ce156" table:number-columns-repeated="2"\/>/,
106
+ `<table:table-cell table:style-name="ce156" office:value-type="string" office:string-value="${note}" calcext:value-type="string"><text:p>${note}</text:p></table:table-cell><table:table-cell table:style-name="ce156"/>`,
107
+ );
108
+ }
109
+
110
+ return updated;
111
+ });
112
+ }
113
+
114
+ function updatePageHeaderRow(sheetXml, title, url) {
115
+ return sheetXml.replace(
116
+ /(<table:table-row\b[\s\S]*?<table:table-cell[^>]*table:formula="of:=CONCATENATE\(\[Échantillon\.B\d+\];&quot; : &quot;;\[Échantillon\.C\d+\]\)"[\s\S]*?<\/table:table-row>)/,
117
+ row => replaceTextP(row, 1, `${title} : ${url}`),
118
+ );
119
+ }
120
+
121
+ function updateEchantillonSheet(sheetXml, pageEntries, siteLabel) {
122
+ return sheetXml.replace(/<table:table-row\b[\s\S]*?<\/table:table-row>/g, row => {
123
+ if (/<text:p>Site[^<]*:<\/text:p>/.test(row)) {
124
+ return replaceTextP(row, 2, siteLabel);
125
+ }
126
+
127
+ const pageMatch = row.match(/<text:p>(P\d{2})<\/text:p>/);
128
+ if (!pageMatch) return row;
129
+ const pageCode = pageMatch[1];
130
+ const entry = pageEntries.find(p => p.pageCode === pageCode);
131
+ if (!entry) return row;
132
+ let r = replaceTextP(row, 2, entry.title || pageCode);
133
+ r = replaceTextP(r, 3, entry.url || '');
134
+ return r;
135
+ });
136
+ }
137
+
138
+ function fillRgaaGridFromReports({
139
+ reports,
140
+ templatePath,
141
+ outputPath,
142
+ replicateToAllSheets = false,
143
+ }) {
144
+ if (!Array.isArray(reports) || reports.length === 0) {
145
+ throw new Error('Aucun rapport fourni.');
146
+ }
147
+ if (!templatePath || !outputPath) {
148
+ throw new Error('Paramètres manquants: templatePath et outputPath sont requis.');
149
+ }
150
+ const resolvedTemplatePath = path.resolve(templatePath);
151
+ const resolvedOutputPath = path.resolve(outputPath);
152
+
153
+ const normalized = reports.map((report, idx) => {
154
+ if (!report || !Array.isArray(report.results)) {
155
+ throw new Error(`Rapport invalide à l'index ${idx}: tableau "results" manquant.`);
156
+ }
157
+ return {
158
+ pageCode: `P${String(idx + 1).padStart(2, '0')}`,
159
+ title: report.title || `Page ${idx + 1}`,
160
+ url: report.url || '',
161
+ criterionMap: aggregateCriterionStatuses(report.results),
162
+ };
163
+ });
164
+
165
+ const pageEntries = Array.from({ length: 20 }, (_, i) => ({
166
+ pageCode: `P${String(i + 1).padStart(2, '0')}`,
167
+ title: 'Non audité',
168
+ url: '',
169
+ criterionMap: null,
170
+ }));
171
+
172
+ if (replicateToAllSheets && normalized[0]) {
173
+ for (const entry of pageEntries) {
174
+ entry.title = normalized[0].title;
175
+ entry.url = normalized[0].url;
176
+ entry.criterionMap = normalized[0].criterionMap;
177
+ }
178
+ } else {
179
+ normalized.forEach((entry, idx) => {
180
+ if (!pageEntries[idx]) return;
181
+ pageEntries[idx].title = entry.title;
182
+ pageEntries[idx].url = entry.url;
183
+ pageEntries[idx].criterionMap = entry.criterionMap;
184
+ });
185
+ }
186
+
187
+ const siteLabel = normalized[0].url || normalized[0].title || 'Site audité';
188
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'rgaa-grid-'));
189
+
190
+ try {
191
+ assertSafeArchiveEntries(resolvedTemplatePath);
192
+ execFileSync('unzip', ['-q', resolvedTemplatePath, '-d', tempDir], { stdio: 'pipe' });
193
+
194
+ const contentXmlPath = path.join(tempDir, 'content.xml');
195
+ const xml = fs.readFileSync(contentXmlPath, 'utf8');
196
+
197
+ let updatedXml = xml;
198
+
199
+ const echantillonRegex = /<table:table table:name="Échantillon"[\s\S]*?<\/table:table>/;
200
+ const echantillonMatch = updatedXml.match(echantillonRegex);
201
+ if (echantillonMatch) {
202
+ const updatedEchantillon = updateEchantillonSheet(echantillonMatch[0], pageEntries, siteLabel);
203
+ updatedXml = updatedXml.replace(echantillonRegex, updatedEchantillon);
204
+ }
205
+
206
+ for (const entry of pageEntries) {
207
+ const sheetRegex = new RegExp(`<table:table table:name="${entry.pageCode}"[\\s\\S]*?<\\/table:table>`);
208
+ const sheetMatch = updatedXml.match(sheetRegex);
209
+ if (!sheetMatch) continue;
210
+ let sheet = sheetMatch[0];
211
+ sheet = updatePageHeaderRow(sheet, entry.title, entry.url);
212
+ if (entry.criterionMap) {
213
+ sheet = updateCriteriaRows(sheet, entry.criterionMap);
214
+ }
215
+ updatedXml = updatedXml.replace(sheetRegex, sheet);
216
+ }
217
+
218
+ fs.writeFileSync(contentXmlPath, updatedXml, 'utf8');
219
+
220
+ if (fs.existsSync(resolvedOutputPath)) fs.unlinkSync(resolvedOutputPath);
221
+
222
+ execFileSync('zip', ['-X', '-0', resolvedOutputPath, 'mimetype'], { cwd: tempDir, stdio: 'pipe' });
223
+ execFileSync('zip', ['-X', '-r', resolvedOutputPath, '.', '-x', 'mimetype'], { cwd: tempDir, stdio: 'pipe' });
224
+
225
+ return {
226
+ outputPath: resolvedOutputPath,
227
+ filledSheets: pageEntries.filter(p => p.criterionMap).length,
228
+ filledCriteria: pageEntries.reduce((acc, p) => acc + (p.criterionMap ? p.criterionMap.size : 0), 0),
229
+ };
230
+ } finally {
231
+ fs.rmSync(tempDir, { recursive: true, force: true });
232
+ }
233
+ }
234
+
235
+ module.exports = {
236
+ fillRgaaGridFromReports,
237
+ // Exposed for tests
238
+ _aggregateCriterionStatuses: aggregateCriterionStatuses,
239
+ _updateCriteriaRows: updateCriteriaRows,
240
+ };