@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)) {
@@ -1196,9 +1221,17 @@ var md5 = /*@__PURE__*/getDefaultExportFromCjs(md5Exports);
1196
1221
  function baidu$1(options) {
1197
1222
  const { appId, secretKey } = options;
1198
1223
  const url = "https://fanyi-api.baidu.com/api/trans/vip/fieldtranslate";
1224
+ const name = "baidu";
1225
+ const checkOptions = () => {
1226
+ if (!appId || !secretKey) {
1227
+ throw new TranslationError(name, `${name} appId and secretKey is required`);
1228
+ }
1229
+ };
1230
+ checkOptions();
1199
1231
  return {
1200
- name: "baidu",
1232
+ name,
1201
1233
  async translate(text, opts) {
1234
+ checkOptions();
1202
1235
  const { to, from = "auto", domain = "it" } = opts;
1203
1236
  if (!Array.isArray(text)) {
1204
1237
  text = [text];
@@ -1223,7 +1256,7 @@ function baidu$1(options) {
1223
1256
  });
1224
1257
  const data = await res.json();
1225
1258
  if (!data || data.error_code || !data.trans_result || data.trans_result.length === 0) {
1226
- throw new Error("Failed to translate text");
1259
+ throw new TranslationError(this.name, `Translate fail ! error_code:${data.error_code}, error_msg: ${data.error_msg}`);
1227
1260
  }
1228
1261
  const translations = [];
1229
1262
  for (const translation of data.trans_result) {
@@ -1238,10 +1271,18 @@ function baidu$1(options) {
1238
1271
 
1239
1272
  function deepl$2(options) {
1240
1273
  const { key } = options;
1274
+ const name = "deepl";
1275
+ const checkOptions = () => {
1276
+ if (!key) {
1277
+ throw new TranslationError(name, `${name} key is required`);
1278
+ }
1279
+ };
1280
+ checkOptions();
1241
1281
  const translator = new deeplEngine.Translator(key);
1242
1282
  return {
1243
- name: "deepl",
1283
+ name,
1244
1284
  async translate(text, opts) {
1285
+ checkOptions();
1245
1286
  const { to, from = "auto" } = opts;
1246
1287
  if (!Array.isArray(text)) {
1247
1288
  text = [text];
@@ -1341,6 +1382,16 @@ function useLogger(name = "") {
1341
1382
  };
1342
1383
  }
1343
1384
 
1385
+ function getGapLine() {
1386
+ return "-".repeat(20);
1387
+ }
1388
+ function getErrorMessages(e, prefix = "Translate fail ! ") {
1389
+ if (e instanceof TypeError) {
1390
+ return prefix + (e.cause.message ?? e.message);
1391
+ }
1392
+ return prefix + e.message;
1393
+ }
1394
+
1344
1395
  var azure = {
1345
1396
  Afrikaans: "af",
1346
1397
  Albanian: "sq",
@@ -2145,6 +2196,8 @@ function getLanguage(engine) {
2145
2196
  };
2146
2197
  }
2147
2198
 
2199
+ const appName = "Translate";
2200
+
2148
2201
  const logger = useLogger();
2149
2202
  const cache = new Cache();
2150
2203
  class Translator {
@@ -2161,33 +2214,44 @@ class Translator {
2161
2214
  }
2162
2215
  this.engines.set(engine.name, engine);
2163
2216
  }
2164
- translate(text, options) {
2217
+ async translate(text, options) {
2165
2218
  const { engine = "google", cache_time = 60 * 1000 } = options;
2166
2219
  let { from = "auto", to } = options;
2167
2220
  from = options.from = normalFromLanguage(from, engine);
2168
2221
  to = options.to = normalToLanguage(to, engine);
2169
2222
  //1. Check if engine exists
2170
2223
  if (!this.engines.has(engine)) {
2171
- throw new Error(`Engine ${engine} not found`);
2224
+ throw new TranslationError(appName, `Engine ${engine} not found`);
2172
2225
  }
2173
2226
  const engineInstance = this.engines.get(engine);
2174
2227
  if (!engineInstance) {
2175
- throw new Error(`Engine ${engine} not found`);
2228
+ throw new TranslationError(appName, `Engine ${engine} not found`);
2176
2229
  }
2177
2230
  if (!from) {
2178
- throw new Error(`Invalid origin language ${from}`);
2231
+ throw new TranslationError(appName, `Invalid origin language ${from}`);
2179
2232
  }
2180
2233
  if (!to) {
2181
- throw new Error(`Invalid target language ${to}`);
2234
+ throw new TranslationError(appName, `Invalid target language ${to}`);
2182
2235
  }
2183
2236
  const key = `${from}:${to}:${engine}:${text}`;
2184
2237
  //3. If the cache is matched, the cache is used directly
2185
2238
  if (cache.get(key)) {
2186
2239
  return Promise.resolve(cache.get(key)?.value);
2187
2240
  }
2188
- return engineInstance.translate(text, options).then((translated) => {
2241
+ return engineInstance
2242
+ .translate(text, options)
2243
+ .then((translated) => {
2189
2244
  cache.set(key, translated, cache_time ?? this.cache_time);
2190
2245
  return translated;
2246
+ })
2247
+ .catch((e) => {
2248
+ logger.error(`${appName} Failed: from=${from},to=${to},engine=${engine},translate text: \n${getGapLine()}\n${text}\n${getGapLine()}\n error: ${getErrorMessages(e)}`);
2249
+ if (e instanceof TranslationError) {
2250
+ throw e;
2251
+ }
2252
+ else {
2253
+ throw new TranslationError(appName, getErrorMessages(e));
2254
+ }
2191
2255
  });
2192
2256
  }
2193
2257
  }
@@ -2201,6 +2265,7 @@ var index = {
2201
2265
  };
2202
2266
 
2203
2267
  exports.Cache = Cache;
2268
+ exports.TranslationError = TranslationError;
2204
2269
  exports.Translator = Translator;
2205
2270
  exports.default = index;
2206
2271
  exports.engines = engines;