UNPKG

1.95 kBJavaScriptView Raw
1import DocumentationBuilder from './Documentation.js';
2import postProcessDocumentation from './utils/postProcessDocumentation.js';
3import babelParse from './babelParser.js';
4import FileState from './FileState.js';
5import { ERROR_CODES, ReactDocgenError } from './error.js';
6import runResolver from './resolver/utils/runResolver.js';
7function executeHandlers(handlers, componentDefinitions) {
8 return componentDefinitions.map((componentDefinition) => {
9 const documentation = new DocumentationBuilder();
10 handlers.forEach((handler) => handler(documentation, componentDefinition));
11 return postProcessDocumentation(documentation.build());
12 });
13}
14/**
15 * Takes JavaScript source code and returns an object with the information
16 * extract from it.
17 *
18 * `resolver` is a strategy to find the AST node(s) of the component
19 * definition(s) inside `src`.
20 * It is a function that gets passed the program AST node of
21 * the source as first argument, and a reference to the parser as second argument.
22 *
23 * This allows you define your own strategy for finding component definitions.
24 *
25 * `handlers` is an array of functions which are passed a reference to the
26 * component definitions (extracted by `resolver`) so that they can extract
27 * information from it. They get also passed a reference to a `Documentation`
28 * object to attach the information to. A reference to the parser is parsed as the
29 * last argument.
30 */
31export default function parse(code, config) {
32 const { babelOptions, handlers, importer, resolver } = config;
33 const ast = babelParse(code, babelOptions);
34 const fileState = new FileState(babelOptions, {
35 ast,
36 code,
37 importer,
38 });
39 const componentDefinitions = runResolver(resolver, fileState);
40 if (componentDefinitions.length === 0) {
41 throw new ReactDocgenError(ERROR_CODES.MISSING_DEFINITION);
42 }
43 return executeHandlers(handlers, componentDefinitions);
44}