|
| 1 | +/** |
| 2 | + * Low-level module analysis primitives for CJS. |
| 3 | + * |
| 4 | + * {@link analyzeCjs} returns a per-parse context object |
| 5 | + * holding plain `{ visitor }` objects and a `buildRecord` function. |
| 6 | + * |
| 7 | + * Consumers are responsible for: |
| 8 | + * 1. Traversing the AST with `ctx.analyzePass.visitor`. |
| 9 | + * 2. Traversing the (mutated) AST with `ctx.transformPass.visitor`. |
| 10 | + * 3. Generating code. |
| 11 | + * 4. Calling `ctx.buildRecord(code, location)` to produce the module record. |
| 12 | + * |
| 13 | + * @module |
| 14 | + */ |
| 15 | + |
| 16 | +import makeCjsModulePlugins from './cjs-babel-plugin.js'; |
| 17 | +import { buildCjsFunctorSource, buildCjsModuleRecord } from './cjs-functor.js'; |
| 18 | +import { createCjsSourceOptions } from './source-options.js'; |
| 19 | + |
| 20 | +/** |
| 21 | + * @import {AnalysisOptions} from './types/analyzer.js' |
| 22 | + * @import {CjsAnalysisContext} from './types/cjs-analyzer.js' |
| 23 | + */ |
| 24 | + |
| 25 | +/** |
| 26 | + * Creates a fresh CJS analysis context for a single module parse. |
| 27 | + * |
| 28 | + * @param {AnalysisOptions} [options] |
| 29 | + * @returns {CjsAnalysisContext} |
| 30 | + */ |
| 31 | + |
| 32 | +export const analyzeCjs = (options = {}) => { |
| 33 | + const { allowHidden = false } = options; |
| 34 | + const sourceOptions = createCjsSourceOptions({ allowHidden }); |
| 35 | + const { analyzePlugin, transformPlugin } = |
| 36 | + makeCjsModulePlugins(sourceOptions); |
| 37 | + |
| 38 | + return { |
| 39 | + analyzePass: analyzePlugin, |
| 40 | + transformPass: transformPlugin, |
| 41 | + |
| 42 | + buildRecord(generatedCode, location) { |
| 43 | + const functorSource = buildCjsFunctorSource( |
| 44 | + generatedCode, |
| 45 | + sourceOptions, |
| 46 | + location, |
| 47 | + ); |
| 48 | + return buildCjsModuleRecord(sourceOptions, functorSource); |
| 49 | + }, |
| 50 | + }; |
| 51 | +}; |
0 commit comments