-
Notifications
You must be signed in to change notification settings - Fork 397
/
Copy pathindex.ts
304 lines (248 loc) · 8.81 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
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
import fs from "fs"
import fsPath from "path"
import mkdirp from "mkdirp"
import generate from "@babel/generator"
import { getConfig } from "@lingui/conf"
const CONFIG = Symbol("I18nConfig")
// Map of messages
const MESSAGES = Symbol("I18nMessages")
// We need to remember all processed nodes. When JSX expressions are
// replaced with CallExpressions, all children are traversed for each CallExpression.
// Then, i18n._ methods are visited multiple times for each parent CallExpression.
const VISITED = Symbol("I18nVisited")
function addMessage(
path,
messages,
{ id, message: newDefault, origin, comment, ...props }
) {
// prevent from adding undefined msgid
if (id === undefined) return
if (messages.has(id)) {
const message = messages.get(id)
// only set/check default language when it's defined.
if (message.message && newDefault && message.message !== newDefault) {
throw path.buildCodeFrameError(
"Different defaults for the same message ID."
)
}
if (newDefault) {
message.message = newDefault
}
;[].push.apply(message.origin, origin)
if (comment) {
;[].push.apply(message.extractedComments, [comment])
}
} else {
const extractedComments = comment ? [comment] : []
messages.set(id, { ...props, message: newDefault, origin, extractedComments })
}
}
export default function ({ types: t }) {
let localTransComponentName
function isTransComponent(node) {
return (
t.isJSXElement(node) &&
t.isJSXIdentifier(node.openingElement.name, {
name: localTransComponentName,
})
)
}
const isI18nMethod = (node) =>
t.isMemberExpression(node) &&
t.isIdentifier(node.object, { name: "i18n" }) &&
t.isIdentifier(node.property, { name: "_" })
function collectMessage(path, file, props) {
const messages = file.get(MESSAGES)
const rootDir = file.get(CONFIG).rootDir
const filename = fsPath
.relative(rootDir, file.opts.filename)
.replace(/\\/g, "/")
const line = path.node.loc ? path.node.loc.start.line : null
props.origin = [[filename, line]]
addMessage(path, messages, props)
}
return {
visitor: {
// Get the local name of Trans component. Usually it's just `Trans`, but
// it might be different when the import is aliased:
// import { Trans as T } from '@lingui/react';
ImportDeclaration(path) {
const { node } = path
const moduleName = node.source.value
if (
!["@lingui/react", "@lingui/macro", "@lingui/core"].includes(
moduleName
)
)
return
const importDeclarations = {}
if (moduleName === "@lingui/react" || moduleName === "@lingui/macro") {
node.specifiers.forEach((specifier) => {
importDeclarations[specifier.imported.name] = specifier.local.name
})
// Trans import might be missing if there's just Plural or similar macro.
// If there's no alias, consider it was imported as Trans.
localTransComponentName = importDeclarations["Trans"] || "Trans"
}
if (!node.specifiers.length) {
path.remove()
}
},
// Extract translation from <Trans /> component.
JSXElement(path, { file }) {
const { node } = path
if (!localTransComponentName || !isTransComponent(node)) return
const attrs = node.openingElement.attributes || []
const props = attrs.reduce((acc, item) => {
const key = item.name.name
if (key === "id" || key === "message" || key === "comment") {
if (item.value.value) {
acc[key] = item.value.value
} else if (
item.value.expression &&
t.isStringLiteral(item.value.expression)
) {
acc[key] = item.value.expression.value
}
}
return acc
}, {})
if (!props.id) {
// <Trans id={message} /> is valid, don't raise warning
const idProp = attrs.filter((item) => item.name.name === "id")[0]
if (idProp === undefined || t.isLiteral(props.id)) {
console.warn("Missing message ID, skipping.")
console.warn(generate(node).code)
}
return
}
collectMessage(path, file, props)
},
CallExpression(path, { file }) {
const visited = file.get(VISITED)
if (visited.has(path.node)) return
const hasComment = [path.node, path.parent].find(
({ leadingComments }) => {
return (
leadingComments &&
leadingComments.filter((node) =>
node.value.match(/^\s*i18n\s*$/)
)[0]
)
}
)
if (!hasComment) return
const props = {
id: path.node.arguments[0].value,
}
if (!props.id) {
console.warn("Missing message ID, skipping.")
console.warn(generate(path.node).code)
return
}
const copyOptions = ["message", "comment"]
if (t.isObjectExpression(path.node.arguments[2])) {
path.node.arguments[2].properties.forEach((property) => {
if (!copyOptions.includes(property.key.name)) return
props[property.key.name] = property.value.value
})
}
visited.add(path.node)
collectMessage(path, file, props)
},
StringLiteral(path, { file }) {
const visited = file.get(VISITED)
const comment =
path.node.leadingComments &&
path.node.leadingComments.filter((node) =>
node.value.match(/^\s*i18n/)
)[0]
if (!comment || visited.has(path.node)) {
return
}
visited.add(path.node)
const props = {
id: path.node.value,
}
if (!props.id) {
console.warn("Missing message ID, skipping.")
console.warn(generate(path.node).code)
return
}
collectMessage(path, file, props)
},
// Extract message descriptors
ObjectExpression(path, { file }) {
const visited = file.get(VISITED)
const comment =
path.node.leadingComments &&
path.node.leadingComments.filter((node) =>
node.value.match(/^\s*i18n/)
)[0]
if (!comment || visited.has(path.node)) {
return
}
visited.add(path.node)
const props = {}
const copyProps = ["id", "message", "comment"]
path.node.properties
.filter(({ key }) => copyProps.indexOf(key.name) !== -1)
.forEach(({ key, value }, i) => {
if (key.name === "comment" && !t.isStringLiteral(value)) {
throw path
.get(`properties.${i}.value`)
.buildCodeFrameError("Only strings are supported as comments.")
}
const isIdLiteral = !value.value && key.name === "id" && t.isTemplateLiteral(value)
props[key.name] = isIdLiteral ? value?.quasis[0]?.value?.cooked : value.value
})
collectMessage(path, file, props)
},
},
pre(file) {
localTransComponentName = null
// Skip validation because config is loaded for each file.
// Config was already validated in CLI.
file.set(
CONFIG,
getConfig({ cwd: file.opts.filename, skipValidation: true })
)
// Ignore else path for now. Collision is possible if other plugin is
// using the same Symbol('I18nMessages').
// istanbul ignore else
if (!file.has(MESSAGES)) {
file.set(MESSAGES, new Map())
}
file.set(VISITED, new WeakSet())
},
post(file) {
/* Write catalog to directory `localeDir`/_build/`path.to.file`/`filename`.json
* e.g: if file is src/components/App.js (relative to package.json), then
* catalog will be in locale/_build/src/components/App.json
*/
const config = file.get(CONFIG)
const localeDir = this.opts.localeDir || config.localeDir
const { filename } = file.opts
const rootDir = config.rootDir
const baseDir = fsPath.dirname(fsPath.relative(rootDir, filename))
const targetDir = fsPath.join(localeDir, "_build", baseDir)
const messages = file.get(MESSAGES)
const catalog = {}
const baseName = fsPath.basename(filename)
const catalogFilename = fsPath.join(targetDir, `${baseName}.json`)
mkdirp.sync(targetDir)
// no messages, skip file
if (!messages.size) {
// clean any existing catalog
if (fs.existsSync(catalogFilename)) {
fs.writeFileSync(catalogFilename, JSON.stringify({}))
}
return
}
messages.forEach((value, key) => {
catalog[key] = value
})
fs.writeFileSync(catalogFilename, JSON.stringify(catalog, null, 2))
},
}
}