vite-gc-i18n-plugin 1.1.0 → 1.1.2

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 CHANGED
@@ -1,2 +1,2736 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("gc-i18n-plugin-core");function t(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}})),t.default=e,Object.freeze(t)}var n=t(require("@babel/core")),r=function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},r.apply(this,arguments)};function o(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{c(r.next(e))}catch(e){i(e)}}function l(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,l)}c((r=r.apply(e,t||[])).next())}))}function i(e,t){var n,r,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=l(0),a.throw=l(1),a.return=l(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function l(l){return function(c){return function(l){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,l[0]&&(i=0)),i;)try{if(n=1,r&&(o=2&l[0]?r.return:l[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,l[1])).done)return o;switch(r=0,o&&(l=[2&l[0],o.value]),l[0]){case 0:case 1:o=l;break;case 4:return i.label++,{value:l[1],done:!1};case 5:i.label++,r=l[1],l=[0];continue;case 7:l=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==l[0]&&2!==l[0])){i=0;continue}if(3===l[0]&&(!o||l[1]>o[0]&&l[1]<o[3])){i.label=l[1];break}if(6===l[0]&&i.label<o[1]){i.label=o[1],o=l;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(l);break}o[2]&&i.ops.pop(),i.trys.pop();continue}l=t.call(e,i)}catch(e){l=[6,e],r=0}finally{n=o=0}if(5&l[0])throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}([l,c])}}}function a(e,t,n){if(n||2===arguments.length)for(var r,o=0,i=t.length;o<i;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))}"function"==typeof SuppressedError&&SuppressedError;var l=[".vue",".ts",".js",".tsx",".jsx"];exports.default=function(t){var c,u="vite-gc-i18n-plugin";if(e.initOption(r({deepScan:!0,globalPath:"./lang",namespace:"lang",translateKey:"$t",distPath:"./dist/assets",distKey:"index",targetLangList:["zh-cn","zh-tw"],originLang:"zh-cn",translator:new e.CNToTWTranslator},t)),!e.checkOption())return{name:u};e.fileUtils.initLangFile();var s=e.fileUtils.getLangObjByJSONFileWithLangKey(e.option.originLang);return e.translateUtils.languageConfigCompletion(s),e.translateUtils.initLangObj(s),{name:u,configResolved:function(e){c=e},transform:function(t,r){return o(this,void 0,void 0,(function(){var o,u;return i(this,(function(i){switch(i.label){case 0:return a(a([],l,!0),e.option.insertFileExtensions||[],!0).some((function(e){return r.endsWith(e)}))?e.option.includePath.length&&!e.baseUtils.checkAgainstRegexArray(r,e.option.includePath)||e.option.excludedPath.length&&e.baseUtils.checkAgainstRegexArray(r,e.option.excludedPath)?[2,t]:(e.FunctionFactoryOption.originLang=e.option.originLang,o=void 0,e.option.translateExtends?[4,null===(u=e.option.translateExtends)||void 0===u?void 0:u.handleInitFile(t,r)]:[3,2]):[3,4];case 1:return o=i.sent(),[3,3];case 2:o={source:t},i.label=3;case 3:return[2,n.transformAsync(o.source,{configFile:!1,plugins:[e.filter.default()]}).then((function(t){return"serve"===(null==c?void 0:c.command)&&e.translateUtils.autoTranslate(),null==t?void 0:t.code})).catch((function(e){console.error(e)}))];case 4:return[2]}}))}))},buildEnd:function(){return o(this,void 0,void 0,(function(){return i(this,(function(t){switch(t.label){case 0:return console.info("构建阶段批量翻译"),[4,e.translateUtils.autoTranslate()];case 1:return t.sent(),[2]}}))}))},closeBundle:function(){return o(this,void 0,void 0,(function(){return i(this,(function(t){switch(t.label){case 0:return c&&"build"===c.command?e.option.uploadEnabled?(console.info("构建阶段:开始上传翻译文件"),[4,e.fileUtils.uploadFile()]):[3,2]:[3,3];case 1:return t.sent(),[3,3];case 2:console.info("构建阶段:上传翻译文件功能已禁用(uploadEnabled: false)"),t.label=3;case 3:return[2]}}))}))}}},Object.keys(e).forEach((function(t){"default"===t||Object.prototype.hasOwnProperty.call(exports,t)||Object.defineProperty(exports,t,{enumerable:!0,get:function(){return e[t]}})}));
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var googleTranslateApi = require('@vitalets/google-translate-api');
6
+ var tunnel = require('tunnel');
7
+ var axios = require('axios');
8
+ var CryptoJS = require('crypto-js');
9
+ var OpenCC = require('opencc-js');
10
+ var types = require('@babel/types');
11
+ var _ = require('lodash');
12
+ var path = require('node:path');
13
+ var fs = require('node:fs');
14
+ var babel = require('@babel/core');
15
+ var generate = require('@babel/generator');
16
+
17
+ function _interopNamespaceDefault(e) {
18
+ var n = Object.create(null);
19
+ if (e) {
20
+ Object.keys(e).forEach(function (k) {
21
+ if (k !== 'default') {
22
+ var d = Object.getOwnPropertyDescriptor(e, k);
23
+ Object.defineProperty(n, k, d.get ? d : {
24
+ enumerable: true,
25
+ get: function () { return e[k]; }
26
+ });
27
+ }
28
+ });
29
+ }
30
+ n.default = e;
31
+ return Object.freeze(n);
32
+ }
33
+
34
+ var OpenCC__namespace = /*#__PURE__*/_interopNamespaceDefault(OpenCC);
35
+ var types__namespace = /*#__PURE__*/_interopNamespaceDefault(types);
36
+ var babel__namespace = /*#__PURE__*/_interopNamespaceDefault(babel);
37
+ var generate__namespace = /*#__PURE__*/_interopNamespaceDefault(generate);
38
+
39
+ /******************************************************************************
40
+ Copyright (c) Microsoft Corporation.
41
+
42
+ Permission to use, copy, modify, and/or distribute this software for any
43
+ purpose with or without fee is hereby granted.
44
+
45
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
46
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
47
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
48
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
49
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
50
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
51
+ PERFORMANCE OF THIS SOFTWARE.
52
+ ***************************************************************************** */
53
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
54
+
55
+ var __assign = function () {
56
+ __assign = Object.assign || function __assign(t) {
57
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
58
+ s = arguments[i];
59
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
60
+ }
61
+ return t;
62
+ };
63
+ return __assign.apply(this, arguments);
64
+ };
65
+ function __awaiter(thisArg, _arguments, P, generator) {
66
+ function adopt(value) {
67
+ return value instanceof P ? value : new P(function (resolve) {
68
+ resolve(value);
69
+ });
70
+ }
71
+ return new (P || (P = Promise))(function (resolve, reject) {
72
+ function fulfilled(value) {
73
+ try {
74
+ step(generator.next(value));
75
+ } catch (e) {
76
+ reject(e);
77
+ }
78
+ }
79
+ function rejected(value) {
80
+ try {
81
+ step(generator["throw"](value));
82
+ } catch (e) {
83
+ reject(e);
84
+ }
85
+ }
86
+ function step(result) {
87
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
88
+ }
89
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
90
+ });
91
+ }
92
+ function __generator(thisArg, body) {
93
+ var _ = {
94
+ label: 0,
95
+ sent: function () {
96
+ if (t[0] & 1) throw t[1];
97
+ return t[1];
98
+ },
99
+ trys: [],
100
+ ops: []
101
+ },
102
+ f,
103
+ y,
104
+ t,
105
+ g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
106
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function () {
107
+ return this;
108
+ }), g;
109
+ function verb(n) {
110
+ return function (v) {
111
+ return step([n, v]);
112
+ };
113
+ }
114
+ function step(op) {
115
+ if (f) throw new TypeError("Generator is already executing.");
116
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
117
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
118
+ if (y = 0, t) op = [op[0] & 2, t.value];
119
+ switch (op[0]) {
120
+ case 0:
121
+ case 1:
122
+ t = op;
123
+ break;
124
+ case 4:
125
+ _.label++;
126
+ return {
127
+ value: op[1],
128
+ done: false
129
+ };
130
+ case 5:
131
+ _.label++;
132
+ y = op[1];
133
+ op = [0];
134
+ continue;
135
+ case 7:
136
+ op = _.ops.pop();
137
+ _.trys.pop();
138
+ continue;
139
+ default:
140
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
141
+ _ = 0;
142
+ continue;
143
+ }
144
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
145
+ _.label = op[1];
146
+ break;
147
+ }
148
+ if (op[0] === 6 && _.label < t[1]) {
149
+ _.label = t[1];
150
+ t = op;
151
+ break;
152
+ }
153
+ if (t && _.label < t[2]) {
154
+ _.label = t[2];
155
+ _.ops.push(op);
156
+ break;
157
+ }
158
+ if (t[2]) _.ops.pop();
159
+ _.trys.pop();
160
+ continue;
161
+ }
162
+ op = body.call(thisArg, _);
163
+ } catch (e) {
164
+ op = [6, e];
165
+ y = 0;
166
+ } finally {
167
+ f = t = 0;
168
+ }
169
+ if (op[0] & 5) throw op[1];
170
+ return {
171
+ value: op[0] ? op[1] : void 0,
172
+ done: true
173
+ };
174
+ }
175
+ }
176
+ function __spreadArray(to, from, pack) {
177
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
178
+ if (ar || !(i in from)) {
179
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
180
+ ar[i] = from[i];
181
+ }
182
+ }
183
+ return to.concat(ar || Array.prototype.slice.call(from));
184
+ }
185
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
186
+ var e = new Error(message);
187
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
188
+ };
189
+
190
+ /**
191
+ * 间隔执行队列
192
+ */
193
+ class IntervalQueue {
194
+ /**
195
+ * @param fn 执行函数
196
+ * @param delay 执行间隔
197
+ * @param timeout 超时时间
198
+ */
199
+ constructor(fn, delay, timeout) {
200
+ this.fn = fn;
201
+ this.delay = delay;
202
+ this.timeout = timeout;
203
+ }
204
+ queue = [];
205
+ async wait() {
206
+ let delay = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.delay;
207
+ await new Promise(resolve => setTimeout(resolve, delay));
208
+ }
209
+ isRunning = false;
210
+ async run() {
211
+ if (this.isRunning) return;
212
+ let item;
213
+ while (item = this.queue.shift()) {
214
+ const {
215
+ args,
216
+ resolve,
217
+ reject
218
+ } = item;
219
+ this.isRunning = true;
220
+ try {
221
+ const result = await this.fn(...args);
222
+ resolve(result);
223
+ } catch (e) {
224
+ reject(e);
225
+ }
226
+ await this.wait();
227
+ }
228
+ this.isRunning = false;
229
+ }
230
+
231
+ /**
232
+ * 执行一次fn
233
+ * @param args fn的入参
234
+ * @returns 返回fn的返回值的Promise
235
+ */
236
+ execute() {
237
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
238
+ args[_key] = arguments[_key];
239
+ }
240
+ return new Promise((resolve, reject) => {
241
+ this.queue.push({
242
+ args,
243
+ resolve,
244
+ reject
245
+ });
246
+ this.run();
247
+ if (this.timeout) {
248
+ setTimeout(() => {
249
+ reject(new Error('IntervalQueue timeout'));
250
+ }, this.timeout);
251
+ }
252
+ });
253
+ }
254
+ }
255
+
256
+ class Translator {
257
+ constructor(option) {
258
+ this.option = this.getResultOption(option);
259
+ }
260
+ defaultErrorHandler = error => {
261
+ const name = this.option.name;
262
+ console.error(`翻译api${name ? `【${name}】` : ''}请求异常:${this.getErrorMessage(error)}`);
263
+ };
264
+ getResultOption(option) {
265
+ const resultOption = {
266
+ version: 1,
267
+ maxChunkSize: 4500,
268
+ // 目前默认是4500
269
+ interval: 0,
270
+ onError: this.defaultErrorHandler,
271
+ ...option
272
+ };
273
+ if (resultOption.interval) {
274
+ const getIntervalFn = (fn, delay) => {
275
+ const queue = new IntervalQueue(fn.bind(null), delay);
276
+ return function () {
277
+ return queue.execute(...arguments);
278
+ };
279
+ };
280
+ resultOption.fetchMethod = getIntervalFn(resultOption.fetchMethod, resultOption.interval);
281
+ }
282
+ return resultOption;
283
+ }
284
+ getErrorMessage(error) {
285
+ if (error instanceof Error) {
286
+ return error.message;
287
+ } else {
288
+ return String(error);
289
+ }
290
+ }
291
+ async translate(text, fromKey, toKey, separator) {
292
+ let result = '';
293
+ try {
294
+ result = await this.option.fetchMethod(text, fromKey, toKey, separator);
295
+ } catch (error) {
296
+ this.option.onError(error, this.defaultErrorHandler);
297
+ }
298
+ return result;
299
+ }
300
+ }
301
+
302
+ /*
303
+ * @Date: 2025-03-11 17:53:11
304
+ * @LastEditors: xiaoshan
305
+ * @LastEditTime: 2025-03-14 14:21:06
306
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/translator/google.ts
307
+ */
308
+ /**
309
+ * 谷歌翻译器
310
+ *
311
+ * 基于@vitalets/google-translate-api,需要翻墙,不稳定,但是免费
312
+ *
313
+ * 使用方式:
314
+ * ```ts
315
+ * vitePluginsAutoI18n({
316
+ ...
317
+ translator: translator: new GoogleTranslator({
318
+ proxyOption: {
319
+ // 如果你本地的代理在127.0.0.0:8899
320
+ host: '127.0.0.1',
321
+ port: 8899,
322
+ headers: {
323
+ 'User-Agent': 'Node'
324
+ }
325
+ }
326
+ })
327
+ })
328
+ * ```
329
+ */
330
+ class GoogleTranslator extends Translator {
331
+ constructor(option) {
332
+ super({
333
+ name: 'Google翻译',
334
+ fetchMethod: async (text, fromKey, toKey) => {
335
+ let data = await googleTranslateApi.translate(text, {
336
+ from: fromKey,
337
+ to: toKey,
338
+ ...(option.proxyOption ? {
339
+ fetchOptions: {
340
+ agent: tunnel.httpsOverHttp({
341
+ proxy: option.proxyOption
342
+ })
343
+ }
344
+ } : {}),
345
+ ...(option.insertOption || {})
346
+ });
347
+ return data['text'] || '';
348
+ },
349
+ onError: (error, cb) => {
350
+ cb(error);
351
+ if (error instanceof Object && 'code' in error && error.code === 'ETIMEDOUT') {
352
+ console.error('❗ 请求超时,请确保你的网络可以访问google ❗');
353
+ }
354
+ },
355
+ interval: option.interval ?? 1000
356
+ });
357
+ }
358
+ }
359
+
360
+ /**
361
+ * 有道翻译器
362
+ *
363
+ * api文档:https://ai.youdao.com/DOCSIRMA/html/trans/api/wbfy/index.html
364
+ *
365
+ * 使用方式:
366
+ * ```ts
367
+ * vitePluginsAutoI18n({
368
+ ...
369
+ translator: new YoudaoTranslator({
370
+ appId: '你申请的appId',
371
+ appKey: '你申请的appKey'
372
+ })
373
+ })
374
+ * ```
375
+ */
376
+ class YoudaoTranslator extends Translator {
377
+ /** 有道的语言类型映射不标准,需要手动控制 */
378
+ YOUDAO_TRANSLATE_KEY_CONVERT_MAP = {
379
+ 'zh-cn': 'zh-CHS',
380
+ 'zh-tw': 'zh-CHT'
381
+ };
382
+ truncate(q) {
383
+ // 检查输入字符串的长度
384
+ if (q.length <= 20) {
385
+ // 如果长度小于等于20,直接返回原字符串
386
+ return q;
387
+ } else {
388
+ // 如果长度大于20,截取前10个字符和后10个字符,并在中间插入长度信息
389
+ const len = q.length;
390
+ return q.substring(0, 10) + len + q.substring(len - 10);
391
+ }
392
+ }
393
+ getTranslateKey(key) {
394
+ return this.YOUDAO_TRANSLATE_KEY_CONVERT_MAP[key] || key;
395
+ }
396
+ constructor(option) {
397
+ super({
398
+ name: '有道翻译',
399
+ fetchMethod: async (text, fromKey, toKey) => {
400
+ let salt = new Date().getTime();
401
+ let curTime = Math.round(new Date().getTime() / 1000);
402
+ let str = option.appId + this.truncate(text) + salt + curTime + option.appKey;
403
+ let sign = CryptoJS.SHA256(str).toString(CryptoJS.enc.Hex);
404
+ const data = {
405
+ q: text,
406
+ appKey: option.appId,
407
+ salt,
408
+ from: this.getTranslateKey(fromKey),
409
+ to: this.getTranslateKey(toKey),
410
+ sign,
411
+ signType: 'v3',
412
+ curtime: curTime,
413
+ ...(option.insertOption || {})
414
+ };
415
+ const response = await axios.post('https://openapi.youdao.com/api', data, {
416
+ headers: {
417
+ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
418
+ },
419
+ proxy: option.proxy
420
+ });
421
+ // 请求成功,返回响应数据
422
+ return response.data.translation?.[0] || '';
423
+ },
424
+ onError: (error, cb) => {
425
+ cb(error);
426
+ console.error('请前往有道翻译官方申请翻译key,默认会有50的额度,并请检查额度是否充足。');
427
+ },
428
+ interval: option.interval ?? 1000
429
+ });
430
+ }
431
+ }
432
+
433
+ /*
434
+ * @Date: 2025-03-16 23:39:13
435
+ * @LastEditors: xiaoshan
436
+ * @LastEditTime: 2025-03-17 01:11:37
437
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/translator/baidu.ts
438
+ */
439
+ /**
440
+ * 百度翻译器
441
+ *
442
+ * api文档:https://api.fanyi.baidu.com/product/113
443
+ *
444
+ * 使用方式:
445
+ * ```ts
446
+ * vitePluginsAutoI18n({
447
+ ...
448
+ translator: new BaiduTranslator({
449
+ appId: '你申请的appId',
450
+ appKey: '你申请的appKey'
451
+ })
452
+ })
453
+ * ```
454
+ */
455
+ class BaiduTranslator extends Translator {
456
+ /** 百度的语言类型映射不标准,需要手动控制 */
457
+ BAIDU_TRANSLATE_KEY_CONVERT_MAP = {
458
+ 'zh-cn': 'zh',
459
+ ja: 'jp',
460
+ ko: 'kor'
461
+ };
462
+ getTranslateKey(key) {
463
+ return this.BAIDU_TRANSLATE_KEY_CONVERT_MAP[key] || key;
464
+ }
465
+ constructor(option) {
466
+ super({
467
+ name: '百度翻译',
468
+ fetchMethod: async (text, fromKey, toKey, separator) => {
469
+ let salt = new Date().getTime();
470
+ const data = {
471
+ q: text,
472
+ appid: option.appId,
473
+ from: this.getTranslateKey(fromKey),
474
+ to: this.getTranslateKey(toKey),
475
+ salt,
476
+ sign: CryptoJS.MD5(option.appId + text + salt + option.appKey).toString(),
477
+ ...(option.insertOption || {})
478
+ };
479
+ const response = await axios.post('https://fanyi-api.baidu.com/api/trans/vip/translate', data, {
480
+ headers: {
481
+ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
482
+ },
483
+ proxy: option.proxy
484
+ });
485
+ const translatedTexts = response.data?.trans_result.map(item => item.dst).filter((_item, index) => index % 2 === 0).join(separator);
486
+
487
+ // 请求成功,返回响应数据
488
+ return translatedTexts || '';
489
+ },
490
+ onError: (error, cb) => {
491
+ cb(error);
492
+ console.error('请前往百度翻译官方申请翻译key,每个月都有免费额度,并请检查额度是否充足。');
493
+ },
494
+ interval: option.interval ?? 1000
495
+ });
496
+ }
497
+ }
498
+
499
+ /*
500
+ * @Date: 2025-03-31 19:05:57
501
+ * @LastEditors: xiaoshan
502
+ * @LastEditTime: 2025-03-31 19:52:10
503
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/translator/scan.ts
504
+ */
505
+
506
+ /**
507
+ * 空翻译器,不翻译文本,用于配合某些特殊的操作
508
+ */
509
+ class EmptyTranslator extends Translator {
510
+ constructor() {
511
+ let option = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
512
+ const resultOption = {
513
+ name: '空翻译器',
514
+ fetchMethod: async (text, _from, _to, separator) => {
515
+ // 相当于把翻译结果统一设置为空串
516
+ const value = text.split(separator).fill('');
517
+ return value.join(separator);
518
+ },
519
+ ...option
520
+ };
521
+ super(resultOption);
522
+ }
523
+ // TODO: 后续可以作为基类,提供更多的配置选项
524
+ }
525
+
526
+ /** @deprecated 别名导出,兼容旧版本 */
527
+ const ScanTranslator = EmptyTranslator;
528
+
529
+ const cn2tw = OpenCC__namespace.Converter({
530
+ from: 'cn',
531
+ to: 'tw'
532
+ });
533
+ class CNToTWTranslator extends Translator {
534
+ constructor() {
535
+ super({
536
+ name: '中翻繁翻译',
537
+ fetchMethod: async (text, fromKey, toKey) => {
538
+ let translatedTexts = text;
539
+ if (fromKey === 'zh-cn' && toKey === 'zh-tw') {
540
+ translatedTexts = cn2tw(text);
541
+ }
542
+
543
+ // 请求成功,返回响应数据
544
+ return translatedTexts;
545
+ },
546
+ onError: (error, cb) => {
547
+ cb(error);
548
+ console.error('翻译失败');
549
+ }
550
+ });
551
+ }
552
+ }
553
+
554
+ /*
555
+ * @Author: xiaoshanwen
556
+ * @Date: 2024-02-29 14:44:18
557
+ * @LastEditTime: 2024-03-01 11:42:34
558
+ * @FilePath: /i18n_translation_vite/autoI18nPluginCore/src/utils/option.ts
559
+ */
560
+
561
+ class FunctionFactoryOption {
562
+ static originLang = '';
563
+ }
564
+
565
+ /*
566
+ * @Author: xiaoshanwen
567
+ * @Date: 2024-03-11 18:59:10
568
+ * @LastEditTime: 2025-03-16 18:15:25
569
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/enums/language.ts
570
+ */
571
+ // 待补充...
572
+ let LanguageEnum = /*#__PURE__*/function (LanguageEnum) {
573
+ return LanguageEnum;
574
+ }({});
575
+ let OriginLangKeyEnum = /*#__PURE__*/function (OriginLangKeyEnum) {
576
+ OriginLangKeyEnum["ZH"] = "zh-cn";
577
+ OriginLangKeyEnum["EN"] = "en";
578
+ OriginLangKeyEnum["JA"] = "ja";
579
+ OriginLangKeyEnum["KO"] = "ko";
580
+ OriginLangKeyEnum["RU"] = "ru";
581
+ return OriginLangKeyEnum;
582
+ }({});
583
+
584
+ /*
585
+ * @Author: xiaoshanwen
586
+ * @Date: 2024-04-06 15:47:14
587
+ * @LastEditTime: 2025-03-16 18:18:28
588
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/constants/translate.ts
589
+ */
590
+ const REGEX_MAP = {
591
+ [OriginLangKeyEnum.ZH]: /[\u4e00-\u9fff]/,
592
+ [OriginLangKeyEnum.EN]: /[a-zA-Z]/,
593
+ [OriginLangKeyEnum.JA]: /[\u3040-\u309F\u30A0-\u30FF\u4E00-\u9FFF]/,
594
+ // 日语假名和汉字
595
+ [OriginLangKeyEnum.KO]: /[\uAC00-\uD7A3]/,
596
+ // 韩语字母
597
+ [OriginLangKeyEnum.RU]: /[йцукенгшщзхъфывапролджэячсмитьбюё .-]{1,}/ // 俄语字母
598
+ };
599
+
600
+ /*
601
+ * @Author: xiaoshanwen
602
+ * @Date: 2023-10-11 10:01:43
603
+ * @LastEditTime: 2025-03-28 19:07:17
604
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/utils/base.ts
605
+ */
606
+ function getOriginRegex() {
607
+ const originLang = FunctionFactoryOption.originLang;
608
+ return REGEX_MAP[originLang];
609
+ }
610
+
611
+ /**
612
+ * @description: 是否包含来源语言字符
613
+ * @param {string} code
614
+ * @return {*}
615
+ */
616
+ function hasOriginSymbols(code) {
617
+ return getOriginRegex().test(code);
618
+ }
619
+
620
+ /**
621
+ * @description: 过滤注释
622
+ * @param {string} code
623
+ * @return {*}
624
+ */
625
+ const removeComments = function (code) {
626
+ // 使用正则表达式匹配并删除单行注释
627
+ code = code.replace(/\/\/.*?\n/g, '');
628
+ // 使用正则表达式匹配并删除多行注释
629
+ code = code.replace(/\/\*[\s\S]*?\*\//g, '');
630
+ // 使用正则表达式匹配并删除HTML注释
631
+ code = code.replace(/<!--[\s\S]*?-->/g, '');
632
+ return code;
633
+ };
634
+
635
+ /**
636
+ * @description: 用于判断提供的值是否符合正则表达式数组中的任一规则,符合则跳过
637
+ * @param {*} value
638
+ * @param {*} regexArray
639
+ * @return {*}
640
+ */
641
+ function checkAgainstRegexArray(value, regexArray) {
642
+ for (let i = 0; i < regexArray.length; i++) {
643
+ const regex = typeof regexArray[i] === 'string' ? new RegExp(regexArray[i]) : regexArray[i];
644
+ if (regex.test(value)) {
645
+ return true; // 如果符合任何一个规则,返回 true
646
+ }
647
+ }
648
+ return false; // 如果所有规则都不符合,返回 false
649
+ }
650
+
651
+ /**
652
+ * @description: 用于解析抽象语法树中的调用表达式,并提取出调用的名称,如a.b.c() 取 c。
653
+ * @param {any} node
654
+ * @return {*}
655
+ */
656
+ function extractFunctionName(node) {
657
+ let callName = '';
658
+ function callObjName(callObj, name) {
659
+ name += '.' + callObj.property.name;
660
+ if (types.isMemberExpression(callObj.object)) {
661
+ // isMemberExpression: 是否是成员表达式
662
+ return callObjName(callObj.object, name);
663
+ }
664
+ name = callObj.object.name + name;
665
+ return name;
666
+ }
667
+ if (types.isCallExpression(node)) {
668
+ // isCallExpression: 是否是调用表达式
669
+ if (types.isMemberExpression(node.callee)) {
670
+ callName = callObjName(node.callee, '');
671
+ } else {
672
+ callName = node.callee.name || '';
673
+ }
674
+ }
675
+ return callName;
676
+ }
677
+
678
+ /**
679
+ * @description: 提取文件的中文部分
680
+ * @param {string} fileContent
681
+ * @return {*}
682
+ */
683
+ const extractCnStrings = fileContent => {
684
+ const regex = /[^\x00-\xff]+/g;
685
+ return extractStrings(fileContent, regex);
686
+ };
687
+
688
+ /**
689
+ * @description: 提取文件指定部分内容
690
+ * @param {string} fileContent
691
+ * @param {any} regex
692
+ * @return {*}
693
+ */
694
+ function extractStrings(fileContent, regex) {
695
+ const matches = fileContent.match(regex);
696
+ return matches ? matches.filter((item, index) => matches.indexOf(item) === index) : [];
697
+ }
698
+
699
+ /**
700
+ * @description: 生成i8n翻译函数
701
+ * @param {string} value
702
+ * @param {boolean} isExpression
703
+ * @param {string} key
704
+ * @return {*}
705
+ */
706
+ function createI18nTranslator(createOption) {
707
+ const {
708
+ value,
709
+ isExpression = false,
710
+ key,
711
+ insertOption
712
+ } = createOption;
713
+
714
+ // 从全局配置对象 option 中获取命名空间
715
+ const nameSpace = exports.option.namespace;
716
+ const {
717
+ trimmedValue,
718
+ valStr
719
+ } = normalizeTranslateValue(value);
720
+ // 若 key 存在则使用 key,否则调用 generateId 函数根据 valStr 生成唯一的键
721
+ const generatedKey = key || generateId(valStr);
722
+ // 提取公共配置对象,避免重复代码
723
+ const config = {
724
+ option: exports.option,
725
+ hash: generatedKey,
726
+ value: trimmedValue,
727
+ uncodeValue: valStr,
728
+ namespace: nameSpace
729
+ };
730
+ if (exports.option.translateExtends) {
731
+ const {
732
+ handleCodeCall,
733
+ handleCodeString
734
+ } = exports.option.translateExtends;
735
+ return isExpression ? handleCodeCall(config, insertOption) : handleCodeString(config, insertOption);
736
+ }
737
+ if (isExpression) {
738
+ const valueExp = types.stringLiteral(trimmedValue);
739
+ valueExp.extra = {
740
+ raw: `'${valStr}'`,
741
+ // 防止转码为unicode
742
+ rawValue: trimmedValue
743
+ };
744
+ return exports.option.useValueAsKey ? types.callExpression(types.identifier(exports.option.translateKey), [valueExp]) : types.callExpression(types.identifier(exports.option.translateKey), [types.stringLiteral(generatedKey), valueExp]);
745
+ } else {
746
+ return `${exports.option.translateKey}('${generatedKey}','${valStr}')`;
747
+ }
748
+ }
749
+ function normalizeTranslateValue(value) {
750
+ const trimmedValue = exports.option.isClearSpace ? value : value.trim();
751
+ const valStr = trimmedValue.replace(/'/g, '"').replace(/(\n)/g, '\\n');
752
+ return {
753
+ trimmedValue,
754
+ valStr
755
+ };
756
+ }
757
+
758
+ /**
759
+ * @description: 生成唯一id
760
+ * @param {string} key
761
+ * @return {*}
762
+ */
763
+ function generateId(key) {
764
+ let hash = 0;
765
+ for (let i = 0; i < key.length; i++) {
766
+ const charCode = key.charCodeAt(i);
767
+ hash = (hash << 5) - hash + charCode;
768
+ hash = hash & hash;
769
+ }
770
+ const id = Math.abs(hash).toString(36) + key.length.toString(36);
771
+ return id;
772
+ }
773
+
774
+ /**
775
+ * @description: unicode转普通字符串
776
+ * @param {string} str
777
+ * @return {*}
778
+ */
779
+ const unicodeToString = str => {
780
+ return str.replace(/\\u[\dA-Fa-f]{4}/g, match => {
781
+ return String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16));
782
+ });
783
+ };
784
+
785
+ /**
786
+ * @description: 有道翻译 标识截取
787
+ * @param {string} q
788
+ * @return {*}
789
+ */
790
+ function truncate(q) {
791
+ // 检查输入字符串的长度
792
+ if (q.length <= 20) {
793
+ // 如果长度小于等于20,直接返回原字符串
794
+ return q;
795
+ } else {
796
+ // 如果长度大于20,截取前10个字符和后10个字符,并在中间插入长度信息
797
+ const len = q.length;
798
+ return q.substring(0, 10) + len + q.substring(len - 10);
799
+ }
800
+ }
801
+
802
+ // 导出一个深拷贝函数,用于克隆对象
803
+ function cloneDeep(value) {
804
+ let cache = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new WeakMap();
805
+ // 处理基本类型和 null
806
+ if (typeof value !== 'object' || value === null) {
807
+ return value;
808
+ }
809
+
810
+ // 处理循环引用
811
+ if (cache.has(value)) {
812
+ return cache.get(value);
813
+ }
814
+
815
+ // 处理特殊对象类型
816
+ if (value instanceof Date) {
817
+ return new Date(value);
818
+ }
819
+ if (value instanceof RegExp) {
820
+ return new RegExp(value.source, value.flags);
821
+ }
822
+
823
+ // 初始化克隆容器
824
+ const clone = Array.isArray(value) ? [] : {};
825
+
826
+ // 缓存对象防止循环引用
827
+ cache.set(value, clone);
828
+
829
+ // 处理 Symbol 和普通键的枚举
830
+ const keys = [...Object.keys(value), ...Object.getOwnPropertySymbols(value).filter(sym => value.propertyIsEnumerable(sym))];
831
+
832
+ // 递归克隆属性
833
+ for (const key of keys) {
834
+ clone[key] = cloneDeep(value[key], cache);
835
+ }
836
+ return clone;
837
+ }
838
+
839
+ var base = /*#__PURE__*/Object.freeze({
840
+ __proto__: null,
841
+ checkAgainstRegexArray: checkAgainstRegexArray,
842
+ cloneDeep: cloneDeep,
843
+ createI18nTranslator: createI18nTranslator,
844
+ extractCnStrings: extractCnStrings,
845
+ extractFunctionName: extractFunctionName,
846
+ extractStrings: extractStrings,
847
+ generateId: generateId,
848
+ getOriginRegex: getOriginRegex,
849
+ hasOriginSymbols: hasOriginSymbols,
850
+ normalizeTranslateValue: normalizeTranslateValue,
851
+ removeComments: removeComments,
852
+ truncate: truncate,
853
+ unicodeToString: unicodeToString
854
+ });
855
+
856
+ // 代码灵感来自https://github.com/dadidi9900/auto-plugins-json-translate/blob/main/src/services/translationService.ts
857
+ /**
858
+ * 火山引擎翻译器,内置豆包、deepseek等模型
859
+ *
860
+ * 火山引擎大模型介绍:https://www.volcengine.com/docs/82379/1099455
861
+ *
862
+ * api文档:https://www.volcengine.com/docs/82379/1298454
863
+ *
864
+ * 使用方式:
865
+ * ```ts
866
+ * vitePluginsAutoI18n({
867
+ ...
868
+ translator: new VolcengineTranslator({
869
+ apiKey: '你申请的apiKey',
870
+ model: '你要调用的模型,如:`doubao-1-5-pro-32k-250115`,请确保使用前已在控制台开通了对应模型'
871
+ })
872
+ })
873
+ * ```
874
+ */
875
+ class VolcengineTranslator extends Translator {
876
+ constructor(option) {
877
+ super({
878
+ name: '火山引擎ai翻译',
879
+ fetchMethod: async (text, fromKey, toKey, separator) => {
880
+ let salt = new Date().getTime();
881
+ const textArr = text.split(separator);
882
+ const sourceMap = Object.fromEntries(textArr.map(text => [generateId(text), text]));
883
+ const data = {
884
+ model: option.model,
885
+ messages: [{
886
+ role: 'system',
887
+ content: `
888
+ ###
889
+ 假如你是一个无情的翻译接口,你将根据一个文本组成的JSON对象,来解决将数组每个成员从源语言A翻译成目标语言B并返回翻译后的JSON对象的任务。需要注意的是,待翻译的文本均来自一个${option.desc ? option.desc + '的' : ''}web平台,遇到歧义时需要做好处理。根据以下规则一步步执行:
890
+ 1. 明确源语言A和目标语言B。
891
+ 2. 对JSON对象中数组的每个成员进行从源语言A到目标语言B的翻译。
892
+ 3. 将翻译后的内容以JSON对象格式返回,确保返回的内容可以被JSON.parse解析。
893
+
894
+ 参考例子:
895
+ 示例1:
896
+ 输入:zh-cn -> en { "awfgx": "你好", "qwfga": "世界" }
897
+ 输出:{ "awfgx": "Hello", "qwfga": "World" }
898
+
899
+ 示例2:
900
+ 输入:de -> fr { "gweaq": "Hallo", "wtrts": "Welt" }
901
+ 输出:{ "gweaq": "Bonjour", "wtrts": "Monde" }
902
+
903
+ 请回答问题:
904
+ 输入:源语言A -> 目标语言B { "wghhj": "XXX" }
905
+ 输出:
906
+
907
+ 要求:
908
+ 1 以JSON对象格式输出
909
+ 2 JSON对象中每个成员为翻译后的内容
910
+ ###
911
+ `
912
+ }, {
913
+ role: 'user',
914
+ content: `${fromKey} -> ${toKey} ${JSON.stringify(sourceMap)}`
915
+ }],
916
+ ...(option.insertOption || {})
917
+ };
918
+ const response = await axios.post(`https://ark.cn-beijing.volces.com/api/v3/chat/completions?t=${salt}`, data, {
919
+ headers: {
920
+ 'Content-Type': 'application/json',
921
+ Authorization: `Bearer ${option.apiKey}`
922
+ },
923
+ proxy: option.proxy
924
+ });
925
+ let resultTextArr = Array.from(textArr).fill('');
926
+ const content = response.data.choices[0].message.content;
927
+ try {
928
+ let resultMap;
929
+ try {
930
+ resultMap = JSON.parse(content);
931
+ } catch (error) {
932
+ throw new Error('大模型返回文本解析失败');
933
+ }
934
+ if (typeof resultMap !== 'object' || !resultMap) {
935
+ throw new Error('大模型返回文本解析后类型不正确');
936
+ }
937
+ const isMiss = Object.keys(resultMap).some(key => !(key in sourceMap));
938
+ if (isMiss) {
939
+ throw new Error('大模型返回文本内容不完整');
940
+ }
941
+ resultTextArr = textArr.map(text => resultMap[generateId(text)]); // 用textArr遍历,保证顺序
942
+ } catch (error) {
943
+ const message = error instanceof Error ? error.message : '未知错误';
944
+ console.warn('⚠', message);
945
+ console.warn('⚠ 返回的文本内容:', content);
946
+ console.warn('⚠ 原文本内容:', JSON.stringify(sourceMap));
947
+ }
948
+ return resultTextArr.join(separator);
949
+ },
950
+ onError: (error, cb) => {
951
+ cb(error);
952
+ console.error('请确保在火山引擎控制台开通了对应模型,且有足够的token余额。控制台地址:https://console.volcengine.com/ark/');
953
+ },
954
+ maxChunkSize: 1000,
955
+ // 太长可能会导致返回文本不完整
956
+ interval: option.interval ?? 1000
957
+ });
958
+ }
959
+ }
960
+
961
+ /*
962
+ * @Author: xiaoshanwen
963
+ * @Date: 2024-04-03 18:12:45
964
+ * @LastEditTime: 2024-04-03 18:33:53
965
+ * @FilePath: /i18n_translation_vite/autoI18nPluginCore/src/enums/translate.ts
966
+ */
967
+ let TranslateApiEnum = /*#__PURE__*/function (TranslateApiEnum) {
968
+ TranslateApiEnum["google"] = "Google";
969
+ TranslateApiEnum["youdao"] = "Youdao";
970
+ return TranslateApiEnum;
971
+ }({});
972
+
973
+ /*
974
+ * @Date: 2025-03-16 14:12:30
975
+ * @LastEditors: xiaoshan
976
+ * @LastEditTime: 2025-03-16 14:13:42
977
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/enums/option.ts
978
+ */
979
+ /**
980
+ * 翻译类型枚举
981
+ */
982
+ let TranslateTypeEnum = /*#__PURE__*/function (TranslateTypeEnum) {
983
+ TranslateTypeEnum["FULL_AUTO"] = "full-auto";
984
+ TranslateTypeEnum["SEMI_AUTO"] = "semi-auto";
985
+ return TranslateTypeEnum;
986
+ }({});
987
+
988
+ /*
989
+ * @Author: xiaoshanwen
990
+ * @Date: 2023-10-26 17:34:47
991
+ * @LastEditTime: 2025-03-31 19:58:37
992
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/option.ts
993
+ */
994
+
995
+ const EXCLUDED_CALL = ['$deepScan', 'console.info', 'console.warn', 'console.error', '$i8n', 'console.log', '$t', 'require', '$$i8n', '$$t', '_createCommentVNode'];
996
+ /**
997
+ * 默认插件配置选项
998
+ */
999
+ const DEFAULT_OPTION = {
1000
+ appCode: '',
1001
+ /** 是否启用插件,默认启用 */
1002
+ enabled: true,
1003
+ /** 翻译调用函数,默认为 $t */
1004
+ translateKey: '$t',
1005
+ /** 标记不翻译调用函数列表,避免某些调用被错误翻译 */
1006
+ excludedCall: [],
1007
+ /** 标记不用翻译的字符串模式数组,默认是匹配文件扩展名 */
1008
+ excludedPattern: [/\.\w+$/],
1009
+ /** 排查不需要翻译的目录下的文件路径(黑名单), 默认不处理node_modules */
1010
+ excludedPath: ['node_modules'],
1011
+ /** 指定需要翻译文件的目录路径正则(白名单) */
1012
+ includePath: [/src\//, /src\\/],
1013
+ /** 配置文件生成位置,默认为 './lang' */
1014
+ globalPath: './lang',
1015
+ /** 打包后生成文件的位置,例如 './dist/assets' */
1016
+ distPath: '',
1017
+ /** 打包后生成文件的主文件名称,默认是 'index' */
1018
+ distKey: 'index',
1019
+ /** 来源语言,默认是中文 */
1020
+ originLang: OriginLangKeyEnum.ZH,
1021
+ /** 翻译目标语言列表,默认包含英文 */
1022
+ targetLangList: ['en'],
1023
+ /** 语言key,用于请求谷歌api和生成配置文件下对应语言的内容文件 */
1024
+ langKey: [],
1025
+ /** 命名空间,防止全局命名冲突 */
1026
+ namespace: 'lang',
1027
+ /** 单位代码 */
1028
+ orgCode: 'GREENCLOUD',
1029
+ /** 是否启用源码的值作为key */
1030
+ useValueAsKey: false,
1031
+ /** 是否在构建结束之后将最新的翻译重新打包到主包中,默认不打包 */
1032
+ buildToDist: false,
1033
+ /** 是否启用上传翻译文件到服务器,默认开启 */
1034
+ uploadEnabled: true,
1035
+ /** 翻译器,决定自动翻译使用的api与调用方式,默认使用 Google 翻译器并使用7890(clash)端口代理 */
1036
+ translator: new GoogleTranslator({
1037
+ proxyOption: {
1038
+ port: 7890,
1039
+ host: '127.0.0.1',
1040
+ headers: {
1041
+ 'User-Agent': 'Node'
1042
+ }
1043
+ }
1044
+ }),
1045
+ /** 翻译器配置选项,优先级低于translator */
1046
+ translatorOption: undefined,
1047
+ /**
1048
+ * 翻译类型,支持全自动和半自动两种模式
1049
+ * 全自动:所有翻译任务自动完成
1050
+ * 半自动:需要人工标识,类似于 $t('key') 的方式
1051
+ * 默认值为全自动
1052
+ */
1053
+ translateType: TranslateTypeEnum.FULL_AUTO,
1054
+ /**
1055
+ * 是否重写配置文件,默认为true
1056
+ */
1057
+ rewriteConfig: true,
1058
+ /**
1059
+ * 通用翻译key,默认使用namespace,如果commonTranslateKey不为空,则使用commonTranslateKey
1060
+ */
1061
+ commonTranslateKey: '',
1062
+ /**
1063
+ * 实验性属性,表示是否进行深层扫描字符串,默认为 false
1064
+ * 当设置为 true 时,会对代码中的字符串进行更深入的扫描
1065
+ */
1066
+ deepScan: false,
1067
+ /**
1068
+ * 自定义文件拓展名数组
1069
+ */
1070
+ insertFileExtensions: [],
1071
+ /**
1072
+ * 自定义拓展类,插件默认翻译函数挂载在window上,如果希望自定义翻译函数挂载在其他对象上,可以使用该属性
1073
+ * 注意:该属性需要继承BaseExtends类,并且需要实现handleInitFile和handleCodeCall和handleCodeString方法
1074
+ */
1075
+ translateExtends: null,
1076
+ isClear: false,
1077
+ // 是否清除已经不在上下文中的内容(清除项目中不再使用到的源语言键值对)
1078
+
1079
+ /**
1080
+ * 是否保留空格
1081
+ */
1082
+ isClearSpace: true
1083
+ };
1084
+
1085
+ /**
1086
+ * 类型定义:插件配置选项类型
1087
+ */
1088
+
1089
+ /**
1090
+ * 全局插件配置实例,复制自默认配置
1091
+ */
1092
+ exports.option = {
1093
+ ...DEFAULT_OPTION
1094
+ };
1095
+
1096
+ /**
1097
+ * 类型定义:用户传入的配置选项
1098
+ */
1099
+
1100
+ /**
1101
+ * 通过深度克隆提供的选项信息生成一个用户选项对象,
1102
+ * 确保原始配置不被修改。它还根据用户的配置初始化翻译器。
1103
+ * @param optionInfo - 包含用户选项和翻译器细节的选项信息。
1104
+ * @returns 一个新的、可能已初始化翻译器的用户选项对象。
1105
+ */
1106
+ function generateUserOption(optionInfo) {
1107
+ // 深拷贝用户传入的配置,防止修改原配置对象
1108
+ const userOption = cloneDeep(optionInfo);
1109
+ userOption.translator = optionInfo?.translator;
1110
+
1111
+ // 如果用户配置了translatorOption则初始化translator,如果都没有则不设置translator
1112
+ userOption.translator ||= userOption.translatorOption ? new Translator(userOption.translatorOption) : undefined;
1113
+ if (!userOption.translator) delete userOption.translator;
1114
+ return userOption;
1115
+ }
1116
+
1117
+ /**
1118
+ * 初始化插件配置选项
1119
+ * @param optionInfo 用户提供的配置选项
1120
+ */
1121
+ function initOption(optionInfo) {
1122
+ // 合并默认配置和用户配置
1123
+ exports.option = {
1124
+ ...DEFAULT_OPTION,
1125
+ ...generateUserOption(optionInfo)
1126
+ };
1127
+
1128
+ // 初始化语言key数组,包含来源语言和目标语言
1129
+ exports.option.langKey = [exports.option.originLang, ...exports.option.targetLangList];
1130
+ // 初始化排除调用函数列表,包含默认排除和调用函数主动排除
1131
+ exports.option.excludedCall = [...exports.option.excludedCall, ...EXCLUDED_CALL, ...[exports.option.translateKey, '$' + exports.option.translateKey]];
1132
+ return exports.option;
1133
+ }
1134
+
1135
+ /**
1136
+ * 校验插件配置选项是否完整有效
1137
+ * @returns {boolean} 校验结果,完整返回 true,否则返回 false
1138
+ */
1139
+ function checkOption() {
1140
+ // 校验翻译调用函数是否配置
1141
+ if (!exports.option.translateKey) {
1142
+ console.error('❌请配置翻译调用函数');
1143
+ return false;
1144
+ }
1145
+
1146
+ // 校验命名空间是否配置
1147
+ if (!exports.option.namespace) {
1148
+ console.error('❌请配置命名空间');
1149
+ return false;
1150
+ }
1151
+
1152
+ // 校验是否配置了打包后生成文件的主文件名称(如果需要打包到主包中)
1153
+ if (exports.option.buildToDist && !exports.option.distKey) {
1154
+ console.log('❌请配置打包后生成文件的主文件名称');
1155
+ return false;
1156
+ }
1157
+
1158
+ // 校验是否配置了打包后生成文件的位置(如果需要打包到主包中)
1159
+ if (exports.option.buildToDist && !exports.option.distPath) {
1160
+ console.log('❌请配置打包后生成文件的位置');
1161
+ return false;
1162
+ }
1163
+
1164
+ // 校验来源语言是否配置
1165
+ if (!exports.option.originLang) {
1166
+ console.error('❌请配置来源语言');
1167
+ return false;
1168
+ }
1169
+
1170
+ // 校验目标翻译语言数组是否配置
1171
+ if (!exports.option.targetLangList || !exports.option.targetLangList.length) {
1172
+ console.error('❌请配置目标翻译语言数组');
1173
+ return false;
1174
+ }
1175
+
1176
+ // 如果所有校验通过,返回 true
1177
+ return true;
1178
+ }
1179
+
1180
+ var allLanguage = [{
1181
+ code: 'zh-CN',
1182
+ name: '简体中文'
1183
+ }, {
1184
+ code: 'zh-TW',
1185
+ name: '繁体中文'
1186
+ }, {
1187
+ code: 'zh-UG',
1188
+ name: '维吾尔语'
1189
+ }, {
1190
+ code: 'en-US',
1191
+ name: '英文'
1192
+ }, {
1193
+ code: 'tr-TR',
1194
+ name: '土耳其语'
1195
+ }, {
1196
+ code: 'es-ES',
1197
+ name: '西班牙语'
1198
+ }, {
1199
+ code: 'ja-JP',
1200
+ name: '日语'
1201
+ }, {
1202
+ code: 'ru-RU',
1203
+ name: '俄语'
1204
+ }, {
1205
+ code: 'fr-FR',
1206
+ name: '法语'
1207
+ }, {
1208
+ code: 'de-DE',
1209
+ name: '德语'
1210
+ }, {
1211
+ code: 'pt-BR',
1212
+ name: '巴西葡萄牙语'
1213
+ }, {
1214
+ code: 'pt-PT',
1215
+ name: '葡萄牙语'
1216
+ }, {
1217
+ code: 'ko-KR',
1218
+ name: '韩语'
1219
+ }, {
1220
+ code: 'vi-VN',
1221
+ name: '越南语'
1222
+ }, {
1223
+ code: 'sv-SE',
1224
+ name: '瑞典语'
1225
+ }, {
1226
+ code: 'id-ID',
1227
+ name: '印尼语'
1228
+ }, {
1229
+ code: 'uk-UA',
1230
+ name: '乌克兰语'
1231
+ }, {
1232
+ code: 'it-IT',
1233
+ name: '意大利语'
1234
+ }, {
1235
+ code: 'th-TH',
1236
+ name: '泰语'
1237
+ }, {
1238
+ code: 'hi-IN',
1239
+ name: '印地语'
1240
+ }, {
1241
+ code: 'fa-IR',
1242
+ name: '波斯语'
1243
+ }, {
1244
+ code: 'ro-RO',
1245
+ name: '罗马尼亚语'
1246
+ }, {
1247
+ code: 'el-GR',
1248
+ name: '希腊语'
1249
+ }, {
1250
+ code: 'nl-NL',
1251
+ name: '荷兰语'
1252
+ }, {
1253
+ code: 'cs-CZ',
1254
+ name: '捷克语'
1255
+ }, {
1256
+ code: 'mn-MN',
1257
+ name: '蒙古语'
1258
+ }, {
1259
+ code: 'mn-TR',
1260
+ name: '传统蒙古语'
1261
+ }, {
1262
+ code: 'fi-FI',
1263
+ name: '芬兰语'
1264
+ }, {
1265
+ code: 'ar-SA',
1266
+ name: '阿拉伯语'
1267
+ }, {
1268
+ code: 'ar-EG',
1269
+ name: '阿拉伯语-埃及'
1270
+ }, {
1271
+ code: 'da-DK',
1272
+ name: '丹麦语'
1273
+ }, {
1274
+ code: 'pl-PL',
1275
+ name: '波兰语'
1276
+ }, {
1277
+ code: 'nb-NO',
1278
+ name: '挪威语'
1279
+ }, {
1280
+ code: 'si-LK',
1281
+ name: '僧伽罗语'
1282
+ }];
1283
+
1284
+ /**
1285
+ * JSON 格式化配置类型
1286
+ */
1287
+
1288
+ // 默认的缩进配置
1289
+ const indentConfig = {
1290
+ tab: {
1291
+ char: '\t',
1292
+ size: 1
1293
+ },
1294
+ space: {
1295
+ char: ' ',
1296
+ size: 4
1297
+ }
1298
+ };
1299
+
1300
+ // 默认格式化配置
1301
+ const configDefault = {
1302
+ type: 'tab'
1303
+ };
1304
+
1305
+ // 临时存储替换字符串的数组
1306
+ let placeholderStorage = [];
1307
+
1308
+ // 临时存储处理函数
1309
+ const pushPlaceholder = match => `\\${placeholderStorage.push(match)}\\`;
1310
+ const popPlaceholder = (_match, index) => placeholderStorage[+index - 1];
1311
+
1312
+ // 生成缩进字符
1313
+ const generateIndentation = (count, indentType) => {
1314
+ return new Array(count + 1).join(indentType);
1315
+ };
1316
+
1317
+ /**
1318
+ * 格式化 JSON 字符串
1319
+ * @param json JSON 字符串
1320
+ * @param indentType 缩进类型
1321
+ * @returns 格式化的 JSON 字符串
1322
+ */
1323
+ function formatJSON(json, indentType) {
1324
+ placeholderStorage = [];
1325
+ let output = '';
1326
+ let indentLevel = 0;
1327
+
1328
+ // 提取反斜杠和字符串
1329
+ json = json.replace(/\\./g, pushPlaceholder) // 处理反斜杠
1330
+ .replace(/(".*?"|'.*?')/g, pushPlaceholder) // 处理字符串
1331
+ .replace(/\s+/g, ''); // 去除多余空格
1332
+
1333
+ // 根据 JSON 内容添加换行和缩进
1334
+ for (let i = 0; i < json.length; i++) {
1335
+ const char = json.charAt(i);
1336
+ switch (char) {
1337
+ case '{':
1338
+ case '[':
1339
+ output += char + '\n' + generateIndentation(++indentLevel, indentType);
1340
+ break;
1341
+ case '}':
1342
+ case ']':
1343
+ output += '\n' + generateIndentation(--indentLevel, indentType) + char;
1344
+ break;
1345
+ case ',':
1346
+ output += ',\n' + generateIndentation(indentLevel, indentType);
1347
+ break;
1348
+ case ':':
1349
+ output += ': ';
1350
+ break;
1351
+ default:
1352
+ output += char;
1353
+ break;
1354
+ }
1355
+ }
1356
+
1357
+ // 去除数字数组的空格,并还原反斜杠和字符串
1358
+ output = output.replace(/\[[\d,\s]+?\]/g, match => match.replace(/\s/g, '')).replace(/\\(\d+)\\/g, popPlaceholder) // 还原填充数据
1359
+ .replace(/\\(\d+)\\/g, popPlaceholder); // 再次还原填充数据
1360
+
1361
+ return output;
1362
+ }
1363
+
1364
+ /**
1365
+ * 格式化 JSON 的主函数
1366
+ * @param json 需要格式化的 JSON 对象或字符串
1367
+ * @param config 配置选项
1368
+ * @returns 格式化后的 JSON 字符串
1369
+ */
1370
+ function jsonFormatter(json) {
1371
+ let config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : configDefault;
1372
+ // 确保输入是 JSON 字符串
1373
+ const jsonString = typeof json === 'string' ? json : JSON.stringify(json);
1374
+
1375
+ // 获取缩进配置
1376
+ const indent = indentConfig[config.type];
1377
+ if (!indent) {
1378
+ throw new Error(`Unrecognized indent type: "${config.type}"`);
1379
+ }
1380
+
1381
+ // 生成缩进字符
1382
+ const indentType = generateIndentation(config.size || indent.size, indent.char);
1383
+
1384
+ // 格式化 JSON 字符串
1385
+ return formatJSON(jsonString, indentType);
1386
+ }
1387
+
1388
+ /**
1389
+ * @description: 新建国际化配置文件夹
1390
+ * @return {*}
1391
+ */
1392
+ function initLangFile() {
1393
+ if (!fs.existsSync(exports.option.globalPath)) {
1394
+ fs.mkdirSync(exports.option.globalPath); // 创建lang文件夹
1395
+ }
1396
+ initLangTranslateJSONFile();
1397
+ initTranslateBasicFnFile();
1398
+ }
1399
+ /**
1400
+ * @description: 初始化翻译基础函数文件
1401
+ * @returns {void}
1402
+ */
1403
+ async function initTranslateBasicFnFile() {
1404
+ // 从配置选项中获取必要的配置信息
1405
+ const {
1406
+ targetLangList
1407
+ } = exports.option;
1408
+ // 生成语言映射列表
1409
+ let languages = [];
1410
+ let langList = targetLangList.map(item => {
1411
+ const parts = item.split('-');
1412
+ const lang = parts[0] + '-' + parts[1].toUpperCase();
1413
+ return _.find(allLanguage, {
1414
+ code: lang
1415
+ });
1416
+ });
1417
+ langList
1418
+ // 构建语言映射项
1419
+ .map(item => {
1420
+ languages.push(`{
1421
+ code: "${item.code}",
1422
+ name: "${item.name}"
1423
+ }`);
1424
+ });
1425
+ // 用逗号和换行符连接所有映射项
1426
+ const translateBasicFnText = `
1427
+ import gc_i18n from 'gc_i18n'
1428
+ export const languages = [${languages.toString()}]
1429
+ const gcI18nInstance = new gc_i18n({
1430
+ appCode: 'TEST',
1431
+ env: 'dev', // local 本地部署 dev 多语言测试环境 prod 多语言生产环境
1432
+ orgCode: 'GREENCLOUD',
1433
+ messages: {} // 如果你需要自己引入语言包
1434
+ })
1435
+ export default {
1436
+ install(app, router) {
1437
+ gcI18nInstance.setRouter(router)
1438
+ }
1439
+ }`;
1440
+ // 构建翻译基础函数文件的路径
1441
+ const indexPath = path.join(exports.option.globalPath, 'index.js');
1442
+
1443
+ // 文件已存在 同时 不重写配置,那么这里就结束
1444
+ if (fs.existsSync(indexPath) && !exports.option.rewriteConfig) return;
1445
+
1446
+ // 新增哈希比对逻辑
1447
+
1448
+ // 标记是否需要更新文件
1449
+ let needUpdate = true;
1450
+ if (fs.existsSync(indexPath)) {
1451
+ // 检查文件是否已存在
1452
+ // 读取现有文件内容
1453
+ const existingContent = fs.readFileSync(indexPath, 'utf-8');
1454
+ // 生成现有内容的哈希值
1455
+ const existingHash = generateId(existingContent);
1456
+ // 判断是否需要更新文件
1457
+ // needUpdate = currentHash !== existingHash
1458
+ needUpdate = !existingHash;
1459
+ }
1460
+
1461
+ // 如果需要更新文件,则写入新内容
1462
+ if (needUpdate) {
1463
+ fs.writeFileSync(indexPath, translateBasicFnText);
1464
+ }
1465
+ }
1466
+ /**
1467
+ * @description: 生成国际化JSON文件
1468
+ * @return {*}
1469
+ */
1470
+ function initLangTranslateJSONFile() {
1471
+ const indexPath = path.join(exports.option.globalPath, 'index.json');
1472
+ if (!fs.existsSync(indexPath)) {
1473
+ // 不存在就创建
1474
+ fs.writeFileSync(indexPath, JSON.stringify({})); // 创建
1475
+ }
1476
+ }
1477
+
1478
+ /**
1479
+ * @description: 读取国际化JSON文件
1480
+ * @return {*}
1481
+ */
1482
+ function getLangTranslateJSONFile() {
1483
+ const filePath = path.join(exports.option.globalPath, 'index.json');
1484
+ try {
1485
+ const content = fs.readFileSync(filePath, 'utf-8');
1486
+ return content;
1487
+ } catch (error) {
1488
+ if (error.code === 'ENOENT') {
1489
+ console.log('❌读取JSON配置文件异常,文件不存在');
1490
+ } else {
1491
+ console.log('❌读取JSON配置文件异常,无法读取文件');
1492
+ }
1493
+ return JSON.stringify({});
1494
+ }
1495
+ }
1496
+
1497
+ /**
1498
+ * @description: 基于langKey获取JSON配置文件中对应语言对象
1499
+ * @param {string} key
1500
+ * @return {*}
1501
+ */
1502
+ function getLangObjByJSONFileWithLangKey(key) {
1503
+ let insertJSONObj = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
1504
+ // 获取翻译配置对象,优先使用传入的配置,否则从本地文件读取
1505
+ const JSONObj = insertJSONObj || JSON.parse(getLangTranslateJSONFile());
1506
+
1507
+ // 初始化语言映射对象,用于存储不同语言的hash: value映射
1508
+ const langObj = {};
1509
+
1510
+ // 遍历hash,提取hash对应语言key的值,并写入到langObj
1511
+ Object.keys(JSONObj).forEach(langCode => {
1512
+ langObj[langCode] = JSONObj[langCode][key];
1513
+ });
1514
+
1515
+ // 返回当前语言的hash: value映射对象
1516
+ // 例如: 'zh-cn' > {'hash1': '你好', 'hash2': '世界'}
1517
+ // 'en' > {'hash1': 'hello', 'hash2': 'world'}
1518
+ return langObj;
1519
+ }
1520
+
1521
+ /**
1522
+ * @description: 设置国际化JSON文件
1523
+ * @return {*}
1524
+ */
1525
+ function setLangTranslateJSONFile(obj) {
1526
+ const filePath = path.join(exports.option.globalPath, 'index.json');
1527
+ const jsonObj = jsonFormatter(obj);
1528
+ if (fs.existsSync(filePath)) {
1529
+ fs.writeFileSync(filePath, jsonObj);
1530
+ } else {
1531
+ console.log('❌JSON配置文件写入异常,文件不存在');
1532
+ }
1533
+ }
1534
+
1535
+ /**
1536
+ * @description: 构建时把lang配置文件设置到打包后到主文件中
1537
+ * @return {*}
1538
+ */
1539
+ function uploadFile() {
1540
+ const JSONObj = JSON.parse(getLangTranslateJSONFile());
1541
+ upload(JSONObj);
1542
+ // if (!option.buildToDist) return
1543
+ // let langObjMap: any = {}
1544
+ // option.langKey.forEach(item => {
1545
+ // langObjMap[item] = getLangObjByJSONFileWithLangKey(item)
1546
+ // })
1547
+ // if (fs.existsSync(option.distPath)) {
1548
+ // fs.readdir(option.distPath, (err, files) => {
1549
+ // if (err) {
1550
+ // console.error('❌构建文件夹为空,翻译配置无法写入')
1551
+ // return
1552
+ // }
1553
+
1554
+ // files.forEach(file => {
1555
+ // if (file.startsWith(option.distKey) && file.endsWith('.js')) {
1556
+ // const filePath = path.join(option.distPath, file)
1557
+ // fs.readFile(filePath, 'utf-8', (err, data) => {
1558
+ // if (err) {
1559
+ // console.log(filePath)
1560
+ // console.error('❌构建主文件不存在,翻译配置无法写入')
1561
+ // return
1562
+ // }
1563
+ // let buildLangConfigString = ''
1564
+ // Object.keys(langObjMap).forEach(item => {
1565
+ // buildLangConfigString =
1566
+ // buildLangConfigString +
1567
+ // `globalThis['${option.namespace}']['${item}']=${JSON.stringify(langObjMap[item])};`
1568
+ // })
1569
+ // try {
1570
+ // // 翻译配置写入主文件
1571
+ // fs.writeFileSync(
1572
+ // filePath,
1573
+ // `globalThis['${option.namespace}']={};${buildLangConfigString}` +
1574
+ // data
1575
+ // )
1576
+ // console.info('恭喜:翻译配置写入构建主文件成功🌟🌟🌟')
1577
+ // } catch (err) {
1578
+ // console.error('翻译配置写入构建主文件失败:', err)
1579
+ // }
1580
+ // })
1581
+ // }
1582
+ // })
1583
+ // })
1584
+ // }
1585
+ }
1586
+
1587
+ var file = /*#__PURE__*/Object.freeze({
1588
+ __proto__: null,
1589
+ getLangObjByJSONFileWithLangKey: getLangObjByJSONFileWithLangKey,
1590
+ getLangTranslateJSONFile: getLangTranslateJSONFile,
1591
+ initLangFile: initLangFile,
1592
+ initLangTranslateJSONFile: initLangTranslateJSONFile,
1593
+ initTranslateBasicFnFile: initTranslateBasicFnFile,
1594
+ setLangTranslateJSONFile: setLangTranslateJSONFile,
1595
+ uploadFile: uploadFile
1596
+ });
1597
+
1598
+ /*
1599
+ * @Author: xiaoshanwen
1600
+ * @Date: 2023-10-30 18:23:03
1601
+ * @LastEditTime: 2025-03-16 19:12:54
1602
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/utils/translate.ts
1603
+ */
1604
+
1605
+ const SEPARATOR = '\n┇┇┇\n';
1606
+ const SPLIT_SEPARATOR_REGEX = /\n┇ *┇ *┇\n/;
1607
+ let langObj = {};
1608
+
1609
+ /**
1610
+ * @description: 设置翻译对象属性
1611
+ * @param {string} key
1612
+ * @param {string} value
1613
+ * @return {*}
1614
+ */
1615
+ function setLangObj(key, value) {
1616
+ if (!langObj[key]) {
1617
+ langObj[key] = value;
1618
+ }
1619
+ }
1620
+
1621
+ /**
1622
+ * @description: 读取翻译对象
1623
+ * @return {*}
1624
+ */
1625
+ function getLangObj() {
1626
+ return langObj;
1627
+ }
1628
+
1629
+ /**
1630
+ * @description: 初始化翻译对象
1631
+ * @param {langObj} obj
1632
+ * @return {*}
1633
+ */
1634
+ function initLangObj(obj) {
1635
+ if (!Object.keys(langObj)) {
1636
+ langObj = obj;
1637
+ }
1638
+ }
1639
+
1640
+ // todo 类型修复
1641
+ /**
1642
+ * 自动生成多语言配置文件的核心方法
1643
+ *
1644
+ * 主要流程:
1645
+ * 1. 加载现有翻译文件
1646
+ * 2. 对比找出新增需要翻译的内容
1647
+ * 3. 分块并行翻译所有目标语言
1648
+ * 4. 合并翻译结果并生成最终配置文件
1649
+ *
1650
+ * 异常处理:
1651
+ * - 翻译结果不完整时中断流程
1652
+ * - 文件读写失败时明确报错
1653
+ */
1654
+ async function autoTranslate() {
1655
+ const enabled = typeof exports.option.enabled === 'function' ? exports.option.enabled() : exports.option.enabled;
1656
+ if (!enabled) return;
1657
+
1658
+ // 初始化现有翻译文件缓存
1659
+ const originLangObjMap = {};
1660
+
1661
+ // 加载所有语言的现有翻译内容
1662
+ // 获取当前待翻译内容(深拷贝避免污染原始数据)
1663
+ const currentLangObj = JSON.parse(JSON.stringify(getLangObj()));
1664
+ exports.option.langKey.forEach(lang => {
1665
+ const keyMap = getLangObjByJSONFileWithLangKey(lang);
1666
+ originLangObjMap[lang] = keyMap;
1667
+ });
1668
+
1669
+ // 筛选需要翻译的新增内容
1670
+ const transLangObj = {};
1671
+ Object.keys(currentLangObj).forEach(key => {
1672
+ if (!originLangObjMap[exports.option.originLang][key]) {
1673
+ transLangObj[key] = currentLangObj[key];
1674
+ }
1675
+ });
1676
+
1677
+ // 无新内容提前退出
1678
+ if (Object.keys(transLangObj).length === 0) {
1679
+ console.info('✅ 当前没有需要翻译的新内容');
1680
+ return;
1681
+ }
1682
+
1683
+ // 初始化翻译结果存储结构
1684
+ const newLangObjMap = {};
1685
+
1686
+ // 遍历所有目标语言进行处理
1687
+ for (let langIndex = 0; langIndex < exports.option.langKey.length; langIndex++) {
1688
+ const currentLang = exports.option.langKey[langIndex];
1689
+
1690
+ // 原始语言直接存储原文,读取扫出来的元素翻译内容
1691
+ if (langIndex === 0) {
1692
+ newLangObjMap[exports.option.originLang] = Object.values(transLangObj);
1693
+ continue;
1694
+ }
1695
+ console.info('开始自动翻译...');
1696
+
1697
+ // ─── 分块翻译流程开始 ───
1698
+ const translatedValues = await translateChunks(transLangObj, exports.option.langKey[langIndex]);
1699
+ // ─── 分块翻译流程结束 ───=
1700
+
1701
+ // ─── 翻译结果校验 ───
1702
+ if (translatedValues.length !== Object.keys(transLangObj).length) {
1703
+ console.error('❌ 使用付费翻译时,请检查翻译API额度是否充足,或是否已申请对应翻译API使用权限');
1704
+ console.error(`❌ 翻译结果不完整
1705
+ 预期数量: ${Object.keys(transLangObj).length}
1706
+ 实际数量: ${translatedValues.length}
1707
+ 样例数据: ${JSON.stringify(translatedValues.slice(0, 3))}`);
1708
+ return;
1709
+ }
1710
+
1711
+ // 存储当前语言翻译结果
1712
+ newLangObjMap[currentLang] = translatedValues;
1713
+ console.info(`✅ ${currentLang} 翻译完成`);
1714
+ }
1715
+
1716
+ // ─── 合并翻译结果到配置 ───
1717
+ Object.keys(transLangObj).forEach((key, index) => {
1718
+ exports.option.langKey.forEach(item => {
1719
+ originLangObjMap[item][key] = newLangObjMap[item][index];
1720
+ });
1721
+ });
1722
+
1723
+ // ─── 生成最终配置文件结构 ───
1724
+ console.log('📄 构建配置文件数据结构...');
1725
+ const configLangObj = {};
1726
+ Object.keys(originLangObjMap[exports.option.originLang]).forEach(key => {
1727
+ configLangObj[key] = {};
1728
+ exports.option.langKey.forEach(lang => {
1729
+ configLangObj[key][lang] = originLangObjMap[lang][key];
1730
+ });
1731
+ });
1732
+
1733
+ // ─── 写入文件系统 ───
1734
+ try {
1735
+ setLangTranslateJSONFile(configLangObj);
1736
+ console.info('🎉 多语言配置文件已成功更新');
1737
+ } catch (error) {
1738
+ console.error('❌ 配置文件写入失败,原因:', error);
1739
+ // todo 可添加重试逻辑或回滚机制
1740
+ }
1741
+ }
1742
+
1743
+ /**
1744
+ * @description: 新增语言类型配置补全
1745
+ * @param {any} obj
1746
+ * @return {*}
1747
+ */
1748
+ function languageConfigCompletion(obj) {
1749
+ if (!Object.keys(obj)) return;
1750
+ const enabled = typeof exports.option.enabled === 'function' ? exports.option.enabled() : exports.option.enabled;
1751
+ if (!enabled) return;
1752
+ let needCompletionList = [];
1753
+ const JSONobj = JSON.parse(getLangTranslateJSONFile());
1754
+ exports.option.targetLangList.forEach(item => {
1755
+ // 获取目标语言 hash:value 对象 和 语言的复合对象,如果当前语言不存在,是langObj的value卡都为空
1756
+ let langObj = getLangObjByJSONFileWithLangKey(item, JSONobj);
1757
+ needCompletionList.push({
1758
+ key: item,
1759
+ curLangObj: langObj
1760
+ });
1761
+ });
1762
+ needCompletionList.forEach(async item => {
1763
+ await completionTranslateAndWriteConfigFile(obj, item.curLangObj, item.key);
1764
+ });
1765
+ }
1766
+
1767
+ /**
1768
+ * @description: 补全新增语言翻译写入函数
1769
+ * @param langObj
1770
+ * @param curLangObj
1771
+ * @param translateKey
1772
+ * @return
1773
+ */
1774
+ async function completionTranslateAndWriteConfigFile(langObj, curLangObj, translateKey) {
1775
+ // 构建需要翻译的语言映射对象
1776
+ // langObj: 源语言的键值对映射,格式为 { hash: sourceText }
1777
+ // curLangObj: 目标语言的键值对映射,格式为 { hash: targetText },未翻译的值为空
1778
+
1779
+ // 创建待翻译内容对象,仅包含未翻译的条目,key是hash,value是源语言的对应hash的文本
1780
+ const transLangObj = {};
1781
+ Object.keys(langObj).forEach(key => {
1782
+ // 如果目标语言中对应的翻译为空,则将 源语言的对应hash的文本 加入待翻译内容对象 中
1783
+ if (curLangObj[key] === undefined) {
1784
+ transLangObj[key] = langObj[key];
1785
+ }
1786
+ });
1787
+ if (!Object.values(transLangObj).length) return;
1788
+
1789
+ // ─── 分块翻译流程开始 ───
1790
+
1791
+ console.info('进入新增语言补全翻译...');
1792
+
1793
+ // 调用抽离的函数
1794
+ const resultValues = await translateChunks(transLangObj, translateKey);
1795
+ // ─── 分块翻译流程结束 ───
1796
+
1797
+ if (resultValues.length !== Object.values(langObj).length) {
1798
+ console.error('翻译异常,翻译结果缺失❌');
1799
+ return;
1800
+ }
1801
+ let newLangObjMap = resultValues;
1802
+ console.info('翻译成功⭐️⭐️⭐️');
1803
+ Object.keys(transLangObj).forEach((key, index) => {
1804
+ curLangObj[key] = newLangObjMap[index];
1805
+ });
1806
+ console.log('开始写入JSON配置文件...');
1807
+ const configLangObj = JSON.parse(getLangTranslateJSONFile());
1808
+ Object.keys(transLangObj).forEach(key => {
1809
+ configLangObj[key][translateKey] = curLangObj[key];
1810
+ });
1811
+ try {
1812
+ setLangTranslateJSONFile(configLangObj);
1813
+ console.info('JSON配置文件写入成功⭐️⭐️⭐️');
1814
+ } catch (error) {
1815
+ console.error('❌JSON配置文件写入失败' + error);
1816
+ }
1817
+ console.info('新增语言翻译补全成功⭐️⭐️⭐️');
1818
+ }
1819
+
1820
+ // 分块翻译流程函数
1821
+ async function translateChunks(transLangObj, translateKey) {
1822
+ const {
1823
+ translator
1824
+ } = exports.option;
1825
+ // 获取分块后的文本列表
1826
+ const translationChunks = createTextSplitter(Object.values(transLangObj), translator.option.maxChunkSize);
1827
+ // 并行执行分块翻译
1828
+ const translatePromises = [];
1829
+ for (let i = 0; i < translationChunks.length; i++) {
1830
+ translatePromises.push(translator.translate(translationChunks[i], exports.option.originLang, translateKey, SEPARATOR));
1831
+ }
1832
+
1833
+ // 等待所有分块完成并合并结果
1834
+ const chunkResults = await Promise.all(translatePromises);
1835
+ return chunkResults.map(item => {
1836
+ // 提取分割逻辑到单独的函数中,提高代码复用性
1837
+ const splitTranslation = (text, separatorRegex) => {
1838
+ return text.split(separatorRegex).map(v => v.trim());
1839
+ };
1840
+
1841
+ // 分割符可能会被翻译,所以这里做了兼容处理
1842
+ if (SPLIT_SEPARATOR_REGEX.test(item)) {
1843
+ return splitTranslation(item, SPLIT_SEPARATOR_REGEX);
1844
+ } else {
1845
+ const lines = item.split('\n');
1846
+ const separator = lines.find(line => line.length === 3);
1847
+ let value = [];
1848
+ if (separator) {
1849
+ value = splitTranslation(item, new RegExp(`\\n${separator}\\n`));
1850
+ }
1851
+ const realList = value.filter(Boolean);
1852
+ if (realList.length > 1) {
1853
+ return realList;
1854
+ }
1855
+ return splitTranslation(item, SPLIT_SEPARATOR_REGEX);
1856
+ }
1857
+ }).flat();
1858
+ }
1859
+ /**
1860
+ * @description: 清理多余的翻译配置JSON文件
1861
+ * @return {void} 无返回值
1862
+ */
1863
+ function cleanupUnusedTranslations() {
1864
+ if (!exports.option.isClear) return;
1865
+ console.log('🧹 进入清理流程');
1866
+ // 获取当前的语言对象,如果不存在则使用空对象
1867
+ const langObj = getLangObj() || {};
1868
+
1869
+ // 创建一个Set用于存储当前语言对象的所有key,便于快速查找
1870
+ let langSet = new Set(Object.keys(langObj));
1871
+
1872
+ // 获取基础对象:优先使用传入的insertObj,否则从翻译文件中读取
1873
+ const baseObj = JSON.parse(getLangTranslateJSONFile());
1874
+
1875
+ // 获取基础对象的所有key
1876
+ const baseObjKeys = Object.keys(baseObj);
1877
+ // 遍历所有key,删除在当前语言对象中不存在的配置
1878
+ baseObjKeys.forEach(key => {
1879
+ if (!langSet.has(key)) {
1880
+ baseObj[key] && delete baseObj[key];
1881
+ }
1882
+ });
1883
+ setLangTranslateJSONFile(baseObj);
1884
+ }
1885
+
1886
+ var translate = /*#__PURE__*/Object.freeze({
1887
+ __proto__: null,
1888
+ SEPARATOR: SEPARATOR,
1889
+ SPLIT_SEPARATOR_REGEX: SPLIT_SEPARATOR_REGEX,
1890
+ autoTranslate: autoTranslate,
1891
+ cleanupUnusedTranslations: cleanupUnusedTranslations,
1892
+ completionTranslateAndWriteConfigFile: completionTranslateAndWriteConfigFile,
1893
+ getLangObj: getLangObj,
1894
+ initLangObj: initLangObj,
1895
+ get langObj () { return langObj; },
1896
+ languageConfigCompletion: languageConfigCompletion,
1897
+ setLangObj: setLangObj
1898
+ });
1899
+
1900
+ /*
1901
+ * @Date: 2025-02-17 17:11:26
1902
+ * @LastEditors: xiaoshan
1903
+ * @LastEditTime: 2025-02-17 18:00:37
1904
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/utils/chunk.ts
1905
+ */
1906
+
1907
+ /**
1908
+ * 智能文本分块处理器
1909
+ * @param values 待分块的原始文本数组
1910
+ * @param maxChunkSize 最大分块长度
1911
+ * @returns 包含分块文本和重组方法的对象
1912
+ *
1913
+ * 功能特性:
1914
+ * 1. 自动合并小文本为最大可能块
1915
+ * 2. 处理超长文本并给出警告
1916
+ * 3. 保证块长度不超过限制
1917
+ * 4. 保留原始顺序和分隔符语义
1918
+ */
1919
+ function createTextSplitter(values, maxChunkSize) {
1920
+ // 分隔符定义(用于合并/拆分时保持语义)
1921
+ const SEP_LENGTH = SEPARATOR.length;
1922
+
1923
+ // 结果存储和缓冲区
1924
+ const result = []; // 最终分块结果
1925
+ let buffer = []; // 当前累积块缓冲区
1926
+ let currentSize = 0; // 当前缓冲区字符数(含分隔符)
1927
+
1928
+ /**
1929
+ * 提交缓冲区内容到结果集
1930
+ * - 将缓冲区内容用分隔符连接
1931
+ * - 重置缓冲区和计数器
1932
+ */
1933
+ const commitBuffer = () => {
1934
+ if (buffer.length > 0) {
1935
+ // 计算实际连接长度用于验证
1936
+ const actualLength = buffer.join(SEPARATOR).length;
1937
+ if (actualLength > maxChunkSize) {
1938
+ console.warn(`缓冲区提交异常:生成块长度 ${actualLength} 超过限制`);
1939
+ }
1940
+ result.push(buffer.join(SEPARATOR));
1941
+ buffer = [];
1942
+ currentSize = 0;
1943
+ }
1944
+ };
1945
+
1946
+ // 主处理循环:遍历所有原始文本项
1947
+ for (const value of values) {
1948
+ // 计算需要新增的空间:文本长度 + 分隔符(非首项)
1949
+ const neededSpace = value.length + (buffer.length > 0 ? SEP_LENGTH : 0);
1950
+
1951
+ // ─── 超长文本处理策略 ───
1952
+ if (value.length > maxChunkSize) {
1953
+ // 优先提交现有缓冲区内容
1954
+ if (buffer.length > 0) commitBuffer();
1955
+
1956
+ /**
1957
+ * 超长文本处理逻辑:
1958
+ * - 长度超过1.5倍限制时发出强警告
1959
+ * - 强制单独成块(即使超过限制)
1960
+ * - 后续需要特殊处理这些异常块
1961
+ */
1962
+ if (value.length > maxChunkSize * 1.5) {
1963
+ console.warn(`超长文本告警:检测到长度 ${value.length} 字符的文本项,可能影响翻译质量`);
1964
+ }
1965
+ // 结果直接新增一个超长文本
1966
+ result.push(value);
1967
+ continue;
1968
+ }
1969
+
1970
+ // ─── 正常分块逻辑 ───
1971
+ // 空间不足时提交当前缓冲区
1972
+ if (currentSize + neededSpace > maxChunkSize) {
1973
+ commitBuffer();
1974
+ }
1975
+
1976
+ // 更新缓冲区状态(累加长度需包含分隔符)
1977
+ currentSize += neededSpace;
1978
+ buffer.push(value);
1979
+ }
1980
+
1981
+ // 提交最终未完成的缓冲区内容
1982
+ commitBuffer();
1983
+
1984
+ // 返回分块结果
1985
+ return result;
1986
+ }
1987
+
1988
+ /*
1989
+ * @Date: 2025-03-26 20:28:21
1990
+ * @LastEditors: xiaoshan
1991
+ * @LastEditTime: 2025-03-31 10:29:49
1992
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/utils/split.ts
1993
+ */
1994
+ // 插件核心文件
1995
+ // 字符串切割与转换函数
1996
+ // import generate from '@babel/generator'
1997
+
1998
+ // todo 这个切割函数可以优化,性能可能很差
1999
+ /**
2000
+ * 根据正则表达式分割字符串,并将符合正则的连续字符拼接起来。
2001
+ * @param str - 要分割的字符串。
2002
+ * @param separatorRegex - 用于分割字符串的正则表达式。
2003
+ * @returns 分割并拼接后的字符串数组。
2004
+ */
2005
+ /**
2006
+ * 这个函数的主要功能是根据给定的正则表达式分割字符串,并对分割结果进行特殊处理。
2007
+ * 处理过程分为三个主要步骤:
2008
+ *
2009
+ * 1. 首先根据分隔符正则和标点符号正则进行初步分割
2010
+ * 2. 然后将连续的标点符号和符合分隔符正则的部分重新连接
2011
+ * 3. 最后将不符合分隔符正则的相邻部分合并
2012
+ *
2013
+ * @param str - 需要分割的源字符串
2014
+ * @param separatorRegex - 用于分割的正则表达式
2015
+ * @returns 处理后的字符串数组
2016
+ */
2017
+ function splitByRegex(str, separatorRegex) {
2018
+ if (str.includes('\n')) console.log(str, separatorRegex);
2019
+
2020
+ // 定义标点符号的正则表达式
2021
+ const punctuationRegex = /[,。?!《》,..:!?""'';'"、0-9\n\r\t\v\f]/;
2022
+ // 创建一个新的正则表达式,用于分割字符串
2023
+ const splitRegex = new RegExp(`(${separatorRegex.source}|${punctuationRegex.source})`, separatorRegex.flags);
2024
+
2025
+ // 使用正则表达式分割字符串,并过滤掉空字符串
2026
+ const splitArr = str.split(splitRegex).filter(Boolean);
2027
+ const result = [];
2028
+ let currentMatch = '';
2029
+
2030
+ // 定义连接标点符号的正则表达式
2031
+ const connectPunctuationRegex = /[,。?!《》,..:!?;'"、0-9]/;
2032
+ // 创建一个新的正则表达式,用于检测是否需要连接
2033
+ const connectRegex = new RegExp(`(${separatorRegex.source}|${connectPunctuationRegex.source})`, separatorRegex.flags);
2034
+
2035
+ // 遍历分割后的数组
2036
+ for (const item of splitArr) {
2037
+ if (connectRegex.test(item)) {
2038
+ // 如果当前项符合连接条件,则将其添加到当前匹配字符串中
2039
+ currentMatch += item;
2040
+ } else {
2041
+ // 如果当前匹配字符串不为空,则将其添加到结果数组中
2042
+ if (currentMatch) {
2043
+ result.push(currentMatch);
2044
+ currentMatch = '';
2045
+ }
2046
+ // 将当前项添加到结果数组中
2047
+ result.push(item);
2048
+ }
2049
+ }
2050
+
2051
+ // 如果最后一个匹配字符串不为空,则将其添加到结果数组中
2052
+ if (currentMatch) {
2053
+ result.push(currentMatch);
2054
+ }
2055
+
2056
+ // 再遍历一次,把不符合separatorRegex 这个正则的拼起来
2057
+ const finalResult = [];
2058
+ let tempStr = '';
2059
+ for (let i = 0; i < result.length; i++) {
2060
+ const item = result[i];
2061
+ if (separatorRegex.test(item)) {
2062
+ if (tempStr) {
2063
+ finalResult.push(tempStr);
2064
+ tempStr = '';
2065
+ }
2066
+ finalResult.push(item);
2067
+ } else {
2068
+ tempStr += item;
2069
+ if (i === result.length - 1 || separatorRegex.test(result[i + 1])) {
2070
+ finalResult.push(tempStr);
2071
+ tempStr = '';
2072
+ }
2073
+ }
2074
+ }
2075
+ if (tempStr) {
2076
+ finalResult.push(tempStr);
2077
+ }
2078
+ return finalResult;
2079
+ }
2080
+
2081
+ /**
2082
+ * 检查字符串是否需要切割。
2083
+ * @param str - 要检查的字符串。
2084
+ * @returns 如果字符串需要切割,则返回 true,否则返回 false。
2085
+ */
2086
+ function checkNeedSplit(str) {
2087
+ // 检查字符串中是否包含需要切割的特殊字符
2088
+ return str.includes('\n') || str.includes('\\') || str.includes('\r') || str.includes('\t') || str.includes('\v') || str.includes('\f') || str.includes('>') || str.includes('<');
2089
+ }
2090
+
2091
+ /**
2092
+ * @description: 将字符串数组转换为babel的模板字符串节点
2093
+ * @param {string[]} strArray - 字符串数组
2094
+ * @return {types.CallExpression} - babel的深度扫描的表达式
2095
+ */
2096
+ function convertToTemplateLiteral(strArray, option) {
2097
+ const quasis = [];
2098
+ const expressions = [];
2099
+ strArray.forEach((str, index) => {
2100
+ if (index === 0) {
2101
+ if (getOriginRegex().test(str)) {
2102
+ quasis.push(types__namespace.templateElement({
2103
+ raw: '',
2104
+ cooked: ''
2105
+ }, false));
2106
+ expressions.push(createI18nTranslator({
2107
+ value: str,
2108
+ isExpression: true,
2109
+ insertOption: option
2110
+ }));
2111
+ } else {
2112
+ quasis.push(types__namespace.templateElement({
2113
+ raw: str,
2114
+ cooked: str
2115
+ }, false));
2116
+ }
2117
+ } else {
2118
+ if (getOriginRegex().test(str)) {
2119
+ expressions.push(createI18nTranslator({
2120
+ value: str,
2121
+ isExpression: true,
2122
+ insertOption: option
2123
+ }));
2124
+ } else {
2125
+ quasis.push(types__namespace.templateElement({
2126
+ raw: str,
2127
+ cooked: str
2128
+ }, false));
2129
+ }
2130
+ }
2131
+ });
2132
+ if (quasis.length === expressions.length) {
2133
+ quasis.push(types__namespace.templateElement({
2134
+ raw: '',
2135
+ cooked: ''
2136
+ }, true));
2137
+ } else if (quasis.length > expressions.length) {
2138
+ quasis[quasis.length - 1].tail = true;
2139
+ }
2140
+ const templateLiteral = types__namespace.templateLiteral(quasis, expressions);
2141
+ const deepScanCall = types__namespace.callExpression(types__namespace.identifier('$deepScan'), [templateLiteral]);
2142
+ // 打印转换结果
2143
+ // console.log('deepScanCall', (generate as any).default(deepScanCall).code)
2144
+ return deepScanCall;
2145
+ }
2146
+
2147
+ // 上传到远程服务器
2148
+ // import { getAppCode, saveConfig, convertToUploadJson } from './config.js'
2149
+ async function upload(json) {
2150
+ const {
2151
+ appCode,
2152
+ targetLangList
2153
+ } = exports.option;
2154
+ let data = [];
2155
+ _.map(json, (value, key) => {
2156
+ _.map(targetLangList, item => {
2157
+ const parts = item.split('-');
2158
+ const lang = parts[0] + '-' + parts[1].toUpperCase();
2159
+ data.push({
2160
+ page: 'common',
2161
+ key,
2162
+ lang,
2163
+ value: _.get(value, item, key)
2164
+ });
2165
+ });
2166
+ });
2167
+ const res = await axios.post('http://192.168.0.104:8108/i18n-web/kv_translate/batch', {
2168
+ appCode,
2169
+ data
2170
+ }, {
2171
+ headers: {
2172
+ 'Content-Type': 'application/json'
2173
+ }
2174
+ });
2175
+ if (res.status === 200 && res.data.result === 0) {
2176
+ console.info('上传翻译服务成功✔');
2177
+ } else {
2178
+ console.error('上传翻译服务失败❌');
2179
+ console.log(`请求数据为:`, JSON.stringify(data));
2180
+ console.log(`返回报错信息为:`, res.data);
2181
+ }
2182
+ }
2183
+
2184
+ var upload$1 = /*#__PURE__*/Object.freeze({
2185
+ __proto__: null,
2186
+ upload: upload
2187
+ });
2188
+
2189
+ class Vue2Extends {
2190
+ constructor() {
2191
+ this.handleInitFile = async (source, path) => {
2192
+ let code = source;
2193
+
2194
+ // 检查是否已经引入了 Vue
2195
+ let importVue = false;
2196
+ let hasVue = false;
2197
+ let importDefaultChar = 'Vue';
2198
+ const result = await babel.transformAsync(code, {
2199
+ configFile: false,
2200
+ plugins: [{
2201
+ visitor: {
2202
+ ImportDeclaration(path) {
2203
+ const {
2204
+ node
2205
+ } = path;
2206
+ if (node.source.value === 'vue') {
2207
+ importVue = true;
2208
+ const specifiers = node.specifiers;
2209
+ specifiers.forEach(specifier => {
2210
+ if (types.isImportDefaultSpecifier(specifier)) {
2211
+ hasVue = true;
2212
+ importDefaultChar = specifier.local.name;
2213
+ }
2214
+ });
2215
+ if (!hasVue) {
2216
+ hasVue = true;
2217
+ specifiers.unshift(types.importDefaultSpecifier(types.identifier('Vue')));
2218
+ }
2219
+ }
2220
+ }
2221
+ }
2222
+ }]
2223
+ });
2224
+ if (importVue && result) code = result.code;
2225
+ if (!importVue) code = `import Vue from 'vue'
2226
+ ${code}`;
2227
+ return {
2228
+ path,
2229
+ importDefaultChar,
2230
+ source: code
2231
+ };
2232
+ };
2233
+ this.handleCodeCall = (config, _initFileResult) => {
2234
+ const {
2235
+ option,
2236
+ hash,
2237
+ value,
2238
+ uncodeValue,
2239
+ namespace
2240
+ } = config;
2241
+ const valueExp = types.stringLiteral(value);
2242
+ valueExp.extra = {
2243
+ raw: `'${uncodeValue}'`,
2244
+ // 防止转码为unicode
2245
+ rawValue: value
2246
+ };
2247
+ return types.callExpression(types.memberExpression(types.memberExpression(types.identifier(_initFileResult.importDefaultChar), types.identifier('prototype')), types.identifier(option.translateKey)), [types.stringLiteral(hash), valueExp, types.stringLiteral(namespace)]);
2248
+ };
2249
+ this.handleCodeString = (config, _initFileResult) => {
2250
+ const {
2251
+ option,
2252
+ hash,
2253
+ uncodeValue,
2254
+ namespace
2255
+ } = config;
2256
+ return `${_initFileResult.importDefaultChar}.prototype.${option.translateKey}('${hash}','${uncodeValue}','${namespace}')`;
2257
+ };
2258
+ }
2259
+ }
2260
+
2261
+ /*
2262
+ * @Author: xiaoshanwen
2263
+ * @Date: 2023-11-01 16:35:38
2264
+ * @LastEditTime: 2025-03-31 02:29:02
2265
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/filter/visitor/TemplateElement.ts
2266
+ */
2267
+
2268
+ // 定义一个包含亚洲语言代码的数组
2269
+ const asianLangs = ['zh-cn', 'ja', 'ko'];
2270
+ function TemplateLiteral (insertOption) {
2271
+ return function (path) {
2272
+ // 如果是半自动翻译,不做处理
2273
+ if (exports.option.translateType === TranslateTypeEnum.SEMI_AUTO) {
2274
+ return;
2275
+ }
2276
+ let {
2277
+ node,
2278
+ parent
2279
+ } = path;
2280
+ if (!node.quasis.length) return;
2281
+ if (types.isTaggedTemplateExpression(parent)) {
2282
+ return;
2283
+ }
2284
+
2285
+ // 获取真实调用函数
2286
+ const extractFnName = extractFunctionName(parent);
2287
+
2288
+ // 调用语句判断当前调用语句是否包含需要过滤的调用语句
2289
+ if (types.isCallExpression(parent) && extractFnName && (exports.option.excludedCall.includes(extractFnName) || extractFnName?.split('.')?.pop() && exports.option.excludedCall.includes(extractFnName?.split('.')?.pop() || ''))) return;
2290
+ if (node.expressions.length && handleTemplateLiteralWithExpressions(node, path)) {
2291
+ return;
2292
+ }
2293
+ node.quasis.forEach(item => handleTemplateElement(item, insertOption));
2294
+ };
2295
+ }
2296
+ function handleTemplateLiteralWithExpressions(node, path) {
2297
+ const placeholders = node.expressions.map(expression => getExpressionPlaceholder(expression));
2298
+ if (placeholders.some(placeholder => !placeholder)) {
2299
+ return false;
2300
+ }
2301
+ const fullValue = node.quasis.reduce((result, quasi, index) => {
2302
+ let value = quasi.value.raw || quasi.value.cooked || '';
2303
+ if (asianLangs.some(lang => exports.option.originLang.includes(lang) || exports.option.originLang === lang)) {
2304
+ try {
2305
+ value = unicodeToString(value);
2306
+ } catch (error) {
2307
+ console.log('转换异常');
2308
+ }
2309
+ }
2310
+ return result + value + (index < node.expressions.length ? `\${${placeholders[index]}}` : '');
2311
+ }, '');
2312
+ if (!fullValue || !hasOriginSymbols(fullValue) || !exports.option.excludedPattern.length || checkAgainstRegexArray(fullValue, [...exports.option.excludedPattern])) {
2313
+ return false;
2314
+ }
2315
+ const {
2316
+ trimmedValue,
2317
+ valStr
2318
+ } = normalizeTranslateValue(fullValue);
2319
+ const id = generateId(valStr);
2320
+ const translateNode = createTranslateNode(path, id, valStr, placeholders, node.expressions);
2321
+ path.replaceWith(translateNode);
2322
+ path.skip();
2323
+ setLangObj(id, trimmedValue);
2324
+ return true;
2325
+ }
2326
+ function getExpressionPlaceholder(expression) {
2327
+ if (types.isIdentifier(expression)) {
2328
+ return expression.name;
2329
+ }
2330
+ if (types.isMemberExpression(expression)) {
2331
+ const objectName = getExpressionPlaceholder(expression.object);
2332
+ const propertyName = expression.computed ? getExpressionPlaceholder(expression.property) : types.isIdentifier(expression.property) ? expression.property.name : '';
2333
+ const value = [objectName, propertyName].filter(Boolean).join('.');
2334
+ return cleanVueRuntimePrefix(value);
2335
+ }
2336
+ if (types.isStringLiteral(expression) || types.isNumericLiteral(expression)) {
2337
+ return String(expression.value);
2338
+ }
2339
+ if (types.isTSAsExpression(expression) || types.isTSTypeAssertion(expression)) {
2340
+ return getExpressionPlaceholder(expression.expression);
2341
+ }
2342
+ if (types.isTSNonNullExpression(expression)) {
2343
+ return getExpressionPlaceholder(expression.expression);
2344
+ }
2345
+ const generateCode = generate__namespace.default?.default || generate__namespace.default || generate__namespace;
2346
+ return cleanVueRuntimePrefix(generateCode(expression).code);
2347
+ }
2348
+ function createTranslateNode(path, id, valStr) {
2349
+ let placeholders = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
2350
+ let expressions = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : [];
2351
+ const args = [types.stringLiteral(id), types.stringLiteral(valStr)];
2352
+ if (placeholders.length) {
2353
+ args.push(types.objectExpression(placeholders.map((placeholder, index) => types.objectProperty(types.stringLiteral(placeholder), types.cloneNode(expressions[index])))));
2354
+ }
2355
+ const translateCall = types.callExpression(types.identifier(exports.option.translateKey), args);
2356
+ if (!isVueTemplateRender(path)) {
2357
+ return translateCall;
2358
+ }
2359
+ return types.sequenceExpression([createVueTemplateLanguageDependency(), translateCall]);
2360
+ }
2361
+ function isVueTemplateRender(path) {
2362
+ return Boolean(path.scope?.getBinding('_vm'));
2363
+ }
2364
+ function createVueTemplateLanguageDependency() {
2365
+ const vm = types.identifier('_vm');
2366
+ const store = types.memberExpression(types.cloneNode(vm), types.identifier('$store'));
2367
+ const storeState = types.memberExpression(types.cloneNode(store), types.identifier('state'));
2368
+ const siteState = types.memberExpression(types.cloneNode(storeState), types.identifier('site'));
2369
+ const storeLanguage = types.logicalExpression('&&', types.logicalExpression('&&', types.logicalExpression('&&', types.cloneNode(store), types.cloneNode(storeState)), types.cloneNode(siteState)), types.memberExpression(types.cloneNode(siteState), types.identifier('language')));
2370
+ const i18n = types.memberExpression(types.cloneNode(vm), types.identifier('$i18n'));
2371
+ const i18nLocale = types.logicalExpression('&&', types.cloneNode(i18n), types.memberExpression(types.cloneNode(i18n), types.identifier('locale')));
2372
+ return types.logicalExpression('||', storeLanguage, i18nLocale);
2373
+ }
2374
+ function cleanVueRuntimePrefix(value) {
2375
+ return value.replace(/^(?:\$setup|_ctx|_vm|this)\./, '').replace(/([^\w$.])(?:\$setup|_ctx|_vm|this)\./g, '$1');
2376
+ }
2377
+
2378
+ // 处理模板元素
2379
+ function handleTemplateElement(node, insertOption) {
2380
+ let value = node.value.raw || node.value.cooked; // 获取模板字符串的值
2381
+ if (asianLangs.some(lang => exports.option.originLang.includes(lang) || exports.option.originLang === lang)) {
2382
+ try {
2383
+ value = unicodeToString(value || '');
2384
+ } catch (error) {
2385
+ console.log('转换异常');
2386
+ }
2387
+ }
2388
+ // 是否存在来源语言字符,是否在默认字符串中,是否包含过滤字段
2389
+ if (value && hasOriginSymbols(value) && exports.option.excludedPattern.length && !checkAgainstRegexArray(value, [...exports.option.excludedPattern])) {
2390
+ // 生成字符类型翻译节点
2391
+ let newNode = createI18nTranslator({
2392
+ insertOption,
2393
+ value
2394
+ });
2395
+
2396
+ // 替换为字符类型翻译节点
2397
+ node.value.raw = node.value.cooked = `\${${newNode}}`;
2398
+ const {
2399
+ valStr
2400
+ } = normalizeTranslateValue(value);
2401
+ let id = generateId(valStr);
2402
+ if (id && value) {
2403
+ setLangObj(id, value);
2404
+ }
2405
+ }
2406
+ }
2407
+
2408
+ /*
2409
+ * @Author: xiaoshanwen
2410
+ * @Date: 2023-10-12 18:18:51
2411
+ * @LastEditTime: 2025-03-16 15:17:30
2412
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/filter/visitor/CallExpression.ts
2413
+ */
2414
+
2415
+ // 收集翻译对象
2416
+ function CallExpressionFn (insertOption) {
2417
+ return function (path) {
2418
+ let {
2419
+ node
2420
+ } = path;
2421
+ // 提取公共部分,减少重复访问 node.callee 属性
2422
+ const callee = node.callee;
2423
+ if (callee.name === exports.option.translateKey || callee.property && callee.property.name === exports.option.translateKey // 拓展 半自动模式下的 如 a.b.c() 调用
2424
+ ) {
2425
+ if (exports.option.translateType === TranslateTypeEnum.SEMI_AUTO) {
2426
+ // 获取当前翻译函数的参数
2427
+ let arg = node.arguments || [];
2428
+ // 如果参数数量不为 1,则直接返回
2429
+ if (arg.length === 1) {
2430
+ const value = arg[0]?.value || '';
2431
+ // 生成真实调用函数
2432
+ const replaceNode = createI18nTranslator({
2433
+ insertOption,
2434
+ value,
2435
+ isExpression: true
2436
+ });
2437
+ path.replaceWith(replaceNode);
2438
+ translateSetLang(replaceNode);
2439
+ }
2440
+ } else if (exports.option.translateType === TranslateTypeEnum.FULL_AUTO) {
2441
+ // 全自动模式下还是只收集 单独 $t 调用
2442
+ if (callee.name === exports.option.translateKey || callee.property && callee.property.name === exports.option.translateKey) translateSetLang(node);
2443
+ }
2444
+ }
2445
+ };
2446
+ }
2447
+
2448
+ /**
2449
+ * @description: 处理翻译并设置语言对象属性
2450
+ * @param node - 调用表达式节点
2451
+ * @return
2452
+ */
2453
+ function translateSetLang(node) {
2454
+ // 获取调用表达式的参数
2455
+ let arg = node.arguments || [];
2456
+ // 提取参数作为值
2457
+ // 检查参数是否为字符串字面量
2458
+ const id = types__namespace.isStringLiteral(arg[0]) ? arg[0].value : '';
2459
+ const value = types__namespace.isStringLiteral(arg[1]) ? arg[1].value : '';
2460
+ // 检查 ID 和值是否存在,并且第二个参数是字符串字面量
2461
+ if (id && value && types__namespace.isStringLiteral(arg[1])) {
2462
+ // 调用翻译工具的 setLangObj 方法设置语言对象属性
2463
+ setLangObj(id, value);
2464
+ }
2465
+ }
2466
+
2467
+ /*
2468
+ * @Author: xiaoshanwen
2469
+ * @Date: 2023-10-12 18:18:51
2470
+ * @LastEditTime: 2025-03-31 02:28:53
2471
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/filter/visitor/StringLiteral.ts
2472
+ */
2473
+ function StringLiteralFn (insertOption) {
2474
+ return function (path) {
2475
+ if (exports.option.translateType === TranslateTypeEnum.SEMI_AUTO) {
2476
+ return;
2477
+ }
2478
+ let {
2479
+ node,
2480
+ parent
2481
+ } = path;
2482
+ let value = node.value;
2483
+
2484
+ // 定义一个包含亚洲语言代码的数组
2485
+ const asianLangs = ['zh-cn', 'ja', 'ko'];
2486
+ if (asianLangs.some(lang => exports.option.originLang.includes(lang) || exports.option.originLang === lang)) {
2487
+ try {
2488
+ value = unicodeToString(value);
2489
+ } catch (error) {
2490
+ console.log('转换异常');
2491
+ }
2492
+ }
2493
+ if (hasOriginSymbols(value) && exports.option.excludedPattern.length && !checkAgainstRegexArray(value, [...exports.option.excludedPattern])) {
2494
+ // 获取真实调用函数
2495
+ const extractFnName = extractFunctionName(parent);
2496
+
2497
+ // 防止导入语句,只处理那些当前节点不是键值对的键的字符串字面量,调用语句判断当前调用语句是否包含需要过滤的调用语句
2498
+ if (isTranslateCall(parent) || types__namespace.isImportDeclaration(parent) || parent.key === node || types__namespace.isCallExpression(parent) && extractFnName && (exports.option.excludedCall.includes(extractFnName) || extractFnName?.split('.')?.pop() && exports.option.excludedCall.includes(extractFnName?.split('.')?.pop() || ''))) return;
2499
+ let replaceNode;
2500
+ if (exports.option.deepScan && checkNeedSplit(value)) {
2501
+ replaceNode = convertToTemplateLiteral(splitByRegex(value, getOriginRegex()), insertOption);
2502
+ } else if (types__namespace.isJSXAttribute(parent)) {
2503
+ let expression = createI18nTranslator({
2504
+ insertOption,
2505
+ value,
2506
+ isExpression: true
2507
+ });
2508
+ replaceNode = types__namespace.jSXExpressionContainer(expression);
2509
+ } else {
2510
+ replaceNode = createI18nTranslator({
2511
+ insertOption,
2512
+ value,
2513
+ isExpression: true
2514
+ });
2515
+ }
2516
+ path.replaceWith(replaceNode);
2517
+ }
2518
+ };
2519
+ }
2520
+ function isTranslateCall(node) {
2521
+ if (!types__namespace.isCallExpression(node)) return false;
2522
+ const callee = node.callee;
2523
+ if (types__namespace.isIdentifier(callee)) {
2524
+ return callee.name === exports.option.translateKey;
2525
+ }
2526
+ if (types__namespace.isMemberExpression(callee)) {
2527
+ return types__namespace.isIdentifier(callee.property) && callee.property.name === exports.option.translateKey;
2528
+ }
2529
+ return false;
2530
+ }
2531
+
2532
+ /*
2533
+ * @Author: xiaoshanwen
2534
+ * @Date: 2023-11-01 16:35:38
2535
+ * @LastEditTime: 2025-03-16 18:24:44
2536
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/filter/visitor/JSXText.ts
2537
+ */
2538
+ function JSXTextFn (insertOption) {
2539
+ return function (path) {
2540
+ console.log('jsx text');
2541
+ if (exports.option.translateType === TranslateTypeEnum.SEMI_AUTO) {
2542
+ return;
2543
+ }
2544
+ let {
2545
+ node
2546
+ } = path;
2547
+ let value = node.value;
2548
+ // 定义一个包含亚洲语言代码的数组
2549
+ const asianLangs = ['zh-cn', 'ja', 'ko'];
2550
+ if (asianLangs.some(lang => exports.option.originLang.includes(lang) || exports.option.originLang === lang)) {
2551
+ try {
2552
+ value = unicodeToString(value);
2553
+ } catch (error) {
2554
+ console.log('转换异常');
2555
+ }
2556
+ }
2557
+ if (hasOriginSymbols(value) && exports.option.excludedPattern.length && !checkAgainstRegexArray(value, [...exports.option.excludedPattern])) {
2558
+ // 生成翻译节点
2559
+ let expression = createI18nTranslator({
2560
+ insertOption,
2561
+ value,
2562
+ isExpression: true
2563
+ });
2564
+ // 生成的翻译节点包装在 types.JSXExpressionContainer 中
2565
+ let newNode = types__namespace.jSXExpressionContainer(expression);
2566
+ // 使用 path.replaceWith 方法将原来的节点替换为新的翻译节点
2567
+ path.replaceWith(newNode);
2568
+ }
2569
+ };
2570
+ }
2571
+
2572
+ /*
2573
+ * @Author: xiaoshanwen
2574
+ * @Date: 2023-10-12 18:00:37
2575
+ * @LastEditTime: 2023-11-02 10:36:02
2576
+ * @FilePath: /i18n_translation_vite/src/plugins/filter/index.ts
2577
+ */
2578
+
2579
+ function index (insertOption) {
2580
+ // 分别调用各个访问器函数并传入插入选项
2581
+ const stringLiteralVisitor = StringLiteralFn(insertOption);
2582
+ const jsxTextVisitor = JSXTextFn(insertOption);
2583
+ const templateLiteralVisitor = TemplateLiteral(insertOption);
2584
+ const callExpressionVisitor = CallExpressionFn(insertOption);
2585
+
2586
+ // 返回一个函数,该函数返回包含访问器的对象
2587
+ return function () {
2588
+ return {
2589
+ // 定义 Babel 访问器对象
2590
+ visitor: {
2591
+ StringLiteral: stringLiteralVisitor,
2592
+ JSXText: jsxTextVisitor,
2593
+ TemplateLiteral: templateLiteralVisitor,
2594
+ CallExpression: callExpressionVisitor
2595
+ }
2596
+ };
2597
+ };
2598
+ }
2599
+
2600
+ var index$1 = /*#__PURE__*/Object.freeze({
2601
+ __proto__: null,
2602
+ default: index
2603
+ });
2604
+
2605
+ var allowedExtensions = ['.vue', '.ts', '.js', '.tsx', '.jsx'];
2606
+ function vitePluginsAutoI18n(optionInfo) {
2607
+ var name = 'vite-gc-i18n-plugin';
2608
+ var config;
2609
+ initOption(__assign({
2610
+ deepScan: true,
2611
+ globalPath: './lang',
2612
+ namespace: 'lang',
2613
+ translateKey: '$t',
2614
+ distPath: './dist/assets',
2615
+ distKey: 'index',
2616
+ targetLangList: ['zh-cn', 'zh-tw'],
2617
+ originLang: 'zh-cn',
2618
+ translator: new CNToTWTranslator()
2619
+ }, optionInfo));
2620
+ if (!checkOption()) return {
2621
+ name: name
2622
+ };
2623
+ initLangFile();
2624
+ var originLangObj = getLangObjByJSONFileWithLangKey(exports.option.originLang);
2625
+ languageConfigCompletion(originLangObj);
2626
+ initLangObj(originLangObj);
2627
+ var plugin = {
2628
+ name: name,
2629
+ configResolved: function (resolvedConfig) {
2630
+ // 存储最终解析的配置
2631
+ config = resolvedConfig;
2632
+ },
2633
+ transform: function (code, path) {
2634
+ return __awaiter(this, void 0, void 0, function () {
2635
+ var sourceObj;
2636
+ var _a;
2637
+ return __generator(this, function (_b) {
2638
+ switch (_b.label) {
2639
+ case 0:
2640
+ if (!__spreadArray(__spreadArray([], allowedExtensions, true), exports.option.insertFileExtensions || [], true).some(function (ext) {
2641
+ return path.endsWith(ext);
2642
+ })) return [3 /*break*/, 4];
2643
+ if (exports.option.includePath.length && !checkAgainstRegexArray(path, exports.option.includePath)) return [2 /*return*/, code];
2644
+ if (exports.option.excludedPath.length && checkAgainstRegexArray(path, exports.option.excludedPath)) return [2 /*return*/, code];
2645
+ FunctionFactoryOption.originLang = exports.option.originLang;
2646
+ sourceObj = void 0;
2647
+ if (!exports.option.translateExtends) return [3 /*break*/, 2];
2648
+ return [4 /*yield*/, (_a = exports.option.translateExtends) === null || _a === void 0 ? void 0 : _a.handleInitFile(code, path)];
2649
+ case 1:
2650
+ sourceObj = _b.sent();
2651
+ return [3 /*break*/, 3];
2652
+ case 2:
2653
+ sourceObj = {
2654
+ source: code
2655
+ };
2656
+ _b.label = 3;
2657
+ case 3:
2658
+ return [2 /*return*/, babel__namespace.transformAsync(sourceObj.source, {
2659
+ configFile: false,
2660
+ plugins: [index()]
2661
+ }).then(function (result) {
2662
+ if ((config === null || config === void 0 ? void 0 : config.command) === 'serve') {
2663
+ autoTranslate(); // 执行前需要确保transformAsync已经完成
2664
+ }
2665
+ return result === null || result === void 0 ? void 0 : result.code;
2666
+ }).catch(function (e) {
2667
+ console.error(e);
2668
+ })];
2669
+ case 4:
2670
+ return [2 /*return*/];
2671
+ }
2672
+ });
2673
+ });
2674
+ },
2675
+ buildEnd: function () {
2676
+ return __awaiter(this, void 0, void 0, function () {
2677
+ return __generator(this, function (_a) {
2678
+ switch (_a.label) {
2679
+ case 0:
2680
+ console.info('构建阶段批量翻译');
2681
+ return [4 /*yield*/, autoTranslate()];
2682
+ case 1:
2683
+ _a.sent();
2684
+ return [2 /*return*/];
2685
+ }
2686
+ });
2687
+ });
2688
+ },
2689
+ closeBundle: function () {
2690
+ return __awaiter(this, void 0, void 0, function () {
2691
+ return __generator(this, function (_a) {
2692
+ switch (_a.label) {
2693
+ case 0:
2694
+ if (!(config && config.command === 'build')) return [3 /*break*/, 3];
2695
+ if (!exports.option.uploadEnabled) return [3 /*break*/, 2];
2696
+ console.info('构建阶段:开始上传翻译文件');
2697
+ return [4 /*yield*/, uploadFile()];
2698
+ case 1:
2699
+ _a.sent();
2700
+ return [3 /*break*/, 3];
2701
+ case 2:
2702
+ console.info('构建阶段:上传翻译文件功能已禁用(uploadEnabled: false)');
2703
+ _a.label = 3;
2704
+ case 3:
2705
+ return [2 /*return*/];
2706
+ }
2707
+ });
2708
+ });
2709
+ }
2710
+ };
2711
+ return plugin;
2712
+ }
2713
+
2714
+ exports.BaiduTranslator = BaiduTranslator;
2715
+ exports.CNToTWTranslator = CNToTWTranslator;
2716
+ exports.EmptyTranslator = EmptyTranslator;
2717
+ exports.FunctionFactoryOption = FunctionFactoryOption;
2718
+ exports.GoogleTranslator = GoogleTranslator;
2719
+ exports.LanguageEnum = LanguageEnum;
2720
+ exports.OriginLangKeyEnum = OriginLangKeyEnum;
2721
+ exports.ScanTranslator = ScanTranslator;
2722
+ exports.TranslateApiEnum = TranslateApiEnum;
2723
+ exports.TranslateTypeEnum = TranslateTypeEnum;
2724
+ exports.Translator = Translator;
2725
+ exports.VolcengineTranslator = VolcengineTranslator;
2726
+ exports.Vue2Extends = Vue2Extends;
2727
+ exports.YoudaoTranslator = YoudaoTranslator;
2728
+ exports.baseUtils = base;
2729
+ exports.checkOption = checkOption;
2730
+ exports.default = vitePluginsAutoI18n;
2731
+ exports.fileUtils = file;
2732
+ exports.filter = index$1;
2733
+ exports.initOption = initOption;
2734
+ exports.translateUtils = translate;
2735
+ exports.uploadUtils = upload$1;
2
2736
  //# sourceMappingURL=index.cjs.map