diff --git a/doc/api/esm.md b/doc/api/esm.md index 56691d0622ed3a..44f0d155bc3493 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -960,17 +960,33 @@ export function getFormat(url, context, defaultGetFormat) { return defaultGetFormat(url, context, defaultGetFormat); } -export function transformSource(source, context, defaultTransformSource) { - const { url, format } = context; - - if (extensionsRegex.test(url)) { - return { - source: CoffeeScript.compile(source, { bare: true }) - }; - } - - // Let Node.js handle all other sources. - return defaultTransformSource(source, context, defaultTransformSource); +async function getPackageType(url) { + // `url` is only a file path during the first iteration when passed the + // resolved url from the load() hook + // an actual file path from load() will contain a file extension as it's + // required by the spec + // this simple truthy check for whether `url` contains a file extension will + // work for most projects but does not cover some edge-cases (such as + // extension-less files or a url ending in a trailing space) + const isFilePath = !!extname(url); + // If it is a file path, get the directory it's in + const dir = isFilePath ? + dirname(fileURLToPath(url)) : + url; + // Compose a file path to a package.json in the same directory, + // which may or may not exist + const packagePath = resolvePath(dir, 'package.json'); + // Try to read the possibly nonexistent package.json + const type = await readFile(packagePath, { encoding: 'utf8' }) + .then((filestring) => JSON.parse(filestring).type) + .catch((err) => { + if (err?.code !== 'ENOENT') console.error(err); + }); + // Ff package.json existed and contained a `type` field with a value, voila + if (type) return type; + // Otherwise, (if not at the root) continue checking the next directory up + // If at the root, stop and return false + return dir.length > 1 && getPackageType(resolvePath(dir, '..')); } ```