Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 | 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 235x 235x 230x 230x 5x 5x 5x 5x 5x 7x 3x 3x 3x 235x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 2x 4x 4x 4x 4x 4x 427x 427x 427x 427x 427x 427x 2x 2x 1x 1x 1x 1x 1x 1x 2x 427x 427x 427x 427x 427x 427x 58x 58x 58x 58x 58x 58x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 60x 60x 60x 60x 60x 60x 60x 142x 142x 82x 82x 82x 60x 60x 60x 60x 60x 37x 37x 23x 23x 23x 60x 60x 427x 427x 427x 427x 427x 427x 427x 427x 58x 58x 58x 58x 58x 58x 58x 58x 4x 4x 4x 3x 3x 4x 4x 58x 54x 54x 58x 58x 58x 58x 58x 54x 54x 54x 54x 54x 58x 58x 58x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 52x 52x 55x 58x 58x 56x 56x 1x 1x 1x 56x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 427x 427x 427x 427x 427x 12x 12x 12x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 427x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 44x 44x 44x 44x 39x 39x 35x 35x 35x 35x 35x 35x 10x 10x 10x 10x 10x 10x 10x 35x 25x 26x 26x 25x 25x 25x 25x 25x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 3x 3x 3x 1x 3x 2x 2x 3x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 427x 427x 427x 427x 427x 427x 427x 427x 427x 32x 32x 32x 32x 3x 3x 3x 3x 3x 3x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 6x 5x 5x 5x 6x 6x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 4x 4x 3x 3x 3x 4x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 29x 29x 29x 29x 29x 10x 10x 10x 10x 7x 7x 3x 3x 19x 32x 32x 32x 32x 12x 12x 12x 12x 12x 12x 7x 7x 1x 7x 6x 6x 7x 32x 7x 7x 32x | import fs from 'fs';
import path from 'path';
import { execSync } from 'child_process';
import AvenxCompiler from '../../lib/compiler.js';
import { reportAtlasDiagnostics } from '../../lib/compiler/atlas/diagnostics.js';
import { reportRewindDiagnostics } from '../../lib/compiler/rewind/diagnostics.js';
import { cyan, gray, green, red } from '../colors.js';
import { BuildError } from '../../lib/compiler/errors/index.js';
import { AvenxErrorCodes } from '../../lib/core/runtime/AvenxError.js';
import { A11Y_WARNING_CODES } from '../../lib/compiler/rules/accessibility.js';
import { watchDirectories } from '../utils.js';
/**
* Runs a configured lifecycle hook.
*
* A hook is part of the build, so a non-zero exit from one fails the build.
* execSync throws a generic "Command failed" error; it is re-thrown as a coded
* BuildError so the reason is legible and the CLI can render it like any other
* build failure.
* @param {string} phase - 'prebuild' or 'postbuild'.
* @param {string} command - The shell command to run.
* @param {string} baseDir - Working directory for the hook.
* @throws {BuildError} When the hook exits non-zero.
*/
function runHook(phase, command, baseDir) {
if (typeof command !== 'string' || command.trim() === '') {
return;
}
console.log(gray(`๐ Running ${phase} hook: ${command}...`));
try {
execSync(command, { stdio: 'inherit', cwd: baseDir });
} catch (err) {
const reason = typeof err.status === 'number' ? `exited with code ${err.status}` : err.message;
throw new BuildError(AvenxErrorCodes.COMPILER_HOOK_FAILED, phase, reason, command);
}
}
/**
* Runs the compiler build along with optional prebuild and postbuild lifecycle hooks.
*
* Throws on any failure. The caller turns that into an exit code; nothing here
* may report success for a build that did not complete.
* @param {object} cli - AvenxCLI instance containing config and baseDir.
* @param {object} [options] - Build options.
* @param {boolean} [options.watch] - True when this build is one cycle of a
* long-lived watch session, which is what allows the compilation cache.
* @returns {object} The compiler's build result.
* @throws {BuildError} When a hook or the compilation fails.
*/
export function buildProject(cli, options = {}) {
const hooks = (cli && cli.config && cli.config.hooks) || {};
const baseDir = (cli && cli.baseDir) || process.cwd();
runHook('prebuild', hooks.prebuild, baseDir);
// `watch` is what lets the compiler reuse cached compilation products, and it
// is passed only by the commands that keep a process alive across rebuilds.
// `avenx build` calls this without it and so always builds cold.
const result = new AvenxCompiler({
...cli.config,
watch: options.watch === true,
...(options.codeSplitting !== undefined ? { codeSplitting: options.codeSplitting } : {}),
}).build();
runHook('postbuild', hooks.postbuild, baseDir);
return result;
}
/**
* Runs one build and returns its diagnostics alongside the outcome.
*
* {@link buildProject} prints diagnostics and throws on failure, which is all
* `avenx build` needs. A long-lived caller -- the dev server -- needs the same
* pass as data, so it can put the diagnostics somewhere other than the
* terminal. The console is wrapped rather than silenced: everything still
* prints exactly as before, and the structured copies are collected on the
* side.
*
* Never throws: a failed build is reported as `ok: false` with the failure in
* both `error` and the last diagnostic, because the caller is a watch loop
* that must survive it.
* @param {object} cli - AvenxCLI instance containing config and baseDir.
* @param {object} [options] - Build options, forwarded to {@link buildProject}.
* @returns {{ok: boolean, result: object|null, error: Error|null, diagnostics: object[]}}
*/
export function runBuildPass(cli, options = {}) {
const diagnostics = [];
const originalWarn = console.warn;
const originalError = console.error;
console.warn = (...messages) => {
diagnostics.push(parseDiagnostic('warning', messages));
originalWarn(...messages);
};
console.error = (...messages) => {
diagnostics.push(parseDiagnostic('error', messages));
originalError(...messages);
};
try {
const result = buildProject(cli, options);
return { ok: true, result, error: null, diagnostics };
} catch (error) {
diagnostics.push(parseDiagnostic('error', [error]));
return { ok: false, result: null, error, diagnostics };
} finally {
console.warn = originalWarn;
console.error = originalError;
}
}
/**
* Cleans the project by deleting the build output directory.
* @param {object} cli - AvenxCLI instance containing config and baseDir.
*/
export function cleanProject(cli) {
const distDir = path.join(cli.baseDir, cli.config.distDir);
if (fs.existsSync(distDir)) {
console.log(cyan(`๐งน Cleaning build output directory: ${cli.config.distDir}...`));
fs.rmSync(distDir, { recursive: true, force: true });
console.log(green('โ
Clean complete.'));
} else {
console.log(cyan(`๐งน Build output directory ${cli.config.distDir} does not exist. Nothing to clean.`));
}
}
/**
* Strips ANSI color escape codes from a message string.
* @param {string} str
* @returns {string}
*/
function stripAnsi(str) {
if (typeof str !== 'string') return String(str || '');
const ansiPattern = '(?:\\u001b|\\u009b)[[(#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nseries]';
const ansiRegex = new RegExp(ansiPattern, 'g');
return str.replace(ansiRegex, '').trim();
}
/**
* Splits a trailing caret code frame off a diagnostic message.
*
* Compiler errors append their frame to `message` (see
* `CompilerError.setLocation`), and warnings printed with one do the same. A
* consumer that renders the message and the frame in different places -- the
* dev-server error overlay puts the frame in a monospaced block -- needs them
* apart, so the frame is recognised by its gutter (` 12 | ...` and ` | ^^^`)
* and removed from the message.
* @param {string} message - The diagnostic text, frame included.
* @returns {{message: string, frame: string|null}} The split parts.
*/
export function splitCodeFrame(message) {
if (typeof message !== 'string' || message === '') {
return { message: typeof message === 'string' ? message : '', frame: null };
}
const lines = message.split(/\r?\n/);
const isFrameLine = (line) => /^\s*(?:\d+\s*)?\|/.test(line);
let start = lines.length;
while (start > 0) {
const line = lines[start - 1];
if (isFrameLine(line) || (line.trim() === '' && start < lines.length)) {
start -= 1;
continue;
}
break;
}
// A block of blank lines alone is not a frame.
if (!lines.slice(start).some(isFrameLine)) {
return { message, frame: null };
}
const frame = lines.slice(start).join('\n').replace(/^\n+|\n+$/g, '');
const head = lines.slice(0, start).join('\n').replace(/\s+$/, '');
return { message: head, frame: frame || null };
}
/**
* Parses raw diagnostic inputs into a structured object.
* @param {string} severity - 'warning' or 'error'
* @param {any[]} args - Log or error arguments
* @returns {object} Diagnostic object
*/
export function parseDiagnostic(severity, args) {
let file = null;
let code = null;
let rawMsg;
let line = null;
let column = null;
const firstArg = args && args[0];
if (firstArg instanceof Error) {
rawMsg = firstArg.message || String(firstArg);
if (firstArg.code) code = firstArg.code;
if (firstArg.filePath || firstArg.fileName || firstArg.filename || firstArg.file) {
file = firstArg.filePath || firstArg.fileName || firstArg.filename || firstArg.file;
}
if (typeof firstArg.line === 'number') line = firstArg.line;
if (typeof firstArg.column === 'number') column = firstArg.column;
} else if (Array.isArray(args)) {
rawMsg = args.map((a) => (typeof a === 'object' && a !== null ? (a.message || JSON.stringify(a)) : String(a))).join(' ');
} else {
rawMsg = String(args || '');
}
rawMsg = stripAnsi(rawMsg);
// Extract error code if not found on error object
if (!code) {
const codeMatch = rawMsg.match(/\[?(AVX_[A-Z0-9]+)\]?/);
if (codeMatch) {
code = codeMatch[1];
}
}
// Extract file path/name if not found on error object
if (!file) {
const searchable = rawMsg.replace(/avenx\.config\.json/gi, '');
const fileMatch =
searchable.match(/in template of\s+["']?([^"'\s]+\.[a-zA-Z0-9]+)["']?/i) ||
searchable.match(/in stylesheet\s+["']?([^"'\s]+\.[a-zA-Z0-9]+)["']?/i) ||
searchable.match(/in component\s+<([^>]+)>/i) ||
searchable.match(/at\s+["']?([^"'\s]+\.[a-zA-Z0-9]+)["']?/i) ||
searchable.match(/["']?([a-zA-Z0-9_\-/\\]+\.(?:component\.js|page\.js|js|mjs|cjs|html|css|json))(?![\w.])["']?/i);
if (fileMatch) {
file = fileMatch[1];
}
}
if (line === null) {
const locMatch = rawMsg.match(/:(\d+):(\d+)/) || rawMsg.match(/line\s+(\d+),\s+column\s+(\d+)/i);
if (locMatch) {
line = parseInt(locMatch[1], 10);
column = parseInt(locMatch[2], 10);
}
}
// Strip leading code bracket like "[AVX_W03] " from clean message
let cleanMessage = rawMsg;
if (code) {
cleanMessage = cleanMessage.replace(new RegExp(`^\\[?${code}\\]?\\s*:?\\s*`), '');
}
// The frame is carried as its own field so a consumer can render it as code
// rather than as prose. `error.frame` is authoritative when the diagnostic
// came from a CompilerError; otherwise it is recovered from the text.
const split = splitCodeFrame(cleanMessage);
let frame = split.frame;
if (!frame && firstArg instanceof Error && typeof firstArg.frame === 'string' && firstArg.frame !== '') {
frame = stripAnsi(firstArg.frame);
}
const result = {
file: file || null,
code: code || 'AVX_UNK',
severity: severity === 'error' ? 'error' : 'warning',
message: split.message.trim(),
};
if (line !== null) result.line = line;
if (column !== null) result.column = column;
if (frame) result.frame = frame;
return result;
}
/**
* Helper to get formatted local time string for timestamps (HH:MM:SS format).
* @returns {string}
*/
function getTimestamp() {
return new Date().toLocaleTimeString('en-US', { hour12: false });
}
/**
* Runs a single template check pass and returns structured results.
* @param {object} cli - AvenxCLI instance containing config and baseDir.
* @param {string[]} [args] - Command line arguments.
* @param {object} [options] - Pass options.
* @param {boolean} [options.watch] - True when this pass is one cycle of
* `check --watch`, which is what allows the compilation cache.
* @returns {{ valid: boolean, errorCount: number, warningCount: number, diagnostics: any[] }}
*/
export function runCheckPass(cli, args = [], options = {}) {
const isJson = args.includes('--json') || args.includes('-j');
const diagnostics = [];
const originalWarn = console.warn;
const originalError = console.error;
const originalLog = console.log;
const originalInfo = console.info;
const originalDebug = console.debug;
const originalTrace = console.trace;
let warningCount = 0;
let errorCount = 0;
let blockingWarningCount = 0;
const handleWarning = (...messages) => {
warningCount++;
const diag = parseDiagnostic('warning', messages);
diagnostics.push(diag);
if (!A11Y_WARNING_CODES.has(diag.code)) {
blockingWarningCount++;
}
};
const handleError = (...messages) => {
errorCount++;
diagnostics.push(parseDiagnostic('error', messages));
};
if (isJson) {
console.warn = handleWarning;
console.error = handleError;
console.log = () => {};
console.info = () => {};
console.debug = () => {};
console.trace = () => {};
} else {
console.warn = (...messages) => {
handleWarning(...messages);
originalWarn(...messages);
};
console.error = (...messages) => {
handleError(...messages);
originalError(...messages);
};
}
try {
// analyze() is the same pipeline the build runs, so check sees exactly
// what a build would: bridges included, which the previous
// processComponents/processPages pair skipped entirely. It is tolerant so
// one broken bridge cannot hide every template diagnostic behind it; the
// failure itself is reported below.
const compiler = new AvenxCompiler({
...cli.config,
...(cli.baseDir ? { rootDir: cli.baseDir } : {}),
watch: options.watch === true,
});
const model = compiler.analyze();
for (const failure of model.errors) {
errorCount++;
const message = `[${failure.code}] ${failure.message}`;
if (isJson) {
diagnostics.push(parseDiagnostic('error', [message]));
} else {
originalError(red(`โ ${message}`));
}
}
reportAtlasDiagnostics(model, cli.config);
reportRewindDiagnostics(model, cli.config);
} catch (err) {
errorCount++;
if (isJson) {
diagnostics.push(parseDiagnostic('error', [err]));
} else {
originalError(red(`โ ${err.message || err}`));
}
} finally {
console.warn = originalWarn;
console.error = originalError;
console.log = originalLog;
console.info = originalInfo;
console.debug = originalDebug;
console.trace = originalTrace;
}
const isStrict = args.includes('--strict') || args.includes('--strict-a11y');
const effectiveBlocking = errorCount + (isStrict ? warningCount : blockingWarningCount);
return {
valid: effectiveBlocking === 0,
errorCount,
warningCount,
blockingWarningCount,
diagnostics,
};
}
/**
* Validates template files without building.
* Supports --watch / -w for continuous watching and template linting.
* @param {object} cli - AvenxCLI instance containing config and baseDir.
* @param {string[]} [args] - Additional command line arguments.
* @returns {object|fs.FSWatcher|undefined} Diagnostic report or watcher instance.
*/
export function checkProject(cli, args = []) {
const isJson = args.includes('--json') || args.includes('-j');
const isWatch = args.includes('--watch') || args.includes('-w');
if (isWatch) {
const srcDir = (cli && cli.config && cli.config.srcDir) || 'src';
const srcPath = path.join((cli && cli.baseDir) || process.cwd(), srcDir);
console.log(cyan(`[${getTimestamp()}] ๐ Watching for template changes in ${srcDir}/...`));
const executeCheck = () => {
const timestamp = getTimestamp();
const report = runCheckPass(cli, args, { watch: true });
if (isJson) {
const jsonReport = {
timestamp,
...report,
};
console.log(JSON.stringify(jsonReport, null, 2));
} else {
const isStrict = args.includes('--strict') || args.includes('--strict-a11y');
const blockingIssues = report.errorCount + (isStrict ? report.warningCount : (report.blockingWarningCount || 0));
if (blockingIssues > 0) {
const totalIssues = report.warningCount + report.errorCount;
console.error(red(`[${timestamp}] โ Found ${totalIssues} validation issue(s).`));
} else if (report.warningCount > 0) {
console.log(cyan(`[${timestamp}] โ Template validation passed with ${report.warningCount} accessibility warning(s).`));
} else {
console.log(green(`[${timestamp}] โ No template validation issues found.`));
}
}
return report;
};
// Initial check
const initialReport = executeCheck();
if (!fs.existsSync(srcPath)) {
console.error(red(`โ Source directory does not exist: ${srcPath}`));
return initialReport;
}
let timeout;
const templateDirs = [(cli && cli.config && cli.config.templatesDir) || '.avenxtemplates', 'templates'];
const watcher = watchDirectories(
[srcPath, ...templateDirs.map((dir) => path.join((cli && cli.baseDir) || process.cwd(), dir))],
(_eventType, filename) => {
clearTimeout(timeout);
timeout = setTimeout(() => {
const fileMsg = filename ? ` in ${filename}` : '';
console.log(`\n${cyan(`[${getTimestamp()}] ๐ Change detected${fileMsg}. Re-checking templates...`)}`);
executeCheck();
}, 100);
},
);
const cleanup = () => {
console.log(`\n${gray('Stopping template check watcher...')}`);
clearTimeout(timeout);
if (watcher) watcher.close();
if (!cli || !cli._noExit) {
process.exit(0);
}
};
process.on('SIGINT', cleanup);
if (cli) {
cli._watcher = watcher;
}
return watcher;
}
// Single-pass mode
const report = runCheckPass(cli, args);
if (isJson) {
console.log(JSON.stringify(report, null, 2));
process.exitCode = report.valid ? 0 : 1;
if (!cli || !cli._noExit) {
process.exit(process.exitCode);
}
return report;
}
const isStrict = args.includes('--strict') || args.includes('--strict-a11y');
const blockingIssues = report.errorCount + (isStrict ? report.warningCount : (report.blockingWarningCount || 0));
if (blockingIssues > 0) {
const totalIssues = report.warningCount + report.errorCount;
console.error(`\n${red(`Found ${totalIssues} validation issue(s).`)}`);
process.exitCode = 1;
if (!cli || !cli._noExit) {
process.exit(1);
}
return report;
}
if (report.warningCount > 0) {
console.log(cyan(`\nโ Template validation passed with ${report.warningCount} accessibility warning(s).`));
} else {
console.log(green('โ No template validation issues found.'));
}
process.exitCode = 0;
if (!cli || !cli._noExit) {
process.exit(0);
}
return report;
}
|