fs.mjs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import { promises } from 'fs';
  2. import { importModule } from 'local-pkg';
  3. import { tryInstallPkg } from './install-pkg.mjs';
  4. import { resolvePath } from 'mlly';
  5. import '@antfu/install-pkg';
  6. import '@antfu/utils';
  7. import 'kolorist';
  8. import './warn.mjs';
  9. const _collections = /* @__PURE__ */ Object.create(null);
  10. const isLegacyExists = /* @__PURE__ */ Object.create(null);
  11. async function loadCollectionFromFS(name, autoInstall = false, scope = "@iconify-json", cwd = process.cwd()) {
  12. const cache = _collections[cwd] || (_collections[cwd] = /* @__PURE__ */ Object.create(null));
  13. if (!await cache[name]) {
  14. cache[name] = task();
  15. }
  16. return cache[name];
  17. async function task() {
  18. const packageName = scope.length === 0 ? name : `${scope}/${name}`;
  19. let jsonPath = await resolvePath(`${packageName}/icons.json`, {
  20. url: cwd
  21. }).catch(() => void 0);
  22. if (scope === "@iconify-json") {
  23. if (isLegacyExists[cwd] === void 0) {
  24. const testResult = await resolvePath(
  25. `@iconify/json/collections.json`,
  26. {
  27. url: cwd
  28. }
  29. ).catch(() => void 0);
  30. isLegacyExists[cwd] = !!testResult;
  31. }
  32. const checkLegacy = isLegacyExists[cwd];
  33. if (!jsonPath && checkLegacy) {
  34. jsonPath = await resolvePath(
  35. `@iconify/json/json/${name}.json`,
  36. {
  37. url: cwd
  38. }
  39. ).catch(() => void 0);
  40. }
  41. if (!jsonPath && !checkLegacy && autoInstall) {
  42. await tryInstallPkg(packageName, autoInstall);
  43. jsonPath = await resolvePath(`${packageName}/icons.json`, {
  44. url: cwd
  45. }).catch(() => void 0);
  46. }
  47. } else if (!jsonPath && autoInstall) {
  48. await tryInstallPkg(packageName, autoInstall);
  49. jsonPath = await resolvePath(`${packageName}/icons.json`, {
  50. url: cwd
  51. }).catch(() => void 0);
  52. }
  53. if (!jsonPath) {
  54. let packagePath = await resolvePath(packageName, {
  55. url: cwd
  56. }).catch(() => void 0);
  57. if (packagePath?.match(/^[a-z]:/i)) {
  58. packagePath = `file:///${packagePath}`.replace(/\\/g, "/");
  59. }
  60. if (packagePath) {
  61. const { icons } = await importModule(
  62. packagePath
  63. );
  64. if (icons)
  65. return icons;
  66. }
  67. }
  68. let stat;
  69. try {
  70. stat = jsonPath ? await promises.lstat(jsonPath) : void 0;
  71. } catch (err) {
  72. return void 0;
  73. }
  74. if (stat?.isFile()) {
  75. return JSON.parse(
  76. await promises.readFile(jsonPath, "utf8")
  77. );
  78. } else {
  79. return void 0;
  80. }
  81. }
  82. }
  83. export { loadCollectionFromFS };