All files / lib/core/runtime RouteMatcher.js

98.44% Statements 253/257
91.78% Branches 67/73
100% Functions 6/6
98.44% Lines 253/257

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 25864x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 619x 619x 619x 619x 619x 64x 64x 64x 64x 64x 64x 64x 619x 619x 619x 619x 54x 41x 41x 41x 13x 13x 619x 619x 619x 619x 64x 64x 64x 64x 64x 64x 64x 64x 305x 305x 305x 2x 2x 305x 305x 305x 305x 305x 305x 6x 6x 305x 305x 14x 14x 5x 5x 9x 9x 9x 9x 9x 9x 9x 14x 3x 3x 6x 14x 2x 2x 14x 297x 305x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 299x 625x 619x 619x 625x 8x   8x   8x 8x 8x 8x 619x 619x 619x 619x 619x 619x 619x 625x 267x 267x 267x 267x 267x 267x 267x 267x 352x 625x 6x 6x 4x 8x 8x 4x 4x 6x 6x 6x 6x 6x 6x 6x 6x 625x 27x 299x 64x 64x 64x 64x 64x 64x 64x 64x 64x 7x 7x 1x 1x 6x 6x 6x 6x 6x 6x     6x 6x 7x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 293x 293x 6x 6x 287x 287x 287x 287x 287x 287x 287x 287x 287x 287x 293x 2x 2x 287x 293x 19x 19x 32x 4x 32x 1x 28x 9x 23x 18x 18x 32x 19x 287x 287x 293x 264x 264x 5x 5x 264x 264x 34x 34x 34x 34x 1x 1x 264x 264x 264x 264x 264x 264x 264x 264x 287x 287x 293x 4x 4x 4x 4x 4x 4x 3x 3x 4x 287x 287x 293x 64x  
/**
 * Pure environment-agnostic module for compiling route patterns and matching URLs.
 */
export class RouteMatcher {
  /**
   * Brings a declared route pattern into the form a normalized hash has.
   *
   * A hash is normalized to `#/path` before matching, but the pattern used to
   * be compiled exactly as written -- so only a pattern spelled `#/...`
   * could ever match. `''`, `'/'` and `'/about'` compiled to regexes
   * (`^$`, `^/$`, `^/about$`) that no normalized hash can satisfy, and the
   * route was silently dead: no match, no error, an empty container.
   *
   * The scaffolded routing template hid this by declaring the root twice,
   * `'': 'Home'` next to `'#/': 'Home'`, so the working spelling carried the
   * dead one. The compiler already treats all four forms as the same route
   * (`normalizeRoute` in lib/compiler/atlas/routes.js), so this is also what
   * makes Atlas's model and the runtime agree about what a route table says.
   * @param {string} routePattern - The pattern as declared.
   * @returns {string} The pattern in `#/path` form.
   */
  static normalizePattern(routePattern) {
    let path = String(routePattern);
    if (path.startsWith('#')) path = path.slice(1);
    if (!path.startsWith('/')) path = '/' + path;
    return '#' + path;
  }
 
  /**
   * Compiles a route pattern into a regular expression, tracking parameter names.
   * @param {string} routePattern - The route pattern (e.g. '/user/:id').
   * @returns {{regex: RegExp, paramNames: string[]}}
   */
  static compileRoute(routePattern) {
    const paramNames = [];
    const escaped = routePattern.replace(/[.+^${}()|[\]\\]/g, '\\$&');
 
    const regexStr = escaped.replace(/(:[a-zA-Z0-9_$]+)|(\*)/g, (_match, param) => {
      if (param) {
        paramNames.push(param.slice(1));
        return '([^/]+)';
      }
      paramNames.push('wildcard');
      return '(.*)';
    });
 
    return { regex: new RegExp(`^${regexStr}$`), paramNames };
  }
 
  /**
   * Normalizes a hash string with an optional namespace prefix.
   * @param {string} hash - Raw hash string (e.g. '#/app1/home').
   * @param {string} [prefix] - Namespace prefix (e.g. '/app1').
   * @returns {string|null} Normalized hash (e.g. '#/home'), or null if prefix does not match.
   */
  static normalizeHash(hash, prefix) {
    let normalized = hash || '#/';
    const secondHashIndex = normalized.indexOf('#', 1);
    if (secondHashIndex !== -1) {
      normalized = normalized.substring(0, secondHashIndex);
    }
 
    // A bare '#' is what every `<a href="#">` in a page puts in the URL, and
    // what a browser leaves behind when a hash is cleared. It means the root,
    // so it has to normalize to the root rather than to a path of its own that
    // no pattern can match.
    if (normalized === '#') {
      normalized = '#/';
    }
 
    if (prefix) {
      const expectedStart = '#' + prefix;
      if (!normalized.startsWith(expectedStart)) {
        return null;
      }
      // The prefix names a path segment, so it only owns a hash that ends
      // there or continues with a separator. Matching on the string alone made
      // `/widget` claim `#/widgets/list`: the router stripped seven characters
      // off an unrelated host route, matched the remainder against its own
      // table and, finding nothing, mounted its `*` fallback over a page it
      // does not own.
      const rest = normalized.substring(expectedStart.length);
      if (!expectedStart.endsWith('/') && rest !== '' && !rest.startsWith('/') && !rest.startsWith('?')) {
        return null;
      }
      normalized = '#' + rest;
      if (!normalized.startsWith('#/')) {
        normalized = '#/' + normalized.substring(1);
      }
    }
    return normalized;
  }
 
  /**
   * Recursively finds a route match.
   * @param {Object} routes - The routes configuration
   * @param {string} decodedPath - The decoded path to match against
   * @param {string} basePath - The accumulated base path
   * @param {Object|null} parentDef - The parent route definition, if any
   * @returns {Object|null} The match result or null if not found
   */
  static _findMatch(routes, decodedPath, basePath = '', parentDef = null) {
    for (const [routePattern, routeDef] of Object.entries(routes)) {
      if (routePattern === '*') continue;
 
      let fullPattern = routePattern;
      if (basePath) {
        if (basePath.endsWith('/') && routePattern.startsWith('/')) {
          fullPattern = basePath + routePattern.slice(1);
        } else if (!basePath.endsWith('/') && !routePattern.startsWith('/')) {
          fullPattern = basePath + '/' + routePattern;
        } else {
          fullPattern = basePath + routePattern;
        }
      }
 
      // Normalized here rather than per declared pattern, so a nested child
      // joins to its parent as written and the join is normalized once.
      fullPattern = RouteMatcher.normalizePattern(fullPattern);
 
      const { regex, paramNames } = RouteMatcher.compileRoute(fullPattern);
      const match = decodedPath.match(regex);
      if (match) {
        return {
          pattern: fullPattern,
          definition: routeDef,
          parent: parentDef,
          match,
          paramNames,
        };
      }
 
      if (routeDef && typeof routeDef === 'object' && routeDef.children) {
        let childRoutes = routeDef.children;
        if (Array.isArray(childRoutes)) {
          childRoutes = childRoutes.reduce((acc, child) => {
            acc[child.path] = child;
            return acc;
          }, {});
        }
 
        const nestedMatch = this._findMatch(childRoutes, decodedPath, fullPattern, {
          pattern: fullPattern,
          definition: routeDef,
        });
 
        if (nestedMatch) return nestedMatch;
      }
    }
    return null;
  }
 
  /**
   * Checks if the route definitions have a non-fallback match for the given hash.
   * @param {Object<string, any>} routes - Map of route patterns.
   * @param {string} hash - The URL hash.
   * @param {object} [options] - Router options (e.g. prefix).
   * @returns {boolean} True if a non-fallback route matches.
   */
  static matches(routes, hash, options = {}) {
    const normalizedHash = RouteMatcher.normalizeHash(hash, options.prefix);
    if (normalizedHash === null) {
      return false;
    }
 
    const [pathPart] = normalizedHash.split('?');
    let decodedPath;
    try {
      decodedPath = decodeURIComponent(pathPart);
    } catch {
      decodedPath = pathPart;
    }
 
    return !!this._findMatch(routes, decodedPath);
  }
 
  /**
   * Matches a hash string against a collection of routes.
   * @param {Object<string, any>} routes - Map of route patterns to definitions.
   * @param {string} hash - The URL hash.
   * @param {object} [options] - Router options (e.g. prefix).
   * @param {Iterable<object>} [activeRouters] - Active router instances to check for fallback wildcard resolution.
   * @param {object} [currentRouter] - The current router instance.
   * @returns {object}
   */
  static matchRoute(routes, hash, options = {}, activeRouters = [], currentRouter = null) {
    const normalizedHash = RouteMatcher.normalizeHash(hash, options.prefix);
    if (normalizedHash === null) {
      return { matchedRoute: null, params: {}, otherRouterMatches: false, normalizedHash: null };
    }
 
    let matchedRoute = null;
    const params = {};
    const query = {};
 
    const [pathPart, queryPart] = normalizedHash.split('?');
    let decodedPath;
 
    try {
      decodedPath = decodeURIComponent(pathPart);
    } catch {
      decodedPath = pathPart;
    }
 
    if (queryPart) {
      const queryParams = new URLSearchParams(queryPart);
      for (const [key, value] of queryParams.entries()) {
        if (value === 'true') {
          query[key] = true;
        } else if (value === 'false') {
          query[key] = false;
        } else if (/^\d+$/.test(value)) {
          query[key] = Number(value);
        } else {
          query[key] = value;
        }
      }
    }
 
    const found = this._findMatch(routes, decodedPath);
    if (found) {
      matchedRoute = { pattern: found.pattern, definition: found.definition };
      if (found.parent) {
        matchedRoute.parent = found.parent;
      }
 
      found.paramNames.forEach((name, idx) => {
        const value = found.match[idx + 1];
        try {
          params[name] = decodeURIComponent(value);
        } catch {
          params[name] = value;
        }
      });
 
      // Always install `query` on matched params, even when the URL has no
      // `?` segment (value then stays `undefined`). Page state only tracks keys
      // that exist at first mount; omitting the key here meant a page opened
      // without a query string never observed later query changes (#1524).
      params.query = Object.keys(query).length > 0 ? { ...query } : undefined;
    }
 
    let otherRouterMatches = false;
    if (!matchedRoute && routes['*']) {
      const rawHash = hash || '#/';
      otherRouterMatches = Array.from(activeRouters || []).some(
        (r) => r !== currentRouter && typeof r.matches === 'function' && r.matches(rawHash),
      );
 
      if (!otherRouterMatches) {
        matchedRoute = { pattern: '*', definition: routes['*'] };
      }
    }
 
    return { matchedRoute, params, query, path: pathPart, otherRouterMatches, normalizedHash };
  }
}