path-arg.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { parse, resolve } from 'path';
  2. import { inspect } from 'util';
  3. import platform from './platform.js';
  4. const pathArg = (path, opt = {}) => {
  5. const type = typeof path;
  6. if (type !== 'string') {
  7. const ctor = path && type === 'object' && path.constructor;
  8. const received = ctor && ctor.name
  9. ? `an instance of ${ctor.name}`
  10. : type === 'object'
  11. ? inspect(path)
  12. : `type ${type} ${path}`;
  13. const msg = 'The "path" argument must be of type string. ' + `Received ${received}`;
  14. throw Object.assign(new TypeError(msg), {
  15. path,
  16. code: 'ERR_INVALID_ARG_TYPE',
  17. });
  18. }
  19. if (/\0/.test(path)) {
  20. // simulate same failure that node raises
  21. const msg = 'path must be a string without null bytes';
  22. throw Object.assign(new TypeError(msg), {
  23. path,
  24. code: 'ERR_INVALID_ARG_VALUE',
  25. });
  26. }
  27. path = resolve(path);
  28. const { root } = parse(path);
  29. if (path === root && opt.preserveRoot !== false) {
  30. const msg = 'refusing to remove root directory without preserveRoot:false';
  31. throw Object.assign(new Error(msg), {
  32. path,
  33. code: 'ERR_PRESERVE_ROOT',
  34. });
  35. }
  36. if (platform === 'win32') {
  37. const badWinChars = /[*|"<>?:]/;
  38. const { root } = parse(path);
  39. if (badWinChars.test(path.substring(root.length))) {
  40. throw Object.assign(new Error('Illegal characters in path.'), {
  41. path,
  42. code: 'EINVAL',
  43. });
  44. }
  45. }
  46. return path;
  47. };
  48. export default pathArg;
  49. //# sourceMappingURL=path-arg.js.map