All files / src/lib pathUtils.ts

100% Statements 66/66
96.36% Branches 53/55
100% Functions 8/8
100% Lines 66/66

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 2031x 1x                     1x 1x 1x 1x         1x 26x             10x               1x 11x 11x 11x 11x 11x 11x     11x 1x                       10x 3x             10x 10x 10x 2x               10x 2x             10x 10x 1x         10x 1x             10x 2x           8x                     1x   23x 1x     22x 22x 22x 22x     22x     22x 1x       21x 21x       21x 20x       21x 19x     21x             1x 4x               1x 4x             1x 6x 1x   5x 5x               1x   5x 1x       4x 4x     4x    
import * as path from 'path';
import { platform } from 'os';
import {
  ValidationOptions,
  ValidationResult,
  ValidationError,
  NormalizationOptions,
  OSType,
  ValidationErrorCode,
} from '../types/path.types';
 
// Constants
const WINDOWS_MAX_PATH = 260;
const POSIX_MAX_PATH = 4096;
const WINDOWS_ILLEGAL_CHARS = /[<>:"|?*\x00-\x1F]/g;
const POSIX_ILLEGAL_CHARS = /\x00/g;
 
/**
 * Determines the current operating system type
 */
export function getCurrentOS(): OSType {
  return platform() === 'win32' ? 'windows' : 'posix';
}
 
/**
 * Gets the maximum path length for the specified OS
 */
function getMaxPathLength(os: OSType): number {
  return os === 'windows' ? WINDOWS_MAX_PATH : POSIX_MAX_PATH;
}
 
/**
 * Validates a path string against OS-specific rules
 * @param pathStr - The path to validate
 * @param options - Validation options
 */
export function validatePath(pathStr: string, options: ValidationOptions = {}): ValidationResult {
  const errors: ValidationError[] = [];
  const os = options.os === 'auto' || !options.os ? getCurrentOS() : options.os;
  const maxLength = options.maxLength || getMaxPathLength(os);
  const allowTraversal = options.allowTraversal ?? false;
  const allowAbsolute = options.allowAbsolute ?? true;
  const allowRelative = options.allowRelative ?? true;
 
  // Check for empty path
  if (!pathStr) {
    return {
      isValid: false,
      errors: [
        {
          code: 'EMPTY_PATH',
          message: 'Path cannot be empty',
        },
      ],
    };
  }
 
  // Check path length
  if (pathStr.length > maxLength) {
    errors.push({
      code: 'TOO_LONG',
      message: `Path exceeds maximum length of ${maxLength} characters`,
    });
  }
 
  // Check for illegal characters
  const illegalChars = os === 'windows' ? WINDOWS_ILLEGAL_CHARS : POSIX_ILLEGAL_CHARS;
  const illegalMatch = pathStr.match(illegalChars);
  if (illegalMatch) {
    errors.push({
      code: 'ILLEGAL_CHAR',
      message: `Path contains illegal character: ${illegalMatch[0]}`,
      position: illegalMatch.index,
    });
  }
 
  // Check for path traversal
  if (!allowTraversal && pathStr.includes('..')) {
    errors.push({
      code: 'TRAVERSAL',
      message: 'Path traversal (..) is not allowed',
    });
  }
 
  // Check absolute/relative path restrictions
  const isAbsolute = path.isAbsolute(pathStr);
  if (isAbsolute && !allowAbsolute) {
    errors.push({
      code: 'ABSOLUTE_NOT_ALLOWED',
      message: 'Absolute paths are not allowed',
    });
  }
  if (!isAbsolute && !allowRelative) {
    errors.push({
      code: 'RELATIVE_NOT_ALLOWED',
      message: 'Relative paths are not allowed',
    });
  }
 
  // Return validation result
  if (errors.length === 0) {
    return {
      isValid: true,
      normalizedPath: normalizePath(pathStr, { os }),
    };
  }
 
  return {
    isValid: false,
    errors,
  };
}
 
/**
 * Normalizes a path according to the specified options
 * @param pathStr - The path to normalize
 * @param options - Normalization options
 */
export function normalizePath(pathStr: string, options: NormalizationOptions = {}): string {
  // Handle empty path
  if (!pathStr) {
    return '';
  }
 
  const os = options.os === 'auto' || !options.os ? getCurrentOS() : options.os;
  const forceForwardSlash = options.forceForwardSlash ?? true;
  const removeTrailingSlash = options.removeTrailingSlash ?? true;
  const toLowerCase = options.toLowerCase ?? os === 'windows';
 
  // Normalize path separators
  let normalized = path.normalize(pathStr);
 
  // Handle '.' case from path.normalize
  if (normalized === '.') {
    return pathStr;
  }
 
  // Force forward slashes if requested
  if (forceForwardSlash) {
    normalized = normalized.replace(/\\/g, '/');
  }
 
  // Remove trailing slash if requested
  if (removeTrailingSlash && normalized.length > 1) {
    normalized = normalized.replace(/[/\\]$/, '');
  }
 
  // Convert to lowercase for Windows
  if (toLowerCase) {
    normalized = normalized.toLowerCase();
  }
 
  return normalized;
}
 
/**
 * Safely joins path segments
 * @param paths - Path segments to join
 */
export function joinPaths(...paths: string[]): string {
  return path.join(...paths);
}
 
/**
 * Gets a relative path from one path to another
 * @param from - Source path
 * @param to - Target path
 */
export function getRelativePath(from: string, to: string): string {
  return path.relative(from, to);
}
 
/**
 * Checks if a path contains traversal
 * @param pathStr - The path to check
 */
export function isPathTraversal(pathStr: string): boolean {
  if (!pathStr) {
    return false;
  }
  const normalized = normalizePath(pathStr);
  return normalized.includes('..');
}
 
/**
 * Sanitizes a path by removing illegal characters and normalizing it
 * @param pathStr - The path to sanitize
 * @param os - Target operating system
 */
export function sanitizePath(pathStr: string, os: OSType = getCurrentOS()): string {
  // Handle empty path
  if (!pathStr) {
    return '';
  }
 
  // Remove illegal characters based on OS
  const illegalChars = os === 'windows' ? WINDOWS_ILLEGAL_CHARS : POSIX_ILLEGAL_CHARS;
  const sanitized = pathStr.replace(illegalChars, '');
 
  // Normalize the sanitized path
  return normalizePath(sanitized, { os });
}