resolveSilent.cjs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // NOTICE: This file is generated by Rollup. To modify it,
  2. // please instead edit the ESM counterpart and rebuild with Rollup (npm run build).
  3. 'use strict';
  4. const fs = require('node:fs');
  5. const path = require('node:path');
  6. const node_url = require('node:url');
  7. const importMetaResolve = require('@dual-bundle/import-meta-resolve');
  8. const resolveFrom = require('resolve-from');
  9. /**
  10. * TODO: These suffixes are here for commonjs compatibility reason, we should remove these codes after migrating to pure ESM, because in ESM accurate paths are required
  11. */
  12. const pathSuffixes = ['', '.js', '.json', `${path.sep}index.js`, `${path.sep}index.json`];
  13. const specifierSuffixes = ['', '.js', '.json', '/index.js', '/index.json'];
  14. /**
  15. * Checks whether the given file exists as a file.
  16. * @param {string} filename The file to check.
  17. * @returns {boolean} `true` if the file exists and is a file, otherwise `false`.
  18. */
  19. function existsFile(filename) {
  20. return fs.statSync(filename, { throwIfNoEntry: false })?.isFile() ?? false;
  21. }
  22. /**
  23. * @param {string} parent
  24. * @param {string} lookup
  25. * @returns {string | undefined}
  26. */
  27. function resolveSilent(parent, lookup) {
  28. if (path.isAbsolute(lookup)) {
  29. for (const suffix of pathSuffixes) {
  30. const filename = lookup + suffix;
  31. if (existsFile(filename)) {
  32. return filename;
  33. }
  34. }
  35. return;
  36. }
  37. const base = node_url.pathToFileURL(path.resolve(parent, 'noop.js')).toString();
  38. for (const suffix of specifierSuffixes) {
  39. try {
  40. const resolved = node_url.fileURLToPath(importMetaResolve.resolve(lookup + suffix, base));
  41. if (existsFile(resolved)) {
  42. return resolved;
  43. }
  44. } catch {
  45. //
  46. }
  47. }
  48. /**
  49. * Yarn P'n'P does not support pure ESM well by default, this is only a workaround for it
  50. * @see https://github.com/wooorm/import-meta-resolve/issues/23
  51. *
  52. * TODO: this workaround is still necessary before native `import.meta.resolve` replacement
  53. */
  54. return resolveFrom.silent(parent, lookup);
  55. }
  56. module.exports = resolveSilent;