All files / lib config.js

95.14% Statements 490/515
90.69% Branches 195/215
100% Functions 6/6
95.14% Lines 490/515

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 515325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 466x 466x 466x 466x 1181x 1181x 1181x 1181x 239x 239x 239x 212x 212x 239x     1181x 31x 31x 938x 938x 938x 940x 223x 223x 715x 715x 715x 223x 223x 466x 325x 325x 325x 325x 325x 325x 325x 325x 423x 423x 423x 6305x 6305x 423x 3525x 3525x 423x 5882x 47237x 47237x 47237x 47237x 47237x 47237x 5882x 423x 423x 325x 325x 325x 325x 325x 325x 325x 325x 325x 28x 28x 28x 423x 423x 60x 60x 60x 423x 28x 13x 13x 15x 28x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 1091x 477x 477x 1091x 9x 9x 1091x 574x 574x 687x 687x 574x 574x 31x 1091x 325x 325x 325x 325x 325x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 134x 134x 134x 380x 380x 380x 380x 380x 380x 380x 380x 380x 380x 514x 3x 3x 380x 514x 380x 380x 380x 380x 380x 2x 380x 1x 1x 380x 380x 481x 12x 12x 12x 481x 469x 10x 10x 12x 1x 1x 1x 1x 12x 10x 469x 152x 152x 152x 1x 1x 1x 1x 152x 152x 469x 3x 3x 4x 1x 1x 1x 1x 4x 3x 1x 1x 1x 3x 469x 4x 4x 7x 1x 1x 1x 1x 7x 4x 469x 1x 1x 1x         1x 1x 469x 1x 1x 1x 1x 1x 1x 1x 1x 1x 469x 7x 7x 8x 1x 1x 1x 1x 8x 7x 469x 481x 380x 380x 383x 14x 1x 1x 14x 379x 383x         379x 383x 8x 1x 1x 8x 1x 1x 8x 1x 1x 8x 376x 383x 1x 1x 1x 1x 1x 1x 1x 375x 375x 383x   383x     375x 375x 375x 375x 375x 375x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x 514x     375x 375x 375x 514x 1x 1x 383x 1x 1x 373x 514x 1x 1x 383x 1x 1x 371x 514x 1x 1x 383x 1x 1x 369x 514x 3x 3x 366x 366x 366x 366x 366x 366x 366x 366x 367x 365x 514x 2x 2x 364x 364x 383x 14x 1x 1x 13x 14x 1x 1x 14x 362x 362x 383x         362x 362x 514x 362x 514x     362x 514x 2x 2x 360x 514x 1x 1x 359x 383x 1x 1x 358x 358x 358x 514x 357x 514x 2x 2x 356x 356x 356x 356x 356x 514x     356x 356x 380x 24x 24x 24x 24x     514x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 325x 489x 489x 489x 489x 489x 5x 2x 2x 2x 2x 5x 487x 487x 489x
import fs from 'fs';
import path from 'path';
import { logger } from './core/runtime/AvenxLogger.js';
import { setDebugReactivity } from './core/reactive/watcher.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;
}
 
/**
 * 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[]}}
 */
export const CONFIG_SCHEMA = {
  topLevel: [
    'srcDir',
    'distDir',
    'templatesDir',
    'mode',
    'server',
    'style',
    'debug',
    'outputName',
    'logging',
    'voidTags',
    'templateGlobals',
    'warnings',
    'treeShakeComponents',
    'preprocessors',
    'alias',
    'hooks',
    'trace',
    'rewind',
    'expressionCacheCapacity',
    'sourceMap',
    'sourcesContent',
  ],
  server: ['port', 'host', 'liveReload', 'headers'],
  style: ['preprocessor', 'sourceMap', 'inlineSourceMap', 'dev'],
  debug: ['debugReactivity'],
  trace: ['redact', 'maxNodes'],
  rewind: ['onConflict', 'maxSnapshotItems'],
  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,
    server: {
      port: 3000,
      host: 'localhost',
      liveReload: true,
      headers: {},
    },
    style: {
      preprocessor: 'none',
    },
    debug: {
      debugReactivity: false,
    },
    voidTags: [],
    templateGlobals: [],
    warnings: {},
    preprocessors: {},
    trace: {
      redact: [],
      maxNodes: 0,
    },
    rewind: {
      onConflict: 'safe',
      maxSnapshotItems: 10000,
    },
  };
 
  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 === '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 || {}),
      },
      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.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"`);
      }
    }
 
    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 (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.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');
    }
 
    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;
}