提交学习笔记专用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

587 lines
18 KiB

  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 fs = __toESM(require("fs"));
  25. //#region src/utils.ts
  26. function cleanPath(path$1) {
  27. let normalized = (0, path.normalize)(path$1);
  28. if (normalized.length > 1 && normalized[normalized.length - 1] === path.sep) normalized = normalized.substring(0, normalized.length - 1);
  29. return normalized;
  30. }
  31. const SLASHES_REGEX = /[\\/]/g;
  32. function convertSlashes(path$1, separator) {
  33. return path$1.replace(SLASHES_REGEX, separator);
  34. }
  35. const WINDOWS_ROOT_DIR_REGEX = /^[a-z]:[\\/]$/i;
  36. function isRootDirectory(path$1) {
  37. return path$1 === "/" || WINDOWS_ROOT_DIR_REGEX.test(path$1);
  38. }
  39. function normalizePath(path$1, options) {
  40. const { resolvePaths, normalizePath: normalizePath$1, pathSeparator } = options;
  41. const pathNeedsCleaning = process.platform === "win32" && path$1.includes("/") || path$1.startsWith(".");
  42. if (resolvePaths) path$1 = (0, path.resolve)(path$1);
  43. if (normalizePath$1 || pathNeedsCleaning) path$1 = cleanPath(path$1);
  44. if (path$1 === ".") return "";
  45. const needsSeperator = path$1[path$1.length - 1] !== pathSeparator;
  46. return convertSlashes(needsSeperator ? path$1 + pathSeparator : path$1, pathSeparator);
  47. }
  48. //#endregion
  49. //#region src/api/functions/join-path.ts
  50. function joinPathWithBasePath(filename, directoryPath) {
  51. return directoryPath + filename;
  52. }
  53. function joinPathWithRelativePath(root, options) {
  54. return function(filename, directoryPath) {
  55. const sameRoot = directoryPath.startsWith(root);
  56. if (sameRoot) return directoryPath.slice(root.length) + filename;
  57. else return convertSlashes((0, path.relative)(root, directoryPath), options.pathSeparator) + options.pathSeparator + filename;
  58. };
  59. }
  60. function joinPath(filename) {
  61. return filename;
  62. }
  63. function joinDirectoryPath(filename, directoryPath, separator) {
  64. return directoryPath + filename + separator;
  65. }
  66. function build$7(root, options) {
  67. const { relativePaths, includeBasePath } = options;
  68. return relativePaths && root ? joinPathWithRelativePath(root, options) : includeBasePath ? joinPathWithBasePath : joinPath;
  69. }
  70. //#endregion
  71. //#region src/api/functions/push-directory.ts
  72. function pushDirectoryWithRelativePath(root) {
  73. return function(directoryPath, paths) {
  74. paths.push(directoryPath.substring(root.length) || ".");
  75. };
  76. }
  77. function pushDirectoryFilterWithRelativePath(root) {
  78. return function(directoryPath, paths, filters) {
  79. const relativePath = directoryPath.substring(root.length) || ".";
  80. if (filters.every((filter) => filter(relativePath, true))) paths.push(relativePath);
  81. };
  82. }
  83. const pushDirectory = (directoryPath, paths) => {
  84. paths.push(directoryPath || ".");
  85. };
  86. const pushDirectoryFilter = (directoryPath, paths, filters) => {
  87. const path$1 = directoryPath || ".";
  88. if (filters.every((filter) => filter(path$1, true))) paths.push(path$1);
  89. };
  90. const empty$2 = () => {};
  91. function build$6(root, options) {
  92. const { includeDirs, filters, relativePaths } = options;
  93. if (!includeDirs) return empty$2;
  94. if (relativePaths) return filters && filters.length ? pushDirectoryFilterWithRelativePath(root) : pushDirectoryWithRelativePath(root);
  95. return filters && filters.length ? pushDirectoryFilter : pushDirectory;
  96. }
  97. //#endregion
  98. //#region src/api/functions/push-file.ts
  99. const pushFileFilterAndCount = (filename, _paths, counts, filters) => {
  100. if (filters.every((filter) => filter(filename, false))) counts.files++;
  101. };
  102. const pushFileFilter = (filename, paths, _counts, filters) => {
  103. if (filters.every((filter) => filter(filename, false))) paths.push(filename);
  104. };
  105. const pushFileCount = (_filename, _paths, counts, _filters) => {
  106. counts.files++;
  107. };
  108. const pushFile = (filename, paths) => {
  109. paths.push(filename);
  110. };
  111. const empty$1 = () => {};
  112. function build$5(options) {
  113. const { excludeFiles, filters, onlyCounts } = options;
  114. if (excludeFiles) return empty$1;
  115. if (filters && filters.length) return onlyCounts ? pushFileFilterAndCount : pushFileFilter;
  116. else if (onlyCounts) return pushFileCount;
  117. else return pushFile;
  118. }
  119. //#endregion
  120. //#region src/api/functions/get-array.ts
  121. const getArray = (paths) => {
  122. return paths;
  123. };
  124. const getArrayGroup = () => {
  125. return [""].slice(0, 0);
  126. };
  127. function build$4(options) {
  128. return options.group ? getArrayGroup : getArray;
  129. }
  130. //#endregion
  131. //#region src/api/functions/group-files.ts
  132. const groupFiles = (groups, directory, files) => {
  133. groups.push({
  134. directory,
  135. files,
  136. dir: directory
  137. });
  138. };
  139. const empty = () => {};
  140. function build$3(options) {
  141. return options.group ? groupFiles : empty;
  142. }
  143. //#endregion
  144. //#region src/api/functions/resolve-symlink.ts
  145. const resolveSymlinksAsync = function(path$1, state, callback$1) {
  146. const { queue, fs: fs$1, options: { suppressErrors } } = state;
  147. queue.enqueue();
  148. fs$1.realpath(path$1, (error, resolvedPath) => {
  149. if (error) return queue.dequeue(suppressErrors ? null : error, state);
  150. fs$1.stat(resolvedPath, (error$1, stat) => {
  151. if (error$1) return queue.dequeue(suppressErrors ? null : error$1, state);
  152. if (stat.isDirectory() && isRecursive(path$1, resolvedPath, state)) return queue.dequeue(null, state);
  153. callback$1(stat, resolvedPath);
  154. queue.dequeue(null, state);
  155. });
  156. });
  157. };
  158. const resolveSymlinks = function(path$1, state, callback$1) {
  159. const { queue, fs: fs$1, options: { suppressErrors } } = state;
  160. queue.enqueue();
  161. try {
  162. const resolvedPath = fs$1.realpathSync(path$1);
  163. const stat = fs$1.statSync(resolvedPath);
  164. if (stat.isDirectory() && isRecursive(path$1, resolvedPath, state)) return;
  165. callback$1(stat, resolvedPath);
  166. } catch (e) {
  167. if (!suppressErrors) throw e;
  168. }
  169. };
  170. function build$2(options, isSynchronous) {
  171. if (!options.resolveSymlinks || options.excludeSymlinks) return null;
  172. return isSynchronous ? resolveSymlinks : resolveSymlinksAsync;
  173. }
  174. function isRecursive(path$1, resolved, state) {
  175. if (state.options.useRealPaths) return isRecursiveUsingRealPaths(resolved, state);
  176. let parent = (0, path.dirname)(path$1);
  177. let depth = 1;
  178. while (parent !== state.root && depth < 2) {
  179. const resolvedPath = state.symlinks.get(parent);
  180. const isSameRoot = !!resolvedPath && (resolvedPath === resolved || resolvedPath.startsWith(resolved) || resolved.startsWith(resolvedPath));
  181. if (isSameRoot) depth++;
  182. else parent = (0, path.dirname)(parent);
  183. }
  184. state.symlinks.set(path$1, resolved);
  185. return depth > 1;
  186. }
  187. function isRecursiveUsingRealPaths(resolved, state) {
  188. return state.visited.includes(resolved + state.options.pathSeparator);
  189. }
  190. //#endregion
  191. //#region src/api/functions/invoke-callback.ts
  192. const onlyCountsSync = (state) => {
  193. return state.counts;
  194. };
  195. const groupsSync = (state) => {
  196. return state.groups;
  197. };
  198. const defaultSync = (state) => {
  199. return state.paths;
  200. };
  201. const limitFilesSync = (state) => {
  202. return state.paths.slice(0, state.options.maxFiles);
  203. };
  204. const onlyCountsAsync = (state, error, callback$1) => {
  205. report(error, callback$1, state.counts, state.options.suppressErrors);
  206. return null;
  207. };
  208. const defaultAsync = (state, error, callback$1) => {
  209. report(error, callback$1, state.paths, state.options.suppressErrors);
  210. return null;
  211. };
  212. const limitFilesAsync = (state, error, callback$1) => {
  213. report(error, callback$1, state.paths.slice(0, state.options.maxFiles), state.options.suppressErrors);
  214. return null;
  215. };
  216. const groupsAsync = (state, error, callback$1) => {
  217. report(error, callback$1, state.groups, state.options.suppressErrors);
  218. return null;
  219. };
  220. function report(error, callback$1, output, suppressErrors) {
  221. if (error && !suppressErrors) callback$1(error, output);
  222. else callback$1(null, output);
  223. }
  224. function build$1(options, isSynchronous) {
  225. const { onlyCounts, group, maxFiles } = options;
  226. if (onlyCounts) return isSynchronous ? onlyCountsSync : onlyCountsAsync;
  227. else if (group) return isSynchronous ? groupsSync : groupsAsync;
  228. else if (maxFiles) return isSynchronous ? limitFilesSync : limitFilesAsync;
  229. else return isSynchronous ? defaultSync : defaultAsync;
  230. }
  231. //#endregion
  232. //#region src/api/functions/walk-directory.ts
  233. const readdirOpts = { withFileTypes: true };
  234. const walkAsync = (state, crawlPath, directoryPath, currentDepth, callback$1) => {
  235. state.queue.enqueue();
  236. if (currentDepth < 0) return state.queue.dequeue(null, state);
  237. const { fs: fs$1 } = state;
  238. state.visited.push(crawlPath);
  239. state.counts.directories++;
  240. fs$1.readdir(crawlPath || ".", readdirOpts, (error, entries = []) => {
  241. callback$1(entries, directoryPath, currentDepth);
  242. state.queue.dequeue(state.options.suppressErrors ? null : error, state);
  243. });
  244. };
  245. const walkSync = (state, crawlPath, directoryPath, currentDepth, callback$1) => {
  246. const { fs: fs$1 } = state;
  247. if (currentDepth < 0) return;
  248. state.visited.push(crawlPath);
  249. state.counts.directories++;
  250. let entries = [];
  251. try {
  252. entries = fs$1.readdirSync(crawlPath || ".", readdirOpts);
  253. } catch (e) {
  254. if (!state.options.suppressErrors) throw e;
  255. }
  256. callback$1(entries, directoryPath, currentDepth);
  257. };
  258. function build(isSynchronous) {
  259. return isSynchronous ? walkSync : walkAsync;
  260. }
  261. //#endregion
  262. //#region src/api/queue.ts
  263. /**
  264. * This is a custom stateless queue to track concurrent async fs calls.
  265. * It increments a counter whenever a call is queued and decrements it
  266. * as soon as it completes. When the counter hits 0, it calls onQueueEmpty.
  267. */
  268. var Queue = class {
  269. count = 0;
  270. constructor(onQueueEmpty) {
  271. this.onQueueEmpty = onQueueEmpty;
  272. }
  273. enqueue() {
  274. this.count++;
  275. return this.count;
  276. }
  277. dequeue(error, output) {
  278. if (this.onQueueEmpty && (--this.count <= 0 || error)) {
  279. this.onQueueEmpty(error, output);
  280. if (error) {
  281. output.controller.abort();
  282. this.onQueueEmpty = void 0;
  283. }
  284. }
  285. }
  286. };
  287. //#endregion
  288. //#region src/api/counter.ts
  289. var Counter = class {
  290. _files = 0;
  291. _directories = 0;
  292. set files(num) {
  293. this._files = num;
  294. }
  295. get files() {
  296. return this._files;
  297. }
  298. set directories(num) {
  299. this._directories = num;
  300. }
  301. get directories() {
  302. return this._directories;
  303. }
  304. /**
  305. * @deprecated use `directories` instead
  306. */
  307. /* c8 ignore next 3 */
  308. get dirs() {
  309. return this._directories;
  310. }
  311. };
  312. //#endregion
  313. //#region src/api/aborter.ts
  314. /**
  315. * AbortController is not supported on Node 14 so we use this until we can drop
  316. * support for Node 14.
  317. */
  318. var Aborter = class {
  319. aborted = false;
  320. abort() {
  321. this.aborted = true;
  322. }
  323. };
  324. //#endregion
  325. //#region src/api/walker.ts
  326. var Walker = class {
  327. root;
  328. isSynchronous;
  329. state;
  330. joinPath;
  331. pushDirectory;
  332. pushFile;
  333. getArray;
  334. groupFiles;
  335. resolveSymlink;
  336. walkDirectory;
  337. callbackInvoker;
  338. constructor(root, options, callback$1) {
  339. this.isSynchronous = !callback$1;
  340. this.callbackInvoker = build$1(options, this.isSynchronous);
  341. this.root = normalizePath(root, options);
  342. this.state = {
  343. root: isRootDirectory(this.root) ? this.root : this.root.slice(0, -1),
  344. paths: [""].slice(0, 0),
  345. groups: [],
  346. counts: new Counter(),
  347. options,
  348. queue: new Queue((error, state) => this.callbackInvoker(state, error, callback$1)),
  349. symlinks: /* @__PURE__ */ new Map(),
  350. visited: [""].slice(0, 0),
  351. controller: new Aborter(),
  352. fs: options.fs || fs
  353. };
  354. this.joinPath = build$7(this.root, options);
  355. this.pushDirectory = build$6(this.root, options);
  356. this.pushFile = build$5(options);
  357. this.getArray = build$4(options);
  358. this.groupFiles = build$3(options);
  359. this.resolveSymlink = build$2(options, this.isSynchronous);
  360. this.walkDirectory = build(this.isSynchronous);
  361. }
  362. start() {
  363. this.pushDirectory(this.root, this.state.paths, this.state.options.filters);
  364. this.walkDirectory(this.state, this.root, this.root, this.state.options.maxDepth, this.walk);
  365. return this.isSynchronous ? this.callbackInvoker(this.state, null) : null;
  366. }
  367. walk = (entries, directoryPath, depth) => {
  368. const { paths, options: { filters, resolveSymlinks: resolveSymlinks$1, excludeSymlinks, exclude, maxFiles, signal, useRealPaths, pathSeparator }, controller } = this.state;
  369. if (controller.aborted || signal && signal.aborted || maxFiles && paths.length > maxFiles) return;
  370. const files = this.getArray(this.state.paths);
  371. for (let i = 0; i < entries.length; ++i) {
  372. const entry = entries[i];
  373. if (entry.isFile() || entry.isSymbolicLink() && !resolveSymlinks$1 && !excludeSymlinks) {
  374. const filename = this.joinPath(entry.name, directoryPath);
  375. this.pushFile(filename, files, this.state.counts, filters);
  376. } else if (entry.isDirectory()) {
  377. let path$1 = joinDirectoryPath(entry.name, directoryPath, this.state.options.pathSeparator);
  378. if (exclude && exclude(entry.name, path$1)) continue;
  379. this.pushDirectory(path$1, paths, filters);
  380. this.walkDirectory(this.state, path$1, path$1, depth - 1, this.walk);
  381. } else if (this.resolveSymlink && entry.isSymbolicLink()) {
  382. let path$1 = joinPathWithBasePath(entry.name, directoryPath);
  383. this.resolveSymlink(path$1, this.state, (stat, resolvedPath) => {
  384. if (stat.isDirectory()) {
  385. resolvedPath = normalizePath(resolvedPath, this.state.options);
  386. if (exclude && exclude(entry.name, useRealPaths ? resolvedPath : path$1 + pathSeparator)) return;
  387. this.walkDirectory(this.state, resolvedPath, useRealPaths ? resolvedPath : path$1 + pathSeparator, depth - 1, this.walk);
  388. } else {
  389. resolvedPath = useRealPaths ? resolvedPath : path$1;
  390. const filename = (0, path.basename)(resolvedPath);
  391. const directoryPath$1 = normalizePath((0, path.dirname)(resolvedPath), this.state.options);
  392. resolvedPath = this.joinPath(filename, directoryPath$1);
  393. this.pushFile(resolvedPath, files, this.state.counts, filters);
  394. }
  395. });
  396. }
  397. }
  398. this.groupFiles(this.state.groups, directoryPath, files);
  399. };
  400. };
  401. //#endregion
  402. //#region src/api/async.ts
  403. function promise(root, options) {
  404. return new Promise((resolve$1, reject) => {
  405. callback(root, options, (err, output) => {
  406. if (err) return reject(err);
  407. resolve$1(output);
  408. });
  409. });
  410. }
  411. function callback(root, options, callback$1) {
  412. let walker = new Walker(root, options, callback$1);
  413. walker.start();
  414. }
  415. //#endregion
  416. //#region src/api/sync.ts
  417. function sync(root, options) {
  418. const walker = new Walker(root, options);
  419. return walker.start();
  420. }
  421. //#endregion
  422. //#region src/builder/api-builder.ts
  423. var APIBuilder = class {
  424. constructor(root, options) {
  425. this.root = root;
  426. this.options = options;
  427. }
  428. withPromise() {
  429. return promise(this.root, this.options);
  430. }
  431. withCallback(cb) {
  432. callback(this.root, this.options, cb);
  433. }
  434. sync() {
  435. return sync(this.root, this.options);
  436. }
  437. };
  438. //#endregion
  439. //#region src/builder/index.ts
  440. let pm = null;
  441. /* c8 ignore next 6 */
  442. try {
  443. require.resolve("picomatch");
  444. pm = require("picomatch");
  445. } catch {}
  446. var Builder = class {
  447. globCache = {};
  448. options = {
  449. maxDepth: Infinity,
  450. suppressErrors: true,
  451. pathSeparator: path.sep,
  452. filters: []
  453. };
  454. globFunction;
  455. constructor(options) {
  456. this.options = {
  457. ...this.options,
  458. ...options
  459. };
  460. this.globFunction = this.options.globFunction;
  461. }
  462. group() {
  463. this.options.group = true;
  464. return this;
  465. }
  466. withPathSeparator(separator) {
  467. this.options.pathSeparator = separator;
  468. return this;
  469. }
  470. withBasePath() {
  471. this.options.includeBasePath = true;
  472. return this;
  473. }
  474. withRelativePaths() {
  475. this.options.relativePaths = true;
  476. return this;
  477. }
  478. withDirs() {
  479. this.options.includeDirs = true;
  480. return this;
  481. }
  482. withMaxDepth(depth) {
  483. this.options.maxDepth = depth;
  484. return this;
  485. }
  486. withMaxFiles(limit) {
  487. this.options.maxFiles = limit;
  488. return this;
  489. }
  490. withFullPaths() {
  491. this.options.resolvePaths = true;
  492. this.options.includeBasePath = true;
  493. return this;
  494. }
  495. withErrors() {
  496. this.options.suppressErrors = false;
  497. return this;
  498. }
  499. withSymlinks({ resolvePaths = true } = {}) {
  500. this.options.resolveSymlinks = true;
  501. this.options.useRealPaths = resolvePaths;
  502. return this.withFullPaths();
  503. }
  504. withAbortSignal(signal) {
  505. this.options.signal = signal;
  506. return this;
  507. }
  508. normalize() {
  509. this.options.normalizePath = true;
  510. return this;
  511. }
  512. filter(predicate) {
  513. this.options.filters.push(predicate);
  514. return this;
  515. }
  516. onlyDirs() {
  517. this.options.excludeFiles = true;
  518. this.options.includeDirs = true;
  519. return this;
  520. }
  521. exclude(predicate) {
  522. this.options.exclude = predicate;
  523. return this;
  524. }
  525. onlyCounts() {
  526. this.options.onlyCounts = true;
  527. return this;
  528. }
  529. crawl(root) {
  530. return new APIBuilder(root || ".", this.options);
  531. }
  532. withGlobFunction(fn) {
  533. this.globFunction = fn;
  534. return this;
  535. }
  536. /**
  537. * @deprecated Pass options using the constructor instead:
  538. * ```ts
  539. * new fdir(options).crawl("/path/to/root");
  540. * ```
  541. * This method will be removed in v7.0
  542. */
  543. /* c8 ignore next 4 */
  544. crawlWithOptions(root, options) {
  545. this.options = {
  546. ...this.options,
  547. ...options
  548. };
  549. return new APIBuilder(root || ".", this.options);
  550. }
  551. glob(...patterns) {
  552. if (this.globFunction) return this.globWithOptions(patterns);
  553. return this.globWithOptions(patterns, ...[{ dot: true }]);
  554. }
  555. globWithOptions(patterns, ...options) {
  556. const globFn = this.globFunction || pm;
  557. /* c8 ignore next 5 */
  558. if (!globFn) throw new Error("Please specify a glob function to use glob matching.");
  559. var isMatch = this.globCache[patterns.join("\0")];
  560. if (!isMatch) {
  561. isMatch = globFn(patterns, ...options);
  562. this.globCache[patterns.join("\0")] = isMatch;
  563. }
  564. this.options.filters.push((path$1) => isMatch(path$1));
  565. return this;
  566. }
  567. };
  568. //#endregion
  569. exports.fdir = Builder;