forked from BANG88/typescript-react-intl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
290 lines (271 loc) · 7.94 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
import ts = require("typescript");
function isMethodCall(
el: ts.Declaration,
methodName: string,
): el is ts.VariableDeclaration {
return (
ts.isVariableDeclaration(el) &&
!!el.initializer &&
ts.isCallExpression(el.initializer) &&
el.initializer.expression &&
ts.isIdentifier(el.initializer.expression) &&
el.initializer.expression.text === methodName
);
}
function isExportMethodCall(
el: ts.Declaration,
methodName: string,
): el is ts.ExportAssignment {
return (
ts.isExportAssignment(el) &&
!!el.expression &&
ts.isCallExpression(el.expression) &&
!!el.expression.expression &&
ts.isIdentifier(el.expression.expression) &&
el.expression.expression.text === methodName
);
}
/**
* Represents a react-intl message descriptor
*/
export interface Message {
defaultMessage?: string;
description?: string;
id: string;
}
// This is the only JSX element we can extract messages from:
type ElementName = "FormattedMessage" | string;
// These are the two methods we can extract messages from:
type MethodName = "defineMessages" | "formatMessage";
// MessageExtracter defines a function type which can extract zero or more
// valid Messages from an ObjectLiteralExpression:
type MessageExtracter = (obj: ts.ObjectLiteralExpression) => Message[];
// sets `target[key] = value`, but only if it is a legal Message key
function copyIfMessageKey(
target: Partial<Message>,
key: string,
value: string,
) {
switch (key) {
case "defaultMessage":
case "description":
case "id":
target[key] = value;
break;
default:
break;
}
}
// are the required keys of a valid Message present?
function isValidMessage(obj: Partial<Message>): obj is Message {
return "id" in obj;
}
function extractMessagesForDefineMessages(
objLiteral: ts.ObjectLiteralExpression,
): Message[] {
const messages: Message[] = [];
objLiteral.properties.forEach((p) => {
const msg: Partial<Message> = {};
if (
ts.isPropertyAssignment(p) &&
ts.isObjectLiteralExpression(p.initializer) &&
p.initializer.properties
) {
p.initializer.properties.forEach((ip) => {
if (
ip.name &&
(ts.isIdentifier(ip.name) || ts.isLiteralExpression(ip.name))
) {
const name = ip.name.text;
if (
ts.isPropertyAssignment(ip) &&
(ts.isStringLiteral(ip.initializer) ||
ts.isNoSubstitutionTemplateLiteral(ip.initializer))
) {
copyIfMessageKey(msg, name, ip.initializer.text);
}
// else: key/value is not a string literal/identifier
}
});
isValidMessage(msg) && messages.push(msg);
}
});
return messages;
}
function extractMessagesForFormatMessage(
objLiteral: ts.ObjectLiteralExpression,
): Message[] {
const msg: Partial<Message> = {};
objLiteral.properties.forEach((p) => {
if (
ts.isPropertyAssignment(p) &&
(ts.isIdentifier(p.name) || ts.isLiteralExpression(p.name)) &&
ts.isStringLiteral(p.initializer)
) {
copyIfMessageKey(msg, p.name.text, p.initializer.text);
}
// else: key/value is not a string literal/identifier
});
return isValidMessage(msg) ? [msg] : [];
}
function extractMessagesForNode(
node: ts.Node,
extractMessages: MessageExtracter,
): Message[] {
const res: Message[] = [];
function find(n: ts.Node): Message[] | undefined {
if (ts.isObjectLiteralExpression(n)) {
res.push(...extractMessages(n));
return undefined;
} else {
return ts.forEachChild(n, find);
}
}
find(node);
return res;
}
function forAllVarDecls(
node: ts.Node,
cb: (decl: ts.VariableDeclaration | ts.ExportAssignment) => void,
) {
if (ts.isVariableDeclaration(node) || ts.isExportAssignment(node)) {
cb(node);
} else {
ts.forEachChild(node, (n) => forAllVarDecls(n, cb));
}
}
function findJsxOpeningLikeElementsWithName(
node: ts.SourceFile,
tagName: ElementName,
) {
const messages: ts.JsxOpeningLikeElement[] = [];
function findJsxElement(n: ts.Node): undefined {
// Is this a JsxElement with an identifier name?
if (ts.isJsxOpeningLikeElement(n) && ts.isIdentifier(n.tagName)) {
// Does the tag name match what we're looking for?
const childTagName = n.tagName;
if (childTagName.text === tagName) {
messages.push(n);
}
}
return ts.forEachChild(n, findJsxElement);
}
findJsxElement(node);
return messages;
}
function findMethodCallsWithName(
sourceFile: ts.SourceFile,
methodName: MethodName,
extractMessages: MessageExtracter,
) {
let messages: Message[] = [];
forAllVarDecls(sourceFile, (decl: ts.Declaration) => {
if (isMethodCall(decl, methodName)) {
if (
decl.initializer &&
ts.isCallExpression(decl.initializer) &&
decl.initializer.arguments.length
) {
const nodeProps = decl.initializer.arguments[0];
const declMessages = extractMessagesForNode(nodeProps, extractMessages);
messages = messages.concat(declMessages);
}
} else if (isExportMethodCall(decl, methodName)) {
if (
decl.expression &&
ts.isCallExpression(decl.expression) &&
decl.expression.arguments.length
) {
const nodeProps = decl.expression.arguments[0];
const declMessages = extractMessagesForNode(nodeProps, extractMessages);
messages = messages.concat(declMessages);
}
}
});
return messages;
}
export interface Options {
tagNames: string[];
}
/**
* Parse tsx files
*/
function main(
contents: string,
options: Options = { tagNames: [] },
): Message[] {
const sourceFile = ts.createSourceFile(
"file.ts",
contents,
ts.ScriptTarget.ES2015,
/*setParentNodes */ false,
ts.ScriptKind.TSX,
);
const dm = findMethodCallsWithName(
sourceFile,
"defineMessages",
extractMessagesForDefineMessages,
);
// TODO formatMessage might not be the initializer for a VarDecl
// eg console.log(formatMessage(...))
const fm = findMethodCallsWithName(
sourceFile,
"formatMessage",
extractMessagesForFormatMessage,
);
const results: Message[] = [];
const tagNames = ["FormattedMessage"].concat(options.tagNames);
tagNames.forEach((tagName) => {
const elements = findJsxOpeningLikeElementsWithName(sourceFile, tagName);
// convert JsxOpeningLikeElements to Message maps
const jsxMessages = getElementsMessages(elements);
results.push(...jsxMessages);
});
return results.concat(dm).concat(fm);
}
/**
* convert JsxOpeningLikeElements to Message maps
* @param elements
*/
function getElementsMessages(elements: ts.JsxOpeningLikeElement[]) {
return elements
.map((element) => {
const msg: Partial<Message> = {};
if (element.attributes) {
element.attributes.properties.forEach((attr: ts.JsxAttributeLike) => {
if (!ts.isJsxAttribute(attr) || !attr.initializer) {
// Either JsxSpreadAttribute, or JsxAttribute without initializer.
return;
}
const key = attr.name.text;
const init = attr.initializer;
let text;
if (ts.isStringLiteral(init)) {
text = init.text;
} else if (ts.isJsxExpression(init)) {
if (
init.expression &&
(ts.isStringLiteral(init.expression) ||
ts.isNoSubstitutionTemplateLiteral(init.expression))
) {
text = init.expression.text;
} else {
// Either the JsxExpression has no expression (?)
// or a non-StringLiteral expression.
return;
}
} else {
// Should be a StringLiteral or JsxExpression, but it's not!
return;
}
copyIfMessageKey(msg, key, text);
});
}
return isValidMessage(msg) ? msg : null;
})
.filter(notNull);
}
function notNull<T>(value: T | null): value is T {
return value !== null;
}
export default main;