node/lib/internal/modules/esm/create_dynamic_module.js
Myles Borins 2931c50a42
esm: refactor dynamic modules
This is a change from the ecmascript-modules fork.
There is no change to behavior and we would like to
upstream to reduce the delta between our repos.

Refs: https://github.com/nodejs/ecmascript-modules#9

PR-URL: https://github.com/nodejs/node/pull/24560
Refs: https://github.com/nodejs/ecmascript-modules/pull/9
Reviewed-By: Guy Bedford <guybedford@gmail.com>
Reviewed-By: Gus Caplan <me@gus.host>
2018-11-30 16:38:57 -05:00

59 lines
1.3 KiB
JavaScript

'use strict';
const { ModuleWrap, callbackMap } = internalBinding('module_wrap');
const debug = require('util').debuglog('esm');
const ArrayJoin = Function.call.bind(Array.prototype.join);
const ArrayMap = Function.call.bind(Array.prototype.map);
const createDynamicModule = (exports, url = '', evaluate) => {
debug(
`creating ESM facade for ${url} with exports: ${ArrayJoin(exports, ', ')}`
);
const names = ArrayMap(exports, (name) => `${name}`);
const source = `
${ArrayJoin(ArrayMap(names, (name) =>
`let $${name};
export { $${name} as ${name} };
import.meta.exports.${name} = {
get: () => $${name},
set: (v) => $${name} = v,
};`), '\n')
}
import.meta.done();
`;
const m = new ModuleWrap(source, `${url}`);
m.link(() => 0);
m.instantiate();
const readyfns = new Set();
const reflect = {
namespace: m.namespace(),
exports: {},
onReady: (cb) => { readyfns.add(cb); },
};
callbackMap.set(m, {
initializeImportMeta: (meta, wrap) => {
meta.exports = reflect.exports;
meta.done = () => {
evaluate(reflect);
reflect.onReady = (cb) => cb(reflect);
for (const fn of readyfns) {
readyfns.delete(fn);
fn(reflect);
}
};
},
});
return {
module: m,
reflect,
};
};
module.exports = createDynamicModule;