diff --git a/src/try-import.mts b/src/try-import.mts index c2695e9..9f23c43 100644 --- a/src/try-import.mts +++ b/src/try-import.mts @@ -1,6 +1,6 @@ import path from "path/posix"; +import { createRequire } from "module"; import { coerce, satisfies } from "semver"; -// import extractRootModuleName from "./extract-root-module-name.js"; const LOCAL_MODULE_RE = /^[.]{1,2}($|\/.*)/g; const ABSOLUTE_MODULE_RE = /^\/.*/g; @@ -8,6 +8,7 @@ const ABSOLUTE_MODULE_RE = /^\/.*/g; const PACKAGE_RE = "[^/]+"; const SCOPED_PACKAGE_RE = "@[^/]+(/[^/]+)"; const ROOT_MODULE_RE = new RegExp(`^(${SCOPED_PACKAGE_RE}|${PACKAGE_RE})`, "g"); +const require = createRequire(import.meta.url); /** * returns the module name that likely contains the package.json @@ -25,15 +26,28 @@ function extractRootModuleName(pModuleName: string): string | undefined { } } -async function getVersion(pModuleName: string): Promise { - const lManifest = await import( +function getVersion(pModuleName: string): string { + // // The 'proper' way to do this would be with a dynamic import with an + // // import assertion. Because it's 'experimental' since node 16 and prints + // // an ugly warning on stderr since node 19 we'll be using the require + // // hack below in stead. + // const lManifest = await import( + // // @ts-expect-error TS2345 extractRootModuleName can return either a string or + // // undefined. If undefined this function will throw. Which is _fine_, even + // // _expected_ in the context it's currently used + // path.join(extractRootModuleName(pModuleName), "package.json"), + // { assert: { type: "json" } } + // ); + // // changes the return type to Promise + // return lManifest.default.version; + const lManifest = require(path.join( // @ts-expect-error TS2345 extractRootModuleName can return either a string or // undefined. If undefined this function will throw. Which is _fine_, even // _expected_ in the context it's currently used - path.join(extractRootModuleName(pModuleName), "package.json"), - { assert: { type: "json" } } - ); - return lManifest.default.version; + extractRootModuleName(pModuleName), + "package.json" + )); + return lManifest.version; } export default async function tryImport( @@ -47,7 +61,7 @@ export default async function tryImport( lReturnValue = lModule.default; if (pSemanticVersion) { - const lVersion = await getVersion(pModuleName); + const lVersion = getVersion(pModuleName); const lCoerced = coerce(lVersion); if ( lVersion &&