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

fix: Fallback to parentLoad if parsing fails #104

Merged
merged 8 commits into from
Jun 14, 2024
Merged
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
37 changes: 29 additions & 8 deletions hook.js
Original file line number Diff line number Diff line change
Expand Up @@ -246,14 +246,16 @@ function createHook (meta) {
async function getSource (url, context, parentGetSource) {
if (hasIitm(url)) {
const realUrl = deleteIitm(url)
const setters = await processModule({
srcUrl: realUrl,
context,
parentGetSource,
parentResolve: cachedResolve
})
return {
source: `

try {
const setters = await processModule({
srcUrl: realUrl,
context,
parentGetSource,
parentResolve: cachedResolve
})
return {
source: `
import { register } from '${iitmURL}'
import * as namespace from ${JSON.stringify(realUrl)}

Expand All @@ -268,6 +270,25 @@ ${Array.from(setters.values()).join('\n')}

register(${JSON.stringify(realUrl)}, _, set, ${JSON.stringify(specifiers.get(realUrl))})
`
}
} catch (cause) {
// If there are other ESM loader hooks registered as well as iitm,
// depending on the order they are registered, source might not be
// JavaScript.
//
// If we fail to parse a module for exports, we should fall back to the
// parent loader. These modules will not be wrapped with proxies and
// cannot be Hook'ed but at least this does not take down the entire app
// and block iitm from being used.
//
// We log the error because there might be bugs in iitm and without this
// it would be very tricky to debug
const err = new Error(`'import-in-the-middle' failed to wrap '${realUrl}'`)
err.cause = cause
console.warn(err)

// Revert back to the non-iitm URL
url = realUrl
}
}

Expand Down