index.cjs 13 KB

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