All files / src/utils routing.ts

100% Statements 26/26
100% Branches 22/22
100% Functions 3/3
100% Lines 25/25

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  354x         346x 1x     345x 345x 1x   344x                             209x 1x     208x 7x     201x   1x     200x 200x 200x 200x 2362x 366x 162x   204x 1996x 203x 203x     38x    
export function removeTrailingSlashesAndMultiSlashes(str: string): string {
  return str.replace(/\/+$/, '').replace(/(?<=\/)\/+/, '')
}
 
export function createRoutePathPrefix(route: string): string {
  // sanity check
  if (!route.startsWith('/')) {
    throw new Error('All route paths must start with a /')
  }
 
  const normalizedPath = removeTrailingSlashesAndMultiSlashes(route)
  if (!normalizedPath) {
    return '/'
  }
  return normalizedPath
}
 
/**
 * Removes the specified number of path segments from the URL's path, returning the updated path.
 *
 * @param url the URL with the path to parse.
 * @param segmentCount the number of segments to parse, must be greater than or equal to 0.
 *
 * @return If the input path had at least the expected number of path segments, returns the path with the count of segments removed.
 * Will always start with a /. If the input path did not have the expected number of path segments, returns undefined.
 *
 * @throws {Error} `segmentCount` is less than zero.
 */
export function stripPrefixPathSegments(url: URL, segmentCount: number): string | undefined {
  if (segmentCount < 0) {
    throw new Error('segmentCount must be greater than or equal to 0')
  }
 
  if (segmentCount === 0) {
    return url.pathname
  }
 
  if (url.pathname === '/' && segmentCount === 1) {
    // Special case: a path of / has one segment
    return '/'
  }
 
  const path = url.pathname
  let count = 0
  let inSegment = false
  for (let i = 0; i < path.length; i++) {
    if (path[i] === '/') {
      if (inSegment && count === segmentCount) {
        return path.slice(i)
      }
      inSegment = false
    } else if (!inSegment) {
      inSegment = true
      count++
    }
  }
  return count === segmentCount ? '/' : undefined
}