-
Notifications
You must be signed in to change notification settings - Fork 76
/
extract.ts
222 lines (178 loc) · 6 KB
/
extract.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
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import { walk } from 'estree-walker';
import { parse } from 'svelte/compiler';
import { deepSet } from './includes/deepSet';
import { getObjFromExpression } from './includes/getObjFromExpression';
import { delve } from '../shared/delve';
import type { Message, WalkerOperationThis } from './types';
import type { Ast } from 'svelte/types/compiler/interfaces';
import type {
Node,
ObjectExpression,
ImportDeclaration,
ImportSpecifier,
CallExpression,
Identifier,
Literal,
} from 'estree';
const LIB_NAME = 'svelte-i18n';
const DEFINE_MESSAGES_METHOD_NAME = 'defineMessages';
const FORMAT_METHOD_NAMES = new Set(['format', '_', 't']);
function isFormatCall(node: Node, imports: Set<string>) {
if (node.type !== 'CallExpression') return false;
let identifier: Identifier | undefined;
if (node.callee.type === 'Identifier') {
identifier = node.callee;
}
if (!identifier || identifier.type !== 'Identifier') {
return false;
}
const methodName = identifier.name.slice(1);
return imports.has(methodName);
}
function isMessagesDefinitionCall(node: Node, methodName: string) {
if (node.type !== 'CallExpression') return false;
return (
node.callee &&
node.callee.type === 'Identifier' &&
node.callee.name === methodName
);
}
function getLibImportDeclarations(ast: Ast): ImportDeclaration[] {
const bodyElements = [
...(ast.instance?.content.body ?? []),
...(ast.module?.content.body ?? []),
];
return bodyElements.filter(
(node) =>
node.type === 'ImportDeclaration' && node.source.value === LIB_NAME,
) as ImportDeclaration[];
}
function getDefineMessagesSpecifier(decl: ImportDeclaration) {
return decl.specifiers.find(
(spec) =>
'imported' in spec && spec.imported.name === DEFINE_MESSAGES_METHOD_NAME,
) as ImportSpecifier;
}
function getFormatSpecifiers(decl: ImportDeclaration) {
return decl.specifiers.filter(
(spec) => 'imported' in spec && FORMAT_METHOD_NAMES.has(spec.imported.name),
) as ImportSpecifier[];
}
export function collectFormatCalls(ast: Ast) {
const importDecls = getLibImportDeclarations(ast);
if (importDecls.length === 0) return [];
const imports = new Set(
importDecls.flatMap((decl) =>
getFormatSpecifiers(decl).map((n) => n.local.name),
),
);
if (imports.size === 0) return [];
const calls: CallExpression[] = [];
function enter(this: WalkerOperationThis, node: Node) {
if (isFormatCall(node, imports)) {
calls.push(node as CallExpression);
this.skip();
}
}
// @ts-expect-error - https://github.com/Rich-Harris/estree-walker/issues/28
walk(ast.instance as any, { enter });
// @ts-expect-error - https://github.com/Rich-Harris/estree-walker/issues/28
walk(ast.html as any, { enter });
return calls;
}
// walk(ast: import("estree").BaseNode, { enter, leave }: {
// enter?: (this: {
// skip: () => void;
// remove: () => void;
// replace: (node: import("estree").BaseNode) => void;
// }, node: import("estree").BaseNode, parent: import("estree").BaseNode, key: string, index: number) => void;
export function collectMessageDefinitions(ast: Ast) {
const definitions: ObjectExpression[] = [];
const defineImportDecl = getLibImportDeclarations(ast).find(
getDefineMessagesSpecifier,
);
if (defineImportDecl == null) return [];
const defineMethodName =
getDefineMessagesSpecifier(defineImportDecl).local.name;
const nodeStepInstructions = {
enter(this: WalkerOperationThis, node: Node) {
if (isMessagesDefinitionCall(node, defineMethodName) === false) return;
const [arg] = (node as CallExpression).arguments;
if (arg.type === 'ObjectExpression') {
definitions.push(arg);
this.skip();
}
},
};
// @ts-expect-error - https://github.com/Rich-Harris/estree-walker/issues/28
walk(ast.instance as any, nodeStepInstructions);
// @ts-expect-error - https://github.com/Rich-Harris/estree-walker/issues/28
walk(ast.module as any, nodeStepInstructions);
return definitions.flatMap((definitionDict) =>
definitionDict.properties.map((propNode) => {
if (propNode.type !== 'Property') {
throw new Error(
`Found invalid '${propNode.type}' at L${propNode.loc!.start.line}:${
propNode.loc!.start.column
}`,
);
}
return propNode.value as ObjectExpression;
}),
);
}
export function collectMessages(markup: string): Message[] {
const ast = parse(markup);
const calls = collectFormatCalls(ast);
const definitions = collectMessageDefinitions(ast);
return [
...definitions.map((definition) => getObjFromExpression(definition)),
...calls.map((call) => {
const [pathNode, options] = call.arguments;
let messageObj: Message;
if (pathNode.type === 'ObjectExpression') {
// _({ ...opts })
messageObj = getObjFromExpression(pathNode);
} else {
const node = pathNode as Literal;
const id = node.value as string;
if (options && options.type === 'ObjectExpression') {
// _(id, { ...opts })
messageObj = getObjFromExpression(options);
messageObj.id = id;
} else {
// _(id)
messageObj = { id };
}
}
if (messageObj?.id == null) return null;
return messageObj;
}),
].filter(Boolean) as Message[];
}
export function extractMessages(
markup: string,
{
accumulator = {},
shallow = false,
}: {
accumulator?: Record<string, any>;
shallow?: boolean;
} = {},
) {
collectMessages(markup).forEach((messageObj) => {
let defaultValue = messageObj.default;
if (typeof defaultValue === 'undefined') {
defaultValue = '';
}
if (shallow) {
if (messageObj.id in accumulator) return;
accumulator[messageObj.id] = defaultValue;
} else {
if (typeof delve(accumulator, messageObj.id) !== 'undefined') return;
deepSet(accumulator, messageObj.id, defaultValue);
}
});
return accumulator;
}