All files / src/node util.ts

80.75% Statements 172/213
72.34% Branches 68/94
77.77% Functions 21/27
81.08% Lines 150/185

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 31845x 45x 45x     45x 45x 45x   45x   45x     12176x   32686x 16636x 16636x 16635x 14239x         45x 16341x 16340x       4390x 2x         45x 4390x 4390x 4388x     45x 18752x 2x 2x 2x           18750x       2x     2x 2x 18x             2x     45x 18757x 13x 13x   11x     2x     18746x 18746x   18746x     45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x     2446x 2446x 2446x   2446x   2100x   20x       1x       299x   3x   6x       6x       1x   4x   2x   4x       45x 2446x 2446x   2446x 2158x     2446x     45x 104x 104x       45x 5084x   4039x 4037x 4037x       2x     45x 12834x     45x 6094x     45x 3261x 1509x 1266x     45x   45x                               1015x 1015x   1015x     1015x 1015x 1015x 1015x 1015x 1011x 1x 1010x     1010x         1010x 1010x 1010x 1010x     4x 3x 1x     1x 1x 1x 1x     1015x 1015x 1011x   4x 4x   1015x 1015x     45x             748x         748x 748x 738x 738x 738x   10x 10x   748x 748x 738x 1x     10x 10x   748x     45x 1088x 68x     45x         45x             45x             45x              
import { ERRSTR, FLAGS } from './constants';
import * as errors from '../internal/errors';
import { Buffer } from '../internal/buffer';
import type { FsCallbackApi } from './types';
import type * as misc from './types/misc';
import { ENCODING_UTF8, TEncodingExtended } from '../encoding';
import { bufferFrom } from '../internal/buffer';
import queueMicrotask from '../queueMicrotask';
 
export const isWin = process.platform === 'win32';
 
export function promisify(
  fs: FsCallbackApi,
  fn: string,
  getResult: (result: any) => any = input => input,
): (...args) => Promise<any> {
  return (...args) =>
    new Promise((resolve, reject) => {
      fs[fn].bind(fs)(...args, (error, result) => {
        if (error) return reject(error);
        return resolve(getResult(result));
      });
    });
}
 
export function validateCallback<T>(callback: T): misc.AssertCallback<T> {
  if (typeof callback !== 'function') throw TypeError(ERRSTR.CB);
  return callback as misc.AssertCallback<T>;
}
 
function _modeToNumber(mode: misc.TMode | undefined, def?): number | undefined {
  if (typeof mode === 'number') return mode;
  if (typeof mode === 'string') return parseInt(mode, 8);
  Iif (def) return modeToNumber(def);
  return undefined;
}
 
export function modeToNumber(mode: misc.TMode | undefined, def?): number {
  const result = _modeToNumber(mode, def);
  if (typeof result !== 'number' || isNaN(result)) throw new TypeError(ERRSTR.MODE_INT);
  return result;
}
 
export function nullCheck(path, callback?) {
  if (('' + path).indexOf('\u0000') !== -1) {
    const er = new Error('Path must be a string without null bytes');
    (er as any).code = 'ENOENT';
    if (typeof callback !== 'function') throw er;
    queueMicrotask(() => {
      callback(er);
    });
    return false;
  }
  return true;
}
 
function getPathFromURLPosix(url): string {
  Iif (url.hostname !== '') {
    throw new errors.TypeError('ERR_INVALID_FILE_URL_HOST', process.platform);
  }
  const pathname = url.pathname;
  for (let n = 0; n < pathname.length; n++) {
    Iif (pathname[n] === '%') {
      const third = pathname.codePointAt(n + 2) | 0x20;
      Iif (pathname[n + 1] === '2' && third === 102) {
        throw new errors.TypeError('ERR_INVALID_FILE_URL_PATH', 'must not include encoded / characters');
      }
    }
  }
  return decodeURIComponent(pathname);
}
 
export function pathToFilename(path: misc.PathLike): string {
  if (typeof path !== 'string' && !Buffer.isBuffer(path)) {
    try {
      if (!(path instanceof require('url').URL)) throw new TypeError(ERRSTR.PATH_STR);
    } catch (err) {
      throw new TypeError(ERRSTR.PATH_STR);
    }
 
    path = getPathFromURLPosix(path);
  }
 
  const pathString = String(path);
  nullCheck(pathString);
  // return slash(pathString);
  return pathString;
}
 
const ENOENT = 'ENOENT';
const EBADF = 'EBADF';
const EINVAL = 'EINVAL';
const EPERM = 'EPERM';
const EPROTO = 'EPROTO';
const EEXIST = 'EEXIST';
const ENOTDIR = 'ENOTDIR';
const EMFILE = 'EMFILE';
const EACCES = 'EACCES';
const EISDIR = 'EISDIR';
const ENOTEMPTY = 'ENOTEMPTY';
const ENOSYS = 'ENOSYS';
const ERR_FS_EISDIR = 'ERR_FS_EISDIR';
const ERR_OUT_OF_RANGE = 'ERR_OUT_OF_RANGE';
 
function formatError(errorCode: string, func = '', path = '', path2 = '') {
  let pathFormatted = '';
  if (path) pathFormatted = ` '${path}'`;
  if (path2) pathFormatted += ` -> '${path2}'`;
 
  switch (errorCode) {
    case ENOENT:
      return `ENOENT: no such file or directory, ${func}${pathFormatted}`;
    case EBADF:
      return `EBADF: bad file descriptor, ${func}${pathFormatted}`;
    case EINVAL:
      return `EINVAL: invalid argument, ${func}${pathFormatted}`;
    case EPERM:
      return `EPERM: operation not permitted, ${func}${pathFormatted}`;
    case EPROTO:
      return `EPROTO: protocol error, ${func}${pathFormatted}`;
    case EEXIST:
      return `EEXIST: file already exists, ${func}${pathFormatted}`;
    case ENOTDIR:
      return `ENOTDIR: not a directory, ${func}${pathFormatted}`;
    case EISDIR:
      return `EISDIR: illegal operation on a directory, ${func}${pathFormatted}`;
    case EACCES:
      return `EACCES: permission denied, ${func}${pathFormatted}`;
    case ENOTEMPTY:
      return `ENOTEMPTY: directory not empty, ${func}${pathFormatted}`;
    case EMFILE:
      return `EMFILE: too many open files, ${func}${pathFormatted}`;
    case ENOSYS:
      return `ENOSYS: function not implemented, ${func}${pathFormatted}`;
    case ERR_FS_EISDIR:
      return `[ERR_FS_EISDIR]: Path is a directory: ${func} returned EISDIR (is a directory) ${path}`;
    case ERR_OUT_OF_RANGE:
      return `[ERR_OUT_OF_RANGE]: value out of range, ${func}${pathFormatted}`;
    default:
      return `${errorCode}: error occurred, ${func}${pathFormatted}`;
  }
}
 
export function createError(errorCode: string, func = '', path = '', path2 = '', Constructor = Error) {
  const error = new Constructor(formatError(errorCode, func, path, path2));
  (error as any).code = errorCode;
 
  if (path) {
    (error as any).path = path;
  }
 
  return error;
}
 
export function genRndStr6(): string {
  const str = (Math.random() + 1).toString(36).substring(2, 8);
  if (str.length === 6) return str;
  else Ereturn genRndStr6();
}
 
export function flagsToNumber(flags: misc.TFlags | undefined): number {
  if (typeof flags === 'number') return flags;
 
  if (typeof flags === 'string') {
    const flagsNum = FLAGS[flags];
    if (typeof flagsNum !== 'undefined') return flagsNum;
  }
 
  // throw new TypeError(formatError(ERRSTR_FLAG(flags)));
  throw new errors.TypeError('ERR_INVALID_OPT_VALUE', 'flags', flags);
}
 
export function isFd(path): boolean {
  return path >>> 0 === path;
}
 
export function validateFd(fd) {
  if (!isFd(fd)) throw TypeError(ERRSTR.FD);
}
 
export function dataToBuffer(data: misc.TData, encoding: string = ENCODING_UTF8): Buffer {
  if (Buffer.isBuffer(data)) return data;
  else if (data instanceof Uint8Array) return bufferFrom(data);
  else return bufferFrom(String(data), encoding);
}
 
export const bufToUint8 = (buf: Buffer): Uint8Array => new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
 
export const getWriteArgs = (
  fd: number,
  a?: unknown,
  b?: unknown,
  c?: unknown,
  d?: unknown,
  e?: unknown,
): [
  fd: number,
  dataAsStr: boolean,
  buf: Buffer,
  offset: number,
  length: number,
  position: number | null,
  callback: (...args) => void,
] => {
  validateFd(fd);
  let offset: number = 0;
  let length: number | undefined;
  let position: number | null = null;
  let encoding: BufferEncoding | undefined;
  let callback: ((...args) => void) | undefined;
  const tipa = typeof a;
  const tipb = typeof b;
  const tipc = typeof c;
  const tipd = typeof d;
  if (tipa !== 'string') {
    if (tipb === 'function') {
      callback = <(...args) => void>b;
    } else Iif (tipc === 'function') {
      offset = (<number>b) | 0;
      callback = <(...args) => void>c;
    } else Iif (tipd === 'function') {
      offset = (<number>b) | 0;
      length = <number>c;
      callback = <(...args) => void>d;
    } else {
      offset = (<number>b) | 0;
      length = <number>c;
      position = <number | null>d;
      callback = <(...args) => void>e;
    }
  } else {
    if (tipb === 'function') {
      callback = <(...args) => void>b;
    } else Iif (tipc === 'function') {
      position = <number | null>b;
      callback = <(...args) => void>c;
    } else if (tipd === 'function') {
      position = <number | null>b;
      encoding = <BufferEncoding>c;
      callback = <(...args) => void>d;
    }
  }
  const buf: Buffer = dataToBuffer(<string | Buffer>a, encoding);
  if (tipa !== 'string') {
    if (typeof length === 'undefined') length = buf.length;
  } else {
    offset = 0;
    length = buf.length;
  }
  const cb = validateCallback(callback);
  return [fd, tipa === 'string', buf, offset, length!, position, cb];
};
 
export const getWriteSyncArgs = (
  fd: number,
  a: string | Buffer | ArrayBufferView | DataView,
  b?: number,
  c?: number | BufferEncoding,
  d?: number | null,
): [fd: number, buf: Buffer, offset: number, length?: number, position?: number | null] => {
  validateFd(fd);
  let encoding: BufferEncoding | undefined;
  let offset: number | undefined;
  let length: number | undefined;
  let position: number | null | undefined;
  const isBuffer = typeof a !== 'string';
  if (isBuffer) {
    offset = (b || 0) | 0;
    length = c as number;
    position = d;
  } else {
    position = b;
    encoding = c as BufferEncoding;
  }
  const buf: Buffer = dataToBuffer(a, encoding);
  if (isBuffer) {
    if (typeof length === 'undefined') {
      length = buf.length;
    }
  } else {
    offset = 0;
    length = buf.length;
  }
  return [fd, buf, offset || 0, length, position];
};
 
export function bufferToEncoding(buffer: Buffer, encoding?: TEncodingExtended): misc.TDataOut {
  if (!encoding || encoding === 'buffer') return buffer;
  else return buffer.toString(encoding);
}
 
const isSeparator = (str, i) => {
  let char = str[i];
  return i > 0 && (char === '/' || (isWin && char === '\\'));
};
 
const removeTrailingSeparator = (str: string): string => {
  let i = str.length - 1;
  Iif (i < 2) return str;
  while (isSeparator(str, i)) i--;
  return str.substr(0, i + 1);
};
 
const normalizePath = (str, stripTrailing): string => {
  Iif (typeof str !== 'string') throw new TypeError('expected a string');
  str = str.replace(/[\\\/]+/g, '/');
  Iif (stripTrailing !== false) str = removeTrailingSeparator(str);
  return str;
};
 
export const unixify = (filepath: string, stripTrailing: boolean = true): string => {
  Iif (isWin) {
    filepath = normalizePath(filepath, stripTrailing);
    return filepath.replace(/^([a-zA-Z]+:|\.\/)/, '');
  }
  return filepath;
};