|
| 1 | +/* eslint-disable no-underscore-dangle */ |
| 2 | +/** |
| 3 | + * Provides {@link buildCjsExecuteRecord}, a function that converts a |
| 4 | + * {@link CjsModuleSourceRecord} into a {@link FinalStaticModuleType}. |
| 5 | + * |
| 6 | + * For use with `@endo/parser-pipeline`'s `createComposedParser()`. |
| 7 | + * |
| 8 | + * @module |
| 9 | + */ |
| 10 | + |
| 11 | +import { getModulePaths, wrap } from './parse-cjs-shared-export-wrapper.js'; |
| 12 | + |
| 13 | +/** |
| 14 | + * @import {CjsModuleSourceRecord} from '@endo/module-source' |
| 15 | + * @import {ReadFn, ReadPowers} from './types.js' |
| 16 | + * @import {FinalStaticModuleType} from 'ses' |
| 17 | + */ |
| 18 | + |
| 19 | +const { freeze } = Object; |
| 20 | + |
| 21 | +/** |
| 22 | + * Converts a {@link CjsModuleSourceRecord} (which has a `cjsFunctor` string) |
| 23 | + * into a `FinalStaticModuleType`-compatible record (which has an `execute` |
| 24 | + * function). This is the bridge between the composed-pipeline CJS analysis and |
| 25 | + * the compartment-mapper execution model. |
| 26 | + * |
| 27 | + * Used by both {@link parseCjsBabel} (single-shot parser) and |
| 28 | + * {@link createCjsExecParser} (composed-pipeline parser) so the execution |
| 29 | + * logic lives in exactly one place. |
| 30 | + * |
| 31 | + * @param {CjsModuleSourceRecord} cjsRecord |
| 32 | + * @param {string} location |
| 33 | + * @param {ReadFn | ReadPowers | undefined} readPowers |
| 34 | + * @returns {FinalStaticModuleType} |
| 35 | + */ |
| 36 | + |
| 37 | +export const buildCjsExecuteRecord = (cjsRecord, location, readPowers) => { |
| 38 | + const { filename, dirname } = getModulePaths(readPowers, location); |
| 39 | + |
| 40 | + /** |
| 41 | + * @param {object} moduleEnvironmentRecord |
| 42 | + * @param {Compartment} compartment |
| 43 | + * @param {Record<string, string>} resolvedImports |
| 44 | + */ |
| 45 | + const execute = (moduleEnvironmentRecord, compartment, resolvedImports) => { |
| 46 | + const functor = compartment.evaluate(cjsRecord.cjsFunctor); |
| 47 | + |
| 48 | + const wrapResult = wrap({ |
| 49 | + moduleEnvironmentRecord, |
| 50 | + compartment, |
| 51 | + resolvedImports, |
| 52 | + location, |
| 53 | + readPowers, |
| 54 | + }); |
| 55 | + |
| 56 | + const args = [ |
| 57 | + wrapResult.require, |
| 58 | + wrapResult.moduleExports, |
| 59 | + wrapResult.module, |
| 60 | + filename, |
| 61 | + dirname, |
| 62 | + ]; |
| 63 | + |
| 64 | + if (cjsRecord.__needsImport__ && wrapResult.importFn) { |
| 65 | + args.push(wrapResult.importFn); |
| 66 | + } |
| 67 | + |
| 68 | + functor.call(wrapResult.moduleExports, ...args); |
| 69 | + |
| 70 | + wrapResult.afterExecute(); |
| 71 | + }; |
| 72 | + |
| 73 | + return freeze({ |
| 74 | + imports: cjsRecord.imports, |
| 75 | + exports: cjsRecord.exports, |
| 76 | + reexports: cjsRecord.reexports, |
| 77 | + execute, |
| 78 | + }); |
| 79 | +}; |
0 commit comments