index.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /**
  2. * @typedef {import('./lib/errors.js').ErrnoException} ErrnoException
  3. */
  4. import {defaultResolve} from './lib/resolve.js'
  5. export {moduleResolve} from './lib/resolve.js'
  6. /**
  7. * Match `import.meta.resolve` except that `parent` is required (you can pass
  8. * `import.meta.url`).
  9. *
  10. * @param {string} specifier
  11. * The module specifier to resolve relative to parent
  12. * (`/example.js`, `./example.js`, `../example.js`, `some-package`, `fs`,
  13. * etc).
  14. * @param {string} parent
  15. * The absolute parent module URL to resolve from.
  16. * You must pass `import.meta.url` or something else.
  17. * @returns {string}
  18. * Returns a string to a full `file:`, `data:`, or `node:` URL
  19. * to the found thing.
  20. */
  21. export function resolve(specifier, parent) {
  22. if (!parent) {
  23. throw new Error(
  24. 'Please pass `parent`: `import-meta-resolve` cannot ponyfill that'
  25. )
  26. }
  27. try {
  28. return defaultResolve(specifier, {parentURL: parent}).url
  29. } catch (error) {
  30. // See: <https://github.com/nodejs/node/blob/45f5c9b/lib/internal/modules/esm/initialize_import_meta.js#L34>
  31. const exception = /** @type {ErrnoException} */ (error)
  32. if (
  33. (exception.code === 'ERR_UNSUPPORTED_DIR_IMPORT' ||
  34. exception.code === 'ERR_MODULE_NOT_FOUND') &&
  35. typeof exception.url === 'string'
  36. ) {
  37. return exception.url
  38. }
  39. throw error
  40. }
  41. }