-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathindex.ts
41 lines (31 loc) · 1.26 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/* eslint-disable @typescript-eslint/no-explicit-any */
import arrayify from 'arrify';
import { parse as babelParse } from '@babel/parser';
import { setDefaults, getNode } from './utils';
import { Input, Options, Plugin, Result } from './types';
import basePlugin from './plugins/initial';
// eslint-disable-next-line import/prefer-default-export
export function parseFunction(code: Input, options?: Options) {
const opts: Options = { parse: babelParse, ...options };
const result: Result = setDefaults(code);
if (!result.isValid) {
return result;
}
const isFunction = result.value.startsWith('function');
const isAsyncFn = result.value.startsWith('async function');
const isAsync = result.value.startsWith('async');
const isArrow = result.value.includes('=>');
const isAsyncArrow = isAsync && isArrow;
const isMethod = /^\*?.+\([\s\S\w\W]*\)\s*\{/i.test(result.value);
if (!(isFunction || isAsyncFn || isAsyncArrow) && isMethod) {
result.value = `{ ${result.value} }`;
}
const node = getNode(result, opts);
const plugins = arrayify(opts.plugins);
return [basePlugin, ...plugins]
.filter(Boolean)
.reduce((res: any, fn: Plugin) => {
const pluginResult = fn(node, { ...res }) || res;
return pluginResult;
}, result);
}