forked from Binhluan1234/translate-google-api
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
85 lines (69 loc) · 2.23 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import fetch from 'node-fetch';
import { generateToken } from './util/token.js';
import { isSupported, getCode } from './util/language.js';
export const translate = async (text, options = {}) => {
let error;
[ options.from, options.to ].forEach(lang => {
if (lang && !isSupported(lang)) {
error = new Error(`The language '${lang}' is not supported`);
error.code = 400;
throw error;
}
});
options.from = Object.hasOwn(options, 'from') ? getCode(options.from) : 'auto';
options.to = Object.hasOwn(options, 'to') ? getCode(options.to) : 'en';
const tld = options.tld ?? 'com';
const token = await generateToken(text, { tld });
const params = {
client: options.client ?? 'gtx',
sl: options.from ?? 'auto',
tl: options.to ?? 'en',
hl: options.to ?? 'en',
ie: 'UTF-8',
oe: 'UTF-8',
otf: 1,
ssel: 0,
tsel: 0,
kc: 7,
q: text,
[token.name]: token.value
};
const headers = {
'Content-Type': 'application/json',
'Accept': 'application/json, text/plain, */*',
'X-Requested-With': 'XMLHttpRequest'
};
const url = new URL(`https://translate.google.${tld}/translate_a/single`);
url.search = new URLSearchParams(params);
[ 'at', 'bd', 'ex', 'ld', 'md', 'qca', 'rw', 'rm', 'ss', 't' ].forEach(param => url.searchParams.append('dt', param));
return fetch(url, { method: 'POST', headers })
.then(res => res.json())
.then(body => {
if (options.raw) return body;
const result = {
text: '',
from: {
language: {
iso: ''
},
text: {
value: ''
}
}
};
body[0].forEach(obj => {
if (obj[0]) result.text += obj[0];
});
result.from.language.iso = body[2];
if (body[2] !== body[8][0][0])
result.from.language.didYouMean = body[8][0][0];
if (body[7] && body[7][0]) {
result.from.text.value = body[7][0]
.replaceAll('<b><i>', '[')
.replaceAll('</i></b>', ']');
body[7][5] === true ? result.from.text.autoCorrected = true : result.from.text.didYouMean = true;
}
return result;
});
};
export { langs, getCode, isSupported } from './util/language.js';