index.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. "use strict";
  2. var __create = Object.create;
  3. var __defProp = Object.defineProperty;
  4. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  5. var __getOwnPropNames = Object.getOwnPropertyNames;
  6. var __getProtoOf = Object.getPrototypeOf;
  7. var __hasOwnProp = Object.prototype.hasOwnProperty;
  8. var __export = (target, all) => {
  9. for (var name in all)
  10. __defProp(target, name, { get: all[name], enumerable: true });
  11. };
  12. var __copyProps = (to, from, except, desc) => {
  13. if (from && typeof from === "object" || typeof from === "function") {
  14. for (let key of __getOwnPropNames(from))
  15. if (!__hasOwnProp.call(to, key) && key !== except)
  16. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  17. }
  18. return to;
  19. };
  20. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  21. // If the importer is in node compatibility mode or this is not an ESM
  22. // file that has been converted to a CommonJS file using a Babel-
  23. // compatible transform (i.e. "__esModule" has not been set), then set
  24. // "default" to the CommonJS "module.exports" for node compatibility.
  25. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  26. mod
  27. ));
  28. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  29. // src/index.ts
  30. var src_exports = {};
  31. __export(src_exports, {
  32. convertPathToPattern: () => convertPathToPattern,
  33. escapePath: () => escapePath,
  34. glob: () => glob,
  35. globSync: () => globSync,
  36. isDynamicPattern: () => isDynamicPattern
  37. });
  38. module.exports = __toCommonJS(src_exports);
  39. var import_node_path = __toESM(require("path"));
  40. var import_fdir = require("fdir");
  41. var import_picomatch2 = __toESM(require("picomatch"));
  42. // src/utils.ts
  43. var import_picomatch = __toESM(require("picomatch"));
  44. var ESCAPED_WIN32_BACKSLASHES = /\\(?![()[\]{}!+@])/g;
  45. function convertPosixPathToPattern(path2) {
  46. return escapePosixPath(path2);
  47. }
  48. function convertWin32PathToPattern(path2) {
  49. return escapeWin32Path(path2).replace(ESCAPED_WIN32_BACKSLASHES, "/");
  50. }
  51. var convertPathToPattern = process.platform === "win32" ? convertWin32PathToPattern : convertPosixPathToPattern;
  52. var POSIX_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g;
  53. var WIN32_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g;
  54. var escapePosixPath = (path2) => path2.replace(POSIX_UNESCAPED_GLOB_SYMBOLS, "\\$&");
  55. var escapeWin32Path = (path2) => path2.replace(WIN32_UNESCAPED_GLOB_SYMBOLS, "\\$&");
  56. var escapePath = process.platform === "win32" ? escapeWin32Path : escapePosixPath;
  57. function isDynamicPattern(pattern, options) {
  58. if ((options == null ? void 0 : options.caseSensitiveMatch) === false) {
  59. return true;
  60. }
  61. const scan = import_picomatch.default.scan(pattern);
  62. return scan.isGlob || scan.negated;
  63. }
  64. // src/index.ts
  65. function normalizePattern(pattern, expandDirectories, cwd, properties, isIgnore) {
  66. var _a;
  67. let result = pattern;
  68. if (pattern.endsWith("/")) {
  69. result = pattern.slice(0, -1);
  70. }
  71. if (!result.endsWith("*") && expandDirectories) {
  72. result += "/**";
  73. }
  74. if (import_node_path.default.isAbsolute(result.replace(/\\(?=[()[\]{}!*+?@|])/g, ""))) {
  75. result = import_node_path.posix.relative(cwd, result);
  76. } else {
  77. result = import_node_path.posix.normalize(result);
  78. }
  79. const parentDirectoryMatch = /^(\/?\.\.)+/.exec(result);
  80. if (parentDirectoryMatch == null ? void 0 : parentDirectoryMatch[0]) {
  81. const potentialRoot = import_node_path.posix.join(cwd, parentDirectoryMatch[0]);
  82. if (properties.root.length > potentialRoot.length) {
  83. properties.root = potentialRoot;
  84. properties.depthOffset = -(parentDirectoryMatch[0].length + 1) / 3;
  85. }
  86. } else if (!isIgnore && properties.depthOffset >= 0) {
  87. const current = result.split("/");
  88. (_a = properties.commonPath) != null ? _a : properties.commonPath = current;
  89. const newCommonPath = [];
  90. for (let i = 0; i < Math.min(properties.commonPath.length, current.length); i++) {
  91. const part = current[i];
  92. if (part === "**" && !current[i + 1]) {
  93. newCommonPath.pop();
  94. break;
  95. }
  96. if (part !== properties.commonPath[i] || isDynamicPattern(part) || i === current.length - 1) {
  97. break;
  98. }
  99. newCommonPath.push(part);
  100. }
  101. properties.depthOffset = newCommonPath.length;
  102. properties.commonPath = newCommonPath;
  103. properties.root = newCommonPath.length > 0 ? `${cwd}/${newCommonPath.join("/")}` : cwd;
  104. }
  105. return result;
  106. }
  107. function processPatterns({ patterns, ignore = [], expandDirectories = true }, cwd, properties) {
  108. if (typeof patterns === "string") {
  109. patterns = [patterns];
  110. } else if (!patterns) {
  111. patterns = ["**/*"];
  112. }
  113. if (typeof ignore === "string") {
  114. ignore = [ignore];
  115. }
  116. const matchPatterns = [];
  117. const ignorePatterns = [];
  118. for (const pattern of ignore) {
  119. if (!pattern.startsWith("!") || pattern[1] === "(") {
  120. const newPattern = normalizePattern(pattern, expandDirectories, cwd, properties, true);
  121. ignorePatterns.push(newPattern);
  122. }
  123. }
  124. for (const pattern of patterns) {
  125. if (!pattern.startsWith("!") || pattern[1] === "(") {
  126. const newPattern = normalizePattern(pattern, expandDirectories, cwd, properties, false);
  127. matchPatterns.push(newPattern);
  128. } else if (pattern[1] !== "!" || pattern[2] === "(") {
  129. const newPattern = normalizePattern(pattern.slice(1), expandDirectories, cwd, properties, true);
  130. ignorePatterns.push(newPattern);
  131. }
  132. }
  133. return { match: matchPatterns, ignore: ignorePatterns };
  134. }
  135. function getRelativePath(path2, cwd, root) {
  136. return import_node_path.posix.relative(cwd, `${root}/${path2}`);
  137. }
  138. function processPath(path2, cwd, root, isDirectory, absolute) {
  139. const relativePath = absolute ? path2.slice(root.length + 1) || "." : path2;
  140. if (root === cwd) {
  141. return isDirectory && relativePath !== "." ? relativePath.slice(0, -1) : relativePath;
  142. }
  143. return getRelativePath(relativePath, cwd, root);
  144. }
  145. function crawl(options, cwd, sync) {
  146. const properties = {
  147. root: cwd,
  148. commonPath: null,
  149. depthOffset: 0
  150. };
  151. const processed = processPatterns(options, cwd, properties);
  152. const matcher = (0, import_picomatch2.default)(processed.match, {
  153. dot: options.dot,
  154. nocase: options.caseSensitiveMatch === false,
  155. ignore: processed.ignore
  156. });
  157. const exclude = (0, import_picomatch2.default)(processed.ignore, {
  158. dot: options.dot,
  159. nocase: options.caseSensitiveMatch === false
  160. });
  161. const fdirOptions = {
  162. // use relative paths in the matcher
  163. filters: [(p, isDirectory) => matcher(processPath(p, cwd, properties.root, isDirectory, options.absolute))],
  164. exclude: (_, p) => exclude(processPath(p, cwd, properties.root, true, true)),
  165. pathSeparator: "/",
  166. relativePaths: true,
  167. resolveSymlinks: true
  168. };
  169. if (options.deep) {
  170. fdirOptions.maxDepth = Math.round(options.deep - properties.depthOffset);
  171. }
  172. if (options.absolute) {
  173. fdirOptions.relativePaths = false;
  174. fdirOptions.resolvePaths = true;
  175. fdirOptions.includeBasePath = true;
  176. }
  177. if (options.followSymbolicLinks === false) {
  178. fdirOptions.resolveSymlinks = false;
  179. fdirOptions.excludeSymlinks = true;
  180. }
  181. if (options.onlyDirectories) {
  182. fdirOptions.excludeFiles = true;
  183. fdirOptions.includeDirs = true;
  184. } else if (options.onlyFiles === false) {
  185. fdirOptions.includeDirs = true;
  186. }
  187. properties.root = properties.root.replace(/\\/g, "");
  188. const api = new import_fdir.fdir(fdirOptions).crawl(properties.root);
  189. if (cwd === properties.root || options.absolute) {
  190. return sync ? api.sync() : api.withPromise();
  191. }
  192. return sync ? api.sync().map((p) => getRelativePath(p, cwd, properties.root) + (!p || p.endsWith("/") ? "/" : "")) : api.withPromise().then((paths) => paths.map((p) => getRelativePath(p, cwd, properties.root) + (!p || p.endsWith("/") ? "/" : "")));
  193. }
  194. async function glob(patternsOrOptions, options) {
  195. if (patternsOrOptions && (options == null ? void 0 : options.patterns)) {
  196. throw new Error("Cannot pass patterns as both an argument and an option");
  197. }
  198. const opts = Array.isArray(patternsOrOptions) || typeof patternsOrOptions === "string" ? { ...options, patterns: patternsOrOptions } : patternsOrOptions;
  199. const cwd = opts.cwd ? import_node_path.default.resolve(opts.cwd).replace(/\\/g, "/") : process.cwd().replace(/\\/g, "/");
  200. return crawl(opts, cwd, false);
  201. }
  202. function globSync(patternsOrOptions, options) {
  203. if (patternsOrOptions && (options == null ? void 0 : options.patterns)) {
  204. throw new Error("Cannot pass patterns as both an argument and an option");
  205. }
  206. const opts = Array.isArray(patternsOrOptions) || typeof patternsOrOptions === "string" ? { ...options, patterns: patternsOrOptions } : patternsOrOptions;
  207. const cwd = opts.cwd ? import_node_path.default.resolve(opts.cwd).replace(/\\/g, "/") : process.cwd().replace(/\\/g, "/");
  208. return crawl(opts, cwd, true);
  209. }
  210. // Annotate the CommonJS export names for ESM import in node:
  211. 0 && (module.exports = {
  212. convertPathToPattern,
  213. escapePath,
  214. glob,
  215. globSync,
  216. isDynamicPattern
  217. });