@yxw007/translate 0.0.13 → 0.0.15

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.0.13 Copyright (c) 2024 Potter<aa4790139@gmail.com> and contributors
1
+ // translate v0.0.15 Copyright (c) 2024 Potter<aa4790139@gmail.com> and contributors
2
2
  'use strict';
3
3
 
4
4
  Object.defineProperty(exports, '__esModule', { value: true });
@@ -6,6 +6,15 @@ Object.defineProperty(exports, '__esModule', { value: true });
6
6
  var clientTranslate = require('@aws-sdk/client-translate');
7
7
  var deeplEngine = require('deepl-node');
8
8
 
9
+ class TranslationError extends Error {
10
+ region;
11
+ constructor(region, message) {
12
+ super(`${region}: ${message}`);
13
+ this.region = region;
14
+ Error.captureStackTrace(this, this.constructor);
15
+ }
16
+ }
17
+
9
18
  function google$1(options) {
10
19
  const base = "https://translate.googleapis.com/translate_a/single";
11
20
  return {
@@ -20,7 +29,7 @@ function google$1(options) {
20
29
  const res = await fetch(url);
21
30
  const body = await res.json();
22
31
  if (!body || body.length === 0) {
23
- throw new Error("Translate fail ! translate's result is null or empty");
32
+ throw new TranslationError(this.name, "Translate fail ! translate's result is null or empty");
24
33
  }
25
34
  const translations = [];
26
35
  for (let i = 0; body[0] && i < body[0].length; i++) {
@@ -40,10 +49,18 @@ function google$1(options) {
40
49
  */
41
50
  function azure$1(options) {
42
51
  const { key, region } = options;
52
+ const name = "azure";
53
+ const checkOptions = () => {
54
+ if (!key || !region) {
55
+ throw new TranslationError(name, `${name} key and region is required`);
56
+ }
57
+ };
58
+ checkOptions();
43
59
  const base = "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0";
44
60
  return {
45
- name: "azure",
61
+ name,
46
62
  async translate(text, opts) {
63
+ checkOptions();
47
64
  const { from, to } = opts;
48
65
  const url = `${base}&to=${to}${from && from !== "auto" ? `&from=${from}` : ""}`;
49
66
  if (!Array.isArray(text)) {
@@ -60,11 +77,11 @@ function azure$1(options) {
60
77
  });
61
78
  const bodyRes = await res.json();
62
79
  if (bodyRes.error) {
63
- throw new Error(`Translate fail ! code: ${bodyRes.error.code}, message: ${bodyRes.error.message}`);
80
+ throw new TranslationError(this.name, `Translate fail ! code: ${bodyRes.error.code}, message: ${bodyRes.error.message}`);
64
81
  }
65
82
  const body = bodyRes;
66
83
  if (!body || body.length === 0) {
67
- throw new Error("Translate fail ! translate's result is null or empty");
84
+ throw new TranslationError(this.name, "Translate fail ! translate's result is null or empty");
68
85
  }
69
86
  const translations = [];
70
87
  for (const translation of body) {
@@ -80,9 +97,17 @@ function azure$1(options) {
80
97
 
81
98
  function amazon$1(options) {
82
99
  const { region, accessKeyId, secretAccessKey } = options;
100
+ const name = "amazon";
101
+ const checkOptions = () => {
102
+ if (!region || !accessKeyId || !secretAccessKey) {
103
+ throw new TranslationError(name, `${name} region, accessKeyId ,secretAccessKey is required`);
104
+ }
105
+ };
106
+ checkOptions();
83
107
  return {
84
- name: "amazon",
108
+ name,
85
109
  async translate(text, opts) {
110
+ checkOptions();
86
111
  const { from = "auto", to } = opts;
87
112
  const translateClient = new clientTranslate.TranslateClient({ region: region, credentials: { accessKeyId, secretAccessKey } });
88
113
  if (!Array.isArray(text)) {
@@ -1230,9 +1255,17 @@ var md5 = /*@__PURE__*/getDefaultExportFromCjs(md5Exports);
1230
1255
  function baidu$1(options) {
1231
1256
  const { appId, secretKey } = options;
1232
1257
  const url = "https://fanyi-api.baidu.com/api/trans/vip/fieldtranslate";
1258
+ const name = "baidu";
1259
+ const checkOptions = () => {
1260
+ if (!appId || !secretKey) {
1261
+ throw new TranslationError(name, `${name} appId and secretKey is required`);
1262
+ }
1263
+ };
1264
+ checkOptions();
1233
1265
  return {
1234
- name: "baidu",
1266
+ name,
1235
1267
  async translate(text, opts) {
1268
+ checkOptions();
1236
1269
  const { to, from = "auto", domain = "it" } = opts;
1237
1270
  if (!Array.isArray(text)) {
1238
1271
  text = [text];
@@ -1257,7 +1290,7 @@ function baidu$1(options) {
1257
1290
  });
1258
1291
  const data = await res.json();
1259
1292
  if (!data || data.error_code || !data.trans_result || data.trans_result.length === 0) {
1260
- throw new Error("Failed to translate text");
1293
+ throw new TranslationError(this.name, `Translate fail ! error_code:${data.error_code}, error_msg: ${data.error_msg}`);
1261
1294
  }
1262
1295
  const translations = [];
1263
1296
  for (const translation of data.trans_result) {
@@ -1272,10 +1305,18 @@ function baidu$1(options) {
1272
1305
 
1273
1306
  function deepl$2(options) {
1274
1307
  const { key } = options;
1308
+ const name = "deepl";
1309
+ const checkOptions = () => {
1310
+ if (!key) {
1311
+ throw new TranslationError(name, `${name} key is required`);
1312
+ }
1313
+ };
1314
+ checkOptions();
1275
1315
  const translator = new deeplEngine.Translator(key);
1276
1316
  return {
1277
- name: "deepl",
1317
+ name,
1278
1318
  async translate(text, opts) {
1319
+ checkOptions();
1279
1320
  const { to, from = "auto" } = opts;
1280
1321
  if (!Array.isArray(text)) {
1281
1322
  text = [text];
@@ -1375,6 +1416,16 @@ function useLogger(name = "") {
1375
1416
  };
1376
1417
  }
1377
1418
 
1419
+ function getGapLine() {
1420
+ return "-".repeat(20);
1421
+ }
1422
+ function getErrorMessages(e, prefix = "Translate fail ! ") {
1423
+ if (e instanceof TypeError) {
1424
+ return prefix + (e.cause.message ?? e.message);
1425
+ }
1426
+ return prefix + e.message;
1427
+ }
1428
+
1378
1429
  var azure = {
1379
1430
  Afrikaans: "af",
1380
1431
  Albanian: "sq",
@@ -2179,6 +2230,8 @@ function getLanguage(engine) {
2179
2230
  };
2180
2231
  }
2181
2232
 
2233
+ const appName = "Translate";
2234
+
2182
2235
  const logger = useLogger();
2183
2236
  const cache = new Cache();
2184
2237
  class Translator {
@@ -2195,33 +2248,44 @@ class Translator {
2195
2248
  }
2196
2249
  this.engines.set(engine.name, engine);
2197
2250
  }
2198
- translate(text, options) {
2251
+ async translate(text, options) {
2199
2252
  const { engine = "google", cache_time = 60 * 1000 } = options;
2200
2253
  let { from = "auto", to } = options;
2201
2254
  from = options.from = normalFromLanguage(from, engine);
2202
2255
  to = options.to = normalToLanguage(to, engine);
2203
2256
  //1. Check if engine exists
2204
2257
  if (!this.engines.has(engine)) {
2205
- throw new Error(`Engine ${engine} not found`);
2258
+ throw new TranslationError(appName, `Engine ${engine} not found`);
2206
2259
  }
2207
2260
  const engineInstance = this.engines.get(engine);
2208
2261
  if (!engineInstance) {
2209
- throw new Error(`Engine ${engine} not found`);
2262
+ throw new TranslationError(appName, `Engine ${engine} not found`);
2210
2263
  }
2211
2264
  if (!from) {
2212
- throw new Error(`Invalid origin language ${from}`);
2265
+ throw new TranslationError(appName, `Invalid origin language ${from}`);
2213
2266
  }
2214
2267
  if (!to) {
2215
- throw new Error(`Invalid target language ${to}`);
2268
+ throw new TranslationError(appName, `Invalid target language ${to}`);
2216
2269
  }
2217
2270
  const key = `${from}:${to}:${engine}:${text}`;
2218
2271
  //3. If the cache is matched, the cache is used directly
2219
2272
  if (cache.get(key)) {
2220
2273
  return Promise.resolve(cache.get(key)?.value);
2221
2274
  }
2222
- return engineInstance.translate(text, options).then((translated) => {
2275
+ return engineInstance
2276
+ .translate(text, options)
2277
+ .then((translated) => {
2223
2278
  cache.set(key, translated, cache_time ?? this.cache_time);
2224
2279
  return translated;
2280
+ })
2281
+ .catch((e) => {
2282
+ logger.error(`${appName} Failed: from=${from},to=${to},engine=${engine},translate text: \n${getGapLine()}\n${text}\n${getGapLine()}\n error: ${getErrorMessages(e)}`);
2283
+ if (e instanceof TranslationError) {
2284
+ throw e;
2285
+ }
2286
+ else {
2287
+ throw new TranslationError(appName, getErrorMessages(e));
2288
+ }
2225
2289
  });
2226
2290
  }
2227
2291
  }
@@ -2235,6 +2299,7 @@ var index = {
2235
2299
  };
2236
2300
 
2237
2301
  exports.Cache = Cache;
2302
+ exports.TranslationError = TranslationError;
2238
2303
  exports.Translator = Translator;
2239
2304
  exports.default = index;
2240
2305
  exports.engines = engines;