-
Notifications
You must be signed in to change notification settings - Fork 34
/
index.js
206 lines (166 loc) · 5.23 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
// @flow
import p from 'path'
import * as t from 'babel-types'
import type { State } from './types'
// import blog from 'babel-log'
const PKG_NAME = 'react-intl'
const FUNC_NAME = 'defineMessages'
const isImportLocalName = (name: string, { file }: State) => {
const imports = file.metadata.modules.imports
const intlImports = imports.find(x => x.source === PKG_NAME)
if (intlImports) {
const specifier = intlImports.specifiers.find(x => x.imported === FUNC_NAME)
if (specifier) {
return specifier.local === name
}
}
return false
}
const REG = new RegExp(`\\${p.sep}`, 'g')
const dotPath = (str: string) => str.replace(REG, '.')
const getPrefix = (
{
file: { opts: { filename } },
opts: { removePrefix = '', filebase = false },
}: State,
exportName: string | null
) => {
if (removePrefix === true) {
return exportName === null ? '' : exportName
}
const file = p.relative(process.cwd(), filename)
const fomatted = filebase ? file.replace(/\..+$/, '') : p.dirname(file)
removePrefix = removePrefix === false ? '' : removePrefix
const fixed = dotPath(fomatted).replace(
new RegExp(`^${removePrefix.replace(/\//g, '')}\\${dotPath(p.sep)}?`),
''
)
const result = exportName === null ? fixed : `${fixed}.${exportName}`
return result
}
const getId = (path, prefix) => {
let name
if (path.isStringLiteral()) {
name = path.node.value
} else if (path.isIdentifier()) {
name = path.node.name
}
if (!name) {
throw new Error(`requires Object key or string literal`)
}
return dotPath(p.join(prefix, name))
}
const isLiteral = node => t.isStringLiteral(node) || t.isTemplateLiteral(node)
const isValidate = (path: Object, state: State): boolean => {
const callee = path.get('callee')
if (!callee.isIdentifier()) {
return false
}
if (!isImportLocalName(callee.node.name, state)) {
return false
}
const msgPath = path.get('arguments.0')
if (!msgPath || !(msgPath.isObjectExpression() || msgPath.isIdentifier())) {
return false
}
return true
}
const getLeadingComment = prop => {
const commentNodes = prop.node.leadingComments
return commentNodes
? commentNodes.map(node => node.value.trim()).join('\n')
: null
}
const objectProperty = (key, value) => {
const valueNode = typeof value === 'string' ? t.stringLiteral(value) : value
return t.objectProperty(t.stringLiteral(key), valueNode)
}
const replaceProperties = (
properties: $ReadOnlyArray<Object>,
state: State,
exportName: string | null
) => {
const prefix = getPrefix(state, exportName)
for (const prop of properties) {
const propValue = prop.get('value')
// eslint-disable-next-line
const messageDescriptorProperties: Object[] = []
// { defaultMessage: 'hello', description: 'this is hello' }
if (propValue.isObjectExpression()) {
const objProps = propValue.get('properties')
// { id: 'already has id', defaultMessage: 'hello' }
const isNotHaveId = objProps.every(v => v.get('key').node.name !== 'id')
if (isNotHaveId) {
const id = getId(prop.get('key'), prefix)
messageDescriptorProperties.push(objectProperty('id', id))
}
messageDescriptorProperties.push(...objProps.map(v => v.node))
// 'hello' or `hello ${user}`
} else if (isLiteral(propValue)) {
const id = getId(prop.get('key'), prefix)
messageDescriptorProperties.push(
objectProperty('id', id),
objectProperty('defaultMessage', propValue.node)
)
}
const { extractComments = true } = state.opts
if (extractComments) {
const hasDescription = messageDescriptorProperties.find(
v => v.key.name === 'description'
)
if (!hasDescription) {
const description = getLeadingComment(prop)
if (description) {
messageDescriptorProperties.push(
objectProperty('description', description)
)
}
}
}
propValue.replaceWith(t.objectExpression(messageDescriptorProperties))
}
}
const getExportName = (path, includeExportName): string | null => {
const namedExport = path.findParent(v => v.isExportNamedDeclaration())
const defaultExport = path.findParent(v => v.isExportDefaultDeclaration())
if (includeExportName && namedExport) {
return namedExport.get('declaration.declarations.0.id.name').node
}
if (includeExportName === 'all' && defaultExport) {
return 'default'
}
return null
}
function getProperties(path): $ReadOnlyArray<Object> | null {
if (path.isObjectExpression()) {
return path.get('properties')
} else if (path.isIdentifier()) {
const { name } = path.node
const obj = path.scope.getBinding(name)
if (!obj) {
return null
}
return obj.path.get('init.properties')
}
return null
}
export default function() {
return {
name: 'react-intl-auto',
visitor: {
CallExpression(path: Object, state: State) {
if (!isValidate(path, state)) {
return
}
const properties = getProperties(path.get('arguments.0'))
if (properties) {
const exportName = getExportName(
path,
state.opts.includeExportName || false
)
replaceProperties(properties, state, exportName)
}
},
},
}
}