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 | 1×
1×
1×
1×
1×
1×
1×
1×
1×
38×
38×
38×
10×
6×
1×
1×
1×
1×
1×
1×
1×
61×
2×
61×
5×
56×
9×
8×
8×
6×
8×
1×
8×
1×
9×
47×
4×
4×
1×
1×
137×
21×
6×
15×
1×
14×
4×
10×
10×
2×
8×
4×
2×
2×
4×
4×
1×
1×
4×
1×
1×
1×
1×
6×
1×
1×
1×
10×
10×
1×
10×
6×
4×
4×
4×
4×
1×
1×
| import fs from 'fs'
import path from 'path'
import espree from 'espree'
import estraverse from 'estraverse'
import escodegen from 'escodegen'
import inlineSourceMapComment from'inline-source-map-comment'
const espreeConfig = {
// attach range information to each node
range: true,
// attach line/column location information to each node
loc: true,
// create a top-level comments array containing all comments
comment: true,
// attach comments to the closest relevant node as leadingComments and
// trailingComments
attachComment: true,
// create a top-level tokens array containing all tokens
tokens: true,
// specify the language version (3, 5, 6, or 7, default is 5)
ecmaVersion: 7,
// specify which type of script you're parsing (script or module, default is script)
sourceType: 'module',
// specify additional language features
ecmaFeatures: {
// enable JSX parsing
jsx: true,
// enable return in global scope
globalReturn: true,
// enable implied strict mode (if ecmaVersion >= 5)
impliedStrict: true,
// allow experimental object rest/spread
experimentalObjectRestSpread: true,
// allow let and const declarations
blockBindings: true
}
}
const namespace = '__NUTRA_MOCK__'
const createIdentifier = (id) => {
const identifier = {
type: 'Identifier',
name: id
}
identifier[namespace] = true
return identifier
}
const setEntryMethod = (entry, id) => ({
type: 'ExpressionStatement',
expression: {
type: 'CallExpression',
callee: createIdentifier('NutraMock.setEntry'),
arguments: [
{
type: 'Literal',
value: entry,
raw: `"${entry}"`
}, {
type: 'Literal',
value: id,
raw: `"${id}"`
},
createIdentifier(id)
]
}
})
const mockObject = (entry, id) => ({
type: 'MemberExpression',
object: {
type: 'MemberExpression',
object: {
type: 'MemberExpression',
object: {
type: 'MemberExpression',
object: createIdentifier('NutraMock'),
property: createIdentifier('store'),
computed: false
},
property: {
type: 'Literal',
value: entry,
raw: `"${entry}"`
},
computed: true
},
property: {
type: 'Literal',
value: id,
raw: `"${id}"`
},
computed: true
},
property: createIdentifier('fake'),
computed: false
})
const mockObjectExpression = (entry, id) => ({
type: 'ExpressionStatement',
expression: mockObject(entry, id)
})
const SourceModifier = (source, filename) => {
const ast = espree.parse(source, espreeConfig)
const entry = path.join('.', filename.replace(process.cwd(), ''))
const topImportNodes = {}
const topConstantNodes = {}
// collect relevant nodes in the main execution context
estraverse.traverse(ast, {
enter: (node, parent) => {
if (/FunctionExpression|FunctionDeclaration/.test(node.type)) {
return estraverse.VisitorOption.Skip
}
},
leave: (node, parent) => {
if (node[namespace]) {
return
}
if (node.type === 'Identifier' && /Import|Export/.test(parent.type)) {
if (parent.local && parent.local.name) {
parent.local[namespace] = true
if (parent.type.startsWith('Import')) {
topImportNodes[parent.local.name] = true
}
if (parent.imported &&
parent.imported.name !== parent.local.name) {
parent.imported[namespace] = true
}
Iif (parent.exported &&
parent.exported.name !== parent.local.name) {
parent.exported[namespace] = true
}
} else {
node[namespace] = true
}
return
}
if (node.type === 'VariableDeclarator' && parent.kind === 'const') {
topConstantNodes[node.id.name] = true
node.id[namespace] = true
}
}
})
// replace relevant nodes in deep execution contexts
const topNodes = Object.assign({}, topImportNodes, topConstantNodes)
estraverse.replace(ast, {
enter: function(node, parent) {
if (node.type === 'Identifier' && !node[namespace]) {
if (!topNodes[node.name]) {
return
}
if (parent.type === 'ExperimentalSpreadProperty')
return
if (parent.type === 'MemberExpression' && !parent.computed)
return
Iif (parent.type === 'FunctionDeclaration')
return
if (parent.type === 'VariableDeclarator')
return
if (parent.type === 'Property') {
if (parent.shorthand) {
parent.shorthand = false
parent.value = mockObject(entry, node.name)
}
return
}
return mockObject(entry, node.name)
}
}
})
// get index of the last import node
let afterImportNodeIndex = 0
for (let i = 0; i < ast.body.length; i++) {
if (!ast.body[i].type.startsWith('Import')) {
afterImportNodeIndex = i
break
}
}
// build the import mock registrations
const importSetEntryMethods = []
Object.keys(topImportNodes).forEach(
id => importSetEntryMethods.push(setEntryMethod(entry, id))
)
// insert the import mock registrations after the last import node
let spliceArgs = [afterImportNodeIndex, 0].concat(importSetEntryMethods)
Array.prototype.splice.apply(ast.body, spliceArgs)
// insert the constant mock registrations after each constant node
for (let node, i = (afterImportNodeIndex * 2); i < ast.body.length; i++) {
node = ast.body[i]
if (node.type === 'ExportNamedDeclaration') {
Iif (node.declaration && typeof node.declaration === 'object') {
node = node.declaration
}
}
if (node.type !== 'VariableDeclaration' || node.kind !== 'const') {
continue
}
Eif (node.declarations && typeof node.declarations[0] === 'object') {
node = node.declarations[0]
}
Eif (node.type === 'VariableDeclarator' && topConstantNodes[node.id.name]) {
ast.body.splice(++i, 0, setEntryMethod(entry, node.id.name))
}
}
// reconstruct source
const modifiedSource = escodegen.generate(ast, {
sourceMap: filename,
sourceMapWithCode: true
})
return {
code: modifiedSource.code,
map: modifiedSource.map
}
}
export default SourceModifier
|