micromark events to Acorn parser utility
micromark-util-events-to-acorn is a core utility within the micromark ecosystem, specifically designed to bridge micromark's low-level parsing events with acorn's robust JavaScript parsing capabilities. It takes an array of micromark events and attempts to construct an Abstract Syntax Tree (AST) using an acorn parser instance. This package is crucial for handling MDX expressions and similar constructs where embedded JavaScript needs to be parsed and validated. The current stable version is 2.0.3. While it doesn't have an independent, fixed release cadence, its updates are typically coordinated with major and minor releases of related micromark extensions, such as micromark-extension-mdx-expression. A key differentiator is its specialized role in the micromark architecture, providing a performant and integrated way to parse JavaScript directly from event streams, requiring the acorn parser and its options to be passed explicitly rather than being a direct dependency. It is ESM-only, requiring Node.js 16 or later.
Common errors
-
TypeError: Cannot read properties of undefined (reading 'includes')
cause The `tokenTypes` option was not provided to `eventsToAcorn` or was not an array of strings, which is a required parameter since v2.0.0 for processing the event stream.fixPass `tokenTypes: ['someTokenType']` as an option to `eventsToAcorn`, where 'someTokenType' are the micromark token types containing the code to be parsed. -
ERR_REQUIRE_ESM
cause You attempted to `require()` this ESM-only package (`micromark-util-events-to-acorn`) in a CommonJS environment (e.g., in a `.js` file without `"type": "module"` in `package.json`).fixRefactor your code to use ES Modules (e.g., `import { eventsToAcorn } from 'micromark-util-events-to-acorn'`) and ensure your project is configured for ESM. -
Error: Cannot find module 'acorn'
cause The `acorn` parser library is a required peer/external dependency that must be installed and explicitly passed to `eventsToAcorn`, but it was not found.fixInstall `acorn` (e.g., `npm install acorn`) and ensure you provide an `acorn` object with `parse` and `parseExpressionAt` methods in the `options` object.
Warnings
- breaking Version 2.0.0 and later require Node.js 16 or higher. Older Node.js versions are no longer supported, aligning with the `unified` collective's compatibility policy.
- breaking The `eventsToAcorn` function now explicitly requires the `tokenTypes` option to be passed. This array of strings specifies which `micromark` token types should be concatenated to form the source text that `acorn` will parse.
- gotcha This package is ESM-only. Attempting to `require()` it in a CommonJS module will result in a runtime error.
- gotcha While `micromark-util-events-to-acorn` itself accepts `acornOptions`, the parent `micromark-extension-mdx-expression@3.0.0` changed its default `ecmaVersion` to 2024. If using this utility in an MDX context, ensure your `acornOptions` are explicitly set if you require a different ECMAScript version.
Install
-
npm install micromark-util-events-to-acorn -
yarn add micromark-util-events-to-acorn -
pnpm add micromark-util-events-to-acorn
Imports
- eventsToAcorn
const { eventsToAcorn } = require('micromark-util-events-to-acorn')import { eventsToAcorn } from 'micromark-util-events-to-acorn' - Options
import type { Options } from 'micromark-util-events-to-acorn' - Result
import type { Result } from 'micromark-util-events-to-acorn'
Quickstart
import { eventsToAcorn } from 'micromark-util-events-to-acorn';
import * as acorn from 'acorn'; // acorn must be installed and provided
// Mock micromark events representing a simple MDX expression `{1 + 1}`.
// In a real micromark application, these events would be generated by a tokenizer
// parsing Markdown/MDX content.
const sampleEvents = [
{ type: 'mdxExpressionText', start: { line: 1, column: 2, offset: 1 }, end: { line: 1, column: 7, offset: 6 } }
];
const mockAcornOptions = { ecmaVersion: 2024, sourceType: 'module' };
// Attempt to parse the micromark events into an ESTree AST using acorn.
const result = eventsToAcorn(sampleEvents, {
acorn: {
parse: acorn.parse,
parseExpressionAt: acorn.parseExpressionAt,
},
tokenTypes: ['mdxExpressionText'], // Essential since v2.0.0: list micromark token types that represent code data
acornOptions: mockAcornOptions,
start: { line: 1, column: 1, offset: 0 }, // Start position for source mapping
expression: true, // Indicate that we are parsing an expression
allowEmpty: false, // Do not allow empty expressions
prefix: '',
suffix: ''
});
if (result.error) {
console.error('Failed to parse expression:', result.error.message);
} else if (result.estree) {
console.log('Successfully parsed ESTree expression:');
console.log(JSON.stringify(result.estree.body[0], null, 2));
// Expected output will be an ESTree node for '1 + 1'.
} else {
console.log('Parsing completed, but no ESTree generated (e.g., empty expression allowed).');
}