index.mjs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. import path, { dirname, win32, join } from 'node:path';
  2. import fs, { promises } from 'node:fs';
  3. import fsp from 'node:fs/promises';
  4. import process from 'node:process';
  5. import { interopDefault, resolvePathSync } from 'mlly';
  6. import { fileURLToPath } from 'node:url';
  7. /*
  8. How it works:
  9. `this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value.
  10. */
  11. class Node {
  12. value;
  13. next;
  14. constructor(value) {
  15. this.value = value;
  16. }
  17. }
  18. class Queue {
  19. #head;
  20. #tail;
  21. #size;
  22. constructor() {
  23. this.clear();
  24. }
  25. enqueue(value) {
  26. const node = new Node(value);
  27. if (this.#head) {
  28. this.#tail.next = node;
  29. this.#tail = node;
  30. } else {
  31. this.#head = node;
  32. this.#tail = node;
  33. }
  34. this.#size++;
  35. }
  36. dequeue() {
  37. const current = this.#head;
  38. if (!current) {
  39. return;
  40. }
  41. this.#head = this.#head.next;
  42. this.#size--;
  43. return current.value;
  44. }
  45. clear() {
  46. this.#head = undefined;
  47. this.#tail = undefined;
  48. this.#size = 0;
  49. }
  50. get size() {
  51. return this.#size;
  52. }
  53. * [Symbol.iterator]() {
  54. let current = this.#head;
  55. while (current) {
  56. yield current.value;
  57. current = current.next;
  58. }
  59. }
  60. }
  61. function pLimit(concurrency) {
  62. if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {
  63. throw new TypeError('Expected `concurrency` to be a number from 1 and up');
  64. }
  65. const queue = new Queue();
  66. let activeCount = 0;
  67. const next = () => {
  68. activeCount--;
  69. if (queue.size > 0) {
  70. queue.dequeue()();
  71. }
  72. };
  73. const run = async (fn, resolve, args) => {
  74. activeCount++;
  75. const result = (async () => fn(...args))();
  76. resolve(result);
  77. try {
  78. await result;
  79. } catch {}
  80. next();
  81. };
  82. const enqueue = (fn, resolve, args) => {
  83. queue.enqueue(run.bind(undefined, fn, resolve, args));
  84. (async () => {
  85. // This function needs to wait until the next microtask before comparing
  86. // `activeCount` to `concurrency`, because `activeCount` is updated asynchronously
  87. // when the run function is dequeued and called. The comparison in the if-statement
  88. // needs to happen asynchronously as well to get an up-to-date value for `activeCount`.
  89. await Promise.resolve();
  90. if (activeCount < concurrency && queue.size > 0) {
  91. queue.dequeue()();
  92. }
  93. })();
  94. };
  95. const generator = (fn, ...args) => new Promise(resolve => {
  96. enqueue(fn, resolve, args);
  97. });
  98. Object.defineProperties(generator, {
  99. activeCount: {
  100. get: () => activeCount,
  101. },
  102. pendingCount: {
  103. get: () => queue.size,
  104. },
  105. clearQueue: {
  106. value: () => {
  107. queue.clear();
  108. },
  109. },
  110. });
  111. return generator;
  112. }
  113. class EndError extends Error {
  114. constructor(value) {
  115. super();
  116. this.value = value;
  117. }
  118. }
  119. // The input can also be a promise, so we await it.
  120. const testElement = async (element, tester) => tester(await element);
  121. // The input can also be a promise, so we `Promise.all()` them both.
  122. const finder = async element => {
  123. const values = await Promise.all(element);
  124. if (values[1] === true) {
  125. throw new EndError(values[0]);
  126. }
  127. return false;
  128. };
  129. async function pLocate(
  130. iterable,
  131. tester,
  132. {
  133. concurrency = Number.POSITIVE_INFINITY,
  134. preserveOrder = true,
  135. } = {},
  136. ) {
  137. const limit = pLimit(concurrency);
  138. // Start all the promises concurrently with optional limit.
  139. const items = [...iterable].map(element => [element, limit(testElement, element, tester)]);
  140. // Check the promises either serially or concurrently.
  141. const checkLimit = pLimit(preserveOrder ? 1 : Number.POSITIVE_INFINITY);
  142. try {
  143. await Promise.all(items.map(element => checkLimit(finder, element)));
  144. } catch (error) {
  145. if (error instanceof EndError) {
  146. return error.value;
  147. }
  148. throw error;
  149. }
  150. }
  151. const typeMappings = {
  152. directory: 'isDirectory',
  153. file: 'isFile',
  154. };
  155. function checkType(type) {
  156. if (Object.hasOwnProperty.call(typeMappings, type)) {
  157. return;
  158. }
  159. throw new Error(`Invalid type specified: ${type}`);
  160. }
  161. const matchType = (type, stat) => stat[typeMappings[type]]();
  162. const toPath$1 = urlOrPath => urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath;
  163. async function locatePath(
  164. paths,
  165. {
  166. cwd = process.cwd(),
  167. type = 'file',
  168. allowSymlinks = true,
  169. concurrency,
  170. preserveOrder,
  171. } = {},
  172. ) {
  173. checkType(type);
  174. cwd = toPath$1(cwd);
  175. const statFunction = allowSymlinks ? promises.stat : promises.lstat;
  176. return pLocate(paths, async path_ => {
  177. try {
  178. const stat = await statFunction(path.resolve(cwd, path_));
  179. return matchType(type, stat);
  180. } catch {
  181. return false;
  182. }
  183. }, {concurrency, preserveOrder});
  184. }
  185. const toPath = urlOrPath => urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath;
  186. const findUpStop = Symbol('findUpStop');
  187. async function findUpMultiple(name, options = {}) {
  188. let directory = path.resolve(toPath(options.cwd) || '');
  189. const {root} = path.parse(directory);
  190. const stopAt = path.resolve(directory, options.stopAt || root);
  191. const limit = options.limit || Number.POSITIVE_INFINITY;
  192. const paths = [name].flat();
  193. const runMatcher = async locateOptions => {
  194. if (typeof name !== 'function') {
  195. return locatePath(paths, locateOptions);
  196. }
  197. const foundPath = await name(locateOptions.cwd);
  198. if (typeof foundPath === 'string') {
  199. return locatePath([foundPath], locateOptions);
  200. }
  201. return foundPath;
  202. };
  203. const matches = [];
  204. // eslint-disable-next-line no-constant-condition
  205. while (true) {
  206. // eslint-disable-next-line no-await-in-loop
  207. const foundPath = await runMatcher({...options, cwd: directory});
  208. if (foundPath === findUpStop) {
  209. break;
  210. }
  211. if (foundPath) {
  212. matches.push(path.resolve(directory, foundPath));
  213. }
  214. if (directory === stopAt || matches.length >= limit) {
  215. break;
  216. }
  217. directory = path.dirname(directory);
  218. }
  219. return matches;
  220. }
  221. async function findUp(name, options = {}) {
  222. const matches = await findUpMultiple(name, {...options, limit: 1});
  223. return matches[0];
  224. }
  225. function _resolve(path, options = {}) {
  226. if (options.platform === "auto" || !options.platform)
  227. options.platform = process.platform === "win32" ? "win32" : "posix";
  228. const modulePath = resolvePathSync(path, {
  229. url: options.paths
  230. });
  231. if (options.platform === "win32")
  232. return win32.normalize(modulePath);
  233. return modulePath;
  234. }
  235. function resolveModule(name, options = {}) {
  236. try {
  237. return _resolve(name, options);
  238. } catch (e) {
  239. return void 0;
  240. }
  241. }
  242. async function importModule(path) {
  243. const i = await import(path);
  244. if (i)
  245. return interopDefault(i);
  246. return i;
  247. }
  248. function isPackageExists(name, options = {}) {
  249. return !!resolvePackage(name, options);
  250. }
  251. function getPackageJsonPath(name, options = {}) {
  252. const entry = resolvePackage(name, options);
  253. if (!entry)
  254. return;
  255. return searchPackageJSON(entry);
  256. }
  257. async function getPackageInfo(name, options = {}) {
  258. const packageJsonPath = getPackageJsonPath(name, options);
  259. if (!packageJsonPath)
  260. return;
  261. const packageJson = JSON.parse(await fs.promises.readFile(packageJsonPath, "utf8"));
  262. return {
  263. name,
  264. version: packageJson.version,
  265. rootPath: dirname(packageJsonPath),
  266. packageJsonPath,
  267. packageJson
  268. };
  269. }
  270. function getPackageInfoSync(name, options = {}) {
  271. const packageJsonPath = getPackageJsonPath(name, options);
  272. if (!packageJsonPath)
  273. return;
  274. const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
  275. return {
  276. name,
  277. version: packageJson.version,
  278. rootPath: dirname(packageJsonPath),
  279. packageJsonPath,
  280. packageJson
  281. };
  282. }
  283. function resolvePackage(name, options = {}) {
  284. try {
  285. return _resolve(`${name}/package.json`, options);
  286. } catch {
  287. }
  288. try {
  289. return _resolve(name, options);
  290. } catch (e) {
  291. if (e.code !== "MODULE_NOT_FOUND" && e.code !== "ERR_MODULE_NOT_FOUND")
  292. console.error(e);
  293. return false;
  294. }
  295. }
  296. function searchPackageJSON(dir) {
  297. let packageJsonPath;
  298. while (true) {
  299. if (!dir)
  300. return;
  301. const newDir = dirname(dir);
  302. if (newDir === dir)
  303. return;
  304. dir = newDir;
  305. packageJsonPath = join(dir, "package.json");
  306. if (fs.existsSync(packageJsonPath))
  307. break;
  308. }
  309. return packageJsonPath;
  310. }
  311. async function loadPackageJSON(cwd = process.cwd()) {
  312. const path = await findUp("package.json", { cwd });
  313. if (!path || !fs.existsSync(path))
  314. return null;
  315. return JSON.parse(await fsp.readFile(path, "utf-8"));
  316. }
  317. async function isPackageListed(name, cwd) {
  318. const pkg = await loadPackageJSON(cwd) || {};
  319. return name in (pkg.dependencies || {}) || name in (pkg.devDependencies || {});
  320. }
  321. export { getPackageInfo, getPackageInfoSync, importModule, isPackageExists, isPackageListed, loadPackageJSON, resolveModule };