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 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 | 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 694x 694x 694x 694x 1632x 1632x 1632x 1632x 399x 399x 399x 364x 364x 399x 1632x 33x 33x 1235x 1235x 1235x 1239x 297x 297x 938x 938x 938x 297x 297x 694x 550x 550x 550x 550x 550x 550x 550x 550x 894x 894x 894x 10368x 10368x 894x 7034x 7034x 894x 9474x 73605x 73605x 73605x 73605x 73605x 73605x 9474x 894x 894x 550x 550x 550x 550x 550x 550x 550x 550x 550x 75x 75x 75x 673x 673x 114x 114x 114x 673x 75x 33x 33x 42x 75x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 8x 8x 8x 8x 1x 8x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 8x 8x 8x 8x 2x 2x 2x 2x 2x 2x 6x 8x 2x 2x 2x 4x 4x 8x 8x 1x 1x 1x 1x 1x 3x 3x 8x 1x 1x 1x 2x 2x 8x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 1839x 751x 751x 1839x 9x 9x 1839x 1026x 1026x 1163x 1163x 1026x 1026x 53x 1839x 550x 550x 550x 550x 550x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 313x 313x 313x 652x 652x 652x 652x 652x 652x 652x 652x 652x 652x 965x 3x 3x 652x 965x 652x 652x 652x 652x 652x 2x 652x 1x 1x 652x 652x 770x 12x 12x 12x 770x 758x 10x 10x 12x 1x 1x 1x 1x 12x 10x 758x 290x 290x 290x 1x 1x 1x 1x 290x 290x 758x 3x 3x 4x 1x 1x 1x 1x 4x 3x 1x 1x 1x 3x 758x 4x 4x 7x 1x 1x 1x 1x 7x 4x 758x 11x 11x 10x 2x 2x 2x 2x 10x 11x 758x 1x 1x 1x 1x 1x 758x 1x 1x 1x 1x 1x 1x 1x 1x 1x 758x 7x 7x 8x 1x 1x 1x 1x 8x 7x 758x 770x 652x 652x 658x 39x 1x 1x 39x 651x 658x 6x 6x 651x 658x 8x 1x 1x 8x 1x 1x 8x 1x 1x 8x 648x 658x 1x 1x 1x 1x 1x 1x 1x 647x 647x 658x 658x 647x 647x 647x 647x 647x 647x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 965x 647x 647x 647x 965x 1x 1x 658x 1x 1x 645x 965x 1x 1x 658x 1x 1x 643x 658x 643x 965x 1x 1x 658x 1x 1x 641x 965x 3x 3x 638x 638x 638x 638x 638x 638x 638x 638x 639x 637x 965x 2x 2x 636x 636x 658x 41x 1x 1x 40x 41x 2x 2x 41x 8x 8x 41x 633x 633x 658x 633x 633x 965x 633x 965x 633x 658x 12x 1x 1x 12x 658x 5x 5x 627x 965x 2x 2x 625x 965x 1x 1x 624x 658x 1x 1x 623x 658x 623x 623x 623x 965x 622x 965x 2x 2x 621x 621x 621x 621x 621x 965x 621x 621x 621x 621x 621x 621x 621x 621x 621x 655x 31x 31x 31x 31x 965x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 550x 1218x 1218x 1218x 1218x 1218x 40x 14x 14x 14x 14x 40x 1204x 1204x 1218x | import fs from 'fs';
import path from 'path';
import { logger } from './core/runtime/AvenxLogger.js';
import { AvenxErrorCodes } from './core/runtime/AvenxError.js';
import { setDebugReactivity } from './core/reactive/watcher.js';
import { setExpressionCacheCapacity } from './core/expression/compile.js';
/**
* Find the project root directory by scanning upwards from startDir.
* Looks for package.json or index.html.
* @param {string} startDir
* @returns {string}
*/
function findProjectRoot(startDir = process.cwd()) {
let currentDir = startDir;
while (true) {
const packageJsonPath = path.join(currentDir, 'package.json');
const indexHtmlPath = path.join(currentDir, 'index.html');
if (fs.existsSync(packageJsonPath)) {
try {
const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
if (pkg && (pkg.name !== 'avenx-core' || process.env.NODE_ENV === 'test')) {
return currentDir;
}
} catch {
return currentDir;
}
} else if (fs.existsSync(indexHtmlPath)) {
return currentDir;
}
const parentDir = path.dirname(currentDir);
if (parentDir === currentDir) {
break;
}
currentDir = parentDir;
}
return startDir;
}
/**
* Computes the Levenshtein distance between two strings.
* @param {string} a
* @param {string} b
* @returns {number}
*/
export function levenshtein(a, b) {
const tmp = [];
let i, j;
for (i = 0; i <= a.length; i++) {
tmp.push([i]);
}
for (j = 0; j <= b.length; j++) {
tmp[0][j] = j;
}
for (i = 1; i <= a.length; i++) {
for (j = 1; j <= b.length; j++) {
tmp[i][j] = Math.min(
tmp[i - 1][j] + 1,
tmp[i][j - 1] + 1,
tmp[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)
);
}
}
return tmp[a.length][b.length];
}
/**
* Returns the closest match from allowedKeys based on Levenshtein distance,
* if it is within a threshold.
* @param {string} key
* @param {string[]} allowedKeys
* @returns {string|null}
*/
export function getClosestKey(key, allowedKeys) {
let closest = null;
let minDistance = Infinity;
for (const allowed of allowedKeys) {
const dist = levenshtein(key.toLowerCase(), allowed.toLowerCase());
if (dist < minDistance) {
minDistance = dist;
closest = allowed;
}
}
if (minDistance <= 3) {
return closest;
}
return null;
}
/**
* Every diagnostic code the framework can emit, and the subset a `warnings`
* entry in avenx.config.json can actually steer.
*
* `AvenxErrorCodes` (lib/core/runtime/AvenxError.js) is the registry of real
* codes — see "Diagnostic Codes" in CONTRIBUTING.md. A severity override is
* only ever consulted for the `AVX_W*` warning codes (see reportWarning and
* the compiler's warning path): the `AVX_C*` / `AVX_R*` diagnostics are
* thrown or reported directly, never warned through the `warnings` map, so an
* override naming one could never take effect.
* @type {Set<string>}
*/
const KNOWN_DIAGNOSTIC_CODES = new Set(Object.values(AvenxErrorCodes));
/** @type {string[]} */
const KNOWN_WARNING_CODES = [...KNOWN_DIAGNOSTIC_CODES].filter((code) => code.startsWith('AVX_W'));
/**
* Normalizes a `warnings` key the way `avenx explain` normalizes the code it
* is given (see normalizeCode in lib/core/diagnostics/catalogue.js):
* upper-cased, with the `AVX_` prefix restored when it is missing or run
* together. "W55", "avx_w55" and "AVXW55" all normalize to "AVX_W55".
* @param {string} code
* @returns {string}
*/
function normalizeWarningCode(code) {
const clean = code.trim().toUpperCase();
if (clean.startsWith('AVX_')) return clean;
if (clean.startsWith('AVX')) return `AVX_${clean.slice(3)}`;
return `AVX_${clean}`;
}
/**
* Reports a `warnings` key that names no warning, the way loadConfig already
* reports an unknown configuration key: a warning, not an error, because a
* stale code left over from an upgrade should not stop a build — but never
* silence, because an entry that does nothing is indistinguishable from a
* fix that is not working. When the key is a recognisable variant of a real
* warning code, the canonical spelling is suggested; the entry itself is not
* applied, so only the canonical spelling takes effect.
* @param {string} code - The `warnings` key as written in avenx.config.json.
*/
function reportUnknownWarningCode(code) {
const normalized = normalizeWarningCode(code);
if (KNOWN_DIAGNOSTIC_CODES.has(normalized) && !KNOWN_WARNING_CODES.includes(normalized)) {
// The code exists, but it is not a warning: its entry can never apply.
logger.warn(
`Warning severity for "${code}" in avenx.config.json has no effect: "${normalized}" is not a warning code. The "warnings" map only overrides warning codes (AVX_W*).`
);
return;
}
if (KNOWN_WARNING_CODES.includes(normalized)) {
logger.warn(`Unknown warning code "${code}" in avenx.config.json. Did you mean "${normalized}"?`);
return;
}
const completions = KNOWN_WARNING_CODES.filter((known) => known.startsWith(normalized)).sort();
if (completions.length === 1) {
logger.warn(`Unknown warning code "${code}" in avenx.config.json. Did you mean "${completions[0]}"?`);
return;
}
if (completions.length > 1) {
logger.warn(
`Unknown warning code "${code}" in avenx.config.json. Did you mean one of: ${completions.map((known) => `"${known}"`).join(', ')}?`
);
return;
}
const near = KNOWN_WARNING_CODES.filter((known) => levenshtein(normalized.toLowerCase(), known.toLowerCase()) === 1);
if (near.length === 1) {
logger.warn(`Unknown warning code "${code}" in avenx.config.json. Did you mean "${near[0]}"?`);
return;
}
logger.warn(`Unknown warning code "${code}" in avenx.config.json. No diagnostic uses this code, so this entry has no effect.`);
}
/**
* The configuration keys avenx.config.json accepts.
*
* Exported so that every consumer validates against one list. `avenx doctor`
* kept a second copy and drifted from this one, reporting valid options as
* unrecognised.
* @type {{topLevel: string[], server: string[], style: string[], debug: string[], logging: string[], hooks: string[], trace: string[], rewind: string[], csp: string[]}}
*/
export const CONFIG_SCHEMA = {
topLevel: [
'srcDir',
'distDir',
'templatesDir',
'mode',
'server',
'style',
'debug',
'outputName',
'logging',
'voidTags',
'templateGlobals',
'warnings',
'treeShakeComponents',
'codeSplitting',
'preprocessors',
'alias',
'hooks',
'trace',
'rewind',
'csp',
'expressionCacheCapacity',
'sourceMap',
'sourcesContent',
'incremental',
],
server: ['port', 'host', 'liveReload', 'errorOverlay', 'headers'],
style: ['preprocessor', 'sourceMap', 'inlineSourceMap', 'dev'],
debug: ['debugReactivity'],
trace: ['redact', 'maxNodes'],
rewind: ['onConflict', 'maxSnapshotItems'],
csp: ['strict'],
logging: ['level', 'silent'],
hooks: ['prebuild', 'postbuild'],
};
/**
* Recursively traverses string values in an object/array/value and replaces
* $VAR_NAME or ${VAR_NAME} placeholders with process.env.VAR_NAME values.
* @param {*} val
* @returns {*}
*/
export function interpolateEnv(val) {
if (typeof val === 'string') {
return val.replace(/\$\{?([A-Z0-9_]+)\}?/gi, (_, key) => (process.env[key] !== undefined ? process.env[key] : ''));
}
if (Array.isArray(val)) {
return val.map(interpolateEnv);
}
if (val && typeof val === 'object') {
const result = {};
for (const [k, v] of Object.entries(val)) {
result[k] = interpolateEnv(v);
}
return result;
}
return val;
}
/**
* Load the Avenx configuration from avenx.config.json file.
* @param {string} [baseDir] - The base directory of the project.
*/
function loadConfig(baseDir) {
const defaults = {
srcDir: 'src',
distDir: 'dist',
templatesDir: '.avenxtemplates',
alias: {},
hooks: {},
expressionCacheCapacity: 1000,
// Off by default. Reusing a previous compilation is only safe while the key
// covers everything a unit was derived from, and the test that demonstrates
// that -- an edit sequence whose incremental output is byte-identical to a
// cold build -- is younger than the code it checks. A project opts in; a
// project that does not is unaffected.
incremental: false,
server: {
port: 3000,
host: 'localhost',
liveReload: true,
// The build-diagnostic overlay belongs to the development server and
// nothing else: `avenx serve` injects it, `avenx build` never emits a
// trace of it. On by default, because a compile error the developer
// cannot see is the problem it exists to solve.
errorOverlay: true,
headers: {},
},
style: {
preprocessor: 'none',
},
debug: {
debugReactivity: false,
},
voidTags: [],
templateGlobals: [],
warnings: {},
preprocessors: {},
trace: {
redact: [],
maxNodes: 0,
},
rewind: {
onConflict: 'safe',
maxSnapshotItems: 10000,
},
// Off by default, and that is the whole backward-compatibility story: a
// project that says nothing about CSP gets byte-identical output to the
// build before this option existed. Turning it on is a statement about the
// deployment -- "this application is served under a policy without
// 'unsafe-eval'" -- and the build then holds itself to it in both modes
// rather than only in production.
csp: {
strict: false,
},
};
const rootDir = baseDir || findProjectRoot(process.cwd());
const configPath = path.join(rootDir, 'avenx.config.json');
if (!fs.existsSync(configPath)) {
setDebugReactivity(defaults.debug.debugReactivity);
return defaults;
}
try {
const userConfigRaw = JSON.parse(fs.readFileSync(configPath, 'utf8'));
const userConfig = interpolateEnv(userConfigRaw);
// templateGlobals holds identifier names, not values, and JavaScript
// identifiers may start with `$` — which env interpolation would read as a
// placeholder and blank out, making a name like `$i18n` impossible to
// declare. Nothing in this option could ever want to be an environment
// reference, so it is taken verbatim from the file.
if (userConfigRaw && Array.isArray(userConfigRaw.templateGlobals)) {
userConfig.templateGlobals = userConfigRaw.templateGlobals;
}
if (userConfig && typeof userConfig === 'object' && !Array.isArray(userConfig)) {
if (
userConfig.server &&
typeof userConfig.server.port === 'string' &&
/^\d+$/.test(userConfig.server.port) &&
typeof userConfigRaw.server?.port === 'string' &&
userConfigRaw.server.port.includes('$')
) {
userConfig.server.port = Number(userConfig.server.port);
}
const allowedTopLevel = CONFIG_SCHEMA.topLevel;
for (const key of Object.keys(userConfig)) {
if (!allowedTopLevel.includes(key)) {
const closest = getClosestKey(key, allowedTopLevel);
const suggestion = closest ? `. Did you mean "${closest}"?` : '.';
logger.warn(`Unknown configuration option "${key}" in avenx.config.json${suggestion} Supported top-level options are: ${allowedTopLevel.join(', ')}.`);
} else {
if (key === 'server' && userConfig.server && typeof userConfig.server === 'object' && !Array.isArray(userConfig.server)) {
const allowedServerKeys = CONFIG_SCHEMA.server;
for (const subKey of Object.keys(userConfig.server)) {
if (!allowedServerKeys.includes(subKey)) {
const closest = getClosestKey(subKey, allowedServerKeys);
const suggestion = closest ? `. Did you mean "server.${closest}"?` : '.';
logger.warn(`Unknown configuration option "server.${subKey}" in avenx.config.json${suggestion} Supported options for "server" are: ${allowedServerKeys.join(', ')}.`);
}
}
}
if (key === 'style' && userConfig.style && typeof userConfig.style === 'object' && !Array.isArray(userConfig.style)) {
const allowedStyleKeys = CONFIG_SCHEMA.style;
for (const subKey of Object.keys(userConfig.style)) {
if (!allowedStyleKeys.includes(subKey)) {
const closest = getClosestKey(subKey, allowedStyleKeys);
const suggestion = closest ? `. Did you mean "style.${closest}"?` : '.';
logger.warn(`Unknown configuration option "style.${subKey}" in avenx.config.json${suggestion} Supported options for "style" are: ${allowedStyleKeys.join(', ')}.`);
}
}
}
if (key === 'trace' && userConfig.trace && typeof userConfig.trace === 'object' && !Array.isArray(userConfig.trace)) {
const allowedTraceKeys = CONFIG_SCHEMA.trace;
for (const subKey of Object.keys(userConfig.trace)) {
if (!allowedTraceKeys.includes(subKey)) {
const closest = getClosestKey(subKey, allowedTraceKeys);
const suggestion = closest ? `. Did you mean "trace.${closest}"?` : '.';
logger.warn(`Unknown configuration option "trace.${subKey}" in avenx.config.json${suggestion} Supported options for "trace" are: ${allowedTraceKeys.join(', ')}.`);
}
}
if (userConfig.trace.redact !== undefined && !Array.isArray(userConfig.trace.redact)) {
logger.warn('Configuration option "trace.redact" must be an array of property-path patterns. Ignoring it.');
delete userConfig.trace.redact;
}
}
if (key === 'rewind' && userConfig.rewind && typeof userConfig.rewind === 'object' && !Array.isArray(userConfig.rewind)) {
const allowedRewindKeys = CONFIG_SCHEMA.rewind;
for (const subKey of Object.keys(userConfig.rewind)) {
if (!allowedRewindKeys.includes(subKey)) {
const closest = getClosestKey(subKey, allowedRewindKeys);
const suggestion = closest ? `. Did you mean "rewind.${closest}"?` : '.';
logger.warn(`Unknown configuration option "rewind.${subKey}" in avenx.config.json${suggestion} Supported options for "rewind" are: ${allowedRewindKeys.join(', ')}.`);
}
}
}
if (key === 'csp' && userConfig.csp && typeof userConfig.csp === 'object' && !Array.isArray(userConfig.csp)) {
const allowedCspKeys = CONFIG_SCHEMA.csp;
for (const subKey of Object.keys(userConfig.csp)) {
if (!allowedCspKeys.includes(subKey)) {
const closest = getClosestKey(subKey, allowedCspKeys);
const suggestion = closest ? `. Did you mean "csp.${closest}"?` : '.';
logger.warn(`Unknown configuration option "csp.${subKey}" in avenx.config.json${suggestion} Supported options for "csp" are: ${allowedCspKeys.join(', ')}.`);
}
}
}
if (key === 'debug' && userConfig.debug && typeof userConfig.debug === 'object' && !Array.isArray(userConfig.debug)) {
const allowedDebugKeys = CONFIG_SCHEMA.debug;
for (const subKey of Object.keys(userConfig.debug)) {
if (!allowedDebugKeys.includes(subKey)) {
const closest = getClosestKey(subKey, allowedDebugKeys);
const suggestion = closest ? `. Did you mean "debug.${closest}"?` : '.';
logger.warn(`Unknown configuration option "debug.${subKey}" in avenx.config.json${suggestion} Supported options for "debug" are: ${allowedDebugKeys.join(', ')}.`);
}
}
}
if (key === 'logging' && userConfig.logging && typeof userConfig.logging === 'object' && !Array.isArray(userConfig.logging)) {
const allowedLoggingKeys = CONFIG_SCHEMA.logging;
for (const subKey of Object.keys(userConfig.logging)) {
if (!allowedLoggingKeys.includes(subKey)) {
const closest = getClosestKey(subKey, allowedLoggingKeys);
const suggestion = closest ? `. Did you mean "logging.${closest}"?` : '.';
logger.warn(`Unknown configuration option "logging.${subKey}" in avenx.config.json${suggestion} Supported options for "logging" are: ${allowedLoggingKeys.join(', ')}.`);
}
}
}
if (key === 'hooks' && userConfig.hooks && typeof userConfig.hooks === 'object' && !Array.isArray(userConfig.hooks)) {
const allowedHooksKeys = CONFIG_SCHEMA.hooks;
for (const subKey of Object.keys(userConfig.hooks)) {
if (!allowedHooksKeys.includes(subKey)) {
const closest = getClosestKey(subKey, allowedHooksKeys);
const suggestion = closest ? `. Did you mean "hooks.${closest}"?` : '.';
logger.warn(`Unknown configuration option "hooks.${subKey}" in avenx.config.json${suggestion} Supported options for "hooks" are: ${allowedHooksKeys.join(', ')}.`);
}
}
}
}
}
}
if (userConfig.warnings !== undefined) {
if (typeof userConfig.warnings !== 'object' || userConfig.warnings === null || Array.isArray(userConfig.warnings)) {
throw new Error('warnings must be an object');
}
}
if (userConfig.alias !== undefined) {
if (typeof userConfig.alias !== 'object' || userConfig.alias === null || Array.isArray(userConfig.alias)) {
throw new Error('alias must be an object');
}
}
if (userConfig.hooks !== undefined) {
if (typeof userConfig.hooks !== 'object' || userConfig.hooks === null || Array.isArray(userConfig.hooks)) {
throw new Error('hooks must be an object');
}
if (userConfig.hooks.prebuild !== undefined && typeof userConfig.hooks.prebuild !== 'string') {
throw new Error('hooks.prebuild must be a string');
}
if (userConfig.hooks.postbuild !== undefined && typeof userConfig.hooks.postbuild !== 'string') {
throw new Error('hooks.postbuild must be a string');
}
}
if (userConfig.preprocessors !== undefined) {
if (
(typeof userConfig.preprocessors !== 'object' || userConfig.preprocessors === null || Array.isArray(userConfig.preprocessors)) &&
typeof userConfig.preprocessors !== 'function'
) {
throw new Error('preprocessors must be an object or function');
}
}
let preprocessors = defaults.preprocessors;
if (typeof userConfig.preprocessors === 'function') {
preprocessors = userConfig.preprocessors;
} else if (userConfig.preprocessors) {
preprocessors = { ...defaults.preprocessors, ...userConfig.preprocessors };
}
const config = {
...defaults,
...userConfig,
server: {
...defaults.server,
...(userConfig.server || {}),
},
style: {
...defaults.style,
...(userConfig.style || {}),
},
debug: {
...defaults.debug,
...(userConfig.debug || {}),
},
warnings: {
...defaults.warnings,
...(userConfig.warnings || {}),
},
hooks: {
...defaults.hooks,
...(userConfig.hooks || {}),
},
rewind: {
...defaults.rewind,
...(userConfig.rewind || {}),
},
csp: {
...defaults.csp,
...(userConfig.csp || {}),
},
preprocessors,
};
if (typeof config.debug.debugReactivity !== 'boolean') {
throw new Error('debug.debugReactivity must be a boolean');
}
setDebugReactivity(config.debug.debugReactivity);
if (typeof config.srcDir !== 'string' || config.srcDir.trim() === '') {
throw new Error('srcDir must be a non-empty string');
}
if (path.isAbsolute(config.srcDir)) {
throw new Error('srcDir must be a relative path');
}
if (typeof config.distDir !== 'string' || config.distDir.trim() === '') {
throw new Error('distDir must be a non-empty string');
}
if (path.isAbsolute(config.distDir)) {
throw new Error('distDir must be a relative path');
}
if (typeof config.incremental !== 'boolean') {
throw new Error('incremental must be a boolean');
}
if (typeof config.templatesDir !== 'string' || config.templatesDir.trim() === '') {
throw new Error('templatesDir must be a non-empty string');
}
if (path.isAbsolute(config.templatesDir)) {
throw new Error('templatesDir must be a relative path');
}
if (!Array.isArray(config.voidTags) || config.voidTags.some((tag) => typeof tag !== 'string' || tag.trim() === '')) {
throw new Error('voidTags must be an array of non-empty strings');
}
// Identifiers a plugin publishes into every component's template scope —
// `app.mixin()` members, most often. Template validation has no way to see
// those: they are contributed at runtime, by code the compiler never reads.
// Declaring them here is how a project says "this name is provided", so a
// template using it is checked rather than either warned about wrongly or
// exempted by switching the whole check off.
if (
!Array.isArray(config.templateGlobals) ||
config.templateGlobals.some((name) => typeof name !== 'string' || name.trim() === '')
) {
throw new Error('templateGlobals must be an array of non-empty identifier names');
}
const allowedSeverities = ['off', 'ignore', 'warn', 'warning', 'error'];
for (const [code, severity] of Object.entries(config.warnings)) {
if (typeof severity !== 'string') {
throw new Error(`warnings.${code} must be a string severity ("off", "ignore", "warn", "warning", "error")`);
}
const normSeverity = severity.trim().toLowerCase();
if (!allowedSeverities.includes(normSeverity)) {
throw new Error(`Invalid severity "${severity}" for warning "${code}". Allowed values: "off", "ignore", "warn", "warning", "error"`);
}
if (!KNOWN_WARNING_CODES.includes(code)) {
reportUnknownWarningCode(code);
}
}
const allowedConflictPolicies = ['safe', 'force', 'abort'];
if (!allowedConflictPolicies.includes(config.rewind.onConflict)) {
throw new Error(
`Invalid rewind.onConflict "${config.rewind.onConflict}". Allowed values: ${allowedConflictPolicies.map((p) => `"${p}"`).join(', ')}`,
);
}
if (
typeof config.rewind.maxSnapshotItems !== 'number' ||
!Number.isInteger(config.rewind.maxSnapshotItems) ||
config.rewind.maxSnapshotItems <= 0
) {
throw new Error('rewind.maxSnapshotItems must be a positive integer');
}
if (userConfig.csp !== undefined) {
if (typeof userConfig.csp !== 'object' || userConfig.csp === null || Array.isArray(userConfig.csp)) {
throw new Error('csp must be an object');
}
}
if (typeof config.csp.strict !== 'boolean') {
throw new Error('csp.strict must be a boolean');
}
if (typeof config.server.port !== 'number' || config.server.port < 0 || config.server.port > 65535) {
throw new Error('server.port must be a valid port number (0-65535)');
}
if (typeof config.server.host !== 'string' || config.server.host.trim() === '') {
throw new Error('server.host must be a non-empty string');
}
if (typeof config.server.liveReload !== 'boolean') {
throw new Error('server.liveReload must be a boolean');
}
if (typeof config.server.errorOverlay !== 'boolean') {
throw new Error('server.errorOverlay must be a boolean');
}
if (
typeof config.server.headers !== 'object' ||
config.server.headers === null ||
Array.isArray(config.server.headers)
) {
throw new Error('server.headers must be an object');
}
if (
config.expressionCacheCapacity !== undefined &&
(typeof config.expressionCacheCapacity !== 'number' ||
config.expressionCacheCapacity <= 0 ||
!Number.isInteger(config.expressionCacheCapacity))
) {
throw new Error('expressionCacheCapacity must be a positive integer');
}
// The compiled-expression cache is a build-time cache: it holds the parsed
// form of every expression the build compiled, so its capacity is set from
// the config the build runs with.
if (config.expressionCacheCapacity !== undefined) {
setExpressionCacheCapacity(config.expressionCacheCapacity);
}
return config;
} catch (err) {
logger.error(`Invalid avenx.config.json: ${err.message}`);
if (process.env.NODE_ENV === 'test') {
throw err;
}
process.exit(1);
}
}
loadConfig.findProjectRoot = findProjectRoot;
loadConfig.interpolateEnv = interpolateEnv;
export default loadConfig;
/**
* Resolves a path alias (e.g., "@/components/Header") to its absolute or root-relative path.
* @param {string} importPath - The import string to resolve.
* @param {object} [config] - The parsed Avenx config object.
* @param {string} [rootDir] - The root project directory.
* @returns {string} The resolved file path or original string if no alias matched.
*/
export function resolvePathAlias(importPath, config = {}, rootDir = process.cwd()) {
if (!importPath || typeof importPath !== 'string') return importPath;
const safeConfig = config || {};
const aliases = safeConfig.alias || {};
for (const [alias, target] of Object.entries(aliases)) {
if (importPath === alias || importPath.startsWith(alias + '/')) {
const relativePart = importPath.slice(alias.length);
const targetPath = path.isAbsolute(target) ? target : path.join(rootDir, target);
return path.normalize(path.join(targetPath, relativePart));
}
}
return importPath;
} |