Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add assert function, assert import.meta.resolve returns string or null #236

Closed
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions src/esmockErr.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,20 @@ const errModuleIdNotFound = (moduleId, parent) =>
const errModuleIdNotMocked = (moduleId, parent) =>
new Error(`un-mocked moduleId: "${moduleId}" (used by ${parent})`)

const errModuleIdNoDefs = (moduleId, parent) =>
new Error(`no mocks provided for module: "${moduleId}" (used by ${parent})`)

const errModuleIdUrlInvalid = (moduleId, parent) =>
new Error(`moduleUrl invalid for module: "${moduleId}" (used by ${parent})`)

const errMissingLoader = () =>
new Error('the loader chain process must include esmock. '
+ 'start the process using --loader=esmock.')

const errModuleIdNoDefs = (moduleId, parent) =>
new Error(`no mocks provided for module: "${moduleId}" (used by ${parent})`)

export default {
errModuleIdNotFound,
errModuleIdNotMocked,
errMissingLoader,
errModuleIdNoDefs
errModuleIdNoDefs,
errModuleIdUrlInvalid,
errMissingLoader
}
17 changes: 15 additions & 2 deletions src/esmockModule.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,27 @@ const asFileURL = p => fileurlre.test(p) ? p : url.pathToFileURL(p)
const objProto = Object.getPrototypeOf({})
const isPlainObj = o => Object.getPrototypeOf(o) === objProto

// see https://github.com/iambumblehead/esmock/issues/234
//
// node v20.6.x returns invalid import.meta.resolve result "{}"
const assertImportMetaResolveReturn = (url, id, parent) => {
if (typeof url === 'string' || url === null)
return url

throw esmockErr.errModuleIdUrlInvalid(id, parent)
}

// when import.meta.resolve fails to resolve windows paths, fallback resolvewith
const resolve = isMetaResolve ?
(import.meta.resolve.constructor.name === 'AsyncFunction'
? async (id, p) => import.meta.resolve(id, asFileURL(p))
.then(url => assertImportMetaResolveReturn(url, id, p))
iambumblehead marked this conversation as resolved.
Show resolved Hide resolved
.catch(() => resolvewith(id, p))
: (id, p) => {
try { return import.meta.resolve(id, asFileURL(p)) }
catch { return resolvewith(id, p) }
try {
return assertImportMetaResolveReturn(
import.meta.resolve(id, asFileURL(p)), id, p)
} catch { return resolvewith(id, p) }
})
: resolvewith

Expand Down
Loading