Skip to content

Commit

Permalink
use function to ensure loader is registered once only
Browse files Browse the repository at this point in the history
  • Loading branch information
bumblehead committed Sep 9, 2023
1 parent 8b872ef commit d2c3e02
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 11 deletions.
4 changes: 3 additions & 1 deletion src/esmockLoader.js
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,9 @@ export {
load,
resolve,
getSource,
initialize,
// if getSource and initialize exported at the time,
// getSource is never called :(
// initialize,
globalPreload,
loaderIsVerified as default
}
31 changes: 21 additions & 10 deletions src/esmockRegister.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,28 @@ import threads from 'node:worker_threads'
const channel = threads.MessageChannel
&& new threads.MessageChannel()

if (channel && module.register) {
module.register('./esmockLoader.js', {
parentURL: import.meta.url,
data: { port: channel.port2 },
transferList: [channel.port2]
})
}
const register = (res => () => {
if (typeof res === 'boolean')
return res

if (!(res = global.shouldRegister === true))
return res

if ((res = Boolean(channel && module.register))) {
module.register('./esmockLoader.js', {
parentURL: import.meta.url,
data: { port: channel.port2 },
transferList: [channel.port2]
})
}

return res
})()

export default msg => {
if (typeof global.postMessageEsmk === 'function')
global.postMessageEsmk(msg)
if (channel && channel.port1)
if (register()) {
channel.port1.postMessage(msg)
} else if (typeof global.postMessageEsmk === 'function') {
global.postMessageEsmk(msg)
}
}

0 comments on commit d2c3e02

Please sign in to comment.