Code coverage report for src/route-recognizer.js

Statements: 88.34% (144 / 163)      Branches: 72.06% (49 / 68)      Functions: 93.75% (15 / 16)      Lines: 88.2% (142 / 161)      Ignored: none     

All files » src/ » route-recognizer.js
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 3451 1 1                           1 28 28                 56 28 28     28 28 28 28 28 28 28   55 58 58 3     55       55       55     28 3 3     28   28 27 27 28             28 28 28   28                   4 4 1     3                   2                     12 16   16 16 1     15 15 15   15 29   29 1     28 28 28 3     25     12 1         9     12 12   12                       17 17 17 17   17 17           17   17 1     17 17         17 200 200 2       17 17 15 15       17   17 17     15       15             15 15 15 15 15       1     28 28       28   28 28 58 58 58 20 20 20 20     38 38 6 6 6 32 3   29 29       28                         1 17                                                   1 200   200 200 200     200     1 15 15 15 15 15   15 15 15 15   15 16     15     15     1 55 55 200     55    
import {buildQueryString, parseQueryString} from 'aurelia-path';
import {State} from './state';
import {
  StaticSegment,
  DynamicSegment,
  StarSegment,
  EpsilonSegment
} from './segments';
 
/**
* Class that parses route patterns and matches path strings.
*
* @class RouteRecognizer
* @constructor
*/
export class RouteRecognizer {
  constructor() {
    this.rootState = new State();
    this.names = {};
  }
 
  /**
  * Parse a route pattern and add it to the collection of recognized routes.
  *
  * @param route The route to add.
  */
  add(route: ConfigurableRoute|ConfigurableRoute[]): State {
    if (Array.isArray(route)) {
      route.forEach(r => this.add(r));
      return undefined;
    }
 
    let currentState = this.rootState;
    let regex = '^';
    let types = { statics: 0, dynamics: 0, stars: 0 };
    let names = [];
    let routeName = route.handler.name;
    let isEmpty = true;
    let segments = parse(route.path, names, types, route.caseSensitive);
 
    for (let i = 0, ii = segments.length; i < ii; i++) {
      let segment = segments[i];
      if (segment instanceof EpsilonSegment) {
        continue;
      }
 
      isEmpty = false;
 
      // Add a '/' for the new segment
      currentState = currentState.put({ validChars: '/' });
      regex += '/';
 
      // Add a representation of the segment to the NFA and regex
      currentState = addSegment(currentState, segment);
      regex += segment.regex();
    }
 
    if (isEmpty) {
      currentState = currentState.put({ validChars: '/' });
      regex += '/';
    }
 
    let handlers = [{ handler: route.handler, names: names }];
 
    if (routeName) {
      let routeNames = Array.isArray(routeName) ? routeName : [routeName];
      for (let i = 0; i < routeNames.length; i++) {
        this.names[routeNames[i]] = {
          segments: segments,
          handlers: handlers
        };
      }
    }
 
    currentState.handlers = handlers;
    currentState.regex = new RegExp(regex + '$', route.caseSensitive ? '' : 'i');
    currentState.types = types;
 
    return currentState;
  }
 
  /**
  * Retrieve the handlers registered for the named route.
  *
  * @param name The name of the route.
  * @returns The handlers.
  */
  handlersFor(name: string): HandlerEntry[] {
    let route = this.names[name];
    if (!route) {
      throw new Error(`There is no route named ${name}`);
    }
 
    return [...route.handlers];
  }
 
  /**
  * Check if this RouteRecognizer recognizes a named route.
  *
  * @param name The name of the route.
  * @returns True if the named route is recognized.
  */
  hasRoute(name: string): boolean {
    return !!this.names[name];
  }
 
  /**
  * Generate a path and query string from a route name and params object.
  *
  * @param name The name of the route.
  * @param params The route params to use when populating the pattern.
  *  Properties not required by the pattern will be appended to the query string.
  * @returns The generated absolute path and query string.
  */
  generate(name: string, params: Object): string {
    let routeParams = Object.assign({}, params);
 
    let route = this.names[name];
    if (!route) {
      throw new Error(`There is no route named ${name}`);
    }
 
    let segments = route.segments;
    let consumed = {};
    let output = '';
 
    for (let i = 0, l = segments.length; i < l; i++) {
      let segment = segments[i];
 
      if (segment instanceof EpsilonSegment) {
        continue;
      }
 
      output += '/';
      let segmentValue = segment.generate(routeParams, consumed);
      if (segmentValue === null || segmentValue === undefined) {
        throw new Error(`A value is required for route parameter '${segment.name}' in route '${name}'.`);
      }
 
      output += segmentValue;
    }
 
    if (output.charAt(0) !== '/') {
      output = '/' + output;
    }
 
    // remove params used in the path and add the rest to the querystring
    for (let param in consumed) {
      delete routeParams[param];
    }
 
    let queryString = buildQueryString(routeParams);
    output += queryString ? `?${queryString}` : '';
 
    return output;
  }
 
  /**
  * Match a path string against registered route patterns.
  *
  * @param path The path to attempt to match.
  * @returns Array of objects containing `handler`, `params`, and
  *  `isDynanic` values for the matched route(s), or undefined if no match
  *  was found.
  */
  recognize(path: string): RecognizedRoute[] {
    let states = [this.rootState];
    let queryParams = {};
    let isSlashDropped = false;
    let normalizedPath = path;
 
    let queryStart = normalizedPath.indexOf('?');
    Iif (queryStart !== -1) {
      let queryString = normalizedPath.substr(queryStart + 1, normalizedPath.length);
      normalizedPath = normalizedPath.substr(0, queryStart);
      queryParams = parseQueryString(queryString);
    }
 
    normalizedPath = decodeURI(normalizedPath);
 
    if (normalizedPath.charAt(0) !== '/') {
      normalizedPath = '/' + normalizedPath;
    }
 
    let pathLen = normalizedPath.length;
    Iif (pathLen > 1 && normalizedPath.charAt(pathLen - 1) === '/') {
      normalizedPath = normalizedPath.substr(0, pathLen - 1);
      isSlashDropped = true;
    }
 
    for (let i = 0, l = normalizedPath.length; i < l; i++) {
      states = recognizeChar(states, normalizedPath.charAt(i));
      if (!states.length) {
        break;
      }
    }
 
    let solutions = [];
    for (let i = 0, l = states.length; i < l; i++) {
      Eif (states[i].handlers) {
        solutions.push(states[i]);
      }
    }
 
    states = sortSolutions(solutions);
 
    let state = solutions[0];
    if (state && state.handlers) {
      // if a trailing slash was dropped and a star segment is the last segment
      // specified, put the trailing slash back
      Iif (isSlashDropped && state.regex.source.slice(-5) === '(.+)$') {
        normalizedPath = normalizedPath + '/';
      }
 
      return findHandler(state, normalizedPath, queryParams);
    }
  }
}
 
class RecognizeResults {
  constructor(queryParams: Object) {
    this.splice = Array.prototype.splice;
    this.slice = Array.prototype.slice;
    this.push = Array.prototype.push;
    this.length = 0;
    this.queryParams = queryParams || {};
  }
}
 
function parse(route, names, types, caseSensitive) {
  // normalize route as not starting with a '/'. Recognition will
  // also normalize.
  let normalizedRoute = route;
  Iif (route.charAt(0) === '/') {
    normalizedRoute = route.substr(1);
  }
 
  let results = [];
 
  let splitRoute = normalizedRoute.split('/');
  for (let i = 0, ii = splitRoute.length; i < ii; ++i) {
    let segment = splitRoute[i];
    let match = segment.match(/^:([^\/]+)$/);
    if (match) {
      results.push(new DynamicSegment(match[1]));
      names.push(match[1]);
      types.dynamics++;
      continue;
    }
 
    match = segment.match(/^\*([^\/]+)$/);
    if (match) {
      results.push(new StarSegment(match[1]));
      names.push(match[1]);
      types.stars++;
    } else if (segment === '') {
      results.push(new EpsilonSegment());
    } else {
      results.push(new StaticSegment(segment, caseSensitive));
      types.statics++;
    }
  }
 
  return results;
}
 
// This is a somewhat naive strategy, but should work in a lot of cases
// A better strategy would properly resolve /posts/:id/new and /posts/edit/:id.
//
// This strategy generally prefers more static and less dynamic matching.
// Specifically, it
//
//  * prefers fewer stars to more, then
//  * prefers using stars for less of the match to more, then
//  * prefers fewer dynamic segments to more, then
//  * prefers more static segments to more
function sortSolutions(states) {
  return states.sort((a, b) => {
    if (a.types.stars !== b.types.stars) {
      return a.types.stars - b.types.stars;
    }
 
    if (a.types.stars) {
      if (a.types.statics !== b.types.statics) {
        return b.types.statics - a.types.statics;
      }
      if (a.types.dynamics !== b.types.dynamics) {
        return b.types.dynamics - a.types.dynamics;
      }
    }
 
    if (a.types.dynamics !== b.types.dynamics) {
      return a.types.dynamics - b.types.dynamics;
    }
 
    if (a.types.statics !== b.types.statics) {
      return b.types.statics - a.types.statics;
    }
 
    return 0;
  });
}
 
function recognizeChar(states, ch) {
  let nextStates = [];
 
  for (let i = 0, l = states.length; i < l; i++) {
    let state = states[i];
    nextStates.push(...state.match(ch));
  }
 
  return nextStates;
}
 
function findHandler(state, path, queryParams) {
  let handlers = state.handlers;
  let regex = state.regex;
  let captures = path.match(regex);
  let currentCapture = 1;
  let result = new RecognizeResults(queryParams);
 
  for (let i = 0, l = handlers.length; i < l; i++) {
    let handler = handlers[i];
    let names = handler.names;
    let params = {};
 
    for (let j = 0, m = names.length; j < m; j++) {
      params[names[j]] = captures[currentCapture++];
    }
 
    result.push({ handler: handler.handler, params: params, isDynamic: !!names.length });
  }
 
  return result;
}
 
function addSegment(currentState, segment) {
  let state = currentState;
  segment.eachChar(ch => {
    state = state.put(ch);
  });
 
  return state;
}