utils.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.parseFiles = parseFiles;
  6. exports.parseFoldersToGlobs = parseFoldersToGlobs;
  7. exports.jsonStringifyReplacerSortKeys = void 0;
  8. var _path = require("path");
  9. var _fs = require("fs");
  10. var _normalizePath = _interopRequireDefault(require("normalize-path"));
  11. var _arrify = _interopRequireDefault(require("arrify"));
  12. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13. // @ts-ignore
  14. // @ts-ignore
  15. /**
  16. * @param {string|string[]} files
  17. * @param {string} context
  18. * @returns {string[]}
  19. */
  20. function parseFiles(files, context) {
  21. return (0, _arrify.default)(files).map(
  22. /** @type {string} */
  23. file => (0, _normalizePath.default)((0, _path.resolve)(context, file)));
  24. }
  25. /**
  26. * @param {string|string[]} patterns
  27. * @param {string|string[]} extensions
  28. * @returns {string[]}
  29. */
  30. function parseFoldersToGlobs(patterns, extensions = []) {
  31. const extensionsList = (0, _arrify.default)(extensions);
  32. const [prefix, postfix] = extensionsList.length > 1 ? ['{', '}'] : ['', ''];
  33. const extensionsGlob = extensionsList.map(
  34. /** @type {string} */
  35. extension => extension.replace(/^\./u, '')).join(',');
  36. return (0, _arrify.default)(patterns).map(
  37. /** @type {string} */
  38. pattern => {
  39. try {
  40. // The patterns are absolute because they are prepended with the context.
  41. const stats = (0, _fs.statSync)(pattern);
  42. /* istanbul ignore else */
  43. if (stats.isDirectory()) {
  44. return pattern.replace(/[/\\]*?$/u, `/**${extensionsGlob ? `/*.${prefix + extensionsGlob + postfix}` : ''}`);
  45. }
  46. } catch (_) {// Return the pattern as is on error.
  47. }
  48. return pattern;
  49. });
  50. }
  51. /**
  52. *
  53. * @param {string} _ key, but unused
  54. * @param {any} value
  55. */
  56. const jsonStringifyReplacerSortKeys = (_, value) => {
  57. /**
  58. * @param {{ [x: string]: any; }} sorted
  59. * @param {string | number} key
  60. */
  61. const insert = (sorted, key) => {
  62. // eslint-disable-next-line no-param-reassign
  63. sorted[key] = value[key];
  64. return sorted;
  65. };
  66. return value instanceof Object && !(value instanceof Array) ? Object.keys(value).sort().reduce(insert, {}) : value;
  67. };
  68. exports.jsonStringifyReplacerSortKeys = jsonStringifyReplacerSortKeys;