This repository has been archived by the owner on Feb 8, 2020. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
240 lines (221 loc) · 7.4 KB
/
index.js
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
/*!
* parse-function <https://github.com/tunnckoCore/parse-function>
*
* Copyright (c) 2017 Charlike Mike Reagent <[email protected]> (https://i.am.charlike.online)
* Released under the MIT license.
*/
/**
* Utilities
*/
import utils from './lib/utils.js'
/**
* Core plugins
*/
import initial from './lib/plugins/initial.js'
/**
* > Initializes with optional `opts` object which is passed directly
* to the desired parser and returns an object
* with `.use` and `.parse` methods. The default parse which
* is used is [babylon][]'s `.parseExpression` method from `v7`.
*
* ```js
* const parseFunction = require('parse-function')
*
* const app = parseFunction({
* ecmaVersion: 2017
* })
*
* const fixtureFn = (a, b, c) => {
* a = b + c
* return a + 2
* }
*
* const result = app.parse(fixtureFn)
* console.log(result)
*
* // see more
* console.log(result.name) // => null
* console.log(result.isNamed) // => false
* console.log(result.isArrow) // => true
* console.log(result.isAnonymous) // => true
*
* // array of names of the arguments
* console.log(result.args) // => ['a', 'b', 'c']
*
* // comma-separated names of the arguments
* console.log(result.params) // => 'a, b, c'
* ```
*
* @param {Object} `opts` optional, merged with options passed to `.parse` method
* @return {Object} `app` object with `.use` and `.parse` methods
* @name parseFunction
* @api public
*/
export default function parseFunction (opts) {
const plugins = []
const app = {
/**
* > Parse a given `code` and returns a `result` object
* with useful properties - such as `name`, `body` and `args`.
* By default it uses Babylon parser, but you can switch it by
* passing `options.parse` - for example `options.parse: acorn.parse`.
* In the below example will show how to use `acorn` parser, instead
* of the default one.
*
* ```js
* const acorn = require('acorn')
* const parseFn = require('parse-function')
* const app = parseFn()
*
* const fn = function foo (bar, baz) { return bar * baz }
* const result = app.parse(fn, {
* parse: acorn.parse,
* ecmaVersion: 2017
* })
*
* console.log(result.name) // => 'foo'
* console.log(result.args) // => ['bar', 'baz']
* console.log(result.body) // => ' return bar * baz '
* console.log(result.isNamed) // => true
* console.log(result.isArrow) // => false
* console.log(result.isAnonymous) // => false
* console.log(result.isGenerator) // => false
* ```
*
* @param {Function|String} `code` any kind of function or string to be parsed
* @param {Object} `options` directly passed to the parser - babylon, acorn, espree
* @param {Function} `options.parse` by default `babylon.parseExpression`,
* all `options` are passed as second argument
* to that provided function
* @return {Object} `result` see [result section](#result) for more info
* @name .parse
* @api public
*/
parse (code, options) {
let result = utils.setDefaults(code)
if (!result.isValid) {
return result
}
opts = Object.assign({}, opts, options)
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
// eslint-disable-next-line no-useless-escape
const isMethod = /^\*?.+\([\s\S\w\W]*\)\s*\{/i.test(result.value)
if (!(isFunction || isAsyncFn || isAsyncArrow) && isMethod) {
result.value = `{ ${result.value} }`
}
let node = utils.getNode(result, opts)
return plugins.reduce((res, fn) => fn(node, res) || res, result)
},
/**
* > Add a plugin `fn` function for extending the API or working on the
* AST nodes. The `fn` is immediately invoked and passed
* with `app` argument which is instance of `parseFunction()` call.
* That `fn` may return another function that
* accepts `(node, result)` signature, where `node` is an AST node
* and `result` is an object which will be returned [result](#result)
* from the `.parse` method. This retuned function is called on each
* node only when `.parse` method is called.
*
* _See [Plugins Architecture](#plugins-architecture) section._
*
* ```js
* // plugin extending the `app`
* app.use((app) => {
* app.define(app, 'hello', (place) => `Hello ${place}!`)
* })
*
* const hi = app.hello('World')
* console.log(hi) // => 'Hello World!'
*
* // or plugin that works on AST nodes
* app.use((app) => (node, result) => {
* if (node.type === 'ArrowFunctionExpression') {
* result.thatIsArrow = true
* }
* return result
* })
*
* const result = app.parse((a, b) => (a + b + 123))
* console.log(result.name) // => null
* console.log(result.isArrow) // => true
* console.log(result.thatIsArrow) // => true
*
* const result = app.parse(function foo () { return 123 })
* console.log(result.name) // => 'foo'
* console.log(result.isArrow) // => false
* console.log(result.thatIsArrow) // => undefined
* ```
*
* @param {Function} `fn` plugin to be called
* @return {Object} `app` instance for chaining
* @name .use
* @api public
*/
use (fn) {
const ret = fn(app)
if (typeof ret === 'function') {
plugins.push(ret)
}
return app
},
/**
* > Define a non-enumerable property on an object. Just
* a convenience mirror of the [define-property][] library,
* so check out its docs. Useful to be used in plugins.
*
* ```js
* const parseFunction = require('parse-function')
* const app = parseFunction()
*
* // use it like `define-property` lib
* const obj = {}
* app.define(obj, 'hi', 'world')
* console.log(obj) // => { hi: 'world' }
*
* // or define a custom plugin that adds `.foo` property
* // to the end result, returned from `app.parse`
* app.use((app) => {
* return (node, result) => {
* // this function is called
* // only when `.parse` is called
*
* app.define(result, 'foo', 123)
*
* return result
* }
* })
*
* // fixture function to be parsed
* const asyncFn = async (qux) => {
* const bar = await Promise.resolve(qux)
* return bar
* }
*
* const result = app.parse(asyncFn)
*
* console.log(result.name) // => null
* console.log(result.foo) // => 123
* console.log(result.args) // => ['qux']
*
* console.log(result.isAsync) // => true
* console.log(result.isArrow) // => true
* console.log(result.isNamed) // => false
* console.log(result.isAnonymous) // => true
* ```
*
* @param {Object} `obj` the object on which to define the property
* @param {String} `prop` the name of the property to be defined or modified
* @param {Any} `val` the descriptor for the property being defined or modified
* @return {Object} `obj` the passed object, but modified
* @name .define
* @api public
*/
define: utils.define,
}
app.use(initial)
return app
}