-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplugin.ts
97 lines (82 loc) · 2.15 KB
/
plugin.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
import { writeFileSync } from 'fs';
import { Program } from 'typescript';
import transformerFactory, {
TXConfig,
getPhrases,
ContextedPhrases,
contextedPhrasesFilter,
Phrase,
} from './src/transformer/transformer';
import { phrasesStringify, StringifySeparateOutput } from './src/utils/stringify';
type MultipleOutput = {
file: string;
test: string[];
};
type PluginOptions = Pick<TXConfig,
| 'exclude'
| 'include'
| 'packageName'
| 'jsxFnName'
| 'textFnName'
> & {
humanTextCheckRegExp?: string;
verbose?: boolean;
output?: string | MultipleOutput[];
outputOptions?: {
indent?: string;
valueWrapper?: [string, string];
};
};
export default function txPlugin(_: Program, pluginOptions: PluginOptions) {
const verbose = pluginOptions.verbose ? (...args: any[]) => console.log('[tx-i18n]', ...args) : (() => {});
function save() {
const {
output = './locale.default.ts',
outputOptions = {},
} = pluginOptions;
phrasesStringify({
output: prepareOutput(output),
phrases: getPhrases(),
indent: outputOptions.indent,
valueWrapper: outputOptions.valueWrapper,
}).forEach(({file, content}) => {
verbose('Write locale file', file);
writeFileSync(file, content);
});
}
process.on('SIGINT', () => {
verbose('process.SIGINT');
save();
});
process.on('exit', () => {
verbose('process.exit');
save();
});
console.log('txPlugin:', pluginOptions);
const extra: TXConfig = {verbose};
if (pluginOptions.humanTextCheckRegExp) {
const re = new RegExp(pluginOptions.humanTextCheckRegExp, 'i');
extra.isHumanText = (val: string) => re.test(val);
}
return transformerFactory({
...pluginOptions,
...Object(extra),
});
}
function prepareOutput(output: PluginOptions['output']): string | StringifySeparateOutput {
if (typeof output === 'string') {
return output;
}
const filters = output.map(({file, test}) => {
const regexp = test.map((val) => new RegExp(val));
const filter = ({file}: Phrase) => regexp.some((re) => re.test(file));
return {
file,
filter,
};
});
return (phrases: ContextedPhrases) => filters.map(({file, filter}) => ({
file,
phrases: contextedPhrasesFilter(phrases, filter),
}));
}