index.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. //#region rolldown:runtime
  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 __copyProps = (to, from, except, desc) => {
  9. if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
  10. key = keys[i];
  11. if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
  12. get: ((k) => from[k]).bind(null, key),
  13. enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
  14. });
  15. }
  16. return to;
  17. };
  18. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
  19. value: mod,
  20. enumerable: true
  21. }) : target, mod));
  22. //#endregion
  23. const path = __toESM(require("path"));
  24. const fdir = __toESM(require("fdir"));
  25. const picomatch = __toESM(require("picomatch"));
  26. //#region src/utils.ts
  27. const ONLY_PARENT_DIRECTORIES = /^(\/?\.\.)+$/;
  28. function getPartialMatcher(patterns, options) {
  29. const patternsCount = patterns.length;
  30. const patternsParts = Array(patternsCount);
  31. const regexes = Array(patternsCount);
  32. for (let i = 0; i < patternsCount; i++) {
  33. const parts = splitPattern(patterns[i]);
  34. patternsParts[i] = parts;
  35. const partsCount = parts.length;
  36. const partRegexes = Array(partsCount);
  37. for (let j = 0; j < partsCount; j++) partRegexes[j] = picomatch.default.makeRe(parts[j], options);
  38. regexes[i] = partRegexes;
  39. }
  40. return (input) => {
  41. const inputParts = input.split("/");
  42. if (inputParts[0] === ".." && ONLY_PARENT_DIRECTORIES.test(input)) return true;
  43. for (let i = 0; i < patterns.length; i++) {
  44. const patternParts = patternsParts[i];
  45. const regex = regexes[i];
  46. const inputPatternCount = inputParts.length;
  47. const minParts = Math.min(inputPatternCount, patternParts.length);
  48. let j = 0;
  49. while (j < minParts) {
  50. const part = patternParts[j];
  51. if (part.includes("/")) return true;
  52. const match = regex[j].test(inputParts[j]);
  53. if (!match) break;
  54. if (part === "**") return true;
  55. j++;
  56. }
  57. if (j === inputPatternCount) return true;
  58. }
  59. return false;
  60. };
  61. }
  62. const splitPatternOptions = { parts: true };
  63. function splitPattern(path$2) {
  64. var _result$parts;
  65. const result = picomatch.default.scan(path$2, splitPatternOptions);
  66. return ((_result$parts = result.parts) === null || _result$parts === void 0 ? void 0 : _result$parts.length) ? result.parts : [path$2];
  67. }
  68. const isWin = process.platform === "win32";
  69. const ESCAPED_WIN32_BACKSLASHES = /\\(?![()[\]{}!+@])/g;
  70. function convertPosixPathToPattern(path$2) {
  71. return escapePosixPath(path$2);
  72. }
  73. function convertWin32PathToPattern(path$2) {
  74. return escapeWin32Path(path$2).replace(ESCAPED_WIN32_BACKSLASHES, "/");
  75. }
  76. const convertPathToPattern = isWin ? convertWin32PathToPattern : convertPosixPathToPattern;
  77. const POSIX_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g;
  78. const WIN32_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g;
  79. const escapePosixPath = (path$2) => path$2.replace(POSIX_UNESCAPED_GLOB_SYMBOLS, "\\$&");
  80. const escapeWin32Path = (path$2) => path$2.replace(WIN32_UNESCAPED_GLOB_SYMBOLS, "\\$&");
  81. const escapePath = isWin ? escapeWin32Path : escapePosixPath;
  82. function isDynamicPattern(pattern, options) {
  83. if ((options === null || options === void 0 ? void 0 : options.caseSensitiveMatch) === false) return true;
  84. const scan = picomatch.default.scan(pattern);
  85. return scan.isGlob || scan.negated;
  86. }
  87. function log(...tasks) {
  88. console.log(`[tinyglobby ${new Date().toLocaleTimeString("es")}]`, ...tasks);
  89. }
  90. //#endregion
  91. //#region src/index.ts
  92. const PARENT_DIRECTORY = /^(\/?\.\.)+/;
  93. const ESCAPING_BACKSLASHES = /\\(?=[()[\]{}!*+?@|])/g;
  94. const BACKSLASHES = /\\/g;
  95. function normalizePattern(pattern, expandDirectories, cwd, props, isIgnore) {
  96. let result = pattern;
  97. if (pattern.endsWith("/")) result = pattern.slice(0, -1);
  98. if (!result.endsWith("*") && expandDirectories) result += "/**";
  99. const escapedCwd = escapePath(cwd);
  100. if (path.default.isAbsolute(result.replace(ESCAPING_BACKSLASHES, ""))) result = path.posix.relative(escapedCwd, result);
  101. else result = path.posix.normalize(result);
  102. const parentDirectoryMatch = PARENT_DIRECTORY.exec(result);
  103. const parts = splitPattern(result);
  104. if (parentDirectoryMatch === null || parentDirectoryMatch === void 0 ? void 0 : parentDirectoryMatch[0]) {
  105. const n = (parentDirectoryMatch[0].length + 1) / 3;
  106. let i = 0;
  107. const cwdParts = escapedCwd.split("/");
  108. while (i < n && parts[i + n] === cwdParts[cwdParts.length + i - n]) {
  109. result = result.slice(0, (n - i - 1) * 3) + result.slice((n - i) * 3 + parts[i + n].length + 1) || ".";
  110. i++;
  111. }
  112. const potentialRoot = path.posix.join(cwd, parentDirectoryMatch[0].slice(i * 3));
  113. if (!potentialRoot.startsWith(".") && props.root.length > potentialRoot.length) {
  114. props.root = potentialRoot;
  115. props.depthOffset = -n + i;
  116. }
  117. }
  118. if (!isIgnore && props.depthOffset >= 0) {
  119. var _props$commonPath;
  120. (_props$commonPath = props.commonPath) !== null && _props$commonPath !== void 0 || (props.commonPath = parts);
  121. const newCommonPath = [];
  122. const length = Math.min(props.commonPath.length, parts.length);
  123. for (let i = 0; i < length; i++) {
  124. const part = parts[i];
  125. if (part === "**" && !parts[i + 1]) {
  126. newCommonPath.pop();
  127. break;
  128. }
  129. if (part !== props.commonPath[i] || isDynamicPattern(part) || i === parts.length - 1) break;
  130. newCommonPath.push(part);
  131. }
  132. props.depthOffset = newCommonPath.length;
  133. props.commonPath = newCommonPath;
  134. props.root = newCommonPath.length > 0 ? path.default.posix.join(cwd, ...newCommonPath) : cwd;
  135. }
  136. return result;
  137. }
  138. function processPatterns({ patterns, ignore = [], expandDirectories = true }, cwd, props) {
  139. if (typeof patterns === "string") patterns = [patterns];
  140. else if (!patterns) patterns = ["**/*"];
  141. if (typeof ignore === "string") ignore = [ignore];
  142. const matchPatterns = [];
  143. const ignorePatterns = [];
  144. for (const pattern of ignore) {
  145. if (!pattern) continue;
  146. if (pattern[0] !== "!" || pattern[1] === "(") ignorePatterns.push(normalizePattern(pattern, expandDirectories, cwd, props, true));
  147. }
  148. for (const pattern of patterns) {
  149. if (!pattern) continue;
  150. if (pattern[0] !== "!" || pattern[1] === "(") matchPatterns.push(normalizePattern(pattern, expandDirectories, cwd, props, false));
  151. else if (pattern[1] !== "!" || pattern[2] === "(") ignorePatterns.push(normalizePattern(pattern.slice(1), expandDirectories, cwd, props, true));
  152. }
  153. return {
  154. match: matchPatterns,
  155. ignore: ignorePatterns
  156. };
  157. }
  158. function getRelativePath(path$2, cwd, root) {
  159. return path.posix.relative(cwd, `${root}/${path$2}`) || ".";
  160. }
  161. function processPath(path$2, cwd, root, isDirectory, absolute) {
  162. const relativePath = absolute ? path$2.slice(root === "/" ? 1 : root.length + 1) || "." : path$2;
  163. if (root === cwd) return isDirectory && relativePath !== "." ? relativePath.slice(0, -1) : relativePath;
  164. return getRelativePath(relativePath, cwd, root);
  165. }
  166. function formatPaths(paths, cwd, root) {
  167. for (let i = paths.length - 1; i >= 0; i--) {
  168. const path$2 = paths[i];
  169. paths[i] = getRelativePath(path$2, cwd, root) + (!path$2 || path$2.endsWith("/") ? "/" : "");
  170. }
  171. return paths;
  172. }
  173. function crawl(options, cwd, sync) {
  174. if (process.env.TINYGLOBBY_DEBUG) options.debug = true;
  175. if (options.debug) log("globbing with options:", options, "cwd:", cwd);
  176. if (Array.isArray(options.patterns) && options.patterns.length === 0) return sync ? [] : Promise.resolve([]);
  177. const props = {
  178. root: cwd,
  179. commonPath: null,
  180. depthOffset: 0
  181. };
  182. const processed = processPatterns(options, cwd, props);
  183. const nocase = options.caseSensitiveMatch === false;
  184. if (options.debug) log("internal processing patterns:", processed);
  185. const matcher = (0, picomatch.default)(processed.match, {
  186. dot: options.dot,
  187. nocase,
  188. ignore: processed.ignore
  189. });
  190. const ignore = (0, picomatch.default)(processed.ignore, {
  191. dot: options.dot,
  192. nocase
  193. });
  194. const partialMatcher = getPartialMatcher(processed.match, {
  195. dot: options.dot,
  196. nocase
  197. });
  198. const fdirOptions = {
  199. filters: [options.debug ? (p, isDirectory) => {
  200. const path$2 = processPath(p, cwd, props.root, isDirectory, options.absolute);
  201. const matches = matcher(path$2);
  202. if (matches) log(`matched ${path$2}`);
  203. return matches;
  204. } : (p, isDirectory) => matcher(processPath(p, cwd, props.root, isDirectory, options.absolute))],
  205. exclude: options.debug ? (_, p) => {
  206. const relativePath = processPath(p, cwd, props.root, true, true);
  207. const skipped = relativePath !== "." && !partialMatcher(relativePath) || ignore(relativePath);
  208. if (skipped) log(`skipped ${p}`);
  209. else log(`crawling ${p}`);
  210. return skipped;
  211. } : (_, p) => {
  212. const relativePath = processPath(p, cwd, props.root, true, true);
  213. return relativePath !== "." && !partialMatcher(relativePath) || ignore(relativePath);
  214. },
  215. pathSeparator: "/",
  216. relativePaths: true,
  217. resolveSymlinks: true
  218. };
  219. if (options.deep !== void 0) fdirOptions.maxDepth = Math.round(options.deep - props.depthOffset);
  220. if (options.absolute) {
  221. fdirOptions.relativePaths = false;
  222. fdirOptions.resolvePaths = true;
  223. fdirOptions.includeBasePath = true;
  224. }
  225. if (options.followSymbolicLinks === false) {
  226. fdirOptions.resolveSymlinks = false;
  227. fdirOptions.excludeSymlinks = true;
  228. }
  229. if (options.onlyDirectories) {
  230. fdirOptions.excludeFiles = true;
  231. fdirOptions.includeDirs = true;
  232. } else if (options.onlyFiles === false) fdirOptions.includeDirs = true;
  233. props.root = props.root.replace(BACKSLASHES, "");
  234. const root = props.root;
  235. if (options.debug) log("internal properties:", props);
  236. const api = new fdir.fdir(fdirOptions).crawl(root);
  237. if (cwd === root || options.absolute) return sync ? api.sync() : api.withPromise();
  238. return sync ? formatPaths(api.sync(), cwd, root) : api.withPromise().then((paths) => formatPaths(paths, cwd, root));
  239. }
  240. async function glob(patternsOrOptions, options) {
  241. if (patternsOrOptions && (options === null || options === void 0 ? void 0 : options.patterns)) throw new Error("Cannot pass patterns as both an argument and an option");
  242. const opts = Array.isArray(patternsOrOptions) || typeof patternsOrOptions === "string" ? {
  243. ...options,
  244. patterns: patternsOrOptions
  245. } : patternsOrOptions;
  246. const cwd = opts.cwd ? path.default.resolve(opts.cwd).replace(BACKSLASHES, "/") : process.cwd().replace(BACKSLASHES, "/");
  247. return crawl(opts, cwd, false);
  248. }
  249. function globSync(patternsOrOptions, options) {
  250. if (patternsOrOptions && (options === null || options === void 0 ? void 0 : options.patterns)) throw new Error("Cannot pass patterns as both an argument and an option");
  251. const opts = Array.isArray(patternsOrOptions) || typeof patternsOrOptions === "string" ? {
  252. ...options,
  253. patterns: patternsOrOptions
  254. } : patternsOrOptions;
  255. const cwd = opts.cwd ? path.default.resolve(opts.cwd).replace(BACKSLASHES, "/") : process.cwd().replace(BACKSLASHES, "/");
  256. return crawl(opts, cwd, true);
  257. }
  258. //#endregion
  259. exports.convertPathToPattern = convertPathToPattern;
  260. exports.escapePath = escapePath;
  261. exports.glob = glob;
  262. exports.globSync = globSync;
  263. exports.isDynamicPattern = isDynamicPattern;