auto-i18n-plugin-core 0.0.16 → 0.0.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +2 -1015
- package/dist/index.cjs.map +1 -0
- package/dist/index.mjs +2 -984
- package/dist/index.mjs.map +1 -0
- package/package.json +6 -3
package/dist/index.mjs
CHANGED
|
@@ -1,984 +1,2 @@
|
|
|
1
|
-
import cloneDeep from 'lodash/cloneDeep';
|
|
2
|
-
|
|
3
|
-
import tunnel from 'tunnel';
|
|
4
|
-
import axios from 'axios';
|
|
5
|
-
import CryptoJS from 'crypto-js';
|
|
6
|
-
import fs from 'node:fs';
|
|
7
|
-
import path from 'node:path';
|
|
8
|
-
import * as types$3 from '@babel/types';
|
|
9
|
-
|
|
10
|
-
/*
|
|
11
|
-
* @Author: xiaoshanwen
|
|
12
|
-
* @Date: 2024-03-11 18:59:10
|
|
13
|
-
* @LastEditTime: 2024-04-07 19:40:33
|
|
14
|
-
* @FilePath: /i18n_translation_vite/autoI18nPluginCore/src/enums/language.ts
|
|
15
|
-
*/
|
|
16
|
-
// 待补充...
|
|
17
|
-
var OriginLangKeyEnum;
|
|
18
|
-
(function (OriginLangKeyEnum) {
|
|
19
|
-
OriginLangKeyEnum["ZH"] = "zh-cn";
|
|
20
|
-
OriginLangKeyEnum["EN"] = "en";
|
|
21
|
-
})(OriginLangKeyEnum || (OriginLangKeyEnum = {}));
|
|
22
|
-
|
|
23
|
-
/*
|
|
24
|
-
* @Author: xiaoshanwen
|
|
25
|
-
* @Date: 2024-04-03 18:12:45
|
|
26
|
-
* @LastEditTime: 2024-04-03 18:33:53
|
|
27
|
-
* @FilePath: /i18n_translation_vite/autoI18nPluginCore/src/enums/translate.ts
|
|
28
|
-
*/
|
|
29
|
-
var TranslateApiEnum;
|
|
30
|
-
(function (TranslateApiEnum) {
|
|
31
|
-
TranslateApiEnum["google"] = "Google";
|
|
32
|
-
TranslateApiEnum["youdao"] = "Youdao";
|
|
33
|
-
})(TranslateApiEnum || (TranslateApiEnum = {}));
|
|
34
|
-
|
|
35
|
-
class IntervalQueue {
|
|
36
|
-
delay;
|
|
37
|
-
timeout;
|
|
38
|
-
fn;
|
|
39
|
-
/**
|
|
40
|
-
* 间隔执行队列
|
|
41
|
-
* @param fn 执行函数
|
|
42
|
-
* @param delay 执行间隔
|
|
43
|
-
* @param timeout 超时时间
|
|
44
|
-
*/
|
|
45
|
-
constructor(fn, delay, timeout) {
|
|
46
|
-
this.fn = fn;
|
|
47
|
-
this.delay = delay;
|
|
48
|
-
this.timeout = timeout;
|
|
49
|
-
}
|
|
50
|
-
queue = [];
|
|
51
|
-
execute(...args) {
|
|
52
|
-
return new Promise((resolve, reject) => {
|
|
53
|
-
this.queue.push({ args, resolve, reject });
|
|
54
|
-
this.run();
|
|
55
|
-
if (this.timeout) {
|
|
56
|
-
setTimeout(() => {
|
|
57
|
-
reject(new Error('IntervalQueue timeout'));
|
|
58
|
-
}, this.timeout);
|
|
59
|
-
}
|
|
60
|
-
});
|
|
61
|
-
}
|
|
62
|
-
async wait(delay = this.delay) {
|
|
63
|
-
await new Promise(resolve => setTimeout(resolve, delay));
|
|
64
|
-
}
|
|
65
|
-
isRunning = false;
|
|
66
|
-
async run() {
|
|
67
|
-
if (this.isRunning)
|
|
68
|
-
return;
|
|
69
|
-
let item;
|
|
70
|
-
while ((item = this.queue.shift())) {
|
|
71
|
-
const { args, resolve, reject } = item;
|
|
72
|
-
this.isRunning = true;
|
|
73
|
-
try {
|
|
74
|
-
resolve(await this.fn(...args));
|
|
75
|
-
}
|
|
76
|
-
catch (e) {
|
|
77
|
-
reject(e);
|
|
78
|
-
}
|
|
79
|
-
await this.wait();
|
|
80
|
-
}
|
|
81
|
-
this.isRunning = false;
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
const interval = (fn, delay) => {
|
|
85
|
-
const queue = new IntervalQueue(fn.bind(null), delay);
|
|
86
|
-
return (...args) => {
|
|
87
|
-
return queue.execute(...args);
|
|
88
|
-
};
|
|
89
|
-
};
|
|
90
|
-
class Translator {
|
|
91
|
-
option;
|
|
92
|
-
constructor(option) {
|
|
93
|
-
this.option = option;
|
|
94
|
-
if (this.option.interval) {
|
|
95
|
-
this.option.fetchMethod = interval(this.option.fetchMethod, this.option.interval);
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
getErrorMessage(error) {
|
|
99
|
-
if (error instanceof Error) {
|
|
100
|
-
return error.message;
|
|
101
|
-
}
|
|
102
|
-
else {
|
|
103
|
-
return String(error);
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
async translate(text, fromKey, toKey) {
|
|
107
|
-
let result = '';
|
|
108
|
-
try {
|
|
109
|
-
result = await this.option.fetchMethod(text, fromKey, toKey);
|
|
110
|
-
}
|
|
111
|
-
catch (error) {
|
|
112
|
-
const name = this.option.name;
|
|
113
|
-
console.error(`翻译api${name ? `【${name}】` : ''}请求异常:${this.getErrorMessage(error)}`);
|
|
114
|
-
}
|
|
115
|
-
return result;
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
class GoogleTranslator extends Translator {
|
|
120
|
-
constructor(option) {
|
|
121
|
-
super({
|
|
122
|
-
name: 'Google翻译',
|
|
123
|
-
fetchMethod: async (text, fromKey, toKey) => {
|
|
124
|
-
let data = await translate$1(text, {
|
|
125
|
-
from: fromKey,
|
|
126
|
-
to: toKey,
|
|
127
|
-
fetchOptions: {
|
|
128
|
-
agent: tunnel.httpsOverHttp({
|
|
129
|
-
proxy: option.proxyOption
|
|
130
|
-
})
|
|
131
|
-
}
|
|
132
|
-
});
|
|
133
|
-
return data['text'] || '';
|
|
134
|
-
}
|
|
135
|
-
});
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
class YoudaoTranslator extends Translator {
|
|
140
|
-
/** 有道的语言类型映射不标准,需要手动控制 */
|
|
141
|
-
YOUDAO_TRANSLATE_KEY_CONVERT_MAP = {
|
|
142
|
-
'zh-cn': 'zh-CHS',
|
|
143
|
-
'zh-tw': 'zh-CHT'
|
|
144
|
-
};
|
|
145
|
-
truncate(q) {
|
|
146
|
-
// 检查输入字符串的长度
|
|
147
|
-
if (q.length <= 20) {
|
|
148
|
-
// 如果长度小于等于20,直接返回原字符串
|
|
149
|
-
return q;
|
|
150
|
-
}
|
|
151
|
-
else {
|
|
152
|
-
// 如果长度大于20,截取前10个字符和后10个字符,并在中间插入长度信息
|
|
153
|
-
const len = q.length;
|
|
154
|
-
return q.substring(0, 10) + len + q.substring(len - 10);
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
getTranslateKey(key) {
|
|
158
|
-
return this.YOUDAO_TRANSLATE_KEY_CONVERT_MAP[key] || key;
|
|
159
|
-
}
|
|
160
|
-
constructor(option) {
|
|
161
|
-
super({
|
|
162
|
-
name: '有道翻译',
|
|
163
|
-
fetchMethod: async (text, fromKey, toKey) => {
|
|
164
|
-
let salt = new Date().getTime();
|
|
165
|
-
let curTime = Math.round(new Date().getTime() / 1000);
|
|
166
|
-
let str = option.appId + this.truncate(text) + salt + curTime + option.appKey;
|
|
167
|
-
let sign = CryptoJS.SHA256(str).toString(CryptoJS.enc.Hex);
|
|
168
|
-
const data = {
|
|
169
|
-
q: text,
|
|
170
|
-
appKey: option.appId,
|
|
171
|
-
salt,
|
|
172
|
-
from: this.getTranslateKey(fromKey),
|
|
173
|
-
to: this.getTranslateKey(toKey),
|
|
174
|
-
sign,
|
|
175
|
-
signType: 'v3',
|
|
176
|
-
curtime: curTime
|
|
177
|
-
};
|
|
178
|
-
const response = await axios.post('https://openapi.youdao.com/api', data, {
|
|
179
|
-
headers: {
|
|
180
|
-
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
|
|
181
|
-
},
|
|
182
|
-
proxy: option.proxy
|
|
183
|
-
});
|
|
184
|
-
// 请求成功,返回响应数据
|
|
185
|
-
return response.data.translation?.[0] || '';
|
|
186
|
-
},
|
|
187
|
-
interval: option.interval ?? 1000
|
|
188
|
-
});
|
|
189
|
-
}
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
var index$2 = /*#__PURE__*/Object.freeze({
|
|
193
|
-
__proto__: null,
|
|
194
|
-
GoogleTranslator: GoogleTranslator,
|
|
195
|
-
Translator: Translator,
|
|
196
|
-
YoudaoTranslator: YoudaoTranslator
|
|
197
|
-
});
|
|
198
|
-
|
|
199
|
-
/*
|
|
200
|
-
* @Author: xiaoshanwen
|
|
201
|
-
* @Date: 2023-10-26 17:34:47
|
|
202
|
-
* @LastEditTime: 2025-02-11 23:09:10
|
|
203
|
-
* @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/option.ts
|
|
204
|
-
*/
|
|
205
|
-
/**
|
|
206
|
-
* 默认插件配置选项
|
|
207
|
-
*/
|
|
208
|
-
const DEFAULT_OPTION = {
|
|
209
|
-
/** 翻译调用函数,默认为 $t */
|
|
210
|
-
translateKey: '$t',
|
|
211
|
-
/** 标记不翻译调用函数列表,避免某些调用被错误翻译 */
|
|
212
|
-
excludedCall: ['$i8n', 'require', '$$i8n', 'console.log', '$t'],
|
|
213
|
-
/** 标记不用翻译的字符串模式数组,默认是匹配文件扩展名 */
|
|
214
|
-
excludedPattern: [/\.\w+$/],
|
|
215
|
-
/** 排查不需要翻译的目录下的文件路径(黑名单), 默认不处理node_modules */
|
|
216
|
-
excludedPath: ['node_modules'],
|
|
217
|
-
/** 指定需要翻译文件的目录路径正则(白名单) */
|
|
218
|
-
includePath: [/src\//],
|
|
219
|
-
/** 配置文件生成位置,默认为 './lang' */
|
|
220
|
-
globalPath: './lang',
|
|
221
|
-
/** 打包后生成文件的位置,例如 './dist/assets' */
|
|
222
|
-
distPath: '',
|
|
223
|
-
/** 打包后生成文件的主文件名称,默认是 'index' */
|
|
224
|
-
distKey: 'index',
|
|
225
|
-
/** 来源语言,默认是中文 */
|
|
226
|
-
originLang: OriginLangKeyEnum.ZH,
|
|
227
|
-
/** 翻译目标语言列表,默认包含英文 */
|
|
228
|
-
targetLangList: ['en'],
|
|
229
|
-
/** 语言key,用于请求谷歌api和生成配置文件下对应语言的内容文件 */
|
|
230
|
-
langKey: [],
|
|
231
|
-
/** 命名空间,防止全局命名冲突 */
|
|
232
|
-
namespace: '',
|
|
233
|
-
/** 是否在构建结束之后将最新的翻译重新打包到主包中,默认不打包 */
|
|
234
|
-
buildToDist: false,
|
|
235
|
-
/** 默认使用 Google 翻译器 */
|
|
236
|
-
translator: new GoogleTranslator({
|
|
237
|
-
proxyOption: {
|
|
238
|
-
port: 7890,
|
|
239
|
-
host: '127.0.0.1',
|
|
240
|
-
headers: {
|
|
241
|
-
'User-Agent': 'Node'
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
}),
|
|
245
|
-
/** 翻译器配置选项,优先级低于translator */
|
|
246
|
-
translatorOption: undefined
|
|
247
|
-
};
|
|
248
|
-
/**
|
|
249
|
-
* 全局插件配置实例,复制自默认配置
|
|
250
|
-
*/
|
|
251
|
-
let option = { ...DEFAULT_OPTION };
|
|
252
|
-
/**
|
|
253
|
-
* 生成用户传入的配置选项,进行必要前置处理
|
|
254
|
-
* @param optionInfo 用户提供的配置选项
|
|
255
|
-
* @returns 处理后的用户配置选项
|
|
256
|
-
*/
|
|
257
|
-
function generateUserOption(optionInfo) {
|
|
258
|
-
// 深拷贝用户传入的配置,防止修改原配置对象
|
|
259
|
-
const userOption = cloneDeep(optionInfo.option);
|
|
260
|
-
// 如果用户配置了translatorOption则初始化translator,如果都没有则不设置translator
|
|
261
|
-
userOption.translator ||= userOption.translatorOption
|
|
262
|
-
? new Translator(userOption.translatorOption)
|
|
263
|
-
: undefined;
|
|
264
|
-
if (!userOption.translator)
|
|
265
|
-
delete userOption.translator;
|
|
266
|
-
return userOption;
|
|
267
|
-
}
|
|
268
|
-
/**
|
|
269
|
-
* 初始化插件配置选项
|
|
270
|
-
* @param optionInfo 用户提供的配置选项
|
|
271
|
-
*/
|
|
272
|
-
function initOption(optionInfo) {
|
|
273
|
-
// 合并默认配置和用户配置
|
|
274
|
-
option = { ...DEFAULT_OPTION, ...generateUserOption(optionInfo) };
|
|
275
|
-
// 初始化语言key数组,包含来源语言和目标语言
|
|
276
|
-
option.langKey = [option.originLang, ...option.targetLangList];
|
|
277
|
-
}
|
|
278
|
-
/**
|
|
279
|
-
* 校验插件配置选项是否完整有效
|
|
280
|
-
* @returns {boolean} 校验结果,完整返回 true,否则返回 false
|
|
281
|
-
*/
|
|
282
|
-
function checkOption() {
|
|
283
|
-
// 校验翻译调用函数是否配置
|
|
284
|
-
if (!option.translateKey) {
|
|
285
|
-
console.error('❌请配置翻译调用函数');
|
|
286
|
-
return false;
|
|
287
|
-
}
|
|
288
|
-
// 校验命名空间是否配置
|
|
289
|
-
if (!option.namespace) {
|
|
290
|
-
console.error('❌请配置命名空间');
|
|
291
|
-
return false;
|
|
292
|
-
}
|
|
293
|
-
// 校验是否配置了打包后生成文件的主文件名称(如果需要打包到主包中)
|
|
294
|
-
if (option.buildToDist && !option.distKey) {
|
|
295
|
-
console.log('❌请配置打包后生成文件的主文件名称');
|
|
296
|
-
return false;
|
|
297
|
-
}
|
|
298
|
-
// 校验是否配置了打包后生成文件的位置(如果需要打包到主包中)
|
|
299
|
-
if (option.buildToDist && !option.distPath) {
|
|
300
|
-
console.log('❌请配置打包后生成文件的位置');
|
|
301
|
-
return false;
|
|
302
|
-
}
|
|
303
|
-
// 校验来源语言是否配置
|
|
304
|
-
if (!option.originLang) {
|
|
305
|
-
console.error('❌请配置来源语言');
|
|
306
|
-
return false;
|
|
307
|
-
}
|
|
308
|
-
// 校验目标翻译语言数组是否配置
|
|
309
|
-
if (!option.targetLangList || !option.targetLangList.length) {
|
|
310
|
-
console.error('❌请配置目标翻译语言数组');
|
|
311
|
-
return false;
|
|
312
|
-
}
|
|
313
|
-
// 如果所有校验通过,返回 true
|
|
314
|
-
return true;
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
class FunctionFactoryOption {
|
|
318
|
-
static originLang = '';
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
/*
|
|
322
|
-
* @Author: xiaoshanwen
|
|
323
|
-
* @Date: 2024-04-06 15:47:14
|
|
324
|
-
* @LastEditTime: 2024-04-07 19:40:36
|
|
325
|
-
* @FilePath: /i18n_translation_vite/autoI18nPluginCore/src/constants/translate.ts
|
|
326
|
-
*/
|
|
327
|
-
const REGEX_MAP = {
|
|
328
|
-
[OriginLangKeyEnum.ZH]: /[\u4e00-\u9fff]/,
|
|
329
|
-
[OriginLangKeyEnum.EN]: /[a-zA-Z]/
|
|
330
|
-
};
|
|
331
|
-
|
|
332
|
-
const types$2 = require('@babel/types');
|
|
333
|
-
/**
|
|
334
|
-
* @description: 是否包含来源语言字符
|
|
335
|
-
* @param {string} code
|
|
336
|
-
* @return {*}
|
|
337
|
-
*/
|
|
338
|
-
function hasOriginSymbols(code) {
|
|
339
|
-
const originLang = FunctionFactoryOption.originLang;
|
|
340
|
-
return REGEX_MAP[originLang].test(code);
|
|
341
|
-
}
|
|
342
|
-
/**
|
|
343
|
-
* @description: 过滤注释
|
|
344
|
-
* @param {string} code
|
|
345
|
-
* @return {*}
|
|
346
|
-
*/
|
|
347
|
-
const removeComments = function (code) {
|
|
348
|
-
// 使用正则表达式匹配并删除单行注释
|
|
349
|
-
code = code.replace(/\/\/.*?\n/g, '');
|
|
350
|
-
// 使用正则表达式匹配并删除多行注释
|
|
351
|
-
code = code.replace(/\/\*[\s\S]*?\*\//g, '');
|
|
352
|
-
// 使用正则表达式匹配并删除HTML注释
|
|
353
|
-
code = code.replace(/<!--[\s\S]*?-->/g, '');
|
|
354
|
-
return code;
|
|
355
|
-
};
|
|
356
|
-
/**
|
|
357
|
-
* @description: 用于判断提供的值是否符合正则表达式数组中的任一规则,符合则跳过
|
|
358
|
-
* @param {*} value
|
|
359
|
-
* @param {*} regexArray
|
|
360
|
-
* @return {*}
|
|
361
|
-
*/
|
|
362
|
-
function checkAgainstRegexArray(value, regexArray) {
|
|
363
|
-
for (let i = 0; i < regexArray.length; i++) {
|
|
364
|
-
const regex = typeof regexArray[i] === 'string' ? new RegExp(regexArray[i]) : regexArray[i];
|
|
365
|
-
if (regex.test(value)) {
|
|
366
|
-
return true; // 如果符合任何一个规则,返回 true
|
|
367
|
-
}
|
|
368
|
-
}
|
|
369
|
-
return false; // 如果所有规则都不符合,返回 false
|
|
370
|
-
}
|
|
371
|
-
/**
|
|
372
|
-
* @description: 用于解析抽象语法树中的调用表达式,并提取出调用的名称,如a.b.c() 取 c。
|
|
373
|
-
* @param {any} node
|
|
374
|
-
* @return {*}
|
|
375
|
-
*/
|
|
376
|
-
function extractFunctionName(node) {
|
|
377
|
-
let callName = '';
|
|
378
|
-
function callObjName(callObj, name) {
|
|
379
|
-
name += '.' + callObj.property.name;
|
|
380
|
-
if (types$2.isMemberExpression(callObj.object)) {
|
|
381
|
-
// isMemberExpression: 是否是成员表达式
|
|
382
|
-
return callObjName(callObj.object, name);
|
|
383
|
-
}
|
|
384
|
-
name = callObj.object.name + name;
|
|
385
|
-
return name;
|
|
386
|
-
}
|
|
387
|
-
if (types$2.isCallExpression(node)) {
|
|
388
|
-
// isCallExpression: 是否是调用表达式
|
|
389
|
-
if (types$2.isMemberExpression(node.callee)) {
|
|
390
|
-
callName = callObjName(node.callee, '');
|
|
391
|
-
}
|
|
392
|
-
else {
|
|
393
|
-
callName = node.callee.name || '';
|
|
394
|
-
}
|
|
395
|
-
}
|
|
396
|
-
return callName;
|
|
397
|
-
}
|
|
398
|
-
/**
|
|
399
|
-
* @description: 提取文件的中文部分
|
|
400
|
-
* @param {string} fileContent
|
|
401
|
-
* @return {*}
|
|
402
|
-
*/
|
|
403
|
-
const extractCnStrings = (fileContent) => {
|
|
404
|
-
const regex = /[^\x00-\xff]+/g;
|
|
405
|
-
return extractStrings(fileContent, regex);
|
|
406
|
-
};
|
|
407
|
-
/**
|
|
408
|
-
* @description: 提取文件指定部分内容
|
|
409
|
-
* @param {string} fileContent
|
|
410
|
-
* @param {any} regex
|
|
411
|
-
* @return {*}
|
|
412
|
-
*/
|
|
413
|
-
function extractStrings(fileContent, regex) {
|
|
414
|
-
const matches = fileContent.match(regex);
|
|
415
|
-
return matches ? matches.filter((item, index) => matches.indexOf(item) === index) : [];
|
|
416
|
-
}
|
|
417
|
-
/**
|
|
418
|
-
* @description: 生成i8n翻译函数
|
|
419
|
-
* @param {string} value
|
|
420
|
-
* @param {boolean} isExpression
|
|
421
|
-
* @param {string} key
|
|
422
|
-
* @return {*}
|
|
423
|
-
*/
|
|
424
|
-
function createI18nTranslator(value, isExpression, key) {
|
|
425
|
-
const nameSpace = option.namespace;
|
|
426
|
-
const trimmedValue = value.trim();
|
|
427
|
-
const valStr = trimmedValue.replace(/'/g, '"').replace(/(\n)/g, '\\n');
|
|
428
|
-
const generatedKey = key || generateId(valStr);
|
|
429
|
-
if (isExpression) {
|
|
430
|
-
const valueExp = types$2.stringLiteral(trimmedValue);
|
|
431
|
-
valueExp.extra = {
|
|
432
|
-
raw: `'${valStr}'`, // 防止转码为unicode
|
|
433
|
-
rawValue: trimmedValue
|
|
434
|
-
};
|
|
435
|
-
return types$2.callExpression(types$2.identifier(option.translateKey), [
|
|
436
|
-
types$2.stringLiteral(generatedKey),
|
|
437
|
-
valueExp,
|
|
438
|
-
types$2.stringLiteral(nameSpace)
|
|
439
|
-
]);
|
|
440
|
-
}
|
|
441
|
-
else {
|
|
442
|
-
return `${option.translateKey}('${generatedKey}','${valStr}','${nameSpace}')`;
|
|
443
|
-
}
|
|
444
|
-
}
|
|
445
|
-
/**
|
|
446
|
-
* @description: 生成唯一id
|
|
447
|
-
* @param {string} key
|
|
448
|
-
* @return {*}
|
|
449
|
-
*/
|
|
450
|
-
function generateId(key) {
|
|
451
|
-
let hash = 0;
|
|
452
|
-
for (let i = 0; i < key.length; i++) {
|
|
453
|
-
const charCode = key.charCodeAt(i);
|
|
454
|
-
hash = (hash << 5) - hash + charCode;
|
|
455
|
-
hash = hash & hash;
|
|
456
|
-
}
|
|
457
|
-
const id = Math.abs(hash).toString(36) + key.length.toString(36);
|
|
458
|
-
return id;
|
|
459
|
-
}
|
|
460
|
-
/**
|
|
461
|
-
* @description: unicode转中文
|
|
462
|
-
* @param {string} str
|
|
463
|
-
* @return {*}
|
|
464
|
-
*/
|
|
465
|
-
const unicodeToChinese = (str) => {
|
|
466
|
-
return str.replace(/\\u[\dA-Fa-f]{4}/g, (match) => {
|
|
467
|
-
return String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16));
|
|
468
|
-
});
|
|
469
|
-
};
|
|
470
|
-
/**
|
|
471
|
-
* @description: 有道翻译 标识截取
|
|
472
|
-
* @param {string} q
|
|
473
|
-
* @return {*}
|
|
474
|
-
*/
|
|
475
|
-
function truncate(q) {
|
|
476
|
-
// 检查输入字符串的长度
|
|
477
|
-
if (q.length <= 20) {
|
|
478
|
-
// 如果长度小于等于20,直接返回原字符串
|
|
479
|
-
return q;
|
|
480
|
-
}
|
|
481
|
-
else {
|
|
482
|
-
// 如果长度大于20,截取前10个字符和后10个字符,并在中间插入长度信息
|
|
483
|
-
const len = q.length;
|
|
484
|
-
return q.substring(0, 10) + len + q.substring(len - 10);
|
|
485
|
-
}
|
|
486
|
-
}
|
|
487
|
-
|
|
488
|
-
var base = /*#__PURE__*/Object.freeze({
|
|
489
|
-
__proto__: null,
|
|
490
|
-
checkAgainstRegexArray: checkAgainstRegexArray,
|
|
491
|
-
createI18nTranslator: createI18nTranslator,
|
|
492
|
-
extractCnStrings: extractCnStrings,
|
|
493
|
-
extractFunctionName: extractFunctionName,
|
|
494
|
-
extractStrings: extractStrings,
|
|
495
|
-
generateId: generateId,
|
|
496
|
-
hasOriginSymbols: hasOriginSymbols,
|
|
497
|
-
removeComments: removeComments,
|
|
498
|
-
truncate: truncate,
|
|
499
|
-
unicodeToChinese: unicodeToChinese
|
|
500
|
-
});
|
|
501
|
-
|
|
502
|
-
/*
|
|
503
|
-
* @Author: xiaoshanwen
|
|
504
|
-
* @Date: 2023-10-12 13:28:03
|
|
505
|
-
* @LastEditTime: 2024-12-07 16:28:31
|
|
506
|
-
* @FilePath: /i18n_translation_vite/autoI18nPluginCore/src/utils/file.ts
|
|
507
|
-
*/
|
|
508
|
-
const jsonFormat = require('json-format');
|
|
509
|
-
/**
|
|
510
|
-
* @description: 新建国际化配置文件夹
|
|
511
|
-
* @return {*}
|
|
512
|
-
*/
|
|
513
|
-
function initLangFile() {
|
|
514
|
-
if (!fs.existsSync(option.globalPath)) {
|
|
515
|
-
fs.mkdirSync(option.globalPath); // 创建lang文件夹
|
|
516
|
-
}
|
|
517
|
-
initLangTranslateJSONFile();
|
|
518
|
-
initTranslateBasicFnFile();
|
|
519
|
-
}
|
|
520
|
-
/**
|
|
521
|
-
* @description: 生成国际化基础调用函数文件
|
|
522
|
-
* @return {*}
|
|
523
|
-
*/
|
|
524
|
-
function initTranslateBasicFnFile() {
|
|
525
|
-
const key = option.translateKey;
|
|
526
|
-
const translateBasicFnText = `(function () {
|
|
527
|
-
let ${key} = function (key, val, nameSpace) {
|
|
528
|
-
const langPackage = ${key}[nameSpace]
|
|
529
|
-
return (langPackage || {})[key] || val;
|
|
530
|
-
};
|
|
531
|
-
let $${key} = function (val) {
|
|
532
|
-
return val;
|
|
533
|
-
};
|
|
534
|
-
${key}.locale = function (locale, nameSpace) {
|
|
535
|
-
${key}[nameSpace] = locale || {};
|
|
536
|
-
};
|
|
537
|
-
window.${key} = window.${key} || ${key};
|
|
538
|
-
window.$${key} = $${key};
|
|
539
|
-
window._getJSONKey = function (key, insertJSONObj = undefined) {
|
|
540
|
-
const JSONObj = insertJSONObj
|
|
541
|
-
const langObj = {}
|
|
542
|
-
Object.keys(JSONObj).forEach((value)=>{
|
|
543
|
-
langObj[value] = JSONObj[value][key]
|
|
544
|
-
})
|
|
545
|
-
return langObj
|
|
546
|
-
}
|
|
547
|
-
})();`;
|
|
548
|
-
const indexPath = path.join(option.globalPath, 'index.js');
|
|
549
|
-
if (!fs.existsSync(indexPath)) {
|
|
550
|
-
// 不存在就创建
|
|
551
|
-
fs.writeFileSync(indexPath, translateBasicFnText); // 创建
|
|
552
|
-
}
|
|
553
|
-
}
|
|
554
|
-
/**
|
|
555
|
-
* @description: 生成国际化JSON文件
|
|
556
|
-
* @return {*}
|
|
557
|
-
*/
|
|
558
|
-
function initLangTranslateJSONFile() {
|
|
559
|
-
const indexPath = path.join(option.globalPath, 'index.json');
|
|
560
|
-
if (!fs.existsSync(indexPath)) {
|
|
561
|
-
// 不存在就创建
|
|
562
|
-
fs.writeFileSync(indexPath, JSON.stringify({})); // 创建
|
|
563
|
-
}
|
|
564
|
-
}
|
|
565
|
-
/**
|
|
566
|
-
* @description: 读取国际化JSON文件
|
|
567
|
-
* @return {*}
|
|
568
|
-
*/
|
|
569
|
-
function getLangTranslateJSONFile() {
|
|
570
|
-
const filePath = path.join(option.globalPath, 'index.json');
|
|
571
|
-
try {
|
|
572
|
-
const content = fs.readFileSync(filePath, 'utf-8');
|
|
573
|
-
return content;
|
|
574
|
-
}
|
|
575
|
-
catch (error) {
|
|
576
|
-
if (error.code === 'ENOENT') {
|
|
577
|
-
console.log('❌读取JSON配置文件异常,文件不存在');
|
|
578
|
-
}
|
|
579
|
-
else {
|
|
580
|
-
console.log('❌读取JSON配置文件异常,无法读取文件');
|
|
581
|
-
}
|
|
582
|
-
return JSON.stringify({});
|
|
583
|
-
}
|
|
584
|
-
}
|
|
585
|
-
/**
|
|
586
|
-
* @description: 基于langKey获取JSON配置文件中对应语言对象
|
|
587
|
-
* @param {string} key
|
|
588
|
-
* @return {*}
|
|
589
|
-
*/
|
|
590
|
-
function getLangObjByJSONFileWithLangKey(key, insertJSONObj = undefined) {
|
|
591
|
-
const JSONObj = insertJSONObj || JSON.parse(getLangTranslateJSONFile());
|
|
592
|
-
const langObj = {};
|
|
593
|
-
Object.keys(JSONObj).forEach(value => {
|
|
594
|
-
langObj[value] = JSONObj[value][key];
|
|
595
|
-
});
|
|
596
|
-
return langObj;
|
|
597
|
-
}
|
|
598
|
-
/**
|
|
599
|
-
* @description: 设置国际化JSON文件
|
|
600
|
-
* @return {*}
|
|
601
|
-
*/
|
|
602
|
-
function setLangTranslateJSONFile(obj) {
|
|
603
|
-
const filePath = path.join(option.globalPath, 'index.json');
|
|
604
|
-
const jsonObj = jsonFormat(obj);
|
|
605
|
-
if (fs.existsSync(filePath)) {
|
|
606
|
-
fs.writeFileSync(filePath, jsonObj);
|
|
607
|
-
}
|
|
608
|
-
else {
|
|
609
|
-
console.log('❌JSON配置文件写入异常,文件不存在');
|
|
610
|
-
}
|
|
611
|
-
}
|
|
612
|
-
/**
|
|
613
|
-
* @description: 构建时把lang配置文件设置到打包后到主文件中
|
|
614
|
-
* @return {*}
|
|
615
|
-
*/
|
|
616
|
-
function buildSetLangConfigToIndexFile() {
|
|
617
|
-
if (!option.buildToDist)
|
|
618
|
-
return;
|
|
619
|
-
let langObjMap = {};
|
|
620
|
-
option.langKey.forEach(item => {
|
|
621
|
-
langObjMap[item] = getLangObjByJSONFileWithLangKey(item);
|
|
622
|
-
});
|
|
623
|
-
if (fs.existsSync(option.distPath)) {
|
|
624
|
-
fs.readdir(option.distPath, (err, files) => {
|
|
625
|
-
if (err) {
|
|
626
|
-
console.error('❌构建文件夹为空,翻译配置无法写入');
|
|
627
|
-
return;
|
|
628
|
-
}
|
|
629
|
-
files.forEach(file => {
|
|
630
|
-
if (file.startsWith(option.distKey) && file.endsWith('.js')) {
|
|
631
|
-
const filePath = path.join(option.distPath, file);
|
|
632
|
-
fs.readFile(filePath, 'utf-8', (err, data) => {
|
|
633
|
-
if (err) {
|
|
634
|
-
console.log(filePath);
|
|
635
|
-
console.error('❌构建主文件不存在,翻译配置无法写入');
|
|
636
|
-
return;
|
|
637
|
-
}
|
|
638
|
-
let buildLangConfigString = '';
|
|
639
|
-
Object.keys(langObjMap).forEach(item => {
|
|
640
|
-
buildLangConfigString =
|
|
641
|
-
buildLangConfigString +
|
|
642
|
-
`window['${option.namespace}']['${item}']=${JSON.stringify(langObjMap[item])};`;
|
|
643
|
-
});
|
|
644
|
-
try {
|
|
645
|
-
// 翻译配置写入主文件
|
|
646
|
-
fs.writeFileSync(filePath, `window['${option.namespace}']={};${buildLangConfigString}` + data);
|
|
647
|
-
console.info('恭喜:翻译配置写入构建主文件成功🌟🌟🌟');
|
|
648
|
-
}
|
|
649
|
-
catch (err) {
|
|
650
|
-
console.error('翻译配置写入构建主文件失败:', err);
|
|
651
|
-
}
|
|
652
|
-
});
|
|
653
|
-
}
|
|
654
|
-
});
|
|
655
|
-
});
|
|
656
|
-
}
|
|
657
|
-
}
|
|
658
|
-
|
|
659
|
-
var file = /*#__PURE__*/Object.freeze({
|
|
660
|
-
__proto__: null,
|
|
661
|
-
buildSetLangConfigToIndexFile: buildSetLangConfigToIndexFile,
|
|
662
|
-
getLangObjByJSONFileWithLangKey: getLangObjByJSONFileWithLangKey,
|
|
663
|
-
getLangTranslateJSONFile: getLangTranslateJSONFile,
|
|
664
|
-
initLangFile: initLangFile,
|
|
665
|
-
initLangTranslateJSONFile: initLangTranslateJSONFile,
|
|
666
|
-
initTranslateBasicFnFile: initTranslateBasicFnFile,
|
|
667
|
-
setLangTranslateJSONFile: setLangTranslateJSONFile
|
|
668
|
-
});
|
|
669
|
-
|
|
670
|
-
/*
|
|
671
|
-
* @Author: xiaoshanwen
|
|
672
|
-
* @Date: 2023-10-30 18:23:03
|
|
673
|
-
* @LastEditTime: 2024-04-06 17:17:19
|
|
674
|
-
* @FilePath: /i18n_translation_vite/autoI18nPluginCore/src/utils/translate/index.ts
|
|
675
|
-
*/
|
|
676
|
-
let langObj = {};
|
|
677
|
-
/**
|
|
678
|
-
* @description: 设置翻译对象属性
|
|
679
|
-
* @param {string} key
|
|
680
|
-
* @param {string} value
|
|
681
|
-
* @return {*}
|
|
682
|
-
*/
|
|
683
|
-
function setLangObj(key, value) {
|
|
684
|
-
if (!langObj[key]) {
|
|
685
|
-
langObj[key] = value;
|
|
686
|
-
}
|
|
687
|
-
}
|
|
688
|
-
/**
|
|
689
|
-
* @description: 读取翻译对象
|
|
690
|
-
* @return {*}
|
|
691
|
-
*/
|
|
692
|
-
function getLangObj() {
|
|
693
|
-
return langObj;
|
|
694
|
-
}
|
|
695
|
-
/**
|
|
696
|
-
* @description: 初始化翻译对象
|
|
697
|
-
* @param {langObj} obj
|
|
698
|
-
* @return {*}
|
|
699
|
-
*/
|
|
700
|
-
function initLangObj(obj) {
|
|
701
|
-
if (!Object.keys(langObj)) {
|
|
702
|
-
langObj = obj;
|
|
703
|
-
}
|
|
704
|
-
}
|
|
705
|
-
/**
|
|
706
|
-
* @description: 生成国际化配置文件
|
|
707
|
-
* @return {*}
|
|
708
|
-
*/
|
|
709
|
-
async function autoTranslate() {
|
|
710
|
-
let originLangObjMap = {};
|
|
711
|
-
// 获取原始语言
|
|
712
|
-
option.langKey.forEach(item => {
|
|
713
|
-
originLangObjMap[item] = getLangObjByJSONFileWithLangKey(item);
|
|
714
|
-
});
|
|
715
|
-
// 拿到更新后的语言
|
|
716
|
-
const langObj = JSON.parse(JSON.stringify(getLangObj()));
|
|
717
|
-
// 生产需要更新的语言对象
|
|
718
|
-
let transLangObj = {};
|
|
719
|
-
Object.keys(langObj).forEach(key => {
|
|
720
|
-
if (!originLangObjMap[option.originLang][key]) {
|
|
721
|
-
transLangObj[key] = langObj[key];
|
|
722
|
-
}
|
|
723
|
-
});
|
|
724
|
-
// 没有需要翻译的
|
|
725
|
-
if (!Object.keys(transLangObj).length) {
|
|
726
|
-
console.info('没有需要翻译的内容!');
|
|
727
|
-
return;
|
|
728
|
-
}
|
|
729
|
-
// 创建翻译文本
|
|
730
|
-
let text = Object.values(transLangObj).join('\n┇┇┇\n');
|
|
731
|
-
let newLangObjMap = {};
|
|
732
|
-
for (let index = 0; index < option.langKey.length; index++) {
|
|
733
|
-
if (index === 0) {
|
|
734
|
-
newLangObjMap[option.originLang] = transLangObj;
|
|
735
|
-
continue;
|
|
736
|
-
}
|
|
737
|
-
console.info('开始自动翻译...');
|
|
738
|
-
const res = await option.translator.translate(text, option.originLang, option.langKey[index]);
|
|
739
|
-
const resultValues = res.split(/\n┇ *┇ *┇\n/).map(v => v.trim()); // 拆分文案
|
|
740
|
-
if (resultValues.length !== Object.values(transLangObj).length) {
|
|
741
|
-
console.error('翻译异常,翻译结果缺失❌');
|
|
742
|
-
return;
|
|
743
|
-
}
|
|
744
|
-
newLangObjMap[option.langKey[index]] = resultValues;
|
|
745
|
-
console.info('翻译成功⭐️⭐️⭐️');
|
|
746
|
-
}
|
|
747
|
-
Object.keys(transLangObj).forEach((key, index) => {
|
|
748
|
-
option.langKey.forEach((item, i) => {
|
|
749
|
-
if (i === 0) {
|
|
750
|
-
originLangObjMap[item][key] = newLangObjMap[item][key];
|
|
751
|
-
}
|
|
752
|
-
else {
|
|
753
|
-
originLangObjMap[item][key] = newLangObjMap[item][index];
|
|
754
|
-
}
|
|
755
|
-
});
|
|
756
|
-
});
|
|
757
|
-
console.log('开始写入JSON配置文件...');
|
|
758
|
-
const configLangObj = {};
|
|
759
|
-
Object.keys(originLangObjMap[option.originLang]).forEach(key => {
|
|
760
|
-
configLangObj[key] = {};
|
|
761
|
-
option.langKey.forEach(item => {
|
|
762
|
-
configLangObj[key][item] = originLangObjMap[item][key];
|
|
763
|
-
});
|
|
764
|
-
});
|
|
765
|
-
try {
|
|
766
|
-
setLangTranslateJSONFile(configLangObj);
|
|
767
|
-
console.info('JSON配置文件写入成功⭐️⭐️⭐️');
|
|
768
|
-
}
|
|
769
|
-
catch (error) {
|
|
770
|
-
console.error('❌JSON配置文件写入失败' + error);
|
|
771
|
-
}
|
|
772
|
-
}
|
|
773
|
-
/**
|
|
774
|
-
* @description: 新增语言类型配置补全
|
|
775
|
-
* @param {any} obj
|
|
776
|
-
* @return {*}
|
|
777
|
-
*/
|
|
778
|
-
function languageConfigCompletion(obj) {
|
|
779
|
-
if (!Object.keys(obj))
|
|
780
|
-
return;
|
|
781
|
-
let needCompletionList = [];
|
|
782
|
-
const JSONobj = JSON.parse(getLangTranslateJSONFile());
|
|
783
|
-
option.targetLangList.forEach(item => {
|
|
784
|
-
let langObj = getLangObjByJSONFileWithLangKey(item, JSONobj);
|
|
785
|
-
needCompletionList.push({
|
|
786
|
-
key: item,
|
|
787
|
-
curLangObj: langObj
|
|
788
|
-
});
|
|
789
|
-
});
|
|
790
|
-
needCompletionList.forEach(async (item) => {
|
|
791
|
-
await completionTranslateAndWriteConfigFile(obj, item.curLangObj, item.key);
|
|
792
|
-
});
|
|
793
|
-
}
|
|
794
|
-
/**
|
|
795
|
-
* @description: 补全新增语言翻译写入函数
|
|
796
|
-
* @param {any} langObj
|
|
797
|
-
* @param {any} curLangObj
|
|
798
|
-
* @param {string} translateKey
|
|
799
|
-
* @return {*}
|
|
800
|
-
*/
|
|
801
|
-
async function completionTranslateAndWriteConfigFile(langObj, curLangObj, translateKey) {
|
|
802
|
-
// 生产需要更新的语言对象
|
|
803
|
-
let transLangObj = {};
|
|
804
|
-
Object.keys(langObj).forEach(key => {
|
|
805
|
-
if (!curLangObj[key]) {
|
|
806
|
-
transLangObj[key] = langObj[key];
|
|
807
|
-
}
|
|
808
|
-
});
|
|
809
|
-
if (!Object.values(transLangObj).length)
|
|
810
|
-
return;
|
|
811
|
-
// 创建翻译文本
|
|
812
|
-
let text = Object.values(transLangObj).join('\n┇┇┇\n');
|
|
813
|
-
console.info('进入新增语言补全翻译...');
|
|
814
|
-
const res = await option.translator.translate(text, option.originLang, translateKey);
|
|
815
|
-
const resultValues = res.split(/\n┇ *┇ *┇\n/).map(v => v.trim()); // 拆分文案
|
|
816
|
-
if (resultValues.length !== Object.values(langObj).length) {
|
|
817
|
-
console.error('翻译异常,翻译结果缺失❌');
|
|
818
|
-
return;
|
|
819
|
-
}
|
|
820
|
-
let newLangObjMap = resultValues;
|
|
821
|
-
console.info('翻译成功⭐️⭐️⭐️');
|
|
822
|
-
Object.keys(transLangObj).forEach((key, index) => {
|
|
823
|
-
curLangObj[key] = newLangObjMap[index];
|
|
824
|
-
});
|
|
825
|
-
console.log('开始写入JSON配置文件...');
|
|
826
|
-
const configLangObj = JSON.parse(getLangTranslateJSONFile());
|
|
827
|
-
Object.keys(transLangObj).forEach(key => {
|
|
828
|
-
configLangObj[key][translateKey] = curLangObj[key];
|
|
829
|
-
});
|
|
830
|
-
try {
|
|
831
|
-
setLangTranslateJSONFile(configLangObj);
|
|
832
|
-
console.info('JSON配置文件写入成功⭐️⭐️⭐️');
|
|
833
|
-
}
|
|
834
|
-
catch (error) {
|
|
835
|
-
console.error('❌JSON配置文件写入失败' + error);
|
|
836
|
-
}
|
|
837
|
-
console.info('新增语言翻译补全成功⭐️⭐️⭐️');
|
|
838
|
-
}
|
|
839
|
-
|
|
840
|
-
var translate = /*#__PURE__*/Object.freeze({
|
|
841
|
-
__proto__: null,
|
|
842
|
-
autoTranslate: autoTranslate,
|
|
843
|
-
completionTranslateAndWriteConfigFile: completionTranslateAndWriteConfigFile,
|
|
844
|
-
getLangObj: getLangObj,
|
|
845
|
-
initLangObj: initLangObj,
|
|
846
|
-
get langObj () { return langObj; },
|
|
847
|
-
languageConfigCompletion: languageConfigCompletion,
|
|
848
|
-
setLangObj: setLangObj
|
|
849
|
-
});
|
|
850
|
-
|
|
851
|
-
/*
|
|
852
|
-
* @Author: xiaoshanwen
|
|
853
|
-
* @Date: 2023-10-12 18:18:51
|
|
854
|
-
* @LastEditTime: 2023-11-20 13:33:55
|
|
855
|
-
* @FilePath: /i18n_translation_vite/vitePluginsAutoI18n/src/filter/visitor/StringLiteral.ts
|
|
856
|
-
*/
|
|
857
|
-
function StringLiteral (path) {
|
|
858
|
-
let { node, parent } = path;
|
|
859
|
-
let value = node.value;
|
|
860
|
-
// 是否存在来源语言字符,是否在默认字符串中
|
|
861
|
-
if (hasOriginSymbols(value) &&
|
|
862
|
-
option.excludedPattern.length &&
|
|
863
|
-
!checkAgainstRegexArray(value, [...option.excludedPattern])) {
|
|
864
|
-
// 获取真实调用函数
|
|
865
|
-
const extractFnName = extractFunctionName(parent);
|
|
866
|
-
// 防止导入语句,只处理那些当前节点不是键值对的键的字符串字面量,调用语句判断当前调用语句是否包含需要过滤的调用语句
|
|
867
|
-
if (types$3.isImportDeclaration(parent) ||
|
|
868
|
-
parent.key === node ||
|
|
869
|
-
(types$3.isCallExpression(parent) &&
|
|
870
|
-
extractFnName &&
|
|
871
|
-
option.excludedCall.includes(extractFnName)))
|
|
872
|
-
return;
|
|
873
|
-
let replaceNode;
|
|
874
|
-
if (types$3.isJSXAttribute(parent)) {
|
|
875
|
-
let expression = createI18nTranslator(value, true);
|
|
876
|
-
replaceNode = types$3.jSXExpressionContainer(expression);
|
|
877
|
-
}
|
|
878
|
-
else {
|
|
879
|
-
replaceNode = createI18nTranslator(value, true);
|
|
880
|
-
}
|
|
881
|
-
path.replaceWith(replaceNode);
|
|
882
|
-
}
|
|
883
|
-
}
|
|
884
|
-
|
|
885
|
-
/*
|
|
886
|
-
* @Author: xiaoshanwen
|
|
887
|
-
* @Date: 2023-10-12 18:18:51
|
|
888
|
-
* @LastEditTime: 2023-10-31 14:37:24
|
|
889
|
-
* @FilePath: /i18n_translation_vite/src/plugins/filter/visitor/CallExpression.ts
|
|
890
|
-
*/
|
|
891
|
-
const types$1 = require('@babel/types');
|
|
892
|
-
// 收集翻译对象
|
|
893
|
-
function CallExpression (path) {
|
|
894
|
-
let { node } = path;
|
|
895
|
-
if (node.callee.name === option.translateKey) {
|
|
896
|
-
let arg = node.arguments || [];
|
|
897
|
-
const id = arg[0]?.value || '';
|
|
898
|
-
const value = arg[1]?.value || '';
|
|
899
|
-
if (id && value && types$1.isStringLiteral(arg[1])) {
|
|
900
|
-
setLangObj(id, value);
|
|
901
|
-
}
|
|
902
|
-
}
|
|
903
|
-
}
|
|
904
|
-
|
|
905
|
-
/*
|
|
906
|
-
* @Author: xiaoshanwen
|
|
907
|
-
* @Date: 2023-11-01 16:35:38
|
|
908
|
-
* @LastEditTime: 2024-12-07 16:45:35
|
|
909
|
-
* @FilePath: /i18n_translation_vite/autoI18nPluginCore/src/filter/visitor/TemplateElement.ts
|
|
910
|
-
*/
|
|
911
|
-
const types = require('@babel/types');
|
|
912
|
-
function TemplateElement (path) {
|
|
913
|
-
let { node, parent } = path;
|
|
914
|
-
if (!node.value)
|
|
915
|
-
return;
|
|
916
|
-
let value = node.value.raw || node.value.cooked; // 获取模板字符串的值
|
|
917
|
-
// 是否存在来源语言字符,是否在默认字符串中,是否包含过滤字段
|
|
918
|
-
if (hasOriginSymbols(value) &&
|
|
919
|
-
option.excludedPattern.length &&
|
|
920
|
-
!checkAgainstRegexArray(value, [...option.excludedPattern])) {
|
|
921
|
-
// 获取真实调用函数
|
|
922
|
-
const extractFnName = extractFunctionName(parent);
|
|
923
|
-
// 调用语句判断当前调用语句是否包含需要过滤的调用语句
|
|
924
|
-
if (types.isCallExpression(parent) &&
|
|
925
|
-
extractFnName &&
|
|
926
|
-
option.excludedCall.includes(extractFnName))
|
|
927
|
-
return;
|
|
928
|
-
// 生成字符类型翻译节点
|
|
929
|
-
let newNode = createI18nTranslator(value);
|
|
930
|
-
// 替换为字符类型翻译节点
|
|
931
|
-
node.value.raw = node.value.cooked = `\${${newNode}}`;
|
|
932
|
-
let id = generateId(value);
|
|
933
|
-
if (id && value) {
|
|
934
|
-
setLangObj(id, value);
|
|
935
|
-
}
|
|
936
|
-
}
|
|
937
|
-
}
|
|
938
|
-
|
|
939
|
-
/*
|
|
940
|
-
* @Author: xiaoshanwen
|
|
941
|
-
* @Date: 2023-11-01 16:35:38
|
|
942
|
-
* @LastEditTime: 2024-12-07 16:45:20
|
|
943
|
-
* @FilePath: /i18n_translation_vite/autoI18nPluginCore/src/filter/visitor/JSXText.ts
|
|
944
|
-
*/
|
|
945
|
-
function JSXText (path) {
|
|
946
|
-
console.log('jsx text');
|
|
947
|
-
let { node } = path;
|
|
948
|
-
let value = node.value;
|
|
949
|
-
// 是否存在来源语言字符,是否在默认字符串中
|
|
950
|
-
if (hasOriginSymbols(value) &&
|
|
951
|
-
option.excludedPattern.length &&
|
|
952
|
-
!checkAgainstRegexArray(value, [...option.excludedPattern])) {
|
|
953
|
-
// 生成翻译节点
|
|
954
|
-
let expression = createI18nTranslator(value, true);
|
|
955
|
-
// 生成的翻译节点包装在 types.JSXExpressionContainer 中
|
|
956
|
-
let newNode = types$3.jSXExpressionContainer(expression);
|
|
957
|
-
// 使用 path.replaceWith 方法将原来的节点替换为新的翻译节点
|
|
958
|
-
path.replaceWith(newNode);
|
|
959
|
-
}
|
|
960
|
-
}
|
|
961
|
-
|
|
962
|
-
/*
|
|
963
|
-
* @Author: xiaoshanwen
|
|
964
|
-
* @Date: 2023-10-12 18:00:37
|
|
965
|
-
* @LastEditTime: 2023-11-02 10:36:02
|
|
966
|
-
* @FilePath: /i18n_translation_vite/src/plugins/filter/index.ts
|
|
967
|
-
*/
|
|
968
|
-
function index () {
|
|
969
|
-
return {
|
|
970
|
-
visitor: {
|
|
971
|
-
StringLiteral,
|
|
972
|
-
JSXText,
|
|
973
|
-
TemplateElement,
|
|
974
|
-
CallExpression
|
|
975
|
-
}
|
|
976
|
-
};
|
|
977
|
-
}
|
|
978
|
-
|
|
979
|
-
var index$1 = /*#__PURE__*/Object.freeze({
|
|
980
|
-
__proto__: null,
|
|
981
|
-
default: index
|
|
982
|
-
});
|
|
983
|
-
|
|
984
|
-
export { FunctionFactoryOption, GoogleTranslator, Translator, YoudaoTranslator, base as baseUtils, checkOption, file as fileUtils, index$1 as filter, initOption, option, translate as translateUtils, index$2 as translator };
|
|
1
|
+
import n from"lodash/cloneDeep";import{translate as t}from"@vitalets/google-translate-api";import e from"tunnel";import r from"axios";import o from"crypto-js";import a from"node:fs";import i from"node:path";import*as c from"@babel/types";var s=function(n,t){return s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,t){n.__proto__=t}||function(n,t){for(var e in t)Object.prototype.hasOwnProperty.call(t,e)&&(n[e]=t[e])},s(n,t)};function l(n,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function e(){this.constructor=n}s(n,t),n.prototype=null===t?Object.create(t):(e.prototype=t.prototype,new e)}var u,f,g=function(){return g=Object.assign||function(n){for(var t,e=1,r=arguments.length;e<r;e++)for(var o in t=arguments[e])Object.prototype.hasOwnProperty.call(t,o)&&(n[o]=t[o]);return n},g.apply(this,arguments)};function p(n,t,e,r){return new(e||(e=Promise))((function(o,a){function i(n){try{s(r.next(n))}catch(n){a(n)}}function c(n){try{s(r.throw(n))}catch(n){a(n)}}function s(n){var t;n.done?o(n.value):(t=n.value,t instanceof e?t:new e((function(n){n(t)}))).then(i,c)}s((r=r.apply(n,t||[])).next())}))}function h(n,t){var e,r,o,a,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function c(c){return function(s){return function(c){if(e)throw new TypeError("Generator is already executing.");for(;a&&(a=0,c[0]&&(i=0)),i;)try{if(e=1,r&&(o=2&c[0]?r.return:c[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,c[1])).done)return o;switch(r=0,o&&(c=[2&c[0],o.value]),c[0]){case 0:case 1:o=c;break;case 4:return i.label++,{value:c[1],done:!1};case 5:i.label++,r=c[1],c=[0];continue;case 7:c=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==c[0]&&2!==c[0])){i=0;continue}if(3===c[0]&&(!o||c[1]>o[0]&&c[1]<o[3])){i.label=c[1];break}if(6===c[0]&&i.label<o[1]){i.label=o[1],o=c;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(c);break}o[2]&&i.ops.pop(),i.trys.pop();continue}c=t.call(n,i)}catch(n){c=[6,n],r=0}finally{e=o=0}if(5&c[0])throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}([c,s])}}}function d(n,t,e){if(e||2===arguments.length)for(var r,o=0,a=t.length;o<a;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return n.concat(r||Array.prototype.slice.call(t))}"function"==typeof SuppressedError&&SuppressedError,function(n){n.ZH="zh-cn",n.EN="en"}(u||(u={})),function(n){n.google="Google",n.youdao="Youdao"}(f||(f={}));var v=function(){function n(n,t,e){this.queue=[],this.isRunning=!1,this.fn=n,this.delay=t,this.timeout=e}return n.prototype.execute=function(){for(var n=this,t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return new Promise((function(e,r){n.queue.push({args:t,resolve:e,reject:r}),n.run(),n.timeout&&setTimeout((function(){r(new Error("IntervalQueue timeout"))}),n.timeout)}))},n.prototype.wait=function(){return p(this,arguments,void 0,(function(n){return void 0===n&&(n=this.delay),h(this,(function(t){switch(t.label){case 0:return[4,new Promise((function(t){return setTimeout(t,n)}))];case 1:return t.sent(),[2]}}))}))},n.prototype.run=function(){return p(this,void 0,void 0,(function(){var n,t,e,r,o,a;return h(this,(function(i){switch(i.label){case 0:if(this.isRunning)return[2];i.label=1;case 1:if(!(n=this.queue.shift()))return[3,7];t=n.args,e=n.resolve,r=n.reject,this.isRunning=!0,i.label=2;case 2:return i.trys.push([2,4,,5]),o=e,[4,this.fn.apply(this,t)];case 3:return o.apply(void 0,[i.sent()]),[3,5];case 4:return a=i.sent(),r(a),[3,5];case 5:return[4,this.wait()];case 6:return i.sent(),[3,1];case 7:return this.isRunning=!1,[2]}}))}))},n}(),y=function(){function n(n){var t,e,r;this.option=n,this.option.interval&&(this.option.fetchMethod=(t=this.option.fetchMethod,e=this.option.interval,r=new v(t.bind(null),e),function(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];return r.execute.apply(r,n)}))}return n.prototype.getErrorMessage=function(n){return n instanceof Error?n.message:String(n)},n.prototype.translate=function(n,t,e){return p(this,void 0,void 0,(function(){var r,o,a;return h(this,(function(i){switch(i.label){case 0:r="",i.label=1;case 1:return i.trys.push([1,3,,4]),[4,this.option.fetchMethod(n,t,e)];case 2:return r=i.sent(),[3,4];case 3:return o=i.sent(),a=this.option.name,console.error("翻译api".concat(a?"【".concat(a,"】"):"","请求异常:").concat(this.getErrorMessage(o))),[3,4];case 4:return[2,r]}}))}))},n}(),b=function(n){function r(r){var o=n.call(this,{name:"Google翻译",fetchMethod:function(n,a,i){return p(o,void 0,void 0,(function(){return h(this,(function(o){switch(o.label){case 0:return[4,t(n,{from:a,to:i,fetchOptions:{agent:e.httpsOverHttp({proxy:r.proxyOption})}})];case 1:return[2,o.sent().text||""]}}))}))}})||this;return o}return l(r,n),r}(y),O=function(n){function t(t){var e,a=n.call(this,{name:"有道翻译",fetchMethod:function(n,e,i){return p(a,void 0,void 0,(function(){var a,c,s,l,u,f,g;return h(this,(function(p){switch(p.label){case 0:return a=(new Date).getTime(),c=Math.round((new Date).getTime()/1e3),s=t.appId+this.truncate(n)+a+c+t.appKey,l=o.SHA256(s).toString(o.enc.Hex),u={q:n,appKey:t.appId,salt:a,from:this.getTranslateKey(e),to:this.getTranslateKey(i),sign:l,signType:"v3",curtime:c},[4,r.post("https://openapi.youdao.com/api",u,{headers:{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},proxy:t.proxy})];case 1:return f=p.sent(),[2,(null===(g=f.data.translation)||void 0===g?void 0:g[0])||""]}}))}))},interval:null!==(e=t.interval)&&void 0!==e?e:1e3})||this;return a.YOUDAO_TRANSLATE_KEY_CONVERT_MAP={"zh-cn":"zh-CHS","zh-tw":"zh-CHT"},a}return l(t,n),t.prototype.truncate=function(n){if(n.length<=20)return n;var t=n.length;return n.substring(0,10)+t+n.substring(t-10)},t.prototype.getTranslateKey=function(n){return this.YOUDAO_TRANSLATE_KEY_CONVERT_MAP[n]||n},t}(y),m=Object.freeze({__proto__:null,GoogleTranslator:b,Translator:y,YoudaoTranslator:O}),S={translateKey:"$t",excludedCall:["$i8n","require","$$i8n","console.log","$t"],excludedPattern:[/\.\w+$/],excludedPath:["node_modules"],includePath:[/src\//],globalPath:"./lang",distPath:"",distKey:"index",originLang:u.ZH,targetLangList:["en"],langKey:[],namespace:"",buildToDist:!1,translator:new b({proxyOption:{port:7890,host:"127.0.0.1",headers:{"User-Agent":"Node"}}}),translatorOption:void 0},j=g({},S);function x(t){j=g(g({},S),function(t){var e=n(t.option);return e.translator||(e.translator=e.translatorOption?new y(e.translatorOption):void 0),e.translator||delete e.translator,e}(t)),j.langKey=d([j.originLang],j.targetLangList,!0)}function w(){return j.translateKey?j.namespace?j.buildToDist&&!j.distKey?(console.log("❌请配置打包后生成文件的主文件名称"),!1):j.buildToDist&&!j.distPath?(console.log("❌请配置打包后生成文件的位置"),!1):j.originLang?!(!j.targetLangList||!j.targetLangList.length)||(console.error("❌请配置目标翻译语言数组"),!1):(console.error("❌请配置来源语言"),!1):(console.error("❌请配置命名空间"),!1):(console.error("❌请配置翻译调用函数"),!1)}var E,L=function(){function n(){}return n.originLang="",n}(),T=((E={})[u.ZH]=/[\u4e00-\u9fff]/,E[u.EN]=/[a-zA-Z]/,E),_=require("@babel/types");function N(n){var t=L.originLang;return T[t].test(n)}function P(n,t){for(var e=0;e<t.length;e++){if(("string"==typeof t[e]?new RegExp(t[e]):t[e]).test(n))return!0}return!1}function k(n){var t="";return _.isCallExpression(n)&&(t=_.isMemberExpression(n.callee)?function n(t,e){return e+="."+t.property.name,_.isMemberExpression(t.object)?n(t.object,e):e=t.object.name+e}(n.callee,""):n.callee.name||""),t}function J(n,t){var e=n.match(t);return e?e.filter((function(n,t){return e.indexOf(n)===t})):[]}function K(n,t,e){var r=j.namespace,o=n.trim(),a=o.replace(/'/g,'"').replace(/(\n)/g,"\\n"),i=e||C(a);if(t){var c=_.stringLiteral(o);return c.extra={raw:"'".concat(a,"'"),rawValue:o},_.callExpression(_.identifier(j.translateKey),[_.stringLiteral(i),c,_.stringLiteral(r)])}return"".concat(j.translateKey,"('").concat(i,"','").concat(a,"','").concat(r,"')")}function C(n){for(var t=0,e=0;e<n.length;e++){t=(t<<5)-t+n.charCodeAt(e),t|=0}return Math.abs(t).toString(36)+n.length.toString(36)}var A=Object.freeze({__proto__:null,checkAgainstRegexArray:P,createI18nTranslator:K,extractCnStrings:function(n){return J(n,/[^\x00-\xff]+/g)},extractFunctionName:k,extractStrings:J,generateId:C,hasOriginSymbols:N,removeComments:function(n){return n=(n=(n=n.replace(/\/\/.*?\n/g,"")).replace(/\/\*[\s\S]*?\*\//g,"")).replace(/<!--[\s\S]*?-->/g,"")},truncate:function(n){if(n.length<=20)return n;var t=n.length;return n.substring(0,10)+t+n.substring(t-10)},unicodeToChinese:function(n){return n.replace(/\\u[\dA-Fa-f]{4}/g,(function(n){return String.fromCharCode(parseInt(n.replace(/\\u/g,""),16))}))}}),F=require("json-format");function M(){var n=j.translateKey,t="(function () {\n let ".concat(n," = function (key, val, nameSpace) {\n const langPackage = ").concat(n,"[nameSpace]\n return (langPackage || {})[key] || val;\n };\n let $").concat(n," = function (val) {\n return val;\n };\n ").concat(n,".locale = function (locale, nameSpace) {\n ").concat(n,"[nameSpace] = locale || {};\n };\n window.").concat(n," = window.").concat(n," || ").concat(n,";\n window.$").concat(n," = $").concat(n,";\n window._getJSONKey = function (key, insertJSONObj = undefined) {\n const JSONObj = insertJSONObj\n const langObj = {}\n Object.keys(JSONObj).forEach((value)=>{\n langObj[value] = JSONObj[value][key]\n })\n return langObj\n }\n })();"),e=i.join(j.globalPath,"index.js");a.existsSync(e)||a.writeFileSync(e,t)}function z(){var n=i.join(j.globalPath,"index.json");a.existsSync(n)||a.writeFileSync(n,JSON.stringify({}))}function D(){var n=i.join(j.globalPath,"index.json");try{return a.readFileSync(n,"utf-8")}catch(n){return"ENOENT"===n.code?console.log("❌读取JSON配置文件异常,文件不存在"):console.log("❌读取JSON配置文件异常,无法读取文件"),JSON.stringify({})}}function R(n,t){void 0===t&&(t=void 0);var e=t||JSON.parse(D()),r={};return Object.keys(e).forEach((function(t){r[t]=e[t][n]})),r}function $(n){var t=i.join(j.globalPath,"index.json"),e=F(n);a.existsSync(t)?a.writeFileSync(t,e):console.log("❌JSON配置文件写入异常,文件不存在")}var q=Object.freeze({__proto__:null,buildSetLangConfigToIndexFile:function(){if(j.buildToDist){var n={};j.langKey.forEach((function(t){n[t]=R(t)})),a.existsSync(j.distPath)&&a.readdir(j.distPath,(function(t,e){t?console.error("❌构建文件夹为空,翻译配置无法写入"):e.forEach((function(t){if(t.startsWith(j.distKey)&&t.endsWith(".js")){var e=i.join(j.distPath,t);a.readFile(e,"utf-8",(function(t,r){if(t)return console.log(e),void console.error("❌构建主文件不存在,翻译配置无法写入");var o="";Object.keys(n).forEach((function(t){o+="window['".concat(j.namespace,"']['").concat(t,"']=").concat(JSON.stringify(n[t]),";")}));try{a.writeFileSync(e,"window['".concat(j.namespace,"']={};").concat(o)+r),console.info("恭喜:翻译配置写入构建主文件成功🌟🌟🌟")}catch(t){console.error("翻译配置写入构建主文件失败:",t)}}))}}))}))}},getLangObjByJSONFileWithLangKey:R,getLangTranslateJSONFile:D,initLangFile:function(){a.existsSync(j.globalPath)||a.mkdirSync(j.globalPath),z(),M()},initLangTranslateJSONFile:z,initTranslateBasicFnFile:M,setLangTranslateJSONFile:$}),H={};function I(n,t){H[n]||(H[n]=t)}function U(){return H}function W(n,t,e){return p(this,void 0,void 0,(function(){var r,o,a,i,c,s;return h(this,(function(l){switch(l.label){case 0:return r={},Object.keys(n).forEach((function(e){t[e]||(r[e]=n[e])})),Object.values(r).length?(o=Object.values(r).join("\n┇┇┇\n"),console.info("进入新增语言补全翻译..."),[4,j.translator.translate(o,j.originLang,e)]):[2];case 1:if(a=l.sent(),(i=a.split(/\n┇ *┇ *┇\n/).map((function(n){return n.trim()}))).length!==Object.values(n).length)return console.error("翻译异常,翻译结果缺失❌"),[2];c=i,console.info("翻译成功⭐️⭐️⭐️"),Object.keys(r).forEach((function(n,e){t[n]=c[e]})),console.log("开始写入JSON配置文件..."),s=JSON.parse(D()),Object.keys(r).forEach((function(n){s[n][e]=t[n]}));try{$(s),console.info("JSON配置文件写入成功⭐️⭐️⭐️")}catch(n){console.error("❌JSON配置文件写入失败"+n)}return console.info("新增语言翻译补全成功⭐️⭐️⭐️"),[2]}}))}))}var Y=Object.freeze({__proto__:null,autoTranslate:function(){return p(this,void 0,void 0,(function(){var n,t,e,r,o,a,i,c,s;return h(this,(function(l){switch(l.label){case 0:if(n={},j.langKey.forEach((function(t){n[t]=R(t)})),t=JSON.parse(JSON.stringify(U())),e={},Object.keys(t).forEach((function(r){n[j.originLang][r]||(e[r]=t[r])})),!Object.keys(e).length)return console.info("没有需要翻译的内容!"),[2];r=Object.values(e).join("\n┇┇┇\n"),o={},a=0,l.label=1;case 1:return a<j.langKey.length?0===a?(o[j.originLang]=e,[3,3]):(console.info("开始自动翻译..."),[4,j.translator.translate(r,j.originLang,j.langKey[a])]):[3,4];case 2:if(i=l.sent(),(c=i.split(/\n┇ *┇ *┇\n/).map((function(n){return n.trim()}))).length!==Object.values(e).length)return console.error("翻译异常,翻译结果缺失❌"),[2];o[j.langKey[a]]=c,console.info("翻译成功⭐️⭐️⭐️"),l.label=3;case 3:return a++,[3,1];case 4:Object.keys(e).forEach((function(t,e){j.langKey.forEach((function(r,a){n[r][t]=0===a?o[r][t]:o[r][e]}))})),console.log("开始写入JSON配置文件..."),s={},Object.keys(n[j.originLang]).forEach((function(t){s[t]={},j.langKey.forEach((function(e){s[t][e]=n[e][t]}))}));try{$(s),console.info("JSON配置文件写入成功⭐️⭐️⭐️")}catch(n){console.error("❌JSON配置文件写入失败"+n)}return[2]}}))}))},completionTranslateAndWriteConfigFile:W,getLangObj:U,initLangObj:function(n){Object.keys(H)||(H=n)},get langObj(){return H},languageConfigCompletion:function(n){var t=this;if(Object.keys(n)){var e=[],r=JSON.parse(D());j.targetLangList.forEach((function(n){var t=R(n,r);e.push({key:n,curLangObj:t})})),e.forEach((function(e){return p(t,void 0,void 0,(function(){return h(this,(function(t){switch(t.label){case 0:return[4,W(n,e.curLangObj,e.key)];case 1:return t.sent(),[2]}}))}))}))}},setLangObj:I});function G(n){var t=n.node,e=n.parent,r=t.value;if(N(r)&&j.excludedPattern.length&&!P(r,d([],j.excludedPattern,!0))){var o=k(e);if(c.isImportDeclaration(e)||e.key===t||c.isCallExpression(e)&&o&&j.excludedCall.includes(o))return;var a=void 0;if(c.isJSXAttribute(e)){var i=K(r,!0);a=c.jSXExpressionContainer(i)}else a=K(r,!0);n.replaceWith(a)}}var X=require("@babel/types");function Z(n){var t,e,r=n.node;if(r.callee.name===j.translateKey){var o=r.arguments||[],a=(null===(t=o[0])||void 0===t?void 0:t.value)||"",i=(null===(e=o[1])||void 0===e?void 0:e.value)||"";a&&i&&X.isStringLiteral(o[1])&&I(a,i)}}var V=require("@babel/types");function B(n){var t=n.node,e=n.parent;if(t.value){var r=t.value.raw||t.value.cooked;if(N(r)&&j.excludedPattern.length&&!P(r,d([],j.excludedPattern,!0))){var o=k(e);if(V.isCallExpression(e)&&o&&j.excludedCall.includes(o))return;var a=K(r);t.value.raw=t.value.cooked="${".concat(a,"}");var i=C(r);i&&r&&I(i,r)}}}function Q(n){console.log("jsx text");var t=n.node.value;if(N(t)&&j.excludedPattern.length&&!P(t,d([],j.excludedPattern,!0))){var e=K(t,!0),r=c.jSXExpressionContainer(e);n.replaceWith(r)}}var nn=Object.freeze({__proto__:null,default:function(){return{visitor:{StringLiteral:G,JSXText:Q,TemplateElement:B,CallExpression:Z}}}});export{L as FunctionFactoryOption,b as GoogleTranslator,y as Translator,O as YoudaoTranslator,A as baseUtils,w as checkOption,q as fileUtils,nn as filter,x as initOption,j as option,Y as translateUtils,m as translator};
|
|
2
|
+
//# sourceMappingURL=index.mjs.map
|