index.cjs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
  2. //#region \0rolldown/runtime.js
  3. var __create = Object.create;
  4. var __defProp = Object.defineProperty;
  5. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  6. var __getOwnPropNames = Object.getOwnPropertyNames;
  7. var __getProtoOf = Object.getPrototypeOf;
  8. var __hasOwnProp = Object.prototype.hasOwnProperty;
  9. var __copyProps = (to, from, except, desc) => {
  10. if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
  11. key = keys[i];
  12. if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
  13. get: ((k) => from[k]).bind(null, key),
  14. enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
  15. });
  16. }
  17. return to;
  18. };
  19. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
  20. value: mod,
  21. enumerable: true
  22. }) : target, mod));
  23. //#endregion
  24. let fs = require("fs");
  25. let path = require("path");
  26. let url = require("url");
  27. let fdir = require("fdir");
  28. let picomatch = require("picomatch");
  29. picomatch = __toESM(picomatch, 1);
  30. //#region src/utils.ts
  31. const isReadonlyArray = Array.isArray;
  32. const BACKSLASHES = /\\/g;
  33. const DRIVE_RELATIVE_PATH = /^[A-Za-z]:$/;
  34. const isWin = process.platform === "win32";
  35. const ONLY_PARENT_DIRECTORIES = /^(\/?\.\.)+$/;
  36. function getPartialMatcher(patterns, options = {}) {
  37. const patternsCount = patterns.length;
  38. const patternsParts = Array(patternsCount);
  39. const matchers = Array(patternsCount);
  40. let i, j;
  41. for (i = 0; i < patternsCount; i++) {
  42. const parts = splitPattern(patterns[i]);
  43. patternsParts[i] = parts;
  44. const partsCount = parts.length;
  45. const partMatchers = Array(partsCount);
  46. for (j = 0; j < partsCount; j++) partMatchers[j] = (0, picomatch.default)(parts[j], options);
  47. matchers[i] = partMatchers;
  48. }
  49. return (input) => {
  50. const inputParts = input.split("/");
  51. if (inputParts[0] === ".." && ONLY_PARENT_DIRECTORIES.test(input)) return true;
  52. for (i = 0; i < patternsCount; i++) {
  53. const patternParts = patternsParts[i];
  54. const matcher = matchers[i];
  55. const inputPatternCount = inputParts.length;
  56. const minParts = Math.min(inputPatternCount, patternParts.length);
  57. j = 0;
  58. while (j < minParts) {
  59. const part = patternParts[j];
  60. if (part.includes("/")) return true;
  61. if (!matcher[j](inputParts[j])) break;
  62. if (!options.noglobstar && part === "**") return true;
  63. j++;
  64. }
  65. if (j === inputPatternCount) return true;
  66. }
  67. return false;
  68. };
  69. }
  70. /* node:coverage ignore next 2 */
  71. const WIN32_ROOT_DIR = /^[A-Z]:\/$/i;
  72. const isRoot = isWin ? (p) => WIN32_ROOT_DIR.test(p) : (p) => p === "/";
  73. function buildFormat(cwd, root, absolute) {
  74. if (cwd === root || root.startsWith(`${cwd}/`)) {
  75. if (absolute) {
  76. const start = cwd.length + +!isRoot(cwd);
  77. return (p, isDir) => p.slice(start, isDir ? -1 : void 0) || ".";
  78. }
  79. const prefix = root.slice(cwd.length + 1);
  80. if (prefix) return (p, isDir) => {
  81. if (p === ".") return prefix;
  82. const result = `${prefix}/${p}`;
  83. return isDir ? result.slice(0, -1) : result;
  84. };
  85. return (p, isDir) => isDir && p !== "." ? p.slice(0, -1) : p;
  86. }
  87. if (absolute) return (p) => path.posix.relative(cwd, p) || ".";
  88. return (p) => path.posix.relative(cwd, `${root}/${p}`) || ".";
  89. }
  90. function buildRelative(cwd, root) {
  91. if (root.startsWith(`${cwd}/`)) {
  92. const prefix = root.slice(cwd.length + 1);
  93. return (p) => `${prefix}/${p}`;
  94. }
  95. return (p) => {
  96. const result = path.posix.relative(cwd, `${root}/${p}`);
  97. return p[p.length - 1] === "/" && result !== "" ? `${result}/` : result || ".";
  98. };
  99. }
  100. function ensureNonDriveRelativePath(path$1) {
  101. return path$1.replace(DRIVE_RELATIVE_PATH, (match) => `${match}/`);
  102. }
  103. const splitPatternOptions = { parts: true };
  104. function splitPattern(path$2) {
  105. var _result$parts;
  106. const result = picomatch.default.scan(path$2, splitPatternOptions);
  107. return ((_result$parts = result.parts) === null || _result$parts === void 0 ? void 0 : _result$parts.length) ? result.parts : [path$2];
  108. }
  109. const ESCAPED_WIN32_BACKSLASHES = /\\(?![()[\]{}!+@])/g;
  110. function convertPosixPathToPattern(path$3) {
  111. return escapePosixPath(path$3);
  112. }
  113. function convertWin32PathToPattern(path$4) {
  114. return escapeWin32Path(path$4).replace(ESCAPED_WIN32_BACKSLASHES, "/");
  115. }
  116. /**
  117. * Converts a path to a pattern depending on the platform.
  118. * Identical to {@link escapePath} on POSIX systems.
  119. * @see {@link https://superchupu.dev/tinyglobby/documentation#convertPathToPattern}
  120. */
  121. /* node:coverage ignore next 3 */
  122. const convertPathToPattern = isWin ? convertWin32PathToPattern : convertPosixPathToPattern;
  123. const POSIX_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g;
  124. const WIN32_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g;
  125. const escapePosixPath = (path$5) => path$5.replace(POSIX_UNESCAPED_GLOB_SYMBOLS, "\\$&");
  126. const escapeWin32Path = (path$6) => path$6.replace(WIN32_UNESCAPED_GLOB_SYMBOLS, "\\$&");
  127. /**
  128. * Escapes a path's special characters depending on the platform.
  129. * @see {@link https://superchupu.dev/tinyglobby/documentation#escapePath}
  130. */
  131. /* node:coverage ignore next */
  132. const escapePath = isWin ? escapeWin32Path : escapePosixPath;
  133. /**
  134. * Checks if a pattern has dynamic parts.
  135. *
  136. * Has a few minor differences with [`fast-glob`](https://github.com/mrmlnc/fast-glob) for better accuracy:
  137. *
  138. * - Doesn't necessarily return `false` on patterns that include `\`.
  139. * - Returns `true` if the pattern includes parentheses, regardless of them representing one single pattern or not.
  140. * - Returns `true` for unfinished glob extensions i.e. `(h`, `+(h`.
  141. * - Returns `true` for unfinished brace expansions as long as they include `,` or `..`.
  142. *
  143. * @see {@link https://superchupu.dev/tinyglobby/documentation#isDynamicPattern}
  144. */
  145. function isDynamicPattern(pattern, options) {
  146. if ((options === null || options === void 0 ? void 0 : options.caseSensitiveMatch) === false) return true;
  147. const scan = picomatch.default.scan(pattern);
  148. return scan.isGlob || scan.negated;
  149. }
  150. function log(...tasks) {
  151. console.log(`[tinyglobby ${(/* @__PURE__ */ new Date()).toLocaleTimeString("es")}]`, ...tasks);
  152. }
  153. function ensureStringArray(value) {
  154. return typeof value === "string" ? [value] : value !== null && value !== void 0 ? value : [];
  155. }
  156. //#endregion
  157. //#region src/patterns.ts
  158. const PARENT_DIRECTORY = /^(\/?\.\.)+/;
  159. const ESCAPING_BACKSLASHES = /\\(?=[()[\]{}!*+?@|])/g;
  160. function normalizePattern(pattern, opts, props, isIgnore) {
  161. var _PARENT_DIRECTORY$exe;
  162. const cwd = opts.cwd;
  163. let result = pattern;
  164. if (pattern[pattern.length - 1] === "/") result = pattern.slice(0, -1);
  165. if (result[result.length - 1] !== "*" && opts.expandDirectories) result += "/**";
  166. const escapedCwd = escapePath(cwd);
  167. result = (0, path.isAbsolute)(result.replace(ESCAPING_BACKSLASHES, "")) ? path.posix.relative(escapedCwd, result) : path.posix.normalize(result);
  168. const parentDir = (_PARENT_DIRECTORY$exe = PARENT_DIRECTORY.exec(result)) === null || _PARENT_DIRECTORY$exe === void 0 ? void 0 : _PARENT_DIRECTORY$exe[0];
  169. const parts = splitPattern(result);
  170. if (parentDir) {
  171. const n = (parentDir.length + 1) / 3;
  172. let i = 0;
  173. const cwdParts = escapedCwd.split("/");
  174. while (i < n && parts[i + n] === cwdParts[cwdParts.length + i - n]) {
  175. result = result.slice(0, (n - i - 1) * 3) + result.slice((n - i) * 3 + parts[i + n].length + 1) || ".";
  176. i++;
  177. }
  178. const potentialRoot = path.posix.join(cwd, parentDir.slice(i * 3));
  179. if (potentialRoot[0] !== "." && props.root.length > potentialRoot.length) {
  180. props.root = ensureNonDriveRelativePath(potentialRoot);
  181. props.depthOffset = -n + i;
  182. }
  183. }
  184. if (!isIgnore && props.depthOffset >= 0) {
  185. var _props$commonPath;
  186. (_props$commonPath = props.commonPath) !== null && _props$commonPath !== void 0 || (props.commonPath = parts);
  187. const newCommonPath = [];
  188. const length = Math.min(props.commonPath.length, parts.length);
  189. for (let i = 0; i < length; i++) {
  190. const part = parts[i];
  191. if (part === "**" && !parts[i + 1]) {
  192. newCommonPath.pop();
  193. break;
  194. }
  195. if (i === parts.length - 1 || part !== props.commonPath[i] || isDynamicPattern(part)) break;
  196. newCommonPath.push(part);
  197. }
  198. props.depthOffset = newCommonPath.length;
  199. props.commonPath = newCommonPath;
  200. props.root = ensureNonDriveRelativePath(newCommonPath.length > 0 ? path.posix.join(cwd, ...newCommonPath) : cwd);
  201. }
  202. return result;
  203. }
  204. function processPatterns(options, patterns, props) {
  205. const matchPatterns = [];
  206. const ignorePatterns = [];
  207. for (const pattern of options.ignore) {
  208. if (!pattern) continue;
  209. if (pattern[0] !== "!" || pattern[1] === "(") ignorePatterns.push(normalizePattern(pattern, options, props, true));
  210. }
  211. for (const pattern of patterns) {
  212. if (!pattern) continue;
  213. if (pattern[0] !== "!" || pattern[1] === "(") matchPatterns.push(normalizePattern(pattern, options, props, false));
  214. else if (pattern[1] !== "!" || pattern[2] === "(") ignorePatterns.push(normalizePattern(pattern.slice(1), options, props, true));
  215. }
  216. return {
  217. match: matchPatterns,
  218. ignore: ignorePatterns
  219. };
  220. }
  221. //#endregion
  222. //#region src/crawler.ts
  223. function buildCrawler(options, patterns) {
  224. const cwd = options.cwd;
  225. const props = {
  226. root: cwd,
  227. depthOffset: 0
  228. };
  229. const processed = processPatterns(options, patterns, props);
  230. if (options.debug) log("internal processing patterns:", processed);
  231. const { absolute, caseSensitiveMatch, debug, dot, followSymbolicLinks, onlyDirectories } = options;
  232. const root = props.root.replace(BACKSLASHES, "");
  233. const matchOptions = {
  234. dot,
  235. nobrace: options.braceExpansion === false,
  236. nocase: !caseSensitiveMatch,
  237. noextglob: options.extglob === false,
  238. noglobstar: options.globstar === false,
  239. posix: true
  240. };
  241. const matcher = (0, picomatch.default)(processed.match, matchOptions);
  242. const ignore = (0, picomatch.default)(processed.ignore, matchOptions);
  243. const partialMatcher = getPartialMatcher(processed.match, matchOptions);
  244. const format = buildFormat(cwd, root, absolute);
  245. const excludeFormatter = absolute ? format : buildFormat(cwd, root, true);
  246. const excludePredicate = (_, p) => {
  247. const relativePath = excludeFormatter(p, true);
  248. return relativePath !== "." && !partialMatcher(relativePath) || ignore(relativePath);
  249. };
  250. let maxDepth;
  251. if (options.deep !== void 0) maxDepth = Math.round(options.deep - props.depthOffset);
  252. const crawler = new fdir.fdir({
  253. filters: [debug ? (p, isDirectory) => {
  254. const path = format(p, isDirectory);
  255. const matches = matcher(path) && !ignore(path);
  256. if (matches) log(`matched ${path}`);
  257. return matches;
  258. } : (p, isDirectory) => {
  259. const path = format(p, isDirectory);
  260. return matcher(path) && !ignore(path);
  261. }],
  262. exclude: debug ? (_, p) => {
  263. const skipped = excludePredicate(_, p);
  264. log(`${skipped ? "skipped" : "crawling"} ${p}`);
  265. return skipped;
  266. } : excludePredicate,
  267. fs: options.fs,
  268. pathSeparator: "/",
  269. relativePaths: !absolute,
  270. resolvePaths: absolute,
  271. includeBasePath: absolute,
  272. resolveSymlinks: followSymbolicLinks,
  273. excludeSymlinks: !followSymbolicLinks,
  274. excludeFiles: onlyDirectories,
  275. includeDirs: onlyDirectories || !options.onlyFiles,
  276. maxDepth,
  277. signal: options.signal
  278. }).crawl(root);
  279. if (options.debug) log("internal properties:", {
  280. ...props,
  281. root
  282. });
  283. return [crawler, cwd !== root && !absolute && buildRelative(cwd, root)];
  284. }
  285. //#endregion
  286. //#region src/index.ts
  287. function formatPaths(paths, mapper) {
  288. if (mapper) for (let i = paths.length - 1; i >= 0; i--) paths[i] = mapper(paths[i]);
  289. return paths;
  290. }
  291. const defaultOptions = {
  292. caseSensitiveMatch: true,
  293. debug: !!process.env.TINYGLOBBY_DEBUG,
  294. expandDirectories: true,
  295. followSymbolicLinks: true,
  296. onlyFiles: true
  297. };
  298. function getOptions(options) {
  299. const opts = Object.assign({}, options);
  300. for (const key in defaultOptions) if (opts[key] === void 0) Object.assign(opts, { [key]: defaultOptions[key] });
  301. opts.cwd = (opts.cwd instanceof URL ? (0, url.fileURLToPath)(opts.cwd) : (0, path.resolve)(opts.cwd || process.cwd())).replace(BACKSLASHES, "/");
  302. opts.ignore = ensureStringArray(opts.ignore);
  303. opts.fs && (opts.fs = {
  304. readdir: opts.fs.readdir || fs.readdir,
  305. readdirSync: opts.fs.readdirSync || fs.readdirSync,
  306. realpath: opts.fs.realpath || fs.realpath,
  307. realpathSync: opts.fs.realpathSync || fs.realpathSync,
  308. stat: opts.fs.stat || fs.stat,
  309. statSync: opts.fs.statSync || fs.statSync
  310. });
  311. if (opts.debug) log("globbing with options:", opts);
  312. return opts;
  313. }
  314. function getCrawler(globInput, inputOptions = {}) {
  315. var _ref;
  316. if (globInput && (inputOptions === null || inputOptions === void 0 ? void 0 : inputOptions.patterns)) throw new Error("Cannot pass patterns as both an argument and an option");
  317. const isModern = isReadonlyArray(globInput) || typeof globInput === "string";
  318. const patterns = ensureStringArray((_ref = isModern ? globInput : globInput.patterns) !== null && _ref !== void 0 ? _ref : "**/*");
  319. const options = getOptions(isModern ? inputOptions : globInput);
  320. return patterns.length > 0 ? buildCrawler(options, patterns) : [];
  321. }
  322. async function glob(globInput, options) {
  323. const [crawler, relative] = getCrawler(globInput, options);
  324. return crawler ? formatPaths(await crawler.withPromise(), relative) : [];
  325. }
  326. function globSync(globInput, options) {
  327. const [crawler, relative] = getCrawler(globInput, options);
  328. return crawler ? formatPaths(crawler.sync(), relative) : [];
  329. }
  330. //#endregion
  331. exports.convertPathToPattern = convertPathToPattern;
  332. exports.escapePath = escapePath;
  333. exports.glob = glob;
  334. exports.globSync = globSync;
  335. exports.isDynamicPattern = isDynamicPattern;