@yxw007/translate 0.3.2 → 0.4.1

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.
@@ -1,4 +1,4 @@
1
- // translate v0.3.2 Copyright (c) 2025 Potter<aa4790139@gmail.com> and contributors
1
+ // translate v0.4.1 Copyright (c) 2025 Potter<aa4790139@gmail.com> and contributors
2
2
  'use strict';
3
3
 
4
4
  Object.defineProperty(exports, '__esModule', { value: true });
@@ -17,6 +17,14 @@ class TranslationError extends Error {
17
17
  Error.captureStackTrace(this, this.constructor);
18
18
  }
19
19
  }
20
+ class CheckLanguageError extends Error {
21
+ region;
22
+ constructor(region, message) {
23
+ super(message);
24
+ this.region = region;
25
+ Error.captureStackTrace(this, this.constructor);
26
+ }
27
+ }
20
28
  const OPEN_AI_MODELS = [
21
29
  "o1-preview",
22
30
  "o1-preview-2024-09-12",
@@ -231,6 +239,22 @@ function google(options) {
231
239
  }
232
240
  return translations;
233
241
  },
242
+ async checkLanguage(text) {
243
+ const url = `${base}?client=gtx&sl=auto&tl=en&dt=t&q=${encodeURI(text)}`;
244
+ const res = await fetch(url);
245
+ if (!res.ok) {
246
+ throw await throwResponseError(this.name, res);
247
+ }
248
+ const body = await res.json();
249
+ if (!body || body.length < 3) {
250
+ throw new CheckLanguageError(this.name, "Check language fail! No result returned");
251
+ }
252
+ const detectedLanguage = body[2];
253
+ if (!detectedLanguage) {
254
+ throw new CheckLanguageError(this.name, "Check language fail! Language not detected");
255
+ }
256
+ return detectedLanguage;
257
+ },
234
258
  };
235
259
  }
236
260
 
@@ -270,7 +294,7 @@ function azure$1(options) {
270
294
  }
271
295
  const bodyRes = await res.json();
272
296
  if (bodyRes.error) {
273
- throw new TranslationError(this.name, `Translate fail ! code: ${bodyRes.error.code}, message: ${bodyRes.error.message}`);
297
+ throw new TranslationError(this.name, `Translate fail ! code: ${bodyRes.error.code}, message: ${bodyRes.error.message} \n Go to https://learn.microsoft.com/zh-cn/azure/ai-services/translator/text-translation/reference/v3/translate view details`);
274
298
  }
275
299
  const body = bodyRes;
276
300
  if (!body || body.length === 0) {
@@ -285,6 +309,34 @@ function azure$1(options) {
285
309
  }
286
310
  return translations;
287
311
  },
312
+ async checkLanguage(text) {
313
+ checkOptions();
314
+ const url = `${base}&to=en`;
315
+ const res = await fetch(url, {
316
+ method: "POST",
317
+ headers: {
318
+ "Content-Type": "application/json; charset=UTF-8",
319
+ "Ocp-Apim-Subscription-Key": key,
320
+ "Ocp-Apim-Subscription-Region": region,
321
+ },
322
+ body: JSON.stringify([{ Text: text }]),
323
+ });
324
+ if (!res.ok) {
325
+ throw await throwResponseError(this.name, res);
326
+ }
327
+ const bodyRes = await res.json();
328
+ if (bodyRes.error) {
329
+ throw new CheckLanguageError(this.name, `checkLanguage fail ! code: ${bodyRes.error.code}, message: ${bodyRes.error.message} \n Go to https://learn.microsoft.com/zh-cn/azure/ai-services/translator/text-translation/reference/v3/translate view details`);
330
+ }
331
+ if (!bodyRes || !Array.isArray(bodyRes) || bodyRes.length === 0) {
332
+ throw new CheckLanguageError(this.name, "Check language fail! No result returned");
333
+ }
334
+ const detectedLanguage = bodyRes[0]?.detectedLanguage?.language;
335
+ if (!detectedLanguage) {
336
+ throw new CheckLanguageError(this.name, "Check language fail! Language not detected");
337
+ }
338
+ return detectedLanguage;
339
+ },
288
340
  };
289
341
  }
290
342
 
@@ -319,6 +371,28 @@ function amazon$1(options) {
319
371
  }
320
372
  return translations;
321
373
  },
374
+ async checkLanguage(text) {
375
+ checkOptions();
376
+ const translateClient = new clientTranslate.TranslateClient({
377
+ region: region,
378
+ credentials: { accessKeyId, secretAccessKey },
379
+ });
380
+ const command = new clientTranslate.TranslateTextCommand({
381
+ SourceLanguageCode: "auto",
382
+ TargetLanguageCode: "en",
383
+ Text: text,
384
+ });
385
+ try {
386
+ const response = await translateClient.send(command);
387
+ if (!response.SourceLanguageCode) {
388
+ throw new TranslationError(name, "Check language fail! Source language not detected");
389
+ }
390
+ return response.SourceLanguageCode;
391
+ }
392
+ catch (error) {
393
+ throw new TranslationError(name, `Check language fail! ${error.message || error}`);
394
+ }
395
+ },
322
396
  };
323
397
  }
324
398
 
@@ -1411,7 +1485,7 @@ function requireCore () {
1411
1485
  var md5Exports = md5$1.exports;
1412
1486
  var md5 = /*@__PURE__*/getDefaultExportFromCjs(md5Exports);
1413
1487
 
1414
- function baidu$1(options) {
1488
+ function baidu$2(options) {
1415
1489
  const { appId, secretKey } = options;
1416
1490
  const url = "https://fanyi-api.baidu.com/api/trans/vip/fieldtranslate";
1417
1491
  const name = "baidu";
@@ -1452,7 +1526,7 @@ function baidu$1(options) {
1452
1526
  }
1453
1527
  const data = await res.json();
1454
1528
  if (!data || data.error_code || !data.trans_result || data.trans_result.length === 0) {
1455
- throw new TranslationError(this.name, `Translate fail ! error_code:${data.error_code}, error_msg: ${data.error_msg}`);
1529
+ throw new TranslationError(this.name, `Translate fail ! error_code:${data.error_code}, error_msg: ${data.error_msg} \n Go to https://fanyi-api.baidu.com/product/123 view details`);
1456
1530
  }
1457
1531
  const translations = [];
1458
1532
  for (const translation of data.trans_result) {
@@ -1462,6 +1536,31 @@ function baidu$1(options) {
1462
1536
  }
1463
1537
  return translations;
1464
1538
  },
1539
+ async checkLanguage(text) {
1540
+ checkOptions();
1541
+ const salt = Date.now();
1542
+ const sign = md5(`${appId}${text}${salt}${secretKey}`).toString();
1543
+ const body = new URLSearchParams();
1544
+ body.append("q", text);
1545
+ body.append("appid", appId);
1546
+ body.append("salt", salt.toString());
1547
+ body.append("sign", sign);
1548
+ const res = await fetch("https://fanyi-api.baidu.com/api/trans/vip/language", {
1549
+ method: "POST",
1550
+ headers: {
1551
+ "Content-Type": "application/x-www-form-urlencoded",
1552
+ },
1553
+ body: body.toString(),
1554
+ });
1555
+ if (!res.ok) {
1556
+ throw await throwResponseError(this.name, res);
1557
+ }
1558
+ const response = await res.json();
1559
+ if (!response || response.error_code != 0) {
1560
+ throw new CheckLanguageError(this.name, `Check language fail ! error_code:${response.error_code}, error_msg: ${response.error_msg} \n Go to https://fanyi-api.baidu.com/product/143 view details`);
1561
+ }
1562
+ return response.data.src;
1563
+ },
1465
1564
  };
1466
1565
  }
1467
1566
 
@@ -1512,6 +1611,39 @@ function deepl$2(options) {
1512
1611
  const translations = body.map((t) => t.text);
1513
1612
  return translations;
1514
1613
  },
1614
+ async checkLanguage(text) {
1615
+ checkOptions();
1616
+ const res = await fetch(url, {
1617
+ method: "POST",
1618
+ headers: {
1619
+ "Content-Type": "application/json; charset=UTF-8",
1620
+ Authorization: `DeepL-Auth-Key ${key}`,
1621
+ Accept: "*/*",
1622
+ Host: "api-free.deepl.com",
1623
+ Connection: "keep-alive",
1624
+ },
1625
+ body: JSON.stringify({
1626
+ text: [text],
1627
+ target_lang: "EN",
1628
+ }),
1629
+ });
1630
+ if (!res.ok) {
1631
+ throw await throwResponseError(this.name, res);
1632
+ }
1633
+ const bodyRes = await res.json();
1634
+ if (bodyRes.error) {
1635
+ throw new CheckLanguageError(this.name, `Check language fail ! code: ${bodyRes.error.code}, message: ${bodyRes.error.message}`);
1636
+ }
1637
+ const body = bodyRes.translations;
1638
+ if (!body || body.length === 0) {
1639
+ throw new CheckLanguageError(this.name, "Check language fail! No result returned");
1640
+ }
1641
+ const detectedLanguage = body[0].detected_source_language;
1642
+ if (!detectedLanguage) {
1643
+ throw new CheckLanguageError(this.name, "Check language fail! Language not detected");
1644
+ }
1645
+ return detectedLanguage;
1646
+ },
1515
1647
  };
1516
1648
  }
1517
1649
 
@@ -1694,7 +1826,7 @@ function tencent$2(options) {
1694
1826
  }
1695
1827
  const data = await res.json();
1696
1828
  if (data.Response?.Error) {
1697
- throw new TranslationError(name, `Tencent translate fail: ${data.Response.Error.Code}, ${data.Response.Error.Message}`);
1829
+ throw new TranslationError(name, `Tencent translate fail: ${data.Response.Error.Code}, ${data.Response.Error.Message} \n Go to https://cloud.tencent.com/document/product/551/15619 view details`);
1698
1830
  }
1699
1831
  const translatedResults = data.Response?.TargetText.split("\n") ?? [];
1700
1832
  if (!Array.isArray(translatedResults) || translatedResults.length === 0) {
@@ -1708,6 +1840,51 @@ function tencent$2(options) {
1708
1840
  throw new TranslationError(name, `Translation failed: ${error}`);
1709
1841
  }
1710
1842
  },
1843
+ async checkLanguage(text) {
1844
+ checkOptions();
1845
+ const payloadObj = {
1846
+ SourceText: text,
1847
+ Source: "auto",
1848
+ Target: "en",
1849
+ ProjectId: 0,
1850
+ };
1851
+ const payload = JSON.stringify(payloadObj);
1852
+ const headers = buildAuthorization({
1853
+ secretId,
1854
+ secretKey,
1855
+ service,
1856
+ host,
1857
+ payload,
1858
+ httpRequestMethod: "POST",
1859
+ action,
1860
+ apiVersion,
1861
+ region,
1862
+ });
1863
+ try {
1864
+ const res = await fetch(endpoint, {
1865
+ method: "POST",
1866
+ headers,
1867
+ body: payload,
1868
+ });
1869
+ if (!res.ok) {
1870
+ throw new CheckLanguageError(name, `HTTP ${res.status}: ${await res.text()}`);
1871
+ }
1872
+ const data = await res.json();
1873
+ if (data.Response?.Error) {
1874
+ throw new CheckLanguageError(name, `Tencent language detect fail: ${data.Response.Error.Code}, ${data.Response.Error.Message} \n Go to https://cloud.tencent.com/document/product/551/15619 view details`);
1875
+ }
1876
+ const detectedLanguage = data.Response?.Source;
1877
+ if (!detectedLanguage) {
1878
+ throw new CheckLanguageError(name, "Language detect fail! No result returned");
1879
+ }
1880
+ return detectedLanguage;
1881
+ }
1882
+ catch (error) {
1883
+ if (error instanceof CheckLanguageError)
1884
+ throw error;
1885
+ throw new CheckLanguageError(name, `Language detection failed: ${error}`);
1886
+ }
1887
+ },
1711
1888
  };
1712
1889
  }
1713
1890
 
@@ -1715,7 +1892,7 @@ const engines = {
1715
1892
  google,
1716
1893
  azure: azure$1,
1717
1894
  amazon: amazon$1,
1718
- baidu: baidu$1,
1895
+ baidu: baidu$2,
1719
1896
  deepl: deepl$2,
1720
1897
  openai: openai$1,
1721
1898
  tencent: tencent$2,
@@ -2105,7 +2282,7 @@ var openai = {
2105
2282
  Zulu: "zu",
2106
2283
  };
2107
2284
 
2108
- var baidu = {
2285
+ var baidu$1 = {
2109
2286
  Achinese: "ach",
2110
2287
  Afrikaans: "afr",
2111
2288
  Akan: "aka",
@@ -2455,7 +2632,7 @@ var amazon = {
2455
2632
  const originLanguages = {
2456
2633
  azure: azure,
2457
2634
  google: openai,
2458
- baidu: baidu,
2635
+ baidu: baidu$1,
2459
2636
  deepl: deepl$1,
2460
2637
  amazon: amazon,
2461
2638
  openai: openai,
@@ -2525,13 +2702,26 @@ var tencent = {
2525
2702
  const targetLanguages = {
2526
2703
  azure: azure,
2527
2704
  google: openai,
2528
- baidu: baidu,
2705
+ baidu: baidu$1,
2529
2706
  deepl: deepl,
2530
2707
  amazon: amazon,
2531
2708
  openai: openai,
2532
2709
  tencent: tencent,
2533
2710
  };
2534
2711
 
2712
+ var baidu = {
2713
+ Chinese: "zh",
2714
+ English: "en",
2715
+ Japanese: "jp",
2716
+ Korean: "kor",
2717
+ Thai: "th",
2718
+ Russian: "ru",
2719
+ };
2720
+
2721
+ const checkLanguages = Object.assign(Object.assign({}, originLanguages), {
2722
+ baidu: baidu,
2723
+ });
2724
+
2535
2725
  function normalFromLanguage(from, engine) {
2536
2726
  if (from === "auto") {
2537
2727
  return "auto";
@@ -2610,6 +2800,42 @@ class Translator {
2610
2800
  }
2611
2801
  this.engines.delete(engineName);
2612
2802
  }
2803
+ isSupportCheckLanguage(engineName) {
2804
+ if (!engineName || !this.engines.has(engineName)) {
2805
+ logger.warn("Engine name is required or not found");
2806
+ return false;
2807
+ }
2808
+ const engine = this.engines.get(engineName);
2809
+ if (!engine) {
2810
+ logger.warn(`Engine ${engineName} not found`);
2811
+ return false;
2812
+ }
2813
+ return !!engine.checkLanguage;
2814
+ }
2815
+ async checkLanguage(text, options) {
2816
+ const { engine = "google", max_character_num = defaultMaxCharacterNum } = options;
2817
+ if (!this.engines.has(engine)) {
2818
+ throw new CheckLanguageError(appName, `Engine ${engine} not found`);
2819
+ }
2820
+ const engineInstance = this.engines.get(engine);
2821
+ if (!engineInstance) {
2822
+ throw new CheckLanguageError(appName, `Engine ${engine} is null`);
2823
+ }
2824
+ if (!engineInstance.checkLanguage) {
2825
+ throw new CheckLanguageError(appName, `Engine ${engine} does not support checkLanguage method`);
2826
+ }
2827
+ const sample = max_character_num > 0 ? text.substring(0, max_character_num) : text;
2828
+ if (sample.length <= 0) {
2829
+ throw new TranslationError(appName, "Text is empty or too short to check language");
2830
+ }
2831
+ return engineInstance
2832
+ .checkLanguage(sample)
2833
+ .then((r) => r)
2834
+ .catch((e) => {
2835
+ logger.error(`${appName} Failed to check language for text: \n${getGapLine()}\n${text}\n${getGapLine()}\n error: ${getErrorMessages(e)}`);
2836
+ throw e;
2837
+ });
2838
+ }
2613
2839
  async translate(text, options) {
2614
2840
  const { engine = "google", cache_time = 60 * 1000 } = options;
2615
2841
  let { from = "auto", to } = options;
@@ -2621,7 +2847,7 @@ class Translator {
2621
2847
  }
2622
2848
  const engineInstance = this.engines.get(engine);
2623
2849
  if (!engineInstance) {
2624
- throw new TranslationError(appName, `Engine ${engine} not found`);
2850
+ throw new TranslationError(appName, `Engine ${engine} is null`);
2625
2851
  }
2626
2852
  if (!from) {
2627
2853
  throw new TranslationError(appName, `Invalid origin language ${from}`);
@@ -2709,11 +2935,16 @@ var index = {
2709
2935
  };
2710
2936
 
2711
2937
  exports.Cache = Cache;
2938
+ exports.CheckLanguageError = CheckLanguageError;
2712
2939
  exports.OPEN_AI_MODELS = OPEN_AI_MODELS;
2713
2940
  exports.TranslationError = TranslationError;
2714
2941
  exports.Translator = Translator;
2942
+ exports.checkLanguages = checkLanguages;
2715
2943
  exports.default = index;
2716
2944
  exports.engines = engines;
2717
2945
  exports.getLanguage = getLanguage;
2946
+ exports.normalFromLanguage = normalFromLanguage;
2947
+ exports.normalToLanguage = normalToLanguage;
2948
+ exports.originLanguages = originLanguages;
2949
+ exports.targetLanguages = targetLanguages;
2718
2950
  exports.translator = translator;
2719
- //# sourceMappingURL=index.cjs.map