All files / lib/compiler/atlas routes.js

96.9% Statements 344/355
87.36% Branches 83/95
100% Functions 7/7
96.9% Lines 344/355

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 356458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 80x 80x 80x 80x 80x 80x 458x 458x 458x 458x 458x 458x 458x 344x 344x 344x 12015x 12015x 1436x 1436x 1436x 6869x 6869x 6869x 1436x 1436x 12015x 9909x 670x 670x 670x 12015x   344x 458x 458x 458x 458x 458x 458x 344x 344x 344x 344x 344x 11327x 11327x 1436x 1436x 1436x 6869x 6869x 6869x 1436x 1436x 11327x 9565x 9239x 541x 541x 541x 11327x 344x 154x 154x 344x 344x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 347x 347x 347x 180x 347x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 538x 538x 538x 538x 538x 344x 344x 344x 344x 344x 344x 344x 695x 695x 695x 695x 695x 695x 695x 695x 506x 506x 506x 183x 183x 183x 183x 183x 183x 137x 137x 137x 183x 183x 183x 183x 183x 183x 183x 183x 183x 183x 183x       344x 538x 538x 538x 458x 458x 458x 458x 458x 458x 458x 305x 305x 610x 610x 326x 89x 80x 80x 80x 80x 80x 294x 305x 305x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 305x 305x 305x 305x 305x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 305x 305x 305x 253x 253x 253x 253x 253x 253x 253x 253x 253x 253x 253x 253x 253x 253x 253x 253x 270x 140x 140x 140x 139x 140x 1x 1x 1x 1x 140x 253x 253x 253x 253x 253x 253x 253x 253x 253x 253x 253x 270x 342x 342x 342x 342x 342x 342x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 342x 342x 342x 342x 342x 342x 342x 342x 342x 342x 342x 342x 342x 342x 342x 342x 330x 330x 330x 330x 330x 330x 330x 342x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 342x               342x 342x 75x 75x 2x 2x 2x 2x 2x 2x 2x 2x 2x 73x 73x 73x 73x 73x 73x 73x 73x 342x 305x 458x 458x  
/**
 * @file routes.js
 * @description Route and guard discovery, as part of the compiler's model.
 *
 * Routing is declared, not inferred: `initRouter` takes an object literal
 * mapping patterns to pages, and guards are classes in known directories. Both
 * are therefore compiler knowledge — but until now the only code that read
 * them was `bin/commands/inspect.js`, with a regex, at CLI time.
 *
 * Moving the reading here gives Atlas, `inspect` and `stats` one source of
 * truth instead of three scanners that agree by coincidence.
 * @module lib/compiler/atlas/routes
 */
 
import fs from 'fs';
import path from 'path';
import { AtlasEdgeKind, AtlasNodeKind, Confidence, UnresolvedReason, nodeId } from './AppModel.js';
import { lineIndex, positionAt } from './source.js';
import { relativePath } from './build.js';
import { AvenxErrorCodes } from '../../core/runtime/AvenxError.js';
import { BuildError } from '../errors/index.js';
import { reportWarning } from '../utils/warningReporter.js';
 
/**
 * Converts a file base name to the class name the compiler generates.
 * @param {string} base - A file base name, e.g. `user-profile`.
 * @returns {string} The PascalCase class name.
 */
export function toClassName(base) {
  return base
    .split(/[-_]/)
    .filter(Boolean)
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join('');
}
 
/**
 * Finds the offset of the bracket closing the one at `open`.
 * @param {string} source - The source text.
 * @param {number} open - Offset of the opening bracket.
 * @returns {number} Offset of the match, or -1.
 */
function matchBrace(source, open) {
  let depth = 0;
  for (let i = open; i < source.length; i++) {
    const ch = source[i];
    if (ch === '"' || ch === "'" || ch === '`') {
      const quote = ch;
      i++;
      while (i < source.length && source[i] !== quote) {
        if (source[i] === '\\') i++;
        i++;
      }
      continue;
    }
    if (ch === '{' || ch === '[' || ch === '(') depth++;
    else if (ch === '}' || ch === ']' || ch === ')') {
      depth--;
      if (depth === 0) return i;
    }
  }
  return -1;
}
 
/**
 * Splits an object literal's body into its top-level entries.
 * @param {string} body - The text between the outer braces.
 * @returns {Array<{text: string, offset: number}>} The entries.
 */
function splitEntries(body) {
  const entries = [];
  let depth = 0;
  let start = 0;
  for (let i = 0; i < body.length; i++) {
    const ch = body[i];
    if (ch === '"' || ch === "'" || ch === '`') {
      const quote = ch;
      i++;
      while (i < body.length && body[i] !== quote) {
        if (body[i] === '\\') i++;
        i++;
      }
      continue;
    }
    if (ch === '{' || ch === '[' || ch === '(') depth++;
    else if (ch === '}' || ch === ']' || ch === ')') depth--;
    else if (ch === ',' && depth === 0) {
      entries.push({ text: body.slice(start, i), offset: start });
      start = i + 1;
    }
  }
  if (body.slice(start).trim()) {
    entries.push({ text: body.slice(start), offset: start });
  }
  return entries;
}
 
/**
 * Normalizes a route pattern to the form the router matches.
 *
 * `''`, `'#'` and `'#/'` all mean the root; a leading `#` is display syntax
 * rather than part of the path.
 * @param {string} pattern - The declared pattern.
 * @returns {string} The normalized path.
 */
export function normalizeRoute(pattern) {
  let route = String(pattern).trim();
  if (route.startsWith('#')) route = route.slice(1);
  if (route === '' || route === '/') return '/';
  return route;
}
 
/**
 * Reads every `initRouter({...})` declaration in a source file.
 *
 * Handles both accepted forms of a route target: a bare page name, and an
 * object carrying `page` and `guards`.
 * @param {string} source - The file contents.
 * @returns {Array<object>} Route declarations with their offsets.
 */
export function parseRouteTable(source) {
  const routes = [];
  const callRegex = /initRouter\s*\(\s*\{/g;
  let call;
 
  while ((call = callRegex.exec(source)) !== null) {
    const open = source.indexOf('{', call.index);
    const close = matchBrace(source, open);
    if (close === -1) continue;
    const bodyOffset = open + 1;
    const body = source.slice(bodyOffset, close);
 
    for (const entry of splitEntries(body)) {
      const keyMatch = entry.text.match(/^\s*(?:(['"])([^'"]*)\1|([A-Za-z0-9_$]+))\s*:/);
      if (!keyMatch) continue;
      const pattern = keyMatch[2] !== undefined ? keyMatch[2] : keyMatch[3];
      const valueText = entry.text.slice(keyMatch[0].length).trim();
      const offset = bodyOffset + entry.offset + entry.text.indexOf(keyMatch[0].trimStart());
 
      const literal = valueText.match(/^(['"])([A-Za-z0-9_$]+)\1/);
      if (literal) {
        routes.push({ pattern, page: literal[2], guards: [], offset, dynamic: false });
        continue;
      }
 
      if (valueText.startsWith('{')) {
        const pageMatch = valueText.match(/\bpage\s*:\s*(['"])([A-Za-z0-9_$]+)\1/);
        const guardsMatch = valueText.match(/\bguards\s*:\s*\[([^\]]*)\]/);
        const guards = guardsMatch
          ? guardsMatch[1]
            .split(',')
            .map((item) => item.trim().replace(/^['"]|['"]$/g, ''))
            .filter((item) => /^[A-Za-z_$][\w$]*$/.test(item))
          : [];
        routes.push({
          pattern,
          page: pageMatch ? pageMatch[2] : null,
          guards,
          offset,
          dynamic: !pageMatch,
          expr: valueText.slice(0, 80),
        });
        continue;
      }

      routes.push({ pattern, page: null, guards: [], offset, dynamic: true, expr: valueText.slice(0, 80) });
    }
  }
 
  return routes;
}
 
/**
 * Collects the guard classes a project declares.
 * @param {string} srcDir - The project source directory.
 * @returns {Array<{name: string, filePath: string}>} Declared guards.
 */
export function findGuards(srcDir) {
  const guards = [];
  for (const dirName of ['guards', 'global']) {
    const dir = path.join(srcDir, dirName);
    if (!fs.existsSync(dir)) continue;
    for (const entry of fs.readdirSync(dir)) {
      if (!entry.endsWith('.guard.js')) continue;
      guards.push({
        name: `${toClassName(path.basename(entry, '.guard.js'))}Guard`,
        filePath: path.join(dir, entry),
      });
    }
  }
  return guards;
}
 
/**
 * Adds routes, guards and the relationships between them to the model.
 *
 * Route nodes are keyed by their normalized pattern rather than by the page
 * they resolve to: two patterns can reach the same page, and `avenx impact`
 * should list both.
 * @param {object} model - The AppModel being built.
 * @param {object} context - `{srcDir, rootDir}`.
 * @returns {void}
 */
export function addRoutesAndGuards(model, context) {
  const { srcDir, rootDir, config } = context;
 
  /** @type {Map<string, string>} */
  const guardNodes = new Map();
  for (const guard of findGuards(srcDir)) {
    const id = nodeId(AtlasNodeKind.GUARD, null, guard.name);
    model.addNode({
      id,
      kind: AtlasNodeKind.GUARD,
      name: guard.name,
      file: relativePath(guard.filePath, rootDir),
      loc: { file: relativePath(guard.filePath, rootDir) },
    });
    guardNodes.set(guard.name, id);
  }
 
  const mainFile = path.join(srcDir, 'main.app.js');
  if (!fs.existsSync(mainFile)) return;
 
  const source = fs.readFileSync(mainFile, 'utf-8');
  const file = relativePath(mainFile, rootDir);
  const starts = lineIndex(source);
 
  // An application may mount a page directly instead of declaring a route
  // table. Recorded rather than inferred later, because this is the one place
  // that reads the entry point.
  //
  // Component registrations are read here too. Pages are registered by the
  // compiler, components are not: an application must call `app.register()` for
  // each one, and a component a template uses but nothing registers renders
  // nothing at all. Knowing which names the entry point registers is what lets
  // that be reported instead of discovered in a browser.
  const registered = new Set();
  let dynamicRegistration = false;
  for (const match of source.matchAll(/\.register\s*\(\s*([^,)]*)/g)) {
    const argument = match[1].trim();
    const literal = argument.match(/^(['"`])([A-Za-z_$][\w$]*)\1$/);
    if (literal) {
      registered.add(literal[2]);
    } else {
      // A name computed at run time could be any component, so no absence
      // claim about registration is safe anywhere in this application.
      dynamicRegistration = true;
    }
  }
 
  model.entry = {
    file,
    mountsDirectly: /\bmountPage\s*\(/.test(source),
    registeredComponents: registered,
    dynamicRegistration,
  };
 
  /** @type {Map<string, {page: string|null, expr: string|null}>} */
  const seenRoutes = new Map();
 
  for (const route of parseRouteTable(source)) {
    const normalized = normalizeRoute(route.pattern);
    const routeId = nodeId(AtlasNodeKind.ROUTE, null, normalized);
    const loc = { file, line: positionAt(starts, route.offset).line };
 
    // Duplicate check: applies "last-wins" semantics and issues AVX_W59.
    if (seenRoutes.has(normalized)) {
      const previous = seenRoutes.get(normalized);
      const newTarget = route.page || route.expr || 'unknown';
      const previousTarget = previous.page || previous.expr || 'unknown';
 
      // 1. Reports AVX_W59 through the same path as every other compiler warning,
      // so the `warnings` setting can silence or escalate it.
      reportWarning(
        AvenxErrorCodes.COMPILER_DUPLICATE_ROUTE_PATTERN,
        new BuildError(
          AvenxErrorCodes.COMPILER_DUPLICATE_ROUTE_PATTERN,
          normalized,
          newTarget,
          previousTarget
        ),
        config,
        loc
      );
 
      // 2. Last-wins: drop the earlier target's ROUTES_TO edge, as AvenxRouter does.
      model.removeEdges(routeId, AtlasEdgeKind.ROUTES_TO);
    }
 
    // Updates the record to the current standard.
    seenRoutes.set(normalized, { page: route.page, expr: route.expr });
 
    model.addNode({
      id: routeId,
      kind: AtlasNodeKind.ROUTE,
      name: normalized,
      pattern: route.pattern,
      file,
      loc,
    });
 
    if (route.page) {
      const pageId = nodeId(AtlasNodeKind.PAGE, null, route.page);
      if (model.hasNode(pageId)) {
        model.addEdge({
          from: routeId,
          to: pageId,
          kind: AtlasEdgeKind.ROUTES_TO,
          confidence: Confidence.CERTAIN,
          loc,
        });
      } else {
        // A named page the compiler never compiled is a real finding, not a
        // silent gap: it is the shape of a typo or a deleted file.
        model.addUnresolved({
          reason: UnresolvedReason.DYNAMIC_ROUTE,
          expr: `${route.pattern} -> ${route.page}`,
          name: route.page,
          owner: routeId,
          loc,
        });
      }
    } else if (route.dynamic) {
      model.addUnresolved({
        reason: UnresolvedReason.DYNAMIC_ROUTE,
        expr: route.expr || route.pattern,
        owner: routeId,
        loc,
      });
    }
 
    for (const guardName of route.guards) {
      const guardId = guardNodes.get(guardName);
      if (!guardId) {
        model.addUnresolved({
          reason: UnresolvedReason.UNKNOWN_IDENTIFIER,
          expr: guardName,
          name: guardName,
          owner: routeId,
          loc,
        });
        continue;
      }
      model.addEdge({
        from: routeId,
        to: guardId,
        kind: AtlasEdgeKind.GUARDED_BY,
        confidence: Confidence.CERTAIN,
        loc,
      });
    }
  }
}
 
export default { addRoutesAndGuards, parseRouteTable, findGuards, normalizeRoute, toClassName };